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/ChangeLog b/ChangeLog index 0f13e4651b1..7537a891c9b 100644 --- a/ChangeLog +++ b/ChangeLog @@ -19,9 +19,60 @@ WARNING: Following changes may create regressions for some external modules, but were necessary to make Dolibarr better: * The ICS value for direct debit or credit transfer is now store on each bank account instead of into the global setup. * API /setup/shipment_methods has been replaced with API /setup/shipping_methods +* Field "tva" renamed into "total_tva" in llx_propal, llx_supplier_proposal, llx_commande, llx_commande_fournisseur for better field name consistency +* Field "total" renamed into "total_ttc" in llx_propal, llx_supplier_proposal for better field name consistency +* If your database is PostgreSql, you must use version 9.1.0 or more (Dolibarr need the SQL function CONCAT) +* If your database is MySql or MariaDB, you need at least version 5.1 +***** ChangeLog for 13.0.2 compared to 13.0.1 ***** + +FIX: 11.0 - $this->socid injected in query without checking for empty value +FIX: #16096 #16085 Any call of ajax pages must provide the token +FIX: #16296 +FIX: #16325 +FIX: #16341 : Fetch the Product ExtraFields in Shippment lines +FIX: #16366 +FIX: #16393 Do not sanitize +FIX: #16420 #16423 #16488 #16477 +FIX: #16431 +FIX: #16465 +FIX: #16480 +FIX: #16485 +FIX: #16487 +FIX: #16503 +FIX: #16530 +FIX: #16533 +FIX: #16629 +FIX: #16671 Can not generate zip file of documents in backup tool +FIX: Add "Now" link on social charges creation card +FIX: avoid undefined url and missing token +FIX: Bad project filter in ticket list +FIX: Buttons to disable bindings not working +FIX: class not found when creating recuring invoice from invoice+discount +FIX: File attachment on lots +FIX: handling $heightforinfotot when he's superior to a page height on Supplier Invoice +FIX: hourglass and hide button to pay +FIX: massaction validate invoice do not regenerate pdf +FIX: missing mp4 video mime +FIX: picto on shipment to reset qty to 0. Some quantities were not reset. +FIX: Protection to avoid #16504 +FIX: rounding amount on card updating +FIX: Rounding amount on social charges card updating +FIX: select list dependencies now work for ModuleBuilder sellist field +FIX: Status in popup of member in widget +FIX: status on tooltip on widgets +FIX: Timezone management for datetime on list of events +FIX: Timezone management for datetime with modulebuilder and extrafields +FIX: Total_ht not show in contract link element +FIX: use post instead get +FIX: use var "saved_url" instead global var "$url" +FIX: Various payment - Missing fields for check transmitter & bank name +FIX: warning if setup of chart of account is not yet done. +FIX: wrong extension + + ***** ChangeLog for 13.0.1 compared to 13.0.0 ***** FIX: 10.0 before crediting a withdrawal receipt, check whether it has been credited already. @@ -29,18 +80,19 @@ FIX: 11.0 when a mandatory extrafield of type sellist contains '0' it should be FIX: 11.0 when a new intervention is created from an object, a new $extrafields object is instantiated but not initialized FIX: create MO, Column 'tms' cannot be null FIX: #14290 #15900 -FIX: #16076 -FIX: #16077 -FIX: #16079 -FIX: #16080 -FIX: 16084 +FIX: #16076 patch user/list.php for extrafields +FIX: #16077 patch wrong timezone +FIX: #16079 error of service date at duplicated invoice +FIX: #16080 mailing list title +FIX: #16084 DB error at projects FIX: #16107 -FIX: #16118 Timezone problem on some fields +FIX: #16118 Timezone problem on some fields FIX: #16131 FIX: #16135 FIX: #16143 FIX: #16156 FIX: #16160 +FIX: #16165 Create customer discount without vat FIX: #16185 FIX: #16189, fix download/see check deposit PDF FIX: #16215 @@ -65,13 +117,17 @@ FIX: select default mail template FIX: Select transport mode function when creating a supplier invoice and add unique key to the table llx_c_transport_mode in migrate sql FIX: Merge of thirdparties : "unknow column fk_soc" + "Delivery" label FIX: SQL Error in group by with postgres or mysql strict mode -FIX: takepos : load date function +FIX: TakePOS : load date function FIX: Timeout during import FIX: Trigger on expense report was not fired FIX: User creation of expense report not visible FIX: warning when adding a line if $remise_percent is an empty string FIX: status late on purchase orders FIX: ODT generation very slow +FIX: amount in summary of report +FIX: vat value when code contains number +FIX: payment term label on PDF +FIX: date selector when using reduced year (like on smartphone) ***** ChangeLog for 13.0.0 compared to 12.0.0 ***** @@ -322,6 +378,63 @@ Following changes may create regressions for some external modules, but were nec * Dolibarr v13 is still compatible with any PHP version between 5.6.0 and 7.4.*; Unit tests are OK with PHP 8.0 but some warnings or troubles may appears with PHP 8.0. * All your Ajax services must contains such a line at begin of file: if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal + + +***** ChangeLog for 12.0.5 compared to 12.0.4 ***** +FIX: before crediting a withdrawal receipt, check whether it has been credited already +FIX: mandatory extrafields of type sellist +FIX: when a mandatory extrafield of type sellist contains '0' it should be considered empty and trigger an error message upon insertion +FIX: when a new intervention is created from an object, a new $extrafields object is instantiated but not initialized +FIX: "openall" filter on ticket list does not include read tickets +FIX: ticket - extrafields of type 'date' are not saved +FIX: ticket - the "openall" filter on the ticket list does not include tickets with status READ +FIX: #14290 #15900 +FIX: #15388 #15891 +FIX: #15465 External user sees last 5 shipments to other customers in the dashboard +FIX: #15629 +FIX: #15751 Miscellaneous payment type change to 0 after updating subledger account +FIX: #15946 +FIX: #15966 #15967 +FIX: Accountancy - Fix some problems on CEGID export +FIX: Accountancy - label_operation is used instead of label_compte +FIX: Accountancy - Retire entire opening balance feature +FIX: add autofix of count of email target when data is corrupted +FIX: add categories params on llxHeader filter +FIX: Add critical price patch from 12 to 11. +FIX: Bad cleaning of VAT rate when numbers are into code +FIX: Bad dates filtering in the ticket list causes sql error +FIX: balance starting and ending fiscal month #14197 +FIX: bom line unit display #13831 +FIX: cash fence for takepos with multientity +FIX: Check of customer/vendor code fails in some cases +FIX: create ticket : thirdparty/contact notification #15629 +FIX: Creation of thirdparty when setup is empty +FIX: Dates of sales start in TakePOS +FIX: dupliacete customer or supplier code must be error dipslayed with new code proposed +FIX: Export FEC - Force Carriage Return Line Feed +FIX: Facture Situation Out : status condition +FIX: Filter on date of next generation on template invoices +FIX: Fix detect dispatched product and set to received completely when the supplier order have services (support STOCK_SUPPORTS_SERVICES) +FIX: Invoice Situation Out : status condition +FIX: issue 15659 : Missing test if supplier conf is enabled +FIX: link to create event when task is in a project with a thirdparty +FIX: Localtax must be converted with price2num +FIX: manage price min for PRODUIT_CUSTOMER_PRICES +FIX: missing GETPOST parameters on card_presend.tpl.php +FIX: missing socid into link to create event from project agenda tab +FIX: Must delete extrafields before main table on product deletion. +FIX: (path) htdocs removed +FIX: php alert sms.php +FIX: right to show VAT rate in product list +FIX: select default mail template +FIX: Timeout during import +FIX: update order by api +FIX: useless tracking number displayed on pdf if empty issue #14501 +FIX: Visible date of payment +FIX: warning when adding a line if $remise_percent is an empty string +FIX: When creating a new POS sell, the creation date must be modified. +FIX: wrong name for search status param issue #15516 + ***** ChangeLog for 12.0.4 compared to 12.0.3 ***** FIX: make formConfirm an addreplace-type hook FIX: regex to remove 'action' parameter: taking feedback from PR#15213 into account 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/SECURITY.md b/SECURITY.md index 08ca64e4a4c..f63f9c3f277 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -12,7 +12,7 @@ This file contains some policies about the security reports on Dolibarr ERP CRM ## Reporting a Vulnerability -To report a vulnerability, please use GitHub security advisory (alternatively send an email to security@dolibarr.org) +To report a vulnerability, please use GitHub security advisory at https://github.com/Dolibarr/dolibarr/security/advisories/new (or alternatively send an email to security@dolibarr.org) ## Hunting vulnerabilities on Dolibarr diff --git a/build/debian/control b/build/debian/control index eed54669555..059325eecb9 100755 --- a/build/debian/control +++ b/build/debian/control @@ -33,7 +33,7 @@ Depends: libapache2-mod-php5 | libapache2-mod-php5filter | php5-cgi | php5-fpm | Recommends: apache2 | lighttpd | httpd, mariadb-server | virtual-mysql-server, # Required PHP extensions for debian 9 but we can't add them into a Depends, it does not exists on debian 7 and 8 - php-xml, php-mbstring + php-xml, php-mbstring, php-intl Suggests: www-browser, php5-geoip Description: Web based software to manage a company or foundation Dolibarr ERP & CRM is an easy to use open source/free software package for diff --git a/build/generate_filelist_xml.php b/build/generate_filelist_xml.php index 50eb6c84def..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,26 +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"); @@ -198,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 5c5baaac3bc..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) { @@ -579,7 +582,6 @@ if ($nboftargetok) { $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/teclib*`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/timesheet*`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/webmail*`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/workstation*`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/themes/oblyon*`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/themes/allscreen*`; $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/theme/common/octicons/LICENSE`; @@ -614,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`; @@ -624,8 +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 -fr $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/tools`; - $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/build/rpm/dolibarr_fedora.spec b/build/rpm/dolibarr_fedora.spec index 99061b24eab..d50c91d1f05 100755 --- a/build/rpm/dolibarr_fedora.spec +++ b/build/rpm/dolibarr_fedora.spec @@ -212,6 +212,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/product %_datadir/dolibarr/htdocs/projet %_datadir/dolibarr/htdocs/public +%_datadir/dolibarr/htdocs/recruitment %_datadir/dolibarr/htdocs/reception %_datadir/dolibarr/htdocs/resource %_datadir/dolibarr/htdocs/salaries 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/doc/images/dolibarr_screenshot12_1920x1080.jpg b/doc/images/dolibarr_screenshot12_1920x1080.jpg new file mode 100644 index 00000000000..72ae74cb00f Binary files /dev/null and b/doc/images/dolibarr_screenshot12_1920x1080.jpg differ diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index 47a984cd467..faf55427786 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -49,20 +49,30 @@ $search_pcgtype = GETPOST('search_pcgtype', 'alpha'); $chartofaccounts = GETPOST('chartofaccounts', 'int'); // Security check -if ($user->socid > 0) accessforbidden(); -if (!$user->rights->accounting->chartofaccount) accessforbidden(); +if ($user->socid > 0) { + accessforbidden(); +} +if (!$user->rights->accounting->chartofaccount) { + accessforbidden(); +} // 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 (!$sortfield) $sortfield = "aa.account_number"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "aa.account_number"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} $arrayfields = array( 'aa.account_number'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1), @@ -74,7 +84,9 @@ $arrayfields = array( 'aa.active'=>array('label'=>$langs->trans("Activated"), 'checked'=>1) ); -if ($conf->global->MAIN_FEATURES_LEVEL < 2) unset($arrayfields['aa.reconcilable']); +if ($conf->global->MAIN_FEATURES_LEVEL < 2) { + unset($arrayfields['aa.reconcilable']); +} $accounting = new AccountingAccount($db); @@ -84,21 +96,27 @@ $accounting = new AccountingAccount($db); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha')) { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha')) { + $massaction = ''; +} $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 (!empty($cancel)) $action = ''; +if (empty($reshook)) { + if (!empty($cancel)) { + $action = ''; + } include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers $search_account = ""; $search_label = ""; $search_labelshort = ""; @@ -107,23 +125,21 @@ if (empty($reshook)) $search_array_options = array(); } if ((GETPOST('valid_change_chart', 'alpha') && GETPOST('chartofaccounts', 'int') > 0) // explicit click on button 'Change and load' with js on - || (GETPOST('chartofaccounts', 'int') > 0 && GETPOST('chartofaccounts', 'int') != $conf->global->CHARTOFACCOUNTS)) // a submit of form is done and chartofaccounts combo has been modified - { - if ($chartofaccounts > 0) - { + || (GETPOST('chartofaccounts', 'int') > 0 && GETPOST('chartofaccounts', 'int') != $conf->global->CHARTOFACCOUNTS)) { // a submit of form is done and chartofaccounts combo has been modified + if ($chartofaccounts > 0) { // Get language code for this $chartofaccounts $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_country as c, '.MAIN_DB_PREFIX.'accounting_system as a'; $sql .= ' WHERE c.rowid = a.fk_country AND a.rowid = '.(int) $chartofaccounts; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $country_code = $obj->code; - } else dol_print_error($db); + } else { + dol_print_error($db); + } // Try to load sql file - if ($country_code) - { + if ($country_code) { $sqlfile = DOL_DOCUMENT_ROOT.'/install/mysql/data/llx_accounting_account_'.strtolower($country_code).'.sql'; $offsetforchartofaccount = 0; @@ -131,16 +147,15 @@ 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); - if (preg_match('/-- ADD (\d+) to rowid/ims', $tmp, $reg)) - { + $reg = array(); + if (preg_match('/-- ADD (\d+) to rowid/ims', $tmp, $reg)) { $offsetforchartofaccount += $reg[1]; } $offsetforchartofaccount += ($conf->entity * 100000000); $result = run_sql($sqlfile, 1, $conf->entity, 1, '', 'default', 32768, 0, $offsetforchartofaccount); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans("ChartLoaded"), null, 'mesgs'); } else { setEventMessages($langs->trans("ErrorDuringChartLoad"), null, 'warnings'); @@ -198,8 +213,11 @@ $sql = "SELECT aa.rowid, aa.fk_pcg_version, aa.pcg_type, aa.account_number, aa.a $sql .= " a2.rowid as rowid2, a2.label as label2, a2.account_number as account_number2"; $sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version AND aa.entity = ".$conf->entity; -if ($db->type == 'pgsql') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = ".$conf->entity; -else $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = ".$conf->entity; +if ($db->type == 'pgsql') { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = ".$conf->entity; +} else { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = ".$conf->entity; +} $sql .= " WHERE asy.rowid = ".$pcgver; //print $sql; if (strlen(trim($search_account))) { @@ -224,31 +242,38 @@ if (strlen(trim($search_account))) { $search_account_tmp_clean = $search_account_tmp; $search_account_clean = $search_account; $startchar = '%'; - if (strpos($search_account_tmp, '^') === 0) - { + if (strpos($search_account_tmp, '^') === 0) { $startchar = ''; $search_account_tmp_clean = preg_replace('/^\^/', '', $search_account_tmp); $search_account_clean = preg_replace('/^\^/', '', $search_account); } $sql .= " AND (aa.account_number LIKE '".$db->escape($startchar.$search_account_tmp_clean)."'"; $sql .= " OR aa.account_number LIKE '".$db->escape($startchar.$search_account_clean)."%')"; - } else $sql .= natural_search("aa.account_number", $search_account_tmp); + } else { + $sql .= natural_search("aa.account_number", $search_account_tmp); + } } } -if (strlen(trim($search_label))) $sql .= natural_search("aa.label", $search_label); -if (strlen(trim($search_labelshort))) $sql .= natural_search("aa.labelshort", $search_labelshort); -if (strlen(trim($search_accountparent)) && $search_accountparent != '-1') $sql .= natural_search("aa.account_parent", $search_accountparent, 2); -if (strlen(trim($search_pcgtype))) $sql .= natural_search("aa.pcg_type", $search_pcgtype); +if (strlen(trim($search_label))) { + $sql .= natural_search("aa.label", $search_label); +} +if (strlen(trim($search_labelshort))) { + $sql .= natural_search("aa.labelshort", $search_labelshort); +} +if (strlen(trim($search_accountparent)) && $search_accountparent != '-1') { + $sql .= natural_search("aa.account_parent", $search_accountparent, 2); +} +if (strlen(trim($search_pcgtype))) { + $sql .= natural_search("aa.pcg_type", $search_pcgtype); +} $sql .= $db->order($sortfield, $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 resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -259,22 +284,36 @@ $sql .= $db->plimit($limit + 1, $offset); dol_syslog('accountancy/admin/account.php:: $sql='.$sql); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $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_account) $param .= '&search_account='.urlencode($search_account); - if ($search_label) $param .= '&search_label='.urlencode($search_label); - if ($search_labelshort) $param .= '&search_labelshort='.urlencode($search_labelshort); - if ($search_accountparent > 0 || $search_accountparent == '0') $param .= '&search_accountparent='.urlencode($search_accountparent); - if ($search_pcgtype) $param .= '&search_pcgtype='.urlencode($search_pcgtype); - 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 ($search_account) { + $param .= '&search_account='.urlencode($search_account); + } + if ($search_label) { + $param .= '&search_label='.urlencode($search_label); + } + if ($search_labelshort) { + $param .= '&search_labelshort='.urlencode($search_labelshort); + } + if ($search_accountparent > 0 || $search_accountparent == '0') { + $param .= '&search_accountparent='.urlencode($search_accountparent); + } + if ($search_pcgtype) { + $param .= '&search_pcgtype='.urlencode($search_pcgtype); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print ' '."\n"; } @@ -781,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 @@ -826,9 +907,6 @@ if ($rowid > 0) { print ''; $today = dol_now(); - $datefrom = 0; - $dateto = 0; - $paymentdate = -1; // Date payment if (GETPOST('paymentyear') && GETPOST('paymentmonth') && GETPOST('paymentday')) { @@ -868,7 +946,9 @@ if ($rowid > 0) { // Label print ''.$langs->trans("Label").''; print 'global->MEMBER_NO_DEFAULT_LABEL)) { + print $langs->trans("Subscription").' '.dol_print_date(($datefrom ? $datefrom : time()), "%Y"); + } print '">'; // Complementary action @@ -896,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); @@ -921,16 +1006,21 @@ if ($rowid > 0) { print 'fk_soc)) print ' disabled'; print '> '.$langs->trans("MoreActionBankViaInvoice"); - 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); @@ -1001,7 +1091,9 @@ if ($rowid > 0) { $arraydefaultmessage = null; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION; - 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; diff --git a/htdocs/adherents/subscription/card.php b/htdocs/adherents/subscription/card.php index 1be08bb5b34..575d6d2301b 100644 --- a/htdocs/adherents/subscription/card.php +++ b/htdocs/adherents/subscription/card.php @@ -48,19 +48,27 @@ $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 $permissiontoedit = $user->rights->adherent->cotisation->creer; // Used by the include of actions_lineupdonw.inc.php +$hookmanager->initHooks(array('subscriptioncard', 'globalcard')); + +// Security check +$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 @@ -117,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; } } @@ -148,8 +158,8 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->adherent- $form = new Form($db); - -llxHeader('', $langs->trans("SubscriptionCard"), 'EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros'); +$help_url = 'EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros'; +llxHeader('', $langs->trans("SubscriptionCard"), $help_url); dol_htmloutput_errors($errmsg); @@ -264,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); } @@ -337,9 +349,8 @@ if ($rowid && $action != 'edit') { print dol_get_fiche_end(); /* - * Barre d'actions - * - */ + * Action bar + */ print '
'; if ($user->rights->adherent->cotisation->creer) { @@ -361,17 +372,17 @@ if ($rowid && $action != 'edit') { print '
'; print ''; // ancre - // Documents generes + // Generated documents /* - $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, ''); @@ -379,16 +390,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 05a0567a8d9..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; @@ -209,24 +241,47 @@ if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $ exit; } -llxHeader('', $langs->trans("ListOfSubscriptions"), 'EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros'); +$help_url = 'EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros'; +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'; @@ -236,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 = ''; @@ -245,7 +302,9 @@ if ($user->rights->adherent->cotisation->creer) { } print '
'; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -253,7 +312,7 @@ print ''; print ''; print ''; -print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'members', 0, $newcardbutton, '', $limit, 0, 0, 1); +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $subscription->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); $topicmail = "Information"; $modelmail = "subscription"; @@ -262,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).'
'; } @@ -270,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 ''."\n"; @@ -365,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'; @@ -383,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"; @@ -419,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'])) { @@ -428,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 @@ -453,7 +550,9 @@ while ($i < min($num, $limit)) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Banque @@ -466,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 @@ -497,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++; @@ -527,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 e9e6be408c8..a867a884775 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); @@ -203,7 +213,9 @@ if ($action == 'confirm_delete' && $user->rights->adherent->configurer) { $form = new Form($db); $formproduct = new FormProduct($db); -llxHeader('', $langs->trans("MembersTypeSetup"), '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("MembersTypeSetup"), $help_url); // List of members type if (!$rowid && $action != 'create' && $action != 'edit') { @@ -221,8 +233,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) { @@ -230,7 +246,9 @@ if (!$rowid && $action != 'create' && $action != 'edit') { } print ''; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; @@ -272,14 +290,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 ""; @@ -317,19 +341,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 ''; @@ -484,8 +508,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); @@ -509,8 +533,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; @@ -550,12 +577,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; @@ -632,10 +671,10 @@ if ($rowid > 0) { // Type /*print ''; + $membertypestatic->id=$objp->type_id; + $membertypestatic->label=$objp->type; + print $membertypestatic->getNomUrl(1,12); + print ''; */ // Moral/Physique @@ -662,7 +701,9 @@ if ($rowid > 0) { print ''."\n"; print ''; print ''."\n"; // Show each trigger (list is in c_action_trigger) -if (!empty($triggers)) -{ - foreach ($triggers as $trigger) - { +if (!empty($triggers)) { + foreach ($triggers as $trigger) { $module = $trigger['element']; - if ($module == 'order_supplier' || $module == 'invoice_supplier') $module = 'fournisseur'; - if ($module == 'shipping') $module = 'expedition_bon'; - if ($module == 'member') $module = 'adherent'; - if ($module == 'project') $module = 'projet'; - if ($module == 'proposal_supplier') $module = 'supplier_proposal'; - if ($module == 'contact') $module = 'societe'; + if ($module == 'order_supplier' || $module == 'invoice_supplier') { + $module = 'fournisseur'; + } + if ($module == 'shipping') { + $module = 'expedition_bon'; + } + if ($module == 'member') { + $module = 'adherent'; + } + if ($module == 'project') { + $module = 'projet'; + } + if ($module == 'proposal_supplier') { + $module = 'supplier_proposal'; + } + if ($module == 'contact') { + $module = 'societe'; + } // If 'element' value is myobject@mymodule instead of mymodule $tmparray = explode('@', $module); @@ -174,14 +179,16 @@ if (!empty($triggers)) } //print 'module='.$module.' code='.$trigger['code'].'
'; - if (!empty($conf->$module->enabled)) - { + if (!empty($conf->$module->enabled)) { // Discard special case: If option FICHINTER_CLASSIFY_BILLED is not set, we discard both trigger FICHINTER_CLASSIFY_BILLED and FICHINTER_CLASSIFY_UNBILLED - if ($trigger['code'] == 'FICHINTER_CLASSIFY_BILLED' && empty($conf->global->FICHINTER_CLASSIFY_BILLED)) continue; - if ($trigger['code'] == 'FICHINTER_CLASSIFY_UNBILLED' && empty($conf->global->FICHINTER_CLASSIFY_BILLED)) continue; + if ($trigger['code'] == 'FICHINTER_CLASSIFY_BILLED' && empty($conf->global->FICHINTER_CLASSIFY_BILLED)) { + continue; + } + if ($trigger['code'] == 'FICHINTER_CLASSIFY_UNBILLED' && empty($conf->global->FICHINTER_CLASSIFY_BILLED)) { + continue; + } - if ($search_event === '' || preg_match('/'.preg_quote($search_event, '/').'/i', $trigger['code'])) - { + if ($search_event === '' || preg_match('/'.preg_quote($search_event, '/').'/i', $trigger['code'])) { print ''; print ''; print ''; diff --git a/htdocs/admin/agenda_extrafields.php b/htdocs/admin/agenda_extrafields.php index 36c7bc3edf8..f140b207aaf 100644 --- a/htdocs/admin/agenda_extrafields.php +++ b/htdocs/admin/agenda_extrafields.php @@ -31,8 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'agenda')); @@ -43,13 +44,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 = 'actioncomm'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -82,8 +87,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -96,8 +100,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '
'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -109,8 +112,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/admin/agenda_extsites.php b/htdocs/admin/agenda_extsites.php index f99c530c7e2..9ce55583d99 100644 --- a/htdocs/admin/agenda_extsites.php +++ b/htdocs/admin/agenda_extsites.php @@ -32,7 +32,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('agenda', 'admin', 'other')); @@ -41,7 +43,9 @@ $def = array(); $actiontest = GETPOST('test', 'alpha'); $actionsave = GETPOST('save', 'alpha'); -if (empty($conf->global->AGENDA_EXT_NB)) $conf->global->AGENDA_EXT_NB = 5; +if (empty($conf->global->AGENDA_EXT_NB)) { + $conf->global->AGENDA_EXT_NB = 5; +} $MAXAGENDA = $conf->global->AGENDA_EXT_NB; // List of available colors @@ -52,8 +56,7 @@ $colorlist = array('BECEDD', 'DDBECE', 'BFDDBE', 'F598B4', 'F68654', 'CBF654', ' * Actions */ -if ($actionsave) -{ +if ($actionsave) { $db->begin(); $disableext = GETPOST('AGENDA_DISABLE_EXT', 'alpha'); @@ -63,17 +66,17 @@ if ($actionsave) $error = 0; // Save agendas - while ($i <= $MAXAGENDA) - { + while ($i <= $MAXAGENDA) { $name = trim(GETPOST('AGENDA_EXT_NAME'.$i, 'alpha')); $src = trim(GETPOST('AGENDA_EXT_SRC'.$i, 'alpha')); $offsettz = trim(GETPOST('AGENDA_EXT_OFFSETTZ'.$i, 'alpha')); $color = trim(GETPOST('AGENDA_EXT_COLOR'.$i, 'alpha')); - if ($color == '-1') $color = ''; + if ($color == '-1') { + $color = ''; + } $enabled = trim(GETPOST('AGENDA_EXT_ENABLED'.$i, 'alpha')); - if (!empty($src) && !dol_is_url($src)) - { + if (!empty($src) && !dol_is_url($src)) { setEventMessages($langs->trans("ErrorParamMustBeAnUrl"), null, 'errors'); $error++; $errorsaved++; @@ -82,34 +85,48 @@ if ($actionsave) //print '-name='.$name.'-color='.$color; $res = dolibarr_set_const($db, 'AGENDA_EXT_NAME'.$i, $name, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } $res = dolibarr_set_const($db, 'AGENDA_EXT_SRC'.$i, $src, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } $res = dolibarr_set_const($db, 'AGENDA_EXT_OFFSETTZ'.$i, $offsettz, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } $res = dolibarr_set_const($db, 'AGENDA_EXT_COLOR'.$i, $color, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } $res = dolibarr_set_const($db, 'AGENDA_EXT_ENABLED'.$i, $enabled, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } $i++; } // Save nb of agenda - if (!$error) - { + if (!$error) { $res = dolibarr_set_const($db, 'AGENDA_EXT_NB', trim(GETPOST('AGENDA_EXT_NB', 'int')), 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; - if (empty($conf->global->AGENDA_EXT_NB)) $conf->global->AGENDA_EXT_NB = 5; + if (!($res > 0)) { + $error++; + } + if (empty($conf->global->AGENDA_EXT_NB)) { + $conf->global->AGENDA_EXT_NB = 5; + } $MAXAGENDA = empty($conf->global->AGENDA_EXT_NB) ? 5 : $conf->global->AGENDA_EXT_NB; } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { $db->rollback(); - if (empty($errorsaved)) setEventMessages($langs->trans("Error"), null, 'errors'); + if (empty($errorsaved)) { + setEventMessages($langs->trans("Error"), null, 'errors'); + } } } @@ -143,7 +160,11 @@ print "
\n"; $selectedvalue = $conf->global->AGENDA_DISABLE_EXT; -if ($selectedvalue == 1) $selectedvalue = 0; else $selectedvalue = 1; +if ($selectedvalue == 1) { + $selectedvalue = 0; +} else { + $selectedvalue = 1; +} 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..0ce4b2314b4 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'); @@ -173,18 +175,17 @@ print dol_get_fiche_end(); -/* ************************************************************************** */ -/* */ -/* Barre d'action */ -/* */ -/* ************************************************************************** */ - +/* + * Action bar + */ 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 +243,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/accountant.php b/htdocs/admin/accountant.php index a0dbe4e9838..3ed43f1664f 100644 --- a/htdocs/admin/accountant.php +++ b/htdocs/admin/accountant.php @@ -34,7 +34,9 @@ $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'adm // Load translation files required by the page $langs->loadLangs(array('admin', 'companies')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $error = 0; @@ -45,11 +47,12 @@ $error = 0; $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 (($action == 'update' && !GETPOST("cancel", 'alpha')) -|| ($action == 'updateedit')) -{ +|| ($action == 'updateedit')) { dolibarr_set_const($db, "MAIN_INFO_ACCOUNTANT_NAME", GETPOST("nom", 'nohtml'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_INFO_ACCOUNTANT_ADDRESS", GETPOST("address", 'nohtml'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_INFO_ACCOUNTANT_TOWN", GETPOST("town", 'nohtml'), 'chaine', 0, '', $conf->entity); @@ -64,8 +67,7 @@ if (($action == 'update' && !GETPOST("cancel", 'alpha')) dolibarr_set_const($db, "MAIN_INFO_ACCOUNTANT_CODE", GETPOST("code", 'nohtml'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_INFO_ACCOUNTANT_NOTE", GETPOST("note", 'restricthtml'), 'chaine', 0, '', $conf->entity); - if ($action != 'updateedit' && !$error) - { + if ($action != 'updateedit' && !$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); header("Location: ".$_SERVER["PHP_SELF"]); exit; @@ -131,7 +133,9 @@ print '
'; print img_picto('', 'globe-americas', 'class="paddingrightonly"'); print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id', 'int') : (!empty($conf->global->MAIN_INFO_ACCOUNTANT_COUNTRY) ? $conf->global->MAIN_INFO_ACCOUNTANT_COUNTRY : '')), 'country_id'); -if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); +if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); +} print '
'; diff --git a/htdocs/admin/agenda.php b/htdocs/admin/agenda.php index efdd6213dd5..9829be288a5 100644 --- a/htdocs/admin/agenda.php +++ b/htdocs/admin/agenda.php @@ -28,8 +28,9 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'agenda')); @@ -45,12 +46,10 @@ $sql = "SELECT a.rowid, a.code, a.label, a.elementtype, a.rang as position"; $sql .= " FROM ".MAIN_DB_PREFIX."c_action_trigger as a"; $sql .= " ORDER BY a.rang ASC"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $triggers[$i]['rowid'] = $obj->rowid; $triggers[$i]['code'] = $obj->code; @@ -73,36 +72,32 @@ if ($resql) */ // 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_event = ''; $action = ''; } -if (GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) // To avoid the save when we click on search -{ +if (GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { // To avoid the save when we click on search $action = ''; } -if ($action == "save" && empty($cancel)) -{ +if ($action == "save" && empty($cancel)) { $i = 0; $db->begin(); - foreach ($triggers as $trigger) - { + foreach ($triggers as $trigger) { $keyparam = 'MAIN_AGENDA_ACTIONAUTO_'.$trigger['code']; //print "param=".$param." - ".$_POST[$param]; - if ($search_event === '' || preg_match('/'.preg_quote($search_event, '/').'/i', $keyparam)) - { + if ($search_event === '' || preg_match('/'.preg_quote($search_event, '/').'/i', $keyparam)) { $res = dolibarr_set_const($db, $keyparam, (GETPOST($keyparam, 'alpha') ?GETPOST($keyparam, 'alpha') : ''), 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } } } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); $db->commit(); } else { @@ -155,17 +150,27 @@ print ''.$langs->trans("ActionsEvents").''.$langs->trans("All").'/'.$langs->trans("None").'
'.$trigger['code'].''.$trigger['label'].'
"; @@ -157,12 +178,10 @@ print ""; print ''; print ""; print ''; print ""; $i = 1; -while ($i <= $MAXAGENDA) -{ +while ($i <= $MAXAGENDA) { $key = $i; $name = 'AGENDA_EXT_NAME'.$key; $src = 'AGENDA_EXT_SRC'.$key; diff --git a/htdocs/admin/agenda_other.php b/htdocs/admin/agenda_other.php index a072869be8c..54d5158b4ed 100644 --- a/htdocs/admin/agenda_other.php +++ b/htdocs/admin/agenda_other.php @@ -30,9 +30,11 @@ 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) +if (!$user->admin) { accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'agenda', 'users')); @@ -52,12 +54,10 @@ $type = 'action'; include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; $reg = array(); -if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) -{ +if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; $value = (GETPOST($code, 'alpha') ? GETPOST($code, 'alpha') : 1); - if (dolibarr_set_const($db, $code, $value, 'chaine', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, $code, $value, 'chaine', 0, '', $conf->entity) > 0) { Header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -65,27 +65,47 @@ if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) } } -if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) -{ +if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; - if (dolibarr_del_const($db, $code, $conf->entity) > 0) - { + if (dolibarr_del_const($db, $code, $conf->entity) > 0) { Header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { dol_print_error($db); } } -if ($action == 'set') -{ +if ($action == 'set') { $getDefaultFilter = GETPOST('AGENDA_DEFAULT_FILTER_TYPE'); $defaultfilter = (is_array($getDefaultFilter)) ? implode(',', $getDefaultFilter) : $getDefaultFilter; dolibarr_set_const($db, 'AGENDA_USE_EVENT_TYPE_DEFAULT', GETPOST('AGENDA_USE_EVENT_TYPE_DEFAULT'), 'chaine', 0, '', $conf->entity); 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); -} elseif ($action == 'specimen') // For orders -{ + + $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'); $commande = new CommandeFournisseur($db); @@ -95,25 +115,21 @@ if ($action == 'set') // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/action/doc/pdf_".$modele.".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db, $commande); - if ($module->write_file($commande, $langs) > 0) - { + if ($module->write_file($commande, $langs) > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=action&file=SPECIMEN.pdf"); return; } else { @@ -124,27 +140,20 @@ if ($action == 'set') setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); } -} - -// Activate a model -elseif ($action == 'setmodel') -{ +} elseif ($action == 'setmodel') { + // Activate a model //print "sssd".$value; $ret = addDocumentModel($value, $type, $label, $scandir); -} elseif ($action == 'del') -{ +} elseif ($action == 'del') { $ret = delDocumentModel($value, $type); - if ($ret > 0) - { - if ($conf->global->ACTION_EVENT_ADDON_PDF == "$value") dolibarr_del_const($db, 'ACTION_EVENT_ADDON_PDF', $conf->entity); + if ($ret > 0) { + if ($conf->global->ACTION_EVENT_ADDON_PDF == "$value") { + dolibarr_del_const($db, 'ACTION_EVENT_ADDON_PDF', $conf->entity); + } } -} - -// Set default model -elseif ($action == 'setdoc') -{ - if (dolibarr_set_const($db, "ACTION_EVENT_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) - { +} elseif ($action == 'setdoc') { + // Set default model + if (dolibarr_set_const($db, "ACTION_EVENT_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { // La constante qui a ete lue en avant du nouveau set // on passe donc par une variable pour avoir un affichage coherent $conf->global->ACTION_EVENT_ADDON_PDF = $value; @@ -152,8 +161,7 @@ elseif ($action == 'setdoc') // On active le modele $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, $type, $label, $scandir); } } @@ -193,12 +201,10 @@ $sql .= " WHERE type = 'action'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -207,8 +213,7 @@ if ($resql) dol_print_error($db); } -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) -{ +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { print load_fiche_titre($langs->trans("AgendaModelModule"), '', ''); print '
".$langs->trans("ExtSitesEnableThisTool")."'; -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print ajax_constantonoff('AGENDA_DISABLE_EXT', array('enabled'=>array(0=>'.hideifnotset')), null, 1); } else { - if (empty($conf->global->AGENDA_DISABLE_EXT)) - { + if (empty($conf->global->AGENDA_DISABLE_EXT)) { print ''.img_picto($langs->trans("Enabled"), 'on').''; } else { print ''.img_picto($langs->trans("Disabled"), 'off').''; @@ -194,8 +213,7 @@ print ''.$langs->trans("Color").'
'."\n"; @@ -223,19 +228,14 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) clearstatcache(); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/action/doc"); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -249,17 +249,17 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) print "\n"; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print ''."\n"; print ''."\n"; print ''."\n"; +if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { + print ''; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; +} + // AGENDA_DEFAULT_VIEW print ''."\n"; $htmltext = $langs->trans("ThisValueCanOverwrittenOnUserLevel", $langs->transnoentitiesnoconv("UserGUISetup")); @@ -342,16 +350,21 @@ $tmplist = array(''=>' ', 'show_list'=>$langs->trans("ViewList"), 'show_mon print $form->selectarray('AGENDA_DEFAULT_VIEW', $tmplist, $conf->global->AGENDA_DEFAULT_VIEW); print ''."\n"; -if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) -{ - print ''; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; +// AGENDA_EVENT_DEFAULT_STATUS +print ''."\n"; +print ''."\n"; +print ''."\n"; +print ''."\n"; // AGENDA_DEFAULT_FILTER_TYPE print ''."\n"; diff --git a/htdocs/admin/agenda_reminder.php b/htdocs/admin/agenda_reminder.php index 36f0c572de4..b3a85d1fe4b 100644 --- a/htdocs/admin/agenda_reminder.php +++ b/htdocs/admin/agenda_reminder.php @@ -27,8 +27,9 @@ 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.'/cron/class/cronjob.class.php'; -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array("admin", "other", "agenda")); @@ -47,12 +48,10 @@ $type = 'action'; include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; -if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) -{ +if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; $value = (GETPOST($code, 'alpha') ? GETPOST($code, 'alpha') : 1); - if (dolibarr_set_const($db, $code, $value, 'chaine', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, $code, $value, 'chaine', 0, '', $conf->entity) > 0) { Header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -60,25 +59,21 @@ if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) } } -if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) -{ +if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; - if (dolibarr_del_const($db, $code, $conf->entity) > 0) - { + if (dolibarr_del_const($db, $code, $conf->entity) > 0) { Header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { dol_print_error($db); } } -if ($action == 'set') -{ +if ($action == 'set') { dolibarr_set_const($db, 'AGENDA_USE_EVENT_TYPE_DEFAULT', GETPOST('AGENDA_USE_EVENT_TYPE_DEFAULT'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, 'AGENDA_DEFAULT_FILTER_TYPE', GETPOST('AGENDA_DEFAULT_FILTER_TYPE'), '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); -} elseif ($action == 'specimen') // For orders -{ +} elseif ($action == 'specimen') { // For orders $modele = GETPOST('module', 'alpha'); $commande = new CommandeFournisseur($db); @@ -88,25 +83,21 @@ if ($action == 'set') // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/action/doc/pdf_".$modele.".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db, $commande); - if ($module->write_file($commande, $langs) > 0) - { + if ($module->write_file($commande, $langs) > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=action&file=SPECIMEN.pdf"); return; } else { @@ -117,27 +108,20 @@ if ($action == 'set') setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); } -} - -// Activate a model -elseif ($action == 'setmodel') -{ +} elseif ($action == 'setmodel') { + // Activate a model //print "sssd".$value; $ret = addDocumentModel($value, $type, $label, $scandir); -} elseif ($action == 'del') -{ +} elseif ($action == 'del') { $ret = delDocumentModel($value, $type); - if ($ret > 0) - { - if ($conf->global->ACTION_EVENT_ADDON_PDF == "$value") dolibarr_del_const($db, 'ACTION_EVENT_ADDON_PDF', $conf->entity); + if ($ret > 0) { + if ($conf->global->ACTION_EVENT_ADDON_PDF == "$value") { + dolibarr_del_const($db, 'ACTION_EVENT_ADDON_PDF', $conf->entity); + } } -} - -// Set default model -elseif ($action == 'setdoc') -{ - if (dolibarr_set_const($db, "ACTION_EVENT_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) - { +} elseif ($action == 'setdoc') { + // Set default model + if (dolibarr_set_const($db, "ACTION_EVENT_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { // The constant that has been read in front of the new set // is therefore passed through a variable to have a coherent display $conf->global->ACTION_EVENT_ADDON_PDF = $value; @@ -145,8 +129,7 @@ elseif ($action == 'setdoc') // On active le modele $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, $type, $label, $scandir); } } @@ -184,7 +167,7 @@ print ''."\n"; print ''."\n"; print ''."\n"; print ''."\n"; -print ''."\n"; print ''."\n"; -print '"; print ''; print '"; print ''; print ""; print ""; @@ -183,8 +185,7 @@ $message .= $langs->trans("AgendaUrlOptionsIncludeHolidays", '1', '1').'
'; print info_admin($message); -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print "\n".' - trans("OtherSetup"), '', 'title_setup'); @@ -196,8 +191,7 @@ print getTitleFieldOfList('Name', 0, $_SERVER['PHP_SELF'], 'name', '', $param, ' print getTitleFieldOfList("Value", 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); print getTitleFieldOfList("Comment", 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); print getTitleFieldOfList('DateModificationShort', 0, $_SERVER['PHP_SELF'], 'tms', '', $param, '', $sortfield, $sortorder, 'center ')."\n"; -if (!empty($conf->multicompany->enabled) && !$user->entity) -{ +if (!empty($conf->multicompany->enabled) && !$user->entity) { print getTitleFieldOfList('Entity', 0, $_SERVER['PHP_SELF'], 'tms', '', $param, '', $sortfield, $sortorder, 'center ')."\n"; } print getTitleFieldOfList("", 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'center '); @@ -219,8 +213,7 @@ print ''; print ''; // Limit to superadmin -if (!empty($conf->multicompany->enabled) && !$user->entity) -{ +if (!empty($conf->multicompany->enabled) && !$user->entity) { print ''; @@ -245,20 +238,23 @@ $sql .= ", tms"; $sql .= ", entity"; $sql .= " FROM ".MAIN_DB_PREFIX."const"; $sql .= " WHERE entity IN (".$user->entity.",".$conf->entity.")"; -if ((empty($user->entity) || $user->admin) && $debug) {} // to force for superadmin to debug -elseif (!GETPOST('visible') || GETPOST('visible') != 'all') $sql .= " AND visible = 1"; // We must always have this. Otherwise, array is too large and submitting data fails due to apache POST or GET limits -if (GETPOST('name')) $sql .= natural_search("name", GETPOST('name')); +if ((empty($user->entity) || $user->admin) && $debug) { +} elseif (!GETPOST('visible') || GETPOST('visible') != 'all') { + // to force for superadmin to debug + $sql .= " AND visible = 1"; // We must always have this. Otherwise, array is too large and submitting data fails due to apache POST or GET limits +} +if (GETPOST('name')) { + $sql .= natural_search("name", GETPOST('name')); +} $sql .= $db->order($sortfield, $sortorder); dol_syslog("Const::listConstant", LOG_DEBUG); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); print "\n"; @@ -270,22 +266,21 @@ if ($result) print ''; print ''; print ''; - print ''; + print ''; print ''; // Note print ''; // Date last change - print ''; // Entity limit to superadmin - if (!empty($conf->multicompany->enabled) && !$user->entity) - { + if (!empty($conf->multicompany->enabled) && !$user->entity) { print ''; @@ -295,8 +290,7 @@ if ($result) print ''; } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print ''; } else { print ''.img_delete().''; @@ -313,8 +307,7 @@ if ($result) print '
\n"; require_once $dir.'/'.$file; $module = new $classname($db, $specimenthirdparty); - if (method_exists($module, 'info')) + if (method_exists($module, 'info')) { print $module->info($langs); - else print $module->description; + } else { + print $module->description; + } print "'."\n"; - if ($conf->global->ACTION_EVENT_ADDON_PDF != "$name") - { + if ($conf->global->ACTION_EVENT_ADDON_PDF != "$name") { print 'scandir.'&label='.urlencode($module->name).'&type=action">'; print img_picto($langs->trans("Enabled"), 'switch_on'); print ''; @@ -275,8 +275,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // Default print ''; - if ($conf->global->ACTION_EVENT_ADDON_PDF == "$name") - { + if ($conf->global->ACTION_EVENT_ADDON_PDF == "$name") { print img_picto($langs->trans("Default"), 'on'); } else { print 'scandir.'&label='.urlencode($module->name).'&type=action"" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; @@ -324,14 +323,23 @@ print ''.$langs->trans("AGENDA_USE_EVENT_TYPE").' '."\n"; //print ajax_constantonoff('AGENDA_USE_EVENT_TYPE'); Do not use ajax here, we need to reload page to change other combo list -if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) -{ +if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) { print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; } else { print ''.img_picto($langs->trans("Enabled"), 'switch_on').''; } print '
'.$langs->trans("AGENDA_USE_EVENT_TYPE_DEFAULT").' '."\n"; + $formactions->select_type_actions($conf->global->AGENDA_USE_EVENT_TYPE_DEFAULT, "AGENDA_USE_EVENT_TYPE_DEFAULT", 'systemauto', 0, 1); + print '
'.$langs->trans("AGENDA_USE_EVENT_TYPE_DEFAULT").' '."\n"; - $formactions->select_type_actions($conf->global->AGENDA_USE_EVENT_TYPE_DEFAULT, "AGENDA_USE_EVENT_TYPE_DEFAULT", 'systemauto', 0, 1); - 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_REMINDER_BROWSER').' '."\n"; +print ''."\n"; if (empty($conf->global->AGENDA_REMINDER_BROWSER)) { if (!isHTTPS()) { @@ -232,7 +215,7 @@ if (!empty($conf->cron->enabled)) { } print ' '."\n"; +print ''."\n"; if (empty($conf->cron->enabled)) { print ''.$langs->trans("WarningModuleNotActive", $langs->transnoentitiesnoconv("Module2300Name")).''; diff --git a/htdocs/admin/agenda_xcal.php b/htdocs/admin/agenda_xcal.php index 6d77b9f4416..586194375fc 100644 --- a/htdocs/admin/agenda_xcal.php +++ b/htdocs/admin/agenda_xcal.php @@ -29,8 +29,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array("admin", "other", "agenda")); @@ -39,8 +40,7 @@ $def = array(); $actionsave = GETPOST('save', 'alpha'); // Sauvegardes parametres -if ($actionsave) -{ +if ($actionsave) { $i = 0; $db->begin(); @@ -50,8 +50,7 @@ if ($actionsave) $i += dolibarr_set_const($db, 'MAIN_AGENDA_EXPORT_CACHE', trim(GETPOST('MAIN_AGENDA_EXPORT_CACHE', 'alpha')), 'chaine', 0, '', $conf->entity); $i += dolibarr_set_const($db, 'AGENDA_EXPORT_FIX_TZ', trim(GETPOST('AGENDA_EXPORT_FIX_TZ', 'alpha')), 'chaine', 0, '', $conf->entity); - if ($i >= 4) - { + if ($i >= 4) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -66,7 +65,9 @@ if ($actionsave) * View */ -if (!isset($conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY)) $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY = 100; +if (!isset($conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY)) { + $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY = 100; +} $wikihelp = 'EN:Module_Agenda_En|FR:Module_Agenda|ES:Módulo_Agenda'; llxHeader('', $langs->trans("AgendaSetup"), $wikihelp); @@ -97,8 +98,9 @@ print "
'.$langs->trans("PasswordTogetVCalExport")."'; -if (!empty($conf->use_javascript_ajax)) +if (!empty($conf->use_javascript_ajax)) { print ' '.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"'); +} print ' 
'; print ''; print ''; print ''; - print ''; + print ''; print ''; + print ''; print dol_print_date($db->jdate($obj->tms), 'dayhour'); print ''; print ''; print '
'; print '
'; -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print '
'; print '
'; print ''; diff --git a/htdocs/admin/contract.php b/htdocs/admin/contract.php index 05330e92b89..30b77f6db8b 100644 --- a/htdocs/admin/contract.php +++ b/htdocs/admin/contract.php @@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "errors", "contracts")); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); @@ -39,8 +41,7 @@ $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); $type = 'contract'; -if (empty($conf->global->CONTRACT_ADDON)) -{ +if (empty($conf->global->CONTRACT_ADDON)) { $conf->global->CONTRACT_ADDON = 'mod_contract_serpis'; } @@ -51,22 +52,23 @@ if (empty($conf->global->CONTRACT_ADDON)) include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; -if ($action == 'updateMask') -{ +if ($action == 'updateMask') { $maskconst = GETPOST('maskconstcontract', 'alpha'); $maskvalue = GETPOST('maskcontract', 'alpha'); - if ($maskconst) $res = dolibarr_set_const($db, $maskconst, $maskvalue, 'chaine', 0, '', $conf->entity); + if ($maskconst) { + $res = dolibarr_set_const($db, $maskconst, $maskvalue, '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'); } -} elseif ($action == 'specimen') // For contract -{ +} elseif ($action == 'specimen') { // For contract $modele = GETPOST('module', 'alpha'); $contract = new Contrat($db); @@ -75,25 +77,21 @@ if ($action == 'updateMask') // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/contract/doc/pdf_".$modele.".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db); - if ($module->write_file($contract, $langs) > 0) - { + if ($module->write_file($contract, $langs) > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=contract&file=SPECIMEN.pdf"); return; } else { @@ -104,26 +102,19 @@ if ($action == 'updateMask') setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); } -} - -// Activate a model -elseif ($action == 'set') -{ +} elseif ($action == 'set') { + // Activate a model $ret = addDocumentModel($value, $type, $label, $scandir); -} elseif ($action == 'del') -{ +} elseif ($action == 'del') { $ret = delDocumentModel($value, $type); - if ($ret > 0) - { - if ($conf->global->CONTRACT_ADDON_PDF == "$value") dolibarr_del_const($db, 'CONTRACT_ADDON_PDF', $conf->entity); + if ($ret > 0) { + if ($conf->global->CONTRACT_ADDON_PDF == "$value") { + dolibarr_del_const($db, 'CONTRACT_ADDON_PDF', $conf->entity); + } } -} - -// Set default model -elseif ($action == 'setdoc') -{ - if (dolibarr_set_const($db, "CONTRACT_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) - { +} elseif ($action == 'setdoc') { + // Set default model + if (dolibarr_set_const($db, "CONTRACT_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { // La constante qui a ete lue en avant du nouveau set // on passe donc par une variable pour avoir un affichage coherent $conf->global->CONTRACT_ADDON_PDF = $value; @@ -131,18 +122,15 @@ elseif ($action == 'setdoc') // On active le modele $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, $type, $label, $scandir); } -} elseif ($action == 'setmod') -{ +} elseif ($action == 'setmod') { // TODO Verifier si module numerotation choisi peut etre active // par appel methode canBeActivated dolibarr_set_const($db, "CONTRACT_ADDON", $value, 'chaine', 0, '', $conf->entity); -} elseif ($action == 'set_other') -{ +} elseif ($action == 'set_other') { $freetext = GETPOST('CONTRACT_FREE_TEXT', 'restricthtml'); // No alpha here, we want exact string $res1 = dolibarr_set_const($db, "CONTRACT_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity); @@ -152,10 +140,11 @@ elseif ($action == 'setdoc') $value = GETPOST('activate_hideClosedServiceByDefault', 'alpha'); $res3 = dolibarr_set_const($db, "CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT", $value, 'chaine', 0, '', $conf->entity); - if (!$res1 > 0 || !$res2 > 0 || !$res3 > 0) $error++; + if (!$res1 > 0 || !$res2 > 0 || !$res3 > 0) { + $error++; + } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -197,19 +186,14 @@ print "\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ +foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/contract/"); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (substr($file, 0, 13) == 'mod_contract_' && substr($file, dol_strlen($file) - 3, 3) == 'php') - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (substr($file, 0, 13) == 'mod_contract_' && substr($file, dol_strlen($file) - 3, 3) == 'php') { $file = substr($file, 0, dol_strlen($file) - 4); require_once $dir.$file.'.php'; @@ -217,11 +201,14 @@ foreach ($dirmodels as $reldir) $module = new $file($db); // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } - if ($module->isEnabled()) - { + if ($module->isEnabled()) { print ''.$module->nom."\n"; print $module->info(); print ''; @@ -232,14 +219,15 @@ foreach ($dirmodels as $reldir) if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '
'.$langs->trans($tmp).'
'; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; } - elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); - else print $tmp; print ''."\n"; print ''; - if ($conf->global->CONTRACT_ADDON == "$file") - { + if ($conf->global->CONTRACT_ADDON == "$file") { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print ''; @@ -258,8 +246,9 @@ foreach ($dirmodels as $reldir) if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { $nextval = $langs->trans($nextval); + } $htmltooltip .= $nextval.'
'; } else { $htmltooltip .= $langs->trans($module->error).'
'; @@ -294,12 +283,10 @@ $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; $sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -321,31 +308,23 @@ print "\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ - foreach (array('', '/doc') as $valdir) - { +foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { $realpath = $reldir."core/modules/contract".$valdir; $dir = dol_buildpath($realpath); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -353,21 +332,26 @@ 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 == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print ''; print (empty($module->name) ? $name : $module->name); print "\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print ''; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print ''."\n"; print '
'; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -381,8 +365,7 @@ foreach ($dirmodels as $reldir) // Defaut print ''; - if ($conf->global->CONTRACT_ADDON_PDF == $name) - { + if ($conf->global->CONTRACT_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').''; @@ -392,8 +375,7 @@ foreach ($dirmodels as $reldir) // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '
'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; @@ -412,8 +394,7 @@ foreach ($dirmodels as $reldir) // Preview print ''; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print ''.img_object($langs->trans("Preview"), 'pdf').''; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); @@ -452,15 +433,16 @@ print "\n"; $substitutionarray = pdf_getSubstitutionArray($langs, array('objectamount'), null, 2); $substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; -foreach ($substitutionarray as $key => $val) $htmltext .= $key.'
'; +foreach ($substitutionarray as $key => $val) { + $htmltext .= $key.'
'; +} $htmltext .= '
'; print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnContracts"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'tooltiphelp'); print '
'; $variablename = 'CONTRACT_FREE_TEXT'; -if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) -{ +if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; diff --git a/htdocs/admin/dav.php b/htdocs/admin/dav.php index 4008a3cd7be..32b91ed7cea 100644 --- a/htdocs/admin/dav.php +++ b/htdocs/admin/dav.php @@ -28,8 +28,9 @@ require_once DOL_DOCUMENT_ROOT.'/dav/dav.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "other", "agenda")); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Parameters $action = GETPOST('action', 'aZ09'); @@ -57,8 +58,9 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; * View */ +$help_url = 'EN:Module_DAV'; -llxHeader('', $langs->trans("DAVSetup"), $wikihelp); +llxHeader('', $langs->trans("DAVSetup"), $help_url); $linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("DAVSetup"), $linkback, 'title_setup'); @@ -71,8 +73,7 @@ $head = dav_admin_prepare_head(); print dol_get_fiche_head($head, 'webdav', '', -1, 'action'); -if ($action == 'edit') -{ +if ($action == 'edit') { print ''; print ''; print ''; @@ -80,9 +81,10 @@ if ($action == 'edit') print ''; print ''; - foreach ($arrayofparameters as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) continue; + foreach ($arrayofparameters as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { + continue; + } print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); @@ -93,11 +95,9 @@ if ($action == 'edit') } print $form->textwithpicto($label, $tooltiphelp); print ''; - if ($key == 'DAV_ALLOW_PRIVATE_DIR') - { + if ($key == 'DAV_ALLOW_PRIVATE_DIR') { print $langs->trans("AlwaysActive"); - } elseif ($key == 'DAV_ALLOW_PUBLIC_DIR' || $key == 'DAV_ALLOW_ECM_DIR') - { + } elseif ($key == 'DAV_ALLOW_PUBLIC_DIR' || $key == 'DAV_ALLOW_ECM_DIR') { print $form->selectyesno($key, $conf->global->$key, 1); } else { print ''; @@ -117,8 +117,7 @@ if ($action == 'edit') print ''; print ''; - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); $label = $langs->trans($key); @@ -128,11 +127,9 @@ if ($action == 'edit') } print $form->textwithpicto($label, $tooltiphelp); print ''; - if ($key == 'DAV_ALLOW_PRIVATE_DIR') - { + if ($key == 'DAV_ALLOW_PRIVATE_DIR') { print $langs->trans("AlwaysActive"); - } elseif ($key == 'DAV_ALLOW_PUBLIC_DIR' || $key == 'DAV_ALLOW_ECM_DIR') - { + } elseif ($key == 'DAV_ALLOW_PUBLIC_DIR' || $key == 'DAV_ALLOW_ECM_DIR') { print yn($conf->global->$key); } else { print $conf->global->$key; @@ -174,8 +171,7 @@ $message = ''; $url = ''.$urlwithroot.'/dav/fileserver.php'; $message .= img_picto('', 'globe').' '.str_replace('{url}', $url, $langs->trans("WebDavServer", 'WebDAV', '{url}')); $message .= '
'; -if (!empty($conf->global->DAV_ALLOW_PUBLIC_DIR)) -{ +if (!empty($conf->global->DAV_ALLOW_PUBLIC_DIR)) { $urlEntity = (!empty($conf->multicompany->enabled) ? '?entity='.$conf->entity : ''); $url = ''.$urlwithroot.'/dav/fileserver.php/public/'.$urlEntity.''; $message .= img_picto('', 'globe').' '.str_replace('{url}', $url, $langs->trans("WebDavServer", 'WebDAV public', '{url}')); diff --git a/htdocs/admin/debugbar.php b/htdocs/admin/debugbar.php index 840157d47e0..19a440520b1 100644 --- a/htdocs/admin/debugbar.php +++ b/htdocs/admin/debugbar.php @@ -29,7 +29,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; global $conf; -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array("admin", "other")); @@ -43,19 +45,16 @@ $action = GETPOST('action', 'aZ09'); */ // Set modes -if ($action == 'set') -{ +if ($action == 'set') { $db->begin(); $result1 = dolibarr_set_const($db, "DEBUGBAR_LOGS_LINES_NUMBER", GETPOST('DEBUGBAR_LOGS_LINES_NUMBER', 'int'), 'chaine', 0, '', 0); $result2 = dolibarr_set_const($db, "DEBUGBAR_USE_LOG_FILE", GETPOST('DEBUGBAR_USE_LOG_FILE', 'int'), 'chaine', 0, '', 0); - if ($result1 < 0 || $result2 < 0) - { + if ($result1 < 0 || $result2 < 0) { $error++; } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -76,8 +75,7 @@ $form = new Form($db); $linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("DebugBarSetup"), $linkback, 'title_setup'); -if (!function_exists('mb_check_encoding')) -{ +if (!function_exists('mb_check_encoding')) { $langs->load("errors"); print info_admin($langs->trans("ErrorPHPNeedModule", 'mbstring'), 0, 0, 'error'); } diff --git a/htdocs/admin/defaultvalues.php b/htdocs/admin/defaultvalues.php index ae9427d70e0..dc801059e41 100644 --- a/htdocs/admin/defaultvalues.php +++ b/htdocs/admin/defaultvalues.php @@ -30,28 +30,37 @@ 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')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $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'); $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 = 'page,param'; -if (!$sortorder) $sortorder = 'ASC'; +if (!$sortfield) { + $sortfield = 'page,param'; +} +if (!$sortorder) { + $sortorder = 'ASC'; +} $defaulturl = GETPOST('defaulturl', 'alphanohtml'); $defaultkey = GETPOST('defaultkey', 'alphanohtml'); @@ -67,22 +76,28 @@ $value = GETPOST('value', 'restricthtml'); $hookmanager->initHooks(array('admindefaultvalues', 'globaladmin')); +$object = new DefaultValues($db); /* * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && !empty($massaction) && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && !empty($massaction) && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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'); +} include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 $defaulturl = ''; $defaultkey = ''; $defaultvalue = ''; @@ -90,85 +105,87 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_array_options = array(); } -if ($action == 'setMAIN_ENABLE_DEFAULT_VALUES') -{ - if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 1, 'chaine', 0, '', $conf->entity); - else dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 0, 'chaine', 0, '', $conf->entity); +if ($action == 'setMAIN_ENABLE_DEFAULT_VALUES') { + if (GETPOST('value')) { + dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 1, 'chaine', 0, '', $conf->entity); + } else { + dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 0, 'chaine', 0, '', $conf->entity); + } } -if (($action == 'add' || (GETPOST('add') && $action != 'update')) || GETPOST('actionmodify')) -{ +if (($action == 'add' || (GETPOST('add') && $action != 'update')) || GETPOST('actionmodify')) { $error = 0; - if (($action == 'add' || (GETPOST('add') && $action != 'update'))) - { - if (empty($defaulturl)) - { + if (($action == 'add' || (GETPOST('add') && $action != 'update'))) { + if (empty($defaulturl)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Url")), null, 'errors'); $error++; } - if (empty($defaultkey)) - { + if (empty($defaultkey)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Field")), null, 'errors'); $error++; } } - if (GETPOST('actionmodify')) - { - if (empty($urlpage)) - { + if (GETPOST('actionmodify')) { + if (empty($urlpage)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Url")), null, 'errors'); $error++; } - if (empty($key)) - { + if (empty($key)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Field")), null, 'errors'); $error++; } } - 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).")"; + if (!$error) { + if ($action == 'add' || (GETPOST('add') && $action != 'update')) { + $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 = ''; + if (GETPOST('actionmodify')) { + $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); +if ($action == 'delete') { + $object->id=$id; + $result=$object->delete($user); + if ($result<0) { + $action = ''; + setEventMessages($object->error, $object->errors, 'errors'); } } @@ -187,8 +204,7 @@ llxHeader('', $langs->trans("Setup"), $wikihelp); $param = '&mode='.$mode; $enabledisablehtml = $langs->trans("EnableDefaultValues").' '; -if (empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) -{ +if (empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) { // Button off, click to enable $enabledisablehtml .= ''; $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); @@ -205,16 +221,30 @@ print load_fiche_titre($langs->trans("DefaultValues"), $enabledisablehtml, 'titl print ''.$langs->trans("DefaultValuesDesc")."
\n"; print "
\n"; -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 ($defaulturl) $param .= '&defaulturl='.urlencode($defaulturl); -if ($defaultkey) $param .= '&defaultkey='.urlencode($defaultkey); -if ($defaultvalue) $param .= '&defaultvalue='.urlencode($defaultvalue); +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 ($defaulturl) { + $param .= '&defaulturl='.urlencode($defaulturl); +} +if ($defaultkey) { + $param .= '&defaultkey='.urlencode($defaultkey); +} +if ($defaultvalue) { + $param .= '&defaultvalue='.urlencode($defaultvalue); +} print 'entity) && !empty($debug)) ? '?debug=1' : '').'" method="POST">'; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -226,12 +256,10 @@ $head = defaultvalues_prepare_head(); print dol_get_fiche_head($head, $mode, '', -1, ''); -if ($mode == 'sortorder') -{ +if ($mode == 'sortorder') { print info_admin($langs->trans("WarningSettingSortOrder")).'
'; } -if ($mode == 'mandatory') -{ +if ($mode == 'mandatory') { print info_admin($langs->trans("FeatureSupportedOnTextFieldsOnly")).'
'; } @@ -244,15 +272,17 @@ print ''; print ''; // Page $texthelp = $langs->trans("PageUrlForDefaultValues"); -if ($mode == 'createform') $texthelp .= $langs->trans("PageUrlForDefaultValuesCreate", 'societe/card.php', 'societe/card.php?abc=val1&def=val2'); -else $texthelp .= $langs->trans("PageUrlForDefaultValuesList", 'societe/list.php', 'societe/list.php?abc=val1&def=val2'); +if ($mode == 'createform') { + $texthelp .= $langs->trans("PageUrlForDefaultValuesCreate", 'societe/card.php', 'societe/card.php?abc=val1&def=val2'); +} else { + $texthelp .= $langs->trans("PageUrlForDefaultValuesList", 'societe/list.php', 'societe/list.php?abc=val1&def=val2'); +} $texthelp .= '

'.$langs->trans("AlsoDefaultValuesAreEffectiveForActionCreate"); $texturl = $form->textwithpicto($langs->trans("RelativeURL"), $texthelp); print_liste_field_titre($texturl, $_SERVER["PHP_SELF"], 'page,param', '', $param, '', $sortfield, $sortorder); // Field $texthelp = $langs->trans("TheKeyIsTheNameOfHtmlField"); -if ($mode != 'sortorder') -{ +if ($mode != 'sortorder') { $textkey = $form->textwithpicto($langs->trans("Field"), $texthelp); } else { $texthelp = 'field or alias.field'; @@ -260,15 +290,12 @@ if ($mode != 'sortorder') } print_liste_field_titre($textkey, $_SERVER["PHP_SELF"], 'param', '', $param, '', $sortfield, $sortorder); // Value -if ($mode != 'focus' && $mode != 'mandatory') -{ - if ($mode != 'sortorder') - { +if ($mode != 'focus' && $mode != 'mandatory') { + if ($mode != 'sortorder') { $substitutionarray = getCommonSubstitutionArray($langs, 2, array('object', 'objectamount')); // Must match list into GETPOST unset($substitutionarray['__USER_SIGNATURE__']); $texthelp = $langs->trans("FollowingConstantsWillBeSubstituted").'
'; - foreach ($substitutionarray as $key => $val) - { + foreach ($substitutionarray as $key => $val) { $texthelp .= $key.' -> '.$val.'
'; } $textvalue = $form->textwithpicto($langs->trans("Value"), $texthelp, 1, 'help', '', 0, 2, 'subsitutiontooltip'); @@ -279,8 +306,11 @@ if ($mode != 'focus' && $mode != 'mandatory') print_liste_field_titre($textvalue, $_SERVER["PHP_SELF"], 'value', '', $param, '', $sortfield, $sortorder); } // Entity -if (!empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,page', '', $param, '', $sortfield, $sortorder); -else print_liste_field_titre("", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); +if (!empty($conf->multicompany->enabled) && !$user->entity) { + print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,page', '', $param, '', $sortfield, $sortorder); +} else { + print_liste_field_titre("", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); +} // Actions print_liste_field_titre("", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); print "\n"; @@ -299,15 +329,13 @@ print ''; // Value -if ($mode != 'focus' && $mode != 'mandatory') -{ +if ($mode != 'focus' && $mode != 'mandatory') { print ''; } // Limit to superadmin -if (!empty($conf->multicompany->enabled) && !$user->entity) -{ +if (!empty($conf->multicompany->enabled) && !$user->entity) { print ''; @@ -318,57 +346,45 @@ if (!empty($conf->multicompany->enabled) && !$user->entity) } 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 - if ($mode != 'focus' && $mode != 'mandatory') - { + if ($mode != 'focus' && $mode != 'mandatory') { print ''; } @@ -376,14 +392,13 @@ if ($result) // Actions print '
'; print ''; print ''; print ''; print ''; print ''; // We see environment, but to change it we must switch on other entity print ''; $disabled = ''; -if (empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) $disabled = ' disabled="disabled"'; +if (empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) { + $disabled = ' disabled="disabled"'; +} print ''; 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 ''; /*print ''; - print ''; - print ''; - print ''; - */ - if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print dol_escape_htmltag($obj->value); - else print ''; + print ''; + print ''; + print ''; + */ + if ($action != 'edit' || GETPOST('rowid') != $defaultvalue->id) print dol_escape_htmltag($defaultvalue->value); + 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 ''; } @@ -393,8 +408,6 @@ if ($result) print "\n"; $i++; } -} else { - dol_print_error($db); } print '
'; diff --git a/htdocs/admin/delais.php b/htdocs/admin/delais.php index 90ea5f290b6..6c0cd230cc9 100644 --- a/htdocs/admin/delais.php +++ b/htdocs/admin/delais.php @@ -30,134 +30,138 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page $langs->load("admin"); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); -if (empty($action)) $action = 'edit'; +if (empty($action)) { + $action = 'edit'; +} // Define list of managed delays $modules = array( - 'agenda' => array( - array( - 'code' => 'MAIN_DELAY_ACTIONS_TODO', - 'img' => 'action' - ) - ), - 'projet' => array( - array( - 'code' => 'MAIN_DELAY_PROJECT_TO_CLOSE', - 'img' => 'project' - ), - array( - 'code' => 'MAIN_DELAY_TASKS_TODO', - 'img' => 'projecttask' - ) - ), - 'propal' => array( - array( - 'code' => 'MAIN_DELAY_PROPALS_TO_CLOSE', - 'img' => 'propal' - ), - array( - 'code' => 'MAIN_DELAY_PROPALS_TO_BILL', - 'img' => 'propal' - ) - ), - 'commande' => array( - array( - 'code' => 'MAIN_DELAY_ORDERS_TO_PROCESS', - 'img' => 'order' - ) - ), - 'facture' => array( - array( - 'code' => 'MAIN_DELAY_CUSTOMER_BILLS_UNPAYED', - 'img' => 'bill' - ) - ), - 'fournisseur' => array( - array( - 'code' => 'MAIN_DELAY_SUPPLIER_ORDERS_TO_PROCESS', - 'img' => 'order' - ), - array( - 'code' => 'MAIN_DELAY_SUPPLIER_BILLS_TO_PAY', - 'img' => 'bill' - ) - ), - 'service' => array( - array( - 'code' => 'MAIN_DELAY_NOT_ACTIVATED_SERVICES', - 'img' => 'service' - ), - array( - 'code' => 'MAIN_DELAY_RUNNING_SERVICES', - 'img' => 'service' - ) - ), - 'banque' => array( - array( - 'code' => 'MAIN_DELAY_TRANSACTIONS_TO_CONCILIATE', - 'img' => 'account' - ), - array( - 'code' => 'MAIN_DELAY_CHEQUES_TO_DEPOSIT', - 'img' => 'account' - ) - ), - 'adherent' => array( - array( - 'code' => 'MAIN_DELAY_MEMBERS', - 'img' => 'user' - ) - ), - 'expensereport' => array( - array( - 'code' => 'MAIN_DELAY_EXPENSEREPORTS', - 'img' => 'trip' - ), - /* TODO Enable this - array( - 'code' => 'MAIN_DELAY_EXPENSEREPORTS_TO_PAY', - 'img' => 'trip' - )*/ - ), - 'holiday' => array( - array( - 'code' => 'MAIN_DELAY_HOLIDAYS', - 'img' => 'holiday' - ), - ), + 'agenda' => array( + array( + 'code' => 'MAIN_DELAY_ACTIONS_TODO', + 'img' => 'action' + ) + ), + 'projet' => array( + array( + 'code' => 'MAIN_DELAY_PROJECT_TO_CLOSE', + 'img' => 'project' + ), + array( + 'code' => 'MAIN_DELAY_TASKS_TODO', + 'img' => 'projecttask' + ) + ), + 'propal' => array( + array( + 'code' => 'MAIN_DELAY_PROPALS_TO_CLOSE', + 'img' => 'propal' + ), + array( + 'code' => 'MAIN_DELAY_PROPALS_TO_BILL', + 'img' => 'propal' + ) + ), + 'commande' => array( + array( + 'code' => 'MAIN_DELAY_ORDERS_TO_PROCESS', + 'img' => 'order' + ) + ), + 'facture' => array( + array( + 'code' => 'MAIN_DELAY_CUSTOMER_BILLS_UNPAYED', + 'img' => 'bill' + ) + ), + 'fournisseur' => array( + array( + 'code' => 'MAIN_DELAY_SUPPLIER_ORDERS_TO_PROCESS', + 'img' => 'order' + ), + array( + 'code' => 'MAIN_DELAY_SUPPLIER_BILLS_TO_PAY', + 'img' => 'bill' + ) + ), + 'service' => array( + array( + 'code' => 'MAIN_DELAY_NOT_ACTIVATED_SERVICES', + 'img' => 'service' + ), + array( + 'code' => 'MAIN_DELAY_RUNNING_SERVICES', + 'img' => 'service' + ) + ), + 'banque' => array( + array( + 'code' => 'MAIN_DELAY_TRANSACTIONS_TO_CONCILIATE', + 'img' => 'account' + ), + array( + 'code' => 'MAIN_DELAY_CHEQUES_TO_DEPOSIT', + 'img' => 'account' + ) + ), + 'adherent' => array( + array( + 'code' => 'MAIN_DELAY_MEMBERS', + 'img' => 'user' + ) + ), + 'expensereport' => array( + array( + 'code' => 'MAIN_DELAY_EXPENSEREPORTS', + 'img' => 'trip' + ), + /* TODO Enable this + array( + 'code' => 'MAIN_DELAY_EXPENSEREPORTS_TO_PAY', + 'img' => 'trip' + )*/ + ), + 'holiday' => array( + array( + 'code' => 'MAIN_DELAY_HOLIDAYS', + 'img' => 'holiday' + ), + ), ); $labelmeteo = array(0=>$langs->trans("No"), 1=>$langs->trans("Yes"), 2=>$langs->trans("OnMobileOnly")); if (!isset($conf->global->MAIN_DELAY_PROJECT_TO_CLOSE)) { - $conf->global->MAIN_DELAY_PROJECT_TO_CLOSE = 7; // Must be same value than into conf.class.php + $conf->global->MAIN_DELAY_PROJECT_TO_CLOSE = 7; // Must be same value than into conf.class.php } if (!isset($conf->global->MAIN_DELAY_TASKS_TODO)) { - $conf->global->MAIN_DELAY_TASKS_TODO = 7; // Must be same value than into conf.class.php + $conf->global->MAIN_DELAY_TASKS_TODO = 7; // Must be same value than into conf.class.php } if (!isset($conf->global->MAIN_DELAY_MEMBERS)) { - $conf->global->MAIN_DELAY_MEMBERS = 0; // Must be same value than into conf.class.php + $conf->global->MAIN_DELAY_MEMBERS = 0; // Must be same value than into conf.class.php } if (!isset($conf->global->MAIN_DELAY_ACTIONS_TODO)) { - $conf->global->MAIN_DELAY_ACTIONS_TODO = 7; // Must be same value than into conf.class.php + $conf->global->MAIN_DELAY_ACTIONS_TODO = 7; // Must be same value than into conf.class.php } if (!isset($conf->global->MAIN_DELAY_ORDERS_TO_PROCESS)) { - $conf->global->MAIN_DELAY_ORDERS_TO_PROCESS = 2; + $conf->global->MAIN_DELAY_ORDERS_TO_PROCESS = 2; } if (!isset($conf->global->MAIN_DELAY_SUPPLIER_ORDERS_TO_PROCESS)) { - $conf->global->MAIN_DELAY_SUPPLIER_ORDERS_TO_PROCESS = 7; + $conf->global->MAIN_DELAY_SUPPLIER_ORDERS_TO_PROCESS = 7; } if (!isset($conf->global->MAIN_DELAY_ORDERS_TO_PROCESS)) { - $conf->global->MAIN_DELAY_ORDERS_TO_PROCESS = 2; + $conf->global->MAIN_DELAY_ORDERS_TO_PROCESS = 2; } if (!isset($conf->global->MAIN_DELAY_ORDERS_TO_PROCESS)) { - $conf->global->MAIN_DELAY_ORDERS_TO_PROCESS = 2; + $conf->global->MAIN_DELAY_ORDERS_TO_PROCESS = 2; } if (!isset($conf->global->MAIN_DELAY_ORDERS_TO_PROCESS)) { - $conf->global->MAIN_DELAY_ORDERS_TO_PROCESS = 2; + $conf->global->MAIN_DELAY_ORDERS_TO_PROCESS = 2; } @@ -166,32 +170,31 @@ if (!isset($conf->global->MAIN_DELAY_ORDERS_TO_PROCESS)) { * Actions */ -if ($action == 'update') -{ - foreach ($modules as $module => $delays) - { - if (!empty($conf->$module->enabled)) - { - foreach ($delays as $delay) - { - if (GETPOST($delay['code']) != '') - { - dolibarr_set_const($db, $delay['code'], GETPOST($delay['code']), 'chaine', 0, '', $conf->entity); - } - } - } - } +if ($action == 'update') { + foreach ($modules as $module => $delays) { + if (!empty($conf->$module->enabled)) { + foreach ($delays as $delay) { + if (GETPOST($delay['code']) != '') { + dolibarr_set_const($db, $delay['code'], GETPOST($delay['code']), 'chaine', 0, '', $conf->entity); + } + } + } + } - dolibarr_set_const($db, "MAIN_DISABLE_METEO", $_POST["MAIN_DISABLE_METEO"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_USE_METEO_WITH_PERCENTAGE", GETPOST("MAIN_USE_METEO_WITH_PERCENTAGE"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_DISABLE_METEO", $_POST["MAIN_DISABLE_METEO"], 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_USE_METEO_WITH_PERCENTAGE", GETPOST("MAIN_USE_METEO_WITH_PERCENTAGE"), 'chaine', 0, '', $conf->entity); - // For update value with percentage - $plus = ''; - if (!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) $plus = '_PERCENTAGE'; - // Update values - for ($i = 0; $i < 4; $i++) { - if (GETPOSTISSET('MAIN_METEO'.$plus.'_LEVEL'.$i)) dolibarr_set_const($db, 'MAIN_METEO'.$plus.'_LEVEL'.$i, GETPOST('MAIN_METEO'.$plus.'_LEVEL'.$i, 'int'), 'chaine', 0, '', $conf->entity); - } + // For update value with percentage + $plus = ''; + if (!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) { + $plus = '_PERCENTAGE'; + } + // Update values + for ($i = 0; $i < 4; $i++) { + if (GETPOSTISSET('MAIN_METEO'.$plus.'_LEVEL'.$i)) { + dolibarr_set_const($db, 'MAIN_METEO'.$plus.'_LEVEL'.$i, GETPOST('MAIN_METEO'.$plus.'_LEVEL'.$i, 'int'), 'chaine', 0, '', $conf->entity); + } + } setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); @@ -213,158 +216,165 @@ print ''.$langs->transnoentities("DelaysOfToleranceD print " ".$langs->trans("OnlyActiveElementsAreShown", DOL_URL_ROOT.'/admin/modules.php')."
\n"; print "
\n"; -if ($action == 'edit') -{ - print ''; - print ''; - print ''; +if ($action == 'edit') { + print ''; + print ''; + print ''; - print ''; - print ''; + print '
'.$langs->trans("DelaysOfToleranceBeforeWarning").''.$langs->trans("Value").'
'; + print ''; - foreach ($modules as $module => $delays) - { - if (!empty($conf->$module->enabled)) - { - foreach ($delays as $delay) - { - $value = (!empty($conf->global->{$delay['code']}) ? $conf->global->{$delay['code']}:0); - print ''; - print ''; - print ''; - } - } - } + foreach ($modules as $module => $delays) { + if (!empty($conf->$module->enabled)) { + foreach ($delays as $delay) { + $value = (!empty($conf->global->{$delay['code']}) ? $conf->global->{$delay['code']}:0); + print ''; + print ''; + print ''; + } + } + } - print '
'.$langs->trans("DelaysOfToleranceBeforeWarning").''.$langs->trans("Value").'
'.img_object('', $delay['img']).''.$langs->trans('Delays_'.$delay['code']).''; - print ' '.$langs->trans("days").'
'.img_object('', $delay['img']).''.$langs->trans('Delays_'.$delay['code']).''; + print ' '.$langs->trans("days").'
'; + print '
'; - print '
'; + print '
'; - // Show if meteo is enabled - print ''; - print ''; + // Show if meteo is enabled + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; + print ''; - print ''; - print ''; + print ''; + print ''; - print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_DISABLE_METEO").''; - print $form->selectarray('MAIN_DISABLE_METEO', $labelmeteo, (empty($conf->global->MAIN_DISABLE_METEO) ? 0 : $conf->global->MAIN_DISABLE_METEO)); - print '
'.$langs->trans("MAIN_DISABLE_METEO").''; + print $form->selectarray('MAIN_DISABLE_METEO', $labelmeteo, (empty($conf->global->MAIN_DISABLE_METEO) ? 0 : $conf->global->MAIN_DISABLE_METEO)); + print '
'; + print '
'; } else { - /* - * Show parameters - */ + /* + * Show parameters + */ - print ''; - print ''; + print '
'.$langs->trans("DelaysOfToleranceBeforeWarning").''.$langs->trans("Value").'
'; + print ''; - foreach ($modules as $module => $delays) - { - if (!empty($conf->$module->enabled)) - { - foreach ($delays as $delay) - { - $value = (!empty($conf->global->{$delay['code']}) ? $conf->global->{$delay['code']}:0); - print ''; - print ''; - print ''; - print ''; - } - } - } + foreach ($modules as $module => $delays) { + if (!empty($conf->$module->enabled)) { + foreach ($delays as $delay) { + $value = (!empty($conf->global->{$delay['code']}) ? $conf->global->{$delay['code']}:0); + print ''; + print ''; + print ''; + print ''; + } + } + } - print '
'.$langs->trans("DelaysOfToleranceBeforeWarning").''.$langs->trans("Value").'
'.img_object('', $delay['img']).''.$langs->trans('Delays_'.$delay['code']).''.$value.' '.$langs->trans("days").'
'.img_object('', $delay['img']).''.$langs->trans('Delays_'.$delay['code']).''.$value.' '.$langs->trans("days").'
'; + print ''; - print '
'; + print '
'; - // Show if meteo is enabled - print ''; - print ''; + // Show if meteo is enabled + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; + print ''; - print ''; - print ''; + print ''; + print ''; - print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_DISABLE_METEO").''; - print $labelmeteo[$conf->global->MAIN_DISABLE_METEO]; - print '
'.$langs->trans("MAIN_DISABLE_METEO").''; + print $labelmeteo[$conf->global->MAIN_DISABLE_METEO]; + print '
'; + print ''; } print '
'; if ($conf->global->MAIN_DISABLE_METEO != 1) { - // Show logo for weather - print ''.$langs->trans("DescWeather").' '; + // Show logo for weather + print ''.$langs->trans("DescWeather").' '; - if ($action == 'edit') { - $str_mode_std = $langs->trans('MeteoStdModEnabled').' : '.$langs->trans('MeteoUseMod', $langs->transnoentitiesnoconv('MeteoPercentageMod')); - $str_mode_percentage = $langs->trans('MeteoPercentageModEnabled').' : '.$langs->trans('MeteoUseMod', $langs->transnoentitiesnoconv('MeteoStdMod')); - if (empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) $str_mode_enabled = $str_mode_std; - else $str_mode_enabled = $str_mode_percentage; - print ''.$str_mode_enabled.''; - print ''; + if ($action == 'edit') { + $str_mode_std = $langs->trans('MeteoStdModEnabled').' : '.$langs->trans('MeteoUseMod', $langs->transnoentitiesnoconv('MeteoPercentageMod')); + $str_mode_percentage = $langs->trans('MeteoPercentageModEnabled').' : '.$langs->trans('MeteoUseMod', $langs->transnoentitiesnoconv('MeteoStdMod')); + if (empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) { + $str_mode_enabled = $str_mode_std; + } else { + $str_mode_enabled = $str_mode_percentage; + } + print ''.$str_mode_enabled.''; + print ''; - print '

'; - } else { - if (empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) print $langs->trans('MeteoStdModEnabled'); - else print $langs->trans('MeteoPercentageModEnabled'); - print '

'; - } + print '

'; + } else { + if (empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) { + print $langs->trans('MeteoStdModEnabled'); + } else { + print $langs->trans('MeteoPercentageModEnabled'); + } + print '

'; + } - $offset = 0; - $cursor = 10; // By default - //if (! empty($conf->global->MAIN_METEO_OFFSET)) $offset=$conf->global->MAIN_METEO_OFFSET; - //if (! empty($conf->global->MAIN_METEO_GAP)) $cursor=$conf->global->MAIN_METEO_GAP; - $level0 = $offset; if (!empty($conf->global->MAIN_METEO_LEVEL0)) $level0 = $conf->global->MAIN_METEO_LEVEL0; - $level1 = $offset + 1 * $cursor; if (!empty($conf->global->MAIN_METEO_LEVEL1)) $level1 = $conf->global->MAIN_METEO_LEVEL1; - $level2 = $offset + 2 * $cursor; if (!empty($conf->global->MAIN_METEO_LEVEL2)) $level2 = $conf->global->MAIN_METEO_LEVEL2; - $level3 = $offset + 3 * $cursor; if (!empty($conf->global->MAIN_METEO_LEVEL3)) $level3 = $conf->global->MAIN_METEO_LEVEL3; - $text = ''; $options = 'class="valignmiddle" height="60px"'; + $offset = 0; + $cursor = 10; // By default + //if (! empty($conf->global->MAIN_METEO_OFFSET)) $offset=$conf->global->MAIN_METEO_OFFSET; + //if (! empty($conf->global->MAIN_METEO_GAP)) $cursor=$conf->global->MAIN_METEO_GAP; + $level0 = $offset; if (!empty($conf->global->MAIN_METEO_LEVEL0)) { + $level0 = $conf->global->MAIN_METEO_LEVEL0; + } + $level1 = $offset + 1 * $cursor; if (!empty($conf->global->MAIN_METEO_LEVEL1)) { + $level1 = $conf->global->MAIN_METEO_LEVEL1; + } + $level2 = $offset + 2 * $cursor; if (!empty($conf->global->MAIN_METEO_LEVEL2)) { + $level2 = $conf->global->MAIN_METEO_LEVEL2; + } + $level3 = $offset + 3 * $cursor; if (!empty($conf->global->MAIN_METEO_LEVEL3)) { + $level3 = $conf->global->MAIN_METEO_LEVEL3; + } + $text = ''; $options = 'class="valignmiddle" height="60px"'; - if ($action == 'edit') { - print '
global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '' : 'style="display:none;"').'>'; + if ($action == 'edit') { + print '
global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '' : 'style="display:none;"').'>'; - print '
'; - print '
'; - print img_weather($text, 0, $options); - print ' <= '; - print '
'; - print img_weather($text, 1, $options); - print ' <= '; - print '
'; - print img_weather($text, 2, $options); - print ' <= '; - print '
'; - print img_weather($text, 3, $options); - print ' <= '; - print '
'; - print '
'; + print '
'; + print '
'; + print img_weather($text, 0, $options); + print ' <= '; + print '
'; + print img_weather($text, 1, $options); + print ' <= '; + print '
'; + print img_weather($text, 2, $options); + print ' <= '; + print '
'; + print img_weather($text, 3, $options); + print ' <= '; + print '
'; + print '
'; - print '
'; + print '
'; - print '
global->MAIN_USE_METEO_WITH_PERCENTAGE) ? 'style="display:none;"' : '').'>'; + print '
global->MAIN_USE_METEO_WITH_PERCENTAGE) ? 'style="display:none;"' : '').'>'; - print '
'; - print '
'; - print img_weather($text, 0, $options); - print ' <=  %'; - print '
'; - print img_weather($text, 1, $options); - print ' <=  %'; - print '
'; - print img_weather($text, 2, $options); - print ' <=  %'; - print '
'; - print img_weather($text, 3, $options); - print ' <=  %'; - print '
'; - print '
'; + print '
'; + print '
'; + print img_weather($text, 0, $options); + print ' <=  %'; + print '
'; + print img_weather($text, 1, $options); + print ' <=  %'; + print '
'; + print img_weather($text, 2, $options); + print ' <=  %'; + print '
'; + print img_weather($text, 3, $options); + print ' <=  %'; + print '
'; + print '
'; - print '
'; + print '
'; - ?> + ?> '."\n"; @@ -545,8 +545,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; print ''; // List filters - foreach ($object->filters as $rulefilter) - { + foreach ($object->filters as $rulefilter) { $rulefilterobj = new EmailCollectorFilter($db); $rulefilterobj->fetch($rulefilter['id']); @@ -580,9 +579,15 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea 'loadthirdparty'=>$langs->trans('LoadThirdPartyFromName', $langs->transnoentities("ThirdPartyName")), 'loadandcreatethirdparty'=>$langs->trans('LoadThirdPartyFromNameOrCreate', $langs->transnoentities("ThirdPartyName")), 'recordevent'=>'RecordEvent'); - if ($conf->projet->enabled) $arrayoftypes['project'] = 'CreateLeadAndThirdParty'; - if ($conf->ticket->enabled) $arrayoftypes['ticket'] = 'CreateTicketAndThirdParty'; - if ($conf->recruitment->enabled) $arrayoftypes['candidature'] = 'CreateCandidature'; + if ($conf->projet->enabled) { + $arrayoftypes['project'] = 'CreateLeadAndThirdParty'; + } + if ($conf->ticket->enabled) { + $arrayoftypes['ticket'] = 'CreateTicketAndThirdParty'; + } + if ($conf->recruitment->enabled) { + $arrayoftypes['candidature'] = 'CreateCandidature'; + } // support hook for add action $parameters = array('arrayoftypes' => $arrayoftypes); @@ -591,7 +596,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($res) { $arrayoftypes = $hookmanager->resArray; } else { - foreach ($hookmanager->resArray as $k=>$desc) { + foreach ($hookmanager->resArray as $k => $desc) { $arrayoftypes[$k] = $desc; } } @@ -611,8 +616,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $table_element_line = 'emailcollector_emailcollectoraction'; $fk_element = 'position'; $i = 0; - foreach ($object->actions as $ruleaction) - { + foreach ($object->actions as $ruleaction) { $ruleactionobj = new EmailcollectorAction($db); $ruleactionobj->fetch($ruleaction['id']); @@ -620,16 +624,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; print ''; print $langs->trans($arrayoftypes[$ruleaction['type']]); - if (in_array($ruleaction['type'], array('recordevent'))) - { + if (in_array($ruleaction['type'], array('recordevent'))) { print $form->textwithpicto('', $langs->transnoentitiesnoconv('IfTrackingIDFoundEventWillBeLinked')); } elseif (in_array($ruleaction['type'], array('loadthirdparty', 'loadandcreatethirdparty'))) { print $form->textwithpicto('', $langs->transnoentitiesnoconv('EmailCollectorLoadThirdPartyHelp')); } print ''; print ''; - if ($action == 'editoperation' && $ruleaction['id'] == $operationid) - { + if ($action == 'editoperation' && $ruleaction['id'] == $operationid) { print '
'; print '
'; print ''; @@ -640,8 +642,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; // Move up/down print ''; - if ($i > 0) - { + if ($i > 0) { print ''.img_up('default', 0, 'imgupforline').''; } if ($i < count($object->actions) - 1) { @@ -681,10 +682,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '
'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Edit print ''; @@ -703,8 +705,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '
'."\n"; } - if (!empty($debuginfo)) - { + if (!empty($debuginfo)) { print info_admin($debuginfo); } } diff --git a/htdocs/admin/emailcollector_list.php b/htdocs/admin/emailcollector_list.php index e85a9652075..09a790a9f68 100644 --- a/htdocs/admin/emailcollector_list.php +++ b/htdocs/admin/emailcollector_list.php @@ -51,7 +51,9 @@ $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 < 0 || 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 < 0 || 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; @@ -70,13 +72,16 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Security check $socid = 0; -if ($user->socid > 0) // Protection if external user -{ +if ($user->socid > 0) { // Protection if external user //$socid = $user->socid; accessforbidden(); } @@ -85,22 +90,23 @@ if ($user->socid > 0) // Protection if external user // Initialize array of search criterias $search_all = GETPOST("search_all", 'alphanohtml'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of array of fields for columns $arrayfields = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field if (!empty($val['visible'])) { $visible = dol_eval($val['visible'], 1); @@ -113,10 +119,8 @@ foreach ($object->fields as $key => $val) } } // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], @@ -138,8 +142,12 @@ $permissiontoread = $user->admin; $permissiontoadd = $user->admin; $permissiontodelete = $user->admin; -if (!$user->admin) accessforbidden(); -if (empty($conf->emailcollector->enabled)) accessforbidden('Module not enabled'); +if (!$user->admin) { + accessforbidden(); +} +if (empty($conf->emailcollector->enabled)) { + accessforbidden('Module not enabled'); +} @@ -147,31 +155,33 @@ if (empty($conf->emailcollector->enabled)) accessforbidden('Module not enabled') * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($object->fields as $key => $val) - { + 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 + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $toselect = ''; $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -197,13 +207,14 @@ $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("EmailCollector") // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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.', ' : ''); + 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(); @@ -211,20 +222,32 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -else $sql .= " WHERE 1 = 1"; -foreach ($search as $key => $val) -{ - if ($key == 'status' && $search[$key] == -1) continue; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); if (strpos($object->fields[$key]['type'], 'integer:') === 0) { - if ($search[$key] == '-1') $search[$key] = ''; + if ($search[$key] == '-1') { + $search[$key] = ''; + } $mode_search = 2; } - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -253,26 +276,24 @@ $sql .= $db->order($sortfield, $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 || empty($limit))) -{ +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -281,8 +302,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/emailcollector/emailcollector_card.php?id='.$id); @@ -313,14 +333,24 @@ jQuery(document).ready(function() { $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ - if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); - else $param .= '&search_'.$key.'='.urlencode($search[$key]); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +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'; @@ -329,12 +359,18 @@ $arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -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 ''; @@ -363,11 +399,13 @@ $moreforfilter.= '
';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '
'; print $moreforfilter; print '
'; @@ -384,20 +422,26 @@ print ''; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; } } @@ -419,15 +463,18 @@ print ''."\n"; // Fields title label // -------------------------------------------------------------------- print ''; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -444,11 +491,11 @@ print ''."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -457,38 +504,51 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->setVarsFromFetchObj($obj); // Show here line of result print ''; - foreach ($object->fields as $key => $val) - { + foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; - if ($key == 'status') print $object->getLibStatut(5); - else print $object->showOutputField($val, $key, $object->$key, ''); + if ($key == 'status') { + print $object->getLibStatut(5); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } print ''; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $object->$key; } } @@ -501,14 +561,17 @@ while ($i < ($limit ? min($num, $limit) : $num)) print $hookmanager->resPrint; // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print ''."\n"; @@ -520,10 +583,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 ''; } @@ -539,10 +605,11 @@ print ''."\n"; print ''."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/admin/eventorganization.php b/htdocs/admin/eventorganization.php new file mode 100644 index 00000000000..8625f182f47 --- /dev/null +++ b/htdocs/admin/eventorganization.php @@ -0,0 +1,600 @@ + + * + * 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/admin/setup.php + * \ingroup eventorganization + * \brief EventOrganization setup page. + */ + +// Load Dolibarr environment +require '../main.inc.php'; + +global $langs, $user; + +// Libraries +require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; +require_once DOL_DOCUMENT_ROOT.'/core/lib/eventorganization.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + +// Translations +$langs->loadLangs(array("admin", "eventorganization")); + +// Access control +if (!$user->admin) { + accessforbidden(); +} + +// Parameters +$action = GETPOST('action', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); + +$value = GETPOST('value', 'alpha'); +$label = GETPOST('label', 'alpha'); +$scandir = GETPOST('scan_dir', 'alpha'); +$type = 'myobject'; + +$arrayofparameters = array( + 'EVENTORGANIZATION_TASK_LABEL'=>array('type'=>'textarea','enabled'=>1), + 'EVENTORGANIZATION_CATEG_THIRDPARTY_CONF'=>array('type'=>'category:'.Categorie::TYPE_CUSTOMER, 'enabled'=>1), + 'EVENTORGANIZATION_CATEG_THIRDPARTY_BOOTH'=>array('type'=>'category:'.Categorie::TYPE_CUSTOMER, 'enabled'=>1), + 'EVENTORGANIZATION_TEMPLATE_EMAIL_ASK_CONF'=>array('type'=>'emailtemplate:eventorganization_send', 'enabled'=>1), + 'EVENTORGANIZATION_TEMPLATE_EMAIL_ASK_BOOTH'=>array('type'=>'emailtemplate:eventorganization_send', 'enabled'=>1), + 'EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_BOOTH'=>array('type'=>'emailtemplate:eventorganization_send', 'enabled'=>1), + 'EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_EVENT'=>array('type'=>'emailtemplate:eventorganization_send', 'enabled'=>1), + 'EVENTORGANIZATION_TEMPLATE_EMAIL_BULK_SPEAKER'=>array('type'=>'emailtemplate:eventorganization_send', 'enabled'=>1), + 'EVENTORGANIZATION_TEMPLATE_EMAIL_BULK_ATTENDES'=>array('type'=>'emailtemplate:eventorganization_send', 'enabled'=>1), +); + +$error = 0; +$setupnotempty = 0; + + +/* + * Actions + */ + +if ((float) DOL_VERSION >= 6) { + include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; +} + +if ($action == 'updateMask') { + $maskconstorder = GETPOST('maskconstorder', 'alpha'); + $maskorder = GETPOST('maskorder', 'alpha'); + + if ($maskconstorder) { + $res = dolibarr_set_const($db, $maskconstorder, $maskorder, 'chaine', 0, '', $conf->entity); + if (!($res > 0)) { + $error++; + } + } + + if (!$error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'errors'); + } +} elseif ($action == 'specimen') { + $modele = GETPOST('module', 'alpha'); + $tmpobjectkey = GETPOST('object'); + + $tmpobject = new $tmpobjectkey($db); + $tmpobject->initAsSpecimen(); + + // Search template files + $file = ''; $classname = ''; $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + $file = dol_buildpath($reldir."core/modules/eventorganization/doc/pdf_".$modele."_".strtolower($tmpobjectkey).".modules.php", 0); + if (file_exists($file)) { + $filefound = 1; + $classname = "pdf_".$modele; + break; + } + } + + if ($filefound) { + require_once $file; + + $module = new $classname($db); + + if ($module->write_file($tmpobject, $langs) > 0) { + header("Location: ".DOL_URL_ROOT."/document.php?modulepart=".strtolower($tmpobjectkey)."&file=SPECIMEN.pdf"); + return; + } else { + setEventMessages($module->error, null, 'errors'); + dol_syslog($module->error, LOG_ERR); + } + } else { + setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); + dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); + } +} elseif ($action == 'setmod') { + // TODO Check if numbering module chosen can be activated by calling method canBeActivated + $tmpobjectkey = GETPOST('object'); + if (!empty($tmpobjectkey)) { + $constforval = 'EVENTORGANIZATION_'.strtoupper($tmpobjectkey)."_ADDON"; + dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity); + } +} elseif ($action == 'set') { + // Activate a model + $ret = addDocumentModel($value, $type, $label, $scandir); +} elseif ($action == 'del') { + $ret = delDocumentModel($value, $type); + if ($ret > 0) { + $tmpobjectkey = GETPOST('object'); + if (!empty($tmpobjectkey)) { + $constforval = 'EVENTORGANIZATION_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; + if ($conf->global->$constforval == "$value") { + dolibarr_del_const($db, $constforval, $conf->entity); + } + } + } +} elseif ($action == 'setdoc') { + // Set or unset default model + $tmpobjectkey = GETPOST('object'); + if (!empty($tmpobjectkey)) { + $constforval = 'EVENTORGANIZATION_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; + if (dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity)) { + // The constant that was read before the new set + // We therefore requires a variable to have a coherent view + $conf->global->$constforval = $value; + } + + // We disable/enable the document template (into llx_document_model table) + $ret = delDocumentModel($value, $type); + if ($ret > 0) { + $ret = addDocumentModel($value, $type, $label, $scandir); + } + } +} elseif ($action == 'unsetdoc') { + $tmpobjectkey = GETPOST('object'); + if (!empty($tmpobjectkey)) { + $constforval = 'EVENTORGANIZATION_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; + dolibarr_del_const($db, $constforval, $conf->entity); + } +} + + + +/* + * View + */ + +$form = new Form($db); + +$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + +$page_name = "EventOrganizationSetup"; +llxHeader('', $langs->trans($page_name)); + +// Subheader +$linkback = ''.$langs->trans("BackToModuleList").''; + +print load_fiche_titre($langs->trans($page_name), $linkback, 'eventorganization'); + +// Configuration header +$head = eventorganizationAdminPrepareHead(); +print dol_get_fiche_head($head, 'settings', $langs->trans($page_name), -1, 'eventorganization'); + +// Setup page goes here +echo ''.$langs->trans("EventOrganizationSetupPage").'

'; + + +if ($action == 'edit') { + print '
'; + print ''; + print ''; + + print '
'; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - elseif (strpos($val['type'], 'integer:') === 0) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print ''; + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { + print ''; + } print '
'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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($object->id, $arrayofselected)) $selected = 1; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } print ''; } print '
'.$langs->trans("NoRecordFound").'
'; + print ''; + + foreach ($arrayofparameters as $constname => $val) { + if ($val['enabled']==1) { + $setupnotempty++; + print ''; + } + } + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; + $tooltiphelp = (($langs->trans($constname . 'Tooltip') != $constname . 'Tooltip') ? $langs->trans($constname . 'Tooltip') : ''); + print ''.$form->textwithpicto($langs->trans($constname), $tooltiphelp, 1, 'info', '', 0, 3, 'tootips'.$constname).''; + print ''; + + if ($val['type'] == 'textarea') { + print '\n"; + } elseif ($val['type']== 'html') { + require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; + $doleditor = new DolEditor($constname, $conf->global->{$constname}, '', 160, 'dolibarr_notes', '', false, false, $conf->fckeditor->enabled, ROWS_5, '90%'); + $doleditor->Create(); + } elseif ($val['type'] == 'yesno') { + print $form->selectyesno($constname, $conf->global->{$constname}, 1); + } elseif (preg_match('/emailtemplate:/', $val['type'])) { + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + + $tmp = explode(':', $val['type']); + $nboftemplates = $formmail->fetchAllEMailTemplate($tmp[1], $user, null, 1); // We set lang=null to get in priority record with no lang + //$arraydefaultmessage = $formmail->getEMailTemplate($db, $tmp[1], $user, null, 0, 1, ''); + $arrayofmessagename = array(); + if (is_array($formmail->lines_model)) { + foreach ($formmail->lines_model as $modelmail) { + //var_dump($modelmail); + $moreonlabel = ''; + if (!empty($arrayofmessagename[$modelmail->label])) { + $moreonlabel = ' (' . $langs->trans("SeveralLangugeVariatFound") . ')'; + } + // The 'label' is the key that is unique if we exclude the language + $arrayofmessagename[$modelmail->id] = $langs->trans(preg_replace('/\(|\)/', '', $modelmail->label)) . $moreonlabel; + } + } + print $form->selectarray($constname, $arrayofmessagename, $conf->global->{$constname}, 'None', 0, 0, '', 0, 0, 0, '', '', 1); + } elseif (preg_match('/category:/', $val['type'])) { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; + $formother = new FormOther($db); + + $tmp = explode(':', $val['type']); + print img_picto('', 'category', 'class="pictofixedwidth"'); + print $formother->select_categories($tmp[1], $conf->global->{$constname}, $constname, 0, $langs->trans('CustomersProspectsCategoriesShort')); + } else { + print ''; + } + print '
'; + + print '
'; + print ''; + print '
'; + + print ''; + print '
'; +} else { + if (!empty($arrayofparameters)) { + print ''; + print ''; + + foreach ($arrayofparameters as $constname => $val) { + if ($val['enabled']==1) { + $setupnotempty++; + print ''; + } + } + + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; + $tooltiphelp = (($langs->trans($constname . 'Tooltip') != $constname . 'Tooltip') ? $langs->trans($constname . 'Tooltip') : ''); + print $form->textwithpicto($langs->trans($constname), $tooltiphelp); + print ''; + + if ($val['type'] == 'textarea') { + print dol_nl2br($conf->global->{$constname}); + } elseif ($val['type']== 'html') { + print $conf->global->{$constname}; + } elseif ($val['type'] == 'yesno') { + print ajax_constantonoff($constname); + } elseif (preg_match('/emailtemplate:/', $val['type'])) { + if (!empty($conf->global->{$constname})) { + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + + $tmp = explode(':', $val['type']); + + $template = $formmail->getEMailTemplate($db, $tmp[1], $user, $langs, $conf->global->{$constname}); + if ($template < 0) { + setEventMessages(null, $formmail->errors, 'errors'); + } + print $langs->trans($template->label); + } + } elseif (preg_match('/category:/', $val['type'])) { + if (!empty($conf->global->{$constname})) { + $c = new Categorie($db); + $result = $c->fetch($conf->global->{$constname}); + if ($result < 0) { + setEventMessages(null, $c->errors, 'errors'); + } + $ways = $c->print_all_ways(' >> ', 'none', 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text + $toprint = array(); + foreach ($ways as $way) { + $toprint[] = '
  • color ? ' style="background: #' . $c->color . ';"' : ' style="background: #bbb"') . '>' . $way . '
  • '; + } + print '
      ' . implode(' ', $toprint) . '
    '; + } + } else { + print $conf->global->{$constname}; + } + print '
    '; + + print '
    '; + print ''.$langs->trans("Modify").''; + print '
    '; + } else { + print '
    '.$langs->trans("NothingToSetup"); + } +} + + +$moduledir = 'eventorganization'; +$myTmpObjects = array(); +$myTmpObjects['MyObject'] = array('includerefgeneration'=>0, 'includedocgeneration'=>0); + + +foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { + if ($myTmpObjectKey == 'MyObject') { + continue; + } + if ($myTmpObjectArray['includerefgeneration']) { + /* + * Orders Numbering model + */ + $setupnotempty++; + + print load_fiche_titre($langs->trans("NumberingModules", $myTmpObjectKey), '', ''); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''."\n"; + + clearstatcache(); + + foreach ($dirmodels as $reldir) { + $dir = dol_buildpath($reldir."core/modules/".$moduledir); + + if (is_dir($dir)) { + $handle = opendir($dir); + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php') { + $file = substr($file, 0, dol_strlen($file) - 4); + + require_once $dir.'/'.$file.'.php'; + + $module = new $file($db); + + // Show modules according to features level + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } + + if ($module->isEnabled()) { + dol_include_once('/'.$moduledir.'/class/'.strtolower($myTmpObjectKey).'.class.php'); + + print ''; + + // Show example of numbering model + print ''."\n"; + + print ''; + + $mytmpinstance = new $myTmpObjectKey($db); + $mytmpinstance->initAsSpecimen(); + + // Info + $htmltooltip = ''; + $htmltooltip .= ''.$langs->trans("Version").': '.$module->getVersion().'
    '; + + $nextval = $module->getNextValue($mytmpinstance); + if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval + $htmltooltip .= ''.$langs->trans("NextValue").': '; + if ($nextval) { + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { + $nextval = $langs->trans($nextval); + } + $htmltooltip .= $nextval.'
    '; + } else { + $htmltooltip .= $langs->trans($module->error).'
    '; + } + } + + print ''; + + print "\n"; + } + } + } + closedir($handle); + } + } + } + print "
    '.$langs->trans("Name").''.$langs->trans("Description").''.$langs->trans("Example").''.$langs->trans("Status").''.$langs->trans("ShortInfo").'
    '.$module->name."\n"; + print $module->info(); + print ''; + $tmp = $module->getExample(); + if (preg_match('/^Error/', $tmp)) { + $langs->load("errors"); + print '
    '.$langs->trans($tmp).'
    '; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; + } + print '
    '; + $constforvar = 'EVENTORGANIZATION_'.strtoupper($myTmpObjectKey).'_ADDON'; + if ($conf->global->$constforvar == $file) { + print img_picto($langs->trans("Activated"), 'switch_on'); + } else { + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; + } + print ''; + print $form->textwithpicto('', $htmltooltip, 1, 0); + print '

    \n"; + } + + if ($myTmpObjectArray['includedocgeneration']) { + /* + * Document templates generators + */ + $setupnotempty++; + $type = strtolower($myTmpObjectKey); + + print load_fiche_titre($langs->trans("DocumentModules", $myTmpObjectKey), '', ''); + + // Load array def with activated templates + $def = array(); + $sql = "SELECT nom"; + $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; + $sql .= " WHERE type = '".$db->escape($type)."'"; + $sql .= " AND entity = ".$conf->entity; + $resql = $db->query($sql); + if ($resql) { + $i = 0; + $num_rows = $db->num_rows($resql); + while ($i < $num_rows) { + $array = $db->fetch_array($resql); + array_push($def, $array[0]); + $i++; + } + } else { + dol_print_error($db); + } + + print "\n"; + print "\n"; + print ''; + print ''; + print '\n"; + print '\n"; + print ''; + print ''; + print "\n"; + + clearstatcache(); + + foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { + $realpath = $reldir."core/modules/".$moduledir.$valdir; + $dir = dol_buildpath($realpath); + + if (is_dir($dir)) { + $handle = opendir($dir); + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + $filelist[] = $file; + } + closedir($handle); + arsort($filelist); + + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { + $name = substr($file, 4, dol_strlen($file) - 16); + $classname = substr($file, 0, dol_strlen($file) - 12); + + require_once $dir.'/'.$file; + $module = new $classname($db); + + $modulequalified = 1; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + $modulequalified = 0; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + $modulequalified = 0; + } + + if ($modulequalified) { + print ''; + + // Active + if (in_array($name, $def)) { + print ''; + } else { + print '"; + } + + // Default + print ''; + + // Info + $htmltooltip = ''.$langs->trans("Name").': '.$module->name; + $htmltooltip .= '
    '.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); + if ($module->type == 'pdf') { + $htmltooltip .= '
    '.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + } + $htmltooltip .= '
    '.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + + $htmltooltip .= '

    '.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
    '.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); + $htmltooltip .= '
    '.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); + + print ''; + + // Preview + print ''; + + print "\n"; + } + } + } + } + } + } + } + } + + print '
    '.$langs->trans("Name").''.$langs->trans("Description").''.$langs->trans("Status")."'.$langs->trans("Default")."'.$langs->trans("ShortInfo").''.$langs->trans("Preview").'
    '; + print (empty($module->name) ? $name : $module->name); + print "\n"; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } + print ''."\n"; + 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 "'; + $constforvar = 'EVENTORGANIZATION_'.strtoupper($myTmpObjectKey).'_ADDON'; + if ($conf->global->$constforvar == $name) { + //print img_picto($langs->trans("Default"), 'on'); + // Even if choice is the default value, we allow to disable it. Replace this with previous line if you need to disable unset + print 'scandir.'&label='.urlencode($module->name).'&type='.urlencode($type).'" alt="'.$langs->trans("Disable").'">'.img_picto($langs->trans("Enabled"), 'on').''; + } else { + print 'scandir).'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; + } + print ''; + print $form->textwithpicto('', $htmltooltip, 1, 0); + print ''; + if ($module->type == 'pdf') { + print ''.img_object($langs->trans("Preview"), 'pdf').''; + } else { + print img_object($langs->trans("PreviewNotAvailable"), 'generic'); + } + print '
    '; + } +} + +if (empty($setupnotempty)) { + print '
    '.$langs->trans("NothingToSetup"); +} + +// Page end +print dol_get_fiche_end(); + +llxFooter(); +$db->close(); diff --git a/htdocs/admin/eventorganization_confbooth_extrafields.php b/htdocs/admin/eventorganization_confbooth_extrafields.php new file mode 100644 index 00000000000..4b6f9bdc46a --- /dev/null +++ b/htdocs/admin/eventorganization_confbooth_extrafields.php @@ -0,0 +1,109 @@ + + * + * 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/admin/eventorganization_extrafields.php + * \ingroup bom + * \brief Page to setup extra fields of EventOrganization + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/eventorganization.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array('eventorganization', 'admin')); + +$extrafields = new ExtraFields($db); +$form = new Form($db); + +// List of supported format +$tmptype2label = ExtraFields::$type2label; +$type2label = array(''); +foreach ($tmptype2label as $key => $val) { + $type2label[$key] = $langs->transnoentitiesnoconv($val); +} + +$action = GETPOST('action', 'aZ09'); +$attrname = GETPOST('attrname', 'alpha'); +$elementtype = 'actioncomm'; + +if (!$user->admin) { + accessforbidden(); +} + + +/* + * Actions + */ + +require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; + + + +/* + * View + */ + + +llxHeader('', $langs->trans("EventOrganizationSetup")); + + +$linkback = ''.$langs->trans("BackToModuleList").''; +print load_fiche_titre($langs->trans("EventOrganizationSetup"), $linkback, 'eventorganization'); + + +$head = eventorganizationAdminPrepareHead(); + +print dol_get_fiche_head($head, 'eventorganization_extrafields', $langs->trans("ExtraFields"), -1, 'eventorganization'); + +require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; + +print dol_get_fiche_end(); + + +// Buttons +if ($action != 'create' && $action != 'edit') { + print '
    '; + print "".$langs->trans("NewAttribute").""; + print "
    "; +} + + +/* + * Creation of an optional field + */ +if ($action == 'create') { + print '
    '; + print load_fiche_titre($langs->trans('NewAttribute')); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php'; +} + +/* + * Edition of an optional field + */ +if ($action == 'edit' && !empty($attrname)) { + print "
    "; + print load_fiche_titre($langs->trans("FieldEdition", $attrname)); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php'; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/admin/events.php b/htdocs/admin/events.php index 66099eb3a30..6216820166e 100644 --- a/htdocs/admin/events.php +++ b/htdocs/admin/events.php @@ -44,7 +44,9 @@ $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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -57,17 +59,18 @@ $eventstolog = $securityevent->eventstolog; * Actions */ -if ($action == "save") -{ +if ($action == "save") { $i = 0; $db->begin(); - foreach ($eventstolog as $key => $arr) - { + foreach ($eventstolog as $key => $arr) { $param = 'MAIN_LOGEVENTS_'.$arr['id']; - if (GETPOST($param, 'alphanohtml')) dolibarr_set_const($db, $param, GETPOST($param, 'alphanohtml'), 'chaine', 0, '', $conf->entity); - else dolibarr_del_const($db, $param, $conf->entity); + if (GETPOST($param, 'alphanohtml')) { + dolibarr_set_const($db, $param, GETPOST($param, 'alphanohtml'), 'chaine', 0, '', $conf->entity); + } else { + dolibarr_del_const($db, $param, $conf->entity); + } } $db->commit(); @@ -110,10 +113,8 @@ print getTitleFieldOfList("LogEvents", 0, $_SERVER["PHP_SELF"], '', '', '', '', print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; print "\n"; // Loop on each event type -foreach ($eventstolog as $key => $arr) -{ - if ($arr['id']) - { +foreach ($eventstolog as $key => $arr) { + if ($arr['id']) { print ''; print ''.$arr['id'].''; print ''; diff --git a/htdocs/admin/expedition.php b/htdocs/admin/expedition.php index 9a09c62b818..8be9aeee0bc 100644 --- a/htdocs/admin/expedition.php +++ b/htdocs/admin/expedition.php @@ -37,8 +37,9 @@ require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "sendings", "deliveries", "other")); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); @@ -46,8 +47,7 @@ $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); $type = 'shipping'; -if (empty($conf->global->EXPEDITION_ADDON_NUMBER)) -{ +if (empty($conf->global->EXPEDITION_ADDON_NUMBER)) { $conf->global->EXPEDITION_ADDON_NUMBER = 'mod_expedition_safor'; } @@ -58,43 +58,39 @@ if (empty($conf->global->EXPEDITION_ADDON_NUMBER)) include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; -if ($action == 'updateMask') -{ +if ($action == 'updateMask') { $maskconst = GETPOST('maskconstexpedition', 'alpha'); $maskvalue = GETPOST('maskexpedition', 'alpha'); - if (!empty($maskconst)) + if (!empty($maskconst)) { $res = dolibarr_set_const($db, $maskconst, $maskvalue, 'chaine', 0, '', $conf->entity); - - if (isset($res)) - { - if ($res > 0) - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - else setEventMessages($langs->trans("Error"), null, 'errors'); } -} elseif ($action == 'set_param') -{ + + if (isset($res)) { + if ($res > 0) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'errors'); + } + } +} elseif ($action == 'set_param') { $freetext = GETPOST('SHIPPING_FREE_TEXT', 'restricthtml'); // No alpha here, we want exact string $res = dolibarr_set_const($db, "SHIPPING_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity); - if ($res <= 0) - { + if ($res <= 0) { $error++; setEventMessages($langs->trans("Error"), null, 'errors'); } $draft = GETPOST('SHIPPING_DRAFT_WATERMARK', 'alpha'); $res = dolibarr_set_const($db, "SHIPPING_DRAFT_WATERMARK", trim($draft), 'chaine', 0, '', $conf->entity); - if ($res <= 0) - { + if ($res <= 0) { $error++; setEventMessages($langs->trans("Error"), null, 'errors'); } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } -} elseif ($action == 'specimen') -{ +} elseif ($action == 'specimen') { $modele = GETPOST('module', 'alpha'); $exp = new Expedition($db); @@ -103,25 +99,21 @@ if ($action == 'updateMask') // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/expedition/doc/pdf_".$modele.".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db); - if ($module->write_file($exp, $langs) > 0) - { + if ($module->write_file($exp, $langs) > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=expedition&file=SPECIMEN.pdf"); return; } else { @@ -132,26 +124,19 @@ if ($action == 'updateMask') setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); } -} - -// Activate a model -elseif ($action == 'set') -{ +} elseif ($action == 'set') { + // Activate a model $ret = addDocumentModel($value, $type, $label, $scandir); -} elseif ($action == 'del') -{ +} elseif ($action == 'del') { $ret = delDocumentModel($value, $type); - if ($ret > 0) - { - if ($conf->global->EXPEDITION_ADDON_PDF == "$value") dolibarr_del_const($db, 'EXPEDITION_ADDON_PDF', $conf->entity); + if ($ret > 0) { + if ($conf->global->EXPEDITION_ADDON_PDF == "$value") { + dolibarr_del_const($db, 'EXPEDITION_ADDON_PDF', $conf->entity); + } } -} - -// Set default model -elseif ($action == 'setdoc') -{ - if (dolibarr_set_const($db, "EXPEDITION_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) - { +} elseif ($action == 'setdoc') { + // Set default model + if (dolibarr_set_const($db, "EXPEDITION_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { // La constante qui a ete lue en avant du nouveau set // on passe donc par une variable pour avoir un affichage coherent $conf->global->EXPEDITION_ADDON_PDF = $value; @@ -159,12 +144,10 @@ elseif ($action == 'setdoc') // On active le modele $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, $type, $label, $scandir); } -} elseif ($action == 'setmodel') -{ +} elseif ($action == 'setmodel') { dolibarr_set_const($db, "EXPEDITION_ADDON_NUMBER", $value, 'chaine', 0, '', $conf->entity); } @@ -201,17 +184,13 @@ print "\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ +foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/expedition/"); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { if (preg_match('/^mod_expedition_([a-z0-9_]*)\.php$/', $file)) { $file = substr($file, 0, dol_strlen($file) - 4); @@ -219,11 +198,14 @@ foreach ($dirmodels as $reldir) $module = new $file; - if ($module->isEnabled()) - { + if ($module->isEnabled()) { // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } print ''.$module->name."\n"; print ''; @@ -236,13 +218,15 @@ foreach ($dirmodels as $reldir) if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '
    '.$langs->trans($tmp).'
    '; - } elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); - else print $tmp; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; + } print ''."\n"; print ''; - if ($conf->global->EXPEDITION_ADDON_NUMBER == "$file") - { + if ($conf->global->EXPEDITION_ADDON_NUMBER == "$file") { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print 'scandir.'&label='.urlencode($module->name).'">'; @@ -261,8 +245,9 @@ foreach ($dirmodels as $reldir) if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { $nextval = $langs->trans($nextval); + } $htmltooltip .= $nextval.'
    '; } else { $htmltooltip .= $langs->trans($module->error).'
    '; @@ -300,12 +285,10 @@ $sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -326,30 +309,22 @@ print "\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ - foreach (array('', '/doc') as $valdir) - { +foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { $dir = dol_buildpath($reldir."core/modules/expedition".$valdir); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -357,21 +332,26 @@ 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 == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print ''; print (empty($module->name) ? $name : $module->name); print "\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print ''; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print ''."\n"; print '
    '; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -385,8 +365,7 @@ foreach ($dirmodels as $reldir) // Defaut print ''; - if ($conf->global->EXPEDITION_ADDON_PDF == $name) - { + if ($conf->global->EXPEDITION_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').''; @@ -396,8 +375,7 @@ foreach ($dirmodels as $reldir) // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '
    '.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '
    '.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } $htmltooltip .= '

    '.$langs->trans("FeaturesSupported").':'; @@ -413,8 +391,7 @@ foreach ($dirmodels as $reldir) // Preview print ''; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print 'scandir.'&label='.urlencode($module->name).'">'.img_object($langs->trans("Preview"), 'pdf').''; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); @@ -453,14 +430,15 @@ print ""; $substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
    '; -foreach ($substitutionarray as $key => $val) $htmltext .= $key.'
    '; +foreach ($substitutionarray as $key => $val) { + $htmltext .= $key.'
    '; +} $htmltext .= '
    '; print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnShippings"), $langs->trans("AddCRIfTooLong").'

    '.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
    '; $variablename = 'SHIPPING_FREE_TEXT'; -if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) -{ +if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; diff --git a/htdocs/admin/expedition_extrafields.php b/htdocs/admin/expedition_extrafields.php index 901caf58c00..70a9629e1d6 100644 --- a/htdocs/admin/expedition_extrafields.php +++ b/htdocs/admin/expedition_extrafields.php @@ -32,8 +32,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/expedition.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'sendings', 'deliveries')); @@ -45,13 +46,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 = 'expedition'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -84,8 +89,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -98,8 +102,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '
    '; print load_fiche_titre($langs->trans('NewAttribute')); @@ -111,8 +114,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
    "; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/admin/expeditiondet_extrafields.php b/htdocs/admin/expeditiondet_extrafields.php index 6f917618bf2..7df27d0d84b 100644 --- a/htdocs/admin/expeditiondet_extrafields.php +++ b/htdocs/admin/expeditiondet_extrafields.php @@ -34,8 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/expedition.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'sendings')); @@ -46,13 +47,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 = 'expeditiondet'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -85,8 +90,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -99,8 +103,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '
    '; print load_fiche_titre($langs->trans('NewAttribute')); @@ -112,8 +115,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
    "; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/admin/expensereport_extrafields.php b/htdocs/admin/expensereport_extrafields.php index ac88ec78912..716ba5d1a03 100644 --- a/htdocs/admin/expensereport_extrafields.php +++ b/htdocs/admin/expensereport_extrafields.php @@ -30,8 +30,9 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/expensereport.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('admin', 'errors', 'trips', 'other')); @@ -42,13 +43,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 = 'expensereport'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -78,8 +83,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -92,8 +96,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '
    '; print load_fiche_titre($langs->trans('NewAttribute')); @@ -105,8 +108,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
    "; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/admin/expensereport_ik.php b/htdocs/admin/expensereport_ik.php index 968833b764c..bdaaa5845f3 100644 --- a/htdocs/admin/expensereport_ik.php +++ b/htdocs/admin/expensereport_ik.php @@ -33,7 +33,9 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_ik.class.php' // Load translation files required by the page $langs->loadLangs(array("admin", "trips", "errors", "other", "dict")); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $error = 0; @@ -45,13 +47,13 @@ $coef = GETPOST('coef', 'int'); $fk_c_exp_tax_cat = GETPOST('fk_c_exp_tax_cat'); $fk_range = GETPOST('fk_range'); -if ($action == 'updateik') -{ +if ($action == 'updateik') { $expIk = new ExpenseReportIk($db); - if ($id > 0) - { + if ($id > 0) { $result = $expIk->fetch($id); - if ($result < 0) dol_print_error('', $expIk->error, $expIk->errors); + if ($result < 0) { + dol_print_error('', $expIk->error, $expIk->errors); + } } $expIk->setValues($_POST); @@ -64,13 +66,13 @@ if ($action == 'updateik') } else { setEventMessages($expIk->error, $expIk->errors, 'errors'); } -} elseif ($action == 'delete') // TODO add confirm -{ +} elseif ($action == 'delete') { // TODO add confirm $expIk = new ExpenseReportIk($db); - if ($id > 0) - { + if ($id > 0) { $result = $expIk->fetch($id); - if ($result < 0) dol_print_error('', $expIk->error, $expIk->errors); + if ($result < 0) { + dol_print_error('', $expIk->error, $expIk->errors); + } $expIk->delete($user); } @@ -102,8 +104,7 @@ print '

    '; echo '
    '; -if ($action == 'edit') -{ +if ($action == 'edit') { echo ''; echo ''; echo ''; @@ -114,8 +115,7 @@ echo ''; echo ''; -foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) -{ +foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) { $title = ($Tab['active'] == 1) ? $langs->trans($Tab['label']) : $form->textwithpicto($langs->trans($Tab['label']), $langs->trans('expenseReportCatDisabled'), 1, 'help', '', 0, 3); echo ''; echo ''; @@ -125,16 +125,22 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) echo ''; echo ''; - if ($Tab['active'] == 0) continue; + if ($Tab['active'] == 0) { + continue; + } $tranche = 1; - foreach ($Tab['ranges'] as $k => $range) - { - if (isset($Tab['ranges'][$k + 1])) $label = $langs->trans('expenseReportRangeFromTo', $range->range_ik, ($Tab['ranges'][$k + 1]->range_ik - 1)); - else $label = $langs->trans('expenseReportRangeMoreThan', $range->range_ik); + foreach ($Tab['ranges'] as $k => $range) { + if (isset($Tab['ranges'][$k + 1])) { + $label = $langs->trans('expenseReportRangeFromTo', $range->range_ik, ($Tab['ranges'][$k + 1]->range_ik - 1)); + } else { + $label = $langs->trans('expenseReportRangeMoreThan', $range->range_ik); + } - if ($range->range_active == 0) $label = $form->textwithpicto($label, $langs->trans('expenseReportRangeDisabled'), 1, 'help', '', 0, 3); + if ($range->range_active == 0) { + $label = $form->textwithpicto($label, $langs->trans('expenseReportRangeDisabled'), 1, 'help', '', 0, 3); + } echo ''; @@ -143,15 +149,19 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) // Offset echo ''; // Coef echo ''; // Total for one @@ -159,15 +169,15 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) // Action echo ''; print ""; print ""; print ''."\n"; // Logo - if ($result > 0 && empty($rss->error)) - { + if ($result > 0 && empty($rss->error)) { print ''; print ""; print ''; print ''."\n"; } @@ -336,10 +334,8 @@ $db->close(); */ function _isInBoxList($idrss, array $boxlist) { - foreach ($boxlist as $box) - { - if ($box->boxcode === "lastrssinfos" && strpos($box->note, $idrss) !== false) - { + foreach ($boxlist as $box) { + if ($box->boxcode === "lastrssinfos" && strpos($box->note, $idrss) !== false) { return true; } } diff --git a/htdocs/admin/facture.php b/htdocs/admin/facture.php index c5b8262c4be..a16df0d7fc4 100644 --- a/htdocs/admin/facture.php +++ b/htdocs/admin/facture.php @@ -36,7 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'errors', 'other', 'bills')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); @@ -51,8 +53,7 @@ $type = 'invoice'; include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; -if ($action == 'updateMask') -{ +if ($action == 'updateMask') { $maskconstinvoice = GETPOST('maskconstinvoice', 'alpha'); $maskconstreplacement = GETPOST('maskconstreplacement', 'alpha'); $maskconstcredit = GETPOST('maskconstcredit', 'alpha'); @@ -61,21 +62,29 @@ if ($action == 'updateMask') $maskreplacement = GETPOST('maskreplacement', 'alpha'); $maskcredit = GETPOST('maskcredit', 'alpha'); $maskdeposit = GETPOST('maskdeposit', 'alpha'); - if ($maskconstinvoice) $res = dolibarr_set_const($db, $maskconstinvoice, $maskinvoice, 'chaine', 0, '', $conf->entity); - if ($maskconstreplacement) $res = dolibarr_set_const($db, $maskconstreplacement, $maskreplacement, 'chaine', 0, '', $conf->entity); - if ($maskconstcredit) $res = dolibarr_set_const($db, $maskconstcredit, $maskcredit, 'chaine', 0, '', $conf->entity); - if ($maskconstdeposit) $res = dolibarr_set_const($db, $maskconstdeposit, $maskdeposit, 'chaine', 0, '', $conf->entity); + if ($maskconstinvoice) { + $res = dolibarr_set_const($db, $maskconstinvoice, $maskinvoice, 'chaine', 0, '', $conf->entity); + } + if ($maskconstreplacement) { + $res = dolibarr_set_const($db, $maskconstreplacement, $maskreplacement, 'chaine', 0, '', $conf->entity); + } + if ($maskconstcredit) { + $res = dolibarr_set_const($db, $maskconstcredit, $maskcredit, 'chaine', 0, '', $conf->entity); + } + if ($maskconstdeposit) { + $res = dolibarr_set_const($db, $maskconstdeposit, $maskdeposit, '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'); } -} elseif ($action == 'specimen') -{ +} elseif ($action == 'specimen') { $modele = GETPOST('module', 'alpha'); $facture = new Facture($db); @@ -84,25 +93,21 @@ if ($action == 'updateMask') // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/facture/doc/pdf_".$modele.".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db); - if ($module->write_file($facture, $langs) > 0) - { + if ($module->write_file($facture, $langs) > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=facture&file=SPECIMEN.pdf"); return; } else { @@ -113,24 +118,19 @@ if ($action == 'updateMask') setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); } -} -// Activate a model -elseif ($action == 'set') -{ +} elseif ($action == 'set') { + // Activate a model $ret = addDocumentModel($value, $type, $label, $scandir); -} elseif ($action == 'del') -{ +} elseif ($action == 'del') { $ret = delDocumentModel($value, $type); - if ($ret > 0) - { - if ($conf->global->FACTURE_ADDON_PDF == "$value") dolibarr_del_const($db, 'FACTURE_ADDON_PDF', $conf->entity); + if ($ret > 0) { + if ($conf->global->FACTURE_ADDON_PDF == "$value") { + dolibarr_del_const($db, 'FACTURE_ADDON_PDF', $conf->entity); + } } -} -// Set default model -elseif ($action == 'setdoc') -{ - if (dolibarr_set_const($db, "FACTURE_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) - { +} elseif ($action == 'setdoc') { + // Set default model + if (dolibarr_set_const($db, "FACTURE_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { // La constante qui a ete lue en avant du nouveau set // on passe donc par une variable pour avoir un affichage coherent $conf->global->FACTURE_ADDON_PDF = $value; @@ -138,90 +138,86 @@ elseif ($action == 'setdoc') // On active le modele $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, $type, $label, $scandir); } -} elseif ($action == 'setmod') -{ +} elseif ($action == 'setmod') { // TODO Verifier si module numerotation choisi peut etre active // par appel methode canBeActivated dolibarr_set_const($db, "FACTURE_ADDON", $value, 'chaine', 0, '', $conf->entity); -} elseif ($action == 'setribchq') -{ +} elseif ($action == 'setribchq') { $rib = GETPOST('rib', 'alpha'); $chq = GETPOST('chq', 'alpha'); $res = dolibarr_set_const($db, "FACTURE_RIB_NUMBER", $rib, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "FACTURE_CHQ_NUMBER", $chq, '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'); } -} elseif ($action == 'set_FACTURE_DRAFT_WATERMARK') -{ +} elseif ($action == 'set_FACTURE_DRAFT_WATERMARK') { $draft = GETPOST('FACTURE_DRAFT_WATERMARK', 'alpha'); $res = dolibarr_set_const($db, "FACTURE_DRAFT_WATERMARK", trim($draft), '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'); } -} elseif ($action == 'set_INVOICE_FREE_TEXT') -{ +} elseif ($action == 'set_INVOICE_FREE_TEXT') { $freetext = GETPOST('INVOICE_FREE_TEXT', 'restricthtml'); // No alpha here, we want exact string $res = dolibarr_set_const($db, "INVOICE_FREE_TEXT", $freetext, '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'); } -} elseif ($action == 'setforcedate') -{ +} elseif ($action == 'setforcedate') { $forcedate = GETPOST('forcedate', 'alpha'); $res = dolibarr_set_const($db, "FAC_FORCE_DATE_VALIDATION", $forcedate, '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'); } -} elseif ($action == 'setDefaultPDFModulesByType') -{ +} elseif ($action == 'setDefaultPDFModulesByType') { $invoicetypemodels = GETPOST('invoicetypemodels'); - if (!empty($invoicetypemodels) && is_array($invoicetypemodels)) - { + if (!empty($invoicetypemodels) && is_array($invoicetypemodels)) { $error = 0; - foreach ($invoicetypemodels as $type => $value) - { + foreach ($invoicetypemodels as $type => $value) { $res = dolibarr_set_const($db, 'FACTURE_ADDON_PDF_'.intval($type), $value, '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'); @@ -264,44 +260,42 @@ print ''."\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ +foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/facture/"); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (!is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (!is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) { $filebis = $file; $classname = preg_replace('/\.php$/', '', $file); // For compatibility - if (!is_file($dir.$filebis)) - { + if (!is_file($dir.$filebis)) { $filebis = $file."/".$file.".modules.php"; $classname = "mod_facture_".$file; } // Check if there is a filter on country preg_match('/\-(.*)_(.*)$/', $classname, $reg); - if (!empty($reg[2]) && $reg[2] != strtoupper($mysoc->country_code)) continue; + if (!empty($reg[2]) && $reg[2] != strtoupper($mysoc->country_code)) { + continue; + } $classname = preg_replace('/\-.*$/', '', $classname); - if (!class_exists($classname) && is_readable($dir.$filebis) && (preg_match('/mod_/', $filebis) || preg_match('/mod_/', $classname)) && substr($filebis, dol_strlen($filebis) - 3, 3) == 'php') - { + if (!class_exists($classname) && is_readable($dir.$filebis) && (preg_match('/mod_/', $filebis) || preg_match('/mod_/', $classname)) && substr($filebis, dol_strlen($filebis) - 3, 3) == 'php') { // Charging the numbering class require_once $dir.$filebis; $module = new $classname($db); // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } - if ($module->isEnabled()) - { + if ($module->isEnabled()) { print ''."\n"; print ''; @@ -426,12 +427,10 @@ $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; $sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -454,31 +453,23 @@ clearstatcache(); $activatedModels = array(); -foreach ($dirmodels as $reldir) -{ - foreach (array('', '/doc') as $valdir) - { +foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { $realpath = $reldir."core/modules/facture".$valdir; $dir = dol_buildpath($realpath); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -486,21 +477,26 @@ 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 == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print ''; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print '
    '.$title.' 
    '; - if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) echo ''; - else { + if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) { + echo ''; + } else { echo $range->ik->ikoffset; } echo ''; - if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) echo ''; - else echo ($range->ik->id > 0 ? $range->ik->coef : $langs->trans('expenseReportCoefUndefined')); + if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) { + echo ''; + } else { + echo ($range->ik->id > 0 ? $range->ik->coef : $langs->trans('expenseReportCoefUndefined')); + } echo ''; - if ($range->range_active == 1) - { - if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) - { + if ($range->range_active == 1) { + if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) { echo ''; echo ''; } else { echo ''.img_edit().''; - if (!empty($range->ik->id)) echo ''.img_delete().''; + if (!empty($range->ik->id)) { + echo ''.img_delete().''; + } // TODO add delete link } } diff --git a/htdocs/admin/export.php b/htdocs/admin/export.php index 5dd541b34b5..b83b15571b8 100644 --- a/htdocs/admin/export.php +++ b/htdocs/admin/export.php @@ -34,8 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'exports', 'other')); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); diff --git a/htdocs/admin/external_rss.php b/htdocs/admin/external_rss.php index 48db3ee4429..bbb0f212707 100644 --- a/htdocs/admin/external_rss.php +++ b/htdocs/admin/external_rss.php @@ -37,7 +37,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; $langs->load("admin"); // Security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $def = array(); $lastexternalrss = 0; @@ -53,59 +55,56 @@ $sql = "SELECT ".$db->decrypt('name')." as name FROM ".MAIN_DB_PREFIX."const"; $sql .= " WHERE ".$db->decrypt('name')." LIKE 'EXTERNAL_RSS_URLRSS_%'"; //print $sql; $result = $db->query($sql); // We can't use SELECT MAX() because EXTERNAL_RSS_URLRSS_10 is lower than EXTERNAL_RSS_URLRSS_9 -if ($result) -{ - while ($obj = $db->fetch_object($result)) - { +if ($result) { + while ($obj = $db->fetch_object($result)) { preg_match('/([0-9]+)$/i', $obj->name, $reg); - if ($reg[1] && $reg[1] > $lastexternalrss) $lastexternalrss = $reg[1]; + if ($reg[1] && $reg[1] > $lastexternalrss) { + $lastexternalrss = $reg[1]; + } } } else { dol_print_error($db); } -if ($action == 'add' || GETPOST("modify")) -{ +if ($action == 'add' || GETPOST("modify")) { $external_rss_title = "external_rss_title_".GETPOST("norss", 'int'); $external_rss_urlrss = "external_rss_urlrss_".GETPOST("norss", 'int'); - if (!empty($_POST[$external_rss_urlrss])) - { + if (!empty($_POST[$external_rss_urlrss])) { $boxlabel = '(ExternalRSSInformations)'; //$external_rss_url = "external_rss_url_" . $_POST["norss"]; $db->begin(); - if ($_POST["modify"]) - { + if ($_POST["modify"]) { // Supprime boite box_external_rss de definition des boites /* $sql = "UPDATE ".MAIN_DB_PREFIX."boxes_def"; $sql.= " SET name = '".$db->escape($boxlabel)."'"; - $sql.= " WHERE file ='box_external_rss.php' AND note like '".$db->escape($_POST["norss"])." %'"; + $sql.= " WHERE file ='box_external_rss.php' AND note like '".$db->escape($_POST["norss"])." %'"; $resql=$db->query($sql); if (! $resql) - { + { dol_print_error($db,"sql=$sql"); exit; - } - */ + } + */ } else { // Ajoute boite box_external_rss dans definition des boites $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes_def (file, note)"; $sql .= " VALUES ('box_external_rss.php','".$db->escape(GETPOST("norss", 'int').' ('.GETPOST($external_rss_title, 'alpha')).")')"; - if (!$db->query($sql)) - { + if (!$db->query($sql)) { dol_print_error($db); $err++; } } $result1 = dolibarr_set_const($db, "EXTERNAL_RSS_TITLE_".GETPOST("norss", 'int'), GETPOST($external_rss_title, 'alpha'), 'chaine', 0, '', $conf->entity); - if ($result1) $result2 = dolibarr_set_const($db, "EXTERNAL_RSS_URLRSS_".GETPOST("norss", 'int'), GETPOST($external_rss_urlrss, 'alpha'), 'chaine', 0, '', $conf->entity); + if ($result1) { + $result2 = dolibarr_set_const($db, "EXTERNAL_RSS_URLRSS_".GETPOST("norss", 'int'), GETPOST($external_rss_urlrss, 'alpha'), 'chaine', 0, '', $conf->entity); + } - if ($result1 && $result2) - { + if ($result1 && $result2) { $db->commit(); header("Location: ".$_SERVER["PHP_SELF"]); exit; @@ -116,10 +115,8 @@ if ($action == 'add' || GETPOST("modify")) } } -if ($_POST["delete"]) -{ - if (GETPOST("norss", 'int')) - { +if ($_POST["delete"]) { + if (GETPOST("norss", 'int')) { $db->begin(); // Supprime boite box_external_rss de definition des boites @@ -127,12 +124,10 @@ if ($_POST["delete"]) $sql .= " WHERE file = 'box_external_rss.php' AND note LIKE '".$db->escape(GETPOST("norss", 'int'))." %'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes"; @@ -144,8 +139,7 @@ if ($_POST["delete"]) $sql .= " WHERE rowid = ".$obj->rowid; $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { $db->rollback(); dol_print_error($db, "sql=".$sql); exit; @@ -163,10 +157,11 @@ if ($_POST["delete"]) $result1 = dolibarr_del_const($db, "EXTERNAL_RSS_TITLE_".GETPOST("norss", 'int'), $conf->entity); - if ($result1) $result2 = dolibarr_del_const($db, "EXTERNAL_RSS_URLRSS_".GETPOST("norss", 'int'), $conf->entity); + if ($result1) { + $result2 = dolibarr_del_const($db, "EXTERNAL_RSS_URLRSS_".GETPOST("norss", 'int'), $conf->entity); + } - if ($result1 && $result2) - { + if ($result1 && $result2) { $db->commit(); header("Location: external_rss.php"); exit; @@ -228,14 +223,12 @@ $sql .= " ORDER BY note"; dol_syslog("select rss boxes", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $boxlist = InfoBox::listBoxes($db, 'activated', -1, null); $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); preg_match('/^([0-9]+)/i', $obj->note, $reg); @@ -279,29 +272,34 @@ if ($resql) print '
    ".$langs->trans("Status").""; - if ($result > 0 && empty($rss->error)) - { + if ($result > 0 && empty($rss->error)) { print ''.$langs->trans("Online").''; } else { print ''.$langs->trans("Offline"); $langs->load("errors"); - if ($rssparser->error) print ' - '.$langs->trans($rssparser->error); + if ($rssparser->error) { + print ' - '.$langs->trans($rssparser->error); + } print ''; } print "
    ".$langs->trans("Logo")."'; $imageurl = $rssparser->getImageUrl(); $linkrss = $rssparser->getLink(); - if (!preg_match('/^http/', $imageurl)) $imageurl = $linkrss.$imageurl; - if ($imageurl) print ''; - else print $langs->trans("None"); + if (!preg_match('/^http/', $imageurl)) { + $imageurl = $linkrss.$imageurl; + } + if ($imageurl) { + print ''; + } else { + print $langs->trans("None"); + } print '
    '; echo preg_replace('/\-.*$/', '', preg_replace('/mod_facture_/', '', preg_replace('/\.php$/', '', $file))); print "\n"; @@ -316,14 +310,16 @@ foreach ($dirmodels as $reldir) if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '
    '.$langs->trans($tmp).'
    '; - } elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); - else print $tmp; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; + } print '
    '; //print "> ".$conf->global->FACTURE_ADDON." - ".$file; - if ($conf->global->FACTURE_ADDON == $file || $conf->global->FACTURE_ADDON.'.php' == $file) - { + if ($conf->global->FACTURE_ADDON == $file || $conf->global->FACTURE_ADDON.'.php' == $file) { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; @@ -341,8 +337,9 @@ foreach ($dirmodels as $reldir) if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= $langs->trans("NextValueForInvoices").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { $nextval = $langs->trans($nextval); + } $htmltooltip .= $nextval.'
    '; } else { $htmltooltip .= $langs->trans($module->error).'
    '; @@ -354,8 +351,9 @@ foreach ($dirmodels as $reldir) if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= $langs->trans("NextValueForReplacements").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { $nextval = $langs->trans($nextval); + } $htmltooltip .= $nextval.'
    '; } else { $htmltooltip .= $langs->trans($module->error).'
    '; @@ -368,8 +366,9 @@ foreach ($dirmodels as $reldir) if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= $langs->trans("NextValueForCreditNotes").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { $nextval = $langs->trans($nextval); + } $htmltooltip .= $nextval.'
    '; } else { $htmltooltip .= $langs->trans($module->error).'
    '; @@ -381,8 +380,9 @@ foreach ($dirmodels as $reldir) if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= $langs->trans("NextValueForDeposit").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { $nextval = $langs->trans($nextval); + } $htmltooltip .= $nextval; } else { $htmltooltip .= $langs->trans($module->error); @@ -392,9 +392,10 @@ foreach ($dirmodels as $reldir) print '
    '; print $form->textwithpicto('', $htmltooltip, 1, 0); - if ($conf->global->FACTURE_ADDON.'.php' == $file) // If module is the one used, we show existing errors - { - if (!empty($module->error)) dol_htmloutput_mesg($module->error, '', 'error', 1); + if ($conf->global->FACTURE_ADDON.'.php' == $file) { // If module is the one used, we show existing errors + if (!empty($module->error)) { + dol_htmloutput_mesg($module->error, '', 'error', 1); + } } print '
    '; print (empty($module->name) ? $name : $module->name); print "\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print ''."\n"; print ''; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -514,8 +510,7 @@ foreach ($dirmodels as $reldir) // Defaut print ''; - if ($conf->global->FACTURE_ADDON_PDF == "$name") - { + if ($conf->global->FACTURE_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("SetAsDefault"), 'off').''; @@ -525,8 +520,7 @@ foreach ($dirmodels as $reldir) // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '
    '.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '
    '.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } $htmltooltip .= '
    '.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; @@ -547,8 +541,7 @@ foreach ($dirmodels as $reldir) // Preview print '
    '; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print ''.img_object($langs->trans("Preview"), 'pdf').''; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); @@ -566,11 +559,10 @@ foreach ($dirmodels as $reldir) } print '
    '; -if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf -{ +if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) { // Hidden conf /* - * Document templates generators - */ + * Document templates generators + */ print '
    '; print load_fiche_titre($langs->trans("BillsPDFModulesAccordindToInvoiceType"), '', ''); print ''; @@ -589,13 +581,11 @@ if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf Facture::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), Facture::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"), ); - if (!empty($conf->global->INVOICE_USE_SITUATION)) - { + if (!empty($conf->global->INVOICE_USE_SITUATION)) { $listtype[Facture::TYPE_SITUATION] = $langs->trans("InvoiceSituation"); } - foreach ($listtype as $type => $trans) - { + foreach ($listtype as $type => $trans) { $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$type; $current = !empty($conf->global->{$thisTypeConfName}) ? $conf->global->{$thisTypeConfName}:$conf->global->FACTURE_ADDON_PDF; print ''; @@ -629,24 +619,20 @@ print "\n"; print ''; print "".$langs->trans("SuggestPaymentByRIBOnAccount").""; print ""; -if (!empty($conf->banque->enabled)) -{ +if (!empty($conf->banque->enabled)) { $sql = "SELECT rowid, label"; $sql .= " FROM ".MAIN_DB_PREFIX."bank_account"; $sql .= " WHERE clos = 0"; $sql .= " AND courant = 1"; $sql .= " AND entity IN (".getEntity('bank_account').")"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num > 0) - { + if ($num > 0) { print ''; print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnInvoices"), $langs->trans("AddCRIfTooLong").'

    '.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
    '; $variablename = 'INVOICE_FREE_TEXT'; -if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) -{ +if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; diff --git a/htdocs/admin/facture_situation.php b/htdocs/admin/facture_situation.php index 364297712e7..ffe1680c80f 100644 --- a/htdocs/admin/facture_situation.php +++ b/htdocs/admin/facture_situation.php @@ -36,7 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'errors', 'other', 'bills')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); @@ -60,7 +62,8 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); llxHeader( - "", $langs->trans("BillsSetup"), + "", + $langs->trans("BillsSetup"), 'EN:Invoice_Configuration|FR:Configuration_module_facture|ES:ConfiguracionFactura' ); diff --git a/htdocs/admin/fckeditor.php b/htdocs/admin/fckeditor.php index 6523ec833b3..0671783615c 100644 --- a/htdocs/admin/fckeditor.php +++ b/htdocs/admin/fckeditor.php @@ -41,7 +41,9 @@ $action = GETPOST('action', 'aZ09'); // Full (not sure this one is used) $mode = GETPOST('mode') ?GETPOST('mode', 'alpha') : 'dolibarr_notes'; -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Constant and translation of the module description $modules = array( @@ -86,29 +88,24 @@ $picto = array( * Actions */ -foreach ($modules as $const => $desc) -{ - if ($action == 'activate_'.strtolower($const)) - { +foreach ($modules as $const => $desc) { + if ($action == 'activate_'.strtolower($const)) { dolibarr_set_const($db, "FCKEDITOR_ENABLE_".$const, "1", 'chaine', 0, '', $conf->entity); // If fckeditor is active in the product/service description, it is activated in the forms - if ($const == 'PRODUCTDESC' && !empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if ($const == 'PRODUCTDESC' && !empty($conf->global->PRODUIT_DESC_IN_FORM)) { dolibarr_set_const($db, "FCKEDITOR_ENABLE_DETAILS", "1", 'chaine', 0, '', $conf->entity); } header("Location: ".$_SERVER["PHP_SELF"]); exit; } - if ($action == 'disable_'.strtolower($const)) - { + if ($action == 'disable_'.strtolower($const)) { dolibarr_del_const($db, "FCKEDITOR_ENABLE_".$const, $conf->entity); header("Location: ".$_SERVER["PHP_SELF"]); exit; } } -if (GETPOST('save', 'alpha')) -{ +if (GETPOST('save', 'alpha')) { $error = 0; $fckeditor_skin = GETPOST('fckeditor_skin', 'alpha'); @@ -129,8 +126,7 @@ if (GETPOST('save', 'alpha')) $error++; } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -147,8 +143,7 @@ $linkback = ''; -if (empty($conf->use_javascript_ajax)) -{ +if (empty($conf->use_javascript_ajax)) { setEventMessages(array($langs->trans("NotAvailable"), $langs->trans("JavascriptDisabled")), null, 'errors'); } else { print ''; @@ -158,10 +153,11 @@ if (empty($conf->use_javascript_ajax)) print "\n"; // Modules - foreach ($modules as $const => $desc) - { + foreach ($modules as $const => $desc) { // If this condition is not met, the option is not offered - if (!$conditions[$const]) continue; + if (!$conditions[$const]) { + continue; + } print ''; print ''; @@ -169,11 +165,9 @@ if (empty($conf->use_javascript_ajax)) print '\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ +foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/fichinter/"); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/^(mod_.*)\.php$/i', $file, $reg)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/^(mod_.*)\.php$/i', $file, $reg)) { $file = $reg[1]; $classname = substr($file, 4); @@ -277,11 +262,14 @@ foreach ($dirmodels as $reldir) $module = new $file; - if ($module->isEnabled()) - { + if ($module->isEnabled()) { // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } print ''."\n"; print '\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ +foreach ($dirmodels as $reldir) { $realpath = $reldir."core/modules/fichinter/doc"; $dir = dol_buildpath($realpath); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -411,21 +393,26 @@ 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 == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print ''; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print "\n"; $substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
    '; -foreach ($substitutionarray as $key => $val) $htmltext .= $key.'
    '; +foreach ($substitutionarray as $key => $val) { + $htmltext .= $key.'
    '; +} $htmltext .= '
    '; print ''; @@ -509,8 +496,7 @@ print ''; print ''; print ''; print ''; print '\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ +foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/holiday/"); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (substr($file, 0, 12) == 'mod_holiday_' && substr($file, dol_strlen($file) - 3, 3) == 'php') - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (substr($file, 0, 12) == 'mod_holiday_' && substr($file, dol_strlen($file) - 3, 3) == 'php') { $file = substr($file, 0, dol_strlen($file) - 4); require_once $dir.$file.'.php'; @@ -217,11 +201,14 @@ foreach ($dirmodels as $reldir) $module = new $file($db); // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } - if ($module->isEnabled()) - { + if ($module->isEnabled()) { print ''; @@ -232,13 +219,15 @@ foreach ($dirmodels as $reldir) if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '
    '.$langs->trans($tmp).'
    '; - } elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); - else print $tmp; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; + } print ''."\n"; print '\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ - foreach (array('', '/doc') as $valdir) - { +foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { $realpath = $reldir."core/modules/holiday".$valdir; $dir = dol_buildpath($realpath); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -365,21 +345,26 @@ 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 == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print ''; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print '\n"; $substitutionarray = pdf_getSubstitutionArray($langs, array('objectamount'), null, 2); $substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
    '; -foreach ($substitutionarray as $key => $val) $htmltext .= $key.'
    '; +foreach ($substitutionarray as $key => $val) { + $htmltext .= $key.'
    '; +} $htmltext .= '
    '; print ''."\n"; print ''; // Synchro contact active -if (!empty($conf->societe->enabled)) -{ +if (!empty($conf->societe->enabled)) { print ''; // Port print ''; // Pass print ''; print ''; print ''; +// Filter, used to filter search +print ''; +print ''; +print ''; + print '
    '.img_object("", $picto[$const]).''; $constante = 'FCKEDITOR_ENABLE_'.$const; $value = (isset($conf->global->$constante) ? $conf->global->$constante : 0); - if ($value == 0) - { + if ($value == 0) { print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; - } elseif ($value == 1) - { + } elseif ($value == 1) { print ''.img_picto($langs->trans("Enabled"), 'switch_on').''; } @@ -194,20 +188,24 @@ if (empty($conf->use_javascript_ajax)) $listofmodes = array('dolibarr_mailings', 'dolibarr_notes', 'dolibarr_details', 'dolibarr_readonly', 'Full', 'Full_inline'); $linkstomode = ''; - foreach ($listofmodes as $newmode) - { - if ($linkstomode) $linkstomode .= ' - '; + foreach ($listofmodes as $newmode) { + if ($linkstomode) { + $linkstomode .= ' - '; + } $linkstomode .= ''; - if ($mode == $newmode) $linkstomode .= ''; + if ($mode == $newmode) { + $linkstomode .= ''; + } $linkstomode .= $newmode; - if ($mode == $newmode) $linkstomode .= ''; + if ($mode == $newmode) { + $linkstomode .= ''; + } $linkstomode .= ''; } $linkstomode .= ''; print load_fiche_titre($langs->trans("TestSubmitForm"), $linkstomode, ''); print ''; - if ($mode != 'Full_inline') - { + if ($mode != 'Full_inline') { $uselocalbrowser = true; $readonly = ($mode == 'dolibarr_readonly' ? 1 : 0); $editor = new DolEditor('formtestfield', isset($conf->global->FCKEDITOR_TEST) ? $conf->global->FCKEDITOR_TEST : 'Test', '', 200, $mode, 'In', true, $uselocalbrowser, 1, 120, 8, $readonly); @@ -224,20 +222,20 @@ if (empty($conf->use_javascript_ajax)) // Add env of ckeditor // This is to show how CKEditor detect browser to understand why editor is disabled or not. To help debug. /* - print '
    '; - } - */ + jsdump(CKEDITOR.env, "divforlog"); + '; + } + */ } // End of page diff --git a/htdocs/admin/fichinter.php b/htdocs/admin/fichinter.php index afe6bc2239c..b0dcf2f39c4 100644 --- a/htdocs/admin/fichinter.php +++ b/htdocs/admin/fichinter.php @@ -37,7 +37,9 @@ require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'errors', 'interventions', 'other')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); @@ -52,22 +54,23 @@ $type = 'ficheinter'; include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; -if ($action == 'updateMask') -{ +if ($action == 'updateMask') { $maskconst = GETPOST('maskconst', 'alpha'); $maskvalue = GETPOST('maskvalue', 'alpha'); - if ($maskconst) $res = dolibarr_set_const($db, $maskconst, $maskvalue, 'chaine', 0, '', $conf->entity); + if ($maskconst) { + $res = dolibarr_set_const($db, $maskconst, $maskvalue, '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'); } -} elseif ($action == 'specimen') // For fiche inter -{ +} elseif ($action == 'specimen') { // For fiche inter $modele = GETPOST('module', 'alpha'); $inter = new Fichinter($db); @@ -76,25 +79,21 @@ if ($action == 'updateMask') // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/fichinter/doc/pdf_".$modele.".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db); - if ($module->write_file($inter, $langs) > 0) - { + if ($module->write_file($inter, $langs) > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=ficheinter&file=SPECIMEN.pdf"); return; } else { @@ -105,26 +104,19 @@ if ($action == 'updateMask') setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); } -} - -// Activate a model -elseif ($action == 'set') -{ +} elseif ($action == 'set') { + // Activate a model $ret = addDocumentModel($value, $type, $label, $scandir); -} elseif ($action == 'del') -{ +} elseif ($action == 'del') { $ret = delDocumentModel($value, $type); - if ($ret > 0) - { - if ($conf->global->FICHEINTER_ADDON_PDF == "$value") dolibarr_del_const($db, 'FICHEINTER_ADDON_PDF', $conf->entity); + if ($ret > 0) { + if ($conf->global->FICHEINTER_ADDON_PDF == "$value") { + dolibarr_del_const($db, 'FICHEINTER_ADDON_PDF', $conf->entity); + } } -} - -// Set default model -elseif ($action == 'setdoc') -{ - if (dolibarr_set_const($db, "FICHEINTER_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) - { +} elseif ($action == 'setdoc') { + // Set default model + if (dolibarr_set_const($db, "FICHEINTER_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { // La constante qui a ete lue en avant du nouveau set // on passe donc par une variable pour avoir un affichage coherent $conf->global->FICHEINTER_ADDON_PDF = $value; @@ -132,51 +124,49 @@ elseif ($action == 'setdoc') // On active le modele $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, $type, $label, $scandir); } -} elseif ($action == 'setmod') -{ +} elseif ($action == 'setmod') { // TODO Verifier si module numerotation choisi peut etre active // par appel methode canBeActivated dolibarr_set_const($db, "FICHEINTER_ADDON", $value, 'chaine', 0, '', $conf->entity); -} elseif ($action == 'set_FICHINTER_FREE_TEXT') -{ +} elseif ($action == 'set_FICHINTER_FREE_TEXT') { $freetext = GETPOST('FICHINTER_FREE_TEXT', 'restricthtml'); // No alpha here, we want exact string $res = dolibarr_set_const($db, "FICHINTER_FREE_TEXT", $freetext, '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'); } -} elseif ($action == 'set_FICHINTER_DRAFT_WATERMARK') -{ +} elseif ($action == 'set_FICHINTER_DRAFT_WATERMARK') { $draft = GETPOST('FICHINTER_DRAFT_WATERMARK', 'alpha'); $res = dolibarr_set_const($db, "FICHINTER_DRAFT_WATERMARK", trim($draft), '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'); } -} elseif ($action == 'set_FICHINTER_PRINT_PRODUCTS') -{ +} elseif ($action == 'set_FICHINTER_PRINT_PRODUCTS') { $val = GETPOST('FICHINTER_PRINT_PRODUCTS', 'alpha'); $res = dolibarr_set_const($db, "FICHINTER_PRINT_PRODUCTS", ($val == 'on' ? 1 : 0), 'bool', 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'); @@ -257,19 +247,14 @@ print "
    '.$module->nom."\n"; @@ -294,13 +282,15 @@ foreach ($dirmodels as $reldir) if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '
    '.$langs->trans($tmp).'
    '; - } elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); - else print $tmp; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; + } print '
    '; - if ($conf->global->FICHEINTER_ADDON == $classname) - { + if ($conf->global->FICHEINTER_ADDON == $classname) { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; @@ -317,8 +307,9 @@ foreach ($dirmodels as $reldir) if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { $nextval = $langs->trans($nextval); + } $htmltooltip .= $nextval.'
    '; } else { $htmltooltip .= $langs->trans($module->error).'
    '; @@ -354,12 +345,10 @@ $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; $sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -381,29 +370,22 @@ print "
    '; print (empty($module->name) ? $name : $module->name); print "\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print '\n"; print 'scandir.'&label='.urlencode($module->name).'">'; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -439,8 +426,7 @@ foreach ($dirmodels as $reldir) // Default print ""; - if ($conf->global->FICHEINTER_ADDON_PDF == "$name") - { + if ($conf->global->FICHEINTER_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').''; @@ -465,8 +451,7 @@ foreach ($dirmodels as $reldir) // Preview print ''; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print ''.img_object($langs->trans("Preview"), 'pdf').''; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); @@ -500,7 +485,9 @@ print "
    '; print $form->textwithpicto($langs->trans("FreeLegalTextOnInterventions"), $langs->trans("AddCRIfTooLong").'

    '.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
    '; $variablename = 'FICHINTER_FREE_TEXT'; -if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) -{ +if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -541,8 +527,9 @@ print '' print '
    '; print $langs->trans("PrintProductsOnFichinter").' ('.$langs->trans("PrintProductsOnFichinterDetails").')global->FICHINTER_PRINT_PRODUCTS) +if ($conf->global->FICHINTER_PRINT_PRODUCTS) { print 'checked '; +} print '/>'; print ''; print ''; diff --git a/htdocs/admin/geoipmaxmind.php b/htdocs/admin/geoipmaxmind.php index 63d15169da2..109bd6b388d 100644 --- a/htdocs/admin/geoipmaxmind.php +++ b/htdocs/admin/geoipmaxmind.php @@ -28,8 +28,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php'; // Security check -if (!$user->admin) -accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array("admin", "errors")); @@ -41,8 +42,7 @@ $action = GETPOST('action', 'aZ09'); * Actions */ -if ($action == 'set') -{ +if ($action == 'set') { $error = 0; $gimcdf = GETPOST("GEOIPMAXMIND_COUNTRY_DATAFILE"); @@ -52,22 +52,23 @@ if ($action == 'set') $error++; } - if (!$error && $gimcdf && !file_exists($gimcdf)) - { + if (!$error && $gimcdf && !file_exists($gimcdf)) { setEventMessages($langs->trans("ErrorFileNotFound", $gimcdf), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $res1 = dolibarr_set_const($db, "GEOIP_VERSION", GETPOST('geoipversion', 'aZ09'), 'chaine', 0, '', $conf->entity); - if (!$res1 > 0) $error++; + if (!$res1 > 0) { + $error++; + } $res2 = dolibarr_set_const($db, "GEOIPMAXMIND_COUNTRY_DATAFILE", $gimcdf, 'chaine', 0, '', $conf->entity); - if (!$res2 > 0) $error++; + if (!$res2 > 0) { + $error++; + } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -75,7 +76,9 @@ if ($action == 'set') } } -if (!isset($conf->global->GEOIP_VERSION)) $conf->global->GEOIP_VERSION = '2'; +if (!isset($conf->global->GEOIP_VERSION)) { + $conf->global->GEOIP_VERSION = '2'; +} /* @@ -92,8 +95,7 @@ print '
    '; $version = ''; $geoip = ''; -if (!empty($conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE)) -{ +if (!empty($conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE)) { $geoip = new DolGeoIP('country', $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE); } @@ -113,11 +115,11 @@ print '
    '.$langs->trans("GeoIPLibVersion").'< print ''; $arrayofvalues = array('php' => 'Native PHP functions', '1' => 'Embedded GeoIP v1', '2' => 'Embedded GeoIP v2'); print $form->selectarray('geoipversion', $arrayofvalues, (isset($conf->global->GEOIP_VERSION) ? $conf->global->GEOIP_VERSION : '2')); -if ($conf->global->GEOIP_VERSION == 'php') -{ - if ($geoip) $version = $geoip->getVersion(); - if ($version) - { +if ($conf->global->GEOIP_VERSION == 'php') { + if ($geoip) { + $version = $geoip->getVersion(); + } + if ($version) { print '
    '.$langs->trans("Version").': '.$version; } } @@ -127,8 +129,7 @@ print '
    '.$langs->trans("PathToGeoIPMaxmindCountryDataFile").''; -if ($conf->global->GEOIP_VERSION == 'php') -{ +if ($conf->global->GEOIP_VERSION == 'php') { print 'Using geoip PHP internal functions. Value must be '.geoip_db_filename(GEOIP_COUNTRY_EDITION).' or '.geoip_db_filename(GEOIP_CITY_EDITION_REV1).' or /pathtodatafile/GeoLite2-Country.mmdb
    '; } print ''; @@ -150,22 +151,27 @@ print '
    '; $url2 = 'http://www.maxmind.com/en/city?rId=awstats'; print $langs->trans("YouCanDownloadAdvancedDatFileTo", ''.$url2.''); -if ($geoip) -{ +if ($geoip) { print '

    '; print '
    '.$langs->trans("TestGeoIPResult", $ip).':'; $ip = '24.24.24.24'; print '
    '.$ip.' -> '; $result = dol_print_ip($ip, 1); - if ($result) print $result; - else print $langs->trans("Error"); + if ($result) { + print $result; + } else { + print $langs->trans("Error"); + } $ip = '2a01:e0a:7e:4a60:429a:23ff:f7b8:dc8a'; // should be France print '
    '.$ip.' -> '; $result = dol_print_ip($ip, 1); - if ($result) print $result; - else print $langs->trans("Error"); + if ($result) { + print $result; + } else { + print $langs->trans("Error"); + } /* We disable this test because dol_print_ip need an ip as input @@ -179,17 +185,22 @@ if ($geoip) $ip = getUserRemoteIP(); //$ip='91.161.249.43'; $isip = is_ip($ip); - if ($isip == 1) - { + if ($isip == 1) { print '
    '.$ip.' -> '; $result = dol_print_ip($ip, 1); - if ($result) print $result; - else print $langs->trans("Error"); + if ($result) { + print $result; + } else { + print $langs->trans("Error"); + } } else { print '
    '.$ip.' -> '; $result = dol_print_ip($ip, 1); - if ($result) print $result; - else print $langs->trans("NotAPublicIp"); + if ($result) { + print $result; + } else { + print $langs->trans("NotAPublicIp"); + } } $geoip->close(); diff --git a/htdocs/admin/holiday.php b/htdocs/admin/holiday.php index d8de2dd847d..28fbeba9063 100644 --- a/htdocs/admin/holiday.php +++ b/htdocs/admin/holiday.php @@ -33,7 +33,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/holiday.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "errors", "holiday")); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); @@ -41,8 +43,7 @@ $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); $type = 'contract'; -if (empty($conf->global->HOLIDAY_ADDON)) -{ +if (empty($conf->global->HOLIDAY_ADDON)) { $conf->global->HOLIDAY_ADDON = 'mod_holiday_madonna'; } @@ -53,22 +54,23 @@ if (empty($conf->global->HOLIDAY_ADDON)) include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; -if ($action == 'updateMask') -{ +if ($action == 'updateMask') { $maskconst = GETPOST('maskconstholiday', 'alpha'); $maskvalue = GETPOST('maskholiday', 'alpha'); - if ($maskconst) $res = dolibarr_set_const($db, $maskconst, $maskvalue, 'chaine', 0, '', $conf->entity); + if ($maskconst) { + $res = dolibarr_set_const($db, $maskconst, $maskvalue, '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'); } -} elseif ($action == 'specimen') // For contract -{ +} elseif ($action == 'specimen') { // For contract $modele = GETPOST('module', 'alpha'); $holiday = new Holiday($db); @@ -77,25 +79,21 @@ if ($action == 'updateMask') // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/holiday/doc/pdf_".$modele.".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db); - if ($module->write_file($holiday, $langs) > 0) - { + if ($module->write_file($holiday, $langs) > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=holiday&file=SPECIMEN.pdf"); return; } else { @@ -106,26 +104,19 @@ if ($action == 'updateMask') setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); } -} - -// Activate a model -elseif ($action == 'set') -{ +} elseif ($action == 'set') { + // Activate a model $ret = addDocumentModel($value, $type, $label, $scandir); -} elseif ($action == 'del') -{ +} elseif ($action == 'del') { $ret = delDocumentModel($value, $type); - if ($ret > 0) - { - if ($conf->global->HOLIDAY_ADDON_PDF == "$value") dolibarr_del_const($db, 'HOLIDAY_ADDON_PDF', $conf->entity); + if ($ret > 0) { + if ($conf->global->HOLIDAY_ADDON_PDF == "$value") { + dolibarr_del_const($db, 'HOLIDAY_ADDON_PDF', $conf->entity); + } } -} - -// Set default model -elseif ($action == 'setdoc') -{ - if (dolibarr_set_const($db, "HOLIDAY_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) - { +} elseif ($action == 'setdoc') { + // Set default model + if (dolibarr_set_const($db, "HOLIDAY_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { // La constante qui a ete lue en avant du nouveau set // on passe donc par une variable pour avoir un affichage coherent $conf->global->HOLIDAY_ADDON_PDF = $value; @@ -133,28 +124,26 @@ elseif ($action == 'setdoc') // On active le modele $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, $type, $label, $scandir); } -} elseif ($action == 'setmod') -{ +} elseif ($action == 'setmod') { // TODO Verifier si module numerotation choisi peut etre active // par appel methode canBeActivated dolibarr_set_const($db, "HOLIDAY_ADDON", $value, 'chaine', 0, '', $conf->entity); -} elseif ($action == 'set_other') -{ +} elseif ($action == 'set_other') { $freetext = GETPOST('HOLIDAY_FREE_TEXT', 'restricthtml'); // No alpha here, we want exact string $res1 = dolibarr_set_const($db, "HOLIDAY_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity); $draft = GETPOST('HOLIDAY_DRAFT_WATERMARK', 'alpha'); $res2 = dolibarr_set_const($db, "HOLIDAY_DRAFT_WATERMARK", trim($draft), 'chaine', 0, '', $conf->entity); - if (!$res1 > 0 || !$res2 > 0) $error++; + if (!$res1 > 0 || !$res2 > 0) { + $error++; + } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -197,19 +186,14 @@ print "
    '.$module->nom."\n"; print $module->info(); print ''; - if ($conf->global->HOLIDAY_ADDON == "$file") - { + if ($conf->global->HOLIDAY_ADDON == "$file") { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print ''; @@ -257,8 +246,9 @@ foreach ($dirmodels as $reldir) if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { $nextval = $langs->trans($nextval); + } $htmltooltip .= $nextval.'
    '; } else { $htmltooltip .= $langs->trans($module->error).'
    '; @@ -305,12 +295,10 @@ $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; $sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -333,31 +321,23 @@ print "
    '; print (empty($module->name) ? $name : $module->name); print "\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print ''."\n"; print ''; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -393,8 +378,7 @@ foreach ($dirmodels as $reldir) // Default print ''; - if ($conf->global->HOLIDAY_ADDON_PDF == $name) - { + if ($conf->global->HOLIDAY_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').''; @@ -404,8 +388,7 @@ foreach ($dirmodels as $reldir) // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '
    '.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '
    '.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } $htmltooltip .= '
    '.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; @@ -424,8 +407,7 @@ foreach ($dirmodels as $reldir) // Preview print '
    '; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print ''.img_object($langs->trans("Preview"), 'pdf').''; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); @@ -467,15 +449,16 @@ print "
    '; print $form->textwithpicto($langs->trans("FreeLegalTextOnHolidays"), $langs->trans("AddCRIfTooLong").'

    '.$htmltext, 1, 'help', '', 0, 2, 'tooltiphelp'); print '
    '; $variablename = 'HOLIDAY_FREE_TEXT'; -if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) -{ +if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; diff --git a/htdocs/admin/holiday_extrafields.php b/htdocs/admin/holiday_extrafields.php index 077ad08a12a..732eb0997d7 100644 --- a/htdocs/admin/holiday_extrafields.php +++ b/htdocs/admin/holiday_extrafields.php @@ -30,8 +30,9 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/holiday.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('admin', 'errors', 'holiday', 'other')); @@ -42,13 +43,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 = 'holiday'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -78,8 +83,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -92,8 +96,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '
    '; print load_fiche_titre($langs->trans('NewAttribute')); @@ -105,8 +108,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
    "; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/admin/ihm.php b/htdocs/admin/ihm.php index bebb9f7d0bd..81263cba82e 100644 --- a/htdocs/admin/ihm.php +++ b/htdocs/admin/ihm.php @@ -36,12 +36,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'languages', 'other', 'companies', 'products', 'members', 'projects', 'hrm', 'agenda')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'adminihm'; // To manage different context of search -if (!defined("MAIN_MOTD")) define("MAIN_MOTD", ""); +if (!defined("MAIN_MOTD")) { + define("MAIN_MOTD", ""); +} @@ -51,22 +55,25 @@ if (!defined("MAIN_MOTD")) define("MAIN_MOTD", ""); $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 (GETPOST('cancel', 'alpha')) -{ +if (GETPOST('cancel', 'alpha')) { $action = ''; } // Convert action set_XXX and del_XXX to set var (this is used when no javascript on for ajax_constantonoff) $regs = array(); if (preg_match('/^(set|del)_([A-Z_]+)$/', $action, $regs)) { - if ($regs[1] == 'set') dolibarr_set_const($db, $regs[2], 1, 'chaine', 0, '', $conf->entity); - else dolibarr_del_const($db, $regs[2], $conf->entity); + if ($regs[1] == 'set') { + dolibarr_set_const($db, $regs[2], 1, 'chaine', 0, '', $conf->entity); + } else { + dolibarr_del_const($db, $regs[2], $conf->entity); + } } -if ($action == 'removebackgroundlogin' && !empty($conf->global->MAIN_LOGIN_BACKGROUND)) -{ +if ($action == 'removebackgroundlogin' && !empty($conf->global->MAIN_LOGIN_BACKGROUND)) { dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", (int) $conf->global->MAIN_IHM_PARAMS_REV + 1, 'chaine', 0, '', $conf->entity); require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -76,18 +83,17 @@ if ($action == 'removebackgroundlogin' && !empty($conf->global->MAIN_LOGIN_BACKG $mysoc->logo = ''; /*$logosmallfile=$conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; - dol_delete_file($logosmallfile); - dolibarr_del_const($db, "MAIN_INFO_SOCIETE_LOGO_SMALL",$conf->entity); - $mysoc->logo_small=''; + dol_delete_file($logosmallfile); + dolibarr_del_const($db, "MAIN_INFO_SOCIETE_LOGO_SMALL",$conf->entity); + $mysoc->logo_small=''; - $logominifile=$conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_mini; - dol_delete_file($logominifile); - dolibarr_del_const($db, "MAIN_INFO_SOCIETE_LOGO_MINI",$conf->entity); - $mysoc->logo_mini='';*/ + $logominifile=$conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_mini; + dol_delete_file($logominifile); + dolibarr_del_const($db, "MAIN_INFO_SOCIETE_LOGO_MINI",$conf->entity); + $mysoc->logo_mini='';*/ } -if ($action == 'update') -{ +if ($action == 'update') { dolibarr_set_const($db, "MAIN_LANG_DEFAULT", GETPOST("MAIN_LANG_DEFAULT", 'aZ09'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", (int) $conf->global->MAIN_IHM_PARAMS_REV + 1, 'chaine', 0, '', $conf->entity); //dolibarr_set_const($db, "MAIN_MULTILANGS", $_POST["MAIN_MULTILANGS"], 'chaine', 0, '', $conf->entity); @@ -99,58 +105,100 @@ if ($action == 'update') else dolibarr_set_const($db, 'THEME_TOPMENU_DISABLE_IMAGE', GETPOST('THEME_TOPMENU_DISABLE_IMAGE'), 'chaine', 0, '', $conf->entity);*/ $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_BACKBODY'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_BACKBODY', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_BACKBODY', $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_BACKBODY', $conf->entity); + } else { + dolibarr_set_const($db, 'THEME_ELDY_BACKBODY', $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_TOPMENU_BACK1'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TOPMENU_BACK1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_TOPMENU_BACK1', $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_TOPMENU_BACK1', $conf->entity); + } else { + dolibarr_set_const($db, 'THEME_ELDY_TOPMENU_BACK1', $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_VERMENU_BACK1'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_VERMENU_BACK1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_VERMENU_BACK1', $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_VERMENU_BACK1', $conf->entity); + } else { + dolibarr_set_const($db, 'THEME_ELDY_VERMENU_BACK1', $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_TEXTTITLENOTAB'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $conf->entity); + } else { + dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_BACKTITLE1'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_BACKTITLE1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_BACKTITLE1', $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_BACKTITLE1', $conf->entity); + } else { + dolibarr_set_const($db, 'THEME_ELDY_BACKTITLE1', $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_TEXTTITLE'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TEXTTITLE', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLE', $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_TEXTTITLE', $conf->entity); + } else { + dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLE', $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_TEXTTITLELINK'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TEXTTITLELINK', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLELINK', $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_TEXTTITLELINK', $conf->entity); + } else { + dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLELINK', $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR1', $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR1', $conf->entity); + } else { + dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR1', $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR2', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR2', $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR2', $conf->entity); + } else { + dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR2', $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR1', $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR1', $conf->entity); + } else { + dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR1', $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR2', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR2', $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR2', $conf->entity); + } else { + dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR2', $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_TEXTLINK'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TEXTLINK', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_TEXTLINK', $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_TEXTLINK', $conf->entity); + } else { + dolibarr_set_const($db, 'THEME_ELDY_TEXTLINK', $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_USE_HOVER'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_USE_HOVER', $conf->entity); - else dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_USE_HOVER', $conf->entity); + } else { + dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", $val, 'chaine', 0, '', $conf->entity); + } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_USE_CHECKED'), array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_USE_CHECKED', $conf->entity); - else dolibarr_set_const($db, "THEME_ELDY_USE_CHECKED", $val, 'chaine', 0, '', $conf->entity); + if ($val == '') { + dolibarr_del_const($db, 'THEME_ELDY_USE_CHECKED', $conf->entity); + } else { + dolibarr_set_const($db, "THEME_ELDY_USE_CHECKED", $val, 'chaine', 0, '', $conf->entity); + } dolibarr_set_const($db, "MAIN_SIZE_LISTE_LIMIT", GETPOST("main_size_liste_limit", 'int'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_SIZE_SHORTLIST_LIMIT", GETPOST("main_size_shortliste_limit", 'int'), 'chaine', 0, '', $conf->entity); @@ -171,27 +219,21 @@ if ($action == 'update') //dolibarr_set_const($db, "MAIN_HELP_DISABLELINK", GETPOST("MAIN_HELP_DISABLELINK", 'aZ09'), 'chaine', 0, '', 0); // Param for all entities $varforimage = 'imagebackground'; $dirforimage = $conf->mycompany->dir_output.'/logos/'; - if ($_FILES[$varforimage]["tmp_name"]) - { + if ($_FILES[$varforimage]["tmp_name"]) { $reg = array(); - if (preg_match('/([^\\/:]+)$/i', $_FILES[$varforimage]["name"], $reg)) - { + if (preg_match('/([^\\/:]+)$/i', $_FILES[$varforimage]["name"], $reg)) { $original_file = $reg[1]; $isimage = image_format_supported($original_file); - if ($isimage >= 0) - { + if ($isimage >= 0) { dol_syslog("Move file ".$_FILES[$varforimage]["tmp_name"]." to ".$dirforimage.$original_file); - if (!is_dir($dirforimage)) - { + if (!is_dir($dirforimage)) { dol_mkdir($dirforimage); } $result = dol_move_uploaded_file($_FILES[$varforimage]["tmp_name"], $dirforimage.$original_file, 1, 0, $_FILES[$varforimage]['error']); - if ($result > 0) - { + if ($result > 0) { dolibarr_set_const($db, "MAIN_LOGIN_BACKGROUND", $original_file, 'chaine', 0, '', $conf->entity); - } elseif (preg_match('/^ErrorFileIsInfectedWithAVirus/', $result)) - { + } elseif (preg_match('/^ErrorFileIsInfectedWithAVirus/', $result)) { $error++; $langs->load("errors"); $tmparray = explode(':', $result); @@ -380,8 +422,7 @@ complete_substitutions_array($substitutionarray, $langs); print '
    '; $texthelp = $langs->trans("FollowingConstantsWillBeSubstituted").'
    '; -foreach ($substitutionarray as $key => $val) -{ +foreach ($substitutionarray as $key => $val) { $texthelp .= $key.'
    '; } print $form->textwithpicto($langs->trans("MessageOfDay"), $texthelp, 1, 'help', '', 0, 2, 'tooltipmessageofday'); @@ -417,8 +458,7 @@ $substitutionarray = getCommonSubstitutionArray($langs, 0, array('object', 'obje complete_substitutions_array($substitutionarray, $langs); print '
    '; $texthelp = $langs->trans("FollowingConstantsWillBeSubstituted").'
    '; -foreach ($substitutionarray as $key => $val) -{ +foreach ($substitutionarray as $key => $val) { $texthelp .= $key.'
    '; } print $form->textwithpicto($langs->trans("MessageLogin"), $texthelp, 1, 'help', '', 0, 2, 'tooltipmessagelogin'); @@ -431,10 +471,11 @@ print '
    '; print '
    '; $disabled = ''; -if (!empty($conf->global->ADD_UNSPLASH_LOGIN_BACKGROUND)) $disabled = ' disabled="disabled"'; +if (!empty($conf->global->ADD_UNSPLASH_LOGIN_BACKGROUND)) { + $disabled = ' disabled="disabled"'; +} print ''; -if ($disabled) -{ +if ($disabled) { print '('.$langs->trans("DisabledByOptionADD_UNSPLASH_LOGIN_BACKGROUND").') '; } if (!empty($conf->global->MAIN_LOGIN_BACKGROUND)) { diff --git a/htdocs/admin/import.php b/htdocs/admin/import.php index e70d8eadbba..38f8ae7554b 100644 --- a/htdocs/admin/import.php +++ b/htdocs/admin/import.php @@ -35,8 +35,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'exports', 'other')); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); diff --git a/htdocs/admin/index.php b/htdocs/admin/index.php index 44bfd678fb4..d94c8a3fffd 100644 --- a/htdocs/admin/index.php +++ b/htdocs/admin/index.php @@ -27,7 +27,9 @@ require '../main.inc.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'companies')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('homesetup')); @@ -45,16 +47,15 @@ llxHeader('', $langs->trans("Setup"), $wikihelp); print load_fiche_titre($langs->trans("SetupArea"), '', 'tools'); -if (!empty($conf->global->MAIN_MOTD_SETUPPAGE)) -{ +if (!empty($conf->global->MAIN_MOTD_SETUPPAGE)) { $conf->global->MAIN_MOTD_SETUPPAGE = preg_replace('//i', '
    ', $conf->global->MAIN_MOTD_SETUPPAGE); - if (!empty($conf->global->MAIN_MOTD_SETUPPAGE)) - { + if (!empty($conf->global->MAIN_MOTD_SETUPPAGE)) { $i = 0; - while (preg_match('/__\(([a-zA-Z|@]+)\)__/i', $conf->global->MAIN_MOTD_SETUPPAGE, $reg) && $i < 100) - { + while (preg_match('/__\(([a-zA-Z|@]+)\)__/i', $conf->global->MAIN_MOTD_SETUPPAGE, $reg) && $i < 100) { $tmp = explode('|', $reg[1]); - if (!empty($tmp[1])) $langs->load($tmp[1]); + if (!empty($tmp[1])) { + $langs->load($tmp[1]); + } $conf->global->MAIN_MOTD_SETUPPAGE = preg_replace('/__\('.preg_quote($reg[1]).'\)__/i', $langs->trans($tmp[0]), $conf->global->MAIN_MOTD_SETUPPAGE); $i++; } @@ -77,10 +78,11 @@ print ''; print '
    '; // Show info setup company -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")); -if (!empty($setupcompanynotcomplete)) -{ +if (empty($conf->global->MAIN_INFO_SOCIETE_NOM) || empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) { + $setupcompanynotcomplete = 1; +} +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;"'); print '
    '; @@ -90,9 +92,8 @@ 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")); -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 -{ +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;"'); print '
    '; @@ -106,8 +107,7 @@ print '
    '; $parameters = array(); $reshook = $hookmanager->executeHooks('addHomeSetup', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks print $hookmanager->resPrint; -if (empty($reshook)) -{ +if (empty($reshook)) { // Show into other print ''.$langs->trans("SetupDescription5")."
    "; print "
    "; diff --git a/htdocs/admin/ldap.php b/htdocs/admin/ldap.php index b8c207644c6..18399894ad0 100644 --- a/htdocs/admin/ldap.php +++ b/htdocs/admin/ldap.php @@ -34,8 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; // Load translation files required by the page $langs->load("admin"); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); @@ -48,32 +49,57 @@ $hookmanager->initHooks(array('adminldap', 'globaladmin')); $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 == 'setvalue' && $user->admin) - { +if (empty($reshook)) { + if ($action == 'setvalue' && $user->admin) { $error = 0; $db->begin(); - if (!dolibarr_set_const($db, 'LDAP_SERVER_TYPE', GETPOST("type", 'aZ09'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_SERVER_PROTOCOLVERSION', GETPOST("LDAP_SERVER_PROTOCOLVERSION", 'aZ09'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_SERVER_HOST', GETPOST("host", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_SERVER_HOST_SLAVE', GETPOST("slave", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_SERVER_PORT', GETPOST("port", 'int'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_SERVER_DN', GETPOST("dn", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_ADMIN_DN', GETPOST("admin", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_ADMIN_PASS', GETPOST("pass", 'none'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_SERVER_USE_TLS', GETPOST("usetls", 'aZ09'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_SYNCHRO_ACTIVE', GETPOST("activesynchro", 'aZ09'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_ACTIVE', GETPOST("activecontact", 'aZ09'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_ACTIVE', GETPOST("activemembers", 'aZ09'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_ACTIVE', GETPOST("activememberstypes", 'aZ09'), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_SERVER_TYPE', GETPOST("type", 'aZ09'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_SERVER_PROTOCOLVERSION', GETPOST("LDAP_SERVER_PROTOCOLVERSION", 'aZ09'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_SERVER_HOST', GETPOST("host", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_SERVER_HOST_SLAVE', GETPOST("slave", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_SERVER_PORT', GETPOST("port", 'int'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_SERVER_DN', GETPOST("dn", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_ADMIN_DN', GETPOST("admin", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_ADMIN_PASS', GETPOST("pass", 'none'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_SERVER_USE_TLS', GETPOST("usetls", 'aZ09'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_SYNCHRO_ACTIVE', GETPOST("activesynchro", 'aZ09'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_ACTIVE', GETPOST("activecontact", 'aZ09'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_ACTIVE', GETPOST("activemembers", 'aZ09'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_ACTIVE', GETPOST("activememberstypes", 'aZ09'), 'chaine', 0, '', $conf->entity)) { + $error++; + } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -96,8 +122,7 @@ print load_fiche_titre($langs->trans("LDAPSetup"), $linkback, 'title_setup'); $head = ldap_prepare_head(); // Test si fonction LDAP actives -if (!function_exists("ldap_connect")) -{ +if (!function_exists("ldap_connect")) { setEventMessages($langs->trans("LDAPFunctionsNotAvailableOnPHP"), null, 'errors'); } @@ -126,15 +151,13 @@ $arraylist['ldap2dolibarr'] = $langs->trans("LDAPToDolibarr"); $arraylist['dolibarr2ldap'] = $langs->trans("DolibarrToLDAP"); print $form->selectarray('activesynchro', $arraylist, $conf->global->LDAP_SYNCHRO_ACTIVE); print '
    '.$langs->trans("LDAPDnSynchroActiveExample"); -if ($conf->global->LDAP_SYNCHRO_ACTIVE && !$conf->global->LDAP_USER_DN) -{ +if ($conf->global->LDAP_SYNCHRO_ACTIVE && !$conf->global->LDAP_USER_DN) { print '
    '.$langs->trans("LDAPSetupNotComplete").''; } print '
    '.$langs->trans("LDAPDnContactActive").''; $arraylist = array(); $arraylist['0'] = $langs->trans("No"); @@ -144,8 +167,7 @@ if (!empty($conf->societe->enabled)) } // Synchro member active -if (!empty($conf->adherent->enabled)) -{ +if (!empty($conf->adherent->enabled)) { print '
    '.$langs->trans("LDAPDnMemberActive").''; $arraylist = array(); $arraylist['0'] = $langs->trans("No"); @@ -156,8 +178,7 @@ if (!empty($conf->adherent->enabled)) } // Synchro member type active -if (!empty($conf->adherent->enabled)) -{ +if (!empty($conf->adherent->enabled)) { print '
    '.$langs->trans("LDAPDnMemberTypeActive").''; $arraylist = array(); $arraylist['0'] = $langs->trans("No"); @@ -209,8 +230,7 @@ print ''.$langs->trans("LDAPServerExample").'
    '.$langs->trans("LDAPServerPort").''; -if (!empty($conf->global->LDAP_SERVER_PORT)) -{ +if (!empty($conf->global->LDAP_SERVER_PORT)) { print ''; } else { print ''; @@ -241,8 +261,7 @@ print ''.$langs->trans("LDAPAdminDnExample").'
    '.$langs->trans("LDAPPassword").''; -if (!empty($conf->global->LDAP_ADMIN_PASS)) -{ +if (!empty($conf->global->LDAP_ADMIN_PASS)) { print ''; // je le met en visible pour test } else { print ''; @@ -263,29 +282,23 @@ print '
    '; /* * Test de la connexion */ -if (function_exists("ldap_connect")) -{ - if (!empty($conf->global->LDAP_SERVER_HOST)) - { +if (function_exists("ldap_connect")) { + if (!empty($conf->global->LDAP_SERVER_HOST)) { print ''.$langs->trans("LDAPTestConnect").'

    '; } - if ($_GET["action"] == 'test') - { + if ($_GET["action"] == 'test') { $ldap = new Ldap(); // Les parametres sont passes et recuperes via $conf $result = $ldap->connect_bind(); - if ($result > 0) - { + if ($result > 0) { // Test ldap connect and bind print img_picto('', 'info').' '; print ''.$langs->trans("LDAPTCPConnectOK", $conf->global->LDAP_SERVER_HOST, $conf->global->LDAP_SERVER_PORT).''; print '
    '; - if ($conf->global->LDAP_ADMIN_DN && !empty($conf->global->LDAP_ADMIN_PASS)) - { - if ($result == 2) - { + if ($conf->global->LDAP_ADMIN_DN && !empty($conf->global->LDAP_ADMIN_PASS)) { + if ($result == 2) { print img_picto('', 'info').' '; print ''.$langs->trans("LDAPBindOK", $conf->global->LDAP_SERVER_HOST, $conf->global->LDAP_SERVER_PORT, $conf->global->LDAP_ADMIN_DN, preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)).''; print '
    '; @@ -304,8 +317,7 @@ if (function_exists("ldap_connect")) // Test ldap_getversion - if (($ldap->getVersion() == 3)) - { + if (($ldap->getVersion() == 3)) { print img_picto('', 'info').' '; print ''.$langs->trans("LDAPSetupForVersion3").''; print '
    '; diff --git a/htdocs/admin/ldap_contacts.php b/htdocs/admin/ldap_contacts.php index b29fa00e49e..d21c95405a2 100644 --- a/htdocs/admin/ldap_contacts.php +++ b/htdocs/admin/ldap_contacts.php @@ -35,8 +35,9 @@ require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "errors")); -if (!$user->admin) - accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); @@ -44,38 +45,72 @@ $action = GETPOST('action', 'aZ09'); * Actions */ -if ($action == 'setvalue' && $user->admin) -{ +if ($action == 'setvalue' && $user->admin) { $error = 0; $db->begin(); - if (!dolibarr_set_const($db, 'LDAP_CONTACT_DN', GETPOST("contactdn"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_CONTACT_DN', GETPOST("contactdn"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) { + $error++; + } - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_NAME', GETPOST("fieldname"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_FIRSTNAME', GETPOST("fieldfirstname"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_COMPANY', GETPOST("fieldcompany"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_MAIL', GETPOST("fieldmail"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_PHONE', GETPOST("fieldphone"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_HOMEPHONE', GETPOST("fieldhomephone"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_MOBILE', GETPOST("fieldmobile"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_SKYPE', GETPOST("fieldskype"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_FAX', GETPOST("fieldfax"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_ADDRESS', GETPOST("fieldaddress"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_ZIP', GETPOST("fieldzip"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_TOWN', GETPOST("fieldtown"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_COUNTRY', GETPOST("fieldcountry"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_NAME', GETPOST("fieldname"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_FIRSTNAME', GETPOST("fieldfirstname"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_COMPANY', GETPOST("fieldcompany"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_MAIL', GETPOST("fieldmail"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_PHONE', GETPOST("fieldphone"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_HOMEPHONE', GETPOST("fieldhomephone"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_MOBILE', GETPOST("fieldmobile"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_SKYPE', GETPOST("fieldskype"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_FAX', GETPOST("fieldfax"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_ADDRESS', GETPOST("fieldaddress"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_ZIP', GETPOST("fieldzip"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_TOWN', GETPOST("fieldtown"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_CONTACT_FIELD_COUNTRY', GETPOST("fieldcountry"), 'chaine', 0, '', $conf->entity)) { + $error++; + } // This one must be after the others $valkey = ''; $key = GETPOST("key"); - if ($key) $valkey = $conf->global->$key; - if (!dolibarr_set_const($db, 'LDAP_KEY_CONTACTS', $valkey, 'chaine', 0, '', $conf->entity)) $error++; + if ($key) { + $valkey = $conf->global->$key; + } + if (!dolibarr_set_const($db, 'LDAP_KEY_CONTACTS', $valkey, 'chaine', 0, '', $conf->entity)) { + $error++; + } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -100,8 +135,7 @@ print load_fiche_titre($langs->trans("LDAPSetup"), $linkback, 'title_setup'); $head = ldap_prepare_head(); // Test si fonction LDAP actives -if (!function_exists("ldap_connect")) -{ +if (!function_exists("ldap_connect")) { setEventMessages($langs->trans("LDAPFunctionsNotAvailableOnPHP"), null, 'errors'); } @@ -265,10 +299,8 @@ $objectclass = $conf->global->LDAP_CONTACT_OBJECT_CLASS; show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass); -if (function_exists("ldap_connect")) -{ - if ($_GET["action"] == 'test') - { +if (function_exists("ldap_connect")) { + if ($_GET["action"] == 'test') { // Creation objet $object = new Contact($db); $object->initAsSpecimen(); @@ -277,8 +309,7 @@ if (function_exists("ldap_connect")) $ldap = new Ldap(); $result = $ldap->connect_bind(); - if ($result > 0) - { + if ($result > 0) { $info = $object->_load_ldap_info(); $dn = $object->_load_ldap_dn($info); @@ -286,8 +317,7 @@ if (function_exists("ldap_connect")) $result2 = $ldap->add($dn, $info, $user); // Now the test $result3 = $ldap->delete($dn); // Clean what we did - if ($result2 > 0) - { + if ($result2 > 0) { print img_picto('', 'info').' '; print ''.$langs->trans("LDAPSynchroOK").'
    '; } else { diff --git a/htdocs/admin/ldap_groups.php b/htdocs/admin/ldap_groups.php index 61d2e8b69e9..13532474681 100644 --- a/htdocs/admin/ldap_groups.php +++ b/htdocs/admin/ldap_groups.php @@ -36,8 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "errors")); -if (!$user->admin) - accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); @@ -46,28 +47,44 @@ $action = GETPOST('action', 'aZ09'); * Actions */ -if ($action == 'setvalue' && $user->admin) -{ +if ($action == 'setvalue' && $user->admin) { $error = 0; $db->begin(); - if (!dolibarr_set_const($db, 'LDAP_GROUP_DN', GETPOST("group", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_GROUP_OBJECT_CLASS', GETPOST("objectclass", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; - - if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_FULLNAME', GETPOST("fieldfullname", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_DN', GETPOST("group", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + 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++; + } //if (! dolibarr_set_const($db, 'LDAP_GROUP_FIELD_NAME',GETPOST("fieldname", 'alphanohtml'),'chaine',0,'',$conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_DESCRIPTION', GETPOST("fielddescription", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_GROUPMEMBERS', GETPOST("fieldgroupmembers", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_GROUPID', GETPOST("fieldgroupid", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_DESCRIPTION', GETPOST("fielddescription", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_GROUPMEMBERS', GETPOST("fieldgroupmembers", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_GROUPID', GETPOST("fieldgroupid", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) { + $error++; + } // This one must be after the others $valkey = ''; $key = GETPOST("key"); - if ($key) $valkey = $conf->global->$key; - if (!dolibarr_set_const($db, 'LDAP_KEY_GROUPS', $valkey, 'chaine', 0, '', $conf->entity)) $error++; + if ($key) { + $valkey = $conf->global->$key; + } + if (!dolibarr_set_const($db, 'LDAP_KEY_GROUPS', $valkey, 'chaine', 0, '', $conf->entity)) { + $error++; + } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -90,8 +107,7 @@ print load_fiche_titre($langs->trans("LDAPSetup"), $linkback, 'title_setup'); $head = ldap_prepare_head(); // Test si fonction LDAP actives -if (!function_exists("ldap_connect")) -{ +if (!function_exists("ldap_connect")) { setEventMessages($langs->trans("LDAPFunctionsNotAvailableOnPHP"), null, 'errors'); } @@ -127,6 +143,13 @@ print '
    '.$langs->trans("LDAPGroupObjectClassListExample").' 
    '.$langs->trans("LDAPFilterConnection").''; +print ''; +print ''.$langs->trans("LDAPGroupFilterExample").'
    '; print '
    '; print ''; @@ -190,21 +213,25 @@ print ''; /* * Test de la connexion */ -if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') -{ +if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') { $butlabel = $langs->trans("LDAPTestSynchroGroup"); $testlabel = 'testgroup'; $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); +} 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 (function_exists("ldap_connect")) { + if ($action == 'testgroup') { // Creation objet $object = new UserGroup($db); $object->initAsSpecimen(); @@ -213,8 +240,7 @@ if (function_exists("ldap_connect")) $ldap = new Ldap(); $result = $ldap->connect_bind(); - if ($result > 0) - { + if ($result > 0) { $info = $object->_load_ldap_info(); $dn = $object->_load_ldap_dn($info); @@ -227,8 +253,7 @@ if (function_exists("ldap_connect")) $result2 = $ldap->add($dn, $info, $user); // Now the test $result3 = $ldap->delete($dn); // Clean what we did - if ($result2 > 0) - { + if ($result2 > 0) { print img_picto('', 'info').' '; print ''.$langs->trans("LDAPSynchroOK").'
    '; } else { @@ -251,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/ldap_members.php b/htdocs/admin/ldap_members.php index 214a4f2cb9b..d64628516ca 100644 --- a/htdocs/admin/ldap_members.php +++ b/htdocs/admin/ldap_members.php @@ -36,8 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'errors')); -if (!$user->admin) - accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); @@ -45,54 +46,116 @@ $action = GETPOST('action', 'aZ09'); * Actions */ -if ($action == 'setvalue' && $user->admin) -{ +if ($action == 'setvalue' && $user->admin) { $error = 0; $db->begin(); - if (!dolibarr_set_const($db, 'LDAP_MEMBER_DN', GETPOST("user"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FILTER', GETPOST("filterconnection"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_MEMBER_DN', GETPOST("user"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FILTER', GETPOST("filterconnection"), 'chaine', 0, '', $conf->entity)) { + $error++; + } // Members - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_LOGIN', GETPOST("fieldlogin"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_LOGIN_SAMBA', GETPOST("fieldloginsamba"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_PASSWORD', GETPOST("fieldpassword"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_PASSWORD_CRYPTED', GETPOST("fieldpasswordcrypted"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_NAME', GETPOST("fieldname"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_FIRSTNAME', GETPOST("fieldfirstname"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_MAIL', GETPOST("fieldmail"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_PHONE', GETPOST("fieldphone"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_PHONE_PERSO', GETPOST("fieldphoneperso"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_MOBILE', GETPOST("fieldmobile"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_SKYPE', GETPOST("fieldskype"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_FAX', GETPOST("fieldfax"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_COMPANY', GETPOST("fieldcompany"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_ADDRESS', GETPOST("fieldaddress"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_ZIP', GETPOST("fieldzip"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_TOWN', GETPOST("fieldtown"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_COUNTRY', GETPOST("fieldcountry"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_DESCRIPTION', GETPOST("fielddescription"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_NOTE_PUBLIC', GETPOST("fieldnotepublic"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_BIRTHDATE', GETPOST("fieldbirthdate"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_STATUS', GETPOST("fieldstatus"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION', GETPOST("fieldendlastsubscription"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_LOGIN', GETPOST("fieldlogin"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_LOGIN_SAMBA', GETPOST("fieldloginsamba"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_PASSWORD', GETPOST("fieldpassword"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_PASSWORD_CRYPTED', GETPOST("fieldpasswordcrypted"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_NAME', GETPOST("fieldname"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_FIRSTNAME', GETPOST("fieldfirstname"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_MAIL', GETPOST("fieldmail"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_PHONE', GETPOST("fieldphone"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_PHONE_PERSO', GETPOST("fieldphoneperso"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_MOBILE', GETPOST("fieldmobile"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_SKYPE', GETPOST("fieldskype"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_FAX', GETPOST("fieldfax"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_COMPANY', GETPOST("fieldcompany"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_ADDRESS', GETPOST("fieldaddress"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_ZIP', GETPOST("fieldzip"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_TOWN', GETPOST("fieldtown"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_COUNTRY', GETPOST("fieldcountry"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_DESCRIPTION', GETPOST("fielddescription"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_NOTE_PUBLIC', GETPOST("fieldnotepublic"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_BIRTHDATE', GETPOST("fieldbirthdate"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_STATUS', GETPOST("fieldstatus"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION', GETPOST("fieldendlastsubscription"), 'chaine', 0, '', $conf->entity)) { + $error++; + } // Subscriptions - if (!dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE', GETPOST("fieldfirstsubscriptiondate"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT', GETPOST("fieldfirstsubscriptionamount"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE', GETPOST("fieldlastsubscriptiondate"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT', GETPOST("fieldlastsubscriptionamount"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE', GETPOST("fieldfirstsubscriptiondate"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT', GETPOST("fieldfirstsubscriptionamount"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE', GETPOST("fieldlastsubscriptiondate"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT', GETPOST("fieldlastsubscriptionamount"), 'chaine', 0, '', $conf->entity)) { + $error++; + } // This one must be after the others $valkey = ''; $key = GETPOST("key"); - if ($key) $valkey = $conf->global->$key; - if (!dolibarr_set_const($db, 'LDAP_KEY_MEMBERS', $valkey, 'chaine', 0, '', $conf->entity)) $error++; + if ($key) { + $valkey = $conf->global->$key; + } + if (!dolibarr_set_const($db, 'LDAP_KEY_MEMBERS', $valkey, 'chaine', 0, '', $conf->entity)) { + $error++; + } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -117,8 +180,7 @@ print load_fiche_titre($langs->trans("LDAPSetup"), $linkback, 'title_setup'); $head = ldap_prepare_head(); // Test si fonction LDAP actives -if (!function_exists("ldap_connect")) -{ +if (!function_exists("ldap_connect")) { setEventMessages($langs->trans("LDAPFunctionsNotAvailableOnPHP"), null, 'errors'); } @@ -377,8 +439,7 @@ print ''; /* * Test de la connexion */ -if (!empty($conf->global->LDAP_MEMBER_ACTIVE)) -{ +if (!empty($conf->global->LDAP_MEMBER_ACTIVE)) { $butlabel = $langs->trans("LDAPTestSynchroMember"); $testlabel = 'testmember'; $key = $conf->global->LDAP_KEY_MEMBERS; @@ -388,10 +449,8 @@ if (!empty($conf->global->LDAP_MEMBER_ACTIVE)) show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass); } -if (function_exists("ldap_connect")) -{ - if ($_GET["action"] == 'testmember') - { +if (function_exists("ldap_connect")) { + if ($_GET["action"] == 'testmember') { // Creation objet $object = new Adherent($db); $object->initAsSpecimen(); @@ -400,8 +459,7 @@ if (function_exists("ldap_connect")) $ldap = new Ldap(); $result = $ldap->connect_bind(); - if ($result > 0) - { + if ($result > 0) { $info = $object->_load_ldap_info(); $dn = $object->_load_ldap_dn($info); @@ -409,8 +467,7 @@ if (function_exists("ldap_connect")) $result2 = $ldap->add($dn, $info, $user); // Now the test $result3 = $ldap->delete($dn); // Clean what we did - if ($result2 > 0) - { + if ($result2 > 0) { print img_picto('', 'info').' '; print ''.$langs->trans("LDAPSynchroOK").'
    '; } else { diff --git a/htdocs/admin/ldap_members_types.php b/htdocs/admin/ldap_members_types.php index 489e6047f9b..75ed864ecf0 100644 --- a/htdocs/admin/ldap_members_types.php +++ b/htdocs/admin/ldap_members_types.php @@ -36,8 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'errors')); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); @@ -46,26 +47,38 @@ $action = GETPOST('action', 'aZ09'); * Actions */ -if ($action == 'setvalue' && $user->admin) -{ +if ($action == 'setvalue' && $user->admin) { $error = 0; $db->begin(); - if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_DN', GETPOST("membertype"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_DN', GETPOST("membertype"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) { + $error++; + } - if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_DESCRIPTION', GETPOST("fielddescription"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS', GETPOST("fieldmembertypemembers"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_DESCRIPTION', GETPOST("fielddescription"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS', GETPOST("fieldmembertypemembers"), 'chaine', 0, '', $conf->entity)) { + $error++; + } // This one must be after the others $valkey = ''; $key = GETPOST("key"); - if ($key) $valkey = $conf->global->$key; - if (!dolibarr_set_const($db, 'LDAP_KEY_MEMBERS_TYPES', $valkey, 'chaine', 0, '', $conf->entity)) $error++; + if ($key) { + $valkey = $conf->global->$key; + } + if (!dolibarr_set_const($db, 'LDAP_KEY_MEMBERS_TYPES', $valkey, 'chaine', 0, '', $conf->entity)) { + $error++; + } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -88,8 +101,7 @@ print load_fiche_titre($langs->trans("LDAPSetup"), $linkback, 'title_setup'); $head = ldap_prepare_head(); // Test si fonction LDAP actives -if (!function_exists("ldap_connect")) -{ +if (!function_exists("ldap_connect")) { setEventMessages($langs->trans("LDAPFunctionsNotAvailableOnPHP"), null, 'errors'); } @@ -172,8 +184,7 @@ print ''; /* * Test de la connexion */ -if ($conf->global->LDAP_MEMBER_TYPE_ACTIVE == '1') -{ +if ($conf->global->LDAP_MEMBER_TYPE_ACTIVE == '1') { $butlabel = $langs->trans("LDAPTestSynchroMemberType"); $testlabel = 'testmembertype'; $key = $conf->global->LDAP_KEY_MEMBERS_TYPES; @@ -183,10 +194,8 @@ if ($conf->global->LDAP_MEMBER_TYPE_ACTIVE == '1') show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass); } -if (function_exists("ldap_connect")) -{ - if ($_GET["action"] == 'testmembertype') - { +if (function_exists("ldap_connect")) { + if ($_GET["action"] == 'testmembertype') { // Creation objet $object = new AdherentType($db); $object->initAsSpecimen(); @@ -195,8 +204,7 @@ if (function_exists("ldap_connect")) $ldap = new Ldap(); $result = $ldap->connect_bind(); - if ($result > 0) - { + if ($result > 0) { $info = $object->_load_ldap_info(); $dn = $object->_load_ldap_dn($info); @@ -209,8 +217,7 @@ if (function_exists("ldap_connect")) $result2 = $ldap->add($dn, $info, $user); // Now the test $result3 = $ldap->delete($dn); // Clean what we did - if ($result2 > 0) - { + if ($result2 > 0) { print img_picto('', 'info').' '; print ''.$langs->trans("LDAPSynchroOK").'
    '; } else { diff --git a/htdocs/admin/ldap_users.php b/htdocs/admin/ldap_users.php index efb34cca413..7e53eebc9ce 100644 --- a/htdocs/admin/ldap_users.php +++ b/htdocs/admin/ldap_users.php @@ -37,8 +37,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'errors')); -if (!$user->admin) - accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); @@ -46,47 +47,103 @@ $action = GETPOST('action', 'aZ09'); * Actions */ -if ($action == 'setvalue' && $user->admin) -{ +if ($action == 'setvalue' && $user->admin) { $error = 0; $db->begin(); - if (!dolibarr_set_const($db, 'LDAP_USER_DN', GETPOST("user"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_USER_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FILTER_CONNECTION', GETPOST("filterconnection"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_LOGIN', GETPOST("fieldlogin"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_LOGIN_SAMBA', GETPOST("fieldloginsamba"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_PASSWORD', GETPOST("fieldpassword"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_PASSWORD_CRYPTED', GETPOST("fieldpasswordcrypted"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_NAME', GETPOST("fieldname"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_FIRSTNAME', GETPOST("fieldfirstname"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_MAIL', GETPOST("fieldmail"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_PHONE', GETPOST("fieldphone"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_MOBILE', GETPOST("fieldmobile"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_SKYPE', GETPOST("fieldskype"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_FAX', GETPOST("fieldfax"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_COMPANY', GETPOST("fieldcompany"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_ADDRESS', GETPOST("fieldaddress"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_ZIP', GETPOST("fieldzip"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_TOWN', GETPOST("fieldtown"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_COUNTRY', GETPOST("fieldcountry"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_DESCRIPTION', GETPOST("fielddescription"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_SID', GETPOST("fieldsid"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_TITLE', GETPOST("fieldtitle"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_GROUPID', GETPOST("fieldgroupid"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_USERID', GETPOST("fielduserid"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_HOMEDIRECTORY', GETPOST("fieldhomedirectory"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_FIELD_HOMEDIRECTORYPREFIX', GETPOST("fieldhomedirectoryprefix"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_USER_DN', GETPOST("user"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_USER_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FILTER_CONNECTION', GETPOST("filterconnection"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_LOGIN', GETPOST("fieldlogin"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_LOGIN_SAMBA', GETPOST("fieldloginsamba"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_PASSWORD', GETPOST("fieldpassword"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_PASSWORD_CRYPTED', GETPOST("fieldpasswordcrypted"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_NAME', GETPOST("fieldname"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_FIRSTNAME', GETPOST("fieldfirstname"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_MAIL', GETPOST("fieldmail"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_PHONE', GETPOST("fieldphone"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_MOBILE', GETPOST("fieldmobile"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_SKYPE', GETPOST("fieldskype"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_FAX', GETPOST("fieldfax"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_COMPANY', GETPOST("fieldcompany"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_ADDRESS', GETPOST("fieldaddress"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_ZIP', GETPOST("fieldzip"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_TOWN', GETPOST("fieldtown"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_COUNTRY', GETPOST("fieldcountry"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_DESCRIPTION', GETPOST("fielddescription"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_SID', GETPOST("fieldsid"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_TITLE', GETPOST("fieldtitle"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_GROUPID', GETPOST("fieldgroupid"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_USERID', GETPOST("fielduserid"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_HOMEDIRECTORY', GETPOST("fieldhomedirectory"), 'chaine', 0, '', $conf->entity)) { + $error++; + } + if (!dolibarr_set_const($db, 'LDAP_FIELD_HOMEDIRECTORYPREFIX', GETPOST("fieldhomedirectoryprefix"), 'chaine', 0, '', $conf->entity)) { + $error++; + } // This one must be after the others $valkey = ''; $key = GETPOST("key"); - if ($key) $valkey = $conf->global->$key; - if (!dolibarr_set_const($db, 'LDAP_KEY_USERS', $valkey, 'chaine', 0, '', $conf->entity)) $error++; + if ($key) { + $valkey = $conf->global->$key; + } + if (!dolibarr_set_const($db, 'LDAP_KEY_USERS', $valkey, 'chaine', 0, '', $conf->entity)) { + $error++; + } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -111,8 +168,7 @@ print load_fiche_titre($langs->trans("LDAPSetup"), $linkback, 'title_setup'); $head = ldap_prepare_head(); // Test si fonction LDAP actives -if (!function_exists("ldap_connect")) -{ +if (!function_exists("ldap_connect")) { setEventMessages($langs->trans("LDAPFunctionsNotAvailableOnPHP"), null, 'errors'); } @@ -346,8 +402,7 @@ print ''; /* * Test de la connexion */ -if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') -{ +if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') { $butlabel = $langs->trans("LDAPTestSynchroUser"); $testlabel = 'testuser'; $key = $conf->global->LDAP_KEY_USERS; @@ -355,8 +410,7 @@ if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') $objectclass = $conf->global->LDAP_USER_OBJECT_CLASS; show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass); -} elseif ($conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr') -{ +} elseif ($conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr') { $butlabel = $langs->trans("LDAPTestSearch"); $testlabel = 'testsearchuser'; $key = $conf->global->LDAP_KEY_USERS; @@ -365,10 +419,8 @@ if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass); } -if (function_exists("ldap_connect")) -{ - if ($action == 'testuser') - { +if (function_exists("ldap_connect")) { + if ($action == 'testuser') { // Creation objet $object = new User($db); $object->initAsSpecimen(); @@ -379,8 +431,7 @@ if (function_exists("ldap_connect")) $ldap = new Ldap(); $result = $ldap->connect_bind(); - if ($result > 0) - { + if ($result > 0) { $info = $object->_load_ldap_info(); $dn = $object->_load_ldap_dn($info); @@ -388,8 +439,7 @@ if (function_exists("ldap_connect")) $result2 = $ldap->add($dn, $info, $user); // Now the test $result3 = $ldap->delete($dn); // Clean what we did - if ($result2 > 0) - { + if ($result2 > 0) { print img_picto('', 'info').' '; print ''.$langs->trans("LDAPSynchroOK").'
    '; } else { @@ -413,8 +463,7 @@ if (function_exists("ldap_connect")) } } - if ($action == 'testsearchuser') - { + if ($action == 'testsearchuser') { // Creation objet $object = new User($db); $object->initAsSpecimen(); @@ -425,8 +474,7 @@ if (function_exists("ldap_connect")) $ldap = new Ldap(); $result = $ldap->connect_bind(); - if ($result > 0) - { + if ($result > 0) { $required_fields = array( $conf->global->LDAP_KEY_USERS, $conf->global->LDAP_FIELD_FULLNAME, @@ -453,17 +501,13 @@ if (function_exists("ldap_connect")) $ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 1); //$ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, '', 1); - if (is_array($ldapusers)) - { + if (is_array($ldapusers)) { $liste = array(); - foreach ($ldapusers as $key => $ldapuser) - { + foreach ($ldapusers as $key => $ldapuser) { // Define the label string for this user $label = ''; - foreach ($required_fields as $value) - { - if ($value) - { + foreach ($required_fields as $value) { + if ($value) { $label .= $value."=".$ldapuser[$value]." "; } } diff --git a/htdocs/admin/limits.php b/htdocs/admin/limits.php index 08c19091caa..4a599499053 100644 --- a/htdocs/admin/limits.php +++ b/htdocs/admin/limits.php @@ -29,7 +29,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Load translation files required by the page $langs->loadLangs(array('companies', 'products', 'admin')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $currencycode = GETPOST('currencycode', 'alpha'); @@ -49,39 +51,33 @@ $valmainmaxdecimalstot = GETPOST($mainmaxdecimalstot, 'int'); $valmainmaxdecimalsshown = GETPOST($mainmaxdecimalsshown, 'int'); $valmainroundingruletot = price2num(GETPOST($mainroundingruletot, 'alpha')); -if ($action == 'update') -{ +if ($action == 'update') { $error = 0; $MAXDEC = 8; if ($_POST[$mainmaxdecimalsunit] > $MAXDEC || $_POST[$mainmaxdecimalstot] > $MAXDEC - || $_POST[$mainmaxdecimalsshown] > $MAXDEC) - { + || $_POST[$mainmaxdecimalsshown] > $MAXDEC) { $error++; setEventMessages($langs->trans("ErrorDecimalLargerThanAreForbidden", $MAXDEC), null, 'errors'); } if ($_POST[$mainmaxdecimalsunit].(!empty($currencycode) ? '_'.$currencycode : '') < 0 || $_POST[$mainmaxdecimalstot] < 0 - || $_POST[$mainmaxdecimalsshown] < 0) - { + || $_POST[$mainmaxdecimalsshown] < 0) { $langs->load("errors"); $error++; setEventMessages($langs->trans("ErrorNegativeValueNotAllowed"), null, 'errors'); } - if ($valmainroundingruletot) - { - if ($valmainroundingruletot * pow(10, $valmainmaxdecimalstot) < 1) - { + if ($valmainroundingruletot) { + if ($valmainroundingruletot * pow(10, $valmainmaxdecimalstot) < 1) { $langs->load("errors"); $error++; setEventMessages($langs->trans("ErrorMAIN_ROUNDING_RULE_TOTCanMAIN_MAX_DECIMALS_TOT"), null, 'errors'); } } - if (!$error) - { + if (!$error) { dolibarr_set_const($db, $mainmaxdecimalsunit, $valmainmaxdecimalsunit, 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, $mainmaxdecimalstot, $valmainmaxdecimalstot, 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, $mainmaxdecimalsshown, $valmainmaxdecimalsshown, 'chaine', 0, '', $conf->entity); @@ -109,24 +105,20 @@ print load_fiche_titre($title, '', 'title_setup'); $aCurrencies = array($conf->currency); // Default currency always first position -if (!empty($conf->multicurrency->enabled) && !empty($conf->global->MULTICURRENCY_USE_LIMIT_BY_CURRENCY)) -{ +if (!empty($conf->multicurrency->enabled) && !empty($conf->global->MULTICURRENCY_USE_LIMIT_BY_CURRENCY)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/multicurrency.lib.php'; $sql = 'SELECT rowid, code FROM '.MAIN_DB_PREFIX.'multicurrency'; $sql .= ' WHERE entity = '.$conf->entity; $sql .= ' AND code != "'.$conf->currency.'"'; // Default currency always first position $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $db->fetch_object($resql)) { $aCurrencies[] = $obj->code; } } - if (!empty($aCurrencies) && count($aCurrencies) > 1) - { + if (!empty($aCurrencies) && count($aCurrencies) > 1) { $head = multicurrencyLimitPrepareHead($aCurrencies); print dol_get_fiche_head($head, $currencycode, '', -1, ''); @@ -136,8 +128,7 @@ if (!empty($conf->multicurrency->enabled) && !empty($conf->global->MULTICURRENCY print ''.$langs->trans("LimitsDesc")."
    \n"; print "
    \n"; -if ($action == 'edit') -{ +if ($action == 'edit') { print ''; print ''; print ''; @@ -203,16 +194,13 @@ if ($action == 'edit') print ''; } -if (!empty($conf->multicurrency->enabled) && !empty($conf->global->MULTICURRENCY_USE_LIMIT_BY_CURRENCY)) -{ - if (!empty($aCurrencies) && count($aCurrencies) > 1) - { +if (!empty($conf->multicurrency->enabled) && !empty($conf->global->MULTICURRENCY_USE_LIMIT_BY_CURRENCY)) { + if (!empty($aCurrencies) && count($aCurrencies) > 1) { print dol_get_fiche_end(); } } -if (empty($mysoc->country_code)) -{ +if (empty($mysoc->country_code)) { $langs->load("errors"); $warnpicto = img_warning($langs->trans("WarningMandatorySetupNotComplete")); print '
    '.$warnpicto.' '.$langs->trans("WarningMandatorySetupNotComplete").''; @@ -252,26 +240,22 @@ if (empty($mysoc->country_code)) $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($mysoc->country_code)."' AND (t.taux <> 0 OR t.localtax1 <>0 OR t.localtax2 <>0)"; $sql .= " ORDER BY t.taux ASC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { - for ($i = 0; $i < $num; $i++) - { + if ($num) { + for ($i = 0; $i < $num; $i++) { $obj = $db->fetch_object($resql); $vat_rates[] = array('vat_rate'=>$obj->vat_rate, 'code'=>$obj->vat_code, 'localtax_rate1'=>$obj->localtax_rate1, 'locltax_rate2'=>$obj->localtax_rate2); } } - } else dol_print_error($db); + } else { + dol_print_error($db); + } - if (count($vat_rates)) - { - foreach ($vat_rates as $vatarray) - { + if (count($vat_rates)) { + foreach ($vat_rates as $vatarray) { $vat = $vatarray['vat_rate']; - for ($qty = 1; $qty <= 2; $qty++) - { + for ($qty = 1; $qty <= 2; $qty++) { $vattxt = $vat.($vatarray['code'] ? ' ('.$vatarray['code'].')' : ''); $localtax_array = getLocalTaxesFromRate($vattxt, 0, $mysoc, $mysoc); diff --git a/htdocs/admin/loan.php b/htdocs/admin/loan.php index ee358300ca4..94b0da08d4f 100644 --- a/htdocs/admin/loan.php +++ b/htdocs/admin/loan.php @@ -26,14 +26,17 @@ require '../main.inc.php'; // Class require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('admin', 'loan')); // Security check -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); @@ -48,8 +51,7 @@ $list = array( * Actions */ -if ($action == 'update') -{ +if ($action == 'update') { $error = 0; foreach ($list as $constname) { @@ -60,8 +62,7 @@ if ($action == 'update') } } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -75,7 +76,9 @@ if ($action == 'update') llxHeader(); $form = new Form($db); -if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); +if (!empty($conf->accounting->enabled)) { + $formaccounting = new FormAccounting($db); +} $linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans('ConfigLoan'), $linkback, 'title_setup'); @@ -92,8 +95,7 @@ print ''; print ''; print "\n"; -foreach ($list as $key) -{ +foreach ($list as $key) { print ''; // Param @@ -102,8 +104,7 @@ foreach ($list as $key) // Value print ''; - print ''; + print ''; print ''; // IP print ''; print ''; print ''; - if (!empty($arrayfields['e.user_agent']['checked'])) - { + if (!empty($arrayfields['e.user_agent']['checked'])) { print ''; } - if (!empty($arrayfields['e.prefix_session']['checked'])) - { + if (!empty($arrayfields['e.prefix_session']['checked'])) { print ''; } @@ -311,25 +368,22 @@ if ($result) print_liste_field_titre("IP", $_SERVER["PHP_SELF"], "e.ip", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("User", $_SERVER["PHP_SELF"], "u.login", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("Description", $_SERVER["PHP_SELF"], "e.description", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['e.user_agent']['checked'])) - { + if (!empty($arrayfields['e.user_agent']['checked'])) { print_liste_field_titre("UserAgent", $_SERVER["PHP_SELF"], "e.user_agent", "", $param, '', $sortfield, $sortorder); } - if (!empty($arrayfields['e.prefix_session']['checked'])) - { + if (!empty($arrayfields['e.prefix_session']['checked'])) { print_liste_field_titre("PrefixSession", $_SERVER["PHP_SELF"], "e.prefix_session", "", $param, '', $sortfield, $sortorder); } print_liste_field_titre(''); print "\n"; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($result); print ''; // Date - print ''; + print ''; // Code print ''; @@ -341,8 +395,7 @@ if ($result) // Login print ''; // Description print ''; - if (!empty($arrayfields['e.user_agent']['checked'])) - { + if (!empty($arrayfields['e.user_agent']['checked'])) { // User agent print ''; } - if (!empty($arrayfields['e.prefix_session']['checked'])) - { + if (!empty($arrayfields['e.prefix_session']['checked'])) { // User agent print ''; - else print ''; + if ($num == 0) { + if ($usefilter) { + print ''; + } else { + print ''; + } } print "
    '.$langs->trans('Options').'
    '; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); } else { print ''; diff --git a/htdocs/admin/mailing.php b/htdocs/admin/mailing.php index 4ea5db1cecd..1b0df5843f3 100644 --- a/htdocs/admin/mailing.php +++ b/htdocs/admin/mailing.php @@ -30,7 +30,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "mails")); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); @@ -41,8 +43,7 @@ $form = new Form($db); * Actions */ -if ($action == 'setvalue') -{ +if ($action == 'setvalue') { $db->begin(); $mailfrom = GETPOST('MAILING_EMAIL_FROM', 'alpha'); @@ -53,17 +54,27 @@ if ($action == 'setvalue') $contactbulkdefault = GETPOST('MAILING_CONTACT_DEFAULT_BULK_STATUS', 'int'); $res = dolibarr_set_const($db, "MAILING_EMAIL_FROM", $mailfrom, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } $res = dolibarr_set_const($db, "MAILING_EMAIL_ERRORSTO", $mailerror, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } $res = dolibarr_set_const($db, "MAILING_DELAY", $mailingdelay, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } $res = dolibarr_set_const($db, "MAILING_CONTACT_DEFAULT_BULK_STATUS", $contactbulkdefault, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } // Create temporary encryption key if nedded $res = dolibarr_set_const($db, "MAILING_EMAIL_UNSUBSCRIBE_KEY", $checkread_key, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } if (!$error) { @@ -77,9 +88,10 @@ if ($action == 'setvalue') if ($action == 'setonsearchandlistgooncustomerorsuppliercard') { $setonsearchandlistgooncustomerorsuppliercard = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD", $setonsearchandlistgooncustomerorsuppliercard, 'yesno', 0, '', $conf->entity); - if (!($res > 0)) $error++; - if (!$error) - { + if (!($res > 0)) { + $error++; + } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -95,8 +107,7 @@ llxHeader('', $langs->trans("MailingSetup")); $linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("MailingSetup"), $linkback, 'title_setup'); -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print "\n".' @@ -96,23 +101,21 @@ print $langs->trans("RestoreDesc3", $dolibarr_main_db_name).'

    ';
    trans("ImportMethod"); ?> - -
    - /> - -
    - + /> + +
    + -
    - /> - -
    - + /> + + + trans("RestoreDesc3", $dolibarr_main_db_name).'

    ';
    '; print ''.$langs->trans('RestoreMySQL').''; print '
    '; // Parameteres execution $command = $db->getPathOfRestore(); - if (preg_match("/\s/", $command)) $command = $command = escapeshellarg($command); // Use quotes on command + if (preg_match("/\s/", $command)) { + $command = $command = escapeshellarg($command); // Use quotes on command + } $param = $dolibarr_main_db_name; $param .= " -h ".$dolibarr_main_db_host; - if (!empty($dolibarr_main_db_port)) $param .= " -P ".$dolibarr_main_db_port; + if (!empty($dolibarr_main_db_port)) { + $param .= " -P ".$dolibarr_main_db_port; + } $param .= " -u ".$dolibarr_main_db_user; $paramcrypted = $param; $paramclear = $param; - if (!empty($dolibarr_main_db_pass)) - { + if (!empty($dolibarr_main_db_pass)) { $paramcrypted .= " -p".preg_replace('/./i', '*', $dolibarr_main_db_pass); $paramclear .= " -p".$dolibarr_main_db_pass; } @@ -158,26 +163,29 @@ if (in_array($type, array('mysql', 'mysqli'))) //else print '
    '.$langs->trans("HidePassword").''; print '
    '; print ''; -} elseif (in_array($type, array('pgsql'))) -{ +} elseif (in_array($type, array('pgsql'))) { print '
    '; print 'Restore PostgreSQL'; print '
    '; // Parameteres execution $command = $db->getPathOfRestore(); - if (preg_match("/\s/", $command)) $command = $command = escapeshellarg($command); // Use quotes on command + if (preg_match("/\s/", $command)) { + $command = $command = escapeshellarg($command); // Use quotes on command + } $param = " -d ".$dolibarr_main_db_name; $param .= " -h ".$dolibarr_main_db_host; - if (!empty($dolibarr_main_db_port)) $param .= " -p ".$dolibarr_main_db_port; + if (!empty($dolibarr_main_db_port)) { + $param .= " -p ".$dolibarr_main_db_port; + } $param .= " -U ".$dolibarr_main_db_user; $paramcrypted = $param; $paramclear = $param; /*if (! empty($dolibarr_main_db_pass)) - { - $paramcrypted.=" -p".preg_replace('/./i','*',$dolibarr_main_db_pass); - $paramclear.=" -p".$dolibarr_main_db_pass; - }*/ + { + $paramcrypted.=" -p".preg_replace('/./i','*',$dolibarr_main_db_pass); + $paramclear.=" -p".$dolibarr_main_db_pass; + }*/ $paramcrypted .= " -W"; $paramclear .= " -W"; // With psql: diff --git a/htdocs/admin/tools/export.php b/htdocs/admin/tools/export.php index b2fd7f5c2ee..0fe8be7d50c 100644 --- a/htdocs/admin/tools/export.php +++ b/htdocs/admin/tools/export.php @@ -40,15 +40,22 @@ $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; -if (!$sortorder) $sortorder = "DESC"; -if (!$sortfield) $sortfield = "date"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "date"; +} -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} -if ($file && !$what) -{ +if ($file && !$what) { //print DOL_URL_ROOT.'/dolibarr_export.php'; header("Location: ".DOL_URL_ROOT.'/admin/tools/dolibarr_export.php?msg='.urlencode($langs->trans("ErrorFieldRequired", $langs->transnoentities("ExportMethod"))).(GETPOST('page_y', 'int') ? '&page_y='.GETPOST('page_y', 'int') : '')); exit; @@ -61,12 +68,14 @@ $errormsg = ''; * Actions */ -if ($action == 'delete') -{ +if ($action == 'delete') { $file = $conf->admin->dir_output.'/'.GETPOST('urlfile'); $ret = dol_delete_file($file, 1); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors'); + if ($ret) { + setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors'); + } $action = ''; } @@ -81,8 +90,7 @@ $_SESSION["commandbackupresult"] = ''; // Increase limit of time. Works only if we are not in safe mode $ExecTimeLimit = 600; // Set it to 0 to not use a forced time limit -if (!empty($ExecTimeLimit)) -{ +if (!empty($ExecTimeLimit)) { $err = error_reporting(); error_reporting(0); // Disable all errors //error_reporting(E_ALL); @@ -90,8 +98,7 @@ if (!empty($ExecTimeLimit)) error_reporting($err); } $MemoryLimit = 0; -if (!empty($MemoryLimit)) -{ +if (!empty($MemoryLimit)) { @ini_set('memory_limit', $MemoryLimit); } @@ -118,29 +125,24 @@ $utils = new Utils($db); // MYSQL -if ($what == 'mysql') -{ +if ($what == 'mysql') { $cmddump = GETPOST("mysqldump", 'none'); // Do not sanitize here with 'alpha', will be sanitize later by dol_sanitizePathName and escapeshellarg $cmddump = dol_sanitizePathName($cmddump); - if (!empty($dolibarr_main_restrict_os_commands)) - { + if (!empty($dolibarr_main_restrict_os_commands)) { $arrayofallowedcommand = explode(',', $dolibarr_main_restrict_os_commands); dol_syslog("Command are restricted to ".$dolibarr_main_restrict_os_commands.". We check that one of this command is inside ".$cmddump); $basenamecmddump = basename($cmddump); - if (!in_array($basenamecmddump, $arrayofallowedcommand)) // the provided command $cmddump must be an allowed command - { + if (!in_array($basenamecmddump, $arrayofallowedcommand)) { // the provided command $cmddump must be an allowed command $errormsg = $langs->trans('CommandIsNotInsideAllowedCommands'); } } - if (!$errormsg && $cmddump) - { + if (!$errormsg && $cmddump) { dolibarr_set_const($db, 'SYSTEMTOOLS_MYSQLDUMP', $cmddump, 'chaine', 0, '', $conf->entity); } - if (!$errormsg) - { + if (!$errormsg) { $utils->dumpDatabase(GETPOST('compression', 'alpha'), $what, 0, $file); $errormsg = $utils->error; $_SESSION["commandbackuplastdone"] = $utils->result['commandbackuplastdone']; @@ -149,8 +151,7 @@ if ($what == 'mysql') } // MYSQL NO BIN -if ($what == 'mysqlnobin') -{ +if ($what == 'mysqlnobin') { $utils->dumpDatabase(GETPOST('compression', 'alpha'), $what, 0, $file); $errormsg = $utils->error; @@ -159,30 +160,27 @@ if ($what == 'mysqlnobin') } // POSTGRESQL -if ($what == 'postgresql') -{ +if ($what == 'postgresql') { $cmddump = GETPOST("postgresqldump", 'none'); // Do not sanitize here with 'alpha', will be sanitize later by dol_sanitizePathName and escapeshellarg $cmddump = dol_sanitizePathName($cmddump); /* Not required, the command is output on screen but not ran for pgsql - if (! empty($dolibarr_main_restrict_os_commands)) - { - $arrayofallowedcommand=explode(',', $dolibarr_main_restrict_os_commands); - dol_syslog("Command are restricted to ".$dolibarr_main_restrict_os_commands.". We check that one of this command is inside ".$cmddump); - $basenamecmddump=basename($cmddump); - if (! in_array($basenamecmddump, $arrayofallowedcommand)) // the provided command $cmddump must be an allowed command - { - $errormsg=$langs->trans('CommandIsNotInsideAllowedCommands'); - } - } */ - - if (!$errormsg && $cmddump) + if (! empty($dolibarr_main_restrict_os_commands)) { + $arrayofallowedcommand=explode(',', $dolibarr_main_restrict_os_commands); + dol_syslog("Command are restricted to ".$dolibarr_main_restrict_os_commands.". We check that one of this command is inside ".$cmddump); + $basenamecmddump=basename($cmddump); + if (! in_array($basenamecmddump, $arrayofallowedcommand)) // the provided command $cmddump must be an allowed command + { + $errormsg=$langs->trans('CommandIsNotInsideAllowedCommands'); + } + } */ + + if (!$errormsg && $cmddump) { dolibarr_set_const($db, 'SYSTEMTOOLS_POSTGRESQLDUMP', $cmddump, 'chaine', 0, '', $conf->entity); } - if (!$errormsg) - { + if (!$errormsg) { $utils->dumpDatabase(GETPOST('compression', 'alpha'), $what, 0, $file); $errormsg = $utils->error; $_SESSION["commandbackuplastdone"] = $utils->result['commandbackuplastdone']; @@ -193,8 +191,7 @@ if ($what == 'postgresql') } -if ($errormsg) -{ +if ($errormsg) { setEventMessages($langs->trans("Error")." : ".$errormsg, null, 'errors'); $resultstring = ''; @@ -202,8 +199,7 @@ if ($errormsg) $_SESSION["commandbackupresult"] = $resultstring; } else { - if ($what) - { + if ($what) { setEventMessages($langs->trans("BackupFileSuccessfullyCreated").'.
    '.$langs->trans("YouCanDownloadBackupFile"), null, 'mesgs'); $resultstring = '
    '; diff --git a/htdocs/admin/tools/export_files.php b/htdocs/admin/tools/export_files.php index 6e0b0508a07..34685676320 100644 --- a/htdocs/admin/tools/export_files.php +++ b/htdocs/admin/tools/export_files.php @@ -42,13 +42,23 @@ $file = preg_replace('/(\.zip|\.tar|\.tgz|\.gz|\.tar\.gz|\.bz2)$/i', '', $file); $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (!$sortorder) $sortorder = "DESC"; -if (!$sortfield) $sortfield = "date"; -if ($page < 0) { $page = 0; } elseif (empty($page)) $page = 0; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "date"; +} +if ($page < 0) { + $page = 0; +} elseif (empty($page)) { + $page = 0; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $errormsg = ''; @@ -57,13 +67,15 @@ $errormsg = ''; * Actions */ -if ($action == 'delete') -{ +if ($action == 'delete') { $filerelative = dol_sanitizeFileName(GETPOST('urlfile', 'alpha')); $filepath = $conf->admin->dir_output.'/'.$filerelative; $ret = dol_delete_file($filepath, 1); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", $filerelative), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", $filerelative), null, 'errors'); + if ($ret) { + setEventMessages($langs->trans("FileWasRemoved", $filerelative), null, 'mesgs'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", $filerelative), null, 'errors'); + } $action = ''; } @@ -74,8 +86,7 @@ if ($action == 'delete') // Increase limit of time. Works only if we are not in safe mode $ExecTimeLimit = 1800; // 30mn -if (!empty($ExecTimeLimit)) -{ +if (!empty($ExecTimeLimit)) { $err = error_reporting(); error_reporting(0); // Disable all errors //error_reporting(E_ALL); @@ -83,8 +94,7 @@ if (!empty($ExecTimeLimit)) error_reporting($err); } $MemoryLimit = 0; -if (!empty($MemoryLimit)) -{ +if (!empty($MemoryLimit)) { @ini_set('memory_limit', $MemoryLimit); } @@ -110,12 +120,11 @@ $result = dol_mkdir($outputdir); $utils = new Utils($db); -if ($compression == 'zip') -{ +if ($compression == 'zip') { $file .= '.zip'; - $ret = dol_compress_dir(DOL_DATA_ROOT, $outputdir."/".$file, $compression, '/(\.back|\.old|\.log|[\\\/]temp[\\\/]|documents[\\\/]admin[\\\/]documents[\\\/])/i'); - if ($ret < 0) - { + $excludefiles = '/(\.back|\.old|\.log|[\/\\\]temp[\/\\\]|documents[\/\\\]admin[\/\\\]documents[\/\\\])/i'; + $ret = dol_compress_dir(DOL_DATA_ROOT, $outputdir."/".$file, $compression, $excludefiles); + if ($ret < 0) { if ($ret == -2) { $langs->load("errors"); $errormsg = $langs->trans("ErrNoZipEngine"); @@ -124,8 +133,7 @@ if ($compression == 'zip') $errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputdir); } } -} elseif (in_array($compression, array('gz', 'bz'))) -{ +} elseif (in_array($compression, array('gz', 'bz'))) { $userlogin = ($user->login ? $user->login : 'unknown'); $outputfile = $conf->admin->dir_temp.'/export_files.'.$userlogin.'.out'; // File used with popen method @@ -137,34 +145,29 @@ if ($compression == 'zip') $result = $utils->executeCLI($cmd, $outputfile); $retval = $result['error']; - if ($result['result'] || !empty($retval)) - { + if ($result['result'] || !empty($retval)) { $langs->load("errors"); dol_syslog("Documents tar retval after exec=".$retval, LOG_ERR); $errormsg = 'Error tar generation return '.$retval; } else { - if ($compression == 'gz') - { + if ($compression == 'gz') { $cmd = "gzip -f ".$outputdir."/".$file; } - if ($compression == 'bz') - { + if ($compression == 'bz') { $cmd = "bzip2 -f ".$outputdir."/".$file; } $result = $utils->executeCLI($cmd, $outputfile); $retval = $result['error']; - if ($result['result'] || !empty($retval)) - { + if ($result['result'] || !empty($retval)) { $errormsg = 'Error '.$compression.' generation return '.$retval; unlink($outputdir."/".$file); } } } -if ($errormsg) -{ +if ($errormsg) { setEventMessages($langs->trans("Error")." : ".$errormsg, null, 'errors'); } diff --git a/htdocs/admin/tools/index.php b/htdocs/admin/tools/index.php index 06de5cc285c..4c89ab60989 100644 --- a/htdocs/admin/tools/index.php +++ b/htdocs/admin/tools/index.php @@ -27,8 +27,9 @@ require '../../main.inc.php'; // Load translation files required by the page $langs->loadLangs(array("companies", "admin")); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} /* diff --git a/htdocs/admin/tools/listevents.php b/htdocs/admin/tools/listevents.php index 2b832910623..935804ada10 100644 --- a/htdocs/admin/tools/listevents.php +++ b/htdocs/admin/tools/listevents.php @@ -28,15 +28,15 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/events.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -49,12 +49,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) { $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 = "dateevent"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "dateevent"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} $search_code = GETPOST("search_code", "alpha"); $search_ip = GETPOST("search_ip", "alpha"); @@ -63,23 +69,34 @@ $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")); -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")); -else $date_end = -1; - -// checks:if date_start>date_end then date_end=date_start + 24 hours -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 -{ +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 (!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; +} + +// checks:if date_start>date_end then date_end=date_start + 24 hours +if ($date_start > 0 && $date_end > 0 && $date_start > $date_end) { + $date_end = $date_start + 86400; +} + + +if (empty($date_start)) { // We define date_start and date_end $date_start = dol_get_first_day($nowarray['year'], $nowarray['mon'], false); } -if (empty($date_end)) -{ +if (empty($date_end)) { $date_end = dol_mktime(23, 59, 59, $nowarray['mon'], $nowarray['mday'], $nowarray['year']); } // Set $date_startmonth... @@ -102,7 +119,6 @@ $arrayfields = array( ) ); - /* * Actions */ @@ -110,8 +126,7 @@ $arrayfields = array( $now = dol_now(); // 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 $date_start = -1; $date_end = -1; $search_code = ''; @@ -123,8 +138,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' } // Purge audit events -if ($action == 'confirm_purge' && $confirm == 'yes' && $user->admin) -{ +if ($action == 'confirm_purge' && $confirm == 'yes' && $user->admin) { $error = 0; $db->begin(); @@ -136,8 +150,7 @@ if ($action == 'confirm_purge' && $confirm == 'yes' && $user->admin) dol_syslog("listevents purge", LOG_DEBUG); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; setEventMessages($db->lasterror(), null, 'errors'); } @@ -150,8 +163,7 @@ if ($action == 'confirm_purge' && $confirm == 'yes' && $user->admin) $securityevent->description = $text; $result = $securityevent->create($user); - if ($result > 0) - { + if ($result > 0) { $db->commit(); dol_syslog($text, LOG_WARNING); } else { @@ -166,7 +178,8 @@ if ($action == 'confirm_purge' && $confirm == 'yes' && $user->admin) * View */ -llxHeader('', $langs->trans("Audit")); +$title = $langs->trans("Audit"); +llxHeader('', $title); $form = new Form($db); @@ -179,57 +192,101 @@ $sql .= " u.login, u.admin, u.entity, u.firstname, u.lastname, u.statut as statu $sql .= " FROM ".MAIN_DB_PREFIX."events as e"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = e.fk_user"; $sql .= " WHERE e.entity IN (".getEntity('event').")"; -if ($date_start > 0) $sql .= " AND e.dateevent >= '".$db->idate($date_start)."'"; -if ($date_end > 0) $sql .= " AND e.dateevent <= '".$db->idate($date_end)."'"; -if ($search_code) { $usefilter++; $sql .= natural_search("e.type", $search_code, 0); } -if ($search_ip) { $usefilter++; $sql .= natural_search("e.ip", $search_ip, 0); } -if ($search_user) { $usefilter++; $sql .= natural_search("u.login", $search_user, 0); } -if ($search_desc) { $usefilter++; $sql .= natural_search("e.description", $search_desc, 0); } -if ($search_ua) { $usefilter++; $sql .= natural_search("e.user_agent", $search_ua, 0); } -if ($search_prefix_session) { $usefilter++; $sql .= natural_search("e.prefix_session", $search_prefix_session, 0); } +if ($date_start > 0) { + $sql .= " AND e.dateevent >= '".$db->idate($date_start)."'"; +} +if ($date_end > 0) { + $sql .= " AND e.dateevent <= '".$db->idate($date_end)."'"; +} +if ($search_code) { + $usefilter++; $sql .= natural_search("e.type", $search_code, 0); +} +if ($search_ip) { + $usefilter++; $sql .= natural_search("e.ip", $search_ip, 0); +} +if ($search_user) { + $usefilter++; $sql .= natural_search("u.login", $search_user, 0); +} +if ($search_desc) { + $usefilter++; $sql .= natural_search("e.description", $search_desc, 0); +} +if ($search_ua) { + $usefilter++; $sql .= natural_search("e.user_agent", $search_ua, 0); +} +if ($search_prefix_session) { + $usefilter++; $sql .= natural_search("e.prefix_session", $search_prefix_session, 0); +} $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; /*if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { - $page = 0; - $offset = 0; - } + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } }*/ $sql .= $db->plimit($conf->liste_limit + 1, $offset); //print $sql; $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 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 ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($search_code) $param .= '&search_code='.urlencode($search_code); - if ($search_ip) $param .= '&search_ip='.urlencode($search_ip); - if ($search_user) $param .= '&search_user='.urlencode($search_user); - if ($search_desc) $param .= '&search_desc='.urlencode($search_desc); - if ($search_ua) $param .= '&search_ua='.urlencode($search_ua); - if ($search_prefix_session) $param .= '&search_prefix_session='.urlencode($search_prefix_session); - if ($date_startmonth) $param .= "&date_startmonth=".urlencode($date_startmonth); - if ($date_startday) $param .= "&date_startday=".urlencode($date_startday); - if ($date_startyear) $param .= "&date_startyear=".urlencode($date_startyear); - if ($date_endmonth) $param .= "&date_endmonth=".urlencode($date_endmonth); - if ($date_endday) $param .= "&date_endday=".urlencode($date_endday); - if ($date_endyear) $param .= "&date_endyear=".urlencode($date_endyear); + 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 ($search_code) { + $param .= '&search_code='.urlencode($search_code); + } + if ($search_ip) { + $param .= '&search_ip='.urlencode($search_ip); + } + if ($search_user) { + $param .= '&search_user='.urlencode($search_user); + } + if ($search_desc) { + $param .= '&search_desc='.urlencode($search_desc); + } + if ($search_ua) { + $param .= '&search_ua='.urlencode($search_ua); + } + if ($search_prefix_session) { + $param .= '&search_prefix_session='.urlencode($search_prefix_session); + } + if ($date_startmonth) { + $param .= "&date_startmonth=".urlencode($date_startmonth); + } + if ($date_startday) { + $param .= "&date_startday=".urlencode($date_startday); + } + if ($date_startyear) { + $param .= "&date_startyear=".urlencode($date_startyear); + } + if ($date_endmonth) { + $param .= "&date_endmonth=".urlencode($date_endmonth); + } + if ($date_endday) { + $param .= "&date_endday=".urlencode($date_endday); + } + if ($date_endyear) { + $param .= "&date_endyear=".urlencode($date_endyear); + } $langs->load('withdrawals'); - if ($num) - { + if ($num) { $center = ''.$langs->trans("Purge").''; } @@ -238,8 +295,7 @@ if ($result) print_barre_liste($langs->trans("ListOfSecurityEvents"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $center, $num, $nbtotalofrecords, 'setup', 0, '', '', $limit); - if ($action == 'purge') - { + if ($action == 'purge') { $formquestion = array(); print $form->formconfirm($_SERVER["PHP_SELF"].'?noparam=noparam', $langs->trans('PurgeAuditEvents'), $langs->trans('ConfirmPurgeAuditEvents'), 'confirm_purge', $formquestion, 'no', 1); } @@ -264,36 +320,37 @@ if ($result) // Fields title search 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 ''; //print ''; 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.''; - if ($obj->fk_user) - { + if ($obj->fk_user) { $userstatic->id = $obj->fk_user; $userstatic->login = $obj->login; $userstatic->admin = $obj->admin; @@ -350,39 +403,38 @@ if ($result) $userstatic->status = $obj->status; print $userstatic->getLoginUrl(1); - if (!empty($conf->multicompany->enabled) && $userstatic->admin && !$userstatic->entity) - { + if (!empty($conf->multicompany->enabled) && $userstatic->admin && !$userstatic->entity) { print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); - } elseif ($userstatic->admin) - { + } elseif ($userstatic->admin) { print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); } - } else print ' '; + } else { + print ' '; + } print ''; $text = $langs->trans($obj->description); $reg = array(); - if (preg_match('/\((.*)\)(.*)/i', $obj->description, $reg)) - { + if (preg_match('/\((.*)\)(.*)/i', $obj->description, $reg)) { $val = explode(',', $reg[1]); $text = $langs->trans($val[0], isset($val[1]) ? $val[1] : '', isset($val[2]) ? $val[2] : '', isset($val[3]) ? $val[3] : '', isset($val[4]) ? $val[4] : ''); - if (!empty($reg[2])) $text .= $reg[2]; + if (!empty($reg[2])) { + $text .= $reg[2]; + } } print dol_escape_htmltag($text); print ''; print $obj->user_agent; print ''; print $obj->prefix_session; @@ -400,10 +452,12 @@ if ($result) $i++; } - if ($num == 0) - { - if ($usefilter) print '
    '.$langs->trans("NoEventFoundWithCriteria").'
    '.$langs->trans("NoEventOrNoAuditSetup").'
    '.$langs->trans("NoEventFoundWithCriteria").'
    '.$langs->trans("NoEventOrNoAuditSetup").'
    "; print "
    "; diff --git a/htdocs/admin/tools/listsessions.php b/htdocs/admin/tools/listsessions.php index d8e0a0383a2..61d2b1cea58 100644 --- a/htdocs/admin/tools/listsessions.php +++ b/htdocs/admin/tools/listsessions.php @@ -28,15 +28,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page $langs->loadLangs(array("companies", "install", "users", "other")); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -45,12 +45,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 = "dateevent"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "dateevent"; +} /* @@ -58,25 +64,20 @@ if (!$sortfield) $sortfield = "dateevent"; */ // Purge sessions -if ($action == 'confirm_purge' && $confirm == 'yes' && $user->admin) -{ +if ($action == 'confirm_purge' && $confirm == 'yes' && $user->admin) { $res = purgeSessions(session_id()); } // Lock new sessions -if ($action == 'confirm_lock' && $confirm == 'yes' && $user->admin) -{ - if (dolibarr_set_const($db, 'MAIN_ONLY_LOGIN_ALLOWED', $user->login, 'text', 1, 'Logon is restricted to a particular user', 0) < 0) - { +if ($action == 'confirm_lock' && $confirm == 'yes' && $user->admin) { + if (dolibarr_set_const($db, 'MAIN_ONLY_LOGIN_ALLOWED', $user->login, 'text', 1, 'Logon is restricted to a particular user', 0) < 0) { dol_print_error($db); } } // Unlock new sessions -if ($action == 'confirm_unlock' && $user->admin) -{ - if (dolibarr_del_const($db, 'MAIN_ONLY_LOGIN_ALLOWED', -1) < 0) - { +if ($action == 'confirm_unlock' && $user->admin) { + if (dolibarr_del_const($db, 'MAIN_ONLY_LOGIN_ALLOWED', -1) < 0) { dol_print_error($db); } } @@ -107,22 +108,23 @@ $suhosin = empty($phparray['suhosin']["suhosin.session.encrypt"]["local"]) ? '' print ''.$langs->trans("SessionSaveHandler").': '.$savehandler.'
    '; print ''.$langs->trans("SessionSavePath").': '.$savepath.'
    '; -if ($openbasedir) print ''.$langs->trans("OpenBaseDir").': '.$openbasedir.'
    '; -if ($suhosin) print ''.$langs->trans("SuhosinSessionEncrypt").': '.$suhosin.'
    '; +if ($openbasedir) { + print ''.$langs->trans("OpenBaseDir").': '.$openbasedir.'
    '; +} +if ($suhosin) { + print ''.$langs->trans("SuhosinSessionEncrypt").': '.$suhosin.'
    '; +} print '
    '; -if ($action == 'purge') -{ +if ($action == 'purge') { $formquestion = array(); print $form->formconfirm($_SERVER["PHP_SELF"].'?noparam=noparam', $langs->trans('PurgeSessions'), $langs->trans('ConfirmPurgeSessions'), 'confirm_purge', $formquestion, 'no', 2); -} elseif ($action == 'lock') -{ +} elseif ($action == 'lock') { $formquestion = array(); print $form->formconfirm($_SERVER["PHP_SELF"].'?noparam=noparam', $langs->trans('LockNewSessions'), $langs->trans('ConfirmLockNewSessions', $user->login), 'confirm_lock', $formquestion, 'no', 1); } -if ($savehandler == 'files') -{ +if ($savehandler == 'files') { print ''; print ''; print_liste_field_titre("Login", $_SERVER["PHP_SELF"], "login", "", "", 'align="left"', $sortfield, $sortorder); @@ -134,8 +136,7 @@ if ($savehandler == 'files') print_liste_field_titre(''); print "\n"; - foreach ($listofsessions as $key => $sessionentry) - { + foreach ($listofsessions as $key => $sessionentry) { print ''; // Login @@ -143,8 +144,11 @@ if ($savehandler == 'files') // ID print ''; // Date creation @@ -165,8 +169,7 @@ if ($savehandler == 'files') $i++; } - if (count($listofsessions) == 0) - { + if (count($listofsessions) == 0) { print ''; } print "
    '; - if ("$key" == session_id()) print $form->textwithpicto($key, $langs->trans("YourSession")); - else print $key; + if ("$key" == session_id()) { + print $form->textwithpicto($key, $langs->trans("YourSession")); + } else { + print $key; + } print '
    '.$langs->trans("NoSessionFound", $savepath, $openbasedir).'
    "; @@ -181,17 +184,14 @@ if ($savehandler == 'files') print '
    '; -if (empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) -{ +if (empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) { print ''.$langs->trans("LockNewSessions").''; } else { print ''.$langs->trans("UnlockNewSessions").''; } -if ($savehandler == 'files') -{ - if (count($listofsessions)) - { +if ($savehandler == 'files') { + if (count($listofsessions)) { print ''.$langs->trans("PurgeSessions").''; } } diff --git a/htdocs/admin/tools/purge.php b/htdocs/admin/tools/purge.php index f3266a8c5d0..e20b9c2b13a 100644 --- a/htdocs/admin/tools/purge.php +++ b/htdocs/admin/tools/purge.php @@ -26,8 +26,9 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $langs->load("admin"); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); @@ -36,8 +37,7 @@ $choice = GETPOST('choice', 'aZ09'); // Define filelog to discard it from purge $filelog = ''; -if (!empty($conf->syslog->enabled)) -{ +if (!empty($conf->syslog->enabled)) { $filelog = $conf->global->SYSLOG_FILE; $filelog = preg_replace('/DOL_DATA_ROOT/i', DOL_DATA_ROOT, $filelog); } @@ -46,12 +46,10 @@ if (!empty($conf->syslog->enabled)) /* * Actions */ -if ($action == 'purge' && !preg_match('/^confirm/i', $choice) && ($choice != 'allfiles' || $confirm == 'yes')) -{ +if ($action == 'purge' && !preg_match('/^confirm/i', $choice) && ($choice != 'allfiles' || $confirm == 'yes')) { // Increase limit of time. Works only if we are not in safe mode $ExecTimeLimit = 600; - if (!empty($ExecTimeLimit)) - { + if (!empty($ExecTimeLimit)) { $err = error_reporting(); error_reporting(0); // Disable all errors //error_reporting(E_ALL); diff --git a/htdocs/admin/tools/update.php b/htdocs/admin/tools/update.php index f39766818f3..5a6ff94ce57 100644 --- a/htdocs/admin/tools/update.php +++ b/htdocs/admin/tools/update.php @@ -32,7 +32,9 @@ $langs->loadLangs(array("admin", "other")); $action = GETPOST('action', 'aZ09'); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} if (GETPOST('msg', 'alpha')) { setEventMessages(GETPOST('msg', 'alpha'), null, 'errors'); @@ -52,8 +54,7 @@ $version = '0.0'; * Actions */ -if ($action == 'getlastversion') -{ +if ($action == 'getlastversion') { $result = getURLContent('https://sourceforge.net/projects/dolibarr/rss'); //var_dump($result['content']); $sfurl = simplexml_load_string($result['content']); @@ -73,25 +74,22 @@ print '
    '; print $langs->trans("CurrentVersion").' : '.DOL_VERSION.'
    '; -if (function_exists('curl_init')) -{ +if (function_exists('curl_init')) { $conf->global->MAIN_USE_RESPONSE_TIMEOUT = 10; - if ($action == 'getlastversion') - { - if ($sfurl) - { + if ($action == 'getlastversion') { + if ($sfurl) { $i = 0; - while (!empty($sfurl->channel[0]->item[$i]->title) && $i < 10000) - { + while (!empty($sfurl->channel[0]->item[$i]->title) && $i < 10000) { $title = $sfurl->channel[0]->item[$i]->title; - if (preg_match('/([0-9]+\.([0-9\.]+))/', $title, $reg)) - { + if (preg_match('/([0-9]+\.([0-9\.]+))/', $title, $reg)) { $newversion = $reg[1]; $newversionarray = explode('.', $newversion); $versionarray = explode('.', $version); //var_dump($newversionarray);var_dump($versionarray); - if (versioncompare($newversionarray, $versionarray) > 0) $version = $newversion; + if (versioncompare($newversionarray, $versionarray) > 0) { + $version = $newversion; + } } $i++; } diff --git a/htdocs/admin/translation.php b/htdocs/admin/translation.php index dfaa8e576de..d6b8b2f9f66 100644 --- a/htdocs/admin/translation.php +++ b/htdocs/admin/translation.php @@ -30,7 +30,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; // Load translation files required by the page $langs->loadLangs(array("companies", "products", "admin", "sms", "other", "errors")); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $id = GETPOST('rowid', 'int'); $action = GETPOST('action', 'aZ09'); @@ -46,12 +48,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 (!$sortfield) $sortfield = 'lang,transkey'; -if (!$sortorder) $sortorder = 'ASC'; +if (!$sortfield) { + $sortfield = 'lang,transkey'; +} +if (!$sortorder) { + $sortorder = 'ASC'; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('admintranslation', 'globaladmin')); @@ -61,45 +69,48 @@ $hookmanager->initHooks(array('admintranslation', 'globaladmin')); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && !empty($massaction) && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && !empty($massaction) && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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'); +} include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 $transkey = ''; $transvalue = ''; $toselect = ''; $search_array_options = array(); } -if ($action == 'setMAIN_ENABLE_OVERWRITE_TRANSLATION') -{ - if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 1, 'chaine', 0, '', $conf->entity); - else dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 0, 'chaine', 0, '', $conf->entity); +if ($action == 'setMAIN_ENABLE_OVERWRITE_TRANSLATION') { + if (GETPOST('value')) { + dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 1, 'chaine', 0, '', $conf->entity); + } else { + dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 0, 'chaine', 0, '', $conf->entity); + } } -if ($action == 'update') -{ - if ($transvalue == '') - { +if ($action == 'update') { + if ($transvalue == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NewTranslationStringToShow")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."overwrite_trans set transvalue = '".$db->escape($transvalue)."' WHERE rowid = ".GETPOST('rowid', 'int'); $result = $db->query($sql); - if ($result > 0) - { + if ($result > 0) { $db->commit(); setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); $action = ""; @@ -107,8 +118,7 @@ if ($action == 'update') $transvalue = ""; } else { $db->rollback(); - if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { setEventMessages($langs->trans("WarningAnEntryAlreadyExistForTransKey"), null, 'warnings'); } else { setEventMessages($db->lasterror(), null, 'errors'); @@ -118,33 +128,27 @@ if ($action == 'update') } } -if ($action == 'add') -{ +if ($action == 'add') { $error = 0; - if (empty($langcode)) - { + if (empty($langcode)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Language")), null, 'errors'); $error++; } - if ($transkey == '') - { + if ($transkey == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Key")), null, 'errors'); $error++; } - if ($transvalue == '') - { + if ($transvalue == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NewTranslationStringToShow")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."overwrite_trans(lang, transkey, transvalue, entity) VALUES ('".$db->escape($langcode)."','".$db->escape($transkey)."','".$db->escape($transvalue)."', ".$db->escape($conf->entity).")"; $result = $db->query($sql); - if ($result > 0) - { + if ($result > 0) { $db->commit(); setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); $action = ""; @@ -152,8 +156,7 @@ if ($action == 'add') $transvalue = ""; } else { $db->rollback(); - if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { setEventMessages($langs->trans("WarningAnEntryAlreadyExistForTransKey"), null, 'warnings'); } else { setEventMessages($db->lasterror(), null, 'errors'); @@ -164,12 +167,10 @@ if ($action == 'add') } // Delete line from delete picto -if ($action == 'delete') -{ +if ($action == 'delete') { $sql = "DELETE FROM ".MAIN_DB_PREFIX."overwrite_trans WHERE rowid = ".$db->escape($id); $result = $db->query($sql); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); } else { dol_print_error($db); @@ -194,8 +195,7 @@ $param = '&mode='.urlencode($mode); $enabledisablehtml = ''; $enabledisablehtml .= $langs->trans("EnableOverwriteTranslation").' '; -if (empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) -{ +if (empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) { // Button off, click to enable $enabledisablehtml .= ''; $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); @@ -215,16 +215,30 @@ print $form->textwithpicto(''.$langs->trans("Current print '
    '; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -if (isset($optioncss) && $optioncss != '') $param .= '&optioncss='.urlencode($optioncss); -if ($langcode) $param .= '&langcode='.urlencode($langcode); -if ($transkey) $param .= '&transkey='.urlencode($transkey); -if ($transvalue) $param .= '&transvalue='.urlencode($transvalue); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +if (isset($optioncss) && $optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} +if ($langcode) { + $param .= '&langcode='.urlencode($langcode); +} +if ($transkey) { + $param .= '&transkey='.urlencode($transkey); +} +if ($transvalue) { + $param .= '&transvalue='.urlencode($transvalue); +} print 'entity) && !empty($debug)) ? '?debug=1' : '').'" method="POST">'; -if (isset($optioncss) && $optioncss != '') print ''; +if (isset($optioncss) && $optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -234,14 +248,17 @@ $head = translation_prepare_head(); print dol_get_fiche_head($head, $mode, '', -1, ''); -if ($mode == 'overwrite') -{ +if ($mode == 'overwrite') { print ''; $disabled = ''; - if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) $disabled = ' disabled="disabled"'; + if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) { + $disabled = ' disabled="disabled"'; + } $disablededit = ''; - if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) $disablededit = ' disabled'; + if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) { + $disablededit = ' disabled'; + } print '
    '; print img_info().' '.$langs->trans("SomeTranslationAreUncomplete"); @@ -281,14 +298,14 @@ if ($mode == 'overwrite') print ''; // Limit to superadmin /*if (! empty($conf->multicompany->enabled) && !$user->entity) - { - print ''; - print ''; - print ''; - print ''; - } - else - {*/ + { + print ''; + print ''; + print ''; + print ''; + } + else + {*/ print ''; print ''; //} @@ -306,13 +323,11 @@ if ($mode == 'overwrite') dol_syslog("translation::select from table", LOG_DEBUG); $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); print "\n"; @@ -325,12 +340,11 @@ if ($mode == 'overwrite') // Value print ''; /*print ''; - print ''; - print ''; - print ''; - */ - if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) - { + print ''; + print ''; + print ''; + */ + if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) { print ''; } else { print dol_escape_htmltag($obj->transvalue); @@ -360,8 +374,7 @@ if ($mode == 'overwrite') print '
    '; } -if ($mode == 'searchkey') -{ +if ($mode == 'searchkey') { $langcode = GETPOSTISSET('langcode') ? GETPOST('langcode') : $langs->defaultlang; $newlang = new Translate('', $conf); @@ -378,18 +391,23 @@ if ($mode == 'searchkey') $nbtotaloffiles = 0; $nbempty = 0; /*var_dump($langcode); - var_dump($transkey); - var_dump($transvalue);*/ - if (empty($langcode) || $langcode == '-1') $nbempty++; - if (empty($transkey)) $nbempty++; - if (empty($transvalue)) $nbempty++; + var_dump($transkey); + var_dump($transvalue);*/ + if (empty($langcode) || $langcode == '-1') { + $nbempty++; + } + if (empty($transkey)) { + $nbempty++; + } + if (empty($transvalue)) { + $nbempty++; + } if ($action == 'search' && ($nbempty > 999)) { // 999 to disable this setEventMessages($langs->trans("WarningAtLeastKeyOrTranslationRequired"), null, 'warnings'); } else { // Search into dir of modules (the $modulesdir is already a list that loop on $conf->file->dol_document_root) $i = 0; - foreach ($modulesdir as $keydir => $tmpsearchdir) - { + foreach ($modulesdir as $keydir => $tmpsearchdir) { $searchdir = $tmpsearchdir; // $searchdir can be '.../htdocs/core/modules/' or '.../htdocs/custom/mymodule/core/modules/' // Directory of translation files @@ -397,29 +415,36 @@ if ($mode == 'searchkey') $dir_lang_osencoded = dol_osencode($dir_lang); $filearray = dol_dir_list($dir_lang_osencoded, 'files', 0, '', '', $sortfield, (strtolower($sortorder) == 'asc' ?SORT_ASC:SORT_DESC), 1); - foreach ($filearray as $file) - { + foreach ($filearray as $file) { $tmpfile = preg_replace('/.lang/i', '', basename($file['name'])); $moduledirname = (basename(dirname(dirname($dir_lang)))); $langkey = $tmpfile; - if ($i > 0) $langkey .= '@'.$moduledirname; + if ($i > 0) { + $langkey .= '@'.$moduledirname; + } //var_dump($i.' - '.$keydir.' - '.$dir_lang_osencoded.' -> '.$moduledirname . ' / ' . $tmpfile.' -> '.$langkey); $result = $newlang->load($langkey, 0, 0, '', 0); // Load translation files + database overwrite $result = $newlangfileonly->load($langkey, 0, 0, '', 1); // Load translation files only - if ($result < 0) print 'Failed to load language file '.$tmpfile.'
    '."\n"; - else $nbtotaloffiles++; + if ($result < 0) { + print 'Failed to load language file '.$tmpfile.'
    '."\n"; + } else { + $nbtotaloffiles++; + } //print 'After loading lang '.$langkey.', newlang has '.count($newlang->tab_translate).' records
    '."\n"; } $i++; } // Now search into translation array - foreach ($newlang->tab_translate as $key => $val) - { - if ($transkey && !preg_match('/'.preg_quote($transkey, '/').'/i', $key)) continue; - if ($transvalue && !preg_match('/'.preg_quote($transvalue, '/').'/i', $val)) continue; + foreach ($newlang->tab_translate as $key => $val) { + if ($transkey && !preg_match('/'.preg_quote($transkey, '/').'/i', $key)) { + continue; + } + if ($transvalue && !preg_match('/'.preg_quote($transvalue, '/').'/i', $val)) { + continue; + } $recordtoshow[$key] = $val; } } @@ -428,11 +453,15 @@ if ($mode == 'searchkey') $nbtotalofrecordswithoutfilters = count($newlang->tab_translate); $nbtotalofrecords = count($recordtoshow); $num = $limit + 1; - if (($offset + $num) > $nbtotalofrecords) $num = $limit; + if (($offset + $num) > $nbtotalofrecords) { + $num = $limit; + } //print 'param='.$param.' $_SERVER["PHP_SELF"]='.$_SERVER["PHP_SELF"].' num='.$num.' page='.$page.' nbtotalofrecords='.$nbtotalofrecords." sortfield=".$sortfield." sortorder=".$sortorder; $title = $langs->trans("TranslationKeySearch"); - if ($nbtotalofrecords > 0) $title .= ' ('.$nbtotalofrecords.' / '.$nbtotalofrecordswithoutfilters.' - '.$nbtotaloffiles.' '.$langs->trans("Files").')'; + if ($nbtotalofrecords > 0) { + $title .= ' ('.$nbtotalofrecords.' / '.$nbtotalofrecordswithoutfilters.' - '.$nbtotaloffiles.' '.$langs->trans("Files").')'; + } print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, '', '', $limit, 0, 0, 1); print ''; @@ -461,12 +490,12 @@ if ($mode == 'searchkey') print ''; // Limit to superadmin /*if (! empty($conf->multicompany->enabled) && !$user->entity) - { - print ''; - print ''; - } - else - {*/ + { + print ''; + print ''; + } + else + {*/ print ''; //} print ''; @@ -477,18 +506,29 @@ if ($mode == 'searchkey') print ''; print ''; - if ($sortfield == 'transkey' && strtolower($sortorder) == 'asc') ksort($recordtoshow); - if ($sortfield == 'transkey' && strtolower($sortorder) == 'desc') krsort($recordtoshow); - if ($sortfield == 'transvalue' && strtolower($sortorder) == 'asc') asort($recordtoshow); - if ($sortfield == 'transvalue' && strtolower($sortorder) == 'desc') arsort($recordtoshow); + if ($sortfield == 'transkey' && strtolower($sortorder) == 'asc') { + ksort($recordtoshow); + } + if ($sortfield == 'transkey' && strtolower($sortorder) == 'desc') { + krsort($recordtoshow); + } + if ($sortfield == 'transvalue' && strtolower($sortorder) == 'asc') { + asort($recordtoshow); + } + if ($sortfield == 'transvalue' && strtolower($sortorder) == 'desc') { + arsort($recordtoshow); + } // Show result $i = 0; - foreach ($recordtoshow as $key => $val) - { + foreach ($recordtoshow as $key => $val) { $i++; - if ($i <= $offset) continue; - if ($i > ($offset + $limit)) break; + if ($i <= $offset) { + continue; + } + if ($i > ($offset + $limit)) { + break; + } print ''.$langcode.''.$key.''; print dol_escape_htmltag($val); print ''; @@ -501,8 +541,7 @@ if ($mode == 'searchkey') $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; dol_syslog("translation::select from table", LOG_DEBUG); $result = $db->query($sql); - if ($result) - { + if ($result) { $obj = $db->fetch_object($result); } print '
    '.img_edit().''; @@ -516,8 +555,7 @@ if ($mode == 'searchkey') print ''.img_edit_add($langs->trans("Overwrite")).''; } - if (!empty($conf->global->MAIN_FEATURES_LEVEL)) - { + if (!empty($conf->global->MAIN_FEATURES_LEVEL)) { $transifexlangfile = '$'; // $ means 'All' //$transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?key='.$key; $transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?q=key%3A'.$key; @@ -529,9 +567,9 @@ if ($mode == 'searchkey') print $form->textwithpicto('', $htmltext, 1, 'warning'); } /*if (! empty($conf->multicompany->enabled) && !$user->entity) - { - print ''.$val.''; - }*/ + { + print ''.$val.''; + }*/ print ''."\n"; } @@ -543,8 +581,7 @@ print dol_get_fiche_end(); print "\n"; -if (!empty($langcode)) -{ +if (!empty($langcode)) { dol_set_focus('#transvalue'); } diff --git a/htdocs/admin/triggers.php b/htdocs/admin/triggers.php index ce7f525e8b3..5ea74205c9c 100644 --- a/htdocs/admin/triggers.php +++ b/htdocs/admin/triggers.php @@ -26,7 +26,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; // Load translation files required by the page $langs->load("admin"); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $sortfield = 'file'; $sortorder = 'ASC'; @@ -66,8 +68,7 @@ print getTitleFieldOfList($langs->trans("Active"), 0, $_SERVER["PHP_SELF"], 'act print getTitleFieldOfList('', 0, $_SERVER["PHP_SELF"], 'none', "", $param, ($align ? 'align="'.$align.'"' : ''), $sortfield, $sortorder, '', 1)."\n"; print ''; -foreach ($triggers as $trigger) -{ +foreach ($triggers as $trigger) { print ''; print ''.$trigger['picto'].''; print ''.$trigger['file'].''; diff --git a/htdocs/admin/user.php b/htdocs/admin/user.php index ea6cdf2b6f8..0dccf65e5e7 100644 --- a/htdocs/admin/user.php +++ b/htdocs/admin/user.php @@ -35,7 +35,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'members', 'users')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $extrafields = new ExtraFields($db); @@ -54,25 +56,20 @@ $type = 'user'; include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; -if ($action == 'set_default') -{ +if ($action == 'set_default') { $ret = addDocumentModel($value, $type, $label, $scandir); $res = true; -} elseif ($action == 'del_default') -{ +} elseif ($action == 'del_default') { $ret = delDocumentModel($value, $type); - if ($ret > 0) - { - if ($conf->global->USER_ADDON_PDF_ODT == "$value") dolibarr_del_const($db, 'USER_ADDON_PDF_ODT', $conf->entity); + if ($ret > 0) { + if ($conf->global->USER_ADDON_PDF_ODT == "$value") { + dolibarr_del_const($db, 'USER_ADDON_PDF_ODT', $conf->entity); + } } $res = true; -} - -// Set default model -elseif ($action == 'setdoc') -{ - if (dolibarr_set_const($db, "USER_ADDON_PDF_ODT", $value, 'chaine', 0, '', $conf->entity)) - { +} elseif ($action == 'setdoc') { + // Set default model + if (dolibarr_set_const($db, "USER_ADDON_PDF_ODT", $value, 'chaine', 0, '', $conf->entity)) { // La constante qui a ete lue en avant du nouveau set // on passe donc par une variable pour avoir un affichage coherent $conf->global->USER_ADDON_PDF_ODT = $value; @@ -80,39 +77,31 @@ elseif ($action == 'setdoc') // On active le modele $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, $type, $label, $scandir); } $res = true; -} elseif (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) -{ +} elseif (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; - if (dolibarr_set_const($db, $code, 1, 'chaine', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, $code, 1, 'chaine', 0, '', $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { dol_print_error($db); } -} elseif (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) -{ +} elseif (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; - if (dolibarr_del_const($db, $code, $conf->entity) > 0) - { + if (dolibarr_del_const($db, $code, $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { dol_print_error($db); } -} -//Set hide closed customer into combox or select -elseif ($action == 'sethideinactiveuser') -{ +} elseif ($action == 'sethideinactiveuser') { + //Set hide closed customer into combox or select $status = GETPOST('status', 'alpha'); - if (dolibarr_set_const($db, "USER_HIDE_INACTIVE_IN_COMBOBOX", $status, 'chaine', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, "USER_HIDE_INACTIVE_IN_COMBOBOX", $status, 'chaine', 0, '', $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -152,12 +141,10 @@ print ''.$langs->trans("UserMailRequired").''; print ' '; print ''; -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print ajax_constantonoff('USER_MAIL_REQUIRED'); } else { - if (empty($conf->global->USER_MAIL_REQUIRED)) - { + if (empty($conf->global->USER_MAIL_REQUIRED)) { print ''.img_picto($langs->trans("Disabled"), 'off').''; } else { print ''.img_picto($langs->trans("Enabled"), 'on').''; @@ -172,12 +159,10 @@ print ''.$langs->trans("UserHideInactive").''; print ' '; print ''; -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print ajax_constantonoff('USER_HIDE_INACTIVE_IN_COMBOBOX'); } else { - if (empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX)) - { + if (empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX)) { print ''.img_picto($langs->trans("Disabled"), 'off').''; } else { print ''.img_picto($langs->trans("Enabled"), 'on').''; @@ -198,12 +183,10 @@ $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; $sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -226,29 +209,21 @@ print "\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ - foreach (array('', '/doc') as $valdir) - { +foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { $dir = dol_buildpath($reldir."core/modules/user".$valdir); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -256,21 +231,26 @@ 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 == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print ''; print (empty($module->name) ? $name : $module->name); print "\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print ''; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print ''."\n"; print ''; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -284,8 +264,7 @@ foreach ($dirmodels as $reldir) // Defaut print ''; - if ($conf->global->USER_ADDON_PDF == $name) - { + if ($conf->global->USER_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').''; @@ -295,8 +274,7 @@ foreach ($dirmodels as $reldir) // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '
    '.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '
    '.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } $htmltooltip .= '

    '.$langs->trans("FeaturesSupported").':'; @@ -310,8 +288,7 @@ foreach ($dirmodels as $reldir) // Preview print ''; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print ''.img_object($langs->trans("Preview"), 'pdf').''; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); diff --git a/htdocs/admin/usergroup.php b/htdocs/admin/usergroup.php index 0725cc83f18..b73d3ce4f22 100644 --- a/htdocs/admin/usergroup.php +++ b/htdocs/admin/usergroup.php @@ -34,7 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "members", "users")); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $extrafields = new ExtraFields($db); @@ -48,25 +50,20 @@ $type = 'group'; include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; -if ($action == 'set_default') -{ +if ($action == 'set_default') { $ret = addDocumentModel($value, $type, $label, $scandir); $res = true; -} elseif ($action == 'del_default') -{ +} elseif ($action == 'del_default') { $ret = delDocumentModel($value, $type); - if ($ret > 0) - { - if ($conf->global->USERGROUP_ADDON_PDF_ODT == "$value") dolibarr_del_const($db, 'USERGROUP_ADDON_PDF_ODT', $conf->entity); + if ($ret > 0) { + if ($conf->global->USERGROUP_ADDON_PDF_ODT == "$value") { + dolibarr_del_const($db, 'USERGROUP_ADDON_PDF_ODT', $conf->entity); + } } $res = true; -} - -// Set default model -elseif ($action == 'setdoc') -{ - if (dolibarr_set_const($db, "USERGROUP_ADDON_PDF_ODT", $value, 'chaine', 0, '', $conf->entity)) - { +} elseif ($action == 'setdoc') { + // Set default model + if (dolibarr_set_const($db, "USERGROUP_ADDON_PDF_ODT", $value, 'chaine', 0, '', $conf->entity)) { // La constante qui a ete lue en avant du nouveau set // on passe donc par une variable pour avoir un affichage coherent $conf->global->USERGROUP_ADDON_PDF_ODT = $value; @@ -74,26 +71,21 @@ elseif ($action == 'setdoc') // On active le modele $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, $type, $label, $scandir); } $res = true; -} elseif (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) -{ +} elseif (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; - if (dolibarr_set_const($db, $code, 1, 'chaine', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, $code, 1, 'chaine', 0, '', $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { dol_print_error($db); } -} elseif (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) -{ +} elseif (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; - if (dolibarr_del_const($db, $code, $conf->entity) > 0) - { + if (dolibarr_del_const($db, $code, $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -127,12 +119,10 @@ $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; $sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -155,29 +145,21 @@ print "\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ - foreach (array('', '/doc') as $valdir) - { +foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { $dir = dol_buildpath($reldir."core/modules/usergroup".$valdir); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -185,21 +167,26 @@ 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 == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print ''; print (empty($module->name) ? $name : $module->name); print "\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print ''; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print ''."\n"; print ''; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -213,8 +200,7 @@ foreach ($dirmodels as $reldir) // Defaut print ''; - if ($conf->global->USERGROUP_ADDON_PDF == $name) - { + if ($conf->global->USERGROUP_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').''; @@ -224,8 +210,7 @@ foreach ($dirmodels as $reldir) // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '
    '.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '
    '.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } $htmltooltip .= '

    '.$langs->trans("FeaturesSupported").':'; @@ -239,8 +224,7 @@ foreach ($dirmodels as $reldir) // Preview print ''; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print ''.img_object($langs->trans("Preview"), 'pdf').''; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); diff --git a/htdocs/admin/website.php b/htdocs/admin/website.php index 09225a6e4a8..311b67c21f2 100644 --- a/htdocs/admin/website.php +++ b/htdocs/admin/website.php @@ -42,7 +42,9 @@ $rowid = GETPOST('rowid', 'alpha'); $id = 1; -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $acts[0] = "activate"; $acts[1] = "disable"; @@ -54,13 +56,19 @@ $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 = 'position, ref'; -if (empty($sortorder)) $sortorder = 'ASC'; +if (empty($sortfield)) { + $sortfield = 'position, ref'; +} +if (empty($sortorder)) { + $sortorder = 'ASC'; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('website')); @@ -122,8 +130,7 @@ $sourceList = array(); */ // Actions add or modify a website -if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) -{ +if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) { $listfield = explode(',', $tabfield[$id]); $listfieldinsert = explode(',', $tabfieldinsert[$id]); $listfieldmodify = explode(',', $tabfieldinsert[$id]); @@ -131,10 +138,8 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) // Check that all fields are filled $ok = 1; - foreach ($listfield as $f => $value) - { - if ($value == 'ref' && (!GETPOSTISSET($value) || GETPOST($value) == '')) - { + foreach ($listfield as $f => $value) { + if ($value == 'ref' && (!GETPOSTISSET($value) || GETPOST($value) == '')) { $ok = 0; $fieldnamekey = $listfield[$f]; setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); @@ -153,16 +158,13 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) } // Si verif ok et action add, on ajoute la ligne - if ($ok && GETPOST('actionadd', 'alpha')) - { - if ($tabrowid[$id]) - { + if ($ok && GETPOST('actionadd', 'alpha')) { + if ($tabrowid[$id]) { // Recupere id libre pour insertion $newid = 0; $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; $result = $db->query($sql); - if ($result) - { + if ($result) { $obj = $db->fetch_object($result); $newid = ($obj->newid + 1); } else { @@ -171,43 +173,48 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) } /* $website=new Website($db); - $website->ref= - $website->description= - $website->virtualhost= - $website->create($user); */ + $website->ref= + $website->description= + $website->virtualhost= + $website->create($user); */ // Add new entry $sql = "INSERT INTO ".$tabname[$id]." ("; // List of fields - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) { $sql .= $tabrowid[$id].","; + } $sql .= $tabfieldinsert[$id]; $sql .= ",status)"; $sql .= " VALUES("; // List of values - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) { $sql .= $newid.","; + } $i = 0; - foreach ($listfieldinsert as $f => $value) - { + foreach ($listfieldinsert as $f => $value) { if ($value == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } if ($value == 'ref') { $_POST[$listfieldvalue[$i]] = strtolower($_POST[$listfieldvalue[$i]]); } - if ($i) $sql .= ","; - if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; - else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + if ($i) { + $sql .= ","; + } + if ($_POST[$listfieldvalue[$i]] == '') { + $sql .= "null"; + } else { + $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + } $i++; } $sql .= ",1)"; dol_syslog("actionadd", LOG_DEBUG); $result = $db->query($sql); - if ($result) // Add is ok - { + if ($result) { // Add is ok setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); unset($_POST); // Clean $_POST array, we keep only } else { @@ -220,9 +227,12 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) } // Si verif ok et action modify, on modifie la ligne - if ($ok && GETPOST('actionmodify', 'alpha')) - { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($ok && GETPOST('actionmodify', 'alpha')) { + if ($tabrowid[$id]) { + $rowidcol = $tabrowid[$id]; + } else { + $rowidcol = "rowid"; + } $db->begin(); @@ -233,21 +243,24 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) // Modify entry $sql = "UPDATE ".$tabname[$id]." SET "; // Modifie valeur des champs - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) - { + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) { $sql .= $tabrowid[$id]."="; $sql .= "'".$db->escape($rowid)."', "; } $i = 0; - foreach ($listfieldmodify as $field) - { + foreach ($listfieldmodify as $field) { if ($field == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } - if ($i) $sql .= ","; + if ($i) { + $sql .= ","; + } $sql .= $field."="; - if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; - else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + if ($_POST[$listfieldvalue[$i]] == '') { + $sql .= "null"; + } else { + $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + } $i++; } $sql .= " WHERE ".$rowidcol." = ".((int) $rowid); @@ -255,16 +268,13 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) dol_syslog("actionmodify", LOG_DEBUG); //print $sql; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $newname = dol_sanitizeFileName(GETPOST('ref', 'aZ09')); - if ($newname != $website->ref) - { + if ($newname != $website->ref) { $srcfile = DOL_DATA_ROOT.'/website/'.$website->ref; $destfile = DOL_DATA_ROOT.'/website/'.$newname; - if (dol_is_dir($destfile)) - { + if (dol_is_dir($destfile)) { $error++; setEventMessages($langs->trans('ErrorDirAlreadyExists', $destfile), null, 'errors'); } else { @@ -273,8 +283,7 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) // We must now rename $website->ref into $newname inside files $arrayreplacement = array($website->ref.'/htmlheader.html' => $newname.'/htmlheader.html'); $listofilestochange = dol_dir_list($destfile, 'files', 0, '\.php$'); - foreach ($listofilestochange as $key => $value) - { + foreach ($listofilestochange as $key => $value) { dolReplaceInFile($value['fullname'], $arrayreplacement); } } @@ -284,8 +293,7 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) setEventMessages($db->lasterror(), null, 'errors'); } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -294,20 +302,21 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } -if (GETPOST('actioncancel', 'alpha')) -{ +if (GETPOST('actioncancel', 'alpha')) { //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } -if ($action == 'confirm_delete' && $confirm == 'yes') // delete -{ - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } +if ($action == 'confirm_delete' && $confirm == 'yes') { // delete + if ($tabrowid[$id]) { + $rowidcol = $tabrowid[$id]; + } else { + $rowidcol = "rowid"; + } $website = new Website($db); $website->fetch($rowid); - if ($website->id > 0) - { + if ($website->id > 0) { $sql = "DELETE from ".MAIN_DB_PREFIX."website_account WHERE fk_website = ".((int) $rowid); $result = $db->query($sql); @@ -319,18 +328,15 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete $sql = "DELETE from ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $rowid); $result = $db->query($sql); - if (!$result) - { - if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') - { + if (!$result) { + if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') { setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); } else { dol_print_error($db); } } - if ($website->ref) - { + if ($website->ref) { dol_delete_dir_recursive($conf->website->dir_output.'/'.$website->ref); } } else { @@ -339,33 +345,37 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete } // activate -if ($action == $acts[0]) -{ - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } +if ($action == $acts[0]) { + if ($tabrowid[$id]) { + $rowidcol = $tabrowid[$id]; + } else { + $rowidcol = "rowid"; + } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET status = 1 WHERE rowid = ".((int) $rowid); } $result = $db->query($sql); - if (!$result) - { + if (!$result) { dol_print_error($db); } } // disable -if ($action == $acts[1]) -{ - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } +if ($action == $acts[1]) { + if ($tabrowid[$id]) { + $rowidcol = $tabrowid[$id]; + } else { + $rowidcol = "rowid"; + } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET status = 0 WHERE rowid = ".((int) $rowid); } $result = $db->query($sql); - if (!$result) - { + if (!$result) { dol_print_error($db); } } @@ -407,8 +417,7 @@ print "
    \n"; // Confirmation de la suppression de la ligne -if ($action == 'delete') -{ +if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid, $langs->trans('DeleteWebsite'), $langs->trans('ConfirmDeleteWebsite'), 'confirm_delete', '', 0, 1, 220); } //var_dump($elementList); @@ -416,8 +425,7 @@ if ($action == 'delete') /* * Show website list */ -if ($id) -{ +if ($id) { // Complete requete recherche valeurs avec critere de tri $sql = $tabsql[$id]; $sql .= $db->order($sortfield, $sortorder); @@ -431,31 +439,37 @@ if ($id) print ''; // Form to add a new line - if ($tabname[$id]) - { + if ($tabname[$id]) { $fieldlist = explode(',', $tabfield[$id]); // Line for title print ''; - foreach ($fieldlist as $field => $value) - { - if ($fieldlist[$field] == 'date_creation') continue; + foreach ($fieldlist as $field => $value) { + if ($fieldlist[$field] == 'date_creation') { + continue; + } // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut $valuetoshow = $langs->trans($valuetoshow); // try to translate $align = ''; - if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } - if ($valuetoshow != '') - { + if ($fieldlist[$field] == 'lang') { + $valuetoshow = $langs->trans("Language"); + } + if ($valuetoshow != '') { print ''; } } @@ -469,20 +483,18 @@ if ($id) $obj = new stdClass(); // If data was already input, we define them in obj to populate input fields. - if (GETPOST('actionadd', 'alpha')) - { - foreach ($fieldlist as $key=>$val) - { - if (GETPOST($val, 'alpha')) + if (GETPOST('actionadd', 'alpha')) { + foreach ($fieldlist as $key => $val) { + if (GETPOST($val, 'alpha')) { $obj->$val = GETPOST($val); + } } } fieldListWebsites($fieldlist, $obj, $tabname[$id], 'add'); print ''; @@ -497,12 +509,10 @@ if ($id) // List of websites in database $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num) - { + if ($num) { print '
    '; print ''; @@ -514,8 +524,7 @@ if ($id) // Title of lines print ''; - foreach ($fieldlist as $field => $value) - { + foreach ($fieldlist as $field => $value) { // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees $showfield = 1; // Par defaut @@ -523,22 +532,29 @@ if ($id) $sortable = 1; $valuetoshow = ''; /* - $tmparray=getLabelOfField($fieldlist[$field]); - $showfield=$tmp['showfield']; - $valuetoshow=$tmp['valuetoshow']; - $align=$tmp['align']; - $sortable=$tmp['sortable']; + $tmparray=getLabelOfField($fieldlist[$field]); + $showfield=$tmp['showfield']; + $valuetoshow=$tmp['valuetoshow']; + $align=$tmp['align']; + $sortable=$tmp['sortable']; */ $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut $valuetoshow = $langs->trans($valuetoshow); // try to translate - if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } - if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); } - if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); } - if ($fieldlist[$field] == 'date_creation') { $valuetoshow = $langs->trans("DateCreation"); } + if ($fieldlist[$field] == 'lang') { + $valuetoshow = $langs->trans("Language"); + } + if ($fieldlist[$field] == 'type') { + $valuetoshow = $langs->trans("Type"); + } + if ($fieldlist[$field] == 'code') { + $valuetoshow = $langs->trans("Code"); + } + if ($fieldlist[$field] == 'date_creation') { + $valuetoshow = $langs->trans("DateCreation"); + } // Affiche nom du champ - if ($showfield) - { + if ($showfield) { print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), "", "align=".$align, $sortfield, $sortorder); } } @@ -549,46 +565,48 @@ if ($id) print ''; // Lines with values - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); //print_r($obj); print ''; - if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) - { + if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) { $tmpaction = 'edit'; $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); $reshook = $hookmanager->executeHooks('editWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks $error = $hookmanager->error; $errors = $hookmanager->errors; - if (empty($reshook)) fieldListWebsites($fieldlist, $obj, $tabname[$id], 'edit'); + if (empty($reshook)) { + fieldListWebsites($fieldlist, $obj, $tabname[$id], 'edit'); + } print ''; } else { - $tmpaction = 'view'; + $tmpaction = 'view'; $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); $reshook = $hookmanager->executeHooks('viewWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks $error = $hookmanager->error; $errors = $hookmanager->errors; - if (empty($reshook)) - { - foreach ($fieldlist as $field => $value) - { + if (empty($reshook)) { + foreach ($fieldlist as $field => $value) { $showfield = 1; $align = "left"; $fieldname = $fieldlist[$field]; $valuetoshow = $obj->$fieldname; // Show value for field - if ($showfield) print ''; + if ($showfield) { + print ''; + } } } // Can an entry be erased or disabled ? $iserasable = 1; $isdisable = 1; // true by default - if ($obj->status) $iserasable = 0; // We can't delete a website on. Disable it first. + if ($obj->status) { + $iserasable = 0; // We can't delete a website on. Disable it first. + } $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : '').'&'; @@ -601,8 +619,11 @@ if ($id) print ''; // Delete link - if ($iserasable) print ''; - else print ''; + if ($iserasable) { + print ''; + } else { + print ''; + } print "\n"; } @@ -644,27 +665,37 @@ function fieldListWebsites($fieldlist, $obj = '', $tabname = '', $context = '') $formadmin = new FormAdmin($db); - foreach ($fieldlist as $field => $value) - { + foreach ($fieldlist as $field => $value) { $fieldname = $fieldlist[$field]; - if ($fieldlist[$field] == 'lang') - { + if ($fieldlist[$field] == 'lang') { print ''; } elseif ($fieldlist[$field] == 'code' && isset($obj->$fieldname)) { print ''; } else { - if ($fieldlist[$field] == 'date_creation') continue; + if ($fieldlist[$field] == 'date_creation') { + continue; + } print ''; } diff --git a/htdocs/admin/website_options.php b/htdocs/admin/website_options.php index 8c803defb37..f72235eb8b0 100644 --- a/htdocs/admin/website_options.php +++ b/htdocs/admin/website_options.php @@ -40,7 +40,9 @@ $backtopage = GETPOST('backtopage', 'alpha'); $rowid = GETPOST('rowid', 'alpha'); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $status = 1; @@ -49,7 +51,9 @@ $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; @@ -97,8 +101,7 @@ $h++; print dol_get_fiche_head($head, 'options', '', -1); -if ($action == 'edit') -{ +if ($action == 'edit') { print ''; print ''; print ''; @@ -106,8 +109,7 @@ if ($action == 'edit') print '
    '; - if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; - elseif (!empty($tabhelp[$id][$value])) - { - if ($value == 'virtualhost') print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltipvirtual'); - else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); - } else print $valuetoshow; + if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) { + print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; + } elseif (!empty($tabhelp[$id][$value])) { + if ($value == 'virtualhost') { + print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltipvirtual'); + } else { + print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); + } + } else { + print $valuetoshow; + } print ''; - if ($action != 'edit') - { + if ($action != 'edit') { print ''; } print '
     '; print ' '.$valuetoshow.''.$valuetoshow.''.img_edit().''.img_delete().''.img_delete($langs->trans("DisableSiteFirst"), 'class="opacitymedium"').''.img_delete().''.img_delete($langs->trans("DisableSiteFirst"), 'class="opacitymedium"').'
    '; print $formadmin->select_language($conf->global->MAIN_LANG_DEFAULT, 'lang'); print ''; $size = ''; - if ($fieldlist[$field] == 'code') $size = 'size="8" '; - if ($fieldlist[$field] == 'position') $size = 'size="4" '; - if ($fieldlist[$field] == 'libelle') $size = 'size="32" '; - if ($fieldlist[$field] == 'tracking') $size = 'size="92" '; - if ($fieldlist[$field] == 'sortorder') $size = 'size="2" '; + if ($fieldlist[$field] == 'code') { + $size = 'size="8" '; + } + if ($fieldlist[$field] == 'position') { + $size = 'size="4" '; + } + if ($fieldlist[$field] == 'libelle') { + $size = 'size="32" '; + } + if ($fieldlist[$field] == 'tracking') { + $size = 'size="92" '; + } + if ($fieldlist[$field] == 'sortorder') { + $size = 'size="2" '; + } print ''; print '
    '; print ''; - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { print ''; @@ -125,8 +127,7 @@ if ($action == 'edit') print '
    '.$langs->trans("Parameter").''.$langs->trans("Value").'
    '; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); print '
    '; print ''; - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { print ''; diff --git a/htdocs/admin/workflow.php b/htdocs/admin/workflow.php index c1e099362ad..916c54f4fb3 100644 --- a/htdocs/admin/workflow.php +++ b/htdocs/admin/workflow.php @@ -1,7 +1,7 @@ * Copyright (C) 2004 Eric Seigne - * Copyright (C) 2005-2016 Laurent Destailleur + * Copyright (C) 2005-2021 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * * This program is free software; you can redistribute it and/or modify @@ -28,7 +28,9 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array("admin", "workflow", "propal", "workflow", "orders", "supplier_proposal", "receptions", "errors", 'sendings')); @@ -70,7 +72,7 @@ $workflowcodes = array( 'picto'=>'bill' ), - 'separator1'=>array('family'=>'separator', 'position'=>25), + 'separator1'=>array('family'=>'separator', 'position'=>25, 'title'=>''), // Automatic classification of proposal 'WORKFLOW_ORDER_CLASSIFY_BILLED_PROPAL'=>array( @@ -148,7 +150,8 @@ if (!empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts['w // remove not available workflows (based on activated modules and global defined keys) $workflowcodes = array_filter($workflowcodes, function ($var) { - return $var['enabled']; }); + return $var['enabled']; +}); /* * View @@ -183,6 +186,7 @@ foreach ($workflowcodes as $key => $params) { if ($params['family'] == 'separator') { print '
    '.$langs->trans("Parameter").''.$langs->trans("Value").'
    '; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); print ''.$conf->global->$key.'
    '; print '
    '; + print ''; continue; @@ -193,12 +197,24 @@ foreach ($workflowcodes as $key => $params) { $header = $langs->trans("AutomaticCreation"); } elseif (preg_match('/classify_(.*)/', $params['family'], $reg)) { $header = $langs->trans("AutomaticClassification"); - if ($reg[1] == 'proposal') $header .= ' - '.$langs->trans('Proposal'); - if ($reg[1] == 'order') $header .= ' - '.$langs->trans('Order'); - if ($reg[1] == 'supplier_proposal') $header .= ' - '.$langs->trans('SupplierProposal'); - if ($reg[1] == 'supplier_order') $header .= ' - '.$langs->trans('SupplierOrder'); - if ($reg[1] == 'reception') $header .= ' - '.$langs->trans('Reception'); - if ($reg[1] == 'shipping') $header .= ' - '.$langs->trans('Shipment'); + if ($reg[1] == 'proposal') { + $header .= ' - '.$langs->trans('Proposal'); + } + if ($reg[1] == 'order') { + $header .= ' - '.$langs->trans('Order'); + } + if ($reg[1] == 'supplier_proposal') { + $header .= ' - '.$langs->trans('SupplierProposal'); + } + if ($reg[1] == 'supplier_order') { + $header .= ' - '.$langs->trans('SupplierOrder'); + } + if ($reg[1] == 'reception') { + $header .= ' - '.$langs->trans('Reception'); + } + if ($reg[1] == 'shipping') { + $header .= ' - '.$langs->trans('Shipment'); + } } else { $header = $langs->trans("Description"); } diff --git a/htdocs/admin/workstation.php b/htdocs/admin/workstation.php index 98d72bf9f00..c0b4055ba5b 100755 --- a/htdocs/admin/workstation.php +++ b/htdocs/admin/workstation.php @@ -17,7 +17,7 @@ */ /** - * \file workstation/admin/setup.php + * \file htdocs/admin/workstation.php * \ingroup workstation * \brief Workstation setup page. */ @@ -31,10 +31,12 @@ require_once DOL_DOCUMENT_ROOT . '/workstation/lib/workstation.lib.php'; //require_once "../class/myclass.class.php"; // Translations -$langs->loadLangs(array("admin", "workstation@workstation")); +$langs->loadLangs(array("admin", "workstation")); // Access control -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Parameters $action = GETPOST('action', 'aZ09'); @@ -55,28 +57,28 @@ $setupnotempty = 0; * Actions */ -if ((float) DOL_VERSION >= 6) -{ +if ((float) DOL_VERSION >= 6) { include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; } -if ($action == 'updateMask') -{ +if ($action == 'updateMask') { $maskconstorder = GETPOST('maskconstWorkstation', 'alpha'); $maskorder = GETPOST('maskWorkstation', 'alpha'); - if ($maskconstorder) $res = dolibarr_set_const($db, $maskconstorder, $maskorder, 'chaine', 0, '', $conf->entity); + if ($maskconstorder) { + $res = dolibarr_set_const($db, $maskconstorder, $maskorder, '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'); } -} elseif ($action == 'specimen') -{ +} elseif ($action == 'specimen') { $modele = GETPOST('module', 'alpha'); $tmpobjectkey = GETPOST('object'); @@ -86,25 +88,21 @@ if ($action == 'updateMask') // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/workstation/doc/pdf_".$modele."_".strtolower($tmpobjectkey).".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db); - if ($module->write_file($tmpobject, $langs) > 0) - { + if ($module->write_file($tmpobject, $langs) > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=".strtolower($tmpobjectkey)."&file=SPECIMEN.pdf"); return; } else { @@ -115,31 +113,24 @@ if ($action == 'updateMask') setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); } -} - -// Activate a model -elseif ($action == 'set') -{ +} elseif ($action == 'set') { + // Activate a model $ret = addDocumentModel($value, $type, $label, $scandir); -} elseif ($action == 'del') -{ +} elseif ($action == 'del') { $tmpobjectkey = GETPOST('object'); $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $constforval = strtoupper($tmpobjectkey).'_ADDON_PDF'; - if ($conf->global->$constforval == "$value") dolibarr_del_const($db, $constforval, $conf->entity); + if ($conf->global->$constforval == "$value") { + dolibarr_del_const($db, $constforval, $conf->entity); + } } -} - -// Set default model -elseif ($action == 'setdoc') -{ +} elseif ($action == 'setdoc') { + // Set default model $tmpobjectkey = GETPOST('object'); $constforval = strtoupper($tmpobjectkey).'_ADDON_PDF'; - if (dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity)) - { + if (dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity)) { // The constant that was read before the new set // We therefore requires a variable to have a coherent view $conf->global->$constforval = $value; @@ -147,12 +138,10 @@ elseif ($action == 'setdoc') // On active le modele $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, $type, $label, $scandir); } -} elseif ($action == 'setmod') -{ +} elseif ($action == 'setmod') { // TODO Check if numbering module chosen can be activated // by calling method canBeActivated $tmpobjectkey = GETPOST('object'); @@ -186,8 +175,7 @@ print dol_get_fiche_head($head, 'settings', '', -1, "workstation@workstation"); //echo ''.$langs->trans("WorkstationSetupPage").'

    '; -if ($action == 'edit') -{ +if ($action == 'edit') { print ''; print ''; print ''; @@ -195,8 +183,7 @@ if ($action == 'edit') print '
    '; print ''; - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { print ''; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { // Accountancy_code_asset print ''; print ''; @@ -398,10 +409,8 @@ if ($action == 'create') /* View mode */ /* */ /* ************************************************************************** */ -if ($rowid > 0) -{ - if ($action != 'edit') - { +if ($rowid > 0) { + if ($action != 'edit') { $object = new AssetType($db); $object->fetch($rowid); $object->fetch_optionals(); @@ -409,14 +418,13 @@ if ($rowid > 0) /* * Confirmation suppression */ - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER['PHP_SELF']."?rowid=".$object->id, $langs->trans("DeleteAnAssetType"), $langs->trans("ConfirmDeleteAssetType", $object->label), "confirm_delete", '', 0, 1); } $head = asset_type_prepare_head($object); - print dol_get_fiche_head($head, 'card', $langs->trans("AssetType"), -1, 'setup'); + print dol_get_fiche_head($head, 'card', $langs->trans("AssetType"), -1, 'asset'); $linkback = ''.$langs->trans("BackToList").''; @@ -431,14 +439,13 @@ if ($rowid > 0) print '
    '; print '
    '; - print '
    '.$langs->trans("Parameter").''.$langs->trans("Value").'
    '; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); @@ -211,13 +198,11 @@ if ($action == 'edit') print ''; print '
    '; } else { - if (!empty($arrayofparameters)) - { + if (!empty($arrayofparameters)) { print ''; print ''; - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { $setupnotempty++; print ''."\n"; print ''; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { 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/api/class/api.class.php b/htdocs/api/class/api.class.php index 89d170feb60..8ddcf9f2dc3 100644 --- a/htdocs/api/class/api.class.php +++ b/htdocs/api/class/api.class.php @@ -51,7 +51,9 @@ class DolibarrApi { global $conf, $dolibarr_main_url_root; - if (empty($cachedir)) $cachedir = $conf->api->dir_temp; + if (empty($cachedir)) { + $cachedir = $conf->api->dir_temp; + } Defaults::$cacheDirectory = $cachedir; $this->db = $db; @@ -140,7 +142,7 @@ class DolibarrApi unset($object->labelStatusShort); unset($object->stats_propale); - unset($object->stats_commande); + unset($object->stats_commande); unset($object->stats_contrat); unset($object->stats_facture); unset($object->stats_commande_fournisseur); @@ -191,8 +193,7 @@ class DolibarrApi // If object has lines, remove $db property if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) { $nboflines = count($object->lines); - for ($i = 0; $i < $nboflines; $i++) - { + for ($i = 0; $i < $nboflines; $i++) { $this->_cleanObjectDatas($object->lines[$i]); unset($object->lines[$i]->contact); @@ -284,12 +285,14 @@ class DolibarrApi $ok = 0; $i = 0; $nb = strlen($tmp); $counter = 0; - while ($i < $nb) - { - if ($tmp[$i] == '(') $counter++; - if ($tmp[$i] == ')') $counter--; - if ($counter < 0) - { + while ($i < $nb) { + if ($tmp[$i] == '(') { + $counter++; + } + if ($tmp[$i] == ')') { + $counter--; + } + if ($counter < 0) { $error = "Bad sqlfilters=".$sqlfilters; dol_syslog($error, LOG_WARNING); return false; @@ -313,14 +316,17 @@ class DolibarrApi global $db; //dol_syslog("Convert matches ".$matches[1]); - if (empty($matches[1])) return ''; + if (empty($matches[1])) { + return ''; + } $tmp = explode(':', $matches[1]); - if (count($tmp) < 3) return ''; + if (count($tmp) < 3) { + return ''; + } $tmpescaped = $tmp[2]; $regbis = array(); - if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) - { + if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) { $tmpescaped = "'".$db->escape($regbis[1])."'"; } else { $tmpescaped = $db->escape($tmpescaped); diff --git a/htdocs/api/class/api_access.class.php b/htdocs/api/class/api_access.class.php index 926a51456c7..99582b62047 100644 --- a/htdocs/api/class/api_access.class.php +++ b/htdocs/api/class/api_access.class.php @@ -35,7 +35,6 @@ use \Luracast\Restler\Resources; use \Luracast\Restler\Defaults; use \Luracast\Restler\RestException; - /** * Dolibarr API access class * @@ -90,28 +89,24 @@ class DolibarrApiAccess implements iAuthenticate /*foreach ($_SERVER as $key => $val) { - dol_syslog($key.' - '.$val); + dol_syslog($key.' - '.$val); }*/ // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx $api_key = ''; - if (isset($_GET['api_key'])) // For backward compatibility - { + if (isset($_GET['api_key'])) { // For backward compatibility // TODO Add option to disable use of api key on url. Return errors if used. $api_key = $_GET['api_key']; } - if (isset($_GET['DOLAPIKEY'])) - { + if (isset($_GET['DOLAPIKEY'])) { // TODO Add option to disable use of api key on url. Return errors if used. $api_key = $_GET['DOLAPIKEY']; // With GET method } - if (isset($_SERVER['HTTP_DOLAPIKEY'])) // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY - { + if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded) } - if ($api_key) - { + if ($api_key) { $userentity = 0; $sql = "SELECT u.login, u.datec, u.api_key, "; @@ -121,17 +116,14 @@ class DolibarrApiAccess implements iAuthenticate // TODO Check if 2 users has same API key. $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $login = $obj->login; $stored_key = $obj->api_key; $userentity = $obj->entity; - if (!defined("DOLENTITY") && $conf->entity != ($obj->entity ? $obj->entity : 1)) // If API was not forced with HTTP_DOLENTITY, and user is on another entity, so we reset entity to entity of user - { + if (!defined("DOLENTITY") && $conf->entity != ($obj->entity ? $obj->entity : 1)) { // If API was not forced with HTTP_DOLENTITY, and user is on another entity, so we reset entity to entity of user $conf->entity = ($obj->entity ? $obj->entity : 1); // We must also reload global conf to get params from the entity dol_syslog("Entity was not set on http header with HTTP_DOLAPIENTITY (recommanded for performance purpose), so we switch now on entity of user (".$conf->entity.") and we have to reload configuration.", LOG_WARNING); @@ -147,8 +139,7 @@ class DolibarrApiAccess implements iAuthenticate return false; } - if (!$login) - { + if (!$login) { throw new RestException(503, 'Error when searching login user from api key'); } $fuser = new User($this->db); @@ -173,7 +164,9 @@ class DolibarrApiAccess implements iAuthenticate $userClass::setCacheIdentifier(static::$role); Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess'; $requirefortest = static::$requires; - if (!is_array($requirefortest)) $requirefortest = explode(',', $requirefortest); + if (!is_array($requirefortest)) { + $requirefortest = explode(',', $requirefortest); + } return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin'; } diff --git a/htdocs/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php index ebeeac5c5b9..00fd1a91a8a 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -20,7 +20,6 @@ use Luracast\Restler\RestException; use Luracast\Restler\Format\UploadFormat; - require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -36,7 +35,7 @@ class Documents extends DolibarrApi /** * @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object */ - static $DOCUMENT_FIELDS = array( + public static $DOCUMENT_FIELDS = array( 'modulepart' ); @@ -106,8 +105,7 @@ class Documents extends DolibarrApi $filename = basename($original_file); $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset - if (!file_exists($original_file_osencoded)) - { + if (!file_exists($original_file_osencoded)) { dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING); throw new RestException(404, 'File not found'); } @@ -148,8 +146,7 @@ class Documents extends DolibarrApi } $outputlangs = $langs; - if ($langcode && $langs->defaultlang != $langcode) - { + if ($langcode && $langs->defaultlang != $langcode) { $outputlangs = new Translate('', $conf); $outputlangs->setDefaultLang($langcode); } @@ -187,8 +184,7 @@ class Documents extends DolibarrApi $templateused = ''; - if ($modulepart == 'facture' || $modulepart == 'invoice') - { + if ($modulepart == 'facture' || $modulepart == 'invoice') { require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $this->invoice = new Facture($this->db); $result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); @@ -201,9 +197,7 @@ class Documents extends DolibarrApi if ($result <= 0) { throw new RestException(500, 'Error generating document'); } - } - elseif ($modulepart == 'commande' || $modulepart == 'order') - { + } elseif ($modulepart == 'commande' || $modulepart == 'order') { require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $this->order = new Commande($this->db); $result = $this->order->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); @@ -215,9 +209,7 @@ class Documents extends DolibarrApi if ($result <= 0) { throw new RestException(500, 'Error generating document'); } - } - elseif ($modulepart == 'propal' || $modulepart == 'proposal') - { + } elseif ($modulepart == 'propal' || $modulepart == 'proposal') { require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $this->propal = new Propal($this->db); $result = $this->propal->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); @@ -236,8 +228,7 @@ class Documents extends DolibarrApi $filename = basename($original_file); $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset - if (!file_exists($original_file_osencoded)) - { + if (!file_exists($original_file_osencoded)) { throw new RestException(404, 'File not found'); } @@ -278,8 +269,7 @@ class Documents extends DolibarrApi $recursive = 0; $type = 'files'; - if ($modulepart == 'societe' || $modulepart == 'thirdparty') - { + if ($modulepart == 'societe' || $modulepart == 'thirdparty') { require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; if (!DolibarrApiAccess::$user->rights->societe->lire) { @@ -293,9 +283,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id; - } - elseif ($modulepart == 'user') - { + } elseif ($modulepart == 'user') { require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; // Can get doc if has permission to read all user or if it is user itself @@ -310,9 +298,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->user->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id; - } - elseif ($modulepart == 'adherent' || $modulepart == 'member') - { + } elseif ($modulepart == 'adherent' || $modulepart == 'member') { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; if (!DolibarrApiAccess::$user->rights->adherent->lire) { @@ -326,9 +312,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->adherent->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'member'); - } - elseif ($modulepart == 'propal' || $modulepart == 'proposal') - { + } elseif ($modulepart == 'propal' || $modulepart == 'proposal') { require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; if (!DolibarrApiAccess::$user->rights->propal->lire) { @@ -342,9 +326,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal'); - } - elseif ($modulepart == 'commande' || $modulepart == 'order') - { + } elseif ($modulepart == 'commande' || $modulepart == 'order') { require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; if (!DolibarrApiAccess::$user->rights->commande->lire) { @@ -358,9 +340,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande'); - } - elseif ($modulepart == 'shipment' || $modulepart == 'expedition') - { + } elseif ($modulepart == 'shipment' || $modulepart == 'expedition') { require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; if (!DolibarrApiAccess::$user->rights->expedition->lire) { @@ -374,9 +354,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment'); - } - elseif ($modulepart == 'facture' || $modulepart == 'invoice') - { + } elseif ($modulepart == 'facture' || $modulepart == 'invoice') { require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; if (!DolibarrApiAccess::$user->rights->facture->lire) { @@ -390,9 +368,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice'); - } - elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') - { + } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') { $modulepart = 'supplier_invoice'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; @@ -408,9 +384,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref); - } - elseif ($modulepart == 'produit' || $modulepart == 'product') - { + } elseif ($modulepart == 'produit' || $modulepart == 'product') { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; if (!DolibarrApiAccess::$user->rights->produit->lire) { @@ -426,9 +400,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product'); - } - elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event') - { + } elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event') { require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; if (!DolibarrApiAccess::$user->rights->agenda->myactions->read && !DolibarrApiAccess::$user->rights->agenda->allactions->read) { @@ -442,9 +414,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref); - } - elseif ($modulepart == 'expensereport') - { + } elseif ($modulepart == 'expensereport') { require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; if (!DolibarrApiAccess::$user->rights->expensereport->read && !DolibarrApiAccess::$user->rights->expensereport->read) { @@ -458,9 +428,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref); - } - elseif ($modulepart == 'categorie' || $modulepart == 'category') - { + } elseif ($modulepart == 'categorie' || $modulepart == 'category') { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; if (!DolibarrApiAccess::$user->rights->categorie->lire) { @@ -523,9 +491,9 @@ class Documents extends DolibarrApi * @throws RestException */ /* - public function get($id) { - return array('note'=>'xxx'); - }*/ + public function get($id) { + return array('note'=>'xxx'); + }*/ /** @@ -557,12 +525,11 @@ class Documents extends DolibarrApi global $db, $conf; /*var_dump($modulepart); - var_dump($filename); - var_dump($filecontent); - exit;*/ + var_dump($filename); + var_dump($filecontent); + exit;*/ - if (empty($modulepart)) - { + if (empty($modulepart)) { throw new RestException(400, 'Modulepart not provided.'); } @@ -571,41 +538,39 @@ class Documents extends DolibarrApi } $newfilecontent = ''; - if (empty($fileencoding)) $newfilecontent = $filecontent; - if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent); + if (empty($fileencoding)) { + $newfilecontent = $filecontent; + } + if ($fileencoding == 'base64') { + $newfilecontent = base64_decode($filecontent); + } $original_file = dol_sanitizeFileName($filename); // Define $uploadir $object = null; $entity = DolibarrApiAccess::$user->entity; - if (empty($entity)) $entity = 1; + if (empty($entity)) { + $entity = 1; + } - if ($ref) - { + if ($ref) { $tmpreldir = ''; - if ($modulepart == 'facture' || $modulepart == 'invoice') - { + if ($modulepart == 'facture' || $modulepart == 'invoice') { $modulepart = 'facture'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $object = new Facture($this->db); - } - elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') - { + } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') { $modulepart = 'supplier_invoice'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; $object = new FactureFournisseur($this->db); - } - elseif ($modulepart == 'project') - { + } elseif ($modulepart == 'project') { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $object = new Project($this->db); - } - elseif ($modulepart == 'task' || $modulepart == 'project_task') - { + } elseif ($modulepart == 'task' || $modulepart == 'project_task') { $modulepart = 'project_task'; require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; @@ -614,36 +579,26 @@ class Documents extends DolibarrApi $task_result = $object->fetch('', $ref); // Fetching the tasks project is required because its out_dir might be a sub-directory of the project - if ($task_result > 0) - { + if ($task_result > 0) { $project_result = $object->fetch_projet(); - if ($project_result >= 0) - { + if ($project_result >= 0) { $tmpreldir = dol_sanitizeFileName($object->project->ref).'/'; } } else { throw new RestException(500, 'Error while fetching Task '.$ref); } - } - elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') - { + } elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $object = new Product($this->db); - } - elseif ($modulepart == 'expensereport') - { + } elseif ($modulepart == 'expensereport') { require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; $object = new ExpenseReport($this->db); - } - elseif ($modulepart == 'adherent' || $modulepart == 'member') - { + } elseif ($modulepart == 'adherent' || $modulepart == 'member') { $modulepart = 'adherent'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; $object = new Adherent($this->db); - } - elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale') - { + } elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale') { $modulepart = 'propale'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $object = new Propal($this->db); @@ -652,22 +607,18 @@ class Documents extends DolibarrApi throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.'); } - if (is_object($object)) - { + if (is_object($object)) { $result = $object->fetch('', $ref); - if ($result == 0) - { + if ($result == 0) { throw new RestException(404, "Object with ref '".$ref."' was not found."); - } - elseif ($result < 0) - { + } elseif ($result < 0) { throw new RestException(500, 'Error while fetching object: '.$object->error); } } if (!($object->id > 0)) { - throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found."); + throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found."); } // Special cases that need to use get_exdir to get real dir of object @@ -681,13 +632,16 @@ class Documents extends DolibarrApi $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write'); $upload_dir = $tmp['original_file']; // No dirname here, tmp['original_file'] is already the dir because dol_check_secure_access_document was called with param original_file that is only the dir - if (empty($upload_dir) || $upload_dir == '/') - { + if (empty($upload_dir) || $upload_dir == '/') { throw new RestException(500, 'This value of modulepart ('.$modulepart.') does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); } } else { - if ($modulepart == 'invoice') $modulepart = 'facture'; - if ($modulepart == 'member') $modulepart = 'adherent'; + if ($modulepart == 'invoice') { + $modulepart = 'facture'; + } + if ($modulepart == 'member') { + $modulepart = 'adherent'; + } $relativefile = $subdir; $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write'); @@ -771,12 +725,12 @@ class Documents extends DolibarrApi // Special cases that need to use get_exdir to get real dir of object // If future, all object should use this to define path of documents. /* - $tmpreldir = ''; - if ($modulepart == 'supplier_invoice') { - $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier'); - } + $tmpreldir = ''; + if ($modulepart == 'supplier_invoice') { + $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier'); + } - $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */ + $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */ $relativefile = $original_file; $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read'); @@ -794,8 +748,7 @@ class Documents extends DolibarrApi $filename = basename($original_file); $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset - if (!file_exists($original_file_osencoded)) - { + if (!file_exists($original_file_osencoded)) { dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING); throw new RestException(404, 'File not found'); } @@ -825,8 +778,9 @@ class Documents extends DolibarrApi // phpcs:enable $result = array(); foreach (Documents::$DOCUMENT_FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $result[$field] = $data[$field]; } return $result; diff --git a/htdocs/api/class/api_login.class.php b/htdocs/api/class/api_login.class.php index 17d8916b9aa..b9666269cc1 100644 --- a/htdocs/api/class/api_login.class.php +++ b/htdocs/api/class/api_login.class.php @@ -61,14 +61,16 @@ class Login // TODO Remove the API login. The token must be generated from backoffice only. // Authentication mode - if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'dolibarr'; + if (empty($dolibarr_main_authentication)) { + $dolibarr_main_authentication = 'dolibarr'; + } // Authentication mode: forceuser - if ($dolibarr_main_authentication == 'forceuser') - { - if (empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto'; - if ($dolibarr_auto_user != $login) - { + if ($dolibarr_main_authentication == 'forceuser') { + if (empty($dolibarr_auto_user)) { + $dolibarr_auto_user = 'auto'; + } + if ($dolibarr_auto_user != $login) { dol_syslog("Warning: your instance is set to use the automatic forced login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode."); throw new RestException(403, "Your instance is set to use the automatic login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode."); } @@ -77,16 +79,16 @@ class Login // Set authmode $authmode = explode(',', $dolibarr_main_authentication); - if ($entity != '' && !is_numeric($entity)) - { + if ($entity != '' && !is_numeric($entity)) { throw new RestException(403, "Bad value for entity, must be the numeric ID of company."); } - if ($entity == '') $entity = 1; + if ($entity == '') { + $entity = 1; + } include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; $login = checkLoginPassEntity($login, $password, $entity, $authmode, 'api'); - if (empty($login)) - { + if (empty($login)) { throw new RestException(403, 'Access denied'); } @@ -94,17 +96,14 @@ class Login $tmpuser = new User($this->db); $tmpuser->fetch(0, $login, 0, 0, $entity); - if (empty($tmpuser->id)) - { + if (empty($tmpuser->id)) { throw new RestException(500, 'Failed to load user'); } // Renew the hash - if (empty($tmpuser->api_key) || $reset) - { + if (empty($tmpuser->api_key) || $reset) { $tmpuser->getrights(); - if (empty($tmpuser->rights->user->self->creer)) - { + if (empty($tmpuser->rights->user->self->creer)) { throw new RestException(403, 'User need write permission on itself to reset its API token'); } @@ -118,8 +117,7 @@ class Login dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror()); } } else { diff --git a/htdocs/api/class/api_setup.class.php b/htdocs/api/class/api_setup.class.php index 4e4996df7e0..674cc53b69f 100644 --- a/htdocs/api/class/api_setup.class.php +++ b/htdocs/api/class/api_setup.class.php @@ -310,7 +310,7 @@ class Setup extends DolibarrApi * Get state by ID. * * @param int $id ID of state - * @return array Array of cleaned object properties + * @return array Array of cleaned object properties * * @url GET dictionary/states/{id} * diff --git a/htdocs/api/index.php b/htdocs/api/index.php index 2c85533fd11..bb74144a40d 100644 --- a/htdocs/api/index.php +++ b/htdocs/api/index.php @@ -26,22 +26,42 @@ use Luracast\Restler\Format\UploadFormat; -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library -if (!defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) -if (!defined("NOSESSION")) define("NOSESSION", '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +} +if (!defined("NOLOGIN")) { + define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) +} +if (!defined("NOSESSION")) { + define("NOSESSION", '1'); +} // Force entity if a value is provided into HTTP header. Otherwise, will use the entity of user of token used. -if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']); +if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) { + define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']); +} $res = 0; -if (!$res && file_exists("../main.inc.php")) $res = include '../main.inc.php'; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = include '../main.inc.php'; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php'; @@ -61,14 +81,12 @@ if (preg_match('/api\/index\.php$/', $url)) { // sometimes $_SERVER['PHP_SELF'] $url = $_SERVER['PHP_SELF'].$_SERVER['PATH_INFO']; } // Fix for some NGINX setups (this should not be required even with NGINX, however setup of NGINX are often mysterious and this may help is such cases) -if (!empty($conf->global->MAIN_NGINX_FIX)) -{ +if (!empty($conf->global->MAIN_NGINX_FIX)) { $url = (isset($_SERVER['SCRIPT_URI']) && $_SERVER["SCRIPT_URI"] !== null) ? $_SERVER["SCRIPT_URI"] : $_SERVER['PHP_SELF']; } // Enable and test if module Api is enabled -if (empty($conf->global->MAIN_MODULE_API)) -{ +if (empty($conf->global->MAIN_MODULE_API)) { $langs->load("admin"); dol_syslog("Call Dolibarr API interfaces with module REST disabled"); print $langs->trans("WarningModuleNotActive", 'Api').'.

    '; @@ -78,8 +96,7 @@ if (empty($conf->global->MAIN_MODULE_API)) } // Test if explorer is not disabled -if (preg_match('/api\/index\.php\/explorer/', $url) && !empty($conf->global->API_EXPLORER_DISABLED)) -{ +if (preg_match('/api\/index\.php\/explorer/', $url) && !empty($conf->global->API_EXPLORER_DISABLED)) { $langs->load("admin"); dol_syslog("Call Dolibarr API interfaces with module REST disabled"); print $langs->trans("WarningAPIExplorerDisabled").'.

    '; @@ -112,8 +129,7 @@ preg_match('/index\.php\/([^\/]+)(.*)$/', $url, $reg); // using the explorer. And when we make another call for another API, the API is not into the api/temp/routes.php and a 404 is returned. // So we force refresh to each call. $refreshcache = (empty($conf->global->API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE) ? true : false); -if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) -{ +if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) { $refreshcache = true; } @@ -132,12 +148,10 @@ UploadFormat::$allowedMimeTypes = array('image/jpeg', 'image/png', 'text/plain', // Restrict API to some IPs -if (!empty($conf->global->API_RESTRICT_ON_IP)) -{ +if (!empty($conf->global->API_RESTRICT_ON_IP)) { $allowedip = explode(' ', $conf->global->API_RESTRICT_ON_IP); $ipremote = getUserRemoteIP(); - if (!in_array($ipremote, $allowedip)) - { + if (!in_array($ipremote, $allowedip)) { dol_syslog('Remote ip is '.$ipremote.', not into list '.$conf->global->API_RESTRICT_ON_IP); print 'APIs are not allowed from the IP '.$ipremote; header('HTTP/1.1 503 API not allowed from your IP '.$ipremote); @@ -148,65 +162,64 @@ if (!empty($conf->global->API_RESTRICT_ON_IP)) // Call Explorer file for all APIs definitions (this part is slow) -if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) -{ +if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) { // Scan all API files to load them $listofapis = array(); $modulesdir = dolGetModulesDirs(); - foreach ($modulesdir as $dir) - { + foreach ($modulesdir as $dir) { // Search available module dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files"); $handle = @opendir(dol_osencode($dir)); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $regmod = array(); - if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) - { + if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) { $module = strtolower($regmod[1]); $moduledirforclass = getModuleDirForApiClass($module); $modulenameforenabled = $module; - if ($module == 'propale') { $modulenameforenabled = 'propal'; } - if ($module == 'supplierproposal') { $modulenameforenabled = 'supplier_proposal'; } - if ($module == 'ficheinter') { $modulenameforenabled = 'ficheinter'; } + if ($module == 'propale') { + $modulenameforenabled = 'propal'; + } + if ($module == 'supplierproposal') { + $modulenameforenabled = 'supplier_proposal'; + } + if ($module == 'ficheinter') { + $modulenameforenabled = 'ficheinter'; + } dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass); // Defined if module is enabled $enabled = true; - if (empty($conf->$modulenameforenabled->enabled)) $enabled = false; + if (empty($conf->$modulenameforenabled->enabled)) { + $enabled = false; + } - if ($enabled) - { + if ($enabled) { // If exists, load the API class for enable module // Search files named api_.class.php into /htdocs//class directory // @todo : use getElementProperties() function ? $dir_part = dol_buildpath('/'.$moduledirforclass.'/class/'); $handle_part = @opendir(dol_osencode($dir_part)); - if (is_resource($handle_part)) - { - while (($file_searched = readdir($handle_part)) !== false) - { - if ($file_searched == 'api_access.class.php') continue; + if (is_resource($handle_part)) { + while (($file_searched = readdir($handle_part)) !== false) { + if ($file_searched == 'api_access.class.php') { + continue; + } $regapi = array(); - if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) - { + if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) { $classname = ucwords($regapi[1]); $classname = str_replace('_', '', $classname); require_once $dir_part.$file_searched; - if (class_exists($classname.'Api')) - { + if (class_exists($classname.'Api')) { //dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched); $listofapis[strtolower($classname.'Api')] = $classname.'Api'; - } elseif (class_exists($classname)) - { + } elseif (class_exists($classname)) { //dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched); $listofapis[strtolower($classname)] = $classname; } else { @@ -224,8 +237,7 @@ if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $ // Sort the classes before adding them to Restler. // The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted. asort($listofapis); - foreach ($listofapis as $apiname => $classname) - { + foreach ($listofapis as $apiname => $classname) { $api->r->addAPIClass($classname, $apiname); } //var_dump($api->r); @@ -233,11 +245,9 @@ if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $ // Call one APIs or one definition of an API $regbis = array(); -if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && $reg[2] != '/resources.json' && preg_match('/^\/(swagger|resources)\.json\/(.+)$/', $reg[2], $regbis) && $regbis[2] != 'root'))) -{ +if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && $reg[2] != '/resources.json' && preg_match('/^\/(swagger|resources)\.json\/(.+)$/', $reg[2], $regbis) && $regbis[2] != 'root'))) { $moduleobject = $reg[1]; - if ($moduleobject == 'explorer') // If we call page to explore details of a service - { + if ($moduleobject == 'explorer') { // If we call page to explore details of a service $moduleobject = $regbis[2]; } @@ -248,21 +258,27 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && dol_syslog("Load a dedicated API file moduleobject=".$moduleobject." moduledirforclass=".$moduledirforclass); $tmpmodule = $moduleobject; - if ($tmpmodule != 'api') + if ($tmpmodule != 'api') { $tmpmodule = preg_replace('/api$/i', '', $tmpmodule); + } $classfile = str_replace('_', '', $tmpmodule); // Special cases that does not match name rules conventions - if ($moduleobject == 'supplierproposals') + if ($moduleobject == 'supplierproposals') { $classfile = 'supplier_proposals'; - if ($moduleobject == 'supplierorders') + } + if ($moduleobject == 'supplierorders') { $classfile = 'supplier_orders'; - if ($moduleobject == 'supplierinvoices') + } + if ($moduleobject == 'supplierinvoices') { $classfile = 'supplier_invoices'; - if ($moduleobject == 'ficheinter') + } + if ($moduleobject == 'ficheinter') { $classfile = 'interventions'; - if ($moduleobject == 'interventions') + } + if ($moduleobject == 'interventions') { $classfile = 'interventions'; + } $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2); @@ -271,8 +287,9 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && dol_syslog('Search api file /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.' classname='.$classname); $res = false; - if ($dir_part_file) + if ($dir_part_file) { $res = include_once $dir_part_file; + } if (!$res) { dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING); print 'API not found (failed to include API file)'; @@ -281,8 +298,9 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && exit(0); } - if (class_exists($classname)) + if (class_exists($classname)) { $api->r->addAPIClass($classname); + } } diff --git a/htdocs/asset/admin/assets_extrafields.php b/htdocs/asset/admin/assets_extrafields.php index 3334610b927..9a68f99fe06 100644 --- a/htdocs/asset/admin/assets_extrafields.php +++ b/htdocs/asset/admin/assets_extrafields.php @@ -35,13 +35,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 = 'don'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -74,8 +78,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -88,8 +91,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print "
    "; print load_fiche_titre($langs->trans('NewAttribute')); @@ -101,8 +103,7 @@ if ($action == 'create') /* Edit optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
    "; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/asset/admin/assets_type_extrafields.php b/htdocs/asset/admin/assets_type_extrafields.php index e17d421437d..6d2799e0228 100644 --- a/htdocs/asset/admin/assets_type_extrafields.php +++ b/htdocs/asset/admin/assets_type_extrafields.php @@ -34,13 +34,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(); +} /* @@ -72,8 +76,7 @@ require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -86,8 +89,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print "
    "; print load_fiche_titre($langs->trans('NewAttribute')); @@ -99,8 +101,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
    "; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); 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/admin/setup.php b/htdocs/asset/admin/setup.php index 42a5888c537..c6cd45a0cc5 100644 --- a/htdocs/asset/admin/setup.php +++ b/htdocs/asset/admin/setup.php @@ -32,7 +32,9 @@ global $langs, $user; $langs->loadLangs(array("admin", "assets")); // Access control -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Parameters $action = GETPOST('action', 'aZ09'); @@ -63,8 +65,7 @@ $head = asset_admin_prepare_head(); print dol_get_fiche_head($head, 'settings', $langs->trans("Assets"), -1, 'generic'); -if ($action == 'edit') -{ +if ($action == 'edit') { print '
    '; print ''; print ''; @@ -72,8 +73,7 @@ if ($action == 'edit') print '
    '.$langs->trans("Parameter").''.$langs->trans("Value").'
    '; @@ -243,7 +228,9 @@ $myTmpObjects['workstation'] = array('includerefgeneration'=>1, 'includedocgener foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { - if ($myTmpObjectKey == 'MyObject') continue; + if ($myTmpObjectKey == 'MyObject') { + continue; + } if ($myTmpObjectArray['includerefgeneration']) { /* * Orders Numbering model @@ -263,19 +250,14 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { clearstatcache(); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/".$moduledir); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php') - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php') { $file = substr($file, 0, dol_strlen($file) - 4); require_once $dir.'/'.$file.'.php'; @@ -283,11 +265,14 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { $module = new $file($db); // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } - if ($module->isEnabled()) - { + if ($module->isEnabled()) { dol_include_once('/'.$moduledir.'/class/'.strtolower($myTmpObjectKey).'.class.php'); print '
    '.$module->name."\n"; @@ -300,14 +285,16 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '
    '.$langs->trans($tmp).'
    '; - } elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); - else print $tmp; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; + } print '
    '; $constforvar = 'WORKSTATION_'.strtoupper($myTmpObjectKey).'_ADDON'; - if ($conf->global->$constforvar == $file) - { + if ($conf->global->$constforvar == $file) { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print ''; @@ -327,8 +314,9 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { $nextval = $langs->trans($nextval); + } $htmltooltip .= $nextval.'
    '; } else { $htmltooltip .= $langs->trans($module->error).'
    '; @@ -366,12 +354,10 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { $sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -392,31 +378,23 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { clearstatcache(); - foreach ($dirmodels as $reldir) - { - foreach (array('', '/doc') as $valdir) - { + foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { $realpath = $reldir."core/modules/".$moduledir.$valdir; $dir = dol_buildpath($realpath); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -424,21 +402,26 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { $module = new $classname($db); $modulequalified = 1; - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print '
    '; print (empty($module->name) ? $name : $module->name); print "\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print ''."\n"; print ''; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -453,8 +436,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { // Default print ''; $constforvar = 'WORKSTATION_'.strtoupper($myTmpObjectKey).'_ADDON'; - if ($conf->global->$constforvar == $name) - { + if ($conf->global->$constforvar == $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').''; @@ -464,8 +446,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '
    '.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '
    '.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } $htmltooltip .= '
    '.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; @@ -480,8 +461,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { // Preview print '
    '; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print ''.img_object($langs->trans("Preview"), 'generic').''; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); diff --git a/htdocs/api/admin/explorer.php b/htdocs/api/admin/explorer.php index 835a5485544..53b9233c130 100644 --- a/htdocs/api/admin/explorer.php +++ b/htdocs/api/admin/explorer.php @@ -41,8 +41,7 @@ $langs->load("admin"); */ // Enable and test if module Api is enabled -if (empty($conf->global->MAIN_MODULE_API)) -{ +if (empty($conf->global->MAIN_MODULE_API)) { dol_syslog("Call Dolibarr API interfaces with module REST disabled"); print $langs->trans("WarningModuleNotActive", 'Api').'.

    '; print $langs->trans("ToActivateModule"); @@ -59,20 +58,16 @@ $api->r->addAuthenticationClass('DolibarrApiAccess', ''); $listofapis = array(); $modulesdir = dolGetModulesDirs(); -foreach ($modulesdir as $dir) -{ +foreach ($modulesdir as $dir) { /* - * Search available module - */ + * Search available module + */ //dol_syslog("Scan directory ".$dir." for API modules"); $handle = @opendir(dol_osencode($dir)); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) { $modulename = $reg[1]; // Defined if module is enabled @@ -96,60 +91,58 @@ foreach ($modulesdir as $dir) $module = 'fichinter'; } - if (empty($conf->$module->enabled)) $enabled = false; + if (empty($conf->$module->enabled)) { + $enabled = false; + } if ($enabled) { /* - * If exists, load the API class for enable module - * - * Search files named api_.class.php into /htdocs//class directory - * - * @todo : take care of externals module! - * @todo : use getElementProperties() function ? - */ + * If exists, load the API class for enable module + * + * Search files named api_.class.php into /htdocs//class directory + * + * @todo : take care of externals module! + * @todo : use getElementProperties() function ? + */ $dir_part = DOL_DOCUMENT_ROOT.'/'.$part.'/class/'; $handle_part = @opendir(dol_osencode($dir_part)); - if (is_resource($handle_part)) - { - while (($file_searched = readdir($handle_part)) !== false) - { - if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg)) - { + if (is_resource($handle_part)) { + while (($file_searched = readdir($handle_part)) !== false) { + if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg)) { $classname = ucwords($reg[1]); require_once $dir_part.$file_searched; - if (class_exists($classname)) - { + if (class_exists($classname)) { dol_syslog("Found API classname=".$classname." into ".$dir); $listofapis[] = $classname; } } /* - if (is_readable($dir_part.$file_searched) && preg_match("/^(api_.*)\.class\.php$/i",$file_searched,$reg)) - { - $classname=$reg[1]; - $classname = str_replace('Api_','',ucwords($reg[1])).'Api'; - //$classname = str_replace('Api_','',ucwords($reg[1])); - $classname = ucfirst($classname); - require_once $dir_part.$file_searched; + if (is_readable($dir_part.$file_searched) && preg_match("/^(api_.*)\.class\.php$/i",$file_searched,$reg)) + { + $classname=$reg[1]; + $classname = str_replace('Api_','',ucwords($reg[1])).'Api'; + //$classname = str_replace('Api_','',ucwords($reg[1])); + $classname = ucfirst($classname); + require_once $dir_part.$file_searched; - // if (class_exists($classname)) - // { - // dol_syslog("Found API classname=".$classname); - // $api->r->addAPIClass($classname,''); + // if (class_exists($classname)) + // { + // dol_syslog("Found API classname=".$classname); + // $api->r->addAPIClass($classname,''); - // require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Routes.php'; - // $tmpclass = new ReflectionClass($classname); - // try { - // $classMetadata = CommentParser::parse($tmpclass->getDocComment()); - // } catch (Exception $e) { - // throw new RestException(500, "Error while parsing comments of `$classname` class. " . $e->getMessage()); - // } + // require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Routes.php'; + // $tmpclass = new ReflectionClass($classname); + // try { + // $classMetadata = CommentParser::parse($tmpclass->getDocComment()); + // } catch (Exception $e) { + // throw new RestException(500, "Error while parsing comments of `$classname` class. " . $e->getMessage()); + // } - // //$listofapis[]=array('classname'=>$classname, 'fullpath'=>$file_searched); - // } - }*/ + // //$listofapis[]=array('classname'=>$classname, 'fullpath'=>$file_searched); + // } + }*/ } } } @@ -186,21 +179,23 @@ print '
    '; $oldclass = ''; print $langs->trans("ListOfAvailableAPIs").':
    '; -foreach ($listofapis['v1'] as $key => $val) -{ - if ($key == 'login') continue; - if ($key == 'index') continue; +foreach ($listofapis['v1'] as $key => $val) { + if ($key == 'login') { + continue; + } + if ($key == 'index') { + continue; + } - if ($key) - { - foreach ($val as $method => $val2) - { + if ($key) { + foreach ($val as $method => $val2) { $newclass = $val2['className']; - if (preg_match('/restler/i', $newclass)) continue; + if (preg_match('/restler/i', $newclass)) { + continue; + } - if ($oldclass != $newclass) - { + if ($oldclass != $newclass) { print "\n
    \n".$langs->trans("Class").': '.$newclass.'
    '."\n"; $oldclass = $newclass; } 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 "
    '.$langs->trans("ApiProductionMode").''; print img_picto($langs->trans("Activated"), 'switch_on'); print '
    '; print ''; - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { print ''; @@ -91,8 +91,7 @@ if ($action == 'edit') print '
    '.$langs->trans("Parameter").''.$langs->trans("Value").'
    '; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); print '
    '; print ''; - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { print ''; diff --git a/htdocs/asset/card.php b/htdocs/asset/card.php index 58307781cf2..3d722bca400 100644 --- a/htdocs/asset/card.php +++ b/htdocs/asset/card.php @@ -55,18 +55,23 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. // Security check -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'asset', $id); $permissiontoread = $user->rights->asset->read; @@ -74,7 +79,7 @@ $permissiontoadd = $user->rights->asset->write; // Used by the include of action $permissiontodelete = $user->rights->asset->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT); $permissionnote = $user->rights->asset->write; // Used by the include of actions_setnotes.inc.php $permissiondellink = $user->rights->asset->write; // Used by the include of actions_dellink.inc.php -$upload_dir = $conf->mymodule->multidir_output[isset($object->entity) ? $object->entity : 1]; +$upload_dir = $conf->asset->multidir_output[isset($object->entity) ? $object->entity : 1]; /* @@ -83,10 +88,11 @@ $upload_dir = $conf->mymodule->multidir_output[isset($object->entity) ? $object- $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 (empty($reshook)) { $error = 0; $backurlforlist = dol_buildpath('/asset/list.php', 1); @@ -109,12 +115,10 @@ if (empty($reshook)) // Action to build doc include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - if ($action == 'set_thirdparty' && $permissiontoadd) - { + if ($action == 'set_thirdparty' && $permissiontoadd) { $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MYOBJECT_MODIFY'); } - if ($action == 'classin' && $permissiontoadd) - { + if ($action == 'classin' && $permissiontoadd) { $object->setProject(GETPOST('projectid', 'int')); } @@ -125,48 +129,31 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; } - - - /* * View * - * Put here all code to build page */ $form = new Form($db); $formfile = new FormFile($db); -$title = $langs->trans("Assets").' - '.$langs->trans("Card"); +$title = $langs->trans("Asset").' - '.$langs->trans("Card"); $help_url = ''; llxHeader('', $title, $help_url); -// Example : Adding jquery code -print ''; - - // Part to create -if ($action == 'create') -{ - print load_fiche_titre($langs->trans("NewAsset"), '', 'accountancy'); +if ($action == 'create') { + print load_fiche_titre($langs->trans("NewAsset"), '', $object->picto); print ''; print ''; print ''; - if ($backtopage) print ''; - if ($backtopageforcancel) print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } print dol_get_fiche_head(array(), ''); @@ -194,8 +181,7 @@ if ($action == 'create') } // Part to edit record -if (($id || $ref) && $action == 'edit') -{ +if (($id || $ref) && $action == 'edit') { print load_fiche_titre($langs->trans("Assets")); print ''; @@ -203,8 +189,12 @@ if (($id || $ref) && $action == 'edit') print ''; print ''; print ''; - if ($backtopage) print ''; - if ($backtopageforcancel) print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } print dol_get_fiche_head(); @@ -228,8 +218,7 @@ if (($id || $ref) && $action == 'edit') } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_optionals(); $head = asset_prepare_head($object); @@ -238,23 +227,18 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $formconfirm = ''; // Confirmation to delete - if ($action == 'delete') - { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteAssets'), $langs->trans('ConfirmDeleteAssets'), 'confirm_delete', '', 0, 1); - } - - // Confirmation of action xxxx - if ($action == 'xxx') - { - $formquestion = array(); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); + if ($action == 'delete') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteAssets'), $langs->trans('ConfirmDeleteAsset'), 'confirm_delete', '', 0, 1); } // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -292,78 +276,59 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '
    '.$langs->trans("Parameter").''.$langs->trans("Value").'
    '; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); print ''.$conf->global->$key.'
    '; print ''; - print ''; - print ''; print '
    '; print dol_get_fiche_end(); - // Buttons for actions - if ($action != 'presend' && $action != 'editline') { - print '
    '."\n"; + /* + * Buttons + */ + if ($user->socid == 0) { + print '
    '; + $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if (empty($reshook)) - { - // Send - if (empty($user->socid)) { - print ''.$langs->trans('SendMail').''."\n"; - } - - if ($user->rights->asset->write) - { + if (empty($reshook)) { + if ($user->rights->asset->write) { print ''.$langs->trans("Modify").''."\n"; } else { print ''.$langs->trans('Modify').''."\n"; } - if ($user->rights->asset->delete) - { + if ($user->rights->asset->delete) { print ''.$langs->trans('Delete').''."\n"; } else { print ''.$langs->trans('Delete').''."\n"; } } - print '
    '."\n"; + print "
    "; } - - // Select mail models is same action as presend - if (GETPOST('modelselected')) { - $action = 'presend'; - } - - if ($action != 'presend') - { + if ($action != 'presend') { print '
    '; print ''; // ancre // Documents - /*$objref = dol_sanitizeFileName($object->ref); - $relativepath = $comref . '/' . $comref . '.pdf'; - $filedir = $conf->asset->dir_output . '/' . $objref; - $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; + $filename = dol_sanitizeFileName($object->ref); + $filedir = $conf->contrat->dir_output."/".dol_sanitizeFileName($object->ref); + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; $genallowed = $user->rights->asset->read; // If you can read, you can build the PDF to read content - $delallowed = $user->rights->asset->create; // If you can create/edit, you can remove a file on card - print $formfile->showdocuments('asset', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); - */ + $delallowed = $user->rights->asset->write; // If you can create/edit, you can remove a file on card + + print $formfile->showdocuments('asset', $filename, $filedir, $urlsource, 0, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); // Show links to link elements $linktoelem = $form->showLinkToObjectBlock($object, null, array('asset')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
    '; $MAXEVENT = 10; - $morehtmlright = ''; - $morehtmlright .= $langs->trans("SeeAll"); - $morehtmlright .= ''; + $morehtmlcenter = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-list-alt imgforviewmode', DOL_URL_ROOT.'/asset/info.php?id='.$object->id); // List of actions on element include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; @@ -372,19 +337,6 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '
    '; } - - //Select mail models is same action as presend - if (GETPOST('modelselected')) $action = 'presend'; - - // Presend form - /* - $modelmail='asset'; - $defaulttopic='InformationMessage'; - $diroutput = $conf->asset->dir_output.'/asset'; - $trackid = 'asset'.$object->id; - - include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; - */ } diff --git a/htdocs/asset/class/asset.class.php b/htdocs/asset/class/asset.class.php index f4823ae9b6f..66cd9bcb4cf 100644 --- a/htdocs/asset/class/asset.class.php +++ b/htdocs/asset/class/asset.class.php @@ -170,8 +170,12 @@ class Asset extends CommonObject $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled)) { + $this->fields['entity']['enabled'] = 0; + } } /** @@ -304,44 +308,55 @@ class Asset extends CommonObject global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; - $companylink = ''; - $label = ''.$langs->trans("Asset").''; + $label = img_picto('', $this->picto).' '.$langs->trans("Asset").''; + if (isset($this->status)) { + $label .= ' '.$this->getLibStatut(5); + } $label .= '
    '; $label .= ''.$langs->trans('Ref').': '.$this->ref; $url = dol_buildpath('/asset/card.php', 1).'?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowAssets"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -381,7 +396,9 @@ class Asset extends CommonObject $labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled'); $statusType = 'status0'; - if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } return dolGetStatus($labelStatus[$status], $labelStatusShort[$status], '', $statusType, $mode); } @@ -397,30 +414,25 @@ 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; diff --git a/htdocs/asset/class/asset_type.class.php b/htdocs/asset/class/asset_type.class.php index 5af5f3d7591..6b345aaef68 100644 --- a/htdocs/asset/class/asset_type.class.php +++ b/htdocs/asset/class/asset_type.class.php @@ -42,7 +42,7 @@ class AssetType extends CommonObject /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ - public $picto = 'invoice'; + public $picto = 'asset'; /** * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe @@ -131,27 +131,25 @@ class AssetType extends CommonObject dol_syslog("Asset_type::create", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."asset_type"); $result = $this->update($user, 1); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -3; } - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('ASSET_TYPE_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -193,30 +191,27 @@ class AssetType extends CommonObject $sql .= " WHERE rowid =".$this->id; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $action = 'update'; // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('ASSET_TYPE_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -246,11 +241,12 @@ class AssetType extends CommonObject $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger $result = $this->call_trigger('ASSET_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(); @@ -277,10 +273,8 @@ class AssetType extends CommonObject dol_syslog("Asset_type::fetch", LOG_DEBUG); $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; @@ -317,15 +311,12 @@ class AssetType extends CommonObject $sql .= " WHERE entity IN (".getEntity('asset_type').")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $nump = $this->db->num_rows($resql); - if ($nump) - { + if ($nump) { $i = 0; - while ($i < $nump) - { + while ($i < $nump) { $obj = $this->db->fetch_object($resql); $assettypes[$obj->rowid] = $langs->trans($obj->label); @@ -357,18 +348,16 @@ class AssetType extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."asset as a"; $sql .= " WHERE a.entity IN (".getEntity('asset').")"; $sql .= " AND a.fk_asset_type = ".$this->id; - if (!empty($excludefilter)) $sql .= ' AND ('.$excludefilter.')'; + if (!empty($excludefilter)) { + $sql .= ' AND ('.$excludefilter.')'; + } dol_syslog(get_class($this)."::listAssetsForGroup", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { - if (!array_key_exists($obj->rowid, $ret)) - { - if ($mode < 2) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { + if (!array_key_exists($obj->rowid, $ret)) { + if ($mode < 2) { $assetstatic = new Asset($this->db); if ($mode == 1) { $assetstatic->fetch($obj->rowid, '', '', '', false, false); @@ -376,7 +365,9 @@ class AssetType extends CommonObject $assetstatic->fetch($obj->rowid); } $ret[$obj->rowid] = $assetstatic; - } else $ret[$obj->rowid] = $obj->rowid; + } else { + $ret[$obj->rowid] = $obj->rowid; + } } } @@ -406,12 +397,16 @@ class AssetType extends CommonObject $result = ''; $label = $langs->trans("ShowTypeCard", $this->label); - $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; 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/document.php b/htdocs/asset/document.php index 4c2e36aed9a..e5db1465fb6 100644 --- a/htdocs/asset/document.php +++ b/htdocs/asset/document.php @@ -1,6 +1,6 @@ - * Copyright (C) 2018 Alexandre Spangaro + * Copyright (C) 2018-2021 Alexandre Spangaro * * 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 @@ -19,7 +19,7 @@ /** * \file htdocs/asset/document.php * \ingroup asset - * \brief Tab for documents linked to Assets + * \brief Page for attached files on assets */ require '../main.inc.php'; @@ -31,125 +31,108 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; // Load translation files required by the page -$langs->loadLangs(array("assets", "companies")); +$langs->loadLangs(array('assets', 'companies', 'other')); -$action = GETPOST('action', 'aZ09'); -$confirm = GETPOST('confirm'); -$id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); +$id = (GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility $ref = GETPOST('ref', 'alpha'); +$socid = GETPOST('socid', 'int'); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm', 'alpha'); -// Security check - Protection if external user -//if ($user->socid > 0) accessforbidden(); -//if ($user->socid > 0) $socid = $user->socid; -//$result = restrictedArea($user, 'asset', $id); +// Security check +if ($user->socid) { + $socid = $user->socid; +} +$result=restrictedArea($user, 'asset', $id, ''); // Get parameters $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"; +} -// Initialize technical objects $object = new Asset($db); -$extrafields = new ExtraFields($db); -$diroutputmassaction = $conf->assets->dir_output.'/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('assetdocument')); // Note that conf->hooks_modules contains array - -// Fetch optionals attributes and labels -$extrafields->fetch_name_optionals_label($object->table_element); - -// Load object -include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals - -// Security check -if (!empty($user->socid)) $socid = $user->socid; -$result = restrictedArea($user, 'asset', $id); - -//if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/packages/" . dol_sanitizeFileName($object->id); -if ($id > 0 || !empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity]."/packages/".dol_sanitizeFileName($object->ref); - +if ($object->fetch($id)) { + $upload_dir = $conf->asset->dir_output."/".dol_sanitizeFileName($object->ref); +} /* * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* * View */ +$title = $langs->trans('Assets')." - ".$langs->trans('Documents'); +$helpurl = ''; +llxHeader('', $title, $helpurl); + $form = new Form($db); -$title = $langs->trans("Assets").' - '.$langs->trans("Files"); -$help_url = ''; -//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; -llxHeader('', $title, $help_url); - -if ($object->id) -{ - /* - * Show tabs - */ - if (!empty($conf->notification->enabled)) $langs->load("mails"); - $head = asset_prepare_head($object); - - print dol_get_fiche_head($head, 'document', $langs->trans("Asset"), -1, 'generic'); - // Build file list - $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); - $totalsize = 0; - foreach ($filearray as $key => $file) - { - $totalsize += $file['size']; +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { + $upload_dir = $conf->asset->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); + + $head = asset_prepare_head($object); + print dol_get_fiche_head($head, 'documents', $langs->trans('Asset'), -1, 'accounting'); + + // Build file list + $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); + $totalsize = 0; + foreach ($filearray as $key => $file) { + $totalsize += $file['size']; + } + + // Asset content + + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = ''; + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0); + + print '
    '; + print '
    '; + + print ''; + + print ''; + print ''; + print "
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize, 1, 1).'
    \n"; + + print "
    \n"; + + print dol_get_fiche_end(); + + $modulepart = 'asset'; + $permission = $user->rights->asset->write; + $permtoedit = $user->rights->asset->write; + $param = '&id='.$object->id; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; + } else { + dol_print_error($db); } - - // Object card - // ------------------------------------------------------------ - $linkback = ''.$langs->trans("BackToList").''; - - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - - print '
    '; - - print '
    '; - print ''; - - // Number of files - print ''; - - // Total size - print ''; - - print '
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    '; - - print '
    '; - - print dol_get_fiche_end(); - - $modulepart = 'asset'; - //$permission = $user->rights->asset->create; - $permission = 1; - //$permtoedit = $user->rights->asset->create; - $permtoedit = 1; - $param = '&id='.$object->id; - - //$relativepathwithnofile='asset/' . dol_sanitizeFileName($object->id).'/'; - $relativepathwithnofile = 'asset/'.dol_sanitizeFileName($object->ref).'/'; - - include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { - accessforbidden('', 0, 1); + print $langs->trans("ErrorUnknown"); } // End of page 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/asset/info.php b/htdocs/asset/info.php index d211cf0dbad..f6d34454ad4 100644 --- a/htdocs/asset/info.php +++ b/htdocs/asset/info.php @@ -29,12 +29,14 @@ require_once DOL_DOCUMENT_ROOT.'/asset/class/asset.class.php'; // Load translation files required by the page $langs->loadLangs(array("asset")); -$id = GETPOST('id', 'int'); +$id = GETPOSTINT('id'); $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'asset', $id); $object = new Asset($db); diff --git a/htdocs/asset/list.php b/htdocs/asset/list.php index cffcc8a962d..e0beefd688f 100644 --- a/htdocs/asset/list.php +++ b/htdocs/asset/list.php @@ -50,7 +50,9 @@ $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; @@ -68,14 +70,20 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Security check $socid = 0; -if ($user->socid) $socid = $user->socid; -if ($user->socid > 0) // Protection if external user -{ +if ($user->socid) { + $socid = $user->socid; +} +if ($user->socid > 0) { + // Protection if external user //$socid = $user->socid; accessforbidden(); } @@ -86,30 +94,31 @@ $result = restrictedArea($user, 'asset', $id); // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of fields for list $arrayfields = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field - if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); + if (!empty($val['visible'])) { + $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); + } } // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], @@ -132,31 +141,33 @@ $permissiontodelete = $user->rights->asset->delete; * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($object->fields as $key => $val) - { + 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 + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $toselect = ''; $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -185,13 +196,14 @@ $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("Assets")); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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.', ' : ''); + 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(); @@ -199,20 +211,32 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -else $sql .= " WHERE 1 = 1"; -foreach ($search as $key => $val) -{ - if ($key == 'status' && $search[$key] == -1) continue; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); if (strpos($object->fields[$key]['type'], 'integer:') === 0) { - if ($search[$key] == '-1') $search[$key] = ''; + if ($search[$key] == '-1') { + $search[$key] = ''; + } $mode_search = 2; } - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -225,7 +249,7 @@ $sql .= $hookmanager->resPrint; $sql.= " GROUP BY " foreach($object->fields as $key => $val) { - $sql.='t.'.$key.', '; + $sql.='t.'.$key.', '; } // Add fields from extrafields if (! empty($extrafields->attributes[$object->table_element]['label'])) { @@ -242,26 +266,24 @@ $sql .= $db->order($sortfield, $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 || empty($limit))) -{ +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -270,8 +292,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/asset/card.php?id='.$id); @@ -302,14 +323,24 @@ jQuery(document).ready(function() { $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ - if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); - else $param .= '&search_'.$key.'='.urlencode($search[$key]); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +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'; @@ -318,12 +349,18 @@ $arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -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 ''."\n"; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -333,7 +370,7 @@ print ''; $newcardbutton = dolGetButtonTitle($langs->trans('NewAsset'), '', 'fa fa-plus-circle', dol_buildpath('/asset/card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); -print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'accountancy', 0, $newcardbutton, '', $limit, 0, 0, 1); +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); // Add code for pre mass action (confirmation or email presend form) $topicmail = "SendAssetsRef"; @@ -342,9 +379,10 @@ $objecttmp = new Asset($db); $trackid = 'asset'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($sall) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } @@ -355,11 +393,13 @@ $moreforfilter.= '';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; @@ -376,20 +416,26 @@ print ''; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; } } @@ -411,15 +457,18 @@ print ''."\n"; // Fields title label // -------------------------------------------------------------------- print ''; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -436,11 +485,11 @@ print ''."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -449,37 +498,50 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->setVarsFromFetchObj($obj); // Show here line of result print ''; - foreach ($object->fields as $key => $val) - { + foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; - if ($key == 'status') print $object->getLibStatut(5); - else print $object->showOutputField($val, $key, $object->$key, ''); + if ($key == 'status') { + print $object->getLibStatut(5); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } print ''; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $object->$key; } } @@ -492,14 +554,17 @@ while ($i < ($limit ? min($num, $limit) : $num)) print $hookmanager->resPrint; // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print ''."\n"; @@ -510,10 +575,13 @@ while ($i < ($limit ? min($num, $limit) : $num)) include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 ''; } @@ -529,10 +597,11 @@ print ''."\n"; print ''."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/asset/note.php b/htdocs/asset/note.php index 514e05bff72..752591ade9e 100644 --- a/htdocs/asset/note.php +++ b/htdocs/asset/note.php @@ -52,10 +52,14 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->asset->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->asset->multidir_output[$object->entity]."/".$object->id; +} // Security check -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'asset', $id); $permissionnote = 1; @@ -79,8 +83,7 @@ $form = new Form($db); $help_url = ''; llxHeader('', $langs->trans('Assets'), $help_url); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = asset_prepare_head($object); @@ -101,35 +104,35 @@ if ($id > 0 || !empty($ref)) // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; - if ($user->rights->asset->creer) - { - if ($action != 'classify') - //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - $morehtmlref.=' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->asset->creer) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.=''; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } }*/ $morehtmlref .= ''; diff --git a/htdocs/asset/type.php b/htdocs/asset/type.php index fecebb676a8..9d7e848b6d3 100644 --- a/htdocs/asset/type.php +++ b/htdocs/asset/type.php @@ -26,9 +26,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/asset.lib.php'; require_once DOL_DOCUMENT_ROOT.'/asset/class/asset.class.php'; require_once DOL_DOCUMENT_ROOT.'/asset/class/asset_type.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +} +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +} +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +} // Load translation files required by the page $langs->load("assets"); @@ -44,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 = "DESC"; } -if (!$sortfield) { $sortfield = "a.label"; } +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "a.label"; +} $label = GETPOST("label", "alpha"); $accountancy_code_asset = GETPOST('accountancy_code_asset', 'string'); @@ -67,8 +79,7 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -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 $type = ""; $sall = ""; } @@ -86,15 +97,13 @@ $permissiontoadd = $user->rights->asset->setup_advance; if ($cancel) { $action = ''; - if (!empty($backtopage)) - { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } } -if ($action == 'add' && $user->rights->asset->write) -{ +if ($action == 'add' && $user->rights->asset->write) { $object->label = trim($label); $object->accountancy_code_asset = trim($accountancy_code_asset); $object->accountancy_code_depreciation_asset = trim($accountancy_code_depreciation_asset); @@ -103,7 +112,9 @@ if ($action == 'add' && $user->rights->asset->write) // 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++; @@ -121,11 +132,9 @@ if ($action == 'add' && $user->rights->asset->write) } } - if (!$error) - { + if (!$error) { $id = $object->create($user); - if ($id > 0) - { + if ($id > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -137,8 +146,7 @@ if ($action == 'add' && $user->rights->asset->write) } } -if ($action == 'update' && $user->rights->asset->write) -{ +if ($action == 'update' && $user->rights->asset->write) { $object->fetch($rowid); $object->oldcopy = clone $object; @@ -151,13 +159,14 @@ if ($action == 'update' && $user->rights->asset->write) // 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); - if ($ret >= 0 && !count($object->errors)) - { - setEventMessages($langs->trans("AssetsTypeModified"), null, 'mesgs'); + if ($ret >= 0 && !count($object->errors)) { + setEventMessages($langs->trans("AssetTypeModified"), null, 'mesgs'); } else { setEventMessages($object->error, $object->errors, 'errors'); } @@ -166,13 +175,11 @@ if ($action == 'update' && $user->rights->asset->write) exit; } -if ($action == 'confirm_delete' && $user->rights->asset->write) -{ +if ($action == 'confirm_delete' && $user->rights->asset->write) { $object->fetch($rowid); $res = $object->delete(); - if ($res > 0) - { + if ($res > 0) { setEventMessages($langs->trans("AssetsTypeDeleted"), null, 'mesgs'); header("Location: ".$_SERVER["PHP_SELF"]); exit; @@ -194,8 +201,7 @@ llxHeader('', $langs->trans("AssetsTypeSetup"), $helpurl); // List of asset type -if (!$rowid && $action != 'create' && $action != 'edit') -{ +if (!$rowid && $action != 'create' && $action != 'edit') { //print dol_get_fiche_head(''); $sql = "SELECT d.rowid, d.label as label, d.accountancy_code_asset, d.accountancy_code_depreciation_asset, d.accountancy_code_depreciation_expense, d.note"; @@ -203,8 +209,7 @@ if (!$rowid && $action != 'create' && $action != 'edit') $sql .= " WHERE d.entity IN (".getEntity('asset_type').")"; $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $nbtotalofrecords = $num; @@ -213,7 +218,9 @@ if (!$rowid && $action != 'create' && $action != 'edit') $param = ''; print ''; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; @@ -223,7 +230,7 @@ if (!$rowid && $action != 'create' && $action != 'edit') $newcardbutton = dolGetButtonTitle($langs->trans('NewAssetType'), '', 'fa fa-plus-circle', dol_buildpath('/asset/type.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); - print_barre_liste($langs->trans("AssetsTypes"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'accountancy', 0, $newcardbutton, '', $limit); + print_barre_liste($langs->trans("AssetsTypes"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, $object->picto, 0, $newcardbutton, '', $limit); $moreforfilter = ''; @@ -241,8 +248,7 @@ if (!$rowid && $action != 'create' && $action != 'edit') $assettype = new AssetType($db); - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($result); $assettype->id = $objp->rowid; @@ -257,8 +263,7 @@ if (!$rowid && $action != 'create' && $action != 'edit') print ''; print ''; print ''; print ''; - if ($user->rights->asset->write) - print ''; - else print ''; + if ($user->rights->asset->write) { + print ''; + } else { + print ''; + } print ""; $i++; } + + // If no record found + if ($num == 0) { + $colspan = 6; + print ''; + } + print "
    '; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - elseif (strpos($val['type'], 'integer:') === 0) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print ''; + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { + print ''; + } print '
    '; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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($object->id, $arrayofselected)) $selected = 1; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } print ''; } print '
    '.$langs->trans("NoRecordFound").'
    '.dol_escape_htmltag($objp->label).''; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $objp->accountancy_code_asset, 1); @@ -269,8 +274,7 @@ if (!$rowid && $action != 'create' && $action != 'edit') print ''; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { $accountingaccount2 = new AccountingAccount($db); $accountingaccount2->fetch('', $objp->accountancy_code_depreciation_asset, 1); @@ -281,8 +285,7 @@ if (!$rowid && $action != 'create' && $action != 'edit') print ''; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { $accountingaccount3 = new AccountingAccount($db); $accountingaccount3->fetch('', $objp->accountancy_code_depreciation_expense, 1); @@ -292,12 +295,21 @@ if (!$rowid && $action != 'create' && $action != 'edit') } print 'rowid.'">'.img_edit().' rowid.'">'.img_edit().' 
    '.$langs->trans("NoRecordFound").'
    "; print ''; @@ -313,12 +325,13 @@ if (!$rowid && $action != 'create' && $action != 'edit') /* Creation mode */ /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { $object = new AssetType($db); - if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); + if (!empty($conf->accounting->enabled)) { + $formaccounting = new FormAccounting($db); + } - print load_fiche_titre($langs->trans("NewAssetType")); + print load_fiche_titre($langs->trans("NewAssetType"), '', $object->picto); print ''; print ''; @@ -331,8 +344,7 @@ if ($action == 'create') print '
    '.$langs->trans("Label").'
    '.$langs->trans("AccountancyCodeAsset").''; @@ -375,8 +387,7 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } print '
    '; + print '
    '; print ''; - print ''; print ''; } - if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; + if ($oldprojectforbreak != -1) { + $oldprojectforbreak = $projectstatic->id; + } print ''."\n"; @@ -1226,30 +1439,36 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr */ // Project - if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) - { + if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { print ""; } // Thirdparty - if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) - { + if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { print ''; } // Ref print '\n"; // TASK extrafields @@ -1258,17 +1477,18 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Planned Workload - if (!empty($arrayfields['t.planned_workload']['checked'])) - { + if (!empty($arrayfields['t.planned_workload']['checked'])) { print ''; } // Progress declared % - if (!empty($arrayfields['t.progress']['checked'])) - { + if (!empty($arrayfields['t.progress']['checked'])) { print ''; @@ -1277,34 +1497,37 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr // Time spent by everybody print '\n"; // Time spent by user print '\n"; - $disabledproject = 1; $disabledtask = 1; + $disabledproject = 1; + $disabledtask = 1; //print "x".$lines[$i]->fk_project; //var_dump($lines[$i]); //var_dump($projectsrole[$lines[$i]->fk_project]); // If at least one role for project - if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) - { + if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) { $disabledproject = 0; $disabledtask = 0; } // If $restricteditformytask is on and I have no role on task, i disable edit - if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) - { + if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) { $disabledtask = 1; } @@ -1315,9 +1538,13 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr print ''; $cssonholiday = ''; - if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayallday '; - elseif (!$isavailable[$preselectedday]['morning']) $cssonholiday .= 'onholidaymorning '; - elseif (!$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; + if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) { + $cssonholiday .= 'onholidayallday '; + } elseif (!$isavailable[$preselectedday]['morning']) { + $cssonholiday .= 'onholidaymorning '; + } elseif (!$isavailable[$preselectedday]['afternoon']) { + $cssonholiday .= 'onholidayafternoon '; + } global $daytoparse; $tmparray = dol_getdate($daytoparse, true); // detail of current day @@ -1325,8 +1552,7 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $idw = ($tmparray['wday'] - (empty($conf->global->MAIN_START_WEEK) ? 0 : 1)); global $numstartworkingday, $numendworkingday; $cssweekend = ''; - if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. - { + if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) { // This is a day is not inside the setup of working days, so we use a week-end css. $cssweekend = 'weekend'; } @@ -1336,7 +1562,9 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $totalforeachday[$preselectedday] += $dayWorkLoad; $alreadyspent = ''; - if ($dayWorkLoad > 0) $alreadyspent = convertSecondToTime($dayWorkLoad, 'allhourmin'); + if ($dayWorkLoad > 0) { + $alreadyspent = convertSecondToTime($dayWorkLoad, 'allhourmin'); + } $idw = 0; @@ -1366,14 +1594,16 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr // Warning print ''; print "\n"; @@ -1381,15 +1611,13 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $inc++; $level++; - if ($lines[$i]->id > 0) - { + if ($lines[$i]->id > 0) { //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level); //var_dump($totalforeachday); $ret = projectLinesPerDay($inc, $lines[$i]->id, $fuser, ($parent == 0 ? $lineswithoutlevel0 : $lines), $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday, $isavailable, $oldprojectforbreak, $arrayfields, $extrafields); //var_dump('ret with parent='.$lines[$i]->id.' level='.$level); //var_dump($ret); - foreach ($ret as $key => $val) - { + foreach ($ret as $key => $val) { $totalforeachday[$key] += $val; } //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level.' + subtasks'); @@ -1437,50 +1665,45 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ $lineswithoutlevel0 = array(); // Create a smaller array with sublevels only to be used later. This increase dramatically performances. - if ($parent == 0) // Always and only if at first level - { - for ($i = 0; $i < $numlines; $i++) - { - if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i]; + if ($parent == 0) { // Always and only if at first level + for ($i = 0; $i < $numlines; $i++) { + if ($lines[$i]->fk_task_parent) { + $lineswithoutlevel0[] = $lines[$i]; + } } } //dol_syslog('projectLinesPerWeek inc='.$inc.' firstdaytoshow='.$firstdaytoshow.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); - if (empty($oldprojectforbreak)) - { + if (empty($oldprojectforbreak)) { $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : -1); // 0 = start break, -1 = never break } - for ($i = 0; $i < $numlines; $i++) - { - if ($parent == 0) $level = 0; + for ($i = 0; $i < $numlines; $i++) { + if ($parent == 0) { + $level = 0; + } - if ($lines[$i]->fk_task_parent == $parent) - { + if ($lines[$i]->fk_task_parent == $parent) { $obj = &$lines[$i]; // To display extrafields // If we want all or we have a role on task, we show it - if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) - { + if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) { //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); - if ($restricteditformytask == 2 && empty($tasksrole[$lines[$i]->id])) // we have no role on task and we request to hide such cases - { + if ($restricteditformytask == 2 && empty($tasksrole[$lines[$i]->id])) { // we have no role on task and we request to hide such cases continue; } // Break on a new project - if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) - { + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) { $lastprojectid = $lines[$i]->fk_project; $projectstatic->id = $lines[$i]->fk_project; } //var_dump('--- '.$level.' '.$firstdaytoshow.' '.$fuser->id.' '.$projectstatic->id.' '.$workloadforid[$projectstatic->id]); //var_dump($projectstatic->weekWorkLoadPerTask); - if (empty($workloadforid[$projectstatic->id])) - { + if (empty($workloadforid[$projectstatic->id])) { $projectstatic->loadTimeSpent($firstdaytoshow, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week $workloadforid[$projectstatic->id] = 1; } @@ -1504,22 +1727,27 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ $thirdpartystatic->name = $lines[$i]->thirdparty_name; $thirdpartystatic->email = $lines[$i]->thirdparty_email; - if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) - { + if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) { $addcolspan = 0; - if (!empty($arrayfields['t.planned_workload']['checked'])) $addcolspan++; - if (!empty($arrayfields['t.progress']['checked'])) $addcolspan++; - foreach ($arrayfields as $key => $val) - { - if ($val['checked'] && substr($key, 0, 5) == 'efpt.') $addcolspan++; + if (!empty($arrayfields['t.planned_workload']['checked'])) { + $addcolspan++; + } + if (!empty($arrayfields['t.progress']['checked'])) { + $addcolspan++; + } + foreach ($arrayfields as $key => $val) { + if ($val['checked'] && substr($key, 0, 5) == 'efpt.') { + $addcolspan++; + } } print ''."\n"; print ''; // PROJECT fields - if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center '); + if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right '); - $extrafieldsobjectkey='projet'; - $extrafieldsobjectprefix='efp.'; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; + $extrafieldsobjectkey='projet'; + $extrafieldsobjectprefix='efp.'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; - print ''; - print ''; + print ''; + print ''; - // PROJECT fields - if (! empty($arrayfields['p.fk_opp_status']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['p.opp_amount']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['p.opp_percent']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['p.budget_amount']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['p.usage_bill_time']['checked'])) - { - print '\n"; - } + // PROJECT fields + if (! empty($arrayfields['p.fk_opp_status']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['p.opp_amount']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['p.opp_percent']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['p.budget_amount']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['p.usage_bill_time']['checked'])) + { + print '\n"; + } - $extrafieldsobjectkey='projet'; - $extrafieldsobjectprefix='efp.'; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + $extrafieldsobjectkey='projet'; + $extrafieldsobjectprefix='efp.'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - print ''; - print '
    '; + print ''; print $langs->trans("AccountancyCodeAsset"); print ''; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->accountancy_code_asset, 1); @@ -453,8 +460,7 @@ if ($rowid > 0) print ''; print $langs->trans("AccountancyCodeDepreciationAsset"); print ''; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { $accountingaccount2 = new AccountingAccount($db); $accountingaccount2->fetch('', $object->accountancy_code_depreciation_asset, 1); @@ -469,8 +475,7 @@ if ($rowid > 0) print ''; print $langs->trans("AccountancyCodeDepreciationExpense"); print ''; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { $accountingaccount3 = new AccountingAccount($db); $accountingaccount3->fetch('', $object->accountancy_code_depreciation_expense, 1); @@ -499,14 +504,12 @@ if ($rowid > 0) print '
    '; // Edit - if ($user->rights->asset->write) - { + if ($user->rights->asset->write) { print ''; } // Delete - if ($user->rights->asset->write) - { + if ($user->rights->asset->write) { print ''; } @@ -519,12 +522,13 @@ if ($rowid > 0) /* */ /* ************************************************************************** */ - if ($action == 'edit') - { + if ($action == 'edit') { $object = new AssetType($db); $object->fetch($rowid); $object->fetch_optionals(); - if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); + if (!empty($conf->accounting->enabled)) { + $formaccounting = new FormAccounting($db); + } $head = asset_type_prepare_head($object); @@ -537,12 +541,11 @@ if ($rowid > 0) print ''; - print ''; + print ''; print ''; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { // Accountancy_code_asset print ''; print ''; print ''; + if ("$val" != $lastkey[$level] && !$subcount) { + print ''; + } } return 1; } diff --git a/htdocs/core/lib/loan.lib.php b/htdocs/core/lib/loan.lib.php index 3a34d3e57c4..c86d0ecce13 100644 --- a/htdocs/core/lib/loan.lib.php +++ b/htdocs/core/lib/loan.lib.php @@ -60,7 +60,9 @@ function loan_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$tab][0] = DOL_URL_ROOT.'/loan/document.php?id='.$object->id; $head[$tab][1] = $langs->trans("Documents"); - if (($nbFiles + $nbLinks) > 0) $head[$tab][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$tab][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$tab][2] = 'documents'; $tab++; @@ -68,7 +70,9 @@ function loan_prepare_head($object) $nbNote = (empty($object->note_private) ? 0 : 1) + (empty($object->note_public) ? 0 : 1); $head[$tab][0] = DOL_URL_ROOT."/loan/note.php?id=".$object->id; $head[$tab][1] = $langs->trans("Notes"); - if ($nbNote > 0) $head[$tab][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$tab][1] .= ''.$nbNote.''; + } $head[$tab][2] = 'note'; $tab++; } diff --git a/htdocs/core/lib/member.lib.php b/htdocs/core/lib/member.lib.php index 50330686805..93378d77390 100644 --- a/htdocs/core/lib/member.lib.php +++ b/htdocs/core/lib/member.lib.php @@ -43,8 +43,7 @@ function member_prepare_head(Adherent $object) $h++; if ((!empty($conf->ldap->enabled) && !empty($conf->global->LDAP_MEMBER_ACTIVE)) - && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || !empty($user->admin))) - { + && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || !empty($user->admin))) { $langs->load("ldap"); $head[$h][0] = DOL_URL_ROOT.'/adherents/ldap.php?id='.$object->id; @@ -53,13 +52,14 @@ function member_prepare_head(Adherent $object) $h++; } - if (!empty($user->rights->adherent->cotisation->lire)) - { + if (!empty($user->rights->adherent->cotisation->lire)) { $nbSubscription = is_array($object->subscriptions) ?count($object->subscriptions) : 0; $head[$h][0] = DOL_URL_ROOT.'/adherents/subscription.php?rowid='.$object->id; $head[$h][1] = $langs->trans("Subscriptions"); $head[$h][2] = 'subscription'; - if ($nbSubscription > 0) $head[$h][1] .= ''.$nbSubscription.''; + if ($nbSubscription > 0) { + $head[$h][1] .= ''.$nbSubscription.''; + } $h++; } @@ -70,13 +70,21 @@ function member_prepare_head(Adherent $object) complete_head_from_modules($conf, $langs, $object, $head, $h, 'member'); $nbNote = 0; - if (!empty($object->note)) $nbNote++; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note)) { + $nbNote++; + } + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/adherents/note.php?id='.$object->id; $head[$h][1] = $langs->trans("Note"); $head[$h][2] = 'note'; - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $h++; // Attachments @@ -87,17 +95,17 @@ function member_prepare_head(Adherent $object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/adherents/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'document'; $h++; // Show agenda tab - if (!empty($conf->agenda->enabled)) - { + if (!empty($conf->agenda->enabled)) { $head[$h][0] = DOL_URL_ROOT."/adherents/agenda.php?id=".$object->id; $head[$h][1] = $langs->trans("Events"); - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $head[$h][1] .= '/'; $head[$h][1] .= $langs->trans("Agenda"); } @@ -129,8 +137,7 @@ function member_type_prepare_head(AdherentType $object) $h++; // Multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { $head[$h][0] = DOL_URL_ROOT."/adherents/type_translation.php?rowid=".$object->id; $head[$h][1] = $langs->trans("Translation"); $head[$h][2] = 'translation'; @@ -138,8 +145,7 @@ function member_type_prepare_head(AdherentType $object) } if ((!empty($conf->ldap->enabled) && !empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE)) - && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || !empty($user->admin))) - { + && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || !empty($user->admin))) { $langs->load("ldap"); $head[$h][0] = DOL_URL_ROOT.'/adherents/type_ldap.php?rowid='.$object->id; diff --git a/htdocs/core/lib/memory.lib.php b/htdocs/core/lib/memory.lib.php index 7b863391b24..1300c1b771f 100644 --- a/htdocs/core/lib/memory.lib.php +++ b/htdocs/core/lib/memory.lib.php @@ -1,5 +1,6 @@ + * 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 @@ -23,11 +24,34 @@ global $shmkeys, $shmoffset; -$shmkeys = array('main'=>1, 'admin'=>2, 'dict'=>3, 'companies'=>4, 'suppliers'=>5, 'products'=>6, - 'commercial'=>7, 'compta'=>8, 'projects'=>9, 'cashdesk'=>10, 'agenda'=>11, 'bills'=>12, - 'propal'=>13, 'boxes'=>14, 'banks'=>15, 'other'=>16, 'errors'=>17, 'members'=>18, 'ecm'=>19, - 'orders'=>20, 'users'=>21, 'help'=>22, 'stocks'=>23, 'interventions'=>24, - 'donations'=>25, 'contracts'=>26); +$shmkeys = array( + 'main' => 1, + 'admin' => 2, + 'dict' => 3, + 'companies' => 4, + 'suppliers' => 5, + 'products' => 6, + 'commercial' => 7, + 'compta' => 8, + 'projects' => 9, + 'cashdesk' => 10, + 'agenda' => 11, + 'bills' => 12, + 'propal' => 13, + 'boxes' => 14, + 'banks' => 15, + 'other' => 16, + 'errors' => 17, + 'members' => 18, + 'ecm' => 19, + 'orders' => 20, + 'users' => 21, + 'help' => 22, + 'stocks' => 23, + 'interventions' => 24, + 'donations' => 25, + 'contracts' => 26, +); $shmoffset = 1000; // Max number of entries found into a language file. If too low, some entries will be overwritten. @@ -36,60 +60,66 @@ $shmoffset = 1000; // Max number of entries found into a language file. If too l * Save data into a memory area shared by all users, all sessions on server * * @param string $memoryid Memory id of shared area - * @param string $data Data to save - * @return int <0 if KO, Nb of bytes written if OK + * @param mixed $data Data to save. It must not be a null value. + * @param int $expire ttl in seconds, 0 never expire + * @return int <0 if KO, 0 if nothing is done, Nb of bytes written if OK + * @see dol_getcache() */ -function dol_setcache($memoryid, $data) +function dol_setcache($memoryid, $data, $expire = 0) { global $conf; $result = 0; - // Using a memcached server - if (!empty($conf->memcached->enabled) && class_exists('Memcached')) - { - global $dolmemcache; - if (empty($dolmemcache) || !is_object($dolmemcache)) - { - $dolmemcache = new Memcached(); - $tmparray = explode(':', $conf->global->MEMCACHED_SERVER); - $result = $dolmemcache->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211); - if (!$result) return -1; - } + if (strpos($memoryid, 'count_') === 0) { // The memoryid key start with 'count_...' + if (empty($conf->global->MAIN_CACHE_COUNT)) { + return 0; + } + } - $memoryid = session_name().'_'.$memoryid; + if (!empty($conf->memcached->enabled) && class_exists('Memcached')) { + // Using a memcached server + global $dolmemcache; + if (empty($dolmemcache) || !is_object($dolmemcache)) { + $dolmemcache = new Memcached(); + $tmparray = explode(':', $conf->global->MEMCACHED_SERVER); + $result = $dolmemcache->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211); + if (!$result) { + return -1; + } + } + + $memoryid = session_name() . '_' . $memoryid; //$dolmemcache->setOption(Memcached::OPT_COMPRESSION, false); - $dolmemcache->add($memoryid, $data); // This fails if key already exists + $dolmemcache->add($memoryid, $data, $expire); // This fails if key already exists $rescode = $dolmemcache->getResultCode(); - if ($rescode == 0) - { - return count($data); + if ($rescode == 0) { + return is_countable($data) ? count($data) : 0; } else { return -$rescode; } - } elseif (!empty($conf->memcached->enabled) && class_exists('Memcache')) - { + } elseif (!empty($conf->memcached->enabled) && class_exists('Memcache')) { // This is a really not reliable cache ! Use Memcached instead. + // Using a memcache server global $dolmemcache; - if (empty($dolmemcache) || !is_object($dolmemcache)) - { - $dolmemcache = new Memcache(); - $tmparray = explode(':', $conf->global->MEMCACHED_SERVER); - $result = $dolmemcache->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211); - if (!$result) return -1; - } + if (empty($dolmemcache) || !is_object($dolmemcache)) { + $dolmemcache = new Memcache(); + $tmparray = explode(':', $conf->global->MEMCACHED_SERVER); + $result = $dolmemcache->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211); + if (!$result) { + return -1; + } + } - $memoryid = session_name().'_'.$memoryid; + $memoryid = session_name() . '_' . $memoryid; //$dolmemcache->setOption(Memcached::OPT_COMPRESSION, false); - $result = $dolmemcache->add($memoryid, $data); // This fails if key already exists - if ($result) - { - return count($data); + $result = $dolmemcache->add($memoryid, $data, false, $expire); // This fails if key already exists + if ($result) { + return is_countable($data) ? count($data) : 0; } else { return -1; } - } // Using shmop - elseif (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) - { - $result = dol_setshmop($memoryid, $data); + } elseif (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) { // This is a really not reliable cache ! Use Memcached instead. + // Using shmop + $result = dol_setshmop($memoryid, $data, $expire); } return $result; @@ -99,67 +129,73 @@ function dol_setcache($memoryid, $data) * Read a memory area shared by all users, all sessions on server * * @param string $memoryid Memory id of shared area - * @return int <0 if KO, data if OK + * @return int|mixed <0 if KO, data if OK, null if not found into cache or no caching feature enabled + * @see dol_setcache() */ function dol_getcache($memoryid) { global $conf; - // Using a memcached server - if (!empty($conf->memcached->enabled) && class_exists('Memcached')) - { - global $m; - if (empty($m) || !is_object($m)) - { - $m = new Memcached(); - $tmparray = explode(':', $conf->global->MEMCACHED_SERVER); - $result = $m->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211); - if (!$result) return -1; - } + if (strpos($memoryid, 'count_') === 0) { // The memoryid key start with 'count_...' + if (empty($conf->global->MAIN_CACHE_COUNT)) { + return null; + } + } - $memoryid = session_name().'_'.$memoryid; + // Using a memcached server + if (!empty($conf->memcached->enabled) && class_exists('Memcached')) { + global $m; + if (empty($m) || !is_object($m)) { + $m = new Memcached(); + $tmparray = explode(':', $conf->global->MEMCACHED_SERVER); + $result = $m->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211); + if (!$result) { + return -1; + } + } + + $memoryid = session_name() . '_' . $memoryid; //$m->setOption(Memcached::OPT_COMPRESSION, false); //print "Get memoryid=".$memoryid; $data = $m->get($memoryid); $rescode = $m->getResultCode(); - //print "memoryid=".$memoryid." - rescode=".$rescode." - data=".count($data)."\n
    "; + //print "memoryid=".$memoryid." - rescode=".$rescode." - count(response)=".count($data)."\n
    "; //var_dump($data); - if ($rescode == 0) - { + if ($rescode == 0) { return $data; + } elseif ($rescode == 16) { // = Memcached::MEMCACHED_NOTFOUND but this constant doe snot exists. + return null; } else { return -$rescode; } - } elseif (!empty($conf->memcached->enabled) && class_exists('Memcache')) - { + } elseif (!empty($conf->memcached->enabled) && class_exists('Memcache')) { // This is a really not reliable cache ! Use Memcached instead. global $m; - if (empty($m) || !is_object($m)) - { - $m = new Memcache(); - $tmparray = explode(':', $conf->global->MEMCACHED_SERVER); - $result = $m->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211); - if (!$result) return -1; - } + if (empty($m) || !is_object($m)) { + $m = new Memcache(); + $tmparray = explode(':', $conf->global->MEMCACHED_SERVER); + $result = $m->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211); + if (!$result) { + return -1; + } + } - $memoryid = session_name().'_'.$memoryid; + $memoryid = session_name() . '_' . $memoryid; //$m->setOption(Memcached::OPT_COMPRESSION, false); $data = $m->get($memoryid); //print "memoryid=".$memoryid." - rescode=".$rescode." - data=".count($data)."\n
    "; //var_dump($data); - if ($data) - { + if ($data) { return $data; } else { - return -1; + return null; // There is no way to make a difference between NOTFOUND and error when using Memcache. So do not use it, use Memcached instead. } - } // Using shmop - elseif (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) - { + } elseif (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) { // This is a really not reliable cache ! Use Memcached instead. + // Using shmop $data = dol_getshmop($memoryid); return $data; } - return 0; + return null; } @@ -173,7 +209,9 @@ function dol_getcache($memoryid) function dol_getshmopaddress($memoryid) { global $shmkeys, $shmoffset; - if (empty($shmkeys[$memoryid])) return 0; + if (empty($shmkeys[$memoryid])) { // No room reserved for thid memoryid, no way to use cache + return 0; + } return $shmkeys[$memoryid] + $shmoffset; } @@ -187,10 +225,11 @@ function dol_listshmop() global $shmkeys, $shmoffset; $resarray = array(); - foreach ($shmkeys as $key => $val) - { + foreach ($shmkeys as $key => $val) { $result = dol_getshmop($key); - if (!is_numeric($result) || $result > 0) $resarray[$key] = $result; + if (!is_numeric($result) || $result > 0) { + $resarray[$key] = $result; + } } return $resarray; } @@ -199,32 +238,37 @@ function dol_listshmop() * Save data into a memory area shared by all users, all sessions on server * * @param int $memoryid Memory id of shared area ('main', 'agenda', ...) - * @param string $data Data to save - * @return int <0 if KO, Nb of bytes written if OK + * @param string $data Data to save. Must be a not null value. + * @param int $expire ttl in seconds, 0 never expire + * @return int <0 if KO, 0=Caching not available, Nb of bytes written if OK */ -function dol_setshmop($memoryid, $data) +function dol_setshmop($memoryid, $data, $expire) { global $shmkeys, $shmoffset; //print 'dol_setshmop memoryid='.$memoryid."
    \n"; - if (empty($shmkeys[$memoryid]) || !function_exists("shmop_write")) return 0; + if (empty($shmkeys[$memoryid]) || !function_exists("shmop_write")) { + return 0; + } $shmkey = dol_getshmopaddress($memoryid); + if (empty($shmkey)) { + return 0; // No key reserved for this memoryid, we can't cache this memoryid + } + $newdata = serialize($data); $size = strlen($newdata); //print 'dol_setshmop memoryid='.$memoryid." shmkey=".$shmkey." newdata=".$size."bytes
    \n"; $handle = shmop_open($shmkey, 'c', 0644, 6 + $size); - if ($handle) - { + if ($handle) { $shm_bytes_written1 = shmop_write($handle, str_pad($size, 6), 0); $shm_bytes_written2 = shmop_write($handle, $newdata, 6); - if (($shm_bytes_written1 + $shm_bytes_written2) != (6 + dol_strlen($newdata))) - { - print "Couldn't write the entire length of data\n"; + if (($shm_bytes_written1 + $shm_bytes_written2) != (6 + dol_strlen($newdata))) { + print "Couldn't write the entire length of data\n"; } shmop_close($handle); return ($shm_bytes_written1 + $shm_bytes_written2); } else { - print 'Error in shmop_open for memoryid='.$memoryid.' shmkey='.$shmkey.' 6+size=6+'.$size; + print 'Error in shmop_open for memoryid=' . $memoryid . ' shmkey=' . $shmkey . ' 6+size=6+' . $size; return -1; } } @@ -233,24 +277,34 @@ function dol_setshmop($memoryid, $data) * Read a memory area shared by all users, all sessions on server * * @param string $memoryid Memory id of shared area ('main', 'agenda', ...) - * @return int <0 if KO, data if OK + * @return int <0 if KO, data if OK, Null if no cache enabled or not found */ function dol_getshmop($memoryid) { global $shmkeys, $shmoffset; - if (empty($shmkeys[$memoryid]) || !function_exists("shmop_open")) return 0; + $data = null; + + if (empty($shmkeys[$memoryid]) || !function_exists("shmop_open")) { + return null; + } $shmkey = dol_getshmopaddress($memoryid); + if (empty($shmkey)) { + return null; // No key reserved for this memoryid, we can't cache this memoryid + } + //print 'dol_getshmop memoryid='.$memoryid." shmkey=".$shmkey."
    \n"; $handle = @shmop_open($shmkey, 'a', 0, 0); - if ($handle) - { + if ($handle) { $size = trim(shmop_read($handle, 0, 6)); - if ($size) $data = unserialize(shmop_read($handle, 6, $size)); - else return -1; + if ($size) { + $data = unserialize(shmop_read($handle, 6, $size)); + } else { + return -1; + } shmop_close($handle); } else { - return -2; + return null; // Can't open existing block, so we suppose it was not created, so nothing were cached yet for the memoryid } return $data; } diff --git a/htdocs/core/lib/modulebuilder.lib.php b/htdocs/core/lib/modulebuilder.lib.php index ff14ec56e18..85a16ac47cf 100644 --- a/htdocs/core/lib/modulebuilder.lib.php +++ b/htdocs/core/lib/modulebuilder.lib.php @@ -22,8 +22,6 @@ */ - - /** * Regenerate files .class.php * @@ -41,31 +39,30 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = { global $db, $langs; - if (empty($objectname)) return -1; - if (empty($readdir)) $readdir = $destdir; + if (empty($objectname)) { + return -1; + } + if (empty($readdir)) { + $readdir = $destdir; + } - if (!empty($addfieldentry['arrayofkeyval']) && !is_array($addfieldentry['arrayofkeyval'])) - { + if (!empty($addfieldentry['arrayofkeyval']) && !is_array($addfieldentry['arrayofkeyval'])) { dol_print_error('', 'Bad parameter addfieldentry with a property arrayofkeyval defined but that is not an array.'); return -1; } // Check parameters - if (count($addfieldentry) > 0) - { - if (empty($addfieldentry['name'])) - { + if (is_array($addfieldentry) && count($addfieldentry) > 0) { + if (empty($addfieldentry['name'])) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Name")), null, 'errors'); return -2; } - if (empty($addfieldentry['label'])) - { + if (empty($addfieldentry['label'])) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Label")), null, 'errors'); return -2; } if (!preg_match('/^(integer|price|sellist|varchar|double|text|html|duration)/', $addfieldentry['type']) - && !preg_match('/^(boolean|real|date|datetime|timestamp)$/', $addfieldentry['type'])) - { + && !preg_match('/^(boolean|real|date|datetime|timestamp)$/', $addfieldentry['type'])) { setEventMessages($langs->trans('BadValueForType', $objectname), null, 'errors'); return -2; } @@ -73,8 +70,7 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = $pathoffiletoeditsrc = $readdir.'/class/'.strtolower($objectname).'.class.php'; $pathoffiletoedittarget = $destdir.'/class/'.strtolower($objectname).'.class.php'.($readdir != $destdir ? '.new' : ''); - if (!dol_is_file($pathoffiletoeditsrc)) - { + if (!dol_is_file($pathoffiletoeditsrc)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors'); return -3; @@ -85,8 +81,11 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = try { include_once $pathoffiletoeditsrc; - if (class_exists($objectname)) $object = new $objectname($db); - else return -4; + if (class_exists($objectname)) { + $object = new $objectname($db); + } else { + return -4; + } // Backup old file dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1); @@ -95,17 +94,14 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = $contentclass = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r'); // Update ->fields (add or remove entries) - if (count($object->fields)) - { - if (is_array($addfieldentry) && count($addfieldentry)) - { + if (count($object->fields)) { + if (is_array($addfieldentry) && count($addfieldentry)) { $name = $addfieldentry['name']; unset($addfieldentry['name']); $object->fields[$name] = $addfieldentry; } - if (!empty($delfieldentry)) - { + if (!empty($delfieldentry)) { $name = $delfieldentry; unset($object->fields[$name]); } @@ -120,40 +116,62 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = $texttoinsert .= "\t".' */'."\n"; $texttoinsert .= "\t".'public $fields=array('."\n"; - if (count($object->fields)) - { - foreach ($object->fields as $key => $val) - { + if (count($object->fields)) { + foreach ($object->fields as $key => $val) { $i++; $texttoinsert .= "\t\t'".$key."' => array('type'=>'".$val['type']."', 'label'=>'".$val['label']."',"; $texttoinsert .= " 'enabled'=>'".($val['enabled'] !== '' ? $val['enabled'] : 1)."',"; $texttoinsert .= " 'position'=>".($val['position'] !== '' ? $val['position'] : 50).","; $texttoinsert .= " 'notnull'=>".(empty($val['notnull']) ? 0 : $val['notnull']).","; $texttoinsert .= " 'visible'=>".($val['visible'] !== '' ? $val['visible'] : -1).","; - if ($val['noteditable']) $texttoinsert .= " 'noteditable'=>'".$val['noteditable']."',"; - if ($val['default'] || $val['default'] === '0') $texttoinsert .= " 'default'=>'".$val['default']."',"; - if ($val['index']) $texttoinsert .= " 'index'=>".$val['index'].","; - if ($val['foreignkey']) $texttoinsert .= " 'foreignkey'=>'".$val['foreignkey']."',"; - if ($val['searchall']) $texttoinsert .= " 'searchall'=>".$val['searchall'].","; - if ($val['isameasure']) $texttoinsert .= " 'isameasure'=>'".$val['isameasure']."',"; - if ($val['css']) $texttoinsert .= " 'css'=>'".$val['css']."',"; - if ($val['help']) $texttoinsert .= " 'help'=>\"".preg_replace('/"/', '', $val['help'])."\","; - if ($val['showoncombobox']) $texttoinsert .= " 'showoncombobox'=>'".$val['showoncombobox']."',"; - if ($val['disabled']) $texttoinsert .= " 'disabled'=>'".$val['disabled']."',"; - if ($val['autofocusoncreate']) $texttoinsert .= " 'autofocusoncreate'=>'".$val['autofocusoncreate']."',"; - if ($val['arrayofkeyval']) - { + if ($val['noteditable']) { + $texttoinsert .= " 'noteditable'=>'".$val['noteditable']."',"; + } + if ($val['default'] || $val['default'] === '0') { + $texttoinsert .= " 'default'=>'".$val['default']."',"; + } + if ($val['index']) { + $texttoinsert .= " 'index'=>".$val['index'].","; + } + if ($val['foreignkey']) { + $texttoinsert .= " 'foreignkey'=>'".$val['foreignkey']."',"; + } + if ($val['searchall']) { + $texttoinsert .= " 'searchall'=>".$val['searchall'].","; + } + if ($val['isameasure']) { + $texttoinsert .= " 'isameasure'=>'".$val['isameasure']."',"; + } + if ($val['css']) { + $texttoinsert .= " 'css'=>'".$val['css']."',"; + } + if ($val['help']) { + $texttoinsert .= " 'help'=>\"".preg_replace('/"/', '', $val['help'])."\","; + } + if ($val['showoncombobox']) { + $texttoinsert .= " 'showoncombobox'=>'".$val['showoncombobox']."',"; + } + if ($val['disabled']) { + $texttoinsert .= " 'disabled'=>'".$val['disabled']."',"; + } + if ($val['autofocusoncreate']) { + $texttoinsert .= " 'autofocusoncreate'=>'".$val['autofocusoncreate']."',"; + } + if ($val['arrayofkeyval']) { $texttoinsert .= " 'arrayofkeyval'=>array("; $i = 0; - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { - if ($i) $texttoinsert .= ", "; + foreach ($val['arrayofkeyval'] as $key2 => $val2) { + if ($i) { + $texttoinsert .= ", "; + } $texttoinsert .= "'".$key2."'=>'".$val2."'"; $i++; } $texttoinsert .= "),"; } - if ($val['comment']) $texttoinsert .= " 'comment'=>\"".preg_replace('/"/', '', $val['comment'])."\""; + if ($val['comment']) { + $texttoinsert .= " 'comment'=>\"".preg_replace('/"/', '', $val['comment'])."\""; + } $texttoinsert .= "),\n"; } @@ -162,12 +180,10 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = $texttoinsert .= "\t".');'."\n"; //print ($texttoinsert);exit; - if (count($object->fields)) - { + if (count($object->fields)) { //$typetotypephp=array('integer'=>'integer', 'duration'=>'integer', 'varchar'=>'string'); - foreach ($object->fields as $key => $val) - { + foreach ($object->fields as $key => $val) { $i++; //$typephp=$typetotypephp[$val['type']]; $texttoinsert .= "\t".'public $'.$key.";"; @@ -192,8 +208,7 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = @chmod($pathoffiletoedittarget, octdec($newmask)); return $object; - } catch (Exception $e) - { + } catch (Exception $e) { print $e->getMessage(); return -5; } @@ -218,8 +233,12 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' $error = 0; - if (empty($objectname)) return -1; - if (empty($readdir)) $readdir = $destdir; + if (empty($objectname)) { + return -1; + } + if (empty($readdir)) { + $readdir = $destdir; + } $pathoffiletoclasssrc = $readdir.'/class/'.strtolower($objectname).'.class.php'; @@ -232,8 +251,7 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' $pathoffiletoedittarget = $destdir.'/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.sql'.($readdir != $destdir ? '.new' : ''); } - if (!dol_is_file($pathoffiletoeditsrc)) - { + if (!dol_is_file($pathoffiletoeditsrc)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors'); return -1; @@ -241,14 +259,15 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' // Load object from myobject.class.php try { - if (!is_object($object)) - { + if (!is_object($object)) { include_once $pathoffiletoclasssrc; - if (class_exists($objectname)) $object = new $objectname($db); - else return -1; + if (class_exists($objectname)) { + $object = new $objectname($db); + } else { + return -1; + } } - } catch (Exception $e) - { + } catch (Exception $e) { print $e->getMessage(); } @@ -259,31 +278,41 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' $i = 0; $texttoinsert = '-- BEGIN MODULEBUILDER FIELDS'."\n"; - if (count($object->fields)) - { - foreach ($object->fields as $key => $val) - { + if (count($object->fields)) { + foreach ($object->fields as $key => $val) { $i++; $type = $val['type']; $type = preg_replace('/:.*$/', '', $type); // For case type = 'integer:Societe:societe/class/societe.class.php' - if ($type == 'html') $type = 'text'; // html modulebuilder type is a text type in database - elseif ($type == 'price') $type = 'double'; // html modulebuilder type is a text type in database - elseif (in_array($type, array('link', 'sellist', 'duration'))) $type = 'integer'; + if ($type == 'html') { + $type = 'text'; // html modulebuilder type is a text type in database + } elseif ($type == 'price') { + $type = 'double'; // html modulebuilder type is a text type in database + } elseif (in_array($type, array('link', 'sellist', 'duration'))) { + $type = 'integer'; + } $texttoinsert .= "\t".$key." ".$type; - if ($key == 'rowid') $texttoinsert .= ' AUTO_INCREMENT PRIMARY KEY'; - if ($key == 'entity') $texttoinsert .= ' DEFAULT 1'; - else { - if ($val['default'] != '') - { - if (preg_match('/^null$/i', $val['default'])) $texttoinsert .= " DEFAULT NULL"; - elseif (preg_match('/varchar/', $type)) $texttoinsert .= " DEFAULT '".$db->escape($val['default'])."'"; - else $texttoinsert .= (($val['default'] > 0) ? ' DEFAULT '.$val['default'] : ''); + if ($key == 'rowid') { + $texttoinsert .= ' AUTO_INCREMENT PRIMARY KEY'; + } + if ($key == 'entity') { + $texttoinsert .= ' DEFAULT 1'; + } else { + if ($val['default'] != '') { + if (preg_match('/^null$/i', $val['default'])) { + $texttoinsert .= " DEFAULT NULL"; + } elseif (preg_match('/varchar/', $type)) { + $texttoinsert .= " DEFAULT '".$db->escape($val['default'])."'"; + } else { + $texttoinsert .= (($val['default'] > 0) ? ' DEFAULT '.$val['default'] : ''); + } } } $texttoinsert .= (($val['notnull'] > 0) ? ' NOT NULL' : ''); - if ($i < count($object->fields)) $texttoinsert .= ", "; + if ($i < count($object->fields)) { + $texttoinsert .= ", "; + } $texttoinsert .= "\n"; } } @@ -292,8 +321,7 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' $contentsql = preg_replace('/-- BEGIN MODULEBUILDER FIELDS.*END MODULEBUILDER FIELDS/ims', $texttoinsert, $contentsql); $result = file_put_contents($pathoffiletoedittarget, $contentsql); - if ($result) - { + if ($result) { @chmod($pathoffiletoedittarget, octdec($newmask)); } else { $error++; @@ -312,21 +340,16 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' $i = 0; $texttoinsert = '-- BEGIN MODULEBUILDER INDEXES'."\n"; - if (count($object->fields)) - { - foreach ($object->fields as $key => $val) - { + if (count($object->fields)) { + foreach ($object->fields as $key => $val) { $i++; - if (!empty($val['index'])) - { + if (!empty($val['index'])) { $texttoinsert .= "ALTER TABLE llx_".strtolower($module).'_'.strtolower($objectname)." ADD INDEX idx_".strtolower($module).'_'.strtolower($objectname)."_".$key." (".$key.");"; $texttoinsert .= "\n"; } - if (!empty($val['foreignkey'])) - { + if (!empty($val['foreignkey'])) { $tmp = explode('.', $val['foreignkey']); - if (!empty($tmp[0]) && !empty($tmp[1])) - { + if (!empty($tmp[0]) && !empty($tmp[1])) { $texttoinsert .= "ALTER TABLE llx_".strtolower($module).'_'.strtolower($objectname)." ADD CONSTRAINT llx_".strtolower($module).'_'.strtolower($objectname)."_".$key." FOREIGN KEY (".$key.") REFERENCES llx_".preg_replace('/^llx_/', '', $tmp[0])."(".$tmp[1].");"; $texttoinsert .= "\n"; } @@ -340,8 +363,7 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' dol_mkdir(dirname($pathoffiletoedittarget)); $result2 = file_put_contents($pathoffiletoedittarget, $contentsql); - if ($result) - { + if ($result) { @chmod($pathoffiletoedittarget, octdec($newmask)); } else { $error++; diff --git a/htdocs/core/lib/multicurrency.lib.php b/htdocs/core/lib/multicurrency.lib.php index a3f7d56ec90..e77a9ee8081 100644 --- a/htdocs/core/lib/multicurrency.lib.php +++ b/htdocs/core/lib/multicurrency.lib.php @@ -65,8 +65,7 @@ function multicurrencyLimitPrepareHead($aCurrencies) $i = 0; $head = array(); - foreach ($aCurrencies as $currency) - { + foreach ($aCurrencies as $currency) { $head[$i][0] = $_SERVER['PHP_SELF'].'?currencycode='.$currency; $head[$i][1] = $langs->trans("Currency".$currency).' ('.$langs->getCurrencySymbol($currency).')'; $head[$i][2] = $currency; diff --git a/htdocs/core/lib/oauth.lib.php b/htdocs/core/lib/oauth.lib.php index a006aad8964..48356868143 100644 --- a/htdocs/core/lib/oauth.lib.php +++ b/htdocs/core/lib/oauth.lib.php @@ -27,8 +27,7 @@ $supportedoauth2array = array( 'OAUTH_GOOGLE_NAME'=>'google', ); -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) -{ +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { $supportedoauth2array['OAUTH_STRIPE_TEST_NAME'] = 'stripetest'; $supportedoauth2array['OAUTH_STRIPE_LIVE_NAME'] = 'stripelive'; } diff --git a/htdocs/core/lib/order.lib.php b/htdocs/core/lib/order.lib.php index 9bd92a2c79b..2bd8707f86b 100644 --- a/htdocs/core/lib/order.lib.php +++ b/htdocs/core/lib/order.lib.php @@ -34,43 +34,59 @@ function commande_prepare_head(Commande $object) { global $db, $langs, $conf, $user; - if (!empty($conf->expedition->enabled)) $langs->load("sendings"); + if (!empty($conf->expedition->enabled)) { + $langs->load("sendings"); + } $langs->load("orders"); $h = 0; $head = array(); - if (!empty($conf->commande->enabled) && $user->rights->commande->lire) - { + if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { $head[$h][0] = DOL_URL_ROOT.'/commande/card.php?id='.$object->id; $head[$h][1] = $langs->trans("CustomerOrder"); $head[$h][2] = 'order'; $h++; } - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/commande/contact.php?id='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } if (($conf->expedition_bon->enabled && $user->rights->expedition->lire) - || ($conf->delivery_note->enabled && $user->rights->expedition->delivery->lire)) - { - $nbShipments = $object->getNbOfShipments(); $nbReceiption = 0; + || ($conf->delivery_note->enabled && $user->rights->expedition->delivery->lire)) { + $nbShipments = $object->getNbOfShipments(); + $nbReceiption = 0; $head[$h][0] = DOL_URL_ROOT.'/expedition/shipment.php?id='.$object->id; $text = ''; - if ($conf->expedition_bon->enabled) $text .= $langs->trans("Shipments"); - if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled) $text .= ' - '; - if ($conf->delivery_note->enabled) $text .= $langs->trans("Receivings"); - if ($nbShipments > 0 || $nbReceiption > 0) $text .= ''.($nbShipments ? $nbShipments : 0); - if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled && ($nbShipments > 0 || $nbReceiption > 0)) $text .= ' - '; - if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled && ($nbShipments > 0 || $nbReceiption > 0)) $text .= ($nbReceiption ? $nbReceiption : 0); - if ($nbShipments > 0 || $nbReceiption > 0) $text .= ''; + if ($conf->expedition_bon->enabled) { + $text .= $langs->trans("Shipments"); + } + if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled) { + $text .= ' - '; + } + if ($conf->delivery_note->enabled) { + $text .= $langs->trans("Receivings"); + } + if ($nbShipments > 0 || $nbReceiption > 0) { + $text .= ''.($nbShipments ? $nbShipments : 0); + } + if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled && ($nbShipments > 0 || $nbReceiption > 0)) { + $text .= ' - '; + } + if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled && ($nbShipments > 0 || $nbReceiption > 0)) { + $text .= ($nbReceiption ? $nbReceiption : 0); + } + if ($nbShipments > 0 || $nbReceiption > 0) { + $text .= ''; + } $head[$h][1] = $text; $head[$h][2] = 'shipping'; $h++; @@ -82,14 +98,19 @@ function commande_prepare_head(Commande $object) // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'order'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/commande/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; } @@ -101,7 +122,9 @@ function commande_prepare_head(Commande $object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/commande/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; diff --git a/htdocs/core/lib/parsemd.lib.php b/htdocs/core/lib/parsemd.lib.php index ef0de8c1298..72903dd9e76 100644 --- a/htdocs/core/lib/parsemd.lib.php +++ b/htdocs/core/lib/parsemd.lib.php @@ -31,17 +31,14 @@ */ function dolMd2Html($content, $parser = 'parsedown', $replaceimagepath = null) { - if (is_array($replaceimagepath)) - { - foreach ($replaceimagepath as $key => $val) - { + if (is_array($replaceimagepath)) { + foreach ($replaceimagepath as $key => $val) { $keytoreplace = ']('.$key; $valafter = ']('.$val; $content = preg_replace('/'.preg_quote($keytoreplace, '/').'/m', $valafter, $content); } } - if ($parser == 'parsedown') - { + if ($parser == 'parsedown') { include_once DOL_DOCUMENT_ROOT.'/includes/parsedown/Parsedown.php'; $Parsedown = new Parsedown(); $content = $Parsedown->text($content); @@ -63,10 +60,8 @@ function dolMd2Html($content, $parser = 'parsedown', $replaceimagepath = null) */ function dolMd2Asciidoc($content, $parser = 'dolibarr', $replaceimagepath = null) { - if (is_array($replaceimagepath)) - { - foreach ($replaceimagepath as $key => $val) - { + if (is_array($replaceimagepath)) { + foreach ($replaceimagepath as $key => $val) { $keytoreplace = ']('.$key; $valafter = ']('.$val; $content = preg_replace('/'.preg_quote($keytoreplace, '/').'/m', $valafter, $content); diff --git a/htdocs/core/lib/payments.lib.php b/htdocs/core/lib/payments.lib.php index 601dad3275d..835986f5f83 100644 --- a/htdocs/core/lib/payments.lib.php +++ b/htdocs/core/lib/payments.lib.php @@ -137,18 +137,15 @@ function getValidOnlinePaymentMethods($paymentmethod = '') $validpaymentmethod = array(); - if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled)) - { + if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled)) { $langs->load("paypal"); $validpaymentmethod['paypal'] = 'valid'; } - if ((empty($paymentmethod) || $paymentmethod == 'paybox') && !empty($conf->paybox->enabled)) - { + if ((empty($paymentmethod) || $paymentmethod == 'paybox') && !empty($conf->paybox->enabled)) { $langs->load("paybox"); $validpaymentmethod['paybox'] = 'valid'; } - if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled)) - { + if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled)) { $langs->load("stripe"); $validpaymentmethod['stripe'] = 'valid'; } @@ -205,102 +202,142 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current $urltouse = DOL_MAIN_URL_ROOT; - if ($localorexternal) $urltouse = $urlwithroot; + if ($localorexternal) { + $urltouse = $urlwithroot; + } - if ($type == 'free') - { + if ($type == 'free') { $out = $urltouse.'/public/payment/newpayment.php?amount='.($mode ? '' : '').$amount.($mode ? '' : '').'&tag='.($mode ? '' : '').$freetag.($mode ? '' : ''); - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) - { - if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; - else $out .= '&securekey='.dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; + } else { + $out .= '&securekey='.dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + } } //if ($mode) $out.='&noidempotency=1'; - } elseif ($type == 'order') - { + } elseif ($type == 'order') { $out = $urltouse.'/public/payment/newpayment.php?source=order&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'order_ref'; - if ($mode == 0) $out .= urlencode($ref); + if ($mode == 1) { + $out .= 'order_ref'; + } + if ($mode == 0) { + $out .= urlencode($ref); + } $out .= ($mode ? '' : ''); - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) - { - if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; - else { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; + } else { $out .= '&securekey='.($mode ? '' : ''); - if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + order_ref)"; - if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + if ($mode == 1) { + $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + order_ref)"; + } + if ($mode == 0) { + $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + } $out .= ($mode ? '' : ''); } } - } elseif ($type == 'invoice') - { + } elseif ($type == 'invoice') { $out = $urltouse.'/public/payment/newpayment.php?source=invoice&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'invoice_ref'; - if ($mode == 0) $out .= urlencode($ref); + if ($mode == 1) { + $out .= 'invoice_ref'; + } + if ($mode == 0) { + $out .= urlencode($ref); + } $out .= ($mode ? '' : ''); - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) - { - if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; - else { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; + } else { $out .= '&securekey='.($mode ? '' : ''); - if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + invoice_ref)"; - if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + if ($mode == 1) { + $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + invoice_ref)"; + } + if ($mode == 0) { + $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + } $out .= ($mode ? '' : ''); } } - } elseif ($type == 'contractline') - { + } elseif ($type == 'contractline') { $out = $urltouse.'/public/payment/newpayment.php?source=contractline&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'contractline_ref'; - if ($mode == 0) $out .= urlencode($ref); + if ($mode == 1) { + $out .= 'contractline_ref'; + } + if ($mode == 0) { + $out .= urlencode($ref); + } $out .= ($mode ? '' : ''); - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) - { - if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; - else { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; + } else { $out .= '&securekey='.($mode ? '' : ''); - if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + contractline_ref)"; - if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + if ($mode == 1) { + $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + contractline_ref)"; + } + if ($mode == 0) { + $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + } $out .= ($mode ? '' : ''); } } - } elseif ($type == 'member' || $type == 'membersubscription') - { + } elseif ($type == 'member' || $type == 'membersubscription') { $out = $urltouse.'/public/payment/newpayment.php?source=membersubscription&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'member_ref'; - if ($mode == 0) $out .= urlencode($ref); + if ($mode == 1) { + $out .= 'member_ref'; + } + if ($mode == 0) { + $out .= urlencode($ref); + } $out .= ($mode ? '' : ''); - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) - { - if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; - else { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; + } else { $out .= '&securekey='.($mode ? '' : ''); - if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + member_ref)"; - if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + if ($mode == 1) { + $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + member_ref)"; + } + if ($mode == 0) { + $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + } $out .= ($mode ? '' : ''); } } } - if ($type == 'donation') - { + if ($type == 'donation') { $out = $urltouse.'/public/payment/newpayment.php?source=donation&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'donation_ref'; - if ($mode == 0) $out .= urlencode($ref); + if ($mode == 1) { + $out .= 'donation_ref'; + } + if ($mode == 0) { + $out .= urlencode($ref); + } $out .= ($mode ? '' : ''); - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) - { - if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; - else { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; + } else { $out .= '&securekey='.($mode ? '' : ''); - if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + donation_ref)"; - if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + if ($mode == 1) { + $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + donation_ref)"; + } + if ($mode == 0) { + $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + } $out .= ($mode ? '' : ''); } } } // For multicompany - if (!empty($out) && !empty($conf->multicompany->enabled)) $out .= "&entity=".$conf->entity; // Check the entity because we may have the same reference in several entities + if (!empty($out) && !empty($conf->multicompany->enabled)) { + $out .= "&entity=".$conf->entity; // Check the entity because we may have the same reference in several entities + } return $out; } @@ -323,78 +360,86 @@ function htmlPrintOnlinePaymentFooter($fromcompany, $langs, $addformmessage = 0, // Juridical status $line1 = ""; - if ($fromcompany->forme_juridique_code) - { + if ($fromcompany->forme_juridique_code) { $line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code); } // Capital - if ($fromcompany->capital) - { + if ($fromcompany->capital) { $line1 .= ($line1 ? " - " : "").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency); } // Prof Id 1 - if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) - { + if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) { $field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1; } // Prof Id 2 - if ($fromcompany->idprof2) - { + if ($fromcompany->idprof2) { $field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof2; } // Second line of company infos $line2 = ""; // Prof Id 3 - if ($fromcompany->idprof3) - { + if ($fromcompany->idprof3) { $field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3; } // Prof Id 4 - if ($fromcompany->idprof4) - { + if ($fromcompany->idprof4) { $field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4; } // IntraCommunautary VAT - if ($fromcompany->tva_intra != '') - { + if ($fromcompany->tva_intra != '') { $line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra; } print '
    '; print '
    '."\n"; - if ($addformmessage) - { + if ($addformmessage) { print ''; print '
    '; $parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORM_'.$suffix; - if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); - elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM); + if (!empty($conf->global->$parammessageform)) { + print $langs->transnoentities($conf->global->$parammessageform); + } elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) { + print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM); + } // Add other message if VAT exists - if ($object->total_vat != 0 || $object->total_tva != 0) - { + if ($object->total_vat != 0 || $object->total_tva != 0) { $parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORMIFVAT_'.$suffix; - if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); - elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT); + if (!empty($conf->global->$parammessageform)) { + print $langs->transnoentities($conf->global->$parammessageform); + } elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) { + print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT); + } } } print '

    '."\n"; print $fromcompany->name.'
    '; print $line1; - if (strlen($line1.$line2) > 50) print '
    '; - else print ' - '; + if (strlen($line1.$line2) > 50) { + print '
    '; + } else { + print ' - '; + } print $line2; print '
    '."\n"; } diff --git a/htdocs/core/lib/pdf.lib.php b/htdocs/core/lib/pdf.lib.php index 613a68b56d8..529355b94b2 100644 --- a/htdocs/core/lib/pdf.lib.php +++ b/htdocs/core/lib/pdf.lib.php @@ -49,10 +49,11 @@ function pdf_getFormat(Translate $outputlangs = null, $mode = 'setup') dol_syslog("pdf_getFormat Get paper format with mode=".$mode." MAIN_PDF_FORMAT=".(empty($conf->global->MAIN_PDF_FORMAT) ? 'null' : $conf->global->MAIN_PDF_FORMAT)." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')." and langs->defaultlang=".(is_object($langs) ? $langs->defaultlang : 'null')); // Default value if setup was not done and/or entry into c_paper_format not defined - $width = 210; $height = 297; $unit = 'mm'; + $width = 210; + $height = 297; + $unit = 'mm'; - if ($mode == 'auto' || empty($conf->global->MAIN_PDF_FORMAT) || $conf->global->MAIN_PDF_FORMAT == 'auto') - { + if ($mode == 'auto' || empty($conf->global->MAIN_PDF_FORMAT) || $conf->global->MAIN_PDF_FORMAT == 'auto') { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $pdfformat = dol_getDefaultFormat($outputlangs); } else { @@ -62,11 +63,9 @@ function pdf_getFormat(Translate $outputlangs = null, $mode = 'setup') $sql = "SELECT code, label, width, height, unit FROM ".MAIN_DB_PREFIX."c_paper_format"; $sql .= " WHERE code = '".$db->escape($pdfformat)."'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $width = (int) $obj->width; $height = (int) $obj->height; $unit = $obj->unit; @@ -90,8 +89,7 @@ function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P') global $conf; // Define constant for TCPDF - if (!defined('K_TCPDF_EXTERNAL_CONFIG')) - { + if (!defined('K_TCPDF_EXTERNAL_CONFIG')) { define('K_TCPDF_EXTERNAL_CONFIG', 1); // this avoid using tcpdf_config file define('K_PATH_CACHE', DOL_DATA_ROOT.'/admin/temp/'); define('K_PATH_URL_CACHE', DOL_DATA_ROOT.'/admin/temp/'); @@ -133,21 +131,27 @@ function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P') require_once TCPDF_PATH.'tcpdf.php'; // We need to instantiate tcpdi object (instead of tcpdf) to use merging features. But we can disable it (this will break all merge features). - if (empty($conf->global->MAIN_DISABLE_TCPDI)) require_once TCPDI_PATH.'tcpdi.php'; + if (empty($conf->global->MAIN_DISABLE_TCPDI)) { + require_once TCPDI_PATH.'tcpdi.php'; + } //$arrayformat=pdf_getFormat(); //$format=array($arrayformat['width'],$arrayformat['height']); //$metric=$arrayformat['unit']; $pdfa = false; // PDF-1.3 - if (!empty($conf->global->PDF_USE_1A)) $pdfa = true; // PDF1/A + if (!empty($conf->global->PDF_USE_1A)) { + $pdfa = true; // PDF1/A + } - if (class_exists('TCPDI')) $pdf = new TCPDI($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa); - else $pdf = new TCPDF($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa); + if (class_exists('TCPDI')) { + $pdf = new TCPDI($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa); + } else { + $pdf = new TCPDF($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa); + } // Protection and encryption of pdf - if (!empty($conf->global->PDF_SECURITY_ENCRYPTION)) - { + if (!empty($conf->global->PDF_SECURITY_ENCRYPTION)) { /* Permission supported by TCPDF - print : Print the document; - modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble'; @@ -223,13 +227,13 @@ function pdf_getPDFFont($outputlangs) { global $conf; - if (!empty($conf->global->MAIN_PDF_FORCE_FONT)) return $conf->global->MAIN_PDF_FORCE_FONT; + if (!empty($conf->global->MAIN_PDF_FORCE_FONT)) { + return $conf->global->MAIN_PDF_FORCE_FONT; + } $font = 'Helvetica'; // By default, for FPDI, or ISO language on TCPDF - if (class_exists('TCPDF')) // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower) - { - if ($outputlangs->trans('FONTFORPDF') != 'FONTFORPDF') - { + if (class_exists('TCPDF')) { // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower) + if ($outputlangs->trans('FONTFORPDF') != 'FONTFORPDF') { $font = $outputlangs->trans('FONTFORPDF'); } } @@ -247,14 +251,14 @@ function pdf_getPDFFontSize($outputlangs) global $conf; $size = 10; // By default, for FPDI or ISO language on TCPDF - if (class_exists('TCPDF')) // If TCPDF on, we can use an UTF8 font like DejaVuSans if required (slower) - { - if ($outputlangs->trans('FONTSIZEFORPDF') != 'FONTSIZEFORPDF') - { + if (class_exists('TCPDF')) { // If TCPDF on, we can use an UTF8 font like DejaVuSans if required (slower) + if ($outputlangs->trans('FONTSIZEFORPDF') != 'FONTSIZEFORPDF') { $size = (int) $outputlangs->trans('FONTSIZEFORPDF'); } } - if (!empty($conf->global->MAIN_PDF_FORCE_FONT_SIZE)) $size = $conf->global->MAIN_PDF_FORCE_FONT_SIZE; + if (!empty($conf->global->MAIN_PDF_FORCE_FONT_SIZE)) { + $size = $conf->global->MAIN_PDF_FORCE_FONT_SIZE; + } return $size; } @@ -274,10 +278,11 @@ function pdf_getHeightForLogo($logo, $url = false) $maxwidth = 130; include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; $tmp = dol_getImageSize($logo, $url); - if ($tmp['height']) - { + if ($tmp['height']) { $width = round($height * $tmp['width'] / $tmp['height']); - if ($width > $maxwidth) $height = $height * $maxwidth / $width; + if ($width > $maxwidth) { + $height = $height * $maxwidth / $width; + } } //print $tmp['width'].' '.$tmp['height'].' '.$width; exit; return $height; @@ -377,82 +382,103 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t { global $conf, $hookmanager; - if ($mode == 'source' && !is_object($sourcecompany)) return -1; - if ($mode == 'target' && !is_object($targetcompany)) return -1; + if ($mode == 'source' && !is_object($sourcecompany)) { + return -1; + } + if ($mode == 'target' && !is_object($targetcompany)) { + return -1; + } - if (!empty($sourcecompany->state_id) && empty($sourcecompany->state)) $sourcecompany->state = getState($sourcecompany->state_id); - if (!empty($targetcompany->state_id) && empty($targetcompany->state)) $targetcompany->state = getState($targetcompany->state_id); + if (!empty($sourcecompany->state_id) && empty($sourcecompany->state)) { + $sourcecompany->state = getState($sourcecompany->state_id); + } + if (!empty($targetcompany->state_id) && empty($targetcompany->state)) { + $targetcompany->state = getState($targetcompany->state_id); + } $reshook = 0; $stringaddress = ''; - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('sourcecompany' => &$sourcecompany, 'targetcompany' => &$targetcompany, 'targetcontact' => &$targetcontact, 'outputlangs' => $outputlangs, 'mode' => $mode, 'usecontact' => $usecontact); $action = ''; $reshook = $hookmanager->executeHooks('pdf_build_address', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $stringaddress .= $hookmanager->resPrint; } - if (empty($reshook)) - { - if ($mode == 'source') - { + if (empty($reshook)) { + if ($mode == 'source') { $withCountry = 0; - if (!empty($sourcecompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) $withCountry = 1; + if (!empty($sourcecompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) { + $withCountry = 1; + } $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($sourcecompany, $withCountry, "\n", $outputlangs))."\n"; - if (empty($conf->global->MAIN_PDF_DISABLESOURCEDETAILS)) - { + if (empty($conf->global->MAIN_PDF_DISABLESOURCEDETAILS)) { // Phone - if ($sourcecompany->phone) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("PhoneShort").": ".$outputlangs->convToOutputCharset($sourcecompany->phone); + if ($sourcecompany->phone) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("PhoneShort").": ".$outputlangs->convToOutputCharset($sourcecompany->phone); + } // Fax - if ($sourcecompany->fax) $stringaddress .= ($stringaddress ? ($sourcecompany->phone ? " - " : "\n") : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($sourcecompany->fax); + if ($sourcecompany->fax) { + $stringaddress .= ($stringaddress ? ($sourcecompany->phone ? " - " : "\n") : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($sourcecompany->fax); + } // EMail - if ($sourcecompany->email) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($sourcecompany->email); + if ($sourcecompany->email) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($sourcecompany->email); + } // Web - if ($sourcecompany->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($sourcecompany->url); + if ($sourcecompany->url) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($sourcecompany->url); + } } // Intra VAT - if (!empty($conf->global->MAIN_TVAINTRA_IN_SOURCE_ADDRESS)) - { - if ($sourcecompany->tva_intra) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra); + if (!empty($conf->global->MAIN_TVAINTRA_IN_SOURCE_ADDRESS)) { + if ($sourcecompany->tva_intra) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra); + } } // Professionnal Ids $reg = array(); - if (!empty($conf->global->MAIN_PROFID1_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof1)) - { + if (!empty($conf->global->MAIN_PROFID1_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof1)) { $tmp = $outputlangs->transcountrynoentities("ProfId1", $sourcecompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof1); } - if (!empty($conf->global->MAIN_PROFID2_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof2)) - { + if (!empty($conf->global->MAIN_PROFID2_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof2)) { $tmp = $outputlangs->transcountrynoentities("ProfId2", $sourcecompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof2); } - if (!empty($conf->global->MAIN_PROFID3_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof3)) - { + if (!empty($conf->global->MAIN_PROFID3_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof3)) { $tmp = $outputlangs->transcountrynoentities("ProfId3", $sourcecompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof3); } - if (!empty($conf->global->MAIN_PROFID4_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof4)) - { + if (!empty($conf->global->MAIN_PROFID4_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof4)) { $tmp = $outputlangs->transcountrynoentities("ProfId4", $sourcecompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof4); } - if (!empty($conf->global->MAIN_PROFID5_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof5)) - { + if (!empty($conf->global->MAIN_PROFID5_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof5)) { $tmp = $outputlangs->transcountrynoentities("ProfId5", $sourcecompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof5); } - if (!empty($conf->global->MAIN_PROFID6_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof6)) - { + if (!empty($conf->global->MAIN_PROFID6_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof6)) { $tmp = $outputlangs->transcountrynoentities("ProfId6", $sourcecompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof6); } if (!empty($conf->global->PDF_ADD_MORE_AFTER_SOURCE_ADDRESS)) { @@ -460,10 +486,8 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t } } - if ($mode == 'target' || preg_match('/targetwithdetails/', $mode)) - { - if ($usecontact) - { + if ($mode == 'target' || preg_match('/targetwithdetails/', $mode)) { + if ($usecontact) { $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($targetcontact->getFullName($outputlangs, 1)); if (!empty($targetcontact->address)) { @@ -472,8 +496,7 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t $companytouseforaddress = $targetcompany; // Contact on a thirdparty that is a different thirdparty than the thirdparty of object - if ($targetcontact->socid > 0 && $targetcontact->socid != $targetcompany->id) - { + if ($targetcontact->socid > 0 && $targetcontact->socid != $targetcompany->id) { $targetcontact->fetch_thirdparty(); $companytouseforaddress = $targetcontact->thirdparty; } @@ -487,118 +510,142 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code)); } - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode)) - { + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode)) { // Phone - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode)) - { - if (!empty($targetcontact->phone_pro) || !empty($targetcontact->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": "; - if (!empty($targetcontact->phone_pro)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_pro); - if (!empty($targetcontact->phone_pro) && !empty($targetcontact->phone_mobile)) $stringaddress .= " / "; - if (!empty($targetcontact->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_mobile); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode)) { + if (!empty($targetcontact->phone_pro) || !empty($targetcontact->phone_mobile)) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": "; + } + if (!empty($targetcontact->phone_pro)) { + $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_pro); + } + if (!empty($targetcontact->phone_pro) && !empty($targetcontact->phone_mobile)) { + $stringaddress .= " / "; + } + if (!empty($targetcontact->phone_mobile)) { + $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_mobile); + } } // Fax - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode)) - { - if ($targetcontact->fax) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcontact->fax); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode)) { + if ($targetcontact->fax) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcontact->fax); + } } // EMail - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode)) - { - if ($targetcontact->email) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcontact->email); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode)) { + if ($targetcontact->email) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcontact->email); + } } // Web - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode)) - { - if ($targetcontact->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcontact->url); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode)) { + if ($targetcontact->url) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcontact->url); + } } } } else { $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($targetcompany)); // Country - if (!empty($targetcompany->country_code) && $targetcompany->country_code != $sourcecompany->country_code) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code)); + if (!empty($targetcompany->country_code) && $targetcompany->country_code != $sourcecompany->country_code) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code)); + } - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode)) - { + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode)) { // Phone - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode)) - { - if (!empty($targetcompany->phone) || !empty($targetcompany->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": "; - if (!empty($targetcompany->phone)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone); - if (!empty($targetcompany->phone) && !empty($targetcompany->phone_mobile)) $stringaddress .= " / "; - if (!empty($targetcompany->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone_mobile); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode)) { + if (!empty($targetcompany->phone) || !empty($targetcompany->phone_mobile)) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": "; + } + if (!empty($targetcompany->phone)) { + $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone); + } + if (!empty($targetcompany->phone) && !empty($targetcompany->phone_mobile)) { + $stringaddress .= " / "; + } + if (!empty($targetcompany->phone_mobile)) { + $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone_mobile); + } } // Fax - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode)) - { - if ($targetcompany->fax) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcompany->fax); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode)) { + if ($targetcompany->fax) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcompany->fax); + } } // EMail - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode)) - { - if ($targetcompany->email) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcompany->email); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode)) { + if ($targetcompany->email) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcompany->email); + } } // Web - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode)) - { - if ($targetcompany->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode)) { + if ($targetcompany->url) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url); + } } } } // Intra VAT - if (empty($conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS)) - { - if ($targetcompany->tva_intra) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($targetcompany->tva_intra); + if (empty($conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS)) { + if ($targetcompany->tva_intra) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($targetcompany->tva_intra); + } } // Professionnal Ids - if (!empty($conf->global->MAIN_PROFID1_IN_ADDRESS) && !empty($targetcompany->idprof1)) - { + if (!empty($conf->global->MAIN_PROFID1_IN_ADDRESS) && !empty($targetcompany->idprof1)) { $tmp = $outputlangs->transcountrynoentities("ProfId1", $targetcompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof1); } - if (!empty($conf->global->MAIN_PROFID2_IN_ADDRESS) && !empty($targetcompany->idprof2)) - { + if (!empty($conf->global->MAIN_PROFID2_IN_ADDRESS) && !empty($targetcompany->idprof2)) { $tmp = $outputlangs->transcountrynoentities("ProfId2", $targetcompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof2); } - if (!empty($conf->global->MAIN_PROFID3_IN_ADDRESS) && !empty($targetcompany->idprof3)) - { + if (!empty($conf->global->MAIN_PROFID3_IN_ADDRESS) && !empty($targetcompany->idprof3)) { $tmp = $outputlangs->transcountrynoentities("ProfId3", $targetcompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof3); } - if (!empty($conf->global->MAIN_PROFID4_IN_ADDRESS) && !empty($targetcompany->idprof4)) - { + if (!empty($conf->global->MAIN_PROFID4_IN_ADDRESS) && !empty($targetcompany->idprof4)) { $tmp = $outputlangs->transcountrynoentities("ProfId4", $targetcompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof4); } - if (!empty($conf->global->MAIN_PROFID5_IN_ADDRESS) && !empty($targetcompany->idprof5)) - { + if (!empty($conf->global->MAIN_PROFID5_IN_ADDRESS) && !empty($targetcompany->idprof5)) { $tmp = $outputlangs->transcountrynoentities("ProfId5", $targetcompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof5); } - if (!empty($conf->global->MAIN_PROFID6_IN_ADDRESS) && !empty($targetcompany->idprof6)) - { + if (!empty($conf->global->MAIN_PROFID6_IN_ADDRESS) && !empty($targetcompany->idprof6)) { $tmp = $outputlangs->transcountrynoentities("ProfId6", $targetcompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof6); } // Public note - if (!empty($conf->global->MAIN_PUBLIC_NOTE_IN_ADDRESS)) - { - if ($mode == 'source' && !empty($sourcecompany->note_public)) - { + if (!empty($conf->global->MAIN_PUBLIC_NOTE_IN_ADDRESS)) { + if ($mode == 'source' && !empty($sourcecompany->note_public)) { $stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($sourcecompany->note_public); } - if (($mode == 'target' || preg_match('/targetwithdetails/', $mode)) && !empty($targetcompany->note_public)) - { + if (($mode == 'target' || preg_match('/targetwithdetails/', $mode)) && !empty($targetcompany->note_public)) { $stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($targetcompany->note_public); } } @@ -622,8 +669,7 @@ function pdf_pagehead(&$pdf, $outputlangs, $page_height) global $conf; // Add a background image on document - if (!empty($conf->global->MAIN_USE_BACKGROUND_ON_PDF)) // Warning, this option make TCPDF generation being crazy and some content disappeared behind the image - { + if (!empty($conf->global->MAIN_USE_BACKGROUND_ON_PDF)) { // Warning, this option make TCPDF generation being crazy and some content disappeared behind the image $pdf->SetAutoPageBreak(0, 0); // Disable auto pagebreak before adding image $pdf->Image($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_USE_BACKGROUND_ON_PDF, (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_X) ? $conf->global->MAIN_USE_BACKGROUND_ON_PDF_X : 0), (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y) ? $conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y : 0), 0, $page_height); $pdf->SetAutoPageBreak(1, 0); // Restore pagebreak @@ -665,10 +711,15 @@ function pdf_watermark(&$pdf, $outputlangs, $h, $w, $unit, $text) global $langs, $mysoc, $user; // Print Draft Watermark - if ($unit == 'pt') $k = 1; - elseif ($unit == 'mm') $k = 72 / 25.4; - elseif ($unit == 'cm') $k = 72 / 2.54; - elseif ($unit == 'in') $k = 72; + if ($unit == 'pt') { + $k = 1; + } elseif ($unit == 'mm') { + $k = 72 / 25.4; + } elseif ($unit == 'cm') { + $k = 72 / 2.54; + } elseif ($unit == 'in') { + $k = 72; + } // Make substitution $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, null); @@ -676,7 +727,8 @@ function pdf_watermark(&$pdf, $outputlangs, $h, $w, $unit, $text) $text = make_substitutions($text, $substitutionarray, $outputlangs); $text = $outputlangs->convToOutputCharset($text); - $savx = $pdf->getX(); $savy = $pdf->getY(); + $savx = $pdf->getX(); + $savy = $pdf->getY(); $watermark_angle = atan($h / $w) / 2; $watermark_x_pos = 0; @@ -719,8 +771,7 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, $diffsizecontent = (empty($conf->global->PDF_DIFFSIZE_CONTENT) ? 4 : $conf->global->PDF_DIFFSIZE_CONTENT); $pdf->SetXY($curx, $cury); - if (empty($onlynumber)) - { + if (empty($onlynumber)) { $pdf->SetFont('', 'B', $default_font_size - $diffsizetitle); $pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByTransferOnThisBankAccount').':', 0, 'L', 0); $cury += 4; @@ -730,36 +781,36 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, // Use correct name of bank id according to country $bickey = "BICNumber"; - if ($account->getCountryCode() == 'IN') $bickey = "SWIFT"; + if ($account->getCountryCode() == 'IN') { + $bickey = "SWIFT"; + } // Get format of bank account according to its country $usedetailedbban = $account->useDetailedBBAN(); //$onlynumber=0; $usedetailedbban=1; // For tests - if ($usedetailedbban) - { + if ($usedetailedbban) { $savcurx = $curx; - if (empty($onlynumber)) - { + if (empty($onlynumber)) { $pdf->SetFont('', '', $default_font_size - $diffsizecontent); $pdf->SetXY($curx, $cury); $pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': '.$outputlangs->convToOutputCharset($account->bank), 0, 'L', 0); $cury += 3; } - if (empty($conf->global->PDF_BANK_HIDE_NUMBER_SHOW_ONLY_BICIBAN)) // Note that some countries still need bank number, BIC/IBAN not enougth for them - { + if (empty($conf->global->PDF_BANK_HIDE_NUMBER_SHOW_ONLY_BICIBAN)) { // Note that some countries still need bank number, BIC/IBAN not enougth for them // Note: // bank = code_banque (FR), sort code (GB, IR. Example: 12-34-56) // desk = code guichet (FR), used only when $usedetailedbban = 1 // number = account number // key = check control key used only when $usedetailedbban = 1 - if (empty($onlynumber)) $pdf->line($curx + 1, $cury + 1, $curx + 1, $cury + 6); + if (empty($onlynumber)) { + $pdf->line($curx + 1, $cury + 1, $curx + 1, $cury + 6); + } - foreach ($account->getFieldsToShow() as $val) - { + foreach ($account->getFieldsToShow() as $val) { $pdf->SetXY($curx, $cury + 4); $pdf->SetFont('', '', $default_font_size - 3); @@ -812,7 +863,9 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, $pdf->MultiCell(100, 3, $outputlangs->transnoentities("BankAccountNumber").': '.$outputlangs->convToOutputCharset($account->number), 0, 'L', 0); $cury += 3; - if ($diffsizecontent <= 2) $cury += 1; + if ($diffsizecontent <= 2) { + $cury += 1; + } } $pdf->SetFont('', '', $default_font_size - $diffsizecontent); @@ -840,17 +893,17 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, // Use correct name of bank id according to country $ibankey = FormBank::getIBANLabel($account); - if (!empty($account->iban)) - { + if (!empty($account->iban)) { //Remove whitespaces to ensure we are dealing with the format we expect $ibanDisplay_temp = str_replace(' ', '', $outputlangs->convToOutputCharset($account->iban)); $ibanDisplay = ""; $nbIbanDisplay_temp = dol_strlen($ibanDisplay_temp); - for ($i = 0; $i < $nbIbanDisplay_temp; $i++) - { + for ($i = 0; $i < $nbIbanDisplay_temp; $i++) { $ibanDisplay .= $ibanDisplay_temp[$i]; - if ($i % 4 == 3 && $i > 0) $ibanDisplay .= " "; + if ($i % 4 == 3 && $i > 0) { + $ibanDisplay .= " "; + } } $pdf->SetFont('', 'B', $default_font_size - 3); @@ -859,8 +912,7 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, $cury += 3; } - if (!empty($account->bic)) - { + if (!empty($account->bic)) { $pdf->SetFont('', 'B', $default_font_size - 3); $pdf->SetXY($curx, $cury); $pdf->MultiCell(100, 3, $outputlangs->transnoentities($bickey).': '.$outputlangs->convToOutputCharset($account->bic), 0, 'L', 0); @@ -894,8 +946,7 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ $dims = $pdf->getPageDimensions(); // Line of free text - if (empty($hidefreetext) && !empty($conf->global->$paramfreetext)) - { + if (empty($hidefreetext) && !empty($conf->global->$paramfreetext)) { $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); // More substitution keys $substitutionarray['__FROM_NAME__'] = $fromcompany->name; @@ -913,126 +964,123 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ } // First line of company infos - $line1 = ""; $line2 = ""; $line3 = ""; $line4 = ""; + $line1 = ""; + $line2 = ""; + $line3 = ""; + $line4 = ""; - if ($showdetails == 1 || $showdetails == 3) - { + if ($showdetails == 1 || $showdetails == 3) { // Company name - if ($fromcompany->name) - { + if ($fromcompany->name) { $line1 .= ($line1 ? " - " : "").$outputlangs->transnoentities("RegisteredOffice").": ".$fromcompany->name; } // Address - if ($fromcompany->address) - { + if ($fromcompany->address) { $line1 .= ($line1 ? " - " : "").str_replace("\n", ", ", $fromcompany->address); } // Zip code - if ($fromcompany->zip) - { + if ($fromcompany->zip) { $line1 .= ($line1 ? " - " : "").$fromcompany->zip; } // Town - if ($fromcompany->town) - { + if ($fromcompany->town) { $line1 .= ($line1 ? " " : "").$fromcompany->town; } // Country - if ($fromcompany->country) - { + if ($fromcompany->country) { $line1 .= ($line1 ? ", " : "").$fromcompany->country; } // Phone - if ($fromcompany->phone) - { + if ($fromcompany->phone) { $line2 .= ($line2 ? " - " : "").$outputlangs->transnoentities("Phone").": ".$fromcompany->phone; } // Fax - if ($fromcompany->fax) - { + if ($fromcompany->fax) { $line2 .= ($line2 ? " - " : "").$outputlangs->transnoentities("Fax").": ".$fromcompany->fax; } // URL - if ($fromcompany->url) - { + if ($fromcompany->url) { $line2 .= ($line2 ? " - " : "").$fromcompany->url; } // Email - if ($fromcompany->email) - { + if ($fromcompany->email) { $line2 .= ($line2 ? " - " : "").$fromcompany->email; } } - if ($showdetails == 2 || $showdetails == 3 || ($fromcompany->country_code == 'DE')) - { + if ($showdetails == 2 || $showdetails == 3 || ($fromcompany->country_code == 'DE')) { // Managers - if ($fromcompany->managers) - { + if ($fromcompany->managers) { $line2 .= ($line2 ? " - " : "").$fromcompany->managers; } } // Line 3 of company infos // Juridical status - if ($fromcompany->forme_juridique_code) - { + if ($fromcompany->forme_juridique_code) { $line3 .= ($line3 ? " - " : "").$outputlangs->convToOutputCharset(getFormeJuridiqueLabel($fromcompany->forme_juridique_code)); } // Capital - if ($fromcompany->capital) - { + if ($fromcompany->capital) { $tmpamounttoshow = price2num($fromcompany->capital); // This field is a free string - if (is_numeric($tmpamounttoshow) && $tmpamounttoshow > 0) $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", price($tmpamounttoshow, 0, $outputlangs, 0, 0, 0, $conf->currency)); - else $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", $tmpamounttoshow, $outputlangs); + if (is_numeric($tmpamounttoshow) && $tmpamounttoshow > 0) { + $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", price($tmpamounttoshow, 0, $outputlangs, 0, 0, 0, $conf->currency)); + } else { + $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", $tmpamounttoshow, $outputlangs); + } } // Prof Id 1 - if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) - { + if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) { $field = $outputlangs->transcountrynoentities("ProfId1", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line3 .= ($line3 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof1); } // Prof Id 2 - if ($fromcompany->idprof2) - { + if ($fromcompany->idprof2) { $field = $outputlangs->transcountrynoentities("ProfId2", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line3 .= ($line3 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof2); } // Line 4 of company infos // Prof Id 3 - if ($fromcompany->idprof3) - { + if ($fromcompany->idprof3) { $field = $outputlangs->transcountrynoentities("ProfId3", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof3); } // Prof Id 4 - if ($fromcompany->idprof4) - { + if ($fromcompany->idprof4) { $field = $outputlangs->transcountrynoentities("ProfId4", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof4); } // Prof Id 5 - if ($fromcompany->idprof5) - { + if ($fromcompany->idprof5) { $field = $outputlangs->transcountrynoentities("ProfId5", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof5); } // Prof Id 6 - if ($fromcompany->idprof6) - { + if ($fromcompany->idprof6) { $field = $outputlangs->transcountrynoentities("ProfId6", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof6); } // IntraCommunautary VAT - if ($fromcompany->tva_intra != '') - { + if ($fromcompany->tva_intra != '') { $line4 .= ($line4 ? " - " : "").$outputlangs->transnoentities("VATIntraShort").": ".$outputlangs->convToOutputCharset($fromcompany->tva_intra); } @@ -1041,14 +1089,14 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ // The start of the bottom of this page footer is positioned according to # of lines $freetextheight = 0; - if ($line) // Free text - { + if ($line) { // Free text //$line="sample text
    \nfdsfsdf
    \nghfghg
    "; - if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) - { - $width = 20000; $align = 'L'; // By default, ask a manual break: We use a large value 20000, to not have automatic wrap. This make user understand, he need to add CR on its text. + if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { + $width = 20000; + $align = 'L'; // By default, ask a manual break: We use a large value 20000, to not have automatic wrap. This make user understand, he need to add CR on its text. if (!empty($conf->global->MAIN_USE_AUTOWRAP_ON_FREETEXT)) { - $width = 200; $align = 'C'; + $width = 200; + $align = 'C'; } $freetextheight = $pdf->getStringHeight($width, $line); } else { @@ -1060,11 +1108,9 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ $marginwithfooter = $marge_basse + $freetextheight + (!empty($line1) ? 3 : 0) + (!empty($line2) ? 3 : 0) + (!empty($line3) ? 3 : 0) + (!empty($line4) ? 3 : 0); $posy = $marginwithfooter + 0; - if ($line) // Free text - { + if ($line) { // Free text $pdf->SetXY($dims['lm'], -$posy); - if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) // by default - { + if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { // by default $pdf->MultiCell(0, 3, $line, 0, $align, 0); } else { $pdf->writeHTMLCell($pdf->page_largeur - $pdf->margin_left - $pdf->margin_right, $freetextheight, $dims['lm'], $dims['hk'] - $marginwithfooter, dol_htmlentitiesbr($line, 1, 'UTF-8', 0)); @@ -1076,8 +1122,7 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ $pdf->line($dims['lm'], $dims['hk'] - $posy, $dims['wk'] - $dims['rm'], $dims['hk'] - $posy); $posy--; - if (!empty($line1)) - { + if (!empty($line1)) { $pdf->SetFont('', 'B', 7); $pdf->SetXY($dims['lm'], -$posy); $pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line1, 0, 'C', 0); @@ -1085,8 +1130,7 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ $pdf->SetFont('', '', 7); } - if (!empty($line2)) - { + if (!empty($line2)) { $pdf->SetFont('', 'B', 7); $pdf->SetXY($dims['lm'], -$posy); $pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line2, 0, 'C', 0); @@ -1094,22 +1138,19 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ $pdf->SetFont('', '', 7); } - if (!empty($line3)) - { + if (!empty($line3)) { $pdf->SetXY($dims['lm'], -$posy); $pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line3, 0, 'C', 0); } - if (!empty($line4)) - { + if (!empty($line4)) { $posy -= 3; $pdf->SetXY($dims['lm'], -$posy); $pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line4, 0, 'C', 0); } // Show page nb only on iso languages (so default Helvetica font) - if (strtolower(pdf_getPDFFont($outputlangs)) == 'helvetica') - { + if (strtolower(pdf_getPDFFont($outputlangs)) == 'helvetica') { $pdf->SetXY($dims['wk'] - $dims['rm'] - 15, -$posy); //print 'xxx'.$pdf->PageNo().'-'.$pdf->getAliasNbPages().'-'.$pdf->getAliasNumPage();exit; $pdf->MultiCell(15, 2, $pdf->PageNo().'/'.$pdf->getAliasNbPages(), 0, 'R', 0); @@ -1135,13 +1176,10 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ function pdf_writeLinkedObjects(&$pdf, $object, $outputlangs, $posx, $posy, $w, $h, $align, $default_font_size) { $linkedobjects = pdf_getLinkedObjects($object, $outputlangs); - if (!empty($linkedobjects)) - { - foreach ($linkedobjects as $linkedobject) - { + if (!empty($linkedobjects)) { + foreach ($linkedobjects as $linkedobject) { $reftoshow = $linkedobject["ref_title"].' : '.$linkedobject["ref_value"]; - if (!empty($linkedobject["date_value"])) - { + if (!empty($linkedobject["date_value"])) { $reftoshow .= ' / '.$linkedobject["date_value"]; } @@ -1178,18 +1216,20 @@ function pdf_writelinedesc(&$pdf, $object, $i, $outputlangs, $w, $h, $posx, $pos $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = empty($object->lines[$i]->special_code) ? '' : $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('pdf'=>$pdf, 'i'=>$i, 'outputlangs'=>$outputlangs, 'w'=>$w, 'h'=>$h, 'posx'=>$posx, 'posy'=>$posy, 'hideref'=>$hideref, 'hidedesc'=>$hidedesc, 'issupplierline'=>$issupplierline, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_writelinedesc', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { + if (empty($reshook)) { $labelproductservice = pdf_getlinedesc($object, $i, $outputlangs, $hideref, $hidedesc, $issupplierline); //var_dump($labelproductservice);exit; @@ -1229,8 +1269,7 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $note = (!empty($object->lines[$i]->note) ? $object->lines[$i]->note : ''); $dbatch = (!empty($object->lines[$i]->detail_batch) ? $object->lines[$i]->detail_batch : false); - if ($issupplierline) - { + if ($issupplierline) { include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $prodser = new ProductFournisseur($db); } else { @@ -1238,16 +1277,14 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $prodser = new Product($db); if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { - include_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; + include_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; } } - if ($idprod) - { + if ($idprod) { $prodser->fetch($idprod); // If a predefined product and multilang and on other lang, we renamed label with label translated - if (!empty($conf->global->MAIN_MULTILANGS) && ($outputlangs->defaultlang != $langs->defaultlang)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && ($outputlangs->defaultlang != $langs->defaultlang)) { $translatealsoifmodified = (!empty($conf->global->MAIN_MULTILANG_TRANSLATE_EVEN_IF_MODIFIED)); // By default if value was modified manually, we keep it (no translation because we don't have it) // TODO Instead of making a compare to see if param was modified, check that content contains reference translation. If yes, add the added part to the new translation @@ -1269,11 +1306,15 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, } else { $textwasmodified = ($desc == $prodser->description); } - if (!empty($prodser->multilangs[$outputlangs->defaultlang]["description"]) && ($textwasmodified || $translatealsoifmodified)) $desc = $prodser->multilangs[$outputlangs->defaultlang]["description"]; + if (!empty($prodser->multilangs[$outputlangs->defaultlang]["description"]) && ($textwasmodified || $translatealsoifmodified)) { + $desc = $prodser->multilangs[$outputlangs->defaultlang]["description"]; + } // Set note $textwasmodified = ($note == $prodser->note); - if (!empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified)) $note = $prodser->multilangs[$outputlangs->defaultlang]["note"]; + if (!empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified)) { + $note = $prodser->multilangs[$outputlangs->defaultlang]["note"]; + } } } elseif ($object->element == 'facture' || $object->element == 'facturefourn') { if ($object->type == $object::TYPE_DEPOSIT) { @@ -1299,34 +1340,30 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, } // Description long of product line - if (!empty($desc) && ($desc != $label)) - { - if ($libelleproduitservice && empty($hidedesc)) - { + if (!empty($desc) && ($desc != $label)) { + if ($libelleproduitservice && empty($hidedesc)) { $libelleproduitservice .= '__N__'; } - if ($desc == '(CREDIT_NOTE)' && $object->lines[$i]->fk_remise_except) - { + if ($desc == '(CREDIT_NOTE)' && $object->lines[$i]->fk_remise_except) { $discount = new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); $sourceref = !empty($discount->discount_type) ? $discount->ref_invoive_supplier_source : $discount->ref_facture_source; $libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromCreditNote", $sourceref); - } elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except) - { + } elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except) { $discount = new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); $sourceref = !empty($discount->discount_type) ? $discount->ref_invoive_supplier_source : $discount->ref_facture_source; $libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromDeposit", $sourceref); // Add date of deposit - if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) $libelleproduitservice .= ' ('.dol_print_date($discount->datec, 'day', '', $outputlangs).')'; - } elseif ($desc == '(EXCESS RECEIVED)' && $object->lines[$i]->fk_remise_except) - { + if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) { + $libelleproduitservice .= ' ('.dol_print_date($discount->datec, 'day', '', $outputlangs).')'; + } + } elseif ($desc == '(EXCESS RECEIVED)' && $object->lines[$i]->fk_remise_except) { $discount = new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); $libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived", $discount->ref_facture_source); - } elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except) - { + } elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except) { $discount = new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); $libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid", $discount->ref_invoice_supplier_source); @@ -1371,7 +1408,9 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, if ($issupplierline) { if (empty($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES)) { // Common case $ref_prodserv = $prodser->ref; // Show local ref - if ($ref_supplier) $ref_prodserv .= ($prodser->ref ? ' (' : '').$outputlangs->transnoentitiesnoconv("SupplierRef").' '.$ref_supplier.($prodser->ref ? ')' : ''); + if ($ref_supplier) { + $ref_prodserv .= ($prodser->ref ? ' (' : '').$outputlangs->transnoentitiesnoconv("SupplierRef").' '.$ref_supplier.($prodser->ref ? ')' : ''); + } } elseif ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 1) { $ref_prodserv = $ref_supplier; } elseif ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 2) { @@ -1381,69 +1420,68 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $ref_prodserv = $prodser->ref; // Show local ref only if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { - $productCustomerPriceStatic = new Productcustomerprice($db); - $filter = array('fk_product' => $idprod, 'fk_soc' => $object->socid); + $productCustomerPriceStatic = new Productcustomerprice($db); + $filter = array('fk_product' => $idprod, 'fk_soc' => $object->socid); - $nbCustomerPrices = $productCustomerPriceStatic->fetch_all('', '', 1, 0, $filter); + $nbCustomerPrices = $productCustomerPriceStatic->fetch_all('', '', 1, 0, $filter); - if ($nbCustomerPrices > 0) { - $productCustomerPrice = $productCustomerPriceStatic->lines[0]; + if ($nbCustomerPrices > 0) { + $productCustomerPrice = $productCustomerPriceStatic->lines[0]; - if (! empty($productCustomerPrice->ref_customer)) { - switch ($conf->global->PRODUIT_CUSTOMER_PRICES_PDF_REF_MODE) { - case 1: - $ref_prodserv = $productCustomerPrice->ref_customer; - break; + if (! empty($productCustomerPrice->ref_customer)) { + switch ($conf->global->PRODUIT_CUSTOMER_PRICES_PDF_REF_MODE) { + case 1: + $ref_prodserv = $productCustomerPrice->ref_customer; + break; - case 2: - $ref_prodserv = $productCustomerPrice->ref_customer . ' (' . $outputlangs->transnoentitiesnoconv('InternalRef') . ' ' . $ref_prodserv . ')'; - break; + case 2: + $ref_prodserv = $productCustomerPrice->ref_customer . ' (' . $outputlangs->transnoentitiesnoconv('InternalRef') . ' ' . $ref_prodserv . ')'; + break; - default: - $ref_prodserv = $ref_prodserv . ' (' . $outputlangs->transnoentitiesnoconv('RefCustomer') . ' ' . $productCustomerPrice->ref_customer . ')'; - } - } - } + default: + $ref_prodserv = $ref_prodserv . ' (' . $outputlangs->transnoentitiesnoconv('RefCustomer') . ' ' . $productCustomerPrice->ref_customer . ')'; + } + } + } } } - if (!empty($libelleproduitservice) && !empty($ref_prodserv)) $ref_prodserv .= " - "; + if (!empty($libelleproduitservice) && !empty($ref_prodserv)) { + $ref_prodserv .= " - "; + } } - if (!empty($ref_prodserv) && !empty($conf->global->PDF_BOLD_PRODUCT_REF_AND_PERIOD)) { $ref_prodserv = ''.$ref_prodserv.''; } + if (!empty($ref_prodserv) && !empty($conf->global->PDF_BOLD_PRODUCT_REF_AND_PERIOD)) { + $ref_prodserv = ''.$ref_prodserv.''; + } $libelleproduitservice = $prefix_prodserv.$ref_prodserv.$libelleproduitservice; // Add an additional description for the category products - if (!empty($conf->global->CATEGORY_ADD_DESC_INTO_DOC) && $idprod && !empty($conf->categorie->enabled)) - { + if (!empty($conf->global->CATEGORY_ADD_DESC_INTO_DOC) && $idprod && !empty($conf->categorie->enabled)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $categstatic = new Categorie($db); // recovering the list of all the categories linked to product $tblcateg = $categstatic->containing($idprod, Categorie::TYPE_PRODUCT); - foreach ($tblcateg as $cate) - { + foreach ($tblcateg as $cate) { // Adding the descriptions if they are filled $desccateg = $cate->description; - if ($desccateg) + if ($desccateg) { $libelleproduitservice .= '__N__'.$desccateg; + } } } - if (!empty($object->lines[$i]->date_start) || !empty($object->lines[$i]->date_end)) - { + if (!empty($object->lines[$i]->date_start) || !empty($object->lines[$i]->date_end)) { $format = 'day'; $period = ''; // Show duration if exists - if ($object->lines[$i]->date_start && $object->lines[$i]->date_end) - { + if ($object->lines[$i]->date_start && $object->lines[$i]->date_end) { $period = '('.$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs), dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')'; } - if ($object->lines[$i]->date_start && !$object->lines[$i]->date_end) - { + if ($object->lines[$i]->date_start && !$object->lines[$i]->date_end) { $period = '('.$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs)).')'; } - if (!$object->lines[$i]->date_start && $object->lines[$i]->date_end) - { + if (!$object->lines[$i]->date_start && $object->lines[$i]->date_end) { $period = '('.$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')'; } //print '>'.$outputlangs->charset_output.','.$period; @@ -1455,23 +1493,30 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, //print $libelleproduitservice; } - if ($dbatch) - { + if ($dbatch) { $format = 'day'; - foreach ($dbatch as $detail) - { + foreach ($dbatch as $detail) { $dte = array(); - if ($detail->eatby) $dte[] = $outputlangs->transnoentitiesnoconv('printEatby', dol_print_date($detail->eatby, $format, false, $outputlangs)); - if ($detail->sellby) $dte[] = $outputlangs->transnoentitiesnoconv('printSellby', dol_print_date($detail->sellby, $format, false, $outputlangs)); - if ($detail->batch) $dte[] = $outputlangs->transnoentitiesnoconv('printBatch', $detail->batch); + if ($detail->eatby) { + $dte[] = $outputlangs->transnoentitiesnoconv('printEatby', dol_print_date($detail->eatby, $format, false, $outputlangs)); + } + if ($detail->sellby) { + $dte[] = $outputlangs->transnoentitiesnoconv('printSellby', dol_print_date($detail->sellby, $format, false, $outputlangs)); + } + if ($detail->batch) { + $dte[] = $outputlangs->transnoentitiesnoconv('printBatch', $detail->batch); + } $dte[] = $outputlangs->transnoentitiesnoconv('printQty', $detail->qty); $libelleproduitservice .= "__N__ ".implode(" - ", $dte); } } // Now we convert \n into br - if (dol_textishtml($libelleproduitservice)) $libelleproduitservice = preg_replace('/__N__/', '
    ', $libelleproduitservice); - else $libelleproduitservice = preg_replace('/__N__/', "\n", $libelleproduitservice); + if (dol_textishtml($libelleproduitservice)) { + $libelleproduitservice = preg_replace('/__N__/', '
    ', $libelleproduitservice); + } else { + $libelleproduitservice = preg_replace('/__N__/', "\n", $libelleproduitservice); + } $libelleproduitservice = dol_htmlentitiesbr($libelleproduitservice, 1); return $libelleproduitservice; @@ -1493,17 +1538,17 @@ function pdf_getlinenum($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlinenum', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $result .= $hookmanager->resPrint; } - if (empty($reshook)) - { + if (empty($reshook)) { $result .= dol_htmlentitiesbr($object->lines[$i]->num); } return $result; @@ -1526,17 +1571,17 @@ function pdf_getlineref($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineref', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $result .= $hookmanager->resPrint; } - if (empty($reshook)) - { + if (empty($reshook)) { $result .= dol_htmlentitiesbr($object->lines[$i]->product_ref); } return $result; @@ -1558,17 +1603,17 @@ function pdf_getlineref_supplier($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineref_supplier', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $result .= $hookmanager->resPrint; } - if (empty($reshook)) - { + if (empty($reshook)) { $result .= dol_htmlentitiesbr($object->lines[$i]->ref_supplier); } return $result; @@ -1590,38 +1635,41 @@ function pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails = 0) $result = ''; $reshook = 0; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduce this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduce this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlinevatrate', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if (empty($hidedetails) || $hidedetails > 1) - { + if (empty($reshook)) { + if (empty($hidedetails) || $hidedetails > 1) { $tmpresult = ''; $tmpresult .= vatrate($object->lines[$i]->tva_tx, 0, $object->lines[$i]->info_bits, -1); - if (empty($conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX)) - { - if ($object->lines[$i]->total_localtax1 != 0) - { - if (preg_replace('/[\s0%]/', '', $tmpresult)) $tmpresult .= '/'; - else $tmpresult = ''; + if (empty($conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX)) { + if ($object->lines[$i]->total_localtax1 != 0) { + if (preg_replace('/[\s0%]/', '', $tmpresult)) { + $tmpresult .= '/'; + } else { + $tmpresult = ''; + } $tmpresult .= vatrate(abs($object->lines[$i]->localtax1_tx), 0); } } - if (empty($conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX)) - { - if ($object->lines[$i]->total_localtax2 != 0) - { - if (preg_replace('/[\s0%]/', '', $tmpresult)) $tmpresult .= '/'; - else $tmpresult = ''; + if (empty($conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX)) { + if ($object->lines[$i]->total_localtax2 != 0) { + if (preg_replace('/[\s0%]/', '', $tmpresult)) { + $tmpresult .= '/'; + } else { + $tmpresult = ''; + } $tmpresult .= vatrate(abs($object->lines[$i]->localtax2_tx), 0); } } @@ -1647,25 +1695,28 @@ function pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails = 0) global $conf, $hookmanager; $sign = 1; - if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) { + $sign = -1; + } $result = ''; $reshook = 0; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineupexcltax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if (empty($hidedetails) || $hidedetails > 1) - { + if (empty($reshook)) { + if (empty($hidedetails) || $hidedetails > 1) { $subprice = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_subprice : $object->lines[$i]->subprice); $result .= price($sign * $subprice, 0, $outputlangs); } @@ -1687,24 +1738,30 @@ function pdf_getlineupwithtax($object, $i, $outputlangs, $hidedetails = 0) global $hookmanager, $conf; $sign = 1; - if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) { + $sign = -1; + } $result = ''; $reshook = 0; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineupwithtax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if (empty($hidedetails) || $hidedetails > 1) $result .= price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice) * ($object->lines[$i]->tva_tx) / 100), 0, $outputlangs); + if (empty($reshook)) { + if (empty($hidedetails) || $hidedetails > 1) { + $result .= price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice) * ($object->lines[$i]->tva_tx) / 100), 0, $outputlangs); + } } return $result; } @@ -1725,20 +1782,26 @@ function pdf_getlineqty($object, $i, $outputlangs, $hidedetails = 0) $result = ''; $reshook = 0; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineqty', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result = $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result = $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty; + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + return ''; + } + if (empty($hidedetails) || $hidedetails > 1) { + $result .= $object->lines[$i]->qty; + } } return $result; } @@ -1759,20 +1822,26 @@ function pdf_getlineqty_asked($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineqty_asked', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_asked; + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + return ''; + } + if (empty($hidedetails) || $hidedetails > 1) { + $result .= $object->lines[$i]->qty_asked; + } } return $result; } @@ -1793,20 +1862,26 @@ function pdf_getlineqty_shipped($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineqty_shipped', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_shipped; + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + return ''; + } + if (empty($hidedetails) || $hidedetails > 1) { + $result .= $object->lines[$i]->qty_shipped; + } } return $result; } @@ -1827,20 +1902,26 @@ function pdf_getlineqty_keeptoship($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineqty_keeptoship', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result .= ($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped); + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + return ''; + } + if (empty($hidedetails) || $hidedetails > 1) { + $result .= ($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped); + } } return $result; } @@ -1862,8 +1943,7 @@ function pdf_getlineunit($object, $i, $outputlangs, $hidedetails = 0, $hookmanag $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; if (!empty($object->lines[$i]->fk_parent_line)) { $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); @@ -1877,11 +1957,14 @@ function pdf_getlineunit($object, $i, $outputlangs, $hidedetails = 0, $hookmanag $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineunit', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if (empty($hidedetails) || $hidedetails > 1) $result .= $langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short')); + if (empty($reshook)) { + if (empty($hidedetails) || $hidedetails > 1) { + $result .= $langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short')); + } } return $result; } @@ -1905,20 +1988,26 @@ function pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineremisepercent', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result .= dol_print_reduction($object->lines[$i]->remise_percent, $outputlangs); + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + return ''; + } + if (empty($hidedetails) || $hidedetails > 1) { + $result .= dol_print_reduction($object->lines[$i]->remise_percent, $outputlangs); + } } return $result; } @@ -1935,37 +2024,42 @@ function pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails = 0) */ function pdf_getlineprogress($object, $i, $outputlangs, $hidedetails = 0, $hookmanager = null) { - if (empty($hookmanager)) global $hookmanager; + if (empty($hookmanager)) { + global $hookmanager; + } global $conf; $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i' => $i, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'special_code' => $special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineprogress', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) return $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + return $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) - { - if ($conf->global->SITUATION_DISPLAY_DIFF_ON_PDF) - { + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + return ''; + } + if (empty($hidedetails) || $hidedetails > 1) { + if ($conf->global->SITUATION_DISPLAY_DIFF_ON_PDF) { $prev_progress = 0; - if (method_exists($object, 'get_prev_progress')) - { - $prev_progress = $object->lines[$i]->get_prev_progress($object->id); + if (method_exists($object, 'get_prev_progress')) { + $prev_progress = $object->lines[$i]->get_prev_progress($object->id); } - $result = ($object->lines[$i]->situation_percent - $prev_progress).'%'; - } else $result = $object->lines[$i]->situation_percent.'%'; - } + $result = round($object->lines[$i]->situation_percent - $prev_progress, 1).'%'; + } else { + $result = round($object->lines[$i]->situation_percent, 1).'%'; + } + } } return $result; } @@ -1984,37 +2078,36 @@ function pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails = 0) global $conf, $hookmanager; $sign = 1; - if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) { + $sign = -1; + } $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code, 'sign'=>$sign); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlinetotalexcltax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; - } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) - { - $result .= $outputlangs->transnoentities("Option"); + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; } - elseif (empty($hidedetails) || $hidedetails > 1) - { + } + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + $result .= $outputlangs->transnoentities("Option"); + } elseif (empty($hidedetails) || $hidedetails > 1) { $total_ht = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_total_ht : $object->lines[$i]->total_ht); - if (!empty($object->lines[$i]->situation_percent) && $object->lines[$i]->situation_percent > 0) - { + if (!empty($object->lines[$i]->situation_percent) && $object->lines[$i]->situation_percent > 0) { // TODO Remove this. The total should be saved correctly in database instead of being modified here. $prev_progress = 0; $progress = 1; - if (method_exists($object->lines[$i], 'get_prev_progress')) - { + if (method_exists($object->lines[$i], 'get_prev_progress')) { $prev_progress = $object->lines[$i]->get_prev_progress($object->id); $progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100; } @@ -2041,37 +2134,36 @@ function pdf_getlinetotalwithtax($object, $i, $outputlangs, $hidedetails = 0) global $hookmanager, $conf; $sign = 1; - if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) { + $sign = -1; + } $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlinetotalwithtax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; - } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) - { - $result .= $outputlangs->transnoentities("Option"); + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; } - elseif (empty($hidedetails) || $hidedetails > 1) - { + } + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + $result .= $outputlangs->transnoentities("Option"); + } elseif (empty($hidedetails) || $hidedetails > 1) { $total_ttc = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_total_ttc : $object->lines[$i]->total_ttc); - if ($object->lines[$i]->situation_percent > 0) - { + if ($object->lines[$i]->situation_percent > 0) { // TODO Remove this. The total should be saved correctly in database instead of being modified here. $prev_progress = 0; $progress = 1; - if (method_exists($object->lines[$i], 'get_prev_progress')) - { + if (method_exists($object->lines[$i], 'get_prev_progress')) { $prev_progress = $object->lines[$i]->get_prev_progress($object->id); $progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100; } @@ -2101,26 +2193,22 @@ function pdf_getTotalQty($object, $type, $outputlangs) $nblines = count($object->lines); // Loop on each lines - for ($i = 0; $i < $nblines; $i++) - { - if ($object->lines[$i]->special_code != 3) - { - if ($type == 'all') - { + for ($i = 0; $i < $nblines; $i++) { + if ($object->lines[$i]->special_code != 3) { + if ($type == 'all') { $total += $object->lines[$i]->qty; - } elseif ($type == 9 && is_object($hookmanager) && (($object->lines[$i]->product_type == 9 && !empty($object->lines[$i]->special_code)) || !empty($object->lines[$i]->fk_parent_line))) - { + } elseif ($type == 9 && is_object($hookmanager) && (($object->lines[$i]->product_type == 9 && !empty($object->lines[$i]->special_code)) || !empty($object->lines[$i]->fk_parent_line))) { $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getTotalQty', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks return $hookmanager->resPrint; - } elseif ($type == 0 && $object->lines[$i]->product_type == 0) - { + } elseif ($type == 0 && $object->lines[$i]->product_type == 0) { $total += $object->lines[$i]->qty; - } elseif ($type == 1 && $object->lines[$i]->product_type == 1) - { + } elseif ($type == 1 && $object->lines[$i]->product_type == 1) { $total += $object->lines[$i]->qty; } } @@ -2145,81 +2233,73 @@ function pdf_getLinkedObjects($object, $outputlangs) $object->fetchObjectLinked(); - foreach ($object->linkedObjects as $objecttype => $objects) - { - if ($objecttype == 'facture') - { + foreach ($object->linkedObjects as $objecttype => $objects) { + if ($objecttype == 'facture') { // For invoice, we don't want to have a reference line on document. Image we are using recuring invoice, we will have a line longer than document width. - } elseif ($objecttype == 'propal' || $objecttype == 'supplier_proposal') - { + } elseif ($objecttype == 'propal' || $objecttype == 'supplier_proposal') { $outputlangs->load('propal'); - foreach ($objects as $elementobject) - { + foreach ($objects as $elementobject) { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefProposal"); $linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref); $linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DatePropal"); $linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date, 'day', '', $outputlangs); } - } elseif ($objecttype == 'commande' || $objecttype == 'supplier_order') - { + } elseif ($objecttype == 'commande' || $objecttype == 'supplier_order') { $outputlangs->load('orders'); - foreach ($objects as $elementobject) - { + foreach ($objects as $elementobject) { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder"); $linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref).($elementobject->ref_client ? ' ('.$elementobject->ref_client.')' : '').($elementobject->ref_supplier ? ' ('.$elementobject->ref_supplier.')' : ''); $linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate"); $linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date, 'day', '', $outputlangs); } - } elseif ($objecttype == 'contrat') - { + } elseif ($objecttype == 'contrat') { $outputlangs->load('contracts'); - foreach ($objects as $elementobject) - { + foreach ($objects as $elementobject) { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefContract"); $linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref); $linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateContract"); $linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date_contrat, 'day', '', $outputlangs); } - } elseif ($objecttype == 'fichinter') - { + } elseif ($objecttype == 'fichinter') { $outputlangs->load('interventions'); - foreach ($objects as $elementobject) - { + foreach ($objects as $elementobject) { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("InterRef"); $linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref); $linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("InterDate"); $linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->datec, 'day', '', $outputlangs); } - } elseif ($objecttype == 'shipping') - { + } elseif ($objecttype == 'shipping') { $outputlangs->loadLangs(array("orders", "sendings")); - foreach ($objects as $x => $elementobject) - { + foreach ($objects as $x => $elementobject) { $order = null; // We concat this record info into fields xxx_value. title is overwrote. - if (empty($object->linkedObjects['commande']) && $object->element != 'commande') // There is not already a link to order and object is not the order, so we show also info with order - { + if (empty($object->linkedObjects['commande']) && $object->element != 'commande') { // There is not already a link to order and object is not the order, so we show also info with order $elementobject->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); if (!empty($elementobject->linkedObjectsIds['commande'])) { include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $order = new Commande($db); $ret = $order->fetch(reset($elementobject->linkedObjectsIds['commande'])); - if ($ret < 1) { $order = null; } + if ($ret < 1) { + $order = null; + } } } - if (!is_object($order)) - { + if (!is_object($order)) { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefSending"); - if (!empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'] .= ' / '; + if (!empty($linkedobjects[$objecttype]['ref_value'])) { + $linkedobjects[$objecttype]['ref_value'] .= ' / '; + } $linkedobjects[$objecttype]['ref_value'] .= $outputlangs->transnoentities($elementobject->ref); //$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateShipment"); //if (! empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'].=' / '; //$linkedobjects[$objecttype]['date_value'].= dol_print_date($elementobject->date_delivery,'day','',$outputlangs); } else { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder").' / '.$outputlangs->transnoentities("RefSending"); - if (empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'] = $outputlangs->convToOutputCharset($order->ref).($order->ref_client ? ' ('.$order->ref_client.')' : ''); + if (empty($linkedobjects[$objecttype]['ref_value'])) { + $linkedobjects[$objecttype]['ref_value'] = $outputlangs->convToOutputCharset($order->ref).($order->ref_client ? ' ('.$order->ref_client.')' : ''); + } $linkedobjects[$objecttype]['ref_value'] .= ' / '.$outputlangs->transnoentities($elementobject->ref); //$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate") . ($elementobject->date_delivery ? ' / ' . $outputlangs->transnoentities("DateShipment") : ''); //if (empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'] = dol_print_date($order->date,'day','',$outputlangs); @@ -2230,12 +2310,13 @@ function pdf_getLinkedObjects($object, $outputlangs) } // For add external linked objects - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('linkedobjects' => $linkedobjects, 'outputlangs'=>$outputlangs); $action = ''; $hookmanager->executeHooks('pdf_getLinkedObjects', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resArray)) $linkedobjects = $hookmanager->resArray; + if (!empty($hookmanager->resArray)) { + $linkedobjects = $hookmanager->resArray; + } } return $linkedobjects; @@ -2256,11 +2337,9 @@ function pdf_getSizeForImage($realpath) $maxheight = (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT) ? 32 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT); include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; $tmp = dol_getImageSize($realpath); - if ($tmp['height']) - { + if ($tmp['height']) { $width = (int) round($maxheight * $tmp['width'] / $tmp['height']); // I try to use maxheight - if ($width > $maxwidth) // Pb with maxheight, so i use maxwidth - { + if ($width > $maxwidth) { // Pb with maxheight, so i use maxwidth $width = $maxwidth; $height = (int) round($maxwidth * $tmp['height'] / $tmp['width']); } else // No pb with maxheight @@ -2284,15 +2363,17 @@ function pdfGetLineTotalDiscountAmount($object, $i, $outputlangs, $hidedetails = { global $conf, $hookmanager; $sign = 1; - if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; - if ($object->lines[$i]->special_code == 3) - { + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) { + $sign = -1; + } + if ($object->lines[$i]->special_code == 3) { return $outputlangs->transnoentities("Option"); } else { - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array( 'i'=>$i, @@ -2303,13 +2384,14 @@ function pdfGetLineTotalDiscountAmount($object, $i, $outputlangs, $hidedetails = $action = ''; - if ($hookmanager->executeHooks('getlinetotalremise', $parameters, $object, $action) > 0) - { + if ($hookmanager->executeHooks('getlinetotalremise', $parameters, $object, $action) > 0) { return $hookmanager->resPrint; // Note that $action and $object may have been modified by some hooks } } - if (empty($hidedetails) || $hidedetails > 1) return $sign * (($object->lines[$i]->subprice * $object->lines[$i]->qty) - $object->lines[$i]->total_ht); + if (empty($hidedetails) || $hidedetails > 1) { + return $sign * (($object->lines[$i]->subprice * $object->lines[$i]->qty) - $object->lines[$i]->total_ht); + } } return ''; } diff --git a/htdocs/core/lib/prelevement.lib.php b/htdocs/core/lib/prelevement.lib.php index 75bf914b964..bc81ee2bfbd 100644 --- a/htdocs/core/lib/prelevement.lib.php +++ b/htdocs/core/lib/prelevement.lib.php @@ -85,14 +85,22 @@ function prelevement_prepare_head(BonPrelevement $object) function prelevement_check_config($type = 'direct-debit') { global $conf, $db; - if ($type == 'bank-transfer'){ - if (empty($conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT)) return -1; + if ($type == 'bank-transfer') { + if (empty($conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT)) { + return -1; + } //if (empty($conf->global->PRELEVEMENT_ICS)) return -1; - if (empty($conf->global->PAYMENTBYBANKTRANSFER_USER)) return -1; - }else { - if (empty($conf->global->PRELEVEMENT_ID_BANKACCOUNT)) return -1; + if (empty($conf->global->PAYMENTBYBANKTRANSFER_USER)) { + return -1; + } + } else { + if (empty($conf->global->PRELEVEMENT_ID_BANKACCOUNT)) { + return -1; + } //if (empty($conf->global->PRELEVEMENT_ICS)) return -1; - if (empty($conf->global->PRELEVEMENT_USER)) return -1; + if (empty($conf->global->PRELEVEMENT_USER)) { + return -1; + } } return 0; } diff --git a/htdocs/core/lib/price.lib.php b/htdocs/core/lib/price.lib.php index 98311d093cd..3a73f47a6a0 100644 --- a/htdocs/core/lib/price.lib.php +++ b/htdocs/core/lib/price.lib.php @@ -90,13 +90,15 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $result = array(); // Clean parameters - if (empty($info_bits)) $info_bits = 0; - if (empty($txtva)) $txtva = 0; - if (empty($seller) || !is_object($seller)) - { + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($txtva)) { + $txtva = 0; + } + if (empty($seller) || !is_object($seller)) { dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter seller that is missing", LOG_WARNING); - if (!is_object($mysoc)) // mysoc may be not defined (during migration process) - { + if (!is_object($mysoc)) { // mysoc may be not defined (during migration process) $mysoc = new Societe($db); $mysoc->setMysoc($conf); } @@ -116,11 +118,19 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $countryid = $seller->country_id; - if (is_numeric($uselocaltax1_rate)) $uselocaltax1_rate = (float) $uselocaltax1_rate; - if (is_numeric($uselocaltax2_rate)) $uselocaltax2_rate = (float) $uselocaltax2_rate; + if (is_numeric($uselocaltax1_rate)) { + $uselocaltax1_rate = (float) $uselocaltax1_rate; + } + if (is_numeric($uselocaltax2_rate)) { + $uselocaltax2_rate = (float) $uselocaltax2_rate; + } - if ($uselocaltax1_rate < 0) $uselocaltax1_rate = $seller->localtax1_assuj; - if ($uselocaltax2_rate < 0) $uselocaltax2_rate = $seller->localtax2_assuj; + if ($uselocaltax1_rate < 0) { + $uselocaltax1_rate = $seller->localtax1_assuj; + } + if ($uselocaltax2_rate < 0) { + $uselocaltax2_rate = $seller->localtax2_assuj; + } //var_dump($uselocaltax1_rate.' - '.$uselocaltax2_rate); dol_syslog('Price.lib::calcul_price_total qty='.$qty.' pu='.$pu.' remise_percent_ligne='.$remise_percent_ligne.' txtva='.$txtva.' uselocaltax1_rate='.$uselocaltax1_rate.' uselocaltax2_rate='.$uselocaltax2_rate.' remise_percent_global='.$remise_percent_global.' price_base_type='.$price_base_type.' type='.$type.' progress='.$progress); @@ -144,33 +154,37 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $sql .= " WHERE cv.taux = ".$txtva; $sql .= " AND cv.fk_pays = ".$countryid; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $localtax1_rate = (float) $obj->localtax1; // Use float to force to get first numeric value when value is x:y:z $localtax2_rate = (float) $obj->localtax2; // Use float to force to get first numeric value when value is -19:-15:-9 $localtax1_type = $obj->localtax1_type; $localtax2_type = $obj->localtax2_type; //var_dump($localtax1_rate.' '.$localtax2_rate.' '.$localtax1_type.' '.$localtax2_type); } - } else dol_print_error($db); + } else { + dol_print_error($db); + } } // pu calculation from pu_devise if pu empty if (empty($pu) && !empty($pu_devise)) { - if (!empty($multicurrency_tx)) $pu = $pu_devise / $multicurrency_tx; - else { + if (!empty($multicurrency_tx)) { + $pu = $pu_devise / $multicurrency_tx; + } else { dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (multicurrency_tx empty when pu_devise not) ', LOG_ERR); return array(); } } - if ($pu === '') $pu = 0; + if ($pu === '') { + $pu = 0; + } // pu_devise calculation from pu if (empty($pu_devise) && !empty($multicurrency_tx)) { - if (is_numeric($pu) && is_numeric($multicurrency_tx)) $pu_devise = $pu * $multicurrency_tx; - else { + if (is_numeric($pu) && is_numeric($multicurrency_tx)) { + $pu_devise = $pu * $multicurrency_tx; + } else { dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (pu or multicurrency_tx are not numeric)', LOG_ERR); return array(); } @@ -182,13 +196,14 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $tot_avec_remise = $tot_avec_remise_ligne * (1 - ($remise_percent_global / 100)); // initialize result array - for ($i = 0; $i <= 15; $i++) $result[$i] = 0; + for ($i = 0; $i <= 15; $i++) { + $result[$i] = 0; + } // if there's some localtax including vat, we calculate localtaxes (we will add later) // if input unit price is 'HT', we need to have the totals with main VAT for a correct calculation - if ($price_base_type != 'TTC') - { + if ($price_base_type != 'TTC') { $tot_sans_remise_wt = price2num($tot_sans_remise * (1 + ($txtva / 100)), 'MU'); $tot_avec_remise_wt = price2num($tot_avec_remise * (1 + ($txtva / 100)), 'MU'); $pu_wt = price2num($pu * (1 + ($txtva / 100)), 'MU'); @@ -207,22 +222,26 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $apply_tax = true; break; case '4': // localtax on product - if ($type == 0) $apply_tax = true; + if ($type == 0) { + $apply_tax = true; + } break; case '6': // localtax on service - if ($type == 1) $apply_tax = true; + if ($type == 1) { + $apply_tax = true; + } break; } if ($uselocaltax1_rate && $apply_tax) { - $result[14] = price2num(($tot_sans_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_sans_remise_wt, 'MT'); - $localtaxes[0] += $result[14]; + $result[14] = price2num(($tot_sans_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_sans_remise_wt, 'MT'); + $localtaxes[0] += $result[14]; - $result[9] = price2num(($tot_avec_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_avec_remise_wt, 'MT'); - $localtaxes[1] += $result[9]; + $result[9] = price2num(($tot_avec_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_avec_remise_wt, 'MT'); + $localtaxes[1] += $result[9]; - $result[11] = price2num(($pu_wt * (1 + ($localtax1_rate / 100))) - $pu_wt, 'MU'); - $localtaxes[2] += $result[11]; + $result[11] = price2num(($pu_wt * (1 + ($localtax1_rate / 100))) - $pu_wt, 'MU'); + $localtaxes[2] += $result[11]; } $apply_tax = false; @@ -231,26 +250,29 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $apply_tax = true; break; case '4': // localtax on product - if ($type == 0) $apply_tax = true; + if ($type == 0) { + $apply_tax = true; + } break; case '6': // localtax on service - if ($type == 1) $apply_tax = true; + if ($type == 1) { + $apply_tax = true; + } break; } if ($uselocaltax2_rate && $apply_tax) { - $result[15] = price2num(($tot_sans_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_sans_remise_wt, 'MT'); - $localtaxes[0] += $result[15]; + $result[15] = price2num(($tot_sans_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_sans_remise_wt, 'MT'); + $localtaxes[0] += $result[15]; - $result[10] = price2num(($tot_avec_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_avec_remise_wt, 'MT'); - $localtaxes[1] += $result[10]; + $result[10] = price2num(($tot_avec_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_avec_remise_wt, 'MT'); + $localtaxes[1] += $result[10]; - $result[12] = price2num(($pu_wt * (1 + ($localtax2_rate / 100))) - $pu_wt, 'MU'); - $localtaxes[2] += $result[12]; + $result[12] = price2num(($pu_wt * (1 + ($localtax2_rate / 100))) - $pu_wt, 'MU'); + $localtaxes[2] += $result[12]; } //dol_syslog("price.lib::calcul_price_total $qty, $pu, $remise_percent_ligne, $txtva, $price_base_type $info_bits"); - if ($price_base_type == 'HT') - { + if ($price_base_type == 'HT') { // We work to define prices using the price without tax $result[6] = price2num($tot_sans_remise, 'MT'); $result[8] = price2num($tot_sans_remise * (1 + ((($info_bits & 1) ? 0 : $txtva) / 100)) + $localtaxes[0], 'MT'); // Selon TVA NPR ou non @@ -287,8 +309,7 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt // if there's some localtax without vat, we calculate localtaxes (we will add them at end) //If input unit price is 'TTC', we need to have the totals without main VAT for a correct calculation - if ($price_base_type == 'TTC') - { + if ($price_base_type == 'TTC') { $tot_sans_remise = price2num($tot_sans_remise / (1 + ($txtva / 100)), 'MU'); $tot_avec_remise = price2num($tot_avec_remise / (1 + ($txtva / 100)), 'MU'); $pu = price2num($pu / (1 + ($txtva / 100)), 'MU'); @@ -300,21 +321,25 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $apply_tax = true; break; case '3': // localtax on product - if ($type == 0) $apply_tax = true; + if ($type == 0) { + $apply_tax = true; + } break; case '5': // localtax on service - if ($type == 1) $apply_tax = true; + if ($type == 1) { + $apply_tax = true; + } break; } if ($uselocaltax1_rate && $apply_tax) { - $result[14] = price2num(($tot_sans_remise * (1 + ($localtax1_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax1 for total_ht_without_discount - $result[8] += $result[14]; // total_ttc_without_discount + tax1 + $result[14] = price2num(($tot_sans_remise * (1 + ($localtax1_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax1 for total_ht_without_discount + $result[8] += $result[14]; // total_ttc_without_discount + tax1 - $result[9] = price2num(($tot_avec_remise * (1 + ($localtax1_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax1 for total_ht - $result[2] += $result[9]; // total_ttc + tax1 + $result[9] = price2num(($tot_avec_remise * (1 + ($localtax1_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax1 for total_ht + $result[2] += $result[9]; // total_ttc + tax1 - $result[11] = price2num(($pu * (1 + ($localtax1_rate / 100))) - $pu, 'MU'); // amount tax1 for pu_ht - $result[5] += $result[11]; // pu_ht + tax1 + $result[11] = price2num(($pu * (1 + ($localtax1_rate / 100))) - $pu, 'MU'); // amount tax1 for pu_ht + $result[5] += $result[11]; // pu_ht + tax1 } $apply_tax = false; @@ -323,28 +348,30 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $apply_tax = true; break; case '3': // localtax on product - if ($type == 0) $apply_tax = true; + if ($type == 0) { + $apply_tax = true; + } break; case '5': // localtax on service - if ($type == 1) $apply_tax = true; + if ($type == 1) { + $apply_tax = true; + } break; } if ($uselocaltax2_rate && $apply_tax) { - $result[15] = price2num(($tot_sans_remise * (1 + ($localtax2_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax2 for total_ht_without_discount - $result[8] += $result[15]; // total_ttc_without_discount + tax2 + $result[15] = price2num(($tot_sans_remise * (1 + ($localtax2_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax2 for total_ht_without_discount + $result[8] += $result[15]; // total_ttc_without_discount + tax2 - $result[10] = price2num(($tot_avec_remise * (1 + ($localtax2_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax2 for total_ht - $result[2] += $result[10]; // total_ttc + tax2 + $result[10] = price2num(($tot_avec_remise * (1 + ($localtax2_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax2 for total_ht + $result[2] += $result[10]; // total_ttc + tax2 - $result[12] = price2num(($pu * (1 + ($localtax2_rate / 100))) - $pu, 'MU'); // amount tax2 for pu_ht - $result[5] += $result[12]; // pu_ht + tax2 + $result[12] = price2num(($pu * (1 + ($localtax2_rate / 100))) - $pu, 'MU'); // amount tax2 for pu_ht + $result[5] += $result[12]; // pu_ht + tax2 } // If rounding is not using base 10 (rare) - if (!empty($conf->global->MAIN_ROUNDING_RULE_TOT)) - { - if ($price_base_type == 'HT') - { + if (!empty($conf->global->MAIN_ROUNDING_RULE_TOT)) { + if ($price_base_type == 'HT') { $result[0] = round($result[0] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT; $result[1] = round($result[1] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT; $result[9] = round($result[9] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT; @@ -360,8 +387,7 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt } // Multicurrency - if ($multicurrency_tx != 1) - { + if ($multicurrency_tx != 1) { if ($multicurrency_code) { $savMAIN_MAX_DECIMALS_UNIT = $conf->global->MAIN_MAX_DECIMALS_UNIT; $savMAIN_MAX_DECIMALS_TOT = $conf->global->MAIN_MAX_DECIMALS_TOT; diff --git a/htdocs/core/lib/product.lib.php b/htdocs/core/lib/product.lib.php index 9ce8d84d7e3..d5d52761140 100644 --- a/htdocs/core/lib/product.lib.php +++ b/htdocs/core/lib/product.lib.php @@ -38,7 +38,9 @@ function product_prepare_head($object) $langs->load("products"); $label = $langs->trans('Product'); - if ($object->isService()) $label = $langs->trans('Service'); + if ($object->isService()) { + $label = $langs->trans('Service'); + } $h = 0; $head = array(); @@ -48,20 +50,17 @@ function product_prepare_head($object) $head[$h][2] = 'card'; $h++; - if (!empty($object->status)) - { + if (!empty($object->status)) { $head[$h][0] = DOL_URL_ROOT."/product/price.php?id=".$object->id; $head[$h][1] = $langs->trans("SellingPrices"); $head[$h][2] = 'price'; $h++; } - if (!empty($object->status_buy) || (!empty($conf->margin->enabled) && !empty($object->status))) // If margin is on and product on sell, we may need the cost price even if product os not on purchase - { + if (!empty($object->status_buy) || (!empty($conf->margin->enabled) && !empty($object->status))) { // If margin is on and product on sell, we may need the cost price even if product os not on purchase if (((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->lire) || (!empty($conf->margin->enabled) && $user->rights->margin->liretous) - ) - { + ) { $head[$h][0] = DOL_URL_ROOT."/product/fournisseurs.php?id=".$object->id; $head[$h][1] = $langs->trans("BuyingPrices"); $head[$h][2] = 'suppliers'; @@ -70,8 +69,7 @@ function product_prepare_head($object) } // Multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { $head[$h][0] = DOL_URL_ROOT."/product/traduction.php?id=".$object->id; $head[$h][1] = $langs->trans("Translation"); $head[$h][2] = 'translation'; @@ -79,13 +77,14 @@ function product_prepare_head($object) } // Sub products - if (!empty($conf->global->PRODUIT_SOUSPRODUITS)) - { + if (!empty($conf->global->PRODUIT_SOUSPRODUITS)) { $head[$h][0] = DOL_URL_ROOT."/product/composition/card.php?id=".$object->id; $head[$h][1] = $langs->trans('AssociatedProducts'); $nbFatherAndChild = $object->hasFatherOrChild(); - if ($nbFatherAndChild > 0) $head[$h][1] .= ''.$nbFatherAndChild.''; + if ($nbFatherAndChild > 0) { + $head[$h][1] .= ''.$nbFatherAndChild.''; + } $head[$h][2] = 'subproduct'; $h++; } @@ -97,22 +96,21 @@ function product_prepare_head($object) $prodcomb = new ProductCombination($db); - if ($prodcomb->fetchByFkProductChild($object->id) <= 0) - { + if ($prodcomb->fetchByFkProductChild($object->id) <= 0) { $head[$h][0] = DOL_URL_ROOT."/variants/combinations.php?id=".$object->id; $head[$h][1] = $langs->trans('ProductCombinations'); $head[$h][2] = 'combinations'; $nbVariant = $prodcomb->countNbOfCombinationForFkProductParent($object->id); - if ($nbVariant > 0) $head[$h][1] .= ''.$nbVariant.''; + if ($nbVariant > 0) { + $head[$h][1] .= ''.$nbVariant.''; + } } $h++; } - if ($object->isProduct() || ($object->isService() && !empty($conf->global->STOCK_SUPPORTS_SERVICES))) // If physical product we can stock (or service with option) - { - if (!empty($conf->stock->enabled) && $user->rights->stock->lire) - { + if ($object->isProduct() || ($object->isService() && !empty($conf->global->STOCK_SUPPORTS_SERVICES))) { // If physical product we can stock (or service with option) + if (!empty($conf->stock->enabled) && $user->rights->stock->lire) { $head[$h][0] = DOL_URL_ROOT."/product/stock/product.php?id=".$object->id; $head[$h][1] = $langs->trans("Stock"); $head[$h][2] = 'stock'; @@ -121,17 +119,14 @@ function product_prepare_head($object) } // Tab to link resources - if (!empty($conf->resource->enabled)) - { - if ($object->isProduct() && !empty($conf->global->RESOURCE_ON_PRODUCTS)) - { + if (!empty($conf->resource->enabled)) { + if ($object->isProduct() && !empty($conf->global->RESOURCE_ON_PRODUCTS)) { $head[$h][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=product&ref='.$object->ref; $head[$h][1] = $langs->trans("Resources"); $head[$h][2] = 'resources'; $h++; } - if ($object->isService() && !empty($conf->global->RESOURCE_ON_SERVICES)) - { + if ($object->isService() && !empty($conf->global->RESOURCE_ON_SERVICES)) { $head[$h][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=service&ref='.$object->ref; $head[$h][1] = $langs->trans("Resources"); $head[$h][2] = 'resources'; @@ -156,14 +151,19 @@ function product_prepare_head($object) complete_head_from_modules($conf, $langs, $object, $head, $h, 'product'); // Notes - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/product/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; } @@ -171,18 +171,28 @@ function product_prepare_head($object) // Attachments require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - if (!empty($conf->product->enabled) && ($object->type == Product::TYPE_PRODUCT)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); - if (!empty($conf->service->enabled) && ($object->type == Product::TYPE_SERVICE)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); + if (!empty($conf->product->enabled) && ($object->type == Product::TYPE_PRODUCT)) { + $upload_dir = $conf->product->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); + } + if (!empty($conf->service->enabled) && ($object->type == Product::TYPE_SERVICE)) { + $upload_dir = $conf->service->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); + } $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { - if (!empty($conf->product->enabled) && ($object->type == Product::TYPE_PRODUCT)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'product').$object->id.'/photos'; - if (!empty($conf->service->enabled) && ($object->type == Product::TYPE_SERVICE)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'product').$object->id.'/photos'; + if (!empty($conf->product->enabled) && ($object->type == Product::TYPE_PRODUCT)) { + $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'product').$object->id.'/photos'; + } + if (!empty($conf->service->enabled) && ($object->type == Product::TYPE_SERVICE)) { + $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'product').$object->id.'/photos'; + } $nbFiles += count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); } $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/product/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; @@ -191,8 +201,7 @@ function product_prepare_head($object) // Log $head[$h][0] = DOL_URL_ROOT.'/product/agenda.php?id='.$object->id; $head[$h][1] = $langs->trans("Events"); - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $head[$h][1] .= '/'; $head[$h][1] .= $langs->trans("Agenda"); } @@ -231,7 +240,9 @@ function productlot_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT."/product/stock/productlot_document.php?id=".$object->id; $head[$h][1] = $langs->trans("Documents"); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; @@ -245,11 +256,11 @@ function productlot_prepare_head($object) // Log /* - $head[$h][0] = DOL_URL_ROOT.'/product/info.php?id='.$object->id; - $head[$h][1] = $langs->trans("Info"); - $head[$h][2] = 'info'; - $h++; - */ + $head[$h][0] = DOL_URL_ROOT.'/product/info.php?id='.$object->id; + $head[$h][1] = $langs->trans("Info"); + $head[$h][2] = 'info'; + $h++; + */ return $head; } @@ -273,8 +284,7 @@ function product_admin_prepare_head() $head[$h][2] = 'general'; $h++; - if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($conf->global->PRODUIT_MULTIPRICES_ALLOW_AUTOCALC_PRICELEVEL)) - { + if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($conf->global->PRODUIT_MULTIPRICES_ALLOW_AUTOCALC_PRICELEVEL)) { $head[$h] = array( 0 => DOL_URL_ROOT."/product/admin/price_rules.php", 1 => $langs->trans('MultipriceRules'), @@ -358,14 +368,15 @@ function show_stats_for_company($product, $socid) print ''; // Customer proposals - if (!empty($conf->propal->enabled) && $user->rights->propale->lire) - { + if (!empty($conf->propal->enabled) && $user->rights->propale->lire) { $nblines++; $ret = $product->load_stats_propale($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("propal"); print '
    '; } // Supplier proposals - if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) - { + if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) { $nblines++; $ret = $product->load_stats_proposal_supplier($socid); - if ($ret < 0) dol_print_error($db); - $langs->load("propal"); + if ($ret < 0) { + dol_print_error($db); + } + $langs->load("supplier_proposal"); print ''; } // Customer orders - if (!empty($conf->commande->enabled) && $user->rights->commande->lire) - { + if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { $nblines++; $ret = $product->load_stats_commande($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("orders"); print ''; } // Supplier orders - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && $user->rights->fournisseur->commande->lire) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && $user->rights->fournisseur->commande->lire) { $nblines++; $ret = $product->load_stats_commande_fournisseur($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("orders"); print ''; } // Customer invoices - if (!empty($conf->facture->enabled) && $user->rights->facture->lire) - { + if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $nblines++; $ret = $product->load_stats_facture($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("bills"); print ''; } // Supplier invoices - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) { $nblines++; $ret = $product->load_stats_facture_fournisseur($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("bills"); print ''; print ''; } // MO - if (!empty($conf->mrp->enabled) && $user->rights->mrp->read) - { + if (!empty($conf->mrp->enabled) && $user->rights->mrp->read) { $nblines++; $ret = $product->load_stats_mo($socid); if ($ret < 0) { @@ -519,7 +534,7 @@ function show_stats_for_company($product, $socid) } $langs->load("mrp"); print '"; @@ -522,8 +664,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t // Title of task if (count($arrayfields) > 0 && !empty($arrayfields['t.label']['checked'])) { print "\n"; } @@ -555,15 +699,20 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t if (count($arrayfields) > 0 && !empty($arrayfields['t.datee']['checked'])) { print ''; } $plannedworkloadoutputformat = 'allhourmin'; $timespentoutputformat = 'allhourmin'; - if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; - if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT; + if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) { + $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; + } + if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) { + $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT; + } // Planned Workload (in working hours) if (count($arrayfields) > 0 && !empty($arrayfields['t.planned_workload']['checked'])) { @@ -582,15 +731,21 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t // Time spent if (count($arrayfields) > 0 && !empty($arrayfields['t.duration_effective']['checked'])) { print ''; } @@ -598,9 +753,11 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t if (count($arrayfields) > 0 && !empty($arrayfields['t.progress_calculated']['checked'])) { print ''; } @@ -623,8 +780,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t print ''; } - if ($showbilltime) - { + if ($showbilltime) { // Time not billed if (count($arrayfields) > 0 && !empty($arrayfields['t.tobill']['checked'])) { print ''; + }*/ + + // Contacts of task + if (count($arrayfields) > 0 && !empty($arrayfields['c.assigned']['checked'])) { + print ''; } // Extra fields @@ -685,19 +873,26 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t print "\n"; - if (!$showlineingray) $inc++; + if (!$showlineingray) { + $inc++; + } - if ($level >= 0) // Call sublevels - { + if ($level >= 0) { // Call sublevels $level++; - if ($lines[$i]->id) projectLinesa($inc, $lines[$i]->id, $lines, $level, $var, $showproject, $taskrole, $projectsListId, $addordertick, $projectidfortotallink, $filterprogresscalc, $showbilltime, $arrayfields); + if ($lines[$i]->id) { + projectLinesa($inc, $lines[$i]->id, $lines, $level, $var, $showproject, $taskrole, $projectsListId, $addordertick, $projectidfortotallink, $filterprogresscalc, $showbilltime, $arrayfields); + } $level--; } $total_projectlinesa_spent += $lines[$i]->duration; $total_projectlinesa_planned += $lines[$i]->planned_workload; - if ($lines[$i]->planned_workload) $total_projectlinesa_spent_if_planned += $lines[$i]->duration; - if ($lines[$i]->planned_workload) $total_projectlinesa_declared_if_planned += $lines[$i]->planned_workload * $lines[$i]->progress / 100; + if ($lines[$i]->planned_workload) { + $total_projectlinesa_spent_if_planned += $lines[$i]->duration; + } + if ($lines[$i]->planned_workload) { + $total_projectlinesa_declared_if_planned += $lines[$i]->planned_workload * $lines[$i]->progress / 100; + } } } else { //$level--; @@ -705,14 +900,21 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } if (($total_projectlinesa_planned > 0 || $total_projectlinesa_spent > 0 || $total_projectlinesa_tobill > 0 || $total_projectlinesa_billed > 0) - && $level <= 0) - { + && $level <= 0) { print ''; print ''; - if ($showproject) print ''; - if (count($arrayfields) > 0 && !empty($arrayfields['t.label']['checked'])) print ''; - if (count($arrayfields) > 0 && !empty($arrayfields['t.dateo']['checked'])) print ''; - if (count($arrayfields) > 0 && !empty($arrayfields['t.datee']['checked'])) print ''; + if ($showproject) { + print ''; + } + if (count($arrayfields) > 0 && !empty($arrayfields['t.label']['checked'])) { + print ''; + } + if (count($arrayfields) > 0 && !empty($arrayfields['t.dateo']['checked'])) { + print ''; + } + if (count($arrayfields) > 0 && !empty($arrayfields['t.datee']['checked'])) { + print ''; + } if (count($arrayfields) > 0 && !empty($arrayfields['t.planned_workload']['checked'])) { print ''; } @@ -753,14 +957,16 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t if (count($arrayfields) > 0 && !empty($arrayfields['t.progress_calculated']['checked'])) { print ''; } if (count($arrayfields) > 0 && !empty($arrayfields['t.progress']['checked'])) { print ''; } @@ -778,8 +984,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t print ''; } - if ($showbilltime) - { + if ($showbilltime) { if (count($arrayfields) > 0 && !empty($arrayfields['t.tobill']['checked'])) { print ''; } } + // Contacts of task for backward compatibility, + if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) { + print ''; + } // Contacts of task - if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) - { + if (count($arrayfields) > 0 && !empty($arrayfields['c.assigned']['checked'])) { print ''; } print ''; @@ -834,45 +1042,40 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec $numlines = count($lines); // Create a smaller array with sublevels only to be used later. This increase dramatically performances. - if ($parent == 0) // Always and only if at first level - { - for ($i = 0; $i < $numlines; $i++) - { - if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i]; + if ($parent == 0) { // Always and only if at first level + for ($i = 0; $i < $numlines; $i++) { + if ($lines[$i]->fk_task_parent) { + $lineswithoutlevel0[] = $lines[$i]; + } } } - if (empty($oldprojectforbreak)) - { + if (empty($oldprojectforbreak)) { $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : -1); // 0 to start break , -1 no break } //dol_syslog('projectLinesPerDay inc='.$inc.' preselectedday='.$preselectedday.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); - for ($i = 0; $i < $numlines; $i++) - { - if ($parent == 0) $level = 0; + for ($i = 0; $i < $numlines; $i++) { + if ($parent == 0) { + $level = 0; + } //if ($lines[$i]->fk_task_parent == $parent) //{ // If we want all or we have a role on task, we show it - if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) - { + if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) { //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); // Break on a new project - if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) - { + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) { $lastprojectid = $lines[$i]->fk_project; - if ($preselectedday) - { + if ($preselectedday) { $projectstatic->id = $lines[$i]->fk_project; } } - if (empty($workloadforid[$projectstatic->id])) - { - if ($preselectedday) - { + if (empty($workloadforid[$projectstatic->id])) { + if ($preselectedday) { $projectstatic->loadTimeSpent($preselectedday, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week $workloadforid[$projectstatic->id] = 1; } @@ -894,13 +1097,11 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec $thirdpartystatic->name = $lines[$i]->thirdparty_name; $thirdpartystatic->email = $lines[$i]->thirdparty_email; - if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) - { + if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) { print ''."\n"; print ''; } - if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; + if ($oldprojectforbreak != -1) { + $oldprojectforbreak = $projectstatic->id; + } print ''."\n"; @@ -921,8 +1124,7 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec // Project print "'; // Ref print ''; - $disabledproject = 1; $disabledtask = 1; + $disabledproject = 1; + $disabledtask = 1; //print "x".$lines[$i]->fk_project; //var_dump($lines[$i]); //var_dump($projectsrole[$lines[$i]->fk_project]); // If at least one role for project - if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) - { + if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) { $disabledproject = 0; $disabledtask = 0; } // If $restricteditformytask is on and I have no role on task, i disable edit - if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) - { + if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) { $disabledtask = 1; } @@ -974,9 +1181,13 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec print ''; $cssonholiday = ''; - if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayallday '; - elseif (!$isavailable[$preselectedday]['morning']) $cssonholiday .= 'onholidaymorning '; - elseif (!$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; + if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) { + $cssonholiday .= 'onholidayallday '; + } elseif (!$isavailable[$preselectedday]['morning']) { + $cssonholiday .= 'onholidaymorning '; + } elseif (!$isavailable[$preselectedday]['afternoon']) { + $cssonholiday .= 'onholidayafternoon '; + } // Duration print ''."\n"; print ''; + print '
    '.$langs->trans("Ref").''.$object->id.'
    '.$langs->trans("Ref").''.$object->id.'
    '.$langs->trans("Label").'
    '.$langs->trans("AccountancyCodeAsset").''; @@ -585,8 +588,7 @@ if ($rowid > 0) $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $act, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } diff --git a/htdocs/asterisk/cidlookup.php b/htdocs/asterisk/cidlookup.php index 7a3660e350e..716057198f8 100644 --- a/htdocs/asterisk/cidlookup.php +++ b/htdocs/asterisk/cidlookup.php @@ -33,15 +33,13 @@ $phone = GETPOST('phone'); $notfound = $langs->trans("Unknown"); // Security check -if (empty($conf->clicktodial->enabled)) -{ +if (empty($conf->clicktodial->enabled)) { print "Error: Module Click to dial is not enabled.\n"; exit; } // Check parameters -if (empty($phone)) -{ +if (empty($phone)) { print "Error: Url must be called with parameter phone=phone to search\n"; exit; } @@ -57,11 +55,9 @@ $sql .= $db->plimit(1); dol_syslog('cidlookup search information with phone '.$phone, LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $found = $obj->name; } else { $found = $notfound; diff --git a/htdocs/asterisk/wrapper.php b/htdocs/asterisk/wrapper.php index 0a9ac82ce23..77a00aed302 100644 --- a/htdocs/asterisk/wrapper.php +++ b/htdocs/asterisk/wrapper.php @@ -28,13 +28,27 @@ * write = system,call,log,verbose,command,agent,user */ -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOREQUIRETRAN')) { + define('NOREQUIRETRAN', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} /** * Empty header @@ -67,23 +81,40 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; // Security check -if (empty($conf->clicktodial->enabled)) -{ +if (empty($conf->clicktodial->enabled)) { accessforbidden(); exit; } // Define Asterisk setup -if (!isset($conf->global->ASTERISK_HOST)) $conf->global->ASTERISK_HOST = "127.0.0.1"; -if (!isset($conf->global->ASTERISK_TYPE)) $conf->global->ASTERISK_TYPE = "SIP/"; -if (!isset($conf->global->ASTERISK_INDICATIF)) $conf->global->ASTERISK_INDICATIF = "0"; -if (!isset($conf->global->ASTERISK_PORT)) $conf->global->ASTERISK_PORT = 5038; -if ($conf->global->ASTERISK_INDICATIF == 'NONE') $conf->global->ASTERISK_INDICATIF = ''; -if (!isset($conf->global->ASTERISK_CONTEXT)) $conf->global->ASTERISK_CONTEXT = "from-internal"; -if (!isset($conf->global->ASTERISK_WAIT_TIME)) $conf->global->ASTERISK_WAIT_TIME = "30"; -if (!isset($conf->global->ASTERISK_PRIORITY)) $conf->global->ASTERISK_PRIORITY = "1"; -if (!isset($conf->global->ASTERISK_MAX_RETRY)) $conf->global->ASTERISK_MAX_RETRY = "2"; +if (!isset($conf->global->ASTERISK_HOST)) { + $conf->global->ASTERISK_HOST = "127.0.0.1"; +} +if (!isset($conf->global->ASTERISK_TYPE)) { + $conf->global->ASTERISK_TYPE = "SIP/"; +} +if (!isset($conf->global->ASTERISK_INDICATIF)) { + $conf->global->ASTERISK_INDICATIF = "0"; +} +if (!isset($conf->global->ASTERISK_PORT)) { + $conf->global->ASTERISK_PORT = 5038; +} +if ($conf->global->ASTERISK_INDICATIF == 'NONE') { + $conf->global->ASTERISK_INDICATIF = ''; +} +if (!isset($conf->global->ASTERISK_CONTEXT)) { + $conf->global->ASTERISK_CONTEXT = "from-internal"; +} +if (!isset($conf->global->ASTERISK_WAIT_TIME)) { + $conf->global->ASTERISK_WAIT_TIME = "30"; +} +if (!isset($conf->global->ASTERISK_PRIORITY)) { + $conf->global->ASTERISK_PRIORITY = "1"; +} +if (!isset($conf->global->ASTERISK_MAX_RETRY)) { + $conf->global->ASTERISK_MAX_RETRY = "2"; +} $login = GETPOST('login'); @@ -127,11 +158,9 @@ $sql .= $db->plimit(1); dol_syslog('click to dial search information with phone '.$called, LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $found = $obj->name; } else { $found = $notfound; @@ -144,16 +173,13 @@ if ($resql) $number = strtolower($called); $pos = strpos($number, "local"); -if (!empty($number)) -{ - if ($pos === false) - { +if (!empty($number)) { + if ($pos === false) { $errno = 0; $errstr = 0; $strCallerId = "Dolibarr call $found <".strtolower($number).">"; $oSocket = @fsockopen($strHost, $port, $errno, $errstr, 10); - if (!$oSocket) - { + if (!$oSocket) { print ''."\n"; $txt = "Failed to execute fsockopen($strHost, $port, \$errno, \$errstr, 10)
    \n"; print $txt; diff --git a/htdocs/barcode/codeinit.php b/htdocs/barcode/codeinit.php index 52a11e78bdd..f35547523c9 100644 --- a/htdocs/barcode/codeinit.php +++ b/htdocs/barcode/codeinit.php @@ -52,27 +52,21 @@ $maxperinit = 1000; */ // Define barcode template for products -if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) -{ +if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) { $dirbarcodenum = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']); - foreach ($dirbarcodenum as $dirroot) - { + foreach ($dirbarcodenum as $dirroot) { $dir = dol_buildpath($dirroot, 0); $handle = @opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/^mod_barcode_product_.*php$/', $file)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/^mod_barcode_product_.*php$/', $file)) { $file = substr($file, 0, dol_strlen($file) - 4); try { dol_include_once($dirroot.$file.'.php'); - } catch (Exception $e) - { + } catch (Exception $e) { dol_syslog($e->getMessage(), LOG_ERR); } @@ -85,28 +79,23 @@ if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) } } -if ($action == 'initbarcodeproducts') -{ - if (!is_object($modBarCodeProduct)) - { +if ($action == 'initbarcodeproducts') { + if (!is_object($modBarCodeProduct)) { $error++; setEventMessages($langs->trans("NoBarcodeNumberingTemplateDefined"), null, 'errors'); } - if (!$error) - { + if (!$error) { $productstatic = new Product($db); $db->begin(); $nbok = 0; - if (!empty($eraseallbarcode)) - { + if (!empty($eraseallbarcode)) { $sql = "UPDATE ".MAIN_DB_PREFIX."product"; $sql .= " SET barcode = NULL"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { setEventMessages($langs->trans("AllBarcodeReset"), null, 'mesgs'); } else { $error++; @@ -121,16 +110,13 @@ if ($action == 'initbarcodeproducts') dol_syslog("codeinit", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; $nbok = $nbtry = 0; - while ($i < min($num, $maxperinit)) - { + while ($i < min($num, $maxperinit)) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $productstatic->id = $obj->rowid; $productstatic->ref = $obj->ref; $productstatic->type = $obj->fk_product_type; @@ -140,7 +126,9 @@ if ($action == 'initbarcodeproducts') $result = $productstatic->setValueFrom('barcode', $nextvalue, '', '', 'text', '', $user, 'PRODUCT_MODIFY'); $nbtry++; - if ($result > 0) $nbok++; + if ($result > 0) { + $nbok++; + } } $i++; @@ -150,14 +138,12 @@ if ($action == 'initbarcodeproducts') dol_print_error($db); } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); } } - if (!$error) - { + if (!$error) { //$db->rollback(); $db->commit(); } else { @@ -174,8 +160,12 @@ if ($action == 'initbarcodeproducts') * View */ -if (!$user->admin) accessforbidden(); -if (empty($conf->barcode->enabled)) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} +if (empty($conf->barcode->enabled)) { + accessforbidden(); +} $form = new Form($db); @@ -198,8 +188,7 @@ print ''; print '
    '; // For thirdparty -if ($conf->societe->enabled) -{ +if ($conf->societe->enabled) { $nbno = $nbtotal = 0; print load_fiche_titre($langs->trans("BarcodeInitForThirdparties"), '', 'company'); @@ -207,19 +196,21 @@ if ($conf->societe->enabled) print '
    '."\n"; $sql = "SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."societe where barcode IS NULL or barcode = ''"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $nbno = $obj->nb; - } else dol_print_error($db); + } else { + dol_print_error($db); + } $sql = "SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."societe"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $nbtotal = $obj->nb; - } else dol_print_error($db); + } else { + dol_print_error($db); + } print $langs->trans("CurrentlyNWithoutBarCode", $nbno, $nbtotal, $langs->transnoentitiesnoconv("ThirdParties")).'
    '."\n"; @@ -231,8 +222,7 @@ if ($conf->societe->enabled) // For products -if ($conf->product->enabled || $conf->product->service) -{ +if ($conf->product->enabled || $conf->product->service) { // Example 1 : Adding jquery code print ''."\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 7844432f3f8..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; } @@ -773,7 +813,6 @@ class BlockedLog */ public function create($user, $forcesignature = '') { - global $conf, $langs, $hookmanager; $langs->load('blockedlog'); @@ -786,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; @@ -804,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(); @@ -814,9 +854,13 @@ class BlockedLog $keyforsignature = $this->buildKeyForSignature(); + include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php'; + $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 ("; @@ -854,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(); @@ -887,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 @@ -948,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; } /** @@ -1000,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 @@ -1013,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 @@ -1029,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; } @@ -1095,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_agenda.php b/htdocs/bom/bom_agenda.php index a7cc68d5677..6a86f1c2258 100644 --- a/htdocs/bom/bom_agenda.php +++ b/htdocs/bom/bom_agenda.php @@ -41,30 +41,32 @@ $action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); -if (GETPOST('actioncode', 'array')) -{ +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)); } $search_agenda_label = GETPOST('search_agenda_label'); -// Security check - Protection if external user -//if ($user->socid > 0) accessforbidden(); -//if ($user->socid > 0) $socid = $user->socid; -//$result = restrictedArea($user, 'bom', $id); - $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'; +} // Initialize technical objects $object = new BOM($db); @@ -76,8 +78,15 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id; +} +// Security check - Protection if external user +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0); +restrictedArea($user, 'bom', $object->id, '', '', 'fk_soc', 'rowid', $isdraft); /* @@ -86,20 +95,19 @@ if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object-> $parameters = array('id'=>$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)) -{ +if (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // 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 $actioncode = ''; $search_agenda_label = ''; } @@ -115,14 +123,15 @@ $contactstatic = new Contact($db); $form = new Form($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $title = $langs->trans("Agenda"); //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; $help_url = ''; llxHeader('', $title, $help_url); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = bomPrepareHead($object); @@ -147,31 +156,31 @@ if ($object->id > 0) if ($user->rights->bom->creer) { if ($action != 'classify') - //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - $morehtmlref.=' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } - }*/ + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.=''; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + }*/ $morehtmlref .= ''; @@ -196,10 +205,11 @@ if ($object->id > 0) $out = '&origin='.$object->element.'&originid='.$object->id; $permok = $user->rights->agenda->myactions->create; - if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) - { + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { //$out.='trans("AddAnAction"),'filenew'); @@ -209,10 +219,8 @@ if ($object->id > 0) print ''; - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $param = '&id='.$object->id.'&socid='.$socid; - 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); + } //print load_fiche_titre($langs->trans("ActionsOnBom"), '', ''); diff --git a/htdocs/bom/bom_card.php b/htdocs/bom/bom_card.php index 47f1d336279..6d2047d3f49 100644 --- a/htdocs/bom/bom_card.php +++ b/htdocs/bom/bom_card.php @@ -37,10 +37,10 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); -$cancel = GETPOST('cancel', 'aZ09'); +$cancel = GETPOST('cancel', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'bomcard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); -$lineid = GETPOST('lineid', 'int'); +$lineid = GETPOST('lineid', 'int'); // PDF $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); @@ -59,12 +59,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. @@ -72,8 +75,8 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); //if ($user->socid > 0) $socid = $user->socid; -//$isdraft = (($object->statut == $object::STATUS_DRAFT) ? 1 : 0); -//$result = restrictedArea($user, 'bom', $object->id, '', '', 'fk_soc', 'rowid', $isdraft); +$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0); +$result = restrictedArea($user, 'bom', $object->id, '', '', 'fk_soc', 'rowid', $isdraft); $permissionnote = $user->rights->bom->write; // Used by the include of actions_setnotes.inc.php $permissiondellink = $user->rights->bom->write; // Used by the include of actions_dellink.inc.php @@ -88,18 +91,22 @@ $upload_dir = $conf->bom->multidir_output[isset($object->entity) ? $object->enti $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 (empty($reshook)) { $error = 0; $backurlforlist = DOL_URL_ROOT.'/bom/bom_list.php'; if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = dol_buildpath('/bom/bom_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('/bom/bom_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + } } } @@ -127,8 +134,7 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Add line - if ($action == 'addline' && $user->rights->bom->write) - { + if ($action == 'addline' && $user->rights->bom->write) { $langs->load('errors'); $error = 0; @@ -153,8 +159,7 @@ if (empty($reshook)) $error++; } - if (!$error) - { + if (!$error) { $bomline = new BOMLine($db); $bomline->fk_bom = $id; $bomline->fk_product = $idprod; @@ -164,10 +169,10 @@ if (empty($reshook)) $bomline->efficiency = $efficiency; // Rang to use - $rangmax = $object->line_max(0); - $ranktouse = $rangmax + 1; + $rangmax = $object->line_max(0); + $ranktouse = $rangmax + 1; - $bomline->position = ($ranktouse + 1); + $bomline->position = ($ranktouse + 1); $result = $bomline->create($user); if ($result <= 0) { @@ -179,16 +184,15 @@ if (empty($reshook)) unset($_POST['qty_frozen']); unset($_POST['disable_stock_change']); - $object->fetchLines(); + $object->fetchLines(); - $object->calculateCosts(); - } + $object->calculateCosts(); + } } } // Add line - if ($action == 'updateline' && $user->rights->bom->write) - { + if ($action == 'updateline' && $user->rights->bom->write) { $langs->load('errors'); $error = 0; @@ -211,8 +215,7 @@ if (empty($reshook)) $bomline->efficiency = $efficiency; $result = $bomline->update($user); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($bomline->error, $bomline->errors, 'errors'); $action = ''; } else { @@ -221,9 +224,9 @@ if (empty($reshook)) unset($_POST['qty_frozen']); unset($_POST['disable_stock_change']); - $object->fetchLines(); + $object->fetchLines(); - $object->calculateCosts(); + $object->calculateCosts(); } } } @@ -255,8 +258,7 @@ jQuery(document).ready(function() { // Part to create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewBOM"), '', 'bom'); print ''; @@ -288,8 +290,7 @@ if ($action == 'create') } // Part to edit record -if (($id || $ref) && $action == 'edit') -{ +if (($id || $ref) && $action == 'edit') { print load_fiche_titre($langs->trans("BillOfMaterials"), '', 'cubes'); print ''; @@ -322,8 +323,7 @@ if (($id || $ref) && $action == 'edit') } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_optionals(); $head = bomPrepareHead($object); @@ -332,19 +332,16 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $formconfirm = ''; // Confirmation to delete - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBillOfMaterials'), $langs->trans('ConfirmDeleteBillOfMaterials'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line - if ($action == 'deleteline') - { + if ($action == 'deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); } // Confirmation of validation - if ($action == 'validate') - { + if ($action == 'validate') { // We check that object has a temporary ref $ref = substr($object->ref, 1, 4); if ($ref == 'PROV') { @@ -364,13 +361,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea }*/ $formquestion = array(); - if (!empty($conf->bom->enabled)) - { + if (!empty($conf->bom->enabled)) { $langs->load("mrp"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( // 'text' => $langs->trans("ConfirmClone"), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -382,8 +380,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Confirmation of closing - if ($action == 'close') - { + if ($action == 'close') { $text = $langs->trans('ConfirmCloseBom', $object->ref); /*if (! empty($conf->notification->enabled)) { @@ -394,13 +391,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea }*/ $formquestion = array(); - if (!empty($conf->bom->enabled)) - { + if (!empty($conf->bom->enabled)) { $langs->load("mrp"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( // 'text' => $langs->trans("ConfirmClone"), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -412,8 +410,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Confirmation of reopen - if ($action == 'reopen') - { + if ($action == 'reopen') { $text = $langs->trans('ConfirmReopenBom', $object->ref); /*if (! empty($conf->notification->enabled)) { @@ -424,13 +421,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea }*/ $formquestion = array(); - if (!empty($conf->bom->enabled)) - { + if (!empty($conf->bom->enabled)) { $langs->load("mrp"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( // 'text' => $langs->trans("ConfirmClone"), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -449,8 +447,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Confirmation of action xxxx - if ($action == 'setdraft') - { + if ($action == 'setdraft') { $text = $langs->trans('ConfirmSetToDraft', $object->ref); $formquestion = array(); @@ -460,8 +457,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -481,32 +481,32 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; - if ($permissiontoadd) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=$proj->getNomUrl(); - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($permissiontoadd) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.=''; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=$proj->getNomUrl(); + } else { + $morehtmlref.=''; + } + } } */ $morehtmlref .= ''; @@ -544,8 +544,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea * Lines */ - if (!empty($object->table_element_line)) - { + if (!empty($object->table_element_line)) { print ' @@ -558,21 +557,17 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } print '
    '; - if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) - { + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { 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 (!empty($object->lines)) - { + if (!empty($object->lines)) { $object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1, '/bom/tpl'); } // Form to add new line - if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') - { - if ($action != 'editline') - { + if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') { + if ($action != 'editline') { // Add products/services form $object->formAddObjectLine(1, $mysoc, null, '/bom/tpl'); @@ -581,8 +576,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } - if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) - { + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { print '
    '; } print '
    '; @@ -597,29 +591,26 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '
    '."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Send //if (empty($user->socid)) { // print '' . $langs->trans('SendMail') . ''."\n"; //} // Back to draft - if ($object->status == $object::STATUS_VALIDATED) - { - if ($permissiontoadd) - { + if ($object->status == $object::STATUS_VALIDATED) { + if ($permissiontoadd) { print ''.$langs->trans("SetToDraft").''; } } // Modify - if ($object->status == $object::STATUS_DRAFT) - { - if ($permissiontoadd) - { + if ($object->status == $object::STATUS_DRAFT) { + if ($permissiontoadd) { print ''.$langs->trans("Modify").''."\n"; } else { print ''.$langs->trans('Modify').''."\n"; @@ -627,12 +618,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Validate - if ($object->status == $object::STATUS_DRAFT) - { - if ($permissiontoadd) - { - if (is_array($object->lines) && count($object->lines) > 0) - { + if ($object->status == $object::STATUS_DRAFT) { + if ($permissiontoadd) { + if (is_array($object->lines) && count($object->lines) > 0) { print ''.$langs->trans("Validate").''; } else { $langs->load("errors"); @@ -642,48 +630,42 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Re-open - if ($permissiontoadd && $object->status == $object::STATUS_CANCELED) - { + if ($permissiontoadd && $object->status == $object::STATUS_CANCELED) { print ''.$langs->trans("ReOpen").''; } // Create MO - if ($conf->mrp->enabled) - { - if ($object->status == $object::STATUS_VALIDATED && !empty($user->rights->mrp->write)) - { + if ($conf->mrp->enabled) { + if ($object->status == $object::STATUS_VALIDATED && !empty($user->rights->mrp->write)) { print ''.$langs->trans("CreateMO").''; } } // Clone - if ($permissiontoadd) - { + if ($permissiontoadd) { print ''.$langs->trans("ToClone").''; } // Close / Cancel - if ($permissiontoadd && $object->status == $object::STATUS_VALIDATED) - { + if ($permissiontoadd && $object->status == $object::STATUS_VALIDATED) { print ''.$langs->trans("Disable").''; } /* - if ($user->rights->bom->write) - { - if ($object->status == 1) - { - print ''.$langs->trans("Disable").''."\n"; - } - else - { - print ''.$langs->trans("Enable").''."\n"; - } - } - */ - - if ($permissiontodelete) + if ($user->rights->bom->write) { + if ($object->status == 1) + { + print ''.$langs->trans("Disable").''."\n"; + } + else + { + print ''.$langs->trans("Enable").''."\n"; + } + } + */ + + if ($permissiontodelete) { print ''.$langs->trans('Delete').''."\n"; } else { print ''.$langs->trans('Delete').''."\n"; @@ -698,8 +680,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '
    '; print ''; // ancre @@ -734,7 +715,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } //Select mail models is same action as presend - if (GETPOST('modelselected')) $action = 'presend'; + if (GETPOST('modelselected')) { + $action = 'presend'; + } // Presend form $modelmail = 'bom'; diff --git a/htdocs/bom/bom_document.php b/htdocs/bom/bom_document.php index cf752878605..520dd8bb9d7 100644 --- a/htdocs/bom/bom_document.php +++ b/htdocs/bom/bom_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"; +} //if (! $sortfield) $sortfield="position_name"; // Initialize technical objects @@ -69,14 +75,22 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity ? $object->entity : 1]."/bom/".get_exdir(0, 0, 0, 1, $object); +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->bom->multidir_output[$object->entity ? $object->entity : 1]."/bom/".get_exdir(0, 0, 0, 1, $object); +} + +// Security check - Protection if external user +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0); +restrictedArea($user, 'bom', $object->id, '', '', 'fk_soc', 'rowid', $isdraft); /* * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -90,8 +104,7 @@ $help_url = ''; //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($object->id) -{ +if ($object->id) { /* * Show tabs */ @@ -103,8 +116,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/bom/bom_list.php b/htdocs/bom/bom_list.php index 8f8c13f2556..eb1852699c0 100644 --- a/htdocs/bom/bom_list.php +++ b/htdocs/bom/bom_list.php @@ -48,7 +48,9 @@ $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; @@ -67,14 +69,20 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Security check -if (empty($conf->bom->enabled)) accessforbidden('Module not enabled'); +if (empty($conf->bom->enabled)) { + accessforbidden('Module not enabled'); +} $socid = 0; -if ($user->socid > 0) // Protection if external user -{ +if ($user->socid > 0) { + // Protection if external user //$socid = $user->socid; accessforbidden(); } @@ -83,30 +91,31 @@ if ($user->socid > 0) // Protection if external user // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of fields for list $arrayfields = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field - if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); + if (!empty($val['visible'])) { + $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); + } } // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], @@ -129,31 +138,33 @@ $permissiontodelete = $user->rights->bom->delete; * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($object->fields as $key => $val) - { + 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 + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $toselect = ''; $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -167,22 +178,17 @@ if (empty($reshook)) // Validate records - if (!$error && $massaction == 'disable' && $permissiontoadd) - { + if (!$error && $massaction == 'disable' && $permissiontoadd) { $objecttmp = new $objectclass($db); - if (!$error) - { + if (!$error) { $db->begin(); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { - if ($objecttmp->status != $objecttmp::STATUS_VALIDATED) - { + if ($result > 0) { + if ($objecttmp->status != $objecttmp::STATUS_VALIDATED) { $langs->load("errors"); setEventMessages($langs->trans("ErrorObjectMustHaveStatusActiveToBeDisabled", $objecttmp->ref), null, 'errors'); $error++; @@ -191,12 +197,13 @@ if (empty($reshook)) // Can be 'cancel()' or 'close()' $result = $objecttmp->cancel($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -204,10 +211,12 @@ if (empty($reshook)) } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -217,22 +226,17 @@ if (empty($reshook)) } // Validate records - if (!$error && $massaction == 'enable' && $permissiontoadd) - { + if (!$error && $massaction == 'enable' && $permissiontoadd) { $objecttmp = new $objectclass($db); - if (!$error) - { + if (!$error) { $db->begin(); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { - if ($objecttmp->status != $objecttmp::STATUS_DRAFT && $objecttmp->status != $objecttmp::STATUS_CANCELED) - { + if ($result > 0) { + if ($objecttmp->status != $objecttmp::STATUS_DRAFT && $objecttmp->status != $objecttmp::STATUS_CANCELED) { $langs->load("errors"); setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftOrDisabledToBeActivated", $objecttmp->ref), null, 'errors'); $error++; @@ -241,12 +245,13 @@ if (empty($reshook)) // Can be 'cancel()' or 'close()' $result = $objecttmp->validate($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -254,10 +259,12 @@ if (empty($reshook)) } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -284,13 +291,14 @@ $title = $langs->trans('ListOfBOMs'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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.', ' : ''); + 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(); @@ -298,21 +306,33 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -else $sql .= " WHERE 1 = 1"; -foreach ($search as $key => $val) -{ - if ($key == 'status' && $search[$key] == -1) continue; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); if (strpos($object->fields[$key]['type'], 'integer:') === 0) { - if ($search[$key] == '-1') $search[$key] = ''; + if ($search[$key] == '-1') { + $search[$key] = ''; + } $mode_search = 2; } - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -341,26 +361,24 @@ $sql .= $db->order($sortfield, $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 || empty($limit))) -{ +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -369,8 +387,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/bom/bom_card.php?id='.$id); @@ -386,14 +403,24 @@ llxHeader('', $title, $help_url); $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ - if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); - else $param .= '&search_'.$key.'='.urlencode($search[$key]); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +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'; @@ -403,12 +430,18 @@ $arrayofmassactions = array( 'enable'=>$langs->trans("Enable"), 'disable'=>$langs->trans("Disable"), ); -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 ''; @@ -427,9 +460,10 @@ $objecttmp = new BOM($db); $trackid = 'bom'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; } @@ -440,11 +474,13 @@ $moreforfilter.= '
    ';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; @@ -461,20 +497,26 @@ print ''; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; } } @@ -496,15 +538,18 @@ print ''."\n"; // Fields title label // -------------------------------------------------------------------- print ''; -foreach ($object->fields as $key => $val) -{ - $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { +foreach ($object->fields as $key => $val) { + $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'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -521,11 +566,11 @@ print ''."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -534,38 +579,53 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->setVarsFromFetchObj($obj); // Show here line of result print ''; - foreach ($object->fields as $key => $val) - { - $cssforfield = (empty($val['css']) ? '' : $val['css']); - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + foreach ($object->fields as $key => $val) { + $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') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) { + $cssforfield = 'tdoverflowmax100'; + } - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; - if ($key == 'status') print $object->getLibStatut(5); - else print $object->showOutputField($val, $key, $object->$key, ''); + if ($key == 'status') { + print $object->getLibStatut(5); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } print ''; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $object->$key; } } @@ -578,14 +638,17 @@ while ($i < ($limit ? min($num, $limit) : $num)) print $hookmanager->resPrint; // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print ''."\n"; @@ -597,10 +660,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 ''; } @@ -617,10 +683,11 @@ print ''."\n"; print ''."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/bom/bom_note.php b/htdocs/bom/bom_note.php index 78b38732f7f..244bcfd7a49 100644 --- a/htdocs/bom/bom_note.php +++ b/htdocs/bom/bom_note.php @@ -34,7 +34,7 @@ $langs->loadLangs(array("mrp", "companies")); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); -$cancel = GETPOST('cancel', 'aZ09'); +$cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); // Initialize technical objects @@ -53,11 +53,17 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id; +} -$permissionnote = 1; -//$permissionnote=$user->rights->bom->creer; // Used by the include of actions_setnotes.inc.php +$permissionnote = $user->rights->bom->write; // Used by the include of actions_setnotes.inc.php +// Security check - Protection if external user +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0); +restrictedArea($user, 'bom', $object->id, '', '', 'fk_soc', 'rowid', $isdraft); /* @@ -77,8 +83,7 @@ $form = new Form($db); $help_url = ''; llxHeader('', $langs->trans('BillOfMaterials'), $help_url); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = bomPrepareHead($object); @@ -99,35 +104,35 @@ if ($id > 0 || !empty($ref)) // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; - if ($user->rights->bom->creer) - { - if ($action != 'classify') - //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - $morehtmlref.=' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->bom->creer) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.=''; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } }*/ $morehtmlref .= ''; diff --git a/htdocs/bom/class/api_boms.class.php b/htdocs/bom/class/api_boms.class.php index 563cfe35263..24ec68d0e2f 100644 --- a/htdocs/bom/class/api_boms.class.php +++ b/htdocs/bom/class/api_boms.class.php @@ -108,30 +108,42 @@ class Boms extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; + if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." as t"; - if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= " WHERE 1 = 1"; // Example of use $mode //if ($mode == 1) $sql.= " AND s.client IN (1, 3)"; //if ($mode == 2) $sql.= " AND s.client IN (2, 3)"; - if ($tmpobject->ismultientitymanaged) $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')'; - if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($restrictonsocid && $socid) $sql .= " AND t.fk_soc = ".$socid; - if ($restrictonsocid && $search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ($tmpobject->ismultientitymanaged) { + $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')'; + } + if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($restrictonsocid && $socid) { + $sql .= " AND t.fk_soc = ".$socid; + } + if ($restrictonsocid && $search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter - if ($restrictonsocid && $search_sale > 0) - { + if ($restrictonsocid && $search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } - if ($sqlfilters) - { + if ($sqlfilters) { if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } @@ -141,8 +153,7 @@ class Boms extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -151,12 +162,10 @@ class Boms extends DolibarrApi } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $bom_static = new BOM($this->db); if ($bom_static->fetch($obj->rowid)) { @@ -220,7 +229,9 @@ class Boms extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->bom->$field = $value; } @@ -251,8 +262,7 @@ class Boms extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if (!$this->bom->delete(DolibarrApiAccess::$user)) - { + if (!$this->bom->delete(DolibarrApiAccess::$user)) { throw new RestException(500, 'Error when deleting BOM : '.$this->bom->error); } @@ -316,8 +326,7 @@ class Boms extends DolibarrApi // If object has lines, remove $db property if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) { $nboflines = count($object->lines); - for ($i = 0; $i < $nboflines; $i++) - { + for ($i = 0; $i < $nboflines; $i++) { $this->_cleanObjectDatas($object->lines[$i]); unset($object->lines[$i]->lines); @@ -340,9 +349,12 @@ class Boms extends DolibarrApi { $myobject = array(); foreach ($this->bom->fields as $field => $propfield) { - if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) continue; // Not a mandatory field - if (!isset($data[$field])) + if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) { + continue; // Not a mandatory field + } + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $myobject[$field] = $data[$field]; } return $myobject; diff --git a/htdocs/bom/class/bom.class.php b/htdocs/bom/class/bom.class.php index 8444c4e1812..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'), @@ -230,25 +235,24 @@ class BOM extends CommonObject $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } // Translate some data of arrayofkeyval - foreach ($this->fields as $key => $val) - { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } @@ -264,7 +268,9 @@ class BOM extends CommonObject */ public function create(User $user, $notrigger = false) { - if ($this->efficiency <= 0 || $this->efficiency > 1) $this->efficiency = 1; + if ($this->efficiency <= 0 || $this->efficiency > 1) { + $this->efficiency = 1; + } return $this->createCommon($user, $notrigger); } @@ -289,7 +295,9 @@ class BOM extends CommonObject // Load source object $result = $object->fetchCommon($fromid); - if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); + if ($result > 0 && !empty($object->table_element_line)) { + $object->fetchLines(); + } // Get lines so they will be clone //foreach ($object->lines as $line) @@ -306,14 +314,11 @@ class BOM extends CommonObject $object->status = self::STATUS_DRAFT; // ... // Clear extrafields that are unique - if (is_array($object->array_options) && count($object->array_options) > 0) - { + if (is_array($object->array_options) && count($object->array_options) > 0) { $extrafields->fetch_name_optionals_label($object->table_element); - foreach ($object->array_options as $key => $option) - { + foreach ($object->array_options as $key => $option) { $shortkey = preg_replace('/options_/', '', $key); - if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) - { + if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) { //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; unset($object->array_options[$key]); } @@ -329,22 +334,19 @@ class BOM extends CommonObject $this->errors = $object->errors; } - if (!$error) - { + if (!$error) { // copy internal contacts - if ($this->copy_linked_contact($object, 'internal') < 0) - { + if ($this->copy_linked_contact($object, 'internal') < 0) { $error++; } } - if (!$error) - { + if (!$error) { // copy external contacts if same company - if (property_exists($this, 'socid') && $this->socid == $object->socid) - { - if ($this->copy_linked_contact($object, 'external') < 0) + if (property_exists($this, 'socid') && $this->socid == $object->socid) { + if ($this->copy_linked_contact($object, 'external') < 0) { $error++; + } } } @@ -375,7 +377,9 @@ class BOM extends CommonObject { $result = $this->fetchCommon($id, $ref); - if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); + if ($result > 0 && !empty($this->table_element_line)) { + $this->fetchLines(); + } $this->calculateCosts(); return $result; @@ -416,8 +420,11 @@ class BOM extends CommonObject $sql = 'SELECT '; $sql .= $this->getFieldList(); $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if ($this->ismultientitymanaged) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; - else $sql .= ' WHERE 1 = 1'; + if ($this->ismultientitymanaged) { + $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; + } else { + $sql .= ' WHERE 1 = 1'; + } // Manage filter $sqlwhere = array(); if (count($filter) > 0) { @@ -448,8 +455,7 @@ class BOM extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $record = new self($this->db); $record->setVarsFromFetchObj($obj); @@ -475,7 +481,9 @@ class BOM extends CommonObject */ public function update(User $user, $notrigger = false) { - if ($this->efficiency <= 0 || $this->efficiency > 1) $this->efficiency = 1; + if ($this->efficiency <= 0 || $this->efficiency > 1) { + $this->efficiency = 1; + } return $this->updateCommon($user, $notrigger); } @@ -503,8 +511,7 @@ class BOM extends CommonObject */ public function deleteLine(User $user, $idline, $notrigger = false) { - if ($this->status < 0) - { + if ($this->status < 0) { $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; return -2; } @@ -524,8 +531,7 @@ class BOM extends CommonObject global $langs, $conf; $langs->load("mrp"); - if (!empty($conf->global->BOM_ADDON)) - { + if (!empty($conf->global->BOM_ADDON)) { $mybool = false; $file = $conf->global->BOM_ADDON.".php"; @@ -533,16 +539,14 @@ class BOM extends CommonObject // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/bom/"); // Load file with numbering class (if found) $mybool |= @include_once $dir.$file; } - if ($mybool === false) - { + if ($mybool === false) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -550,8 +554,7 @@ class BOM extends CommonObject $obj = new $classname(); $numref = $obj->getNextValue($prod, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -580,27 +583,25 @@ class BOM extends CommonObject $error = 0; // Protection - if ($this->status == self::STATUS_VALIDATED) - { + if ($this->status == self::STATUS_VALIDATED) { dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); return 0; } /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->create)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate)))) - { - $this->error='NotEnoughPermissions'; - dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); - return -1; - }*/ + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate)))) + { + $this->error='NotEnoughPermissions'; + dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); + return -1; + }*/ $now = dol_now(); $this->db->begin(); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $this->fetch_product(); $num = $this->getNextNumRef($this->product); } else { @@ -618,50 +619,47 @@ class BOM extends CommonObject dol_syslog(get_class($this)."::validate()", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $this->error = $this->db->lasterror(); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('BOM_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'bom/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'bom/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->bom->dir_output.'/'.$oldref; $dirdest = $conf->bom->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->bom->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -674,14 +672,12 @@ class BOM extends CommonObject } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $num; $this->status = self::STATUS_VALIDATED; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -700,8 +696,7 @@ class BOM extends CommonObject public function setDraft($user, $notrigger = 0) { // Protection - if ($this->status <= self::STATUS_DRAFT) - { + if ($this->status <= self::STATUS_DRAFT) { return 0; } @@ -725,8 +720,7 @@ class BOM extends CommonObject public function cancel($user, $notrigger = 0) { // Protection - if ($this->status != self::STATUS_VALIDATED) - { + if ($this->status != self::STATUS_VALIDATED) { return 0; } @@ -750,8 +744,7 @@ class BOM extends CommonObject public function reopen($user, $notrigger = 0) { // Protection - if ($this->status != self::STATUS_CANCELED) - { + if ($this->status != self::STATUS_CANCELED) { return 0; } @@ -780,7 +773,9 @@ class BOM extends CommonObject { global $db, $conf, $langs, $hookmanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -793,19 +788,20 @@ class BOM extends CommonObject $url = dol_buildpath('/bom/bom_card.php', 1).'?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowBillOfMaterials"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -813,20 +809,26 @@ class BOM extends CommonObject $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; /* - $hookmanager->initHooks(array('bomdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + $hookmanager->initHooks(array('bomdao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $linkclose = $hookmanager->resPrint; + */ + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -834,8 +836,11 @@ class BOM extends CommonObject $hookmanager->initHooks(array('bomdao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -862,8 +867,7 @@ class BOM extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - if (empty($this->labelStatus)) - { + if (empty($this->labelStatus)) { global $langs; //$langs->load("mrp"); $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft'); @@ -872,8 +876,12 @@ class BOM extends CommonObject } $statusType = 'status'.$status; - if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; - if ($status == self::STATUS_CANCELED) $statusType = 'status6'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } + if ($status == self::STATUS_CANCELED) { + $statusType = 'status6'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatus[$status], '', $statusType, $mode); } @@ -889,30 +897,25 @@ 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; @@ -941,8 +944,7 @@ class BOM extends CommonObject $objectline = new BOMLine($this->db); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_bom = '.$this->id)); - if (is_numeric($result)) - { + if (is_numeric($result)) { $this->error = $this->error; $this->errors = $this->errors; return $result; @@ -1051,8 +1053,7 @@ class BOM extends CommonObject } $line->unit_cost = price2num((!empty($tmpproduct->cost_price)) ? $tmpproduct->cost_price : $tmpproduct->pmp); if (empty($line->unit_cost)) { - if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) - { + if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) { $line->unit_cost = $productFournisseur->fourn_unitprice; } } @@ -1197,25 +1198,24 @@ class BOMLine extends CommonObjectLine $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } // Translate some data of arrayofkeyval - foreach ($this->fields as $key => $val) - { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } @@ -1231,7 +1231,9 @@ class BOMLine extends CommonObjectLine */ public function create(User $user, $notrigger = false) { - if ($this->efficiency < 0 || $this->efficiency > 1) $this->efficiency = 1; + if ($this->efficiency < 0 || $this->efficiency > 1) { + $this->efficiency = 1; + } return $this->createCommon($user, $notrigger); } @@ -1272,8 +1274,11 @@ class BOMLine extends CommonObjectLine $sql = 'SELECT '; $sql .= $this->getFieldList(); $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if ($this->ismultientitymanaged) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; - else $sql .= ' WHERE 1 = 1'; + if ($this->ismultientitymanaged) { + $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; + } else { + $sql .= ' WHERE 1 = 1'; + } // Manage filter $sqlwhere = array(); if (count($filter) > 0) { @@ -1304,8 +1309,7 @@ class BOMLine extends CommonObjectLine if ($resql) { $num = $this->db->num_rows($resql); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $record = new self($this->db); $record->setVarsFromFetchObj($obj); @@ -1331,7 +1335,9 @@ class BOMLine extends CommonObjectLine */ public function update(User $user, $notrigger = false) { - if ($this->efficiency < 0 || $this->efficiency > 1) $this->efficiency = 1; + if ($this->efficiency < 0 || $this->efficiency > 1) { + $this->efficiency = 1; + } return $this->updateCommon($user, $notrigger); } @@ -1363,7 +1369,9 @@ class BOMLine extends CommonObjectLine { global $db, $conf, $langs, $hookmanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -1373,19 +1381,20 @@ class BOMLine extends CommonObjectLine $url = dol_buildpath('/bom/bomline_card.php', 1).'?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowBillOfMaterialsLine"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -1393,20 +1402,26 @@ class BOMLine extends CommonObjectLine $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; /* - $hookmanager->initHooks(array('bomlinedao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + $hookmanager->initHooks(array('bomlinedao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $linkclose = $hookmanager->resPrint; + */ + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -1414,8 +1429,11 @@ class BOMLine extends CommonObjectLine $hookmanager->initHooks(array('bomlinedao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -1456,30 +1474,25 @@ 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; diff --git a/htdocs/bom/lib/bom.lib.php b/htdocs/bom/lib/bom.lib.php index 313c7a1a7ff..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( @@ -88,14 +82,19 @@ function bomPrepareHead($object) $head[$h][2] = 'card'; $h++; - if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) - { + if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/bom/bom_note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.$nbNote.'' : ''); + if ($nbNote > 0) { + $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.$nbNote.'' : ''); + } $head[$h][2] = 'note'; $h++; } @@ -107,7 +106,9 @@ function bomPrepareHead($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/bom/bom_document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.($nbFiles + $nbLinks).'' : ''); + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.($nbFiles + $nbLinks).'' : ''); + } $head[$h][2] = 'document'; $h++; diff --git a/htdocs/bom/tpl/linkedobjectblock.tpl.php b/htdocs/bom/tpl/linkedobjectblock.tpl.php index 3debc7e7d87..fcba37105d3 100644 --- a/htdocs/bom/tpl/linkedobjectblock.tpl.php +++ b/htdocs/bom/tpl/linkedobjectblock.tpl.php @@ -39,12 +39,13 @@ $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1) $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $product_static = new Product($db); $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } echo ''; echo ''; print ''; - if (!empty($conf->global->PRODUCT_USE_UNITS)) - { + if (!empty($conf->global->PRODUCT_USE_UNITS)) { print ''; -if (!empty($conf->global->PRODUCT_USE_UNITS)) -{ +if (!empty($conf->global->PRODUCT_USE_UNITS)) { $coldisplay++; print ''; @@ -154,18 +156,18 @@ jQuery(document).ready(function() { { console.log("#idprod change triggered"); - /* To set focus */ - if (jQuery('#idprod').val() > 0) - { + /* To set focus */ + if (jQuery('#idprod').val() > 0) + { /* focus work on a standard textarea but not if field was replaced with CKEDITOR */ jQuery('#dp_desc').focus(); /* focus if CKEDITOR */ if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined") { var editor = CKEDITOR.instances['dp_desc']; - if (editor) { editor.focus(); } + if (editor) { editor.focus(); } + } } - } }); }); diff --git a/htdocs/bom/tpl/objectline_edit.tpl.php b/htdocs/bom/tpl/objectline_edit.tpl.php index 4d10539c824..46b57e89243 100644 --- a/htdocs/bom/tpl/objectline_edit.tpl.php +++ b/htdocs/bom/tpl/objectline_edit.tpl.php @@ -32,8 +32,7 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page can't be called as URL"; exit; } @@ -41,7 +40,9 @@ if (empty($object) || !is_object($object)) global $forceall; -if (empty($forceall)) $forceall = 0; +if (empty($forceall)) { + $forceall = 0; +} // Define colspan for the button 'Add' @@ -79,8 +80,7 @@ if ($line->fk_product > 0) { print $tmpproduct->getNomUrl(1); } -if (is_object($hookmanager)) -{ +if (is_object($hookmanager)) { $fk_parent_line = (GETPOST('fk_parent_line') ? GETPOST('fk_parent_line') : $line->fk_parent_line); $parameters = array('line'=>$line, 'fk_parent_line'=>$fk_parent_line, 'var'=>$var, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer); $reshook = $hookmanager->executeHooks('formEditProductOptions', $parameters, $this, $action); @@ -90,7 +90,7 @@ print ''; /*if ($object->element == 'supplier_proposal' || $object->element == 'order_supplier' || $object->element == 'invoice_supplier') // We must have same test in printObjectLines { - $coldisplay++; + $coldisplay++; ?> info_bits & 2) != 2) { } print ''; -if (!empty($conf->global->PRODUCT_USE_UNITS)) -{ +if (!empty($conf->global->PRODUCT_USE_UNITS)) { $coldisplay++; print ''; diff --git a/htdocs/bom/tpl/objectline_title.tpl.php b/htdocs/bom/tpl/objectline_title.tpl.php index ad9c54a34ea..d1b29ee03b0 100644 --- a/htdocs/bom/tpl/objectline_title.tpl.php +++ b/htdocs/bom/tpl/objectline_title.tpl.php @@ -34,8 +34,7 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page can't be called as URL"; exit; } @@ -46,7 +45,9 @@ print "\n"; print ''; // Adds a line numbering column -if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print ''; +if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { + print ''; +} // Description print ''; @@ -54,8 +55,7 @@ print ''; // Qty print ''; -if (!empty($conf->global->PRODUCT_USE_UNITS)) -{ +if (!empty($conf->global->PRODUCT_USE_UNITS)) { print ''; } @@ -77,8 +77,7 @@ print ''; print ''; -if ($action == 'selectlines') -{ +if ($action == 'selectlines') { print ''; -if (!empty($conf->global->PRODUCT_USE_UNITS)) -{ +if (!empty($conf->global->PRODUCT_USE_UNITS)) { print ''; //Line extrafield -if (!empty($extrafields)) -{ +if (!empty($extrafields)) { print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"', 'colspan'=>$coldisplay), '', '', 1, 'line'); } 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 ''; print ''; print ''; print ''; $cats = $object->get_filles(); -if ($cats < 0) -{ +if ($cats < 0) { dol_print_error($db, $object->error, $object->errors); -} elseif (count($cats) < 1) -{ +} elseif (count($cats) < 1) { print ''; print ''; print ''; @@ -362,19 +344,25 @@ if ($cats < 0) $fulltree = $categstatic->get_full_arbo($type, $object->id, 1); // Load possible missing includes - if ($conf->global->CATEGORY_SHOW_COUNTS) - { - if ($type == Categorie::TYPE_MEMBER) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; - if ($type == Categorie::TYPE_ACCOUNT) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - if ($type == Categorie::TYPE_PROJECT) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - if ($type == Categorie::TYPE_USER) require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; + if ($conf->global->CATEGORY_SHOW_COUNTS) { + if ($type == Categorie::TYPE_MEMBER) { + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + } + if ($type == Categorie::TYPE_ACCOUNT) { + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + } + if ($type == Categorie::TYPE_PROJECT) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + } + if ($type == Categorie::TYPE_USER) { + require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; + } } // Define data (format for treeview) $data = array(); $data[] = array('rowid'=>0, 'fk_menu'=>-1, 'title'=>"racine", 'mainmenu'=>'', 'leftmenu'=>'', 'fk_mainmenu'=>'', 'fk_leftmenu'=>''); - foreach ($fulltree as $key => $val) - { + foreach ($fulltree as $key => $val) { $categstatic->id = $val['id']; $categstatic->ref = $val['label']; $categstatic->color = $val['color']; @@ -382,8 +370,7 @@ if ($cats < 0) $desc = dol_htmlcleanlastbr($val['description']); $counter = ''; - if ($conf->global->CATEGORY_SHOW_COUNTS) - { + if ($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" @@ -421,8 +408,7 @@ if ($cats < 0) } $nbofentries = (count($data) - 1); - if ($nbofentries > 0) - { + if ($nbofentries > 0) { require_once DOL_DOCUMENT_ROOT.'/core/lib/treeview.lib.php'; print ''; print '
    '; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - elseif (strpos($val['type'], 'integer:') === 0) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print ''; + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { + print ''; + } print '
    '; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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($object->id, $arrayofselected)) $selected = 1; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } print ''; } print '
    '.$langs->trans("NoRecordFound").'
    '.$langs->trans("Bom"); if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) { diff --git a/htdocs/bom/tpl/objectline_create.tpl.php b/htdocs/bom/tpl/objectline_create.tpl.php index 9e54fc67e8a..7cc2873b261 100644 --- a/htdocs/bom/tpl/objectline_create.tpl.php +++ b/htdocs/bom/tpl/objectline_create.tpl.php @@ -38,7 +38,9 @@ if (empty($object) || !is_object($object)) { global $forceall, $forcetoshowtitlelines; -if (empty($forceall)) $forceall = 0; +if (empty($forceall)) { + $forceall = 0; +} // Define colspan for the button 'Add' @@ -60,8 +62,7 @@ if ($nolinesbefore) { print '
    '.$langs->trans('AddNewLine').''; print '
    '.$langs->trans('Qty').''; print ''; print $langs->trans('Unit'); @@ -86,16 +87,18 @@ $coldisplay++; print ''; // Predefined product/service -if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) -{ - if ($forceall >= 0 && $freelines) echo '
    '; +if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) { + if ($forceall >= 0 && $freelines) { + echo '
    '; + } echo ''; $filtertype = ''; - if (!empty($object->element) && $object->element == 'contrat' && empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) $filtertype = '1'; + if (!empty($object->element) && $object->element == 'contrat' && empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) { + $filtertype = '1'; + } $statustoshow = -1; - if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) - { + if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) { // hide products in closed warehouse, but show products for internal transfer $form->select_produits(GETPOST('idprod', 'int'), 'idprod', $filtertype, $conf->product->limit_size, $buyer->price_level, $statustoshow, 2, '', 1, array(), $buyer->id, '1', 0, 'maxwidth500', 0, 'warehouseopen,warehouseinternal', GETPOST('combinations', 'array')); } else { @@ -109,8 +112,7 @@ $coldisplay++; print '
    '; print ''; print ' '; print '
      '.$langs->trans('Description').''.$langs->trans('Description').''.$form->textwithpicto($langs->trans('Qty'), $langs->trans("QtyRequiredIfNoLoss")).''.$langs->trans('Unit').''; print ''; print ''; diff --git a/htdocs/bom/tpl/objectline_view.tpl.php b/htdocs/bom/tpl/objectline_view.tpl.php index bc8506b2151..fff9d077a08 100644 --- a/htdocs/bom/tpl/objectline_view.tpl.php +++ b/htdocs/bom/tpl/objectline_view.tpl.php @@ -35,8 +35,7 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page can't be called as URL"; exit; } @@ -44,11 +43,21 @@ if (empty($object) || !is_object($object)) global $forceall, $senderissupplier, $inputalsopricewithtax, $outputalsopricetotalwithtax; -if (empty($dateSelector)) $dateSelector = 0; -if (empty($forceall)) $forceall = 0; -if (empty($senderissupplier)) $senderissupplier = 0; -if (empty($inputalsopricewithtax)) $inputalsopricewithtax = 0; -if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax = 0; +if (empty($dateSelector)) { + $dateSelector = 0; +} +if (empty($forceall)) { + $forceall = 0; +} +if (empty($senderissupplier)) { + $senderissupplier = 0; +} +if (empty($inputalsopricewithtax)) { + $inputalsopricewithtax = 0; +} +if (empty($outputalsopricetotalwithtax)) { + $outputalsopricetotalwithtax = 0; +} // add html5 elements $domData = ' data-element="'.$line->element.'"'; @@ -79,8 +88,7 @@ $coldisplay++; echo price($line->qty, 0, '', 0, 0); // Yes, it is a quantity, not a price, but we just want the formating role of function price print ''; $label = $tmpproduct->getLabelOfUnit('long'); if ($label !== '') { @@ -159,8 +167,7 @@ if ($action == 'selectlines') { print '
    '; - 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/cashdesk/admin/cashdesk.php b/htdocs/cashdesk/admin/cashdesk.php index 21e10c05fc7..382dd062131 100644 --- a/htdocs/cashdesk/admin/cashdesk.php +++ b/htdocs/cashdesk/admin/cashdesk.php @@ -27,16 +27,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; // If socid provided by ajax company selector -if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY_id'])) -{ +if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY_id'])) { $_GET['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); $_POST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); $_REQUEST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); } // Security check -if (!$user->admin) -accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array("admin", "cashdesk")); @@ -45,11 +45,12 @@ $langs->loadLangs(array("admin", "cashdesk")); /* * Actions */ -if (GETPOST('action', 'alpha') == 'set') -{ +if (GETPOST('action', 'alpha') == 'set') { $db->begin(); - if (GETPOST('socid', 'int') < 0) $_POST["socid"] = ''; + if (GETPOST('socid', 'int') < 0) { + $_POST["socid"] = ''; + } $res = dolibarr_set_const($db, "CASHDESK_ID_THIRDPARTY", (GETPOST('socid', 'int') > 0 ? GETPOST('socid', 'int') : ''), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "CASHDESK_ID_BANKACCOUNT_CASH", (GETPOST('CASHDESK_ID_BANKACCOUNT_CASH', 'alpha') > 0 ? GETPOST('CASHDESK_ID_BANKACCOUNT_CASH', 'alpha') : ''), 'chaine', 0, '', $conf->entity); @@ -62,10 +63,11 @@ if (GETPOST('action', 'alpha') == 'set') dol_syslog("admin/cashdesk: level ".GETPOST('level', 'alpha')); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -93,8 +95,7 @@ print ''; print ''; print ''; -if (!empty($conf->service->enabled)) -{ +if (!empty($conf->service->enabled)) { print ''; print ''; print ''; @@ -121,8 +122,7 @@ print ''; -if (!empty($conf->banque->enabled)) -{ +if (!empty($conf->banque->enabled)) { print ''; print ''; } -if (!empty($conf->stock->enabled)) -{ +if (!empty($conf->stock->enabled)) { print ''; // Force warehouse (this is not a default value) print ''; // Force warehouse (this is not a default value) print ' - + - + - - - - + @@ -130,8 +132,8 @@ for ($i = 0; $i < $nbtoshow; $i++) - - + +
    '.$langs->trans("Parameters").''.$langs->trans("Value").'
    '.$langs->trans("CashDeskThirdParty print ''; print $form->select_company($conf->global->CASHDESK_ID_THIRDPARTY, 'socid', '(s.client in (1,3) AND s.status = 1)', 1, 0, 0, array(), 0); print '
    '.$langs->trans("CashDeskBankAccountForSell").''; $form->select_comptes($conf->global->CASHDESK_ID_BANKACCOUNT_CASH, 'CASHDESK_ID_BANKACCOUNT_CASH', 0, "courant=2", 1); @@ -141,8 +141,7 @@ if (!empty($conf->banque->enabled)) print '
    '.$langs->trans("CashDeskDoNotDecreaseStock").''; if (empty($conf->productbatch->enabled)) { @@ -161,8 +160,7 @@ if (!empty($conf->stock->enabled)) print '
    '.$langs->trans("CashDeskIdWareHouse").''; - if (!$disabled) - { + if (!$disabled) { print $formproduct->selectWarehouses($conf->global->CASHDESK_ID_WAREHOUSE, 'CASHDESK_ID_WAREHOUSE', '', 1, $disabled); print ' ('.$langs->trans("Create").')'; } else { @@ -172,8 +170,7 @@ if (!empty($conf->stock->enabled)) } // Use Dolibarr Receipt Printer -if (!empty($conf->receiptprinter->enabled)) -{ +if (!empty($conf->receiptprinter->enabled)) { print '
    '; print $langs->trans("DolibarrReceiptPrinter").' ('.$langs->trans("FeatureNotYetAvailable").')'; print ''; diff --git a/htdocs/cashdesk/affContenu.php b/htdocs/cashdesk/affContenu.php index 72cb99123a4..384e3490fa1 100644 --- a/htdocs/cashdesk/affContenu.php +++ b/htdocs/cashdesk/affContenu.php @@ -25,15 +25,13 @@ require_once 'class/Facturation.class.php'; // Si nouvelle vente, reinitialisation des donnees (destruction de l'objet et vidage de la table contenant la liste des articles) -if ($_GET['id'] == 'NOUV') -{ +if ($_GET['id'] == 'NOUV') { unset($_SESSION['serObjFacturation']); unset($_SESSION['poscart']); } // Recuperation, s'il existe, de l'objet contenant les infos de la vente en cours ... -if (isset($_SESSION['serObjFacturation'])) -{ +if (isset($_SESSION['serObjFacturation'])) { $obj_facturation = unserialize($_SESSION['serObjFacturation']); unset($_SESSION['serObjFacturation']); } else { @@ -58,17 +56,18 @@ print '
    '; print '
    '; $page = GETPOST('menutpl', 'alpha'); -if (empty($page)) $page = 'facturation'; +if (empty($page)) { + $page = 'facturation'; +} if (in_array( - $page, - array( + $page, + array( 'deconnexion', 'index', 'index_verif', 'facturation', 'facturation_verif', 'facturation_dhtml', 'validation', 'validation_ok', 'validation_ticket', 'validation_verif', ) - )) -{ +)) { include $page.'.php'; } else { dol_print_error('', 'menu param '.$page.' is not inside allowed list'); diff --git a/htdocs/cashdesk/affIndex.php b/htdocs/cashdesk/affIndex.php index 1e3bddf1df7..931bcd76f6f 100644 --- a/htdocs/cashdesk/affIndex.php +++ b/htdocs/cashdesk/affIndex.php @@ -30,8 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/cashdesk/include/keypad.php'; $error = GETPOST('error'); // Test if already logged -if ($_SESSION['uid'] <= 0) -{ +if ($_SESSION['uid'] <= 0) { header('Location: index.php'); exit; } @@ -53,8 +52,7 @@ top_htmlhead($head, $langs->trans("CashDesk"), 0, 0, $arrayofjs, $arrayofcss); print ''."\n"; -if (!empty($error)) -{ +if (!empty($error)) { dol_htmloutput_events(); } diff --git a/htdocs/cashdesk/affPied.php b/htdocs/cashdesk/affPied.php index b3108217346..1a7c9c5b6a7 100644 --- a/htdocs/cashdesk/affPied.php +++ b/htdocs/cashdesk/affPied.php @@ -27,8 +27,7 @@ use_javascript_ajax) && empty($conf->dol_no_mouse_hover)) -{ +if (!empty($conf->use_javascript_ajax) && empty($conf->dol_no_mouse_hover)) { print "\n\n"; print ''); diff --git a/htdocs/cashdesk/index_verif.php b/htdocs/cashdesk/index_verif.php index 45ce3857068..0c0281e5414 100644 --- a/htdocs/cashdesk/index_verif.php +++ b/htdocs/cashdesk/index_verif.php @@ -42,36 +42,31 @@ $bankid_cheque = (GETPOST("CASHDESK_ID_BANKACCOUNT_CHEQUE") > 0) ?GETPOST("CASHD $bankid_cb = (GETPOST("CASHDESK_ID_BANKACCOUNT_CB") > 0) ?GETPOST("CASHDESK_ID_BANKACCOUNT_CB", 'int') : $conf->global->CASHDESK_ID_BANKACCOUNT_CB; // Check username -if (empty($username)) -{ +if (empty($username)) { $retour = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Login")); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); exit; } // Check third party id -if (!($thirdpartyid > 0)) -{ +if (!($thirdpartyid > 0)) { $retour = $langs->trans("ErrorFieldRequired", $langs->transnoentities("CashDeskThirdPartyForSell")); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); exit; } // If we setup stock module to ask movement on invoices, we must not allow access if required setup not finished. -if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !($warehouseid > 0)) -{ +if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !($warehouseid > 0)) { $retour = $langs->trans("CashDeskYouDidNotDisableStockDecease"); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); exit; } // If stock decrease on bill validation, check user has stock edit permissions -if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !empty($username)) -{ +if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !empty($username)) { $testuser = new User($db); $testuser->fetch(0, $username); $testuser->getrights('stock'); - if (empty($testuser->rights->stock->creer)) - { + if (empty($testuser->rights->stock->creer)) { $retour = $langs->trans("UserNeedPermissionToEditStockToUsePos"); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); exit; @@ -83,8 +78,7 @@ if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_S $auth = new Auth($db); $retour = $auth->verif($username, $password); -if ($retour >= 0) -{ +if ($retour >= 0) { $return = array(); $sql = "SELECT rowid, lastname, firstname"; @@ -93,12 +87,10 @@ if ($retour >= 0) $sql .= " AND entity IN (0,".$conf->entity.")"; $result = $db->query($sql); - if ($result) - { + if ($result) { $tab = $db->fetch_array($res); - foreach ($tab as $key => $value) - { + foreach ($tab as $key => $value) { $return[$key] = $value; } diff --git a/htdocs/cashdesk/tpl/facturation1.tpl.php b/htdocs/cashdesk/tpl/facturation1.tpl.php index d48fc544eb0..41a0f0b757e 100644 --- a/htdocs/cashdesk/tpl/facturation1.tpl.php +++ b/htdocs/cashdesk/tpl/facturation1.tpl.php @@ -21,8 +21,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } @@ -64,10 +63,11 @@ $id = $obj_facturation->id(); // Si trop d'articles ont ete trouves, on n'affiche que les X premiers (defini dans le fichier de configuration) ... $nbtoshow = $nbr_enreg; -if (!empty($conf_taille_listes) && $nbtoshow > $conf_taille_listes) $nbtoshow = $conf_taille_listes; +if (!empty($conf_taille_listes) && $nbtoshow > $conf_taille_listes) { + $nbtoshow = $conf_taille_listes; +} -for ($i = 0; $i < $nbtoshow; $i++) -{ +for ($i = 0; $i < $nbtoshow; $i++) { if ($id == $tab_designations[$i]['rowid']) { $selected = 'selected'; } else { @@ -96,9 +96,9 @@ for ($i = 0; $i < $nbtoshow; $i++)
    trans("Qty"); ?> trans("PriceUHT"); ?> trans("Discount"); ?> (%)trans("VATRate"); ?>trans("VATRate"); ?>
    @@ -106,20 +106,22 @@ for ($i = 0; $i < $nbtoshow; $i++) + + - - + + + vatrate; // To get vat rate we just have selected $buyer = new Societe($db); - if ($_SESSION["CASHDESK_ID_THIRDPARTY"] > 0) $buyer->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]); + if ($_SESSION["CASHDESK_ID_THIRDPARTY"] > 0) { + $buyer->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]); + } echo $form->load_tva('selTva', (GETPOSTISSET("selTva") ? GETPOST("selTva", 'alpha', 2) : $vatrate), $mysoc, $buyer, 0, 0, '', false, -1); ?> -
    trans("TotalHT"); ?>
    @@ -165,25 +167,28 @@ for ($i = 0; $i < $nbtoshow; $i++)
    '; - if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CASH']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CASH'] < 0) - { + if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CASH']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CASH'] < 0) { $langs->load("errors"); print 'transnoentitiesnoconv("CashDesk"))).'" />'; - } else print ''; + } else { + print ''; + } print '
    '; print '
    '; - if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CB']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CB'] < 0) - { + if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CB']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CB'] < 0) { $langs->load("errors"); print 'transnoentitiesnoconv("CashDesk"))).'" />'; - } else print ''; + } else { + print ''; + } print '
    '; print '
    '; - if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE'] < 0) - { + if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE'] < 0) { $langs->load("errors"); print 'transnoentitiesnoconv("CashDesk")).'" />'; - } else print ''; + } else { + print ''; + } print '
    '; print '
    '; print '
    '; diff --git a/htdocs/cashdesk/tpl/liste_articles.tpl.php b/htdocs/cashdesk/tpl/liste_articles.tpl.php index e3c3c285966..74be200945f 100644 --- a/htdocs/cashdesk/tpl/liste_articles.tpl.php +++ b/htdocs/cashdesk/tpl/liste_articles.tpl.php @@ -18,8 +18,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } @@ -48,10 +47,10 @@ $societe->fetch($thirdpartyid); $tab = (!empty($_SESSION['poscart']) ? $_SESSION['poscart'] : array()); $tab_size = count($tab); -if ($tab_size <= 0) print '
    '.$langs->trans("NoArticle").'

    '; -else { - for ($i = 0; $i < $tab_size; $i++) - { +if ($tab_size <= 0) { + print '
    '.$langs->trans("NoArticle").'

    '; +} else { + for ($i = 0; $i < $tab_size; $i++) { echo ('
    '."\n"); echo ('

    '.$tab[$i]['ref'].' - '.$tab[$i]['label'].'

    '."\n"); diff --git a/htdocs/cashdesk/tpl/menu.tpl.php b/htdocs/cashdesk/tpl/menu.tpl.php index 1e347f4d01e..67891aa67cf 100644 --- a/htdocs/cashdesk/tpl/menu.tpl.php +++ b/htdocs/cashdesk/tpl/menu.tpl.php @@ -20,8 +20,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } @@ -37,27 +36,23 @@ include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; $company->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]); $companyLink = $company->getNomUrl(1); }*/ -if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) -{ +if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) { $bankcash = new Account($db); $bankcash->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]); $bankcash->label = $bankcash->ref; $bankcashLink = $bankcash->getNomUrl(1); } -if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) -{ +if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) { $bankcb = new Account($db); $bankcb->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"]); $bankcbLink = $bankcb->getNomUrl(1); } -if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) -{ +if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) { $bankcheque = new Account($db); $bankcheque->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"]); $bankchequeLink = $bankcheque->getNomUrl(1); } -if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled)) -{ +if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled)) { $warehouse = new Entrepot($db); $warehouse->fetch($_SESSION["CASHDESK_ID_WAREHOUSE"]); $warehouseLink = $warehouse->getNomUrl(1); @@ -87,8 +82,7 @@ print ''; print $langs->trans("CashDeskBankCB").': '.$bankcbLink.'
    '; print $langs->trans("CashDeskBankCheque").': '.$bankchequeLink.'
    ';*/ print '
    '; -if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) -{ +if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) { print $langs->trans("CashDeskWarehouse").': '.$warehouseLink; } print '
    '; diff --git a/htdocs/cashdesk/tpl/ticket.tpl.php b/htdocs/cashdesk/tpl/ticket.tpl.php index 101ea687e7b..9220e3daad4 100644 --- a/htdocs/cashdesk/tpl/ticket.tpl.php +++ b/htdocs/cashdesk/tpl/ticket.tpl.php @@ -18,8 +18,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } @@ -38,82 +37,81 @@ $object->fetch($facid); ?> - - <?php echo $langs->trans('PrintTicket') ?> - + + <?php echo $langs->trans('PrintTicket') ?> +
    - -
    -

    name; ?>
    -
    -

    + +
    +

    name; ?>
    +
    +

    -

    '; print $object->ref; ?>

    -
    +

    - + - - - - - + + + + + - - - + + - - - - - - - - + + + + + + + - +
    trans("Code"); ?>trans("Label"); ?>trans("Qty"); ?>trans("Discount").' (%)'; ?>trans("TotalHT"); ?>trans("Code"); ?>trans("Label"); ?>trans("Qty"); ?>trans("Discount").' (%)'; ?>trans("TotalHT"); ?>
    currency); ?>
    currency); ?>
    - - + + - + - +
    trans("TotalHT"); ?>amountWithoutTax(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?>trans("TotalHT"); ?>amountWithoutTax(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?>
    trans("TotalVAT").''.price(price2num($obj_facturation->amountVat(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?>trans("TotalVAT").''.price(price2num($obj_facturation->amountVat(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?>
    trans("TotalTTC").''.price(price2num($obj_facturation->amountWithTax(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?>trans("TotalTTC").''.price(price2num($obj_facturation->amountWithTax(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?>
    trans("Close"); ?> diff --git a/htdocs/cashdesk/tpl/validation1.tpl.php b/htdocs/cashdesk/tpl/validation1.tpl.php index cc558cca058..c2a9124f300 100644 --- a/htdocs/cashdesk/tpl/validation1.tpl.php +++ b/htdocs/cashdesk/tpl/validation1.tpl.php @@ -17,8 +17,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } @@ -47,25 +46,27 @@ if ($obj_facturation->amountVat()) {
    trans("TotalTTC"); ?> amountWithTax(), 'MT'), 0, $langs, 0, 0, -1, $conf->currency); ?>
    trans("PaymentMode"); ?> getSetPaymentMode()) - { + switch ($obj_facturation->getSetPaymentMode()) { case 'ESP': echo $langs->trans("Cash"); $filtre = 'courant=2'; - if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) + if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) { $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]; + } break; case 'CB': echo $langs->trans("CreditCard"); $filtre = 'courant=1'; - if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) + if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) { $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CB"]; + } break; case 'CHQ': echo $langs->trans("Cheque"); $filtre = 'courant=1'; - if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) + if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) { $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"]; + } break; case 'DIF': echo $langs->trans("Reported"); diff --git a/htdocs/cashdesk/tpl/validation2.tpl.php b/htdocs/cashdesk/tpl/validation2.tpl.php index 8b3ca9c76d5..d89edfdc41a 100644 --- a/htdocs/cashdesk/tpl/validation2.tpl.php +++ b/htdocs/cashdesk/tpl/validation2.tpl.php @@ -18,8 +18,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } diff --git a/htdocs/cashdesk/validation_ticket.php b/htdocs/cashdesk/validation_ticket.php index 28ad91dc4e7..0c32dfa8c44 100644 --- a/htdocs/cashdesk/validation_ticket.php +++ b/htdocs/cashdesk/validation_ticket.php @@ -33,8 +33,7 @@ $hookmanager->initHooks(array('cashdeskTplTicket')); $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $obj_facturation); -if (empty($reshook)) -{ +if (empty($reshook)) { require 'tpl/ticket.tpl.php'; } diff --git a/htdocs/cashdesk/validation_verif.php b/htdocs/cashdesk/validation_verif.php index da320c7d855..b9ad0d94a02 100644 --- a/htdocs/cashdesk/validation_verif.php +++ b/htdocs/cashdesk/validation_verif.php @@ -36,8 +36,7 @@ $obj_facturation = unserialize($_SESSION['serObjFacturation']); $action = GETPOST('action', 'aZ09'); $bankaccountid = GETPOST('cashdeskbank'); -switch ($action) -{ +switch ($action) { default: $redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=validation'; break; @@ -55,15 +54,18 @@ switch ($action) // To use a specific numbering module for POS, reset $conf->global->FACTURE_ADDON and other vars here // and restore values just after $sav_FACTURE_ADDON = ''; - if (!empty($conf->global->POS_ADDON)) - { + if (!empty($conf->global->POS_ADDON)) { $sav_FACTURE_ADDON = $conf->global->FACTURE_ADDON; $conf->global->FACTURE_ADDON = $conf->global->POS_ADDON; // To force prefix only for POS with terre module - if (!empty($conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX)) $conf->global->INVOICE_NUMBERING_TERRE_FORCE_PREFIX = $conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX; + if (!empty($conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX)) { + $conf->global->INVOICE_NUMBERING_TERRE_FORCE_PREFIX = $conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX; + } // To force prefix only for POS with mars module - if (!empty($conf->global->POS_NUMBERING_MARS_FORCE_PREFIX)) $conf->global->INVOICE_NUMBERING_MARS_FORCE_PREFIX = $conf->global->POS_NUMBERING_MARS_FORCE_PREFIX; + if (!empty($conf->global->POS_NUMBERING_MARS_FORCE_PREFIX)) { + $conf->global->INVOICE_NUMBERING_MARS_FORCE_PREFIX = $conf->global->POS_NUMBERING_MARS_FORCE_PREFIX; + } // To force rule only for POS with mercure //... } @@ -71,8 +73,7 @@ switch ($action) $num = $invoice->getNextNumRef($company); // Restore save values - if (!empty($sav_FACTURE_ADDON)) - { + if (!empty($sav_FACTURE_ADDON)) { $conf->global->FACTURE_ADDON = $sav_FACTURE_ADDON; } @@ -120,14 +121,12 @@ switch ($action) $heure = dol_print_date($now, 'hour'); $note = ''; - if (!is_object($obj_facturation)) - { + if (!is_object($obj_facturation)) { dol_print_error('', 'Empty context'); exit; } - switch ($obj_facturation->getSetPaymentMode()) - { + switch ($obj_facturation->getSetPaymentMode()) { case 'DIF': $mode_reglement_id = 0; //$cond_reglement_id = dol_getIdFromCode($db,'RECEP','cond_reglement','code','rowid') @@ -151,8 +150,12 @@ switch ($action) $cond_reglement_id = 0; break; } - if (empty($mode_reglement_id)) $mode_reglement_id = 0; // If mode_reglement_id not found - if (empty($cond_reglement_id)) $cond_reglement_id = 0; // If cond_reglement_id not found + if (empty($mode_reglement_id)) { + $mode_reglement_id = 0; // If mode_reglement_id not found + } + if (empty($cond_reglement_id)) { + $cond_reglement_id = 0; // If cond_reglement_id not found + } $note .= $_POST['txtaNotes']; dol_syslog("obj_facturation->getSetPaymentMode()=".$obj_facturation->getSetPaymentMode()." mode_reglement_id=".$mode_reglement_id." cond_reglement_id=".$cond_reglement_id); @@ -175,8 +178,7 @@ switch ($action) // Loop on each line into cart $tab_liste_size = count($tab_liste); - for ($i = 0; $i < $tab_liste_size; $i++) - { + for ($i = 0; $i < $tab_liste_size; $i++) { $tmp = getTaxesFromId($tab_liste[$i]['fk_tva']); $vat_rate = $tmp['rate']; $vat_npr = $tmp['npr']; @@ -218,32 +220,32 @@ switch ($action) //print "c=".$invoice->cond_reglement_id." m=".$invoice->mode_reglement_id; exit; // Si paiement differe ... - if ($obj_facturation->getSetPaymentMode() == 'DIF') - { + if ($obj_facturation->getSetPaymentMode() == 'DIF') { $resultcreate = $invoice->create($user, 0, dol_stringtotime($obj_facturation->paiementLe())); - if ($resultcreate > 0) - { + if ($resultcreate > 0) { $warehouseidtodecrease = (isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0); - if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice + if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) { + $warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice + } $resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), 0); - if ($warehouseidtodecrease > 0) - { + if ($warehouseidtodecrease > 0) { // Decrease require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); // Loop on each line $cpt = count($invoice->lines); - for ($i = 0; $i < $cpt; $i++) - { - if ($invoice->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $cpt; $i++) { + if ($invoice->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($db); $mouvP->origin = &$invoice; // We decrease stock for product - if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); - else $result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); + if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) { + $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); + } else { + $result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); + } if ($result < 0) { $error++; } @@ -258,29 +260,30 @@ switch ($action) $id = $invoice->id; } else { $resultcreate = $invoice->create($user, 0, 0); - if ($resultcreate > 0) - { + if ($resultcreate > 0) { $warehouseidtodecrease = (isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0); - if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice + if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) { + $warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice + } $resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), 0); - if ($warehouseidtodecrease > 0) - { + if ($warehouseidtodecrease > 0) { // Decrease require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); // Loop on each line $cpt = count($invoice->lines); - for ($i = 0; $i < $cpt; $i++) - { - if ($invoice->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $cpt; $i++) { + if ($invoice->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($db); $mouvP->origin = &$invoice; // We decrease stock for product - if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); - else $result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); + if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) { + $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); + } else { + $result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); + } if ($result < 0) { setEventMessages($mouvP->error, $mouvP->errors, 'errors'); $error++; @@ -301,26 +304,21 @@ switch ($action) $payment->num_payment = ''; $paiement_id = $payment->create($user); - if ($paiement_id > 0) - { - if (!$error) - { + if ($paiement_id > 0) { + if (!$error) { $result = $payment->addPaymentToBank($user, 'payment', '(CustomerInvoicePayment)', $bankaccountid, '', ''); - if (!$result > 0) - { + if (!$result > 0) { $errmsg = $paiement->error; $error++; } } - if (!$error) - { + if (!$error) { if ($invoice->total_ttc == $obj_facturation->amountWithTax() - && $obj_facturation->getSetPaymentMode() != 'DIFF') - { + && $obj_facturation->getSetPaymentMode() != 'DIFF') { // We set status to paid $result = $invoice->setPaid($user); - //print 'set paid';exit; + //print 'set paid';exit; } } } else { @@ -334,8 +332,7 @@ switch ($action) } - if (!$error) - { + if (!$error) { $db->commit(); $redirection = 'affIndex.php?menutpl=validation_ok&facid='.$id; // Ajout de l'id de la facture, pour l'inclure dans un lien pointant directement vers celle-ci dans Dolibarr } else { diff --git a/htdocs/categories/admin/categorie.php b/htdocs/categories/admin/categorie.php index 693a3e53a2a..bddeb9a771a 100644 --- a/htdocs/categories/admin/categorie.php +++ b/htdocs/categories/admin/categorie.php @@ -27,8 +27,9 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/categories.lib.php'; -if (!$user->admin) -accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array("categories", "admin")); @@ -40,11 +41,9 @@ $action = GETPOST('action', 'aZ09'); */ $reg = array(); -if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) -{ +if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; - if (dolibarr_set_const($db, $code, 1, 'chaine', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, $code, 1, 'chaine', 0, '', $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -52,11 +51,9 @@ if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) } } -if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) -{ +if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; - if (dolibarr_del_const($db, $code, $conf->entity) > 0) - { + if (dolibarr_del_const($db, $code, $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -100,12 +97,10 @@ print ''.$langs->trans("CategorieRecursiv").''.$form->textwithpicto('', $langs->trans("CategorieRecursivHelp"), 1, 'help').''; -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print ajax_constantonoff('CATEGORIE_RECURSIV_ADD'); } else { - if (empty($conf->global->CATEGORIE_RECURSIV_ADD)) - { + if (empty($conf->global->CATEGORIE_RECURSIV_ADD)) { print ''.img_picto($langs->trans("Disabled"), 'off').''; } else { print ''.img_picto($langs->trans("Enabled"), 'on').''; diff --git a/htdocs/categories/admin/categorie_extrafields.php b/htdocs/categories/admin/categorie_extrafields.php index ff6a4ca7881..0d691995c29 100644 --- a/htdocs/categories/admin/categorie_extrafields.php +++ b/htdocs/categories/admin/categorie_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 = 'categorie'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -76,8 +80,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -90,8 +93,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '
    '; print load_fiche_titre($langs->trans('NewAttribute')); @@ -103,8 +105,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
    "; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/categories/card.php b/htdocs/categories/card.php index 74e16f9082d..9f275033b01 100644 --- a/htdocs/categories/card.php +++ b/htdocs/categories/card.php @@ -37,14 +37,16 @@ $langs->load("categories"); // Security check $socid = (int) GETPOST('socid', 'int'); -if (!$user->rights->categorie->lire) accessforbidden(); +if (!$user->rights->categorie->lire) { + accessforbidden(); +} -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); $origin = GETPOST('origin', 'alpha'); $catorigin = (int) GETPOST('catorigin', 'int'); -$type = GETPOST('type', 'aZ09'); -$urlfrom = GETPOST('urlfrom', 'alpha'); +$type = GETPOST('type', 'aZ09'); +$urlfrom = GETPOST('urlfrom', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); $label = (string) GETPOST('label', 'alphanohtml'); @@ -54,15 +56,29 @@ $visible = (int) GETPOST('visible', 'int'); $parent = (int) GETPOST('parent', 'int'); if ($origin) { - if ($type == Categorie::TYPE_PRODUCT) $idProdOrigin = $origin; - if ($type == Categorie::TYPE_SUPPLIER) $idSupplierOrigin = $origin; - if ($type == Categorie::TYPE_CUSTOMER) $idCompanyOrigin = $origin; - if ($type == Categorie::TYPE_MEMBER) $idMemberOrigin = $origin; - if ($type == Categorie::TYPE_CONTACT) $idContactOrigin = $origin; - if ($type == Categorie::TYPE_PROJECT) $idProjectOrigin = $origin; + if ($type == Categorie::TYPE_PRODUCT) { + $idProdOrigin = $origin; + } + if ($type == Categorie::TYPE_SUPPLIER) { + $idSupplierOrigin = $origin; + } + if ($type == Categorie::TYPE_CUSTOMER) { + $idCompanyOrigin = $origin; + } + if ($type == Categorie::TYPE_MEMBER) { + $idMemberOrigin = $origin; + } + if ($type == Categorie::TYPE_CONTACT) { + $idContactOrigin = $origin; + } + if ($type == Categorie::TYPE_PROJECT) { + $idProjectOrigin = $origin; + } } -if ($catorigin && $type == Categorie::TYPE_PRODUCT) $idCatOrigin = $catorigin; +if ($catorigin && $type == Categorie::TYPE_PRODUCT) { + $idCatOrigin = $catorigin; +} $object = new Categorie($db); @@ -80,13 +96,10 @@ $error = 0; */ // Add action -if ($action == 'add' && $user->rights->categorie->creer) -{ - // Action ajout d'une categorie - if ($cancel) - { - if ($urlfrom) - { +if ($action == 'add' && $user->rights->categorie->creer) { + // Action add a category + if ($cancel) { + if ($urlfrom) { header("Location: ".$urlfrom); exit; } elseif ($backtopage) { @@ -125,24 +138,25 @@ if ($action == 'add' && $user->rights->categorie->creer) $object->visible = $visible; $object->type = $type; - if ($parent != "-1") $object->fk_parent = $parent; + if ($parent != "-1") { + $object->fk_parent = $parent; + } $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$object->label) - { + if (!$object->label) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); $action = 'create'; } // Create category in database - if (!$error) - { + if (!$error) { $result = $object->create($user); - if ($result > 0) - { + if ($result > 0) { $action = 'confirmed'; $_POST["addcat"] = ''; } else { @@ -152,41 +166,31 @@ if ($action == 'add' && $user->rights->categorie->creer) } // Confirm action -if (($action == 'add' || $action == 'confirmed') && $user->rights->categorie->creer) -{ - // Action confirmation de creation categorie - if ($action == 'confirmed') - { - if ($urlfrom) - { +if (($action == 'add' || $action == 'confirmed') && $user->rights->categorie->creer) { + // Action confirmation of creation category + if ($action == 'confirmed') { + if ($urlfrom) { header("Location: ".$urlfrom); exit; - } elseif ($backtopage) - { + } elseif ($backtopage) { header("Location: ".$backtopage); exit; - } elseif ($idProdOrigin) - { + } elseif ($idProdOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProdOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); exit; - } elseif ($idCompanyOrigin) - { + } elseif ($idCompanyOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idCompanyOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); exit; - } elseif ($idSupplierOrigin) - { + } elseif ($idSupplierOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idSupplierOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); exit; - } elseif ($idMemberOrigin) - { + } elseif ($idMemberOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idMemberOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); exit; - } elseif ($idContactOrigin) - { + } elseif ($idContactOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idContactOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); exit; - } elseif ($idProjectOrigin) - { + } elseif ($idProjectOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProjectOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); exit; } @@ -204,14 +208,12 @@ if (($action == 'add' || $action == 'confirmed') && $user->rights->categorie->cr $form = new Form($db); $formother = new FormOther($db); -$helpurl = ''; +$helpurl = 'EN:Module_Categories|FR:Module_Catégories'; llxHeader("", $langs->trans("Categories"), $helpurl); -if ($user->rights->categorie->creer) -{ +if ($user->rights->categorie->creer) { // Create or add - if ($action == 'create' || GETPOST("addcat") == 'addcat') - { + if ($action == 'create' || GETPOST("addcat") == 'addcat') { dol_set_focus('#label'); print '
    '; @@ -222,8 +224,12 @@ if ($user->rights->categorie->creer) print ''; print ''; print ''; - if ($origin) print ''; - if ($catorigin) print ''; + if ($origin) { + print ''; + } + if ($catorigin) { + print ''; + } print load_fiche_titre($langs->trans("CreateCat")); @@ -257,8 +263,7 @@ if ($user->rights->categorie->creer) $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index 03610100c9c..65483a561af 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -140,15 +140,12 @@ class Categories extends DolibarrApi $sql = "SELECT t.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."categorie as t"; $sql .= ' WHERE t.entity IN ('.getEntity('category').')'; - if (!empty($type)) - { + if (!empty($type)) { $sql .= ' AND t.type='.array_search($type, Categories::$TYPES); } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -157,8 +154,7 @@ class Categories extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -167,13 +163,11 @@ class Categories extends DolibarrApi } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $i = 0; $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $category_static = new Categorie($this->db); if ($category_static->fetch($obj->rowid)) { @@ -181,8 +175,7 @@ class Categories extends DolibarrApi } $i++; } - } - else { + } else { throw new RestException(503, 'Error when retrieve category list : '.$this->db->lasterror()); } if (!count($obj_ret)) { @@ -238,7 +231,9 @@ class Categories extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->category->$field = $value; } @@ -721,8 +716,9 @@ class Categories extends DolibarrApi { $category = array(); foreach (Categories::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $category[$field] = $data[$field]; } return $category; @@ -747,8 +743,7 @@ class Categories extends DolibarrApi throw new RestException(401); } - if (empty($type)) - { + if (empty($type)) { throw new RestException(500, 'The "type" parameter is required.'); } diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 7f8e415e4b1..ba8ffe0e89f 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -98,7 +98,7 @@ class Categorie extends CommonObject 8 => 'bank_line', 9 => 'warehouse', 10 => 'actioncomm', - 11 => 'website_page' + 11 => 'website_page' ); /** @@ -197,7 +197,7 @@ class Categorie extends CommonObject /** * @var string Category label */ - public $label; + public $label; /** * @var string description @@ -231,9 +231,9 @@ class Categorie extends CommonObject * @see Categorie::TYPE_PROJECT * @see Categorie::TYPE_ACCOUNT * @see Categorie::TYPE_BANK_LINE - * @see Categorie::TYPE_WAREHOUSE - * @see Categorie::TYPE_ACTIONCOMM - * @see Categorie::TYPE_WEBSITE_PAGE + * @see Categorie::TYPE_WAREHOUSE + * @see Categorie::TYPE_ACTIONCOMM + * @see Categorie::TYPE_WEBSITE_PAGE */ public $type; @@ -266,9 +266,9 @@ class Categorie extends CommonObject $mapList = $hookmanager->resArray; $mapId = $mapList['id']; $mapCode = $mapList['code']; - self::$MAP_ID_TO_CODE[$mapId] = $mapCode; - $this->MAP_ID[$mapCode] = $mapId; - $this->MAP_CAT_FK[$mapCode] = $mapList['cat_fk']; + self::$MAP_ID_TO_CODE[$mapId] = $mapCode; + $this->MAP_ID[$mapCode] = $mapId; + $this->MAP_CAT_FK[$mapCode] = $mapList['cat_fk']; $this->MAP_CAT_TABLE[$mapCode] = $mapList['cat_table']; $this->MAP_OBJ_CLASS[$mapCode] = $mapList['obj_class']; $this->MAP_OBJ_TABLE[$mapCode] = $mapList['obj_table']; @@ -313,19 +313,25 @@ class Categorie extends CommonObject global $conf; // Check parameters - if (empty($id) && empty($label) && empty($ref_ext)) return -1; - if (!is_null($type) && !is_numeric($type)) $type = $this->MAP_ID[$type]; + if (empty($id) && empty($label) && empty($ref_ext)) { + return -1; + } + if (!is_null($type) && !is_numeric($type)) { + $type = $this->MAP_ID[$type]; + } $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 { $sql .= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category').")"; - if (!is_null($type)) $sql .= " AND type = ".((int) $type); + if (!is_null($type)) { + $sql .= " AND type = ".((int) $type); + } } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -357,7 +363,9 @@ class Categorie extends CommonObject $this->db->free($resql); // multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) $this->getMultiLangs(); + if (!empty($conf->global->MAIN_MULTILANGS)) { + $this->getMultiLangs(); + } return 1; } else { @@ -365,6 +373,8 @@ class Categorie extends CommonObject } } else { dol_print_error($this->db); + $this->error=$this->db->lasterror; + $this->errors[]=$this->db->lasterror; return -1; } } @@ -385,7 +395,9 @@ class Categorie extends CommonObject $type = $this->type; - if (!is_numeric($type)) $type = $this->MAP_ID[$type]; + if (!is_numeric($type)) { + $type = $this->MAP_ID[$type]; + } $error = 0; @@ -397,7 +409,9 @@ class Categorie extends CommonObject $this->color = trim($this->color); $this->import_key = trim($this->import_key); $this->ref_ext = trim($this->ref_ext); - if (empty($this->visible)) $this->visible = 0; + if (empty($this->visible)) { + $this->visible = 0; + } $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0); if ($this->already_exists()) { @@ -461,7 +475,9 @@ class Categorie extends CommonObject if (!$error) { // Call trigger $result = $this->call_trigger('CATEGORY_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -540,7 +556,9 @@ class Categorie extends CommonObject if (!$error) { // Call trigger $result = $this->call_trigger('CATEGORY_MODIFY', $user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } + if ($result < 0) { + $error++; $this->db->rollback(); return -1; + } // End call triggers } @@ -577,7 +595,9 @@ class Categorie extends CommonObject if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CATEGORY_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -647,9 +667,13 @@ class Categorie extends CommonObject $error = 0; - if ($this->id == -1) return -2; + if ($this->id == -1) { + return -2; + } - if (empty($type)) $type = $obj->element; + if (empty($type)) { + $type = $obj->element; + } $this->db->begin(); @@ -697,7 +721,9 @@ class Categorie extends CommonObject // Call trigger $this->context = array('linkto'=>$obj); // Save object we want to link category to into category instance to provide information to trigger $result = $this->call_trigger('CATEGORY_LINK', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers if (!$error) { @@ -755,7 +781,9 @@ class Categorie extends CommonObject // Call trigger $this->context = array('unlinkoff'=>$obj); // Save object we want to link category to into category instance to provide information to trigger $result = $this->call_trigger('CATEGORY_UNLINK', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers if (!$error) { @@ -803,7 +831,9 @@ class Categorie extends CommonObject if (($type == 'customer' || $type == 'supplier') && $user->socid > 0) { $sql .= " AND o.rowid = ".$user->socid; } - if ($limit > 0 || $offset > 0) $sql .= $this->db->plimit($limit + 1, $offset); + if ($limit > 0 || $offset > 0) { + $sql .= $this->db->plimit($limit + 1, $offset); + } $sql .= $this->db->order($sortfield, $sortorder); dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG); @@ -1035,7 +1065,9 @@ class Categorie extends CommonObject // phpcs:enable global $conf, $langs; - if (!is_numeric($type)) $type = $this->MAP_ID[$type]; + if (!is_numeric($type)) { + $type = $this->MAP_ID[$type]; + } if (is_null($type)) { $this->error = 'BadValueForParameterType'; return -1; @@ -1061,9 +1093,13 @@ class Categorie extends CommonObject // Init $this->cats array $sql = "SELECT DISTINCT c.rowid, c.label, c.ref_ext, c.description, c.color, c.fk_parent, c.visible"; // Distinct reduce pb with old tables with duplicates - if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= ", t.label as label_trans, t.description as description_trans"; + if (!empty($conf->global->MAIN_MULTILANGS)) { + $sql .= ", t.label as label_trans, t.description as description_trans"; + } $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c"; - if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$this->db->escape($current_lang)."'"; + if (!empty($conf->global->MAIN_MULTILANGS)) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$this->db->escape($current_lang)."'"; + } $sql .= " WHERE c.entity IN (".getEntity('category').")"; $sql .= " AND c.type = ".(int) $type; @@ -1202,14 +1238,18 @@ class Categorie extends CommonObject public function get_all_categories($type = null, $parent = false) { // phpcs:enable - if (!is_numeric($type)) $type = $this->MAP_ID[$type]; + if (!is_numeric($type)) { + $type = $this->MAP_ID[$type]; + } $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie"; $sql .= " WHERE entity IN (".getEntity('category').")"; - if (!is_null($type)) + if (!is_null($type)) { $sql .= " AND type = ".(int) $type; - if ($parent) + } + if ($parent) { $sql .= " AND fk_parent = 0"; + } $res = $this->db->query($sql); if ($res) { @@ -1250,7 +1290,9 @@ class Categorie extends CommonObject // phpcs:enable $type = $this->type; - if (!is_numeric($type)) $type = $this->MAP_ID[$type]; + if (!is_numeric($type)) { + $type = $this->MAP_ID[$type]; + } /* We have to select any rowid from llx_categorie which category's mother and label * are equals to those of the calling category @@ -1316,7 +1358,9 @@ class Categorie extends CommonObject // Check contrast with background and correct text color $forced_color = 'categtextwhite'; if ($cat->color) { - if (colorIsLight($cat->color)) $forced_color = 'categtextblack'; + if (colorIsLight($cat->color)) { + $forced_color = 'categtextblack'; + } } } } @@ -1397,8 +1441,9 @@ class Categorie extends CommonObject } } - if (count($ways) == 0) + if (count($ways) == 0) { $ways[0][0] = $this; + } return $ways; } @@ -1417,7 +1462,9 @@ class Categorie extends CommonObject { $cats = array(); - if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; + if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; + } if ($type === Categorie::TYPE_BANK_LINE) { // TODO Remove this with standard category code after migration of llx_bank_categ into llx_categorie // Load bank categories @@ -1507,11 +1554,14 @@ class Categorie extends CommonObject $sql .= " WHERE type = ".$this->MAP_ID[$type]; $sql .= " AND entity IN (".getEntity('category').")"; if ($nom) { - if (!$exact) + if (!$exact) { $nom = '%'.str_replace('*', '%', $nom).'%'; - if (!$case) + } + if (!$case) { $sql .= " AND label LIKE '".$this->db->escape($nom)."'"; - else $sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'"; + } else { + $sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'"; + } } if ($id) { $sql .= " AND rowid = '".$id."'"; @@ -1552,7 +1602,9 @@ class Categorie extends CommonObject // Check contrast with background and correct text color $forced_color = 'categtextwhite'; if ($this->color) { - if (colorIsLight($this->color)) $forced_color = 'categtextblack'; + if (colorIsLight($this->color)) { + $forced_color = 'categtextblack'; + } } $link = ''; @@ -1561,9 +1613,15 @@ class Categorie extends CommonObject $picto = 'category'; - if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); - if ($withpicto && $withpicto != 2) $result .= ' '; - if ($withpicto != 2) $result .= $link.dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength).$linkend; + if ($withpicto) { + $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + if ($withpicto != 2) { + $result .= $link.dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength).$linkend; + } return $result; } @@ -1651,13 +1709,18 @@ class Categorie extends CommonObject // Objet $obj = array(); $obj['photo'] = $photo; - if ($photo_vignette && is_file($dirthumb.$photo_vignette)) $obj['photo_vignette'] = 'thumbs/'.$photo_vignette; - else $obj['photo_vignette'] = ""; + if ($photo_vignette && is_file($dirthumb.$photo_vignette)) { + $obj['photo_vignette'] = 'thumbs/'.$photo_vignette; + } else { + $obj['photo_vignette'] = ""; + } $tabobj[$nbphoto - 1] = $obj; // On continue ou on arrete de boucler - if ($nbmax && $nbphoto >= $nbmax) break; + if ($nbmax && $nbphoto >= $nbmax) { + break; + } } } @@ -1762,8 +1825,9 @@ class Categorie extends CommonObject } // on ne sauvegarde pas des champs vides - if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"]) + if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"]) { dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG); + } if (!$this->db->query($sql2)) { $this->error = $this->db->lasterror(); return -1; @@ -1874,7 +1938,9 @@ class Categorie extends CommonObject */ public static function getFilterJoinQuery($type, $rowIdName) { - if ($type == 'bank_account') $type = 'account'; + if ($type == 'bank_account') { + $type = 'account'; + } return " LEFT JOIN ".MAIN_DB_PREFIX."categorie_".$type." as cp ON ".$rowIdName." = cp.fk_".$type; } @@ -1889,7 +1955,9 @@ class Categorie extends CommonObject */ public static function getFilterSelectQuery($type, $rowIdName, $searchList) { - if ($type == 'bank_account') $type = 'account'; + if ($type == 'bank_account') { + $type = 'account'; + } if (empty($searchList) && !is_array($searchList)) { return ""; diff --git a/htdocs/categories/edit.php b/htdocs/categories/edit.php index a5578032a3d..176b39ca008 100644 --- a/htdocs/categories/edit.php +++ b/htdocs/categories/edit.php @@ -62,7 +62,9 @@ if ($result <= 0) { } $type = $object->type; -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); @@ -90,7 +92,7 @@ if ($cancel) { // Action mise a jour d'une categorie if ($action == 'update' && $user->rights->categorie->creer) { $object->oldcopy = dol_clone($object); - $object->label = $label; + $object->label = $label; $object->description = dol_htmlcleanlastbr($description); $object->color = $color; $object->socid = ($socid > 0 ? $socid : 0); @@ -105,10 +107,11 @@ if ($action == 'update' && $user->rights->categorie->creer) { } if (!$error && empty($object->error)) { $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error && $object->update($user) > 0) - { + if (!$error && $object->update($user) > 0) { if ($backtopage) { header("Location: ".$backtopage); exit; diff --git a/htdocs/categories/index.php b/htdocs/categories/index.php index ff897db86a7..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 @@ -34,7 +35,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; // Load translation files required by the page $langs->load("categories"); -if (!$user->rights->categorie->lire) accessforbidden(); +if (!$user->rights->categorie->lire) { + accessforbidden(); +} $id = GETPOST('id', 'int'); $type = (GETPOST('type', 'aZ09') ? GETPOST('type', 'aZ09') : Categorie::TYPE_PRODUCT); @@ -42,7 +45,9 @@ $catname = GETPOST('catname', 'alpha'); $nosearch = GETPOST('nosearch', 'int'); $categstatic = new Categorie($db); -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} /* @@ -54,11 +59,15 @@ $form = new Form($db); $moreparam = ($nosearch ? '&nosearch=1' : ''); $typetext = $type; -if ($type == Categorie::TYPE_ACCOUNT) $title = $langs->trans('AccountsCategoriesArea'); -elseif ($type == Categorie::TYPE_WAREHOUSE) $title = $langs->trans('StocksCategoriesArea'); -elseif ($type == Categorie::TYPE_ACTIONCOMM) $title = $langs->trans('ActionCommCategoriesArea'); -elseif ($type == Categorie::TYPE_WEBSITE_PAGE) $title = $langs->trans('WebsitePagesCategoriesArea'); -else { +if ($type == Categorie::TYPE_ACCOUNT) { + $title = $langs->trans('AccountsCategoriesArea'); +} elseif ($type == Categorie::TYPE_WAREHOUSE) { + $title = $langs->trans('StocksCategoriesArea'); +} elseif ($type == Categorie::TYPE_ACTIONCOMM) { + $title = $langs->trans('ActionCommCategoriesArea'); +} elseif ($type == Categorie::TYPE_WEBSITE_PAGE) { + $title = $langs->trans('WebsitePagesCategoriesArea'); +} else { $title = $langs->trans(ucfirst($type).'sCategoriesArea'); } @@ -100,15 +109,13 @@ if (empty($nosearch)) { /* * Categories found */ - if ($catname || $id > 0) - { + if ($catname || $id > 0) { $cats = $categstatic->rechercher($id, $catname, $typetext); print ''; print ''; - foreach ($cats as $cat) - { + foreach ($cats as $cat) { $color = $categstatic->color ? ' style="background: #'.sprintf("%06s", $categstatic->color).';"' : ' style="background: #bbb"'; print "\t".''."\n"; @@ -128,7 +135,9 @@ if (empty($nosearch)) { print "\t\n"; } print "
    '.$langs->trans("FoundCats").'
    "; - } else print ' '; + } else { + print ' '; + } print ''; } @@ -143,19 +152,25 @@ $cate_arbo = $categstatic->get_full_arbo($typetext); $fulltree = $cate_arbo; // Load possible missing includes -if ($conf->global->CATEGORY_SHOW_COUNTS) -{ - if ($type == Categorie::TYPE_MEMBER) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; - if ($type == Categorie::TYPE_ACCOUNT) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - if ($type == Categorie::TYPE_PROJECT) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - if ($type == Categorie::TYPE_USER) require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; +if (!empty($conf->global->CATEGORY_SHOW_COUNTS)) { + if ($type == Categorie::TYPE_MEMBER) { + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + } + if ($type == Categorie::TYPE_ACCOUNT) { + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + } + if ($type == Categorie::TYPE_PROJECT) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + } + if ($type == Categorie::TYPE_USER) { + require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; + } } // Define data (format for treeview) $data = array(); $data[] = array('rowid'=>0, 'fk_menu'=>-1, 'title'=>"racine", 'mainmenu'=>'', 'leftmenu'=>'', 'fk_mainmenu'=>'', 'fk_leftmenu'=>''); -foreach ($fulltree as $key => $val) -{ +foreach ($fulltree as $key => $val) { $categstatic->id = $val['id']; $categstatic->ref = $val['label']; $categstatic->color = $val['color']; @@ -163,8 +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" @@ -206,15 +220,13 @@ foreach ($fulltree as $key => $val) print ''; print ''; $nbofentries = (count($data) - 1); -if ($nbofentries > 0) -{ +if ($nbofentries > 0) { print ''; diff --git a/htdocs/categories/info.php b/htdocs/categories/info.php index 536b0c20a2c..f5b54f50de9 100644 --- a/htdocs/categories/info.php +++ b/htdocs/categories/info.php @@ -20,7 +20,7 @@ /** * \file htdocs/categories/info.php * \ingroup categories - * \brief Category info page + * \brief Category info page */ require '../main.inc.php'; @@ -40,7 +40,9 @@ $id = GETPOST('id', 'int'); $label = GETPOST('label', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'categorie', $id, '&category'); $object = new Categorie($db); @@ -50,7 +52,9 @@ if ($result <= 0) { } $type = $object->type; -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} /* * View @@ -67,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 6bb5d79980c..e30067e8815 100644 --- a/htdocs/categories/photos.php +++ b/htdocs/categories/photos.php @@ -38,11 +38,10 @@ $langs->loadlangs(array('categories', 'bills')); $id = GETPOST('id', 'int'); $label = GETPOST('label', 'alpha'); -$action = GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm'); -if ($id == '' && $label == '') -{ +if ($id == '' && $label == '') { dol_print_error('', 'Missing parameter id'); exit(); } @@ -57,7 +56,9 @@ if ($result <= 0) { } $type = $object->type; -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} $upload_dir = $conf->categorie->multidir_output[$object->entity]; @@ -65,16 +66,12 @@ $upload_dir = $conf->categorie->multidir_output[$object->entity]; * Actions */ -if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sendit"] && !empty($conf->global->MAIN_UPLOAD_DOC)) -{ +if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sendit"] && !empty($conf->global->MAIN_UPLOAD_DOC)) { if ($object->id) { $file = $_FILES['userfile']; - if (is_array($file['name']) && count($file['name']) > 0) - { - foreach ($file['name'] as $i => $name) - { - if (empty($file['tmp_name'][$i]) || intval($conf->global->MAIN_UPLOAD_DOC) * 1000 <= filesize($file['tmp_name'][$i])) - { + if (is_array($file['name']) && count($file['name']) > 0) { + foreach ($file['name'] as $i => $name) { + if (empty($file['tmp_name'][$i]) || intval($conf->global->MAIN_UPLOAD_DOC) * 1000 <= filesize($file['tmp_name'][$i])) { setEventMessage($file['name'][$i].' : '.$langs->trans(empty($file['tmp_name'][$i]) ? 'ErrorFailedToSaveFile' : 'MaxSizeForUploadedFiles')); unset($file['name'][$i], $file['type'][$i], $file['tmp_name'][$i], $file['error'][$i], $file['size'][$i]); } @@ -87,13 +84,11 @@ if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sen } } -if ($action == 'confirm_delete' && $_GET["file"] && $confirm == 'yes' && $user->rights->categorie->creer) -{ +if ($action == 'confirm_delete' && $_GET["file"] && $confirm == 'yes' && $user->rights->categorie->creer) { $object->delete_photo($upload_dir."/".$_GET["file"]); } -if ($action == 'addthumb' && $_GET["file"]) -{ +if ($action == 'addthumb' && $_GET["file"]) { $object->addThumbs($upload_dir."/".$_GET["file"]); } @@ -107,20 +102,19 @@ llxHeader("", "", $langs->trans("Categories")); $form = new Form($db); $formother = new FormOther($db); -if ($object->id) -{ +if ($object->id) { $title = Categorie::$MAP_TYPE_TITLE_AREA[$type]; $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").' >> '; $ways = $object->print_all_ways(" >> ", '', 1); - foreach ($ways as $way) - { + foreach ($ways as $way) { $morehtmlref .= $way."
    \n"; } $morehtmlref .= '
    '; @@ -130,8 +124,7 @@ if ($object->id) /* * Confirmation de la suppression de photo */ - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&file='.$_GET["file"], $langs->trans('DeletePicture'), $langs->trans('ConfirmDeletePicture'), 'confirm_delete', '', 0, 1); } @@ -160,18 +153,13 @@ if ($object->id) - /* ************************************************************************** */ - /* */ - /* Barre d'action */ - /* */ - /* ************************************************************************** */ - + /* + * Action bar + */ print '
    '."\n"; - if ($action != 'ajout_photo' && $user->rights->categorie->creer) - { - if (!empty($conf->global->MAIN_UPLOAD_DOC)) - { + if ($action != 'ajout_photo' && $user->rights->categorie->creer) { + if (!empty($conf->global->MAIN_UPLOAD_DOC)) { print ''; print $langs->trans("AddPhoto").''; } else { @@ -185,16 +173,14 @@ if ($object->id) /* * Ajouter une photo */ - if ($action == 'ajout_photo' && $user->rights->categorie->creer && !empty($conf->global->MAIN_UPLOAD_DOC)) - { + if ($action == 'ajout_photo' && $user->rights->categorie->creer && !empty($conf->global->MAIN_UPLOAD_DOC)) { // Affiche formulaire upload $formfile = new FormFile($db); $formfile->form_attach_new_file($_SERVER['PHP_SELF'].'?id='.$object->id.'&type='.$type, $langs->trans("AddPhoto"), 1, '', $user->rights->categorie->creer, 50, $object, '', false, '', 0); } // Affiche photos - if ($action != 'ajout_photo') - { + if ($action != 'ajout_photo') { $nbphoto = 0; $nbbyrow = 5; @@ -206,23 +192,24 @@ if ($object->id) $listofphoto = $object->liste_photos($dir); - if (is_array($listofphoto) && count($listofphoto)) - { + if (is_array($listofphoto) && count($listofphoto)) { print '
    '; print '
    '.$langs->trans("Categories").''; -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print ''; } print '
    '; tree_recur($data, $data[0], 0); print '
    '; - foreach ($listofphoto as $key => $obj) - { + foreach ($listofphoto as $key => $obj) { $nbphoto++; - if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) print ''; - if ($nbbyrow) print ''; + } + if ($nbbyrow) { + print ''; - if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) print ''; + if ($nbbyrow) { + print ''; + } + if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) { + print ''; + } } // Ferme tableau - while ($nbphoto % $nbbyrow) - { + while ($nbphoto % $nbbyrow) { print ''; $nbphoto++; } @@ -266,8 +254,7 @@ if ($object->id) print '
    '; + if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) { + print '
    '; + } print ''; // Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine - if ($obj['photo_vignette']) - { + if ($obj['photo_vignette']) { $filename = $obj['photo_vignette']; } else { $filename = $obj['photo']; @@ -243,22 +230,23 @@ if ($object->id) print '
    '; // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites - if (!$obj['photo_vignette'] && preg_match('/(\.bmp|\.gif|\.jpg|\.jpeg|\.png)$/i', $obj['photo']) && ($object->imgWidth > $maxWidth || $object->imgHeight > $maxHeight)) - { + if (!$obj['photo_vignette'] && preg_match('/(\.bmp|\.gif|\.jpg|\.jpeg|\.png)$/i', $obj['photo']) && ($object->imgWidth > $maxWidth || $object->imgHeight > $maxHeight)) { print '
    '.img_picto($langs->trans('GenerateThumb'), 'refresh').'  '; } - if ($user->rights->categorie->creer) - { + if ($user->rights->categorie->creer) { print ''; print img_delete().''; } - if ($nbbyrow) print '
     
    '; } - if ($nbphoto < 1) - { + if ($nbphoto < 1) { print '
    '.$langs->trans("NoPhotoYet")."
    "; } } diff --git a/htdocs/categories/traduction.php b/htdocs/categories/traduction.php index 898484d0d51..cd5d7ad8214 100644 --- a/htdocs/categories/traduction.php +++ b/htdocs/categories/traduction.php @@ -35,13 +35,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; // Load translation files required by the page $langs->loadLangs(array('categories', 'languages')); -$id = GETPOST('id', 'int'); -$label = GETPOST('label', 'alpha'); +$id = GETPOST('id', 'int'); +$label = GETPOST('label', 'alpha'); $action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'alpha'); -if ($id == '' && $label == '') -{ +if ($id == '' && $label == '') { dol_print_error('', 'Missing parameter id'); exit(); } @@ -56,7 +55,9 @@ if ($result <= 0) { } $type = $object->type; -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} /* * Actions @@ -64,8 +65,7 @@ if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backwar $error = 0; // retour a l'affichage des traduction si annulation -if ($cancel == $langs->trans("Cancel")) -{ +if ($cancel == $langs->trans("Cancel")) { $action = ''; } @@ -73,8 +73,7 @@ if ($cancel == $langs->trans("Cancel")) // Validation de l'ajout if ($action == 'vadd' && $cancel != $langs->trans("Cancel") && -($user->rights->categorie->creer)) -{ +($user->rights->categorie->creer)) { $object->fetch($id); $current_lang = $langs->getDefaultLang(); @@ -106,7 +105,9 @@ $cancel != $langs->trans("Cancel") && // sauvegarde en base $res = $object->setMultiLangs($user); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } } @@ -121,13 +122,11 @@ $cancel != $langs->trans("Cancel") && // Validation de l'edition if ($action == 'vedit' && $cancel != $langs->trans("Cancel") && -($user->rights->categorie->creer)) -{ +($user->rights->categorie->creer)) { $object->fetch($id); $current_lang = $langs->getDefaultLang(); - foreach ($object->multilangs as $key => $value) // enregistrement des nouvelles valeurs dans l'objet - { + foreach ($object->multilangs as $key => $value) { // enregistrement des nouvelles valeurs dans l'objet $libelle = GETPOST('libelle-'.$key, 'alpha'); $desc = GETPOST('desc-'.$key); @@ -147,7 +146,9 @@ $cancel != $langs->trans("Cancel") && if (!$error) { $res = $object->setMultiLangs($user); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } if ($error) { @@ -175,17 +176,16 @@ $head = categories_prepare_head($object, $type); // Calculate $cnt_trans $cnt_trans = 0; -if (!empty($object->multilangs)) -{ - foreach ($object->multilangs as $key => $value) - { +if (!empty($object->multilangs)) { + foreach ($object->multilangs as $key => $value) { $cnt_trans++; } } 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").' >> '; @@ -224,20 +224,17 @@ print dol_get_fiche_end(); -/* ************************************************************************** */ -/* */ -/* Barre d'action */ -/* */ -/* ************************************************************************** */ - +/* + * Action bar + */ print "\n
    \n"; -if ($action == '') -{ - if ($user->rights->produit->creer || $user->rights->service->creer) - { +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').''; + } } } @@ -245,8 +242,7 @@ print "\n
    \n"; -if ($action == 'edit') -{ +if ($action == 'edit') { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -256,10 +252,8 @@ if ($action == 'edit') print ''; print ''; - if (!empty($object->multilangs)) - { - foreach ($object->multilangs as $key => $value) - { + if (!empty($object->multilangs)) { + foreach ($object->multilangs as $key => $value) { print "
    ".$langs->trans('Language_'.$key)." :
    "; print ''; @@ -287,27 +281,27 @@ if ($action == 'edit') print ''; print ''; -} elseif ($action != 'add') -{ - if ($cnt_trans) print '
    '; +} elseif ($action != 'add') { + if ($cnt_trans) { + print '
    '; + } - if (!empty($object->multilangs)) - { - foreach ($object->multilangs as $key => $value) - { + if (!empty($object->multilangs)) { + foreach ($object->multilangs as $key => $value) { $s = picto_from_langcode($key); print '
    '; print ''; print ''; print ''; - if (!empty($conf->global->CATEGORY_USE_OTHER_FIELD_IN_TRANSLATION)) - { + if (!empty($conf->global->CATEGORY_USE_OTHER_FIELD_IN_TRANSLATION)) { print ''; } print '
    '.($s ? $s.' ' : '')." ".$langs->trans('Language_'.$key).": ".''.img_delete('', '').'
    '.$langs->trans('Label').''.$object->multilangs[$key]["label"].'
    '.$langs->trans('Description').''.$object->multilangs[$key]["description"].'
    '.$langs->trans('Other').' ('.$langs->trans("NotUsed").')'.$object->multilangs[$key]["other"].'
    '; } } - if (!$cnt_trans && $action != 'add') print '
    '.$langs->trans('NoTranslation').'
    '; + if (!$cnt_trans && $action != 'add') { + print '
    '.$langs->trans('NoTranslation').'
    '; + } } @@ -315,8 +309,7 @@ if ($action == 'edit') * Form to add a new translation */ -if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service->creer)) -{ +if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service->creer)) { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; diff --git a/htdocs/categories/viewcat.php b/htdocs/categories/viewcat.php index 187691293e4..dedb368202d 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -49,7 +49,7 @@ $cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button $toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'categorylist'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page -$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') // Load variable for pagination @@ -57,13 +57,14 @@ $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 ($id == "" && $label == "") -{ +if ($id == "" && $label == "") { dol_print_error('', 'Missing parameter id'); exit(); } @@ -78,7 +79,9 @@ if ($result <= 0) { } $type = $object->type; -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); @@ -90,8 +93,7 @@ $hookmanager->initHooks(array('categorycard', 'globalcard')); * Actions */ -if ($confirm == 'no') -{ +if ($confirm == 'no') { if ($backtopage) { header("Location: ".$backtopage); exit; @@ -101,26 +103,21 @@ if ($confirm == 'no') $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks // Remove element from category -if ($id > 0 && $removeelem > 0) -{ - if ($type == Categorie::TYPE_PRODUCT && ($user->rights->produit->creer || $user->rights->service->creer)) - { +if ($id > 0 && $removeelem > 0) { + if ($type == Categorie::TYPE_PRODUCT && ($user->rights->produit->creer || $user->rights->service->creer)) { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $tmpobject = new Product($db); $result = $tmpobject->fetch($removeelem); $elementtype = 'product'; - } elseif ($type == Categorie::TYPE_SUPPLIER && $user->rights->societe->creer) - { + } elseif ($type == Categorie::TYPE_SUPPLIER && $user->rights->societe->creer) { $tmpobject = new Societe($db); $result = $tmpobject->fetch($removeelem); $elementtype = 'supplier'; - } elseif ($type == Categorie::TYPE_CUSTOMER && $user->rights->societe->creer) - { + } elseif ($type == Categorie::TYPE_CUSTOMER && $user->rights->societe->creer) { $tmpobject = new Societe($db); $result = $tmpobject->fetch($removeelem); $elementtype = 'customer'; - } elseif ($type == Categorie::TYPE_MEMBER && $user->rights->adherent->creer) - { + } elseif ($type == Categorie::TYPE_MEMBER && $user->rights->adherent->creer) { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; $tmpobject = new Adherent($db); $result = $tmpobject->fetch($removeelem); @@ -130,20 +127,17 @@ if ($id > 0 && $removeelem > 0) $tmpobject = new Contact($db); $result = $tmpobject->fetch($removeelem); $elementtype = 'contact'; - } elseif ($type == Categorie::TYPE_ACCOUNT && $user->rights->banque->configurer) - { + } elseif ($type == Categorie::TYPE_ACCOUNT && $user->rights->banque->configurer) { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $tmpobject = new Account($db); $result = $tmpobject->fetch($removeelem); $elementtype = 'account'; - } elseif ($type == Categorie::TYPE_PROJECT && $user->rights->projet->creer) - { + } elseif ($type == Categorie::TYPE_PROJECT && $user->rights->projet->creer) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $tmpobject = new Project($db); $result = $tmpobject->fetch($removeelem); $elementtype = 'project'; - } elseif ($type == Categorie::TYPE_USER && $user->rights->user->user->creer) - { + } elseif ($type == Categorie::TYPE_USER && $user->rights->user->user->creer) { require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; $tmpobject = new User($db); $result = $tmpobject->fetch($removeelem); @@ -151,13 +145,13 @@ if ($id > 0 && $removeelem > 0) } $result = $object->del_type($tmpobject, $elementtype); - if ($result < 0) dol_print_error('', $object->error); + if ($result < 0) { + dol_print_error('', $object->error); + } } -if ($user->rights->categorie->supprimer && $action == 'confirm_delete' && $confirm == 'yes') -{ - if ($object->delete($user) >= 0) - { +if ($user->rights->categorie->supprimer && $action == 'confirm_delete' && $confirm == 'yes') { + if ($object->delete($user) >= 0) { if ($backtopage) { header("Location: ".$backtopage); exit; @@ -174,20 +168,16 @@ if ($elemid && $action == 'addintocategory' && (($type == Categorie::TYPE_PRODUCT && ($user->rights->produit->creer || $user->rights->service->creer)) || ($type == Categorie::TYPE_CUSTOMER && $user->rights->societe->creer) || ($type == Categorie::TYPE_SUPPLIER && $user->rights->societe->creer) - )) -{ - if ($type == Categorie::TYPE_PRODUCT) - { + )) { + if ($type == Categorie::TYPE_PRODUCT) { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $newobject = new Product($db); $elementtype = 'product'; - } elseif ($type == Categorie::TYPE_CUSTOMER) - { + } elseif ($type == Categorie::TYPE_CUSTOMER) { require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $newobject = new Societe($db); $elementtype = 'customer'; - } elseif ($type == Categorie::TYPE_SUPPLIER) - { + } elseif ($type == Categorie::TYPE_SUPPLIER) { require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $newobject = new Societe($db); $elementtype = 'supplier'; @@ -196,12 +186,10 @@ if ($elemid && $action == 'addintocategory' && // TODO Add into categ $result = $object->add_type($newobject, $elementtype); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans("WasAddedSuccessfully", $newobject->ref), null, 'mesgs'); } else { - if ($cat->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($cat->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { setEventMessages($langs->trans("ObjectAlreadyLinkedToCategory"), null, 'warnings'); } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -227,27 +215,25 @@ $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) -{ +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); /* * Confirmation suppression */ -if ($action == 'delete') -{ +if ($action == 'delete') { if ($backtopage) { print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&backtopage='.urlencode($backtopage), $langs->trans('DeleteCategory'), $langs->trans('ConfirmDeleteCategory'), 'confirm_delete', '', '', 2); } else { @@ -288,16 +274,16 @@ print dol_get_fiche_end(); print "
    \n"; $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $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 ($user->rights->categorie->creer) - { + if ($user->rights->categorie->creer) { $socid = ($object->socid ? "&socid=".$object->socid : ""); print ''.$langs->trans("Modify").''; } - if ($user->rights->categorie->supprimer) - { + if ($user->rights->categorie->supprimer) { print 'id.'&type='.$type.'&backtolist='.urlencode($backtolist).'">'.$langs->trans("Delete").''; } } @@ -305,8 +291,7 @@ if (empty($reshook)) { print "
    "; $newcardbutton = ''; -if (!empty($user->rights->categorie->creer)) -{ +if (!empty($user->rights->categorie->creer)) { $link = DOL_URL_ROOT.'/categories/card.php'; $link .= '?action=create'; $link .= '&type='.$type; @@ -335,8 +320,7 @@ print '
    '.$langs->trans("SubCats").''; -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print '
    '; print ''.img_picto('', 'folder').' '.$langs->trans("UndoExpandAll").''; print " | "; @@ -348,11 +332,9 @@ print '
    '.$langs->trans("NoSubCat").'
    '; @@ -465,19 +451,16 @@ $typeid = $type; // List of products or services (type is type of category) -if ($type == Categorie::TYPE_PRODUCT) -{ +if ($type == Categorie::TYPE_PRODUCT) { $permission = ($user->rights->produit->creer || $user->rights->service->creer); $prods = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($prods < 0) - { + if ($prods < 0) { dol_print_error($db, $object->error, $object->errors); } else { // Form to add record into a category $showclassifyform = 1; - if ($showclassifyform) - { + if ($showclassifyform) { print '
    '; print '
    '; print ''; @@ -510,13 +493,13 @@ if ($type == Categorie::TYPE_PRODUCT) print ''."\n"; print ''."\n"; - if (count($prods) > 0) - { + if (count($prods) > 0) { $i = 0; - foreach ($prods as $prod) - { + foreach ($prods as $prod) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; @@ -1391,45 +1383,48 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $object->load_ref_elements(); - if (!empty($conf->propal->enabled)) - { + if (!empty($conf->propal->enabled)) { print ''; } - if (!empty($conf->commande->enabled) || !empty($conf->expedition->enabled)) - { + if (!empty($conf->commande->enabled) || !empty($conf->expedition->enabled)) { print ''; } - if (!empty($conf->contrat->enabled)) - { + if (!empty($conf->contrat->enabled)) { print ''; } - if (!empty($conf->facture->enabled)) - { + if (!empty($conf->facture->enabled)) { print ''; } print ''; print ''; -if ($object->thirdparty->client) -{ +if ($object->thirdparty->client) { $thirdTypeArray['customer'] = $langs->trans("customer"); - if ($conf->propal->enabled && $user->rights->propal->lire) $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals'); - if ($conf->commande->enabled && $user->rights->commande->lire) $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders'); - if ($conf->facture->enabled && $user->rights->facture->lire) $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices'); - if ($conf->contrat->enabled && $user->rights->contrat->lire) $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts'); + if ($conf->propal->enabled && $user->rights->propal->lire) { + $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals'); + } + if ($conf->commande->enabled && $user->rights->commande->lire) { + $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders'); + } + if ($conf->facture->enabled && $user->rights->facture->lire) { + $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices'); + } + if ($conf->contrat->enabled && $user->rights->contrat->lire) { + $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts'); + } } -if ($conf->ficheinter->enabled && $user->rights->ficheinter->lire) $elementTypeArray['fichinter'] = $langs->transnoentitiesnoconv('Interventions'); +if ($conf->ficheinter->enabled && $user->rights->ficheinter->lire) { + $elementTypeArray['fichinter'] = $langs->transnoentitiesnoconv('Interventions'); +} -if ($object->thirdparty->fournisseur) -{ +if ($object->thirdparty->fournisseur) { $thirdTypeArray['supplier'] = $langs->trans("supplier"); - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) $elementTypeArray['supplier_invoice'] = $langs->transnoentitiesnoconv('SuppliersInvoices'); - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && $user->rights->fournisseur->commande->lire) $elementTypeArray['supplier_order'] = $langs->transnoentitiesnoconv('SuppliersOrders'); + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) { + $elementTypeArray['supplier_invoice'] = $langs->transnoentitiesnoconv('SuppliersInvoices'); + } + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && $user->rights->fournisseur->commande->lire) { + $elementTypeArray['supplier_order'] = $langs->transnoentitiesnoconv('SuppliersOrders'); + } // There no contact type for supplier proposals // if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $user->rights->supplier_proposal->lire) $elementTypeArray['supplier_proposal']=$langs->transnoentitiesnoconv('SupplierProposals'); @@ -166,8 +190,7 @@ print ''; print ''; $sql_select = ''; -if ($type_element == 'fichinter') -{ // Customer : show products from invoices +if ($type_element == 'fichinter') { // Customer : show products from invoices require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; $documentstatic = new Fichinter($db); $sql_select = 'SELECT f.rowid as doc_id, f.ref as doc_number, \'1\' as doc_type, f.datec as dateprint, f.fk_statut as status, tc.libelle as type_contact_label, '; @@ -178,8 +201,7 @@ if ($type_element == 'fichinter') $where = ' WHERE f.entity IN ('.getEntity('ficheinter').')'; $dateprint = 'f.datec'; $doc_number = 'f.ref'; -} elseif ($type_element == 'invoice') -{ // Customer : show products from invoices +} elseif ($type_element == 'invoice') { // Customer : show products from invoices require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $documentstatic = new Facture($db); $sql_select = 'SELECT f.rowid as doc_id, f.ref as doc_number, f.type as doc_type, f.datef as dateprint, f.fk_statut as status, f.paye as paid, tc.libelle as type_contact_label, '; @@ -192,8 +214,7 @@ if ($type_element == 'fichinter') $dateprint = 'f.datef'; $doc_number = 'f.ref'; $thirdTypeSelect = 'customer'; -} elseif ($type_element == 'propal') -{ +} elseif ($type_element == 'propal') { require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $documentstatic = new Propal($db); $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.datep as dateprint, c.fk_statut as status, tc.libelle as type_contact_label, '; @@ -206,8 +227,7 @@ if ($type_element == 'fichinter') $datePrint = 'c.datep'; $doc_number = 'c.ref'; $thirdTypeSelect = 'customer'; -} elseif ($type_element == 'order') -{ +} elseif ($type_element == 'order') { require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $documentstatic = new Commande($db); $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.date_commande as dateprint, c.fk_statut as status, tc.libelle as type_contact_label, '; @@ -220,8 +240,7 @@ if ($type_element == 'fichinter') $dateprint = 'c.date_commande'; $doc_number = 'c.ref'; $thirdTypeSelect = 'customer'; -} elseif ($type_element == 'supplier_invoice') -{ // Supplier : Show products from invoices. +} elseif ($type_element == 'supplier_invoice') { // Supplier : Show products from invoices. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; $documentstatic = new FactureFournisseur($db); $sql_select = 'SELECT f.rowid as doc_id, f.ref as doc_number, \'1\' as doc_type, f.datef as dateprint, f.fk_statut as status, f.paye as paid, tc.libelle as type_contact_label, '; @@ -234,22 +253,19 @@ if ($type_element == 'fichinter') $dateprint = 'f.datef'; $doc_number = 'f.ref'; $thirdTypeSelect = 'supplier'; -} -//elseif ($type_element == 'supplier_proposal') -//{ -// require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; -// $documentstatic=new SupplierProposal($db); -// $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.date_valid as dateprint, c.fk_statut as status, '; -// $tables_from = MAIN_DB_PREFIX."supplier_proposal as c,".MAIN_DB_PREFIX."supplier_proposaldet as d"; -// $where = " WHERE c.fk_soc = s.rowid AND s.rowid = ".$socid; -// $where.= " AND d.fk_supplier_proposal = c.rowid"; -// $where.= " AND c.entity = ".$conf->entity; -// $dateprint = 'c.date_valid'; -// $doc_number='c.ref'; -// $thirdTypeSelect='supplier'; -//} -elseif ($type_element == 'supplier_order') -{ // Supplier : Show products from orders. + //} elseif ($type_element == 'supplier_proposal') { + // require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; + // $documentstatic=new SupplierProposal($db); + // $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.date_valid as dateprint, c.fk_statut as status, '; + // $tables_from = MAIN_DB_PREFIX."supplier_proposal as c,".MAIN_DB_PREFIX."supplier_proposaldet as d"; + // $where = " WHERE c.fk_soc = s.rowid AND s.rowid = ".$socid; + // $where.= " AND d.fk_supplier_proposal = c.rowid"; + // $where.= " AND c.entity = ".$conf->entity; + // $dateprint = 'c.date_valid'; + // $doc_number='c.ref'; + // $thirdTypeSelect='supplier'; + //} +} elseif ($type_element == 'supplier_order') { // Supplier : Show products from orders. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; $documentstatic = new CommandeFournisseur($db); $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.date_valid as dateprint, c.fk_statut as status, tc.libelle as type_contact_label, '; @@ -262,8 +278,7 @@ elseif ($type_element == 'supplier_order') $dateprint = 'c.date_valid'; $doc_number = 'c.ref'; $thirdTypeSelect = 'supplier'; -} elseif ($type_element == 'contract') -{ // Order +} elseif ($type_element == 'contract') { // Order require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; $documentstatic = new Contrat($db); $documentstaticline = new ContratLigne($db); @@ -282,26 +297,40 @@ elseif ($type_element == 'supplier_order') $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook -if (!empty($sql_select)) -{ +if (!empty($sql_select)) { $sql = $sql_select; $sql .= ' d.description as description'; - if ($type_element != 'fichinter' && $type_element != 'contract' && $type_element != 'supplier_proposal') $sql .= ', d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_start, d.date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; - if ($type_element == 'supplier_proposal') $sql .= ', d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; - if ($type_element == 'contract') $sql .= ', d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_ouverture as date_start, d.date_cloture as date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; - if ($type_element != 'fichinter') $sql .= ' p.ref as ref, p.rowid as prod_id, p.rowid as fk_product, p.fk_product_type as prod_type, p.fk_product_type as fk_product_type, p.entity as pentity'; + if ($type_element != 'fichinter' && $type_element != 'contract' && $type_element != 'supplier_proposal') { + $sql .= ', d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_start, d.date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; + } + if ($type_element == 'supplier_proposal') { + $sql .= ', d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; + } + if ($type_element == 'contract') { + $sql .= ', d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_ouverture as date_start, d.date_cloture as date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; + } + if ($type_element != 'fichinter') { + $sql .= ' p.ref as ref, p.rowid as prod_id, p.rowid as fk_product, p.fk_product_type as prod_type, p.fk_product_type as fk_product_type, p.entity as pentity'; + } $sql .= " "; - if ($type_element != 'fichinter') $sql .= ", p.ref as prod_ref, p.label as product_label"; + if ($type_element != 'fichinter') { + $sql .= ", p.ref as prod_ref, p.label as product_label"; + } $sql .= " FROM "/*.MAIN_DB_PREFIX."societe as s, "*/.$tables_from; // if ($type_element != 'fichinter') $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON d.fk_product = p.rowid '; $sql .= $where; $sql .= dolSqlDateFilter($dateprint, 0, $month, $year); - if ($sref) $sql .= " AND ".$doc_number." LIKE '%".$db->escape($sref)."%'"; - if ($sprod_fulldescr) - { + if ($sref) { + $sql .= " AND ".$doc_number." LIKE '%".$db->escape($sref)."%'"; + } + if ($sprod_fulldescr) { $sql .= " AND (d.description LIKE '%".$db->escape($sprod_fulldescr)."%'"; - if (GETPOST('type_element') != 'fichinter') $sql .= " OR p.ref LIKE '%".$db->escape($sprod_fulldescr)."%'"; - if (GETPOST('type_element') != 'fichinter') $sql .= " OR p.label LIKE '%".$db->escape($sprod_fulldescr)."%'"; + if (GETPOST('type_element') != 'fichinter') { + $sql .= " OR p.ref LIKE '%".$db->escape($sprod_fulldescr)."%'"; + } + if (GETPOST('type_element') != 'fichinter') { + $sql .= " OR p.label LIKE '%".$db->escape($sprod_fulldescr)."%'"; + } $sql .= ")"; } $sql .= $db->order($sortfield, $sortorder); @@ -332,21 +361,36 @@ $param .= "&type_element=".urlencode($type_element); $total_qty = 0; -if ($sql_select) -{ +if ($sql_select) { $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $num = $db->num_rows($resql); $param = "&socid=".urlencode($socid)."&type_element=".urlencode($type_element); - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($sprod_fulldescr) $param .= "&sprod_fulldescr=".urlencode($sprod_fulldescr); - if ($sref) $param .= "&sref=".urlencode($sref); - if ($month) $param .= "&month=".urlencode($month); - if ($year) $param .= "&year=".urlencode($year); - 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 ($sprod_fulldescr) { + $param .= "&sprod_fulldescr=".urlencode($sprod_fulldescr); + } + if ($sref) { + $param .= "&sref=".urlencode($sref); + } + if ($month) { + $param .= "&month=".urlencode($month); + } + if ($year) { + $param .= "&year=".urlencode($year); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } print_barre_liste($langs->trans('ProductsIntoElements').' '.$typeElementString.' '.$button, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, '', 0, '', '', $limit); @@ -393,8 +437,7 @@ if ($sql_select) $i = 0; - while (($objp = $db->fetch_object($resql)) && $i < min($num, $limit)) - { + while (($objp = $db->fetch_object($resql)) && $i < min($num, $limit)) { $documentstatic->id = $objp->doc_id; $documentstatic->ref = $objp->doc_number; $documentstatic->type = $objp->doc_type; @@ -405,7 +448,9 @@ if ($sql_select) $documentstatic->paye = $objp->paid; $documentstatic->paid = $objp->paid; - if (is_object($documentstaticline)) $documentstaticline->statut = $objp->status; + if (is_object($documentstaticline)) { + $documentstaticline->statut = $objp->status; + } print ''; print ''; - } + print ''; + } - else - { - print ''; - } - }*/ + else + { + print ''; + } + }*/ // Civility print ''; + if (!empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA)) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + print ''; + } // Attached files if (!empty($this->withfile)) { @@ -368,7 +382,9 @@ class FormTicket if (response.num) { var selecthtml_str = response.value; var selecthtml_dom=$.parseHTML(selecthtml_str); - $("#inputautocomplete"+htmlname).val(selecthtml_dom[0][0].innerHTML); + if (typeof(selecthtml_dom[0][0]) !== \'undefined\') { + $("#inputautocomplete"+htmlname).val(selecthtml_dom[0][0].innerHTML); + } } else { $("#inputautocomplete"+htmlname).val(""); } @@ -396,16 +412,14 @@ class FormTicket } // Notify thirdparty at creation - if (empty($this->ispublic)) - { + if (empty($this->ispublic)) { print ''; } } - if (!empty($conf->projet->enabled) && !$this->ispublic) - { + if (!empty($conf->projet->enabled) && !$this->ispublic) { $formproject = new FormProjets($this->db); print '
    '.$langs->trans("Ref").'
    '; @@ -525,8 +508,7 @@ if ($type == Categorie::TYPE_PRODUCT) print ''.$prod->label."'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -544,19 +526,16 @@ if ($type == Categorie::TYPE_PRODUCT) } } -if ($type == Categorie::TYPE_CUSTOMER) -{ +if ($type == Categorie::TYPE_CUSTOMER) { $permission = $user->rights->societe->creer; $socs = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($socs < 0) - { + if ($socs < 0) { dol_print_error($db, $object->error, $object->errors); } else { // Form to add record into a category $showclassifyform = 1; - if ($showclassifyform) - { + if ($showclassifyform) { print '
    '; print ''; print ''; @@ -588,13 +567,13 @@ if ($type == Categorie::TYPE_CUSTOMER) print ''."\n"; print ''."\n"; - if (count($socs) > 0) - { + if (count($socs) > 0) { $i = 0; - foreach ($socs as $key => $soc) - { + foreach ($socs as $key => $soc) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; // Email - if (!empty($conf->mailing->enabled)) - { + if (!empty($conf->mailing->enabled)) { $langs->load("mails"); print ''; print ''; } // Unsubscribe opt-out - if (!empty($conf->mailing->enabled)) - { + if (!empty($conf->mailing->enabled)) { $result=$object->getNoEmail(); if ($result<0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -1324,8 +1311,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $object->fetch_thirdparty(); if (!empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { - if ($object->thirdparty->client == 2 || $object->thirdparty->client == 3) - { + if ($object->thirdparty->client == 2 || $object->thirdparty->client == 3) { print '
    '; print '
    '; @@ -1336,7 +1322,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '
    '.$langs->trans("Name").'
    '; @@ -602,8 +581,7 @@ if ($type == Categorie::TYPE_CUSTOMER) print "'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -622,19 +600,16 @@ if ($type == Categorie::TYPE_CUSTOMER) } -if ($type == Categorie::TYPE_SUPPLIER) -{ +if ($type == Categorie::TYPE_SUPPLIER) { $permission = $user->rights->societe->creer; $socs = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($socs < 0) - { + if ($socs < 0) { dol_print_error($db, $object->error, $object->errors); } else { // Form to add record into a category $showclassifyform = 1; - if ($showclassifyform) - { + if ($showclassifyform) { print '
    '; print ''; print ''; @@ -666,13 +641,13 @@ if ($type == Categorie::TYPE_SUPPLIER) print ''."\n"; print '\n"; - if (count($socs) > 0) - { + if (count($socs) > 0) { $i = 0; - foreach ($socs as $soc) - { + foreach ($socs as $soc) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; @@ -238,15 +276,14 @@ if (!is_array($x_coll) || !is_array($x_paye)) } else { $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) - { + 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) { + 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]; @@ -284,11 +321,9 @@ if (!is_array($x_coll) || !is_array($x_paye)) $x_both[$my_paye_rate]['paye']['links'] = ''; $x_both[$my_paye_rate]['paye']['detail'] = array(); - foreach ($x_paye[$my_paye_rate]['facid'] as $id=>$dummy) - { + foreach ($x_paye[$my_paye_rate]['facid'] as $id => $dummy) { // ExpenseReport - if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') - { + 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]; @@ -349,7 +384,9 @@ if (!is_array($x_coll) || !is_array($x_paye)) $x_paye_ht = 0; $span = $columns; - if ($modetax != 1) $span += 2; + if ($modetax != 1) { + $span += 2; + } //print ''; @@ -357,12 +394,14 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print ''; print ''; - if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''; - else print ''; + if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') { + print ''; + } else { + print ''; + } print ''; print ''; - if ($modetax != 1) - { + if ($modetax != 1) { print ''; print ''; } @@ -385,11 +424,13 @@ if (!is_array($x_coll) || !is_array($x_paye)) $subtot_coll_total_ht = 0; $subtot_coll_vat = 0; - if (is_array($x_both[$rate]['coll']['detail'])) - { + if (is_array($x_both[$rate]['coll']['detail'])) { // VAT Rate print ""; - print ''; + print ''; print ''."\n"; foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) { @@ -405,115 +446,149 @@ if (!is_array($x_coll) || !is_array($x_paye)) $type = 1; } - - print ''; - - // Ref - print ''; - - // Invoice date - print ''; - - // Payment date - if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''; - else print ''; - - // Company name - print ''; - - // Description - print ''; - - // Total HT - if ($modetax != 1) - { - print ''; - } - // Payment - $ratiopaymentinvoice = 1; - if ($modetax != 1) - { - print ''; } // Total collected - print ''; + $temp_ht=$fields['totalht']*$ratiopaymentinvoice; // 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 ''; + + // Invoice date + print ''; + + // Payment date + if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''; + else print ''; + + // Company name + print ''; + + // Description + print ''; + + // Total HT + if ($modetax != 1) { + print ''; + } + + // Payment + $ratiopaymentinvoice = 1; + if ($modetax != 1) { + print ''; + } + + // Total collected + print ''; + + // 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 ''; @@ -527,8 +602,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; } - if (count($x_coll) == 0) // Show a total line if nothing shown - { + if (count($x_coll) == 0) { // Show a total line if nothing shown print ''; print ''; print ''; @@ -542,7 +616,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) } // Blank line - print ''; + print ''; // Print table headers for this quadri - expenses now print ''; @@ -560,18 +634,19 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print ''."\n"; - foreach (array_keys($x_paye) as $rate) - { + foreach (array_keys($x_paye) as $rate) { $subtot_paye_total_ht = 0; $subtot_paye_vat = 0; - if (is_array($x_both[$rate]['paye']['detail'])) - { + if (is_array($x_both[$rate]['paye']['detail'])) { print ""; - print ''; + print ''; print ''."\n"; - foreach ($x_both[$rate]['paye']['detail'] as $index=>$fields) { + 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']); @@ -584,115 +659,151 @@ if (!is_array($x_coll) || !is_array($x_paye)) $type = 1; } - - print ''; - - // Ref - print ''; - - // Invoice date - print ''; - - // Payment date - if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') print ''; - else print ''; - - // Company name - print ''; - - // Description - print ''; - - // Total HT - if ($modetax != 1) - { - print ''; - } - // Payment $ratiopaymentinvoice = 1; - if ($modetax != 1) - { - print ''; } // VAT paid - print ''; // 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 ''; + + // Invoice date + print ''; + + // Payment date + if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') { + print ''; + } else { + print ''; + } + + // Company name + print ''; + + // Description + print ''; + + // Total HT + if ($modetax != 1) { + print ''; + } + + // Payment + $ratiopaymentinvoice = 1; + if ($modetax != 1) { + print ''; + } + + // VAT paid + print ''; + + // 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/agenda.php b/htdocs/contact/agenda.php index 2aeb2e4e2a1..ca496540a47 100644 --- a/htdocs/contact/agenda.php +++ b/htdocs/contact/agenda.php @@ -65,36 +65,44 @@ $extrafields->fetch_name_optionals_label($object->table_element); $object->getCanvas($id); $objcanvas = null; $canvas = (!empty($object->canvas) ? $object->canvas : GETPOST("canvas")); -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('contact', 'contactcard', $canvas); } -if (GETPOST('actioncode', 'array')) -{ +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)); } $search_agenda_label = GETPOST('search_agenda_label'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', 0); // If we create a contact with no company (shared contacts), no check on write permission $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'; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('contactagenda', 'globalcard')); @@ -106,20 +114,19 @@ $hookmanager->initHooks(array('contactagenda', 'globalcard')); $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)) -{ +if (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // Purge search criteria - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers $actioncode = ''; $search_agenda_label = ''; } @@ -133,29 +140,30 @@ if (empty($reshook)) $form = new Form($db); $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title = $object->lastname; +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) { + $title = $object->lastname; +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($socid > 0) -{ +if ($socid > 0) { $objsoc = new Societe($db); $objsoc->fetch($socid); } -if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) -{ +if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { // ----------------------------------------- // When used with CANVAS // ----------------------------------------- - if (empty($object->error) && $id) - { - $object = new Contact($db); - $result = $object->fetch($id); - if ($result <= 0) dol_print_error('', $object->error); - } - $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates + if (empty($object->error) && $id) { + $object = new Contact($db); + $result = $object->fetch($id); + if ($result <= 0) { + dol_print_error('', $object->error); + } + } + $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates $objcanvas->display_canvas($action); // Show template } else { // ----------------------------------------- @@ -163,26 +171,27 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // ----------------------------------------- // Confirm deleting contact - if ($user->rights->societe->contact->supprimer) - { - if ($action == 'delete') - { + if ($user->rights->societe->contact->supprimer) { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id.($backtopage ? '&backtopage='.$backtopage : ''), $langs->trans("DeleteContact"), $langs->trans("ConfirmDeleteContact"), "confirm_delete", '', 0, 1); } } /* - * Onglets - */ + * Onglets + */ $head = array(); - if ($id > 0) - { + if ($id > 0) { // Si edition contact deja existant $object = new Contact($db); $res = $object->fetch($id, $user); - if ($res < 0) { dol_print_error($db, $object->error); exit; } + if ($res < 0) { + dol_print_error($db, $object->error); exit; + } $res = $object->fetch_optionals(); - if ($res < 0) { dol_print_error($db, $object->error); exit; } + if ($res < 0) { + dol_print_error($db, $object->error); exit; + } // Show tabs $head = contact_prepare_head($object); @@ -190,13 +199,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); } - if (!empty($id) && $action != 'edit' && $action != 'create') - { + if (!empty($id) && $action != 'edit' && $action != 'create') { $objsoc = new Societe($db); /* - * Fiche en mode visualisation - */ + * Fiche en mode visualisation + */ dol_htmloutput_errors($error, $errors); @@ -205,14 +213,16 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
    '; - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $objsoc = new Societe($db); $objsoc->fetch($object->socid); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '; - if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1); - else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + if ($objsoc->id > 0) { + $morehtmlref .= $objsoc->getNomUrl(1); + } else { + $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + } } $morehtmlref .= '
    '; @@ -238,29 +248,31 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $out = ''; $permok = $user->rights->agenda->myactions->create; - if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) - { - if (is_object($objthirdparty) && get_class($objthirdparty) == 'Societe') $out .= '&originid='.$objthirdparty->id.($objthirdparty->id > 0 ? '&socid='.$objthirdparty->id : ''); + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { + if (is_object($objthirdparty) && get_class($objthirdparty) == 'Societe') { + $out .= '&originid='.$objthirdparty->id.($objthirdparty->id > 0 ? '&socid='.$objthirdparty->id : ''); + } $out .= (!empty($objcon->id) ? '&contactid='.$objcon->id : '').'&origin=contact&originid='.$object->id.'&percentage=-1&backtopage='.urlencode($_SERVER['PHP_SELF'].($objcon->id > 0 ? '?id='.$objcon->id : '')); $out .= '&datep='.urlencode(dol_print_date(dol_now(), 'dayhourlog')); } $newcardbutton = ''; - if (!empty($conf->agenda->enabled)) - { - if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) - { + if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { $newcardbutton .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out); } } - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { - print '
    '; + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { + 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 load_fiche_titre($langs->trans("ActionsOnContact"), $newcardbutton, ''); //print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $morehtmlcenter, 0, -1, '', '', '', '', 0, 1, 1); diff --git a/htdocs/contact/canvas/actions_contactcard_common.class.php b/htdocs/contact/canvas/actions_contactcard_common.class.php index f6f6fa0b45e..a32263cd65e 100644 --- a/htdocs/contact/canvas/actions_contactcard_common.class.php +++ b/htdocs/contact/canvas/actions_contactcard_common.class.php @@ -64,14 +64,16 @@ abstract class ActionsContactCardCommon { /*$ret = $this->getInstanceDao(); - if (is_object($this->object) && method_exists($this->object,'fetch')) - { - if (! empty($id)) $this->object->fetch($id); - } - else - {*/ + if (is_object($this->object) && method_exists($this->object,'fetch')) + { + if (! empty($id)) $this->object->fetch($id); + } + else + {*/ $object = new Contact($this->db); - if (!empty($id)) $object->fetch($id); + if (!empty($id)) { + $object->fetch($id); + } $this->object = $object; //} } @@ -90,20 +92,19 @@ abstract class ActionsContactCardCommon 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) - { + foreach ($this->object as $key => $value) { $this->tpl[$key] = $value; } $this->tpl['error'] = $this->error; $this->tpl['errors'] = $this->errors; - if ($action == 'create' || $action == 'edit') - { - if ($conf->use_javascript_ajax) - { + if ($action == 'create' || $action == 'edit') { + if ($conf->use_javascript_ajax) { $this->tpl['ajax_selectcountry'] = "\n".''."\n"; } - if (is_object($objsoc) && $objsoc->id > 0) - { + if (is_object($objsoc) && $objsoc->id > 0) { $this->tpl['company'] = $objsoc->getNomUrl(1); $this->tpl['company_id'] = $objsoc->id; } else { @@ -127,14 +127,25 @@ abstract class ActionsContactCardCommon $this->tpl['select_civility'] = $formcompany->select_civility($this->object->civility_id); // Predefined with third party - if ((isset($objsoc->typent_code) && $objsoc->typent_code == 'TE_PRIVATE') || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) - { - 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_pro)) == 0) $this->object->phone_pro = $objsoc->phone; - if (dol_strlen(trim($this->object->fax)) == 0) $this->object->fax = $objsoc->fax; - if (dol_strlen(trim($this->object->email)) == 0) $this->object->email = $objsoc->email; + if ((isset($objsoc->typent_code) && $objsoc->typent_code == 'TE_PRIVATE') || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) { + 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_pro)) == 0) { + $this->object->phone_pro = $objsoc->phone; + } + if (dol_strlen(trim($this->object->fax)) == 0) { + $this->object->fax = $objsoc->fax; + } + if (dol_strlen(trim($this->object->email)) == 0) { + $this->object->email = $objsoc->email; + } } // Zip @@ -143,28 +154,33 @@ abstract class ActionsContactCardCommon // 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; + } // Public or private $selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate")); $this->tpl['select_visibility'] = $form->selectarray('priv', $selectarray, $this->object->priv, 0); } - if ($action == 'view' || $action == 'edit' || $action == 'delete') - { + if ($action == 'view' || $action == 'edit' || $action == 'delete') { // Emailing - if (!empty($conf->mailing->enabled)) - { + if (!empty($conf->mailing->enabled)) { $langs->load("mails"); $this->tpl['nb_emailing'] = $this->object->getNbOfEMailings(); } @@ -175,46 +191,41 @@ abstract class ActionsContactCardCommon $this->object->load_ref_elements(); - if (!empty($conf->commande->enabled)) - { + if (!empty($conf->commande->enabled)) { $this->tpl['contact_element'][$i]['linked_element_label'] = $langs->trans("ContactForOrders"); $this->tpl['contact_element'][$i]['linked_element_value'] = $this->object->ref_commande ? $this->object->ref_commande : $langs->trans("NoContactForAnyOrder"); $i++; } - if (!empty($conf->propal->enabled)) - { + if (!empty($conf->propal->enabled)) { $this->tpl['contact_element'][$i]['linked_element_label'] = $langs->trans("ContactForProposals"); $this->tpl['contact_element'][$i]['linked_element_value'] = $this->object->ref_propal ? $this->object->ref_propal : $langs->trans("NoContactForAnyProposal"); $i++; } - if (!empty($conf->contrat->enabled)) - { + if (!empty($conf->contrat->enabled)) { $this->tpl['contact_element'][$i]['linked_element_label'] = $langs->trans("ContactForContracts"); $this->tpl['contact_element'][$i]['linked_element_value'] = $this->object->ref_contrat ? $this->object->ref_contrat : $langs->trans("NoContactForAnyContract"); $i++; } - if (!empty($conf->facture->enabled)) - { + if (!empty($conf->facture->enabled)) { $this->tpl['contact_element'][$i]['linked_element_label'] = $langs->trans("ContactForInvoices"); $this->tpl['contact_element'][$i]['linked_element_value'] = $this->object->ref_facturation ? $this->object->ref_facturation : $langs->trans("NoContactForAnyInvoice"); $i++; } // Dolibarr user - if ($this->object->user_id) - { + if ($this->object->user_id) { $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') - { + if ($action == 'view' || $action == 'delete') { $this->tpl['showrefnav'] = $form->showrefnav($this->object, 'id'); - if ($this->object->socid > 0) - { + if ($this->object->socid > 0) { $objsoc = new Societe($this->db); $objsoc->fetch($this->object->socid); @@ -243,14 +254,13 @@ abstract class ActionsContactCardCommon $this->tpl['note'] = nl2br($this->object->note); } - if ($action == 'create_user') - { + if ($action == 'create_user') { // Full firstname and lastname separated with a dot : firstname.lastname include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; 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 @@ -297,12 +307,10 @@ abstract class ActionsContactCardCommon $this->object->canvas = $_POST["canvas"]; // We set country_id, and country_code label of the chosen country - if ($this->object->country_id) - { + if ($this->object->country_id) { $sql = "SELECT code, label FROM ".MAIN_DB_PREFIX."c_country WHERE rowid = ".$this->object->country_id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); } else { dol_print_error($this->db); diff --git a/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php index 98a66e499b9..bd5cf24e195 100644 --- a/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php +++ b/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } diff --git a/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php index 2c82a868ed4..41fbdb5def9 100644 --- a/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php +++ b/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } diff --git a/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php index 43fd48e3ef0..c624eca4026 100644 --- a/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php +++ b/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -30,8 +29,12 @@ 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']; +} ?>
    '.$langs->trans("Name")."
    '; @@ -680,8 +655,7 @@ if ($type == Categorie::TYPE_SUPPLIER) print "'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -701,15 +675,13 @@ if ($type == Categorie::TYPE_SUPPLIER) } // List of members -if ($type == Categorie::TYPE_MEMBER) -{ +if ($type == Categorie::TYPE_MEMBER) { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; $permission = $user->rights->adherent->creer; $prods = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($prods < 0) - { + if ($prods < 0) { dol_print_error($db, $object->error, $object->errors); } else { print ''; @@ -726,13 +698,13 @@ if ($type == Categorie::TYPE_MEMBER) print "\n"; print ''."\n"; - if (count($prods) > 0) - { + if (count($prods) > 0) { $i = 0; - foreach ($prods as $key => $member) - { + foreach ($prods as $key => $member) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; // Bank account - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print ''; - 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; - } - } - 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 ''; -print "\n"; -print ''; - -print '
    '.$langs->trans("Name").'
    '; @@ -743,8 +715,7 @@ if ($type == Categorie::TYPE_MEMBER) print ''.$member->firstname."'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -762,13 +733,11 @@ if ($type == Categorie::TYPE_MEMBER) } // Categorie contact -if ($type == Categorie::TYPE_CONTACT) -{ +if ($type == Categorie::TYPE_CONTACT) { $permission = $user->rights->societe->creer; $contacts = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($contacts < 0) - { + if ($contacts < 0) { dol_print_error($db, $object->error, $object->errors); } else { print ''; @@ -788,13 +757,13 @@ if ($type == Categorie::TYPE_CONTACT) print ''."\n"; print ''."\n"; - if (count($contacts) > 0) - { + if (count($contacts) > 0) { $i = 0; - foreach ($contacts as $key => $contact) - { + foreach ($contacts as $key => $contact) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; print "\n"; - while ($i < min($num, $conf->liste_limit)) - { + while ($i < min($num, $conf->liste_limit)) { $obj = $db->fetch_object($resql); print ''; diff --git a/htdocs/compta/deplacement/card.php b/htdocs/compta/deplacement/card.php index f1e34e99985..3d4693f8c7b 100644 --- a/htdocs/compta/deplacement/card.php +++ b/htdocs/compta/deplacement/card.php @@ -29,8 +29,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/trip.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } @@ -40,7 +39,9 @@ $langs->load("trips"); // Security check $id = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'deplacement', $id, ''); $action = GETPOST('action', 'aZ09'); @@ -60,48 +61,38 @@ $permissionnote = $user->rights->deplacement->creer; // Used by the include of a include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once -if ($action == 'validate' && $user->rights->deplacement->creer) -{ +if ($action == 'validate' && $user->rights->deplacement->creer) { $object->fetch($id); - if ($object->statut == Deplacement::STATUS_DRAFT) - { + if ($object->statut == Deplacement::STATUS_DRAFT) { $result = $object->setStatut(1); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } } -} elseif ($action == 'classifyrefunded' && $user->rights->deplacement->creer) -{ +} elseif ($action == 'classifyrefunded' && $user->rights->deplacement->creer) { $object->fetch($id); - if ($object->statut == Deplacement::STATUS_VALIDATED) - { + if ($object->statut == Deplacement::STATUS_VALIDATED) { $result = $object->setStatut(Deplacement::STATUS_REFUNDED); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } } -} elseif ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->deplacement->supprimer) -{ +} elseif ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->deplacement->supprimer) { $result = $object->delete($id); - if ($result >= 0) - { + if ($result >= 0) { header("Location: index.php"); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } -} elseif ($action == 'add' && $user->rights->deplacement->creer) -{ - if (!GETPOST('cancel', 'alpha')) - { +} elseif ($action == 'add' && $user->rights->deplacement->creer) { + if (!GETPOST('cancel', 'alpha')) { $error = 0; $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); @@ -113,28 +104,23 @@ if ($action == 'validate' && $user->rights->deplacement->creer) $object->note_public = GETPOST('note_public', 'alpha'); $object->statut = Deplacement::STATUS_DRAFT; - if (!$object->date) - { + if (!$object->date) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); $error++; } - if ($object->type == '-1') - { + if ($object->type == '-1') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); $error++; } - if (!($object->fk_user > 0)) - { + if (!($object->fk_user > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Person")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $id = $object->create($user); - if ($id > 0) - { + if ($id > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { @@ -148,11 +134,9 @@ if ($action == 'validate' && $user->rights->deplacement->creer) header("Location: index.php"); exit; } -} // Update record -elseif ($action == 'update' && $user->rights->deplacement->creer) -{ - if (!GETPOST('cancel', 'alpha')) - { +} elseif ($action == 'update' && $user->rights->deplacement->creer) { + // Update record + if (!GETPOST('cancel', 'alpha')) { $result = $object->fetch($id); $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); @@ -165,8 +149,7 @@ elseif ($action == 'update' && $user->rights->deplacement->creer) $result = $object->update($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { @@ -176,24 +159,27 @@ 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) -{ + if ($result < 0) { + dol_print_error($db, $object->error); + } +} 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'); - if ($result < 0) dol_print_error($db, $object->error); -} elseif ($action == 'setkm' && $user->rights->deplacement->creer) -{ + if ($result < 0) { + dol_print_error($db, $object->error); + } +} elseif ($action == 'setkm' && $user->rights->deplacement->creer) { $object->fetch($id); $result = $object->setValueFrom('km', GETPOST('km', 'int'), '', null, 'text', '', $user, 'DEPLACEMENT_MODIFY'); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + dol_print_error($db, $object->error); + } } @@ -208,8 +194,7 @@ $form = new Form($db); /* * Action create */ -if ($action == 'create') -{ +if ($action == 'create') { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -258,8 +243,7 @@ if ($action == 'create') print ''; // Private note - if (empty($user->socid)) - { + if (empty($user->socid)) { print ''; print ''; print '"; // Private note - if (empty($user->socid)) - { + if (empty($user->socid)) { print ''; print ''; print ''; @@ -159,12 +175,13 @@ if ($resql) print ''; print "\n"; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $soc = new Societe($db); - if ($obj->socid) $soc->fetch($obj->socid); + if ($obj->socid) { + $soc->fetch($obj->socid); + } print ''; // Id @@ -181,8 +198,11 @@ if ($resql) print $userstatic->getNomUrl(1); print ''; - if ($obj->socid) print ''; - else print ''; + if ($obj->socid) { + print ''; + } else { + print ''; + } print ''; diff --git a/htdocs/compta/deplacement/stats/index.php b/htdocs/compta/deplacement/stats/index.php index 389c8d9408f..892b2b86dff 100644 --- a/htdocs/compta/deplacement/stats/index.php +++ b/htdocs/compta/deplacement/stats/index.php @@ -33,26 +33,29 @@ $langs->loadLangs(array('trips', 'companies')); $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; +} $id = GETPOST('id', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'deplacement', $id, ''); // Other security check $childids = $user->getAllChildIds(); $childids[] = $user->id; -if ($userid > 0) -{ - if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous) && !in_array($userid, $childids)) - { +if ($userid > 0) { + if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous) && !in_array($userid, $childids)) { accessforbidden(); exit; } @@ -84,10 +87,11 @@ print load_fiche_titre($title, $mesg); dol_mkdir($dir); $useridtofilter = $userid; // Filter from parameters -if (empty($useridtofilter)) -{ +if (empty($useridtofilter)) { $useridtofilter = $childids; - if (!empty($user->rights->deplacement->readall) || !empty($user->rights->deplacement->lire_tous)) $useridtofilter = 0; + if (!empty($user->rights->deplacement->readall) || !empty($user->rights->deplacement->lire_tous)) { + $useridtofilter = 0; + } } $stats = new DeplacementStats($db, $socid, $useridtofilter); @@ -104,12 +108,11 @@ $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=tripsexpensesstats&file $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); - $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + $i = $startyear; + $legend = array(); + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -136,12 +139,11 @@ $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=tripsexpensesstats& $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px2->SetData($data); - $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + $i = $startyear; + $legend = array(); + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -162,25 +164,31 @@ if (!$mesg) $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filename_avg = $dir.'/ordersaverage-'.$user->id.'-'.$year.'.png'; - if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; - if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + if ($mode == 'customer') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + } } else { $filename_avg = $dir.'/ordersaverage-'.$year.'.png'; - if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; - if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; + if ($mode == 'customer') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; + } } $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px3->SetData($data); - $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + $i = $startyear; + $legend = array(); + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -205,7 +213,9 @@ $arrayyears = array(); foreach ($data as $val) { $arrayyears[$val['year']] = $val['year']; } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; @@ -238,12 +248,16 @@ print ''; // User print ''; // Year print ''; @@ -262,11 +276,9 @@ print ''; print ''; $oldyear = 0; -foreach ($data as $val) -{ +foreach ($data as $val) { $year = $val['year']; - while ($year && $oldyear > $year + 1) - { // If we have empty year + while ($year && $oldyear > $year + 1) { // If we have empty year $oldyear--; print ''; print ''; @@ -292,7 +304,9 @@ print '
    '; // Show graphs print '
    '.$langs->trans("Ref").'
    '; @@ -802,8 +771,7 @@ if ($type == Categorie::TYPE_CONTACT) print "'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -822,15 +790,13 @@ if ($type == Categorie::TYPE_CONTACT) } // List of bank accounts -if ($type == Categorie::TYPE_ACCOUNT) -{ +if ($type == Categorie::TYPE_ACCOUNT) { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $permission = $user->rights->banque->creer; $accounts = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($accounts < 0) - { + if ($accounts < 0) { dol_print_error($db, $object->error, $object->errors); } else { print ''; @@ -847,13 +813,13 @@ if ($type == Categorie::TYPE_ACCOUNT) print "\n"; print ''."\n"; - if (count($accounts) > 0) - { + if (count($accounts) > 0) { $i = 0; - foreach ($accounts as $key => $account) - { + foreach ($accounts as $key => $account) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; $i = 0; - foreach ($arrayofpaymentmode as $key => $val) - { + foreach ($arrayofpaymentmode as $key => $val) { print ''; @@ -791,8 +801,7 @@ if (empty($action) || $action == "view" || $action == "close") print ''; // Amount per payment type $i = 0; - foreach ($arrayofpaymentmode as $key => $val) - { + foreach ($arrayofpaymentmode as $key => $val) { print ''; @@ -810,8 +819,7 @@ if (empty($action) || $action == "view" || $action == "close") print ''; // Amount per payment type $i = 0; - foreach ($arrayofpaymentmode as $key => $val) - { + foreach ($arrayofpaymentmode as $key => $val) { print ''; // Amount per payment type $i = 0; - foreach ($arrayofpaymentmode as $key => $val) - { + foreach ($arrayofpaymentmode as $key => $val) { print ''; $i++; @@ -854,8 +866,11 @@ if (empty($action) || $action == "view" || $action == "close") // Save print ''; print ''; diff --git a/htdocs/compta/cashcontrol/cashcontrol_list.php b/htdocs/compta/cashcontrol/cashcontrol_list.php index c6431143a98..3b97b967208 100644 --- a/htdocs/compta/cashcontrol/cashcontrol_list.php +++ b/htdocs/compta/cashcontrol/cashcontrol_list.php @@ -66,7 +66,9 @@ $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; @@ -85,39 +87,37 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. -if (!$sortorder) $sortorder = "ASC"; - -// Security check -$socid = 0; -if ($user->socid > 0) // Protection if external user -{ - //$socid = $user->socid; - accessforbidden(); +if (!$sortfield) { + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; } -//$result = restrictedArea($user, 'monmodule', $id, ''); // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of fields for list $arrayfields = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field - if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); + if (!empty($val['visible'])) { + $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); + } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; @@ -125,37 +125,48 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); +// Security check +if ($user->socid > 0) { // Protection if external user + //$socid = $user->socid; + accessforbidden(); +} +if (!$user->rights->cashdesk->run && !$user->rights->takepos->run) { + accessforbidden(); +} /* * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; + $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($object->fields as $key => $val) - { + 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 + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $toselect = ''; $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -187,14 +198,14 @@ $title = $langs->trans('CashControl'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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(); @@ -202,16 +213,26 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= $hookmanager->resPrint; $sql = preg_replace('/, $/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -else $sql .= " WHERE 1 = 1"; -foreach ($search as $key => $val) -{ - if ($key == 'status' && $search[$key] == -1) continue; - $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -239,26 +260,22 @@ $sql .= $db->order($sortfield, $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; } @@ -267,8 +284,7 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".dol_buildpath('/compta/cashcontrol/cashcontrol_card.php', 1).'?id='.$id); @@ -299,13 +315,18 @@ jQuery(document).ready(function() { $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { $param .= '&search_'.$key.'='.urlencode($search[$key]); } -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'; @@ -315,11 +336,15 @@ $arrayofmassactions = array( //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->monmodule->delete) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +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 ''; @@ -340,9 +365,10 @@ $objecttmp = new CashControl($db); $trackid = 'cashfence'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($sall) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } @@ -353,11 +379,13 @@ $moreforfilter = ''; $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; @@ -374,18 +402,24 @@ print '
    '.$langs->trans("Ref").'
    '; @@ -863,8 +829,7 @@ if ($type == Categorie::TYPE_ACCOUNT) print ''.$account->number."'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -882,15 +847,13 @@ if ($type == Categorie::TYPE_ACCOUNT) } // List of Project -if ($type == Categorie::TYPE_PROJECT) -{ +if ($type == Categorie::TYPE_PROJECT) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $permission = $user->rights->projet->creer; $objects = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($objects < 0) - { + if ($objects < 0) { dol_print_error($db, $object->error, $object->errors); } else { print ''; @@ -908,13 +871,13 @@ if ($type == Categorie::TYPE_PROJECT) print "\n"; print ''."\n"; - if (count($objects) > 0) - { + if (count($objects) > 0) { $i = 0; - foreach ($objects as $key => $project) - { + foreach ($objects as $key => $project) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; print ''; + // Payment mode + print ''; + print ''; + // Delivery date $langs->load('deliveries'); print ''; print ''; @@ -2102,13 +2145,15 @@ if ($action == 'create') print ''; print ''; - // Payment mode - print ''; - print ''; - // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print ''; print ''; // Multicurrency rate - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { print ''; print ''; } - if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && !empty($conf->banque->enabled)) - { + if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && !empty($conf->banque->enabled)) { // Bank Account print ''; - print ''; } if ($totalVolume) { print ''; - print ''; } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print ''; - print ''; @@ -198,16 +209,22 @@ if ($resql) * Draft proposals */ if (!empty($conf->propal->enabled)) { - $sql = "SELECT p.rowid, p.ref, p.ref_client, p.total_ht, p.tva as total_tva, p.total as total_ttc"; + $sql = "SELECT p.rowid, p.ref, p.ref_client, p.total_ht, p.total_tva, p.total_ttc"; $sql .= ", s.rowid as socid, s.nom as name, s.client, s.canvas, s.code_client, s.email, s.entity, s.code_compta"; $sql .= " FROM ".MAIN_DB_PREFIX."propal as p"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE p.entity IN (".getEntity($propalstatic->element).")"; $sql .= " AND p.fk_soc = s.rowid"; $sql .= " AND p.fk_statut =".Propal::STATUS_DRAFT; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND p.fk_soc = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND p.fk_soc = ".$socid; + } $resql = $db->query($sql); if ($resql) { @@ -271,12 +288,18 @@ $sql = "SELECT c.rowid, c.entity, c.ref, c.fk_statut, date_cloture as datec"; $sql .= ", s.nom as socname, s.rowid as socid, s.canvas, s.client"; $sql .= " FROM ".MAIN_DB_PREFIX."propal as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE c.entity IN (".getEntity($propalstatic->element).")"; $sql .= " AND c.fk_soc = s.rowid"; //$sql.= " AND c.fk_statut > 2"; -if ($socid) $sql .= " AND c.fk_soc = ".$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " ORDER BY c.tms DESC"; $sql .= $db->plimit($max, 0); @@ -336,15 +359,21 @@ if ($resql) { */ if (!empty($conf->propal->enabled) && $user->rights->propale->lire) { $sql = "SELECT s.nom as socname, s.rowid as socid, s.canvas, s.client"; - $sql .= ", p.rowid as propalid, p.entity, p.total as total_ttc, p.total_ht, p.ref, p.fk_statut, p.datep as dp, p.fin_validite as dfv"; + $sql .= ", p.rowid as propalid, p.entity, p.total_ttc, p.total_ht, p.ref, p.fk_statut, p.datep as dp, p.fin_validite as dfv"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."propal as p"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE p.fk_soc = s.rowid"; $sql .= " AND p.entity IN (".getEntity($propalstatic->element).")"; $sql .= " AND p.fk_statut = ".Propal::STATUS_VALIDATED; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } $sql .= " ORDER BY p.rowid DESC"; $resql = $db->query($sql); diff --git a/htdocs/comm/propal/info.php b/htdocs/comm/propal/info.php index cf63d919f62..847b42edbc5 100644 --- a/htdocs/comm/propal/info.php +++ b/htdocs/comm/propal/info.php @@ -19,9 +19,9 @@ */ /** - * \file htdocs/comm/propal/info.php - * \ingroup propal - * \brief Page d'affichage des infos d'une proposition commerciale + * \file htdocs/comm/propal/info.php + * \ingroup propal + * \brief Page d'affichage des infos d'une proposition commerciale */ require '../../main.inc.php'; @@ -40,12 +40,13 @@ $ref = GETPOST('ref', 'alpha'); $socid = GETPOST('socid', 'int'); // Security check -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'propal', $id); $object = new Propal($db); -if (!$object->fetch($id, $ref) > 0) -{ +if (!$object->fetch($id, $ref) > 0) { dol_print_error($db); exit; } @@ -80,12 +81,10 @@ $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_cl // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->propal->creer) - { + if ($user->rights->propal->creer) { if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ''; $morehtmlref .= ' : '; diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index cc296e4472a..4c8ee0894f5 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -47,7 +47,9 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; // Load translation files required by the page $langs->loadLangs(array('companies', 'propal', 'compta', 'bills', 'orders', 'products', 'deliveries', 'categories')); -if (!empty($conf->expedition->enabled)) $langs->loadLangs(array('sendings')); +if (!empty($conf->expedition->enabled)) { + $langs->loadLangs(array('sendings')); +} $socid = GETPOST('socid', 'int'); @@ -93,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'); @@ -109,20 +112,32 @@ $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 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 'p.ref'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'p.ref'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} + +$permissiontoread = $user->rights->propal->lire; +$permissiontoadd = $user->rights->propal->write; +$permissiontodelete = $user->rights->propal->supprimer; +$permissiontoclose = $user->rights->propal->cloturer; // Security check $module = 'propal'; $dbtable = ''; $objectid = ''; -if (!empty($user->socid)) $socid = $user->socid; -if (!empty($socid)) -{ +if (!empty($user->socid)) { + $socid = $user->socid; +} +if (!empty($socid)) { $objectid = $socid; $module = 'societe'; $dbtable = '&societe'; @@ -152,7 +167,9 @@ $fieldstosearchall = array( 's.town'=>"Town", 'p.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["p.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["p.note_private"] = "NotePrivate"; +} $checkedtypetiers = 0; @@ -173,17 +190,18 @@ $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), - 'p.total_vat'=>array('label'=>"AmountVAT", 'checked'=>0), + 'p.total_tva'=>array('label'=>"AmountVAT", 'checked'=>0), 'p.total_ttc'=>array('label'=>"AmountTTC", 'checked'=>0), 'p.total_ht_invoiced'=>array('label'=>"AmountInvoicedHT", 'checked'=>0, 'enabled'=>!empty($conf->global->PROPOSAL_SHOW_INVOICED_AMOUNT)), 'p.total_invoiced'=>array('label'=>"AmountInvoicedTTC", 'checked'=>0, 'enabled'=>!empty($conf->global->PROPOSAL_SHOW_INVOICED_AMOUNT)), 'p.multicurrency_code'=>array('label'=>'Currency', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), 'p.multicurrency_tx'=>array('label'=>'CurrencyRate', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), 'p.multicurrency_total_ht'=>array('label'=>'MulticurrencyAmountHT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), - 'p.multicurrency_total_vat'=>array('label'=>'MulticurrencyAmountVAT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), + 'p.multicurrency_total_tva'=>array('label'=>'MulticurrencyAmountVAT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), 'p.multicurrency_total_ttc'=>array('label'=>'MulticurrencyAmountTTC', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), 'p.multicurrency_total_ht_invoiced'=>array('label'=>'MulticurrencyAmountInvoicedHT', 'checked'=>0, 'enabled'=>!empty($conf->multicurrency->enabled) && !empty($conf->global->PROPOSAL_SHOW_INVOICED_AMOUNT)), 'p.multicurrency_total_invoiced'=>array('label'=>'MulticurrencyAmountInvoicedTTC', 'checked'=>0, 'enabled'=>!empty($conf->multicurrency->enabled) && !empty($conf->global->PROPOSAL_SHOW_INVOICED_AMOUNT)), @@ -205,18 +223,24 @@ 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 = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; + $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $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'); +} include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on 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_categ = ''; $search_user = ''; $search_sale = ''; @@ -256,17 +280,17 @@ 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 != '') $search_status = $object_statut; +if ($object_statut != '') { + $search_status = $object_statut; +} -if (empty($reshook)) -{ + +if (empty($reshook)) { $objectclass = 'Propal'; $objectlabel = 'Proposals'; - $permissiontoread = $user->rights->propal->lire; - $permissiontodelete = $user->rights->propal->supprimer; - $permissiontoclose = $user->rights->propal->cloturer; $uploaddir = $conf->propal->multidir_output[$conf->entity]; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -383,23 +407,31 @@ $help_url = 'EN:Commercial_Proposals|FR:Proposition_commerciale|ES:Presupuestos' //llxHeader('',$langs->trans('Proposal'),$help_url); $sql = 'SELECT'; -if ($sall || $search_product_category > 0 || $search_user > 0) $sql = 'SELECT DISTINCT'; +if ($sall || $search_product_category > 0 || $search_user > 0) { + $sql = 'SELECT DISTINCT'; +} $sql .= ' s.rowid as socid, s.nom as name, s.name_alias as alias, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client, '; $sql .= " typent.code as typent_code,"; $sql .= " ava.rowid as availability,"; $sql .= " state.code_departement as state_code, state.nom as state_name,"; -$sql .= ' p.rowid, p.entity, p.note_private, p.total_ht, p.tva as total_vat, p.total as total_ttc, p.localtax1, p.localtax2, p.ref, p.ref_client, p.fk_statut as status, p.fk_user_author, p.datep as dp, p.fin_validite as dfv,p.date_livraison as ddelivery,'; -$sql .= ' p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva as multicurrency_total_vat, p.multicurrency_total_ttc,'; +$sql .= ' p.rowid, p.entity, p.note_private, p.total_ht, p.total_tva, p.total_ttc, p.localtax1, p.localtax2, p.ref, p.ref_client, p.fk_statut as status, p.fk_user_author, p.datep as dp, p.fin_validite as dfv,p.date_livraison as ddelivery,'; +$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) $sql .= ", sc.fk_soc, sc.fk_user"; -if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user"; +} +if ($search_categ_cus) { + $sql .= ", cc.fk_categorie, cc.fk_soc"; +} // 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 : ''); + 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(); @@ -410,74 +442,153 @@ $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; -if (!empty($search_categ_cus)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ +if (!empty($search_categ_cus)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ +} $sql .= ', '.MAIN_DB_PREFIX.'propal as p'; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (p.rowid = ef.fk_object)"; -if ($sall || $search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'propaldet as pd ON p.rowid=pd.fk_propal'; -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (p.rowid = ef.fk_object)"; +} +if ($sall || $search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'propaldet as pd ON p.rowid=pd.fk_propal'; +} +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +} $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON p.fk_user_author = u.rowid'; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr ON pr.rowid = p.fk_projet"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_availability as ava on (ava.rowid = p.fk_availability)"; // We'll need this table joined to the select in order to filter by sale -if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; -if ($search_user > 0) -{ +if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} +if ($search_user > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as c"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql .= ' WHERE p.fk_soc = s.rowid'; $sql .= ' AND p.entity IN ('.getEntity('propal').')'; -if (!$user->rights->societe->client->voir && !$socid) //restriction -{ +if (!$user->rights->societe->client->voir && !$socid) { //restriction $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } -if ($search_town) $sql .= natural_search('s.town', $search_town); -if ($search_zip) $sql .= natural_search("s.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_country) $sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')'; -if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; -if ($search_ref) $sql .= natural_search('p.ref', $search_ref); -if ($search_refcustomer) $sql .= natural_search('p.ref_client', $search_refcustomer); -if ($search_refproject) $sql .= natural_search('pr.ref', $search_refproject); -if ($search_project) $sql .= natural_search('pr.title', $search_project); -if ($search_availability) $sql .= " AND p.fk_availability IN (".$db->sanitize($db->escape($search_availability)).')'; -if ($search_societe) $sql .= natural_search('s.nom', $search_societe); -if ($search_societe_alias) $sql .= natural_search('s.name_alias', $search_societe_alias); -if ($search_login) $sql .= natural_search("u.login", $search_login); -if ($search_montant_ht != '') $sql .= natural_search("p.total_ht", $search_montant_ht, 1); -if ($search_montant_vat != '') $sql .= natural_search("p.tva", $search_montant_vat, 1); -if ($search_montant_ttc != '') $sql .= natural_search("p.total", $search_montant_ttc, 1); -if ($search_multicurrency_code != '') $sql .= ' AND p.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; -if ($search_multicurrency_tx != '') $sql .= natural_search('p.multicurrency_tx', $search_multicurrency_tx, 1); -if ($search_multicurrency_montant_ht != '') $sql .= natural_search('p.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); -if ($search_multicurrency_montant_vat != '') $sql .= natural_search('p.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); -if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('p.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); +if ($search_town) { + $sql .= natural_search('s.town', $search_town); +} +if ($search_zip) { + $sql .= natural_search("s.zip", $search_zip); +} +if ($search_state) { + $sql .= natural_search("state.nom", $search_state); +} +if ($search_country) { + $sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')'; +} +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; +} +if ($search_ref) { + $sql .= natural_search('p.ref', $search_ref); +} +if ($search_refcustomer) { + $sql .= natural_search('p.ref_client', $search_refcustomer); +} +if ($search_refproject) { + $sql .= natural_search('pr.ref', $search_refproject); +} +if ($search_project) { + $sql .= natural_search('pr.title', $search_project); +} +if ($search_availability) { + $sql .= " AND p.fk_availability IN (".$db->sanitize($db->escape($search_availability)).')'; +} +if ($search_societe) { + $sql .= natural_search('s.nom', $search_societe); +} +if ($search_societe_alias) { + $sql .= natural_search('s.name_alias', $search_societe_alias); +} +if ($search_login) { + $sql .= natural_search("u.login", $search_login); +} +if ($search_montant_ht != '') { + $sql .= natural_search("p.total_ht", $search_montant_ht, 1); +} +if ($search_montant_vat != '') { + $sql .= natural_search("p.total_tva", $search_montant_vat, 1); +} +if ($search_montant_ttc != '') { + $sql .= natural_search("p.total_ttc", $search_montant_ttc, 1); +} +if ($search_multicurrency_code != '') { + $sql .= ' AND p.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; +} +if ($search_multicurrency_tx != '') { + $sql .= natural_search('p.multicurrency_tx', $search_multicurrency_tx, 1); +} +if ($search_multicurrency_montant_ht != '') { + $sql .= natural_search('p.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); +} +if ($search_multicurrency_montant_vat != '') { + $sql .= natural_search('p.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); +} +if ($search_multicurrency_montant_ttc != '') { + $sql .= natural_search('p.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); +} if ($sall) { $sql .= natural_search(array_keys($fieldstosearchall), $sall); } -if ($search_categ_cus > 0) $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); -if ($search_categ_cus == -2) $sql .= " AND cc.fk_categorie IS NULL"; +if ($search_categ_cus > 0) { + $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); +} +if ($search_categ_cus == -2) { + $sql .= " AND cc.fk_categorie IS NULL"; +} -if ($search_fk_cond_reglement > 0) $sql .= " AND p.fk_cond_reglement = ".$db->escape($search_fk_cond_reglement); -if ($search_fk_shipping_method > 0) $sql .= " AND p.fk_shipping_method = ".$db->escape($search_fk_shipping_method); -if ($search_fk_mode_reglement > 0) $sql .= " AND p.fk_mode_reglement = ".$db->escape($search_fk_mode_reglement); +if ($search_fk_cond_reglement > 0) { + $sql .= " AND p.fk_cond_reglement = ".$db->escape($search_fk_cond_reglement); +} +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); +} -if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$db->escape($search_product_category); -if ($socid > 0) $sql .= ' AND s.rowid = '.$socid; -if ($search_status != '' && $search_status != '-1') -{ +if ($search_product_category > 0) { + $sql .= " AND cp.fk_categorie = ".$db->escape($search_product_category); +} +if ($socid > 0) { + $sql .= ' AND s.rowid = '.$socid; +} +if ($search_status != '' && $search_status != '-1') { $sql .= ' AND p.fk_statut IN ('.$db->sanitize($db->escape($search_status)).')'; } -if ($search_date_start) $sql .= " AND p.datep >= '".$db->idate($search_date_start)."'"; -if ($search_date_end) $sql .= " AND p.datep <= '".$db->idate($search_date_end)."'"; -if ($search_dateend_start) $sql .= " AND p.fin_validite >= '".$db->idate($search_dateend_start)."'"; -if ($search_dateend_end) $sql .= " AND p.fin_validite <= '".$db->idate($search_dateend_end)."'"; -if ($search_datedelivery_start) $sql .= " AND p.date_livraison >= '".$db->idate($search_datedelivery_start)."'"; -if ($search_datedelivery_end) $sql .= " AND p.date_livraison <= '".$db->idate($search_datedelivery_end)."'"; -if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$db->escape($search_sale); -if ($search_user > 0) -{ +if ($search_date_start) { + $sql .= " AND p.datep >= '".$db->idate($search_date_start)."'"; +} +if ($search_date_end) { + $sql .= " AND p.datep <= '".$db->idate($search_date_end)."'"; +} +if ($search_dateend_start) { + $sql .= " AND p.fin_validite >= '".$db->idate($search_dateend_start)."'"; +} +if ($search_dateend_end) { + $sql .= " AND p.fin_validite <= '".$db->idate($search_dateend_end)."'"; +} +if ($search_datedelivery_start) { + $sql .= " AND p.date_livraison >= '".$db->idate($search_datedelivery_start)."'"; +} +if ($search_datedelivery_end) { + $sql .= " AND p.date_livraison <= '".$db->idate($search_datedelivery_end)."'"; +} +if ($search_sale > 0) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$db->escape($search_sale); +} +if ($search_user > 0) { $sql .= " AND c.fk_c_type_contact = tc.rowid AND tc.element='propal' AND tc.source='internal' AND c.element_id = p.rowid AND c.fk_socpeople = ".$db->escape($search_user); } // Add where from extra fields @@ -493,13 +604,11 @@ $sql .= ', p.ref DESC'; // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -509,17 +618,17 @@ $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $objectstatic = new Propal($db); $userstatic = new User($db); - if ($socid > 0) - { + if ($socid > 0) { $soc = new Societe($db); $soc->fetch($socid); $title = $langs->trans('ListOfProposals').' - '.$soc->name; - if (empty($search_societe)) $search_societe = $soc->name; + if (empty($search_societe)) { + $search_societe = $soc->name; + } } else { $title = $langs->trans('ListOfProposals'); } @@ -528,8 +637,7 @@ if ($resql) $arrayofselected = is_array($toselect) ? $toselect : array(); - if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) - { + if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -541,44 +649,123 @@ if ($resql) llxHeader('', $langs->trans('Proposal'), $help_url); $param = '&search_status='.urlencode($search_status); - 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_date_start) $param .= '&search_date_start='.urlencode($search_date_start); - if ($search_date_end) $param .= '&search_date_end='.urlencode($search_date_end); - if ($search_dateend_start) $param .= '&search_dateend_start='.urlencode($search_dateend_start); - if ($search_dateend_end) $param .= '&search_dateend_end='.urlencode($search_dateend_end); - if ($search_datedelivery_start) $param .= '&search_datedelivery_start='.urlencode($search_datedelivery_start); - if ($search_datedelivery_end) $param .= '&search_datedelivery_end='.urlencode($search_datedelivery_end); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_refcustomer) $param .= '&search_refcustomer='.urlencode($search_refcustomer); - if ($search_refproject) $param .= '&search_refproject='.urlencode($search_refproject); - if ($search_societe) $param .= '&search_societe='.urlencode($search_societe); - if ($search_societe_alias) $param .= '&search_societe_alias='.urlencode($search_societe_alias); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); - if ($search_montant_ht) $param .= '&search_montant_ht='.urlencode($search_montant_ht); - if ($search_multicurrency_code != '') $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); - if ($search_multicurrency_tx != '') $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); - if ($search_multicurrency_montant_ht != '') $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); - if ($search_multicurrency_montant_vat != '') $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); - if ($search_multicurrency_montant_ttc != '') $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); - if ($search_login) $param .= '&search_login='.urlencode($search_login); - if ($search_town) $param .= '&search_town='.urlencode($search_town); - if ($search_zip) $param .= '&search_zip='.urlencode($search_zip); - if ($socid > 0) $param .= '&socid='.urlencode($socid); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($search_categ_cus > 0) $param .= '&search_categ_cus='.urlencode($search_categ_cus); - if ($search_product_category != '') $param .= '&search_product_category='.$search_product_category; - if ($search_fk_cond_reglement > 0) $param .= '&search_fk_cond_reglement='.$search_fk_cond_reglement; - if ($search_fk_shipping_method > 0) $param .= '&search_fk_shipping_method='.$search_fk_shipping_method; - if ($search_fk_mode_reglement > 0) $param .= '&search_fk_mode_reglement='.$search_fk_mode_reglement; - if ($search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.$search_type_thirdparty; - if ($search_town) $param .= '&search_town='.$search_town; - if ($search_zip) $param .= '&search_zip='.$search_zip; - if ($search_state) $param .= '&search_state='.$search_state; - if ($search_town) $param .= '&search_town='.$search_town; - if ($search_country) $param .= '&search_country='.$search_country; + 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_date_start) { + $param .= '&search_date_start='.urlencode($search_date_start); + } + if ($search_date_end) { + $param .= '&search_date_end='.urlencode($search_date_end); + } + if ($search_dateend_start) { + $param .= '&search_dateend_start='.urlencode($search_dateend_start); + } + if ($search_dateend_end) { + $param .= '&search_dateend_end='.urlencode($search_dateend_end); + } + if ($search_datedelivery_start) { + $param .= '&search_datedelivery_start='.urlencode($search_datedelivery_start); + } + if ($search_datedelivery_end) { + $param .= '&search_datedelivery_end='.urlencode($search_datedelivery_end); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_refcustomer) { + $param .= '&search_refcustomer='.urlencode($search_refcustomer); + } + if ($search_refproject) { + $param .= '&search_refproject='.urlencode($search_refproject); + } + if ($search_societe) { + $param .= '&search_societe='.urlencode($search_societe); + } + if ($search_societe_alias) { + $param .= '&search_societe_alias='.urlencode($search_societe_alias); + } + if ($search_user > 0) { + $param .= '&search_user='.urlencode($search_user); + } + if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); + } + if ($search_montant_ht) { + $param .= '&search_montant_ht='.urlencode($search_montant_ht); + } + if ($search_multicurrency_code != '') { + $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); + } + if ($search_multicurrency_tx != '') { + $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); + } + if ($search_multicurrency_montant_ht != '') { + $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); + } + if ($search_multicurrency_montant_vat != '') { + $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); + } + if ($search_multicurrency_montant_ttc != '') { + $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); + } + if ($search_login) { + $param .= '&search_login='.urlencode($search_login); + } + if ($search_town) { + $param .= '&search_town='.urlencode($search_town); + } + if ($search_zip) { + $param .= '&search_zip='.urlencode($search_zip); + } + if ($socid > 0) { + $param .= '&socid='.urlencode($socid); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($search_categ_cus > 0) { + $param .= '&search_categ_cus='.urlencode($search_categ_cus); + } + if ($search_product_category != '') { + $param .= '&search_product_category='.$search_product_category; + } + if ($search_fk_cond_reglement > 0) { + $param .= '&search_fk_cond_reglement='.$search_fk_cond_reglement; + } + 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; + } + if ($search_type_thirdparty > 0) { + $param .= '&search_type_thirdparty='.$search_type_thirdparty; + } + if ($search_town) { + $param .= '&search_town='.$search_town; + } + if ($search_zip) { + $param .= '&search_zip='.$search_zip; + } + if ($search_state) { + $param .= '&search_state='.$search_state; + } + if ($search_town) { + $param .= '&search_town='.$search_town; + } + if ($search_country) { + $param .= '&search_country='.$search_country; + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -592,18 +779,28 @@ if ($resql) 'presign'=>$langs->trans("Sign"), 'nopresign'=>$langs->trans("NoSign"), ); - if ($user->rights->propal->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); - if ($user->rights->propal->cloturer) $arrayofmassactions['closed'] = $langs->trans("Close"); - if (in_array($massaction, array('presend', 'predelete', 'closed'))) $arrayofmassactions = array(); + if ($user->rights->propal->supprimer) { + $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); + } + if ($user->rights->propal->cloturer) { + $arrayofmassactions['closed'] = $langs->trans("Close"); + } + if (in_array($massaction, array('presend', 'predelete', 'closed'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $url = DOL_URL_ROOT.'/comm/propal/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewPropal'), '', 'fa fa-plus-circle', $url, '', $user->rights->propal->creer); // Fields title search print ''; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; @@ -619,24 +816,22 @@ if ($resql) $trackid = 'pro'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($massaction == 'prevalidate') - { + if ($massaction == 'prevalidate') { print $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans("ConfirmMassValidation"), $langs->trans("ConfirmMassValidationQuestion"), "validate", null, '', 0, 200, 500, 1); } - if ($massaction == 'presign') - { + if ($massaction == 'presign') { print $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans("ConfirmMassSignature"), $langs->trans("ConfirmMassSignatureQuestion"), "sign", null, '', 0, 200, 500, 1); } - if ($massaction == 'nopresign') - { + if ($massaction == 'nopresign') { print $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans("ConfirmMassNoSignature"), $langs->trans("ConfirmMassNoSignatureQuestion"), "nosign", null, '', 0, 200, 500, 1); } - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } @@ -645,8 +840,7 @@ if ($resql) $moreforfilter = ''; // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; @@ -654,16 +848,14 @@ if ($resql) $moreforfilter .= '
    '; } // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + if ($user->rights->societe->client->voir || $socid) { $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter .= '
    '; } // If the user can view products - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) - { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; @@ -671,8 +863,7 @@ if ($resql) $moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter .= '
    '; } - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) - { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; @@ -681,11 +872,13 @@ if ($resql) } $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)) - { + if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; @@ -699,69 +892,63 @@ if ($resql) print '
    '.$langs->trans("Ref").'
    '; @@ -924,8 +887,7 @@ if ($type == Categorie::TYPE_PROJECT) print ''.$project->title."'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -943,13 +905,11 @@ if ($type == Categorie::TYPE_PROJECT) } // List of users -if ($type == Categorie::TYPE_USER) -{ +if ($type == Categorie::TYPE_USER) { require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; $users = $object->getObjectsInCateg($type); - if ($users < 0) - { + if ($users < 0) { dol_print_error($db, $object->error, $object->errors); } else { print ''; @@ -969,11 +929,9 @@ if ($type == Categorie::TYPE_USER) print "\n"; print ''."\n"; - if (count($users) > 0) - { + if (count($users) > 0) { // Use "$userentry" here, because "$user" is the current user - foreach ($users as $key => $userentry) - { + foreach ($users as $key => $userentry) { print "\t".''."\n"; print ''; // Status - Percent $withstatus = 0; - if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT') - { + if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT') { $withstatus = 1; - if ($event->percentage >= 0) $withstatus = 2; + if ($event->percentage >= 0) { + $withstatus = 2; + } } print '
    '.$langs->trans("Users").' '.$num.'
    '; print $userentry->getNomUrl(1); @@ -982,8 +940,7 @@ if ($type == Categorie::TYPE_USER) // Link to delete from category print ''; - if ($user->rights->user->user->creer) - { + if ($user->rights->user->user->creer) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -1002,15 +959,13 @@ if ($type == Categorie::TYPE_USER) // List of warehouses -if ($type == Categorie::TYPE_WAREHOUSE) -{ +if ($type == Categorie::TYPE_WAREHOUSE) { $permission = $user->rights->stock->creer; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; $objects = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($objects < 0) - { + if ($objects < 0) { dol_print_error($db, $object->error, $object->errors); } else { print ''; @@ -1028,13 +983,13 @@ if ($type == Categorie::TYPE_WAREHOUSE) print "\n"; print ''."\n"; - if (count($objects) > 0) - { + if (count($objects) > 0) { $i = 0; - foreach ($objects as $key => $project) - { + foreach ($objects as $key => $project) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; $i = 0; - while ($i < 7) - { + while ($i < 7) { print ' '."\n"; $i++; } @@ -1256,15 +1381,11 @@ if (empty($action) || $action == 'show_month') // View by month for ($iter_week = 0; $iter_week < 6; $iter_week++) { echo " \n"; // Get date of the current day, format 'yyyy-mm-dd' - if ($tmpday <= 0) // If number of the current day is in previous month - { + if ($tmpday <= 0) { // If number of the current day is in previous month $currdate0 = sprintf("%04d", $prev_year).sprintf("%02d", $prev_month).sprintf("%02d", $max_day_in_prev_month + $tmpday); - } - elseif ($tmpday <= $max_day_in_month) // If number of the current day is in current month - { + } elseif ($tmpday <= $max_day_in_month) { // If number of the current day is in current month $currdate0 = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $tmpday); - } - else // If number of the current day is in next month + } else // If number of the current day is in next month { $currdate0 = sprintf("%04d", $next_year).sprintf("%02d", $next_month).sprintf("%02d", $tmpday - $max_day_in_month); } @@ -1277,7 +1398,9 @@ if (empty($action) || $action == 'show_month') // View by month if ($tmpday <= 0) { /* Show days before the beginning of the current month (previous month) */ $style = 'cal_other_month cal_past'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; + if ($iter_day == 6) { + $style .= ' cal_other_month_right'; + } echo ' \n"; @@ -1285,11 +1408,19 @@ if (empty($action) || $action == 'show_month') // View by month /* Show days of the current month */ $curtime = dol_mktime(0, 0, 0, $month, $tmpday, $year); $style = 'cal_current_month'; - if ($iter_day == 6) $style .= ' cal_current_month_right'; + if ($iter_day == 6) { + $style .= ' cal_current_month_right'; + } $today = 0; - if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; - if ($today) $style = 'cal_today'; - if ($curtime < $todaytms) $style .= ' cal_past'; + if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $month && $todayarray['year'] == $year) { + $today = 1; + } + if ($today) { + $style = 'cal_today'; + } + if ($curtime < $todaytms) { + $style .= ' cal_past'; + } //var_dump($todayarray['mday']."==".$tmpday." && ".$todayarray['mon']."==".$month." && ".$todayarray['year']."==".$year.' -> '.$style); echo ' \n"; @@ -1343,18 +1476,24 @@ if (empty($action) || $action == 'show_month') // View by month for ($iter_day = 0; $iter_day < 7; $iter_day++) { // Show days of the current week - $curtime = dol_time_plus_duree($firstdaytoshow, $iter_day, 'd'); - $tmparray = dol_getdate($curtime, true); - $tmpday = $tmparray['mday']; - $tmpmonth = $tmparray['mon']; - $tmpyear = $tmparray['year']; + $curtime = dol_time_plus_duree($firstdaytoshow, $iter_day, 'd'); // $firstdaytoshow is in timezone of server + $tmpday = dol_print_date($curtime, '%d', 'tzuserrel'); + $tmpmonth = dol_print_date($curtime, '%m', 'tzuserrel'); + $tmpyear = dol_print_date($curtime, '%Y', 'tzuserrel'); $style = 'cal_current_month'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; + if ($iter_day == 6) { + $style .= ' cal_other_month_right'; + } + $today = 0; $todayarray = dol_getdate($now, 'fast'); - if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1; - if ($today) $style = 'cal_today'; + if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) { + $today = 1; + } + if ($today) { + $style = 'cal_today'; + } echo ' \n"; /* - echo '
    '; - echo '
    '; - echo '
    '; - echo show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, -1); - echo '
    '."\n"; - echo "
    \n"; + echo '
    '; + echo '
    '; + echo '
    '; + echo show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, -1); + echo '
    '."\n"; + echo "
    \n"; */ echo '
    '.$langs->trans("Ref").'
    '; @@ -1044,8 +999,7 @@ if ($type == Categorie::TYPE_WAREHOUSE) print ''.$project->title."'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); diff --git a/htdocs/collab/index.php b/htdocs/collab/index.php index e5fe22c9168..296e0f3852f 100644 --- a/htdocs/collab/index.php +++ b/htdocs/collab/index.php @@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "other", "website")); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $conf->dol_hide_leftmenu = 1; // Force hide of left menu. @@ -41,17 +43,37 @@ $page = GETPOST('page', 'alpha'); $pageid = GETPOST('pageid', 'int'); $action = GETPOST('action', 'aZ09'); -if (GETPOST('delete')) { $action = 'delete'; } -if (GETPOST('preview')) $action = 'preview'; -if (GETPOST('create')) { $action = 'create'; } -if (GETPOST('editmedia')) { $action = 'editmedia'; } -if (GETPOST('editcss')) { $action = 'editcss'; } -if (GETPOST('editmenu')) { $action = 'editmenu'; } -if (GETPOST('setashome')) { $action = 'setashome'; } -if (GETPOST('editmeta')) { $action = 'editmeta'; } -if (GETPOST('editcontent')) { $action = 'editcontent'; } +if (GETPOST('delete')) { + $action = 'delete'; +} +if (GETPOST('preview')) { + $action = 'preview'; +} +if (GETPOST('create')) { + $action = 'create'; +} +if (GETPOST('editmedia')) { + $action = 'editmedia'; +} +if (GETPOST('editcss')) { + $action = 'editcss'; +} +if (GETPOST('editmenu')) { + $action = 'editmenu'; +} +if (GETPOST('setashome')) { + $action = 'setashome'; +} +if (GETPOST('editmeta')) { + $action = 'editmeta'; +} +if (GETPOST('editcontent')) { + $action = 'editcontent'; +} -if (empty($action)) $action = 'preview'; +if (empty($action)) { + $action = 'preview'; +} @@ -60,13 +82,16 @@ if (empty($action)) $action = 'preview'; * Actions */ -if (GETPOST('refreshsite')) $pageid = 0; // If we change the site, we reset the pageid. -if (GETPOST('refreshpage')) $action = 'preview'; +if (GETPOST('refreshsite')) { + $pageid = 0; // If we change the site, we reset the pageid. +} +if (GETPOST('refreshpage')) { + $action = 'preview'; +} // Add a collab page -if ($action == 'add') -{ +if ($action == 'add') { $db->begin(); $objectpage->title = GETPOST('WEBSITE_TITLE'); @@ -74,23 +99,19 @@ if ($action == 'add') $objectpage->description = GETPOST('WEBSITE_DESCRIPTION'); $objectpage->keywords = GETPOST('WEBSITE_KEYWORD'); - if (empty($objectpage->title)) - { + if (empty($objectpage->title)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $res = $objectpage->create($user); - if ($res <= 0) - { + if ($res <= 0) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); } } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); $action = ''; @@ -103,25 +124,21 @@ if ($action == 'add') } // Update page -if ($action == 'delete') -{ +if ($action == 'delete') { $db->begin(); $res = $object->fetch(0, $website); $res = $objectpage->fetch($pageid, $object->fk_website); - if ($res > 0) - { + if ($res > 0) { $res = $objectpage->delete($user); - if (!($res > 0)) - { + if (!($res > 0)) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs'); @@ -149,15 +166,16 @@ llxHeader('', $langs->trans("WebsiteSetup"), $help_url, '', 0, '', '', '', '', ' print "\n".'
    '; print ''; -if ($action == 'create') -{ +if ($action == 'create') { print ''; } // Add a margin under toolbar ? $style = ''; -if ($action != 'preview' && $action != 'editcontent') $style = ' margin-bottom: 5px;'; +if ($action != 'preview' && $action != 'editcontent') { + $style = ' margin-bottom: 5px;'; +} //var_dump($objectpage);exit; print '
    '; diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index 6f1e83103d5..391b418f5b8 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 @@ -77,9 +77,13 @@ $datef = dol_mktime($fulldayevent ? '23' : $p2hour, $fulldayevent ? '59' : $p2mi // Security check $socid = GETPOST('socid', 'int'); $id = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'agenda', $id, 'actioncomm&societe', 'myactions|allactions', 'fk_soc', 'id'); -if ($user->socid && $socid) $result = restrictedArea($user, 'societe', $socid); +if ($user->socid && $socid) { + $result = restrictedArea($user, 'societe', $socid); +} $error = GETPOST("error"); $donotclearsession = GETPOST('donotclearsession') ?GETPOST('donotclearsession') : 0; @@ -114,11 +118,17 @@ $hookmanager->initHooks(array('actioncard', 'globalcard')); $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'); +} $TRemindTypes = array(); -if (!empty($conf->global->AGENDA_REMINDER_BROWSER)) $TRemindTypes['browser'] = array('label'=>$langs->trans('BrowserPush'), 'disabled'=>(empty($conf->global->AGENDA_REMINDER_BROWSER) ? 1 : 0)); -if (!empty($conf->global->AGENDA_REMINDER_EMAIL)) $TRemindTypes['email'] = array('label'=>$langs->trans('EMail'), 'disabled'=>(empty($conf->global->AGENDA_REMINDER_EMAIL) ? 1 : 0)); +if (!empty($conf->global->AGENDA_REMINDER_BROWSER)) { + $TRemindTypes['browser'] = array('label'=>$langs->trans('BrowserPush'), 'disabled'=>(empty($conf->global->AGENDA_REMINDER_BROWSER) ? 1 : 0)); +} +if (!empty($conf->global->AGENDA_REMINDER_EMAIL)) { + $TRemindTypes['email'] = array('label'=>$langs->trans('EMail'), 'disabled'=>(empty($conf->global->AGENDA_REMINDER_EMAIL) ? 1 : 0)); +} $TDurationTypes = array('y'=>$langs->trans('Years'), 'm'=>$langs->trans('Month'), 'w'=>$langs->trans('Weeks'), 'd'=>$langs->trans('Days'), 'h'=>$langs->trans('Hours'), 'i'=>$langs->trans('Minutes')); @@ -129,60 +139,65 @@ $TDurationTypes = array('y'=>$langs->trans('Years'), 'm'=>$langs->trans('Month') $listUserAssignedUpdated = false; // Remove user to assigned list -if (empty($reshook) && (GETPOST('removedassigned') || GETPOST('removedassigned') == '0')) -{ +if (empty($reshook) && (GETPOST('removedassigned') || GETPOST('removedassigned') == '0')) { $idtoremove = GETPOST('removedassigned'); - if (!empty($_SESSION['assignedtouser'])) $tmpassigneduserids = json_decode($_SESSION['assignedtouser'], 1); - else $tmpassigneduserids = array(); + if (!empty($_SESSION['assignedtouser'])) { + $tmpassigneduserids = json_decode($_SESSION['assignedtouser'], 1); + } else { + $tmpassigneduserids = array(); + } - foreach ($tmpassigneduserids as $key => $val) - { - if ($val['id'] == $idtoremove || $val['id'] == -1) unset($tmpassigneduserids[$key]); + foreach ($tmpassigneduserids as $key => $val) { + if ($val['id'] == $idtoremove || $val['id'] == -1) { + unset($tmpassigneduserids[$key]); + } } $_SESSION['assignedtouser'] = json_encode($tmpassigneduserids); $donotclearsession = 1; - if ($action == 'add') $action = 'create'; - if ($action == 'update') $action = 'edit'; + if ($action == 'add') { + $action = 'create'; + } + if ($action == 'update') { + $action = 'edit'; + } $listUserAssignedUpdated = true; } // Add user to assigned list -if (empty($reshook) && (GETPOST('addassignedtouser') || GETPOST('updateassignedtouser'))) -{ +if (empty($reshook) && (GETPOST('addassignedtouser') || GETPOST('updateassignedtouser'))) { // Add a new user - if (GETPOST('assignedtouser') > 0) - { + if (GETPOST('assignedtouser') > 0) { $assignedtouser = array(); - if (!empty($_SESSION['assignedtouser'])) - { + if (!empty($_SESSION['assignedtouser'])) { $assignedtouser = json_decode($_SESSION['assignedtouser'], true); } $assignedtouser[GETPOST('assignedtouser')] = array('id'=>GETPOST('assignedtouser'), 'transparency'=>GETPOST('transparency'), 'mandatory'=>1); $_SESSION['assignedtouser'] = json_encode($assignedtouser); } $donotclearsession = 1; - if ($action == 'add') $action = 'create'; - if ($action == 'update') $action = 'edit'; + if ($action == 'add') { + $action = 'create'; + } + if ($action == 'update') { + $action = 'edit'; + } $listUserAssignedUpdated = true; } // Link to a project if (empty($reshook) && $action == 'classin' && ($user->rights->agenda->allactions->create || - (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->rights->agenda->myactions->create))) -{ + (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->rights->agenda->myactions->create))) { //$object->fetch($id); $object->setProject(GETPOST('projectid', 'int')); } // Action clone object -if (empty($reshook) && $action == 'confirm_clone' && $confirm == 'yes') -{ - if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) - { +if (empty($reshook) && $action == 'confirm_clone' && $confirm == 'yes') { + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { if ($id > 0) { @@ -204,23 +219,22 @@ if (empty($reshook) && $action == 'confirm_clone' && $confirm == 'yes') } // Add event -if (empty($reshook) && $action == 'add') -{ +if (empty($reshook) && $action == 'add') { $error = 0; - if (empty($backtopage)) - { - if ($socid > 0) $backtopage = DOL_URL_ROOT.'/societe/agenda.php?socid='.$socid; - else $backtopage = DOL_URL_ROOT.'/comm/action/index.php'; + if (empty($backtopage)) { + if ($socid > 0) { + $backtopage = DOL_URL_ROOT.'/societe/agenda.php?socid='.$socid; + } else { + $backtopage = DOL_URL_ROOT.'/comm/action/index.php'; + } } - if (!empty($socpeopleassigned[0])) - { + if (!empty($socpeopleassigned[0])) { $result = $contact->fetch($socpeopleassigned[0]); } - if ($cancel) - { + if ($cancel) { header("Location: ".$backtopage); exit; } @@ -232,23 +246,20 @@ if (empty($reshook) && $action == 'add') $datef = dol_mktime($fulldayevent ? '23' : GETPOST("p2hour", 'int'), $fulldayevent ? '59' : GETPOST("p2min", 'int'), $fulldayevent ? '59' : GETPOST("apsec", 'int'), GETPOST("p2month", 'int'), GETPOST("p2day", 'int'), GETPOST("p2year", 'int'), 'tzuser'); // Check parameters - if (!$datef && $percentage == 100) - { + if (!$datef && $percentage == 100) { $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors'); } - if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && !GETPOST('label')) - { + if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && !GETPOST('label')) { $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); } // Initialisation objet cactioncomm - if (GETPOSTISSET('actioncode') && !GETPOST('actioncode', 'aZ09')) // actioncode is '0' - { + if (GETPOSTISSET('actioncode') && !GETPOST('actioncode', 'aZ09')) { // actioncode is '0' $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); @@ -256,8 +267,7 @@ if (empty($reshook) && $action == 'add') $object->type_code = GETPOST('actioncode', 'aZ09'); } - if (!$error) - { + if (!$error) { // Initialisation objet actioncomm $object->priority = GETPOSTISSET("priority") ? GETPOST("priority", "int") : 0; $object->fulldayevent = (!empty($fulldayevent) ? 1 : 0); @@ -265,14 +275,11 @@ if (empty($reshook) && $action == 'add') $object->label = GETPOST('label', 'alphanohtml'); $object->fk_element = GETPOST("fk_element", 'int'); $object->elementtype = GETPOST("elementtype", 'alpha'); - if (!GETPOST('label')) - { - if (GETPOST('actioncode', 'aZ09') == 'AC_RDV' && $contact->getFullName($langs)) - { + if (!GETPOST('label')) { + if (GETPOST('actioncode', 'aZ09') == 'AC_RDV' && $contact->getFullName($langs)) { $object->label = $langs->transnoentitiesnoconv("TaskRDVWith", $contact->getFullName($langs)); } else { - if ($langs->trans("Action".$object->type_code) != "Action".$object->type_code) - { + if ($langs->trans("Action".$object->type_code) != "Action".$object->type_code) { $object->label = $langs->transnoentitiesnoconv("Action".$object->type_code)."\n"; } else { $cactioncomm->fetch($object->type_code); @@ -301,13 +308,15 @@ if (empty($reshook) && $action == 'add') $transparency = (GETPOST("transparency") == 'on' ? 1 : 0); $listofuserid = array(); - if (!empty($_SESSION['assignedtouser'])) $listofuserid = json_decode($_SESSION['assignedtouser'], true); + if (!empty($_SESSION['assignedtouser'])) { + $listofuserid = json_decode($_SESSION['assignedtouser'], true); + } $i = 0; - foreach ($listofuserid as $key => $value) - { - if ($i == 0) // First entry - { - if ($value['id'] > 0) $object->userownerid = $value['id']; + foreach ($listofuserid as $key => $value) { + if ($i == 0) { // First entry + if ($value['id'] > 0) { + $object->userownerid = $value['id']; + } $object->transparency = $transparency; } @@ -317,17 +326,19 @@ if (empty($reshook) && $action == 'add') } } - if (!$error && !empty($conf->global->AGENDA_ENABLE_DONEBY)) - { - if (GETPOST("doneby") > 0) $object->userdoneid = GETPOST("doneby", "int"); + if (!$error && !empty($conf->global->AGENDA_ENABLE_DONEBY)) { + if (GETPOST("doneby") > 0) { + $object->userdoneid = GETPOST("doneby", "int"); + } } $object->note_private = trim(GETPOST("note", "restricthtml")); - if (GETPOSTISSET("contactid")) $object->contact = $contact; + if (GETPOSTISSET("contactid")) { + $object->contact = $contact; + } - if (GETPOST('socid', 'int') > 0) - { + if (GETPOST('socid', 'int') > 0) { $object->socid = GETPOST('socid', 'int'); $object->fetch_thirdparty(); @@ -335,51 +346,45 @@ if (empty($reshook) && $action == 'add') } // Check parameters - if (empty($object->userownerid) && empty($_SESSION['assignedtouser'])) - { + if (empty($object->userownerid) && empty($_SESSION['assignedtouser'])) { $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ActionsOwnedBy")), null, 'errors'); } - if ($object->type_code == 'AC_RDV' && ($datep == '' || ($datef == '' && empty($fulldayevent)))) - { + if ($object->type_code == 'AC_RDV' && ($datep == '' || ($datef == '' && empty($fulldayevent)))) { $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors'); } - if (!GETPOST('apyear') && !GETPOST('adyear')) - { + if (!GETPOST('apyear') && !GETPOST('adyear')) { $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); } - foreach ($socpeopleassigned as $cid) - { + foreach ($socpeopleassigned as $cid) { $object->socpeopleassigned[$cid] = array('id' => $cid); } - if (!empty($object->socpeopleassigned)) - { + if (!empty($object->socpeopleassigned)) { reset($object->socpeopleassigned); $object->contact_id = key($object->socpeopleassigned); } // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { $db->begin(); // Creation of action/event $idaction = $object->create($user); - if ($idaction > 0) - { - if (!$object->error) - { + if ($idaction > 0) { + if (!$object->error) { // Category association $categories = GETPOST('categories', 'array'); $object->setCategories($categories); @@ -387,7 +392,9 @@ if (empty($reshook) && $action == 'add') unset($_SESSION['assignedtouser']); $moreparam = ''; - if ($user->id != $object->userownerid) $moreparam = "filtert=-1"; // We force to remove filter so created record is visible when going back to per user view. + if ($user->id != $object->userownerid) { + $moreparam = "filtert=-1"; // We force to remove filter so created record is visible when going back to per user view. + } // Create reminders if ($addreminder == 'on') { @@ -401,11 +408,12 @@ if (empty($reshook) && $action == 'add') $actionCommReminder->offsetvalue = $offsetvalue; $actionCommReminder->status = $actionCommReminder::STATUS_TODO; $actionCommReminder->fk_actioncomm = $object->id; - if ($remindertype == 'email') $actionCommReminder->fk_email_template = $modelmail; + if ($remindertype == 'email') { + $actionCommReminder->fk_email_template = $modelmail; + } // the notification must be created for every user assigned to the event - foreach ($object->userassigned as $userassigned) - { + foreach ($object->userassigned as $userassigned) { $actionCommReminder->fk_user = $userassigned['id']; $res = $actionCommReminder->create($user); @@ -427,12 +435,10 @@ if (empty($reshook) && $action == 'add') $db->commit(); } - if (!empty($backtopage)) - { + if (!empty($backtopage)) { dol_syslog("Back to ".$backtopage.($moreparam ? (preg_match('/\?/', $backtopage) ? '&'.$moreparam : '?'.$moreparam) : '')); header("Location: ".$backtopage.($moreparam ? (preg_match('/\?/', $backtopage) ? '&'.$moreparam : '?'.$moreparam) : '')); - } elseif ($idaction) - { + } elseif ($idaction) { header("Location: ".DOL_URL_ROOT.'/comm/action/card.php?id='.$idaction.($moreparam ? '&'.$moreparam : '')); } else { header("Location: ".DOL_URL_ROOT.'/comm/action/index.php'.($moreparam ? '?'.$moreparam : '')); @@ -457,10 +463,8 @@ if (empty($reshook) && $action == 'add') /* * Action update event */ -if (empty($reshook) && $action == 'update') -{ - if (empty($cancel)) - { +if (empty($reshook) && $action == 'update') { + if (empty($cancel)) { $fulldayevent = GETPOST('fullday'); $aphour = GETPOST('aphour', 'int'); $apmin = GETPOST('apmin', 'int'); @@ -469,10 +473,18 @@ if (empty($reshook) && $action == 'update') $percentage = in_array(GETPOST('status'), array(-1, 100)) ?GETPOST('status') : (in_array(GETPOST('complete'), array(-1, 100)) ?GETPOST('complete') : GETPOST("percentage")); // If status is -1 or 100, percentage is not defined and we must use status // Clean parameters - if ($aphour == -1) $aphour = '0'; - if ($apmin == -1) $apmin = '0'; - if ($p2hour == -1) $p2hour = '0'; - if ($p2min == -1) $p2min = '0'; + if ($aphour == -1) { + $aphour = '0'; + } + if ($apmin == -1) { + $apmin = '0'; + } + if ($p2hour == -1) { + $p2hour = '0'; + } + if ($p2min == -1) { + $p2min = '0'; + } $object->fetch($id); $object->fetch_optionals(); @@ -493,7 +505,9 @@ if (empty($reshook) && $action == 'update') $object->socid = GETPOST("socid", "int"); $socpeopleassigned = GETPOST("socpeopleassigned", 'array'); $object->socpeopleassigned = array(); - foreach ($socpeopleassigned as $cid) $object->socpeopleassigned[$cid] = array('id' => $cid); + foreach ($socpeopleassigned as $cid) { + $object->socpeopleassigned[$cid] = array('id' => $cid); + } $object->contact_id = GETPOST("contactid", 'int'); if (empty($object->contact_id) && !empty($object->socpeopleassigned)) { reset($object->socpeopleassigned); @@ -503,8 +517,7 @@ if (empty($reshook) && $action == 'update') $object->note_private = trim(GETPOST("note", "restricthtml")); $object->fk_element = GETPOST("fk_element", "int"); $object->elementtype = GETPOST("elementtype", "alphanohtml"); - if (!$datef && $percentage == 100) - { + if (!$datef && $percentage == 100) { $error++; $donotclearsession = 1; setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), $object->errors, 'errors'); $action = 'edit'; @@ -514,23 +527,26 @@ if (empty($reshook) && $action == 'update') // Users $listofuserid = array(); - if (!empty($_SESSION['assignedtouser'])) // Now concat assigned users - { + if (!empty($_SESSION['assignedtouser'])) { // Now concat assigned users // Restore array with key with same value than param 'id' $tmplist1 = json_decode($_SESSION['assignedtouser'], true); - foreach ($tmplist1 as $key => $val) - { - if ($val['id'] > 0 && $val['id'] != $assignedtouser) $listofuserid[$val['id']] = $val; + foreach ($tmplist1 as $key => $val) { + if ($val['id'] > 0 && $val['id'] != $assignedtouser) { + $listofuserid[$val['id']] = $val; + } } } else { $assignedtouser = (!empty($object->userownerid) && $object->userownerid > 0 ? $object->userownerid : 0); - if ($assignedtouser) $listofuserid[$assignedtouser] = array('id'=>$assignedtouser, 'mandatory'=>0, 'transparency'=>($user->id == $assignedtouser ? $transparency : '')); // Owner first + if ($assignedtouser) { + $listofuserid[$assignedtouser] = array('id'=>$assignedtouser, 'mandatory'=>0, 'transparency'=>($user->id == $assignedtouser ? $transparency : '')); // Owner first + } } $object->userassigned = array(); $object->userownerid = 0; // Clear old content $i = 0; - foreach ($listofuserid as $key => $val) - { - if ($i == 0) $object->userownerid = $val['id']; + foreach ($listofuserid as $key => $val) { + if ($i == 0) { + $object->userownerid = $val['id']; + } $object->userassigned[$val['id']] = array('id'=>$val['id'], 'mandatory'=>0, 'transparency'=>($user->id == $val['id'] ? $transparency : '')); $i++; } @@ -538,22 +554,21 @@ if (empty($reshook) && $action == 'update') $object->transparency = $transparency; // We set transparency on event (even if we can also store it on each user, standard says this property is for event) // TODO store also transparency on owner user - if (!empty($conf->global->AGENDA_ENABLE_DONEBY)) - { - if (GETPOST("doneby")) $object->userdoneid = GETPOST("doneby", "int"); + if (!empty($conf->global->AGENDA_ENABLE_DONEBY)) { + if (GETPOST("doneby")) { + $object->userdoneid = GETPOST("doneby", "int"); + } } // Check parameters - if (GETPOSTISSET('actioncode') && !GETPOST('actioncode', 'aZ09')) // actioncode is '0' - { + if (GETPOSTISSET('actioncode') && !GETPOST('actioncode', 'aZ09')) { // actioncode is '0' $error++; $donotclearsession = 1; $action = 'edit'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); } else { $result = $cactioncomm->fetch(GETPOST('actioncode', 'aZ09')); } - if (empty($object->userownerid)) - { + if (empty($object->userownerid)) { $error++; $donotclearsession = 1; $action = 'edit'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ActionsOwnedBy")), null, 'errors'); @@ -561,7 +576,9 @@ if (empty($reshook) && $action == 'update') // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } if (!$error) { // check if an event resource is already in use @@ -622,23 +639,19 @@ if (empty($reshook) && $action == 'update') } } - if (!$error) - { + if (!$error) { $db->begin(); $result = $object->update($user); - if ($result > 0) - { + if ($result > 0) { // Category association $categories = GETPOST('categories', 'array'); $object->setCategories($categories); $object->loadReminders(); - if (!empty($object->reminders) && $object->datep > dol_now()) - { - foreach ($object->reminders as $reminder) - { + if (!empty($object->reminders) && $object->datep > dol_now()) { + foreach ($object->reminders as $reminder) { $reminder->delete($user); } $object->reminders = array(); @@ -656,11 +669,12 @@ if (empty($reshook) && $action == 'update') $actionCommReminder->offsetvalue = $offsetvalue; $actionCommReminder->status = $actionCommReminder::STATUS_TODO; $actionCommReminder->fk_actioncomm = $object->id; - if ($remindertype == 'email') $actionCommReminder->fk_email_template = $modelmail; + if ($remindertype == 'email') { + $actionCommReminder->fk_email_template = $modelmail; + } // the notification must be created for every user assigned to the event - foreach ($object->userassigned as $userassigned) - { + foreach ($object->userassigned as $userassigned) { $actionCommReminder->fk_user = $userassigned['id']; $res = $actionCommReminder->create($user); @@ -677,8 +691,11 @@ if (empty($reshook) && $action == 'update') unset($_SESSION['assignedtouser']); - if (!$error) $db->commit(); - else $db->rollback(); + if (!$error) { + $db->commit(); + } else { + $db->rollback(); + } } else { setEventMessages($object->error, $object->errors, 'errors'); $db->rollback(); @@ -686,10 +703,8 @@ if (empty($reshook) && $action == 'update') } } - if (!$error) - { - if (!empty($backtopage)) - { + if (!$error) { + if (!empty($backtopage)) { unset($_SESSION['assignedtouser']); header("Location: ".$backtopage); exit; @@ -700,20 +715,17 @@ if (empty($reshook) && $action == 'update') /* * delete event */ -if (empty($reshook) && $action == 'confirm_delete' && GETPOST("confirm") == 'yes') -{ +if (empty($reshook) && $action == 'confirm_delete' && GETPOST("confirm") == 'yes') { $object->fetch($id); $object->fetch_optionals(); $object->fetch_userassigned(); $object->oldcopy = clone $object; if ($user->rights->agenda->myactions->delete - || $user->rights->agenda->allactions->delete) - { + || $user->rights->agenda->allactions->delete) { $result = $object->delete(); - if ($result >= 0) - { + if ($result >= 0) { header("Location: index.php"); exit; } else { @@ -726,25 +738,23 @@ if (empty($reshook) && $action == 'confirm_delete' && GETPOST("confirm") == 'yes * Action move update, used when user move an event in calendar by drag'n drop * TODO Move this into page comm/action/index that trigger this call by the drag and drop of event. */ -if (empty($reshook) && GETPOST('actionmove', 'alpha') == 'mupdate') -{ +if (empty($reshook) && GETPOST('actionmove', 'alpha') == 'mupdate') { $error = 0; - $shour = dol_print_date($object->datep, "%H"); - $smin = dol_print_date($object->datep, "%M"); + $shour = dol_print_date($object->datep, "%H", 'tzuserrel'); // We take the date visible by user $newdate is also date visible by user. + $smin = dol_print_date($object->datep, "%M", 'tzuserrel'); $newdate = GETPOST('newdate', 'alpha'); - if (empty($newdate) || strpos($newdate, 'dayevent_') != 0) - { + if (empty($newdate) || strpos($newdate, 'dayevent_') != 0) { header("Location: ".$backtopage); exit; } - $datep = dol_mktime($shour, $smin, 0, substr($newdate, 13, 2), substr($newdate, 15, 2), substr($newdate, 9, 4)); - if ($datep != $object->datep) - { - if (!empty($object->datef)) - { + $datep = dol_mktime($shour, $smin, 0, substr($newdate, 13, 2), substr($newdate, 15, 2), substr($newdate, 9, 4), 'tzuserrel'); + //print dol_print_date($datep, 'dayhour');exit; + + if ($datep != $object->datep) { + if (!empty($object->datef)) { $object->datef += $datep - $object->datep; } $object->datep = $datep; @@ -820,8 +830,7 @@ if (empty($reshook) && GETPOST('actionmove', 'alpha') == 'mupdate') } } } - if (!empty($backtopage)) - { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } else { @@ -855,21 +864,20 @@ $arrayrecurrulefreq = array( $help_url = 'EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda'; llxHeader('', $langs->trans("Agenda"), $help_url); -if ($action == 'create') -{ +if ($action == 'create') { $contact = new Contact($db); $socpeopleassigned = GETPOST("socpeopleassigned", 'array'); - if (!empty($socpeopleassigned[0])) - { + if (!empty($socpeopleassigned[0])) { $result = $contact->fetch($socpeopleassigned[0]); - if ($result < 0) dol_print_error($db, $contact->error); + if ($result < 0) { + dol_print_error($db, $contact->error); + } } dol_set_focus("#label"); - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print "\n".''."\n"; - foreach ($showextcals as $val) - { + foreach ($showextcals as $val) { $htmlname = md5($val['name']); $s .= '
     
    '; } @@ -534,31 +586,41 @@ if (!empty($conf->use_javascript_ajax)) // If javascript on // Calendars from hooks $parameters = array(); $object = null; $reshook = $hookmanager->executeHooks('addCalendarChoice', $parameters, $object, $action); - if (empty($reshook)) - { + if (empty($reshook)) { $s .= $hookmanager->resPrint; - } elseif ($reshook > 1) - { + } elseif ($reshook > 1) { $s = $hookmanager->resPrint; } + + $s .= "\n".''."\n"; } else // If javascript off { $newparam = $param; // newparam is for birthday links $newparam = preg_replace('/showbirthday=[0-1]/i', 'showbirthday='.(empty($showbirthday) ? 1 : 0), $newparam); - if (!preg_match('/showbirthday=/i', $newparam)) $newparam .= '&showbirthday=1'; + if (!preg_match('/showbirthday=/i', $newparam)) { + $newparam .= '&showbirthday=1'; + } $link = '
    '; - if (empty($showbirthday)) $link .= $langs->trans("AgendaShowBirthdayEvents"); - else $link .= $langs->trans("AgendaHideBirthdayEvents"); + if (empty($showbirthday)) { + $link .= $langs->trans("AgendaShowBirthdayEvents"); + } else { + $link .= $langs->trans("AgendaHideBirthdayEvents"); + } $link .= ''; } + // Load events from database into $eventarray $eventarray = array(); + +// DEFAULT CALENDAR + AUTOEVENT CALENDAR + CONFERENCEBOOTH CALENDAR $sql = 'SELECT '; -if ($usergroup > 0) $sql .= " DISTINCT"; +if ($usergroup > 0) { + $sql .= " DISTINCT"; +} $sql .= ' a.id, a.label,'; $sql .= ' a.datep,'; $sql .= ' a.datep2,'; @@ -567,33 +629,46 @@ $sql .= ' a.fk_user_author,a.fk_user_action,'; $sql .= ' a.transparency, a.priority, a.fulldayevent, a.location,'; $sql .= ' a.fk_soc, a.fk_contact, a.fk_project,'; $sql .= ' a.fk_element, a.elementtype,'; -$sql .= ' ca.code as type_code, ca.libelle as type_label, ca.color as type_color'; +$sql .= ' ca.code as type_code, ca.libelle as type_label, ca.color as type_color, ca.type as type_type, ca.picto as type_picto'; $sql .= ' FROM '.MAIN_DB_PREFIX.'c_actioncomm as ca, '.MAIN_DB_PREFIX."actioncomm as a"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; +} // We must filter on resource table -if ($resourceid > 0) $sql .= ", ".MAIN_DB_PREFIX."element_resources as r"; +if ($resourceid > 0) { + $sql .= ", ".MAIN_DB_PREFIX."element_resources as r"; +} // We must filter on assignement table -if ($filtert > 0 || $usergroup > 0) $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar"; -if ($usergroup > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_user = ar.fk_element"; +if ($filtert > 0 || $usergroup > 0) { + $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar"; +} +if ($usergroup > 0) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_user = ar.fk_element"; +} $sql .= ' WHERE a.fk_action = ca.id'; $sql .= ' AND a.entity IN ('.getEntity('agenda').')'; // Condition on actioncode -if (!empty($actioncode)) -{ - if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) - { - if ($actioncode == 'AC_NON_AUTO') $sql .= " AND ca.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND ca.type = 'systemauto'"; - else { - if ($actioncode == 'AC_OTH') $sql .= " AND ca.type != 'systemauto'"; - if ($actioncode == 'AC_OTH_AUTO') $sql .= " AND ca.type = 'systemauto'"; +if (!empty($actioncode)) { + if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) { + if ($actioncode == 'AC_NON_AUTO') { + $sql .= " AND ca.type != 'systemauto'"; + } elseif ($actioncode == 'AC_ALL_AUTO') { + $sql .= " AND ca.type = 'systemauto'"; + } else { + if ($actioncode == 'AC_OTH') { + $sql .= " AND ca.type != 'systemauto'"; + } + if ($actioncode == 'AC_OTH_AUTO') { + $sql .= " AND ca.type = 'systemauto'"; + } } } else { - if ($actioncode == 'AC_NON_AUTO') $sql .= " AND ca.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND ca.type = 'systemauto'"; - else { - if (is_array($actioncode)) - { + if ($actioncode == 'AC_NON_AUTO') { + $sql .= " AND ca.type != 'systemauto'"; + } elseif ($actioncode == 'AC_ALL_AUTO') { + $sql .= " AND ca.type = 'systemauto'"; + } else { + if (is_array($actioncode)) { $sql .= " AND ca.code IN ('".implode("','", $actioncode)."')"; } else { $sql .= " AND ca.code IN ('".implode("','", explode(',', $actioncode))."')"; @@ -601,15 +676,24 @@ if (!empty($actioncode)) } } } -if ($resourceid > 0) $sql .= " AND r.element_type = 'action' AND r.element_id = a.id AND r.resource_id = ".$db->escape($resourceid); -if ($pid) $sql .= " AND a.fk_project=".$db->escape($pid); -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")"; -if ($socid > 0) $sql .= ' AND a.fk_soc = '.$socid; +if ($resourceid > 0) { + $sql .= " AND r.element_type = 'action' AND r.element_id = a.id AND r.resource_id = ".$db->escape($resourceid); +} +if ($pid) { + $sql .= " AND a.fk_project=".$db->escape($pid); +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")"; +} +if ($socid > 0) { + $sql .= ' AND a.fk_soc = '.$socid; +} // We must filter on assignement table -if ($filtert > 0 || $usergroup > 0) $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; +if ($filtert > 0 || $usergroup > 0) { + $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; +} //var_dump($day.' '.$month.' '.$year); -if ($action == 'show_day') -{ +if ($action == 'show_day') { $sql .= " AND ("; $sql .= " (a.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year, 'tzuserrel'))."'"; $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year, 'tzuserrel'))."')"; @@ -633,18 +717,33 @@ if ($action == 'show_day') $sql .= " AND a.datep2 > '".$db->idate(dol_mktime(23, 59, 59, $month, 28, $year) + (60 * 60 * 24 * 10))."')"; $sql .= ')'; } -if ($type) $sql .= " AND ca.id = ".$type; -if ($status == '0') { $sql .= " AND a.percent = 0"; } -if ($status == '-1') { $sql .= " AND a.percent = -1"; } // Not applicable -if ($status == '50') { $sql .= " AND (a.percent > 0 AND a.percent < 100)"; } // Running already started -if ($status == 'done' || $status == '100') { $sql .= " AND (a.percent = 100)"; } -if ($status == 'todo') { $sql .= " AND (a.percent >= 0 AND a.percent < 100)"; } +if ($type) { + $sql .= " AND ca.id = ".$type; +} +if ($status == '0') { + $sql .= " AND a.percent = 0"; +} +if ($status == '-1') { + $sql .= " AND a.percent = -1"; +} // Not applicable +if ($status == '50') { + $sql .= " AND (a.percent > 0 AND a.percent < 100)"; +} // Running already started +if ($status == 'done' || $status == '100') { + $sql .= " AND (a.percent = 100)"; +} +if ($status == 'todo') { + $sql .= " AND (a.percent >= 0 AND a.percent < 100)"; +} // We must filter on assignement table -if ($filtert > 0 || $usergroup > 0) -{ +if ($filtert > 0 || $usergroup > 0) { $sql .= " AND ("; - if ($filtert > 0) $sql .= "ar.fk_element = ".$filtert; - if ($usergroup > 0) $sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup; + if ($filtert > 0) { + $sql .= "ar.fk_element = ".$filtert; + } + if ($usergroup > 0) { + $sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup; + } $sql .= ")"; } // Sort on date @@ -654,19 +753,16 @@ $sql .= ' ORDER BY datep'; dol_syslog("comm/action/index.php", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $MAXONSAMEPAGE = 10000; // Useless to have more. Protection to avoid memory overload when high number of event (for example after a mass import) $i = 0; - while ($i < $num && $i < $MAXONSAMEPAGE) - { + while ($i < $num && $i < $MAXONSAMEPAGE) { $obj = $db->fetch_object($resql); // Discard auto action if option is on - if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') - { + if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') { $i++; continue; } @@ -685,13 +781,17 @@ if ($resql) $event->type_code = $obj->type_code; $event->type_label = $obj->type_label; $event->type_color = $obj->type_color; + $event->type = $obj->type_type; + $event->type_picto = $obj->type_picto; $event->libelle = $obj->label; // deprecated $event->label = $obj->label; $event->percentage = $obj->percent; + $event->authorid = $obj->fk_user_author; // user id of creator $event->userownerid = $obj->fk_user_action; // user id of owner $event->fetch_userassigned(); // This load $event->userassigned + $event->priority = $obj->priority; $event->fulldayevent = $obj->fulldayevent; $event->location = $obj->location; @@ -707,11 +807,13 @@ if ($resql) // Defined date_start_in_calendar and date_end_in_calendar property // They are date start and end of action but modified to not be outside calendar view. $event->date_start_in_calendar = $event->datep; - if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; - else $event->date_end_in_calendar = $event->datep; + if ($event->datef != '' && $event->datef >= $event->datep) { + $event->date_end_in_calendar = $event->datef; + } else { + $event->date_end_in_calendar = $event->datep; + } // Define ponctual property - if ($event->date_start_in_calendar == $event->date_end_in_calendar) - { + if ($event->date_start_in_calendar == $event->date_end_in_calendar) { $event->ponctuel = 1; } @@ -719,8 +821,12 @@ if ($resql) if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow) { // This record is out of visible range } else { - if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; - if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); + if ($event->date_start_in_calendar < $firstdaytoshow) { + $event->date_start_in_calendar = $firstdaytoshow; + } + if ($event->date_end_in_calendar >= $lastdaytoshow) { + $event->date_end_in_calendar = ($lastdaytoshow - 1); + } // Add an entry in actionarray for each day $daycursor = $event->date_start_in_calendar; @@ -740,7 +846,9 @@ if ($resql) $j++; $daykey += 60 * 60 * 24; - if ($daykey > $event->date_end_in_calendar) $loop = false; + if ($daykey > $event->date_end_in_calendar) { + $loop = false; + } } while ($loop); //print 'Event '.$i.' id='.$event->id.' (start='.dol_print_date($event->datep).'-end='.dol_print_date($event->datef); @@ -752,16 +860,15 @@ if ($resql) dol_print_error($db); } +// BIRTHDATES CALENDAR // Complete $eventarray with birthdates -if ($showbirthday) -{ +if ($showbirthday) { // Add events in array $sql = 'SELECT sp.rowid, sp.lastname, sp.firstname, sp.birthday'; $sql .= ' FROM '.MAIN_DB_PREFIX.'socpeople as sp'; $sql .= ' WHERE (priv=0 OR (priv=1 AND fk_user_creat='.$user->id.'))'; $sql .= " AND sp.entity IN (".getEntity('socpeople').")"; - if ($action == 'show_day') - { + if ($action == 'show_day') { $sql .= ' AND MONTH(birthday) = '.$month; $sql .= ' AND DAY(birthday) = '.$day; } else { @@ -771,13 +878,12 @@ if ($showbirthday) dol_syslog("comm/action/index.php", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); + $event = new ActionComm($db); $event->id = $obj->rowid; // We put contact id in action id for birthdays events @@ -788,28 +894,39 @@ if ($showbirthday) $datearray = dol_getdate($datebirth, true); $event->datep = dol_mktime(0, 0, 0, $datearray['mon'], $datearray['mday'], $year, true); // For full day events, date are also GMT but they wont but converted during output $event->datef = $event->datep; + $event->type_code = 'BIRTHDAY'; + $event->type_label = ''; + $event->type_color = ''; + $event->type = 'birthdate'; + $event->type_picto = 'birthdate'; + $event->label = $langs->trans("Birthday").' '.dolGetFirstLastname($obj->firstname, $obj->lastname); $event->percentage = 100; $event->fulldayevent = 1; - $event->date_start_in_calendar = $event->datep; - $event->date_end_in_calendar = $event->datef; + $event->date_start_in_calendar = $db->jdate($event->datep); + $event->date_end_in_calendar = $db->jdate($event->datef); $event->ponctuel = 0; - // Add an entry in actionarray for each day - $daycursor = $event->date_start_in_calendar; - $annee = dol_print_date($daycursor, '%Y'); - $mois = dol_print_date($daycursor, '%m'); - $jour = dol_print_date($daycursor, '%d'); + // Add an entry in eventarray for each day + $daycursor = $event->datep; + $annee = dol_print_date($daycursor, '%Y', 'tzuserrel'); + $mois = dol_print_date($daycursor, '%m', 'tzuserrel'); + $jour = dol_print_date($daycursor, '%d', 'tzuserrel'); - $loop = true; + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee, 'gmt'); + + $eventarray[$daykey][] = $event; + + /*$loop = true; $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); do { $eventarray[$daykey][] = $event; $daykey += 60 * 60 * 24; if ($daykey > $event->date_end_in_calendar) $loop = false; } while ($loop); + */ $i++; } } else { @@ -817,130 +934,116 @@ if ($showbirthday) } } -if ($conf->global->AGENDA_SHOW_HOLIDAYS) -{ - $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.statut, x.rowid, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.statut as status"; - $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u"; - $sql .= " WHERE u.rowid = x.fk_user"; - $sql .= " AND u.statut = '1'"; // Show only active users (0 = inactive user, 1 = active user) - $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved) +$sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.statut, x.rowid, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.statut as status"; +$sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u"; +$sql .= " WHERE u.rowid = x.fk_user"; +$sql .= " AND u.statut = '1'"; // Show only active users (0 = inactive user, 1 = active user) +$sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved) - if ($action == 'show_day') - { - // Request only leaves for the current selected day - $sql .= " AND '".$db->escape($year)."-".$db->escape($month)."-".$db->escape($day)."' BETWEEN x.date_debut AND x.date_fin"; - } elseif ($action == 'show_week') - { - // TODO: Add filter to reduce database request - } elseif ($action == 'show_month') - { - // TODO: Add filter to reduce database request - } +if ($action == 'show_day') { + // Request only leaves for the current selected day + $sql .= " AND '".$db->escape($year)."-".$db->escape($month)."-".$db->escape($day)."' BETWEEN x.date_debut AND x.date_fin"; // date_debut and date_fin are date wihout time +} elseif ($action == 'show_week') { + // TODO: Add filter to reduce database request +} elseif ($action == 'show_month') { + // TODO: Add filter to reduce database request +} - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; +$resql = $db->query($sql); +if ($resql) { + $num = $db->num_rows($resql); + $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); + while ($i < $num) { + $obj = $db->fetch_object($resql); - $dateStartArray = dol_getdate(dol_stringtotime($obj->date_start, 1), true); - $dateEndArray = dol_getdate(dol_stringtotime($obj->date_end, 1), true); + $event = new ActionComm($db); - $event = new ActionComm($db); + // Need the id of the leave object for link to it + $event->id = $obj->rowid; + $event->ref = $event->id; - // Need the id of the leave object for link to it - $event->id = $obj->rowid; - $event->ref = $event->id; + $event->type_code = 'HOLIDAY'; + $event->type_label = ''; + $event->type_color = ''; + $event->type = 'holiday'; + $event->type_picto = 'holiday'; - $event->type_code = 'HOLIDAY'; - $event->datep = dol_mktime(0, 0, 0, $dateStartArray['mon'], $dateStartArray['mday'], $dateStartArray['year'], true); - $event->datef = dol_mktime(0, 0, 0, $dateEndArray['mon'], $dateEndArray['mday'], $dateEndArray['year'], true); - $event->date_start_in_calendar = $event->datep; - $event->date_end_in_calendar = $event->datef; + $event->datep = $db->jdate($obj->date_start); + $event->datef = $db->jdate($obj->date_end); + $event->date_start_in_calendar = $event->datep; + $event->date_end_in_calendar = $event->datef; - if ($obj->status == 3) - { - // Show no symbol for leave with state "leave approved" - $event->percentage = -1; - } elseif ($obj->status == 2) - { - // Show TO-DO symbol for leave with state "leave wait for approval" - $event->percentage = 0; - } - - if ($obj->halfday == 1) - { - $event->label = $obj->lastname.' ('.$langs->trans("Morning").')'; - } elseif ($obj->halfday == -1) - { - $event->label = $obj->lastname.' ('.$langs->trans("Afternoon").')'; - } else { - $event->label = $obj->lastname; - } - - $daycursor = $event->date_start_in_calendar; - $annee = dol_print_date($daycursor, '%Y'); - $mois = dol_print_date($daycursor, '%m'); - $jour = dol_print_date($daycursor, '%d'); - - $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); - - do { - $eventarray[$daykey][] = $event; - - $daykey += 60 * 60 * 24; - } while ($daykey <= $event->date_end_in_calendar); - - $i++; + if ($obj->status == 3) { + // Show no symbol for leave with state "leave approved" + $event->percentage = -1; + } elseif ($obj->status == 2) { + // Show TO-DO symbol for leave with state "leave wait for approval" + $event->percentage = 0; } + + if ($obj->halfday == 1) { + $event->label = $obj->lastname.' ('.$langs->trans("Morning").')'; + } elseif ($obj->halfday == -1) { + $event->label = $obj->lastname.' ('.$langs->trans("Afternoon").')'; + } else { + $event->label = $obj->lastname; + } + + $daycursor = $event->date_start_in_calendar; + $annee = dol_print_date($daycursor, '%Y', 'tzuserrel'); + $mois = dol_print_date($daycursor, '%m', 'tzuserrel'); + $jour = dol_print_date($daycursor, '%d', 'tzuserrel'); + + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee, 'gmt'); + do { + $eventarray[$daykey][] = $event; + + $daykey += 60 * 60 * 24; + } while ($daykey <= $event->date_end_in_calendar); + + $i++; } } +// EXTERNAL CALENDAR // Complete $eventarray with external import Ical -if (count($listofextcals)) -{ +if (count($listofextcals)) { require_once DOL_DOCUMENT_ROOT.'/comm/action/class/ical.class.php'; - foreach ($listofextcals as $extcal) - { + foreach ($listofextcals as $extcal) { $url = $extcal['src']; // Example: https://www.google.com/calendar/ical/eldy10%40gmail.com/private-cde92aa7d7e0ef6110010a821a2aaeb/basic.ics $namecal = $extcal['name']; $offsettz = $extcal['offsettz']; $colorcal = $extcal['color']; $buggedfile = $extcal['buggedfile']; - //print "url=".$url." namecal=".$namecal." colorcal=".$colorcal." buggedfile=".$buggedfile; + $ical = new ICal(); $ical->parse($url); // After this $ical->cal['VEVENT'] contains array of events, $ical->cal['DAYLIGHT'] contains daylight info, $ical->cal['STANDARD'] contains non daylight info, ... //var_dump($ical->cal); exit; $icalevents = array(); - if (is_array($ical->get_event_list())) $icalevents = array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT'] - if (is_array($ical->get_freebusy_list())) $icalevents = array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY'] + if (is_array($ical->get_event_list())) { + $icalevents = array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT'] + } + if (is_array($ical->get_freebusy_list())) { + $icalevents = array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY'] + } - if (count($icalevents) > 0) - { + if (count($icalevents) > 0) { // Duplicate all repeatable events into new entries $moreicalevents = array(); - foreach ($icalevents as $icalevent) - { - if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) //repeatable event - { + foreach ($icalevents as $icalevent) { + if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) { //repeatable event //if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow; //if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow-1); - if ($icalevent['DTSTART;VALUE=DATE']) //fullday event - { + if ($icalevent['DTSTART;VALUE=DATE']) { //fullday event $datecurstart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); $datecurend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day - } elseif (is_array($icalevent['DTSTART']) && !empty($icalevent['DTSTART']['unixtime'])) - { + } elseif (is_array($icalevent['DTSTART']) && !empty($icalevent['DTSTART']['unixtime'])) { $datecurstart = $icalevent['DTSTART']['unixtime']; $datecurend = $icalevent['DTEND']['unixtime']; - if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart) - { + if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart) { //var_dump($ical->cal); $tmpcurstart = $datecurstart; $tmpcurend = $datecurend; @@ -948,10 +1051,16 @@ if (count($listofextcals)) $tmpdaylightend = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['STANDARD']['DTSTART']; //var_dump($tmpcurstart);var_dump($tmpcurend); var_dump($ical->cal['DAYLIGHT']['DTSTART']);var_dump($ical->cal['STANDARD']['DTSTART']); // Edit datecurstart and datecurend - if ($tmpcurstart >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurstart -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; - else $datecurstart -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; - if ($tmpcurend >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurend -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; - else $datecurend -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; + if ($tmpcurstart >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) { + $datecurstart -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; + } else { + $datecurstart -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; + } + if ($tmpcurend >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) { + $datecurend -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; + } else { + $datecurend -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; + } } // datecurstart and datecurend are now GMT date //var_dump($datecurstart); var_dump($datecurend); exit; @@ -965,18 +1074,19 @@ if (count($listofextcals)) $interval = (empty($icalevent['RRULE']['INTERVAL']) ? 1 : $icalevent['RRULE']['INTERVAL']); $until = empty($icalevent['RRULE']['UNTIL']) ? 0 : dol_stringtotime($icalevent['RRULE']['UNTIL'], 1); $maxrepeat = empty($icalevent['RRULE']['COUNT']) ? 0 : $icalevent['RRULE']['COUNT']; - if ($until && ($until + ($datecurend - $datecurstart)) < $firstdaytoshow) continue; // We discard repeatable event that end before start date to show - if ($datecurstart >= $lastdaytoshow) continue; // We discard repeatable event that start after end date to show + if ($until && ($until + ($datecurend - $datecurstart)) < $firstdaytoshow) { + continue; // We discard repeatable event that end before start date to show + } + if ($datecurstart >= $lastdaytoshow) { + continue; // We discard repeatable event that start after end date to show + } $numofevent = 0; - while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) - { - if ($datecurend >= $firstdaytoshow) // We add event - { + while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) { + if ($datecurend >= $firstdaytoshow) { // We add event $newevent = $icalevent; unset($newevent['RRULE']); - if ($icalevent['DTSTART;VALUE=DATE']) - { + if ($icalevent['DTSTART;VALUE=DATE']) { $newevent['DTSTART;VALUE=DATE'] = dol_print_date($datecurstart, '%Y%m%d'); $newevent['DTEND;VALUE=DATE'] = dol_print_date($datecurend + 1, '%Y%m%d'); } else { @@ -988,27 +1098,22 @@ if (count($listofextcals)) // Jump on next occurence $numofevent++; $savdatecurstart = $datecurstart; - if ($icalevent['RRULE']['FREQ'] == 'DAILY') - { + if ($icalevent['RRULE']['FREQ'] == 'DAILY') { $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'd'); $datecurend = dol_time_plus_duree($datecurend, $interval, 'd'); } - if ($icalevent['RRULE']['FREQ'] == 'WEEKLY') - { + if ($icalevent['RRULE']['FREQ'] == 'WEEKLY') { $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'w'); $datecurend = dol_time_plus_duree($datecurend, $interval, 'w'); - } elseif ($icalevent['RRULE']['FREQ'] == 'MONTHLY') - { + } elseif ($icalevent['RRULE']['FREQ'] == 'MONTHLY') { $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'm'); $datecurend = dol_time_plus_duree($datecurend, $interval, 'm'); - } elseif ($icalevent['RRULE']['FREQ'] == 'YEARLY') - { + } elseif ($icalevent['RRULE']['FREQ'] == 'YEARLY') { $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'y'); $datecurend = dol_time_plus_duree($datecurend, $interval, 'y'); } // Test to avoid infinite loop ($datecurstart must increase) - if ($savdatecurstart >= $datecurstart) - { + if ($savdatecurstart >= $datecurstart) { dol_syslog("Found a rule freq ".$icalevent['RRULE']['FREQ']." not managed by dolibarr code. Assume 1 week frequency.", LOG_ERR); $datecurstart += 3600 * 24 * 7; $datecurend += 3600 * 24 * 7; @@ -1019,27 +1124,30 @@ if (count($listofextcals)) $icalevents = array_merge($icalevents, $moreicalevents); // Loop on each entry into cal file to know if entry is qualified and add an ActionComm into $eventarray - foreach ($icalevents as $icalevent) - { + foreach ($icalevents as $icalevent) { //var_dump($icalevent); //print $icalevent['SUMMARY'].'->'.var_dump($icalevent).'
    ';exit; - if (!empty($icalevent['RRULE'])) continue; // We found a repeatable event. It was already split into unitary events, so we discard general rule. + if (!empty($icalevent['RRULE'])) { + continue; // We found a repeatable event. It was already split into unitary events, so we discard general rule. + } // Create a new object action $event = new ActionComm($db); $addevent = false; - if (isset($icalevent['DTSTART;VALUE=DATE'])) // fullday event - { + if (isset($icalevent['DTSTART;VALUE=DATE'])) { // fullday event // For full day events, date are also GMT but they wont but converted using tz during output $datestart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); - $dateend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day + if (empty($icalevent['DTEND;VALUE=DATE'])) { + $dateend = $datestart + 86400 - 1; + } else { + $dateend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day + } //print 'x'.$datestart.'-'.$dateend;exit; //print dol_print_date($dateend,'dayhour','gmt'); $event->fulldayevent = 1; $addevent = true; - } elseif (!is_array($icalevent['DTSTART'])) // not fullday event (DTSTART is not array. It is a value like '19700101T000000Z' for 00:00 in greenwitch) - { + } elseif (!is_array($icalevent['DTSTART'])) { // not fullday event (DTSTART is not array. It is a value like '19700101T000000Z' for 00:00 in greenwitch) $datestart = $icalevent['DTSTART']; $dateend = $icalevent['DTEND']; @@ -1049,8 +1157,7 @@ if (count($listofextcals)) $addevent = true; //var_dump($offsettz); //var_dump(dol_print_date($datestart, 'dayhour', 'gmt')); - } elseif (isset($icalevent['DTSTART']['unixtime'])) // File contains a local timezone + a TZ (for example when using bluemind) - { + } elseif (isset($icalevent['DTSTART']['unixtime'])) { // File contains a local timezone + a TZ (for example when using bluemind) $datestart = $icalevent['DTSTART']['unixtime']; $dateend = $icalevent['DTEND']['unixtime']; @@ -1058,13 +1165,11 @@ if (count($listofextcals)) $dateend += +($offsettz * 3600); // $buggedfile is set to uselocalandtznodaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtznodaylight' - if ($buggedfile === 'uselocalandtznodaylight') // unixtime is a local date that does not take daylight into account, TZID is +1 for example for 'Europe/Paris' in summer instead of 2 - { + if ($buggedfile === 'uselocalandtznodaylight') { // unixtime is a local date that does not take daylight into account, TZID is +1 for example for 'Europe/Paris' in summer instead of 2 // TODO } // $buggedfile is set to uselocalandtzdaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtzdaylight' (for example with bluemind) - if ($buggedfile === 'uselocalandtzdaylight') // unixtime is a local date that does take daylight into account, TZID is +2 for example for 'Europe/Paris' in summer - { + if ($buggedfile === 'uselocalandtzdaylight') { // unixtime is a local date that does take daylight into account, TZID is +2 for example for 'Europe/Paris' in summer $localtzs = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTSTART']['TZID'])); $localtze = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTEND']['TZID'])); $localdts = new DateTime(dol_print_date($datestart, 'dayrfc', 'gmt'), $localtzs); @@ -1078,19 +1183,20 @@ if (count($listofextcals)) $addevent = true; } - if ($addevent) - { + if ($addevent) { $event->id = $icalevent['UID']; $event->ref = $event->id; $userId = $userstatic->findUserIdByEmail($namecal); - if (!empty($userId) && $userId > 0) - { + if (!empty($userId) && $userId > 0) { $event->userassigned[$userId] = $userId; $event->percentage = -1; } - else { - $event->type_code = "ICALEVENT"; - } + + $event->type_code = "ICALEVENT"; + $event->type_label = $namecal; + $event->type_color = $colorcal; + $event->type = 'icalevent'; + $event->type_picto = 'rss'; $event->icalname = $namecal; $event->icalcolor = $colorcal; @@ -1098,21 +1204,30 @@ if (count($listofextcals)) $event->datep = $datestart + $usertime; $event->datef = $dateend + $usertime; - if ($icalevent['SUMMARY']) $event->label = $icalevent['SUMMARY']; - elseif ($icalevent['DESCRIPTION']) $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1); - else $event->label = $langs->trans("ExtSiteNoLabel"); + if ($icalevent['SUMMARY']) { + $event->label = $icalevent['SUMMARY']; + } elseif ($icalevent['DESCRIPTION']) { + $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1); + } else { + $event->label = $langs->trans("ExtSiteNoLabel"); + } // Priority (see https://www.kanzaki.com/docs/ical/priority.html) // LOW = 0 to 4 // MEDIUM = 5 // HIGH = 6 to 9 - if ($icalevent['PRIORITY']) $event->priority = $icalevent['PRIORITY']; + if (!empty($icalevent['PRIORITY'])) { + $event->priority = $icalevent['PRIORITY']; + } // Transparency (see https://www.kanzaki.com/docs/ical/transp.html) - if ($icalevent['TRANSP']) - { - if ($icalevent['TRANSP'] == "TRANSPARENT") $event->transparency = 0; // 0 = available / free - if ($icalevent['TRANSP'] == "OPAQUE") $event->transparency = 1; // 1 = busy + if ($icalevent['TRANSP']) { + if ($icalevent['TRANSP'] == "TRANSPARENT") { + $event->transparency = 0; // 0 = available / free + } + if ($icalevent['TRANSP'] == "OPAQUE") { + $event->transparency = 1; // 1 = busy + } // TODO: MS outlook states // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:TRANSPARENT => Available / Free @@ -1122,47 +1237,56 @@ if (count($listofextcals)) // X-MICROSOFT-CDO-BUSYSTATUS:OOF + TRANSP:OPAQUE => Away from the office / off-site } - if ($icalevent['LOCATION']) $event->location = $icalevent['LOCATION']; + if (!empty($icalevent['LOCATION'])) { + $event->location = $icalevent['LOCATION']; + } $event->date_start_in_calendar = $event->datep; - if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; - else $event->date_end_in_calendar = $event->datep; + if ($event->datef != '' && $event->datef >= $event->datep) { + $event->date_end_in_calendar = $event->datef; + } else { + $event->date_end_in_calendar = $event->datep; + } // Define ponctual property - if ($event->date_start_in_calendar == $event->date_end_in_calendar) - { + if ($event->date_start_in_calendar == $event->date_end_in_calendar) { $event->ponctuel = 1; //print 'x'.$datestart.'-'.$dateend;exit; } // Add event into $eventarray if date range are ok. - if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow) - { + if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow) { //print 'x'.$datestart.'-'.$dateend;exit; //print 'x'.$datestart.'-'.$dateend;exit; //print 'x'.$datestart.'-'.$dateend;exit; // This record is out of visible range } else { - if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; - if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); + if ($event->date_start_in_calendar < $firstdaytoshow) { + $event->date_start_in_calendar = $firstdaytoshow; + } + if ($event->date_end_in_calendar >= $lastdaytoshow) { + $event->date_end_in_calendar = ($lastdaytoshow - 1); + } // Add an entry in actionarray for each day $daycursor = $event->date_start_in_calendar; - $annee = date('Y', $daycursor); - $mois = date('m', $daycursor); - $jour = date('d', $daycursor); + $annee = dol_print_date($daycursor, '%Y', 'tzuserrel'); + $mois = dol_print_date($daycursor, '%m', 'tzuserrel'); + $jour = dol_print_date($daycursor, '%d', 'tzuserrel'); // Loop on each day covered by action to prepare an index to show on calendar $loop = true; $j = 0; // daykey must be date that represent day box in calendar so must be a user time - $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); - $daykeygmt = dol_mktime(0, 0, 0, $mois, $jour, $annee, true, 0); + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee, 'gmt'); + $daykeygmt = dol_mktime(0, 0, 0, $mois, $jour, $annee, 'gmt'); do { //if ($event->fulldayevent) print dol_print_date($daykeygmt,'dayhour','gmt').'-'.dol_print_date($daykey,'dayhour','gmt').'-'.dol_print_date($event->date_end_in_calendar,'dayhour','gmt').' '; $eventarray[$daykey][] = $event; $daykey += 60 * 60 * 24; $daykeygmt += 60 * 60 * 24; // Add one day - if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) $loop = false; + if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) { + $loop = false; + } } while ($loop); } } @@ -1186,8 +1310,7 @@ if (!empty($hookmanager->resArray['eventarray'])) { } // Sort events -foreach ($eventarray as $keyDate => &$dateeventarray) -{ +foreach ($eventarray as $keyDate => &$dateeventarray) { usort($dateeventarray, 'sort_events_by_date'); } @@ -1199,20 +1322,22 @@ $cacheusers = array(); // Define theme_datacolor array $color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/theme_vars.inc.php"; -if (is_readable($color_file)) -{ +if (is_readable($color_file)) { include_once $color_file; } -if (!is_array($theme_datacolor)) $theme_datacolor = array(array(120, 130, 150), array(200, 160, 180), array(190, 190, 220)); +if (!is_array($theme_datacolor)) { + $theme_datacolor = array(array(120, 130, 150), array(200, 160, 180), array(190, 190, 220)); +} +$massactionbutton =''; print_barre_liste($langs->trans("Agenda"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, -1, 'object_action', 0, $nav.''.$newcardbutton, '', $limit, 1, 0, 1, $viewmode); +// Show div with list of calendars print $s; -if (empty($action) || $action == 'show_month') // View by month -{ +if (empty($action) || $action == 'show_month') { // View by month $newparam = $param; // newparam is for birthday links $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done $newparam = preg_replace('/action=show_month&?/i', '', $newparam); @@ -1234,15 +1359,15 @@ if (empty($action) || $action == 'show_month') // View by month // Column title of weeks numbers echo '
    #'; $numdayinweek = (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7); - if (!empty($conf->dol_optimize_smallscreen)) - { + if (!empty($conf->dol_optimize_smallscreen)) { $labelshort = array(0=>'SundayMin', 1=>'MondayMin', 2=>'TuesdayMin', 3=>'WednesdayMin', 4=>'ThursdayMin', 5=>'FridayMin', 6=>'SaturdayMin'); print $langs->trans($labelshort[$numdayinweek]); - } else print $langs->trans("Day".$numdayinweek); + } else { + print $langs->trans("Day".$numdayinweek); + } print '
    '; show_day_events($db, $max_day_in_prev_month + $tmpday, $prev_month, $prev_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); echo " '; show_day_events($db, $tmpday, $month, $year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); @@ -1297,7 +1428,9 @@ if (empty($action) || $action == 'show_month') // View by month } else { /* Show days after the current month (next month) */ $style = 'cal_other_month'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; + if ($iter_day == 6) { + $style .= ' cal_other_month_right'; + } echo ' '; show_day_events($db, $tmpday - $max_day_in_month, $next_month, $next_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); echo "'; show_day_events($db, $tmpday, $tmpmonth, $tmpyear, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300); @@ -1379,7 +1518,9 @@ if (empty($action) || $action == 'show_month') // View by month $style = 'cal_current_month cal_current_month_oneday'; $today = 0; $todayarray = dol_getdate($now, 'fast'); - if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; + if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) { + $today = 1; + } //if ($today) $style='cal_today'; $timestamp = dol_mktime(12, 0, 0, $month, $day, $year); @@ -1397,12 +1538,12 @@ if (empty($action) || $action == 'show_month') // View by month echo "
    '; @@ -1410,8 +1551,7 @@ if (empty($action) || $action == 'show_month') // View by month /* WIP View per hour */ $useviewhour = 0; - if ($useviewhour) - { + if ($useviewhour) { print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table $maxheightwin = (isset($_SESSION["dol_screenheight"]) && $_SESSION["dol_screenheight"] > 500) ? ($_SESSION["dol_screenheight"] - 200) : 660; // Also into index.php file @@ -1424,14 +1564,19 @@ if (empty($action) || $action == 'show_month') // View by month $tmp = explode('-', $conf->global->MAIN_DEFAULT_WORKING_HOURS); $minhour = round($tmp[0], 0); $maxhour = round($tmp[1], 0); - if ($minhour > 23) $minhour = 23; - if ($maxhour < 1) $maxhour = 1; - if ($maxhour <= $minhour) { $maxhour = $minhour + 1; } + if ($minhour > 23) { + $minhour = 23; + } + if ($maxhour < 1) { + $maxhour = 1; + } + if ($maxhour <= $minhour) { + $maxhour = $minhour + 1; + } $i = 0; $j = 0; - while ($i < 24) - { + while ($i < 24) { echo '
    '."\n"; echo '
    '.dol_print_date($i * 3600, 'hour', 'gmt').'
    '; echo '
    '."\n"; @@ -1486,6 +1631,10 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa global $theme_datacolor; global $cachethirdparties, $cachecontacts, $cacheusers, $colorindexused; + if ($conf->use_javascript_ajax) { // Enable the "Show more button..." + $conf->global->MAIN_JS_SWITCH_AGENDA = 1; + } + $dateint = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); print "\n"; @@ -1493,26 +1642,26 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa $curtime = dol_mktime(0, 0, 0, $month, $day, $year); $urltoshow = DOL_URL_ROOT.'/comm/action/index.php?action=show_day&day='.str_pad($day, 2, "0", STR_PAD_LEFT).'&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year.$newparam; $urltocreate = ''; - if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) - { + if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) { $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; $hourminsec = '100000'; $urltocreate = DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.sprintf("%04d%02d%02d", $year, $month, $day).$hourminsec.'&backtopage='.urlencode($_SERVER["PHP_SELF"].($newparam ? '?'.$newparam : '')); } // Line with title of day - print '
    '."\n"; + print '
    '."\n"; - if ($nonew <= 0) - { - print '
    '; return; } @@ -1531,36 +1679,33 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print '
    '; //$curtime = dol_mktime (0, 0, 0, $month, $day, $year); - $i = 0; $numother = 0; $numbirthday = 0; $numical = 0; $numicals = array(); + $i = 0; $ireallyshown = 0; $itoshow = 0; $numother = 0; $numbirthday = 0; $numical = 0; $numicals = array(); $ymd = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); $colorindexused[$user->id] = 0; // Color index for current user (user->id) is always 0 $nextindextouse = is_array($colorindexused) ?count($colorindexused) : 0; // At first run this is 0, so fist user has 0, next 1, ... //var_dump($colorindexused); - foreach ($eventarray as $daykey => $notused) - { + include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; + $tmpholiday = new Holiday($db); + + foreach ($eventarray as $daykey => $notused) { $annee = dol_print_date($daykey, '%Y'); $mois = dol_print_date($daykey, '%m'); $jour = dol_print_date($daykey, '%d'); - if ($day == $jour && $month == $mois && $year == $annee) - { - foreach ($eventarray[$daykey] as $index => $event) - { - if ($i < $maxprint || $maxprint == 0 || !empty($conf->global->MAIN_JS_SWITCH_AGENDA)) - { + if ($day == $jour && $month == $mois && $year == $annee) { + foreach ($eventarray[$daykey] as $index => $event) { + if ($i < $maxprint || $maxprint == 0 || !empty($conf->global->MAIN_JS_SWITCH_AGENDA)) { $keysofuserassigned = array_keys($event->userassigned); $ponct = ($event->date_start_in_calendar == $event->date_end_in_calendar); // Define $color (Hex string like '0088FF') and $cssclass of event $color = -1; $cssclass = ''; $colorindex = -1; - if (in_array($user->id, $keysofuserassigned)) - { + if (in_array($user->id, $keysofuserassigned)) { $cssclass = 'family_mytasks'; - if (empty($cacheusers[$event->userownerid])) - { + if (empty($cacheusers[$event->userownerid])) { $newuser = new User($db); $newuser->fetch($event->userownerid); $cacheusers[$event->userownerid] = $newuser; @@ -1568,9 +1713,10 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa //var_dump($cacheusers[$event->userownerid]->color); // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) - if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; - } elseif ($event->type_code == 'ICALEVENT') // Event come from external ical file - { + if (!empty($cacheusers[$event->userownerid]->color)) { + $color = $cacheusers[$event->userownerid]->color; + } + } elseif ($event->type_code == 'ICALEVENT') { // Event come from external ical file $numical++; if (!empty($event->icalname)) { if (!isset($numicals[dol_string_nospecial($event->icalname)])) { @@ -1581,63 +1727,63 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa $color = ($event->icalcolor ? $event->icalcolor : -1); $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); - } elseif ($event->type_code == 'BIRTHDAY') - { - $numbirthday++; $colorindex = 2; $cssclass = 'family_birthday unmovable'; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); + } elseif ($event->type_code == 'BIRTHDAY') { + $numbirthday++; $colorindex = 2; $cssclass = 'family_birthday '; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); } else { $numother++; $color = ($event->icalcolor ? $event->icalcolor : -1); $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); - if (empty($cacheusers[$event->userownerid])) - { + if (empty($cacheusers[$event->userownerid])) { $newuser = new User($db); $newuser->fetch($event->userownerid); $cacheusers[$event->userownerid] = $newuser; } //var_dump($cacheusers[$event->userownerid]->color); - // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) - if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; + // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) + if (!empty($cacheusers[$event->userownerid]->color)) { + $color = $cacheusers[$event->userownerid]->color; + } } - if ($color < 0) // Color was not set on user card. Set color according to color index. - { + if ($color < 0) { // Color was not set on user card. Set color according to color index. // Define color index if not yet defined $idusertouse = ($event->userownerid ? $event->userownerid : 0); - if (isset($colorindexused[$idusertouse])) - { + if (isset($colorindexused[$idusertouse])) { $colorindex = $colorindexused[$idusertouse]; // Color already assigned to this user } else { - $colorindex = $nextindextouse; - $colorindexused[$idusertouse] = $colorindex; - if (!empty($theme_datacolor[$nextindextouse + 1])) $nextindextouse++; // Prepare to use next color + $colorindex = $nextindextouse; + $colorindexused[$idusertouse] = $colorindex; + if (!empty($theme_datacolor[$nextindextouse + 1])) { + $nextindextouse++; // Prepare to use next color + } } //print '|'.($color).'='.($idusertouse?$idusertouse:0).'='.$colorindex.'
    '; // Define color $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); } - $cssclass = $cssclass.' '.$cssclass.'_day_'.$ymd; + $cssclass = $cssclass.' eventday_'.$ymd; // Defined style to disable drag and drop feature - if ($event->type_code == 'AC_OTH_AUTO') - { + if ($event->type_code == 'AC_OTH_AUTO') { $cssclass .= " unmovable"; - } elseif ($event->type_code == 'ICALEVENT') - { + } elseif ($event->type_code == 'HOLIDAY') { + $cssclass .= " unmovable"; + } elseif ($event->type_code == 'BIRTHDAY') { + $cssclass .= " unmovable"; + } elseif ($event->type_code == 'ICALEVENT') { $cssclass .= " unmovable"; } elseif ($event->date_end_in_calendar && date('Ymd', $event->date_start_in_calendar) != date('Ymd', $event->date_end_in_calendar)) { $tmpyearend = date('Y', $event->date_end_in_calendar); $tmpmonthend = date('m', $event->date_end_in_calendar); $tmpdayend = date('d', $event->date_end_in_calendar); - if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) - { + if ($tmpyearend != $annee || $tmpmonthend != $mois || $tmpdayend != $jour) { $cssclass .= " unmovable"; } } else { if ($user->rights->agenda->allactions->create || - (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create)) - { + (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create)) { $cssclass .= " movable cursormove"; } else { $cssclass .= " unmovable"; @@ -1645,13 +1791,36 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa } $h = ''; $nowrapontd = 1; - if ($action == 'show_day') { $h = 'height: 100%; '; $nowrapontd = 0; } - if ($action == 'show_week') { $h = 'height: 100%; '; $nowrapontd = 0; } + if ($action == 'show_day') { + $h = 'height: 100%; '; $nowrapontd = 0; + } + if ($action == 'show_week') { + $h = 'height: 100%; '; $nowrapontd = 0; + } - // Show rect of event + // Show event box print "\n"; print ''."\n"; - print '
    = $maxprint) { + $morecss = 'showifmore'; + } + if ($event->type == 'birthdate' && !GETPOST('check_birthday')) { + $morecss = 'hidden'; + } + if ($event->type == 'holiday' && !GETPOST('check_holiday')) { + $morecss = 'hidden'; + } + if ($morecss != 'hidden') { + $itoshow++; + } + if ($morecss != 'showifmore' && $morecss != 'hidden') { + $ireallyshown++; + } + //var_dump($event->type.' - '.$morecss.' - '.$cssclass.' - '.$i.' - '.$ireallyshown.' - '.$itoshow); + + print '
    type_code == 'BIRTHDAY') // It's a birthday - { + if ($event->type_code == 'BIRTHDAY') { // It's birthday calendar print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'birthday', 'contact'); - } elseif ($event->type_code == 'HOLIDAY') - { - print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'holiday', 'user'); - } elseif ($event->type_code != 'BIRTHDAY' && $event->type_code != 'HOLIDAY') - { + } elseif ($event->type_code == 'HOLIDAY') { // It's holiday calendar + $tmpholiday->fetch($event->id); + + print $tmpholiday->getNomUrl(1); + + $tmpid = $tmpholiday->fk_user; + if (empty($cacheusers[$tmpid])) { + $newuser = new User($db); + $newuser->fetch($tmpid); + $cacheusers[$tmpid] = $newuser; + } + + $listofusertoshow .= '
    '.$cacheusers[$tmpid]->getNomUrl(-3, '', 0, 0, 0, 0, '', 'paddingright valigntextbottom'); + print $listofusertoshow; + } else { // Other calendar // Picto - if (empty($event->fulldayevent)) - { + if (empty($event->fulldayevent)) { //print $event->getNomUrl(2).' '; } // Date - if (empty($event->fulldayevent)) - { + if (empty($event->fulldayevent)) { // Show hours (start ... end) $tmpyearstart = dol_print_date($event->date_start_in_calendar, '%Y', 'tzuserrel'); $tmpmonthstart = dol_print_date($event->date_start_in_calendar, '%m', 'tzuserrel'); @@ -1712,33 +1887,29 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa $tmpdayend = dol_print_date($event->date_end_in_calendar, '%d', 'tzuserrel'); // Hour start - if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour) - { + if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour) { $daterange .= dol_print_date($event->date_start_in_calendar, 'hour', 'tzuserrel'); - if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) - { - if ($tmpyearstart == $tmpyearend && $tmpmonthstart == $tmpmonthend && $tmpdaystart == $tmpdayend) - $daterange .= '-'; + if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) { + if ($tmpyearstart == $tmpyearend && $tmpmonthstart == $tmpmonthend && $tmpdaystart == $tmpdayend) { + $daterange .= '-'; + } //else //print '...'; } } - if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) - { - if ($tmpyearstart != $tmpyearend || $tmpmonthstart != $tmpmonthend || $tmpdaystart != $tmpdayend) - { + if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) { + if ($tmpyearstart != $tmpyearend || $tmpmonthstart != $tmpmonthend || $tmpdaystart != $tmpdayend) { $daterange .= '...'; } } // Hour end - if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) - { - if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) - $daterange .= dol_print_date($event->date_end_in_calendar, 'hour', 'tzuserrel'); + if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) { + if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) { + $daterange .= dol_print_date($event->date_end_in_calendar, 'hour', 'tzuserrel'); + } } } else { - if ($showinfo) - { + if ($showinfo) { print $langs->trans("EventOnFullDay")."
    \n"; } } @@ -1752,7 +1923,8 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa $event->label = $titletoshow; $event->libelle = $titletoshow; // Note: List of users are inside $event->userassigned. Link may be clickable depending on permissions of user. - $titletoshow = $event->getNomUrl(0, $maxnbofchar, 'cal_event cal_event_title', '', 0, 0); + $titletoshow = (($event->type_picto || $event->type_code) ? $event->getTypePicto() : ''); + $titletoshow .= $event->getNomUrl(0, $maxnbofchar, 'cal_event cal_event_title', '', 0, 0); $event->label = $savlabel; $event->libelle = $savlabel; } @@ -1760,12 +1932,12 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa // Loop on each assigned user $listofusertoshow = ''; $posuserassigned = 0; - foreach ($event->userassigned as $tmpid => $tmpdata) - { - if (!$posuserassigned && $titletoshow) $listofusertoshow .= '
    '; + foreach ($event->userassigned as $tmpid => $tmpdata) { + if (!$posuserassigned && $titletoshow) { + $listofusertoshow .= '
    '; + } $posuserassigned++; - if (empty($cacheusers[$tmpid])) - { + if (empty($cacheusers[$tmpid])) { $newuser = new User($db); $newuser->fetch($tmpid); $cacheusers[$tmpid] = $newuser; @@ -1777,48 +1949,57 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print $titletoshow; print $listofusertoshow; - if ($event->type_code == 'ICALEVENT') print '
    ('.dol_trunc($event->icalname, $maxnbofchar).')'; + if ($event->type_code == 'ICALEVENT') { + print '
    ('.dol_trunc($event->icalname, $maxnbofchar).')'; + } $thirdparty_id = ($event->thirdparty_id > 0 ? $event->thirdparty_id : ((is_object($event->societe) && $event->societe->id > 0) ? $event->societe->id : 0)); $contact_id = ($event->contact_id > 0 ? $event->contact_id : ((is_object($event->contact) && $event->contact->id > 0) ? $event->contact->id : 0)); // If action related to company / contact $linerelatedto = ''; - if ($thirdparty_id > 0) - { - if (!isset($cachethirdparties[$thirdparty_id]) || !is_object($cachethirdparties[$thirdparty_id])) - { + if ($thirdparty_id > 0) { + if (!isset($cachethirdparties[$thirdparty_id]) || !is_object($cachethirdparties[$thirdparty_id])) { $thirdparty = new Societe($db); $thirdparty->fetch($thirdparty_id); $cachethirdparties[$thirdparty_id] = $thirdparty; - } else $thirdparty = $cachethirdparties[$thirdparty_id]; - if (!empty($thirdparty->id)) $linerelatedto .= $thirdparty->getNomUrl(1, '', 0); + } else { + $thirdparty = $cachethirdparties[$thirdparty_id]; + } + if (!empty($thirdparty->id)) { + $linerelatedto .= $thirdparty->getNomUrl(1, '', 0); + } } - if (!empty($contact_id) && $contact_id > 0) - { - if (!is_object($cachecontacts[$contact_id])) - { + if (!empty($contact_id) && $contact_id > 0) { + if (!is_object($cachecontacts[$contact_id])) { $contact = new Contact($db); $contact->fetch($contact_id); $cachecontacts[$contact_id] = $contact; - } else $contact = $cachecontacts[$contact_id]; - if ($linerelatedto) $linerelatedto .= ' '; - if (!empty($contact->id)) $linerelatedto .= $contact->getNomUrl(1, '', 0); + } else { + $contact = $cachecontacts[$contact_id]; + } + if ($linerelatedto) { + $linerelatedto .= ' '; + } + if (!empty($contact->id)) { + $linerelatedto .= $contact->getNomUrl(1, '', 0); + } } - if (!empty($event->fk_element) && $event->fk_element > 0 && !empty($event->elementtype) && !empty($conf->global->AGENDA_SHOW_LINKED_OBJECT)) - { + if (!empty($event->fk_element) && $event->fk_element > 0 && !empty($event->elementtype) && !empty($conf->global->AGENDA_SHOW_LINKED_OBJECT)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - if ($linerelatedto) $linerelatedto .= '
    '; + if ($linerelatedto) { + $linerelatedto .= '
    '; + } $linerelatedto .= dolGetElementUrl($event->fk_element, $event->elementtype, 1); } - if ($linerelatedto) print '
    '.$linerelatedto; + if ($linerelatedto) { + print '
    '.$linerelatedto; + } } // Show location - if ($showinfo) - { - if ($event->location) - { + if ($showinfo) { + if ($event->location) { print '
    '; print $langs->trans("Location").': '.$event->location; } @@ -1827,16 +2008,21 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print '
    '; - if ($withstatus) print $event->getLibStatut(3, 1); - else print ' '; + if ($withstatus) { + print $event->getLibStatut(3, 1); + } else { + print ' '; + } print '
    '; print ''."\n"; + $i++; } else { print '
    '.img_picto("all", "1downarrow_selected.png").' +'.$langs->trans("More").'...'; + if (!empty($conf->global->MAIN_JS_SWITCH_AGENDA) && $itoshow > $ireallyshown && $maxprint) { + print '
    '.img_picto("All", "angle-double-down", 'class="warning"').' +'.($itoshow - $ireallyshown).'
    '; //print ' +'.(count($eventarray[$daykey])-$maxprint); + print ''."\n"; } @@ -1896,8 +2084,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa function dol_color_minus($color, $minus, $minusunit = 16) { $newcolor = $color; - if ($minusunit == 16) - { + if ($minusunit == 16) { $newcolor[0] = dechex(max(min(hexdec($newcolor[0]) - $minus, 15), 0)); $newcolor[2] = dechex(max(min(hexdec($newcolor[2]) - $minus, 15), 0)); $newcolor[4] = dechex(max(min(hexdec($newcolor[4]) - $minus, 15), 0)); @@ -1917,13 +2104,10 @@ function dol_color_minus($color, $minus, $minusunit = 16) function sort_events_by_date($a, $b) { // Sort holidays at first - if ($a->type_code === 'HOLIDAY') - { + if ($a->type_code === 'HOLIDAY') { return -1; } - - if ($b->type_code === 'HOLIDAY') - { + if ($b->type_code === 'HOLIDAY') { return 1; } @@ -1931,20 +2115,17 @@ function sort_events_by_date($a, $b) // datef => Event end time // Events have different start time - if ($a->datep !== $b->datep) - { + if ($a->datep !== $b->datep) { return $a->datep - $b->datep; } // Events have same start time and no end time - if ((!is_numeric($b->datef)) || (!is_numeric($a->datef))) - { + if ((!is_numeric($b->datef)) || (!is_numeric($a->datef))) { return sort_events_by_percentage($a, $b); } // Events have the same start time and same end time - if ($b->datef === $a->datef) - { + if ($b->datef === $a->datef) { return sort_events_by_percentage($a, $b); } @@ -1964,13 +2145,11 @@ function sort_events_by_percentage($a, $b) // Sort events with no percentage before each other // (usefull to sort holidays, sick days or similar on the top) - if ($a->percentage < 0) - { + if ($a->percentage < 0) { return -1; } - if ($b->percentage < 0) - { + if ($b->percentage < 0) { return 1; } diff --git a/htdocs/comm/action/info.php b/htdocs/comm/action/info.php index 40787abb8c3..2360f2925d9 100644 --- a/htdocs/comm/action/info.php +++ b/htdocs/comm/action/info.php @@ -39,8 +39,7 @@ $langs->load("commercial"); $id = GETPOST('id', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -84,8 +83,7 @@ $morehtmlref = '
    '; // Thirdparty //$morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); //$morehtmlref.='
    '.$langs->trans('Project') . ' '; $morehtmlref .= $langs->trans('Project').': '; @@ -95,7 +93,9 @@ if (!empty($conf->projet->enabled)) $morehtmlref .= '
    '; $morehtmlref .= $proj->ref; $morehtmlref .= ''; - if ($proj->title) $morehtmlref .= ' - '.$proj->title; + if ($proj->title) { + $morehtmlref .= ' - '.$proj->title; + } } else { $morehtmlref .= ''; } diff --git a/htdocs/comm/action/list.php b/htdocs/comm/action/list.php index b1d864589e8..64ed79d87ca 100644 --- a/htdocs/comm/action/list.php +++ b/htdocs/comm/action/list.php @@ -27,7 +27,9 @@ * \brief Page to list actions */ -if (!defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); +if (!defined("NOREDIRECTBYMAINTOLOGIN")) { + define('NOREDIRECTBYMAINTOLOGIN', 1); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; @@ -55,14 +57,17 @@ $toselect = GETPOST('toselect', 'array'); $confirm = GETPOST('confirm', 'alpha'); // Set actioncode (this code must be same for setting actioncode into peruser, listacton and index) -if (GETPOST('search_actioncode', 'array')) -{ +if (GETPOST('search_actioncode', 'array')) { $actioncode = GETPOST('search_actioncode', 'array', 3); - if (!count($actioncode)) $actioncode = '0'; + if (!count($actioncode)) { + $actioncode = '0'; + } } else { $actioncode = GETPOST("search_actioncode", "alpha", 3) ?GETPOST("search_actioncode", "alpha", 3) : (GETPOST("search_actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE)); } -if ($actioncode == '' && empty($actioncodearray)) $actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE); +if ($actioncode == '' && empty($actioncodearray)) { + $actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE); +} $search_id = GETPOST('search_id', 'alpha'); $search_title = GETPOST('search_title', 'alpha'); $search_note = GETPOST('search_note', 'alpha'); @@ -70,8 +75,12 @@ $search_note = GETPOST('search_note', 'alpha'); $dateselect = dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int'), 'tzuserrel'); $datestart = dol_mktime(0, 0, 0, GETPOST('datestartmonth', 'int'), GETPOST('datestartday', 'int'), GETPOST('datestartyear', 'int'), 'tzuserrel'); $dateend = dol_mktime(0, 0, 0, GETPOST('dateendmonth', 'int'), GETPOST('dateendday', 'int'), GETPOST('dateendyear', 'int'), 'tzuserrel'); -if ($search_status == '' && !GETPOSTISSET('search_status')) $search_status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); -if (empty($action) && !GETPOSTISSET('action')) $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); +if ($search_status == '' && !GETPOSTISSET('search_status')) { + $search_status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); +} +if (empty($action) && !GETPOSTISSET('action')) { + $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); +} $filter = GETPOST("search_filter", 'alpha', 3) ?GETPOST("search_filter", 'alpha', 3) : GETPOST("filter", 'alpha', 3); $filtert = GETPOST("search_filtert", "int", 3) ?GETPOST("search_filtert", "int", 3) : GETPOST("filtert", "int", 3); @@ -89,8 +98,7 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // If not choice done on calendar owner, we filter on user. -if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) -{ +if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) { $filtert = $user->id; } @@ -98,30 +106,41 @@ $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 ($page == -1 || $page == null) { $page = 0; } -$offset = $limit * $page; -if (!$sortorder) -{ - $sortorder = "DESC,DESC"; - if ($search_status == 'todo') $sortorder = "DESC,DESC"; +if ($page == -1 || $page == null) { + $page = 0; } -if (!$sortfield) -{ +$offset = $limit * $page; +if (!$sortorder) { + $sortorder = "DESC,DESC"; + if ($search_status == 'todo') { + $sortorder = "DESC,DESC"; + } +} +if (!$sortfield) { $sortfield = "a.datep,a.id"; - if ($search_status == 'todo') $sortfield = "a.datep,a.id"; + if ($search_status == 'todo') { + $sortfield = "a.datep,a.id"; + } } // Security check $socid = GETPOST("search_socid", 'int') ?GETPOST("search_socid", 'int') : GETPOST("socid", 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'agenda', 0, '', 'myactions'); -if ($socid < 0) $socid = ''; +if ($socid < 0) { + $socid = ''; +} $canedit = 1; -if (!$user->rights->agenda->myactions->read) accessforbidden(); -if (!$user->rights->agenda->allactions->read) $canedit = 0; -if (!$user->rights->agenda->allactions->read || $filter == 'mine') // If no permission to see all, we show only affected to me -{ +if (!$user->rights->agenda->myactions->read) { + accessforbidden(); +} +if (!$user->rights->agenda->allactions->read) { + $canedit = 0; +} +if (!$user->rights->agenda->allactions->read || $filter == 'mine') { // If no permission to see all, we show only affected to me $filtert = $user->id; } @@ -152,18 +171,14 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Actions */ -if (GETPOST('cancel', 'alpha')) -{ +if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) -{ +if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) { $param = ''; - if (is_array($_POST)) - { - foreach ($_POST as $key => $val) - { + if (is_array($_POST)) { + foreach ($_POST as $key => $val) { $param .= '&'.$key.'='.urlencode($val); } } @@ -174,13 +189,14 @@ if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) $parameters = array('id'=>$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'); +} // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 //$actioncode=''; $search_id = ''; $search_title = ''; @@ -192,12 +208,10 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_array_options = array(); } -if (empty($reshook) && !empty($massaction)) -{ +if (empty($reshook) && !empty($massaction)) { unset($percent); - switch ($massaction) - { + switch ($massaction) { case 'set_all_events_to_todo': $percent = ActionComm::EVENT_TODO; break; @@ -211,13 +225,10 @@ if (empty($reshook) && !empty($massaction)) break; } - if (isset($percent)) - { - foreach ($toselect as $toselectid) - { + if (isset($percent)) { + foreach ($toselect as $toselectid) { $result = $object->updatePercent($toselectid, $percent); - if ($result < 0) - { + if ($result < 0) { dol_print_error($db); break; } @@ -226,8 +237,7 @@ if (empty($reshook) && !empty($massaction)) } // As mass deletion happens with a confirm step, $massaction is not use for the final step (deletion). -if (empty($reshook)) -{ +if (empty($reshook)) { $objectclass = 'ActionComm'; $objectlabel = 'Events'; $uploaddir = true; @@ -258,62 +268,117 @@ llxHeader('', $langs->trans("Agenda"), $help_url); $listofextcals = array(); $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); +} if ($actioncode != '') { if (is_array($actioncode)) { - foreach ($actioncode as $str_action) $param .= "&search_actioncode[]=".urlencode($str_action); - } else $param .= "&search_actioncode=".urlencode($actioncode); + foreach ($actioncode as $str_action) { + $param .= "&search_actioncode[]=".urlencode($str_action); + } + } else { + $param .= "&search_actioncode=".urlencode($actioncode); + } +} +if ($resourceid > 0) { + $param .= "&search_resourceid=".urlencode($resourceid); +} +if ($search_status != '' && $search_status > -1) { + $param .= "&search_status=".urlencode($search_status); +} +if ($filter) { + $param .= "&search_filter=".urlencode($filter); +} +if ($filtert) { + $param .= "&search_filtert=".urlencode($filtert); +} +if ($usergroup > 0) { + $param .= "&search_usergroup=".urlencode($usergroup); +} +if ($socid > 0) { + $param .= "&search_socid=".urlencode($socid); +} +if ($showbirthday) { + $param .= "&search_showbirthday=1"; +} +if ($pid) { + $param .= "&search_projectid=".urlencode($pid); +} +if ($type) { + $param .= "&search_type=".urlencode($type); +} +if ($search_id != '') { + $param .= '&search_title='.urlencode($search_id); +} +if ($search_title != '') { + $param .= '&search_title='.urlencode($search_title); +} +if ($search_note != '') { + $param .= '&search_note='.$search_note; +} +if (GETPOST('datestartday', 'int')) { + $param .= '&datestartday='.GETPOST('datestartday', 'int'); +} +if (GETPOST('datestartmonth', 'int')) { + $param .= '&datestartmonth='.GETPOST('datestartmonth', 'int'); +} +if (GETPOST('datestartyear', 'int')) { + $param .= '&datestartyear='.GETPOST('datestartyear', 'int'); +} +if (GETPOST('dateendday', 'int')) { + $param .= '&dateendday='.GETPOST('dateendday', 'int'); +} +if (GETPOST('dateendmonth', 'int')) { + $param .= '&dateendmonth='.GETPOST('dateendmonth', 'int'); +} +if (GETPOST('dateendyear', 'int')) { + $param .= '&dateendyear='.GETPOST('dateendyear', 'int'); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); } -if ($resourceid > 0) $param .= "&search_resourceid=".urlencode($resourceid); -if ($search_status != '' && $search_status > -1) $param .= "&search_status=".urlencode($search_status); -if ($filter) $param .= "&search_filter=".urlencode($filter); -if ($filtert) $param .= "&search_filtert=".urlencode($filtert); -if ($socid) $param .= "&search_socid=".urlencode($socid); -if ($showbirthday) $param .= "&search_showbirthday=1"; -if ($pid) $param .= "&search_projectid=".urlencode($pid); -if ($type) $param .= "&search_type=".urlencode($type); -if ($usergroup) $param .= "&search_usergroup=".urlencode($usergroup); -if ($search_id != '') $param .= '&search_title='.urlencode($search_id); -if ($search_title != '') $param .= '&search_title='.urlencode($search_title); -if ($search_note != '') $param .= '&search_note='.$search_note; -if (GETPOST('datestartday', 'int')) $param .= '&datestartday='.GETPOST('datestartday', 'int'); -if (GETPOST('datestartmonth', 'int')) $param .= '&datestartmonth='.GETPOST('datestartmonth', 'int'); -if (GETPOST('datestartyear', 'int')) $param .= '&datestartyear='.GETPOST('datestartyear', 'int'); -if (GETPOST('dateendday', 'int')) $param .= '&dateendday='.GETPOST('dateendday', 'int'); -if (GETPOST('dateendmonth', 'int')) $param .= '&dateendmonth='.GETPOST('dateendmonth', 'int'); -if (GETPOST('dateendyear', 'int')) $param .= '&dateendyear='.GETPOST('dateendyear', 'int'); -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; +$paramnoactionodate = $param; + // List of mass actions available $arrayofmassactions = array( 'set_all_events_to_todo' => $langs->trans("SetAllEventsToTodo"), 'set_all_events_to_in_progress' => $langs->trans("SetAllEventsToInProgress"), 'set_all_events_to_finished' => $langs->trans("SetAllEventsToFinished"), ); -if ($user->rights->agenda->allactions->delete) -{ +if ($user->rights->agenda->allactions->delete) { $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); } -if ($user->rights->agenda->myactions->create) $arrayofmassactions['preaffecttag'] = ''.$langs->trans("AffectTag"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete','preaffecttag'))) $arrayofmassactions = array(); +if ($user->rights->agenda->myactions->create) { + $arrayofmassactions['preaffecttag'] = ''.$langs->trans("AffectTag"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete','preaffecttag'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $sql = "SELECT"; -if ($usergroup > 0) $sql .= " DISTINCT"; +if ($usergroup > 0) { + $sql .= " DISTINCT"; +} $sql .= " s.nom as societe, s.rowid as socid, s.client, s.email as socemail,"; $sql .= " a.id, a.code, a.label, a.note, a.datep as dp, a.datep2 as dp2, a.fulldayevent, a.location,"; $sql .= ' a.fk_user_author,a.fk_user_action,'; $sql .= " a.fk_contact, a.note, a.percent as percent,"; $sql .= " a.fk_element, a.elementtype, a.datec, a.tms as datem,"; -$sql .= " c.code as type_code, c.libelle as type_label,"; +$sql .= " c.code as type_code, c.libelle as type_label, c.color as type_color, c.type as type_type, c.picto as type_picto,"; $sql .= " sp.lastname, sp.firstname, sp.email, sp.phone, sp.address, sp.phone as phone_pro, sp.phone_mobile, sp.phone_perso, sp.fk_pays as country_id"; // 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 : ''); + 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 @@ -323,34 +388,47 @@ $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_extrafields as ef ON (a.id = ef.fk_object) "; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; $sql .= " ,".MAIN_DB_PREFIX."c_actioncomm as c"; // We must filter on resource table -if ($resourceid > 0) $sql .= ", ".MAIN_DB_PREFIX."element_resources as r"; +if ($resourceid > 0) { + $sql .= ", ".MAIN_DB_PREFIX."element_resources as r"; +} // We must filter on assignement table -if ($filtert > 0 || $usergroup > 0) $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar"; -if ($usergroup > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_user = ar.fk_element"; +if ($filtert > 0 || $usergroup > 0) { + $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar"; +} +if ($usergroup > 0) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_user = ar.fk_element"; +} $sql .= " WHERE c.id = a.fk_action"; $sql .= ' AND a.entity IN ('.getEntity('agenda').')'; // Condition on actioncode -if (!empty($actioncode)) -{ - if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) - { - if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; - else { - if ($actioncode == 'AC_OTH') $sql .= " AND c.type != 'systemauto'"; - if ($actioncode == 'AC_OTH_AUTO') $sql .= " AND c.type = 'systemauto'"; +if (!empty($actioncode)) { + if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) { + if ($actioncode == 'AC_NON_AUTO') { + $sql .= " AND c.type != 'systemauto'"; + } elseif ($actioncode == 'AC_ALL_AUTO') { + $sql .= " AND c.type = 'systemauto'"; + } else { + if ($actioncode == 'AC_OTH') { + $sql .= " AND c.type != 'systemauto'"; + } + if ($actioncode == 'AC_OTH_AUTO') { + $sql .= " AND c.type = 'systemauto'"; + } } } else { - if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; - else { - if (is_array($actioncode)) - { + if ($actioncode == 'AC_NON_AUTO') { + $sql .= " AND c.type != 'systemauto'"; + } elseif ($actioncode == 'AC_ALL_AUTO') { + $sql .= " AND c.type = 'systemauto'"; + } else { + if (is_array($actioncode)) { $sql .= " AND c.code IN ('".implode("','", $actioncode)."')"; } else { $sql .= " AND c.code IN ('".implode("','", explode(',', $actioncode))."')"; @@ -358,35 +436,74 @@ if (!empty($actioncode)) } } } -if ($resourceid > 0) $sql .= " AND r.element_type = 'action' AND r.element_id = a.id AND r.resource_id = ".$db->escape($resourceid); -if ($pid) $sql .= " AND a.fk_project=".$db->escape($pid); -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")"; -if ($socid > 0) $sql .= " AND s.rowid = ".$socid; +if ($resourceid > 0) { + $sql .= " AND r.element_type = 'action' AND r.element_id = a.id AND r.resource_id = ".$db->escape($resourceid); +} +if ($pid) { + $sql .= " AND a.fk_project=".$db->escape($pid); +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")"; +} +if ($socid > 0) { + $sql .= " AND s.rowid = ".$socid; +} // We must filter on assignement table -if ($filtert > 0 || $usergroup > 0) $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; -if ($type) $sql .= " AND c.id = ".(int) $type; -if ($search_status == '0') { $sql .= " AND a.percent = 0"; } -if ($search_status == 'na') { $sql .= " AND a.percent = -1"; } // Not applicable -if ($search_status == '50') { $sql .= " AND (a.percent > 0 AND a.percent < 100)"; } // Running already started -if ($search_status == '100') { $sql .= " AND a.percent = 100"; } -if ($search_status == 'done') { $sql .= " AND (a.percent = 100)"; } -if ($search_status == 'todo') { $sql .= " AND (a.percent >= 0 AND a.percent < 100)"; } -if ($search_id) $sql .= natural_search("a.id", $search_id, 1); -if ($search_title) $sql .= natural_search("a.label", $search_title); -if ($search_note) $sql .= natural_search('a.note', $search_note); +if ($filtert > 0 || $usergroup > 0) { + $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; +} +if ($type) { + $sql .= " AND c.id = ".(int) $type; +} +if ($search_status == '0') { + $sql .= " AND a.percent = 0"; +} +if ($search_status == 'na') { + $sql .= " AND a.percent = -1"; +} // Not applicable +if ($search_status == '50') { + $sql .= " AND (a.percent > 0 AND a.percent < 100)"; +} // Running already started +if ($search_status == '100') { + $sql .= " AND a.percent = 100"; +} +if ($search_status == 'done') { + $sql .= " AND (a.percent = 100)"; +} +if ($search_status == 'todo') { + $sql .= " AND (a.percent >= 0 AND a.percent < 100)"; +} +if ($search_id) { + $sql .= natural_search("a.id", $search_id, 1); +} +if ($search_title) { + $sql .= natural_search("a.label", $search_title); +} +if ($search_note) { + $sql .= natural_search('a.note', $search_note); +} // We must filter on assignement table -if ($filtert > 0 || $usergroup > 0) -{ +if ($filtert > 0 || $usergroup > 0) { $sql .= " AND ("; - if ($filtert > 0) $sql .= "(ar.fk_element = ".$filtert." OR (ar.fk_element IS NULL AND a.fk_user_action=".$filtert."))"; // The OR is for backward compatibility - if ($usergroup > 0) $sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup; + if ($filtert > 0) { + $sql .= "(ar.fk_element = ".$filtert." OR (ar.fk_element IS NULL AND a.fk_user_action=".$filtert."))"; // The OR is for backward compatibility + } + if ($usergroup > 0) { + $sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup; + } $sql .= ")"; } // The second or of next test is to take event with no end date (we suppose duration is 1 hour in such case) -if ($dateselect > 0) $sql .= " AND ((a.datep2 >= '".$db->idate($dateselect)."' AND a.datep <= '".$db->idate($dateselect + 3600 * 24 - 1)."') OR (a.datep2 IS NULL AND a.datep > '".$db->idate($dateselect - 3600)."' AND a.datep <= '".$db->idate($dateselect + 3600 * 24 - 1)."'))"; -if ($datestart > 0) $sql .= " AND a.datep BETWEEN '".$db->idate($datestart)."' AND '".$db->idate($datestart + 3600 * 24 - 1)."'"; -if ($dateend > 0) $sql .= " AND a.datep2 BETWEEN '".$db->idate($dateend)."' AND '".$db->idate($dateend + 3600 * 24 - 1)."'"; +if ($dateselect > 0) { + $sql .= " AND ((a.datep2 >= '".$db->idate($dateselect)."' AND a.datep <= '".$db->idate($dateselect + 3600 * 24 - 1)."') OR (a.datep2 IS NULL AND a.datep > '".$db->idate($dateselect - 3600)."' AND a.datep <= '".$db->idate($dateselect + 3600 * 24 - 1)."'))"; +} +if ($datestart > 0) { + $sql .= " AND a.datep BETWEEN '".$db->idate($datestart)."' AND '".$db->idate($datestart + 3600 * 24 - 1)."'"; +} +if ($dateend > 0) { + $sql .= " AND a.datep2 BETWEEN '".$db->idate($dateend)."' AND '".$db->idate($dateend + 3600 * 24 - 1)."'"; +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -399,12 +516,10 @@ $sql .= $hookmanager->resPrint; $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -415,8 +530,7 @@ $sql .= $db->plimit($limit + 1, $offset); dol_syslog("comm/action/list.php", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $actionstatic = new ActionComm($db); $societestatic = new Societe($db); @@ -436,7 +550,9 @@ if ($resql) print ''."\n"; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; @@ -444,8 +560,12 @@ if ($resql) print ''; $nav = ''; - if ($filter) $nav .= ''; - if ($showbirthday) $nav .= ''; + if ($filter) { + $nav .= ''; + } + if ($showbirthday) { + $nav .= ''; + } print $nav; //print dol_get_fiche_head($head, $tabactive, $langs->trans('Agenda'), 0, 'action'); @@ -455,19 +575,19 @@ if ($resql) // Add link to show birthdays $link = ''; /* - if (empty($conf->use_javascript_ajax)) - { - $newparam=$param; // newparam is for birthday links - $newparam=preg_replace('/showbirthday=[0-1]/i','showbirthday='.(empty($showbirthday)?1:0),$newparam); - if (! preg_match('/showbirthday=/i',$newparam)) $newparam.='&showbirthday=1'; - $link=''; - if (empty($showbirthday)) $link.=$langs->trans("AgendaShowBirthdayEvents"); - else $link.=$langs->trans("AgendaHideBirthdayEvents"); - $link.=''; - } - */ + if (empty($conf->use_javascript_ajax)) + { + $newparam=$param; // newparam is for birthday links + $newparam=preg_replace('/showbirthday=[0-1]/i','showbirthday='.(empty($showbirthday)?1:0),$newparam); + if (! preg_match('/showbirthday=/i',$newparam)) $newparam.='&showbirthday=1'; + $link=''; + if (empty($showbirthday)) $link.=$langs->trans("AgendaShowBirthdayEvents"); + else $link.=$langs->trans("AgendaHideBirthdayEvents"); + $link.=''; + } + */ $s = $newtitle; @@ -481,31 +601,31 @@ if ($resql) } $viewmode = ''; - $viewmode .= ''; + $viewmode .= ''; //$viewmode .= ''; $viewmode .= img_picto($langs->trans("List"), 'object_list-alt', 'class="pictoactionview block"'); //$viewmode .= ''; $viewmode .= ''.$langs->trans("ViewList").''; - $viewmode .= ''; + $viewmode .= ''; //$viewmode .= ''; $viewmode .= img_picto($langs->trans("ViewCal"), 'object_calendar', 'class="pictoactionview block"'); //$viewmode .= ''; $viewmode .= ''.$langs->trans("ViewCal").''; - $viewmode .= ''; + $viewmode .= ''; //$viewmode .= ''; $viewmode .= img_picto($langs->trans("ViewWeek"), 'object_calendarweek', 'class="pictoactionview block"'); //$viewmode .= ''; $viewmode .= ''.$langs->trans("ViewWeek").''; - $viewmode .= ''; + $viewmode .= ''; //$viewmode .= ''; $viewmode .= img_picto($langs->trans("ViewDay"), 'object_calendarday', 'class="pictoactionview block"'); //$viewmode .= ''; $viewmode .= ''.$langs->trans("ViewDay").''; - $viewmode .= ''; + $viewmode .= ''; //$viewmode .= ''; $viewmode .= img_picto($langs->trans("ViewPerUser"), 'object_calendarperuser', 'class="pictoactionview block"'); //$viewmode .= ''; @@ -548,7 +668,9 @@ if ($resql) $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); + } $i = 0; print '
    '; @@ -559,11 +681,21 @@ if ($resql) print ''."\n"; print ''; - if (!empty($arrayfields['a.id']['checked'])) print ''; - if (!empty($arrayfields['owner']['checked'])) print ''; - if (!empty($arrayfields['c.libelle']['checked'])) print ''; - if (!empty($arrayfields['a.label']['checked'])) print ''; - if (!empty($arrayfields['a.note']['checked'])) print ''; + if (!empty($arrayfields['a.id']['checked'])) { + print ''; + } + if (!empty($arrayfields['owner']['checked'])) { + print ''; + } + if (!empty($arrayfields['c.libelle']['checked'])) { + print ''; + } + if (!empty($arrayfields['a.label']['checked'])) { + print ''; + } + if (!empty($arrayfields['a.note']['checked'])) { + print ''; + } if (!empty($arrayfields['a.datep']['checked'])) { print ''; } - if (!empty($arrayfields['a.fk_contact']['checked'])) print ''; - if (!empty($arrayfields['a.fk_element']['checked'])) print ''; + if (!empty($arrayfields['a.fk_contact']['checked'])) { + print ''; + } + if (!empty($arrayfields['a.fk_element']['checked'])) { + print ''; + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; @@ -588,8 +724,12 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (!empty($arrayfields['a.datec']['checked'])) print ''; - if (!empty($arrayfields['a.tms']['checked'])) print ''; + if (!empty($arrayfields['a.datec']['checked'])) { + print ''; + } + if (!empty($arrayfields['a.tms']['checked'])) { + print ''; + } if (!empty($arrayfields['a.percent']['checked'])) { print '\n"; print ''; - if (!empty($arrayfields['a.id']['checked'])) print_liste_field_titre($arrayfields['a.id']['label'], $_SERVER["PHP_SELF"], "a.id", $param, "", "", $sortfield, $sortorder); - if (!empty($arrayfields['owner']['checked'])) print_liste_field_titre($arrayfields['owner']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); - if (!empty($arrayfields['c.libelle']['checked'])) print_liste_field_titre($arrayfields['c.libelle']['label'], $_SERVER["PHP_SELF"], "c.libelle", $param, "", "", $sortfield, $sortorder); - if (!empty($arrayfields['a.label']['checked'])) print_liste_field_titre($arrayfields['a.label']['label'], $_SERVER["PHP_SELF"], "a.label", $param, "", "", $sortfield, $sortorder); - if (!empty($arrayfields['a.note']['checked'])) print_liste_field_titre($arrayfields['a.note']['label'], $_SERVER["PHP_SELF"], "a.note", $param, "", "", $sortfield, $sortorder); + if (!empty($arrayfields['a.id']['checked'])) { + print_liste_field_titre($arrayfields['a.id']['label'], $_SERVER["PHP_SELF"], "a.id", $param, "", "", $sortfield, $sortorder); + } + if (!empty($arrayfields['owner']['checked'])) { + print_liste_field_titre($arrayfields['owner']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); + } + if (!empty($arrayfields['c.libelle']['checked'])) { + print_liste_field_titre($arrayfields['c.libelle']['label'], $_SERVER["PHP_SELF"], "c.libelle", $param, "", "", $sortfield, $sortorder); + } + if (!empty($arrayfields['a.label']['checked'])) { + print_liste_field_titre($arrayfields['a.label']['label'], $_SERVER["PHP_SELF"], "a.label", $param, "", "", $sortfield, $sortorder); + } + if (!empty($arrayfields['a.note']['checked'])) { + print_liste_field_titre($arrayfields['a.note']['label'], $_SERVER["PHP_SELF"], "a.note", $param, "", "", $sortfield, $sortorder); + } //if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) - if (!empty($arrayfields['a.datep']['checked'])) print_liste_field_titre($arrayfields['a.datep']['label'], $_SERVER["PHP_SELF"], "a.datep,a.id", $param, '', 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['a.datep2']['checked'])) print_liste_field_titre($arrayfields['a.datep2']['label'], $_SERVER["PHP_SELF"], "a.datep2", $param, '', 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", $param, "", "", $sortfield, $sortorder); - if (!empty($arrayfields['a.fk_contact']['checked'])) print_liste_field_titre($arrayfields['a.fk_contact']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); - if (!empty($arrayfields['a.fk_element']['checked'])) print_liste_field_titre($arrayfields['a.fk_element']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); + if (!empty($arrayfields['a.datep']['checked'])) { + print_liste_field_titre($arrayfields['a.datep']['label'], $_SERVER["PHP_SELF"], "a.datep,a.id", $param, '', 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['a.datep2']['checked'])) { + print_liste_field_titre($arrayfields['a.datep2']['label'], $_SERVER["PHP_SELF"], "a.datep2", $param, '', 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", $param, "", "", $sortfield, $sortorder); + } + if (!empty($arrayfields['a.fk_contact']['checked'])) { + print_liste_field_titre($arrayfields['a.fk_contact']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); + } + if (!empty($arrayfields['a.fk_element']['checked'])) { + print_liste_field_titre($arrayfields['a.fk_element']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; @@ -624,10 +784,16 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (!empty($arrayfields['a.datec']['checked'])) print_liste_field_titre($arrayfields['a.datec']['label'], $_SERVER["PHP_SELF"], "a.datec,a.id", $param, "", 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['a.tms']['checked'])) print_liste_field_titre($arrayfields['a.tms']['label'], $_SERVER["PHP_SELF"], "a.tms,a.id", $param, "", 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['a.datec']['checked'])) { + print_liste_field_titre($arrayfields['a.datec']['label'], $_SERVER["PHP_SELF"], "a.datec,a.id", $param, "", 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['a.tms']['checked'])) { + print_liste_field_titre($arrayfields['a.tms']['label'], $_SERVER["PHP_SELF"], "a.tms,a.id", $param, "", 'align="center"', $sortfield, $sortorder); + } - if (!empty($arrayfields['a.percent']['checked']))print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "a.percent", $param, "", 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['a.percent']['checked'])) { + print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "a.percent", $param, "", 'align="center"', $sortfield, $sortorder); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; @@ -640,13 +806,11 @@ if ($resql) $arraylist = $caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : 0), '', 1); $contactListCache = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); // Discard auto action if option is on - if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') - { + if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') { $i++; continue; } @@ -657,6 +821,7 @@ if ($resql) $actionstatic->type_code = $obj->type_code; $actionstatic->type_label = $obj->type_label; $actionstatic->type_picto = $obj->type_picto; + $actionstatic->type_color = $obj->type_color; $actionstatic->label = $obj->label; $actionstatic->location = $obj->location; $actionstatic->note_private = dol_htmlentitiesbr($obj->note); @@ -673,47 +838,34 @@ if ($resql) } // User owner - if (!empty($arrayfields['owner']['checked'])) - { + if (!empty($arrayfields['owner']['checked'])) { print ''; } // Type - if (!empty($arrayfields['c.libelle']['checked'])) - { + if (!empty($arrayfields['c.libelle']['checked'])) { print ''; @@ -741,11 +893,21 @@ if ($resql) print ''; } @@ -759,15 +921,16 @@ if ($resql) // Third party if (!empty($arrayfields['s.nom']['checked'])) { print ''; } @@ -775,17 +938,13 @@ if ($resql) if (!empty($arrayfields['a.fk_contact']['checked'])) { print ''; diff --git a/htdocs/comm/action/pertype.php b/htdocs/comm/action/pertype.php index a399ee3d580..dc70fb30743 100644 --- a/htdocs/comm/action/pertype.php +++ b/htdocs/comm/action/pertype.php @@ -39,7 +39,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; -if (!isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW = 3; +if (!isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) { + $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW = 3; +} $filter = GETPOST("search_filter", 'alpha', 3) ? GETPOST("search_filter", 'alpha', 3) : GETPOST("filter", 'alpha', 3); $filtert = GETPOST("search_filtert", "int", 3) ? GETPOST("search_filtert", "int", 3) : GETPOST("filtert", "int", 3); @@ -49,31 +51,43 @@ $usergroup = GETPOST("search_usergroup", "int", 3) ? GETPOST("search_usergroup", $showbirthday = 0; // If not choice done on calendar owner, we filter on user. -if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) -{ +if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) { $filtert = $user->id; } $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 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "a.datec"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "a.datec"; +} // Security check $socid = GETPOST("search_socid", "int") ?GETPOST("search_socid", "int") : GETPOST("socid", "int"); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'agenda', 0, '', 'myactions'); -if ($socid < 0) $socid = ''; +if ($socid < 0) { + $socid = ''; +} $canedit = 1; -if (!$user->rights->agenda->myactions->read) accessforbidden(); -if (!$user->rights->agenda->allactions->read) $canedit = 0; -if (!$user->rights->agenda->allactions->read || $filter == 'mine') // If no permission to see all, we show only affected to me -{ +if (!$user->rights->agenda->myactions->read) { + accessforbidden(); +} +if (!$user->rights->agenda->allactions->read) { + $canedit = 0; +} +if (!$user->rights->agenda->allactions->read || $filter == 'mine') { // If no permission to see all, we show only affected to me $filtert = $user->id; } @@ -90,18 +104,20 @@ $type = GETPOST("search_type", 'alpha') ?GETPOST("search_type", 'alpha') : GETPO $maxprint = ((GETPOST("maxprint", 'int') != '') ?GETPOST("maxprint", 'int') : $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW); $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') // Set actioncode (this code must be same for setting actioncode into peruser, listacton and index) -if (GETPOST('search_actioncode', 'array')) -{ +if (GETPOST('search_actioncode', 'array')) { $actioncode = GETPOST('search_actioncode', 'array', 3); - if (!count($actioncode)) $actioncode = '0'; + if (!count($actioncode)) { + $actioncode = '0'; + } } else { $actioncode = GETPOST("search_actioncode", "alpha", 3) ?GETPOST("search_actioncode", "alpha", 3) : (GETPOST("search_actioncode", "alpha") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE)); } -if ($actioncode == '' && empty($actioncodearray)) $actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE); +if ($actioncode == '' && empty($actioncodearray)) { + $actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE); +} $dateselect = dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int')); -if ($dateselect > 0) -{ +if ($dateselect > 0) { $day = GETPOST('dateselectday', 'int'); $month = GETPOST('dateselectmonth', 'int'); $year = GETPOST('dateselectyear', 'int'); @@ -112,9 +128,15 @@ $tmp = str_replace(' ', '', $tmp); // FIX 7533 $tmparray = explode('-', $tmp); $begin_h = GETPOST('begin_h', 'int') != '' ?GETPOST('begin_h', 'int') : ($tmparray[0] != '' ? $tmparray[0] : 9); $end_h = GETPOST('end_h', 'int') ?GETPOST('end_h', 'int') : ($tmparray[1] != '' ? $tmparray[1] : 18); -if ($begin_h < 0 || $begin_h > 23) $begin_h = 9; -if ($end_h < 1 || $end_h > 24) $end_h = 18; -if ($end_h <= $begin_h) $end_h = $begin_h + 1; +if ($begin_h < 0 || $begin_h > 23) { + $begin_h = 9; +} +if ($end_h < 1 || $end_h > 24) { + $end_h = 18; +} +if ($end_h <= $begin_h) { + $end_h = $begin_h + 1; +} $tmp = empty($conf->global->MAIN_DEFAULT_WORKING_DAYS) ? '1-5' : $conf->global->MAIN_DEFAULT_WORKING_DAYS; $tmp = str_replace(' ', '', $tmp); // FIX 7533 @@ -122,8 +144,12 @@ $tmparray = explode('-', $tmp); $begin_d = 1; $end_d = 53; -if ($status == '' && !GETPOSTISSET('status')) $status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); -if (empty($action) && !GETPOSTISSET('action')) $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); +if ($status == '' && !GETPOSTISSET('status')) { + $status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); +} +if (empty($action) && !GETPOSTISSET('action')) { + $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); +} if (GETPOST('viewcal', 'alpha') && $action != 'show_day' && $action != 'show_week' && $action != 'show_peruser') { $action = 'show_month'; $day = ''; @@ -149,8 +175,7 @@ $hookmanager->initHooks(array('agenda')); * Actions */ -if ($action == 'delete_action') -{ +if ($action == 'delete_action') { $event = new ActionComm($db); $event->fetch($actionid); $event->fetch_optionals(); @@ -185,7 +210,9 @@ $parameters = array( 'usergroup' => $usergroup, ); $reshook = $hookmanager->executeHooks('beforeAgendaPerType', $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'); +} $form = new Form($db); $companystatic = new Societe($db); @@ -223,31 +250,69 @@ $tmpday = $first_day; //print 'xx'.$next_year.'-'.$next_month.'-'.$next_day; $title = $langs->trans("DoneAndToDoActions"); -if ($status == 'done') $title = $langs->trans("DoneActions"); -if ($status == 'todo') $title = $langs->trans("ToDoActions"); +if ($status == 'done') { + $title = $langs->trans("DoneActions"); +} +if ($status == 'todo') { + $title = $langs->trans("ToDoActions"); +} $param = ''; if ($actioncode || GETPOSTISSET('search_actioncode')) { if (is_array($actioncode)) { - foreach ($actioncode as $str_action) $param .= "&search_actioncode[]=".urlencode($str_action); - } else $param .= "&search_actioncode=".urlencode($actioncode); + foreach ($actioncode as $str_action) { + $param .= "&search_actioncode[]=".urlencode($str_action); + } + } else { + $param .= "&search_actioncode=".urlencode($actioncode); + } +} +if ($resourceid > 0) { + $param .= "&search_resourceid=".urlencode($resourceid); +} +if ($status || GETPOSTISSET('status')) { + $param .= "&search_status=".urlencode($status); +} +if ($filter) { + $param .= "&search_filter=".urlencode($filter); +} +if ($filtert) { + $param .= "&search_filtert=".urlencode($filtert); +} +if ($usergroup > 0) { + $param .= "&search_usergroup=".urlencode($usergroup); +} +if ($socid > 0) { + $param .= "&search_socid=".urlencode($socid); +} +if ($showbirthday) { + $param .= "&search_showbirthday=1"; +} +if ($pid) { + $param .= "&search_projectid=".urlencode($pid); +} +if ($type) { + $param .= "&search_type=".urlencode($type); +} +if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser') { + $param .= '&action='.urlencode($action); +} +if ($begin_h != '') { + $param .= '&begin_h='.urlencode($begin_h); +} +if ($end_h != '') { + $param .= '&end_h='.urlencode($end_h); +} +if ($begin_d != '') { + $param .= '&begin_d='.urlencode($begin_d); +} +if ($end_d != '') { + $param .= '&end_d='.urlencode($end_d); } -if ($resourceid > 0) $param .= "&search_resourceid=".urlencode($resourceid); -if ($status || GETPOSTISSET('status')) $param .= "&search_status=".urlencode($status); -if ($filter) $param .= "&search_filter=".urlencode($filter); -if ($filtert) $param .= "&search_filtert=".urlencode($filtert); -if ($usergroup) $param .= "&search_usergroup=".urlencode($usergroup); -if ($socid) $param .= "&search_socid=".urlencode($socid); -if ($showbirthday) $param .= "&search_showbirthday=1"; -if ($pid) $param .= "&search_projectid=".urlencode($pid); -if ($type) $param .= "&search_type=".urlencode($type); -if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser') $param .= '&action='.urlencode($action); -if ($begin_h != '') $param .= '&begin_h='.urlencode($begin_h); -if ($end_h != '') $param .= '&end_h='.urlencode($end_h); -if ($begin_d != '') $param .= '&begin_d='.urlencode($begin_d); -if ($end_d != '') $param .= '&end_d='.urlencode($end_d); $param .= "&maxprint=".urlencode($maxprint); +$paramnoactionodate = $param; + $prev = dol_get_first_day($year, 1); $prev_year = $year - 1; $prev_month = $month; @@ -299,28 +364,23 @@ print 'use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { $s = ''; $s .= ''."\n"; - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { $s .= '
    '.$langs->trans("LocalAgenda").'  
    '; - if (is_array($showextcals) && count($showextcals) > 0) - { - foreach ($showextcals as $val) - { + if (is_array($showextcals) && count($showextcals) > 0) { + foreach ($showextcals as $val) { $htmlname = md5($val['name']); $s .= ''."\n"; - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { $s .= '
    '.$langs->trans("LocalAgenda").'  
    '; - if (is_array($showextcals) && count($showextcals) > 0) - { - foreach ($showextcals as $val) - { + if (is_array($showextcals) && count($showextcals) > 0) { + foreach ($showextcals as $val) { $htmlname = md5($val['name']); $s .= ''; @@ -1654,8 +1678,7 @@ if ($action == 'create') print ''; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); print ''; print ''; print ''; print '"; // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; print ''; print ''; print ''; print ''; print ''; print '"; - if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 - { + if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1 print '"; } - if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 - { + if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2 print '"; } print '"; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; print '"; print '"; @@ -1775,12 +1792,13 @@ if ($action == 'create') /* * Combobox for copy function - */ + */ - if (empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) print ''; + if (empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) { + print ''; + } - if (!empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) - { + if (!empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) { print '
    '; print $form->selectDate($datestart, 'datestart', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzuserrel'); @@ -577,8 +709,12 @@ if ($resql) if (!empty($arrayfields['s.nom']['checked'])) { print ''; $formactions->form_select_status_action('formaction', $search_status, 1, 'search_status', 1, 2, 'minwidth100imp maxwidth125'); @@ -604,17 +744,37 @@ if ($resql) print "
    '; // With edge and chrome the td overflow is not supported correctly when content is not full text. - if ($obj->fk_user_action > 0) - { + if ($obj->fk_user_action > 0) { $userstatic->fetch($obj->fk_user_action); print $userstatic->getNomUrl(-1); - } else print ' '; + } else { + print ' '; + } print ''; - $actioncomm = $actionstatic; - // TODO Code common with code into showactions - $imgpicto = ''; - if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) - { - if ($actioncomm->type_picto) { - $imgpicto = img_picto('', $actioncomm->type_picto); - } else { - if ($actioncomm->type_code == 'AC_RDV') $imgpicto = img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actioncomm->type_code == 'AC_TEL') $imgpicto = img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actioncomm->type_code == 'AC_FAX') $imgpicto = img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actioncomm->type_code == 'AC_EMAIL' || $actioncomm->type_code == 'AC_EMAIL_IN') $imgpicto = img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actioncomm->type_code == 'AC_INT') $imgpicto = img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actioncomm->type_code == 'AC_OTH' && $actioncomm->code == 'TICKET_MSG') $imgpicto = img_picto('', 'object_conversation', '', false, 0, 0, '', 'paddingright').' '; - elseif (!preg_match('/_AUTO/', $actioncomm->type_code)) $imgpicto = img_picto('', 'object_other', '', false, 0, 0, '', 'paddingright').' '; - } - } - print $imgpicto; - + print $actionstatic->getTypePicto(); $labeltype = $obj->type_code; - if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) $labeltype = 'AC_OTH'; - if ($actioncomm->type_code == 'AC_OTH' && $actioncomm->code == 'TICKET_MSG') { + if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) { + $labeltype = 'AC_OTH'; + } + if ($actionstatic->type_code == 'AC_OTH' && $actionstatic->code == 'TICKET_MSG') { $labeltype = $langs->trans("Message"); } else { - if (!empty($arraylist[$labeltype])) $labeltype = $arraylist[$labeltype]; - if ($obj->type_code == 'AC_OTH_AUTO' && ($obj->type_code != $obj->code) && $labeltype && !empty($arraylist[$obj->code])) $labeltype .= ' - '.$arraylist[$obj->code]; // Use code in priority on type_code + if (!empty($arraylist[$labeltype])) { + $labeltype = $arraylist[$labeltype]; + } + if ($obj->type_code == 'AC_OTH_AUTO' && ($obj->type_code != $obj->code) && $labeltype && !empty($arraylist[$obj->code])) { + $labeltype .= ' - '.$arraylist[$obj->code]; // Use code in priority on type_code + } } print dol_trunc($labeltype, 28); print ''; print dol_print_date($db->jdate($obj->dp), $formatToUse, 'tzuser'); $late = 0; - if ($obj->percent == 0 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) $late = 1; - if ($obj->percent == 0 && !$obj->dp && $obj->dp2 && $db->jdate($obj->dp) < ($now - $delay_warning)) $late = 1; - if ($obj->percent > 0 && $obj->percent < 100 && $obj->dp2 && $db->jdate($obj->dp2) < ($now - $delay_warning)) $late = 1; - if ($obj->percent > 0 && $obj->percent < 100 && !$obj->dp2 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) $late = 1; - if ($late) print img_warning($langs->trans("Late")).' '; + if ($obj->percent == 0 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) { + $late = 1; + } + if ($obj->percent == 0 && !$obj->dp && $obj->dp2 && $db->jdate($obj->dp) < ($now - $delay_warning)) { + $late = 1; + } + if ($obj->percent > 0 && $obj->percent < 100 && $obj->dp2 && $db->jdate($obj->dp2) < ($now - $delay_warning)) { + $late = 1; + } + if ($obj->percent > 0 && $obj->percent < 100 && !$obj->dp2 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) { + $late = 1; + } + if ($late) { + print img_warning($langs->trans("Late")).' '; + } print ''; - if ($obj->socid > 0) - { + if ($obj->socid > 0) { $societestatic->id = $obj->socid; $societestatic->client = $obj->client; $societestatic->name = $obj->societe; $societestatic->email = $obj->socemail; print $societestatic->getNomUrl(1, '', 28); - } else print ' '; + } else { + print ' '; + } print ''; - if (!empty($actionstatic->socpeopleassigned)) - { + if (!empty($actionstatic->socpeopleassigned)) { $contactList = array(); - foreach ($actionstatic->socpeopleassigned as $socpeopleassigned) - { - if (!isset($contactListCache[$socpeopleassigned['id']])) - { + foreach ($actionstatic->socpeopleassigned as $socpeopleassigned) { + if (!isset($contactListCache[$socpeopleassigned['id']])) { // if no cache found we fetch it $contact = new Contact($db); - if ($contact->fetch($socpeopleassigned['id']) > 0) - { + if ($contact->fetch($socpeopleassigned['id']) > 0) { $contactListCache[$socpeopleassigned['id']] = $contact->getNomUrl(1, '', 0); $contactList[] = $contact->getNomUrl(1, '', 0); } @@ -797,8 +956,7 @@ if ($resql) if (!empty($contactList)) { print implode(', ', $contactList); } - } elseif ($obj->fk_contact > 0) //keep for retrocompatibility with faraway event - { + } elseif ($obj->fk_contact > 0) { //keep for retrocompatibility with faraway event $contactstatic->id = $obj->fk_contact; $contactstatic->email = $obj->email; $contactstatic->lastname = $obj->lastname; @@ -850,10 +1008,11 @@ if ($resql) } // Action column print ''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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->id, $arrayofselected)) $selected = 1; + if (in_array($obj->id, $arrayofselected)) { + $selected = 1; + } print ''; } print '
    '.$langs->trans("Project").''; @@ -1666,8 +1689,7 @@ if ($action == 'create') } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '
    '; @@ -1686,8 +1708,7 @@ if ($action == 'create') print "
    '.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).''; @@ -1704,8 +1725,7 @@ if ($action == 'create') print $doleditor->Create(1); // Private note - if (empty($user->socid)) - { + if (empty($user->socid)) { print '
    '.$langs->trans('NotePrivate').''; @@ -1720,8 +1740,7 @@ if ($action == 'create') include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; // Lines from source - if (!empty($origin) && !empty($originid) && is_object($objectsrc)) - { + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) { // TODO for compatibility if ($origin == 'contrat') { // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva @@ -1739,31 +1758,29 @@ if ($action == 'create') print ''; $newclassname = $classname; - if ($newclassname == 'Propal') + if ($newclassname == 'Propal') { $newclassname = 'CommercialProposal'; - elseif ($newclassname == 'Commande') + } elseif ($newclassname == 'Commande') { $newclassname = 'Order'; - elseif ($newclassname == 'Expedition') + } elseif ($newclassname == 'Expedition') { $newclassname = 'Sending'; - elseif ($newclassname == 'Fichinter') + } elseif ($newclassname == 'Fichinter') { $newclassname = 'Intervention'; + } print '
    '.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).'
    '.$langs->trans('AmountHT').''.price($objectsrc->total_ht, 0, $langs, 1, -1, -1, $conf->currency).'
    '.$langs->trans('AmountVAT').''.price($objectsrc->total_tva, 0, $langs, 1, -1, -1, $conf->currency)."
    '.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($objectsrc->total_localtax1, 0, $langs, 1, -1, -1, $conf->currency)."
    '.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($objectsrc->total_localtax2, 0, $langs, 1, -1, -1, $conf->currency)."
    '.$langs->trans('AmountTTC').''.price($objectsrc->total_ttc, 0, $langs, 1, -1, -1, $conf->currency)."
    '.$langs->trans('MulticurrencyAmountHT').''.price($objectsrc->multicurrency_total_ht).'
    '.$langs->trans('MulticurrencyAmountVAT').''.price($objectsrc->multicurrency_total_tva)."
    '.$langs->trans('MulticurrencyAmountTTC').''.price($objectsrc->multicurrency_total_ttc)."
    '; // For backward compatibility @@ -1874,16 +1892,14 @@ if ($action == 'create') $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmClonePropal', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } - if ($action == 'closeas') - { + if ($action == 'closeas') { //Form to close proposal (signed or not) $formquestion = array( array('type' => 'select', 'name' => 'statut', 'label' => ''.$langs->trans("CloseAs").'', 'values' => array($object::STATUS_SIGNED => $object->LibStatut($object::STATUS_SIGNED), $object::STATUS_NOTSIGNED => $object->LibStatut($object::STATUS_NOTSIGNED))), array('type' => 'text', 'name' => 'note_private', 'label' => $langs->trans("Note"), 'value' => '') // Field to complete private note (not replace) ); - if (!empty($conf->notification->enabled)) - { + if (!empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; $notify = new Notify($db); $formquestion = array_merge($formquestion, array( @@ -1892,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 @@ -1925,15 +1941,19 @@ if ($action == 'create') $text .= $notify->confirmMessage('PROPAL_VALIDATE', $object->socid, $object); } - if (!$error) + if (!$error) { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateProp'), $text, 'confirm_validate', '', 0, 1); + } } // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -1949,16 +1969,17 @@ if ($action == 'create') $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer'); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherProposals").')'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' ('.$langs->trans("OtherProposals").')'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($usercancreate) - { - if ($action != 'classify') + if ($usercancreate) { + if ($action != 'classify') { $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= ''; @@ -2023,10 +2044,11 @@ if ($action == 'create') print '
    '; - if ($action != 'editdate' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) + if ($action != 'editdate' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) { print ''; + } print '
    '; print $langs->trans('Date'); print 'id.'">'.img_edit($langs->trans('SetDate'), 1).'
    '; - print '
    '; + print ''; if ($object->statut == Propal::STATUS_DRAFT && $action == 'editdate' && $usercancreate) { print ''; print ''; @@ -2049,10 +2071,11 @@ if ($action == 'create') print ''; - if ($action != 'editecheance' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) + if ($action != 'editecheance' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) { print ''; + } print '
    '; print $langs->trans('DateEndPropal'); print 'id.'">'.img_edit($langs->trans('SetConditions'), 1).'
    '; - print '
    '; + print ''; if ($object->statut == Propal::STATUS_DRAFT && $action == 'editecheance' && $usercancreate) { print ''; print ''; @@ -2063,8 +2086,9 @@ if ($action == 'create') } else { if (!empty($object->fin_validite)) { print dol_print_date($object->fin_validite, 'day'); - if ($object->statut == Propal::STATUS_VALIDATED && $object->fin_validite < ($now - $conf->propal->cloture->warning_delay)) + if ($object->statut == Propal::STATUS_VALIDATED && $object->fin_validite < ($now - $conf->propal->cloture->warning_delay)) { print img_warning($langs->trans("Late")); + } } else { print ' '; } @@ -2077,10 +2101,11 @@ if ($action == 'create') print ''; - if ($action != 'editconditions' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) + if ($action != 'editconditions' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) { print ''; + } print '
    '; print $langs->trans('PaymentConditionsShort'); print 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetConditions'), 1).'
    '; - print '
    '; + print ''; if ($object->statut == Propal::STATUS_DRAFT && $action == 'editconditions' && $usercancreate) { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id'); } else { @@ -2089,11 +2114,29 @@ 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 '
    '; print $form->editfieldkey($langs->trans('DeliveryDate'), 'date_livraison', $object->delivery_date, $object, $usercancreate, 'datepicker'); - print ''; + print ''; print $form->editfieldval($langs->trans('DeliveryDate'), 'date_livraison', $object->delivery_date, $object, $usercancreate, 'datepicker'); print '
    '; print ''; - if ($action != 'editavailability' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) + if ($action != 'editavailability' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) { print ''; + } print '
    '; print $langs->trans('AvailabilityPeriod'); - if (!empty($conf->commande->enabled)) + if (!empty($conf->commande->enabled)) { print ' ('.$langs->trans('AfterOrder').')'; + } print 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetAvailability'), 1).'
    '; - print '
    '; + print ''; if ($object->statut == Propal::STATUS_DRAFT && $action == 'editavailability' && $usercancreate) { $form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'availability_id', 1); } else { @@ -2124,10 +2169,11 @@ if ($action == 'create') print ''; - if ($action != 'editshippingmethod' && $usercancreate) + if ($action != 'editshippingmethod' && $usercancreate) { print ''; + } print '
    '; print $langs->trans('SendingMethod'); print 'id.'">'.img_edit($langs->trans('SetShippingMode'), 1).'
    '; - print '
    '; + print ''; if ($action == 'editshippingmethod' && $usercancreate) { $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); } else { @@ -2145,7 +2191,7 @@ if ($action == 'create') print '
    '; $editenable = $usercancreate; print $form->editfieldkey("Warehouse", 'warehouse', '', $object, $editenable); - print ''; + print ''; if ($action == 'editwarehouse') { $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1); } else { @@ -2160,10 +2206,11 @@ if ($action == 'create') print ''; - if ($action != 'editdemandreason' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) + if ($action != 'editdemandreason' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) { print ''; + } print '
    '; print $langs->trans('Source'); print 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetDemandReason'), 1).'
    '; - print '
    '; + print ''; if ($object->statut == Propal::STATUS_DRAFT && $action == 'editdemandreason' && $usercancreate) { $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'demand_reason_id', 1); } else { @@ -2172,36 +2219,19 @@ 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 '
    '; print ''; - if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT && $usercancreate) + if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT && $usercancreate) { print ''; + } print '
    '; print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0); print 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'
    '; - print '
    '; + print ''; if ($object->statut == $object::STATUS_DRAFT && $action == 'editmulticurrencycode' && $usercancreate) { $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code'); } else { @@ -2210,18 +2240,18 @@ if ($action == 'create') print '
    '; print ''; print ''; - if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency && $usercancreate) + if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency && $usercancreate) { print ''; + } print '
    '; print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0); print 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'
    '; - print '
    '; + print ''; if ($object->statut == $object::STATUS_DRAFT && ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') && $usercancreate) { if ($action == 'actualizemulticurrencyrate') { list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); @@ -2239,12 +2269,11 @@ if ($action == 'create') } } - if ($soc->outstanding_limit) - { + if ($soc->outstanding_limit) { // Outstanding Bill print '
    '; print $langs->trans('OutstandingBill'); - print ''; + print ''; $arrayoutstandingbills = $soc->getOutstandingBills(); print price($arrayoutstandingbills['opened']).' / '; print price($soc->outstanding_limit, 0, $langs, 1, - 1, - 1, $conf->currency); @@ -2252,17 +2281,17 @@ if ($action == 'create') print '
    '; print ''; - if ($action != 'editbankaccount' && $usercancreate) + if ($action != 'editbankaccount' && $usercancreate) { print ''; + } print '
    '; print $langs->trans('BankAccount'); print 'id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'
    '; - print '
    '; + print ''; if ($action == 'editbankaccount') { $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); } else { @@ -2277,31 +2306,32 @@ if ($action == 'create') $totalVolume = $tmparray['volume']; if ($totalWeight) { print '
    '.$langs->trans("CalculatedWeight").''; + print ''; print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND) ? $conf->global->MAIN_WEIGHT_DEFAULT_ROUND : -1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? $conf->global->MAIN_WEIGHT_DEFAULT_UNIT : 'no'); print '
    '.$langs->trans("CalculatedVolume").''; + print ''; print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND) ? $conf->global->MAIN_VOLUME_DEFAULT_ROUND : -1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT) ? $conf->global->MAIN_VOLUME_DEFAULT_UNIT : 'no'); print '
    '; print '
    '; print $langs->trans('IncotermLabel'); print ''; - if ($usercancreate) print ''.img_edit().''; - else print ' '; + if ($usercancreate) { + print ''.img_edit().''; + } else { + print ' '; + } print '
    '; print '
    '; - if ($action != 'editincoterm') - { + print ''; + if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1); } else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); @@ -2321,8 +2351,7 @@ if ($action == 'create') 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 ''; @@ -2350,14 +2379,12 @@ if ($action == 'create') print ''; // Amount Local Taxes - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) // Localtax1 - { + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { // Localtax1 print ''; print ''; print ''; } - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) // Localtax2 - { + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { // Localtax2 print ''; print ''; print ''; @@ -2374,8 +2401,7 @@ if ($action == 'create') 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)).'
    '.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency).'
    '.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency).'
    '; // Margin Infos - if (!empty($conf->margin->enabled)) - { + if (!empty($conf->margin->enabled)) { $formmargin->displayMarginInfos($object); } @@ -2416,19 +2442,16 @@ if ($action == 'create') } print '
    '; - if (!empty($object->lines) || ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines' && $action != 'editline')) - { + if (!empty($object->lines) || ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines' && $action != 'editline')) { print ''; } - if (!empty($object->lines)) - { + if (!empty($object->lines)) { $ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 1); } // Form to add new line - if ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines') - { + if ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines') { if ($action != 'editline') { // Add products/services form $object->formAddObjectLine(1, $mysoc, $soc); @@ -2441,8 +2464,7 @@ if ($action == 'create') } } - if (!empty($object->lines) || ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines' && $action != 'editline')) - { + if (!empty($object->lines) || ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines' && $action != 'editline')) { print '
    '; } print '
    '; @@ -2462,18 +2484,16 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { - if ($action != 'editline') - { + if (empty($reshook)) { + if ($action != 'editline') { // Validate if (($object->statut == Propal::STATUS_DRAFT && $object->total_ttc >= 0 && count($object->lines) > 0) - || ($object->statut == Propal::STATUS_DRAFT && !empty($conf->global->PROPAL_ENABLE_NEGATIVE) && count($object->lines) > 0)) - { - if ($usercanvalidate) - { + || ($object->statut == Propal::STATUS_DRAFT && !empty($conf->global->PROPAL_ENABLE_NEGATIVE) && count($object->lines) > 0)) { + if ($usercanvalidate) { print ''.$langs->trans('Validate').''; - } else print ''.$langs->trans('Validate').''; + } else { + print ''.$langs->trans('Validate').''; + } } // Create event /*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page. @@ -2496,7 +2516,9 @@ if ($action == 'create') if ($object->statut == Propal::STATUS_VALIDATED || $object->statut == Propal::STATUS_SIGNED || !empty($conf->global->PROPOSAL_SENDBYEMAIL_FOR_ALL_STATUS)) { if ($usercansend) { print ''.$langs->trans('SendMail').''; - } else print ''.$langs->trans('SendMail').''; + } else { + print ''.$langs->trans('SendMail').''; + } } } @@ -2508,8 +2530,7 @@ if ($action == 'create') } // Create a purchase order - if (!empty($conf->global->WORKFLOW_CAN_CREATE_PURCHASE_ORDER_FROM_PROPOSAL)) - { + if (!empty($conf->global->WORKFLOW_CAN_CREATE_PURCHASE_ORDER_FROM_PROPOSAL)) { if (!empty($conf->fournisseur->enabled) && $object->statut == Propal::STATUS_SIGNED) { if ($usercancreatepurchaseorder) { print ''.$langs->trans("AddPurchaseOrder").''; @@ -2535,18 +2556,14 @@ if ($action == 'create') } // Create an invoice and classify billed - if ($object->statut == Propal::STATUS_SIGNED) - { - if (!empty($conf->facture->enabled) && $usercancreateinvoice) - { + if ($object->statut == Propal::STATUS_SIGNED) { + if (!empty($conf->facture->enabled) && $usercancreateinvoice) { print ''.$langs->trans("AddBill").''; } $arrayofinvoiceforpropal = $object->getInvoiceArrayList(); - if ((is_array($arrayofinvoiceforpropal) && count($arrayofinvoiceforpropal) > 0) || empty($conf->global->WORKFLOW_PROPAL_NEED_INVOICE_TO_BE_CLASSIFIED_BILLED)) - { - if ($usercanclose) - { + if ((is_array($arrayofinvoiceforpropal) && count($arrayofinvoiceforpropal) > 0) || empty($conf->global->WORKFLOW_PROPAL_NEED_INVOICE_TO_BE_CLASSIFIED_BILLED)) { + if ($usercanclose) { print 'socid.'">'.$langs->trans("ClassifyBilled").''; } else { print ''.$langs->trans("ClassifyBilled").''; @@ -2577,14 +2594,15 @@ if ($action == 'create') } //Select mail models is same action as presend - if (GETPOST('modelselected')) $action = 'presend'; + if (GETPOST('modelselected')) { + $action = 'presend'; + } - if ($action != 'presend') - { + if ($action != 'presend') { print '
    '; print ''; // ancre /* - * Documents generes + * Generated documents */ $objref = dol_sanitizeFileName($object->ref); $filedir = $conf->propal->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref); @@ -2598,8 +2616,7 @@ if ($action == 'create') $linktoelem = $form->showLinkToObjectBlock($object, null, array('propal')); $compatibleImportElementsList = false; - if ($user->rights->propal->creer && $object->statut == Propal::STATUS_DRAFT) - { + if ($user->rights->propal->creer && $object->statut == Propal::STATUS_DRAFT) { $compatibleImportElementsList = array('commande', 'propal'); // import from linked elements } $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList); @@ -2607,16 +2624,14 @@ if ($action == 'create') // Show online signature link $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok - if ($object->statut != Propal::STATUS_DRAFT && $useonlinesignature) - { + if ($object->statut != Propal::STATUS_DRAFT && $useonlinesignature) { print '
    '; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; print showOnlineSignatureUrl('proposal', $object->ref).'
    '; } // Show direct download link - if ($object->statut != Propal::STATUS_DRAFT && !empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) - { + if ($object->statut != Propal::STATUS_DRAFT && !empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) { print '
    '."\n"; print showDirectDownloadLink($object).'
    '; } diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index fd2cb3d371c..84d7cf23385 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -162,28 +162,37 @@ class Proposals extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."propal as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= ' WHERE t.entity IN ('.getEntity('propal').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -192,8 +201,7 @@ class Proposals extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -204,13 +212,11 @@ class Proposals extends DolibarrApi dol_syslog("API Rest request"); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $proposal_static = new Propal($this->db); if ($proposal_static->fetch($obj->rowid)) { @@ -247,12 +253,12 @@ class Proposals extends DolibarrApi $this->propal->$field = $value; } /*if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->propal->lines = $lines; - }*/ + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->propal->lines = $lines; + }*/ if ($this->propal->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating order", array_merge(array($this->propal->error), $this->propal->errors)); } @@ -304,7 +310,7 @@ class Proposals extends DolibarrApi public function postLine($id, $request_data = null) { if (!DolibarrApiAccess::$user->rights->propal->creer) { - throw new RestException(401); + throw new RestException(401); } $result = $this->propal->fetch($id); @@ -319,32 +325,32 @@ class Proposals extends DolibarrApi $request_data = (object) $request_data; $updateRes = $this->propal->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - 'HT', - 0, - $request_data->info_bits, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $request_data->fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->date_start, - $request_data->date_end, - $request_data->array_options, - $request_data->fk_unit, - $request_data->origin, - $request_data->origin_id, - $request_data->multicurrency_subprice, - $request_data->fk_remise_except + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + 'HT', + 0, + $request_data->info_bits, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $request_data->fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->date_start, + $request_data->date_end, + $request_data->array_options, + $request_data->fk_unit, + $request_data->origin, + $request_data->origin_id, + $request_data->multicurrency_subprice, + $request_data->fk_remise_except ); if ($updateRes > 0) { @@ -378,15 +384,15 @@ class Proposals extends DolibarrApi if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + } - $request_data = (object) $request_data; + $request_data = (object) $request_data; - $propalline = new PropaleLigne($this->db); - $result = $propalline->fetch($lineid); - if ($result <= 0) { - throw new RestException(404, 'Proposal line not found'); - } + $propalline = new PropaleLigne($this->db); + $result = $propalline->fetch($lineid); + if ($result <= 0) { + throw new RestException(404, 'Proposal line not found'); + } $updateRes = $this->propal->updateline( $lineid, @@ -572,25 +578,23 @@ class Proposals extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->propal->$field = $value; } // update end of validity date - if (empty($this->propal->fin_validite) && !empty($this->propal->duree_validite) && !empty($this->propal->date_creation)) - { + if (empty($this->propal->fin_validite) && !empty($this->propal->duree_validite) && !empty($this->propal->date_creation)) { $this->propal->fin_validite = $this->propal->date_creation + ($this->propal->duree_validite * 24 * 3600); } - if (!empty($this->propal->fin_validite)) - { - if ($this->propal->set_echeance(DolibarrApiAccess::$user, $this->propal->fin_validite) < 0) - { + if (!empty($this->propal->fin_validite)) { + if ($this->propal->set_echeance(DolibarrApiAccess::$user, $this->propal->fin_validite) < 0) { throw new RestException(500, $this->propal->error); } } - if ($this->propal->update(DolibarrApiAccess::$user) > 0) - { + if ($this->propal->update(DolibarrApiAccess::$user) > 0) { return $this->get($id); } else { throw new RestException(500, $this->propal->error); @@ -834,8 +838,9 @@ class Proposals extends DolibarrApi { $propal = array(); foreach (Proposals::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $propal[$field] = $data[$field]; } return $propal; diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index a115d8bca5e..197c9c7074f 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -13,7 +13,7 @@ * Copyright (C) 2013 Florian Henry * Copyright (C) 2014-2015 Marcos García * Copyright (C) 2018 Nicolas ZABOURI - * Copyright (C) 2018-2020 Frédéric France + * Copyright (C) 2018-2021 Frédéric France * Copyright (C) 2018 Ferran Marcet * * This program is free software; you can redistribute it and/or modify @@ -285,10 +285,10 @@ class Propal extends CommonObject 'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>115), //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>120), 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>125, 'isameasure'=>1), - 'tva' =>array('type'=>'double(24,8)', 'label'=>'VAT', 'enabled'=>1, 'visible'=>-1, 'position'=>130, 'isameasure'=>1), + 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'VAT', 'enabled'=>1, 'visible'=>-1, 'position'=>130, 'isameasure'=>1), 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'LocalTax1', 'enabled'=>1, 'visible'=>-1, 'position'=>135, 'isameasure'=>1), 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'LocalTax2', 'enabled'=>1, 'visible'=>-1, 'position'=>140, 'isameasure'=>1), - 'total' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>145, 'isameasure'=>1), + 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>145, 'isameasure'=>1), 'fk_account' =>array('type'=>'integer', 'label'=>'BankAccount', 'enabled'=>1, 'visible'=>-1, 'position'=>150), 'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Currency', 'enabled'=>1, 'visible'=>-1, 'position'=>155), 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'position'=>160), @@ -376,11 +376,12 @@ class Propal extends CommonObject // phpcs:enable global $conf, $mysoc; - if (!$qty) $qty = 1; + if (!$qty) { + $qty = 1; + } dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent"); - if ($idproduct > 0) - { + if ($idproduct > 0) { $prod = new Product($this->db); $prod->fetch($idproduct); @@ -388,15 +389,16 @@ class Propal extends CommonObject $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id); $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $vat_src_code = ''; // May be defined into tva_tx $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $this->thirdparty, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $this->thirdparty, $tva_npr); // multiprices - if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) - { + if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) { $price = $prod->multiprices[$this->thirdparty->price_level]; } else { $price = $prod->price; @@ -412,7 +414,9 @@ class Propal extends CommonObject $line->vat_src_code = $vat_src_code; $line->tva_tx = $tva_tx; $line->fk_unit = $prod->fk_unit; - if ($tva_npr) $line->info_bits = 1; + if ($tva_npr) { + $line->info_bits = 1; + } $this->lines[] = $line; } @@ -438,10 +442,8 @@ class Propal extends CommonObject $remise = new DiscountAbsolute($this->db); $result = $remise->fetch($idremise); - if ($result > 0) - { - if ($remise->fk_facture) // Protection against multiple submission - { + if ($result > 0) { + if ($remise->fk_facture) { // Protection against multiple submission $this->error = $langs->trans("ErrorDiscountAlreadyUsed"); $this->db->rollback(); return -5; @@ -472,11 +474,9 @@ class Propal extends CommonObject $line->total_ttc = -$remise->amount_ttc; $result = $line->insert(); - if ($result > 0) - { + if ($result > 0) { $result = $this->update_price(1); - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return 1; } else { @@ -537,16 +537,25 @@ class Propal extends CommonObject dol_syslog(get_class($this)."::addline propalid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_except=$remise_percent, price_base_type=$price_base_type, pu_ttc=$pu_ttc, info_bits=$info_bits, type=$type, fk_remise_except=".$fk_remise_except); - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - if (empty($remise_percent)) $remise_percent = 0; - if (empty($qty)) $qty = 0; - if (empty($info_bits)) $info_bits = 0; - if (empty($rang)) $rang = 0; - if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0; + if (empty($remise_percent)) { + $remise_percent = 0; + } + if (empty($qty)) { + $qty = 0; + } + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($rang)) { + $rang = 0; + } + if (empty($fk_parent_line) || $fk_parent_line < 0) { + $fk_parent_line = 0; + } $remise_percent = price2num($remise_percent); $qty = price2num($qty); @@ -559,15 +568,16 @@ class Propal extends CommonObject $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); $pa_ht = price2num($pa_ht); - if ($price_base_type == 'HT') - { + if ($price_base_type == 'HT') { $pu = $pu_ht; } else { $pu = $pu_ttc; } // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); @@ -578,8 +588,7 @@ class Propal extends CommonObject $this->db->begin(); $product_type = $type; - if (!empty($fk_product)) - { + if (!empty($fk_product)) { $product = new Product($this->db); $result = $product->fetch($fk_product); $product_type = $product->type; @@ -603,8 +612,7 @@ class Propal extends CommonObject $reg = array(); $vat_src_code = ''; $reg = array(); - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -628,8 +636,7 @@ class Propal extends CommonObject // Rang to use $ranktouse = $rang; - if ($ranktouse == -1) - { + if ($ranktouse == -1) { $rangmax = $this->line_max($fk_parent_line); $ranktouse = $rangmax + 1; } @@ -638,8 +645,7 @@ class Propal extends CommonObject // Anciens indicateurs: $price, $remise (a ne plus utiliser) $price = $pu; $remise = 0; - if ($remise_percent > 0) - { + if ($remise_percent > 0) { $remise = round(($pu * $remise_percent / 100), 2); $price = $pu - $remise; } @@ -694,7 +700,9 @@ class Propal extends CommonObject $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; // Mise en option de la ligne - if (empty($qty) && empty($special_code)) $this->line->special_code = 3; + if (empty($qty) && empty($special_code)) { + $this->line->special_code = 3; + } // TODO deprecated $this->line->price = $price; @@ -705,10 +713,11 @@ class Propal extends CommonObject } $result = $this->line->insert(); - if ($result > 0) - { + if ($result > 0) { // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) { + $this->line_order(true, 'DESC'); + } // Mise a jour informations denormalisees au niveau de la propale meme $result = $this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. @@ -781,9 +790,15 @@ class Propal extends CommonObject $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); $pa_ht = price2num($pa_ht); - if (empty($qty) && empty($special_code)) $special_code = 3; // Set option tag - if (!empty($qty) && $special_code == 3) $special_code = 0; // Remove option tag - if (empty($type)) $type = 0; + if (empty($qty) && empty($special_code)) { + $special_code = 3; // Set option tag + } + if (!empty($qty) && $special_code == 3) { + $special_code = 0; // Remove option tag + } + if (empty($type)) { + $type = 0; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); @@ -791,8 +806,7 @@ class Propal extends CommonObject return -1; } - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { $this->db->begin(); // Calcul du total TTC et de la TVA pour la ligne a partir de @@ -805,8 +819,7 @@ class Propal extends CommonObject // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -830,8 +843,7 @@ class Propal extends CommonObject // Anciens indicateurs: $price, $remise (a ne plus utiliser) $price = $pu; $remise = 0; - if ($remise_percent > 0) - { + if ($remise_percent > 0) { $remise = round(($pu * $remise_percent / 100), 2); $price = $pu - $remise; } @@ -847,8 +859,7 @@ class Propal extends CommonObject $this->line->context = $this->context; // Reorder if fk_parent_line change - if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) - { + if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) { $rangmax = $this->line_max($fk_parent_line); $this->line->rang = $rangmax + 1; } @@ -902,10 +913,11 @@ class Propal extends CommonObject $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; $result = $this->line->update($notrigger); - if ($result > 0) - { + if ($result > 0) { // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) { + $this->line_order(true, 'DESC'); + } $this->update_price(1); @@ -937,8 +949,7 @@ class Propal extends CommonObject { global $user; - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { $this->db->begin(); $line = new PropaleLigne($this->db); @@ -946,8 +957,7 @@ class Propal extends CommonObject // For triggers $line->fetch($lineid); - if ($line->delete($user) > 0) - { + if ($line->delete($user) > 0) { $this->update_price(1); $this->db->commit(); @@ -979,16 +989,24 @@ class Propal extends CommonObject $now = dol_now(); // Clean parameters - if (empty($this->date)) $this->date = $this->datep; + if (empty($this->date)) { + $this->date = $this->datep; + } $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600); - if (empty($this->availability_id)) $this->availability_id = 0; - if (empty($this->demand_reason_id)) $this->demand_reason_id = 0; + if (empty($this->availability_id)) { + $this->availability_id = 0; + } + if (empty($this->demand_reason_id)) { + $this->demand_reason_id = 0; + } // 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)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date); - else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); - if (empty($this->fk_multicurrency)) - { + if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) { + list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date); + } else { + $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); + } + if (empty($this->fk_multicurrency)) { $this->multicurrency_code = $conf->currency; $this->fk_multicurrency = 0; $this->multicurrency_tx = 1; @@ -1001,19 +1019,16 @@ class Propal extends CommonObject // Check parameters $result = $this->fetch_thirdparty(); - if ($result < 0) - { + if ($result < 0) { $this->error = "Failed to fetch company"; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -3; } // Check parameters - if (!empty($this->ref)) // We check that ref is not already used - { + if (!empty($this->ref)) { // We check that ref is not already used $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used - if ($result > 0) - { + if ($result > 0) { $this->error = 'ErrorRefAlreadyExists'; dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); $this->db->rollback(); @@ -1021,8 +1036,7 @@ class Propal extends CommonObject } } - if (empty($this->date)) - { + if (empty($this->date)) { $this->error = "Date of proposal is required"; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -4; @@ -1038,8 +1052,8 @@ class Propal extends CommonObject $sql .= ", remise"; $sql .= ", remise_percent"; $sql .= ", remise_absolue"; - $sql .= ", tva"; - $sql .= ", total"; + $sql .= ", total_tva"; + $sql .= ", total_ttc"; $sql .= ", datep"; $sql .= ", datec"; $sql .= ", ref"; @@ -1101,36 +1115,30 @@ class Propal extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal"); - if ($this->id) - { + if ($this->id) { $this->ref = '(PROV'.$this->id.')'; $sql = 'UPDATE '.MAIN_DB_PREFIX."propal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } - if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects - { + if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) - { - foreach ($this->linked_objects as $origin => $tmp_origin_id) - { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { + if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) { + foreach ($this->linked_objects as $origin => $tmp_origin_id) { + if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { $this->error = $this->db->lasterror(); $error++; } @@ -1139,8 +1147,7 @@ class Propal extends CommonObject { $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { $this->error = $this->db->lasterror(); $error++; } @@ -1149,18 +1156,16 @@ class Propal extends CommonObject } /* - * Insertion du detail des produits dans la base - * Insert products detail in database - */ - if (!$error) - { + * Insertion du detail des produits dans la base + * Insert products detail in database + */ + if (!$error) { $fk_parent_line = 0; $num = count($this->lines); - for ($i = 0; $i < $num; $i++) - { - if (!is_object($this->lines[$i])) // If this->lines is not array of objects, coming from REST API - { // Convert into object this->lines[$i]. + for ($i = 0; $i < $num; $i++) { + if (!is_object($this->lines[$i])) { // If this->lines is not array of objects, coming from REST API + // Convert into object this->lines[$i]. $line = (object) $this->lines[$i]; } else { $line = $this->lines[$i]; @@ -1171,7 +1176,9 @@ class Propal extends CommonObject } // Complete vat rate with code $vatrate = $line->tva_tx; - if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) $vatrate .= ' ('.$line->vat_src_code.')'; + if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) { + $vatrate .= ' ('.$line->vat_src_code.')'; + } if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) { $originid = $line->origin_id; @@ -1208,8 +1215,7 @@ class Propal extends CommonObject $originid ); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $this->db->error; dol_print_error($this->db); @@ -1233,29 +1239,26 @@ class Propal extends CommonObject $result=$this->db->query($sql); }*/ - if (!$error) - { + if (!$error) { // Mise a jour infos denormalisees $resql = $this->update_price(1); - if ($resql) - { + if ($resql) { $action = 'update'; // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('PROPAL_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } else { @@ -1268,8 +1271,7 @@ class Propal extends CommonObject $error++; } - if (!$error) - { + if (!$error) { $this->db->commit(); dol_syslog(get_class($this)."::create done id=".$this->id); return $this->id; @@ -1313,25 +1315,23 @@ class Propal extends CommonObject $objsoc = new Societe($this->db); // Change socid if needed - if (!empty($socid) && $socid != $object->socid) - { - if ($objsoc->fetch($socid) > 0) - { + if (!empty($socid) && $socid != $object->socid) { + if ($objsoc->fetch($socid) > 0) { $object->socid = $objsoc->id; $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); $object->fk_delivery_address = ''; /*if (!empty($conf->projet->enabled)) - { - $project = new Project($db); - if ($this->fk_project > 0 && $project->fetch($this->fk_project)) { - if ($project->socid <= 0) $clonedObj->fk_project = $this->fk_project; - else $clonedObj->fk_project = ''; - } else { - $clonedObj->fk_project = ''; - } - }*/ + { + $project = new Project($db); + if ($this->fk_project > 0 && $project->fetch($this->fk_project)) { + if ($project->socid <= 0) $clonedObj->fk_project = $this->fk_project; + else $clonedObj->fk_project = ''; + } else { + $clonedObj->fk_project = ''; + } + }*/ $object->fk_project = ''; // A cloned proposal is set by default to no project. } @@ -1354,58 +1354,54 @@ class Propal extends CommonObject $object->date = $now; $object->datep = $now; // deprecated $object->fin_validite = $object->date + ($object->duree_validite * 24 * 3600); - if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $object->ref_client = ''; - if ($conf->global->MAIN_DONT_KEEP_NOTE_ON_CLONING == 1) - { + if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) { + $object->ref_client = ''; + } + if ($conf->global->MAIN_DONT_KEEP_NOTE_ON_CLONING == 1) { $object->note_private = ''; $object->note_public = ''; } // Create clone $object->context['createfromclone'] = 'createfromclone'; $result = $object->create($user); - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $this->errors = array_merge($this->errors, $object->errors); $error++; } - if (!$error) - { + if (!$error) { // copy internal contacts - if ($object->copy_linked_contact($this, 'internal') < 0) - { + if ($object->copy_linked_contact($this, 'internal') < 0) { $error++; } } - if (!$error) - { + if (!$error) { // copy external contacts if same company - if ($this->socid == $object->socid) - { - if ($object->copy_linked_contact($this, 'external') < 0) + if ($this->socid == $object->socid) { + if ($object->copy_linked_contact($this, 'external') < 0) { $error++; + } } } - if (!$error) - { + if (!$error) { // Hook of thirdparty module - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('objFrom'=>$this, 'clonedObj'=>$object); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } } } unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { @@ -1425,7 +1421,7 @@ class Propal extends CommonObject public function fetch($rowid, $ref = '', $ref_ext = '') { $sql = "SELECT p.rowid, p.ref, p.entity, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc"; - $sql .= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; + $sql .= ", p.total_ttc, p.total_tva, p.localtax1, p.localtax2, p.total_ht"; $sql .= ", p.datec"; $sql .= ", p.date_valid as datev"; $sql .= ", p.datep as dp"; @@ -1463,14 +1459,14 @@ class Propal extends CommonObject if ($ref) { $sql .= " WHERE p.entity IN (".getEntity('propal').")"; // Dont't use entity if you use rowid $sql .= " AND p.ref='".$this->db->escape($ref)."'"; - } else $sql .= " WHERE p.rowid=".$rowid; + } else { + $sql .= " WHERE p.rowid=".$rowid; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -1481,12 +1477,12 @@ class Propal extends CommonObject $this->remise = $obj->remise; $this->remise_percent = $obj->remise_percent; $this->remise_absolue = $obj->remise_absolue; - $this->total = $obj->total; // TODO deprecated + $this->total = $obj->total_ttc; // TODO deprecated + $this->total_ttc = $obj->total_ttc; $this->total_ht = $obj->total_ht; - $this->total_tva = $obj->tva; + $this->total_tva = $obj->total_tva; $this->total_localtax1 = $obj->localtax1; $this->total_localtax2 = $obj->localtax2; - $this->total_ttc = $obj->total; $this->socid = $obj->fk_soc; $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty @@ -1537,8 +1533,8 @@ class Propal extends CommonObject $this->extraparams = (array) json_decode($obj->extraparams, true); $this->user_author_id = $obj->fk_user_author; - $this->user_valid_id = $obj->fk_user_valid; - $this->user_close_id = $obj->fk_user_cloture; + $this->user_valid_id = $obj->fk_user_valid; + $this->user_close_id = $obj->fk_user_cloture; //Incoterms $this->fk_incoterms = $obj->fk_incoterms; @@ -1550,11 +1546,10 @@ class Propal extends CommonObject $this->multicurrency_code = $obj->multicurrency_code; $this->multicurrency_tx = $obj->multicurrency_tx; $this->multicurrency_total_ht = $obj->multicurrency_total_ht; - $this->multicurrency_total_tva = $obj->multicurrency_total_tva; - $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; + $this->multicurrency_total_tva = $obj->multicurrency_total_tva; + $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - if ($obj->fk_statut == self::STATUS_DRAFT) - { + if ($obj->fk_statut == self::STATUS_DRAFT) { $this->brouillon = 1; } @@ -1568,8 +1563,7 @@ class Propal extends CommonObject // Lines $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { return -3; } @@ -1598,13 +1592,27 @@ class Propal extends CommonObject $error = 0; // Clean parameters - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->ref_client)) $this->ref_client = trim($this->ref_client); - if (isset($this->note) || isset($this->note_private)) $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note)); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf); - if (isset($this->import_key)) $this->import_key = trim($this->import_key); - if (!empty($this->duree_validite) && is_numeric($this->duree_validite)) $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600); + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->ref_client)) { + $this->ref_client = trim($this->ref_client); + } + if (isset($this->note) || isset($this->note_private)) { + $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note)); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->model_pdf)) { + $this->model_pdf = trim($this->model_pdf); + } + if (isset($this->import_key)) { + $this->import_key = trim($this->import_key); + } + if (!empty($this->duree_validite) && is_numeric($this->duree_validite)) { + $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600); + } // Check parameters // Put here code to add control on parameters values @@ -1616,13 +1624,15 @@ class Propal extends CommonObject $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").","; $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").","; $sql .= " datep=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').","; - if (!empty($this->fin_validite)) $sql .= " fin_validite=".(strval($this->fin_validite) != '' ? "'".$this->db->idate($this->fin_validite)."'" : 'null').","; + if (!empty($this->fin_validite)) { + $sql .= " fin_validite=".(strval($this->fin_validite) != '' ? "'".$this->db->idate($this->fin_validite)."'" : 'null').","; + } $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').","; - $sql .= " tva=".(isset($this->total_tva) ? $this->total_tva : "null").","; + $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").","; $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").","; $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").","; $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").","; - $sql .= " total=".(isset($this->total_ttc) ? $this->total_ttc : "null").","; + $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").","; $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").","; $sql .= " fk_user_author=".(isset($this->user_author_id) ? $this->user_author_id : "null").","; $sql .= " fk_user_valid=".(isset($this->user_valid) ? $this->user_valid : "null").","; @@ -1634,38 +1644,36 @@ 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) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -1703,20 +1711,20 @@ class Propal extends CommonObject $sql .= ' FROM '.MAIN_DB_PREFIX.'propaldet as d'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (d.fk_product = p.rowid)'; $sql .= ' WHERE d.fk_propal = '.$this->id; - if ($only_product) $sql .= ' AND p.fk_product_type = 0'; + if ($only_product) { + $sql .= ' AND p.fk_product_type = 0'; + } $sql .= ' ORDER by d.rang'; dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($result); $line = new PropaleLigne($this->db); @@ -1824,15 +1832,13 @@ class Propal extends CommonObject $error = 0; // Protection - if ($this->statut == self::STATUS_VALIDATED) - { + if ($this->statut == self::STATUS_VALIDATED) { dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); return 0; } if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->propal_advance->validate)))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->propal_advance->validate)))) { $this->error = 'ErrorPermissionDenied'; dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); return -1; @@ -1847,8 +1853,7 @@ class Propal extends CommonObject $soc->fetch($this->socid); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($soc); } else { $num = $this->ref; @@ -1862,49 +1867,47 @@ class Propal extends CommonObject dol_syslog(get_class($this)."::valid", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $error++; } // Trigger calls - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('PROPAL_VALIDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'propale/".$this->db->escape($this->newref)."'"; $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(); } + if (!$resql) { + $error++; + $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->propal->multidir_output[$this->entity].'/'.$oldref; $dirdest = $conf->propal->multidir_output[$this->entity].'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -1942,15 +1945,13 @@ class Propal extends CommonObject public function set_date($user, $date, $notrigger = 0) { // phpcs:enable - if (empty($date)) - { + if (empty($date)) { $this->error = 'ErrorBadParameter'; dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR); return -1; } - if (!empty($user->rights->propal->creer)) - { + if (!empty($user->rights->propal->creer)) { $error = 0; $this->db->begin(); @@ -1960,34 +1961,31 @@ class Propal extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->date = $date; $this->datep = $date; // deprecated } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2009,8 +2007,7 @@ class Propal extends CommonObject public function set_echeance($user, $date_fin_validite, $notrigger = 0) { // phpcs:enable - if (!empty($user->rights->propal->creer)) - { + if (!empty($user->rights->propal->creer)) { $error = 0; $this->db->begin(); @@ -2020,34 +2017,31 @@ class Propal extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->fin_validite = $date_fin_validite; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2083,8 +2077,7 @@ class Propal extends CommonObject */ public function setDeliveryDate($user, $delivery_date, $notrigger = 0) { - if (!empty($user->rights->propal->creer)) - { + if (!empty($user->rights->propal->creer)) { $error = 0; $this->db->begin(); @@ -2095,34 +2088,31 @@ class Propal extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->date_livraison = $delivery_date; $this->delivery_date = $delivery_date; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2144,8 +2134,7 @@ class Propal extends CommonObject public function set_availability($user, $id, $notrigger = 0) { // phpcs:enable - if (!empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) - { + if (!empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) { $error = 0; $this->db->begin(); @@ -2156,34 +2145,31 @@ class Propal extends CommonObject dol_syslog(__METHOD__.' availability('.$id.')', LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->fk_availability = $id; $this->availability_id = $id; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2211,8 +2197,7 @@ class Propal extends CommonObject public function set_demand_reason($user, $id, $notrigger = 0) { // phpcs:enable - if (!empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) - { + if (!empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) { $error = 0; $this->db->begin(); @@ -2223,36 +2208,33 @@ class Propal extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->fk_input_reason = $id; $this->demand_reason_id = $id; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2280,8 +2262,7 @@ class Propal extends CommonObject public function set_ref_client($user, $ref_client, $notrigger = 0) { // phpcs:enable - if (!empty($user->rights->propal->creer)) - { + if (!empty($user->rights->propal->creer)) { $error = 0; $this->db->begin(); @@ -2291,33 +2272,30 @@ class Propal extends CommonObject dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->ref_client = $ref_client; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2343,8 +2321,7 @@ class Propal extends CommonObject // phpcs:enable $remise = trim($remise) ?trim($remise) : 0; - if (!empty($user->rights->propal->creer)) - { + if (!empty($user->rights->propal->creer)) { $remise = price2num($remise); $error = 0; @@ -2356,34 +2333,31 @@ class Propal extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->remise_percent = $remise; $this->update_price(1); } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2408,8 +2382,7 @@ class Propal extends CommonObject // phpcs:enable $remise = trim($remise) ?trim($remise) : 0; - if (!empty($user->rights->propal->creer)) - { + if (!empty($user->rights->propal->creer)) { $remise = price2num($remise); $error = 0; @@ -2422,34 +2395,31 @@ class Propal extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->remise_absolue = $remise; $this->update_price(1); } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2478,7 +2448,9 @@ class Propal extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; $sql .= " SET fk_statut = ".$this->statut.","; - if (!empty($note)) $sql .= " note_private = '".$this->db->escape($note)."',"; + if (!empty($note)) { + $sql .= " note_private = '".$this->db->escape($note)."',"; + } $sql .= " date_cloture=NULL, fk_user_cloture=NULL"; $sql .= " WHERE rowid = ".$this->id; @@ -2487,26 +2459,24 @@ 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) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('PROPAL_REOPEN', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } // Commit or rollback - if ($error) - { - if (!empty($this->errors)) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + if (!empty($this->errors)) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2545,13 +2515,11 @@ class Propal extends CommonObject $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $modelpdf = $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED ? $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED : $this->model_pdf; $triggerName = 'PROPAL_CLOSE_REFUSED'; - if ($status == self::STATUS_SIGNED) - { + if ($status == self::STATUS_SIGNED) { $triggerName = 'PROPAL_CLOSE_SIGNED'; $modelpdf = $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL ? $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL : $this->model_pdf; @@ -2560,24 +2528,20 @@ class Propal extends CommonObject $soc->id = $this->socid; $result = $soc->set_as_client(); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->db->lasterror(); $this->db->rollback(); return -2; } } - if ($status == self::STATUS_BILLED) // ->cloture() can also be called when we set it to billed, after setting it to signed - { + if ($status == self::STATUS_BILLED) { // ->cloture() can also be called when we set it to billed, after setting it to signed $triggerName = 'PROPAL_CLASSIFY_BILLED'; } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); @@ -2586,24 +2550,23 @@ class Propal extends CommonObject $this->generateDocument($modelpdf, $outputlangs); } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->statut = $status; $this->date_cloture = $now; $this->note_private = $newprivatenote; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger($triggerName, $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -2639,33 +2602,30 @@ class Propal extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->statut = self::STATUS_BILLED; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2688,8 +2648,7 @@ class Propal extends CommonObject $error = 0; // Protection - if ($this->statut <= self::STATUS_DRAFT) - { + if ($this->statut <= self::STATUS_DRAFT) { return 0; } @@ -2702,35 +2661,32 @@ class Propal extends CommonObject $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->statut = self::STATUS_DRAFT; $this->brouillon = 1; $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2764,38 +2720,42 @@ class Propal extends CommonObject $sql = "SELECT s.rowid, s.nom as name, s.client,"; $sql .= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; $sql .= " p.datep as dp, p.fin_validite as datelimite"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user"; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE p.entity IN (".getEntity('propal').")"; $sql .= " AND p.fk_soc = s.rowid"; $sql .= " AND p.fk_statut = c.id"; - if (!$user->rights->societe->client->voir && !$socid) //restriction - { + if (!$user->rights->societe->client->voir && !$socid) { //restriction $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } - if ($socid) $sql .= " AND s.rowid = ".$socid; - if ($draft) $sql .= " AND p.fk_statut = ".self::STATUS_DRAFT; - if ($notcurrentuser > 0) $sql .= " AND p.fk_user_author <> ".$user->id; + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } + if ($draft) { + $sql .= " AND p.fk_statut = ".self::STATUS_DRAFT; + } + if ($notcurrentuser > 0) { + $sql .= " AND p.fk_user_author <> ".$user->id; + } $sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->plimit($limit, $offset); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); - if ($shortlist == 1) - { + if ($shortlist == 1) { $ga[$obj->propalid] = $obj->ref; - } elseif ($shortlist == 2) - { + } elseif ($shortlist == 2) { $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')'; } else { $ga[$i]['id'] = $obj->propalid; @@ -2837,25 +2797,19 @@ class Propal extends CommonObject $linkedInvoices = array(); $this->fetchObjectLinked($id, $this->element); - foreach ($this->linkedObjectsIds as $objecttype => $objectid) - { + foreach ($this->linkedObjectsIds as $objecttype => $objectid) { // Nouveau système du comon object renvoi des rowid et non un id linéaire de 1 à n // On parcourt donc une liste d'objets en tant qu'objet unique - foreach ($objectid as $key => $object) - { + foreach ($objectid as $key => $object) { // Cas des factures liees directement - if ($objecttype == 'facture') - { + if ($objecttype == 'facture') { $linkedInvoices[] = $object; - } // Cas des factures liees par un autre objet (ex: commande) - else { + } else { + // Cas des factures liees par un autre objet (ex: commande) $this->fetchObjectLinked($object, $objecttype); - foreach ($this->linkedObjectsIds as $subobjecttype => $subobjectid) - { - foreach ($subobjectid as $subkey => $subobject) - { - if ($subobjecttype == 'facture') - { + foreach ($this->linkedObjectsIds as $subobjecttype => $subobjectid) { + foreach ($subobjectid as $subkey => $subobject) { + if ($subobjecttype == 'facture') { $linkedInvoices[] = $subobject; } } @@ -2864,8 +2818,7 @@ class Propal extends CommonObject } } - if (count($linkedInvoices) > 0) - { + if (count($linkedInvoices) > 0) { $sql = "SELECT rowid as facid, ref, total, datef as df, fk_user_author, fk_statut, paye"; $sql .= " FROM ".MAIN_DB_PREFIX."facture"; $sql .= " WHERE rowid IN (".implode(',', $linkedInvoices).")"; @@ -2873,12 +2826,10 @@ class Propal extends CommonObject dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $tab_sqlobj = array(); $nump = $this->db->num_rows($resql); - for ($i = 0; $i < $nump; $i++) - { + for ($i = 0; $i < $nump; $i++) { $sqlobj = $this->db->fetch_object($resql); $tab_sqlobj[] = $sqlobj; } @@ -2886,11 +2837,9 @@ class Propal extends CommonObject $nump = count($tab_sqlobj); - if ($nump) - { + if ($nump) { $i = 0; - while ($i < $nump) - { + while ($i < $nump) { $obj = array_shift($tab_sqlobj); $ga[$i] = $obj; @@ -2902,7 +2851,9 @@ class Propal extends CommonObject } else { return -1; } - } else return $ga; + } else { + return $ga; + } } /** @@ -2924,7 +2875,9 @@ class Propal extends CommonObject if (!$notrigger) { // Call trigger $result = $this->call_trigger('PROPAL_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -2944,13 +2897,17 @@ class Propal extends CommonObject if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } if (!$error) { // Delete linked contacts $res = $this->delete_linked_contact(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } // Removed extrafields of object @@ -3032,45 +2989,41 @@ class Propal extends CommonObject { global $user; - if ($this->statut >= self::STATUS_DRAFT) - { + if ($this->statut >= self::STATUS_DRAFT) { $error = 0; $this->db->begin(); $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); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->availability_id = $availability_id; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -3100,45 +3053,41 @@ class Propal extends CommonObject // phpcs:enable global $user; - if ($this->statut >= self::STATUS_DRAFT) - { + if ($this->statut >= self::STATUS_DRAFT) { $error = 0; $this->db->begin(); $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); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->demand_reason_id = $demand_reason_id; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -3171,10 +3120,8 @@ class Propal extends CommonObject $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -3187,15 +3134,13 @@ class Propal extends CommonObject $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; @@ -3233,8 +3178,7 @@ class Propal extends CommonObject global $conf; // Init/load array of translation of status - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; $langs->load("propal"); $this->labelStatus[0] = $langs->transnoentitiesnoconv("PropalStatusDraft"); @@ -3250,11 +3194,17 @@ class Propal extends CommonObject } $statusType = ''; - if ($status == self::STATUS_DRAFT) $statusType = 'status0'; - elseif ($status == self::STATUS_VALIDATED) $statusType = 'status1'; - elseif ($status == self::STATUS_SIGNED) $statusType = 'status4'; - elseif ($status == self::STATUS_NOTSIGNED) $statusType = 'status9'; - elseif ($status == self::STATUS_BILLED) $statusType = 'status6'; + if ($status == self::STATUS_DRAFT) { + $statusType = 'status0'; + } elseif ($status == self::STATUS_VALIDATED) { + $statusType = 'status1'; + } elseif ($status == self::STATUS_SIGNED) { + $statusType = 'status4'; + } elseif ($status == self::STATUS_NOTSIGNED) { + $statusType = 'status9'; + } elseif ($status == self::STATUS_BILLED) { + $statusType = 'status6'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -3277,20 +3227,24 @@ class Propal extends CommonObject $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin, p.total_ht"; $sql .= " FROM ".MAIN_DB_PREFIX."propal as p"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = " AND"; } $sql .= $clause." p.entity IN (".getEntity('propal').")"; - if ($mode == 'opened') $sql .= " AND p.fk_statut = ".self::STATUS_VALIDATED; - if ($mode == 'signed') $sql .= " AND p.fk_statut = ".self::STATUS_SIGNED; - if ($user->socid) $sql .= " AND p.fk_soc = ".$user->socid; + if ($mode == 'opened') { + $sql .= " AND p.fk_statut = ".self::STATUS_VALIDATED; + } + if ($mode == 'signed') { + $sql .= " AND p.fk_statut = ".self::STATUS_SIGNED; + } + if ($user->socid) { + $sql .= " AND p.fk_soc = ".$user->socid; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $langs->load("propal"); $now = dol_now(); @@ -3319,16 +3273,13 @@ class Propal extends CommonObject $response->img = img_object('', "propal"); // This assignment in condition is not a bug. It allows walking the results. - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; $response->total += $obj->total_ht; - if ($mode == 'opened') - { + if ($mode == 'opened') { $datelimit = $this->db->jdate($obj->datefin); - if ($datelimit < ($now - $delay_warning)) - { + if ($datelimit < ($now - $delay_warning)) { $response->nbtodolate++; } } @@ -3364,12 +3315,10 @@ class Propal extends CommonObject $sql .= $this->db->plimit(100); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -3401,8 +3350,7 @@ class Propal extends CommonObject // Lines $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new PropaleLigne($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; $line->qty = 1; @@ -3411,8 +3359,7 @@ class Propal extends CommonObject $line->tva_tx = 20; $line->localtax1_tx = 0; $line->localtax2_tx = 0; - if ($xnbp == 2) - { + if ($xnbp == 2) { $line->total_ht = 50; $line->total_ttc = 60; $line->total_tva = 10; @@ -3424,8 +3371,7 @@ class Propal extends CommonObject $line->remise_percent = 00; } - if ($num_prods > 0) - { + if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; $line->product_ref = 'SPECIMEN'; @@ -3458,8 +3404,7 @@ class Propal extends CommonObject $sql = "SELECT count(p.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."propal as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -3467,11 +3412,9 @@ class Propal extends CommonObject $sql .= " ".$clause." p.entity IN (".getEntity('propal').")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // This assignment in condition is not a bug. It allows walking the results. - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["proposals"] = $obj->nb; } $this->db->free($resql); @@ -3498,8 +3441,7 @@ class Propal extends CommonObject $classname = $conf->global->PROPALE_ADDON; - if (!empty($classname)) - { + if (!empty($classname)) { $mybool = false; $file = $classname.".php"; @@ -3513,8 +3455,7 @@ class Propal extends CommonObject $mybool |= @include_once $dir.$file; } - if (!$mybool) - { + if (!$mybool) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -3523,8 +3464,7 @@ class Propal extends CommonObject $numref = ""; $numref = $obj->getNextValue($soc, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -3553,14 +3493,15 @@ class Propal extends CommonObject { global $langs, $conf, $user; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; $label = ''; $url = ''; - if ($user->rights->propal->lire) - { + if ($user->rights->propal->lire) { $label = img_picto('', $this->picto).' '.$langs->trans("Proposal").''; if (isset($this->statut)) { $label .= ' '.$this->getLibStatut(5); @@ -3594,20 +3535,21 @@ class Propal extends CommonObject $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id.$get_params; } - if ($option != 'nolink') - { + 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'; + } } } $linkclose = ''; - if (empty($notooltip) && $user->rights->propal->lire) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip) && $user->rights->propal->lire) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("Proposal"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -3620,8 +3562,12 @@ class Propal extends CommonObject $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; if ($addlinktonotes >= 0) { @@ -3649,7 +3595,9 @@ class Propal extends CommonObject $txttoshow .= dol_string_nohtmltag($this->note_public, 1); } if (!empty($this->note_private)) { - if (!empty($txttoshow)) $txttoshow .= '

    '; + if (!empty($txttoshow)) { + $txttoshow .= '

    '; + } $txttoshow .= dol_string_nohtmltag($this->note_private, 1); } } @@ -3898,12 +3846,10 @@ class PropaleLigne extends CommonObjectLine $sql .= ' WHERE pd.rowid = '.$rowid; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $objp = $this->db->fetch_object($result); - if ($objp) - { + if ($objp) { $this->id = $objp->rowid; $this->rowid = $objp->rowid; // deprecated $this->fk_propal = $objp->fk_propal; @@ -3984,32 +3930,70 @@ class PropaleLigne extends CommonObjectLine $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->localtax1_type)) $this->localtax1_type = 0; - if (empty($this->localtax2_type)) $this->localtax2_type = 0; - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; - if (empty($this->rang)) $this->rang = 0; - if (empty($this->remise)) $this->remise = 0; - if (empty($this->remise_percent) || !is_numeric($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->info_bits)) $this->info_bits = 0; - if (empty($this->special_code)) $this->special_code = 0; - if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; - if (empty($this->fk_fournprice)) $this->fk_fournprice = 0; - if (!is_numeric($this->qty)) $this->qty = 0; - if (empty($this->pa_ht)) $this->pa_ht = 0; - if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0; - if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0; - if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0; - if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0; + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->localtax1_type)) { + $this->localtax1_type = 0; + } + if (empty($this->localtax2_type)) { + $this->localtax2_type = 0; + } + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } + if (empty($this->rang)) { + $this->rang = 0; + } + if (empty($this->remise)) { + $this->remise = 0; + } + if (empty($this->remise_percent) || !is_numeric($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->info_bits)) { + $this->info_bits = 0; + } + if (empty($this->special_code)) { + $this->special_code = 0; + } + if (empty($this->fk_parent_line)) { + $this->fk_parent_line = 0; + } + if (empty($this->fk_fournprice)) { + $this->fk_fournprice = 0; + } + if (!is_numeric($this->qty)) { + $this->qty = 0; + } + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } + if (empty($this->multicurrency_subprice)) { + $this->multicurrency_subprice = 0; + } + if (empty($this->multicurrency_total_ht)) { + $this->multicurrency_total_ht = 0; + } + if (empty($this->multicurrency_total_tva)) { + $this->multicurrency_total_tva = 0; + } + if (empty($this->multicurrency_total_ttc)) { + $this->multicurrency_total_ttc = 0; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0 && $pa_ht_isemptystring) - { - if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) - { + if ($this->pa_ht == 0 && $pa_ht_isemptystring) { + if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { return $result; } else { $this->pa_ht = $result; @@ -4017,7 +4001,9 @@ class PropaleLigne extends CommonObjectLine } // Check parameters - if ($this->product_type < 0) return -1; + if ($this->product_type < 0) { + return -1; + } $this->db->begin(); @@ -4070,26 +4056,21 @@ class PropaleLigne extends CommonObjectLine dol_syslog(get_class($this).'::insert', LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->rowid = $this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet'); - if (!$error) - { + if (!$error) { $this->id = $this->rowid; $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINEPROPAL_INSERT', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -4121,26 +4102,21 @@ class PropaleLigne extends CommonObjectLine $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE rowid = ".$this->rowid; dol_syslog("PropaleLigne::delete", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { // Remove extrafields - if (!$error) - { + if (!$error) { $this->id = $this->rowid; $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINEPROPAL_DELETE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -4171,33 +4147,69 @@ class PropaleLigne extends CommonObjectLine $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. - if (empty($this->id) && !empty($this->rowid)) $this->id = $this->rowid; + if (empty($this->id) && !empty($this->rowid)) { + $this->id = $this->rowid; + } // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; - if (empty($this->localtax1_type)) $this->localtax1_type = 0; - if (empty($this->localtax2_type)) $this->localtax2_type = 0; - if (empty($this->marque_tx)) $this->marque_tx = 0; - if (empty($this->marge_tx)) $this->marge_tx = 0; - if (empty($this->price)) $this->price = 0; // TODO A virer - if (empty($this->remise)) $this->remise = 0; // TODO A virer - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->info_bits)) $this->info_bits = 0; - if (empty($this->special_code)) $this->special_code = 0; - if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; - if (empty($this->fk_fournprice)) $this->fk_fournprice = 0; - if (empty($this->subprice)) $this->subprice = 0; - if (empty($this->pa_ht)) $this->pa_ht = 0; + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } + if (empty($this->localtax1_type)) { + $this->localtax1_type = 0; + } + if (empty($this->localtax2_type)) { + $this->localtax2_type = 0; + } + if (empty($this->marque_tx)) { + $this->marque_tx = 0; + } + if (empty($this->marge_tx)) { + $this->marge_tx = 0; + } + if (empty($this->price)) { + $this->price = 0; // TODO A virer + } + if (empty($this->remise)) { + $this->remise = 0; // TODO A virer + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->info_bits)) { + $this->info_bits = 0; + } + if (empty($this->special_code)) { + $this->special_code = 0; + } + if (empty($this->fk_parent_line)) { + $this->fk_parent_line = 0; + } + if (empty($this->fk_fournprice)) { + $this->fk_fournprice = 0; + } + if (empty($this->subprice)) { + $this->subprice = 0; + } + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0 && $pa_ht_isemptystring) - { - if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) - { + if ($this->pa_ht == 0 && $pa_ht_isemptystring) { + if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { return $result; } else { $this->pa_ht = $result; @@ -4223,8 +4235,7 @@ class PropaleLigne extends CommonObjectLine $sql .= ", price=".price2num($this->price).""; // TODO A virer $sql .= ", remise=".price2num($this->remise).""; // TODO A virer $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'"; - if (empty($this->skip_update_total)) - { + if (empty($this->skip_update_total)) { $sql .= ", total_ht=".price2num($this->total_ht).""; $sql .= ", total_tva=".price2num($this->total_tva).""; $sql .= ", total_ttc=".price2num($this->total_ttc).""; @@ -4233,9 +4244,13 @@ class PropaleLigne extends CommonObjectLine } $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null"); $sql .= ", buy_price_ht=".price2num($this->pa_ht); - if (strlen($this->special_code)) $sql .= ", special_code=".$this->special_code; + if (strlen($this->special_code)) { + $sql .= ", special_code=".$this->special_code; + } $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null"); - if (!empty($this->rang)) $sql .= ", rang=".$this->rang; + if (!empty($this->rang)) { + $sql .= ", rang=".$this->rang; + } $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null"); $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null"); $sql .= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); @@ -4250,23 +4265,18 @@ class PropaleLigne extends CommonObjectLine dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$error) - { + if ($resql) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINEPROPAL_UPDATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -4304,8 +4314,7 @@ class PropaleLigne extends CommonObjectLine dol_syslog("PropaleLigne::update_total", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { diff --git a/htdocs/comm/propal/class/propalestats.class.php b/htdocs/comm/propal/class/propalestats.class.php index ca95be53fc1..f64bc31c6ac 100644 --- a/htdocs/comm/propal/class/propalestats.class.php +++ b/htdocs/comm/propal/class/propalestats.class.php @@ -69,8 +69,7 @@ class PropaleStats extends Stats $this->userid = $userid; $this->join = ''; - if ($mode == 'customer') - { + if ($mode == 'customer') { $object = new Propal($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as p"; @@ -81,8 +80,7 @@ class PropaleStats extends Stats //$this->where .= " p.fk_statut > 0"; } - if ($mode == 'supplier') - { + if ($mode == 'supplier') { $object = new SupplierProposal($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as p"; @@ -95,21 +93,22 @@ class PropaleStats extends Stats } //$this->where.= " AND p.fk_soc = s.rowid AND p.entity = ".$conf->entity; $this->where .= ($this->where ? ' AND ' : '')."p.entity IN (".getEntity('propal').")"; - if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($this->socid) - { + if (!$user->rights->societe->client->voir && !$this->socid) { + $this->where .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($this->socid) { $this->where .= " AND p.fk_soc = ".$this->socid; } - if ($this->userid > 0) $this->where .= ' AND fk_user_author = '.$this->userid; + if ($this->userid > 0) { + $this->where .= ' AND fk_user_author = '.$this->userid; + } - if ($typentid) - { + if ($typentid) { $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc'; $this->where .= ' AND s.fk_typent = '.$typentid; } - if ($categid) - { + if ($categid) { $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_societe as cs ON cs.fk_soc = p.fk_soc'; $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie as c ON c.rowid = cs.fk_categorie'; $this->where .= ' AND c.rowid = '.$categid; @@ -130,7 +129,9 @@ class PropaleStats extends Stats $sql = "SELECT date_format(".$this->field_date.",'%m') as dm, COUNT(*) as nb"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; @@ -153,7 +154,9 @@ class PropaleStats extends Stats $sql = "SELECT date_format(".$this->field_date.",'%Y') as dm, COUNT(*) as nb, SUM(c.".$this->field.")"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE ".$this->where; $sql .= " GROUP BY dm"; @@ -175,7 +178,9 @@ class PropaleStats extends Stats $sql = "SELECT date_format(".$this->field_date.",'%m') as dm, SUM(p.".$this->field.")"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; @@ -198,7 +203,9 @@ class PropaleStats extends Stats $sql = "SELECT date_format(".$this->field_date.",'%m') as dm, AVG(p.".$this->field.")"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; @@ -219,7 +226,9 @@ class PropaleStats extends Stats $sql = "SELECT date_format(".$this->field_date.",'%Y') as year, COUNT(*) as nb, SUM(".$this->field.") as total, AVG(".$this->field.") as avg"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE ".$this->where; $sql .= " GROUP BY year"; @@ -243,7 +252,9 @@ class PropaleStats extends Stats $sql = "SELECT product.ref, COUNT(product.ref) as nb, SUM(tl.".$this->field_line.") as total, AVG(tl.".$this->field_line.") as avg"; $sql .= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE ".$this->where; $sql .= " AND p.rowid = tl.fk_propal AND tl.fk_product = product.rowid"; diff --git a/htdocs/comm/propal/contact.php b/htdocs/comm/propal/contact.php index af3679de945..60d3836cfcb 100644 --- a/htdocs/comm/propal/contact.php +++ b/htdocs/comm/propal/contact.php @@ -33,7 +33,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; // Load translation files required by the page -$langs->loadLangs(array('facture', 'orders', 'sendings', 'companies')); +$langs->loadLangs(array('facture', 'propal', 'orders', 'sendings', 'companies')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); @@ -41,28 +41,26 @@ $lineid = GETPOST('lineid', 'int'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'propal', $id); $object = new Propal($db); // Load object -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $ret = $object->fetch($id, $ref); - if ($ret == 0) - { + if ($ret == 0) { $langs->load("errors"); setEventMessages($langs->trans('ErrorRecordNotFound'), null, 'errors'); $error++; - } elseif ($ret < 0) - { + } elseif ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } -if (!$error) -{ +if (!$error) { $object->fetch_thirdparty(); } else { header('Location: '.DOL_URL_ROOT.'/comm/propal/list.php'); @@ -74,42 +72,34 @@ if (!$error) * Add a new contact */ -if ($action == 'addcontact' && $user->rights->propale->creer) -{ - if ($object->id > 0) - { +if ($action == 'addcontact' && $user->rights->propale->creer) { + if ($object->id > 0) { $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } -} // Toggle the status of a contact -elseif ($action == 'swapstatut' && $user->rights->propale->creer) -{ - if ($object->id > 0) - { +} elseif ($action == 'swapstatut' && $user->rights->propale->creer) { + // Toggle the status of a contact + if ($object->id > 0) { $result = $object->swapContactStatus(GETPOST('ligne')); } -} // Deletes a contact -elseif ($action == 'deletecontact' && $user->rights->propale->creer) -{ +} elseif ($action == 'deletecontact' && $user->rights->propale->creer) { + // Deletes a contact $result = $object->delete_contact($lineid); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -134,8 +124,7 @@ $form = new Form($db); $formcompany = new FormCompany($db); $formother = new FormOther($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $head = propal_prepare_head($object); print dol_get_fiche_head($head, 'contact', $langs->trans("Proposal"), -1, 'propal'); @@ -152,12 +141,10 @@ if ($object->id > 0) // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer'); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->propal->creer) - { + if ($user->rights->propal->creer) { if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ''; $morehtmlref .= ' : '; @@ -194,10 +181,11 @@ if ($object->id > 0) // Contacts lines (modules that overwrite templates must declare this into descriptor) $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); - foreach ($dirtpls as $reldir) - { + foreach ($dirtpls as $reldir) { $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); - if ($res) break; + if ($res) { + break; + } } } diff --git a/htdocs/comm/propal/document.php b/htdocs/comm/propal/document.php index fbe7fdbec5c..4c408adcb28 100644 --- a/htdocs/comm/propal/document.php +++ b/htdocs/comm/propal/document.php @@ -39,15 +39,14 @@ if (!empty($conf->projet->enabled)) { // Load translation files required by the page $langs->loadLangs(array('compta', 'other', 'companies')); -$action = GETPOST('action', 'alpha'); -$confirm = GETPOST('confirm', 'alpha'); -$id = GETPOST('id', 'int'); -$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'alpha'); +$confirm = GETPOST('confirm', 'alpha'); +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); // Security check $socid = ''; -if (!empty($user->socid)) -{ +if (!empty($user->socid)) { $socid = $user->socid; } $result = restrictedArea($user, 'propal', $id); @@ -57,16 +56,26 @@ $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 (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; } -if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; } +if (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { + $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; +} +if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { + $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; +} -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} $object = new Propal($db); $object->fetch($id, $ref); @@ -76,11 +85,10 @@ $object->fetch($id, $ref); * Actions */ -if ($object->id > 0) -{ +if ($object->id > 0) { $object->fetch_thirdparty(); $upload_dir = $conf->propal->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; + include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; } @@ -92,8 +100,7 @@ llxHeader('', $langs->trans('Proposal'), 'EN:Commercial_Proposals|FR:Proposition $form = new Form($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $upload_dir = $conf->propal->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); $head = propal_prepare_head($object); @@ -102,8 +109,7 @@ if ($object->id > 0) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -120,12 +126,10 @@ if ($object->id > 0) // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer'); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->propal->creer) - { + if ($user->rights->propal->creer) { if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ''; $morehtmlref .= ' : '; diff --git a/htdocs/comm/propal/index.php b/htdocs/comm/propal/index.php index b51f138b0e5..812561a63b1 100644 --- a/htdocs/comm/propal/index.php +++ b/htdocs/comm/propal/index.php @@ -20,7 +20,7 @@ */ /** - * \file htdocs/comm/propal/index.php + * \file htdocs/comm/propal/index.php * \ingroup propal * \brief Home page of proposal area */ @@ -29,8 +29,7 @@ require '../../main.inc.php'; // Security check $socid = GETPOST('socid', 'int'); -if (isset($user->socid) && $user->socid > 0) -{ +if (isset($user->socid) && $user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -66,8 +65,7 @@ print '
    '; print '
    '; // This is useless due to the global search combo -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { print ''; print '
    '; print ''; @@ -97,16 +95,21 @@ $listofstatus = array(Propal::STATUS_DRAFT, Propal::STATUS_VALIDATED, Propal::ST $sql = "SELECT count(p.rowid) as nb, p.fk_statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."propal as p"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE p.entity IN (".getEntity($propalstatic->element).")"; $sql .= " AND p.fk_soc = s.rowid"; -if ($user->socid) $sql .= ' AND p.fk_soc = '.$user->socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($user->socid) { + $sql .= ' AND p.fk_soc = '.$user->socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " AND p.fk_statut IN (".implode(" ,", $listofstatus).")"; $sql .= " GROUP BY p.fk_statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; $total = 0; @@ -115,11 +118,9 @@ if ($resql) $colorseries = array(); $vals = array(); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $vals[$obj->status] = $obj->nb; $totalinprocess += $obj->nb; @@ -140,11 +141,21 @@ if ($resql) foreach ($listofstatus as $status) { $dataseries[] = array($propalstatic->LibStatut($status, 1), (isset($vals[$status]) ? (int) $vals[$status] : 0)); - if ($status == Propal::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; - if ($status == Propal::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus1; - if ($status == Propal::STATUS_SIGNED) $colorseries[$status] = $badgeStatus4; - if ($status == Propal::STATUS_NOTSIGNED) $colorseries[$status] = $badgeStatus9; - if ($status == Propal::STATUS_BILLED) $colorseries[$status] = $badgeStatus6; + if ($status == Propal::STATUS_DRAFT) { + $colorseries[$status] = '-'.$badgeStatus0; + } + if ($status == Propal::STATUS_VALIDATED) { + $colorseries[$status] = $badgeStatus1; + } + if ($status == Propal::STATUS_SIGNED) { + $colorseries[$status] = $badgeStatus4; + } + if ($status == Propal::STATUS_NOTSIGNED) { + $colorseries[$status] = $badgeStatus9; + } + if ($status == Propal::STATUS_BILLED) { + $colorseries[$status] = $badgeStatus6; + } if (empty($conf->use_javascript_ajax)) { print '
    '."\n"; print ''; - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print ''; } - if (!empty($arrayfields['p.ref_client']['checked'])) - { + if (!empty($arrayfields['p.ref_client']['checked'])) { print ''; } - if (!empty($arrayfields['pr.ref']['checked'])) - { + if (!empty($arrayfields['pr.ref']['checked'])) { print ''; } - if (!empty($arrayfields['pr.title']['checked'])) - { + if (!empty($arrayfields['pr.title']['checked'])) { print ''; } - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; } - if (!empty($arrayfields['s.name_alias']['checked'])) - { + if (!empty($arrayfields['s.name_alias']['checked'])) { print ''; } - if (!empty($arrayfields['s.town']['checked'])) print ''; - if (!empty($arrayfields['s.zip']['checked'])) print ''; + if (!empty($arrayfields['s.town']['checked'])) { + print ''; + } + if (!empty($arrayfields['s.zip']['checked'])) { + print ''; + } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print ''; } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; } // Company type - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print ''; } // Date - if (!empty($arrayfields['p.date']['checked'])) - { + if (!empty($arrayfields['p.date']['checked'])) { print ''; } // Date end - if (!empty($arrayfields['p.fin_validite']['checked'])) - { + if (!empty($arrayfields['p.fin_validite']['checked'])) { print ''; } // Date delivery - if (!empty($arrayfields['p.date_livraison']['checked'])) - { + if (!empty($arrayfields['p.date_livraison']['checked'])) { print ''; } // Availability - if (!empty($arrayfields['ava.rowid']['checked'])) - { + if (!empty($arrayfields['ava.rowid']['checked'])) { print ''; } // Shipping Method - if (!empty($arrayfields['p.fk_shipping_method']['checked'])) - { + if (!empty($arrayfields['p.fk_shipping_method']['checked'])) { print ''; } + // Source - Input reason + if (!empty($arrayfields['p.fk_input_reason']['checked'])) { + print ''; + } // Payment term - if (!empty($arrayfields['p.fk_cond_reglement']['checked'])) - { + if (!empty($arrayfields['p.fk_cond_reglement']['checked'])) { print ''; } // Payment mode - if (!empty($arrayfields['p.fk_mode_reglement']['checked'])) - { + if (!empty($arrayfields['p.fk_mode_reglement']['checked'])) { print ''; } - if (!empty($arrayfields['p.total_ht']['checked'])) - { + if (!empty($arrayfields['p.total_ht']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['p.total_vat']['checked'])) - { + if (!empty($arrayfields['p.total_tva']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['p.total_ttc']['checked'])) - { + if (!empty($arrayfields['p.total_ttc']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) - { + if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) { // Amount invoiced print ''; } - if (!empty($arrayfields['p.total_invoiced']['checked'])) - { + if (!empty($arrayfields['p.total_invoiced']['checked'])) { // Amount invoiced print ''; } - if (!empty($arrayfields['p.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_code']['checked'])) { // Currency print ''; } - if (!empty($arrayfields['p.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_tx']['checked'])) { // Currency rate print ''; } - if (!empty($arrayfields['p.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_total_ht']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['p.multicurrency_total_vat']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_total_tva']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['p.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_total_ttc']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['p.multicurrency_total_ht_invoiced']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_total_ht_invoiced']['checked'])) { // Amount invoiced print ''; } - if (!empty($arrayfields['p.multicurrency_total_invoiced']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_total_invoiced']['checked'])) { // Amount invoiced print ''; } - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { // Author print ''; } - if (!empty($arrayfields['sale_representative']['checked'])) - { + if (!empty($arrayfields['sale_representative']['checked'])) { print ''; } // Extra fields @@ -923,38 +1096,32 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['p.datec']['checked'])) - { + if (!empty($arrayfields['p.datec']['checked'])) { print ''; } // Date modification - if (!empty($arrayfields['p.tms']['checked'])) - { + if (!empty($arrayfields['p.tms']['checked'])) { print ''; } // Date cloture - if (!empty($arrayfields['p.date_cloture']['checked'])) - { + if (!empty($arrayfields['p.date_cloture']['checked'])) { print ''; } - if (!empty($arrayfields['p.note_public']['checked'])) - { + if (!empty($arrayfields['p.note_public']['checked'])) { // Note public print ''; } - if (!empty($arrayfields['p.note_private']['checked'])) - { + if (!empty($arrayfields['p.note_private']['checked'])) { // Note private print ''; } // Status - if (!empty($arrayfields['p.fk_statut']['checked'])) - { + if (!empty($arrayfields['p.fk_statut']['checked'])) { print ''; @@ -970,50 +1137,129 @@ if ($resql) // Fields title print ''; - if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], 'p.ref', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.ref_client']['checked'])) print_liste_field_titre($arrayfields['p.ref_client']['label'], $_SERVER["PHP_SELF"], 'p.ref_client', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['pr.ref']['checked'])) print_liste_field_titre($arrayfields['pr.ref']['label'], $_SERVER["PHP_SELF"], 'pr.ref', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['pr.title']['checked'])) print_liste_field_titre($arrayfields['pr.title']['label'], $_SERVER["PHP_SELF"], 'pr.title', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.name_alias']['checked'])) print_liste_field_titre($arrayfields['s.name_alias']['label'], $_SERVER["PHP_SELF"], 's.name_alias', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['p.date']['checked'])) print_liste_field_titre($arrayfields['p.date']['label'], $_SERVER["PHP_SELF"], 'p.datep', '', $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['p.fin_validite']['checked'])) print_liste_field_titre($arrayfields['p.fin_validite']['label'], $_SERVER["PHP_SELF"], 'dfv', '', $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['p.date_livraison']['checked'])) print_liste_field_titre($arrayfields['p.date_livraison']['label'], $_SERVER["PHP_SELF"], 'ddelivery', '', $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['ava.rowid']['checked'])) print_liste_field_titre($arrayfields['ava.rowid']['label'], $_SERVER["PHP_SELF"], 'availability', '', $param, '', $sortfield, $sortorder); - 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_cond_reglement']['checked'])) print_liste_field_titre($arrayfields['p.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "p.fk_cond_reglement", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['p.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "p.fk_mode_reglement", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.total_ht']['checked'])) print_liste_field_titre($arrayfields['p.total_ht']['label'], $_SERVER["PHP_SELF"], 'p.total_ht', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['p.total_vat']['checked'])) print_liste_field_titre($arrayfields['p.total_vat']['label'], $_SERVER["PHP_SELF"], 'p.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); - 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); - if (!empty($arrayfields['p.total_invoiced']['checked'])) print_liste_field_titre($arrayfields['p.total_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['p.multicurrency_code']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_code', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.multicurrency_tx']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_tx', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.multicurrency_total_ht']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['p.multicurrency_total_vat']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['p.multicurrency_total_ttc']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['p.multicurrency_total_ht_invoiced']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_total_ht_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['p.multicurrency_total_invoiced']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_total_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['u.login']['checked'])) print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", "$param", '', $sortfield, $sortorder); + if (!empty($arrayfields['p.ref']['checked'])) { + print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], 'p.ref', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.ref_client']['checked'])) { + print_liste_field_titre($arrayfields['p.ref_client']['label'], $_SERVER["PHP_SELF"], 'p.ref_client', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['pr.ref']['checked'])) { + print_liste_field_titre($arrayfields['pr.ref']['label'], $_SERVER["PHP_SELF"], 'pr.ref', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['pr.title']['checked'])) { + print_liste_field_titre($arrayfields['pr.title']['label'], $_SERVER["PHP_SELF"], 'pr.title', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.name_alias']['checked'])) { + print_liste_field_titre($arrayfields['s.name_alias']['label'], $_SERVER["PHP_SELF"], 's.name_alias', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.date']['checked'])) { + print_liste_field_titre($arrayfields['p.date']['label'], $_SERVER["PHP_SELF"], 'p.datep', '', $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.fin_validite']['checked'])) { + print_liste_field_titre($arrayfields['p.fin_validite']['label'], $_SERVER["PHP_SELF"], 'dfv', '', $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.date_livraison']['checked'])) { + print_liste_field_titre($arrayfields['p.date_livraison']['label'], $_SERVER["PHP_SELF"], 'ddelivery', '', $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['ava.rowid']['checked'])) { + print_liste_field_titre($arrayfields['ava.rowid']['label'], $_SERVER["PHP_SELF"], 'availability', '', $param, '', $sortfield, $sortorder); + } + 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); + } + if (!empty($arrayfields['p.fk_mode_reglement']['checked'])) { + print_liste_field_titre($arrayfields['p.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "p.fk_mode_reglement", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.total_ht']['checked'])) { + print_liste_field_titre($arrayfields['p.total_ht']['label'], $_SERVER["PHP_SELF"], 'p.total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.total_tva']['checked'])) { + 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_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); + } + if (!empty($arrayfields['p.total_invoiced']['checked'])) { + print_liste_field_titre($arrayfields['p.total_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.multicurrency_code']['checked'])) { + print_liste_field_titre($arrayfields['p.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_code', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.multicurrency_tx']['checked'])) { + print_liste_field_titre($arrayfields['p.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_tx', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.multicurrency_total_ht']['checked'])) { + print_liste_field_titre($arrayfields['p.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.multicurrency_total_tva']['checked'])) { + print_liste_field_titre($arrayfields['p.multicurrency_total_tva']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.multicurrency_total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['p.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.multicurrency_total_ht_invoiced']['checked'])) { + print_liste_field_titre($arrayfields['p.multicurrency_total_ht_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.multicurrency_total_invoiced']['checked'])) { + print_liste_field_titre($arrayfields['p.multicurrency_total_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['u.login']['checked'])) { + print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['sale_representative']['checked'])) { + print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", "$param", '', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $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['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'], $_SERVER["PHP_SELF"], "p.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); - if (!empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); - if (!empty($arrayfields['p.date_cloture']['checked'])) print_liste_field_titre($arrayfields['p.date_cloture']['label'], $_SERVER["PHP_SELF"], "p.date_cloture", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); - if (!empty($arrayfields['p.note_public']['checked'])) print_liste_field_titre($arrayfields['p.note_public']['label'], $_SERVER["PHP_SELF"], "p.note_public", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['p.note_private']['checked'])) print_liste_field_titre($arrayfields['p.note_private']['label'], $_SERVER["PHP_SELF"], "p.note_private", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['p.fk_statut']['checked'])) print_liste_field_titre($arrayfields['p.fk_statut']['label'], $_SERVER["PHP_SELF"], "p.fk_statut", "", $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['p.datec']['checked'])) { + print_liste_field_titre($arrayfields['p.datec']['label'], $_SERVER["PHP_SELF"], "p.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.tms']['checked'])) { + print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.date_cloture']['checked'])) { + print_liste_field_titre($arrayfields['p.date_cloture']['label'], $_SERVER["PHP_SELF"], "p.date_cloture", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.note_public']['checked'])) { + print_liste_field_titre($arrayfields['p.note_public']['label'], $_SERVER["PHP_SELF"], "p.note_public", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['p.note_private']['checked'])) { + print_liste_field_titre($arrayfields['p.note_private']['label'], $_SERVER["PHP_SELF"], "p.note_private", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['p.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['p.fk_statut']['label'], $_SERVER["PHP_SELF"], "p.fk_statut", "", $param, 'class="right"', $sortfield, $sortorder); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print ''."\n"; @@ -1022,8 +1268,7 @@ if ($resql) $totalarray = array(); $typenArray = null; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->rowid; @@ -1051,14 +1296,14 @@ if ($resql) $TInvoiceData = $objectstatic->InvoiceArrayList($obj->rowid); - if (!empty($TInvoiceData)) - { - foreach ($TInvoiceData as $invoiceData) - { + if (!empty($TInvoiceData)) { + foreach ($TInvoiceData as $invoiceData) { $invoice = new Facture($db); $invoice->fetch($invoiceData->facid); - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS) && $invoice->type == Facture::TYPE_DEPOSIT) continue; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS) && $invoice->type == Facture::TYPE_DEPOSIT) { + continue; + } $totalInvoicedHT += $invoice->total_ht; $totalInvoicedTTC += $invoice->total_ttc; @@ -1069,8 +1314,7 @@ if ($resql) print ''; - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['p.ref_client']['checked'])) - { + if (!empty($arrayfields['p.ref_client']['checked'])) { // Customer ref print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['pr.ref']['checked'])) - { + if (!empty($arrayfields['pr.ref']['checked'])) { // Project ref print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['pr.title']['checked'])) - { + if (!empty($arrayfields['pr.title']['checked'])) { // Project label print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Thirdparty - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Alias - if (!empty($arrayfields['s.name_alias']['checked'])) - { + if (!empty($arrayfields['s.name_alias']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['s.town']['checked'])) - { + if (!empty($arrayfields['s.town']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { + if (!empty($arrayfields['s.zip']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { - if (!is_array($typenArray) || empty($typenArray)) $typenArray = $formcompany->typent_array(1); + if (!empty($arrayfields['typent.code']['checked'])) { + if (!is_array($typenArray) || empty($typenArray)) { + $typenArray = $formcompany->typent_array(1); + } print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date proposal - if (!empty($arrayfields['p.date']['checked'])) - { + if (!empty($arrayfields['p.date']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date end validity - if (!empty($arrayfields['p.fin_validite']['checked'])) - { - if ($obj->dfv) - { + if (!empty($arrayfields['p.fin_validite']['checked'])) { + if ($obj->dfv) { print ''; } else { print ''; } - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date delivery - if (!empty($arrayfields['p.date_livraison']['checked'])) - { - if ($obj->ddelivery) - { + if (!empty($arrayfields['p.date_livraison']['checked'])) { + if ($obj->ddelivery) { print ''; } else { print ''; } - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Availability - if (!empty($arrayfields['ava.rowid']['checked'])) - { + if (!empty($arrayfields['ava.rowid']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - //Shipping Method - if (!empty($arrayfields['p.fk_shipping_method']['checked'])) - { + // Shipping Method + if (!empty($arrayfields['p.fk_shipping_method']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } + } + // Source - input reason + if (!empty($arrayfields['p.fk_input_reason']['checked'])) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } } // Payment terms - if (!empty($arrayfields['p.fk_cond_reglement']['checked'])) - { + if (!empty($arrayfields['p.fk_cond_reglement']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Payment mode - if (!empty($arrayfields['p.fk_mode_reglement']['checked'])) - { + if (!empty($arrayfields['p.fk_mode_reglement']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['p.total_ht']['checked'])) - { + if (!empty($arrayfields['p.total_ht']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.total_ht'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'p.total_ht'; + } $totalarray['val']['p.total_ht'] += $obj->total_ht; } // Amount VAT - if (!empty($arrayfields['p.total_vat']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.total_vat'; - $totalarray['val']['p.total_vat'] += $obj->total_vat; + if (!empty($arrayfields['p.total_tva']['checked'])) { + print '\n"; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'p.total_tva'; + } + $totalarray['val']['p.total_tva'] += $obj->total_tva; } // Amount TTC - if (!empty($arrayfields['p.total_ttc']['checked'])) - { + if (!empty($arrayfields['p.total_ttc']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.total_ttc'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'p.total_ttc'; + } $totalarray['val']['p.total_ttc'] += $obj->total_ttc; } // Amount invoiced - if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) - { + if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.total_ht_invoiced'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'p.total_ht_invoiced'; + } $totalarray['val']['p.total_ht_invoiced'] += $totalInvoicedHT; } // Amount invoiced - if (!empty($arrayfields['p.total_invoiced']['checked'])) - { + if (!empty($arrayfields['p.total_invoiced']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.total_invoiced'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'p.total_invoiced'; + } $totalarray['val']['p.total_invoiced'] += $totalInvoicedTTC; } // Currency - if (!empty($arrayfields['p.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_code']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Currency rate - if (!empty($arrayfields['p.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_tx']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['p.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_total_ht']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount VAT - if (!empty($arrayfields['p.multicurrency_total_vat']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!empty($arrayfields['p.multicurrency_total_tva']['checked'])) { + print '\n"; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount TTC - if (!empty($arrayfields['p.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_total_ttc']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount invoiced - if (!empty($arrayfields['p.multicurrency_total_ht_invoiced']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_total_ht_invoiced']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount invoiced - if (!empty($arrayfields['p.multicurrency_total_invoiced']['checked'])) - { + if (!empty($arrayfields['p.multicurrency_total_invoiced']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } $userstatic->id = $obj->fk_user_author; $userstatic->login = $obj->login; // Author - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['sale_representative']['checked'])) - { + if (!empty($arrayfields['sale_representative']['checked'])) { // Sales representatives print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -1404,61 +1706,70 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['p.datec']['checked'])) - { + if (!empty($arrayfields['p.datec']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['p.tms']['checked'])) - { + if (!empty($arrayfields['p.tms']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date cloture - if (!empty($arrayfields['p.date_cloture']['checked'])) - { + if (!empty($arrayfields['p.date_cloture']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Note public - if (!empty($arrayfields['p.note_public']['checked'])) - { + if (!empty($arrayfields['p.note_public']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Note private - if (!empty($arrayfields['p.note_private']['checked'])) - { + if (!empty($arrayfields['p.note_private']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['p.fk_statut']['checked'])) - { + if (!empty($arrayfields['p.fk_statut']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; @@ -1480,7 +1791,9 @@ if ($resql) print ''."\n"; $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; @@ -1492,7 +1805,7 @@ if ($resql) print $formfile->showdocuments('massfilesarea_proposals', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } else { - dol_print_error($db); + dol_print_error($db); } // End of page diff --git a/htdocs/comm/propal/note.php b/htdocs/comm/propal/note.php index 06be1179fb1..8c1e16dc6e8 100644 --- a/htdocs/comm/propal/note.php +++ b/htdocs/comm/propal/note.php @@ -41,7 +41,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'propale', $id, 'propal'); $object = new Propal($db); @@ -61,20 +63,21 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, * View */ -llxHeader('', $langs->trans('Proposal'), 'EN:Commercial_Proposals|FR:Proposition_commerciale|ES:Presupuestos'); +$help_url = 'EN:Commercial_Proposals|FR:Proposition_commerciale|ES:Presupuestos'; + +llxHeader('', $langs->trans('Proposal'), $help_url); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ - if ($mesg) print $mesg; +if ($id > 0 || !empty($ref)) { + if ($mesg) { + print $mesg; + } $now = dol_now(); - if ($object->fetch($id, $ref) > 0) - { - if ($object->fetch_thirdparty() > 0) - { + if ($object->fetch($id, $ref) > 0) { + if ($object->fetch_thirdparty() > 0) { $head = propal_prepare_head($object); print dol_get_fiche_head($head, 'note', $langs->trans('Proposal'), -1, 'propal'); @@ -95,12 +98,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->propal->creer) - { + if ($user->rights->propal->creer) { if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ''; $morehtmlref .= ' : '; diff --git a/htdocs/comm/propal/stats/index.php b/htdocs/comm/propal/stats/index.php index c28da3ed048..3cb6de90a8d 100644 --- a/htdocs/comm/propal/stats/index.php +++ b/htdocs/comm/propal/stats/index.php @@ -38,8 +38,12 @@ $WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); $mode = GETPOSTISSET("mode") ? GETPOST("mode", 'aZ09') : 'customer'; -if ($mode == 'customer' && !$user->rights->propale->lire) accessforbidden(); -if ($mode == 'supplier' && !$user->rights->supplier_proposal->lire) accessforbidden(); +if ($mode == 'customer' && !$user->rights->propale->lire) { + accessforbidden(); +} +if ($mode == 'supplier' && !$user->rights->supplier_proposal->lire) { + accessforbidden(); +} $object_status = GETPOST('object_status', 'intcomma'); $typent_id = GETPOST('typent_id', 'int'); @@ -48,8 +52,7 @@ $categ_id = GETPOST('categ_id', 'categ_id'); $userid = GETPOST('userid', 'int'); $socid = GETPOST('socid', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -75,16 +78,14 @@ $formother = new FormOther($db); $langs->loadLangs(array('propal', 'other', 'companies')); -if ($mode == 'customer') -{ +if ($mode == 'customer') { $picto = 'propal'; $title = $langs->trans("ProposalsStatistics"); - $dir = $conf->propale->dir_temp; + $dir = $conf->propal->dir_temp; $cat_type = Categorie::TYPE_CUSTOMER; $cat_label = $langs->trans("Category").' '.lcfirst($langs->trans("Customer")); } -if ($mode == 'supplier') -{ +if ($mode == 'supplier') { $picto = 'supplier_proposal'; $title = $langs->trans("ProposalsStatisticsSuppliers"); $dir = $conf->supplier_proposal->dir_temp; @@ -101,15 +102,16 @@ dol_mkdir($dir); $stats = new PropaleStats($db, $socid, ($userid > 0 ? $userid : 0), $mode, ($typent_id > 0 ? $typent_id : 0), ($categ_id > 0 ? $categ_id : 0)); -if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND p.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +if ($object_status != '' && $object_status >= 0) { + $stats->where .= ' AND p.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +} // Build graphic number of object $data = $stats->getNbByMonthWithPrevYear($endyear, $startyear); // $data = array(array('Lib',val1,val2,val3),...) -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filenamenb = $dir.'/proposalsnbinyear-'.$user->id.'-'.$year.'.png'; $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstats&file=proposalsnbinyear-'.$user->id.'-'.$year.'.png'; } else { @@ -119,12 +121,11 @@ if (!$user->rights->societe->client->voir || $user->socid) $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); - $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + $i = $startyear; + $legend = array(); + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -146,8 +147,7 @@ if (!$mesg) $data = $stats->getAmountByMonthWithPrevYear($endyear, $startyear, 0); // $data = array(array('Lib',val1,val2,val3),...) -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filenameamount = $dir.'/proposalsamountinyear-'.$user->id.'-'.$year.'.png'; $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstats&file=proposalsamountinyear-'.$user->id.'-'.$year.'.png'; } else { @@ -157,12 +157,11 @@ if (!$user->rights->societe->client->voir || $user->socid) $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px2->SetData($data); - $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + $i = $startyear; + $legend = array(); + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -183,25 +182,31 @@ if (!$mesg) $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); $fileurl_avg = ''; -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filename_avg = $dir.'/ordersaverage-'.$user->id.'-'.$year.'.png'; - if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; - if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + if ($mode == 'customer') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + } } else { $filename_avg = $dir.'/ordersaverage-'.$year.'.png'; - if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; - if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; + if ($mode == 'customer') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; + } } $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px3->SetData($data); - $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + $i = $startyear; + $legend = array(); + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -228,7 +233,9 @@ foreach ($data as $val) { $arrayyears[$val['year']] = $val['year']; } } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; @@ -264,7 +271,9 @@ print '
    '; print '
    '; // Category print ''; // Year print ''; @@ -304,11 +317,9 @@ print ''; print ''; $oldyear = 0; -foreach ($data as $val) -{ +foreach ($data as $val) { $year = $val['year']; - while (!empty($year) && $oldyear > $year + 1) - { // If we have empty year + while (!empty($year) && $oldyear > $year + 1) { // If we have empty year $oldyear--; print ''; @@ -341,7 +352,9 @@ print '
    '; // Show graphs print '
    '; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print ''; print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); print ajax_combobox('search_type_thirdparty'); print ''; print '
    '; print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); @@ -772,8 +959,7 @@ if ($resql) print '
    '; print '
    '; print $form->selectDate($search_dateend_start ? $search_dateend_start : -1, 'search_dateend_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); @@ -784,8 +970,7 @@ if ($resql) print '
    '; print '
    '; print $form->selectDate($search_datedelivery_start ? $search_datedelivery_start : -1, 'search_datedelivery_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); @@ -796,123 +981,111 @@ if ($resql) print '
    '; $form->selectAvailabilityDelay($search_availability, 'search_availability', '', 1); print ajax_combobox('search_availability'); print ''; $form->selectShippingMethod($search_fk_shipping_method, 'search_fk_shipping_method', '', 1, '', 1); print ''; + $form->selectInputReason($search_fk_input_reason, 'search_fk_input_reason', '', 1, 'maxwidth125', 1); + print ''; $form->select_conditions_paiements($search_fk_cond_reglement, 'search_fk_cond_reglement', -1, 1, 1); print ''; $form->select_types_paiements($search_fk_mode_reglement, 'search_fk_mode_reglement', '', 0, 1, 1, 0, -1); print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1); print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; $formpropal->selectProposalStatus($search_status, 1, 0, 1, 'customer', 'search_statut'); print '
    '; print ''; @@ -1080,9 +1324,10 @@ if ($resql) print ''; // Warning $warnornote = ''; - if ($obj->status == Propal::STATUS_VALIDATED && $db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) $warnornote .= img_warning($langs->trans("Late")); - if ($warnornote) - { + if ($obj->status == Propal::STATUS_VALIDATED && $db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) { + $warnornote .= img_warning($langs->trans("Late")); + } + if ($warnornote) { print ''; @@ -1096,271 +1341,326 @@ if ($resql) print '
    '; print $warnornote; print '
    '; print "
    '; print $obj->ref_client; print ''; if ($obj->project_id > 0) { print $projectstatic->getNomUrl(1); } print ''; if ($obj->project_id > 0) { print $projectstatic->title; } print ''; print $companystatic->getNomUrl(1, 'customer'); print ''; print $obj->alias; print ''; print $obj->town; print ''; print $obj->zip; print '".$obj->state_name."'; $tmparray = getCountry($obj->fk_pays, 'all'); print $tmparray['label']; print ''; print $typenArray[$obj->typent_code]; print ''; print dol_print_date($db->jdate($obj->dp), 'day'); print "'.dol_print_date($db->jdate($obj->dfv), 'day'); print ' '.dol_print_date($db->jdate($obj->ddelivery), 'day'); print ' '; $form->form_availability('', $obj->availability, 'none', 1); print ''; $form->formSelectShippingMethod('', $obj->fk_shipping_method, 'none', 1); print ''; + if ($obj->fk_input_reason > 0) { + print $form->cache_demand_reason[$obj->fk_input_reason]['label']; + } + print ''; $form->form_conditions_reglement($_SERVER['PHP_SELF'], $obj->fk_cond_reglement, 'none'); print ''; $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); print ''.price($obj->total_ht)."'.price($obj->total_vat)."'.price($obj->total_tva)."'.price($obj->total_ttc)."'.price($totalInvoicedHT)."'.price($totalInvoicedTTC)."'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."'; $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code); print "'.price($obj->multicurrency_total_ht)."'.price($obj->multicurrency_total_vat)."'.price($obj->multicurrency_total_tva)."'.price($obj->multicurrency_total_ttc)."'.price($multicurrency_totalInvoicedHT)."'.price($multicurrency_totalInvoicedTTC)."'; - if ($userstatic->id) print $userstatic->getLoginUrl(1); + if ($userstatic->id) { + print $userstatic->getLoginUrl(1); + } print "'; - if ($obj->socid > 0) - { + if ($obj->socid > 0) { $listsalesrepresentatives = $companystatic->getSalesRepresentatives($user); - if ($listsalesrepresentatives < 0) dol_print_error($db); + if ($listsalesrepresentatives < 0) { + dol_print_error($db); + } $nbofsalesrepresentative = count($listsalesrepresentatives); if ($nbofsalesrepresentative > 6) { // We print only number @@ -1394,7 +1694,9 @@ if ($resql) print ' '; } print ''; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_cloture), 'dayhour', 'tzuser'); print ''; print dol_escape_htmltag($obj->note_public); print ''; print dol_escape_htmltag($obj->note_private); print ''.$objectstatic->getLibStatut(5).''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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("ThirdPartyType").''; $sortparam_typent = (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label. print $form->selectarray("typent_id", $formcompany->typent_array(0), $typent_id, 1, 0, 0, '', 0, 0, 0, $sortparam_typent, '', 1); - if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); +if ($user->admin) { + print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); +} print '
    '.$cat_label.''; @@ -280,8 +289,12 @@ print '
    '; print '
    '.$langs->trans("Year").''; - if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; - if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} +if (!in_array($nowyear, $arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print '
    %
    '; print ''; print "\n"; } -if (count($linkedObjectBlock) > 1) -{ +if (count($linkedObjectBlock) > 1) { print ''; print ''; print ''; diff --git a/htdocs/comm/prospect/index.php b/htdocs/comm/prospect/index.php index 7ae61362f09..ea44682b4a3 100644 --- a/htdocs/comm/prospect/index.php +++ b/htdocs/comm/prospect/index.php @@ -31,13 +31,11 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; $langs->load("propal"); -if ($user->socid > 0) -{ +if ($user->socid > 0) { $socid = $user->socid; } - /* * View */ @@ -53,8 +51,7 @@ print load_fiche_titre($langs->trans("ProspectionArea")); print '
    '; -if (!empty($conf->propal->enabled)) -{ +if (!empty($conf->propal->enabled)) { $var = false; print '
    '; print ''; @@ -75,26 +72,27 @@ if (!empty($conf->propal->enabled)) $sql = "SELECT count(*) as cc, st.libelle, st.picto, st.id"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."c_stcomm as st "; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE s.fk_stcomm = st.id"; $sql .= " AND s.client IN (2, 3)"; $sql .= " AND s.entity IN (".getEntity($companystatic->element).")"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " GROUP BY st.id"; $sql .= " ORDER BY st.id"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num > 0) - { + if ($num > 0) { print '
    '; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); print "
    \n"; print $px2->show(); diff --git a/htdocs/comm/propal/tpl/linkedobjectblock.tpl.php b/htdocs/comm/propal/tpl/linkedobjectblock.tpl.php index 300b35cc868..23c1a459c74 100644 --- a/htdocs/comm/propal/tpl/linkedobjectblock.tpl.php +++ b/htdocs/comm/propal/tpl/linkedobjectblock.tpl.php @@ -44,16 +44,16 @@ $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1) $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } print '
    '.$langs->trans("Proposal"); - if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) - { + if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) { $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$objectlink->id; print ' '; } @@ -71,8 +71,7 @@ foreach ($linkedObjectBlock as $key => $objectlink) print ''.img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink').'
    '.$langs->trans("Total").'
    '; print ''; print ''; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '
    '.$langs->trans("ProspectsByStatus").'
    '; @@ -112,31 +110,31 @@ if ($resql) /* * Liste des propal brouillons */ -if (!empty($conf->propal->enabled) && $user->rights->propale->lire) -{ +if (!empty($conf->propal->enabled) && $user->rights->propale->lire) { $sql = "SELECT p.rowid, p.ref, p.price, s.nom as sname"; $sql .= " FROM ".MAIN_DB_PREFIX."propal as p"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE p.fk_statut = 0"; $sql .= " AND p.fk_soc = s.rowid"; $sql .= " AND p.entity IN (".getEntity('propal').")"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $total = 0; $num = $db->num_rows($resql); $i = 0; - if ($num > 0) - { + if ($num > 0) { print ''; print ''; print ''; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; // Ref - if (!empty($arrayfields['c.ref']['checked'])) - { + if (!empty($arrayfields['c.ref']['checked'])) { print ''; } // Ref customer - if (!empty($arrayfields['c.ref_client']['checked'])) - { + if (!empty($arrayfields['c.ref_client']['checked'])) { print ''; } // Project ref - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print ''; } // Project title - if (!empty($arrayfields['p.title']['checked'])) - { + if (!empty($arrayfields['p.title']['checked'])) { print ''; } // Thirpdarty - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; } // Alias - if (!empty($arrayfields['s.name_alias']['checked'])) - { + if (!empty($arrayfields['s.name_alias']['checked'])) { print ''; } // Town - if (!empty($arrayfields['s.town']['checked'])) print ''; + if (!empty($arrayfields['s.town']['checked'])) { + print ''; + } // Zip - if (!empty($arrayfields['s.zip']['checked'])) print ''; + if (!empty($arrayfields['s.zip']['checked'])) { + print ''; + } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print ''; } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; } // Company type - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print ''; } // Date order - if (!empty($arrayfields['c.date_commande']['checked'])) - { + if (!empty($arrayfields['c.date_commande']['checked'])) { print ''; } - if (!empty($arrayfields['c.date_delivery']['checked'])) - { + if (!empty($arrayfields['c.date_delivery']['checked'])) { print ''; } // Shipping Method - if (!empty($arrayfields['c.fk_shipping_method']['checked'])) - { + if (!empty($arrayfields['c.fk_shipping_method']['checked'])) { print ''; } // Payment term - if (!empty($arrayfields['c.fk_cond_reglement']['checked'])) - { + if (!empty($arrayfields['c.fk_cond_reglement']['checked'])) { print ''; } // Payment mode - if (!empty($arrayfields['c.fk_mode_reglement']['checked'])) - { + if (!empty($arrayfields['c.fk_mode_reglement']['checked'])) { print ''; } - if (!empty($arrayfields['c.total_ht']['checked'])) - { + if (!empty($arrayfields['c.total_ht']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['c.total_vat']['checked'])) - { + if (!empty($arrayfields['c.total_vat']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['c.total_ttc']['checked'])) - { + if (!empty($arrayfields['c.total_ttc']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['c.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['c.multicurrency_code']['checked'])) { // Currency print ''; } - if (!empty($arrayfields['c.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['c.multicurrency_tx']['checked'])) { // Currency rate print ''; } - if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) - { + if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) { // Amount VAT print ''; } - if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { // Author print ''; } // Date modification - if (!empty($arrayfields['c.tms']['checked'])) - { + if (!empty($arrayfields['c.tms']['checked'])) { print ''; } // Date cloture - if (!empty($arrayfields['c.date_cloture']['checked'])) - { + if (!empty($arrayfields['c.date_cloture']['checked'])) { print ''; } // Note public - if (!empty($arrayfields['c.note_public']['checked'])) - { + if (!empty($arrayfields['c.note_public']['checked'])) { print ''; } // Note private - if (!empty($arrayfields['c.note_private']['checked'])) - { + if (!empty($arrayfields['c.note_private']['checked'])) { print ''; } // Shippable - if (!empty($arrayfields['shippable']['checked'])) - { + if (!empty($arrayfields['shippable']['checked'])) { print ''; } // Status billed - if (!empty($arrayfields['c.facture']['checked'])) - { + if (!empty($arrayfields['c.facture']['checked'])) { print ''; } // Status - if (!empty($arrayfields['c.fk_statut']['checked'])) - { + if (!empty($arrayfields['c.fk_statut']['checked'])) { print ''; - if (!empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], 'c.ref', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['c.ref_client']['checked'])) print_liste_field_titre($arrayfields['c.ref_client']['label'], $_SERVER["PHP_SELF"], 'c.ref_client', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.title']['checked'])) print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER["PHP_SELF"], "p.title", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.name_alias']['checked'])) print_liste_field_titre($arrayfields['s.name_alias']['label'], $_SERVER["PHP_SELF"], 's.name_alias', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['c.date_commande']['checked'])) print_liste_field_titre($arrayfields['c.date_commande']['label'], $_SERVER["PHP_SELF"], 'c.date_commande', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['c.date_delivery']['checked'])) print_liste_field_titre($arrayfields['c.date_delivery']['label'], $_SERVER["PHP_SELF"], 'c.date_livraison', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['c.fk_shipping_method']['checked'])) print_liste_field_titre($arrayfields['c.fk_shipping_method']['label'], $_SERVER["PHP_SELF"], "c.fk_shipping_method", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['c.fk_cond_reglement']['checked'])) print_liste_field_titre($arrayfields['c.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "c.fk_cond_reglement", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['c.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['c.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "c.fk_mode_reglement", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['c.total_ht']['checked'])) print_liste_field_titre($arrayfields['c.total_ht']['label'], $_SERVER["PHP_SELF"], 'c.total_ht', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['c.total_vat']['checked'])) print_liste_field_titre($arrayfields['c.total_vat']['label'], $_SERVER["PHP_SELF"], 'c.tva', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['c.total_ttc']['checked'])) print_liste_field_titre($arrayfields['c.total_ttc']['label'], $_SERVER["PHP_SELF"], 'c.total_ttc', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['c.multicurrency_code']['checked'])) print_liste_field_titre($arrayfields['c.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_code', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['c.multicurrency_tx']['checked'])) print_liste_field_titre($arrayfields['c.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_tx', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) print_liste_field_titre($arrayfields['c.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) print_liste_field_titre($arrayfields['c.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) print_liste_field_titre($arrayfields['c.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['u.login']['checked'])) print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['c.ref']['checked'])) { + print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], 'c.ref', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['c.ref_client']['checked'])) { + print_liste_field_titre($arrayfields['c.ref_client']['label'], $_SERVER["PHP_SELF"], 'c.ref_client', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.ref']['checked'])) { + print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.title']['checked'])) { + print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER["PHP_SELF"], "p.title", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.name_alias']['checked'])) { + print_liste_field_titre($arrayfields['s.name_alias']['label'], $_SERVER["PHP_SELF"], 's.name_alias', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['c.date_commande']['checked'])) { + print_liste_field_titre($arrayfields['c.date_commande']['label'], $_SERVER["PHP_SELF"], 'c.date_commande', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['c.date_delivery']['checked'])) { + print_liste_field_titre($arrayfields['c.date_delivery']['label'], $_SERVER["PHP_SELF"], 'c.date_livraison', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['c.fk_shipping_method']['checked'])) { + print_liste_field_titre($arrayfields['c.fk_shipping_method']['label'], $_SERVER["PHP_SELF"], "c.fk_shipping_method", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['c.fk_cond_reglement']['checked'])) { + print_liste_field_titre($arrayfields['c.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "c.fk_cond_reglement", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['c.fk_mode_reglement']['checked'])) { + print_liste_field_titre($arrayfields['c.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "c.fk_mode_reglement", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['c.total_ht']['checked'])) { + print_liste_field_titre($arrayfields['c.total_ht']['label'], $_SERVER["PHP_SELF"], 'c.total_ht', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['c.total_vat']['checked'])) { + print_liste_field_titre($arrayfields['c.total_vat']['label'], $_SERVER["PHP_SELF"], 'c.total_tva', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['c.total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['c.total_ttc']['label'], $_SERVER["PHP_SELF"], 'c.total_ttc', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['c.multicurrency_code']['checked'])) { + print_liste_field_titre($arrayfields['c.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_code', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['c.multicurrency_tx']['checked'])) { + print_liste_field_titre($arrayfields['c.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_tx', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) { + print_liste_field_titre($arrayfields['c.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) { + print_liste_field_titre($arrayfields['c.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['c.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['u.login']['checked'])) { + print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; @@ -956,14 +1185,30 @@ if ($resql) $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.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['c.date_cloture']['checked'])) print_liste_field_titre($arrayfields['c.date_cloture']['label'], $_SERVER["PHP_SELF"], "c.date_cloture", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['c.note_public']['checked'])) print_liste_field_titre($arrayfields['c.note_public']['label'], $_SERVER["PHP_SELF"], "c.note_public", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['c.note_private']['checked'])) print_liste_field_titre($arrayfields['c.note_private']['label'], $_SERVER["PHP_SELF"], "c.note_private", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['shippable']['checked'])) print_liste_field_titre($arrayfields['shippable']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['c.facture']['checked'])) print_liste_field_titre($arrayfields['c.facture']['label'], $_SERVER["PHP_SELF"], 'c.facture', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['c.fk_statut']['checked'])) print_liste_field_titre($arrayfields['c.fk_statut']['label'], $_SERVER["PHP_SELF"], "c.fk_statut", "", $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['c.datec']['checked'])) { + print_liste_field_titre($arrayfields['c.datec']['label'], $_SERVER["PHP_SELF"], "c.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['c.tms']['checked'])) { + print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['c.date_cloture']['checked'])) { + print_liste_field_titre($arrayfields['c.date_cloture']['label'], $_SERVER["PHP_SELF"], "c.date_cloture", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['c.note_public']['checked'])) { + print_liste_field_titre($arrayfields['c.note_public']['label'], $_SERVER["PHP_SELF"], "c.note_public", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['c.note_private']['checked'])) { + print_liste_field_titre($arrayfields['c.note_private']['label'], $_SERVER["PHP_SELF"], "c.note_private", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['shippable']['checked'])) { + print_liste_field_titre($arrayfields['shippable']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['c.facture']['checked'])) { + print_liste_field_titre($arrayfields['c.facture']['label'], $_SERVER["PHP_SELF"], 'c.facture', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['c.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['c.fk_statut']['label'], $_SERVER["PHP_SELF"], "c.fk_statut", "", $param, '', $sortfield, $sortorder, 'center '); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'maxwidthsearch center '); print ''."\n"; @@ -978,8 +1223,7 @@ if ($resql) $userstatic = new User($db); $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $notshippable = 0; @@ -1018,8 +1262,7 @@ if ($resql) print ''; // Ref - if (!empty($arrayfields['c.ref']['checked'])) - { + if (!empty($arrayfields['c.ref']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Ref customer - if (!empty($arrayfields['c.ref_client']['checked'])) - { + if (!empty($arrayfields['c.ref_client']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Project ref - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Project label - if (!empty($arrayfields['p.title']['checked'])) - { + if (!empty($arrayfields['p.title']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Third party - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['s.name_alias']['checked'])) - { + if (!empty($arrayfields['s.name_alias']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['s.town']['checked'])) - { + if (!empty($arrayfields['s.town']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { + if (!empty($arrayfields['s.zip']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Order date - if (!empty($arrayfields['c.date_commande']['checked'])) - { + if (!empty($arrayfields['c.date_commande']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Plannned date of delivery - if (!empty($arrayfields['c.date_delivery']['checked'])) - { + if (!empty($arrayfields['c.date_delivery']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } //Shipping Method - if (!empty($arrayfields['c.fk_shipping_method']['checked'])) - { + if (!empty($arrayfields['c.fk_shipping_method']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Payment terms - if (!empty($arrayfields['c.fk_cond_reglement']['checked'])) - { + if (!empty($arrayfields['c.fk_cond_reglement']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Payment mode - if (!empty($arrayfields['c.fk_mode_reglement']['checked'])) - { + if (!empty($arrayfields['c.fk_mode_reglement']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['c.total_ht']['checked'])) - { + if (!empty($arrayfields['c.total_ht']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'c.total_ht'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'c.total_ht'; + } $totalarray['val']['c.total_ht'] += $obj->total_ht; } // Amount VAT - if (!empty($arrayfields['c.total_vat']['checked'])) - { + if (!empty($arrayfields['c.total_vat']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'c.total_tva'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'c.total_tva'; + } $totalarray['val']['c.total_tva'] += $obj->total_tva; } // Amount TTC - if (!empty($arrayfields['c.total_ttc']['checked'])) - { + if (!empty($arrayfields['c.total_ttc']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'c.total_ttc'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'c.total_ttc'; + } $totalarray['val']['c.total_ttc'] += $obj->total_ttc; } // Currency - if (!empty($arrayfields['c.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['c.multicurrency_code']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Currency rate - if (!empty($arrayfields['c.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['c.multicurrency_tx']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount VAT - if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) - { + if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount TTC - if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } $userstatic->id = $obj->fk_user_author; $userstatic->login = $obj->login; // Author - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -1258,53 +1533,57 @@ if ($resql) print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['c.datec']['checked'])) - { + if (!empty($arrayfields['c.datec']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['c.tms']['checked'])) - { + if (!empty($arrayfields['c.tms']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date cloture - if (!empty($arrayfields['c.date_cloture']['checked'])) - { + if (!empty($arrayfields['c.date_cloture']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Note public - if (!empty($arrayfields['c.note_public']['checked'])) - { + if (!empty($arrayfields['c.note_public']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Note private - if (!empty($arrayfields['c.note_private']['checked'])) - { + if (!empty($arrayfields['c.note_private']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Show shippable Icon (this creates subloops, so may be slow) - if (!empty($arrayfields['shippable']['checked'])) - { + if (!empty($arrayfields['shippable']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['c.fk_statut']['checked'])) - { + if (!empty($arrayfields['c.fk_statut']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; @@ -1450,7 +1731,9 @@ if ($resql) print ''."\n"; $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/commande/note.php b/htdocs/commande/note.php index 0cf0da709da..0805bb8d1d9 100644 --- a/htdocs/commande/note.php +++ b/htdocs/commande/note.php @@ -42,13 +42,14 @@ $action = GETPOST('action', 'aZ09'); // Security check $socid = 0; -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'commande', $id, ''); $object = new Commande($db); -if (!$object->fetch($id, $ref) > 0) -{ +if (!$object->fetch($id, $ref) > 0) { dol_print_error($db); exit; } @@ -71,8 +72,7 @@ llxHeader('', $langs->trans('Order'), 'EN:Customers_Orders|FR:Commandes_Clients| $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = commande_prepare_head($object); @@ -91,12 +91,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; $morehtmlref .= ' : '; diff --git a/htdocs/commande/stats/index.php b/htdocs/commande/stats/index.php index 43980135140..0c9b80c3883 100644 --- a/htdocs/commande/stats/index.php +++ b/htdocs/commande/stats/index.php @@ -39,8 +39,12 @@ $WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); $mode = GETPOSTISSET("mode") ? GETPOST("mode", 'aZ09') : 'customer'; -if ($mode == 'customer' && !$user->rights->commande->lire) accessforbidden(); -if ($mode == 'supplier' && !$user->rights->fournisseur->commande->lire) accessforbidden(); +if ($mode == 'customer' && !$user->rights->commande->lire) { + accessforbidden(); +} +if ($mode == 'supplier' && !$user->rights->fournisseur->commande->lire) { + accessforbidden(); +} $object_status = GETPOST('object_status', 'intcomma'); $typent_id = GETPOST('typent_id', 'int'); @@ -49,8 +53,7 @@ $categ_id = GETPOST('categ_id', 'categ_id'); $userid = GETPOST('userid', 'int'); $socid = GETPOST('socid', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -78,8 +81,7 @@ $picto = 'order'; $title = $langs->trans("OrdersStatistics"); $dir = $conf->commande->dir_temp; -if ($mode == 'supplier') -{ +if ($mode == 'supplier') { $picto = 'supplier_order'; $title = $langs->trans("OrdersStatisticsSuppliers"); $dir = $conf->fournisseur->commande->dir_temp; @@ -92,13 +94,15 @@ print load_fiche_titre($title, '', $picto); dol_mkdir($dir); $stats = new CommandeStats($db, $socid, $mode, ($userid > 0 ? $userid : 0), ($typent_id > 0 ? $typent_id : 0), ($categ_id > 0 ? $categ_id : 0)); -if ($mode == 'customer') -{ - if ($object_status != '' && $object_status >= -1) $stats->where .= ' AND c.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +if ($mode == 'customer') { + if ($object_status != '' && $object_status >= -1) { + $stats->where .= ' AND c.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; + } } -if ($mode == 'supplier') -{ - if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND c.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +if ($mode == 'supplier') { + if ($object_status != '' && $object_status >= 0) { + $stats->where .= ' AND c.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; + } } @@ -109,25 +113,30 @@ $data = $stats->getNbByMonthWithPrevYear($endyear, $startyear); // $data = array(array('Lib',val1,val2,val3),...) -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filenamenb = $dir.'/ordersnbinyear-'.$user->id.'-'.$year.'.png'; - if ($mode == 'customer') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersnbinyear-'.$user->id.'-'.$year.'.png'; - if ($mode == 'supplier') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersnbinyear-'.$user->id.'-'.$year.'.png'; + if ($mode == 'customer') { + $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersnbinyear-'.$user->id.'-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersnbinyear-'.$user->id.'-'.$year.'.png'; + } } else { $filenamenb = $dir.'/ordersnbinyear-'.$year.'.png'; - if ($mode == 'customer') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersnbinyear-'.$year.'.png'; - if ($mode == 'supplier') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersnbinyear-'.$year.'.png'; + if ($mode == 'customer') { + $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersnbinyear-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersnbinyear-'.$year.'.png'; + } } $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -150,25 +159,30 @@ $data = $stats->getAmountByMonthWithPrevYear($endyear, $startyear); //var_dump($data); // $data = array(array('Lib',val1,val2,val3),...) -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filenameamount = $dir.'/ordersamountinyear-'.$user->id.'-'.$year.'.png'; - if ($mode == 'customer') $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersamountinyear-'.$user->id.'-'.$year.'.png'; - if ($mode == 'supplier') $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersamountinyear-'.$user->id.'-'.$year.'.png'; + if ($mode == 'customer') { + $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersamountinyear-'.$user->id.'-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersamountinyear-'.$user->id.'-'.$year.'.png'; + } } else { $filenameamount = $dir.'/ordersamountinyear-'.$year.'.png'; - if ($mode == 'customer') $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersamountinyear-'.$year.'.png'; - if ($mode == 'supplier') $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersamountinyear-'.$year.'.png'; + if ($mode == 'customer') { + $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersamountinyear-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersamountinyear-'.$year.'.png'; + } } $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px2->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -189,25 +203,30 @@ if (!$mesg) $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filename_avg = $dir.'/ordersaverage-'.$user->id.'-'.$year.'.png'; - if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; - if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + if ($mode == 'customer') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + } } else { $filename_avg = $dir.'/ordersaverage-'.$year.'.png'; - if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; - if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; + if ($mode == 'customer') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; + } } $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px3->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -235,7 +254,9 @@ foreach ($data as $val) { $arrayyears[$val['year']] = $val['year']; } } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; $head = array(); @@ -244,8 +265,12 @@ $head[$h][1] = $langs->trans("ByMonthYear"); $head[$h][2] = 'byyear'; $h++; -if ($mode == 'customer') $type = 'order_stats'; -if ($mode == 'supplier') $type = 'supplier_order_stats'; +if ($mode == 'customer') { + $type = 'order_stats'; +} +if ($mode == 'supplier') { + $type = 'supplier_order_stats'; +} complete_head_from_modules($conf, $langs, null, $head, $h, $type); @@ -264,26 +289,30 @@ print '
    '.$langs->trans("ProposalsDraft").'
    '; @@ -164,41 +162,45 @@ print '
    '; /* * Actions commerciales a faire */ -if (!empty($conf->agenda->enabled)) show_array_actions_to_do(10); +if (!empty($conf->agenda->enabled)) { + show_array_actions_to_do(10); +} /* * Dernieres propales ouvertes */ -if (!empty($conf->propal->enabled) && $user->rights->propale->lire) -{ +if (!empty($conf->propal->enabled) && $user->rights->propale->lire) { $sql = "SELECT s.nom as name, s.rowid as socid, s.client, s.canvas,"; - $sql .= " p.rowid as propalid, p.total as total_ttc, p.ref, p.datep as dp, c.label as statut, c.id as statutid"; + $sql .= " p.rowid as propalid, p.total_ttc, p.ref, p.datep as dp, c.label as statut, c.id as statutid"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."propal as p"; $sql .= ", ".MAIN_DB_PREFIX."c_propalst as c"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE p.fk_soc = s.rowid"; $sql .= " AND p.fk_statut = c.id"; $sql .= " AND p.fk_statut = 1"; $sql .= " AND p.entity IN (".getEntity('propal').")"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } $sql .= " ORDER BY p.rowid DESC"; $sql .= $db->plimit(5, 0); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $total = 0; $num = $db->num_rows($resql); $i = 0; - if ($num > 0) - { + if ($num > 0) { print ''; print ''; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '"; } print "
    '.$langs->trans("ProposalsOpened").'
    '; @@ -218,8 +220,7 @@ if (!empty($conf->propal->enabled) && $user->rights->propale->lire) $i++; $total += $obj->price; } - if ($total > 0) - { + if ($total > 0) { print '
    '.$langs->trans("Total")."".price($total)."

    "; @@ -235,25 +236,26 @@ if (!empty($conf->propal->enabled) && $user->rights->propale->lire) */ $sql = "SELECT s.nom as name, s.rowid as socid, s.client, s.canvas"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE s.fk_stcomm = 1"; $sql .= " AND s.entity IN (".getEntity($companystatic->element).")"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " ORDER BY s.tms ASC"; $sql .= $db->plimit(15, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num > 0) - { + if ($num > 0) { print ''; print ''; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; // Prefix - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print ''; @@ -84,7 +82,7 @@ if ($socid > 0) print $langs->trans("FeatureNotYetAvailable"); } else { - dol_print_error($db); + dol_print_error($db); } // End of page diff --git a/htdocs/comm/recap-client.php b/htdocs/comm/recap-client.php index 254305a9443..6e82cc16c19 100644 --- a/htdocs/comm/recap-client.php +++ b/htdocs/comm/recap-client.php @@ -28,12 +28,13 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; // Load translation files required by the page $langs->load("companies"); -if (!empty($conf->facture->enabled)) $langs->load("bills"); +if (!empty($conf->facture->enabled)) { + $langs->load("bills"); +} // Security check $socid = $_GET["socid"]; -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -46,14 +47,13 @@ if ($user->socid > 0) llxHeader(); -if ($socid > 0) -{ +if ($socid > 0) { $societe = new Societe($db); $societe->fetch($socid); /* - * Affichage onglets - */ + * Affichage onglets + */ $head = societe_prepare_head($societe); print dol_get_fiche_head($head, 'customer', $langs->trans("ThirdParty"), 0, 'company'); @@ -68,8 +68,7 @@ if ($socid > 0) print ''; // Prefix - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print ''; @@ -84,7 +83,7 @@ if ($socid > 0) print $langs->trans("FeatureNotYetAvailable"); } else { - dol_print_error($db); + dol_print_error($db); } // End of page diff --git a/htdocs/comm/remise.php b/htdocs/comm/remise.php index e93944d4fbe..541983775a7 100644 --- a/htdocs/comm/remise.php +++ b/htdocs/comm/remise.php @@ -33,8 +33,7 @@ $id = GETPOST("id", 'int'); $socid = GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('socid', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $socid = $user->socid; } @@ -45,14 +44,12 @@ $backtopage = GETPOST('backtopage', 'alpha'); * Actions */ -if (GETPOST('cancel', 'alpha') && !empty($backtopage)) -{ +if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } -if (GETPOST('action', 'aZ09') == 'setremise') -{ +if (GETPOST('action', 'aZ09') == 'setremise') { $object = new Societe($db); $object->fetch($id); @@ -64,10 +61,8 @@ if (GETPOST('action', 'aZ09') == 'setremise') $result = $object->set_remise_client(price2num(GETPOST("remise")), GETPOST("note", "alphanohtml"), $user); } - if ($result > 0) - { - if (!empty($backtopage)) - { + if ($result > 0) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } else { @@ -94,8 +89,7 @@ llxHeader(); * Mode fiche * *********************************************************************************/ -if ($socid > 0) -{ +if ($socid > 0) { // On recupere les donnees societes par l'objet $object = new Societe($db); $object->fetch($socid); @@ -154,18 +148,17 @@ if ($socid > 0) /*if (! ($isCustomer && $isSupplier)) { - if ($isCustomer && ! $isSupplier) { - print ''; - } - if (! $isCustomer && $isSupplier) { - print ''; - } + if ($isCustomer && ! $isSupplier) { + print ''; + } + if (! $isCustomer && $isSupplier) { + print ''; + } }*/ print '
    '.$langs->trans("ProspectToContact").'
    '; diff --git a/htdocs/comm/prospect/recap-prospect.php b/htdocs/comm/prospect/recap-prospect.php index 1acf2cbf218..655dda87d0d 100644 --- a/htdocs/comm/prospect/recap-prospect.php +++ b/htdocs/comm/prospect/recap-prospect.php @@ -28,32 +28,31 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; // Load translation files required by the page $langs->loadLangs(array('companies', 'other')); -if (!empty($conf->facture->enabled)) $langs->load("bills"); +if (!empty($conf->facture->enabled)) { + $langs->load("bills"); +} // Security check $socid = $_GET["socid"]; -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } - /* * View */ llxHeader(); -if ($socid > 0) -{ +if ($socid > 0) { $societe = new Societe($db); $societe->fetch($socid); /* - * Affichage onglets - */ + * Affichage onglets + */ $head = societe_prepare_head($societe); print dol_get_fiche_head($head, 'prospect', $langs->trans("ThirdParty"), 0, 'company'); @@ -68,8 +67,7 @@ if ($socid > 0) print '
    '.$langs->trans("Thirdpary").''.$societe->getNomUrl(1).'
    '.$langs->trans("Prefix").''; print ($societe->prefix_comm ? $societe->prefix_comm : ' '); print '
    '.$langs->trans("ThirdParty").''.$societe->getNomUrl(1).'
    '.$langs->trans("Prefix").''; print ($societe->prefix_comm ? $societe->prefix_comm : ' '); print '
    '; - if ($isCustomer || $isSupplier) - { + if ($isCustomer || $isSupplier) { // Discount type print ''; print ''; print ''; print '
    '.$langs->trans('DiscountType').''; if ($isCustomer) { @@ -193,8 +186,7 @@ if ($socid > 0) print '
    '; print ''; - if (!empty($backtopage)) - { + if (!empty($backtopage)) { print '     '; print ''; } @@ -223,8 +215,7 @@ if ($socid > 0) $sql .= " ORDER BY rc.datec DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { print ''; $tag = !$tag; print ''; @@ -234,11 +225,9 @@ if ($socid > 0) print ''; print ''; $num = $db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; print ''; @@ -278,8 +267,7 @@ if ($socid > 0) $sql .= " ORDER BY rc.datec DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { print '
    '.$langs->trans("User").'
    '.dol_print_date($db->jdate($obj->dc), "dayhour").'
    '; $tag = !$tag; print ''; @@ -289,11 +277,9 @@ if ($socid > 0) print ''; print ''; $num = $db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; print ''; diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index e2900858c84..98ada17e54f 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -40,8 +40,7 @@ $backtopage = GETPOST('backtopage', 'alpha'); // Security check $socid = GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('socid', 'int'); -if ($user->socid > 0) -{ +if ($user->socid > 0) { $socid = $user->socid; } @@ -50,14 +49,12 @@ if ($user->socid > 0) * Actions */ -if (GETPOST('cancel', 'alpha') && !empty($backtopage)) -{ +if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } -if ($action == 'confirm_split' && GETPOST("confirm", "alpha") == 'yes') -{ +if ($action == 'confirm_split' && GETPOST("confirm", "alpha") == 'yes') { //if ($user->rights->societe->creer) //if ($user->rights->facture->creer) @@ -70,23 +67,19 @@ if ($action == 'confirm_split' && GETPOST("confirm", "alpha") == 'yes') $remid = (GETPOST("remid", 'int') ? GETPOST("remid", 'int') : 0); $discount = new DiscountAbsolute($db); $res = $discount->fetch($remid); - if (!($res > 0)) - { + if (!($res > 0)) { $error++; setEventMessages($langs->trans("ErrorFailedToLoadDiscount"), null, 'errors'); } - if (!$error && price2num($amount_ttc_1 + $amount_ttc_2) != $discount->amount_ttc) - { + if (!$error && price2num($amount_ttc_1 + $amount_ttc_2) != $discount->amount_ttc) { $error++; setEventMessages($langs->trans("TotalOfTwoDiscountMustEqualsOriginal"), null, 'errors'); } - if (!$error && $discount->fk_facture_line) - { + if (!$error && $discount->fk_facture_line) { $error++; setEventMessages($langs->trans("ErrorCantSplitAUsedDiscount"), null, 'errors'); } - if (!$error) - { + if (!$error) { $newdiscount1 = new DiscountAbsolute($db); $newdiscount2 = new DiscountAbsolute($db); $newdiscount1->fk_facture_source = $discount->fk_facture_source; @@ -101,8 +94,7 @@ if ($action == 'confirm_split' && GETPOST("confirm", "alpha") == 'yes') $newdiscount2->fk_invoice_supplier = $discount->fk_invoice_supplier; $newdiscount1->fk_invoice_supplier_line = $discount->fk_invoice_supplier_line; $newdiscount2->fk_invoice_supplier_line = $discount->fk_invoice_supplier_line; - if ($discount->description == '(CREDIT_NOTE)' || $discount->description == '(DEPOSIT)') - { + if ($discount->description == '(CREDIT_NOTE)' || $discount->description == '(DEPOSIT)') { $newdiscount1->description = $discount->description; $newdiscount2->description = $discount->description; } else { @@ -143,8 +135,7 @@ if ($action == 'confirm_split' && GETPOST("confirm", "alpha") == 'yes') $res = $discount->delete($user); $newid1 = $newdiscount1->create($user); $newid2 = $newdiscount2->create($user); - if ($res > 0 && $newid1 > 0 && $newid2 > 0) - { + if ($res > 0 && $newid1 > 0 && $newid2 > 0) { $db->commit(); header("Location: ".$_SERVER["PHP_SELF"].'?id='.$id.($backtopage ? '&backtopage='.urlencode($backtopage) : '')); // To avoid pb whith back exit; @@ -154,8 +145,7 @@ if ($action == 'confirm_split' && GETPOST("confirm", "alpha") == 'yes') } } -if ($action == 'setremise' && $user->rights->societe->creer) -{ +if ($action == 'setremise' && $user->rights->societe->creer) { //if ($user->rights->societe->creer) //if ($user->rights->facture->creer) @@ -164,25 +154,20 @@ if ($action == 'setremise' && $user->rights->societe->creer) $tva_tx = GETPOST('tva_tx', 'alpha'); $discount_type = !empty($_POST['discount_type']) ?GETPOST('discount_type', 'alpha') : 0; - if ($amount_ht > 0) - { + if ($amount_ht > 0) { $error = 0; - if (empty($desc)) - { + if (empty($desc)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReasonDiscount")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $soc = new Societe($db); $soc->fetch($id); $discountid = $soc->set_remise_except($amount_ht, $user, $desc, $tva_tx, $discount_type); - if ($discountid > 0) - { - if (!empty($backtopage)) - { + if ($discountid > 0) { + if (!empty($backtopage)) { header("Location: ".$backtopage.'&discountid='.$discountid); exit; } else { @@ -199,8 +184,7 @@ if ($action == 'setremise' && $user->rights->societe->creer) } } -if (GETPOST('action', 'aZ09') == 'confirm_remove' && GETPOST("confirm") == 'yes') -{ +if (GETPOST('action', 'aZ09') == 'confirm_remove' && GETPOST("confirm") == 'yes') { //if ($user->rights->societe->creer) //if ($user->rights->facture->creer) @@ -209,8 +193,7 @@ if (GETPOST('action', 'aZ09') == 'confirm_remove' && GETPOST("confirm") == 'yes' $discount = new DiscountAbsolute($db); $result = $discount->fetch(GETPOST("remid")); $result = $discount->delete($user); - if ($result > 0) - { + if ($result > 0) { $db->commit(); header("Location: ".$_SERVER["PHP_SELF"].'?id='.$id); // To avoid pb whith back exit; @@ -231,8 +214,7 @@ $facturefournstatic = new FactureFournisseur($db); llxHeader('', $langs->trans("GlobalDiscount")); -if ($socid > 0) -{ +if ($socid > 0) { // On recupere les donnees societes par l'objet $object = new Societe($db); $object->fetch($socid); @@ -283,11 +265,12 @@ if ($socid > 0) $sql .= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)"; $sql .= " GROUP BY rc.fk_user"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $remise_all += $obj->amount; - if ($obj->fk_user == $user->id) $remise_user += $obj->amount; + if ($obj->fk_user == $user->id) { + $remise_user += $obj->amount; + } } else { dol_print_error($db); } @@ -295,8 +278,7 @@ if ($socid > 0) print ''; print ''; - if (!empty($user->fk_soc)) // No need to show this for external users - { + if (!empty($user->fk_soc)) { // No need to show this for external users print ''; print ''; } @@ -313,11 +295,12 @@ if ($socid > 0) $sql .= " AND (fk_invoice_supplier_line IS NULL AND fk_invoice_supplier IS NULL)"; $sql .= " GROUP BY rc.fk_user"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $remise_all += $obj->amount; - if ($obj->fk_user == $user->id) $remise_user += $obj->amount; + if ($obj->fk_user == $user->id) { + $remise_user += $obj->amount; + } } else { dol_print_error($db); } @@ -325,8 +308,7 @@ if ($socid > 0) print ''; print ''; - if (!empty($user->fk_soc)) // No need to show this for external users - { + if (!empty($user->fk_soc)) { // No need to show this for external users print ''; print ''; } @@ -339,8 +321,7 @@ if ($socid > 0) print dol_get_fiche_end(); - if ($user->rights->societe->creer) - { + if ($user->rights->societe->creer) { print '
    '; print load_fiche_titre($langs->trans("NewGlobalDiscount"), '', ''); @@ -378,12 +359,10 @@ if ($socid > 0) print dol_get_fiche_end(); } - if ($user->rights->societe->creer) - { + if ($user->rights->societe->creer) { print '
    '; print ''; - if (!empty($backtopage)) - { + if (!empty($backtopage)) { print '     '; print ''; } @@ -395,8 +374,7 @@ if ($socid > 0) print '
    '; - if ($_GET['action'] == 'remove') - { + if ($_GET['action'] == 'remove') { print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.GETPOST('remid'), $langs->trans('RemoveDiscount'), $langs->trans('ConfirmRemoveDiscount'), 'confirm_remove', '', 0, 1); } @@ -430,8 +408,7 @@ if ($socid > 0) $sql .= " ORDER BY rc.datec DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { print '
    '; print '
    '.$langs->trans("User").'
    '.dol_print_date($db->jdate($obj->dc), "dayhour").'
    '.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '.$langs->trans("SupplierAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '.$langs->trans("SupplierAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '; print ''; @@ -439,14 +416,12 @@ if ($socid > 0) print ''; print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; @@ -457,32 +432,27 @@ if ($socid > 0) $i = 0; $num = $db->num_rows($resql); - if ($num > 0) - { - while ($i < $num) - { + if ($num > 0) { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; print ''; - if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) - { + if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) { print ''; - } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) - { + } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) { print ''; - } elseif (preg_match('/\(EXCESS RECEIVED\)/', $obj->description)) - { + } elseif (preg_match('/\(EXCESS RECEIVED\)/', $obj->description)) { print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; - if ($user->rights->societe->creer || $user->rights->facture->creer) - { + if ($user->rights->societe->creer || $user->rights->facture->creer) { print ''; - } else print ''; + } else { + print ''; + } print ''; - if ($_GET["action"] == 'split' && GETPOST('remid') == $obj->rowid) - { + if ($_GET["action"] == 'split' && GETPOST('remid') == $obj->rowid) { $showconfirminfo['rowid'] = $obj->rowid; $showconfirminfo['amount_ttc'] = $obj->amount_ttc; } @@ -527,15 +495,16 @@ if ($socid > 0) } } else { $colspan = 8; - if (!empty($conf->multicurrency->enabled)) $colspan += 2; + if (!empty($conf->multicurrency->enabled)) { + $colspan += 2; + } print ''; } $db->free($resql); print "
    '.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("MulticurrencyAmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("MulticurrencyAmountTTC").''.$langs->trans("DiscountOfferedBy").'
    '.dol_print_date($db->jdate($obj->dc), 'dayhour').''; $facturestatic->id = $obj->fk_facture_source; $facturestatic->ref = $obj->ref; $facturestatic->type = $obj->type; print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturestatic->getNomURl(1); print ''; $facturestatic->id = $obj->fk_facture_source; $facturestatic->ref = $obj->ref; $facturestatic->type = $obj->type; print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturestatic->getNomURl(1); print ''; $facturestatic->id = $obj->fk_facture_source; $facturestatic->ref = $obj->ref; @@ -496,30 +466,28 @@ if ($socid > 0) } print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price($obj->multicurrency_amount_ht).''.vatrate($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), true).''.price($obj->amount_ttc).''.price($obj->multicurrency_amount_ttc).''; print ''.img_object($langs->trans("ShowUser"), 'user').' '.$obj->login.''; print ''; print 'rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_split($langs->trans("SplitDiscount")).''; print 'rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_delete($langs->trans("RemoveDiscount")).''; print '  
    '.$langs->trans("None").'
    "; print '
    '; - if (count($showconfirminfo)) - { + if (count($showconfirminfo)) { $amount1 = price2num($showconfirminfo['amount_ttc'] / 2, 'MT'); $amount2 = ($showconfirminfo['amount_ttc'] - $amount1); $formquestion = array( @@ -578,8 +547,7 @@ if ($socid > 0) $sql .= " ORDER BY rc.datec DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { print '
    '; print ''; print ''; @@ -587,14 +555,12 @@ if ($socid > 0) print ''; print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; @@ -605,32 +571,27 @@ if ($socid > 0) $i = 0; $num = $db->num_rows($resql); - if ($num > 0) - { - while ($i < $num) - { + if ($num > 0) { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; print ''; - if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) - { + if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) { print ''; - } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) - { + } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) { print ''; - } elseif (preg_match('/\(EXCESS PAID\)/', $obj->description)) - { + } elseif (preg_match('/\(EXCESS PAID\)/', $obj->description)) { print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; - if ($user->rights->societe->creer || $user->rights->facture->creer) - { + if ($user->rights->societe->creer || $user->rights->facture->creer) { print ''; - } else print ''; + } else { + print ''; + } print ''; - if ($_GET["action"] == 'split' && GETPOST('remid') == $obj->rowid) - { + if ($_GET["action"] == 'split' && GETPOST('remid') == $obj->rowid) { $showconfirminfo['rowid'] = $obj->rowid; $showconfirminfo['amount_ttc'] = $obj->amount_ttc; } @@ -675,15 +634,16 @@ if ($socid > 0) } } else { $colspan = 8; - if (!empty($conf->multicurrency->enabled)) $colspan += 2; + if (!empty($conf->multicurrency->enabled)) { + $colspan += 2; + } print ''; } $db->free($resql); print "
    '.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("MulticurrencyAmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("MulticurrencyAmountTTC").''.$langs->trans("DiscountOfferedBy").'
    '.dol_print_date($db->jdate($obj->dc), 'dayhour').''; $facturefournstatic->id = $obj->fk_invoice_supplier_source; $facturefournstatic->ref = $obj->ref; $facturefournstatic->type = $obj->type; print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturefournstatic->getNomURl(1); print ''; $facturefournstatic->id = $obj->fk_invoice_supplier_source; $facturefournstatic->ref = $obj->ref; $facturefournstatic->type = $obj->type; print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturefournstatic->getNomURl(1); print ''; $facturefournstatic->id = $obj->fk_invoice_supplier_source; $facturefournstatic->ref = $obj->ref; @@ -644,30 +605,28 @@ if ($socid > 0) } print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price($obj->multicurrency_amount_ht).''.vatrate($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), true).''.price($obj->amount_ttc).''.price($obj->multicurrency_amount_ttc).''; print ''.img_object($langs->trans("ShowUser"), 'user').' '.$obj->login.''; print ''; print 'rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_split($langs->trans("SplitDiscount")).''; print 'rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_delete($langs->trans("RemoveDiscount")).''; print '  
    '.$langs->trans("None").'
    "; print '
    '; - if (count($showconfirminfo)) - { + if (count($showconfirminfo)) { $amount1 = price2num($showconfirminfo['amount_ttc'] / 2, 'MT'); $amount2 = ($showconfirminfo['amount_ttc'] - $amount1); $formquestion = array( @@ -758,9 +718,10 @@ if ($socid > 0) $resql = $db->query($sql); $resql2 = null; - if ($resql) $resql2 = $db->query($sql2); - if ($resql2) - { + if ($resql) { + $resql2 = $db->query($sql2); + } + if ($resql2) { print '
    '; print ''; print ''; @@ -768,14 +729,12 @@ if ($socid > 0) print ''; print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; @@ -785,10 +744,8 @@ if ($socid > 0) $tab_sqlobj = array(); $tab_sqlobjOrder = array(); $num = $db->num_rows($resql); - if ($num > 0) - { - for ($i = 0; $i < $num; $i++) - { + if ($num > 0) { + for ($i = 0; $i < $num; $i++) { $sqlobj = $db->fetch_object($resql); $tab_sqlobj[] = $sqlobj; $tab_sqlobjOrder[] = $db->jdate($sqlobj->dc); @@ -797,8 +754,7 @@ if ($socid > 0) $db->free($resql); $num = $db->num_rows($resql2); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $sqlobj = $db->fetch_object($resql2); $tab_sqlobj[] = $sqlobj; $tab_sqlobjOrder[] = $db->jdate($sqlobj->dc); @@ -807,32 +763,27 @@ if ($socid > 0) array_multisort($tab_sqlobjOrder, SORT_DESC, $tab_sqlobj); $num = count($tab_sqlobj); - if ($num > 0) - { + if ($num > 0) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = array_shift($tab_sqlobj); print ''; print ''; - if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) - { + if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) { print ''; - } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) - { + } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) { print ''; - } elseif (preg_match('/\(EXCESS RECEIVED\)/', $obj->description)) - { + } elseif (preg_match('/\(EXCESS RECEIVED\)/', $obj->description)) { print ''; } print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; } @@ -928,9 +878,10 @@ if ($socid > 0) $resql = $db->query($sql); $resql2 = null; - if ($resql) $resql2 = $db->query($sql2); - if ($resql2) - { + if ($resql) { + $resql2 = $db->query($sql2); + } + if ($resql2) { print '
    '; print '
    '.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("MulticurrencyAmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("MulticurrencyAmountTTC").''.$langs->trans("Author").'
    '.dol_print_date($db->jdate($obj->dc), 'dayhour').''; $facturestatic->id = $obj->fk_facture_source; $facturestatic->ref = $obj->invoice_source_ref; $facturestatic->type = $obj->type; print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturestatic->getNomURl(1); print ''; $facturestatic->id = $obj->fk_facture_source; $facturestatic->ref = $obj->invoice_source_ref; $facturestatic->type = $obj->type; print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturestatic->getNomURl(1); print ''; $facturestatic->id = $obj->fk_facture_source; $facturestatic->ref = $obj->invoice_source_ref; @@ -845,20 +796,17 @@ if ($socid > 0) print ''; - if ($obj->invoiceid) - { + if ($obj->invoiceid) { print ''.img_object($langs->trans("ShowBill"), 'bill').' '.$obj->ref.''; } print ''.price($obj->amount_ht).''.price($obj->multicurrency_amount_ht).''.vatrate($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), true).''.price($obj->amount_ttc).''.price($obj->multicurrency_amount_ttc).''; @@ -870,7 +818,9 @@ if ($socid > 0) } } else { $colspan = 8; - if (!empty($conf->multicurrency->enabled)) $colspan += 2; + if (!empty($conf->multicurrency->enabled)) { + $colspan += 2; + } print '
    '.$langs->trans("None").'
    '; print ''; @@ -938,14 +889,12 @@ if ($socid > 0) print ''; print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; @@ -955,10 +904,8 @@ if ($socid > 0) $tab_sqlobj = array(); $tab_sqlobjOrder = array(); $num = $db->num_rows($resql); - if ($num > 0) - { - for ($i = 0; $i < $num; $i++) - { + if ($num > 0) { + for ($i = 0; $i < $num; $i++) { $sqlobj = $db->fetch_object($resql); $tab_sqlobj[] = $sqlobj; $tab_sqlobjOrder[] = $db->jdate($sqlobj->dc); @@ -967,8 +914,7 @@ if ($socid > 0) $db->free($resql); $num = $db->num_rows($resql2); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $sqlobj = $db->fetch_object($resql2); $tab_sqlobj[] = $sqlobj; $tab_sqlobjOrder[] = $db->jdate($sqlobj->dc); @@ -977,32 +923,27 @@ if ($socid > 0) array_multisort($tab_sqlobjOrder, SORT_DESC, $tab_sqlobj); $num = count($tab_sqlobj); - if ($num > 0) - { + if ($num > 0) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = array_shift($tab_sqlobj); print ''; print ''; - if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) - { + if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) { print ''; - } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) - { + } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) { print ''; - } elseif (preg_match('/\(EXCESS PAID\)/', $obj->description)) - { + } elseif (preg_match('/\(EXCESS PAID\)/', $obj->description)) { print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; } diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index f7cc3e7af47..a46e7df6b75 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -60,9 +60,15 @@ if (!empty($conf->variants->enabled)) { // Load translation files required by the page $langs->loadLangs(array('orders', 'sendings', 'companies', 'bills', 'propal', 'deliveries', 'products', 'other')); -if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); -if (!empty($conf->margin->enabled)) $langs->load('margins'); -if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); +if (!empty($conf->incoterm->enabled)) { + $langs->load('incoterm'); +} +if (!empty($conf->margin->enabled)) { + $langs->load('margins'); +} +if (!empty($conf->productbatch->enabled)) { + $langs->load("productbatch"); +} $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('orderid', 'int')); $ref = GETPOST('ref', 'alpha'); @@ -82,8 +88,9 @@ $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($ $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); // Security check -if (!empty($user->socid)) +if (!empty($user->socid)) { $socid = $user->socid; +} $result = restrictedArea($user, 'commande', $id); $object = new Commande($db); @@ -125,14 +132,13 @@ $date_delivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int' $parameters = array('socid' => $socid); // Note that $action and $object may be modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ - if ($cancel) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -146,20 +152,16 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) - { - if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) - { + if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) { + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { - if ($object->id > 0) - { + if ($object->id > 0) { // Because createFromClone modifies the object, we must clone it so that we can restore it later $orig = clone $object; $result = $object->createFromClone($user, $socid); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit; } else { @@ -169,49 +171,38 @@ if (empty($reshook)) } } } - } - - // Reopen a closed order - elseif ($action == 'reopen' && $usercancreate) - { - if ($object->statut == Commande::STATUS_CANCELED || $object->statut == Commande::STATUS_CLOSED) - { + } elseif ($action == 'reopen' && $usercancreate) { + // Reopen a closed order + if ($object->statut == Commande::STATUS_CANCELED || $object->statut == Commande::STATUS_CLOSED) { $result = $object->set_reopen($user); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans('OrderReopened', $object->ref), null); } else { setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // Remove order - elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) - { + } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) { + // Remove order $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { header('Location: list.php?restore_lastsearch_values=1'); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Remove a product line - elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) - { + } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) { + // Remove a product line $result = $object->deleteline($user, $lineid); - if ($result > 0) - { + if ($result > 0) { // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -226,19 +217,13 @@ if (empty($reshook)) } else { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Link to a project - elseif ($action == 'classin' && $usercancreate) - { + } elseif ($action == 'classin' && $usercancreate) { + // Link to a project $object->setProject(GETPOST('projectid', 'int')); - } - - // Add order - elseif ($action == 'add' && $usercancreate) - { + } elseif ($action == 'add' && $usercancreate) { + // Add order $datecommande = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - $datelivraison = dol_mktime(12, 0, 0, GETPOST('liv_month'), GETPOST('liv_day'), GETPOST('liv_year')); + $date_delivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int')); $selectedLines = GETPOST('toselect', 'array'); if ($datecommande == '') { @@ -271,8 +256,8 @@ if (empty($reshook)) $object->fk_account = GETPOST('fk_account', 'int'); $object->availability_id = GETPOST('availability_id'); $object->demand_reason_id = GETPOST('demand_reason_id'); - $object->date_livraison = $datelivraison; // deprecated - $object->delivery_date = $datelivraison; + $object->date_livraison = $date_delivery; // deprecated + $object->delivery_date = $date_delivery; $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); $object->warehouse_id = GETPOST('warehouse_id', 'int'); $object->fk_delivery_address = GETPOST('fk_address'); @@ -282,15 +267,15 @@ if (empty($reshook)) $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); // Fill array 'array_options' with data from add form - if (!$error) - { + if (!$error) { $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } // If creation from another object of another module (Example: origin=propal, originid=1) - if (!empty($origin) && !empty($originid)) - { + if (!empty($origin) && !empty($originid)) { // Parse element/subelement (ex: project_task) $element = $subelement = $origin; if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) { @@ -320,12 +305,10 @@ if (empty($reshook)) $object->linked_objects = array_merge($object->linked_objects, $other_linked_objects); } - if (!$error) - { + if (!$error) { $object_id = $object->create($user); - if ($object_id > 0) - { + if ($object_id > 0) { dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); @@ -333,11 +316,9 @@ if (empty($reshook)) dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); $result = $srcobject->fetch($object->origin_id); - if ($result > 0) - { + if ($result > 0) { $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject, 'fetch_lines')) - { + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) { $srcobject->fetch_lines(); $lines = $srcobject->lines; } @@ -345,9 +326,10 @@ if (empty($reshook)) $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { - if (!in_array($lines[$i]->id, $selectedLines)) continue; // Skip unselected lines + for ($i = 0; $i < $num; $i++) { + if (!in_array($lines[$i]->id, $selectedLines)) { + continue; // Skip unselected lines + } $label = (!empty($lines[$i]->label) ? $lines[$i]->label : ''); $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : ''); @@ -356,15 +338,19 @@ if (empty($reshook)) // Dates // TODO mutualiser $date_start = $lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) + if ($lines[$i]->date_debut_reel) { $date_start = $lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) + } + if ($lines[$i]->date_start) { $date_start = $lines[$i]->date_start; + } $date_end = $lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) + if ($lines[$i]->date_fin_reel) { $date_end = $lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) + } + if ($lines[$i]->date_end) { $date_end = $lines[$i]->date_end; + } // Reset fk_parent_line for no child products and special product if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) { @@ -372,20 +358,42 @@ if (empty($reshook)) } // Extrafields - if (method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if trigger used - { + if (method_exists($lines[$i], 'fetch_optionals')) { // For avoid conflicts if trigger used $lines[$i]->fetch_optionals(); $array_options = $lines[$i]->array_options; } $tva_tx = $lines[$i]->tva_tx; - if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$i]->vat_src_code.')'; + if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) { + $tva_tx .= ' ('.$lines[$i]->vat_src_code.')'; + } $result = $object->addline( - $desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, - $lines[$i]->remise_percent, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $date_start, $date_end, $product_type, - $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, - $lines[$i]->fk_unit, $object->origin, $lines[$i]->rowid + $desc, + $lines[$i]->subprice, + $lines[$i]->qty, + $tva_tx, + $lines[$i]->localtax1_tx, + $lines[$i]->localtax2_tx, + $lines[$i]->fk_product, + $lines[$i]->remise_percent, + $lines[$i]->info_bits, + $lines[$i]->fk_remise_except, + 'HT', + 0, + $date_start, + $date_end, + $product_type, + $lines[$i]->rang, + $lines[$i]->special_code, + $fk_parent_line, + $lines[$i]->fk_fournprice, + $lines[$i]->pa_ht, + $label, + $array_options, + $lines[$i]->fk_unit, + $object->origin, + $lines[$i]->rowid ); if ($result < 0) { @@ -407,26 +415,26 @@ if (empty($reshook)) /* Useless, already into the create if (! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN)) { - $originforcontact = $object->origin; - $originidforcontact = $object->origin_id; - if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order - { - $originforcontact=$srcobject->origin; - $originidforcontact=$srcobject->origin_id; - } - $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc"; - $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'"; + $originforcontact = $object->origin; + $originidforcontact = $object->origin_id; + if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order + { + $originforcontact=$srcobject->origin; + $originidforcontact=$srcobject->origin_id; + } + $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc"; + $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'"; - $resqlcontact = $db->query($sqlcontact); - if ($resqlcontact) - { - while($objcontact = $db->fetch_object($resqlcontact)) - { - //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n"; - $object->add_contact($objcontact->fk_socpeople, $objcontact->code); - } - } - else dol_print_error($resqlcontact); + $resqlcontact = $db->query($sqlcontact); + if ($resqlcontact) + { + while($objcontact = $db->fetch_object($resqlcontact)) + { + //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n"; + $object->add_contact($objcontact->fk_socpeople, $objcontact->code); + } + } + else dol_print_error($resqlcontact); }*/ // Hooks @@ -445,15 +453,13 @@ if (empty($reshook)) $action = 'create'; } } else { - if (!$error) - { + if (!$error) { $object_id = $object->create($user); } } // Insert default contacts if defined - if ($object_id > 0) - { + if ($object_id > 0) { if (GETPOST('contactid', 'int')) { $result = $object->add_contact(GETPOST('contactid', 'int'), 'CUSTOMER', 'external'); if ($result < 0) { @@ -467,8 +473,7 @@ if (empty($reshook)) } // End of object creation, we show it - if ($object_id > 0 && !$error) - { + if ($object_id > 0 && !$error) { $db->commit(); header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object_id); exit(); @@ -478,32 +483,26 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } } - } elseif ($action == 'classifybilled' && $usercancreate) - { + } elseif ($action == 'classifybilled' && $usercancreate) { $ret = $object->classifyBilled($user); if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'classifyunbilled' && $usercancreate) - { - $ret = $object->classifyUnBilled(); + } elseif ($action == 'classifyunbilled' && $usercancreate) { + $ret = $object->classifyUnBilled($user); if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Positionne ref commande client - elseif ($action == 'setref_client' && $usercancreate) { + } elseif ($action == 'setref_client' && $usercancreate) { + // Positionne ref commande client $result = $object->set_ref_client($user, GETPOST('ref_client')); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } } elseif ($action == 'setremise' && $usercancreate) { $result = $object->setDiscount($user, GETPOST('remise')); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } } elseif ($action == 'setabsolutediscount' && $usercancreate) { @@ -533,26 +532,25 @@ if (empty($reshook)) } } elseif ($action == 'setmode' && $usercancreate) { $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - if ($result < 0) + if ($result < 0) { 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) { - $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx'))); + } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + // Multicurrency rate + $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int')); } elseif ($action == 'setavailability' && $usercancreate) { $result = $object->availability(GETPOST('availability_id')); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } elseif ($action == 'setdemandreason' && $usercancreate) { $result = $object->demand_reason(GETPOST('demand_reason_id')); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } elseif ($action == 'setconditions' && $usercancreate) { $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); if ($result < 0) { @@ -562,8 +560,9 @@ if (empty($reshook)) // Define output language $outputlangs = $langs; $newlang = GETPOST('lang_id', 'alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -573,35 +572,26 @@ if (empty($reshook)) $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } } - } - - // Set incoterm - elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { + } elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) { + // Set incoterm $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // bank account - elseif ($action == 'setbankaccount' && $usercancreate) { + } elseif ($action == 'setbankaccount' && $usercancreate) { + // bank account $result = $object->setBankAccount(GETPOST('fk_account', 'int')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // shipping method - elseif ($action == 'setshippingmethod' && $usercancreate) { + } elseif ($action == 'setshippingmethod' && $usercancreate) { + // shipping method $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // warehouse - elseif ($action == 'setwarehouse' && $usercancreate) { + } elseif ($action == 'setwarehouse' && $usercancreate) { + // warehouse $result = $object->setWarehouse(GETPOST('warehouse_id', 'int')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -610,7 +600,7 @@ if (empty($reshook)) $result = $object->setDiscount($user, price2num(GETPOST('remise_percent'), 2)); } elseif ($action == 'setremiseabsolue' && $usercancreate) { $result = $object->set_remise_absolue($user, price2num(GETPOST('remise_absolue'), 'MU')); - } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('vatforalllines', 'alpha')) { + } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('vatforalllines', 'alpha') !== '') { // Define vat_rate $vat_rate = (GETPOST('vatforalllines') ? GETPOST('vatforalllines') : 0); $vat_rate = str_replace('*', '', $vat_rate); @@ -619,19 +609,17 @@ if (empty($reshook)) foreach ($object->lines as $line) { $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $line->info_bits, $line->date_start, $line->date_end, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); } - } elseif ($action == 'addline' && $usercancreate) // Add a new line - { + } elseif ($action == 'addline' && $usercancreate) { // Add a new line $langs->load('errors'); $error = 0; // 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') - { + if ($prod_entry_mode == 'free') { $idprod = 0; $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); } else { @@ -665,8 +653,7 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && empty($idprod) && $price_ht == '' && $price_ht_devise == '') // Unit price can be 0 but not ''. Also price can be negative for order. - { + if ($prod_entry_mode == 'free' && empty($idprod) && $price_ht == '' && $price_ht_devise == '') { // Unit price can be 0 but not ''. Also price can be negative for order. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors'); $error++; } @@ -712,7 +699,9 @@ if (empty($reshook)) // Update if prices fields are defined $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $pu_ht = $prod->price; $pu_ttc = $prod->price_ttc; @@ -720,21 +709,21 @@ if (empty($reshook)) $price_base_type = $prod->price_base_type; // If price per segment - if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) - { + if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) { $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; - if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility - { - if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx = $prod->multiprices_tva_tx[$object->thirdparty->price_level]; - if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr = $prod->multiprices_recuperableonly[$object->thirdparty->price_level]; + if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility + if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) { + $tva_tx = $prod->multiprices_tva_tx[$object->thirdparty->price_level]; + } + if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) { + $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); @@ -742,38 +731,37 @@ if (empty($reshook)) $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $object->thirdparty->id); $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); - if ($result >= 0) - { - if (count($prodcustprice->lines) > 0) - { + if ($result >= 0) { + if (count($prodcustprice->lines) > 0) { $pu_ht = price($prodcustprice->lines[0]->price); $pu_ttc = price($prodcustprice->lines[0]->price_ttc); $price_min = price($prodcustprice->lines[0]->price_min); $price_base_type = $prodcustprice->lines[0]->price_base_type; $tva_tx = $prodcustprice->lines[0]->tva_tx; - if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; + if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) { + $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; + } $tva_npr = $prodcustprice->lines[0]->recuperableonly; - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } } } else { setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors'); } - } - // If price per quantity - elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) - { - if ($prod->prices_by_qty[0]) // yes, this product has some prices per quantity - { + } 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'); // Search price into product_price_by_qty from $prod->id - foreach ($prod->prices_by_qty_list[0] as $priceforthequantityarray) - { - if ($priceforthequantityarray['rowid'] != $pqp) continue; + foreach ($prod->prices_by_qty_list[0] as $priceforthequantityarray) { + if ($priceforthequantityarray['rowid'] != $pqp) { + continue; + } // We found the price - if ($priceforthequantityarray['price_base_type'] == 'HT') - { + if ($priceforthequantityarray['price_base_type'] == 'HT') { $pu_ht = $priceforthequantityarray['unitprice']; } else { $pu_ttc = $priceforthequantityarray['unitprice']; @@ -782,21 +770,18 @@ if (empty($reshook)) break; } } - } - // If price per quantity and customer - elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) - { - if ($prod->prices_by_qty[$object->thirdparty->price_level]) // yes, this product has some prices per quantity - { + } 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'); // Search price into product_price_by_qty from $prod->id - foreach ($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) - { - if ($priceforthequantityarray['rowid'] != $pqp) continue; + foreach ($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) { + if ($priceforthequantityarray['rowid'] != $pqp) { + continue; + } // We found the price - if ($priceforthequantityarray['price_base_type'] == 'HT') - { + if ($priceforthequantityarray['price_base_type'] == 'HT') { $pu_ht = $priceforthequantityarray['unitprice']; } else { $pu_ttc = $priceforthequantityarray['unitprice']; @@ -814,10 +799,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 { @@ -831,16 +815,18 @@ if (empty($reshook)) if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) + } + if (empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $desc = (!empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description; + $desc = (!empty($prod->multilangs[$outputlangs->defaultlang]["description"])) ? $prod->multilangs[$outputlangs->defaultlang]["description"] : $prod->description; } else { $desc = $prod->description; } @@ -850,8 +836,11 @@ if (empty($reshook)) $product_desc=''; } - if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $desc = $product_desc; - else $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) { + $desc = $product_desc; + } else { + $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + } // Add custom code and origin country into description if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) { @@ -860,28 +849,36 @@ if (empty($reshook)) if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'alpha')) + if (empty($newlang) && GETPOST('lang_id', 'alpha')) { $newlang = GETPOST('lang_id', 'alpha'); - if (empty($newlang)) + } + if (empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - if (!empty($prod->customcode)) + if (!empty($prod->customcode)) { $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; - if (!empty($prod->customcode) && !empty($prod->country_code)) + } + if (!empty($prod->customcode) && !empty($prod->country_code)) { $tmptxt .= ' - '; - if (!empty($prod->country_code)) + } + if (!empty($prod->country_code)) { $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0); + } } else { - if (!empty($prod->customcode)) + if (!empty($prod->customcode)) { $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; - if (!empty($prod->customcode) && !empty($prod->country_code)) + } + if (!empty($prod->customcode) && !empty($prod->country_code)) { $tmptxt .= ' - '; - if (!empty($prod->country_code)) + } + if (!empty($prod->country_code)) { $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0); + } } $tmptxt .= ')'; $desc = dol_concatdesc($desc, $tmptxt); @@ -912,8 +909,9 @@ if (empty($reshook)) $desc = dol_htmlcleanlastbr($desc); $info_bits = 0; - if ($tva_npr) + if ($tva_npr) { $info_bits |= 0x01; + } if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && (!empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) { $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)); @@ -930,8 +928,9 @@ if (empty($reshook)) // Define output language $outputlangs = $langs; $newlang = GETPOST('lang_id', 'alpha'); - if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) + if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -977,27 +976,23 @@ if (empty($reshook)) } } } - } - - /* - * Update a line - */ - elseif ($action == 'updateline' && $usercancreate && GETPOST('save')) - { + } elseif ($action == 'updateline' && $usercancreate && GETPOST('save')) { + // Update a line // Clean parameters $date_start = ''; $date_end = ''; $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; - if (preg_match('/\*/', $vat_rate)) + if (preg_match('/\*/', $vat_rate)) { $info_bits |= 0x01; + } // Define vat_rate $vat_rate = str_replace('*', '', $vat_rate); @@ -1020,7 +1015,9 @@ if (empty($reshook)) // Define special_code for special lines $special_code = GETPOST('special_code'); - if (!GETPOST('qty')) $special_code = 3; + if (!GETPOST('qty')) { + $special_code = 3; + } // Check minimum price $productid = GETPOST('productid', 'int'); @@ -1031,8 +1028,9 @@ if (empty($reshook)) $type = $product->type; $price_min = $product->price_min; - if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) + if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) { $price_min = $product->multiprices_min[$object->thirdparty->price_level]; + } $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); @@ -1052,12 +1050,9 @@ if (empty($reshook)) } if (!$error) { - if (empty($user->rights->margins->creer)) - { - foreach ($object->lines as &$line) - { - if ($line->id == GETPOST('lineid')) - { + if (empty($user->rights->margins->creer)) { + foreach ($object->lines as &$line) { + if ($line->id == GETPOST('lineid')) { $fournprice = $line->fk_fournprice; $buyingprice = $line->pa_ht; break; @@ -1071,10 +1066,12 @@ if (empty($reshook)) // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -1117,23 +1114,19 @@ if (empty($reshook)) } elseif ($action == 'updateline' && $usercancreate && GETPOST('cancel', 'alpha') == $langs->trans("Cancel")) { header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); // Pour reaffichage de la fiche en cours d'edition exit(); - } elseif ($action == 'confirm_validate' && $confirm == 'yes' && $usercanvalidate) - { + } elseif ($action == 'confirm_validate' && $confirm == 'yes' && $usercanvalidate) { $idwarehouse = GETPOST('idwarehouse', 'int'); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { - $qualified_for_stock_change = $object->hasProductsOrServices(1); + $qualified_for_stock_change = $object->hasProductsOrServices(1); } // Check parameters - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) - { - if (!$idwarehouse || $idwarehouse == -1) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; @@ -1142,15 +1135,17 @@ if (empty($reshook)) if (!$error) { $result = $object->valid($user, $idwarehouse); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -1164,25 +1159,20 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // Go back to draft status - elseif ($action == 'confirm_modif' && $usercancreate) { + } elseif ($action == 'confirm_modif' && $usercancreate) { + // Go back to draft status $idwarehouse = GETPOST('idwarehouse'); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { - $qualified_for_stock_change = $object->hasProductsOrServices(1); + $qualified_for_stock_change = $object->hasProductsOrServices(1); } // Check parameters - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) - { - if (!$idwarehouse || $idwarehouse == -1) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; @@ -1191,15 +1181,17 @@ if (empty($reshook)) if (!$error) { $result = $object->setDraft($user, $idwarehouse); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -1216,23 +1208,19 @@ if (empty($reshook)) if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'confirm_cancel' && $confirm == 'yes' && $usercanvalidate) - { + } elseif ($action == 'confirm_cancel' && $confirm == 'yes' && $usercanvalidate) { $idwarehouse = GETPOST('idwarehouse', 'int'); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { - $qualified_for_stock_change = $object->hasProductsOrServices(1); + $qualified_for_stock_change = $object->hasProductsOrServices(1); } // Check parameters - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) - { - if (!$idwarehouse || $idwarehouse == -1) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; @@ -1248,58 +1236,53 @@ if (empty($reshook)) } } - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('ORDER_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } - if ($error) $action = 'edit_extras'; + if ($error) { + $action = 'edit_extras'; + } } // add lines from objectlinked if ($action == 'import_lines_from_object' && $usercancreate && $object->statut == Commande::STATUS_DRAFT - ) - { + ) { $fromElement = GETPOST('fromelement'); $fromElementid = GETPOST('fromelementid'); $importLines = GETPOST('line_checkbox'); - if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) - { - if ($fromElement == 'commande') - { + if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) { + if ($fromElement == 'commande') { dol_include_once('/'.$fromElement.'/class/'.$fromElement.'.class.php'); $lineClassName = 'OrderLine'; - } elseif ($fromElement == 'propal') - { + } elseif ($fromElement == 'propal') { dol_include_once('/comm/'.$fromElement.'/class/'.$fromElement.'.class.php'); $lineClassName = 'PropaleLigne'; } $nextRang = count($object->lines) + 1; $importCount = 0; $error = 0; - foreach ($importLines as $lineId) - { + foreach ($importLines as $lineId) { $lineId = intval($lineId); $originLine = new $lineClassName($db); - if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) - { + if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) { $originLine->fetch_optionals(); $desc = $originLine->desc; $pu_ht = $originLine->subprice; @@ -1343,8 +1326,7 @@ if (empty($reshook)) } } - if ($error) - { + if ($error) { setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors'); } } @@ -1366,10 +1348,8 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - if (!$error && !empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) - { - if ($action == 'addcontact') - { + if (!$error && !empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) { + if ($action == 'addcontact') { if ($object->id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); @@ -1387,21 +1367,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->id > 0) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { dol_print_error($db); } - } - - // Efface un contact - elseif ($action == 'deletecontact') - { + } elseif ($action == 'deletecontact') { + // Efface un contact $result = $object->delete_contact($lineid); if ($result >= 0) { @@ -1419,22 +1393,24 @@ if (empty($reshook)) * View */ -llxHeader('', $langs->trans('Order'), 'EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes'); +llxHeader('', $langs->trans('Order'), 'EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes|DE:Modul_Kundenaufträge'); $form = new Form($db); $formfile = new FormFile($db); $formorder = new FormOrder($db); $formmargin = new FormMargin($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} // Mode creation -if ($action == 'create' && $usercancreate) -{ +if ($action == 'create' && $usercancreate) { print load_fiche_titre($langs->trans('CreateOrder'), '', 'order'); $soc = new Societe($db); - if ($socid > 0) + if ($socid > 0) { $res = $soc->fetch($socid); + } $remise_absolue = 0; @@ -1481,8 +1457,9 @@ if ($action == 'create' && $usercancreate) $classname = ucfirst($subelement); $objectsrc = new $classname($db); $objectsrc->fetch($originid); - if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) + if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) { $objectsrc->fetch_lines(); + } $objectsrc->fetch_thirdparty(); // Replicate extrafields @@ -1505,12 +1482,17 @@ if ($action == 'create' && $usercancreate) $dateorder = empty($conf->global->MAIN_AUTOFILL_DATE_ORDER) ?-1 : ''; $date_delivery = (!empty($objectsrc->delivery_date) ? $objectsrc->delivery_date : ''); - if (empty($date_delivery)) $date_delivery = (!empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : ''); + if (empty($date_delivery)) { + $date_delivery = (!empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : ''); + } - if (!empty($conf->multicurrency->enabled)) - { - if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code; - if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; + if (!empty($conf->multicurrency->enabled)) { + if (!empty($objectsrc->multicurrency_code)) { + $currency_code = $objectsrc->multicurrency_code; + } + if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) { + $currency_tx = $objectsrc->multicurrency_tx; + } } $note_private = $object->getDefaultCreateValueFor('note_private', (!empty($objectsrc->note_private) ? $objectsrc->note_private : null)); @@ -1531,18 +1513,25 @@ if ($action == 'create' && $usercancreate) $remise_absolue = 0; $dateorder = empty($conf->global->MAIN_AUTOFILL_DATE_ORDER) ?-1 : ''; - if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; + if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) { + $currency_code = $soc->multicurrency_code; + } $note_private = $object->getDefaultCreateValueFor('note_private'); $note_public = $object->getDefaultCreateValueFor('note_public'); } //Warehouse default if null - if ($soc->fk_warehouse > 0) $warehouse_id = $soc->fk_warehouse; - if (!empty($conf->stock->enabled) && empty($warehouse_id) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) - { - if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) $warehouse_id = $conf->global->MAIN_DEFAULT_WAREHOUSE; - if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) $warehouse_id = $user->fk_warehouse; + if ($soc->fk_warehouse > 0) { + $warehouse_id = $soc->fk_warehouse; + } + if (!empty($conf->stock->enabled) && empty($warehouse_id) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { + if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) { + $warehouse_id = $conf->global->MAIN_DEFAULT_WAREHOUSE; + } + if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) { + $warehouse_id = $user->fk_warehouse; + } } print ''; @@ -1552,7 +1541,9 @@ if ($action == 'create' && $usercancreate) print ''; print ''; print ''; - if (!empty($currency_tx)) print ''; + if (!empty($currency_tx)) { + print ''; + } print dol_get_fiche_head(''); @@ -1563,9 +1554,11 @@ if ($action == 'create' && $usercancreate) // Reference client print ''; - else print ''; + } else { + print ''; + } print ''; // Thirdparty @@ -1580,15 +1573,15 @@ if ($action == 'create' && $usercancreate) print ''; print '\n"; print ''; @@ -1682,8 +1675,7 @@ if ($action == 'create' && $usercancreate) // TODO How record was recorded OrderMode (llx_c_input_method) // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); print ''; print ''; print ''; print '"; // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; print ''; print ''; } - if (!empty($origin) && !empty($originid) && is_object($objectsrc)) - { + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) { // TODO for compatibility if ($origin == 'contrat') { // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva @@ -1811,20 +1799,17 @@ if ($action == 'create' && $usercancreate) // Amount print ''; print '"; - if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE - { + if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1 RE print '"; } - if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF - { + if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2 IRPF print '"; } print '"; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print ''; print '"; print '"; @@ -1882,8 +1867,7 @@ if ($action == 'create' && $usercancreate) } // Confirmation of validation - if ($action == 'validate') - { + if ($action == 'validate') { // We check that object has a temporary ref $ref = substr($object->ref, 1, 4); if ($ref == 'PROV') { @@ -1893,8 +1877,7 @@ if ($action == 'create' && $usercancreate) } $text = $langs->trans('ConfirmValidateOrder', $numref); - if (!empty($conf->notification->enabled)) - { + if (!empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; $notify = new Notify($db); $text .= '
    '; @@ -1902,21 +1885,21 @@ if ($action == 'create' && $usercancreate) } $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { - $qualified_for_stock_change = $object->hasProductsOrServices(1); + $qualified_for_stock_change = $object->hasProductsOrServices(1); } $formquestion = array(); - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { $langs->load("stocks"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( // 'text' => $langs->trans("ConfirmClone"), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -1929,25 +1912,24 @@ if ($action == 'create' && $usercancreate) } // Confirm back to draft status - if ($action == 'modif') - { + if ($action == 'modif') { $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { - $qualified_for_stock_change = $object->hasProductsOrServices(1); + $qualified_for_stock_change = $object->hasProductsOrServices(1); } $text = $langs->trans('ConfirmUnvalidateOrder', $object->ref); $formquestion = array(); - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { $langs->load("stocks"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( // 'text' => $langs->trans("ConfirmClone"), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -1969,25 +1951,24 @@ if ($action == 'create' && $usercancreate) /* * Confirmation de l'annulation */ - if ($action == 'cancel') - { + if ($action == 'cancel') { $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { - $qualified_for_stock_change = $object->hasProductsOrServices(1); + $qualified_for_stock_change = $object->hasProductsOrServices(1); } $text = $langs->trans('ConfirmCancelOrder', $object->ref); $formquestion = array(); - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { $langs->load("stocks"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( // 'text' => $langs->trans("ConfirmClone"), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -2000,8 +1981,7 @@ if ($action == 'create' && $usercancreate) } // Confirmation to delete line - if ($action == 'ask_deleteline') - { + if ($action == 'ask_deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1); } @@ -2018,8 +1998,11 @@ if ($action == 'create' && $usercancreate) $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); // Note that $action and $object may be modified by hook $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -2035,16 +2018,17 @@ if ($action == 'create' && $usercancreate) $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$soc->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherOrders").')'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' ('.$langs->trans("OtherOrders").')'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($usercancreate) - { - if ($action != 'classify') + if ($usercancreate) { + if ($action != 'classify') { $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= ''; @@ -2080,12 +2064,11 @@ if ($action == 'create' && $usercancreate) print '
    '.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("MulticurrencyAmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("MulticurrencyAmountTTC").''.$langs->trans("Author").'
    '.dol_print_date($db->jdate($obj->dc), 'dayhour').''; $facturefournstatic->id = $obj->fk_invoice_supplier_source; $facturefournstatic->ref = $obj->invoice_source_ref; $facturefournstatic->type = $obj->type; print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturefournstatic->getNomURl(1); print ''; $facturefournstatic->id = $obj->fk_invoice_supplier_source; $facturefournstatic->ref = $obj->invoice_source_ref; $facturefournstatic->type = $obj->type; print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturefournstatic->getNomURl(1); print ''; $facturefournstatic->id = $obj->fk_invoice_supplier_source; $facturefournstatic->ref = $obj->invoice_source_ref; @@ -1020,14 +961,12 @@ if ($socid > 0) } print ''.price($obj->amount_ht).''.price($obj->multicurrency_amount_ht).''.vatrate($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), true).''.price($obj->amount_ttc).''.price($obj->multicurrency_amount_ttc).''; @@ -1039,7 +978,9 @@ if ($socid > 0) } } else { $colspan = 8; - if (!empty($conf->multicurrency->enabled)) $colspan += 2; + if (!empty($conf->multicurrency->enabled)) { + $colspan += 2; + } print '
    '.$langs->trans("None").'
    '.$langs->trans('RefCustomer').''; - if (!empty($conf->global->MAIN_USE_PROPAL_REFCLIENT_FOR_ORDER) && !empty($origin) && !empty($originid)) + if (!empty($conf->global->MAIN_USE_PROPAL_REFCLIENT_FOR_ORDER) && !empty($origin) && !empty($originid)) { print '
    '; print img_picto('', 'company').$form->select_company('', 'socid', '(s.client = 1 OR s.client = 2 OR s.client = 3)', 'SelectThirdParty', 0, 0, null, 0, 'minwidth175 maxwidth500 widthcentpercentminusxx'); // reload page to retrieve customer informations - if (empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED)) - { + if (empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED)) { print ''; @@ -1628,7 +1621,7 @@ if ($action == 'create' && $usercancreate) print '
    '.$langs->trans("DateDeliveryPlanned").''; $date_delivery = ($date_delivery ? $date_delivery : $object->date_delivery); - print $form->selectDate($date_delivery ? $date_delivery : -1, 'date_delivery', 1, 1, 1); + print $form->selectDate($date_delivery ? $date_delivery : -1, 'liv_', 1, 1, 1); print "
    '.$langs->trans("Project").''; @@ -1695,15 +1687,13 @@ if ($action == 'create' && $usercancreate) } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '
    '; $incoterm_id = GETPOST('incoterm_id'); $incoterm_location = GETPOST('location_incoterms'); - if (empty($incoterm_id)) - { + if (empty($incoterm_id)) { $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); } @@ -1740,8 +1730,7 @@ if ($action == 'create' && $usercancreate) print "
    '.$form->editfieldkey("Currency", 'multicurrency_code', '', $object, 0).''; @@ -1771,8 +1760,7 @@ if ($action == 'create' && $usercancreate) print '
    '.$langs->trans('AmountHT').''.price($objectsrc->total_ht).'
    '.$langs->trans('AmountVAT').''.price($objectsrc->total_tva)."
    '.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($objectsrc->total_localtax1)."
    '.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($objectsrc->total_localtax2)."
    '.$langs->trans('AmountTTC').''.price($objectsrc->total_ttc)."
    '.$langs->trans('MulticurrencyAmountHT').''.price($objectsrc->multicurrency_total_ht).'
    '.$langs->trans('MulticurrencyAmountVAT').''.price($objectsrc->multicurrency_total_tva)."
    '.$langs->trans('MulticurrencyAmountTTC').''.price($objectsrc->multicurrency_total_ttc)."
    '; - if ($soc->outstanding_limit) - { + if ($soc->outstanding_limit) { // Outstanding Bill print ''; // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print ''; print ''; // Multicurrency rate - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { print ''; print ''; - print ''; } if ($totalVolume) { print ''; - print ''; } @@ -2324,9 +2305,8 @@ if ($action == 'create' && $usercancreate) $editenable = $usercancreate; print $form->editfieldkey("IncotermLabel", 'incoterm', '', $object, $editenable); print ''; - print ''; print ''; - if ($num) - { + if ($num) { $i = 0; - while ($i < $num && $i < $max) - { + while ($i < $num && $i < $max) { $obj = $db->fetch_object($resql); print ''; print '
    '; print $langs->trans('OutstandingBill'); - print ''; + print ''; $arrayoutstandingbills = $soc->getOutstandingBills(); print price($arrayoutstandingbills['opened']).' / '; print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency); @@ -2106,7 +2089,7 @@ if ($action == 'create' && $usercancreate) $addabsolutediscount = ''.$langs->trans("EditGlobalDiscounts").''; $addcreditnote = ''.$langs->trans("AddCreditNote").''; - print '
    '.$langs->trans('Discounts').''; + print '
    '.$langs->trans('Discounts').''; $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); @@ -2124,7 +2107,7 @@ if ($action == 'create' && $usercancreate) print '
    '; $editenable = $usercancreate && $object->statut == Commande::STATUS_DRAFT; print $form->editfieldkey("Date", 'date', '', $object, $editenable); - print ''; + print ''; if ($action == 'editdate') { print ''; print ''; @@ -2145,7 +2128,7 @@ if ($action == 'create' && $usercancreate) print '
    '; $editenable = $usercancreate; print $form->editfieldkey("DateDeliveryPlanned", 'date_livraison', '', $object, $editenable); - print ''; + print ''; if ($action == 'editdate_livraison') { print ''; print ''; @@ -2167,7 +2150,7 @@ if ($action == 'create' && $usercancreate) print '
    '; $editenable = $usercancreate; print $form->editfieldkey("SendingMethod", 'shippingmethod', '', $object, $editenable); - print ''; + print ''; if ($action == 'editshippingmethod') { $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); } else { @@ -2185,7 +2168,7 @@ if ($action == 'create' && $usercancreate) print '
    '; $editenable = $usercancreate; print $form->editfieldkey("Warehouse", 'warehouse', '', $object, $editenable); - print ''; + print ''; if ($action == 'editwarehouse') { $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1); } else { @@ -2199,7 +2182,7 @@ if ($action == 'create' && $usercancreate) print '
    '; $editenable = $usercancreate; print $form->editfieldkey("PaymentConditionsShort", 'conditions', '', $object, $editenable); - print ''; + print ''; if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id', 1); } else { @@ -2213,7 +2196,7 @@ if ($action == 'create' && $usercancreate) print '
    '; $editenable = $usercancreate; print $form->editfieldkey("PaymentMode", 'mode', '', $object, $editenable); - print ''; + print ''; if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1); } else { @@ -2222,14 +2205,13 @@ if ($action == 'create' && $usercancreate) print '
    '; $editenable = $usercancreate && $object->statut == Commande::STATUS_DRAFT; print $form->editfieldkey("Currency", 'multicurrencycode', '', $object, $editenable); - print ''; + print ''; if ($action == 'editmulticurrencycode') { $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code'); } else { @@ -2238,13 +2220,12 @@ if ($action == 'create' && $usercancreate) print '
    '; $editenable = $usercancreate && $object->multicurrency_code && $object->multicurrency_code != $conf->currency && $object->statut == $object::STATUS_DRAFT; print $form->editfieldkey("CurrencyRate", 'multicurrencyrate', '', $object, $editenable); - print ''; + print ''; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { if ($action == 'actualizemulticurrencyrate') { list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); @@ -2266,7 +2247,7 @@ if ($action == 'create' && $usercancreate) print '
    '; $editenable = $usercancreate; print $form->editfieldkey("AvailabilityPeriod", 'availability', '', $object, $editenable); - print ''; + print ''; if ($action == 'editavailability') { $form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'availability_id', 1); } else { @@ -2278,7 +2259,7 @@ if ($action == 'create' && $usercancreate) print '
    '; $editenable = $usercancreate; print $form->editfieldkey("Channel", 'demandreason', '', $object, $editenable); - print ''; + print ''; if ($action == 'editdemandreason') { $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'demand_reason_id', 1); } else { @@ -2305,13 +2286,13 @@ if ($action == 'create' && $usercancreate) $totalVolume = $tmparray['volume']; if ($totalWeight) { print '
    '.$langs->trans("CalculatedWeight").''; + print ''; print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND) ? $conf->global->MAIN_WEIGHT_DEFAULT_ROUND : -1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? $conf->global->MAIN_WEIGHT_DEFAULT_UNIT : 'no'); print '
    '.$langs->trans("CalculatedVolume").''; + print ''; print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND) ? $conf->global->MAIN_VOLUME_DEFAULT_ROUND : -1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT) ? $conf->global->MAIN_VOLUME_DEFAULT_UNIT : 'no'); print '
    '; - if ($action != 'editincoterm') - { + print ''; + if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1); } else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); @@ -2339,7 +2319,7 @@ if ($action == 'create' && $usercancreate) print '
    '; $editenable = $usercancreate; print $form->editfieldkey("BankAccount", 'bankaccount', '', $object, $editenable); - print ''; + print ''; if ($action == 'editbankaccount') { $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); } else { @@ -2361,21 +2341,20 @@ if ($action == 'create' && $usercancreate) print ''; - if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) - { + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { // Multicurrency Amount HT print ''; - print ''; + print ''; print ''; // Multicurrency Amount VAT print ''; - print ''; + print ''; print ''; // Multicurrency Amount TTC print ''; - print ''; + print ''; print ''; } @@ -2385,25 +2364,23 @@ if ($action == 'create' && $usercancreate) $alert = ' '.img_warning($langs->trans('OrderMinAmount').': '.price($object->thirdparty->order_min_amount)); } print ''; - print ''; + print ''; // Total VAT - print ''; + print ''; // Amount Local Taxes - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) // Localtax1 - { + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { // Localtax1 print ''; - print ''; + print ''; } - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) // Localtax2 IRPF - { + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { // Localtax2 IRPF print ''; - print ''; + print ''; } // Total TTC - print ''; + print ''; // Statut //print ''; @@ -2453,18 +2430,17 @@ if ($action == 'create' && $usercancreate) 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)).''.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'
    '.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).''.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).''.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'
    '.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).''.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).''.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'
    '.$langs->trans('AmountHT').''.price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency).$alert.''.price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency).$alert.'
    '.$langs->trans('AmountVAT').''.price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency).'
    '.$langs->trans('AmountVAT').''.price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency).'
    '.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency).'
    '.price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency).'
    '.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'
    '.price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'
    '.$langs->trans('AmountTTC').''.price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency).'
    '.$langs->trans('AmountTTC').''.price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency).'
    ' . $langs->trans('Status') . '' . $object->getLibStatut(4) . '
    '; // Show object lines - if (!empty($object->lines)) + if (!empty($object->lines)) { $ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 1); + } $numlines = count($object->lines); /* * Form to add new line */ - if ($object->statut == Commande::STATUS_DRAFT && $usercancreate && $action != 'selectlines') - { - if ($action != 'editline') - { + if ($object->statut == Commande::STATUS_DRAFT && $usercancreate && $action != 'selectlines') { + if ($action != 'editline') { // Add free products/services $object->formAddObjectLine(1, $mysoc, $soc); @@ -2500,13 +2476,14 @@ if ($action == 'create' && $usercancreate) if ($object->statut > Commande::STATUS_DRAFT || !empty($conf->global->COMMANDE_SENDBYEMAIL_FOR_ALL_STATUS)) { if ($usercansend) { print ''.$langs->trans('SendMail').''; - } else print ''.$langs->trans('SendMail').''; + } else { + print ''.$langs->trans('SendMail').''; + } } } // Valid - if ($object->statut == Commande::STATUS_DRAFT && ($object->total_ttc >= 0 || !empty($conf->global->ORDER_ENABLE_NEGATIVE)) && $numlines > 0 && $usercanvalidate) - { + if ($object->statut == Commande::STATUS_DRAFT && ($object->total_ttc >= 0 || !empty($conf->global->ORDER_ENABLE_NEGATIVE)) && $numlines > 0 && $usercanvalidate) { print ''.$langs->trans('Validate').''; } // Edit @@ -2523,8 +2500,7 @@ if ($action == 'create' && $usercancreate) }*/ // Create a purchase order - if (!empty($conf->global->WORKFLOW_CAN_CREATE_PURCHASE_ORDER_FROM_SALE_ORDER)) - { + if (!empty($conf->global->WORKFLOW_CAN_CREATE_PURCHASE_ORDER_FROM_SALE_ORDER)) { if (!empty($conf->fournisseur->enabled) && $object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED && $object->getNbOfServicesLines() > 0) { if ($usercancreatepurchaseorder) { print ''.$langs->trans("AddPurchaseOrder").''; @@ -2598,8 +2574,7 @@ if ($action == 'create' && $usercancreate) } // Cancel order - if ($object->statut == Commande::STATUS_VALIDATED && (!empty($usercanclose) || !empty($usercancancel))) - { + if ($object->statut == Commande::STATUS_VALIDATED && (!empty($usercanclose) || !empty($usercancancel))) { print ''; } @@ -2620,8 +2595,7 @@ if ($action == 'create' && $usercancreate) $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '
    '; print ''; // ancre // Documents @@ -2639,25 +2613,24 @@ if ($action == 'create' && $usercancreate) $compatibleImportElementsList = false; if ($usercancreate - && $object->statut == Commande::STATUS_DRAFT) - { + && $object->statut == Commande::STATUS_DRAFT) { $compatibleImportElementsList = array('commande', 'propal'); // import from linked elements } $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList); // Show online payment link $useonlinepayment = (!empty($conf->paypal->enabled) || !empty($conf->stripe->enabled) || !empty($conf->paybox->enabled)); - if (!empty($conf->global->ORDER_HIDE_ONLINE_PAYMENT_ON_ORDER)) $useonlinepayment = 0; - if ($object->statut != Commande::STATUS_DRAFT && $useonlinepayment) - { + if (!empty($conf->global->ORDER_HIDE_ONLINE_PAYMENT_ON_ORDER)) { + $useonlinepayment = 0; + } + if ($object->statut != Commande::STATUS_DRAFT && $useonlinepayment) { print '
    '; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; print showOnlinePaymentUrl('order', $object->ref).'
    '; } // Show direct download link - if ($object->statut != Commande::STATUS_DRAFT && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) - { + if ($object->statut != Commande::STATUS_DRAFT && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) { print '
    '."\n"; print showDirectDownloadLink($object).'
    '; } diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php index 71a26eea698..768e6a78c70 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -165,28 +165,37 @@ class Orders extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."commande as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= ' WHERE t.entity IN ('.getEntity('commande').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -195,8 +204,7 @@ class Orders extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -207,13 +215,11 @@ class Orders extends DolibarrApi dol_syslog("API Rest request"); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $commande_static = new Commande($this->db); if ($commande_static->fetch($obj->rowid)) { @@ -252,12 +258,12 @@ class Orders extends DolibarrApi $this->commande->$field = $value; } /*if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->commande->lines = $lines; - }*/ + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->commande->lines = $lines; + }*/ if ($this->commande->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating order", array_merge(array($this->commande->error), $this->commande->errors)); @@ -323,33 +329,33 @@ class Orders extends DolibarrApi } $request_data = (object) $request_data; $updateRes = $this->commande->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - $request_data->info_bits, - $request_data->fk_remise_except, - 'HT', - 0, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $request_data->fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->array_options, - $request_data->fk_unit, - $request_data->origin, - $request_data->origin_id, - $request_data->multicurrency_subprice, - $request_data->ref_ext + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + $request_data->info_bits, + $request_data->fk_remise_except, + 'HT', + 0, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $request_data->fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->array_options, + $request_data->fk_unit, + $request_data->origin, + $request_data->origin_id, + $request_data->multicurrency_subprice, + $request_data->ref_ext ); if ($updateRes > 0) { @@ -407,9 +413,9 @@ class Orders extends DolibarrApi $request_data->special_code, $request_data->array_options, $request_data->fk_unit, - $request_data->multicurrency_subprice, + $request_data->multicurrency_subprice, 0, - $request_data->ref_ext + $request_data->ref_ext ); if ($updateRes > 0) { @@ -613,18 +619,20 @@ class Orders extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->commande->$field = $value; } // Update availability if (!empty($this->commande->availability_id)) { - if ($this->commande->availability($this->commande->availability_id) < 0) - throw new RestException(400, 'Error while updating availability'); + if ($this->commande->availability($this->commande->availability_id) < 0) { + throw new RestException(400, 'Error while updating availability'); + } } - if ($this->commande->update(DolibarrApiAccess::$user) > 0) - { + if ($this->commande->update(DolibarrApiAccess::$user) > 0) { return $this->get($id); } else { throw new RestException(500, $this->commande->error); @@ -979,8 +987,9 @@ class Orders extends DolibarrApi { $commande = array(); foreach (Orders::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, $field." field missing"); + } $commande[$field] = $data[$field]; } return $commande; diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 4c2f643df1c..b29b594f8f2 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -313,7 +313,7 @@ class Commande extends CommonOrder 'remise_percent' =>array('type'=>'double', 'label'=>'RelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>110), 'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>115), //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>120), - 'tva' =>array('type'=>'double(24,8)', 'label'=>'VAT', 'enabled'=>1, 'visible'=>-1, 'position'=>125, 'isameasure'=>1), + 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'VAT', 'enabled'=>1, 'visible'=>-1, 'position'=>125, 'isameasure'=>1), 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'LocalTax1', 'enabled'=>1, 'visible'=>-1, 'position'=>130, 'isameasure'=>1), 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'LocalTax2', 'enabled'=>1, 'visible'=>-1, 'position'=>135, 'isameasure'=>1), 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>140, 'isameasure'=>1), @@ -403,8 +403,7 @@ class Commande extends CommonOrder global $langs, $conf; $langs->load("order"); - if (!empty($conf->global->COMMANDE_ADDON)) - { + if (!empty($conf->global->COMMANDE_ADDON)) { $mybool = false; $file = $conf->global->COMMANDE_ADDON.".php"; @@ -412,16 +411,14 @@ class Commande extends CommonOrder // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/commande/"); // Load file with numbering class (if found) $mybool |= @include_once $dir.$file; } - if ($mybool === false) - { + if ($mybool === false) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -429,8 +426,7 @@ class Commande extends CommonOrder $obj = new $classname(); $numref = $obj->getNextValue($soc, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -461,15 +457,13 @@ class Commande extends CommonOrder $error = 0; // Protection - if ($this->statut == self::STATUS_VALIDATED) - { + if ($this->statut == self::STATUS_VALIDATED) { dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); return 0; } if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->validate)))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->validate)))) { $this->error = 'NotEnoughPermissions'; dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); return -1; @@ -487,8 +481,7 @@ class Commande extends CommonOrder $result = $soc->set_as_client(); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($soc); } else { $num = $this->ref; @@ -505,8 +498,7 @@ class Commande extends CommonOrder dol_syslog(get_class($this)."::valid", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $this->error = $this->db->lasterror(); $error++; @@ -531,7 +523,9 @@ class Commande extends CommonOrder $this->error = $mouvP->error; } } - if ($error) break; + if ($error) { + break; + } } } } @@ -539,7 +533,9 @@ class Commande extends CommonOrder if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('ORDER_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -547,30 +543,28 @@ class Commande extends CommonOrder $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'commande/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'commande/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->commande->multidir_output[$this->entity].'/'.$oldref; $dirdest = $conf->commande->multidir_output[$this->entity].'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->commande->multidir_output[$this->entity].'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -583,15 +577,13 @@ class Commande extends CommonOrder } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $num; $this->statut = self::STATUS_VALIDATED; $this->brouillon = 0; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -616,14 +608,12 @@ class Commande extends CommonOrder $error = 0; // Protection - if ($this->statut <= self::STATUS_DRAFT) - { + if ($this->statut <= self::STATUS_DRAFT) { return 0; } if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->validate)))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->validate)))) { $this->error = 'Permission denied'; return -1; } @@ -636,31 +626,28 @@ class Commande extends CommonOrder $sql .= " SET fk_statut = ".self::STATUS_DRAFT; $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { - if (!$error) - { + if ($this->db->query($sql)) { + if (!$error) { $this->oldcopy = clone $this; } // If stock is decremented on validate order, we must reincrement it - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) { $result = 0; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); $num = count($this->lines); - for ($i = 0; $i < $num; $i++) - { - if ($this->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $num; $i++) { + if ($this->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We increment stock of product (and sub-products) $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderBackToDraftInDolibarr", $this->ref)); - if ($result < 0) { $error++; $this->error = $mouvP->error; break; } + if ($result < 0) { + $error++; $this->error = $mouvP->error; break; + } } } } @@ -668,7 +655,9 @@ class Commande extends CommonOrder if (!$error) { // Call trigger $result = $this->call_trigger('ORDER_UNVALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } if (!$error) { @@ -700,8 +689,7 @@ class Commande extends CommonOrder // phpcs:enable $error = 0; - if ($this->statut != self::STATUS_CANCELED && $this->statut != self::STATUS_CLOSED) - { + if ($this->statut != self::STATUS_CANCELED && $this->statut != self::STATUS_CLOSED) { dol_syslog(get_class($this)."::set_reopen order has not status closed", LOG_WARNING); return 0; } @@ -714,11 +702,12 @@ class Commande extends CommonOrder dol_syslog(get_class($this)."::set_reopen", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger $result = $this->call_trigger('ORDER_REOPEN', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } else { $error++; @@ -726,16 +715,14 @@ class Commande extends CommonOrder dol_print_error($this->db); } - if (!$error) - { + if (!$error) { $this->statut = self::STATUS_VALIDATED; $this->billed = 0; $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::set_reopen ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -760,10 +747,8 @@ class Commande extends CommonOrder $usercanclose = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->creer)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->close))); - if ($usercanclose) - { - if ($this->statut == self::STATUS_CLOSED) - { + if ($usercanclose) { + if ($this->statut == self::STATUS_CLOSED) { return 0; } $this->db->begin(); @@ -776,18 +761,17 @@ class Commande extends CommonOrder $sql .= " date_cloture = '".$this->db->idate($now)."'"; $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; - if ($this->db->query($sql)) - { - if (!$notrigger) - { + if ($this->db->query($sql)) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('ORDER_CLOSE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->statut = self::STATUS_CLOSED; $this->db->commit(); @@ -827,24 +811,19 @@ class Commande extends CommonOrder $sql .= " AND fk_statut = ".self::STATUS_VALIDATED; dol_syslog(get_class($this)."::cancel", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { // If stock is decremented on validate order, we must reincrement it - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); $num = count($this->lines); - for ($i = 0; $i < $num; $i++) - { - if ($this->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $num; $i++) { + if ($this->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($this->db); // We increment stock of product (and sub-products) $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderCanceledInDolibarr", $this->ref)); // price is 0, we don't want WAP to be changed - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $mouvP->error; break; @@ -853,22 +832,21 @@ class Commande extends CommonOrder } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('ORDER_CANCEL', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->statut = self::STATUS_CANCELED; $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -903,10 +881,12 @@ class Commande extends CommonOrder $delivery_date = empty($this->delivery_date) ? $this->date_livraison : $this->delivery_date; // 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)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date); - else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); - if (empty($this->fk_multicurrency)) - { + if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) { + list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date); + } else { + $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); + } + if (empty($this->fk_multicurrency)) { $this->multicurrency_code = $conf->currency; $this->fk_multicurrency = 0; $this->multicurrency_tx = 1; @@ -915,11 +895,9 @@ class Commande extends CommonOrder dol_syslog(get_class($this)."::create user=".$user->id); // Check parameters - if (!empty($this->ref)) // We check that ref is not already used - { + if (!empty($this->ref)) { // We check that ref is not already used $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used - if ($result > 0) - { + if ($result > 0) { $this->error = 'ErrorRefAlreadyExists'; dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); $this->db->rollback(); @@ -929,14 +907,12 @@ class Commande extends CommonOrder $soc = new Societe($this->db); $result = $soc->fetch($this->socid); - if ($result < 0) - { + if ($result < 0) { $this->error = "Failed to fetch company"; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -2; } - if (!empty($conf->global->ORDER_REQUIRE_SOURCE) && $this->source < 0) - { + if (!empty($conf->global->ORDER_REQUIRE_SOURCE) && $this->source < 0) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Source")); dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -1; @@ -991,25 +967,24 @@ class Commande extends CommonOrder dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'commande'); - if ($this->id) - { + if ($this->id) { $fk_parent_line = 0; $num = count($this->lines); /* * Insert products details into db */ - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $line = $this->lines[$i]; // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. - if (!is_object($line)) $line = (object) $line; + if (!is_object($line)) { + $line = (object) $line; + } // Reset fk_parent_line for no child products and special product if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { @@ -1018,7 +993,9 @@ class Commande extends CommonOrder // Complete vat rate with code $vatrate = $line->tva_tx; - if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) $vatrate .= ' ('.$line->vat_src_code.')'; + if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) { + $vatrate .= ' ('.$line->vat_src_code.')'; + } if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) { $originid = $line->origin_id; @@ -1062,10 +1039,8 @@ class Commande extends CommonOrder 0, $line->ref_ext ); - if ($result < 0) - { - if ($result != self::STOCK_NOT_ENOUGH_FOR_ORDER) - { + if ($result < 0) { + if ($result != self::STOCK_NOT_ENOUGH_FOR_ORDER) { $this->error = $this->db->lasterror(); $this->errors[] = $this->error; dol_print_error($this->db); @@ -1081,30 +1056,25 @@ class Commande extends CommonOrder // update ref $initialref = '(PROV'.$this->id.')'; - if (!empty($this->ref)) $initialref = $this->ref; + if (!empty($this->ref)) { + $initialref = $this->ref; + } - $sql = 'UPDATE '.MAIN_DB_PREFIX."commande SET ref='".$this->db->escape($initialref)."' WHERE rowid=".$this->id; - if ($this->db->query($sql)) - { + $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; - if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects - { + if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) - { - foreach ($this->linked_objects as $origin => $tmp_origin_id) - { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { + if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) { + foreach ($this->linked_objects as $origin => $tmp_origin_id) { + if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { $this->error = $this->db->lasterror(); $error++; } @@ -1113,8 +1083,7 @@ class Commande extends CommonOrder { $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { $this->error = $this->db->lasterror(); $error++; } @@ -1122,23 +1091,22 @@ class Commande extends CommonOrder } } - if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) // Get contact from origin object - { + if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object $originforcontact = $this->origin; $originidforcontact = $this->origin_id; - if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order - { + if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; $exp = new Expedition($this->db); $exp->fetch($this->origin_id); $exp->fetchObjectLinked(); - if (count($exp->linkedObjectsIds['commande']) > 0) - { - foreach ($exp->linkedObjectsIds['commande'] as $key => $value) - { + if (count($exp->linkedObjectsIds['commande']) > 0) { + foreach ($exp->linkedObjectsIds['commande'] as $key => $value) { $originforcontact = 'commande'; - if (is_object($value)) $originidforcontact = $value->id; - else $originidforcontact = $value; + if (is_object($value)) { + $originidforcontact = $value->id; + } else { + $originidforcontact = $value; + } break; // We take first one } } @@ -1148,32 +1116,33 @@ class Commande extends CommonOrder $sqlcontact .= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'"; $resqlcontact = $this->db->query($sqlcontact); - if ($resqlcontact) - { - while ($objcontact = $this->db->fetch_object($resqlcontact)) - { + if ($resqlcontact) { + while ($objcontact = $this->db->fetch_object($resqlcontact)) { //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n"; $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object } - } else dol_print_error($resqlcontact); + } else { + dol_print_error($resqlcontact); + } } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('ORDER_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -1210,19 +1179,18 @@ class Commande extends CommonOrder $this->db->begin(); // get lines so they will be clone - foreach ($this->lines as $line) + foreach ($this->lines as $line) { $line->fetch_optionals(); + } // Load source object $objFrom = clone $this; // Change socid if needed - if (!empty($socid) && $socid != $this->socid) - { + if (!empty($socid) && $socid != $this->socid) { $objsoc = new Societe($this->db); - if ($objsoc->fetch($socid) > 0) - { + if ($objsoc->fetch($socid) > 0) { $this->socid = $objsoc->id; $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); @@ -1244,56 +1212,55 @@ class Commande extends CommonOrder $this->date_commande = dol_now(); $this->date_creation = ''; $this->date_validation = ''; - if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $this->ref_client = ''; + if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) { + $this->ref_client = ''; + } // Do not clone ref_ext $num = count($this->lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $this->lines[$i]->ref_ext = ''; } // Create clone $this->context['createfromclone'] = 'createfromclone'; $result = $this->create($user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // copy internal contacts - if ($this->copy_linked_contact($objFrom, 'internal') < 0) - { + if ($this->copy_linked_contact($objFrom, 'internal') < 0) { $error++; } } - if (!$error) - { + if (!$error) { // copy external contacts if same company - if ($this->socid == $objFrom->socid) - { - if ($this->copy_linked_contact($objFrom, 'external') < 0) + if ($this->socid == $objFrom->socid) { + if ($this->copy_linked_contact($objFrom, 'external') < 0) { $error++; + } } } - if (!$error) - { + if (!$error) { // Hook of thirdparty module - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('objFrom'=>$objFrom); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } } } unset($this->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -1323,8 +1290,7 @@ class Commande extends CommonOrder $this->source = 0; $num = count($object->lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $line = new OrderLine($this->db); $line->libelle = $object->lines[$i]->libelle; @@ -1358,8 +1324,9 @@ class Commande extends CommonOrder // get extrafields from original line $object->lines[$i]->fetch_optionals(); - foreach ($object->lines[$i]->array_options as $options_key => $value) + foreach ($object->lines[$i]->array_options as $options_key => $value) { $line->array_options[$options_key] = $value; + } $this->lines[$i] = $line; } @@ -1380,8 +1347,7 @@ class Commande extends CommonOrder $this->contact_id = $object->contact_id; $this->ref_client = $object->ref_client; - if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) - { + if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) { $this->note_private = $object->note_private; $this->note_public = $object->note_public; } @@ -1402,34 +1368,36 @@ class Commande extends CommonOrder } // Possibility to add external linked objects with hooks $this->linked_objects[$this->origin] = $this->origin_id; - if (is_array($object->other_linked_objects) && !empty($object->other_linked_objects)) - { + if (is_array($object->other_linked_objects) && !empty($object->other_linked_objects)) { $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects); } $ret = $this->create($user); - if ($ret > 0) - { + if ($ret > 0) { // Actions hooked (by external module) $hookmanager->initHooks(array('orderdao')); $parameters = array('objFrom'=>$object); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Validate immediatly the order - if (!empty($conf->global->ORDER_VALID_AFTER_CLOSE_PROPAL)) - { + if (!empty($conf->global->ORDER_VALID_AFTER_CLOSE_PROPAL)) { $this->fetch($ret); $this->valid($user); } return $ret; - } else return -1; - } else return -1; + } else { + return -1; + } + } else { + return -1; + } } @@ -1481,22 +1449,41 @@ class Commande extends CommonOrder $logtext .= ", date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise, ref_ext=$ref_ext"; dol_syslog(get_class($this).$logtext, LOG_DEBUG); - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - if (empty($remise_percent)) $remise_percent = 0; - if (empty($qty)) $qty = 0; - if (empty($info_bits)) $info_bits = 0; - if (empty($rang)) $rang = 0; - if (empty($txtva)) $txtva = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; - if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0; - if (empty($this->fk_multicurrency)) $this->fk_multicurrency = 0; - if (empty($ref_ext)) $ref_ext = ''; + if (empty($remise_percent)) { + $remise_percent = 0; + } + if (empty($qty)) { + $qty = 0; + } + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($rang)) { + $rang = 0; + } + if (empty($txtva)) { + $txtva = 0; + } + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } + if (empty($fk_parent_line) || $fk_parent_line < 0) { + $fk_parent_line = 0; + } + if (empty($this->fk_multicurrency)) { + $this->fk_multicurrency = 0; + } + if (empty($ref_ext)) { + $ref_ext = ''; + } $remise_percent = price2num($remise_percent); $qty = price2num($qty); @@ -1509,8 +1496,7 @@ class Commande extends CommonOrder } $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); - if ($price_base_type == 'HT') - { + if ($price_base_type == 'HT') { $pu = $pu_ht; } else { $pu = $pu_ttc; @@ -1519,7 +1505,9 @@ class Commande extends CommonOrder $desc = trim($desc); // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); @@ -1530,14 +1518,12 @@ class Commande extends CommonOrder $this->db->begin(); $product_type = $type; - if (!empty($fk_product)) - { + if (!empty($fk_product)) { $product = new Product($this->db); $result = $product->fetch($fk_product); $product_type = $product->type; - if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty) - { + if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty) { $langs->load("errors"); $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref); $this->errors[] = $this->error; @@ -1556,8 +1542,7 @@ class Commande extends CommonOrder // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -1587,8 +1572,7 @@ class Commande extends CommonOrder // Rang to use $ranktouse = $rang; - if ($ranktouse == -1) - { + if ($ranktouse == -1) { $rangmax = $this->line_max($fk_parent_line); $ranktouse = $rangmax + 1; } @@ -1597,8 +1581,7 @@ class Commande extends CommonOrder // Anciens indicateurs: $price, $remise (a ne plus utiliser) $price = $pu; $remise = 0; - if ($remise_percent > 0) - { + if ($remise_percent > 0) { $remise = round(($pu * $remise_percent / 100), 2); $price = $pu - $remise; } @@ -1661,15 +1644,15 @@ class Commande extends CommonOrder } $result = $this->line->insert($user); - if ($result > 0) - { + if ($result > 0) { // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) { + $this->line_order(true, 'DESC'); + } // Mise a jour informations denormalisees au niveau de la commande meme $result = $this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return $this->line->id; } else { @@ -1708,16 +1691,19 @@ class Commande extends CommonOrder // phpcs:enable global $conf, $mysoc; - if (!$qty) $qty = 1; + if (!$qty) { + $qty = 1; + } - if ($idproduct > 0) - { + if ($idproduct > 0) { $prod = new Product($this->db); $prod->fetch($idproduct); $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id); $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $vat_src_code = ''; // May be defined into tva_tx $localtax1_tx = get_localtax($tva_tx, 1, $this->thirdparty, $mysoc, $tva_npr); @@ -1749,8 +1735,12 @@ class Commande extends CommonOrder $line->fk_unit = $prod->fk_unit; // Save the start and end date of the line in the object - if ($date_start) { $line->date_start = $date_start; } - if ($date_end) { $line->date_end = $date_end; } + if ($date_start) { + $line->date_start = $date_start; + } + if ($date_end) { + $line->date_end = $date_end; + } $this->lines[] = $line; @@ -1767,7 +1757,7 @@ class Commande extends CommonOrder { // print "id : ".$value[1].' :qty: '.$value[0].'
    '; if not in lines { - $this->add_product($value[1], $value[0]); + $this->add_product($value[1], $value[0]); } } } @@ -1788,10 +1778,12 @@ class Commande extends CommonOrder public function fetch($id, $ref = '', $ref_ext = '', $notused = '') { // Check parameters - if (empty($id) && empty($ref) && empty($ref_ext)) return -1; + if (empty($id) && empty($ref) && empty($ref_ext)) { + return -1; + } $sql = 'SELECT c.rowid, c.entity, c.date_creation, c.ref, c.fk_soc, c.fk_user_author, c.fk_user_valid, c.fk_statut'; - $sql .= ', c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason'; + $sql .= ', c.amount_ht, c.total_ht, c.total_ttc, c.total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason'; $sql .= ', c.fk_account'; $sql .= ', c.date_commande, c.date_valid, c.tms'; $sql .= ', c.date_livraison as delivery_date'; @@ -1814,20 +1806,27 @@ class Commande extends CommonOrder $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = dr.rowid'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid'; - if ($id) $sql .= " WHERE c.rowid=".$id; - else $sql .= " WHERE c.entity IN (".getEntity('commande').")"; // Dont't use entity if you use rowid + if ($id) { + $sql .= " WHERE c.rowid=".$id; + } else { + $sql .= " WHERE c.entity IN (".getEntity('commande').")"; // Dont't use entity if you use rowid + } - if ($ref) $sql .= " AND c.ref='".$this->db->escape($ref)."'"; - if ($ref_ext) $sql .= " AND c.ref_ext='".$this->db->escape($ref_ext)."'"; - if ($notused) $sql .= " AND c.ref_int='".$this->db->escape($notused)."'"; + if ($ref) { + $sql .= " AND c.ref='".$this->db->escape($ref)."'"; + } + if ($ref_ext) { + $sql .= " AND c.ref_ext='".$this->db->escape($ref_ext)."'"; + } + if ($notused) { + $sql .= " AND c.ref_int='".$this->db->escape($notused)."'"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $obj = $this->db->fetch_object($result); - if ($obj) - { + if ($obj) { $this->id = $obj->rowid; $this->entity = $obj->entity; @@ -1907,7 +1906,9 @@ class Commande extends CommonOrder $this->lines = array(); - if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; + if ($this->statut == self::STATUS_DRAFT) { + $this->brouillon = 1; + } // Retrieve all extrafield // fetch optionals attributes and labels @@ -1917,8 +1918,7 @@ class Commande extends CommonOrder // Lines $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { return -3; } return 1; @@ -1953,10 +1953,8 @@ class Commande extends CommonOrder $remise = new DiscountAbsolute($this->db); $result = $remise->fetch($idremise); - if ($result > 0) - { - if ($remise->fk_facture) // Protection against multiple submission - { + if ($result > 0) { + if ($remise->fk_facture) { // Protection against multiple submission $this->error = $langs->trans("ErrorDiscountAlreadyUsed"); $this->db->rollback(); return -5; @@ -1983,11 +1981,9 @@ class Commande extends CommonOrder $line->total_ttc = -$remise->amount_ttc; $result = $line->insert(); - if ($result > 0) - { + if ($result > 0) { $result = $this->update_price(1); - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return 1; } else { @@ -2031,18 +2027,18 @@ class Commande extends CommonOrder $sql .= ' FROM '.MAIN_DB_PREFIX.'commandedet as l'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)'; $sql .= ' WHERE l.fk_commande = '.$this->id; - if ($only_product) $sql .= ' AND p.fk_product_type = 0'; + if ($only_product) { + $sql .= ' AND p.fk_product_type = 0'; + } $sql .= ' ORDER BY l.rang, l.rowid'; dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($result); $line = new OrderLine($this->db); @@ -2146,9 +2142,10 @@ class Commande extends CommonOrder public function getNbOfProductsLines() { $nb = 0; - foreach ($this->lines as $line) - { - if ($line->product_type == 0) $nb++; + foreach ($this->lines as $line) { + if ($line->product_type == 0) { + $nb++; + } } return $nb; } @@ -2161,9 +2158,10 @@ class Commande extends CommonOrder public function getNbOfServicesLines() { $nb = 0; - foreach ($this->lines as $line) - { - if ($line->product_type == 1) $nb++; + foreach ($this->lines as $line) { + if ($line->product_type == 1) { + $nb++; + } } return $nb; } @@ -2187,10 +2185,11 @@ class Commande extends CommonOrder dol_syslog(get_class($this)."::getNbOfShipments", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) $nb = $obj->nb; + if ($obj) { + $nb = $obj->nb; + } $this->db->free($resql); return $nb; @@ -2214,25 +2213,31 @@ class Commande extends CommonOrder $sql = 'SELECT cd.rowid, cd.fk_product,'; $sql .= ' sum(ed.qty) as qty'; $sql .= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,'; - if ($filtre_statut >= 0) $sql .= ' '.MAIN_DB_PREFIX.'expedition as e,'; + if ($filtre_statut >= 0) { + $sql .= ' '.MAIN_DB_PREFIX.'expedition as e,'; + } $sql .= ' '.MAIN_DB_PREFIX.'commandedet as cd'; $sql .= ' WHERE'; - if ($filtre_statut >= 0) $sql .= ' ed.fk_expedition = e.rowid AND'; + if ($filtre_statut >= 0) { + $sql .= ' ed.fk_expedition = e.rowid AND'; + } $sql .= ' ed.fk_origin_line = cd.rowid'; $sql .= ' AND cd.fk_commande ='.$this->id; - if ($this->fk_product > 0) $sql .= ' AND cd.fk_product = '.$this->fk_product; - if ($filtre_statut >= 0) $sql .= ' AND e.fk_statut >= '.$filtre_statut; + if ($this->fk_product > 0) { + $sql .= ' AND cd.fk_product = '.$this->fk_product; + } + if ($filtre_statut >= 0) { + $sql .= ' AND e.fk_statut >= '.$filtre_statut; + } $sql .= ' GROUP BY cd.rowid, cd.fk_product'; //print $sql; dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $this->expeditions[$obj->rowid] = $obj->qty; $i++; @@ -2260,15 +2265,17 @@ class Commande extends CommonOrder $sql .= ' FROM '.MAIN_DB_PREFIX.'expedition as e'; $sql .= ', '.MAIN_DB_PREFIX.'element_element as el'; $sql .= ' WHERE el.fk_source = '.$this->id; + $sql .= " AND el.sourcetype = 'commande'"; $sql .= " AND el.fk_target = e.rowid"; $sql .= " AND el.targettype = 'shipping'"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $row = $this->db->fetch_row($resql); return $row[0]; - } else dol_print_error($this->db); + } else { + dol_print_error($this->db); + } } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -2290,19 +2297,16 @@ class Commande extends CommonOrder // Recherche total en stock pour chaque produit // TODO $array_of_product est défini vide juste au dessus !! - if (count($array_of_product)) - { + if (count($array_of_product)) { $sql = "SELECT fk_product, sum(ps.reel) as total"; $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; $sql .= " WHERE ps.fk_product IN (".join(',', $array_of_product).")"; $sql .= ' GROUP BY fk_product '; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $this->stocks[$obj->fk_product] = $obj->total; $i++; @@ -2322,8 +2326,7 @@ class Commande extends CommonOrder */ public function deleteline($user = null, $lineid = 0) { - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { $this->db->begin(); $sql = "SELECT fk_product, qty"; @@ -2331,12 +2334,10 @@ class Commande extends CommonOrder $sql .= " WHERE rowid = ".$lineid; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $obj = $this->db->fetch_object($result); - if ($obj) - { + if ($obj) { $product = new Product($this->db); $product->id = $obj->fk_product; @@ -2346,12 +2347,10 @@ class Commande extends CommonOrder // For triggers $line->fetch($lineid); - if ($line->delete($user) > 0) - { + if ($line->delete($user) > 0) { $result = $this->update_price(1); - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return 1; } else { @@ -2409,8 +2408,7 @@ class Commande extends CommonOrder { $remise = trim($remise) ?trim($remise) : 0; - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { $error = 0; $this->db->begin(); @@ -2423,34 +2421,31 @@ class Commande extends CommonOrder dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->remise_percent = $remise; $this->update_price(1); } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('ORDER_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2475,8 +2470,7 @@ class Commande extends CommonOrder // phpcs:enable $remise = trim($remise) ?trim($remise) : 0; - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { $error = 0; $this->db->begin(); @@ -2489,34 +2483,31 @@ class Commande extends CommonOrder dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->remise_absolue = $remise; $this->update_price(1); } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('ORDER_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2539,8 +2530,7 @@ class Commande extends CommonOrder public function set_date($user, $date, $notrigger = 0) { // phpcs:enable - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { $error = 0; $this->db->begin(); @@ -2551,33 +2541,30 @@ class Commande extends CommonOrder dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->date = $date; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('ORDER_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2615,8 +2602,7 @@ class Commande extends CommonOrder */ public function setDeliveryDate($user, $delivery_date, $notrigger = 0) { - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { $error = 0; $this->db->begin(); @@ -2627,34 +2613,31 @@ class Commande extends CommonOrder dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->date_livraison = $delivery_date; $this->delivery_date = $delivery_date; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('ORDER_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2689,37 +2672,41 @@ class Commande extends CommonOrder $sql = "SELECT s.rowid, s.nom as name, s.client,"; $sql .= " c.rowid as cid, c.ref"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user"; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.entity IN (".getEntity('commande').")"; $sql .= " AND c.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$socid) //restriction - { + if (!$user->rights->societe->client->voir && !$socid) { //restriction $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } - if ($socid) $sql .= " AND s.rowid = ".$socid; - if ($draft) $sql .= " AND c.fk_statut = ".self::STATUS_DRAFT; - if (is_object($excluser)) $sql .= " AND c.fk_user_author <> ".$excluser->id; + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } + if ($draft) { + $sql .= " AND c.fk_statut = ".self::STATUS_DRAFT; + } + if (is_object($excluser)) { + $sql .= " AND c.fk_user_author <> ".$excluser->id; + } $sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->plimit($limit, $offset); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $numc = $this->db->num_rows($result); - if ($numc) - { + if ($numc) { $i = 0; - while ($i < $numc) - { + while ($i < $numc) { $obj = $this->db->fetch_object($result); - if ($shortlist == 1) - { + if ($shortlist == 1) { $ga[$obj->cid] = $obj->ref; - } elseif ($shortlist == 2) - { + } elseif ($shortlist == 2) { $ga[$obj->cid] = $obj->ref.' ('.$obj->name.')'; } else { $ga[$i]['id'] = $obj->cid; @@ -2748,45 +2735,41 @@ class Commande extends CommonOrder global $user; dol_syslog('Commande::availability('.$availability_id.')'); - if ($this->statut >= self::STATUS_DRAFT) - { + if ($this->statut >= self::STATUS_DRAFT) { $error = 0; $this->db->begin(); $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); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->availability_id = $availability_id; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('ORDER_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2816,45 +2799,41 @@ class Commande extends CommonOrder global $user; dol_syslog('Commande::demand_reason('.$demand_reason_id.')'); - if ($this->statut >= self::STATUS_DRAFT) - { + if ($this->statut >= self::STATUS_DRAFT) { $error = 0; $this->db->begin(); $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); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->demand_reason_id = $demand_reason_id; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('ORDER_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2882,8 +2861,7 @@ class Commande extends CommonOrder public function set_ref_client($user, $ref_client, $notrigger = 0) { // phpcs:enable - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { $error = 0; $this->db->begin(); @@ -2894,32 +2872,29 @@ class Commande extends CommonOrder dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->ref_client = $ref_client; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('ORDER_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2942,8 +2917,7 @@ class Commande extends CommonOrder { $error = 0; - if ($this->billed) - { + if ($this->billed) { return 0; } @@ -2953,29 +2927,26 @@ class Commande extends CommonOrder $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; dol_syslog(get_class($this)."::classifyBilled", LOG_DEBUG); - if ($this->db->query($sql)) - { - if (!$error) - { + if ($this->db->query($sql)) { + if (!$error) { $this->oldcopy = clone $this; $this->billed = 1; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('ORDER_CLASSIFY_BILLED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::classifyBilled ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2992,11 +2963,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(); @@ -3005,28 +2977,28 @@ class Commande extends CommonOrder $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; dol_syslog(get_class($this)."::classifyUnBilled", LOG_DEBUG); - if ($this->db->query($sql)) - { - if (!$error) - { + if ($this->db->query($sql)) { + if (!$error) { $this->oldcopy = clone $this; $this->billed = 1; } - // Call trigger - $result = $this->call_trigger('ORDER_CLASSIFY_UNBILLED', $user); - if ($result < 0) $error++; - // End call triggers + if (!$notrigger && empty($error)) { + // Call trigger + $result = $this->call_trigger('ORDER_CLASSIFY_UNBILLED', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } - if (!$error) - { + if (!$error) { $this->billed = 0; $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::classifyUnBilled ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -3077,17 +3049,32 @@ class Commande extends CommonOrder dol_syslog(get_class($this)."::updateline id=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, date_start=$date_start, date_end=$date_end, type=$type, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, special_code=$special_code, ref_ext=$ref_ext"); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - if ($this->statut == Commande::STATUS_DRAFT) - { + if ($this->statut == Commande::STATUS_DRAFT) { // Clean parameters - if (empty($qty)) $qty = 0; - if (empty($info_bits)) $info_bits = 0; - if (empty($txtva)) $txtva = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; - if (empty($remise_percent)) $remise_percent = 0; - if (empty($special_code) || $special_code == 3) $special_code = 0; - if (empty($ref_ext)) $ref_ext = ''; + if (empty($qty)) { + $qty = 0; + } + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($txtva)) { + $txtva = 0; + } + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } + if (empty($remise_percent)) { + $remise_percent = 0; + } + if (empty($special_code) || $special_code == 3) { + $special_code = 0; + } + if (empty($ref_ext)) { + $ref_ext = ''; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); @@ -3118,8 +3105,7 @@ class Commande extends CommonOrder // Clean vat code $vat_src_code = ''; $reg = array(); - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -3143,15 +3129,13 @@ class Commande extends CommonOrder // Anciens indicateurs: $price, $subprice (a ne plus utiliser) $price = $pu_ht; - if ($price_base_type == 'TTC') - { + if ($price_base_type == 'TTC') { $subprice = $pu_ttc; } else { $subprice = $pu_ht; } $remise = 0; - if ($remise_percent > 0) - { + if ($remise_percent > 0) { $remise = round(($pu * $remise_percent / 100), 2); $price = ($pu - $remise); } @@ -3161,14 +3145,12 @@ class Commande extends CommonOrder $line->fetch($rowid); $line->fetch_optionals(); - if (!empty($line->fk_product)) - { + if (!empty($line->fk_product)) { $product = new Product($this->db); $result = $product->fetch($line->fk_product); $product_type = $product->type; - if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty) - { + if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty) { $langs->load("errors"); $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref); $this->errors[] = $this->error; @@ -3185,8 +3167,7 @@ class Commande extends CommonOrder $this->line->context = $this->context; // Reorder if fk_parent_line change - if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) - { + if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) { $rangmax = $this->line_max($fk_parent_line); $this->line->rang = $rangmax + 1; } @@ -3240,10 +3221,11 @@ class Commande extends CommonOrder } $result = $this->line->update($user, $notrigger); - if ($result > 0) - { + if ($result > 0) { // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) { + $this->line_order(true, 'DESC'); + } // Mise a jour info denormalisees $this->update_price(1); @@ -3277,12 +3259,25 @@ class Commande extends CommonOrder $error = 0; // Clean parameters - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->ref_client)) $this->ref_client = trim($this->ref_client); - if (isset($this->note) || isset($this->note_private)) $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note)); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf); - if (isset($this->import_key)) $this->import_key = trim($this->import_key); + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->ref_client)) { + $this->ref_client = trim($this->ref_client); + } + if (isset($this->note) || isset($this->note_private)) { + $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note)); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->model_pdf)) { + $this->model_pdf = trim($this->model_pdf); + } + if (isset($this->import_key)) { + $this->import_key = trim($this->import_key); + } + $delivery_date = empty($this->delivery_date) ? $this->date_livraison : $this->delivery_date; // Check parameters // Put here code to add control on parameters values @@ -3296,7 +3291,7 @@ class Commande extends CommonOrder $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").","; $sql .= " date_commande=".(strval($this->date_commande) != '' ? "'".$this->db->idate($this->date_commande)."'" : 'null').","; $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').","; - $sql .= " tva=".(isset($this->total_tva) ? $this->total_tva : "null").","; + $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").","; $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").","; $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").","; $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").","; @@ -3307,6 +3302,8 @@ class Commande extends CommonOrder $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").","; $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").","; $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").","; + $sql .= " date_livraison=".(strval($this->delivery_date) != '' ? "'".$this->db->idate($this->delivery_date)."'" : 'null').","; + $sql .= " fk_shipping_method=".(isset($this->shipping_method_id) ? $this->shipping_method_id : "null").","; $sql .= " fk_account=".($this->fk_account > 0 ? $this->fk_account : "null").","; $sql .= " fk_input_reason=".($this->demand_reason_id > 0 ? $this->demand_reason_id : "null").","; $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").","; @@ -3314,7 +3311,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(); @@ -3324,28 +3321,25 @@ class Commande extends CommonOrder $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('ORDER_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -3378,13 +3372,14 @@ class Commande extends CommonOrder if (!$notrigger) { // Call trigger $result = $this->call_trigger('ORDER_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } // Test we can delete - if ($this->nb_expedition() != 0) - { + if ($this->nb_expedition() != 0) { $this->errors[] = $langs->trans('SomeShipmentExists'); $error++; } @@ -3405,13 +3400,17 @@ class Commande extends CommonOrder if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } if (!$error) { // Delete linked contacts $res = $this->delete_linked_contact(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } // Removed extrafields of object @@ -3498,8 +3497,7 @@ class Commande extends CommonOrder $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.date_livraison as delivery_date, c.fk_statut, c.total_ht"; $sql .= " FROM ".MAIN_DB_PREFIX."commande as c"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = " AND"; @@ -3507,11 +3505,12 @@ class Commande extends CommonOrder $sql .= $clause." c.entity IN (".getEntity('commande').")"; //$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0"; $sql .= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_SHIPMENTONPROCESS.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))"; // If status is 2 and facture=1, it must be selected - if ($user->socid) $sql .= " AND c.fk_soc = ".$user->socid; + if ($user->socid) { + $sql .= " AND c.fk_soc = ".$user->socid; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $response = new WorkboardResponse(); $response->warning_delay = $conf->commande->client->warning_delay / 60 / 60 / 24; $response->label = $langs->trans("OrdersToProcess"); @@ -3521,8 +3520,7 @@ class Commande extends CommonOrder $generic_commande = new Commande($this->db); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; $response->total += $obj->total_ht; @@ -3555,7 +3553,9 @@ class Commande extends CommonOrder $label = $langs->trans('OrderSource'.$this->source); - if ($label == 'OrderSource') return ''; + if ($label == 'OrderSource') { + return ''; + } return $label; } @@ -3586,7 +3586,9 @@ class Commande extends CommonOrder global $langs, $conf; $billedtext = ''; - if (empty($donotshowbilled)) $billedtext .= ($billed ? ' - '.$langs->transnoentitiesnoconv("Billed") : ''); + if (empty($donotshowbilled)) { + $billedtext .= ($billed ? ' - '.$langs->transnoentitiesnoconv("Billed") : ''); + } $labelTooltip = ''; @@ -3646,25 +3648,36 @@ class Commande extends CommonOrder { global $conf, $langs, $user; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; - if (!empty($conf->expedition->enabled) && ($option == '1' || $option == '2')) $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id; - else $url = DOL_URL_ROOT.'/commande/card.php?id='.$this->id; - - if (!$user->rights->commande->lire) - $option = 'nolink'; - - 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 (!empty($conf->expedition->enabled) && ($option == '1' || $option == '2')) { + $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id; + } else { + $url = DOL_URL_ROOT.'/commande/card.php?id='.$this->id; } - if ($short) return $url; + if (!$user->rights->commande->lire) { + $option = 'nolink'; + } + + 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 ($short) { + return $url; + } $label = ''; @@ -3674,7 +3687,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); } @@ -3693,10 +3706,8 @@ class Commande extends CommonOrder } $linkclose = ''; - if (empty($notooltip) && $user->rights->commande->lire) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip) && $user->rights->commande->lire) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("Order"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -3714,15 +3725,17 @@ class Commande extends CommonOrder } $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; - if ($addlinktonotes) - { + if ($addlinktonotes) { $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { + if ($txttoshow) { $notetoshow = $langs->trans("ViewPrivateNote").':
    '.dol_string_nohtmltag($txttoshow, 1); $result .= ' '; $result .= ''; @@ -3751,30 +3764,25 @@ 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; @@ -3815,12 +3823,10 @@ class Commande extends CommonOrder $sql .= $this->db->plimit(100); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -3848,8 +3854,7 @@ class Commande extends CommonOrder // Lines $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new OrderLine($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; @@ -3857,8 +3862,7 @@ class Commande extends CommonOrder $line->subprice = 100; $line->price = 100; $line->tva_tx = 20; - if ($xnbp == 2) - { + if ($xnbp == 2) { $line->total_ht = 50; $line->total_ttc = 60; $line->total_tva = 10; @@ -3869,8 +3873,7 @@ class Commande extends CommonOrder $line->total_tva = 20; $line->remise_percent = 0; } - if ($num_prods > 0) - { + if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; $line->product_ref = 'SPECIMEN'; @@ -3904,8 +3907,7 @@ class Commande extends CommonOrder $sql = "SELECT count(co.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."commande as co"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -3913,10 +3915,8 @@ class Commande extends CommonOrder $sql .= " ".$clause." co.entity IN (".getEntity('commande').")"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["orders"] = $obj->nb; } $this->db->free($resql); @@ -4018,8 +4018,11 @@ class Commande extends CommonOrder { global $conf, $langs; - if (empty($this->date_livraison)) $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day'); - else $text = $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->date_livraison, 'day'); + if (empty($this->date_livraison)) { + $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day'); + } else { + $text = $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->date_livraison, 'day'); + } $text .= ' '.($conf->commande->client->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->client->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today"); return $text; @@ -4125,8 +4128,7 @@ class OrderLine extends CommonOrderLine $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid'; $sql .= ' WHERE cd.rowid = '.$rowid; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $objp = $this->db->fetch_object($result); $this->rowid = $objp->rowid; $this->id = $objp->rowid; @@ -4235,25 +4237,23 @@ class OrderLine extends CommonOrderLine dol_syslog("OrderLine::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Remove extrafields - if (!$error) - { + if (!$error) { $this->id = $this->rowid; $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINEORDER_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -4262,8 +4262,7 @@ class OrderLine extends CommonOrderLine return 1; } - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -4293,27 +4292,55 @@ class OrderLine extends CommonOrderLine dol_syslog(get_class($this)."::insert rang=".$this->rang); // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->localtax1_type)) $this->localtax1_type = 0; - if (empty($this->localtax2_type)) $this->localtax2_type = 0; - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; - if (empty($this->rang)) $this->rang = 0; - if (empty($this->remise)) $this->remise = 0; - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->info_bits)) $this->info_bits = 0; - if (empty($this->special_code)) $this->special_code = 0; - if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; - if (empty($this->pa_ht)) $this->pa_ht = 0; - if (empty($this->ref_ext)) $this->ref_ext = ''; + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->localtax1_type)) { + $this->localtax1_type = 0; + } + if (empty($this->localtax2_type)) { + $this->localtax2_type = 0; + } + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } + if (empty($this->rang)) { + $this->rang = 0; + } + if (empty($this->remise)) { + $this->remise = 0; + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->info_bits)) { + $this->info_bits = 0; + } + if (empty($this->special_code)) { + $this->special_code = 0; + } + if (empty($this->fk_parent_line)) { + $this->fk_parent_line = 0; + } + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } + if (empty($this->ref_ext)) { + $this->ref_ext = ''; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0 && $pa_ht_isemptystring) - { - if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) - { + if ($this->pa_ht == 0 && $pa_ht_isemptystring) { + if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { return $result; } else { $this->pa_ht = $result; @@ -4321,7 +4348,9 @@ class OrderLine extends CommonOrderLine } // Check parameters - if ($this->product_type < 0) return -1; + if ($this->product_type < 0) { + return -1; + } $this->db->begin(); @@ -4377,25 +4406,23 @@ class OrderLine extends CommonOrderLine dol_syslog(get_class($this)."::insert", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'commandedet'); $this->rowid = $this->id; - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINEORDER_INSERT', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -4404,8 +4431,7 @@ class OrderLine extends CommonOrderLine return 1; } - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::insert ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -4434,30 +4460,64 @@ class OrderLine extends CommonOrderLine $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->localtax1_type)) $this->localtax1_type = 0; - if (empty($this->localtax2_type)) $this->localtax2_type = 0; - if (empty($this->qty)) $this->qty = 0; - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; - if (empty($this->marque_tx)) $this->marque_tx = 0; - if (empty($this->marge_tx)) $this->marge_tx = 0; - if (empty($this->remise)) $this->remise = 0; - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->info_bits)) $this->info_bits = 0; - if (empty($this->special_code)) $this->special_code = 0; - if (empty($this->product_type)) $this->product_type = 0; - if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; - if (empty($this->pa_ht)) $this->pa_ht = 0; - if (empty($this->ref_ext)) $this->ref_ext = ''; + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->localtax1_type)) { + $this->localtax1_type = 0; + } + if (empty($this->localtax2_type)) { + $this->localtax2_type = 0; + } + if (empty($this->qty)) { + $this->qty = 0; + } + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } + if (empty($this->marque_tx)) { + $this->marque_tx = 0; + } + if (empty($this->marge_tx)) { + $this->marge_tx = 0; + } + if (empty($this->remise)) { + $this->remise = 0; + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->info_bits)) { + $this->info_bits = 0; + } + if (empty($this->special_code)) { + $this->special_code = 0; + } + if (empty($this->product_type)) { + $this->product_type = 0; + } + if (empty($this->fk_parent_line)) { + $this->fk_parent_line = 0; + } + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } + if (empty($this->ref_ext)) { + $this->ref_ext = ''; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0 && $pa_ht_isemptystring) - { - if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) - { + if ($this->pa_ht == 0 && $pa_ht_isemptystring) { + if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { return $result; } else { $this->pa_ht = $result; @@ -4482,8 +4542,7 @@ class OrderLine extends CommonOrderLine $sql .= " , remise_percent=".price2num($this->remise_percent).""; $sql .= " , price=".price2num($this->price).""; // TODO A virer $sql .= " , remise=".price2num($this->remise).""; // TODO A virer - if (empty($this->skip_update_total)) - { + if (empty($this->skip_update_total)) { $sql .= " , total_ht=".price2num($this->total_ht).""; $sql .= " , total_tva=".price2num($this->total_tva).""; $sql .= " , total_ttc=".price2num($this->total_ttc).""; @@ -4498,7 +4557,9 @@ class OrderLine extends CommonOrderLine $sql .= " , date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null"); $sql .= " , product_type=".$this->product_type; $sql .= " , fk_parent_line=".(!empty($this->fk_parent_line) ? $this->fk_parent_line : "null"); - if (!empty($this->rang)) $sql .= ", rang=".$this->rang; + if (!empty($this->rang)) { + $sql .= ", rang=".$this->rang; + } $sql .= " , fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); // Multicurrency @@ -4511,23 +4572,21 @@ class OrderLine extends CommonOrderLine dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$error) - { + if ($resql) { + if (!$error) { $this->id = $this->rowid; $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINEORDER_UPDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -4536,8 +4595,7 @@ class OrderLine extends CommonOrderLine return 1; } - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -4563,8 +4621,12 @@ class OrderLine extends CommonOrderLine $this->db->begin(); // Clean parameters - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."commandedet SET"; @@ -4578,8 +4640,7 @@ class OrderLine extends CommonOrderLine dol_syslog("OrderLine::update_total", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { diff --git a/htdocs/commande/class/commandestats.class.php b/htdocs/commande/class/commandestats.class.php index 57f8147cd57..a266dc0c4cf 100644 --- a/htdocs/commande/class/commandestats.class.php +++ b/htdocs/commande/class/commandestats.class.php @@ -20,9 +20,9 @@ */ /** - * \file htdocs/commande/class/commandestats.class.php - * \ingroup commandes - * \brief File of class to manage order statistics + * \file htdocs/commande/class/commandestats.class.php + * \ingroup commandes + * \brief File of class to manage order statistics */ include_once DOL_DOCUMENT_ROOT.'/core/class/stats.class.php'; include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; @@ -70,16 +70,14 @@ class CommandeStats extends Stats $this->cachefilesuffix = $mode; $this->join = ''; - if ($mode == 'customer') - { + if ($mode == 'customer') { $object = new Commande($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as c"; $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl"; $this->field = 'total_ht'; $this->field_line = 'total_ht'; //$this->where .= " c.fk_statut > 0"; // Not draft and not cancelled - } elseif ($mode == 'supplier') - { + } elseif ($mode == 'supplier') { $object = new CommandeFournisseur($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as c"; $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl"; @@ -90,21 +88,22 @@ class CommandeStats extends Stats //$this->where.= " AND c.fk_soc = s.rowid AND c.entity = ".$conf->entity; $this->where .= ($this->where ? ' AND ' : '').'c.entity IN ('.getEntity('commande').')'; - if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($this->socid) - { + if (!$user->rights->societe->client->voir && !$this->socid) { + $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($this->socid) { $this->where .= " AND c.fk_soc = ".$this->socid; } - if ($this->userid > 0) $this->where .= ' AND c.fk_user_author = '.$this->userid; + if ($this->userid > 0) { + $this->where .= ' AND c.fk_user_author = '.$this->userid; + } - if ($typentid) - { + if ($typentid) { $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = c.fk_soc'; $this->where .= ' AND s.fk_typent = '.$typentid; } - if ($categid) - { + if ($categid) { $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_societe as cats ON cats.fk_soc = c.fk_soc'; $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie as cat ON cat.rowid = cats.fk_categorie'; $this->where .= ' AND cat.rowid = '.$categid; @@ -124,7 +123,9 @@ class CommandeStats extends Stats $sql = "SELECT date_format(c.date_commande,'%m') as dm, COUNT(*) as nb"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE c.date_commande BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; @@ -147,7 +148,9 @@ class CommandeStats extends Stats $sql = "SELECT date_format(c.date_commande,'%Y') as dm, COUNT(*) as nb, SUM(c.".$this->field.")"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE ".$this->where; $sql .= " GROUP BY dm"; @@ -169,7 +172,9 @@ class CommandeStats extends Stats $sql = "SELECT date_format(c.date_commande,'%m') as dm, SUM(c.".$this->field.")"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE c.date_commande BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; @@ -192,7 +197,9 @@ class CommandeStats extends Stats $sql = "SELECT date_format(c.date_commande,'%m') as dm, AVG(c.".$this->field.")"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE c.date_commande BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; @@ -213,7 +220,9 @@ class CommandeStats extends Stats $sql = "SELECT date_format(c.date_commande,'%Y') as year, COUNT(*) as nb, SUM(c.".$this->field.") as total, AVG(".$this->field.") as avg"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE ".$this->where; $sql .= " GROUP BY year"; @@ -235,7 +244,9 @@ class CommandeStats extends Stats $sql = "SELECT product.ref, COUNT(product.ref) as nb, SUM(tl.".$this->field_line.") as total, AVG(tl.".$this->field_line.") as avg"; $sql .= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE ".$this->where; $sql .= " AND c.rowid = tl.fk_commande AND tl.fk_product = product.rowid"; diff --git a/htdocs/commande/contact.php b/htdocs/commande/contact.php index 7df7dbea130..0a576707e73 100644 --- a/htdocs/commande/contact.php +++ b/htdocs/commande/contact.php @@ -3,6 +3,7 @@ * Copyright (C) 2005-2011 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2011-2015 Philippe Grand + * 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 @@ -40,7 +41,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'commande', $id, ''); $object = new Commande($db); @@ -49,51 +52,39 @@ $object = new Commande($db); * Ajout d'un nouveau contact */ -if ($action == 'addcontact' && $user->rights->commande->creer) -{ +if ($action == 'addcontact' && $user->rights->commande->creer) { $result = $object->fetch($id); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } -} - -// bascule du statut d'un contact -elseif ($action == 'swapstatut' && $user->rights->commande->creer) -{ - if ($object->fetch($id)) - { +} elseif ($action == 'swapstatut' && $user->rights->commande->creer) { + // 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' && $user->rights->commande->creer) -{ +} elseif ($action == 'deletecontact' && $user->rights->commande->creer) { + // Efface un contact $object->fetch($id); $result = $object->delete_contact($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -128,23 +119,17 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ - $langs->trans("OrderCard"); - - if ($object->fetch($id, $ref) > 0) - { +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { $object->fetch_thirdparty(); $head = commande_prepare_head($object); print dol_get_fiche_head($head, 'contact', $langs->trans("CustomerOrder"), -1, 'order'); - // Order card $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref = '
    '; // Ref customer $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -152,12 +137,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; $morehtmlref .= ' : '; @@ -195,10 +178,11 @@ if ($id > 0 || !empty($ref)) // Contacts lines (modules that overwrite templates must declare this into descriptor) $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); - foreach ($dirtpls as $reldir) - { + foreach ($dirtpls as $reldir) { $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); - if ($res) break; + if ($res) { + break; + } } } else { // Contact not found diff --git a/htdocs/commande/customer.php b/htdocs/commande/customer.php index f2f806cc7af..4f75ca3d4c5 100644 --- a/htdocs/commande/customer.php +++ b/htdocs/commande/customer.php @@ -33,14 +33,14 @@ require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; $action = GETPOST('action', 'aZ09'); // Secrutiy check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } -if (!$user->rights->facture->creer) -accessforbidden(); +if (!$user->rights->facture->creer) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array("companies", "orders")); @@ -49,12 +49,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 = "nom"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "nom"; +} /* @@ -71,25 +77,34 @@ $thirdpartystatic = new Societe($db); $sql = "SELECT s.rowid, s.nom as name, s.client, s.town, s.datec, s.datea"; $sql .= ", st.libelle as stcomm, s.prefix_comm, s.code_client, s.code_compta "; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; +} $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."c_stcomm as st, ".MAIN_DB_PREFIX."commande as c"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE s.fk_stcomm = st.id AND c.fk_soc = s.rowid"; $sql .= " AND s.entity IN (".getEntity('societe').")"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if (dol_strlen($stcomm)) -{ +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if (dol_strlen($stcomm)) { $sql .= " AND s.fk_stcomm=".$stcomm; } -if (GETPOST("search_nom")) $sql .= natural_search("s.nom", GETPOST("search_nom")); -if (GETPOST("search_compta")) $sql .= natural_search("s.code_compta", GETPOST("search_compta")); -if (GETPOST("search_code_client")) $sql .= natural_search("s.code_client", GETPOST("search_code_client")); -if (dol_strlen($begin)) -{ +if (GETPOST("search_nom")) { + $sql .= natural_search("s.nom", GETPOST("search_nom")); +} +if (GETPOST("search_compta")) { + $sql .= natural_search("s.code_compta", GETPOST("search_compta")); +} +if (GETPOST("search_code_client")) { + $sql .= natural_search("s.code_client", GETPOST("search_code_client")); +} +if (dol_strlen($begin)) { $sql .= " AND s.nom like '".$db->escape($begin)."'"; } -if ($socid > 0) -{ +if ($socid > 0) { $sql .= " AND s.rowid = ".$socid; } $sql .= " AND c.fk_statut in (1, 2) AND c.facture = 0"; @@ -98,13 +113,11 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -114,8 +127,7 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -155,8 +167,7 @@ if ($resql) print "\n"; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); print '
    '; diff --git a/htdocs/commande/document.php b/htdocs/commande/document.php index f95f61b6025..37fd7a38928 100644 --- a/htdocs/commande/document.php +++ b/htdocs/commande/document.php @@ -45,8 +45,7 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref'); // Security check -if ($user->socid) -{ +if ($user->socid) { $socid = $user->socid; } $result = restrictedArea($user, 'commande', $id, ''); @@ -56,16 +55,26 @@ $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 (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; } -if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; } +if (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { + $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; +} +if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { + $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; +} -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} $object = new Commande($db); @@ -74,13 +83,12 @@ $object = new Commande($db); * Actions */ -if ($object->fetch($id)) -{ +if ($object->fetch($id)) { $object->fetch_thirdparty(); $upload_dir = $conf->commande->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref); } -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -91,10 +99,8 @@ llxHeader('', $langs->trans('Order'), 'EN:Customers_Orders|FR:Commandes_Clients| $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref)) - { +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref)) { $object->fetch_thirdparty(); $upload_dir = $conf->commande->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); @@ -105,8 +111,7 @@ if ($id > 0 || !empty($ref)) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -122,12 +127,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; $morehtmlref .= ' : '; diff --git a/htdocs/commande/index.php b/htdocs/commande/index.php index 4a18f96ddde..4b6fcc7d8aa 100644 --- a/htdocs/commande/index.php +++ b/htdocs/commande/index.php @@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; -if (!$user->rights->commande->lire) accessforbidden(); +if (!$user->rights->commande->lire) { + accessforbidden(); +} $hookmanager = new HookManager($db); @@ -43,8 +45,7 @@ $langs->loadLangs(array('orders', 'bills')); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -69,8 +70,7 @@ print load_fiche_titre($langs->trans("OrdersArea"), '', 'order'); print '
    '; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo // Search customer orders print ''; print ''; @@ -90,16 +90,21 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useles $sql = "SELECT count(c.rowid) as nb, c.fk_statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."commande as c"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity('societe').")"; -if ($user->socid) $sql .= ' AND c.fk_soc = '.$user->socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($user->socid) { + $sql .= ' AND c.fk_soc = '.$user->socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " GROUP BY c.fk_statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -109,14 +114,14 @@ if ($resql) $colorseries = array(); $vals = array(); // -1=Canceled, 0=Draft, 1=Validated, 2=Accepted/On process, 3=Closed (Sent/Received, billed or not) - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); - if ($row) - { + if ($row) { //if ($row[1]!=-1 && ($row[1]!=3 || $row[2]!=1)) { - if (!isset($vals[$row[1]])) $vals[$row[1]] = 0; + if (!isset($vals[$row[1]])) { + $vals[$row[1]] = 0; + } $vals[$row[1]] += $row[0]; $totalinprocess += $row[0]; } @@ -132,18 +137,28 @@ if ($resql) print '
    '; print ''."\n"; $listofstatus = array(0, 1, 2, 3, -1); - foreach ($listofstatus as $status) - { + foreach ($listofstatus as $status) { $dataseries[] = array($commandestatic->LibStatut($status, 0, 1, 1), (isset($vals[$status]) ? (int) $vals[$status] : 0)); - if ($status == Commande::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; - if ($status == Commande::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus1; - if ($status == Commande::STATUS_SHIPMENTONPROCESS) $colorseries[$status] = $badgeStatus4; - if ($status == Commande::STATUS_CLOSED && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) $colorseries[$status] = $badgeStatus6; - if ($status == Commande::STATUS_CLOSED && (!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) $colorseries[$status] = $badgeStatus6; - if ($status == Commande::STATUS_CANCELED) $colorseries[$status] = $badgeStatus9; + if ($status == Commande::STATUS_DRAFT) { + $colorseries[$status] = '-'.$badgeStatus0; + } + if ($status == Commande::STATUS_VALIDATED) { + $colorseries[$status] = $badgeStatus1; + } + if ($status == Commande::STATUS_SHIPMENTONPROCESS) { + $colorseries[$status] = $badgeStatus4; + } + if ($status == Commande::STATUS_CLOSED && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) { + $colorseries[$status] = $badgeStatus6; + } + if ($status == Commande::STATUS_CLOSED && (!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) { + $colorseries[$status] = $badgeStatus6; + } + if ($status == Commande::STATUS_CANCELED) { + $colorseries[$status] = $badgeStatus9; + } - if (empty($conf->use_javascript_ajax)) - { + if (empty($conf->use_javascript_ajax)) { print ''; print ''; print '\n"; } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print ''; print ''; - if ($num) - { + if ($num) { $i = 0; - while ($i < $num && $i < $max) - { + while ($i < $num && $i < $max) { $obj = $db->fetch_object($resql); print ''; print '
    '.$langs->trans("Statistics").' - '.$langs->trans("CustomersOrders").'
    '.$commandestatic->LibStatut($status, 0, 0, 1).''.(isset($vals[$status]) ? $vals[$status] : 0).' '; @@ -152,8 +167,7 @@ if ($resql) print "
    '; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -181,35 +195,37 @@ if ($resql) /* * Draft orders */ -if (!empty($conf->commande->enabled)) -{ +if (!empty($conf->commande->enabled)) { $sql = "SELECT c.rowid, c.ref, s.nom as name, s.rowid as socid"; $sql .= ", s.client"; $sql .= ", s.code_client"; $sql .= ", s.canvas"; $sql .= " FROM ".MAIN_DB_PREFIX."commande as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity('commande').")"; $sql .= " AND c.fk_statut = 0"; - if ($socid) $sql .= " AND c.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { print '
    '; print ''; print ''; print ''; $langs->load("orders"); $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $commandestatic->id = $obj->rowid; @@ -254,29 +270,32 @@ $sql .= ", s.code_client"; $sql .= ", s.canvas"; $sql .= " FROM ".MAIN_DB_PREFIX."commande as c,"; $sql .= " ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity('commande').")"; //$sql.= " AND c.fk_statut > 2"; -if ($socid) $sql .= " AND c.fk_soc = ".$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " ORDER BY c.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { print '
    '; print '
    '.$langs->trans("DraftOrders").'
    '; print ''; print ''; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; @@ -319,32 +338,38 @@ if ($resql) } } print "
    '.$langs->trans("LastModifiedOrders", $max).'

    "; -} else dol_print_error($db); +} else { + dol_print_error($db); +} $max = 10; /* * Orders to process */ -if (!empty($conf->commande->enabled)) -{ +if (!empty($conf->commande->enabled)) { $sql = "SELECT c.rowid, c.entity, c.ref, c.fk_statut, c.facture, c.date_commande as date, s.nom as name, s.rowid as socid"; $sql .= ", s.client"; $sql .= ", s.code_client"; $sql .= ", s.canvas"; $sql .= " FROM ".MAIN_DB_PREFIX."commande as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity('commande').")"; $sql .= " AND c.fk_statut = ".Commande::STATUS_VALIDATED; - if ($socid) $sql .= " AND c.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= " ORDER BY c.rowid DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '
    '; @@ -352,11 +377,9 @@ if (!empty($conf->commande->enabled)) print '
    '.$langs->trans("OrdersToProcess").' '.$num.'
    '; @@ -405,31 +428,37 @@ if (!empty($conf->commande->enabled)) } print "

    "; - } else dol_print_error($db); + } else { + dol_print_error($db); + } } /* * Orders that are in process */ -if (!empty($conf->commande->enabled)) -{ +if (!empty($conf->commande->enabled)) { $sql = "SELECT c.rowid, c.entity, c.ref, c.fk_statut, c.facture, c.date_commande as date, s.nom as name, s.rowid as socid"; $sql .= ", s.client"; $sql .= ", s.code_client"; $sql .= ", s.canvas"; $sql .= " FROM ".MAIN_DB_PREFIX."commande as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity('commande').")"; $sql .= " AND c.fk_statut = ".Commande::STATUS_ACCEPTED; - if ($socid) $sql .= " AND c.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= " ORDER BY c.rowid DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '
    '; @@ -437,11 +466,9 @@ if (!empty($conf->commande->enabled)) print '
    '.$langs->trans("OnProcessOrders").' '.$num.'
    '; @@ -489,7 +516,9 @@ if (!empty($conf->commande->enabled)) } } print "

    "; - } else dol_print_error($db); + } else { + dol_print_error($db); + } } diff --git a/htdocs/commande/info.php b/htdocs/commande/info.php index 117afab2398..5dd9a64a8a6 100644 --- a/htdocs/commande/info.php +++ b/htdocs/commande/info.php @@ -31,7 +31,9 @@ if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } -if (!$user->rights->commande->lire) accessforbidden(); +if (!$user->rights->commande->lire) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('orders', 'sendings', 'bills')); @@ -42,12 +44,13 @@ $id = GETPOST("id", 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'commande', $comid, ''); $object = new Commande($db); -if (!$object->fetch($id, $ref) > 0) -{ +if (!$object->fetch($id, $ref) > 0) { dol_print_error($db); exit; } @@ -78,12 +81,10 @@ $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_cl // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; $morehtmlref .= ' : '; diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 8b4a79f4dda..73ac91c7098 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -56,9 +56,13 @@ $toselect = GETPOST('toselect', 'array'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'orderlist'; $search_datecloture_start = GETPOST('search_datecloture_start', 'int'); -if (empty($search_datecloture_start)) $search_datecloture_start = dol_mktime(0, 0, 0, GETPOST('search_datecloture_startmonth', 'int'), GETPOST('search_datecloture_startday', 'int'), GETPOST('search_datecloture_startyear', 'int')); +if (empty($search_datecloture_start)) { + $search_datecloture_start = dol_mktime(0, 0, 0, GETPOST('search_datecloture_startmonth', 'int'), GETPOST('search_datecloture_startday', 'int'), GETPOST('search_datecloture_startyear', 'int')); +} $search_datecloture_end = GETPOST('search_datecloture_end', 'int'); -if (empty($search_datecloture_end)) $search_datecloture_end = dol_mktime(23, 59, 59, GETPOST('search_datecloture_endmonth', 'int'), GETPOST('search_datecloture_endday', 'int'), GETPOST('search_datecloture_endyear', 'int')); +if (empty($search_datecloture_end)) { + $search_datecloture_end = dol_mktime(23, 59, 59, GETPOST('search_datecloture_endmonth', 'int'), GETPOST('search_datecloture_endday', 'int'), GETPOST('search_datecloture_endyear', 'int')); +} $search_dateorder_start = dol_mktime(0, 0, 0, GETPOST('search_dateorder_start_month', 'int'), GETPOST('search_dateorder_start_day', 'int'), GETPOST('search_dateorder_start_year', 'int')); $search_dateorder_end = dol_mktime(23, 59, 59, GETPOST('search_dateorder_end_month', 'int'), GETPOST('search_dateorder_end_day', 'int'), GETPOST('search_dateorder_end_year', 'int')); $search_datedelivery_start = dol_mktime(0, 0, 0, GETPOST('search_datedelivery_start_month', 'int'), GETPOST('search_datedelivery_start_day', 'int'), GETPOST('search_datedelivery_start_year', 'int')); @@ -102,7 +106,9 @@ $search_fk_mode_reglement = GETPOST("search_fk_mode_reglement", 'int'); // Security check $id = (GETPOST('orderid') ?GETPOST('orderid', 'int') : GETPOST('id', 'int')); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'commande', $id, ''); $diroutputmassaction = $conf->commande->multidir_output[$conf->entity].'/temp/massgeneration/'.$user->id; @@ -112,12 +118,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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 'c.ref'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'c.ref'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} $show_shippable_command = GETPOST('show_shippable_command', 'aZ09'); @@ -141,7 +153,9 @@ $fieldstosearchall = array( 's.town'=>"Town", 'c.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["c.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["c.note_private"] = "NotePrivate"; +} $checkedtypetiers = 0; $arrayfields = array( @@ -191,21 +205,25 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * 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)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_categ = ''; $search_user = ''; $search_sale = ''; @@ -248,8 +266,7 @@ if (empty($reshook)) $search_fk_mode_reglement = ''; } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -282,21 +299,28 @@ $help_url = "EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_P // llxHeader('',$title,$help_url); $sql = 'SELECT'; -if ($sall || $search_product_category > 0 || $search_user > 0) $sql = 'SELECT DISTINCT'; +if ($sall || $search_product_category > 0 || $search_user > 0) { + $sql = 'SELECT DISTINCT'; +} $sql .= ' s.rowid as socid, s.nom as name, s.name_alias as name_alias, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; $sql .= " typent.code as typent_code,"; $sql .= " state.code_departement as state_code, state.nom as state_name,"; -$sql .= ' c.rowid, c.ref, c.total_ht, c.tva as total_tva, c.total_ttc, c.ref_client, c.fk_user_author,'; +$sql .= ' c.rowid, c.ref, c.total_ht, c.total_tva, c.total_ttc, c.ref_client, c.fk_user_author,'; $sql .= ' c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva as multicurrency_total_vat, c.multicurrency_total_ttc,'; $sql .= ' c.date_valid, c.date_commande, c.note_public, c.note_private, c.date_livraison as date_delivery, c.fk_statut, c.facture as billed,'; $sql .= ' c.date_creation as date_creation, c.tms as date_update, c.date_cloture as date_cloture,'; $sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_label,"; $sql .= " u.login,"; $sql .= ' c.fk_cond_reglement,c.fk_mode_reglement,c.fk_shipping_method'; -if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc"; +if ($search_categ_cus) { + $sql .= ", cc.fk_categorie, cc.fk_soc"; +} // 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 @@ -305,86 +329,171 @@ $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; -if (!empty($search_categ_cus)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ +if (!empty($search_categ_cus)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ +} $sql .= ', '.MAIN_DB_PREFIX.'commande as c'; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_extrafields as ef on (c.rowid = ef.fk_object)"; -if ($sall || $search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON c.rowid=pd.fk_commande'; -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_extrafields as ef on (c.rowid = ef.fk_object)"; +} +if ($sall || $search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON c.rowid=pd.fk_commande'; +} +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = c.fk_projet"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON c.fk_user_author = u.rowid'; // We'll need this table joined to the select in order to filter by sale -if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; -if ($search_user > 0) -{ +if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} +if ($search_user > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql .= ' WHERE c.fk_soc = s.rowid'; $sql .= ' AND c.entity IN ('.getEntity('commande').')'; -if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; -if ($socid > 0) $sql .= ' AND s.rowid = '.$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($search_ref) $sql .= natural_search('c.ref', $search_ref); -if ($search_ref_customer) $sql .= natural_search('c.ref_client', $search_ref_customer); -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if ($search_billed != '' && $search_billed >= 0) $sql .= ' AND c.facture = '.$search_billed; -if ($search_status <> '') -{ - if ($search_status < 4 && $search_status > -3) - { - if ($search_status == 1 && empty($conf->expedition->enabled)) $sql .= ' AND c.fk_statut IN (1,2)'; // If module expedition disabled, we include order with status 'sending in process' into 'validated' - else $sql .= ' AND c.fk_statut = '.$search_status; // brouillon, validee, en cours, annulee +if ($search_product_category > 0) { + $sql .= " AND cp.fk_categorie = ".$search_product_category; +} +if ($socid > 0) { + $sql .= ' AND s.rowid = '.$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($search_ref) { + $sql .= natural_search('c.ref', $search_ref); +} +if ($search_ref_customer) { + $sql .= natural_search('c.ref_client', $search_ref_customer); +} +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} +if ($search_billed != '' && $search_billed >= 0) { + $sql .= ' AND c.facture = '.$search_billed; +} +if ($search_status <> '') { + if ($search_status < 4 && $search_status > -3) { + if ($search_status == 1 && empty($conf->expedition->enabled)) { + $sql .= ' AND c.fk_statut IN (1,2)'; // If module expedition disabled, we include order with status 'sending in process' into 'validated' + } else { + $sql .= ' AND c.fk_statut = '.$search_status; // brouillon, validee, en cours, annulee + } } - if ($search_status == 4) - { + if ($search_status == 4) { $sql .= ' AND c.facture = 1'; // invoice created } - if ($search_status == -2) // To process - { + if ($search_status == -2) { // To process //$sql.= ' AND c.fk_statut IN (1,2,3) AND c.facture = 0'; $sql .= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))"; // If status is 2 and facture=1, it must be selected } - if ($search_status == -3) // To bill - { + if ($search_status == -3) { // To bill //$sql.= ' AND c.fk_statut in (1,2,3)'; //$sql.= ' AND c.facture = 0'; // invoice not created $sql .= ' AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))'; // validated, in process or closed but not billed } } -if ($search_datecloture_start) $sql .= " AND c.date_cloture >= '".$db->idate($search_datecloture_start)."'"; -if ($search_datecloture_end) $sql .= " AND c.date_cloture <= '".$db->idate($search_datecloture_end)."'"; -if ($search_dateorder_start) $sql .= " AND c.date_commande >= '".$db->idate($search_dateorder_start)."'"; -if ($search_dateorder_end) $sql .= " AND c.date_commande <= '".$db->idate($search_dateorder_end)."'"; -if ($search_datedelivery_start) $sql .= " AND c.date_livraison >= '".$db->idate($search_datedelivery_start)."'"; -if ($search_datedelivery_end) $sql .= " AND c.date_livraison <= '".$db->idate($search_datedelivery_end)."'"; -if ($search_town) $sql .= natural_search('s.town', $search_town); -if ($search_zip) $sql .= natural_search("s.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_country) $sql .= " AND s.fk_pays IN (".$search_country.')'; -if ($search_type_thirdparty) $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; -if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_company_alias) $sql .= natural_search('s.name_alias', $search_company_alias); -if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale; -if ($search_user > 0) $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; -if ($search_total_ht != '') $sql .= natural_search('c.total_ht', $search_total_ht, 1); -if ($search_total_vat != '') $sql .= natural_search('c.tva', $search_total_vat, 1); -if ($search_total_ttc != '') $sql .= natural_search('c.total_ttc', $search_total_ttc, 1); -if ($search_warehouse != '' && $search_warehouse != '-1') $sql .= natural_search('c.fk_warehouse', $search_warehouse, 1); -if ($search_multicurrency_code != '') $sql .= ' AND c.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; -if ($search_multicurrency_tx != '') $sql .= natural_search('c.multicurrency_tx', $search_multicurrency_tx, 1); -if ($search_multicurrency_montant_ht != '') $sql .= natural_search('c.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); -if ($search_multicurrency_montant_vat != '') $sql .= natural_search('c.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); -if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('c.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); -if ($search_login) $sql .= natural_search("u.login", $search_login); -if ($search_project_ref != '') $sql .= natural_search("p.ref", $search_project_ref); -if ($search_project != '') $sql .= natural_search("p.title", $search_project); -if ($search_categ_cus > 0) $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); -if ($search_categ_cus == -2) $sql .= " AND cc.fk_categorie IS NULL"; -if ($search_fk_cond_reglement > 0) $sql .= " AND c.fk_cond_reglement = ".$db->escape($search_fk_cond_reglement); -if ($search_fk_shipping_method > 0) $sql .= " AND c.fk_shipping_method = ".$db->escape($search_fk_shipping_method); -if ($search_fk_mode_reglement > 0) $sql .= " AND c.fk_mode_reglement = ".$db->escape($search_fk_mode_reglement); +if ($search_datecloture_start) { + $sql .= " AND c.date_cloture >= '".$db->idate($search_datecloture_start)."'"; +} +if ($search_datecloture_end) { + $sql .= " AND c.date_cloture <= '".$db->idate($search_datecloture_end)."'"; +} +if ($search_dateorder_start) { + $sql .= " AND c.date_commande >= '".$db->idate($search_dateorder_start)."'"; +} +if ($search_dateorder_end) { + $sql .= " AND c.date_commande <= '".$db->idate($search_dateorder_end)."'"; +} +if ($search_datedelivery_start) { + $sql .= " AND c.date_livraison >= '".$db->idate($search_datedelivery_start)."'"; +} +if ($search_datedelivery_end) { + $sql .= " AND c.date_livraison <= '".$db->idate($search_datedelivery_end)."'"; +} +if ($search_town) { + $sql .= natural_search('s.town', $search_town); +} +if ($search_zip) { + $sql .= natural_search("s.zip", $search_zip); +} +if ($search_state) { + $sql .= natural_search("state.nom", $search_state); +} +if ($search_country) { + $sql .= " AND s.fk_pays IN (".$search_country.')'; +} +if ($search_type_thirdparty) { + $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; +} +if ($search_company) { + $sql .= natural_search('s.nom', $search_company); +} +if ($search_company_alias) { + $sql .= natural_search('s.name_alias', $search_company_alias); +} +if ($search_sale > 0) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale; +} +if ($search_user > 0) { + $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; +} +if ($search_total_ht != '') { + $sql .= natural_search('c.total_ht', $search_total_ht, 1); +} +if ($search_total_vat != '') { + $sql .= natural_search('c.total_tva', $search_total_vat, 1); +} +if ($search_total_ttc != '') { + $sql .= natural_search('c.total_ttc', $search_total_ttc, 1); +} +if ($search_warehouse != '' && $search_warehouse != '-1') { + $sql .= natural_search('c.fk_warehouse', $search_warehouse, 1); +} +if ($search_multicurrency_code != '') { + $sql .= ' AND c.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; +} +if ($search_multicurrency_tx != '') { + $sql .= natural_search('c.multicurrency_tx', $search_multicurrency_tx, 1); +} +if ($search_multicurrency_montant_ht != '') { + $sql .= natural_search('c.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); +} +if ($search_multicurrency_montant_vat != '') { + $sql .= natural_search('c.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); +} +if ($search_multicurrency_montant_ttc != '') { + $sql .= natural_search('c.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); +} +if ($search_login) { + $sql .= natural_search("u.login", $search_login); +} +if ($search_project_ref != '') { + $sql .= natural_search("p.ref", $search_project_ref); +} +if ($search_project != '') { + $sql .= natural_search("p.title", $search_project); +} +if ($search_categ_cus > 0) { + $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); +} +if ($search_categ_cus == -2) { + $sql .= " AND cc.fk_categorie IS NULL"; +} +if ($search_fk_cond_reglement > 0) { + $sql .= " AND c.fk_cond_reglement = ".$db->escape($search_fk_cond_reglement); +} +if ($search_fk_shipping_method > 0) { + $sql .= " AND c.fk_shipping_method = ".$db->escape($search_fk_shipping_method); +} +if ($search_fk_mode_reglement > 0) { + $sql .= " AND c.fk_mode_reglement = ".$db->escape($search_fk_mode_reglement); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -397,13 +506,11 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -413,40 +520,47 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ - if ($socid > 0) - { +if ($resql) { + if ($socid > 0) { $soc = new Societe($db); $soc->fetch($socid); $title = $langs->trans('ListOfOrders').' - '.$soc->name; - if (empty($search_company)) $search_company = $soc->name; + if (empty($search_company)) { + $search_company = $soc->name; + } } else { $title = $langs->trans('ListOfOrders'); } - if (strval($search_status) == '0') - $title .= ' - '.$langs->trans('StatusOrderDraftShort'); - if ($search_status == 1) - $title .= ' - '.$langs->trans('StatusOrderValidatedShort'); - if ($search_status == 2) - $title .= ' - '.$langs->trans('StatusOrderSentShort'); - if ($search_status == 3) - $title .= ' - '.$langs->trans('StatusOrderToBillShort'); - if ($search_status == 4) - $title .= ' - '.$langs->trans('StatusOrderProcessedShort'); - if ($search_status == -1) - $title .= ' - '.$langs->trans('StatusOrderCanceledShort'); - if ($search_status == -2) - $title .= ' - '.$langs->trans('StatusOrderToProcessShort'); - if ($search_status == -3) - $title .= ' - '.$langs->trans('StatusOrderValidated').', '.(empty($conf->expedition->enabled) ? '' : $langs->trans("StatusOrderSent").', ').$langs->trans('StatusOrderToBill'); + if (strval($search_status) == '0') { + $title .= ' - '.$langs->trans('StatusOrderDraftShort'); + } + if ($search_status == 1) { + $title .= ' - '.$langs->trans('StatusOrderValidatedShort'); + } + if ($search_status == 2) { + $title .= ' - '.$langs->trans('StatusOrderSentShort'); + } + if ($search_status == 3) { + $title .= ' - '.$langs->trans('StatusOrderToBillShort'); + } + if ($search_status == 4) { + $title .= ' - '.$langs->trans('StatusOrderProcessedShort'); + } + if ($search_status == -1) { + $title .= ' - '.$langs->trans('StatusOrderCanceledShort'); + } + if ($search_status == -2) { + $title .= ' - '.$langs->trans('StatusOrderToProcessShort'); + } + if ($search_status == -3) { + $title .= ' - '.$langs->trans('StatusOrderValidated').', '.(empty($conf->expedition->enabled) ? '' : $langs->trans("StatusOrderSent").', ').$langs->trans('StatusOrderToBill'); + } $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); - if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) - { + if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/commande/card.php?id='.$id); @@ -457,47 +571,129 @@ if ($resql) $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 ($socid > 0) $param .= '&socid='.urlencode($socid); - if ($search_status != '') $param .= '&search_status='.urlencode($search_status); - if ($search_datecloture_start) $param .= '&search_datecloture_start='.urlencode($search_datecloture_start); - if ($search_datecloture_end) $param .= '&search_datecloture_end='.urlencode($search_datecloture_end); - if ($search_dateorder_start) $param .= '&search_dateorder_start_day='.dol_print_date($search_dateorder_start, '%d').'&search_dateorder_start_month='.dol_print_date($search_dateorder_start, '%m').'&search_dateorder_start_year='.dol_print_date($search_dateorder_start, '%Y'); - if ($search_dateorder_end) $param .= '&search_dateorder_end_day='.dol_print_date($search_dateorder_end, '%d').'&search_dateorder_end_month='.dol_print_date($search_dateorder_end, '%m').'&search_dateorder_end_year='.dol_print_date($search_dateorder_end, '%Y'); - if ($search_datedelivery_start) $param .= '&search_datedelivery_start_day='.dol_print_date($search_datedelivery_start, '%d').'&search_datedelivery_start_month='.dol_print_date($search_datedelivery_start, '%m').'&search_datedelivery_start_year='.dol_print_date($search_datedelivery_start, '%Y'); - if ($search_datedelivery_end) $param .= '&search_datedelivery_end_day='.dol_print_date($search_datedelivery_end, '%d').'&search_datedelivery_end_month='.dol_print_date($search_datedelivery_end, '%m').'&search_datedelivery_end_year='.dol_print_date($search_datedelivery_end, '%Y'); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_company) $param .= '&search_company='.urlencode($search_company); - if ($search_company_alias) $param .= '&search_company_alias='.urlencode($search_company_alias); - if ($search_ref_customer) $param .= '&search_ref_customer='.urlencode($search_ref_customer); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); - if ($search_total_ht != '') $param .= '&search_total_ht='.urlencode($search_total_ht); - if ($search_total_vat != '') $param .= '&search_total_vat='.urlencode($search_total_vat); - if ($search_total_ttc != '') $param .= '&search_total_ttc='.urlencode($search_total_ttc); - if ($search_warehouse != '') $param .= '&search_warehouse='.urlencode($search_warehouse); - if ($search_login) $param .= '&search_login='.urlencode($search_login); - if ($search_multicurrency_code != '') $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); - if ($search_multicurrency_tx != '') $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); - if ($search_multicurrency_montant_ht != '') $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); - if ($search_multicurrency_montant_vat != '') $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); - if ($search_multicurrency_montant_ttc != '') $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); - if ($search_project_ref >= 0) $param .= "&search_project_ref=".urlencode($search_project_ref); - 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_type_thirdparty != '' && $search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); - if ($search_product_category != '') $param .= '&search_product_category='.urlencode($search_product_category); - if ($search_categ_cus > 0) $param .= '&search_categ_cus='.urlencode($search_categ_cus); - if ($show_files) $param .= '&show_files='.urlencode($show_files); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($search_billed != '') $param .= '&search_billed='.urlencode($search_billed); - if ($search_fk_cond_reglement > 0) $param .= '&search_fk_cond_reglement='.$search_fk_cond_reglement; - if ($search_fk_shipping_method > 0) $param .= '&search_fk_shipping_method='.$search_fk_shipping_method; - if ($search_fk_mode_reglement > 0) $param .= '&search_fk_mode_reglement='.$search_fk_mode_reglement; + 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 ($socid > 0) { + $param .= '&socid='.urlencode($socid); + } + if ($search_status != '') { + $param .= '&search_status='.urlencode($search_status); + } + if ($search_datecloture_start) { + $param .= '&search_datecloture_start='.urlencode($search_datecloture_start); + } + if ($search_datecloture_end) { + $param .= '&search_datecloture_end='.urlencode($search_datecloture_end); + } + if ($search_dateorder_start) { + $param .= '&search_dateorder_start_day='.dol_print_date($search_dateorder_start, '%d').'&search_dateorder_start_month='.dol_print_date($search_dateorder_start, '%m').'&search_dateorder_start_year='.dol_print_date($search_dateorder_start, '%Y'); + } + if ($search_dateorder_end) { + $param .= '&search_dateorder_end_day='.dol_print_date($search_dateorder_end, '%d').'&search_dateorder_end_month='.dol_print_date($search_dateorder_end, '%m').'&search_dateorder_end_year='.dol_print_date($search_dateorder_end, '%Y'); + } + if ($search_datedelivery_start) { + $param .= '&search_datedelivery_start_day='.dol_print_date($search_datedelivery_start, '%d').'&search_datedelivery_start_month='.dol_print_date($search_datedelivery_start, '%m').'&search_datedelivery_start_year='.dol_print_date($search_datedelivery_start, '%Y'); + } + if ($search_datedelivery_end) { + $param .= '&search_datedelivery_end_day='.dol_print_date($search_datedelivery_end, '%d').'&search_datedelivery_end_month='.dol_print_date($search_datedelivery_end, '%m').'&search_datedelivery_end_year='.dol_print_date($search_datedelivery_end, '%Y'); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_company) { + $param .= '&search_company='.urlencode($search_company); + } + if ($search_company_alias) { + $param .= '&search_company_alias='.urlencode($search_company_alias); + } + if ($search_ref_customer) { + $param .= '&search_ref_customer='.urlencode($search_ref_customer); + } + if ($search_user > 0) { + $param .= '&search_user='.urlencode($search_user); + } + if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); + } + if ($search_total_ht != '') { + $param .= '&search_total_ht='.urlencode($search_total_ht); + } + if ($search_total_vat != '') { + $param .= '&search_total_vat='.urlencode($search_total_vat); + } + if ($search_total_ttc != '') { + $param .= '&search_total_ttc='.urlencode($search_total_ttc); + } + if ($search_warehouse != '') { + $param .= '&search_warehouse='.urlencode($search_warehouse); + } + if ($search_login) { + $param .= '&search_login='.urlencode($search_login); + } + if ($search_multicurrency_code != '') { + $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); + } + if ($search_multicurrency_tx != '') { + $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); + } + if ($search_multicurrency_montant_ht != '') { + $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); + } + if ($search_multicurrency_montant_vat != '') { + $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); + } + if ($search_multicurrency_montant_ttc != '') { + $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); + } + if ($search_project_ref >= 0) { + $param .= "&search_project_ref=".urlencode($search_project_ref); + } + 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_type_thirdparty != '' && $search_type_thirdparty > 0) { + $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); + } + if ($search_product_category != '') { + $param .= '&search_product_category='.urlencode($search_product_category); + } + if ($search_categ_cus > 0) { + $param .= '&search_categ_cus='.urlencode($search_categ_cus); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($search_billed != '') { + $param .= '&search_billed='.urlencode($search_billed); + } + if ($search_fk_cond_reglement > 0) { + $param .= '&search_fk_cond_reglement='.$search_fk_cond_reglement; + } + if ($search_fk_shipping_method > 0) { + $param .= '&search_fk_shipping_method='.$search_fk_shipping_method; + } + if ($search_fk_mode_reglement > 0) { + $param .= '&search_fk_mode_reglement='.$search_fk_mode_reglement; + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -509,18 +705,28 @@ if ($resql) 'cancelorders'=>$langs->trans("Cancel"), 'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->facture->creer) $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisCustomer"); - if ($user->rights->commande->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete', 'createbills'))) $arrayofmassactions = array(); + if ($user->rights->facture->creer) { + $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisCustomer"); + } + if ($user->rights->commande->supprimer) { + $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); + } + if (in_array($massaction, array('presend', 'predelete', 'createbills'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $url = DOL_URL_ROOT.'/commande/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewOrder'), '', 'fa fa-plus-circle', $url, '', $contextpage == 'orderlist' && $user->rights->commande->creer); // Lines of title fields print ''; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; @@ -538,8 +744,7 @@ if ($resql) $trackid = 'ord'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($massaction == 'createbills') - { + if ($massaction == 'createbills') { //var_dump($_REQUEST); print ''; @@ -565,15 +770,17 @@ if ($resql) print $langs->trans('ValidateInvoices'); print '
    '; - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) { print $form->selectyesno('validate_invoices', 0, 1, 1); print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')'; } else { print $form->selectyesno('validate_invoices', 0, 1); } - if (!empty($conf->workflow->enabled) && !empty($conf->global->WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER)) print '     '.$langs->trans("IfValidateInvoiceIsNoOrderStayUnbilled").''; - else print '     '.$langs->trans("OptionToSetOrderBilledNotEnabled").''; + if (!empty($conf->workflow->enabled) && !empty($conf->global->WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER)) { + print '     '.$langs->trans("IfValidateInvoiceIsNoOrderStayUnbilled").''; + } else { + print '     '.$langs->trans("OptionToSetOrderBilledNotEnabled").''; + } print '
    '; @@ -586,34 +793,32 @@ if ($resql) print '
    '; } - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } $moreforfilter = ''; - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { - $langs->load("commercial"); + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) { + $langs->load("commercial"); $moreforfilter .= '
    '; - $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; + $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); - $moreforfilter .= '
    '; - } + $moreforfilter .= '
    '; + } // If the user can view other users - if ($user->rights->user->user->lire) - { + if ($user->rights->user->user->lire) { $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - $moreforfilter .= '
    '; + $moreforfilter .= '
    '; } // If the user can view prospects other than his' - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) - { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; @@ -621,29 +826,30 @@ if ($resql) $moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter .= '
    '; } - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) - { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; - $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; + $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; $moreforfilter .= $formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1); - $moreforfilter .= '
    '; + $moreforfilter .= ''; } if (!empty($conf->expedition->enabled) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $moreforfilter .= '
    '; - $moreforfilter .= $langs->trans('Warehouse').': '; + $moreforfilter .= $langs->trans('Warehouse').': '; $moreforfilter .= $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', '', 1); - $moreforfilter .= '
    '; + $moreforfilter .= ''; } $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)) - { + if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; @@ -668,71 +874,65 @@ if ($resql) print '
    '; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print ''; print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); print ''; print '
    '; print $form->selectDate($search_dateorder_start ? $search_dateorder_start : -1, 'search_dateorder_start_', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); @@ -742,8 +942,7 @@ if ($resql) print '
    '; print '
    '; print '
    '; print $form->selectDate($search_datedelivery_start ? $search_datedelivery_start : -1, 'search_datedelivery_start_', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); @@ -754,84 +953,72 @@ if ($resql) print '
    '; $form->selectShippingMethod($search_fk_shipping_method, 'search_fk_shipping_method', '', 1, '', 1); print ''; $form->select_conditions_paiements($search_fk_cond_reglement, 'search_fk_cond_reglement', -1, 1, 1); print ''; $form->select_types_paiements($search_fk_mode_reglement, 'search_fk_mode_reglement', '', 0, 1, 1, 0, -1); print ''; print ''; print ''; print ''; print ''; print ''; print ''; print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1); print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; @@ -844,20 +1031,17 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['c.datec']['checked'])) - { + if (!empty($arrayfields['c.datec']['checked'])) { print ''; print ''; print ''; print '
    '; print $form->selectDate($search_datecloture_start ? $search_datecloture_start : -1, 'search_datecloture_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); @@ -868,20 +1052,17 @@ if ($resql) print '
    '; print ''; print ''; //print $form->selectyesno('search_shippable', $search_shippable, 1, 0, 1, 1); if (!empty($conf->global->ORDER_SHIPABLE_STATUS_DISABLED_BY_DEFAULT)) { @@ -893,15 +1074,13 @@ if ($resql) print ''; print $form->selectyesno('search_billed', $search_billed, 1, 0, 1, 1); print ''; $liststatus = array( Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraftShort"), @@ -924,31 +1103,81 @@ if ($resql) // Fields title print '
    '; print $generic_commande->getNomUrl(1, ($search_status != 2 ? 0 : $obj->fk_statut), 0, 0, 0, 1, 1); @@ -1034,220 +1277,252 @@ if ($resql) print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); print ''.$obj->ref_client.''; - if ($obj->project_id > 0) - { + if ($obj->project_id > 0) { print $projectstatic->getNomUrl(1); } print ''; - if ($obj->project_id > 0) - { + if ($obj->project_id > 0) { print $projectstatic->title; } print ''; print $getNomUrl_cache[$obj->socid]; // If module invoices enabled and user with invoice creation permissions - if (!empty($conf->facture->enabled) && !empty($conf->global->ORDER_BILLING_ALL_CUSTOMER)) - { - if ($user->rights->facture->creer) - { - if (($obj->fk_statut > 0 && $obj->fk_statut < 3) || ($obj->fk_statut == 3 && $obj->billed == 0)) - { + if (!empty($conf->facture->enabled) && !empty($conf->global->ORDER_BILLING_ALL_CUSTOMER)) { + if ($user->rights->facture->creer) { + if (($obj->fk_statut > 0 && $obj->fk_statut < 3) || ($obj->fk_statut == 3 && $obj->billed == 0)) { print ' '; print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->name, 'object_bill', 'hideonsmartphone').''; } } } print ''; print $obj->alias; print ''; print $obj->town; print ''; print $obj->zip; print '".$obj->state_name."'; $tmparray = getCountry($obj->fk_pays, 'all'); print $tmparray['label']; print ''; - if (empty($typenArray)) $typenArray = $formcompany->typent_array(1); + if (empty($typenArray)) { + $typenArray = $formcompany->typent_array(1); + } print $typenArray[$obj->typent_code]; print ''; print dol_print_date($db->jdate($obj->date_commande), 'day'); print ''; print dol_print_date($db->jdate($obj->date_delivery), 'dayhour'); print ''; $form->formSelectShippingMethod('', $obj->fk_shipping_method, 'none', 1); print ''; $form->form_conditions_reglement($_SERVER['PHP_SELF'], $obj->fk_cond_reglement, 'none'); print ''; $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); print ''.price($obj->total_ht)."'.price($obj->total_tva)."'.price($obj->total_ttc)."'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."'; $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code); print "'.price($obj->multicurrency_total_ht)."'.price($obj->multicurrency_total_vat)."'.price($obj->multicurrency_total_ttc)."'; - if ($userstatic->id) print $userstatic->getLoginUrl(1); - else print ' '; + if ($userstatic->id) { + print $userstatic->getLoginUrl(1); + } else { + print ' '; + } print "'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_cloture), 'dayhour', 'tzuser'); print ''; print dol_escape_htmltag($obj->note_public); print ''; print dol_escape_htmltag($obj->note_private); print ''; if (!empty($show_shippable_command) && !empty($conf->stock->enabled)) { if (($obj->fk_statut > $generic_commande::STATUS_DRAFT) && ($obj->fk_statut < $generic_commande::STATUS_CLOSED)) { @@ -1312,8 +1591,7 @@ if ($resql) $numlines = count($generic_commande->lines); // Loop on each line of order for ($lig = 0; $lig < $numlines; $lig++) { - if ($generic_commande->lines[$lig]->product_type == 0 && $generic_commande->lines[$lig]->fk_product > 0) // If line is a product and not a service - { + if ($generic_commande->lines[$lig]->product_type == 0 && $generic_commande->lines[$lig]->fk_product > 0) { // If line is a product and not a service $nbprod++; // order contains real products $generic_product->id = $generic_commande->lines[$lig]->fk_product; @@ -1327,8 +1605,7 @@ if ($resql) $generic_product->stock_theorique = $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; } - if (empty($conf->global->SHIPPABLE_ORDER_ICON_IN_LIST)) // Default code. Default should be this case. - { + if (empty($conf->global->SHIPPABLE_ORDER_ICON_IN_LIST)) { // Default code. Default should be this case. $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->product_ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); $text_info .= ' - '.$langs->trans("Stock").': '.$generic_product->stock_reel.''; $text_info .= ' - '.$langs->trans("VirtualStock").': '.$generic_product->stock_theorique.''; @@ -1344,8 +1621,7 @@ if ($resql) // stock order and stock order_supplier $stock_order = 0; $stock_order_supplier = 0; - if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) // What about other options ? - { + if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { // What about other options ? if (!empty($conf->commande->enabled)) { if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'])) { $generic_product->load_stats_commande(0, '1,2'); @@ -1405,28 +1681,33 @@ if ($resql) } // Billed - if (!empty($arrayfields['c.facture']['checked'])) - { + if (!empty($arrayfields['c.facture']['checked'])) { print ''.yn($obj->billed).''.$generic_commande->LibStatut($obj->fk_statut, $obj->billed, 5, 1).''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '
    '; print ''; // Company print ''; // ThirdParty Type print ''; // Category -if ($mode == 'customer') -{ +if ($mode == 'customer') { $cat_type = Categorie::TYPE_CUSTOMER; $cat_label = $langs->trans("Category").' '.lcfirst($langs->trans("Customer")); } -if ($mode == 'supplier') -{ +if ($mode == 'supplier') { $cat_type = Categorie::TYPE_SUPPLIER; - $cat_label = $langs->trans("Category").' '.lcfirst($langs->trans("Supplier")); + $cat_label = $langs->trans("Category").' '.lcfirst($langs->trans("Supplier")); } print ''; // Year print ''; @@ -335,11 +366,9 @@ print ''; print ''; $oldyear = 0; -foreach ($data as $val) -{ +foreach ($data as $val) { $year = $val['year']; - while (!empty($year) && $oldyear > $year + 1) - { // If we have empty year + while (!empty($year) && $oldyear > $year + 1) { // If we have empty year $oldyear--; print ''; @@ -375,7 +404,9 @@ print '
    '; // Show graphs print '
    '.$langs->trans("Filter").'
    '.$langs->trans("ThirdParty").''; -if ($mode == 'customer') $filter = 's.client IN (1,2,3)'; -if ($mode == 'supplier') $filter = 's.fournisseur = 1'; +if ($mode == 'customer') { + $filter = 's.client IN (1,2,3)'; +} +if ($mode == 'supplier') { + $filter = 's.fournisseur = 1'; +} print $form->select_company($socid, 'socid', $filter, 1, 0, 0, array(), 0, '', 'style="width: 95%"'); print '
    '.$langs->trans("ThirdPartyType").''; $sortparam_typent = (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label. print $form->selectarray("typent_id", $formcompany->typent_array(0), $typent_id, 1, 0, 0, '', 0, 0, 0, $sortparam_typent, '', 1); -if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); +if ($user->admin) { + print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); +} print '
    '.$cat_label.''; print $formother->select_categories($cat_type, $categ_id, 'categ_id', true); @@ -293,8 +322,7 @@ print '
    '.$langs->trans("CreatedBy").' print $form->select_dolusers($userid, 'userid', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); // Status print '
    '.$langs->trans("Status").''; -if ($mode == 'customer') -{ +if ($mode == 'customer') { $liststatus = array( Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraft"), Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"), @@ -304,15 +332,18 @@ if ($mode == 'customer') ); print $form->selectarray('object_status', $liststatus, GETPOST('object_status', 'intcomma'), -4); } -if ($mode == 'supplier') -{ +if ($mode == 'supplier') { $formorder->selectSupplierOrderStatus((strstr($object_status, ',') ? -1 : $object_status), 0, 'object_status'); } print '
    '.$langs->trans("Year").''; -if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; -if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} +if (!in_array($nowyear, $arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print '
    %
    '; echo ''; print ''; print ''; - if (!empty($conf->multicurrency->enabled)) print ''; + if (!empty($conf->multicurrency->enabled)) { + print ''; + } print ''; - if ($result) - { + if ($result) { $TData = dol_sort_array($filesarray, $sortfield, $sortorder); - if (empty($TData)) - { + if (empty($TData)) { print ''; if (!empty($conf->multicurrency->enabled)) { print ''; @@ -638,8 +649,7 @@ if (!empty($date_start) && !empty($date_stop)) $totalVAT_credit = 0; // Display array - foreach ($TData as $data) - { + foreach ($TData as $data) { $html_class = ''; //if (!empty($data['fk_facture'])) $html_class = 'facid-'.$data['fk_facture']; //elseif (!empty($data['fk_paiement'])) $html_class = 'payid-'.$data['fk_paiement']; @@ -684,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']; @@ -708,9 +718,8 @@ if (!empty($date_start) && !empty($date_stop)) // File link print ''; // Bank - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print ''; + print '\n"; + print ''; // Number - if (!empty($conf->banque->enabled)) - { - // Number + if (!empty($conf->banque->enabled)) { print ''; print ''."\n"; + + // Check transmitter + print ''; + print ''; + + // Bank name + print ''; + print ''; } // Accountancy account @@ -443,8 +483,7 @@ if ($action == 'create') print ''; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); // Associated project @@ -489,26 +528,24 @@ if ($action == 'create') /* */ /* ************************************************************************** */ -if ($id) -{ +if ($id) { $alreadyaccounted = $object->getVentilExportCompta(); $head = various_payment_prepare_head($object); // Clone confirmation - if ($action === 'clone') - { - $set_value_help = $form->textwithpicto('', $langs->trans($langs->trans("AccountingDirectionHelp"))); - $sensarray = array('0' => $langs->trans("Debit"), '1' => $langs->trans("Credit")); + if ($action === 'clone') { + $set_value_help = $form->textwithpicto('', $langs->trans($langs->trans("AccountingDirectionHelp"))); + $sensarray = array('0' => $langs->trans("Debit"), '1' => $langs->trans("Credit")); $formquestion = array( array('type' => 'text', 'name' => 'clone_label', 'label' => $langs->trans("Label"), 'value' => $langs->trans("CopyOf").' '.$object->label), - array('type' => 'date', 'tdclass'=>'fieldrequired', 'name' => 'clone_date_payment', 'label' => $langs->trans("DatePayment"), 'value' => -1), - array('type' => 'date', 'name' => 'clone_date_value', 'label' => $langs->trans("DateValue"), 'value' => -1), - array('type' => 'other', 'tdclass'=>'fieldrequired', 'name' => 'clone_accountid', 'label' => $langs->trans("BankAccount"), 'value' => $form->select_comptes($object->fk_account, "accountid", 0, '', 1, '', 0, 'minwidth200', 1)), - array('type' => 'text', 'name' => 'clone_amount', 'label' => $langs->trans("Amount"), 'value' => price($object->amount)), - array('type' => 'select', 'name' => 'clone_sens', 'label' => $langs->trans("Sens") . ' ' . $set_value_help, 'values' => $sensarray, 'default' => $object->sens), - ); + array('type' => 'date', 'tdclass'=>'fieldrequired', 'name' => 'clone_date_payment', 'label' => $langs->trans("DatePayment"), 'value' => -1), + array('type' => 'date', 'name' => 'clone_date_value', 'label' => $langs->trans("DateValue"), 'value' => -1), + array('type' => 'other', 'tdclass'=>'fieldrequired', 'name' => 'clone_accountid', 'label' => $langs->trans("BankAccount"), 'value' => $form->select_comptes($object->fk_account, "accountid", 0, '', 1, '', 0, 'minwidth200', 1)), + array('type' => 'text', 'name' => 'clone_amount', 'label' => $langs->trans("Amount"), 'value' => price($object->amount)), + array('type' => 'select', 'name' => 'clone_sens', 'label' => $langs->trans("Sens") . ' ' . $set_value_help, 'values' => $sensarray, 'default' => $object->sens), + ); print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneVariousPayment', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 350); } @@ -517,12 +554,10 @@ if ($id) $morehtmlref = '
    '; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= $langs->trans('Project').' '; - if ($user->rights->banque->modifier) - { + if ($user->rights->banque->modifier) { if ($action != 'classify') { $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; } @@ -572,7 +607,11 @@ if ($id) print ''; // Debit / Credit - if ($object->sens == '1') $sens = $langs->trans("Credit"); else $sens = $langs->trans("Debit"); + if ($object->sens == '1') { + $sens = $langs->trans("Credit"); + } else { + $sens = $langs->trans("Debit"); + } print '
    '; print ''; @@ -581,8 +620,7 @@ if ($id) print ''; - if (!empty($conf->banque->enabled)) - { - if ($object->fk_account > 0) - { + if (!empty($conf->banque->enabled)) { + if ($object->fk_account > 0) { $bankline = new AccountLine($db); $bankline->fetch($object->fk_bank); @@ -629,7 +665,7 @@ if ($id) /* - * Action buttons + * Action bar */ print '
    '."\n"; @@ -637,16 +673,13 @@ if ($id) // Add button modify // Clone - if ($user->rights->banque->modifier) - { + if ($user->rights->banque->modifier) { print '"; } // Delete - if (empty($object->rappro)) - { - if (!empty($user->rights->banque->modifier)) - { + if (empty($object->rappro)) { + if (!empty($user->rights->banque->modifier)) { if ($alreadyaccounted) { print ''; } else { diff --git a/htdocs/compta/bank/various_payment/document.php b/htdocs/compta/bank/various_payment/document.php index 14187bf51e3..98486b67287 100644 --- a/htdocs/compta/bank/various_payment/document.php +++ b/htdocs/compta/bank/various_payment/document.php @@ -39,7 +39,9 @@ $confirm = GETPOST('confirm', 'alpha'); // Security check $socid = GETPOST("socid", "int"); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'banque', '', '', ''); // Get parameters @@ -47,12 +49,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) { $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"; +} $object = new PaymentVarious($db); @@ -66,7 +74,7 @@ $modulepart = 'banque'; * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -79,20 +87,17 @@ $title = $langs->trans("VariousPayment").' - '.$langs->trans("Documents"); $help_url = ''; llxHeader("", $title, $help_url); -if ($object->id) -{ +if ($object->id) { $head = various_payment_prepare_head($object); print dol_get_fiche_head($head, 'documents', $langs->trans("VariousPayment"), -1, $object->picto); $morehtmlref = '
    '; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= $langs->trans('Project').' : '; - if ($user->rights->banque->modifier && 0) - { + if ($user->rights->banque->modifier && 0) { if ($action != 'classify') { $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; } @@ -128,8 +133,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/compta/bank/various_payment/info.php b/htdocs/compta/bank/various_payment/info.php index 5d401ede3c1..b173426e179 100644 --- a/htdocs/compta/bank/various_payment/info.php +++ b/htdocs/compta/bank/various_payment/info.php @@ -35,7 +35,9 @@ $action = GETPOST('action', 'aZ09'); // Security check $socid = GETPOST("socid", "int"); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'banque', '', '', ''); /* @@ -55,12 +57,10 @@ print dol_get_fiche_head($head, 'info', $langs->trans("VariousPayment"), -1, $ob $morehtmlref = '
    '; // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= $langs->trans('Project').' : '; - if ($user->rights->banque->modifier && 0) - { + if ($user->rights->banque->modifier && 0) { if ($action != 'classify') { $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; } diff --git a/htdocs/compta/bank/various_payment/list.php b/htdocs/compta/bank/various_payment/list.php index 0d91eb38e7d..39cbb91fde1 100644 --- a/htdocs/compta/bank/various_payment/list.php +++ b/htdocs/compta/bank/various_payment/list.php @@ -37,7 +37,9 @@ $langs->loadLangs(array("compta", "banks", "bills", "accountancy")); // Security check $socid = GETPOST("socid", "int"); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'banque', '', '', ''); $optioncss = GETPOST('optioncss', 'alpha'); @@ -55,37 +57,58 @@ $search_amount_cred = GETPOST('search_amount_cred', 'alpha'); $search_bank_account = GETPOST('search_account', 'int'); $search_bank_entry = GETPOST('search_bank_entry', 'int'); $search_accountancy_account = GETPOST("search_accountancy_account"); -if ($search_accountancy_account == - 1) $search_accountancy_account = ''; +if ($search_accountancy_account == - 1) { + $search_accountancy_account = ''; +} $search_accountancy_subledger = GETPOST("search_accountancy_subledger"); -if ($search_accountancy_subledger == - 1) $search_accountancy_subledger = ''; +if ($search_accountancy_subledger == - 1) { + $search_accountancy_subledger = ''; +} +if (empty($search_datep_start)) { + $search_datep_start = GETPOST("search_datep_start", 'int'); +} +if (empty($search_datep_end)) { + $search_datep_end = GETPOST("search_datep_end", 'int'); +} +if (empty($search_datev_start)) { + $search_datev_start = GETPOST("search_datev_start", 'int'); +} +if (empty($search_datev_end)) { + $search_datev_end = GETPOST("search_datev_end", 'int'); +} $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 = "v.datep,v.rowid"; -if (!$sortorder) $sortorder = "DESC,DESC"; +if (!$sortfield) { + $sortfield = "v.datep,v.rowid"; +} +if (!$sortorder) { + $sortorder = "DESC,DESC"; +} $filtre = GETPOST("filtre", 'alpha'); -if (!GETPOST('typeid')) -{ +if (!GETPOST('typeid')) { $newfiltre = str_replace('filtre=', '', $filtre); $filterarray = explode('-', $newfiltre); - foreach ($filterarray as $val) - { + foreach ($filterarray as $val) { $part = explode(':', $val); - if ($part[0] == 'v.fk_typepayment') $typeid = $part[1]; + if ($part[0] == 'v.fk_typepayment') { + $typeid = $part[1]; + } } } else { $typeid = GETPOST('typeid'); } -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers $search_ref = ''; $search_label = ''; $search_datep_start = ''; @@ -156,7 +179,9 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); $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)) { // Selection of new fields @@ -168,13 +193,27 @@ if (empty($reshook)) { */ $form = new Form($db); -if ($arrayfields['account']['checked'] || $arrayfields['subledger']['checked']) $formaccounting = new FormAccounting($db); -if ($arrayfields['bank']['checked'] && !empty($conf->accounting->enabled)) $accountingjournal = new AccountingJournal($db); -if ($arrayfields['ref']['checked']) $variousstatic = new PaymentVarious($db); -if ($arrayfields['bank']['checked']) $accountstatic = new Account($db); -if ($arrayfields['project']['checked']) $proj = new Project($db); -if ($arrayfields['entry']['checked']) $bankline = new AccountLine($db); -if ($arrayfields['account']['checked']) $accountingaccount = new AccountingAccount($db); +if ($arrayfields['account']['checked'] || $arrayfields['subledger']['checked']) { + $formaccounting = new FormAccounting($db); +} +if ($arrayfields['bank']['checked'] && !empty($conf->accounting->enabled)) { + $accountingjournal = new AccountingJournal($db); +} +if ($arrayfields['ref']['checked']) { + $variousstatic = new PaymentVarious($db); +} +if ($arrayfields['bank']['checked']) { + $accountstatic = new Account($db); +} +if ($arrayfields['project']['checked']) { + $proj = new Project($db); +} +if ($arrayfields['entry']['checked']) { + $bankline = new AccountLine($db); +} +if ($arrayfields['account']['checked']) { + $accountingaccount = new AccountingAccount($db); +} $sql = "SELECT v.rowid, v.sens, v.amount, v.label, v.datep as datep, v.datev as datev, v.fk_typepayment as type, v.num_payment, v.fk_bank, v.accountancy_code, v.subledger_account, v.fk_projet as fk_project,"; $sql .= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number as bank_account_number, ba.fk_accountancy_journal as accountancy_journal, ba.label as blabel,"; @@ -186,43 +225,68 @@ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.ro $sql .= " WHERE v.entity IN (".getEntity('payment_various').")"; // Search criteria -if ($search_ref) $sql .= " AND v.rowid=".$db->escape($search_ref); -if ($search_label) $sql .= natural_search(array('v.label'), $search_label); -if ($search_datep_start) $sql .= " AND v.datep >= '".$db->idate($search_datep_start)."'"; -if ($search_datep_end) $sql .= " AND v.datep <= '".$db->idate($search_datep_end)."'"; -if ($search_datev_start) $sql .= " AND v.datev >= '".$db->idate($search_datev_start)."'"; -if ($search_datev_end) $sql .= " AND v.datev <= '".$db->idate($search_datev_end)."'"; -if ($search_amount_deb) $sql .= natural_search("v.amount", $search_amount_deb, 1); -if ($search_amount_cred) $sql .= natural_search("v.amount", $search_amount_cred, 1); -if ($search_bank_account > 0) $sql .= " AND b.fk_account=".$db->escape($search_bank_account); -if ($search_bank_entry > 0) $sql .= " AND b.fk_account=".$db->escape($search_bank_account); -if ($search_accountancy_account > 0) $sql .= " AND v.accountancy_code=".$db->escape($search_accountancy_account); -if ($search_accountancy_subledger > 0) $sql .= " AND v.subledger_account=".$db->escape($search_accountancy_subledger); -if ($typeid > 0) $sql .= " AND v.fk_typepayment=".$typeid; +if ($search_ref) { + $sql .= " AND v.rowid=".$db->escape($search_ref); +} +if ($search_label) { + $sql .= natural_search(array('v.label'), $search_label); +} +if ($search_datep_start) { + $sql .= " AND v.datep >= '".$db->idate($search_datep_start)."'"; +} +if ($search_datep_end) { + $sql .= " AND v.datep <= '".$db->idate($search_datep_end)."'"; +} +if ($search_datev_start) { + $sql .= " AND v.datev >= '".$db->idate($search_datev_start)."'"; +} +if ($search_datev_end) { + $sql .= " AND v.datev <= '".$db->idate($search_datev_end)."'"; +} +if ($search_amount_deb) { + $sql .= natural_search("v.amount", $search_amount_deb, 1); +} +if ($search_amount_cred) { + $sql .= natural_search("v.amount", $search_amount_cred, 1); +} +if ($search_bank_account > 0) { + $sql .= " AND b.fk_account=".$db->escape($search_bank_account); +} +if ($search_bank_entry > 0) { + $sql .= " AND b.fk_account=".$db->escape($search_bank_account); +} +if ($search_accountancy_account > 0) { + $sql .= " AND v.accountancy_code=".$db->escape($search_accountancy_account); +} +if ($search_accountancy_subledger > 0) { + $sql .= " AND v.subledger_account=".$db->escape($search_accountancy_subledger); +} +if ($typeid > 0) { + $sql .= " AND v.fk_typepayment=".$typeid; +} if ($filtre) { $filtre = str_replace(":", "=", $filtre); $sql .= " AND ".$filtre; } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} $sql .= $db->order($sortfield, $sortorder); $totalnboflines = 0; $result = $db->query($sql); -if ($result) -{ +if ($result) { $totalnboflines = $db->num_rows($result); } $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); // Direct jump if only one record found - if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) - { + if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($result); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/compta/bank/various_payment/card.php?id='.$id); @@ -236,30 +300,64 @@ if ($result) $total = 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 ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_label) $param .= '&search_label='.urlencode($search_label); - if ($search_datep_start) $param .= '&search_datep_start='.urlencode($search_datep_start); - if ($search_datep_end) $param .= '&search_datep_end='.urlencode($search_datep_end); - if ($search_datev_start) $param .= '&search_datev_start='.urlencode($search_datev_start); - if ($search_datev_end) $param .= '&search_datev_end='.urlencode($search_datev_end); - if ($typeid > 0) $param .= '&typeid='.urlencode($typeid); - if ($search_amount_deb) $param .= '&search_amount_deb='.urlencode($search_amount_deb); - if ($search_amount_cred) $param .= '&search_amount_cred='.urlencode($search_amount_cred); - if ($search_bank_account > 0) $param .= '&search_amount='.urlencode($search_bank_account); - if ($search_accountancy_account > 0) $param .= '&search_accountancy_account='.urlencode($search_accountancy_account); - if ($search_accountancy_subledger > 0) $param .= '&search_accountancy_subledger='.urlencode($search_accountancy_subledger); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_label) { + $param .= '&search_label='.urlencode($search_label); + } + if ($search_datep_start) { + $param .= '&search_datep_start='.urlencode($search_datep_start); + } + if ($search_datep_end) { + $param .= '&search_datep_end='.urlencode($search_datep_end); + } + if ($search_datev_start) { + $param .= '&search_datev_start='.urlencode($search_datev_start); + } + if ($search_datev_end) { + $param .= '&search_datev_end='.urlencode($search_datev_end); + } + if ($typeid > 0) { + $param .= '&typeid='.urlencode($typeid); + } + if ($search_amount_deb) { + $param .= '&search_amount_deb='.urlencode($search_amount_deb); + } + if ($search_amount_cred) { + $param .= '&search_amount_cred='.urlencode($search_amount_cred); + } + if ($search_bank_account > 0) { + $param .= '&search_account='.urlencode($search_bank_account); + } + if ($search_accountancy_account > 0) { + $param .= '&search_accountancy_account='.urlencode($search_accountancy_account); + } + if ($search_accountancy_subledger > 0) { + $param .= '&search_accountancy_subledger='.urlencode($search_accountancy_subledger); + } - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } $url = DOL_URL_ROOT.'/compta/bank/various_payment/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('MenuNewVariousPayment'), '', 'fa fa-plus-circle', $url, '', $user->rights->banque->modifier); print ''; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; @@ -269,9 +367,10 @@ if ($result) print_barre_liste($langs->trans("MenuVariousPayment"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, 'object_payment', 0, $newcardbutton, '', $limit, 0, 0, 1); - if ($search_all) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; } @@ -395,20 +494,46 @@ if ($result) print '
    '; - if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { + print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); + } - if ($arrayfields['ref']['checked']) print_liste_field_titre($arrayfields['ref']['label'], $_SERVER["PHP_SELF"], 'v.rowid', '', $param, '', $sortfield, $sortorder); - if ($arrayfields['label']['checked']) print_liste_field_titre($arrayfields['label']['label'], $_SERVER["PHP_SELF"], 'v.label', '', $param, '', $sortfield, $sortorder, 'left '); - if ($arrayfields['datep']['checked']) print_liste_field_titre($arrayfields['datep']['label'], $_SERVER["PHP_SELF"], 'v.datep,v.rowid', '', $param, '', $sortfield, $sortorder, 'center '); - if ($arrayfields['datev']['checked']) print_liste_field_titre($arrayfields['datev']['label'], $_SERVER["PHP_SELF"], 'v.datev,v.rowid', '', $param, '', $sortfield, $sortorder, 'center '); - if ($arrayfields['type']['checked']) print_liste_field_titre($arrayfields['type']['label'], $_SERVER["PHP_SELF"], 'type', '', $param, '', $sortfield, $sortorder, 'left '); - if ($arrayfields['project']['checked']) print_liste_field_titre($arrayfields['project']['label'], $_SERVER["PHP_SELF"], 'fk_project', '', $param, '', $sortfield, $sortorder); - if ($arrayfields['bank']['checked']) print_liste_field_titre($arrayfields['bank']['label'], $_SERVER["PHP_SELF"], 'ba.label', '', $param, '', $sortfield, $sortorder); - if ($arrayfields['entry']['checked']) print_liste_field_titre($arrayfields['entry']['label'], $_SERVER["PHP_SELF"], 'ba.label', '', $param, '', $sortfield, $sortorder); - if ($arrayfields['account']['checked']) print_liste_field_titre($arrayfields['account']['label'], $_SERVER["PHP_SELF"], 'v.accountancy_code', '', $param, '', $sortfield, $sortorder, 'left '); - if ($arrayfields['subledger']['checked']) print_liste_field_titre($arrayfields['subledger']['label'], $_SERVER["PHP_SELF"], 'v.subledger_account', '', $param, '', $sortfield, $sortorder, 'left '); - if ($arrayfields['debit']['checked']) print_liste_field_titre($arrayfields['debit']['label'], $_SERVER["PHP_SELF"], 'v.amount', '', $param, '', $sortfield, $sortorder, 'right '); - if ($arrayfields['credit']['checked']) print_liste_field_titre($arrayfields['credit']['label'], $_SERVER["PHP_SELF"], 'v.amount', '', $param, '', $sortfield, $sortorder, 'right '); + if ($arrayfields['ref']['checked']) { + print_liste_field_titre($arrayfields['ref']['label'], $_SERVER["PHP_SELF"], 'v.rowid', '', $param, '', $sortfield, $sortorder); + } + if ($arrayfields['label']['checked']) { + print_liste_field_titre($arrayfields['label']['label'], $_SERVER["PHP_SELF"], 'v.label', '', $param, '', $sortfield, $sortorder, 'left '); + } + if ($arrayfields['datep']['checked']) { + print_liste_field_titre($arrayfields['datep']['label'], $_SERVER["PHP_SELF"], 'v.datep,v.rowid', '', $param, '', $sortfield, $sortorder, 'center '); + } + if ($arrayfields['datev']['checked']) { + print_liste_field_titre($arrayfields['datev']['label'], $_SERVER["PHP_SELF"], 'v.datev,v.rowid', '', $param, '', $sortfield, $sortorder, 'center '); + } + if ($arrayfields['type']['checked']) { + print_liste_field_titre($arrayfields['type']['label'], $_SERVER["PHP_SELF"], 'type', '', $param, '', $sortfield, $sortorder, 'left '); + } + if ($arrayfields['project']['checked']) { + print_liste_field_titre($arrayfields['project']['label'], $_SERVER["PHP_SELF"], 'fk_project', '', $param, '', $sortfield, $sortorder); + } + if ($arrayfields['bank']['checked']) { + print_liste_field_titre($arrayfields['bank']['label'], $_SERVER["PHP_SELF"], 'ba.label', '', $param, '', $sortfield, $sortorder); + } + if ($arrayfields['entry']['checked']) { + print_liste_field_titre($arrayfields['entry']['label'], $_SERVER["PHP_SELF"], 'ba.label', '', $param, '', $sortfield, $sortorder); + } + if ($arrayfields['account']['checked']) { + print_liste_field_titre($arrayfields['account']['label'], $_SERVER["PHP_SELF"], 'v.accountancy_code', '', $param, '', $sortfield, $sortorder, 'left '); + } + if ($arrayfields['subledger']['checked']) { + print_liste_field_titre($arrayfields['subledger']['label'], $_SERVER["PHP_SELF"], 'v.subledger_account', '', $param, '', $sortfield, $sortorder, 'left '); + } + if ($arrayfields['debit']['checked']) { + print_liste_field_titre($arrayfields['debit']['label'], $_SERVER["PHP_SELF"], 'v.amount', '', $param, '', $sortfield, $sortorder, 'right '); + } + if ($arrayfields['credit']['checked']) { + print_liste_field_titre($arrayfields['credit']['label'], $_SERVER["PHP_SELF"], 'v.amount', '', $param, '', $sortfield, $sortorder, 'right '); + } // Fields from hook $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); @@ -420,8 +545,7 @@ if ($result) $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($result); $variousstatic->id = $obj->rowid; @@ -438,26 +562,34 @@ if ($result) // Ref if ($arrayfields['ref']['checked']) { print '"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Label payment if ($arrayfields['label']['checked']) { print '"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date payment if ($arrayfields['datep']['checked']) { print '"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date value if ($arrayfields['datev']['checked']) { print '"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type @@ -469,7 +601,9 @@ if ($result) } print $obj->num_payment; print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Project @@ -480,14 +614,15 @@ if ($result) print $proj->getNomUrl(1); } print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Bank account if ($arrayfields['bank']['checked']) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Bank entry if ($arrayfields['entry']['checked']) { $bankline->fetch($obj->fk_bank); print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Accounting account @@ -519,44 +658,56 @@ if ($result) $accountingaccount->fetch('', $obj->accountancy_code, 1); print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Accounting subledger account if ($arrayfields['subledger']['checked']) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Debit if ($arrayfields['debit']['checked']) { print ''; } // Credit if ($arrayfields['credit']['checked']) { print ''; } print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print ""; diff --git a/htdocs/compta/cashcontrol/cashcontrol_card.php b/htdocs/compta/cashcontrol/cashcontrol_card.php index ad88e928b6b..ccaa0158af2 100644 --- a/htdocs/compta/cashcontrol/cashcontrol_card.php +++ b/htdocs/compta/cashcontrol/cashcontrol_card.php @@ -49,30 +49,33 @@ $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 = 'rowid'; -if (!$sortorder) $sortorder = 'ASC'; +if (!$sortfield) { + $sortfield = 'rowid'; +} +if (!$sortorder) { + $sortorder = 'ASC'; +} $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'thirdpartylist'; -if ($contextpage == 'takepos') -{ +if ($contextpage == 'takepos') { $_GET['optioncss'] = 'print'; } -// Security check -if (!$user->rights->cashdesk->run && !$user->rights->takepos->run) -{ - accessforbidden(); -} - $arrayofpaymentmode = array('cash'=>'Cash', 'cheque'=>'Cheque', 'card'=>'CreditCard'); $arrayofposavailable = array(); -if (!empty($conf->cashdesk->enabled)) $arrayofposavailable['cashdesk'] = $langs->trans('CashDesk').' (cashdesk)'; -if (!empty($conf->takepos->enabled)) $arrayofposavailable['takepos'] = $langs->trans('TakePOS').' (takepos)'; +if (!empty($conf->cashdesk->enabled)) { + $arrayofposavailable['cashdesk'] = $langs->trans('CashDesk').' (cashdesk)'; +} +if (!empty($conf->takepos->enabled)) { + $arrayofposavailable['takepos'] = $langs->trans('TakePOS').' (takepos)'; +} // TODO Add hook here to allow other POS to add themself $object = new CashControl($db); @@ -87,6 +90,15 @@ $hookmanager->initHooks(array('cashcontrolcard', 'globalcard')); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. +// Security check +if ($user->socid > 0) { // Protection if external user + //$socid = $user->socid; + accessforbidden(); +} +if (!$user->rights->cashdesk->run && !$user->rights->takepos->run) { + accessforbidden(); +} + /* * Actions @@ -94,18 +106,18 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ $permissiontoadd = ($user->rights->cashdesk->run || $user->rights->takepos->run); $permissiontodelete = ($user->rights->cashdesk->run || $user->rights->takepos->run) || ($permissiontoadd && $object->status == 0); -if (empty($backtopage)) $backtopage = dol_buildpath('/compta/cashcontrol/cashcontrol_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); +if (empty($backtopage)) { + $backtopage = dol_buildpath('/compta/cashcontrol/cashcontrol_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); +} $backurlforlist = dol_buildpath('/compta/cashcontrol/cashcontrol_list.php', 1); $triggermodname = 'CACHCONTROL_MODIFY'; // Name of trigger action code to execute when we modify record -if (empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH) && empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH1)) -{ +if (empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH) && empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH1)) { setEventMessages($langs->trans("CashDesk")." - ".$langs->trans("NotConfigured"), null, 'errors'); } -if (GETPOST('cancel', 'alpha')) -{ +if (GETPOST('cancel', 'alpha')) { if ($action == 'valid') { $action = 'view'; } else { @@ -113,8 +125,7 @@ if (GETPOST('cancel', 'alpha')) } } -if ($action == "reopen") -{ +if ($action == "reopen") { $result = $object->setStatut($object::STATUS_DRAFT, null, '', 'CASHFENCE_REOPEN'); if ($result < 0) { dol_print_error($db, $object->error, $object->error); @@ -123,43 +134,35 @@ if ($action == "reopen") $action = 'view'; } -if ($action == "start") -{ +if ($action == "start") { $error = 0; - if (!GETPOST('posmodule', 'alpha') || GETPOST('posmodule', 'alpha') == '-1') - { + if (!GETPOST('posmodule', 'alpha') || GETPOST('posmodule', 'alpha') == '-1') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Module")), null, 'errors'); $action = 'create'; $error++; } - if (GETPOST('posnumber', 'alpha') == '') - { + if (GETPOST('posnumber', 'alpha') == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CashDesk")), null, 'errors'); $action = 'create'; $error++; } - if (!GETPOST('closeyear', 'alpha') || GETPOST('closeyear', 'alpha') == '-1') - { + if (!GETPOST('closeyear', 'alpha') || GETPOST('closeyear', 'alpha') == '-1') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Year")), null, 'errors'); $action = 'create'; $error++; } -} elseif ($action == "add") -{ - if (GETPOST('opening', 'alpha') == '') - { +} elseif ($action == "add") { + if (GETPOST('opening', 'alpha') == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InitialBankBalance")), null, 'errors'); $action = 'start'; $error++; } $error = 0; - foreach ($arrayofpaymentmode as $key=>$val) - { + foreach ($arrayofpaymentmode as $key => $val) { $object->$key = price2num(GETPOST($key.'_amount', 'alpha')); } - if (!$error) - { + if (!$error) { $object->day_close = GETPOST('closeday', 'int'); $object->month_close = GETPOST('closemonth', 'int'); $object->year_close = GETPOST('closeyear', 'int'); @@ -172,8 +175,7 @@ if ($action == "start") $id = $object->create($user); - if ($id > 0) - { + if ($id > 0) { $db->commit(); $action = "view"; } else { @@ -190,8 +192,7 @@ if ($action == "start") } } -if ($action == "valid") // validate = close -{ +if ($action == "valid") { // validate = close $object->fetch($id); $db->begin(); @@ -210,8 +211,7 @@ if ($action == "valid") // validate = close $result = $object->valid($user); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); $db->rollback(); } else { @@ -230,27 +230,27 @@ if ($action == "valid") // validate = close } // Action to delete -if ($action == 'confirm_delete' && !empty($permissiontodelete)) -{ +if ($action == 'confirm_delete' && !empty($permissiontodelete)) { $object->fetch($id); - if (!($object->id > 0)) - { + if (!($object->id > 0)) { dol_print_error('', 'Error, object must be fetched before being deleted'); exit; } $result = $object->delete($user); //var_dump($result); - if ($result > 0) - { + if ($result > 0) { // Delete OK setEventMessages("RecordDeleted", null, 'mesgs'); header("Location: ".$backurlforlist); exit; } else { - if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); + if (!empty($object->errors)) { + setEventMessages(null, $object->errors, 'errors'); + } else { + setEventMessages($object->error, null, 'errors'); + } } } @@ -265,8 +265,7 @@ $initialbalanceforterminal = array(); $theoricalamountforterminal = array(); $theoricalnbofinvoiceforterminal = array(); -if ($action == "create" || $action == "start" || $action == 'close') -{ +if ($action == "create" || $action == "start" || $action == 'close') { if ($action == 'close') { $posmodule = $object->posmodule; $terminalid = $object->posnumber; @@ -275,13 +274,14 @@ if ($action == "create" || $action == "start" || $action == 'close') $syear = $object->year_close; $smonth = $object->month_close; $sday = $object->day_close; - } elseif (GETPOST('posnumber', 'alpha') != '' && GETPOST('posnumber', 'alpha') != '' && GETPOST('posnumber', 'alpha') != '-1') - { + } elseif (GETPOST('posnumber', 'alpha') != '' && GETPOST('posnumber', 'alpha') != '' && GETPOST('posnumber', 'alpha') != '-1') { $posmodule = GETPOST('posmodule', 'alpha'); $terminalid = GETPOST('posnumber', 'alpha'); $terminaltouse = $terminalid; - if ($terminaltouse == '1' && $posmodule == 'cashdesk') $terminaltouse = ''; + if ($terminaltouse == '1' && $posmodule == 'cashdesk') { + $terminaltouse = ''; + } if ($posmodule == 'cashdesk' && $terminaltouse != '' && $terminaltouse != '1') { $terminaltouse = ''; @@ -290,13 +290,10 @@ if ($action == "create" || $action == "start" || $action == 'close') } } - if ($terminalid != '') - { + if ($terminalid != '') { // Calculate $initialbalanceforterminal for terminal 0 - foreach ($arrayofpaymentmode as $key => $val) - { - if ($key != 'cash') - { + foreach ($arrayofpaymentmode as $key => $val) { + if ($key != 'cash') { $initialbalanceforterminal[$terminalid][$key] = 0; continue; } @@ -305,21 +302,28 @@ if ($action == "create" || $action == "start" || $action == 'close') $vartouse = 'CASHDESK_ID_BANKACCOUNT_CASH'.$terminaltouse; $bankid = $conf->global->$vartouse; - if ($bankid > 0) - { + if ($bankid > 0) { $sql = "SELECT SUM(amount) as total FROM ".MAIN_DB_PREFIX."bank"; $sql .= " WHERE fk_account = ".$bankid; - if ($syear && !$smonth) $sql .= " AND dateo < '".$db->idate(dol_get_first_day($syear, 1))."'"; - elseif ($syear && $smonth && !$sday) $sql .= " AND dateo < '".$db->idate(dol_get_first_day($syear, $smonth))."'"; - elseif ($syear && $smonth && $sday) $sql .= " AND dateo < '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."'"; - else dol_print_error('', 'Year not defined'); + if ($syear && !$smonth) { + $sql .= " AND dateo < '".$db->idate(dol_get_first_day($syear, 1))."'"; + } elseif ($syear && $smonth && !$sday) { + $sql .= " AND dateo < '".$db->idate(dol_get_first_day($syear, $smonth))."'"; + } elseif ($syear && $smonth && $sday) { + $sql .= " AND dateo < '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."'"; + } else { + dol_print_error('', 'Year not defined'); + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $initialbalanceforterminal[$terminalid][$key] = $obj->total; - } else dol_print_error($db); + if ($obj) { + $initialbalanceforterminal[$terminalid][$key] = $obj->total; + } + } else { + dol_print_error($db); + } } else { setEventMessages($langs->trans("SetupOfTerminalNotComplete", $terminaltouse), null, 'errors'); $error++; @@ -327,8 +331,7 @@ if ($action == "create" || $action == "start" || $action == 'close') } // Calculate $theoricalamountforterminal - foreach ($arrayofpaymentmode as $key => $val) - { + foreach ($arrayofpaymentmode as $key => $val) { $sql = "SELECT SUM(pf.amount) as total, COUNT(*) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."c_paiement as cp"; $sql .= " WHERE pf.fk_facture = f.rowid AND p.rowid = pf.fk_paiement AND cp.id = p.fk_paiement"; @@ -336,47 +339,55 @@ if ($action == "create" || $action == "start" || $action == 'close') $sql .= " AND f.pos_source = '".$db->escape($terminalid)."'"; $sql .= " AND f.paye = 1"; $sql .= " AND p.entity IN (".getEntity('facture').")"; - if ($key == 'cash') $sql .= " AND cp.code = 'LIQ'"; - elseif ($key == 'cheque') $sql .= " AND cp.code = 'CHQ'"; - elseif ($key == 'card') $sql .= " AND cp.code = 'CB'"; - else { + if ($key == 'cash') { + $sql .= " AND cp.code = 'LIQ'"; + } elseif ($key == 'cheque') { + $sql .= " AND cp.code = 'CHQ'"; + } elseif ($key == 'card') { + $sql .= " AND cp.code = 'CB'"; + } else { dol_print_error('Value for key = '.$key.' not supported'); exit; } - if ($syear && !$smonth) $sql .= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, 1))."' AND '".$db->idate(dol_get_last_day($syear, 12))."'"; - elseif ($syear && $smonth && !$sday) $sql .= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, $smonth))."' AND '".$db->idate(dol_get_last_day($syear, $smonth))."'"; - elseif ($syear && $smonth && $sday) $sql .= " AND datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $smonth, $sday, $syear))."'"; - else dol_print_error('', 'Year not defined'); + if ($syear && !$smonth) { + $sql .= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, 1))."' AND '".$db->idate(dol_get_last_day($syear, 12))."'"; + } elseif ($syear && $smonth && !$sday) { + $sql .= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, $smonth))."' AND '".$db->idate(dol_get_last_day($syear, $smonth))."'"; + } elseif ($syear && $smonth && $sday) { + $sql .= " AND datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $smonth, $sday, $syear))."'"; + } else { + dol_print_error('', 'Year not defined'); + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $theoricalamountforterminal[$terminalid][$key] = $initialbalanceforterminal[$terminalid][$key]; $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $theoricalamountforterminal[$terminalid][$key] = price2num($theoricalamountforterminal[$terminalid][$key] + $obj->total); $theoricalnbofinvoiceforterminal[$terminalid][$key] = $obj->nb; } - } else dol_print_error($db); + } else { + dol_print_error($db); + } } } //var_dump($theoricalamountforterminal); var_dump($theoricalnbofinvoiceforterminal); if ($action != 'close') { - llxHeader(); + llxHeader('', $langs->trans("NewCashFence")); print load_fiche_titre($langs->trans("CashControl")." - ".$langs->trans("New"), '', 'cash-register'); print ''; print ''; - if ($contextpage == 'takepos') print ''; - if ($action == 'start' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '-1') - { + if ($contextpage == 'takepos') { + print ''; + } + if ($action == 'start' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '-1') { print ''; - } elseif ($action == 'close') - { + } elseif ($action == 'close') { print ''; print ''; } else { @@ -406,10 +417,11 @@ if ($action == "create" || $action == "start" || $action == 'close') for ($i = 1; $i <= $numterminals; $i++) { $array[$i] = $i; } - $selectedposnumber = 0; $showempty = 1; - if ($conf->global->TAKEPOS_NUM_TERMINALS == '1') - { - $selectedposnumber = 1; $showempty = 0; + $selectedposnumber = 0; + $showempty = 1; + if ($conf->global->TAKEPOS_NUM_TERMINALS == '1') { + $selectedposnumber = 1; + $showempty = 0; } print $form->selectarray('posnumber', $array, GETPOSTISSET('posnumber') ?GETPOST('posnumber', 'int') : $selectedposnumber, $showempty); //print ''; @@ -417,8 +429,7 @@ if ($action == "create" || $action == "start" || $action == 'close') // Year print ''; // Button Start print ''; - $i++; + print ''; + $i++; } // Save print ''; @@ -545,13 +552,16 @@ if ($action == "create" || $action == "start" || $action == 'close') // Initial amount print ''; // Amount per payment type @@ -568,8 +578,11 @@ if ($action == "create" || $action == "start" || $action == 'close') // Save print ''; print ''; @@ -581,8 +594,7 @@ if ($action == "create" || $action == "start" || $action == 'close') } } -if (empty($action) || $action == "view" || $action == "close") -{ +if (empty($action) || $action == "view" || $action == "close") { $result = $object->fetch($id); llxHeader('', $langs->trans("CashControl")); @@ -648,8 +660,7 @@ if (empty($action) || $action == "view" || $action == "close") print '"; - foreach ($arrayofpaymentmode as $key => $val) - { + foreach ($arrayofpaymentmode as $key => $val) { print '"; @@ -667,8 +678,7 @@ if (empty($action) || $action == "view" || $action == "close") print ''; - if ($object->status == CashControl::STATUS_DRAFT) - { + if ($object->status == CashControl::STATUS_DRAFT) { print ''; print ''; @@ -678,16 +688,18 @@ if (empty($action) || $action == "view" || $action == "close") print ''; - if ($contextpage != 'takepos') print '
    '; + if ($contextpage != 'takepos') { + print '
    '; + } } else { print ''; print ''; - if ($contextpage == 'takepos') print ''; - if ($action == 'start' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '-1') - { + if ($contextpage == 'takepos') { + print ''; + } + if ($action == 'start' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '-1') { print ''; - } elseif ($action == 'close') - { + } elseif ($action == 'close') { print ''; print ''; } else { @@ -695,59 +707,58 @@ if (empty($action) || $action == "view" || $action == "close") } /* - print '
    '; - print '
    '; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); print "
    \n"; print $px2->show(); diff --git a/htdocs/commande/tpl/linkedobjectblock.tpl.php b/htdocs/commande/tpl/linkedobjectblock.tpl.php index a9c01386bf7..428589aa844 100644 --- a/htdocs/commande/tpl/linkedobjectblock.tpl.php +++ b/htdocs/commande/tpl/linkedobjectblock.tpl.php @@ -38,12 +38,13 @@ $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1) $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } echo '
    '.$langs->trans("CustomerOrder"); if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) { diff --git a/htdocs/compta/accounting-files.php b/htdocs/compta/accounting-files.php index 02098e986ba..596abdf0e97 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 @@ -25,7 +26,9 @@ */ if ((array_key_exists('action', $_GET) && $_GET['action'] == 'dl') || (array_key_exists('action', $_POST) && $_POST['action'] == 'dl')) { // To not replace token when downloading file - if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); + if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); + } } require '../main.inc.php'; @@ -70,12 +73,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) { $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 = "date,item"; // Set here default search field -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "date,item"; // Set here default search field +} +if (!$sortorder) { + $sortorder = "DESC"; +} $arrayfields = array( @@ -111,7 +120,9 @@ if (!empty($conf->multicompany->enabled) && is_object($mc)) { $entity = '0,'.join(',', array_keys($arrayofentities)); } } -if (empty($entity)) $entity = $conf->entity; +if (empty($entity)) { + $entity = $conf->entity; +} $error = 0; @@ -129,26 +140,25 @@ $error = 0; $filesarray = array(); $result = false; if (($action == 'searchfiles' || $action == 'dl')) { - if (empty($date_start)) - { + if (empty($date_start)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateStart")), null, 'errors'); $error++; } - if (empty($date_stop)) - { + if (empty($date_stop)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $sql = ''; $wheretail = " '".$db->idate($date_start)."' AND '".$db->idate($date_stop)."'"; // Customer invoices if (GETPOST('selectinvoices')) { - if (!empty($sql)) $sql .= " UNION ALL"; + if (!empty($sql)) { + $sql .= " UNION ALL"; + } $sql .= "SELECT t.rowid as id, t.entity, t.ref, t.paye as paid, t.total as total_ht, t.total_ttc, t.tva as total_vat, t.multicurrency_code as currency, t.fk_soc, t.datef as date, t.date_lim_reglement as date_due, 'Invoice' as item, s.nom as thirdparty_name, s.code_client as thirdparty_code, c.code as country_code, s.tva_intra as vatnum, ".PAY_CREDIT." as sens"; $sql .= " FROM ".MAIN_DB_PREFIX."facture as t LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = s.fk_pays"; $sql .= " WHERE datef between ".$wheretail; @@ -157,7 +167,9 @@ if (($action == 'searchfiles' || $action == 'dl')) { } // Vendor invoices if (GETPOST('selectsupplierinvoices')) { - if (!empty($sql)) $sql .= " UNION ALL"; + if (!empty($sql)) { + $sql .= " UNION ALL"; + } $sql .= " SELECT t.rowid as id, t.entity, t.ref, t.paye as paid, t.total_ht, t.total_ttc, t.total_tva as total_vat, t.multicurrency_code as currency, t.fk_soc, t.datef as date, t.date_lim_reglement as date_due, 'SupplierInvoice' as item, s.nom as thirdparty_name, s.code_fournisseur as thirdparty_code, c.code as country_code, s.tva_intra as vatnum, ".PAY_DEBIT." as sens"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as t LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = s.fk_pays"; $sql .= " WHERE datef between ".$wheretail; @@ -166,7 +178,9 @@ if (($action == 'searchfiles' || $action == 'dl')) { } // Expense reports if (GETPOST('selectexpensereports')) { - if (!empty($sql)) $sql .= " UNION ALL"; + if (!empty($sql)) { + $sql .= " UNION ALL"; + } $sql .= " SELECT t.rowid as id, t.entity, t.ref, t.paid, t.total_ht, t.total_ttc, t.total_tva as total_vat, t.multicurrency_code as currency, t.fk_user_author as fk_soc, t.date_fin as date, t.date_fin as date_due, 'ExpenseReport' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum, ".PAY_DEBIT." as sens"; $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as t LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = t.fk_user_author LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = u.fk_country"; $sql .= " WHERE date_fin between ".$wheretail; @@ -175,7 +189,9 @@ if (($action == 'searchfiles' || $action == 'dl')) { } // Donations if (GETPOST('selectdonations')) { - if (!empty($sql)) $sql .= " UNION ALL"; + if (!empty($sql)) { + $sql .= " UNION ALL"; + } $sql .= " SELECT t.rowid as id, t.entity, t.ref, paid, amount as total_ht, amount as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, 0 as fk_soc, t.datedon as date, t.datedon as date_due, 'Donation' as item, t.societe as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum, ".PAY_CREDIT." as sens"; $sql .= " FROM ".MAIN_DB_PREFIX."don as t LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_country"; $sql .= " WHERE datedon between ".$wheretail; @@ -184,7 +200,9 @@ if (($action == 'searchfiles' || $action == 'dl')) { } // Payments of salaries if (GETPOST('selectpaymentsofsalaries')) { - if (!empty($sql)) $sql .= " UNION ALL"; + if (!empty($sql)) { + $sql .= " UNION ALL"; + } $sql .= " SELECT t.rowid as id, t.entity, t.label as ref, 1 as paid, amount as total_ht, amount as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, t.fk_user as fk_soc, t.datep as date, t.dateep as date_due, 'SalaryPayment' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum, ".PAY_DEBIT." as sens"; $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as t LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = t.fk_user LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = u.fk_country"; $sql .= " WHERE datep between ".$wheretail; @@ -193,7 +211,9 @@ if (($action == 'searchfiles' || $action == 'dl')) { } // Social contributions if (GETPOST('selectsocialcontributions')) { - if (!empty($sql)) $sql .= " UNION ALL"; + if (!empty($sql)) { + $sql .= " UNION ALL"; + } $sql .= " SELECT t.rowid as id, t.entity, t.libelle as ref, t.paye as paid, t.amount as total_ht, t.amount as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, 0 as fk_soc, t.date_ech as date, t.periode as date_due, 'SocialContributions' as item, '' as thirdparty_name, '' as thirdparty_code, '' as country_code, '' as vatnum, ".PAY_DEBIT." as sens"; $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as t"; $sql .= " WHERE t.date_ech between ".$wheretail; @@ -202,7 +222,9 @@ if (($action == 'searchfiles' || $action == 'dl')) { } // Various payments if (GETPOST('selectvariouspayment')) { - if (!empty($sql)) $sql .= " UNION ALL"; + if (!empty($sql)) { + $sql .= " UNION ALL"; + } $sql .= " SELECT t.rowid as id, t.entity, t.ref, 1 as paid, t.amount as total_ht, t.amount as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, 0 as fk_soc, t.datep as date, t.datep as date_due, 'VariousPayment' as item, '' as thirdparty_name, '' as thirdparty_code, '' as country_code, '' as vatnum, sens"; $sql .= " FROM ".MAIN_DB_PREFIX."payment_various as t"; $sql .= " WHERE datep between ".$wheretail; @@ -210,7 +232,9 @@ if (($action == 'searchfiles' || $action == 'dl')) { } // Loan payments if (GETPOST('selectloanspayment')) { - if (!empty($sql)) $sql .= " UNION ALL"; + if (!empty($sql)) { + $sql .= " UNION ALL"; + } $sql .= " SELECT t.rowid as id, l.entity, l.label as ref, 1 as paid, (t.amount_capital+t.amount_insurance+t.amount_interest) as total_ht, (t.amount_capital+t.amount_insurance+t.amount_interest) as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, 0 as fk_soc, t.datep as date, t.datep as date_due, 'LoanPayment' as item, '' as thirdparty_name, '' as thirdparty_code, '' as country_code, '' as vatnum, ".PAY_DEBIT." as sens"; $sql .= " FROM ".MAIN_DB_PREFIX."payment_loan as t LEFT JOIN ".MAIN_DB_PREFIX."loan as l ON l.rowid = t.fk_loan"; $sql .= " WHERE datep between ".$wheretail; @@ -225,8 +249,7 @@ if (($action == 'searchfiles' || $action == 'dl')) { $files = array(); $link = ''; - if ($resd) - { + if ($resd) { $numd = $db->num_rows($resd); $tmpinvoice = new Facture($db); @@ -235,12 +258,10 @@ if (($action == 'searchfiles' || $action == 'dl')) { $upload_dir = ''; $i = 0; - while ($i < $numd) - { + while ($i < $numd) { $objd = $db->fetch_object($resd); - switch ($objd->item) - { + switch ($objd->item) { case "Invoice": $subdir = ''; $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); @@ -306,15 +327,13 @@ if (($action == 'searchfiles' || $action == 'dl')) { break; } - if (!empty($upload_dir)) - { + if (!empty($upload_dir)) { $result = true; $files = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1); //var_dump($upload_dir); //var_dump($files); - if (count($files) < 1) - { + if (count($files) < 1) { $nofile = array(); $nofile['id'] = $objd->id; $nofile['entity'] = $objd->entity; @@ -335,8 +354,7 @@ if (($action == 'searchfiles' || $action == 'dl')) { $filesarray[$nofile['item'].'_'.$nofile['id']] = $nofile; } else { - foreach ($files as $key => $file) - { + foreach ($files as $key => $file) { $file['id'] = $objd->id; $file['entity'] = $objd->entity; $file['date'] = $db->idate($objd->date); @@ -399,17 +417,14 @@ if (($action == 'searchfiles' || $action == 'dl')) { */ $dirfortmpfile = ($conf->accounting->dir_temp ? $conf->accounting->dir_temp : $conf->comptabilite->dir_temp); -if (empty($dirfortmpfile)) -{ +if (empty($dirfortmpfile)) { setEventMessages($langs->trans("ErrorNoAccountingModuleEnabled"), null, 'errors'); $error++; } -if ($result && $action == "dl" && !$error) -{ - if (!extension_loaded('zip')) - { +if ($result && $action == "dl" && !$error) { + if (!extension_loaded('zip')) { setEventMessages('PHPZIPExtentionNotLoaded', null, 'errors'); exit; } @@ -417,8 +432,7 @@ if ($result && $action == "dl" && !$error) dol_mkdir($dirfortmpfile); $log = $langs->transnoentitiesnoconv("Type"); - if (!empty($conf->multicompany->enabled) && is_object($mc)) - { + if (!empty($conf->multicompany->enabled) && is_object($mc)) { $log .= ','.$langs->transnoentitiesnoconv("Entity"); } $log .= ','.$langs->transnoentitiesnoconv("Date"); @@ -441,10 +455,8 @@ if ($result && $action == "dl" && !$error) $zip = new ZipArchive; $res = $zip->open($zipname, ZipArchive::OVERWRITE | ZipArchive::CREATE); - if ($res) - { - foreach ($filesarray as $key => $file) - { + if ($res) { + foreach ($filesarray as $key => $file) { if (!empty($file['files'])) { foreach ($file['files'] as $filecursor) { if (file_exists($filecursor["fullname"])) { @@ -454,8 +466,7 @@ if ($result && $action == "dl" && !$error) } $log .= '"'.$langs->trans($file['item']).'"'; - if (!empty($conf->multicompany->enabled) && is_object($mc)) - { + if (!empty($conf->multicompany->enabled) && is_object($mc)) { $log .= ',"'.(empty($arrayofentities[$file['entity']]) ? $file['entity'] : $arrayofentities[$file['entity']]).'"'; } $log .= ','.dol_print_date($file['date'], 'dayrfc'); @@ -532,8 +543,7 @@ print $langs->trans("ReportPeriod").': '.$form->selectDate($date_start, 'date_st print ' - '.$form->selectDate($date_stop, 'date_stop', 0, 0, 0, "", 1, 1, 0)."\n"; // Export is for current company only -if (!empty($conf->multicompany->enabled) && is_object($mc)) -{ +if (!empty($conf->multicompany->enabled) && is_object($mc)) { $mc->getInfo($conf->entity); print '('.$langs->trans("Entity").' : '; print ""; @@ -559,7 +569,9 @@ $listofchoices = array( 'selectloanspayment'=>array('label'=>'PaymentLoan', 'enabled' => !empty($conf->loan->enabled)), ); foreach ($listofchoices as $choice => $val) { - if (empty($val['enabled'])) continue; // list not qualified + if (empty($val['enabled'])) { + continue; // list not qualified + } $checked = (((!GETPOSTISSET('search') && $action != 'searchfiles') || GETPOST($choice)) ? ' checked="checked"' : ''); print '
    '; } @@ -570,8 +582,7 @@ print ''."\n"; print dol_get_fiche_end(); -if (!empty($date_start) && !empty($date_stop)) -{ +if (!empty($date_start) && !empty($date_stop)) { $param = 'action=searchfiles'; $param .= '&date_startday='.GETPOST('date_startday', 'int'); $param .= '&date_startmonth='.GETPOST('date_startmonth', 'int'); @@ -614,14 +625,14 @@ if (!empty($date_start) && !empty($date_stop)) print '
    '.$langs->trans("Code").''.$langs->trans("Country").''.$langs->trans("VATIntra").''.$langs->trans("Currency").''.$langs->trans("Currency").'
    '.$langs->trans("NoItem").''; - if (!empty($data['files'])) - { - foreach ($data['files'] as $id=>$filecursor) { + if (!empty($data['files'])) { + foreach ($data['files'] as $id => $filecursor) { print ''.($filecursor['name'] ? $filecursor['name'] : $filecursor['ref']).' '.$formfile->showPreview($filecursor, $filecursor['modulepart'], $filecursor['subdir'].'/'.$filecursor['name']).'
    '; } } diff --git a/htdocs/compta/ajaxpayment.php b/htdocs/compta/ajaxpayment.php index 0129d1e5f43..d22e1a0182a 100644 --- a/htdocs/compta/ajaxpayment.php +++ b/htdocs/compta/ajaxpayment.php @@ -20,11 +20,21 @@ * \brief File to return Ajax response on payment breakdown process */ -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no menu to show -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); // If there is no menu to show +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +} require '../main.inc.php'; @@ -46,18 +56,20 @@ $currentInvId = $_POST['imgClicked']; // from DOM elements : imgId (equals invoi $amountPayment = $amountPayment != '' ? (is_numeric(price2num($amountPayment)) ? price2num($amountPayment) : '') : ''; // keep void if not a valid entry // Clean checkamounts -foreach ($amounts as $key => $value) -{ +foreach ($amounts as $key => $value) { $value = price2num($value); $amounts[$key] = $value; - if (empty($value)) unset($amounts[$key]); + if (empty($value)) { + unset($amounts[$key]); + } } // Clean remains -foreach ($remains as $key => $value) -{ +foreach ($remains as $key => $value) { $value = price2num($value); $remains[$key] = (($invoice_type) == 2 ?-1 : 1) * $value; - if (empty($value)) unset($remains[$key]); + if (empty($value)) { + unset($remains[$key]); + } } // Treatment @@ -65,19 +77,16 @@ $result = ($amountPayment != '') ? ($amountPayment - array_sum($amounts)) : arra $toJsonArray = array(); $totalRemaining = price2num(array_sum($remains)); $toJsonArray['label'] = $amountPayment == '' ? '' : $langs->transnoentities('RemainingAmountPayment'); -if ($currentInvId) // Here to breakdown -{ +if ($currentInvId) { // Here to breakdown // Get the current amount (from form) and the corresponding remainToPay (from invoice) $currentAmount = $amounts['amount_'.$currentInvId]; $currentRemain = $remains['remain_'.$currentInvId]; // If amountPayment isn't filled, breakdown invoice amount, else breakdown from amountPayment - if ($amountPayment == '') - { + if ($amountPayment == '') { // Check if current amount exists in amounts $amountExists = array_key_exists('amount_'.$currentInvId, $amounts); - if ($amountExists) - { + if ($amountExists) { $remainAmount = $currentRemain - $currentAmount; // To keep value between curRemain and curAmount $result += $remainAmount; // result must be deduced by $currentAmount += $remainAmount; // curAmount put to curRemain @@ -90,8 +99,7 @@ if ($currentInvId) // Here to breakdown $result += price2num($currentAmount); $currentAmount = 0; - if ($result >= 0) // then we need to calculate the amount to breakdown - { + if ($result >= 0) { // then we need to calculate the amount to breakdown $amountToBreakdown = ($result - $currentRemain >= 0 ? $currentRemain : // Remain can be fully paid $currentRemain + ($result - $currentRemain)); // Remain can only partially be paid diff --git a/htdocs/compta/bank/account_statement_document.php b/htdocs/compta/bank/account_statement_document.php index fd7c6b1d292..ea4911e7050 100644 --- a/htdocs/compta/bank/account_statement_document.php +++ b/htdocs/compta/bank/account_statement_document.php @@ -47,26 +47,30 @@ if ($user->socid) { $action = ''; $socid = $user->socid; } -if ($user->socid) +if ($user->socid) { $socid = $user->socid; +} // Get parameters $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 (empty($page) || $page == -1) { + $page = 0; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) +if (!$sortorder) { $sortorder = "ASC"; -if (!$sortfield) +} +if (!$sortfield) { $sortfield = "name"; +} $object = new Account($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref); $account = $object->id; // Force the search field on id of account } @@ -75,8 +79,7 @@ $result = restrictedArea($user, 'banque', $object->id, 'bank_account', '', ''); // Define number of receipt to show (current, previous or next one ?) $found = false; -if ($_GET["rel"] == 'prev') -{ +if ($_GET["rel"] == 'prev') { // Recherche valeur pour num = numero releve precedent $sql = "SELECT DISTINCT(b.num_releve) as num"; $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; @@ -86,18 +89,15 @@ if ($_GET["rel"] == 'prev') dol_syslog("htdocs/compta/bank/releve.php", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $numrows = $db->num_rows($resql); - if ($numrows > 0) - { + if ($numrows > 0) { $obj = $db->fetch_object($resql); $numref = $obj->num; $found = true; } } -} elseif ($_GET["rel"] == 'next') -{ +} elseif ($_GET["rel"] == 'next') { // Recherche valeur pour num = numero releve precedent $sql = "SELECT DISTINCT(b.num_releve) as num"; $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; @@ -107,11 +107,9 @@ if ($_GET["rel"] == 'prev') dol_syslog("htdocs/compta/bank/releve.php", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $numrows = $db->num_rows($resql); - if ($numrows > 0) - { + if ($numrows > 0) { $obj = $db->fetch_object($resql); $numref = $obj->num; $found = true; @@ -127,13 +125,12 @@ if ($_GET["rel"] == 'prev') * Actions */ -if (!empty($numref)) -{ +if (!empty($numref)) { $object->fetch_thirdparty(); $upload_dir = $conf->bank->dir_output."/".$id."/statement/".dol_sanitizeFileName($numref); } $backtopage = $_SERVER['PHP_SELF']."?account=".$id."&num=".$numref; -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -189,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/annuel.php b/htdocs/compta/bank/annuel.php index a0650e9ffa4..45ae92480a0 100644 --- a/htdocs/compta/bank/annuel.php +++ b/htdocs/compta/bank/annuel.php @@ -41,13 +41,14 @@ $ref = GETPOST('ref'); // 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; +} $result = restrictedArea($user, 'banque', $fieldvalue, 'bank_account&bank_account', '', '', $fieldtype); $year_start = GETPOST('year_start'); $year_current = strftime("%Y", time()); -if (!$year_start) -{ +if (!$year_start) { $year_start = $year_current - 2; $year_end = $year_current; } else { @@ -68,13 +69,11 @@ $form = new Form($db); // Get account informations $object = new Account($db); -if ($id > 0 && !preg_match('/,/', $id)) // if for a particular account and not a list -{ +if ($id > 0 && !preg_match('/,/', $id)) { // if for a particular account and not a list $result = $object->fetch($id); $id = $object->id; } -if (!empty($ref)) -{ +if (!empty($ref)) { $result = $object->fetch(0, $ref); $id = $object->id; } @@ -90,17 +89,16 @@ $sql .= ", ".MAIN_DB_PREFIX."bank_account as ba"; $sql .= " WHERE b.fk_account = ba.rowid"; $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; $sql .= " AND b.amount >= 0"; -if (!empty($id)) +if (!empty($id)) { $sql .= " AND b.fk_account IN (".$db->sanitize($db->escape($id)).")"; +} $sql .= " GROUP BY dm"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); $encaiss[$row[1]] = $row[0]; $i++; @@ -116,17 +114,16 @@ $sql .= ", ".MAIN_DB_PREFIX."bank_account as ba"; $sql .= " WHERE b.fk_account = ba.rowid"; $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; $sql .= " AND b.amount <= 0"; -if (!empty($id)) +if (!empty($id)) { $sql .= " AND b.fk_account IN (".$db->sanitize($db->escape($id)).")"; +} $sql .= " GROUP BY dm"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); $decaiss[$row[1]] = -$row[0]; $i++; @@ -146,20 +143,19 @@ $link = ($year_start ? "'.$langs->trans("BackToList").''; -if (!empty($id)) -{ - if (!preg_match('/,/', $id)) - { +if (!empty($id)) { + if (!preg_match('/,/', $id)) { dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); } else { $bankaccount = new Account($db); $listid = explode(',', $id); - foreach ($listid as $key => $aId) - { + foreach ($listid as $key => $aId) { $bankaccount->fetch($aId); $bankaccount->label = $bankaccount->ref; print $bankaccount->getNomUrl(1); - if ($key < (count($listid) - 1)) print ', '; + if ($key < (count($listid) - 1)) { + print ', '; + } } } } else { @@ -176,39 +172,33 @@ print '
    '; // You can use div-table-responsive- print ''; print ''; -for ($annee = $year_start; $annee <= $year_end; $annee++) -{ +for ($annee = $year_start; $annee <= $year_end; $annee++) { print ''; } print ''; print ''; print ''; -for ($annee = $year_start; $annee <= $year_end; $annee++) -{ +for ($annee = $year_start; $annee <= $year_end; $annee++) { print ''; } print ''; -for ($mois = 1; $mois < 13; $mois++) -{ +for ($mois = 1; $mois < 13; $mois++) { print ''; print ""; - for ($annee = $year_start; $annee <= $year_end; $annee++) - { + for ($annee = $year_start; $annee <= $year_end; $annee++) { $case = sprintf("%04s-%02s", $annee, $mois); print '"; print '"; -for ($annee = $year_start; $annee <= $year_end; $annee++) -{ +for ($annee = $year_start; $annee <= $year_end; $annee++) { print ''; } print "\n"; @@ -239,14 +228,16 @@ $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; $sql .= ", ".MAIN_DB_PREFIX."bank_account as ba"; $sql .= " WHERE b.fk_account = ba.rowid"; $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; -if (!empty($id)) +if (!empty($id)) { $sql .= " AND b.fk_account IN (".$db->sanitize($db->escape($id)).")"; +} $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $balance = $obj->total; + if ($obj) { + $balance = $obj->total; + } } else { dol_print_error($db); } @@ -264,8 +255,7 @@ print "
    '.$langs->trans("Month").''.$annee.'
     '.$langs->trans("Debit").''.$langs->trans("Credit").'
    ".dol_print_date(dol_mktime(1, 1, 1, $mois, 1, 2000), "%B")." '; - if ($decaiss[$case] > 0) - { + if ($decaiss[$case] > 0) { print price($decaiss[$case]); $totsorties[$annee] += $decaiss[$case]; } print " '; - if ($encaiss[$case] > 0) - { + if ($encaiss[$case] > 0) { print price($encaiss[$case]); $totentrees[$annee] += $encaiss[$case]; } @@ -219,8 +209,7 @@ for ($mois = 1; $mois < 13; $mois++) // Total debit-credit print '
    '.$langs->trans("Total")."'.price($totsorties[$annee]).''.price($totentrees[$annee]).'
    "; $year = $year_end; $result = dol_mkdir($conf->bank->dir_temp); -if ($result < 0) -{ +if ($result < 0) { $langs->load("errors"); $error++; setEventMessages($langs->trans("ErrorFailedToCreateDir"), null, 'errors'); @@ -276,11 +266,12 @@ if ($result < 0) $sql .= ", ".MAIN_DB_PREFIX."bank_account as ba"; $sql .= " WHERE b.fk_account = ba.rowid"; $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; - if ($id && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$id.")"; + if ($id && $_GET["option"] != 'all') { + $sql .= " AND b.fk_account IN (".$id.")"; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $obj = $db->fetch_object($resql); $min = $db->jdate($obj->min); @@ -297,8 +288,7 @@ if ($result < 0) $tblyear[1] = array(); $tblyear[2] = array(); - for ($annee = 0; $annee < 3; $annee++) - { + for ($annee = 0; $annee < 3; $annee++) { $sql = "SELECT date_format(b.datev,'%m')"; $sql .= ", SUM(b.amount)"; $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; @@ -308,16 +298,16 @@ if ($result < 0) $sql .= " AND b.datev >= '".($year - $annee)."-01-01 00:00:00'"; $sql .= " AND b.datev <= '".($year - $annee)."-12-31 23:59:59'"; $sql .= " AND b.amount > 0"; - if ($id && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$id.")"; + if ($id && $_GET["option"] != 'all') { + $sql .= " AND b.fk_account IN (".$id.")"; + } $sql .= " GROUP BY date_format(b.datev,'%m');"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); $tblyear[$annee][$row[0]] = $row[1]; $i++; @@ -333,8 +323,7 @@ if ($result < 0) $data_year_1 = array(); $data_year_2 = array(); - for ($i = 0; $i < 12; $i++) - { + for ($i = 0; $i < 12; $i++) { $data_year_0[$i] = isset($tblyear[0][substr("0".($i + 1), -2)]) ? $tblyear[0][substr("0".($i + 1), -2)] : 0; $data_year_1[$i] = isset($tblyear[1][substr("0".($i + 1), -2)]) ? $tblyear[1][substr("0".($i + 1), -2)] : 0; $data_year_2[$i] = isset($tblyear[2][substr("0".($i + 1), -2)]) ? $tblyear[2][substr("0".($i + 1), -2)] : 0; @@ -347,8 +336,7 @@ if ($result < 0) $fileurl = DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/credmovement".$id."-".$year.".png"; $title = $langs->transnoentities("Credit").' - '.$langs->transnoentities("Year").': '.($year - 2).' - '.($year - 1)." - ".$year; $graph_datas = array(); - for ($i = 0; $i < 12; $i++) - { + for ($i = 0; $i < 12; $i++) { $graph_datas[$i] = array($labels[$i], $data_year_0[$i], $data_year_1[$i], $data_year_2[$i]); } @@ -382,8 +370,7 @@ if ($result < 0) $tblyear[1] = array(); $tblyear[2] = array(); - for ($annee = 0; $annee < 3; $annee++) - { + for ($annee = 0; $annee < 3; $annee++) { $sql = "SELECT date_format(b.datev,'%m')"; $sql .= ", SUM(b.amount)"; $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; @@ -393,16 +380,16 @@ if ($result < 0) $sql .= " AND b.datev >= '".($year - $annee)."-01-01 00:00:00'"; $sql .= " AND b.datev <= '".($year - $annee)."-12-31 23:59:59'"; $sql .= " AND b.amount < 0"; - if ($id && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$id.")"; + if ($id && $_GET["option"] != 'all') { + $sql .= " AND b.fk_account IN (".$id.")"; + } $sql .= " GROUP BY date_format(b.datev,'%m');"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); $tblyear[$annee][$row[0]] = abs($row[1]); $i++; @@ -418,8 +405,7 @@ if ($result < 0) $data_year_1 = array(); $data_year_2 = array(); - for ($i = 0; $i < 12; $i++) - { + for ($i = 0; $i < 12; $i++) { $data_year_0[$i] = isset($tblyear[0][substr("0".($i + 1), -2)]) ? $tblyear[0][substr("0".($i + 1), -2)] : 0; $data_year_1[$i] = isset($tblyear[1][substr("0".($i + 1), -2)]) ? $tblyear[1][substr("0".($i + 1), -2)] : 0; $data_year_2[$i] = isset($tblyear[2][substr("0".($i + 1), -2)]) ? $tblyear[2][substr("0".($i + 1), -2)] : 0; @@ -431,8 +417,7 @@ if ($result < 0) $fileurl = DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/debmovement".$id."-".$year.".png"; $title = $langs->transnoentities("Debit").' - '.$langs->transnoentities("Year").': '.($year - 2).' - '.($year - 1)." - ".$year; $graph_datas = array(); - for ($i = 0; $i < 12; $i++) - { + for ($i = 0; $i < 12; $i++) { $graph_datas[$i] = array($labels[$i], $data_year_0[$i], $data_year_1[$i], $data_year_2[$i]); } diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php index 37c125668ec..b621ad9752f 100644 --- a/htdocs/compta/bank/bankentries_list.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -10,7 +10,6 @@ * Copyright (C) 2018 Ferran Marcet * Copyright (C) 2018 Frédéric France * 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 @@ -69,12 +68,15 @@ $contextpage = 'banktransactionlist'.(empty($object->ref) ? '' : '-'.$object->id // Security check $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldtype = (!empty($ref) ? 'ref' : 'rowid'); -if ($fielvalue) -{ - if ($user->socid) $socid = $user->socid; +if ($fielvalue) { + if ($user->socid) { + $socid = $user->socid; + } $result = restrictedArea($user, 'banque', $fieldvalue, 'bank_account&bank_account', '', '', $fieldtype); } else { - if ($user->socid) $socid = $user->socid; + if ($user->socid) { + $socid = $user->socid; + } $result = restrictedArea($user, 'banque'); } @@ -91,34 +93,42 @@ $search_dt_start = dol_mktime(0, 0, 0, GETPOST('search_start_dtmonth', 'int'), G $search_dt_end = dol_mktime(0, 0, 0, GETPOST('search_end_dtmonth', 'int'), GETPOST('search_end_dtday', 'int'), GETPOST('search_end_dtyear', 'int')); $search_dv_start = dol_mktime(0, 0, 0, GETPOST('search_start_dvmonth', 'int'), GETPOST('search_start_dvday', 'int'), GETPOST('search_start_dvyear', 'int')); $search_dv_end = dol_mktime(0, 0, 0, GETPOST('search_end_dvmonth', 'int'), GETPOST('search_end_dvday', 'int'), GETPOST('search_end_dvyear', 'int')); -$search_thirdparty = GETPOST("search_thirdparty", 'alpha') ?GETPOST("search_thirdparty", 'alpha') : GETPOST("thirdparty", 'alpha'); +$search_thirdparty_user = GETPOST("search_thirdparty", 'alpha') ?GETPOST("search_thirdparty", 'alpha') : GETPOST("thirdparty", 'alpha'); $search_req_nb = GETPOST("req_nb", 'alpha'); $search_num_releve = GETPOST("search_num_releve", 'alpha'); $search_conciliated = GETPOST("search_conciliated", 'int'); $num_releve = GETPOST("num_releve", "alpha"); -if (empty($dateop)) $dateop = -1; +if (empty($dateop)) { + $dateop = -1; +} $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'); $pageplusone = GETPOST("pageplusone", 'int'); -if ($pageplusone) $page = $pageplusone - 1; -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if ($pageplusone) { + $page = $pageplusone - 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,desc,desc'; -if (!$sortfield) $sortfield = 'b.datev,b.dateo,b.rowid'; +if (!$sortorder) { + $sortorder = 'desc,desc,desc'; +} +if (!$sortfield) { + $sortfield = 'b.datev,b.dateo,b.rowid'; +} $object = new Account($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref); $search_account = $object->id; // Force the search field on id of account - if (!($object->id > 0)) - { + if (!($object->id > 0)) { $langs->load("errors"); print($langs->trans('ErrorRecordNotFound')); exit; @@ -127,10 +137,11 @@ if ($id > 0 || !empty($ref)) $mode_balance_ok = false; //if (($sortfield == 'b.datev' || $sortfield == 'b.datev,b.dateo,b.rowid')) // TODO Manage balance when account not selected -if (($sortfield == 'b.datev' || $sortfield == 'b.datev,b.dateo,b.rowid')) -{ +if (($sortfield == 'b.datev' || $sortfield == 'b.datev,b.dateo,b.rowid')) { $sortfield = 'b.datev,b.dateo,b.rowid'; - if ($id > 0 || !empty($ref) || $search_account > 0) $mode_balance_ok = true; + if ($id > 0 || !empty($ref) || $search_account > 0) { + $mode_balance_ok = true; + } } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -148,7 +159,7 @@ $arrayfields = array( 'b.datev'=>array('label'=>$langs->trans("DateValueShort"), 'checked'=>1), 'type'=>array('label'=>$langs->trans("Type"), 'checked'=>1), 'b.num_chq'=>array('label'=>$langs->trans("Numero"), 'checked'=>1), - 'bu.label'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>500), + 'bu.label'=>array('label'=>$langs->trans("ThirdParty").'/'.$langs->trans("User"), 'checked'=>1, 'position'=>500), 'ba.ref'=>array('label'=>$langs->trans("BankAccount"), 'checked'=>(($id > 0 || !empty($ref)) ? 0 : 1), 'position'=>1000), 'b.debit'=>array('label'=>$langs->trans("Debit"), 'checked'=>1, 'position'=>600), 'b.credit'=>array('label'=>$langs->trans("Credit"), 'checked'=>1, 'position'=>605), @@ -169,17 +180,23 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; + $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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'); +} include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; -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_dt_start = ''; $search_dt_end = ''; $search_dv_start = ''; @@ -191,17 +208,18 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_ref = ""; $search_req_nb = ''; $search_description = ''; - $search_thirdparty = ''; + $search_thirdparty_user = ''; $search_num_releve = ''; $search_conciliated = ''; $thirdparty = ''; $search_account = ""; - if ($id > 0 || !empty($ref)) $search_account = $object->id; + if ($id > 0 || !empty($ref)) { + $search_account = $object->id; + } } -if (empty($reshook)) -{ +if (empty($reshook)) { $objectclass = 'Account'; $objectlabel = 'BankTransaction'; $permissiontoread = $user->rights->banque->lire; @@ -212,15 +230,13 @@ if (empty($reshook)) // Conciliation if ((GETPOST('confirm_savestatement', 'alpha') || GETPOST('confirm_reconcile', 'alpha')) && $user->rights->banque->consolidate - && (!GETPOSTISSET('pageplusone') || (GETPOST('pageplusone') == GETPOST('pageplusoneold')))) -{ + && (!GETPOSTISSET('pageplusone') || (GETPOST('pageplusone') == GETPOST('pageplusoneold')))) { $error = 0; // Definition, nettoyage parametres $num_releve = GETPOST("num_releve", "alpha"); - if ($num_releve) - { + if ($num_releve) { $bankline = new AccountLine($db); $rowids = GETPOST('rowid', 'array'); @@ -249,22 +265,45 @@ if ((GETPOST('confirm_savestatement', 'alpha') || GETPOST('confirm_reconcile', ' setEventMessages($langs->trans("ErrorPleaseTypeBankTransactionReportName"), null, 'errors'); } - if (!$error) - { + if (!$error) { $param = 'action=reconcile&contextpage=banktransactionlist&id='.$id.'&search_account='.$id; $param .= '&search_conciliated='.urlencode($search_conciliated); - if ($page) $param .= '&page='.urlencode($page); - if ($offset) $param .= '&offset='.urlencode($offset); - if ($search_thirdparty) $param .= '&search_thirdparty='.urlencode($search_thirdparty); - if ($search_num_releve) $param .= '&search_num_releve='.urlencode($search_num_releve); - if ($search_description) $param .= '&search_description='.urlencode($search_description); - if ($search_start_dt) $param .= '&search_start_dt='.urlencode($search_start_dt); - if ($search_end_dt) $param .= '&search_end_dt='.urlencode($search_end_dt); - if ($search_start_dv) $param .= '&search_start_dv='.urlencode($search_start_dv); - if ($search_end_dv) $param .= '&search_end_dv='.urlencode($search_end_dv); - if ($search_type) $param .= '&search_type='.urlencode($search_type); - if ($search_debit) $param .= '&search_debit='.urlencode($search_debit); - if ($search_credit) $param .= '&search_credit='.urlencode($search_credit); + if ($page) { + $param .= '&page='.urlencode($page); + } + if ($offset) { + $param .= '&offset='.urlencode($offset); + } + if ($search_thirdparty_user) { + $param .= '&search_thirdparty='.urlencode($search_thirdparty_user); + } + if ($search_num_releve) { + $param .= '&search_num_releve='.urlencode($search_num_releve); + } + if ($search_description) { + $param .= '&search_description='.urlencode($search_description); + } + if ($search_start_dt) { + $param .= '&search_start_dt='.urlencode($search_start_dt); + } + if ($search_end_dt) { + $param .= '&search_end_dt='.urlencode($search_end_dt); + } + if ($search_start_dv) { + $param .= '&search_start_dv='.urlencode($search_start_dv); + } + if ($search_end_dv) { + $param .= '&search_end_dv='.urlencode($search_end_dv); + } + if ($search_type) { + $param .= '&search_type='.urlencode($search_type); + } + if ($search_debit) { + $param .= '&search_debit='.urlencode($search_debit); + } + if ($search_credit) { + $param .= '&search_credit='.urlencode($search_credit); + } $param .= '&sortfield='.urlencode($sortfield).'&sortorder='.urlencode($sortorder); header('Location: '.$_SERVER["PHP_SELF"].'?'.$param); // To avoid to submit twice and allow the back button exit; @@ -272,12 +311,10 @@ if ((GETPOST('confirm_savestatement', 'alpha') || GETPOST('confirm_reconcile', ' } -if (GETPOST('save') && !$cancel && $user->rights->banque->modifier) -{ +if (GETPOST('save') && !$cancel && $user->rights->banque->modifier) { $error = 0; - if (price2num(GETPOST("addcredit")) > 0) - { + if (price2num(GETPOST("addcredit")) > 0) { $amount = price2num(GETPOST("addcredit")); } else { $amount = - price2num(GETPOST("adddebit")); @@ -313,17 +350,16 @@ if (GETPOST('save') && !$cancel && $user->rights->banque->modifier) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankAccount")), null, 'errors'); } /*if (! empty($conf->accounting->enabled) && (empty($search_accountancy_code) || $search_accountancy_code == '-1')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("AccountAccounting")), null, 'errors'); - $error++; - }*/ + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("AccountAccounting")), null, 'errors'); + $error++; + }*/ if (!$error && !empty($conf->global->BANK_USE_OLD_VARIOUS_PAYMENT)) { $objecttmp = new Account($db); $objecttmp->fetch($bankaccountid); $insertid = $objecttmp->addline($dateop, $operation, $label, $amount, $num_chq, ($cat1 > 0 ? $cat1 : 0), $user, '', '', $search_accountancy_code); - if ($insertid > 0) - { + if ($insertid > 0) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); header("Location: ".$_SERVER['PHP_SELF'].($id ? "?id=".$id : '')); exit; @@ -335,8 +371,7 @@ if (GETPOST('save') && !$cancel && $user->rights->banque->modifier) } } -if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->banque->modifier) -{ +if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->banque->modifier) { $accline = new AccountLine($db); $result = $accline->fetch(GETPOST("rowid", "int")); $result = $accline->delete($user); @@ -359,6 +394,7 @@ $formaccounting = new FormAccounting($db); $companystatic = new Societe($db); $bankaccountstatic = new Account($db); +$userstatic= new User($db); $banktransferstatic = new BonPrelevement($db); $societestatic = new Societe($db); @@ -383,28 +419,72 @@ $now = dol_now(); // Must be before button action $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -if ($id > 0) $param .= '&id='.urlencode($id); -if (!empty($ref)) $param .= '&ref='.urlencode($ref); -if (!empty($search_ref)) $param .= '&search_ref='.urlencode($search_ref); -if (!empty($search_description)) $param .= '&search_description='.urlencode($search_description); -if (!empty($search_type)) $param .= '&type='.urlencode($search_type); -if (!empty($search_thirdparty)) $param .= '&search_thirdparty='.urlencode($search_thirdparty); -if (!empty($search_debit)) $param .= '&search_debit='.urlencode($search_debit); -if (!empty($search_credit)) $param .= '&search_credit='.urlencode($search_credit); -if (!empty($search_account)) $param .= '&search_account='.urlencode($search_account); -if (!empty($search_num_releve)) $param .= '&search_num_releve='.urlencode($search_num_releve); -if ($search_conciliated != '' && $search_conciliated != '-1') $param .= '&search_conciliated='.urlencode($search_conciliated); -if ($search_bid > 0) $param .= '&search_bid='.urlencode($search_bid); -if (dol_strlen($search_dt_start) > 0) $param .= '&search_start_dtmonth='.GETPOST('search_start_dtmonth', 'int').'&search_start_dtday='.GETPOST('search_start_dtday', 'int').'&search_start_dtyear='.GETPOST('search_start_dtyear', 'int'); -if (dol_strlen($search_dt_end) > 0) $param .= '&search_end_dtmonth='.GETPOST('search_end_dtmonth', 'int').'&search_end_dtday='.GETPOST('search_end_dtday', 'int').'&search_end_dtyear='.GETPOST('search_end_dtyear', 'int'); -if (dol_strlen($search_dv_start) > 0) $param .= '&search_start_dvmonth='.GETPOST('search_start_dvmonth', 'int').'&search_start_dvday='.GETPOST('search_start_dvday', 'int').'&search_start_dvyear='.GETPOST('search_start_dvyear', 'int'); -if (dol_strlen($search_dv_end) > 0) $param .= '&search_end_dvmonth='.GETPOST('search_end_dvmonth', 'int').'&search_end_dvday='.GETPOST('search_end_dvday', 'int').'&search_end_dvyear='.GETPOST('search_end_dvyear', 'int'); -if ($search_req_nb) $param .= '&req_nb='.urlencode($search_req_nb); -if (GETPOST("search_thirdparty", 'int')) $param .= '&thirdparty='.urlencode(GETPOST("search_thirdparty", 'int')); -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); -if ($action == 'reconcile') $param .= '&action=reconcile'; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +if ($id > 0) { + $param .= '&id='.urlencode($id); +} +if (!empty($ref)) { + $param .= '&ref='.urlencode($ref); +} +if (!empty($search_ref)) { + $param .= '&search_ref='.urlencode($search_ref); +} +if (!empty($search_description)) { + $param .= '&search_description='.urlencode($search_description); +} +if (!empty($search_type)) { + $param .= '&type='.urlencode($search_type); +} +if (!empty($search_thirdparty_user)) { + $param .= '&search_thirdparty='.urlencode($search_thirdparty_user); +} +if (!empty($search_debit)) { + $param .= '&search_debit='.urlencode($search_debit); +} +if (!empty($search_credit)) { + $param .= '&search_credit='.urlencode($search_credit); +} +if (!empty($search_account)) { + $param .= '&search_account='.urlencode($search_account); +} +if (!empty($search_num_releve)) { + $param .= '&search_num_releve='.urlencode($search_num_releve); +} +if ($search_conciliated != '' && $search_conciliated != '-1') { + $param .= '&search_conciliated='.urlencode($search_conciliated); +} +if ($search_bid > 0) { + $param .= '&search_bid='.urlencode($search_bid); +} +if (dol_strlen($search_dt_start) > 0) { + $param .= '&search_start_dtmonth='.GETPOST('search_start_dtmonth', 'int').'&search_start_dtday='.GETPOST('search_start_dtday', 'int').'&search_start_dtyear='.GETPOST('search_start_dtyear', 'int'); +} +if (dol_strlen($search_dt_end) > 0) { + $param .= '&search_end_dtmonth='.GETPOST('search_end_dtmonth', 'int').'&search_end_dtday='.GETPOST('search_end_dtday', 'int').'&search_end_dtyear='.GETPOST('search_end_dtyear', 'int'); +} +if (dol_strlen($search_dv_start) > 0) { + $param .= '&search_start_dvmonth='.GETPOST('search_start_dvmonth', 'int').'&search_start_dvday='.GETPOST('search_start_dvday', 'int').'&search_start_dvyear='.GETPOST('search_start_dvyear', 'int'); +} +if (dol_strlen($search_dv_end) > 0) { + $param .= '&search_end_dvmonth='.GETPOST('search_end_dvmonth', 'int').'&search_end_dvday='.GETPOST('search_end_dvday', 'int').'&search_end_dvyear='.GETPOST('search_end_dvyear', 'int'); +} +if ($search_req_nb) { + $param .= '&req_nb='.urlencode($search_req_nb); +} +if (GETPOST("search_thirdparty", 'int')) { + $param .= '&thirdparty='.urlencode(GETPOST("search_thirdparty", 'int')); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} +if ($action == 'reconcile') { + $param .= '&action=reconcile'; +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -413,8 +493,7 @@ $options = array(); $buttonreconcile = ''; $morehtmlref = ''; -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $title = $langs->trans("FinancialAccount").' - '.$langs->trans("Transactions"); $helpurl = ""; llxHeader('', $title, $helpurl); @@ -439,13 +518,11 @@ if ($id > 0 || !empty($ref)) /* - * Buttons actions - */ + * Buttons actions + */ - if ($action != 'reconcile') - { - if ($object->canBeConciliated() > 0) - { + if ($action != 'reconcile') { + if ($object->canBeConciliated() > 0) { $allowautomaticconciliation = false; // TODO $titletoconciliatemanual = $langs->trans("Conciliate"); $titletoconciliateauto = $langs->trans("Conciliate"); @@ -481,40 +558,72 @@ if ($id > 0 || !empty($ref)) $sql = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro as conciliated, b.num_releve, b.num_chq,"; $sql .= " b.fk_account, b.fk_type,"; -$sql .= " ba.rowid as bankid, ba.ref as bankref,"; -$sql .= " bu.url_id,"; -$sql .= " s.nom, s.name_alias, s.client, s.fournisseur, s.email, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur"; +$sql .= " ba.rowid as bankid, ba.ref as bankref"; // 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 : ''); + 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 $sql .= $hookmanager->resPrint; $sql .= " FROM "; -if ($search_bid > 0) $sql .= MAIN_DB_PREFIX."bank_class as l,"; +if ($search_bid > 0) { + $sql .= MAIN_DB_PREFIX."bank_class as l,"; +} $sql .= " ".MAIN_DB_PREFIX."bank_account as ba,"; $sql .= " ".MAIN_DB_PREFIX."bank as b"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (b.rowid = ef.fk_object)"; -$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = b.rowid AND type = 'company'"; -$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON bu.url_id = s.rowid"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (b.rowid = ef.fk_object)"; +} $sql .= " WHERE b.fk_account = ba.rowid"; $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; -if ($search_account > 0) $sql .= " AND b.fk_account = ".$search_account; +if ($search_account > 0) { + $sql .= " AND b.fk_account = ".$search_account; +} // Search period criteria -if (dol_strlen($search_dt_start) > 0) $sql .= " AND b.dateo >= '".$db->idate($search_dt_start)."'"; -if (dol_strlen($search_dt_end) > 0) $sql .= " AND b.dateo <= '".$db->idate($search_dt_end)."'"; +if (dol_strlen($search_dt_start) > 0) { + $sql .= " AND b.dateo >= '".$db->idate($search_dt_start)."'"; +} +if (dol_strlen($search_dt_end) > 0) { + $sql .= " AND b.dateo <= '".$db->idate($search_dt_end)."'"; +} // Search period criteria -if (dol_strlen($search_dv_start) > 0) $sql .= " AND b.datev >= '".$db->idate($search_dv_start)."'"; -if (dol_strlen($search_dv_end) > 0) $sql .= " AND b.datev <= '".$db->idate($search_dv_end)."'"; -if ($search_ref) $sql .= natural_search("b.rowid", $search_ref, 1); -if ($search_req_nb) $sql .= natural_search("b.num_chq", $search_req_nb); -if ($search_num_releve) $sql .= natural_search("b.num_releve", $search_num_releve); -if ($search_conciliated != '' && $search_conciliated != '-1') $sql .= " AND b.rappro = ".urlencode($search_conciliated); -if ($search_thirdparty) $sql .= natural_search("s.nom", $search_thirdparty); -if ($search_description) -{ +if (dol_strlen($search_dv_start) > 0) { + $sql .= " AND b.datev >= '".$db->idate($search_dv_start)."'"; +} +if (dol_strlen($search_dv_end) > 0) { + $sql .= " AND b.datev <= '".$db->idate($search_dv_end)."'"; +} +if ($search_ref) { + $sql .= natural_search("b.rowid", $search_ref, 1); +} +if ($search_req_nb) { + $sql .= natural_search("b.num_chq", $search_req_nb); +} +if ($search_num_releve) { + $sql .= natural_search("b.num_releve", $search_num_releve); +} +if ($search_conciliated != '' && $search_conciliated != '-1') { + $sql .= " AND b.rappro = ".urlencode($search_conciliated); +} +if ($search_thirdparty_user) { + $sql.= " AND (b.rowid IN "; + $sql.= " ( SELECT bu.fk_bank FROM ".MAIN_DB_PREFIX."bank_url AS bu"; + $sql.= " JOIN ".MAIN_DB_PREFIX."bank AS b2 ON b2.rowid = bu.fk_bank"; + $sql.= " JOIN ".MAIN_DB_PREFIX."user AS subUser ON (bu.type = 'user' AND bu.url_id = subUser.rowid)"; + $sql.= " WHERE ". natural_search(array("subUser.firstname", "subUser.lastname"), $search_thirdparty_user, '', 1)."))"; + + $sql.= " OR b.rowid IN "; + $sql.= " ( SELECT bu.fk_bank FROM ".MAIN_DB_PREFIX."bank_url AS bu"; + $sql.= " JOIN ".MAIN_DB_PREFIX."bank AS b2 ON b2.rowid = bu.fk_bank"; + $sql.= " JOIN ".MAIN_DB_PREFIX."societe AS subSoc ON (bu.type = 'company' AND bu.url_id = subSoc.rowid)"; + $sql.= " WHERE ". natural_search(array("subSoc.nom"), $search_thirdparty_user, '', 1); + $sql.= ")"; +} +if ($search_description) { $search_description_to_use = $search_description; $arrayoffixedlabels = array( 'payment_salary', @@ -526,23 +635,30 @@ if ($search_description) 'SubscriptionPayment', 'WithdrawalPayment' ); - foreach ($arrayoffixedlabels as $keyforlabel) - { + foreach ($arrayoffixedlabels as $keyforlabel) { $translatedlabel = $langs->transnoentitiesnoconv($keyforlabel); - if (preg_match('/'.$search_description.'/i', $translatedlabel)) - { + if (preg_match('/'.$search_description.'/i', $translatedlabel)) { $search_description_to_use .= "|".$keyforlabel; } } $sql .= natural_search("b.label", $search_description_to_use); // Warning some text are just translation keys, not translated strings } -if ($search_bid > 0) $sql .= " AND b.rowid=l.lineid AND l.fk_categ=".$search_bid; -if (!empty($search_type)) $sql .= " AND b.fk_type = '".$db->escape($search_type)."' "; + +if ($search_bid > 0) { + $sql .= " AND b.rowid = l.lineid AND l.fk_categ = ".((int) $search_bid); +} +if (!empty($search_type)) { + $sql .= " AND b.fk_type = '".$db->escape($search_type)."'"; +} // Search criteria amount -$search_debit = price2num(str_replace('-', '', $search_debit)); -$search_credit = price2num(str_replace('-', '', $search_credit)); -if ($search_debit) $sql .= natural_search('- b.amount', $search_debit, 1); -if ($search_credit) $sql .= natural_search('b.amount', $search_credit, 1); +if ($search_debit) { + $sql .= natural_search('ABS(b.amount)', $search_debit, 1); + $sql .= ' AND b.amount <= 0'; +} +if ($search_credit) { + $sql .= natural_search('b.amount', $search_credit, 1); + $sql .= ' AND b.amount >= 0'; +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -555,48 +671,66 @@ $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; $nbtotalofpages = 0; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); $nbtotalofpages = ceil($nbtotalofrecords / $limit); } -if (($id > 0 || !empty($ref)) && ((string) $page == '')) -{ +if (($id > 0 || !empty($ref)) && ((string) $page == '')) { // We open a list of transaction of a dedicated account and no page was set by defaut // We force on last page. $page = ($nbtotalofpages - 1); $offset = $limit * $page; - if ($page < 0) $page = 0; + if ($page < 0) { + $page = 0; + } } -if ($page >= $nbtotalofpages) -{ +if ($page >= $nbtotalofpages) { // If we made a search and result has low page than the page number we were on $page = ($nbtotalofpages - 1); $offset = $limit * $page; - if ($page < 0) $page = 0; + if ($page < 0) { + $page = 0; + } } // If not account defined $mode_balance_ok=false -if (empty($search_account)) $mode_balance_ok = false; +if (empty($search_account)) { + $mode_balance_ok = false; +} // If a search is done $mode_balance_ok=false -if (!empty($search_ref)) $mode_balance_ok = false; -if (!empty($search_description)) $mode_balance_ok = false; -if (!empty($search_type)) $mode_balance_ok = false; -if (!empty($search_debit)) $mode_balance_ok = false; -if (!empty($search_credit)) $mode_balance_ok = false; -if (!empty($search_thirdparty)) $mode_balance_ok = false; -if ($search_conciliated != '' && $search_conciliated != '-1') $mode_balance_ok = false; -if (!empty($search_num_releve)) $mode_balance_ok = false; +if (!empty($search_ref)) { + $mode_balance_ok = false; +} +if (!empty($search_description)) { + $mode_balance_ok = false; +} +if (!empty($search_type)) { + $mode_balance_ok = false; +} +if (!empty($search_debit)) { + $mode_balance_ok = false; +} +if (!empty($search_credit)) { + $mode_balance_ok = false; +} +if (!empty($search_thirdparty_user)) { + $mode_balance_ok = false; +} +if ($search_conciliated != '' && $search_conciliated != '-1') { + $mode_balance_ok = false; +} +if (!empty($search_num_releve)) { + $mode_balance_ok = false; +} $sql .= $db->plimit($limit + 1, $offset); //print $sql; dol_syslog('compta/bank/bankentries_list.php', LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); @@ -607,19 +741,22 @@ if ($resql) //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->bank->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); // Confirmation delete - if ($action == 'delete') - { + if ($action == 'delete') { $text = $langs->trans('ConfirmDeleteTransaction'); print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id.'&rowid='.GETPOST("rowid"), $langs->trans('DeleteTransaction'), $text, 'confirm_delete', null, '', 1); } // Lines of title fields print '
    '."\n"; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; @@ -629,17 +766,17 @@ if ($resql) print ''; print ''; print ''; - if (GETPOST('bid')) print ''; + if (GETPOST('bid')) { + print ''; + } // Form to reconcile - if ($user->rights->banque->consolidate && $action == 'reconcile') - { + if ($user->rights->banque->consolidate && $action == 'reconcile') { print '
    '; print ''.$langs->trans("InputReceiptNumber").': '; print ''; // The only default value is value we just entered print '
    '; - if (is_array($options) && count($options)) - { + if (is_array($options) && count($options)) { print $langs->trans("EventualyAddCategory").': '; print Form::selectarray('cat', $options, GETPOST('cat'), 1); } @@ -661,13 +798,11 @@ if ($resql) print '
    '; print $langs->trans("LastAccountStatements").' : '; $resqlr = $db->query($sql); - if ($resqlr) - { + if ($resqlr) { $numr = $db->num_rows($resqlr); $i = 0; $last_ok = 0; - while (($i < $numr) && ($i < $nbmax)) - { + while (($i < $numr) && ($i < $nbmax)) { $objr = $db->fetch_object($resqlr); if (!$last_ok) { $last_releve = $objr->num_releve; @@ -676,16 +811,19 @@ if ($resql) $i++; $liste = ''.$objr->num_releve.'   '.$liste; } - if ($numr >= $nbmax) $liste = "...   ".$liste; + if ($numr >= $nbmax) { + $liste = "...   ".$liste; + } print $liste; - if ($numr <= 0) print ''.$langs->trans("None").''; + if ($numr <= 0) { + print ''.$langs->trans("None").''; + } } else { dol_print_error($db); } // Using BANK_REPORT_LAST_NUM_RELEVE to automatically report last num (or not) - if (!empty($conf->global->BANK_REPORT_LAST_NUM_RELEVE)) - { + if (!empty($conf->global->BANK_REPORT_LAST_NUM_RELEVE)) { print ' '."\n"; + } + print ''; print ''; print ''; @@ -381,8 +412,7 @@ if ($action == 'create') print '
    '; print $form->editfieldkey('BankAccount', 'selectaccountid', '', $object, 0, 'string', '', 1).''; $form->select_comptes($accountid, "accountid", 0, '', 2); // Affiche liste des comptes courant @@ -390,19 +420,29 @@ if ($action == 'create') } // Type payment - print '
    '; - print $form->editfieldkey('PaymentMode', 'selectpaymenttype', '', $object, 0, 'string', '', 1).''; - $form->select_types_paiements($paymenttype, "paymenttype"); - print '
    '.$langs->trans('PaymentMode').''; + $form->select_types_paiements($paymenttype, 'paymenttype', '', 2); + print "
    '.$langs->trans("Sens").''.$sens.'
    '.$langs->trans("Amount").''.price($object->amount, 0, $outputlangs, 1, -1, -1, $conf->currency).'
    '; print $langs->trans("AccountAccounting"); print ''; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->accountancy_code, 1); @@ -599,10 +637,8 @@ if ($id) print $form->editfieldval('SubledgerAccount', 'subledger_account', $object->subledger_account, $object, (!$alreadyaccounted && $user->rights->banque->modifier), 'string', '', 0); print '
    '.$variousstatic->getNomUrl(1)."'.$variousstatic->label."'.dol_print_date($obj->datep, 'day')."'.dol_print_date($obj->datev, 'day')."'; - if ($obj->bid > 0) - { + if ($obj->bid > 0) { $accountstatic->id = $obj->bid; $accountstatic->ref = $obj->bref; $accountstatic->number = $obj->bnumber; @@ -504,14 +639,18 @@ if ($result) print ' '; } print ''.$bankline->getNomUrl(1).''.$accountingaccount->getNomUrl(0, 1, 1, '', 1).''.length_accounta($obj->subledger_account).''; - if ($obj->sens == 0) - { + if ($obj->sens == 0) { print price($obj->amount); $totalarray['val']['total_deb'] += $obj->amount; } - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'total_deb'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'total_deb'; + } print ''; - if ($obj->sens == 1) - { + if ($obj->sens == 1) { print price($obj->amount); $totalarray['val']['total_cred'] += $obj->amount; } - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'total_cred'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'total_cred'; + } print '
    '; $retstring = ''; - for ($year = $syear - 10; $year < $syear + 10; $year++) - { + for ($year = $syear - 10; $year < $syear + 10; $year++) { $retstring .= ''; } $retstring .= "\n"; @@ -428,8 +439,7 @@ if ($action == "create" || $action == "start" || $action == 'close') print ''; $retstring = ''; $retstring .= ''; - for ($month = 1; $month <= 12; $month++) - { + for ($month = 1; $month <= 12; $month++) { $retstring .= '"; @@ -441,8 +451,7 @@ if ($action == "create" || $action == "start" || $action == 'close') print ''; $retstring = ''; $retstring .= ''; - for ($day = 1; $day <= 31; $day++) - { + for ($day = 1; $day <= 31; $day++) { $retstring .= ''; } $retstring .= ""; @@ -450,8 +459,7 @@ if ($action == "create" || $action == "start" || $action == 'close') print ''; - if ($action == 'start' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '-1') - { + if ($action == 'start' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '-1') { print ''; } else { print ''; @@ -461,8 +469,7 @@ if ($action == "create" || $action == "start" || $action == 'close') print ''; // Table to see/enter balance - if (($action == 'start' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '-1') || $action == 'close') - { + if (($action == 'start' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '-1') || $action == 'close') { $posmodule = GETPOST('posmodule', 'alpha'); $terminalid = GETPOST('posnumber', 'alpha'); @@ -511,10 +518,10 @@ if ($action == "create" || $action == "start" || $action == 'close') $i = 0; foreach ($arrayofpaymentmode as $key => $val) { - print ''; - print $theoricalnbofinvoiceforterminal[$terminalid][$key]; - print ''; + print $theoricalnbofinvoiceforterminal[$terminalid][$key]; + print ''; print ''; print ''; print ''; - if ($action == 'start') print ''; - elseif ($action == 'close') print ''; + if ($action == 'start') { + print ''; + } elseif ($action == 'close') { + print ''; + } print '
    '.$langs->trans("InitialBankBalance").' - '.$langs->trans("Cash").''; print price($object->opening, 0, $langs, 1, -1, -1, $conf->currency); print "
    '.$langs->trans($val).''; print price($object->$key, 0, $langs, 1, -1, -1, $conf->currency); print "
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; + print '
    '; + print '
    '.$langs->trans("Module").''.$langs->trans("Terminal").''.$langs->trans("Year").''.$langs->trans("Month").''.$langs->trans("Day").'
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; - $disabled = 1; - $prefix = 'close'; + $disabled = 1; + $prefix = 'close'; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; - // Year - print ''; - // Month - print ''; - // Day - print ''; + $array = array(); + $numterminals = max(1, $conf->global->TAKEPOS_NUM_TERMINALS); + for($i = 1; $i <= $numterminals; $i++) { + $array[$i] = $i; + } + $selectedposnumber = $object->posnumber; $showempty = 1; + //print $form->selectarray('posnumber', $array, GETPOSTISSET('posnumber') ?GETPOST('posnumber', 'int') : $selectedposnumber, $showempty, 0, 0, '', 0, 0, $disabled); + print ''; + print ''; + print ''; + // Year + print ''; + // Month + print ''; + // Day + print ''; print ''; - print '
    '.$langs->trans("Module").''.$langs->trans("Terminal").''.$langs->trans("Year").''.$langs->trans("Month").''.$langs->trans("Day").'
    '.$form->selectarray('posmodulebis', $arrayofposavailable, $object->posmodule, (count($arrayofposavailable) > 1 ? 1 : 0), 0, 0, '', 0, 0, $disabled).''; + print '
    '.$form->selectarray('posmodulebis', $arrayofposavailable, $object->posmodule, (count($arrayofposavailable) > 1 ? 1 : 0), 0, 0, '', 0, 0, $disabled).''; - $array = array(); - $numterminals = max(1, $conf->global->TAKEPOS_NUM_TERMINALS); - for($i = 1; $i <= $numterminals; $i++) { - $array[$i] = $i; - } - $selectedposnumber = $object->posnumber; $showempty = 1; - //print $form->selectarray('posnumber', $array, GETPOSTISSET('posnumber') ?GETPOST('posnumber', 'int') : $selectedposnumber, $showempty, 0, 0, '', 0, 0, $disabled); - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
    '; - print ''; - */ + print '
    '; + print ''; + */ // Table to see/enter balance - if (($action == 'start' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '-1') || $action == 'close') - { + if (($action == 'start' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '-1') || $action == 'close') { $posmodule = $object->posmodule; $terminalid = $object->posnumber; @@ -774,8 +785,7 @@ if (empty($action) || $action == "view" || $action == "close") //print '
    '.$langs->trans("TheoricalAmount").'
    '.$langs->trans("RealAmount"); print '
    '.$langs->trans($val); //print '
    '.$langs->trans("TheoricalAmount").'
    '.$langs->trans("RealAmount"); print '
    '; print $theoricalnbofinvoiceforterminal[$terminalid][$key]; print ''; if ($key == 'cash') { $deltaforcash = ($object->opening - $initialbalanceforterminal[$terminalid]['cash']); @@ -831,22 +839,26 @@ if (empty($action) || $action == "view" || $action == "close") // Initial amount print ''; print ''; print ''; print ''; print ''; print ''; - if ($action == 'start') print ''; - elseif ($action == 'close') print ''; + if ($action == 'start') { + print ''; + } elseif ($action == 'close') { + print ''; + } print '
    '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; } } @@ -407,15 +441,18 @@ print ''."\n"; // Fields title label // -------------------------------------------------------------------- print ''; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -431,11 +468,11 @@ print ''."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -444,42 +481,57 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->id = $obj->rowid; - foreach ($object->fields as $key => $val) - { - if (property_exists($obj, $key)) $object->$key = $obj->$key; + foreach ($object->fields as $key => $val) { + if (property_exists($obj, $key)) { + $object->$key = $obj->$key; + } } // Show here line of result print ''; - foreach ($object->fields as $key => $val) - { + foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; - if ($key == 'status') print $object->getLibStatut(5); - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); - else print $object->showOutputField($val, $key, $obj->$key, ''); + if ($key == 'status') { + print $object->getLibStatut(5); + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); + } else { + print $object->showOutputField($val, $key, $obj->$key, ''); + } print ''; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $obj->$key; } } @@ -492,14 +544,17 @@ while ($i < min($num, $limit)) print $hookmanager->resPrint; // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print ''; @@ -511,10 +566,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 ''; } @@ -529,10 +587,11 @@ print ''."\n"; print ''."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/compta/cashcontrol/class/cashcontrol.class.php b/htdocs/compta/cashcontrol/class/cashcontrol.class.php index 842322f7f20..1b9860c976a 100644 --- a/htdocs/compta/cashcontrol/class/cashcontrol.class.php +++ b/htdocs/compta/cashcontrol/class/cashcontrol.class.php @@ -136,9 +136,15 @@ class CashControl extends CommonObject $error = 0; // Clean data - if (empty($this->cash)) $this->cash = 0; - if (empty($this->cheque)) $this->cheque = 0; - if (empty($this->card)) $this->card = 0; + if (empty($this->cash)) { + $this->cash = 0; + } + if (empty($this->cheque)) { + $this->cheque = 0; + } + if (empty($this->card)) { + $this->card = 0; + } // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."pos_cash_fence ("; @@ -216,8 +222,7 @@ class CashControl extends CommonObject $error = 0; // Protection - if ($this->status == self::STATUS_VALIDATED) - { + if ($this->status == self::STATUS_VALIDATED) { dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); return 0; } @@ -239,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(); @@ -256,11 +261,12 @@ class CashControl extends CommonObject $this->fk_user_valid = $user->id; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CASHCONTROL_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -340,8 +346,7 @@ class CashControl extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[0] = $langs->trans('Draft'); @@ -351,7 +356,9 @@ class CashControl extends CommonObject } $statusType = 'status0'; - if ($status == self::STATUS_VALIDATED) $statusType = 'status6'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status6'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -370,7 +377,9 @@ class CashControl extends CommonObject { global $conf, $langs, $hookmanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -382,19 +391,20 @@ class CashControl extends CommonObject $url = DOL_URL_ROOT.'/compta/cashcontrol/cashcontrol_card.php?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowMyObject"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -402,20 +412,26 @@ class CashControl extends CommonObject $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; /* - $hookmanager->initHooks(array('myobjectdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + $hookmanager->initHooks(array('myobjectdao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $linkclose = $hookmanager->resPrint; + */ + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); diff --git a/htdocs/compta/cashcontrol/report.php b/htdocs/compta/cashcontrol/report.php index 04cdea52f7f..95c18dbf261 100644 --- a/htdocs/compta/cashcontrol/report.php +++ b/htdocs/compta/cashcontrol/report.php @@ -29,8 +29,12 @@ * \brief List of bank transactions */ -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); // Disable browser notification +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/cashcontrol/class/cashcontrol.class.php'; @@ -68,14 +72,24 @@ $sday = $cashcontrol->day_close; $posmodule = $cashcontrol->posmodule; $terminalid = $cashcontrol->posnumber; +// Security check +if ($user->socid > 0) { // Protection if external user + //$socid = $user->socid; + accessforbidden(); +} +if (!$user->rights->cashdesk->run && !$user->rights->takepos->run) { + accessforbidden(); +} + /* * View */ +$title = $langs->trans("CashControl"); $param = ''; -llxHeader('', $langs->trans("CashControl"), '', '', 0, 0, array(), array(), $param); +llxHeader('', $title, '', '', 0, 0, array(), array(), $param); /*$sql = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro as conciliated, b.num_releve, b.num_chq,"; $sql.= " b.fk_account, b.fk_type,"; @@ -110,7 +124,7 @@ $sql .= " WHERE pf.fk_facture = f.rowid AND p.rowid = pf.fk_paiement AND cp.id = $sql .= " AND f.module_source = '".$db->escape($posmodule)."'"; $sql .= " AND f.pos_source = '".$db->escape($terminalid)."'"; $sql .= " AND f.paye = 1"; -$sql .= " AND p.entity IN (".getEntity('facture').")"; +$sql .= " AND p.entity = ".$conf->entity; // Never share entities for features related to accountancy /*if ($key == 'cash') $sql.=" AND cp.code = 'LIQ'"; elseif ($key == 'cheque') $sql.=" AND cp.code = 'CHQ'"; elseif ($key == 'card') $sql.=" AND cp.code = 'CB'"; @@ -119,10 +133,15 @@ else dol_print_error('Value for key = '.$key.' not supported'); exit; }*/ -if ($syear && !$smonth) $sql .= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, 1))."' AND '".$db->idate(dol_get_last_day($syear, 12))."'"; -elseif ($syear && $smonth && !$sday) $sql .= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, $smonth))."' AND '".$db->idate(dol_get_last_day($syear, $smonth))."'"; -elseif ($syear && $smonth && $sday) $sql .= " AND datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $smonth, $sday, $syear))."'"; -else dol_print_error('', 'Year not defined'); +if ($syear && !$smonth) { + $sql .= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, 1))."' AND '".$db->idate(dol_get_last_day($syear, 12))."'"; +} elseif ($syear && $smonth && !$sday) { + $sql .= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, $smonth))."' AND '".$db->idate(dol_get_last_day($syear, $smonth))."'"; +} elseif ($syear && $smonth && $sday) { + $sql .= " AND datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $smonth, $sday, $syear))."'"; +} else { + dol_print_error('', 'Year not defined'); +} $resql = $db->query($sql); if ($resql) { @@ -131,8 +150,11 @@ if ($resql) { print "\n"; print "

    "; - if ($cashcontrol->status != $cashcontrol::STATUS_DRAFT) print $langs->trans("CashControl")." ".$cashcontrol->id; - else print $langs->trans("CashControl")." - ".$langs->trans("Draft"); + if ($cashcontrol->status != $cashcontrol::STATUS_DRAFT) { + print $langs->trans("CashControl")." ".$cashcontrol->id; + } else { + print $langs->trans("CashControl")." - ".$langs->trans("Draft"); + } print "
    ".$langs->trans("DateCreationShort").": ".dol_print_date($cashcontrol->date_creation, 'dayhour'); print "

    "; @@ -193,13 +215,17 @@ if ($resql) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } // Date ope print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } // Bank account print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } // Type print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } // Debit print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totaldebfield'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'totaldebfield'; + } // Credit print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalcredfield'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'totalcredfield'; + } print ""; @@ -296,7 +339,7 @@ if ($resql) { $sql = "UPDATE ".MAIN_DB_PREFIX."pos_cash_fence "; $sql .= "SET"; $sql .= " cash='".$db->escape($cash)."'"; - $sql .= ", card='".$db->escape($bank)."'"; + $sql .= ", card='".$db->escape($bank)."'"; $sql .= " where rowid=".$id; $db->query($sql); */ diff --git a/htdocs/compta/charges/index.php b/htdocs/compta/charges/index.php index 3588dced3f4..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'; @@ -45,13 +46,17 @@ $hookmanager->initHooks(array('specialexpensesindex')); $langs->loadLangs(array('compta', 'bills')); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax|salaries', '', '', 'charges|'); $mode = GETPOST("mode", 'alpha'); $year = GETPOST("year", 'int'); $filtre = GETPOST("filtre", 'alpha'); -if (!$year) { $year = date("Y", time()); } +if (!$year) { + $year = date("Y", time()); +} $search_account = GETPOST('search_account', 'int'); @@ -59,12 +64,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 (!$sortfield) $sortfield = "cs.date_ech"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "cs.date_ech"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} /* @@ -74,7 +85,7 @@ if (!$sortorder) $sortorder = "DESC"; $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")); @@ -82,16 +93,26 @@ llxHeader('', $langs->trans("SpecialExpensesArea")); $title = $langs->trans("SpecialExpensesArea"); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; -if ($sortfield) $param .= '&sortfield='.$sortfield; -if ($sortorder) $param .= '&sortorder='.$sortorder; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.$contextpage; +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; +} +if ($sortfield) { + $param .= '&sortfield='.$sortfield; +} +if ($sortorder) { + $param .= '&sortorder='.$sortorder; +} $totalnboflines = 0; $num = 0; print '
    '; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -102,13 +123,14 @@ print ''; $nav = ($year ? ''.img_previous($langs->trans("Previous"), 'class="valignbottom"')." ".$langs->trans("Year").' '.$year.' '.img_next($langs->trans("Next"), 'class="valignbottom"')."" : ""); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, 'object_payment', 0, $nav, '', $limit, 1); -if ($year) $param .= '&year='.$year; +if ($year) { + $param .= '&year='.$year; +} print ''.$langs->trans("DescTaxAndDividendsArea").'
    '; print "
    "; -if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) -{ +if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) { // Social contributions only print load_fiche_titre($langs->trans("SocialContributionsPayments").($year ? ' ('.$langs->trans("Year").' '.$year.')' : ''), '', ''); @@ -121,7 +143,9 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print_liste_field_titre("RefPayment", $_SERVER["PHP_SELF"], "pc.rowid", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "pc.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); + 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"], "pc.amount", "", $param, 'class="right"', $sortfield, $sortorder); print "\n"; @@ -138,8 +162,7 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql .= " WHERE cs.fk_type = c.id"; $sql .= " AND cs.entity IN (".getEntity("tax").")"; - if ($year > 0) - { + if ($year > 0) { $sql .= " AND ("; // Si period renseignee on l'utilise comme critere de date, sinon on prend date echeance, // ceci afin d'etre compatible avec les cas ou la periode n'etait pas obligatoire @@ -147,27 +170,29 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql .= " OR (cs.periode IS NULL AND cs.date_ech between '".$db->idate(dol_get_first_day($year))."' AND '".$db->idate(dol_get_last_day($year))."')"; $sql .= ")"; } - if (preg_match('/^cs\./', $sortfield) || preg_match('/^c\./', $sortfield) || preg_match('/^pc\./', $sortfield) || preg_match('/^pct\./', $sortfield)) $sql .= $db->order($sortfield, $sortorder); + if (preg_match('/^cs\./', $sortfield) || preg_match('/^c\./', $sortfield) || preg_match('/^pc\./', $sortfield) || preg_match('/^pct\./', $sortfield)) { + $sql .= $db->order($sortfield, $sortorder); + } //$sql.= $db->plimit($limit+1,$offset); //print $sql; dol_syslog("compta/charges/index.php: select payment", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; $total = 0; $totalnb = 0; $totalpaye = 0; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); print '
    '; // Date $date = $obj->periode; - if (empty($date)) $date = $obj->date_ech; + if (empty($date)) { + $date = $obj->date_ech; + } print ''; // Label print ''; // Type payment print ''; // Account - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print ''; } // Paid print ''; print ''; @@ -223,7 +252,9 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print ''; print ''; print ''; - if (!empty($conf->banque->enabled)) print ''; + if (!empty($conf->banque->enabled)) { + print ''; + } print '"; print ""; } else { @@ -233,8 +264,7 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) } // VAT -if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) -{ +if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) { print "
    "; $tva = new Tva($db); @@ -249,17 +279,17 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $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 pv.fk_typepayment = pct.id"; $sql .= " WHERE pv.entity IN (".getEntity("tax").")"; - if ($year > 0) - { + if ($year > 0) { // Si period renseignee on l'utilise comme critere de date, sinon on prend date echeance, // ceci afin d'etre compatible avec les cas ou la periode n'etait pas obligatoire $sql .= " AND pv.datev between '".$db->idate(dol_get_first_day($year, 1, false))."' AND '".$db->idate(dol_get_last_day($year, 12, false))."'"; } - if (preg_match('/^pv\./', $sortfield)) $sql .= $db->order($sortfield, $sortorder); + if (preg_match('/^pv\./', $sortfield)) { + $sql .= $db->order($sortfield, $sortorder); + } $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $i = 0; $total = 0; @@ -271,12 +301,13 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print_liste_field_titre("RefPayment", $_SERVER["PHP_SELF"], "pv.rowid", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "pv.datev", "", $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); + 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"], "pv.amount", "", $param, 'class="right"', $sortfield, $sortorder); print "\n"; $var = 1; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); $total = $total + $obj->amount; @@ -299,15 +330,15 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) // Type payment print ''; // Account - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print ''; } @@ -343,16 +376,13 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) } // Localtax -if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") -{ +if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { $j = 1; $numlt = 3; -} elseif ($mysoc->localtax1_assuj == "1") -{ +} elseif ($mysoc->localtax1_assuj == "1") { $j = 1; $numlt = 2; -} elseif ($mysoc->localtax2_assuj == "1") -{ +} elseif ($mysoc->localtax2_assuj == "1") { $j = 2; $numlt = 3; } else { @@ -360,8 +390,7 @@ if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") $numlt = 0; } -while ($j < $numlt) -{ +while ($j < $numlt) { print "
    "; $tva = new Tva($db); @@ -372,20 +401,22 @@ while ($j < $numlt) $sql = "SELECT pv.rowid, pv.amount, pv.label, pv.datev as dm, pv.datep as dp"; $sql .= " FROM ".MAIN_DB_PREFIX."localtax as pv"; $sql .= " WHERE pv.entity = ".$conf->entity." AND localtaxtype = ".$j; - if ($year > 0) - { + if ($year > 0) { // Si period renseignee on l'utilise comme critere de date, sinon on prend date echeance, // ceci afin d'etre compatible avec les cas ou la periode n'etait pas obligatoire $sql .= " AND pv.datev between '".$db->idate(dol_get_first_day($year, 1, false))."' AND '".$db->idate(dol_get_last_day($year, 12, false))."'"; } - if (preg_match('/^pv/', $sortfield)) $sql .= $db->order($sortfield, $sortorder); + if (preg_match('/^pv/', $sortfield)) { + $sql .= $db->order($sortfield, $sortorder); + } $result = $db->query($sql); - if ($result) - { + if ($result) { $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 '
    '; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - else print ''; + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } else { + print ''; + } print '
    '; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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").'
    '; print $invoicetmp->getNomUrl(1); print ''; print ''.dol_print_date($db->jdate($objp->do), "day").""; print "'; @@ -214,20 +240,29 @@ if ($resql) { } elseif ($objp->code == 'CB') { $bank += $objp->amount; } 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 $other += $objp->amount; + 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 { + $other += $objp->amount; + } } print "'; - print $objp->code; - if (empty($amountpertype[$objp->code])) $amountpertype[$objp->code] = 0; + print $objp->code; + if (empty($amountpertype[$objp->code])) { + $amountpertype[$objp->code] = 0; + } print "'; @@ -237,8 +272,12 @@ if ($resql) { $amountpertype[$objp->code] += $objp->amount; } print "'; @@ -248,8 +287,12 @@ if ($resql) { $amountpertype[$objp->code] -= $objp->amount; } print "
    '.dol_print_date($date, 'day').''; @@ -188,14 +213,14 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print ''.dol_print_date($db->jdate($obj->datep), 'day').''; - if ($obj->payment_code) print $langs->trans("PaymentTypeShort".$obj->payment_code).' '; + if ($obj->payment_code) { + print $langs->trans("PaymentTypeShort".$obj->payment_code).' '; + } print $obj->num_payment.''; - if ($obj->fk_bank > 0) - { + if ($obj->fk_bank > 0) { //$accountstatic->fetch($obj->fk_bank); $accountstatic->id = $obj->bid; $accountstatic->ref = $obj->bref; @@ -204,12 +229,16 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $accountstatic->accountancy_journal = $obj->accountancy_journal; $accountstatic->label = $obj->blabel; print $accountstatic->getNomUrl(1); - } else print ' '; + } else { + print ' '; + } print ''; - if ($obj->totalpaye) print price($obj->totalpaye); + if ($obj->totalpaye) { + print price($obj->totalpaye); + } print '
       '.price($totalpaye)."
    '; - if ($obj->payment_code) print $langs->trans("PaymentTypeShort".$obj->payment_code).' '; + if ($obj->payment_code) { + print $langs->trans("PaymentTypeShort".$obj->payment_code).' '; + } print $obj->num_payment.''; - if ($obj->fk_bank > 0) - { + if ($obj->fk_bank > 0) { //$accountstatic->fetch($obj->fk_bank); $accountstatic->id = $obj->bid; $accountstatic->ref = $obj->bref; @@ -316,7 +347,9 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $accountstatic->accountancy_journal = $obj->accountancy_journal; $accountstatic->label = $obj->blabel; print $accountstatic->getNomUrl(1); - } else print ' '; + } else { + print ' '; + } print '
    '; print ''; print_liste_field_titre("PeriodEndDate", $_SERVER["PHP_SELF"], "pv.datev", "", $param, 'width="120"', $sortfield, $sortorder); @@ -396,8 +427,7 @@ while ($j < $numlt) print_liste_field_titre("PayedByThisPayment", $_SERVER["PHP_SELF"], "pv.amount", "", $param, 'class="right"', $sortfield, $sortorder); print "\n"; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); $total = $total + $obj->amount; @@ -428,6 +458,8 @@ while ($j < $numlt) print ""; print "
    "; + print ''; + $db->free($result); } else { dol_print_error($db); @@ -436,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/clients.php b/htdocs/compta/clients.php index 1b4e86bbb4c..191038ed28a 100644 --- a/htdocs/compta/clients.php +++ b/htdocs/compta/clients.php @@ -30,14 +30,14 @@ require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; $action = GETPOST('action', 'aZ09'); // Secrutiy check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } -if (!$user->rights->facture->lire) -accessforbidden(); +if (!$user->rights->facture->lire) { + accessforbidden(); +} // Load translation files required by the page $langs->load("companies"); @@ -48,12 +48,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 = "nom"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "nom"; +} /* @@ -64,14 +70,12 @@ llxHeader(); $thirdpartystatic = new Societe($db); -if ($action == 'note') -{ +if ($action == 'note') { $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET note='".$db->escape($note)."' WHERE rowid=".$socid; $result = $db->query($sql); } -if ($mode == 'search') -{ +if ($mode == 'search') { $resql = $db->query($sql); if ($resql) { if ($db->num_rows($resql) == 1) { @@ -90,40 +94,39 @@ if ($mode == 'search') $sql = "SELECT s.rowid, s.nom as name, s.client, s.town, s.datec, s.datea"; $sql .= ", st.libelle as stcomm, s.prefix_comm, s.code_client, s.code_compta "; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; +} $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."c_stcomm as st"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE s.fk_stcomm = st.id AND s.client in (1, 3)"; $sql .= " AND s.entity IN (".getEntity('societe').")"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if (dol_strlen($stcomm)) -{ +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if (dol_strlen($stcomm)) { $sql .= " AND s.fk_stcomm=".$stcomm; } -if ($socname) -{ +if ($socname) { $sql .= natural_search("s.nom", $socname); $sortfield = "s.nom"; $sortorder = "ASC"; } -if ($_GET["search_nom"]) -{ +if ($_GET["search_nom"]) { $sql .= natural_search("s.nom", GETPOST("search_nom")); } -if ($_GET["search_compta"]) -{ +if ($_GET["search_compta"]) { $sql .= natural_search("s.code_compta", GETPOST("search_compta")); } -if ($_GET["search_code_client"]) -{ +if ($_GET["search_code_client"]) { $sql .= natural_search("s.code_client", GETPOST("search_code_client")); } -if (dol_strlen($begin)) -{ +if (dol_strlen($begin)) { $sql .= natural_search("s.nom", $begin); } -if ($socid) -{ +if ($socid) { $sql .= " AND s.rowid = ".$socid; } $sql .= " ORDER BY $sortfield $sortorder "; @@ -131,8 +134,7 @@ $sql .= $db->plimit($conf->liste_limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -173,8 +175,7 @@ if ($resql) print '
    '.$langs->trans('NotePrivate').''; @@ -284,23 +268,19 @@ if ($action == 'create') print ''; print ''; -} elseif ($id) -{ +} elseif ($id) { $result = $object->fetch($id); - if ($result > 0) - { + if ($result > 0) { $head = trip_prepare_head($object); print dol_get_fiche_head($head, 'card', $langs->trans("TripCard"), 0, 'trip'); - if ($action == 'edit' && $user->rights->deplacement->creer) - { + if ($action == 'edit' && $user->rights->deplacement->creer) { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $soc = new Societe($db); - if ($object->socid) - { + if ($object->socid) { $soc->fetch($object->socid); } @@ -355,8 +335,7 @@ if ($action == 'create') print "
    '.$langs->trans("NotePrivate").''; @@ -384,15 +363,16 @@ if ($action == 'create') print ''; } else { /* - * Confirm delete trip - */ - if ($action == 'delete') - { + * Confirm delete trip + */ + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("DeleteTrip"), $langs->trans("ConfirmDeleteTrip"), "confirm_delete"); } $soc = new Societe($db); - if ($object->socid) $soc->fetch($object->socid); + if ($object->socid) { + $soc->fetch($object->socid); + } print ''; @@ -436,12 +416,13 @@ if ($action == 'create') // Where print ''; print ''; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load('projects'); print ''; print ''; print "\n"; $listoftype = $tripandexpense_static->listOfTypes(); -foreach ($listoftype as $code => $label) -{ +foreach ($listoftype as $code => $label) { $dataseries[] = array($label, (isset($nb[$code]) ? (int) $nb[$code] : 0)); } -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print ''; print ''; print ''; - if ($num) - { + if ($num) { $total_ttc = $totalam = $total = 0; $deplacementstatic = new Deplacement($db); $userstatic = new User($db); - while ($i < $num && $i < $max) - { + while ($i < $num && $i < $max) { $obj = $db->fetch_object($result); $deplacementstatic->ref = $obj->rowid; $deplacementstatic->id = $obj->rowid; @@ -196,7 +207,9 @@ if ($result) print ''; } print '
    '.$langs->trans("CompanyVisited").''; - if ($soc->id) print $soc->getNomUrl(1); + if ($soc->id) { + print $soc->getNomUrl(1); + } print '
    '; @@ -449,16 +430,14 @@ if ($action == 'create') print ''; - if ($action != 'classify' && $user->rights->deplacement->creer) - { + if ($action != 'classify' && $user->rights->deplacement->creer) { print ''; } print '
    '; print $langs->trans('Project'); print 'id.'">'; print img_edit($langs->trans('SetProject'), 1); print '
    '; print '
    '; - if ($action == 'classify') - { + if ($action == 'classify') { $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1); } else { $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0); @@ -484,43 +463,35 @@ if ($action == 'create') print ''; /* - * Barre d'actions - */ - + * Action bar + */ print '
    '; - if ($object->statut < Deplacement::STATUS_REFUNDED) // if not refunded - { - if ($user->rights->deplacement->creer) - { + if ($object->statut < Deplacement::STATUS_REFUNDED) { // if not refunded + if ($user->rights->deplacement->creer) { print ''.$langs->trans('Modify').''; } else { print ''.$langs->trans('Modify').''; } } - if ($object->statut == Deplacement::STATUS_DRAFT) // if draft - { - if ($user->rights->deplacement->creer) - { + if ($object->statut == Deplacement::STATUS_DRAFT) { // if draft + if ($user->rights->deplacement->creer) { print ''.$langs->trans('Validate').''; } else { print ''.$langs->trans('Validate').''; } } - if ($object->statut == Deplacement::STATUS_VALIDATED) // if validated - { - if ($user->rights->deplacement->creer) - { + if ($object->statut == Deplacement::STATUS_VALIDATED) { // if validated + if ($user->rights->deplacement->creer) { print ''.$langs->trans('ClassifyRefunded').''; } else { print ''.$langs->trans('ClassifyRefunded').''; } } - if ($user->rights->deplacement->supprimer) - { + if ($user->rights->deplacement->supprimer) { print ''.$langs->trans('Delete').''; } else { print ''.$langs->trans('Delete').''; diff --git a/htdocs/compta/deplacement/class/deplacement.class.php b/htdocs/compta/deplacement/class/deplacement.class.php index 75d2f71284c..c34d89bfa2f 100644 --- a/htdocs/compta/deplacement/class/deplacement.class.php +++ b/htdocs/compta/deplacement/class/deplacement.class.php @@ -141,13 +141,11 @@ class Deplacement extends CommonObject global $conf; // Check parameters - if (empty($this->type) || $this->type < 0) - { + if (empty($this->type) || $this->type < 0) { $this->error = 'ErrorBadParameter'; return -1; } - if (empty($this->fk_user) || $this->fk_user < 0) - { + if (empty($this->fk_user) || $this->fk_user < 0) { $this->error = 'ErrorBadParameter'; return -1; } @@ -181,22 +179,19 @@ class Deplacement extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."deplacement"); // Call trigger $result = $this->call_trigger('DEPLACEMENT_CREATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -2; } // End call triggers $result = $this->update($user); - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return $this->id; } else { @@ -225,19 +220,18 @@ class Deplacement extends CommonObject $this->km = price2num($this->km); // Check parameters - if (!is_numeric($this->km)) $this->km = 0; - if (empty($this->date)) - { + if (!is_numeric($this->km)) { + $this->km = 0; + } + if (empty($this->date)) { $this->error = 'ErrorBadParameter'; return -1; } - if (empty($this->type) || $this->type < 0) - { + if (empty($this->type) || $this->type < 0) { $this->error = 'ErrorBadParameter'; return -1; } - if (empty($this->fk_user) || $this->fk_user < 0) - { + if (empty($this->fk_user) || $this->fk_user < 0) { $this->error = 'ErrorBadParameter'; return -1; } @@ -259,8 +253,7 @@ class Deplacement extends CommonObject dol_syslog(get_class($this)."::update", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->db->commit(); return 1; } else { @@ -282,13 +275,15 @@ class Deplacement extends CommonObject $sql = "SELECT rowid, fk_user, type, fk_statut, km, fk_soc, dated, note_private, note_public, fk_projet as fk_project, extraparams"; $sql .= " FROM ".MAIN_DB_PREFIX."deplacement"; $sql .= " WHERE entity IN (".getEntity('deplacement').")"; - if ($ref) $sql .= " AND ref ='".$this->db->escape($ref)."'"; - else $sql .= " AND rowid = ".$id; + if ($ref) { + $sql .= " AND ref ='".$this->db->escape($ref)."'"; + } else { + $sql .= " AND rowid = ".((int) $id); + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -322,12 +317,11 @@ 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); - if ($result) - { + if ($result) { $this->db->commit(); return 1; } else { @@ -362,32 +356,42 @@ class Deplacement extends CommonObject // phpcs:enable global $langs; - if ($mode == 0) - { + if ($mode == 0) { return $langs->trans($this->statuts[$status]); - } elseif ($mode == 1) - { + } elseif ($mode == 1) { return $langs->trans($this->statuts_short[$status]); - } elseif ($mode == 2) - { - if ($status == 0) return img_picto($langs->trans($this->statuts_short[$status]), 'statut0').' '.$langs->trans($this->statuts_short[$status]); - elseif ($status == 1) return img_picto($langs->trans($this->statuts_short[$status]), 'statut4').' '.$langs->trans($this->statuts_short[$status]); - elseif ($status == 2) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts_short[$status]); - } elseif ($mode == 3) - { - if ($status == 0 && !empty($this->statuts_short[$status])) return img_picto($langs->trans($this->statuts_short[$status]), 'statut0'); - elseif ($status == 1 && !empty($this->statuts_short[$status])) return img_picto($langs->trans($this->statuts_short[$status]), 'statut4'); - elseif ($status == 2 && !empty($this->statuts_short[$status])) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6'); - } elseif ($mode == 4) - { - if ($status == 0 && !empty($this->statuts_short[$status])) return img_picto($langs->trans($this->statuts_short[$status]), 'statut0').' '.$langs->trans($this->statuts[$status]); - elseif ($status == 1 && !empty($this->statuts_short[$status])) return img_picto($langs->trans($this->statuts_short[$status]), 'statut4').' '.$langs->trans($this->statuts[$status]); - elseif ($status == 2 && !empty($this->statuts_short[$status])) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts[$status]); - } elseif ($mode == 5) - { - if ($status == 0 && !empty($this->statuts_short[$status])) return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]), 'statut0'); - elseif ($status == 1 && !empty($this->statuts_short[$status])) return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]), 'statut4'); - elseif ($status == 2 && !empty($this->statuts_short[$status])) return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]), 'statut6'); + } elseif ($mode == 2) { + if ($status == 0) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut0').' '.$langs->trans($this->statuts_short[$status]); + } elseif ($status == 1) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut4').' '.$langs->trans($this->statuts_short[$status]); + } elseif ($status == 2) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts_short[$status]); + } + } elseif ($mode == 3) { + if ($status == 0 && !empty($this->statuts_short[$status])) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut0'); + } elseif ($status == 1 && !empty($this->statuts_short[$status])) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut4'); + } elseif ($status == 2 && !empty($this->statuts_short[$status])) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut6'); + } + } elseif ($mode == 4) { + if ($status == 0 && !empty($this->statuts_short[$status])) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut0').' '.$langs->trans($this->statuts[$status]); + } elseif ($status == 1 && !empty($this->statuts_short[$status])) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut4').' '.$langs->trans($this->statuts[$status]); + } elseif ($status == 2 && !empty($this->statuts_short[$status])) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts[$status]); + } + } elseif ($mode == 5) { + if ($status == 0 && !empty($this->statuts_short[$status])) { + return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]), 'statut0'); + } elseif ($status == 1 && !empty($this->statuts_short[$status])) { + return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]), 'statut4'); + } elseif ($status == 2 && !empty($this->statuts_short[$status])) { + return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]), 'statut6'); + } } } @@ -410,9 +414,15 @@ class Deplacement extends CommonObject $picto = 'trip'; - if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); - if ($withpicto && $withpicto != 2) $result .= ' '; - if ($withpicto != 2) $result .= $link.$this->ref.$linkend; + if ($withpicto) { + $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + if ($withpicto != 2) { + $result .= $link.$this->ref.$linkend; + } return $result; } @@ -435,12 +445,10 @@ class Deplacement extends CommonObject dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $ret[$obj->code] = (($langs->trans($obj->code) != $obj->code) ? $langs->trans($obj->code) : $obj->label); $i++; @@ -463,25 +471,21 @@ 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); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_modif) - { + if ($obj->fk_user_modif) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modif); $this->user_modification = $muser; diff --git a/htdocs/compta/deplacement/class/deplacementstats.class.php b/htdocs/compta/deplacement/class/deplacementstats.class.php index d6ad82a4cbe..bb99b477584 100644 --- a/htdocs/compta/deplacement/class/deplacementstats.class.php +++ b/htdocs/compta/deplacement/class/deplacementstats.class.php @@ -64,12 +64,14 @@ class DeplacementStats extends Stats $this->where = " fk_statut > 0"; $this->where .= " AND entity = ".$conf->entity; - if ($this->socid) - { + if ($this->socid) { $this->where .= " AND fk_soc = ".$this->socid; } - if (is_array($this->userid) && count($this->userid) > 0) $this->where .= ' AND fk_user IN ('.join(',', $this->userid).')'; - elseif ($this->userid > 0) $this->where .= ' AND fk_user = '.$this->userid; + if (is_array($this->userid) && count($this->userid) > 0) { + $this->where .= ' AND fk_user IN ('.join(',', $this->userid).')'; + } elseif ($this->userid > 0) { + $this->where .= ' AND fk_user = '.$this->userid; + } } diff --git a/htdocs/compta/deplacement/document.php b/htdocs/compta/deplacement/document.php index 86d0dd383f1..dd87a0c67f9 100644 --- a/htdocs/compta/deplacement/document.php +++ b/htdocs/compta/deplacement/document.php @@ -43,7 +43,9 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'deplacement', $id, ''); @@ -52,12 +54,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) { $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"; +} $object = new Deplacement($db); @@ -71,7 +79,7 @@ $modulepart = 'trip'; * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -83,8 +91,7 @@ $form = new Form($db); llxHeader("", "", $langs->trans("TripCard")); -if ($object->id) -{ +if ($object->id) { $object->fetch_thirdparty(); $head = trip_prepare_head($object); @@ -95,8 +102,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/compta/deplacement/index.php b/htdocs/compta/deplacement/index.php index bcebeb128d0..780835b0c5e 100644 --- a/htdocs/compta/deplacement/index.php +++ b/htdocs/compta/deplacement/index.php @@ -32,19 +32,27 @@ $langs->loadLangs(array('companies', 'users', 'trips')); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'deplacement', '', ''); $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.dated"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "d.dated"; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; @@ -67,17 +75,17 @@ $totalnb = 0; $sql = "SELECT count(d.rowid) as nb, sum(d.km) as km, d.type"; $sql .= " FROM ".MAIN_DB_PREFIX."deplacement as d"; $sql .= " WHERE d.entity = ".$conf->entity; -if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous)) $sql .= ' AND d.fk_user IN ('.join(',', $childids).')'; +if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous)) { + $sql .= ' AND d.fk_user IN ('.join(',', $childids).')'; +} $sql .= " GROUP BY d.type"; $sql .= " ORDER BY d.type"; $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($result); $somme[$objp->type] = $objp->km; @@ -104,13 +112,11 @@ print '
    '.$langs->trans("Statistics").'
    '; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -144,18 +150,25 @@ $langs->load("boxes"); $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, d.rowid, d.dated as date, d.tms as dm, d.km, d.fk_statut"; $sql .= " FROM ".MAIN_DB_PREFIX."deplacement as d, ".MAIN_DB_PREFIX."user as u"; -if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE u.rowid = d.fk_user"; $sql .= " AND d.entity = ".$conf->entity; -if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous)) $sql .= ' AND d.fk_user IN ('.join(',', $childids).')'; -if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND d.fk_soc = s. rowid AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND d.fk_soc = ".$socid; +if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous)) { + $sql .= ' AND d.fk_user IN ('.join(',', $childids).')'; +} +if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= " AND d.fk_soc = s. rowid AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND d.fk_soc = ".$socid; +} $sql .= $db->order("d.tms", "DESC"); $sql .= $db->plimit($max, 0); $result = $db->query($sql); -if ($result) -{ +if ($result) { $var = false; $num = $db->num_rows($result); @@ -168,14 +181,12 @@ if ($result) print ''.$langs->trans("DateModificationShort").' 
    '.$langs->trans("None").'

    '; -} else dol_print_error($db); +} else { + dol_print_error($db); +} print ''; diff --git a/htdocs/compta/deplacement/info.php b/htdocs/compta/deplacement/info.php index 586eac52ee7..e180e104eb4 100644 --- a/htdocs/compta/deplacement/info.php +++ b/htdocs/compta/deplacement/info.php @@ -32,7 +32,9 @@ $langs->load("trips"); // Security check $id = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'deplacement', $id, ''); @@ -42,8 +44,7 @@ $result = restrictedArea($user, 'deplacement', $id, ''); llxHeader(); -if ($id) -{ +if ($id) { $object = new Deplacement($db); $object->fetch($id); $object->info($id); diff --git a/htdocs/compta/deplacement/list.php b/htdocs/compta/deplacement/list.php index df18b09e2b4..46d17c30e96 100644 --- a/htdocs/compta/deplacement/list.php +++ b/htdocs/compta/deplacement/list.php @@ -36,7 +36,9 @@ $langs->loadLangs(array('companies', 'users', 'trips')); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'deplacement', '', ''); $search_ref = GETPOST('search_ref', 'int'); @@ -47,19 +49,24 @@ $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -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.dated"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "d.dated"; +} $year = GETPOST("year"); $month = GETPOST("month"); $day = GETPOST("day"); -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $search_ref = ""; $search_name = ""; $search_company = ""; @@ -89,20 +96,28 @@ $sql .= " u.lastname, u.firstname"; // Qui $sql .= " FROM ".MAIN_DB_PREFIX."user as u"; $sql .= ", ".MAIN_DB_PREFIX."deplacement as d"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON d.fk_soc = s.rowid"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; +} $sql .= " WHERE d.fk_user = u.rowid"; $sql .= " AND d.entity = ".$conf->entity; -if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous)) $sql .= ' AND d.fk_user IN ('.join(',', $childids).')'; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id." OR d.fk_soc IS NULL) "; -if ($socid) $sql .= " AND s.rowid = ".$socid; +if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous)) { + $sql .= ' AND d.fk_user IN ('.join(',', $childids).')'; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND (sc.fk_user = ".$user->id." OR d.fk_soc IS NULL) "; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} -if ($search_ref) $sql .= " AND d.rowid=".$search_ref; -if ($search_name) -{ +if ($search_ref) { + $sql .= " AND d.rowid=".$search_ref; +} +if ($search_name) { $sql .= natural_search('u.lastname', $search_name); } -if ($search_company) -{ +if ($search_company) { $sql .= natural_search('s.nom', $search_company); } $sql .= dolSqlDateFilter("d.dated", $day, $month, $year); @@ -112,8 +127,7 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); print_barre_liste($langs->trans("ListOfFees"), $page, $_SERVER["PHP_SELF"], "&socid=$socid", $sortfield, $sortorder, '', $num); @@ -140,7 +154,9 @@ if ($resql) print ' '; print '
    '; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print ''; + } print ''; $formother->select_year($year ? $year : -1, 'year', 1, 20, 5); print '
    '.$soc->getNomUrl(1).' '.$soc->getNomUrl(1).' '.$obj->km.'
    '.$langs->trans("User").''; $include = ''; -if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous)) $include = 'hierarchy'; +if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous)) { + $include = 'hierarchy'; +} print $form->select_dolusers($userid, 'userid', 1, '', 0, $include, '', 0, 0, 0, '', 0, '', 'maxwidth300'); print '
    '.$langs->trans("Year").''; -if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print '
    '.$langs->trans("AmountAverage").'
    '.$oldyear.'
    '; if ($action == 'edit') { - print ''; + print ''; } else { print ''; } @@ -596,8 +559,9 @@ if ($id) print '
    '; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); print "
    \n"; print $px2->show(); diff --git a/htdocs/compta/facture/admin/facture_cust_extrafields.php b/htdocs/compta/facture/admin/facture_cust_extrafields.php index 0e971954d56..b3ca5f5f233 100644 --- a/htdocs/compta/facture/admin/facture_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facture_cust_extrafields.php @@ -38,13 +38,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 = 'facture'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -77,8 +81,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -91,8 +94,7 @@ if ($action != 'create' && $action != 'edit') * */ -if ($action == 'create') -{ +if ($action == 'create') { print '
    '; print load_fiche_titre($langs->trans('NewAttribute')); @@ -104,8 +106,7 @@ if ($action == 'create') * Edition of an optional field * */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { $langs->load("members"); print "
    "; diff --git a/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php b/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php index dbc395e5d65..7d2d2b1df97 100644 --- a/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php @@ -39,13 +39,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 = 'facture_rec'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -78,8 +82,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -92,8 +95,7 @@ if ($action != 'create' && $action != 'edit') * */ -if ($action == 'create') -{ +if ($action == 'create') { print '
    '; print load_fiche_titre($langs->trans('NewAttribute')); @@ -105,8 +107,7 @@ if ($action == 'create') * Edition of an optional field * */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { $langs->load("members"); print "
    "; diff --git a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php index c07eb3ac2aa..82520c02fac 100644 --- a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php @@ -39,13 +39,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 = 'facturedet'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -78,8 +82,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -92,8 +95,7 @@ if ($action != 'create' && $action != 'edit') * */ -if ($action == 'create') -{ +if ($action == 'create') { print '
    '; print load_fiche_titre($langs->trans('NewAttribute')); @@ -105,8 +107,7 @@ if ($action == 'create') * Edition d'un champ optionnel * */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
    "; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php index 772a3aa680c..5264ee5472c 100644 --- a/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php @@ -39,13 +39,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 = 'facturedet_rec'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -78,8 +82,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -92,8 +95,7 @@ if ($action != 'create' && $action != 'edit') * */ -if ($action == 'create') -{ +if ($action == 'create') { print '
    '; print load_fiche_titre($langs->trans('NewAttribute')); @@ -105,8 +107,7 @@ if ($action == 'create') * Edition d'un champ optionnel * */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
    "; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/compta/facture/card-rec.php b/htdocs/compta/facture/card-rec.php index a1471f48482..167e9e4a577 100644 --- a/htdocs/compta/facture/card-rec.php +++ b/htdocs/compta/facture/card-rec.php @@ -58,10 +58,13 @@ $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'inv $id = (GETPOST('facid', 'int') ?GETPOST('facid', 'int') : GETPOST('id', 'int')); $lineid = GETPOST('lineid', 'int'); $ref = GETPOST('ref', 'alpha'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $objecttype = 'facture_rec'; -if ($action == "create" || $action == "add") $objecttype = ''; -$result = restrictedArea($user, 'facture', $id, $objecttype); +if ($action == "create" || $action == "add") { + $objecttype = ''; +} $projectid = GETPOST('projectid', 'int'); $year_date_when = GETPOST('year_date_when'); @@ -71,19 +74,23 @@ $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; -if (!$sortorder) $sortorder = 'DESC'; -if (!$sortfield) $sortfield = 'f.titre'; +if (!$sortorder) { + $sortorder = 'DESC'; +} +if (!$sortfield) { + $sortfield = 'f.titre'; +} $pageprev = $page - 1; $pagenext = $page + 1; $object = new FactureRec($db); -if (($id > 0 || $ref) && $action != 'create' && $action != 'add') -{ +if (($id > 0 || $ref) && $action != 'create' && $action != 'add') { $ret = $object->fetch($id, $ref); - if (!$ret) - { + if (!$ret) { setEventMessages($langs->trans("ErrorRecordNotFound"), null, 'errors'); } } @@ -119,21 +126,31 @@ $now = dol_now(); $error = 0; +$result = restrictedArea($user, 'facture', $object->id, $objecttype); + /* * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; + $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $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)) -{ - if (GETPOST('cancel', 'alpha')) $action = ''; +if (empty($reshook)) { + if (GETPOST('cancel', 'alpha')) { + $action = ''; + } // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; @@ -147,17 +164,15 @@ if (empty($reshook)) // Mass actions /*$objectclass='MyObject'; - $objectlabel='MyObject'; - $permissiontoread = $user->rights->mymodule->read; - $permissiontodelete = $user->rights->mymodule->delete; - $uploaddir = $conf->mymodule->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';*/ + $objectlabel='MyObject'; + $permissiontoread = $user->rights->mymodule->read; + $permissiontodelete = $user->rights->mymodule->delete; + $uploaddir = $conf->mymodule->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';*/ // Create predefined invoice - if ($action == 'add') - { - if (!GETPOST('title', 'alphanohtml')) - { + if ($action == 'add') { + if (!GETPOST('title', 'alphanohtml')) { setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("Title")), null, 'errors'); $action = "create"; $error++; @@ -172,24 +187,20 @@ if (empty($reshook)) $nb_gen_max = GETPOST('nb_gen_max', 'int'); //if (empty($nb_gen_max)) $nb_gen_max =0; - if (GETPOST('frequency', 'int')) - { - if (empty($reyear) || empty($remonth) || empty($reday)) - { + if (GETPOST('frequency', 'int')) { + if (empty($reyear) || empty($remonth) || empty($reday)) { setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("Date")), null, 'errors'); $action = "create"; $error++; } - if ($nb_gen_max === '') - { + if ($nb_gen_max === '') { setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("MaxPeriodNumber")), null, 'errors'); $action = "create"; $error++; } } - if (!$error) - { + if (!$error) { $object->titre = GETPOST('title', 'nohtml'); // deprecated $object->title = GETPOST('title', 'nohtml'); $object->note_private = GETPOST('note_private', 'restricthtml'); @@ -208,15 +219,13 @@ if (empty($reshook)) $object->date_when = $date_next_execution; // Get first contract linked to invoice used to generate template (facid is id of source invoice) - if (GETPOST('facid', 'int') > 0) - { + if (GETPOST('facid', 'int') > 0) { $srcObject = new Facture($db); $srcObject->fetch(GETPOST('facid', 'int')); $srcObject->fetchObjectLinked(); - if (!empty($srcObject->linkedObjectsIds['contrat'])) - { + if (!empty($srcObject->linkedObjectsIds['contrat'])) { $contractidid = reset($srcObject->linkedObjectsIds['contrat']); $object->origin = 'contrat'; @@ -231,11 +240,9 @@ if (empty($reshook)) $oldinvoice->fetch(GETPOST('facid', 'int')); $result = $object->create($user, $oldinvoice->id); - if ($result > 0) - { + if ($result > 0) { $result = $oldinvoice->delete($user, 1); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($oldinvoice->error, $oldinvoice->errors, 'errors'); $action = "create"; @@ -246,12 +253,11 @@ if (empty($reshook)) $action = "create"; } - if (!$error) - { + if (!$error) { $db->commit(); header("Location: ".$_SERVER['PHP_SELF'].'?facid='.$object->id); - exit; + exit; } else { $db->rollback(); @@ -263,8 +269,7 @@ if (empty($reshook)) } // Delete - if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $user->rights->facture->supprimer) - { + if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $user->rights->facture->supprimer) { $object->delete($user); header("Location: ".DOL_URL_ROOT.'/compta/facture/invoicetemplate_list.php'); @@ -274,26 +279,21 @@ if (empty($reshook)) // Update field // Set condition - if ($action == 'setconditions' && $user->rights->facture->creer) - { + 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('title', $ref, '', null, 'text', '', $user, 'BILLREC_MODIFY'); - if ($result > 0) - { - $object->titre = GETPOST('ref', 'alpha'); // deprecated - $object->title = GETPOST('ref', 'alpha'); + $result = $object->setValueFrom('titre', $ref, '', null, 'text', '', $user, 'BILLREC_MODIFY'); + if ($result > 0) { + $object->titre = $ref; // deprecated + $object->title = $ref; $object->ref = $object->title; } else { $error++; @@ -304,86 +304,74 @@ 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) - { + if (!empty($date)) { + $object->setNextDate($date); + } + } 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); $res = $object->setValueFrom('suspended', 1); - if ($res <= 0) - { + if ($res <= 0) { $error++; } - if (!$error) - { + if (!$error) { $db->commit(); } else { $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); $res = $object->setValueFrom('suspended', 0); - if ($res <= 0) - { + if ($res <= 0) { $error++; } - if (!$error) - { + if (!$error) { $db->commit(); } else { $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')); } // Delete line - if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer) - { + if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer) { $object->fetch($id); $object->fetch_thirdparty(); @@ -394,12 +382,10 @@ if (empty($reshook)) // For triggers $line->id = $lineid; - if ($line->delete($user) > 0) - { + if ($line->delete($user) > 0) { $result = $object->update_price(1); - if ($result > 0) - { + if ($result > 0) { $db->commit(); $object->fetch($object->id); // Reload lines } else { @@ -410,19 +396,18 @@ if (empty($reshook)) $db->rollback(); setEventMessages($line->error, $line->errors, 'errors'); } - } elseif ($action == 'update_extras') - { + } elseif ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { $result = $object->insertExtraFields('BILLREC_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -430,19 +415,17 @@ if (empty($reshook)) } // Add a new line - if ($action == 'addline' && $user->rights->facture->creer) - { + if ($action == 'addline' && $user->rights->facture->creer) { $langs->load('errors'); $error = 0; // 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') - { + if ($prod_entry_mode == 'free') { $idprod = 0; $tva_tx = (GETPOST('tva_tx', 'alpha') ? GETPOST('tva_tx', 'alpha') : 0); } else { @@ -457,8 +440,7 @@ if (empty($reshook)) $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line); $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef); // Unset extrafield - if (is_array($extralabelsline)) - { + if (is_array($extralabelsline)) { // Get extra fields foreach ($extralabelsline as $key => $value) { unset($_POST["options_".$key.$predef]); @@ -473,8 +455,7 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && empty($idprod) && (!($price_ht >= 0) || $price_ht == '')) // Unit price can be 0 but not '' - { + if ($prod_entry_mode == 'free' && empty($idprod) && (!($price_ht >= 0) || $price_ht == '')) { // Unit price can be 0 but not '' setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors'); $error++; } @@ -492,8 +473,7 @@ if (empty($reshook)) $error++; } - if (!$error && ($qty >= 0) && (!empty($product_desc) || !empty($idprod))) - { + if (!$error && ($qty >= 0) && (!empty($product_desc) || !empty($idprod))) { $ret = $object->fetch($id); if ($ret < 0) { dol_print_error($db, $object->error); @@ -515,8 +495,7 @@ if (empty($reshook)) // Ecrase $tva_tx par celui du produit // Ecrase $base_price_type par celui du produit // Replaces $fk_unit with the product's - if (!empty($idprod)) - { + if (!empty($idprod)) { $prod = new Product($db); $prod->fetch($idprod); @@ -525,7 +504,9 @@ if (empty($reshook)) // Update if prices fields are defined $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp']. $pqp = (GETPOST('pbq', 'int') ? GETPOST('pbq', 'int') : 0); @@ -543,16 +524,13 @@ if (empty($reshook)) $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx)); // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ? - if (!empty($price_ht)) - { + 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) - { - if ($price_base_type != 'HT') - { + } 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 { $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); @@ -562,16 +540,16 @@ if (empty($reshook)) $desc = ''; // Define output language - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) + } + if (empty($newlang)) { $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -584,27 +562,42 @@ if (empty($reshook)) $desc = dol_concatdesc($desc, $product_desc); // Add custom code and origin country into description - if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) - { + if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) { $tmptxt = '('; // Define output language if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'alpha')) $newlang = GETPOST('lang_id', 'alpha'); - if (empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (empty($newlang) && GETPOST('lang_id', 'alpha')) { + $newlang = GETPOST('lang_id', 'alpha'); + } + if (empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - if (!empty($prod->customcode)) $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; - if (!empty($prod->customcode) && !empty($prod->country_code)) $tmptxt .= ' - '; - if (!empty($prod->country_code)) $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0); + if (!empty($prod->customcode)) { + $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; + } + if (!empty($prod->customcode) && !empty($prod->country_code)) { + $tmptxt .= ' - '; + } + if (!empty($prod->country_code)) { + $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0); + } } else { - if (!empty($prod->customcode)) $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; - if (!empty($prod->customcode) && !empty($prod->country_code)) $tmptxt .= ' - '; - if (!empty($prod->country_code)) $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0); + if (!empty($prod->customcode)) { + $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; + } + if (!empty($prod->customcode) && !empty($prod->country_code)) { + $tmptxt .= ' - '; + } + if (!empty($prod->country_code)) { + $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0); + } } $tmptxt .= ')'; $desc = dol_concatdesc($desc, $tmptxt); @@ -617,7 +610,9 @@ if (empty($reshook)) $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); $tva_tx = str_replace('*', '', $tva_tx); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); $desc = $product_desc; $type = GETPOST('type'); @@ -636,8 +631,9 @@ if (empty($reshook)) $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr); $info_bits = 0; - if ($tva_npr) + if ($tva_npr) { $info_bits |= 0x01; + } if ($usercanproductignorepricemin && (!empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) { $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)); @@ -646,26 +642,25 @@ if (empty($reshook)) // Insert line $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit, 0, $date_start_fill, $date_end_fill, $fournprice, $buyingprice); - if ($result > 0) - { + if ($result > 0) { // Define output language and generate document /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->model_pdf; - $ret = $object->fetch($id); // Reload to get new records + { + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); - }*/ + $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + }*/ $object->fetch($object->id); // Reload lines unset($_POST['prod_entry_mode']); @@ -713,9 +708,10 @@ if (empty($reshook)) $action = ''; } } - } elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) - { - if (!$object->fetch($id) > 0) dol_print_error($db); + } elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) { + if (!$object->fetch($id) > 0) { + dol_print_error($db); + } $object->fetch_thirdparty(); // Clean parameters @@ -724,14 +720,16 @@ 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; - if (preg_match('/\*/', $vat_rate)) $info_bits |= 0x01; + if (preg_match('/\*/', $vat_rate)) { + $info_bits |= 0x01; + } // Define vat_rate $vat_rate = str_replace('*', '', $vat_rate); @@ -747,12 +745,10 @@ if (empty($reshook)) $array_options = $extrafields->getOptionalsFromPost($object->table_element_line); $objectline = new FactureLigneRec($db); - if ($objectline->fetch(GETPOST('lineid', 'int'))) - { + if ($objectline->fetch(GETPOST('lineid', 'int'))) { $objectline->array_options = $array_options; $result = $objectline->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { setEventMessages($langs->trans('Error').$result, null, 'errors'); } } @@ -760,49 +756,48 @@ if (empty($reshook)) $position = ($objectline->rang >= 0 ? $objectline->rang : 0); // Unset extrafield - if (is_array($extralabelsline)) - { + if (is_array($extralabelsline)) { // Get extra fields - foreach ($extralabelsline as $key => $value) - { + foreach ($extralabelsline as $key => $value) { unset($_POST["options_".$key]); } } // Define special_code for special lines $special_code = GETPOST('special_code', 'int'); - if (!GETPOST('qty', 'alpha')) $special_code = 3; + if (!GETPOST('qty', 'alpha')) { + $special_code = 3; + } /*$line = new FactureLigne($db); - $line->fetch(GETPOST('lineid')); - $percent = $line->get_prev_progress($object->id); + $line->fetch(GETPOST('lineid')); + $percent = $line->get_prev_progress($object->id); - if (GETPOST('progress') < $percent) - { - $mesg = '
    ' . $langs->trans("CantBeLessThanMinPercent") . '
    '; - setEventMessages($mesg, null, 'warnings'); - $error++; - $result = -1; - }*/ + if (GETPOST('progress') < $percent) + { + $mesg = '
    ' . $langs->trans("CantBeLessThanMinPercent") . '
    '; + setEventMessages($mesg, null, 'warnings'); + $error++; + $result = -1; + }*/ // Check minimum price $productid = GETPOST('productid', 'int'); - if (!empty($productid)) - { + if (!empty($productid)) { $product = new Product($db); $product->fetch($productid); $type = $product->type; $price_min = $product->price_min; - if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) + if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) { $price_min = $product->multiprices_min[$object->thirdparty->price_level]; + } $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); // Check price is not lower than minimum (check is done only for standard or replacement invoices) - if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent', 2)) / 100) < price2num($price_min)))) - { + if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent', 2)) / 100) < price2num($price_min)))) { setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors'); $error++; } @@ -826,8 +821,7 @@ if (empty($reshook)) $date_end_fill = GETPOST('date_end_fill', 'int'); // Update line - if (!$error) - { + if (!$error) { $result = $object->updateline( GETPOST('lineid'), $description, @@ -855,24 +849,23 @@ if (empty($reshook)) $buyingprice ); - if ($result >= 0) - { + if ($result >= 0) { /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) - $newlang = GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) + $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } - $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - }*/ + $ret = $object->fetch($id); // Reload to get new records + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + }*/ $object->fetch($object->id); // Reload lines @@ -928,7 +921,9 @@ llxHeader('', $langs->trans("RepeatableInvoices"), $help_url); $form = new Form($db); $formother = new FormOther($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $companystatic = new Societe($db); $invoicerectmp = new FactureRec($db); @@ -939,15 +934,13 @@ $nowlasthour = dol_get_last_hour($now); /* * Create mode */ -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("CreateRepeatableInvoice"), '', 'bill'); $object = new Facture($db); // Source invoice $product_static = new Product($db); - if ($object->fetch($id, $ref) > 0) - { + if ($object->fetch($id, $ref) > 0) { $result = $object->getLinesArray(); print '
    '; @@ -958,8 +951,12 @@ if ($action == 'create') print dol_get_fiche_head(null, '', '', 0); $rowspan = 4; - if (!empty($conf->projet->enabled)) $rowspan++; - if ($object->fk_account > 0) $rowspan++; + if (!empty($conf->projet->enabled)) { + $rowspan++; + } + if ($object->fk_account > 0) { + $rowspan++; + } print ''; @@ -996,8 +993,7 @@ if ($action == 'create') $substitutionarray['__INVOICE_COUNTER_MAX__'] = $langs->trans("MaxPeriodNumber"); $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
    '; - foreach ($substitutionarray as $key => $val) - { + foreach ($substitutionarray as $key => $val) { $htmltext .= $key.' = '.$langs->trans($val).'
    '; } $htmltext .= '
    '; @@ -1012,8 +1008,7 @@ if ($action == 'create') print $doleditor->Create(1); // Private note - if (empty($user->socid)) - { + if (empty($user->socid)) { print ''; print '"; // Project - if (!empty($conf->projet->enabled) && is_object($object->thirdparty) && $object->thirdparty->id > 0) - { + if (!empty($conf->projet->enabled) && is_object($object->thirdparty) && $object->thirdparty->id > 0) { $projectid = GETPOST('projectid') ?GETPOST('projectid') : $object->fk_project; $langs->load('projects'); print '"; @@ -1100,8 +1093,7 @@ if ($action == 'create') print ""; // Auto generate document - if (!empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION)) - { + if (!empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION)) { print "'; // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print ''; print ''; // Multicurrency rate - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { print ''; print ''; // Auto generate documents - if (!empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION)) - { + if (!empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION)) { print ''; print ''; print ''; @@ -1575,12 +1559,10 @@ if ($action == 'create') print '
    '; print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate'); @@ -1039,8 +1034,7 @@ if ($action == 'create') print "
    '.$langs->trans('Project').''; @@ -1050,8 +1044,7 @@ if ($action == 'create') } // Bank account - if ($object->fk_account > 0) - { + if ($object->fk_account > 0) { print "
    ".$langs->trans('BankAccount').""; $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); print "
    ".$langs->trans("StatusOfGeneratedDocuments").""; $select = array('0'=>$langs->trans('DoNotGenerateDoc'), '1'=>$langs->trans('AutoGenerateDoc')); print $form->selectarray('generate_pdf', $select, GETPOST('generate_pdf')); @@ -1116,10 +1108,11 @@ if ($action == 'create') $title = $langs->trans("ProductsAndServices"); - if (empty($conf->service->enabled)) + if (empty($conf->service->enabled)) { $title = $langs->trans("Products"); - elseif (empty($conf->product->enabled)) + } elseif (empty($conf->product->enabled)) { $title = $langs->trans("Services"); + } print load_fiche_titre($title, '', ''); @@ -1129,8 +1122,7 @@ if ($action == 'create') print '
    '; print ''; // Show object lines - if (!empty($object->lines)) - { + if (!empty($object->lines)) { $disableedit = 1; $disablemove = 1; $disableremove = 1; @@ -1142,8 +1134,7 @@ if ($action == 'create') print ''; - if ($flag_price_may_change) - { + if ($flag_price_may_change) { print ''; // Amount Local Taxes - if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) // Localtax1 - { + if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) { // Localtax1 print ''; print ''; } - if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) // Localtax2 - { + if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) { // Localtax2 print ''; print ''; } @@ -1277,14 +1266,13 @@ if ($action == 'create') print '
    '; print '
    '.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency).'
    '.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'
    '; - if ($action != 'editconditions' && $user->rights->facture->creer) + if ($action != 'editconditions' && $user->rights->facture->creer) { print ''; + } print '
    '; print $langs->trans('PaymentConditionsShort'); print 'id.'">'.img_edit($langs->trans('SetConditions'), 1).'
    '; print '
    '; - if ($object->type != Facture::TYPE_CREDIT_NOTE) - { - if ($action == 'editconditions') - { + if ($object->type != Facture::TYPE_CREDIT_NOTE) { + if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->cond_reglement_id, 'cond_reglement_id'); } else { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->cond_reglement_id, 'none'); @@ -1299,12 +1287,12 @@ if ($action == 'create') print ''; - if ($action != 'editmode' && $user->rights->facture->creer) + if ($action != 'editmode' && $user->rights->facture->creer) { print ''; + } print '
    '; print $langs->trans('PaymentMode'); print 'id.'">'.img_edit($langs->trans('SetMode'), 1).'
    '; print '
    '; - if ($action == 'editmode') - { + if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1); } else { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'none'); @@ -1312,8 +1300,7 @@ if ($action == 'create') print '
    '; @@ -1330,8 +1317,7 @@ if ($action == 'create') print '
    '; print ''; print '
    '; @@ -1361,7 +1347,9 @@ if ($action == 'create') // Help of substitution key $dateexample = dol_now(); - if (!empty($object->frequency) && !empty($object->date_when)) $dateexample = $object->date_when; + if (!empty($object->frequency) && !empty($object->date_when)) { + $dateexample = $object->date_when; + } $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object); @@ -1381,8 +1369,7 @@ if ($action == 'create') $substitutionarray['__INVOICE_COUNTER_MAX__'] = $object->nb_gen_max; $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
    '; - foreach ($substitutionarray as $key => $val) - { + foreach ($substitutionarray as $key => $val) { $htmltext .= $key.' = '.$langs->trans($val).'
    '; } $htmltext .= '
    '; @@ -1408,12 +1395,12 @@ if ($action == 'create') print ''; + } print '
    '; print $langs->trans('BankAccount'); print ''; - if (($action != 'editbankaccount') && $user->rights->facture->creer && $object->statut == FactureRec::STATUS_DRAFT) + if (($action != 'editbankaccount') && $user->rights->facture->creer && $object->statut == FactureRec::STATUS_DRAFT) { print 'id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'
    '; print '
    '; - if ($action == 'editbankaccount') - { + if ($action == 'editbankaccount') { $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); } else { $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); @@ -1426,12 +1413,12 @@ if ($action == 'create') print ''; + } print '
    '; print $langs->trans('Model'); print ''; - if (($action != 'editmodelpdf') && $user->rights->facture->creer && $object->statut == FactureRec::STATUS_DRAFT) + if (($action != 'editmodelpdf') && $user->rights->facture->creer && $object->statut == FactureRec::STATUS_DRAFT) { print 'id.'">'.img_edit($langs->trans('SetModel'), 1).'
    '; print '
    '; - if ($action == 'editmodelpdf') - { + if ($action == 'editmodelpdf') { include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; $list = array(); $models = ModelePDFFactures::liste_modeles($db); @@ -1473,12 +1460,12 @@ if ($action == 'create') print ''; - if ($action != 'editfrequency' && $user->rights->facture->creer) + if ($action != 'editfrequency' && $user->rights->facture->creer) { print ''; + } print '
    '; print $langs->trans('Frequency'); print 'id.'">'.img_edit($langs->trans('Edit'), 1).'
    '; print '
    '; - if ($action == 'editfrequency') - { + if ($action == 'editfrequency') { print ''; print ''; print ''; @@ -1489,8 +1476,7 @@ if ($action == 'create') print '
    '; } else { - if ($object->frequency > 0) - { + if ($object->frequency > 0) { print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency); } else { print $langs->trans("NotARecurringInvoiceTemplate"); @@ -1500,21 +1486,20 @@ if ($action == 'create') // Date when (next invoice generation) print '
    '; - if ($action == 'date_when' || $object->frequency > 0) - { + if ($action == 'date_when' || $object->frequency > 0) { print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day'); } else { print $langs->trans("NextDateToExecution"); } print ''; - if ($action == 'date_when' || $object->frequency > 0) - { + if ($action == 'date_when' || $object->frequency > 0) { print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day', $object->date_when, null, '', '', 0, 'strikeIfMaxNbGenReached'); } //var_dump(dol_print_date($object->date_when+60, 'dayhour').' - '.dol_print_date($now, 'dayhour')); - if (!$object->isMaxNbGenReached()) - { - if (!$object->suspended && $action != 'editdate_when' && $object->frequency > 0 && $object->date_when && $object->date_when < $now) print img_warning($langs->trans("Late")); + if (!$object->isMaxNbGenReached()) { + if (!$object->suspended && $action != 'editdate_when' && $object->frequency > 0 && $object->date_when && $object->date_when < $now) { + print img_warning($langs->trans("Late")); + } } else { print img_info($langs->trans("MaxNumberOfGenerationReached")); } @@ -1523,15 +1508,13 @@ if ($action == 'create') // Max period / Rest period print '
    '; - if ($action == 'nb_gen_max' || $object->frequency > 0) - { + if ($action == 'nb_gen_max' || $object->frequency > 0) { print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->rights->facture->creer); } else { print $langs->trans("MaxPeriodNumber"); } print ''; - if ($action == 'nb_gen_max' || $object->frequency > 0) - { + if ($action == 'nb_gen_max' || $object->frequency > 0) { print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max ? $object->nb_gen_max : '', $object, $user->rights->facture->creer); } else { print ''; @@ -1541,29 +1524,30 @@ if ($action == 'create') // Status of generated invoices print '
    '; - if ($action == 'auto_validate' || $object->frequency > 0) + if ($action == 'auto_validate' || $object->frequency > 0) { print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer); - else print $langs->trans("StatusOfGeneratedInvoices"); + } else { + print $langs->trans("StatusOfGeneratedInvoices"); + } print ''; $select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated'); - if ($action == 'auto_validate' || $object->frequency > 0) - { + if ($action == 'auto_validate' || $object->frequency > 0) { print $form->editfieldval($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer, $select); } print '
    '; - if ($action == 'generate_pdf' || $object->frequency > 0) + if ($action == 'generate_pdf' || $object->frequency > 0) { print $form->editfieldkey($langs->trans("StatusOfGeneratedDocuments"), 'generate_pdf', $object->generate_pdf, $object, $user->rights->facture->creer); - else print $langs->trans("StatusOfGeneratedDocuments"); + } else { + print $langs->trans("StatusOfGeneratedDocuments"); + } print ''; $select = 'select;0:'.$langs->trans('DoNotGenerateDoc').',1:'.$langs->trans('AutogenerateDoc'); - if ($action == 'generate_pdf' || $object->frequency > 0) - { + if ($action == 'generate_pdf' || $object->frequency > 0) { print $form->editfieldval($langs->trans("StatusOfGeneratedDocuments"), 'generate_pdf', $object->generate_pdf, $object, $user->rights->facture->creer, $select); } print '
    '; // Frequencry/Recurring section - if ($object->frequency > 0) - { + if ($object->frequency > 0) { print '
    '; - if (empty($conf->cron->enabled)) - { + if (empty($conf->cron->enabled)) { print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name"))); } @@ -1629,17 +1611,14 @@ if ($action == 'create') print '
    '; print ''; // Show object lines - if (!empty($object->lines)) - { + if (!empty($object->lines)) { $canchangeproduct = 1; $ret = $object->printObjectLines($action, $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice } // Form to add new line - if ($object->statut == $object::STATUS_DRAFT && $user->rights->facture->creer && $action != 'valid' && $action != 'editline') - { - if ($action != 'editline') - { + if ($object->statut == $object::STATUS_DRAFT && $user->rights->facture->creer && $action != 'valid' && $action != 'editline') { + if ($action != 'editline') { // Add free products/services $object->formAddObjectLine(0, $mysoc, $object->thirdparty); // No date selector for template invoice @@ -1656,17 +1635,14 @@ if ($action == 'create') print dol_get_fiche_end(); - /** - * Barre d'actions + /* + * Action bar */ print '
    '; - if (empty($object->suspended)) - { - if ($user->rights->facture->creer) - { - if (!empty($object->frequency) && $object->nb_gen_max > 0 && ($object->nb_gen_done >= $object->nb_gen_max)) - { + if (empty($object->suspended)) { + if ($user->rights->facture->creer) { + if (!empty($object->frequency) && $object->nb_gen_max > 0 && ($object->nb_gen_done >= $object->nb_gen_max)) { print ''; } else { if (empty($object->frequency) || $object->date_when <= $nowlasthour) { @@ -1680,10 +1656,8 @@ if ($action == 'create') } } - if ($user->rights->facture->creer) - { - if (empty($object->suspended)) - { + if ($user->rights->facture->creer) { + if (empty($object->suspended)) { print ''; } else { print ''; @@ -1691,8 +1665,7 @@ if ($action == 'create') } //if ($object->statut == Facture::STATUS_DRAFT && $user->rights->facture->supprimer) - if ($user->rights->facture->supprimer) - { + if ($user->rights->facture->supprimer) { print ''; } diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index cdb729991da..cd1905f528f 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -50,8 +50,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (!empty($conf->commande->enabled)) +if (!empty($conf->commande->enabled)) { require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +} if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; @@ -67,8 +68,12 @@ if (!empty($conf->accounting->enabled)) { // Load translation files required by the page $langs->loadLangs(array('bills', 'companies', 'compta', 'products', 'banks', 'main', 'withdrawals')); -if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); -if (!empty($conf->margin->enabled)) $langs->load('margins'); +if (!empty($conf->incoterm->enabled)) { + $langs->load('incoterm'); +} +if (!empty($conf->margin->enabled)) { + $langs->load('margins'); +} $projectid = (GETPOST('projectid', 'int') ? GETPOST('projectid', 'int') : 0); @@ -133,18 +138,20 @@ $permissiondellink = $usercancreate; // Used by the include of actions_dellink.i $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdonw.inc.php $permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php -// Security check -$fieldid = (!empty($ref) ? 'ref' : 'rowid'); -if ($user->socid) $socid = $user->socid; -$isdraft = (($object->statut == Facture::STATUS_DRAFT) ? 1 : 0); -$result = restrictedArea($user, 'facture', $id, '', '', 'fk_soc', $fieldid, $isdraft); - // retained warranty invoice available type $retainedWarrantyInvoiceAvailableType = array(); if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) { $retainedWarrantyInvoiceAvailableType = explode('+', $conf->global->INVOICE_USE_RETAINED_WARRANTY); } +// Security check +$fieldid = (!empty($ref) ? 'ref' : 'rowid'); +if ($user->socid) { + $socid = $user->socid; +} +$isdraft = (($object->statut == Facture::STATUS_DRAFT) ? 1 : 0); +$result = restrictedArea($user, 'facture', $object->id, '', '', 'fk_soc', $fieldid, $isdraft); + /* * Actions @@ -152,14 +159,13 @@ if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) { $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)) -{ - if ($cancel) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -173,23 +179,22 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) - { + if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) { $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid. $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int')); $objectutil->socid = $socid; $result = $objectutil->createFromClone($user, $id); if ($result > 0) { - header("Location: ".$_SERVER['PHP_SELF'].'?facid='.$result); - exit(); - } else { - $langs->load("errors"); - setEventMessages($object->error, $object->errors, 'errors'); - $action = ''; + header("Location: ".$_SERVER['PHP_SELF'].'?facid='.$result); + exit(); + } else { + $langs->load("errors"); + setEventMessages($object->error, $object->errors, 'errors'); + $action = ''; } - } // Change status of invoice - elseif ($action == 'reopen' && $usercancreate) { + } elseif ($action == 'reopen' && $usercancreate) { + // Change status of invoice $result = $object->fetch($id); if ($object->statut == Facture::STATUS_CLOSED || ($object->statut == Facture::STATUS_ABANDONED && ($object->close_code != 'replaced' || $object->getIdReplacingInvoice() == 0)) || ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 1)) { // ($object->statut == 1 && $object->paye == 1) should not happened but can be found when data are corrupted @@ -201,8 +206,8 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } } - } // Delete invoice - elseif ($action == 'confirm_delete' && $confirm == 'yes') { + } elseif ($action == 'confirm_delete' && $confirm == 'yes') { + // Delete invoice $result = $object->fetch($id); $object->fetch_thirdparty(); @@ -218,8 +223,7 @@ if (empty($reshook)) $isErasable = $object->is_erasable(); if (($usercandelete && $isErasable > 0) - || ($usercancreate && $isErasable == 1)) - { + || ($usercancreate && $isErasable == 1)) { $result = $object->delete($user, 0, $idwarehouse); if ($result > 0) { header('Location: '.DOL_URL_ROOT.'/compta/facture/list.php?restore_lastsearch_values=1'); @@ -229,9 +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(); @@ -240,10 +243,12 @@ if (empty($reshook)) // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($_REQUEST['lang_id'])) + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($_REQUEST['lang_id'])) { $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -261,15 +266,13 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); $action = ''; } - } // Delete link of credit note to invoice - elseif ($action == 'unlinkdiscount' && $usercancreate) - { + } elseif ($action == 'unlinkdiscount' && $usercancreate) { + // Delete link of credit note to invoice $discount = new DiscountAbsolute($db); $result = $discount->fetch(GETPOST("discountid")); $discount->unlink_invoice(); - } // Validation - elseif ($action == 'valid' && $usercancreate) - { + } elseif ($action == 'valid' && $usercancreate) { + // Validation $object->fetch($id); // On verifie signe facture @@ -299,20 +302,22 @@ if (empty($reshook)) foreach ($object->lines as $line) { //$vat_src_code_for_line = $line->vat_src_code; // TODO We chek sign of total per vat without taking into account the vat code because for the moment the vat code is lost/unknown when we add a down payment. $vat_src_code_for_line = ''; - if (empty($array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line])) $array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] = 0; - if (empty($array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line])) $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] = 0; + if (empty($array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line])) { + $array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] = 0; + } + if (empty($array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line])) { + $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] = 0; + } $array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] += $line->total_ht; $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] += $line->multicurrency_total_ht; } //var_dump($array_of_total_ht_per_vat_rate);exit; - foreach ($array_of_total_ht_per_vat_rate as $vatrate => $tmpvalue) - { + foreach ($array_of_total_ht_per_vat_rate as $vatrate => $tmpvalue) { $tmp_total_ht = $array_of_total_ht_per_vat_rate[$vatrate]; $tmp_total_ht_devise = $array_of_total_ht_devise_per_vat_rate[$vatrate]; - if (($tmp_total_ht < 0 || $tmp_total_ht_devise < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) - { + if (($tmp_total_ht < 0 || $tmp_total_ht_devise < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) { if ($object->type == $object::TYPE_DEPOSIT) { $langs->load("errors"); // Using negative lines on deposit lead to headach and blocking problems when you want to consume them. @@ -333,61 +338,68 @@ if (empty($reshook)) } } } - } - - elseif ($action == 'classin' && $usercancreate) - { + } elseif ($action == 'classin' && $usercancreate) { $object->fetch($id); $object->setProject($_POST['projectid']); - } elseif ($action == 'setmode' && $usercancreate) - { + } elseif ($action == 'setmode' && $usercancreate) { $object->fetch($id); $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - if ($result < 0) + if ($result < 0) { dol_print_error($db, $object->error); - } elseif ($action == 'setretainedwarrantyconditions' && $user->rights->facture->creer) - { + } + } elseif ($action == 'setretainedwarrantyconditions' && $user->rights->facture->creer) { $object->fetch($id); $object->retained_warranty_fk_cond_reglement = 0; // To clean property $result = $object->setRetainedWarrantyPaymentTerms(GETPOST('retained_warranty_fk_cond_reglement', 'int')); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + dol_print_error($db, $object->error); + } $old_rw_date_lim_reglement = $object->retained_warranty_date_limit; $new_rw_date_lim_reglement = $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement); - if ($new_rw_date_lim_reglement > $old_rw_date_lim_reglement) $object->retained_warranty_date_limit = $new_rw_date_lim_reglement; - if ($object->retained_warranty_date_limit < $object->date) $object->retained_warranty_date_limit = $object->date; + if ($new_rw_date_lim_reglement > $old_rw_date_lim_reglement) { + $object->retained_warranty_date_limit = $new_rw_date_lim_reglement; + } + if ($object->retained_warranty_date_limit < $object->date) { + $object->retained_warranty_date_limit = $object->date; + } $result = $object->update($user); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + dol_print_error($db, $object->error); + } } elseif ($action == 'setretainedwarranty' && $user->rights->facture->creer) { $object->fetch($id); $result = $object->setRetainedWarranty(GETPOST('retained_warranty', 'float')); - if ($result < 0) + if ($result < 0) { dol_print_error($db, $object->error); + } } elseif ($action == 'setretainedwarrantydatelimit' && $user->rights->facture->creer) { $object->fetch($id); $result = $object->setRetainedWarrantyDateLimit(GETPOST('retained_warranty_date_limit', 'float')); - if ($result < 0) + if ($result < 0) { dol_print_error($db, $object->error); - } // 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')); } 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']); - if (empty($date)) - { + $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'); exit; } $object->date = $date; $new_date_lim_reglement = $object->calculate_date_lim_reglement(); - if ($new_date_lim_reglement > $old_date_lim_reglement) $object->date_lim_reglement = $new_date_lim_reglement; - if ($object->date_lim_reglement < $object->date) $object->date_lim_reglement = $object->date; + if ($new_date_lim_reglement > $old_date_lim_reglement) { + $object->date_lim_reglement = $new_date_lim_reglement; + } + if ($object->date_lim_reglement < $object->date) { + $object->date_lim_reglement = $object->date; + } $result = $object->update($user); if ($result < 0) { dol_print_error($db, $object->error); @@ -400,8 +412,7 @@ if (empty($reshook)) if ($result < 0) { dol_print_error($db, $object->error); } - } elseif ($action == 'setconditions' && $usercancreate) - { + } elseif ($action == 'setconditions' && $usercancreate) { $object->fetch($id); $object->cond_reglement_code = 0; // To clean property $object->cond_reglement_id = 0; // To clean property @@ -421,8 +432,12 @@ if (empty($reshook)) if (!$error) { $old_date_lim_reglement = $object->date_lim_reglement; $new_date_lim_reglement = $object->calculate_date_lim_reglement(); - if ($new_date_lim_reglement > $old_date_lim_reglement) $object->date_lim_reglement = $new_date_lim_reglement; - if ($object->date_lim_reglement < $object->date) $object->date_lim_reglement = $object->date; + if ($new_date_lim_reglement > $old_date_lim_reglement) { + $object->date_lim_reglement = $new_date_lim_reglement; + } + if ($object->date_lim_reglement < $object->date) { + $object->date_lim_reglement = $object->date; + } $result = $object->update($user); if ($result < 0) { $error++; @@ -435,8 +450,7 @@ if (empty($reshook)) } else { $db->commit(); } - } elseif ($action == 'setpaymentterm' && $usercancreate) - { + } elseif ($action == 'setpaymentterm' && $usercancreate) { $object->fetch($id); $object->date_lim_reglement = dol_mktime(12, 0, 0, $_POST['paymenttermmonth'], $_POST['paymenttermday'], $_POST['paymenttermyear']); if ($object->date_lim_reglement < $object->date) { @@ -447,8 +461,7 @@ if (empty($reshook)) if ($result < 0) { dol_print_error($db, $object->error); } - } elseif ($action == 'setrevenuestamp' && $usercancreate) - { + } elseif ($action == 'setrevenuestamp' && $usercancreate) { $object->fetch($id); $object->revenuestamp = GETPOST('revenuestamp'); $result = $object->update($user); @@ -457,12 +470,15 @@ if (empty($reshook)) dol_print_error($db, $object->error); } else { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -472,14 +488,14 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } } - } // Set incoterm - elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) { + } elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) { // Set incoterm $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); - } // bank account - elseif ($action == 'setbankaccount' && $usercancreate) { + } elseif ($action == 'setbankaccount' && $usercancreate) { // bank account $result = $object->setBankAccount(GETPOST('fk_account', 'int')); } elseif ($action == 'setremisepercent' && $usercancreate) { $object->fetch($id); @@ -500,23 +516,20 @@ if (empty($reshook)) } } // We use the credit to reduce remain to pay - if (GETPOST("remise_id_for_payment", 'int') > 0) - { + if (GETPOST("remise_id_for_payment", 'int') > 0) { require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discount = new DiscountAbsolute($db); $discount->fetch(GETPOST("remise_id_for_payment", 'int')); //var_dump($object->getRemainToPay(0)); //var_dump($discount->amount_ttc);exit; - if (price2num($discount->amount_ttc) > price2num($object->getRemainToPay(0))) - { + if (price2num($discount->amount_ttc) > price2num($object->getRemainToPay(0))) { // TODO Split the discount in 2 automatically $error++; setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors'); } - if (!$error) - { + if (!$error) { $result = $discount->link_to_invoice(0, $id); if ($result < 0) { setEventMessages($discount->error, $discount->errors, 'errors'); @@ -524,12 +537,15 @@ if (empty($reshook)) } } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -537,19 +553,18 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } - } elseif ($action == 'setref' && $usercancreate) - { + } elseif ($action == 'setref' && $usercancreate) { $object->fetch($id); $object->setValueFrom('ref', GETPOST('ref'), '', null, '', '', $user, 'BILL_MODIFY'); - } elseif ($action == 'setref_client' && $usercancreate) - { + } 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); @@ -559,22 +574,17 @@ if (empty($reshook)) // Check for mandatory fields in thirdparty (defined into setup) $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL'); - foreach ($array_to_check as $key) - { + foreach ($array_to_check as $key) { $keymin = strtolower($key); $i = (int) preg_replace('/[^0-9]/', '', $key); $vallabel = $object->thirdparty->$keymin; - if ($i > 0) - { - if ($object->thirdparty->isACompany()) - { + if ($i > 0) { + if ($object->thirdparty->isACompany()) { // Check for mandatory prof id (but only if country is other than ours) - if ($mysoc->country_id > 0 && $object->thirdparty->country_id == $mysoc->country_id) - { + if ($mysoc->country_id > 0 && $object->thirdparty->country_id == $mysoc->country_id) { $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY'; - if (!$vallabel && !empty($conf->global->$idprof_mandatory)) - { + if (!$vallabel && !empty($conf->global->$idprof_mandatory)) { $langs->load("errors"); $error++; setEventMessages($langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $object->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')', null, 'errors'); @@ -583,11 +593,9 @@ if (empty($reshook)) } } else { //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY); - if ($key == 'EMAIL') - { + if ($key == 'EMAIL') { // Check for mandatory - if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($object->thirdparty->email)) - { + if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($object->thirdparty->email)) { $langs->load("errors"); $error++; setEventMessages($langs->trans("ErrorBadEMail", $object->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").')', null, 'errors'); @@ -598,15 +606,13 @@ if (empty($reshook)) // Check for mandatory fields in invoice $array_to_check = array('REF_CUSTOMER'=>'RefCustomer'); - foreach ($array_to_check as $key => $val) - { + foreach ($array_to_check as $key => $val) { $keymin = strtolower($key); $vallabel = $object->$keymin; // Check for mandatory $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION'; - if (!$vallabel && !empty($conf->global->$keymandatory)) - { + if (!$vallabel && !empty($conf->global->$keymandatory)) { $langs->load("errors"); $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val)), null, 'errors'); @@ -614,8 +620,7 @@ if (empty($reshook)) } // Check for warehouse - if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) - { + if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) { $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change = $object->hasProductsOrServices(2); @@ -623,8 +628,7 @@ if (empty($reshook)) $qualified_for_stock_change = $object->hasProductsOrServices(1); } - if ($qualified_for_stock_change) - { + if ($qualified_for_stock_change) { if (!$idwarehouse || $idwarehouse == - 1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); @@ -633,18 +637,19 @@ if (empty($reshook)) } } - if (!$error) - { + if (!$error) { $result = $object->validate($user, '', $idwarehouse); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -655,24 +660,27 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } } else { - if (count($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, $object->errors, 'errors'); + if (count($object->errors)) { + setEventMessages(null, $object->errors, 'errors'); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } } } - } // Go back to draft status (unvalidate) - elseif ($action == 'confirm_modif' && $usercanunvalidate) - { + } elseif ($action == 'confirm_modif' && $usercanunvalidate) { + // Go back to draft status (unvalidate) $idwarehouse = GETPOST('idwarehouse', 'int'); $object->fetch($id); $object->fetch_thirdparty(); // Check parameters - if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) - { + if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) { $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change = $object->hasProductsOrServices(2); @@ -680,8 +688,7 @@ if (empty($reshook)) $qualified_for_stock_change = $object->hasProductsOrServices(1); } - if ($qualified_for_stock_change) - { + if ($qualified_for_stock_change) { if (!$idwarehouse || $idwarehouse == - 1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); @@ -716,20 +723,23 @@ if (empty($reshook)) $ventilExportCompta = $object->getVentilExportCompta(); // On verifie si aucun paiement n'a ete effectue - if ($ventilExportCompta == 0) - { - if (!empty($conf->global->INVOICE_CAN_ALWAYS_BE_EDITED) || ($resteapayer == $object->total_ttc && empty($object->paye))) - { + if ($ventilExportCompta == 0) { + if (!empty($conf->global->INVOICE_CAN_ALWAYS_BE_EDITED) || ($resteapayer == $object->total_ttc && empty($object->paye))) { $result = $object->setDraft($user, $idwarehouse); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -743,38 +753,41 @@ if (empty($reshook)) } } } - } // Classify "paid" - elseif ($action == 'confirm_paid' && $confirm == 'yes' && $usercanissuepayment) - { + } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $usercanissuepayment) { + // Classify "paid" $object->fetch($id); $result = $object->setPaid($user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); - } // Classif "paid partialy" - elseif ($action == 'confirm_paid_partially' && $confirm == 'yes' && $usercanissuepayment) - { + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } elseif ($action == 'confirm_paid_partially' && $confirm == 'yes' && $usercanissuepayment) { + // Classif "paid partialy" $object->fetch($id); $close_code = GETPOST("close_code", 'restricthtml'); $close_note = GETPOST("close_note", 'restricthtml'); if ($close_code) { $result = $object->setPaid($user, $close_code, $close_note); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } else { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors'); } - } // Classify "abandoned" - elseif ($action == 'confirm_canceled' && $confirm == 'yes') { + } elseif ($action == 'confirm_canceled' && $confirm == 'yes') { + // Classify "abandoned" $object->fetch($id); $close_code = GETPOST("close_code", 'restricthtml'); $close_note = GETPOST("close_note", 'restricthtml'); if ($close_code) { $result = $object->setCanceled($user, $close_code, $close_note); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } else { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors'); } - } // Convertir en reduc - elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) - { + } elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) { + // Convertir en reduc $object->fetch($id); $object->fetch_thirdparty(); //$object->fetch_lines(); // Already done into fetch @@ -784,10 +797,14 @@ if (empty($reshook)) $result = $discountcheck->fetch(0, $object->id); $canconvert = 0; - if ($object->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) $canconvert = 1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) - if (($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) && $object->paye == 0 && empty($discountcheck->id)) $canconvert = 1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc) - if ($canconvert) - { + if ($object->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) { + $canconvert = 1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) + } + if (($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) && $object->paye == 0 && empty($discountcheck->id)) { + $canconvert = 1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc) + } + + if ($canconvert) { $db->begin(); $amount_ht = $amount_tva = $amount_ttc = array(); @@ -795,10 +812,8 @@ if (empty($reshook)) // Loop on each vat rate $i = 0; - foreach ($object->lines as $line) - { - if ($line->product_type < 9 && $line->total_ht != 0) // Remove lines with product_type greater than or equal to 9 and no need to create discount if amount is null - { + foreach ($object->lines as $line) { + if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9 and no need to create discount if amount is null $keyforvatrate = $line->tva_tx.($line->vat_src_code ? ' ('.$line->vat_src_code.')' : ''); $amount_ht[$keyforvatrate] += $line->total_ht; @@ -830,13 +845,13 @@ if (empty($reshook)) // Insert one discount by VAT rate category $discount = new DiscountAbsolute($db); - if ($object->type == Facture::TYPE_CREDIT_NOTE) + if ($object->type == Facture::TYPE_CREDIT_NOTE) { $discount->description = '(CREDIT_NOTE)'; - elseif ($object->type == Facture::TYPE_DEPOSIT) + } elseif ($object->type == Facture::TYPE_DEPOSIT) { $discount->description = '(DEPOSIT)'; - elseif ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) + } elseif ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) { $discount->description = '(EXCESS RECEIVED)'; - else { + } else { setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors'); } $discount->fk_soc = $object->socid; @@ -844,8 +859,7 @@ if (empty($reshook)) $error = 0; - if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) - { + if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) { // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT // Total payments @@ -856,7 +870,9 @@ if (empty($reshook)) $sql .= ' AND pf.fk_paiement = p.rowid'; $sql .= ' AND p.entity IN ('.getEntity('invoice').')'; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $res = $db->fetch_object($resql); $total_paiements = $res->total_paiements; @@ -872,7 +888,9 @@ if (empty($reshook)) while ($obj = $db->fetch_object($resql)) { $total_creditnote_and_deposit += $obj->amount_ttc; } - } else dol_print_error($db); + } else { + dol_print_error($db); + } $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $object->total_ttc; $discount->amount_tva = 0; @@ -880,15 +898,12 @@ if (empty($reshook)) $discount->vat_src_code = ''; $result = $discount->create($user); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) - { - foreach ($amount_ht as $tva_tx => $xxx) - { + if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) { + foreach ($amount_ht as $tva_tx => $xxx) { $discount->amount_ht = abs($amount_ht[$tva_tx]); $discount->amount_tva = abs($amount_tva[$tva_tx]); $discount->amount_ttc = abs($amount_ttc[$tva_tx]); @@ -899,8 +914,7 @@ if (empty($reshook)) // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $tva_tx, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx, $reg)) { $vat_src_code = $reg[1]; $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx); // Remove code into vatrate. } @@ -909,21 +923,18 @@ if (empty($reshook)) $discount->vat_src_code = $vat_src_code; $result = $discount->create($user); - if ($result < 0) - { + if ($result < 0) { $error++; break; } } } - if (empty($error)) - { + if (empty($error)) { if ($object->type != Facture::TYPE_DEPOSIT) { // Classe facture $result = $object->setPaid($user); - if ($result >= 0) - { + if ($result >= 0) { $db->commit(); } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -937,12 +948,10 @@ if (empty($reshook)) $db->rollback(); } } - } // Delete payment - elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercancreate) - { + } elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercancreate) { + // Delete payment $object->fetch($id); - if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0) - { + if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0) { $paiement = new Paiement($db); $result = $paiement->fetch(GETPOST('paiement_id')); if ($result > 0) { @@ -953,12 +962,11 @@ if (empty($reshook)) setEventMessages($paiement->error, $paiement->errors, 'errors'); } } - } /* - * Insert new invoice in database - */ - elseif ($action == 'add' && $usercancreate) - { - if ($socid > 0) $object->socid = GETPOST('socid', 'int'); + } elseif ($action == 'add' && $usercancreate) { + // Insert new invoice in database + if ($socid > 0) { + $object->socid = GETPOST('socid', 'int'); + } $selectedLines = GETPOST('toselect', 'array'); $db->begin(); @@ -967,11 +975,12 @@ if (empty($reshook)) $originentity = GETPOST('originentity'); // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } // Replacement invoice - if (GETPOST('type') == Facture::TYPE_REPLACEMENT) - { + if (GETPOST('type') == Facture::TYPE_REPLACEMENT) { $dateinvoice = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); if (empty($dateinvoice)) { $error++; @@ -983,7 +992,7 @@ if (empty($reshook)) $action = 'create'; } - if (!($_POST['fac_replacement'] > 0)) { + if (!(GETPOST('fac_replacement', 'int') > 0)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors'); $action = 'create'; @@ -1014,7 +1023,7 @@ if (empty($reshook)) $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); // Proprietes particulieres a facture de remplacement - $object->fk_facture_source = $_POST['fac_replacement']; + $object->fk_facture_source = GETPOST('fac_replacement', 'int'); $object->type = Facture::TYPE_REPLACEMENT; $id = $object->createFromCurrent($user); @@ -1025,11 +1034,9 @@ if (empty($reshook)) } // Credit note invoice - if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) - { + if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) { $sourceinvoice = GETPOST('fac_avoir', 'int'); - if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) - { + if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors'); $action = 'create'; @@ -1048,8 +1055,7 @@ if (empty($reshook)) $date_pointoftax = dol_mktime(12, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int')); - if (!$error) - { + if (!$error) { if (!empty($originentity)) { $object->entity = $originentity; } @@ -1077,10 +1083,8 @@ if (empty($reshook)) $object->type = Facture::TYPE_CREDIT_NOTE; $facture_source = new Facture($db); // fetch origin object - if ($facture_source->fetch($object->fk_facture_source) > 0) - { - if ($facture_source->type == Facture::TYPE_SITUATION) - { + if ($facture_source->fetch($object->fk_facture_source) > 0) { + if ($facture_source->type == Facture::TYPE_SITUATION) { $object->situation_counter = $facture_source->situation_counter; $object->situation_cycle_ref = $facture_source->situation_cycle_ref; $facture_source->fetchPreviousNextSituationInvoice(); @@ -1093,14 +1097,11 @@ if (empty($reshook)) // NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good) // NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad) // NOTE: fields situation_percent on credit note are stored as delta on lines (good) - if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) - { - if (!empty($facture_source->lines)) - { + if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) { + if (!empty($facture_source->lines)) { $fk_parent_line = 0; - foreach ($facture_source->lines as $line) - { + foreach ($facture_source->lines as $line) { // Extrafields if (method_exists($line, 'fetch_optionals')) { // load extrafields @@ -1113,22 +1114,18 @@ if (empty($reshook)) } - if ($facture_source->type == Facture::TYPE_SITUATION) - { + if ($facture_source->type == Facture::TYPE_SITUATION) { $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from - if (!empty($facture_source->tab_previous_situation_invoice)) - { + if (!empty($facture_source->tab_previous_situation_invoice)) { // search the last standard invoice in cycle and the possible credit note between this last and facture_source // TODO Move this out of loop of $facture_source->lines $tab_jumped_credit_notes = array(); $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1; $searchPreviousInvoice = true; - while ($searchPreviousInvoice) - { - if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) - { + while ($searchPreviousInvoice) { + if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) { $searchPreviousInvoice = false; // find, exit; break; } else { @@ -1140,10 +1137,8 @@ if (empty($reshook)) } $maxPrevSituationPercent = 0; - foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) - { - if ($prevLine->id == $source_fk_prev_id) - { + foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) { + if ($prevLine->id == $source_fk_prev_id) { $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent); //$line->subprice = $line->subprice - $prevLine->subprice; @@ -1168,10 +1163,8 @@ if (empty($reshook)) // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta) $maxPrevSituationPercent = 0; foreach ($tab_jumped_credit_notes as $index => $creditnoteid) { - foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) - { - if ($prevLine->fk_prev_id == $source_fk_prev_id) - { + foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) { + if ($prevLine->fk_prev_id == $source_fk_prev_id) { $maxPrevSituationPercent = $prevLine->situation_percent; $line->total_ht -= $prevLine->total_ht; @@ -1225,10 +1218,8 @@ if (empty($reshook)) } } - if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) - { - if ($facture_source->fetch($object->fk_facture_source) > 0) - { + if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) { + if ($facture_source->fetch($object->fk_facture_source) > 0) { $totalpaye = $facture_source->getSommePaiement(); $totalcreditnotes = $facture_source->getSumCreditNotesUsed(); $totaldeposits = $facture_source->getSumDepositsUsed(); @@ -1253,8 +1244,7 @@ if (empty($reshook)) } // Standard invoice or Deposit invoice, created from a Predefined template invoice - if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT) && GETPOST('fac_rec', 'int') > 0) - { + if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT) && GETPOST('fac_rec', 'int') > 0) { $dateinvoice = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); if (empty($dateinvoice)) { $error++; @@ -1268,8 +1258,7 @@ if (empty($reshook)) $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']); - if (!$error) - { + if (!$error) { $object->socid = GETPOST('socid', 'int'); $object->type = GETPOST('type'); $object->ref = GETPOST('ref'); @@ -1298,17 +1287,20 @@ if (empty($reshook)) } } - // Standard or deposit or proforma invoice, not from a Predefined template invoice - if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT || GETPOST('type') == Facture::TYPE_PROFORMA || (GETPOST('type') == Facture::TYPE_SITUATION && !GETPOST('situations'))) && GETPOST('fac_rec') <= 0) - { - if (GETPOST('socid', 'int') < 1) - { + // Standard or deposit invoice, not from a Predefined template invoice + if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT || GETPOST('type') == Facture::TYPE_PROFORMA || (GETPOST('type') == Facture::TYPE_SITUATION && !GETPOST('situations'))) && GETPOST('fac_rec') <= 0) { + $typeamount = GETPOST('typedeposit', 'aZ09'); + $valuestandardinvoice = price2num(str_replace('%', '', GETPOST('valuestandardinvoice', 'alpha')), 'MU'); + $valuedeposit = price2num(str_replace('%', '', GETPOST('valuedeposit', 'alpha')), 'MU'); + $dateinvoice = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); + $date_pointoftax = dol_mktime(12, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int')); + + if (GETPOST('socid', 'int') < 1) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors'); $action = 'create'; } - $dateinvoice = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); if (empty($dateinvoice)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); @@ -1319,10 +1311,34 @@ if (empty($reshook)) $action = 'create'; } - $date_pointoftax = dol_mktime(12, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int')); - if (!$error) - { + if (GETPOST('type') == Facture::TYPE_STANDARD) { + if ($valuestandardinvoice < 0 || $valuestandardinvoice > 100) { + setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors'); + $error++; + $action = 'create'; + } + } elseif (GETPOST('type') == Facture::TYPE_DEPOSIT) { + if ($typeamount && !empty($origin) && !empty($originid)) { + if ($typeamount == 'amount' && $valuedeposit <= 0) { + setEventMessages($langs->trans("ErrorAnAmountWithoutTaxIsRequired"), null, 'errors'); + $error++; + $action = 'create'; + } + if ($typeamount == 'variable' && $valuedeposit <= 0) { + setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors'); + $error++; + $action = 'create'; + } + if ($typeamount == 'variablealllines' && $valuedeposit <= 0) { + setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors'); + $error++; + $action = 'create'; + } + } + } + + if (!$error) { // Si facture standard $object->socid = GETPOST('socid', 'int'); $object->type = GETPOST('type'); @@ -1345,8 +1361,7 @@ if (empty($reshook)) $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); - if (GETPOST('type') == Facture::TYPE_SITUATION) - { + if (GETPOST('type') == Facture::TYPE_SITUATION) { $object->situation_counter = 1; $object->situation_final = 0; $object->situation_cycle_ref = $object->newCycle(); @@ -1361,21 +1376,21 @@ if (empty($reshook)) } $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit'); - if (!empty($retained_warranty_date_limit) && $db->jdate($retained_warranty_date_limit)) { - $object->retained_warranty_date_limit = $db->jdate($retained_warranty_date_limit); + if (!empty($retained_warranty_date_limit) && dol_stringtotime($retained_warranty_date_limit)) { + $object->retained_warranty_date_limit = dol_stringtotime($retained_warranty_date_limit); } $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement); $object->fetch_thirdparty(); // If creation from another object of another module (Example: origin=propal, originid=1) - if (!empty($origin) && !empty($originid)) - { + if (!empty($origin) && !empty($originid)) { + $regs = array(); // Parse element/subelement (ex: project_task) $element = $subelement = $origin; if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) { - $element = $regs [1]; - $subelement = $regs [2]; + $element = $regs[1]; + $subelement = $regs[2]; } // For compatibility @@ -1402,8 +1417,7 @@ if (empty($reshook)) // Possibility to add external linked objects with hooks $object->linked_objects[$object->origin] = $object->origin_id; // link with order if it is a shipping invoice - if ($object->origin == 'shipping') - { + if ($object->origin == 'shipping') { require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; $exp = new Expedition($db); $exp->fetch($object->origin_id); @@ -1415,15 +1429,13 @@ if (empty($reshook)) } } - if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) - { + if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) { $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); } $id = $object->create($user); // This include class to add_object_linked() and add add_contact() - if ($id > 0) - { + if ($id > 0) { dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); @@ -1432,48 +1444,47 @@ if (empty($reshook)) dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines or deposit lines"); $result = $srcobject->fetch($object->origin_id); - $typeamount = GETPOST('typedeposit', 'aZ09'); - $valuedeposit = price2num(GETPOST('valuedeposit', 'alpha'), 'MU'); - - // If deposit invoice - if ($_POST['type'] == Facture::TYPE_DEPOSIT && in_array($typeamount, array('amount', 'variable'))) - { + // If deposit invoice - down payment with 1 line (fixed amount or percent) + if (GETPOST('type') == Facture::TYPE_DEPOSIT && in_array($typeamount, array('amount', 'variable'))) { + // Define the array $amountdeposit $amountdeposit = array(); - if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) - { - if ($typeamount == 'amount') $amount = $valuedeposit; - else $amount = $srcobject->total_ttc * ($valuedeposit / 100); + if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) { + if ($typeamount == 'amount') { + $amount = $valuedeposit; + } else { + $amount = $srcobject->total_ttc * ($valuedeposit / 100); + } $TTotalByTva = array(); - foreach ($srcobject->lines as &$line) - { - if (!empty($line->special_code)) continue; + foreach ($srcobject->lines as &$line) { + if (!empty($line->special_code)) { + continue; + } $TTotalByTva[$line->tva_tx] += $line->total_ttc; } - foreach ($TTotalByTva as $tva => &$total) - { + foreach ($TTotalByTva as $tva => &$total) { $coef = $total / $srcobject->total_ttc; // Calc coef $am = $amount * $coef; $amount_ttc_diff += $am; $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline } } else { - if ($typeamount == 'amount') - { + if ($typeamount == 'amount') { $amountdeposit[0] = $valuedeposit; - } elseif ($typeamount == 'variable') - { - if ($result > 0) - { + } elseif ($typeamount == 'variable') { + if ($result > 0) { $totalamount = 0; $lines = $srcobject->lines; $numlines = count($lines); - for ($i = 0; $i < $numlines; $i++) - { + for ($i = 0; $i < $numlines; $i++) { $qualified = 1; - if (empty($lines[$i]->qty)) $qualified = 0; // We discard qty=0, it is an option - if (!empty($lines[$i]->special_code)) $qualified = 0; // We discard special_code (frais port, ecotaxe, option, ...) + if (empty($lines[$i]->qty)) { + $qualified = 0; // We discard qty=0, it is an option + } + if (!empty($lines[$i]->special_code)) { + $qualified = 0; // We discard special_code (frais port, ecotaxe, option, ...) + } if ($qualified) { $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ? $tva_tx = $lines[$i]->tva_tx; @@ -1493,9 +1504,10 @@ if (empty($reshook)) $amount_ttc_diff = $amountdeposit[0]; } - foreach ($amountdeposit as $tva => $amount) - { - if (empty($amount)) continue; + foreach ($amountdeposit as $tva => $amount) { + if (empty($amount)) { + continue; + } $arraylist = array( 'amount' => 'FixAmount', @@ -1511,56 +1523,62 @@ if (empty($reshook)) $descline .= ' - '.$srcobject->ref; $result = $object->addline( - $descline, - $amount, // subprice - 1, // quantity - $tva, // vat rate - 0, // localtax1_tx - 0, // localtax2_tx - (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product - 0, // remise_percent - 0, // date_start - 0, // date_end - 0, - $lines[$i]->info_bits, // info_bits - 0, - 'HT', - 0, - 0, // product_type - 1, - $lines[$i]->special_code, - $object->origin, - 0, - 0, - 0, - 0 - //,$langs->trans('Deposit') //Deprecated - ); + $descline, + $amount, // subprice + 1, // quantity + $tva, // vat rate + 0, // localtax1_tx + 0, // localtax2_tx + (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product + 0, // remise_percent + 0, // date_start + 0, // date_end + 0, + $lines[$i]->info_bits, // info_bits + 0, + 'HT', + 0, + 0, // product_type + 1, + $lines[$i]->special_code, + $object->origin, + 0, + 0, + 0, + 0 + //,$langs->trans('Deposit') //Deprecated + ); } $diff = $object->total_ttc - $amount_ttc_diff; - if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) - { + if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) { $object->fetch_lines(); $subprice_diff = $object->lines[0]->subprice - $diff / (1 + $object->lines[0]->tva_tx / 100); $object->updateline($object->lines[0]->id, $object->lines[0]->desc, $subprice_diff, $object->lines[0]->qty, $object->lines[0]->remise_percent, $object->lines[0]->date_start, $object->lines[0]->date_end, $object->lines[0]->tva_tx, 0, 0, 'HT', $object->lines[0]->info_bits, $object->lines[0]->product_type, 0, 0, 0, $object->lines[0]->pa_ht, $object->lines[0]->label, 0, array(), 100); } } - if ($_POST['type'] != Facture::TYPE_DEPOSIT || ($_POST['type'] == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines')) - { - if ($result > 0) - { + // standard invoice, credit note, or down payment from a percent of all lines + if (GETPOST('type') != Facture::TYPE_DEPOSIT || (GETPOST('type') == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines')) { + if ($result > 0) { $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject, 'fetch_lines')) - { + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) { $srcobject->fetch_lines(); $lines = $srcobject->lines; } - // If we create a deposit with all lines and a percent, we change amount - if ($_POST['type'] == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines') { + // If we create a standard invoice with a percent, we change amount by changing the qty + if (GETPOST('type') == Facture::TYPE_STANDARD && $valuestandardinvoice > 0 && $valuestandardinvoice < 100) { + if (is_array($lines)) { + foreach ($lines as $line) { + // We keep ->subprice and ->pa_ht, but we change the qty + $line->qty = price2num($line->qty * $valuestandardinvoice / 100, 'MS'); + } + } + } + // If we create a down payment with a percent on all lines, we change amount by changing the qty + if (GETPOST('type') == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines') { if (is_array($lines)) { foreach ($lines as $line) { // We keep ->subprice and ->pa_ht, but we change the qty @@ -1572,22 +1590,30 @@ if (empty($reshook)) $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { - if (!in_array($lines[$i]->id, $selectedLines)) continue; // Skip unselected lines + for ($i = 0; $i < $num; $i++) { + if (!in_array($lines[$i]->id, $selectedLines)) { + continue; // Skip unselected lines + } // Don't add lines with qty 0 when coming from a shipment including all order lines - if ($srcobject->element == 'shipping' && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS && $lines[$i]->qty == 0) continue; + if ($srcobject->element == 'shipping' && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS && $lines[$i]->qty == 0) { + continue; + } // Don't add closed lines when coming from a contract (Set constant to '0,5' to exclude also inactive lines) - if (!isset($conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE)) $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE = '5'; - if ($srcobject->element == 'contrat' && in_array($lines[$i]->statut, explode(',', $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE))) continue; + if (!isset($conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE)) { + $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE = '5'; + } + if ($srcobject->element == 'contrat' && in_array($lines[$i]->statut, explode(',', $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE))) { + continue; + } $label = (!empty($lines[$i]->label) ? $lines[$i]->label : ''); $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->libelle); - if ($object->situation_counter == 1) $lines[$i]->situation_percent = 0; + if ($object->situation_counter == 1) { + $lines[$i]->situation_percent = 0; + } - if ($lines[$i]->subprice < 0 && empty($conf->global->INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN)) - { + if ($lines[$i]->subprice < 0 && empty($conf->global->INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN)) { // Negative line, we create a discount line $discount = new DiscountAbsolute($db); $discount->fk_soc = $object->socid; @@ -1611,23 +1637,29 @@ if (empty($reshook)) // Date start $date_start = false; - if ($lines[$i]->date_debut_prevue) + if ($lines[$i]->date_debut_prevue) { $date_start = $lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) + } + if ($lines[$i]->date_debut_reel) { $date_start = $lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) + } + if ($lines[$i]->date_start) { $date_start = $lines[$i]->date_start; + } - // Date end + // Date end $date_end = false; - if ($lines[$i]->date_fin_prevue) + if ($lines[$i]->date_fin_prevue) { $date_end = $lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) + } + if ($lines[$i]->date_fin_reel) { $date_end = $lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) + } + if ($lines[$i]->date_end) { $date_end = $lines[$i]->date_end; + } - // Reset fk_parent_line for no child products and special product + // Reset fk_parent_line for no child products and special product if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) { $fk_parent_line = 0; } @@ -1639,7 +1671,9 @@ if (empty($reshook)) } $tva_tx = $lines[$i]->tva_tx; - if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$i]->vat_src_code.')'; + if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) { + $tva_tx .= ' ('.$lines[$i]->vat_src_code.')'; + } // View third's localtaxes for NOW and do not use value from origin. // TODO Is this really what we want ? Yes if source is template invoice but what if proposal or order ? @@ -1647,11 +1681,34 @@ if (empty($reshook)) $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty); $result = $object->addline( - $desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $localtax1_tx, $localtax2_tx, $lines[$i]->fk_product, - $lines[$i]->remise_percent, $date_start, $date_end, 0, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, - 'HT', 0, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $object->origin, $lines[$i]->rowid, - $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, - $lines[$i]->situation_percent, $lines[$i]->fk_prev_id, $lines[$i]->fk_unit + $desc, + $lines[$i]->subprice, + $lines[$i]->qty, + $tva_tx, + $localtax1_tx, + $localtax2_tx, + $lines[$i]->fk_product, + $lines[$i]->remise_percent, + $date_start, + $date_end, + 0, + $lines[$i]->info_bits, + $lines[$i]->fk_remise_except, + 'HT', + 0, + $product_type, + $lines[$i]->rang, + $lines[$i]->special_code, + $object->origin, + $lines[$i]->rowid, + $fk_parent_line, + $lines[$i]->fk_fournprice, + $lines[$i]->pa_ht, + $label, + $array_options, + $lines[$i]->situation_percent, + $lines[$i]->fk_prev_id, + $lines[$i]->fk_unit ); if ($result > 0) { @@ -1678,34 +1735,33 @@ if (empty($reshook)) /* Useless, already into the create if (! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN)) { - $originforcontact = $object->origin; - $originidforcontact = $object->origin_id; - if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order - { - $originforcontact=$srcobject->origin; - $originidforcontact=$srcobject->origin_id; - } - $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc"; - $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'"; + $originforcontact = $object->origin; + $originidforcontact = $object->origin_id; + if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order + { + $originforcontact=$srcobject->origin; + $originidforcontact=$srcobject->origin_id; + } + $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc"; + $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'"; - $resqlcontact = $db->query($sqlcontact); - if ($resqlcontact) - { - while($objcontact = $db->fetch_object($resqlcontact)) - { - //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n"; - $object->add_contact($objcontact->fk_socpeople, $objcontact->code); - } - } - else dol_print_error($resqlcontact); + $resqlcontact = $db->query($sqlcontact); + if ($resqlcontact) + { + while($objcontact = $db->fetch_object($resqlcontact)) + { + //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n"; + $object->add_contact($objcontact->fk_socpeople, $objcontact->code); + } + } + else dol_print_error($resqlcontact); }*/ // Hooks $parameters = array('objFrom' => $srcobject); $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if ($reshook < 0) - { + if ($reshook < 0) { setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); $error++; } @@ -1730,8 +1786,7 @@ if (empty($reshook)) } // Situation invoices - if (GETPOST('type') == Facture::TYPE_SITUATION && GETPOST('situations')) - { + if (GETPOST('type') == Facture::TYPE_SITUATION && GETPOST('situations')) { $dateinvoice = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); if (empty($dateinvoice)) { $error++; @@ -1757,24 +1812,20 @@ if (empty($reshook)) $object->fk_facture_source = GETPOST('situations', 'int'); $object->type = Facture::TYPE_SITUATION; - if (!empty($origin) && !empty($originid)) - { + if (!empty($origin) && !empty($originid)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; $object->origin = $origin; $object->origin_id = $originid; // retained warranty - if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) - { + if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) { $retained_warranty = GETPOST('retained_warranty', 'int'); - if (price2num($retained_warranty) > 0) - { + if (price2num($retained_warranty) > 0) { $object->retained_warranty = price2num($retained_warranty); } - if (GETPOST('retained_warranty_fk_cond_reglement', 'int') > 0) - { + if (GETPOST('retained_warranty_fk_cond_reglement', 'int') > 0) { $object->retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int'); } @@ -1785,8 +1836,7 @@ if (empty($reshook)) $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement); } - foreach ($object->lines as $i => &$line) - { + foreach ($object->lines as $i => &$line) { $line->origin = $object->origin; $line->origin_id = $line->id; $line->fk_prev_id = $line->id; @@ -1805,15 +1855,12 @@ if (empty($reshook)) $line->multicurrency_total_ttc = $tabprice[18]; // Si fk_remise_except defini on vérifie si la réduction à déjà été appliquée - if ($line->fk_remise_except) - { + if ($line->fk_remise_except) { $discount = new DiscountAbsolute($line->db); $result = $discount->fetch($line->fk_remise_except); - if ($result > 0) - { + if ($result > 0) { // Check if discount not already affected to another invoice - if ($discount->fk_facture_line > 0) - { + if ($discount->fk_facture_line > 0) { $line->fk_remise_except = 0; } } @@ -1839,8 +1886,7 @@ if (empty($reshook)) $object->situation_counter = $object->situation_counter + 1; $id = $object->createFromCurrent($user); - if ($id <= 0) - { + if ($id <= 0) { $mesg = $object->error; } else { $nextSituationInvoice = new Facture($db); @@ -1857,17 +1903,19 @@ if (empty($reshook)) } // End of object creation, we show it - if ($id > 0 && !$error) - { + if ($id > 0 && !$error) { $db->commit(); // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && count($object->lines)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && count($object->lines)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -1877,7 +1925,9 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id); @@ -1889,7 +1939,7 @@ if (empty($reshook)) $_GET["originid"] = $_POST["originid"]; setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'addline' && GETPOST('submitforalllines', 'aZ09') && GETPOST('vatforalllines', 'alpha')) { + } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('vatforalllines', 'alpha') !== '') { // Define vat_rate $vat_rate = (GETPOST('vatforalllines') ? GETPOST('vatforalllines') : 0); $vat_rate = str_replace('*', '', $vat_rate); @@ -1898,19 +1948,17 @@ if (empty($reshook)) foreach ($object->lines as $line) { $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice); } - } elseif ($action == 'addline' && $usercancreate) // Add a new line - { + } elseif ($action == 'addline' && $usercancreate) { // Add a new line $langs->load('errors'); $error = 0; // 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') - { + if ($prod_entry_mode == 'free') { $idprod = 0; $tva_tx = (GETPOST('tva_tx', 'alpha') ? GETPOST('tva_tx', 'alpha') : 0); } else { @@ -1936,10 +1984,8 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; } - if (!$prod_entry_mode) - { - if (GETPOST('type') < 0 && !GETPOST('search_idprod')) - { + if (!$prod_entry_mode) { + if (GETPOST('type') < 0 && !GETPOST('search_idprod')) { setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors'); $error++; } @@ -1948,10 +1994,8 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); $error++; } - if (($prod_entry_mode == 'free' && empty($idprod) && (($price_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $price_ht == '') && $price_ht_devise == '') && $object->type != Facture::TYPE_CREDIT_NOTE) // Unit price can be 0 but not '' - { - if ($price_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) - { + if (($prod_entry_mode == 'free' && empty($idprod) && (($price_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $price_ht == '') && $price_ht_devise == '') && $object->type != Facture::TYPE_CREDIT_NOTE) { // Unit price can be 0 but not '' + if ($price_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) { $langs->load("errors"); if ($object->type == $object::TYPE_DEPOSIT) { // Using negative lines on deposit lead to headach and blocking problems when you want to consume them. @@ -2015,8 +2059,7 @@ if (empty($reshook)) // Ecrase $tva_tx par celui du produit // Ecrase $base_price_type par celui du produit // Replaces $fk_unit with the product's - if (!empty($idprod)) - { + if (!empty($idprod)) { $prod = new Product($db); $prod->fetch($idprod); @@ -2038,16 +2081,13 @@ if (empty($reshook)) $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx)); // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ? - if (!empty($price_ht) || $price_ht === '0') - { + 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) - { - if ($price_base_type != 'HT') - { + } 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 { $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); @@ -2060,10 +2100,12 @@ if (empty($reshook)) if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) + } + if (empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -2080,8 +2122,11 @@ if (empty($reshook)) $product_desc=''; } - if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $desc = $product_desc; - else $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) { + $desc = $product_desc; + } else { + $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + } // Add custom code and origin country into description if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) { @@ -2090,28 +2135,36 @@ if (empty($reshook)) if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'alpha')) + if (empty($newlang) && GETPOST('lang_id', 'alpha')) { $newlang = GETPOST('lang_id', 'alpha'); - if (empty($newlang)) + } + if (empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - if (!empty($prod->customcode)) + if (!empty($prod->customcode)) { $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; - if (!empty($prod->customcode) && !empty($prod->country_code)) + } + if (!empty($prod->customcode) && !empty($prod->country_code)) { $tmptxt .= ' - '; - if (!empty($prod->country_code)) + } + if (!empty($prod->country_code)) { $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0); + } } else { - if (!empty($prod->customcode)) + if (!empty($prod->customcode)) { $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; - if (!empty($prod->customcode) && !empty($prod->country_code)) + } + if (!empty($prod->customcode) && !empty($prod->country_code)) { $tmptxt .= ' - '; - if (!empty($prod->country_code)) + } + if (!empty($prod->country_code)) { $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0); + } } $tmptxt .= ')'; $desc = dol_concatdesc($desc, $tmptxt); @@ -2124,7 +2177,9 @@ if (empty($reshook)) $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); $tva_tx = str_replace('*', '', $tva_tx); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); $desc = $product_desc; $type = GETPOST('type'); @@ -2141,15 +2196,22 @@ if (empty($reshook)) $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr); $info_bits = 0; - if ($tva_npr) + if ($tva_npr) { $info_bits |= 0x01; + } $price2num_pu_ht = price2num($pu_ht); $price2num_remise_percent = price2num($remise_percent); $price2num_price_min = price2num($price_min); - if (empty($price2num_pu_ht)) $price2num_pu_ht = 0; - if (empty($price2num_remise_percent)) $price2num_remise_percent = 0; - if (empty($price2num_price_min)) $price2num_price_min = 0; + if (empty($price2num_pu_ht)) { + $price2num_pu_ht = 0; + } + if (empty($price2num_remise_percent)) { + $price2num_remise_percent = 0; + } + if (empty($price2num_price_min)) { + $price2num_price_min = 0; + } if ($usercanproductignorepricemin && (!empty($price_min) && ($price2num_pu_ht * (1 - $price2num_remise_percent / 100) < $price2num_price_min))) { $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)); @@ -2158,15 +2220,17 @@ if (empty($reshook)) // Insert line $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $date_start, $date_end, 0, $info_bits, '', $price_base_type, $pu_ttc, $type, - 1, $special_code, '', 0, GETPOST('fk_parent_line'), $fournprice, $buyingprice, $label, $array_options, $_POST['progress'], '', $fk_unit, $pu_ht_devise); - if ($result > 0) - { + if ($result > 0) { // Define output language and generate document - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -2176,7 +2240,9 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } unset($_POST['prod_entry_mode']); @@ -2221,9 +2287,10 @@ if (empty($reshook)) $action = ''; } } - } elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) - { - if (!$object->fetch($id) > 0) dol_print_error($db); + } elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) { + if (!$object->fetch($id) > 0) { + dol_print_error($db); + } $object->fetch_thirdparty(); // Clean parameters @@ -2232,14 +2299,16 @@ 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; - if (preg_match('/\*/', $vat_rate)) $info_bits |= 0x01; + if (preg_match('/\*/', $vat_rate)) { + $info_bits |= 0x01; + } // Define vat_rate $vat_rate = str_replace('*', '', $vat_rate); @@ -2263,30 +2332,28 @@ if (empty($reshook)) // Define special_code for special lines $special_code = GETPOST('special_code'); - if (!GETPOST('qty')) $special_code = 3; + if (!GETPOST('qty')) { + $special_code = 3; + } $line = new FactureLigne($db); $line->fetch(GETPOST('lineid', 'int')); $percent = $line->get_prev_progress($object->id); - if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->situation_cycle_ref > 0) - { + if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->situation_cycle_ref > 0) { // in case of situation credit note - if (GETPOST('progress') >= 0) - { + if (GETPOST('progress') >= 0) { $mesg = $langs->trans("CantBeNullOrPositive"); setEventMessages($mesg, null, 'warnings'); $error++; $result = -1; - } elseif (GETPOST('progress') < $line->situation_percent) // TODO : use a modified $line->get_prev_progress($object->id) result - { + } elseif (GETPOST('progress') < $line->situation_percent) { // TODO : use a modified $line->get_prev_progress($object->id) result $mesg = $langs->trans("CantBeLessThanMinPercent"); setEventMessages($mesg, null, 'warnings'); $error++; $result = -1; } - } elseif (GETPOST('progress') < $percent) - { + } elseif (GETPOST('progress') < $percent) { $mesg = '
    '.$langs->trans("CantBeLessThanMinPercent").'
    '; setEventMessages($mesg, null, 'warnings'); $error++; @@ -2295,16 +2362,16 @@ if (empty($reshook)) // Check minimum price $productid = GETPOST('productid', 'int'); - if (!empty($productid)) - { + if (!empty($productid)) { $product = new Product($db); $product->fetch($productid); $type = $product->type; $price_min = $product->price_min; - if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) + if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) { $price_min = $product->multiprices_min [$object->thirdparty->price_level]; + } $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); @@ -2328,10 +2395,8 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); $error++; } - if ((empty($productid) && (($pu_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $pu_ht == '') && $pu_ht_devise == '') && $object->type != Facture::TYPE_CREDIT_NOTE) // Unit price can be 0 but not '' - { - if ($pu_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) - { + if ((empty($productid) && (($pu_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $pu_ht == '') && $pu_ht_devise == '') && $object->type != Facture::TYPE_CREDIT_NOTE) { // Unit price can be 0 but not '' + if ($pu_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) { $langs->load("errors"); if ($object->type == $object::TYPE_DEPOSIT) { // Using negative lines on deposit lead to headach and blocking problems when you want to consume them. @@ -2349,12 +2414,9 @@ if (empty($reshook)) // Update line if (!$error) { - if (empty($usercancreatemargin)) - { - foreach ($object->lines as &$line) - { - if ($line->id == GETPOST('lineid')) - { + if (empty($usercancreatemargin)) { + foreach ($object->lines as &$line) { + if ($line->id == GETPOST('lineid')) { $fournprice = $line->fk_fournprice; $buyingprice = $line->pa_ht; break; @@ -2362,20 +2424,43 @@ if (empty($reshook)) } } - $result = $object->updateline(GETPOST('lineid', 'int'), $description, $pu_ht, $qty, price2num(GETPOST('remise_percent'), 2), - $date_start, $date_end, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $info_bits, $type, - GETPOST('fk_parent_line', 'int'), 0, $fournprice, $buyingprice, $label, $special_code, $array_options, price2num(GETPOST('progress', 'alpha')), - GETPOST('units', 'alpha'), $pu_ht_devise); + $result = $object->updateline( + GETPOST('lineid', 'int'), + $description, + $pu_ht, + $qty, + price2num(GETPOST('remise_percent'), 2), + $date_start, + $date_end, + $vat_rate, + $localtax1_rate, + $localtax2_rate, + 'HT', + $info_bits, + $type, + GETPOST('fk_parent_line', 'int'), + 0, + $fournprice, + $buyingprice, + $label, + $special_code, + $array_options, + price2num(GETPOST('progress', 'alpha')), + GETPOST('units', 'alpha'), + $pu_ht_devise + ); if ($result >= 0) { if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -2425,54 +2510,51 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } } - } elseif ($action == 'updatealllines' && $usercancreate && $_POST['all_percent'] == $langs->trans('Modifier')) // Update all lines of situation invoice - { - if (!$object->fetch($id) > 0) dol_print_error($db); - if (GETPOST('all_progress') != "") - { + } elseif ($action == 'updatealllines' && $usercancreate && $_POST['all_percent'] == $langs->trans('Modifier')) { // Update all lines of situation invoice + if (!$object->fetch($id) > 0) { + dol_print_error($db); + } + if (GETPOST('all_progress') != "") { $all_progress = GETPOST('all_progress', 'int'); - foreach ($object->lines as $line) - { + foreach ($object->lines as $line) { $percent = $line->get_prev_progress($object->id); if (floatval($all_progress) < floatval($percent)) { $mesg = $langs->trans("Line").' '.$i.' : '.$langs->trans("CantBeLessThanMinPercent"); setEventMessages($mesg, null, 'warnings'); $result = -1; - } else $object->update_percent($line, $_POST['all_progress']); + } else { + $object->update_percent($line, $_POST['all_progress']); + } } } } elseif ($action == 'updateline' && $usercancreate && $_POST['cancel'] == $langs->trans("Cancel")) { header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id); // To show again edited page exit(); - } // Outing situation invoice from cycle - elseif ($action == 'confirm_situationout' && $confirm == 'yes' && $usercancreate) - { + } elseif ($action == 'confirm_situationout' && $confirm == 'yes' && $usercancreate) { + // Outing situation invoice from cycle $object->fetch($id, '', '', '', true); - if (in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED)) - && $object->type == Facture::TYPE_SITUATION - && $usercancreate - && !$objectidnext - && $object->is_last_in_cycle() - && $usercanunvalidate - ) - { - $outingError = 0; - $newCycle = $object->newCycle(); // we need to keep the "situation behavior" so we place it on a new situation cycle - if ($newCycle > 1) - { - // Search credit notes - $lastCycle = $object->situation_cycle_ref; - $lastSituationCounter = $object->situation_counter; - $linkedCreditNotesList = array(); + if (in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED)) + && $object->type == Facture::TYPE_SITUATION + && $usercancreate + && !$objectidnext + && $object->is_last_in_cycle() + && $usercanunvalidate + ) { + $outingError = 0; + $newCycle = $object->newCycle(); // we need to keep the "situation behavior" so we place it on a new situation cycle + if ($newCycle > 1) { + // Search credit notes + $lastCycle = $object->situation_cycle_ref; + $lastSituationCounter = $object->situation_counter; + $linkedCreditNotesList = array(); if (count($object->tab_next_situation_invoice) > 0) { foreach ($object->tab_next_situation_invoice as $next_invoice) { if ($next_invoice->type == Facture::TYPE_CREDIT_NOTE && $next_invoice->situation_counter == $object->situation_counter && $next_invoice->fk_facture_source == $object->id - ) - { + ) { $linkedCreditNotesList[] = $next_invoice->id; } } @@ -2481,11 +2563,9 @@ if (empty($reshook)) $object->situation_cycle_ref = $newCycle; $object->situation_counter = 1; $object->situation_final = 0; - if ($object->update($user) > 0) - { + if ($object->update($user) > 0) { $errors = 0; - if (count($linkedCreditNotesList) > 0) - { + if (count($linkedCreditNotesList) > 0) { // now, credit note must follow $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture '; $sql .= ' SET situation_cycle_ref='.$newCycle; @@ -2494,24 +2574,24 @@ if (empty($reshook)) $sql .= ' WHERE rowid IN ('.implode(',', $linkedCreditNotesList).')'; $resql = $db->query($sql); - if (!$resql) $errors++; + if (!$resql) { + $errors++; + } // Change each progression persent on each lines - foreach ($object->lines as $line) - { + foreach ($object->lines as $line) { // no traitement for special product - if ($line->product_type == 9) continue; + if ($line->product_type == 9) { + continue; + } - if (!empty($object->tab_previous_situation_invoice)) - { + if (!empty($object->tab_previous_situation_invoice)) { // search the last invoice in cycle $lineIndex = count($object->tab_previous_situation_invoice) - 1; $searchPreviousInvoice = true; - while ($searchPreviousInvoice) - { - if ($object->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) - { + while ($searchPreviousInvoice) { + if ($object->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) { $searchPreviousInvoice = false; // find, exit; break; } else { @@ -2521,10 +2601,8 @@ if (empty($reshook)) $maxPrevSituationPercent = 0; - foreach ($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) - { - if ($prevLine->id == $line->fk_prev_id) - { + foreach ($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) { + if ($prevLine->id == $line->fk_prev_id) { $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent); } } @@ -2532,13 +2610,14 @@ if (empty($reshook)) $line->situation_percent = $line->situation_percent - $maxPrevSituationPercent; - if ($line->update() < 0) $errors++; + if ($line->update() < 0) { + $errors++; + } } } } - if (!$errors) - { + if (!$errors) { setEventMessages($langs->trans('Updated'), '', 'mesgs'); header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); } else { @@ -2551,36 +2630,30 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorFindNextSituationInvoice'), array(), 'errors'); } } - } // add lines from objectlinked - elseif ($action == 'import_lines_from_object' + } elseif ($action == 'import_lines_from_object' && $usercancreate && $object->statut == Facture::STATUS_DRAFT - && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION)) - { + && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION)) { + // add lines from objectlinked $fromElement = GETPOST('fromelement'); $fromElementid = GETPOST('fromelementid'); $importLines = GETPOST('line_checkbox'); - if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) - { - if ($fromElement == 'commande') - { + if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) { + if ($fromElement == 'commande') { dol_include_once('/'.$fromElement.'/class/'.$fromElement.'.class.php'); $lineClassName = 'OrderLine'; - } elseif ($fromElement == 'propal') - { + } elseif ($fromElement == 'propal') { dol_include_once('/comm/'.$fromElement.'/class/'.$fromElement.'.class.php'); $lineClassName = 'PropaleLigne'; } $nextRang = count($object->lines) + 1; $importCount = 0; $error = 0; - foreach ($importLines as $lineId) - { + foreach ($importLines as $lineId) { $lineId = intval($lineId); $originLine = new $lineClassName($db); - if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) - { + if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) { $originLine->fetch_optionals(); $desc = $originLine->desc; $pu_ht = $originLine->subprice; @@ -2628,8 +2701,7 @@ if (empty($reshook)) } } - if ($error) - { + if ($error) { setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors'); } } @@ -2639,7 +2711,9 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - if (empty($id)) $id = $facid; + if (empty($id)) { + $id = $facid; + } $triggersendname = 'BILL_SENTBYMAIL'; $paramname = 'id'; $autocopy = 'MAIN_MAIL_AUTOCOPY_INVOICE_TO'; @@ -2657,21 +2731,22 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('BILL_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) { @@ -2695,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); @@ -2715,8 +2790,9 @@ if (empty($reshook)) } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } } @@ -2732,32 +2808,34 @@ $formmargin = new FormMargin($db); $soc = new Societe($db); $paymentstatic = new Paiement($db); $bankaccountstatic = new Account($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $now = dol_now(); $title = $langs->trans('InvoiceCustomer')." - ".$langs->trans('Card'); $helpurl = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes"; + llxHeader('', $title, $helpurl); // Mode creation -if ($action == 'create') -{ +if ($action == 'create') { $facturestatic = new Facture($db); $extrafields->fetch_name_optionals_label($facturestatic->table_element); print load_fiche_titre($langs->trans('NewBill'), '', 'bill'); - if ($socid > 0) + if ($socid > 0) { $res = $soc->fetch($socid); + } $currency_code = $conf->currency; // Load objectsrc $remise_absolue = 0; - if (!empty($origin) && !empty($originid)) - { + if (!empty($origin) && !empty($originid)) { // Parse element/subelement (ex: project_task) $element = $subelement = $origin; $regs = array(); @@ -2803,17 +2881,18 @@ if ($action == 'create') $classname = ucfirst($subelement); $objectsrc = new $classname($db); $objectsrc->fetch($originid); - if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) + if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) { $objectsrc->fetch_lines(); + } $objectsrc->fetch_thirdparty(); $projectid = (!empty($projectid) ? $projectid : $objectsrc->fk_project); $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer : '')); - $ref_int = (!empty($objectsrc->ref_int) ? $objectsrc->ref_int : ''); // only if socid not filled else it's allready done upper - if (empty($socid)) + if (empty($socid)) { $soc = $objectsrc->thirdparty; + } $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice); @@ -2844,10 +2923,13 @@ if ($action == 'create') $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0)); $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0)); - if (!empty($conf->multicurrency->enabled)) - { - if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code; - if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; + if (!empty($conf->multicurrency->enabled)) { + if (!empty($objectsrc->multicurrency_code)) { + $currency_code = $objectsrc->multicurrency_code; + } + if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) { + $currency_tx = $objectsrc->multicurrency_tx; + } } // Replicate extrafields @@ -2863,7 +2945,9 @@ if ($action == 'create') $remise_absolue = 0; $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice); // Do not set 0 here (0 for a date is 1970) - if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; + if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) { + $currency_code = $soc->multicurrency_code; + } } // when payment condition is empty (means not override by payment condition form a other object, like third-party), try to use default value @@ -2876,7 +2960,9 @@ if ($action == 'create') $mode_reglement_id = GETPOST("mode_reglement_id"); } - if (!empty($soc->id)) $absolute_discount = $soc->getAvailableDiscounts(); + if (!empty($soc->id)) { + $absolute_discount = $soc->getAvailableDiscounts(); + } $note_public = $object->getDefaultCreateValueFor('note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_public : null)); $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_private : null)); @@ -2887,13 +2973,11 @@ if ($action == 'create') print ajax_combobox('situations'); } - if ($origin == 'contrat') - { + if ($origin == 'contrat') { $langs->load("admin"); $text = $langs->trans("ToCreateARecurringInvoice"); $text .= ' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates")); - if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) - { + if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) { $text .= ' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name')); } print info_admin($text, 0, 0, 0).'
    '; @@ -2902,7 +2986,9 @@ if ($action == 'create') print '
    '; print ''; print ''; - if ($soc->id > 0) print ''."\n"; + if ($soc->id > 0) { + print ''."\n"; + } print ''; print ''; print ''; @@ -2911,25 +2997,25 @@ if ($action == 'create') print ''; print ''; print ''; - if (!empty($currency_tx)) print ''; + if (!empty($currency_tx)) { + print ''; + } print dol_get_fiche_head(''); print '
    '; // Ref - print ''; + //print ''; $exampletemplateinvoice = new FactureRec($db); $invoice_predefined = new FactureRec($db); - if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) - { + if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) { $invoice_predefined->fetch(GETPOST('fac_rec', 'int')); } // Thirdparty - if ($soc->id > 0 && (!GETPOST('fac_rec', 'int') || !empty($invoice_predefined->frequency))) - { + if ($soc->id > 0 && (!GETPOST('fac_rec', 'int') || !empty($invoice_predefined->frequency))) { // If thirdparty known and not a predefined invoiced without a recurring rule print ''; print ''; print ''."\n"; } else { @@ -2953,8 +3039,7 @@ if ($action == 'create') print ''; print ''."\n"; } // Overwrite some values if creation of invoice is from a predefined invoice - if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) - { + if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) { $invoice_predefined->fetch(GETPOST('fac_rec', 'int')); $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later - if (empty($projectid)) $projectid = $invoice_predefined->fk_project; + if (empty($projectid)) { + $projectid = $invoice_predefined->fk_project; + } $cond_reglement_id = $invoice_predefined->cond_reglement_id; $mode_reglement_id = $invoice_predefined->mode_reglement_id; $fk_account = $invoice_predefined->fk_account; $note_public = $invoice_predefined->note_public; $note_private = $invoice_predefined->note_private; - if (!empty($invoice_predefined->multicurrency_code)) $currency_code = $invoice_predefined->multicurrency_code; - if (!empty($invoice_predefined->multicurrency_tx)) $currency_tx = $invoice_predefined->multicurrency_tx; + if (!empty($invoice_predefined->multicurrency_code)) { + $currency_code = $invoice_predefined->multicurrency_code; + } + if (!empty($invoice_predefined->multicurrency_tx)) { + $currency_tx = $invoice_predefined->multicurrency_tx; + } $sql = 'SELECT r.rowid, r.titre as title, r.total_ttc'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as r'; $sql .= ' WHERE r.fk_soc = '.$invoice_predefined->socid; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num > 0) - { + if ($num > 0) { print '
    '.$langs->trans('Ref').''.$langs->trans('Draft').'
    '.$langs->trans('Ref').''.$langs->trans('Draft').'
    '.$langs->trans('Customer').''; @@ -2938,14 +3024,14 @@ if ($action == 'create') // Outstanding Bill $arrayoutstandingbills = $soc->getOutstandingBills(); $outstandingBills = $arrayoutstandingbills['opened']; - print ' ('.$langs->trans('CurrentOutstandingBill').': '; + print ' - '.$langs->trans('CurrentOutstandingBill').': '; print price($outstandingBills, '', $langs, 0, 0, -1, $conf->currency); - if ($soc->outstanding_limit != '') - { - if ($outstandingBills > $soc->outstanding_limit) print img_warning($langs->trans("OutstandingBillReached")); + if ($soc->outstanding_limit != '') { + if ($outstandingBills > $soc->outstanding_limit) { + print img_warning($langs->trans("OutstandingBillReached")); + } print ' / '.price($soc->outstanding_limit, '', $langs, 0, 0, -1, $conf->currency); } - print ')'; print '
    '; print img_picto('', 'company').$form->select_company($soc->id, 'socid', '((s.client = 1 OR s.client = 3) AND s.status=1)', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); // Option to reload page to retrieve customer informations. - if (empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED)) - { + if (empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED)) { print ''; } - if (!GETPOST('fac_rec', 'int')) print ' '; + if (!GETPOST('fac_rec', 'int')) { + print ' '; + } print '
    '.$langs->trans('CreateFromRepeatableInvoice').''; //print ''; print ''; // Option to reload page to retrieve customer informations. Note, this clear other input - if (empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE_DISABLED)) - { + if (empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE_DISABLED)) { print ''; $tmp = $tmp.''; $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3); - print '
    '; + print ''; + print ''; - if (($origin == 'propal') || ($origin == 'commande')) - { - print ''; - print ''; } - print '
    '; print $desc; print ''; + if (($origin == 'propal') || ($origin == 'commande')) { + print ''; $arraylist = array( 'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')), 'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')), @@ -3090,18 +3212,18 @@ if ($action == 'create') ); print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit', 'aZ09'), 0, 0, 0, '', 1); print ''.$langs->trans('Value').':'; + print ''; + print ''.$langs->trans("AmountOrPercent").''; + print '
    '; + print '
    '; print ''; - } + } } - if ($socid > 0) - { - if (!empty($conf->global->INVOICE_USE_SITUATION)) - { + if ($socid > 0) { + if (!empty($conf->global->INVOICE_USE_SITUATION)) { // First situation invoice print '
    '; $tmp = ' '; @@ -3115,13 +3237,15 @@ if ($action == 'create') print '
    '; $tmp = ''.$langs->trans('NoSituations').'') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) + if ($opt == ('') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) { $tmp .= ' disabled'; + } $tmp .= '> '; $text = ' '; $text .= ''; @@ -3131,8 +3255,7 @@ if ($action == 'create') } // Replacement - if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT)) - { + if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT)) { // Type de facture $facids = $facturestatic->list_replacable_invoices($soc->id); if ($facids < 0) { @@ -3141,11 +3264,11 @@ if ($action == 'create') } $options = ""; if (is_array($facids)) { - foreach ($facids as $facparam) - { + foreach ($facids as $facparam) { $options .= ''; @@ -3155,7 +3278,9 @@ if ($action == 'create') print ''; print '
    '; $tmp = 'id > 0) $tmp .= ' disabled'; + if (!$options || $invoice_predefined->id > 0) { + $tmp .= ' disabled'; + } $tmp .= '> '; print ''; $text = ''; $text .= ' '; $text = ' '; @@ -3210,24 +3335,19 @@ if ($action == 'create') } - if (empty($origin)) - { - if ($socid > 0) - { + if (empty($origin)) { + if ($socid > 0) { // Credit note - if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) - { + if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) { // Show link for credit note $facids = $facturestatic->list_qualified_avoir_invoices($soc->id); - if ($facids < 0) - { + if ($facids < 0) { dol_print_error($db, $facturestatic); exit; } $optionsav = ""; $newinvoice_static = new Facture($db); - foreach ($facids as $key => $valarray) - { + foreach ($facids as $key => $valarray) { $newinvoice_static->id = $key; $newinvoice_static->ref = $valarray ['ref']; $newinvoice_static->statut = $valarray ['status']; @@ -3235,8 +3355,9 @@ if ($action == 'create') $newinvoice_static->paye = $valarray ['paye']; $optionsav .= '
    '; - dol_fiche_end(); + dol_fiche_end(); print '
    '; print ''; @@ -508,19 +476,17 @@ if ($action == 'create') print ''; print '
    '; - print ''; + print ''; } // View mode -if ($id) -{ +if ($id) { $head = vat_prepare_head($object); $totalpaye = $object->getSommePaiement(); // Clone confirmation - if ($action === 'clone') - { + if ($action === 'clone') { $formquestion = array( array('type' => 'text', 'name' => 'clone_label', 'label' => $langs->trans("Label"), 'value' => $langs->trans("CopyOf").' '.$object->label), ); @@ -531,20 +497,17 @@ if ($id) print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneVAT', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 240); } - if ($action == 'paid') - { + if ($action == 'paid') { $text = $langs->trans('ConfirmPayVAT'); print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans('PayVAT'), $text, "confirm_paid", '', '', 2); } - if ($action == 'delete') - { + if ($action == 'delete') { $text = $langs->trans('ConfirmDeleteVAT'); print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('DeleteVAT'), $text, 'confirm_delete', '', '', 2); } - if ($action == 'edit') - { + if ($action == 'edit') { print "
    id&action=update\" method=\"post\">"; print ''; } @@ -586,7 +549,7 @@ if ($id) print '
    ' . $langs->trans("Amount") . '
    ' . $langs->trans("Amount") . '
    ' . $langs->trans("Amount") . '' . price($object->amount) . '
    '; - if ($action != 'editmode') + if ($action != 'editmode') { print ''; + } print '
    '; print $langs->trans('PaymentMode'); print 'id.'">'.img_edit($langs->trans('SetMode'), 1).'
    '; print '
    '; if ($action == 'editmode') { @@ -608,14 +572,14 @@ if ($id) print '
    '; print ''; + } print '
    '; print $langs->trans('BankAccount'); print ''; - if ($action != 'editbankaccount' && $user->rights->tax->charges->creer) + if ($action != 'editbankaccount' && $user->rights->tax->charges->creer) { print 'id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'
    '; print '
    '; if ($action == 'editbankaccount') { @@ -662,12 +626,12 @@ if ($id) //print $sql; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $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 ''; @@ -681,11 +645,9 @@ if ($id) print ''; print ''; - if ($num > 0) - { + if ($num > 0) { $bankaccountstatic = new Account($db); - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); print '\n"; $labeltype = $langs->trans("PaymentType".$objp->type_code) != ("PaymentType".$objp->type_code) ? $langs->trans("PaymentType".$objp->type_code) : $objp->paiement_type; print "\n"; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { $bankaccountstatic->id = $objp->baid; $bankaccountstatic->ref = $objp->baref; $bankaccountstatic->label = $objp->baref; @@ -710,8 +671,9 @@ if ($id) } print ''; } print '\n"; @@ -719,8 +681,7 @@ if ($id) $totalpaye += $objp->amount; $i++; } - } - else { + } else { print ''; print ''; print ''; @@ -739,8 +700,7 @@ if ($id) print ''; $db->free($resql); - } - else { + } else { dol_print_error($db); } @@ -752,8 +712,7 @@ if ($id) dol_fiche_end(); - if ($action == 'edit') - { + if ($action == 'edit') { print '
    '; print ''; print '   '; @@ -763,26 +722,22 @@ if ($id) } /* - * Action buttons + * Action bar */ print "
    \n"; - if ($action != 'edit') - { + if ($action != 'edit') { // Reopen - if ($object->paye && $user->rights->tax->charges->creer) - { + if ($object->paye && $user->rights->tax->charges->creer) { print ""; } // Edit - if ($object->paye == 0 && $user->rights->tax->charges->creer) - { + if ($object->paye == 0 && $user->rights->tax->charges->creer) { print ""; } // Emit payment - if ($object->paye == 0 && ((price2num($object->amount) < 0 && price2num($resteapayer, 'MT') < 0) || (price2num($object->amount) > 0 && price2num($resteapayer, 'MT') > 0)) && $user->rights->tax->charges->creer) - { + if ($object->paye == 0 && ((price2num($object->amount) < 0 && price2num($resteapayer, 'MT') < 0) || (price2num($object->amount) > 0 && price2num($resteapayer, 'MT') > 0)) && $user->rights->tax->charges->creer) { print ""; } @@ -792,22 +747,18 @@ if ($id) (round($resteapayer) <= 0 && $object->amount > 0) || (round($resteapayer) >= 0 && $object->amount < 0) ) - && $user->rights->tax->charges->creer) - { + && $user->rights->tax->charges->creer) { print ""; } // Clone - if ($user->rights->tax->charges->creer) - { + if ($user->rights->tax->charges->creer) { print ""; } - if (!empty($user->rights->tax->charges->supprimer) && empty($totalpaye)) - { + if (!empty($user->rights->tax->charges->supprimer) && empty($totalpaye)) { print ''; - } - else { + } else { print ''; } } diff --git a/htdocs/compta/tva/class/paymentvat.class.php b/htdocs/compta/tva/class/paymentvat.class.php index 13369e596bc..9ba1bd2ed1d 100644 --- a/htdocs/compta/tva/class/paymentvat.class.php +++ b/htdocs/compta/tva/class/paymentvat.class.php @@ -48,8 +48,8 @@ class PaymentVAT extends CommonObject public $picto = 'payment'; /** - * @var int ID - */ + * @var int ID + */ public $fk_tva; public $datec = ''; @@ -62,12 +62,12 @@ class PaymentVAT extends CommonObject */ public $total; - public $amount; // Total amount of payment - public $amounts = array(); // Array of amounts + public $amount; // Total amount of payment + public $amounts = array(); // Array of amounts - /** - * @var int ID - */ + /** + * @var int ID + */ public $fk_typepaiement; /** @@ -82,18 +82,18 @@ class PaymentVAT extends CommonObject public $num_payment; /** - * @var int ID - */ + * @var int ID + */ public $fk_bank; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_creat; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_modif; /** @@ -108,8 +108,8 @@ class PaymentVAT extends CommonObject /** * Create payment of social contribution into database. - * Use this->amounts to have list of lines for the payment - * + * Use this->amounts to have list of lines for the payment + * * @param User $user User making payment * @param int $closepaidcontrib 1=Also close payed contributions to paid, 0=Do nothing more * @return int <0 if KO, id of payment if OK @@ -120,45 +120,62 @@ class PaymentVAT extends CommonObject $error = 0; - $now = dol_now(); + $now = dol_now(); dol_syslog(get_class($this)."::create", LOG_DEBUG); // Validate parametres - if (!$this->datepaye) - { + if (!$this->datepaye) { $this->error = 'ErrorBadValueForParameterCreatePaymentVAT'; return -1; } // Clean parameters - if (isset($this->fk_tva)) $this->fk_tva = (int) $this->fk_tva; - if (isset($this->amount)) $this->amount = trim($this->amount); - if (isset($this->fk_typepaiement)) $this->fk_typepaiement = (int) $this->fk_typepaiement; - if (isset($this->num_paiement)) $this->num_paiement = trim($this->num_paiement); // deprecated - if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); - if (isset($this->note)) $this->note = trim($this->note); - if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; - if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; - if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + if (isset($this->fk_tva)) { + $this->fk_tva = (int) $this->fk_tva; + } + if (isset($this->amount)) { + $this->amount = trim($this->amount); + } + if (isset($this->fk_typepaiement)) { + $this->fk_typepaiement = (int) $this->fk_typepaiement; + } + if (isset($this->num_paiement)) { + $this->num_paiement = trim($this->num_paiement); // deprecated + } + if (isset($this->num_payment)) { + $this->num_payment = trim($this->num_payment); + } + if (isset($this->note)) { + $this->note = trim($this->note); + } + if (isset($this->fk_bank)) { + $this->fk_bank = (int) $this->fk_bank; + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = (int) $this->fk_user_creat; + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = (int) $this->fk_user_modif; + } - $totalamount = 0; - foreach ($this->amounts as $key => $value) // How payment is dispatch - { - $newvalue = price2num($value, 'MT'); - $this->amounts[$key] = $newvalue; - $totalamount += $newvalue; - } - $totalamount = price2num($totalamount); + $totalamount = 0; + foreach ($this->amounts as $key => $value) { // How payment is dispatch + $newvalue = price2num($value, 'MT'); + $this->amounts[$key] = $newvalue; + $totalamount += $newvalue; + } + $totalamount = price2num($totalamount); - // Check parameters - if ($totalamount == 0) return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null + // Check parameters + if ($totalamount == 0) { + return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null + } $this->db->begin(); - if ($totalamount != 0) - { + if ($totalamount != 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_vat (fk_tva, datec, datep, amount,"; $sql .= " fk_typepaiement, num_paiement, note, fk_user_creat, fk_bank)"; $sql .= " VALUES ($this->chid, '".$this->db->idate($now)."',"; @@ -168,21 +185,17 @@ class PaymentVAT extends CommonObject $sql .= " 0)"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_vat"); // Insere tableau des montants / factures - foreach ($this->amounts as $key => $amount) - { + foreach ($this->amounts as $key => $amount) { $contribid = $key; - if (is_numeric($amount) && $amount <> 0) - { + if (is_numeric($amount) && $amount <> 0) { $amount = price2num($amount); // If we want to closed payed invoices - if ($closepaidcontrib) - { + if ($closepaidcontrib) { $contrib = new Tva($this->db); $contrib->fetch($contribid); $paiement = $contrib->getSommePaiement(); @@ -192,31 +205,30 @@ class PaymentVAT extends CommonObject $deposits = 0; $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT'); $remaintopay = price2num($contrib->amount - $paiement - $creditnotes - $deposits, 'MT'); - if ($remaintopay == 0) - { + if ($remaintopay == 0) { $result = $contrib->setPaid($user); + } else { + dol_syslog("Remain to pay for conrib ".$contribid." not null. We do nothing."); } - else dol_syslog("Remain to pay for conrib ".$contribid." not null. We do nothing."); } } } - } - else { + } else { $error++; } } $result = $this->call_trigger('PAYMENTVAT_CREATE', $user); - if ($result < 0) $error++; - - if ($totalamount != 0 && !$error) - { - $this->amount = $totalamount; - $this->total = $totalamount; // deprecated - $this->db->commit(); - return $this->id; + if ($result < 0) { + $error++; } - else { + + if ($totalamount != 0 && !$error) { + $this->amount = $totalamount; + $this->total = $totalamount; // deprecated + $this->db->commit(); + return $this->id; + } else { $this->error = $this->db->error(); $this->db->rollback(); return -1; @@ -249,15 +261,13 @@ 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); $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; @@ -285,8 +295,7 @@ class PaymentVAT extends CommonObject $this->db->free($resql); return 1; - } - else { + } else { $this->error = "Error ".$this->db->lasterror(); return -1; } @@ -307,15 +316,33 @@ class PaymentVAT extends CommonObject // Clean parameters - if (isset($this->fk_tva)) $this->fk_tva = (int) $this->fk_tva; - if (isset($this->amount)) $this->amount = trim($this->amount); - if (isset($this->fk_typepaiement)) $this->fk_typepaiement = (int) $this->fk_typepaiement; - if (isset($this->num_paiement)) $this->num_paiement = trim($this->num_paiement); // deprecated - if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); - if (isset($this->note)) $this->note = trim($this->note); - if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; - if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; - if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + if (isset($this->fk_tva)) { + $this->fk_tva = (int) $this->fk_tva; + } + if (isset($this->amount)) { + $this->amount = trim($this->amount); + } + if (isset($this->fk_typepaiement)) { + $this->fk_typepaiement = (int) $this->fk_typepaiement; + } + if (isset($this->num_paiement)) { + $this->num_paiement = trim($this->num_paiement); // deprecated + } + if (isset($this->num_payment)) { + $this->num_payment = trim($this->num_payment); + } + if (isset($this->note)) { + $this->note = trim($this->note); + } + if (isset($this->fk_bank)) { + $this->fk_bank = (int) $this->fk_bank; + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = (int) $this->fk_user_creat; + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = (int) $this->fk_user_modif; + } @@ -338,26 +365,26 @@ 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(); } + if (!$resql) { + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } - else { + } else { $this->db->commit(); return 1; } @@ -380,39 +407,37 @@ class PaymentVAT extends CommonObject $this->db->begin(); - if ($this->bank_line > 0) - { - $accline = new AccountLine($this->db); + if ($this->bank_line > 0) { + $accline = new AccountLine($this->db); $accline->fetch($this->bank_line); $result = $accline->delete(); if ($result < 0) { $this->errors[] = $accline->error; $error++; } - } + } - if (!$error) - { + 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(); } + if (!$resql) { + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } - else { + } else { $this->db->commit(); return 1; } @@ -448,8 +473,7 @@ class PaymentVAT extends CommonObject $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $error++; } @@ -457,12 +481,10 @@ class PaymentVAT extends CommonObject unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; - } - else { + } else { $this->db->rollback(); return -1; } @@ -470,11 +492,11 @@ class PaymentVAT extends CommonObject /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void */ public function initAsSpecimen() { @@ -495,101 +517,97 @@ class PaymentVAT extends CommonObject } - /** - * Add record into bank for payment with links between this bank record and invoices of payment. - * All payment properties must have been set first like after a call to create(). - * - * @param User $user Object of user making payment - * @param string $mode 'payment_sc' - * @param string $label Label to use in bank record - * @param int $accountid Id of bank account to do link with - * @param string $emetteur_nom Name of transmitter - * @param string $emetteur_banque Name of bank - * @return int <0 if KO, >0 if OK - */ - public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque) - { - global $conf; + /** + * Add record into bank for payment with links between this bank record and invoices of payment. + * All payment properties must have been set first like after a call to create(). + * + * @param User $user Object of user making payment + * @param string $mode 'payment_sc' + * @param string $label Label to use in bank record + * @param int $accountid Id of bank account to do link with + * @param string $emetteur_nom Name of transmitter + * @param string $emetteur_banque Name of bank + * @return int <0 if KO, >0 if OK + */ + public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque) + { + global $conf; // Clean data - $this->num_payment = trim($this->num_payment ? $this->num_payment : $this->num_paiement); + $this->num_payment = trim($this->num_payment ? $this->num_payment : $this->num_paiement); - $error = 0; + $error = 0; - if (!empty($conf->banque->enabled)) - { - include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + if (!empty($conf->banque->enabled)) { + include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - $acc = new Account($this->db); - $acc->fetch($accountid); + $acc = new Account($this->db); + $acc->fetch($accountid); - $total = $this->total; - if ($mode == 'payment_vat') $total = -$total; + $total = $this->total; + if ($mode == 'payment_vat') { + $total = -$total; + } - // Insert payment into llx_bank - $bank_line_id = $acc->addline( - $this->datepaye, - $this->paiementtype, // Payment mode id or code ("CHQ or VIR for example") - $label, - $total, - $this->num_payment, - '', - $user, - $emetteur_nom, - $emetteur_banque - ); + // Insert payment into llx_bank + $bank_line_id = $acc->addline( + $this->datepaye, + $this->paiementtype, // Payment mode id or code ("CHQ or VIR for example") + $label, + $total, + $this->num_payment, + '', + $user, + $emetteur_nom, + $emetteur_banque + ); - // Mise a jour fk_bank dans llx_paiement. - // On connait ainsi le paiement qui a genere l'ecriture bancaire - if ($bank_line_id > 0) - { - $result = $this->update_fk_bank($bank_line_id); - if ($result <= 0) - { - $error++; - dol_print_error($this->db); - } + // Mise a jour fk_bank dans llx_paiement. + // On connait ainsi le paiement qui a genere l'ecriture bancaire + if ($bank_line_id > 0) { + $result = $this->update_fk_bank($bank_line_id); + if ($result <= 0) { + $error++; + dol_print_error($this->db); + } - // Add link 'payment', 'payment_supplier', 'payment_sc' in bank_url between payment and bank transaction - $url = ''; - if ($mode == 'payment_vat') $url = DOL_URL_ROOT.'/compta/payment_vat/card.php?id='; - if ($url) - { - $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); - if ($result <= 0) - { - $error++; - dol_print_error($this->db); - } - } + // Add link 'payment', 'payment_supplier', 'payment_sc' in bank_url between payment and bank transaction + $url = ''; + if ($mode == 'payment_vat') { + $url = DOL_URL_ROOT.'/compta/payment_vat/card.php?id='; + } + if ($url) { + $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); + if ($result <= 0) { + $error++; + dol_print_error($this->db); + } + } - // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment) - $linkaddedforthirdparty = array(); - foreach ($this->amounts as $key => $value) - { - if ($mode == 'payment_vat') - { - $tva = new Tva($this->db); - $tva->fetch($key); - $result = $acc->add_url_line($bank_line_id, $tva->id, DOL_URL_ROOT.'/compta/tva/card.php?id=', '('.$tva->label.')', 'vat'); - if ($result <= 0) dol_print_error($this->db); - } - } - } - else { - $this->error = $acc->error; - $error++; - } - } + // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment) + $linkaddedforthirdparty = array(); + foreach ($this->amounts as $key => $value) { + if ($mode == 'payment_vat') { + $tva = new Tva($this->db); + $tva->fetch($key); + $result = $acc->add_url_line($bank_line_id, $tva->id, DOL_URL_ROOT.'/compta/tva/card.php?id=', '('.$tva->label.')', 'vat'); + if ($result <= 0) { + dol_print_error($this->db); + } + } + } + } else { + $this->error = $acc->error; + $error++; + } + } - if (!$error) - { - return 1; - } - else { - return -1; - } - } + if (!$error) { + return 1; + } else { + return -1; + } + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -606,11 +624,9 @@ class PaymentVAT extends CommonObject dol_syslog(get_class($this)."::update_fk_bank", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { return 1; - } - else { + } else { $this->error = $this->db->error(); return 0; } @@ -693,30 +709,41 @@ class PaymentVAT extends CommonObject $result = ''; - if (empty($this->ref)) $this->ref = $this->lib; + if (empty($this->ref)) { + $this->ref = $this->lib; + } $label = img_picto('', $this->picto).' '.$langs->trans("VATPayment").''; $label .= '
    '.$langs->trans('Ref').': '.$this->ref; if (!empty($this->label)) { $labeltoshow = $this->label; $reg = array(); - if (preg_match('/^\((.*)\)$/i', $this->label, $reg)) - { + if (preg_match('/^\((.*)\)$/i', $this->label, $reg)) { // Label generique car entre parentheses. On l'affiche en le traduisant - if ($reg[1] == 'paiement') $reg[1] = 'Payment'; + if ($reg[1] == 'paiement') { + $reg[1] = 'Payment'; + } $labeltoshow = $langs->trans($reg[1]); } $label .= '
    '.$langs->trans('Label').': '.$labeltoshow; } - if ($this->datep) $label .= '
    '.$langs->trans('Date').': '.dol_print_date($this->datep, 'day'); + if ($this->datep) { + $label .= '
    '.$langs->trans('Date').': '.dol_print_date($this->datep, 'day'); + } if (!empty($this->id)) { $link = ''; $linkend = ''; - if ($withpicto) $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); - if ($withpicto && $withpicto != 2) $result .= ' '; - if ($withpicto != 2) $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + if ($withpicto) { + $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + if ($withpicto != 2) { + $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + } } return $result; diff --git a/htdocs/compta/tva/class/tva.class.php b/htdocs/compta/tva/class/tva.class.php index a39a00d8b01..552195cf2d2 100644 --- a/htdocs/compta/tva/class/tva.class.php +++ b/htdocs/compta/tva/class/tva.class.php @@ -57,13 +57,13 @@ class Tva extends CommonObject public $num_payment; /** - * @var string label - */ - public $label; + * @var string label + */ + public $label; - /** - * @var int ID - */ + /** + * @var int ID + */ public $fk_bank; /** @@ -72,39 +72,39 @@ class Tva extends CommonObject public $accountid; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_creat; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_modif; const STATUS_UNPAID = 0; const STATUS_PAID = 1; - /** + /** * Constructor * * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Create in database - * - * @param User $user User that create - * @return int <0 if KO, >0 if OK - */ - public function create($user) - { - global $conf, $langs; + /** + * Create in database + * + * @param User $user User that create + * @return int <0 if KO, >0 if OK + */ + public function create($user) + { + global $conf, $langs; $error = 0; $now = dol_now(); @@ -135,7 +135,7 @@ class Tva extends CommonObject $sql .= "fk_typepayment,"; $sql .= "fk_user_creat,"; $sql .= "fk_user_modif"; - $sql .= ") VALUES ("; + $sql .= ") VALUES ("; $sql .= " '".$this->db->idate($now)."',"; $sql .= " '".$this->db->idate($this->datep)."',"; $sql .= " '".$this->db->idate($this->datev)."',"; @@ -148,44 +148,42 @@ class Tva extends CommonObject $sql .= " '".$this->db->escape($this->fk_user_modif)."'"; $sql .= ")"; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."tva"); + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."tva"); - // Call trigger - $result = $this->call_trigger('TVA_CREATE', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('TVA_CREATE', $user); + if ($result < 0) { + $error++; + } + // End call triggers - if (!$error) - { - $this->db->commit(); - return $this->id; - } - else { + if (!$error) { + $this->db->commit(); + return $this->id; + } else { $this->db->rollback(); return -1; - } - } - else { + } + } else { $this->error = "Error ".$this->db->lasterror(); $this->db->rollback(); return -1; - } - } + } + } - /** - * Update database - * - * @param User $user User that modify - * @param int $notrigger 0=no, 1=yes (no update trigger) - * @return int <0 if KO, >0 if OK - */ - public function update($user, $notrigger = 0) - { - global $conf, $langs; + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=no, 1=yes (no update trigger) + * @return int <0 if KO, >0 if OK + */ + public function update($user, $notrigger = 0) + { + global $conf, $langs; $error = 0; @@ -202,7 +200,7 @@ class Tva extends CommonObject $this->db->begin(); // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."tva SET"; + $sql = "UPDATE ".MAIN_DB_PREFIX."tva SET"; $sql .= " tms='".$this->db->idate($this->tms)."',"; $sql .= " datep='".$this->db->idate($this->datep)."',"; $sql .= " datev='".$this->db->idate($this->datev)."',"; @@ -211,34 +209,32 @@ 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); - if (!$resql) - { - $this->error = "Error ".$this->db->lasterror(); - $error++; - } + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->error = "Error ".$this->db->lasterror(); + $error++; + } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('TVA_MODIFY', $user); - if ($result < 0) $error++; - // End call triggers - } + if (!$error && !$notrigger) { + // Call trigger + $result = $this->call_trigger('TVA_MODIFY', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } - if (!$error) - { - $this->db->commit(); - return 1; - } - else { - $this->db->rollback(); - return -1; - } - } + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } /** * Tag TVA as payed completely @@ -253,8 +249,11 @@ class Tva extends CommonObject $sql .= " paye = 1"; $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) return 1; - else return -1; + if ($resql) { + return 1; + } else { + return -1; + } } /** @@ -270,22 +269,25 @@ class Tva extends CommonObject $sql .= " paye = 0"; $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) return 1; - else return -1; + if ($resql) { + return 1; + } else { + return -1; + } } - /** - * Load object in memory from database - * - * @param int $id id object - * @param User $user User that load - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $user = null) - { - global $langs; - $sql = "SELECT"; + /** + * Load object in memory from database + * + * @param int $id id object + * @param User $user User that load + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $user = null) + { + global $langs; + $sql = "SELECT"; $sql .= " t.rowid,"; $sql .= " t.tms,"; @@ -301,20 +303,18 @@ class Tva extends CommonObject $sql .= " t.fk_user_modif,"; $sql .= " t.fk_account"; - $sql .= " FROM ".MAIN_DB_PREFIX."tva as t"; + $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); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->ref = $obj->rowid; + $this->id = $obj->rowid; + $this->ref = $obj->rowid; $this->tms = $this->db->jdate($obj->tms); $this->datep = $this->db->jdate($obj->datep); $this->datev = $this->db->jdate($obj->datev); @@ -329,22 +329,21 @@ class Tva extends CommonObject $this->fk_account = $obj->fk_account; $this->fk_type = $obj->fk_type; $this->rappro = $obj->rappro; - } - $this->db->free($resql); + } + $this->db->free($resql); - return 1; - } - else { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - } + return 1; + } else { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } - /** + /** * Delete object in database * - * @param User $user User that delete + * @param User $user User that delete * @return int <0 if KO, >0 if OK */ public function delete($user) @@ -355,16 +354,17 @@ class Tva extends CommonObject // Call trigger $result = $this->call_trigger('TVA_DELETE', $user); - if ($result < 0) return -1; + if ($result < 0) { + return -1; + } // 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); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = "Error ".$this->db->lasterror(); return -1; } @@ -375,11 +375,11 @@ class Tva extends CommonObject /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void */ public function initAsSpecimen() { @@ -397,244 +397,233 @@ class Tva extends CommonObject } - /** - * Balance of VAT - * - * @param int $year Year - * @return double Amount - */ - public function solde($year = 0) - { + /** + * Balance of VAT + * + * @param int $year Year + * @return double Amount + */ + public function solde($year = 0) + { - $reglee = $this->tva_sum_reglee($year); + $reglee = $this->tva_sum_reglee($year); - $payee = $this->tva_sum_payee($year); - $collectee = $this->tva_sum_collectee($year); + $payee = $this->tva_sum_payee($year); + $collectee = $this->tva_sum_collectee($year); - $solde = $reglee - ($collectee - $payee); + $solde = $reglee - ($collectee - $payee); - return $solde; - } + return $solde; + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Total of the VAT from invoices emitted by the thirdparty. - * - * @param int $year Year - * @return double Amount - */ - public function tva_sum_collectee($year = 0) - { + /** + * Total of the VAT from invoices emitted by the thirdparty. + * + * @param int $year Year + * @return double Amount + */ + public function tva_sum_collectee($year = 0) + { // phpcs:enable - $sql = "SELECT sum(f.tva) as amount"; - $sql .= " FROM ".MAIN_DB_PREFIX."facture as f WHERE f.paye = 1"; - if ($year) - { + $sql = "SELECT sum(f.tva) as amount"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture as f WHERE f.paye = 1"; + if ($year) { $sql .= " AND f.datef >= '".$this->db->escape($year)."-01-01' AND f.datef <= '".$this->db->escape($year)."-12-31' "; - } + } - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); $ret = $obj->amount; - $this->db->free($result); - return $ret; - } - else { - $this->db->free($result); + $this->db->free($result); + return $ret; + } else { + $this->db->free($result); return 0; - } - } - else { - print $this->db->lasterror(); - return -1; - } - } + } + } else { + print $this->db->lasterror(); + return -1; + } + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * VAT payed - * - * @param int $year Year - * @return double Amount - */ - public function tva_sum_payee($year = 0) - { + /** + * VAT payed + * + * @param int $year Year + * @return double Amount + */ + public function tva_sum_payee($year = 0) + { // phpcs:enable - $sql = "SELECT sum(f.total_tva) as total_tva"; - $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - if ($year) - { - $sql .= " WHERE f.datef >= '".$this->db->escape($year)."-01-01' AND f.datef <= '".$this->db->escape($year)."-12-31' "; - } + $sql = "SELECT sum(f.total_tva) as total_tva"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + if ($year) { + $sql .= " WHERE f.datef >= '".$this->db->escape($year)."-01-01' AND f.datef <= '".$this->db->escape($year)."-12-31' "; + } - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - $ret = $obj->total_tva; - $this->db->free($result); - return $ret; - } - else { - $this->db->free($result); + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $ret = $obj->total_tva; + $this->db->free($result); + return $ret; + } else { + $this->db->free($result); return 0; - } - } - else { - print $this->db->lasterror(); - return -1; - } - } + } + } else { + print $this->db->lasterror(); + return -1; + } + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Total of the VAT payed - * - * @param int $year Year - * @return double Amount - */ - public function tva_sum_reglee($year = 0) - { + /** + * Total of the VAT payed + * + * @param int $year Year + * @return double Amount + */ + public function tva_sum_reglee($year = 0) + { // phpcs:enable - $sql = "SELECT sum(f.amount) as amount"; - $sql .= " FROM ".MAIN_DB_PREFIX."tva as f"; + $sql = "SELECT sum(f.amount) as amount"; + $sql .= " FROM ".MAIN_DB_PREFIX."tva as f"; - if ($year) - { + if ($year) { $sql .= " WHERE f.datev >= '".$this->db->escape($year)."-01-01' AND f.datev <= '".$this->db->escape($year)."-12-31' "; - } + } - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - $ret = $obj->amount; - $this->db->free($result); - return $ret; - } - else { - $this->db->free($result); + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $ret = $obj->amount; + $this->db->free($result); + return $ret; + } else { + $this->db->free($result); return 0; - } - } - else { - print $this->db->lasterror(); - return -1; - } - } + } + } else { + print $this->db->lasterror(); + return -1; + } + } - /** - * Create in database - * + /** + * Create in database + * * @param User $user Object user that insert * @return int <0 if KO, rowid in tva table if OK - */ - public function addPayment($user) - { - global $conf, $langs; + */ + public function addPayment($user) + { + global $conf, $langs; - $this->db->begin(); + $this->db->begin(); - // Clean parameters - $this->amount = price2num(trim($this->amount)); - $this->label = trim($this->label); + // Clean parameters + $this->amount = price2num(trim($this->amount)); + $this->label = trim($this->label); $this->note = trim($this->note); $this->num_payment = trim($this->num_payment); $this->fk_bank = (int) $this->fk_bank; $this->fk_user_creat = (int) $this->fk_user_creat; $this->fk_user_modif = (int) $this->fk_user_modif; - if (empty($this->datec)) $this->datec = dol_now(); + if (empty($this->datec)) { + $this->datec = dol_now(); + } - // Check parameters - if (!$this->label) - { + // Check parameters + if (!$this->label) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")); return -3; } - if ($this->amount == '') - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); - return -4; - } - if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Account")); - return -5; - } - if (!empty($conf->banque->enabled) && (empty($this->type_payment) || $this->type_payment <= 0)) - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); - return -5; - } + if ($this->amount == '') { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); + return -4; + } + if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Account")); + return -5; + } + if (!empty($conf->banque->enabled) && (empty($this->type_payment) || $this->type_payment <= 0)) { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); + return -5; + } - // Insert into llx_tva - $sql = "INSERT INTO ".MAIN_DB_PREFIX."tva ("; - $sql .= "datec"; - $sql .= ", datep"; - $sql .= ", datev"; + // Insert into llx_tva + $sql = "INSERT INTO ".MAIN_DB_PREFIX."tva ("; + $sql .= "datec"; + $sql .= ", datep"; + $sql .= ", datev"; $sql .= ", amount"; $sql .= ", fk_typepayment"; $sql .= ", num_payment"; - if ($this->note) $sql .= ", note"; - if ($this->label) $sql .= ", label"; - $sql .= ", fk_user_creat"; + if ($this->note) { + $sql .= ", note"; + } + if ($this->label) { + $sql .= ", label"; + } + $sql .= ", fk_user_creat"; $sql .= ", fk_bank"; $sql .= ", entity"; $sql .= ") "; - $sql .= " VALUES ("; - $sql .= " '".$this->db->idate($this->datec)."'"; - $sql .= ", '".$this->db->idate($this->datep)."'"; - $sql .= ", '".$this->db->idate($this->datev)."'"; + $sql .= " VALUES ("; + $sql .= " '".$this->db->idate($this->datec)."'"; + $sql .= ", '".$this->db->idate($this->datep)."'"; + $sql .= ", '".$this->db->idate($this->datev)."'"; $sql .= ", ".$this->amount; - $sql .= ", '".$this->db->escape($this->type_payment)."'"; + $sql .= ", '".$this->db->escape($this->type_payment)."'"; $sql .= ", '".$this->db->escape($this->num_payment)."'"; - if ($this->note) $sql .= ", '".$this->db->escape($this->note)."'"; - if ($this->label) $sql .= ", '".$this->db->escape($this->label)."'"; - $sql .= ", '".$this->db->escape($user->id)."'"; + if ($this->note) { + $sql .= ", '".$this->db->escape($this->note)."'"; + } + if ($this->label) { + $sql .= ", '".$this->db->escape($this->label)."'"; + } + $sql .= ", '".$this->db->escape($user->id)."'"; $sql .= ", NULL"; $sql .= ", ".$conf->entity; - $sql .= ")"; + $sql .= ")"; dol_syslog(get_class($this)."::addPayment", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."tva"); // TODO should be called 'payment_vat' + $result = $this->db->query($sql); + if ($result) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."tva"); // TODO should be called 'payment_vat' - // Call trigger - //XXX: Should be done just befor commit no ? - $result = $this->call_trigger('TVA_ADDPAYMENT', $user); - if ($result < 0) - { - $this->id = 0; - $ok = 0; - } - // End call triggers + // Call trigger + //XXX: Should be done just befor commit no ? + $result = $this->call_trigger('TVA_ADDPAYMENT', $user); + if ($result < 0) { + $this->id = 0; + $ok = 0; + } + // End call triggers - if ($this->id > 0) - { - $ok = 1; - if (!empty($conf->banque->enabled) && !empty($this->amount)) - { - // Insert into llx_bank - require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + if ($this->id > 0) { + $ok = 1; + if (!empty($conf->banque->enabled) && !empty($this->amount)) { + // Insert into llx_bank + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - $acc = new Account($this->db); + $acc = new Account($this->db); $result = $acc->fetch($this->accountid); - if ($result <= 0) dol_print_error($this->db); + if ($result <= 0) { + dol_print_error($this->db); + } if ($this->amount > 0) { $bank_line_id = $acc->addline($this->datep, $this->type_payment, $this->label, -abs($this->amount), $this->num_payment, '', $user); @@ -642,65 +631,56 @@ class Tva extends CommonObject $bank_line_id = $acc->addline($this->datep, $this->type_payment, $this->label, abs($this->amount), $this->num_payment, '', $user); } - // Update fk_bank into llx_tva. So we know vat line used to generate bank transaction - if ($bank_line_id > 0) - { - $this->update_fk_bank($bank_line_id); - } - else { + // Update fk_bank into llx_tva. So we know vat line used to generate bank transaction + if ($bank_line_id > 0) { + $this->update_fk_bank($bank_line_id); + } else { $this->error = $acc->error; $ok = 0; } - // Update links - $result = $acc->add_url_line($bank_line_id, $this->id, DOL_URL_ROOT.'/compta/tva/card.php?id=', "(VATPayment)", "payment_vat"); - if ($result < 0) - { - $this->error = $acc->error; - $ok = 0; - } - } + // Update links + $result = $acc->add_url_line($bank_line_id, $this->id, DOL_URL_ROOT.'/compta/tva/card.php?id=', "(VATPayment)", "payment_vat"); + if ($result < 0) { + $this->error = $acc->error; + $ok = 0; + } + } - if ($ok) - { + if ($ok) { $this->db->commit(); return $this->id; - } - else { + } else { $this->db->rollback(); return -3; } - } - else { - $this->db->rollback(); - return -2; - } - } - else { - $this->error = $this->db->error(); - $this->db->rollback(); - return -1; - } - } + } else { + $this->db->rollback(); + return -2; + } + } else { + $this->error = $this->db->error(); + $this->db->rollback(); + return -1; + } + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** + /** * Update link between payment tva and line generate into llx_bank - * - * @param int $id_bank Id bank account + * + * @param int $id_bank Id bank account * @return int <0 if KO, >0 if OK - */ + */ public function update_fk_bank($id_bank) { // phpcs:enable $sql = 'UPDATE '.MAIN_DB_PREFIX.'tva SET fk_bank = '.(int) $id_bank; $sql .= ' WHERE rowid = '.(int) $this->id; $result = $this->db->query($sql); - if ($result) - { + if ($result) { return 1; - } - else { + } else { dol_print_error($this->db); return -1; } @@ -711,8 +691,8 @@ class Tva extends CommonObject * * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto * @param string $option link option - * @param int $notooltip 1=Disable tooltip - * @param string $morecss More CSS + * @param int $notooltip 1=Disable tooltip + * @param string $morecss More CSS * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking * @return string Chaine with URL */ @@ -720,83 +700,92 @@ class Tva extends CommonObject { global $langs, $conf; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; $label = ''.$langs->trans("ShowVatPayment").''; $label .= '
    '; $label .= ''.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->label)) + if (!empty($this->label)) { $label .= '
    '.$langs->trans('Label').': '.$this->label; + } - $url = DOL_URL_ROOT.'/compta/tva/card.php?id='.$this->id; + $url = DOL_URL_ROOT.'/compta/tva/card.php?id='.$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 ($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'; + } + } - $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("ShowMyObject"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } - else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + $linkclose = ''; + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $label = $langs->trans("ShowMyObject"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } - $linkstart = ''; - $linkend = ''; + $linkstart = ''; + $linkend = ''; $picto = 'payment'; $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; return $result; } /** - * Return amount of payments already done - * - * @return int Amount of payment already done, <0 if KO - */ - public function getSommePaiement() - { - $table = 'payment_vat'; - $field = 'fk_tva'; + * Return amount of payments already done + * + * @return int Amount of payment already done, <0 if KO + */ + public function getSommePaiement() + { + $table = 'payment_vat'; + $field = 'fk_tva'; - $sql = 'SELECT sum(amount) as amount'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$table; - $sql .= ' WHERE '.$field.' = '.$this->id; + $sql = 'SELECT sum(amount) as amount'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$table; + $sql .= ' WHERE '.$field.' = '.$this->id; - dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $amount = 0; + dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $amount = 0; - $obj = $this->db->fetch_object($resql); - if ($obj) $amount = $obj->amount ? $obj->amount : 0; + $obj = $this->db->fetch_object($resql); + if ($obj) { + $amount = $obj->amount ? $obj->amount : 0; + } - $this->db->free($resql); - return $amount; - } - else { - return -1; - } - } + $this->db->free($resql); + return $amount; + } else { + return -1; + } + } /** * Informations of vat payment object @@ -812,10 +801,8 @@ class Tva extends CommonObject dol_syslog(get_class($this)."::info", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -838,8 +825,7 @@ class Tva extends CommonObject } $this->db->free($result); - } - else { + } else { dol_print_error($this->db); } } @@ -877,21 +863,28 @@ class Tva extends CommonObject $this->labelStatus = array(); $this->labelStatusShort = array(); - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[self::STATUS_UNPAID] = $langs->trans('BillStatusNotPaid'); $this->labelStatus[self::STATUS_PAID] = $langs->trans('BillStatusPaid'); - if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) { + $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + } $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans('BillStatusNotPaid'); $this->labelStatusShort[self::STATUS_PAID] = $langs->trans('BillStatusPaid'); - if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) { + $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + } } $statusType = 'status1'; - if ($status == 0 && $alreadypaid <> 0) $statusType = 'status3'; - if ($status == 1) $statusType = 'status6'; + if ($status == 0 && $alreadypaid <> 0) { + $statusType = 'status3'; + } + if ($status == 1) { + $statusType = 'status6'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } diff --git a/htdocs/compta/tva/clients.php b/htdocs/compta/tva/clients.php index d4acecf063d..7ec5ad5b4f1 100644 --- a/htdocs/compta/tva/clients.php +++ b/htdocs/compta/tva/clients.php @@ -46,12 +46,13 @@ $langs->loadLangs(array("other", "compta", "banks", "bills", "companies", "produ $now = dol_now(); $current_date = dol_getdate($now); -if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) $conf->global->SOCIETE_FISCAL_MONTH_START = 1; +if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) { + $conf->global->SOCIETE_FISCAL_MONTH_START = 1; +} // Date range $year = GETPOST("year", "int"); -if (empty($year)) -{ +if (empty($year)) { $year_current = $current_date['year']; $year_start = $year_current; } else { @@ -61,12 +62,13 @@ if (empty($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 -{ +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($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; @@ -88,25 +90,45 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end } } } 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); } + 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); + } } } $min = price2num(GETPOST("min", "alpha")); -if (empty($min)) $min = 0; +if (empty($min)) { + $min = 0; +} // 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; -if (GETPOSTISSET("modetax")) $modetax = GETPOST("modetax", 'int'); -if (empty($modetax)) $modetax = 0; +if (GETPOSTISSET("modetax")) { + $modetax = GETPOST("modetax", 'int'); +} +if (empty($modetax)) { + $modetax = 0; +} // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); @@ -128,9 +150,10 @@ $user_static = new User($db); $morequerystring = ''; $listofparams = array('date_startmonth', 'date_startyear', 'date_startday', 'date_endmonth', 'date_endyear', 'date_endday'); -foreach ($listofparams as $param) -{ - if (GETPOST($param) != '') $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param); +foreach ($listofparams as $param) { + if (GETPOST($param) != '') { + $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param); + } } $special_report = false; @@ -149,9 +172,15 @@ $fsearch .= ''; // Show report header $name = $langs->trans("VATReportByThirdParties"); $calcmode = ''; -if ($modetax == 0) $calcmode = $langs->trans('OptionVATDefault'); -if ($modetax == 1) $calcmode = $langs->trans('OptionVATDebitOption'); -if ($modetax == 2) $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +if ($modetax == 0) { + $calcmode = $langs->trans('OptionVATDefault'); +} +if ($modetax == 1) { + $calcmode = $langs->trans('OptionVATDebitOption'); +} +if ($modetax == 2) { + $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +} $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); @@ -173,19 +202,28 @@ if ($nextquarter < 4) { } $builddate = dol_now(); -if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description .= $langs->trans("RulesVATDueProducts"); -if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description .= $langs->trans("RulesVATInProducts"); -if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description .= '
    '.$langs->trans("RulesVATDueServices"); -if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description .= '
    '.$langs->trans("RulesVATInServices"); +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') { + $description .= $langs->trans("RulesVATDueProducts"); +} +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') { + $description .= $langs->trans("RulesVATInProducts"); +} +if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') { + $description .= '
    '.$langs->trans("RulesVATDueServices"); +} +if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') { + $description .= '
    '.$langs->trans("RulesVATInServices"); +} if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $description .= '
    '.$langs->trans("DepositsAreNotIncluded"); } -if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description .= '
    '.$langs->trans("ThisIsAnEstimatedValue"); +if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) { + $description .= '
    '.$langs->trans("ThisIsAnEstimatedValue"); +} //$periodlink=($year_start?"".img_previous()." ".img_next()."":""); $description .= ($description ? '
    ' : '').$fsearch; -if (!empty($conf->global->TAX_REPORT_EXTRA_REPORT)) -{ +if (!empty($conf->global->TAX_REPORT_EXTRA_REPORT)) { $description .= '
    '; $description .= ' '; $description .= $langs->trans('SimpleReport'); @@ -229,8 +267,7 @@ $columns = 5; $x_coll = tax_by_thirdparty('vat', $db, 0, $date_start, $date_end, $modetax, 'sell'); $x_paye = tax_by_thirdparty('vat', $db, 0, $date_start, $date_end, $modetax, 'buy'); -if (!is_array($x_coll) || !is_array($x_paye)) -{ +if (!is_array($x_coll) || !is_array($x_paye)) { $langs->load("errors"); if ($x_coll == -1) { print '
    '; @@ -242,15 +279,14 @@ if (!is_array($x_coll) || !is_array($x_paye)) } else { $x_both = array(); //now, from these two arrays, get another array with one rate per line - foreach (array_keys($x_coll) as $my_coll_thirdpartyid) - { + foreach (array_keys($x_coll) as $my_coll_thirdpartyid) { $x_both[$my_coll_thirdpartyid]['coll']['totalht'] = $x_coll[$my_coll_thirdpartyid]['totalht']; $x_both[$my_coll_thirdpartyid]['coll']['vat'] = $x_coll[$my_coll_thirdpartyid]['vat']; $x_both[$my_coll_thirdpartyid]['paye']['totalht'] = 0; $x_both[$my_coll_thirdpartyid]['paye']['vat'] = 0; $x_both[$my_coll_thirdpartyid]['coll']['links'] = ''; $x_both[$my_coll_thirdpartyid]['coll']['detail'] = array(); - foreach ($x_coll[$my_coll_thirdpartyid]['facid'] as $id=>$dummy) { + foreach ($x_coll[$my_coll_thirdpartyid]['facid'] as $id => $dummy) { $invoice_customer->id = $x_coll[$my_coll_thirdpartyid]['facid'][$id]; $invoice_customer->ref = $x_coll[$my_coll_thirdpartyid]['facnum'][$id]; $invoice_customer->type = $x_coll[$my_coll_thirdpartyid]['type'][$id]; @@ -289,11 +325,9 @@ if (!is_array($x_coll) || !is_array($x_paye)) $x_both[$my_paye_thirdpartyid]['paye']['links'] = ''; $x_both[$my_paye_thirdpartyid]['paye']['detail'] = array(); - foreach ($x_paye[$my_paye_thirdpartyid]['facid'] as $id=>$dummy) - { + foreach ($x_paye[$my_paye_thirdpartyid]['facid'] as $id => $dummy) { // ExpenseReport - if ($x_paye[$my_paye_thirdpartyid]['ptype'][$id] == 'ExpenseReportPayment') - { + if ($x_paye[$my_paye_thirdpartyid]['ptype'][$id] == 'ExpenseReportPayment') { $expensereport->id = $x_paye[$my_paye_thirdpartyid]['facid'][$id]; $expensereport->ref = $x_paye[$my_paye_thirdpartyid]['facnum'][$id]; $expensereport->type = $x_paye[$my_paye_thirdpartyid]['type'][$id]; @@ -356,7 +390,9 @@ if (!is_array($x_coll) || !is_array($x_paye)) $x_paye_ht = 0; $span = $columns; - if ($modetax != 1) $span += 2; + if ($modetax != 1) { + $span += 2; + } //print ''; @@ -364,12 +400,14 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print ''; print ''; - if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''; - else print ''; + if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') { + print ''; + } else { + print ''; + } print ''; print ''; - if ($modetax != 1) - { + if ($modetax != 1) { print ''; print ''; } @@ -392,10 +430,8 @@ if (!is_array($x_coll) || !is_array($x_paye)) $subtot_coll_total_ht = 0; $subtot_coll_vat = 0; - if ($min == 0 || ($min > 0 && $x_both[$thirdparty_id]['coll']['totalht'] > $min)) - { - if (is_array($x_both[$thirdparty_id]['coll']['detail'])) - { + if ($min == 0 || ($min > 0 && $x_both[$thirdparty_id]['coll']['totalht'] > $min)) { + if (is_array($x_both[$thirdparty_id]['coll']['detail'])) { // VAT Rate print ""; print ''; print ''; print ''; @@ -563,8 +598,11 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print ''; print ''; - if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') print ''; - else print ''; + if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') { + print ''; + } else { + print ''; + } print ''; print ''; if ($modetax != 1) { @@ -575,8 +613,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print ''."\n"; - foreach (array_keys($x_paye) as $thirdparty_id) - { + foreach (array_keys($x_paye) as $thirdparty_id) { $subtot_paye_total_ht = 0; $subtot_paye_vat = 0; @@ -673,18 +710,15 @@ if (!is_array($x_coll) || !is_array($x_paye)) // Payment $ratiopaymentinvoice = 1; - if ($modetax != 1) - { + if ($modetax != 1) { print '
    '.$langs->trans("Amount").'
    '; @@ -693,8 +655,7 @@ if ($id) print ''.dol_print_date($db->jdate($objp->dp), 'day')."".$labeltype.' '.$objp->num_payment."'; - if ($bankaccountstatic->id) + if ($bankaccountstatic->id) { print $bankaccountstatic->getNomUrl(1, 'transactions'); + } print ''.price($objp->amount)."
    '.$langs->trans("None").'
    '.$langs->trans("ErrorNoAccountancyModuleLoaded").'
    '..')
    '.$elementcust.''.$langs->trans("DateInvoice").''.$langs->trans("DatePayment").''.$langs->trans("DatePayment").''.$namerate.''.$productcust.''.$amountcust.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')
    '; @@ -542,8 +578,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) } } - if (count($x_coll) == 0) // Show a total ine if nothing shown - { + if (count($x_coll) == 0) { // Show a total ine if nothing shown print '
    '.$langs->trans("Total").':
    '.$elementsup.''.$langs->trans("DateInvoice").''.$langs->trans("DatePayment").''.$langs->trans("DatePayment").''.$namesup.''.$productsup.''.$vatsup.'
    '; - if ($fields['payment_amount'] && $fields['ftotal_ttc']) - { + 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')) - { + || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) { print $langs->trans("NA"); } else { if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) { diff --git a/htdocs/compta/tva/document.php b/htdocs/compta/tva/document.php index e310e61fcb8..38d88fb3d12 100644 --- a/htdocs/compta/tva/document.php +++ b/htdocs/compta/tva/document.php @@ -34,8 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/vat.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } @@ -48,7 +47,9 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', 'vat', 'charges'); @@ -63,12 +64,18 @@ if (empty($page) || $page == -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"; +} $object = new Tva($db); -if ($id > 0) $object->fetch($id); +if ($id > 0) { + $object->fetch($id); +} $upload_dir = $conf->tax->dir_output.'/vat/'.dol_sanitizeFileName($object->ref); $modulepart = 'tax-vat'; @@ -78,14 +85,14 @@ $modulepart = 'tax-vat'; * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; -if ($action == 'setlib' && $user->rights->tax->charges->creer) -{ +if ($action == 'setlib' && $user->rights->tax->charges->creer) { $object->fetch($id); $result = $object->setValueFrom('label', GETPOST('lib', 'alpha'), '', '', 'text', '', $user, 'TAX_MODIFY'); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } @@ -94,14 +101,15 @@ if ($action == 'setlib' && $user->rights->tax->charges->creer) */ $form = new Form($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $title = $langs->trans("VATPayment").' - '.$langs->trans("Documents"); $help_url = 'EN:Module_Taxes_and_social_contributions|FR:Module Taxes et dividendes|ES:Módulo Impuestos y cargas sociales (IVA, impuestos)'; llxHeader("", $title, $help_url); -if ($object->id) -{ +if ($object->id) { $alreadypayed = $object->getSommePaiement(); $head = vat_prepare_head($object); @@ -126,8 +134,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/compta/tva/index.php b/htdocs/compta/tva/index.php index 081023cd2e8..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 @@ -39,68 +40,112 @@ $langs->loadLangs(array("other", "compta", "banks", "bills", "companies", "produ $form = new Form($db); $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; -} else { - $year_current = $year; - $year_start = $year; +if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) { + $conf->global->SOCIETE_FISCAL_MONTH_START = 1; } -$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--; - } - } + +$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 { + $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); } - } } // 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; -if (GETPOSTISSET("modetax")) $modetax = GETPOST("modetax", 'int'); -if (empty($modetax)) $modetax = 0; +if (GETPOSTISSET("modetax")) { + $modetax = GETPOST("modetax", 'int'); +} +if (empty($modetax)) { + $modetax = 0; +} // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); @@ -114,102 +159,95 @@ $result = restrictedArea($user, 'tax', '', '', 'charges'); */ function pt($db, $sql, $date) { - global $conf, $bc, $langs, $form; + global $conf, $bc, $langs, $form; - $result = $db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $i = 0; - $total = 0; - print ''; + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $i = 0; + $total = 0; + print '
    '; - print ''; - print ''; - print ''; - print ''; - print "\n"; + print ''; + print ''; + print ''; + print ''; + print "\n"; - $totalclaimed = 0; - $totalpaid = 0; - $amountclaimed = 0; - $amountpaid = 0; - $previousmonth = ''; - $previousmode = ''; - $mode = ''; + $totalclaimed = 0; + $totalpaid = 0; + $amountclaimed = 0; + $amountpaid = 0; + $previousmonth = ''; + $previousmode = ''; + $mode = ''; - while ($i < $num) { - $obj = $db->fetch_object($result); - $mode = $obj->mode; + while ($i < $num) { + $obj = $db->fetch_object($result); + $mode = $obj->mode; - //print $obj->dm.' '.$obj->mode.' '.$previousmonth.' '.$previousmode; - if ($obj->mode == 'claimed' && !empty($previousmode)) - { - print ''; - print '\n"; - print '\n"; - print '\n"; - print "\n"; + //print $obj->dm.' '.$obj->mode.' '.$previousmonth.' '.$previousmode; + if ($obj->mode == 'claimed' && !empty($previousmode)) { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; - $amountclaimed = 0; - $amountpaid = 0; - } + $amountclaimed = 0; + $amountpaid = 0; + } - if ($obj->mode == 'claimed') - { - $amountclaimed = $obj->mm; - $totalclaimed = $totalclaimed + $amountclaimed; - } - if ($obj->mode == 'paid') - { - $amountpaid = $obj->mm; - $totalpaid = $totalpaid + $amountpaid; - } + if ($obj->mode == 'claimed') { + $amountclaimed = $obj->mm; + $totalclaimed = $totalclaimed + $amountclaimed; + } + if ($obj->mode == 'paid') { + $amountpaid = $obj->mm; + $totalpaid = $totalpaid + $amountpaid; + } - if ($obj->mode == 'paid') - { - print ''; - print '\n"; - print '\n"; - print '\n"; - print "\n"; - $amountclaimed = 0; - $amountpaid = 0; - $previousmode = ''; - $previousmonth = ''; - } - else { - $previousmode = $obj->mode; - $previousmonth = $obj->dm; - } + if ($obj->mode == 'paid') { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; + $amountclaimed = 0; + $amountpaid = 0; + $previousmode = ''; + $previousmonth = ''; + } else { + $previousmode = $obj->mode; + $previousmonth = $obj->dm; + } - $i++; - } + $i++; + } - if ($mode == 'claimed' && !empty($previousmode)) - { - print ''; - print '\n"; - print '\n"; - print '\n"; - print "\n"; + if ($mode == 'claimed' && !empty($previousmode)) { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; - $amountclaimed = 0; - $amountpaid = 0; - } + $amountclaimed = 0; + $amountpaid = 0; + } - print ''; - print ''; - print ''; - print ''; - print ""; + print ''; + print ''; + print ''; + print ''; + print ""; - print "
    '.$date.''.$langs->trans("ClaimedForThisPeriod").''.$langs->trans("PaidDuringThisPeriod").$form->textwithpicto('', $langs->trans('PaidDuringThisPeriodDesc'), 1).'
    '.$date.''.$langs->trans("ClaimedForThisPeriod").''.$langs->trans("PaidDuringThisPeriod").$form->textwithpicto('', $langs->trans('PaidDuringThisPeriodDesc'), 1).'
    '.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
    '.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
    '.$obj->dm."'.price($amountclaimed)."'.price($amountpaid)."
    '.$obj->dm."'.price($amountclaimed)."'.price($amountpaid)."
    '.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
    '.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
    '.$langs->trans("Total").''.price($totalclaimed).''.price($totalpaid).'
    '.$langs->trans("Total").''.price($totalclaimed).''.price($totalpaid).'
    "; + print "
    "; - $db->free($result); - } - else { - dol_print_error($db); - } + $db->free($result); + } else { + dol_print_error($db); + } } @@ -229,20 +267,36 @@ $description = $fsearch; // Show report header $name = $langs->trans("VATReportByMonth"); $calcmode = ''; -if ($modetax == 0) $calcmode = $langs->trans('OptionVATDefault'); -if ($modetax == 1) $calcmode = $langs->trans('OptionVATDebitOption'); -if ($modetax == 2) $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +if ($modetax == 0) { + $calcmode = $langs->trans('OptionVATDefault'); +} +if ($modetax == 1) { + $calcmode = $langs->trans('OptionVATDebitOption'); +} +if ($modetax == 2) { + $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +} $calcmode .= ' ('.$langs->trans("TaxModuleSetupToModifyRules", DOL_URL_ROOT.'/admin/taxes.php').')'; $description .= $langs->trans("VATSummary").'
    '; -if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description .= $langs->trans("RulesVATDueProducts"); -if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description .= $langs->trans("RulesVATInProducts"); -if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description .= '
    '.$langs->trans("RulesVATDueServices"); -if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description .= '
    '.$langs->trans("RulesVATInServices"); +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') { + $description .= $langs->trans("RulesVATDueProducts"); +} +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') { + $description .= $langs->trans("RulesVATInProducts"); +} +if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') { + $description .= '
    '.$langs->trans("RulesVATDueServices"); +} +if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') { + $description .= '
    '.$langs->trans("RulesVATInServices"); +} if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $description .= '
    '.$langs->trans("DepositsAreNotIncluded"); } -if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description .= '
    '.$langs->trans("ThisIsAnEstimatedValue"); +if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) { + $description .= '
    '.$langs->trans("ThisIsAnEstimatedValue"); +} $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); @@ -261,366 +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) ); } } + + // 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(); + + 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_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) + ); + } + } + } + //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'; + + // 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 (!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; + } + } + 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; + } } - //now we have an array (x_both) indexed by rates for coll and paye + print ''; + print "\n"; + print ''; - $action = "tva"; - $object = array(&$x_coll, &$x_paye, &$x_both); - $parameters["mode"] = $modetax; - $parameters["year"] = $y; - $parameters["month"] = $m; - $parameters["type"] = 'vat'; - - // 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 (!is_array($x_coll) && $coll_listbuy == -1) - { - $langs->load("errors"); - print ''; - break; - } - if (!is_array($x_paye) && $coll_listbuy == -2) - { - print ''; - break; - } + 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')) . '' . 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')) . ' 
    ' . $langs->trans("TotalToPay") . ':' . price(price2num($total, 'MT')) . ' 
    '.$langs->trans("ErrorNoAccountancyModuleLoaded").'
    '.$langs->trans("FeatureNotYetAvailable").'
    '; - print '
    '.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')).' 
    '.$langs->trans("TotalToPay").':'.price(price2num($total, '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")); - - -if (!empty($conf->global->MAIN_FEATURES_LEVEL)) -{ - print '
    '; /* - * Recap - */ + * Paid + */ + print load_fiche_titre($langs->trans("VATPaid"), '', ''); - print load_fiche_titre($langs->trans("VATBalance"), '', ''); // need to add translation + $sql = ''; - $sql1 = "SELECT SUM(amount) as mm"; - $sql1 .= " FROM ".MAIN_DB_PREFIX."tva as f"; - $sql1 .= " WHERE f.entity = ".$conf->entity; - $sql1 .= " AND f.datev >= '".$db->idate($date_start)."'"; - $sql1 .= " AND f.datev <= '".$db->idate($date_end)."'"; + $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"; - $result = $db->query($sql1); - if ($result) { - $obj = $db->fetch_object($result); - print ''; + $sql .= " UNION "; - print ""; - print ''; - print ''; - print "\n"; + $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"; - print ""; - print ''; - print '\n"; - print "\n"; + $sql .= " ORDER BY dm ASC, mode ASC"; + //print $sql; - $restopay = $total - $obj->mm; - print ""; - print ''; - print ''; - print "\n"; + pt($db, $sql, $langs->trans("Month")); - print '
    '.$langs->trans("VATDue").''.price(price2num($total, 'MT')).'
    '.$langs->trans("VATPaid").''.price(price2num($obj->mm, 'MT'))."
    '.$langs->trans("RemainToPay").''.price(price2num($restopay, 'MT')).'
    '; - } + print '
    '; } -print ''; - llxFooter(); $db->close(); diff --git a/htdocs/compta/tva/info.php b/htdocs/compta/tva/info.php index 45799c8e1f5..fb3d0c62d86 100644 --- a/htdocs/compta/tva/info.php +++ b/htdocs/compta/tva/info.php @@ -34,7 +34,9 @@ $action = GETPOST('action', 'aZ09'); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); $object = new Tva($db); @@ -45,12 +47,12 @@ $object = new Tva($db); * Actions */ -if ($action == 'setlib' && $user->rights->tax->charges->creer) -{ +if ($action == 'setlib' && $user->rights->tax->charges->creer) { $object->fetch($id); $result = $object->setValueFrom('label', GETPOST('lib', 'alpha'), '', '', 'text', '', $user, 'TAX_MODIFY'); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } diff --git a/htdocs/compta/tva/list.php b/htdocs/compta/tva/list.php index dd5118bc656..c7146023aab 100644 --- a/htdocs/compta/tva/list.php +++ b/htdocs/compta/tva/list.php @@ -30,7 +30,9 @@ require '../../main.inc.php'; // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; @@ -65,13 +67,19 @@ $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 = 't.datev'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 't.datev'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} $arrayfields = array( 't.rowid' =>array('checked'=>1, 'position'=>10, 'label'=>"Ref",), @@ -94,14 +102,15 @@ $object = new Tva($db); $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)) { include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $search_ref = ''; $search_label = ''; $search_dateend_start = ''; @@ -137,16 +146,36 @@ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as pst ON t.fk_typepayment = ps $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_vat as ptva ON ptva.fk_tva = t.rowid"; $sql .= ' WHERE t.entity IN ('.getEntity($object->element).')'; -if (!empty($search_ref)) $sql .= natural_search('t.rowid', $search_ref); -if (!empty($search_label)) $sql .= natural_search('t.label', $search_label); -if (!empty($search_dateend_start)) $sql .= ' AND t.datev >= "'.$db->idate($search_dateend_start).'"'; -if (!empty($search_dateend_end)) $sql .= ' AND t.datev <= "'.$db->idate($search_dateend_end).'"'; -if (!empty($search_datepayment_start)) $sql .= ' AND t.datep >= "'.$db->idate($search_datepayment_start).'"'; -if (!empty($search_datepayment_end)) $sql .= ' AND t.datep <= "'.$db->idate($search_datepayment_end).'"'; -if (!empty($search_type) && $search_type > 0) $sql .= ' AND t.fk_typepayment='.$search_type; -if (!empty($search_account) && $search_account > 0) $sql .= ' AND b.fk_account='.$search_account; -if (!empty($search_amount)) $sql .= natural_search('t.amount', price2num(trim($search_amount)), 1); -if ($search_status != '' && $search_status >= 0) $sql .= " AND t.paye = ".$db->escape($search_status); +if (!empty($search_ref)) { + $sql .= natural_search('t.rowid', $search_ref); +} +if (!empty($search_label)) { + $sql .= natural_search('t.label', $search_label); +} +if (!empty($search_dateend_start)) { + $sql .= ' AND t.datev >= "'.$db->idate($search_dateend_start).'"'; +} +if (!empty($search_dateend_end)) { + $sql .= ' AND t.datev <= "'.$db->idate($search_dateend_end).'"'; +} +if (!empty($search_datepayment_start)) { + $sql .= ' AND t.datep >= "'.$db->idate($search_datepayment_start).'"'; +} +if (!empty($search_datepayment_end)) { + $sql .= ' AND t.datep <= "'.$db->idate($search_datepayment_end).'"'; +} +if (!empty($search_type) && $search_type > 0) { + $sql .= ' AND t.fk_typepayment='.$search_type; +} +if (!empty($search_account) && $search_account > 0) { + $sql .= ' AND b.fk_account='.$search_account; +} +if (!empty($search_amount)) { + $sql .= natural_search('t.amount', price2num(trim($search_amount)), 1); +} +if ($search_status != '' && $search_status >= 0) { + $sql .= " AND t.paye = ".$db->escape($search_status); +} $sql .= " GROUP BY t.rowid, t.amount, t.label, t.datev, t.datep, t.paye, t.fk_typepayment, t.num_payment, pst.code"; $sql .= $db->order($sortfield, $sortorder); @@ -166,8 +195,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); -if (!$result) -{ +if (!$result) { dol_print_error($db); llxFooter(); $db->close(); @@ -177,32 +205,78 @@ if (!$result) $num = $db->num_rows($result); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER['PHP_SELF']) $param .= '&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); +if (!empty($contextpage) && $contextpage != $_SERVER['PHP_SELF']) { + $param .= '&contextpage='.$contextpage; +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} -if (!empty($search_ref)) $param .= '&search_ref="'.$search_ref.'"'; -if (!empty($search_label)) $param .= '&search_label="'.$search_label.'"'; -if (!empty($search_dateend_start)) $param .= '&search_dateend_startyear='.GETPOST('search_dateend_startyear', 'int'); -if (!empty($search_dateend_start)) $param .= '&search_dateend_startmonth='.GETPOST('search_dateend_startmonth', 'int'); -if (!empty($search_dateend_start)) $param .= '&search_dateend_startday='.GETPOST('search_dateend_startday', 'int'); -if (!empty($search_dateend_end)) $param .= '&search_dateend_endyear='.GETPOST('search_dateend_endyear', 'int'); -if (!empty($search_dateend_end)) $param .= '&search_dateend_endmonth='.GETPOST('search_dateend_endmonth', 'int'); -if (!empty($search_dateend_end)) $param .= '&search_dateend_endday='.GETPOST('search_dateend_endday', 'int'); -if (!empty($search_datepayment_start)) $param .= '&search_datepayment_startyear='.GETPOST('search_datepayment_startyear', 'int'); -if (!empty($search_datepayment_start)) $param .= '&search_datepayment_startmonth='.GETPOST('search_datepayment_startmonth', 'int'); -if (!empty($search_datepayment_start)) $param .= '&search_datepayment_startday='.GETPOST('search_datepayment_startday', 'int'); -if (!empty($search_datepayment_end)) $param .= '&search_datepayment_endyear='.GETPOST('search_datepayment_endyear', 'int'); -if (!empty($search_datepayment_end)) $param .= '&search_datepayment_endmonth='.GETPOST('search_datepayment_endmonth', 'int'); -if (!empty($search_datepayment_end)) $param .= '&search_datepayment_endday='.GETPOST('search_datepayment_endday', 'int'); -if (!empty($search_type) && $search_type > 0) $param .= '&search_type='.$search_type; -if (!empty($search_cheque)) $param .= '&search_cheque="'.$search_cheque.'"'; -if (!empty($search_account) && $search_account > 0) $param .= '&search_account='.$search_account; -if (!empty($search_amount)) $param .= '&search_amount="'.$search_amount.'"'; -if ($search_status != '' && $search_status != '-1') $param .= '&search_status='.urlencode($search_status); +if (!empty($search_ref)) { + $param .= '&search_ref="'.$search_ref.'"'; +} +if (!empty($search_label)) { + $param .= '&search_label="'.$search_label.'"'; +} +if (!empty($search_dateend_start)) { + $param .= '&search_dateend_startyear='.GETPOST('search_dateend_startyear', 'int'); +} +if (!empty($search_dateend_start)) { + $param .= '&search_dateend_startmonth='.GETPOST('search_dateend_startmonth', 'int'); +} +if (!empty($search_dateend_start)) { + $param .= '&search_dateend_startday='.GETPOST('search_dateend_startday', 'int'); +} +if (!empty($search_dateend_end)) { + $param .= '&search_dateend_endyear='.GETPOST('search_dateend_endyear', 'int'); +} +if (!empty($search_dateend_end)) { + $param .= '&search_dateend_endmonth='.GETPOST('search_dateend_endmonth', 'int'); +} +if (!empty($search_dateend_end)) { + $param .= '&search_dateend_endday='.GETPOST('search_dateend_endday', 'int'); +} +if (!empty($search_datepayment_start)) { + $param .= '&search_datepayment_startyear='.GETPOST('search_datepayment_startyear', 'int'); +} +if (!empty($search_datepayment_start)) { + $param .= '&search_datepayment_startmonth='.GETPOST('search_datepayment_startmonth', 'int'); +} +if (!empty($search_datepayment_start)) { + $param .= '&search_datepayment_startday='.GETPOST('search_datepayment_startday', 'int'); +} +if (!empty($search_datepayment_end)) { + $param .= '&search_datepayment_endyear='.GETPOST('search_datepayment_endyear', 'int'); +} +if (!empty($search_datepayment_end)) { + $param .= '&search_datepayment_endmonth='.GETPOST('search_datepayment_endmonth', 'int'); +} +if (!empty($search_datepayment_end)) { + $param .= '&search_datepayment_endday='.GETPOST('search_datepayment_endday', 'int'); +} +if (!empty($search_type) && $search_type > 0) { + $param .= '&search_type='.$search_type; +} +if (!empty($search_cheque)) { + $param .= '&search_cheque="'.$search_cheque.'"'; +} +if (!empty($search_account) && $search_account > 0) { + $param .= '&search_account='.$search_account; +} +if (!empty($search_amount)) { + $param .= '&search_amount="'.$search_amount.'"'; +} +if ($search_status != '' && $search_status != '-1') { + $param .= '&search_status='.urlencode($search_status); +} print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -211,13 +285,17 @@ print ''; print ''; $url = DOL_URL_ROOT.'/compta/tva/card.php?action=create'; -if (!empty($socid)) $url .= '&socid='.$socid; +if (!empty($socid)) { + $url .= '&socid='.$socid; +} $newcardbutton = dolGetButtonTitle($langs->trans('NewVATPayment', ($ltt + 1)), '', 'fa fa-plus-circle', $url, '', $user->rights->tax->charges->creer); print_barre_liste($langs->trans("VATDeclarations"), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit, 0, 0, 1); $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 ''; @@ -303,13 +381,27 @@ print ''; print ''; print ''; -if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['t.rowid']['checked'])) print_liste_field_titre($arrayfields['t.rowid']['label'], $_SERVER['PHP_SELF'], 't.rowid', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['t.label']['checked'])) print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER['PHP_SELF'], 't.label', '', $param, 'align="left"', $sortfield, $sortorder); -if (!empty($arrayfields['t.datev']['checked'])) print_liste_field_titre($arrayfields['t.datev']['label'], $_SERVER['PHP_SELF'], 't.datev', '', $param, 'align="center"', $sortfield, $sortorder); -if (!empty($arrayfields['t.fk_typepayment']['checked'])) print_liste_field_titre($arrayfields['t.fk_typepayment']['label'], $_SERVER['PHP_SELF'], 't.fk_typepayment', '', $param, '', $sortfield, $sortorder, 'left '); -if (!empty($arrayfields['t.amount']['checked'])) print_liste_field_titre($arrayfields['t.amount']['label'], $_SERVER['PHP_SELF'], 't.amount', '', $param, '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['t.status']['checked'])) print_liste_field_titre($arrayfields['t.status']['label'], $_SERVER["PHP_SELF"], "t.paye", "", $param, 'class="right"', $sortfield, $sortorder); +if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { + print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['t.rowid']['checked'])) { + print_liste_field_titre($arrayfields['t.rowid']['label'], $_SERVER['PHP_SELF'], 't.rowid', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['t.label']['checked'])) { + print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER['PHP_SELF'], 't.label', '', $param, 'align="left"', $sortfield, $sortorder); +} +if (!empty($arrayfields['t.datev']['checked'])) { + print_liste_field_titre($arrayfields['t.datev']['label'], $_SERVER['PHP_SELF'], 't.datev', '', $param, 'align="center"', $sortfield, $sortorder); +} +if (!empty($arrayfields['t.fk_typepayment']['checked'])) { + print_liste_field_titre($arrayfields['t.fk_typepayment']['label'], $_SERVER['PHP_SELF'], 't.fk_typepayment', '', $param, '', $sortfield, $sortorder, 'left '); +} +if (!empty($arrayfields['t.amount']['checked'])) { + print_liste_field_titre($arrayfields['t.amount']['label'], $_SERVER['PHP_SELF'], 't.amount', '', $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['t.status']['checked'])) { + print_liste_field_titre($arrayfields['t.status']['label'], $_SERVER["PHP_SELF"], "t.paye", "", $param, 'class="right"', $sortfield, $sortorder); +} // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); @@ -333,25 +425,33 @@ while ($i < min($num, $limit)) { // No if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Ref if (!empty($arrayfields['t.rowid']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Label if (!empty($arrayfields['t.label']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date end period if (!empty($arrayfields['t.datev']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date payment @@ -361,10 +461,11 @@ while ($i < min($num, $limit)) { }*/ // Type - if (!empty($arrayfields['t.fk_typepayment']['checked'])) - { + if (!empty($arrayfields['t.fk_typepayment']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Account @@ -390,15 +491,21 @@ while ($i < min($num, $limit)) { if (!empty($arrayfields['t.amount']['checked'])) { $total = $total + $obj->amount; print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } $totalarray['pos'][$totalarray['nbfield']] = 'amount'; $totalarray['val']['amount'] += $obj->amount; } if (!empty($arrayfields['t.status']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; - if (!empty($arrayfields['t.amount']['checked'])) $totalarray['pos'][$totalarray['nbfield']] = ''; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($arrayfields['t.amount']['checked'])) { + $totalarray['pos'][$totalarray['nbfield']] = ''; + } } // Buttons diff --git a/htdocs/compta/tva/payments.php b/htdocs/compta/tva/payments.php index 0cdf7e7086b..73e2dae0e05 100644 --- a/htdocs/compta/tva/payments.php +++ b/htdocs/compta/tva/payments.php @@ -39,24 +39,34 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $langs->loadLangs(array('compta', 'bills')); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax|salaries', '', '', 'charges|'); $mode = GETPOST("mode", 'alpha'); $year = GETPOST("year", 'int'); $filtre = GETPOST("filtre", 'alpha'); -if (!$year && $mode != 'tvaonly') { $year = date("Y", time()); } +if (!$year && $mode != 'tvaonly') { + $year = date("Y", time()); +} $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 = "ptva.datep"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "ptva.datep"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} /* @@ -73,14 +83,24 @@ llxHeader('', $langs->trans("VATExpensesArea")); $title = $langs->trans("VATPayments"); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; -if ($sortfield) $param .= '&sortfield='.$sortfield; -if ($sortorder) $param .= '&sortorder='.$sortorder; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.$contextpage; +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; +} +if ($sortfield) { + $param .= '&sortfield='.$sortfield; +} +if ($sortorder) { + $param .= '&sortorder='.$sortorder; +} print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -90,10 +110,11 @@ print ''; print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $center, $num, $totalnboflines, 'title_accountancy', 0, '', '', $limit); -if ($year) $param .= '&year='.$year; +if ($year) { + $param .= '&year='.$year; +} -if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) -{ +if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) { print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '
    '.(($offset * $limit) + $i).''.$tva_static->getNomUrl(1).''.dol_trunc($obj->label, 40).''.dol_print_date($db->jdate($obj->datev), 'day').''.$langs->trans("PaymentTypeShort".$obj->payment_code).'' . price($obj->amount) . '' . $tva_static->LibStatut($obj->paye, 5, $obj->alreadypayed) . '
    '; print ''; @@ -120,8 +141,7 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON ptva.fk_typepaiement = pct.id"; $sql .= " WHERE ptva.fk_tva = tva.rowid"; $sql .= " AND tva.entity = ".$conf->entity; - if ($year > 0) - { + if ($year > 0) { $sql .= " AND ("; // Si period renseignee on l'utilise comme critere de date, sinon on prend date echeance, // ceci afin d'etre compatible avec les cas ou la periode n'etait pas obligatoire @@ -133,22 +153,22 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) || preg_match('/^tva\./', $sortfield) || preg_match('/^ptva\./', $sortfield) || preg_match('/^pct\./', $sortfield) - || preg_match('/^bank\./', $sortfield)) $sql .= $db->order($sortfield, $sortorder); + || preg_match('/^bank\./', $sortfield)) { + $sql .= $db->order($sortfield, $sortorder); + } //$sql.= $db->plimit($limit+1,$offset); //print $sql; dol_syslog("compta/tva/payments.php: select payment", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; $total = 0; $totalnb = 0; $totalpaye = 0; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $payment_vat_static->id = $obj->pid; @@ -159,11 +179,13 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print '\n"; // Date payment print ''; - // Type payment - print ''; - // Account + // Type payment + print ''; + // Account print ''; // Paid print ''; print ''; @@ -194,16 +218,15 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $totalpaye = $totalpaye + $obj->totalpaye; $i++; } - print ''; - print ''; // A total here has no sense - //print ''; - print ''; + print ''; + print ''; // A total here has no sense + //print ''; print ''; print ''; - print '"; + print ''; + print '"; print ""; - } - else { + } else { dol_print_error($db); } print '
    '.$payment_vat_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->payment_code) { + print $langs->trans("PaymentTypeShort".$obj->payment_code).' '; + } + print $obj->num_payment.''; $account = new Account($db); $account->fetch($obj->fk_account); @@ -185,7 +207,9 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print ''.price($obj->total).''; - if ($obj->totalpaye) print price($obj->totalpaye); + if ($obj->totalpaye) { + print price($obj->totalpaye); + } print '
    '.$langs->trans("Total").'  
    '.$langs->trans("Total").'   '.price($totalpaye)." '.price($totalpaye)."
    '; diff --git a/htdocs/compta/tva/quadri_detail.php b/htdocs/compta/tva/quadri_detail.php index ba12b08b3b0..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,68 +46,88 @@ 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; +if (empty($min)) { + $min = 0; +} // 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; -if (GETPOSTISSET("modetax")) $modetax = GETPOST("modetax", 'int'); -if (empty($modetax)) $modetax = 0; +$modetax = (empty($conf->global->TAX_MODE) ? 0 : $conf->global->TAX_MODE); +if (GETPOSTISSET("modetax")) { + $modetax = GETPOSTINT("modetax"); +} +if (empty($modetax)) { + $modetax = 0; +} // Security check -$socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +$socid = GETPOSTINT('socid'); +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); @@ -127,9 +148,10 @@ $paymentexpensereport_static = new PaymentExpenseReport($db); $morequerystring = ''; $listofparams = array('date_startmonth', 'date_startyear', 'date_startday', 'date_endmonth', 'date_endyear', 'date_endday'); -foreach ($listofparams as $param) -{ - if (GETPOST($param) != '') $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param); +foreach ($listofparams as $param) { + if (GETPOST($param) != '') { + $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param); + } } $title = $langs->trans("VATReport")." ".dol_print_date($date_start)." -> ".dol_print_date($date_end); @@ -149,13 +171,20 @@ $fsearch .= ''; // Show report header $name = $langs->trans("VATReportByRates"); $calcmode = ''; -if ($modetax == 0) $calcmode = $langs->trans('OptionVATDefault'); -if ($modetax == 1) $calcmode = $langs->trans('OptionVATDebitOption'); -if ($modetax == 2) $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +if ($modetax == 0) { + $calcmode = $langs->trans('OptionVATDefault'); +} +if ($modetax == 1) { + $calcmode = $langs->trans('OptionVATDebitOption'); +} +if ($modetax == 2) { + $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +} $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 { @@ -173,14 +202,24 @@ if ($nextquarter < 4) { $description .= $fsearch; $builddate = dol_now(); -if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description .= $langs->trans("RulesVATDueProducts"); -if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description .= $langs->trans("RulesVATInProducts"); -if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description .= '
    '.$langs->trans("RulesVATDueServices"); -if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description .= '
    '.$langs->trans("RulesVATInServices"); +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') { + $description .= $langs->trans("RulesVATDueProducts"); +} +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') { + $description .= $langs->trans("RulesVATInProducts"); +} +if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') { + $description .= '
    '.$langs->trans("RulesVATDueServices"); +} +if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') { + $description .= '
    '.$langs->trans("RulesVATInServices"); +} if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $description .= '
    '.$langs->trans("DepositsAreNotIncluded"); } -if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description .= '
    '.$langs->trans("ThisIsAnEstimatedValue"); +if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) { + $description .= '
    '.$langs->trans("ThisIsAnEstimatedValue"); +} // Customers invoices $elementcust = $langs->trans("CustomersInvoices"); @@ -202,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); } @@ -225,8 +264,7 @@ $columns = 5; $x_coll = tax_by_rate('vat', $db, 0, 0, $date_start, $date_end, $modetax, 'sell'); $x_paye = tax_by_rate('vat', $db, 0, 0, $date_start, $date_end, $modetax, 'buy'); -if (!is_array($x_coll) || !is_array($x_paye)) -{ +if (!is_array($x_coll) || !is_array($x_paye)) { $langs->load("errors"); if ($x_coll == -1) { print '
    '.$langs->trans("ErrorNoAccountancyModuleLoaded").'
    '..')
    '.$elementcust.''.$langs->trans("DateInvoice").''.$langs->trans("DatePayment").''.$langs->trans("DatePayment").''.$namecust.''.$productcust.''.$amountcust.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')
    '.$langs->trans("Rate").': '.vatrate($rate).'%'; + print $langs->trans('Rate') . ' : ' . vatrate($rate) . '%'; + print ' - ' . img_picto('', 'chevron-down', 'class="paddingrightonly"') . $langs->trans('VATReportShowByRateDetails') . ''; + print '
    '.$fields['link'].''.dol_print_date($fields['datef'], 'day').''.dol_print_date($fields['datep'], 'day').''.$fields['company_link'].''; - 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 ''; - 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 ''; - //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); - } + $ratiopaymentinvoice=1; + if ($modetax != 1) { if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) - { - print $langs->trans("NA"); + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { } 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 ''; - $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; - print price(price2num($temp_ht, 'MT'), 1); - print ''; - $temp_vat = $fields['vat'] * $ratiopaymentinvoice; - print price(price2num($temp_vat, 'MT'), 1); - //print price($fields['vat']); - print '
    ' . $fields['link'] . '' . dol_print_date($fields['datef'], 'day') . '' . dol_print_date($fields['datep'], 'day') . '' . $fields['company_link'] . ''; + 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 ''; + 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 ''; + //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 ''; + $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; + print price(price2num($temp_ht, 'MT'), 1); + print ''; + $temp_vat = $fields['vat'] * $ratiopaymentinvoice; + print price(price2num($temp_vat, 'MT'), 1); + //print price($fields['vat']); + print '
    '.$langs->trans("Total").':
     
     
    '.$vatsup.'
    '.$langs->trans("Rate").': '.vatrate($rate).'%'; + print $langs->trans('Rate') . ' : ' . vatrate($rate) . '%'; + print ' - ' . img_picto('', 'chevron-down', 'class="paddingrightonly"') . $langs->trans('VATReportShowByRateDetails') . ''; + print '
    '.$fields['link'].''.dol_print_date($fields['datef'], 'day').''.dol_print_date($fields['datep'], 'day').''.$fields['company_link'].''; - 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 ''; - 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 ''; - if ($fields['payment_amount'] && $fields['ftotal_ttc']) - { - $paymentfourn_static->id = $fields['payment_id']; - print $paymentfourn_static->getNomUrl(2); - } - + if ($modetax != 1) { if (($type == 0 && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) - { - print $langs->trans("NA"); + || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) { } 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 ''; $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; - print price(price2num($temp_ht, 'MT'), 1); - print ''; $temp_vat = $fields['vat'] * $ratiopaymentinvoice; - print price(price2num($temp_vat, 'MT'), 1); - //print price($fields['vat']); - print '
    ' . $fields['link'] . '' . dol_print_date($fields['datef'], 'day') . '' . dol_print_date($fields['datep'], 'day') . '' . $fields['company_link'] . ''; + 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 ''; + 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 ''; + 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 ''; + $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; + print price(price2num($temp_ht, 'MT'), 1); + print ''; + $temp_vat = $fields['vat'] * $ratiopaymentinvoice; + print price(price2num($temp_vat, 'MT'), 1); + //print price($fields['vat']); + print '
    diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index 943c704b17f..bae45672257 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -8,7 +8,7 @@ * Copyright (C) 2013-2016 Alexandre Spangaro * Copyright (C) 2014 Juanjo Menent * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2018-2020 Frédéric France + * Copyright (C) 2018-2021 Frédéric France * Copyright (C) 2019 Josep Lluís Amador * Copyright (C) 2020 Open-Dsi * @@ -71,24 +71,26 @@ $socialnetworks = getArrayOfSocialNetworks(); $object->getCanvas($id); $objcanvas = null; $canvas = (!empty($object->canvas) ? $object->canvas : GETPOST("canvas")); -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('contact', 'contactcard', $canvas); } // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', 0); // If we create a contact with no company (shared contacts), no check on write permission // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('contactcard', 'globalcard')); -if ($id > 0) $object->fetch($id); +if ($id > 0) { + $object->fetch($id); +} -if (!($object->id > 0) && $action == 'view') -{ +if (!($object->id > 0) && $action == 'view') { $langs->load("errors"); print($langs->trans('ErrorRecordNotFound')); exit; @@ -100,36 +102,32 @@ if (!($object->id > 0) && $action == 'view') $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)) -{ +if (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // Creation utilisateur depuis contact - if ($action == 'confirm_create_user' && $confirm == 'yes' && $user->rights->user->user->creer) - { + if ($action == 'confirm_create_user' && $confirm == 'yes' && $user->rights->user->user->creer) { // Recuperation contact actuel $result = $object->fetch($id); - if ($result > 0) - { + if ($result > 0) { $db->begin(); // Creation user $nuser = new User($db); $result = $nuser->create_from_contact($object, GETPOST("login")); // Do not use GETPOST(alpha) - if ($result > 0) - { + if ($result > 0) { $result2 = $nuser->setPassword($user, GETPOST("password"), 0, 0, 1); // Do not use GETPOST(alpha) - if ($result2) - { + if ($result2) { $db->commit(); } else { $error = $nuser->error; $errors = $nuser->errors; @@ -146,11 +144,9 @@ if (empty($reshook)) // Confirmation desactivation - if ($action == 'disable') - { + if ($action == 'disable') { $object->fetch($id); - if ($object->setstatus(0) < 0) - { + if ($object->setstatus(0) < 0) { setEventMessages($object->error, $object->errors, 'errors'); } else { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id); @@ -159,11 +155,9 @@ if (empty($reshook)) } // Confirmation activation - if ($action == 'enable') - { + if ($action == 'enable') { $object->fetch($id); - if ($object->setstatus(1) < 0) - { + if ($object->setstatus(1) < 0) { setEventMessages($object->error, $object->errors, 'errors'); } else { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id); @@ -172,11 +166,12 @@ if (empty($reshook)) } // Add contact - if ($action == 'add' && $user->rights->societe->contact->creer) - { + if ($action == 'add' && $user->rights->societe->contact->creer) { $db->begin(); - if ($canvas) $object->canvas = $canvas; + if ($canvas) { + $object->canvas = $canvas; + } $object->entity = (GETPOSTISSET('entity') ?GETPOST('entity', 'int') : $conf->entity); $object->socid = GETPOST("socid", 'int'); @@ -221,8 +216,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) - { + if ($ret < 0) { $error++; $action = 'create'; } @@ -233,8 +227,7 @@ if (empty($reshook)) $action = 'create'; } - if (!empty($object->email) && !isValidEMail($object->email)) - { + if (!empty($object->email) && !isValidEMail($object->email)) { $langs->load("errors"); $error++; $errors[] = $langs->trans("ErrorBadEMail", GETPOST('email', 'alpha')); @@ -279,11 +272,13 @@ if (empty($reshook)) } } - if (empty($error) && $id > 0) - { + if (empty($error) && $id > 0) { $db->commit(); - if (!empty($backtopage)) $url = $backtopage; - else $url = 'card.php?id='.$id; + if (!empty($backtopage)) { + $url = $backtopage; + } else { + $url = 'card.php?id='.$id; + } header("Location: ".$url); exit; } else { @@ -291,8 +286,7 @@ if (empty($reshook)) } } - if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->societe->contact->supprimer) - { + if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->societe->contact->supprimer) { $result = $object->fetch($id); $object->oldcopy = clone $object; @@ -313,10 +307,8 @@ if (empty($reshook)) } } - if ($action == 'update' && empty($cancel) && $user->rights->societe->contact->creer) - { - if (!GETPOST("lastname", 'alpha')) - { + if ($action == 'update' && empty($cancel) && $user->rights->societe->contact->creer) { + if (!GETPOST("lastname", 'alpha')) { $error++; $errors = array($langs->trans("ErrorFieldRequired", $langs->transnoentities("Name").' / '.$langs->transnoentities("Label"))); $action = 'edit'; } @@ -327,16 +319,14 @@ if (empty($reshook)) $action = 'edit'; } - if (!empty(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL)) && !isValidEMail(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL))) - { + if (!empty(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL)) && !isValidEMail(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL))) { $langs->load("errors"); $error++; $errors[] = $langs->trans("ErrorBadEMail", GETPOST('email', 'alpha')); $action = 'edit'; } - if (!$error) - { + if (!$error) { $contactid = GETPOST("contactid", 'int'); $object->fetch($contactid); $object->fetchRoles($contactid); @@ -344,27 +334,22 @@ if (empty($reshook)) // Photo save $dir = $conf->societe->multidir_output[$object->entity]."/contact/".$object->id."/photos"; $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']); - if (GETPOST('deletephoto') && $object->photo) - { + if (GETPOST('deletephoto') && $object->photo) { $fileimg = $dir.'/'.$object->photo; $dirthumbs = $dir.'/thumbs'; dol_delete_file($fileimg); dol_delete_dir_recursive($dirthumbs); $object->photo = ''; } - if ($file_OK) - { - if (image_format_supported($_FILES['photo']['name']) > 0) - { + if ($file_OK) { + if (image_format_supported($_FILES['photo']['name']) > 0) { dol_mkdir($dir); - if (@is_dir($dir)) - { + if (@is_dir($dir)) { $newfile = $dir.'/'.dol_sanitizeFileName($_FILES['photo']['name']); $result = dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1); - if (!$result > 0) - { + if (!$result > 0) { $errors[] = "ErrorFailedToSaveFile"; } else { $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); @@ -377,8 +362,7 @@ if (empty($reshook)) $errors[] = "ErrorBadImageFormat"; } } else { - switch ($_FILES['photo']['error']) - { + switch ($_FILES['photo']['error']) { case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form $errors[] = "ErrorFileSizeTooLarge"; @@ -433,10 +417,11 @@ 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++; + } - if (!$error) - { + if (!$error) { $result = $object->update($contactid, $user); if ($result > 0) { @@ -445,8 +430,7 @@ if (empty($reshook)) $object->setCategories($categories); // Update mass emailing flag into table mailing_unsubscribe - if (GETPOSTISSET('no_email') && $object->email) - { + if (GETPOSTISSET('no_email') && $object->email) { $no_email = GETPOST('no_email', 'int'); $result=$object->setNoEmail($no_email); if ($result<0) { @@ -465,31 +449,31 @@ if (empty($reshook)) } } - if (!$error && empty($errors)) - { - if (!empty($backtopage)) - { - header("Location: ".$backtopage); - exit; - } + if (!$error && empty($errors)) { + if (!empty($backtopage)) { + header("Location: ".$backtopage); + exit; + } } } - if ($action == 'setprospectcontactlevel' && $user->rights->societe->contact->creer) - { + if ($action == 'setprospectcontactlevel' && $user->rights->societe->contact->creer) { $object->fetch($id); $object->fk_prospectlevel = GETPOST('prospect_contact_level_id', 'alpha'); $result = $object->update($object->id, $user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // set communication status - if ($action == 'setstcomm') - { + if ($action == 'setstcomm') { $object->fetch($id); $object->stcomm_id = dol_getIdFromCode($db, GETPOST('stcomm', 'alpha'), 'c_stcommcontact'); $result = $object->update($object->id, $user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Actions to send emails @@ -506,7 +490,9 @@ if (empty($reshook)) $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title = $object->lastname; +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) { + $title = $object->lastname; +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); @@ -515,24 +501,23 @@ $formcompany = new FormCompany($db); $countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; -if ($socid > 0) -{ +if ($socid > 0) { $objsoc = new Societe($db); $objsoc->fetch($socid); } -if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) -{ +if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { // ----------------------------------------- // When used with CANVAS // ----------------------------------------- - if (empty($object->error) && $id) - { - $object = new Contact($db); - $result = $object->fetch($id); - if ($result <= 0) dol_print_error('', $object->error); - } - $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates + if (empty($object->error) && $id) { + $object = new Contact($db); + $result = $object->fetch($id); + if ($result <= 0) { + dol_print_error('', $object->error); + } + } + $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates $objcanvas->display_canvas($action); // Show template } else { // ----------------------------------------- @@ -540,20 +525,17 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // ----------------------------------------- // Confirm deleting contact - if ($user->rights->societe->contact->supprimer) - { - if ($action == 'delete') - { + if ($user->rights->societe->contact->supprimer) { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id.($backtopage ? '&backtopage='.$backtopage : ''), $langs->trans("DeleteContact"), $langs->trans("ConfirmDeleteContact"), "confirm_delete", '', 0, 1); } } /* - * Onglets - */ + * Onglets + */ $head = array(); - if ($id > 0) - { + if ($id > 0) { // Si edition contact deja existant $object = new Contact($db); $res = $object->fetch($id, $user); @@ -569,21 +551,18 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); } - if ($user->rights->societe->contact->creer) - { - if ($action == 'create') - { + if ($user->rights->societe->contact->creer) { + if ($action == 'create') { /* - * Fiche en mode creation - */ + * Fiche en mode creation + */ $object->canvas = $canvas; $object->state_id = GETPOST("state_id"); // We set country_id, country_code and label for the selected country $object->country_id = $_POST["country_id"] ?GETPOST("country_id") : (empty($objsoc->country_id) ? $mysoc->country_id : $objsoc->country_id); - if ($object->country_id) - { + if ($object->country_id) { $tmparray = getCountry($object->country_id, 'all'); $object->country_code = $tmparray['code']; $object->country = $tmparray['label']; @@ -596,8 +575,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Show errors dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors); - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print "\n".''."\n"; } - if (!GETPOSTISSET("no_email") && !empty($object->email)) - { + if (!GETPOSTISSET("no_email") && !empty($object->email)) { $result=$object->getNoEmail(); if ($result<0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -793,6 +784,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ''; print ''; print ''; print ''; @@ -821,7 +815,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ''; print ''; } @@ -829,8 +823,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $parameters = array('socid' => $socid, 'objsoc' => $objsoc, 'colspan' => ' colspan="3"', 'cols' => 3); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } @@ -846,8 +839,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Date To Birth print ''; print ''; print ''; - print ''; + $useempty = (isset($conf->global->MAILING_CONTACT_DEFAULT_BULK_STATUS) && ($conf->global->MAILING_CONTACT_DEFAULT_BULK_STATUS == -1)); + print ''; print ''; } @@ -1086,7 +1073,10 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ''; print ''; print ''; print ''; } elseif (!empty($object->socialnetworks[$key])) { @@ -1145,36 +1135,31 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $parameters = array('colspan' => ' colspan="3"', 'cols'=> '3'); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } $object->load_ref_elements(); - if (!empty($conf->commande->enabled)) - { + if (!empty($conf->commande->enabled)) { print ''; } - if (!empty($conf->propal->enabled)) - { + if (!empty($conf->propal->enabled)) { print ''; } - if (!empty($conf->contrat->enabled)) - { + if (!empty($conf->contrat->enabled)) { print ''; } - if (!empty($conf->facture->enabled)) - { + if (!empty($conf->facture->enabled)) { print ''; @@ -1182,12 +1167,13 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Login Dolibarr print ''; // Photo @@ -1199,7 +1185,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print "
    \n"; } print '
    '; + if (!empty($value['icon'])) { + print ''; + } print ''; print '
    '.$langs->trans("ContactByDefaultFor").''; $contactType = $object->listeTypeContacts('external', '', 1); - print $form->multiselectarray('roles', $contactType); + print $form->multiselectarray('roles', $contactType, array(), 0, 0, 'minwidth500'); print '
    '; $form = new Form($db); - if ($object->birthday) - { + if ($object->birthday) { print $form->selectDate($object->birthday, 'birthday', 0, 0, 0, "perso", 1, 0); } else { print $form->selectDate('', 'birthday', 0, 0, 1, "perso", 1, 0); @@ -855,8 +847,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ': '; - if ($object->birthday_alert) - { + if ($object->birthday_alert) { print ''; } else { print ''; @@ -870,8 +861,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '
    '; print ''; - if (!empty($backtopage)) - { + if (!empty($backtopage)) { print '     '; print ''; } else { @@ -883,12 +873,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ""; } elseif ($action == 'edit' && !empty($id)) { /* - * Fiche en mode edition - */ + * Fiche en mode edition + */ // We set country_id, and country_code label of the chosen country - if (GETPOSTISSET("country_id") || $object->country_id) - { + if (GETPOSTISSET("country_id") || $object->country_id) { $tmparray = getCountry($object->country_id, 'all'); $object->country_code = $tmparray['code']; $object->country = $tmparray['label']; @@ -900,8 +889,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Show errors dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors); - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print "\n".''."\n"; } - if (!GETPOSTISSET("no_email") && !empty($object->email)) - { + if (!GETPOSTISSET("no_email") && !empty($object->email)) { $result=$object->getNoEmail(); if ($result<0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -1076,7 +1062,8 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } print '
    '.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ? GETPOST("no_email", 'int') : $object->no_email), 1, false, ($conf->global->MAILING_CONTACT_DEFAULT_BULK_STATUS==-1)).''.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ? GETPOST("no_email", 'int') : $object->no_email), 1, false, $useempty).'
    '; - print ''; + if (!empty($value['icon'])) { + print ''; + } + print ''; print '
    '.$langs->trans("ContactForOrders").''; print $object->ref_commande ? $object->ref_commande : $langs->trans("NoContactForAnyOrder"); print '
    '.$langs->trans("ContactForProposals").''; print $object->ref_propal ? $object->ref_propal : $langs->trans("NoContactForAnyProposal"); print '
    '.$langs->trans("ContactForContracts").''; print $object->ref_contrat ? $object->ref_contrat : $langs->trans("NoContactForAnyContract"); print '
    '.$langs->trans("ContactForInvoices").''; print $object->ref_facturation ? $object->ref_facturation : $langs->trans("NoContactForAnyInvoice"); print '
    '.$langs->trans("DolibarrLogin").''; - if ($object->user_id) - { + if ($object->user_id) { $dolibarr_user = new User($db); $result = $dolibarr_user->fetch($object->user_id); print $dolibarr_user->getLoginUrl(1); - } else print $langs->trans("NoDolibarrAccess"); + } else { + print $langs->trans("NoDolibarrAccess"); + } print '
    '; - if ($object->photo) print ''; + if ($object->photo) { + print ''; + } //print ''; print ''; print '
    '.$langs->trans("Delete").'

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

    '.$langs->trans("PhotoFile").'
    '; @@ -1226,8 +1214,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $action = 'presend'; } - if (!empty($id) && $action != 'edit' && $action != 'create') - { + if (!empty($id) && $action != 'edit' && $action != 'create') { $objsoc = new Societe($db); // View mode @@ -1237,15 +1224,13 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print dol_get_fiche_head($head, 'card', $title, -1, 'contact'); - if ($action == 'create_user') - { + if ($action == 'create_user') { // Full firstname and lastname separated with a dot : firstname.lastname include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $login = dol_buildlogin($object->lastname, $object->firstname); $generated_password = ''; - if (!$ldap_sid) // TODO ldap_sid ? - { + if (!$ldap_sid) { // TODO ldap_sid ? require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; $generated_password = getRandomPassword(false); } @@ -1258,10 +1243,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) //array('label' => $form->textwithpicto($langs->trans("Type"),$langs->trans("InternalExternalDesc")), 'type' => 'select', 'name' => 'intern', 'default' => 1, 'values' => array(0=>$langs->trans('Internal'),1=>$langs->trans('External'))) ); $text = $langs->trans("ConfirmCreateContact").'
    '; - if (!empty($conf->societe->enabled)) - { - if ($object->socid > 0) $text .= $langs->trans("UserWillBeExternalUser"); - else $text .= $langs->trans("UserWillBeInternalUser"); + if (!empty($conf->societe->enabled)) { + if ($object->socid > 0) { + $text .= $langs->trans("UserWillBeExternalUser"); + } else { + $text .= $langs->trans("UserWillBeInternalUser"); + } } print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("CreateDolibarrLogin"), $text, "confirm_create_user", $formquestion, 'yes'); } @@ -1269,13 +1256,15 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
    '; - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $objsoc->fetch($object->socid); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '; - if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1, 'contact'); - else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + if ($objsoc->id > 0) { + $morehtmlref .= $objsoc->getNomUrl(1, 'contact'); + } else { + $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + } } $morehtmlref .= '
    '; @@ -1297,16 +1286,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '
    '.$langs->trans("PostOrFunction").''.$object->poste.'
    '.$langs->trans("NbOfEMailingsSend").''.$object->getNbOfEMailings().'
    '; + if ($action != 'editlevel' && $user->rights->societe->contact->creer) { + print ''; + } print '
    '; print $langs->trans('ProspectLevel'); print ''; - if ($action != 'editlevel' && $user->rights->societe->contact->creer) print 'id.'">'.img_edit($langs->trans('Modify'), 1).'id.'">'.img_edit($langs->trans('Modify'), 1).'
    '; print '
    '; if ($action == 'editlevel') { @@ -1354,8 +1342,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '
    '; foreach ($object->cacheprospectstatus as $key => $val) { $titlealt = 'default'; - if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt = $val['label']; - if ($object->stcomm_id != $val['id']) print ''.img_action($titlealt, $val['code'], $val['picto']).''; + if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) { + $titlealt = $val['label']; + } + if ($object->stcomm_id != $val['id']) { + print ''.img_action($titlealt, $val['code'], $val['picto']).''; + } } print '
    '.$langs->trans("ContactForProposals").''; print $object->ref_propal ? $object->ref_propal : $langs->trans("NoContactForAnyProposal"); print '
    '; - if (!empty($conf->expedition->enabled)) { print $langs->trans("ContactForOrdersOrShipments"); } else print $langs->trans("ContactForOrders"); + if (!empty($conf->expedition->enabled)) { + print $langs->trans("ContactForOrdersOrShipments"); + } else { + print $langs->trans("ContactForOrders"); + } print ''; $none = $langs->trans("NoContactForAnyOrder"); - if (!empty($conf->expedition->enabled)) { $none = $langs->trans("NoContactForAnyOrderOrShipments"); } + if (!empty($conf->expedition->enabled)) { + $none = $langs->trans("NoContactForAnyOrderOrShipments"); + } print $object->ref_commande ? $object->ref_commande : $none; print '
    '.$langs->trans("ContactForContracts").''; print $object->ref_contrat ? $object->ref_contrat : $langs->trans("NoContactForAnyContract"); print '
    '.$langs->trans("ContactForInvoices").''; print $object->ref_facturation ? $object->ref_facturation : $langs->trans("NoContactForAnyInvoice"); print '
    '.$langs->trans("DolibarrLogin").''; - if ($object->user_id) - { + if ($object->user_id) { $dolibarr_user = new User($db); $result = $dolibarr_user->fetch($object->user_id); print $dolibarr_user->getLoginUrl(1); - } else print $langs->trans("NoDolibarrAccess"); + } else { + print $langs->trans("NoDolibarrAccess"); + } print '
    '; @@ -1447,16 +1442,16 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print dol_get_fiche_end(); - // Barre d'actions + /* + * Action bar + */ print '
    '; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook) && $action != 'presend') - { + if (empty($reshook) && $action != 'presend') { if (empty($user->socid)) { - if (!empty($object->email)) - { + if (!empty($object->email)) { $langs->load("mails"); print ''; } else { @@ -1465,30 +1460,25 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } } - if ($user->rights->societe->contact->creer) - { + if ($user->rights->societe->contact->creer) { print ''.$langs->trans('Modify').''; } - if (!$object->user_id && $user->rights->user->user->creer) - { + if (!$object->user_id && $user->rights->user->user->creer) { print ''.$langs->trans("CreateDolibarrLogin").''; } // Activer - if ($object->statut == 0 && $user->rights->societe->contact->creer) - { + if ($object->statut == 0 && $user->rights->societe->contact->creer) { print ''.$langs->trans("Reactivate").''; } // Desactiver - if ($object->statut == 1 && $user->rights->societe->contact->creer) - { + if ($object->statut == 1 && $user->rights->societe->contact->creer) { print ''.$langs->trans("DisableUser").''; } // Delete - if ($user->rights->societe->contact->supprimer) - { + if ($user->rights->societe->contact->supprimer) { print ''.$langs->trans('Delete').''; } } @@ -1500,8 +1490,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '
    '; print '
    '; @@ -1521,7 +1510,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Presend form $modelmail = 'contact'; $defaulttopic = 'Information'; - $diroutput = $conf->contact->dir_output; + $diroutput = $conf->societe->dir_output.'/contact/'; $trackid = 'ctc'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 1d2cb3355a5..5e0c65e1b70 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -473,40 +473,35 @@ class Contact extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."socpeople"); - if (!$error) - { + if (!$error) { $result = $this->update($this->id, $user, 1, 'add'); // This include updateRoles(), ... - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $this->db->lasterror(); } } - if (!$error) - { + if (!$error) { $result = $this->update_perso($this->id, $user, 1); // TODO Remove function update_perso, should be same than update - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $this->db->lasterror(); } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('CONTACT_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -558,13 +553,20 @@ class Contact extends CommonObject $this->town = (empty($this->town) ? '' : trim($this->town)); $this->setUpperOrLowerCase(); $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id); - if (empty($this->statut)) $this->statut = 0; - if (empty($this->civility_code) && !is_numeric($this->civility_id)) $this->civility_code = $this->civility_id; // For backward compatibility + if (empty($this->statut)) { + $this->statut = 0; + } + if (empty($this->civility_code) && !is_numeric($this->civility_id)) { + $this->civility_code = $this->civility_id; // For backward compatibility + } $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET "; - if ($this->socid > 0) $sql .= " fk_soc='".$this->db->escape($this->socid)."',"; - elseif ($this->socid == -1) $sql .= " fk_soc=null,"; + if ($this->socid > 0) { + $sql .= " fk_soc='".$this->db->escape($this->socid)."',"; + } elseif ($this->socid == -1) { + $sql .= " fk_soc=null,"; + } $sql .= " civility='".$this->db->escape($this->civility_code)."'"; $sql .= ", lastname='".$this->db->escape($this->lastname)."'"; $sql .= ", firstname='".$this->db->escape($this->firstname)."'"; @@ -586,8 +588,7 @@ class Contact extends CommonObject $sql .= ", phone_mobile = ".(isset($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null"); $sql .= ", priv = '".$this->db->escape($this->priv)."'"; $sql .= ", fk_prospectcontactlevel = '".$this->db->escape($this->fk_prospectlevel)."'"; - if (isset($this->stcomm_id)) - { + if (isset($this->stcomm_id)) { $sql .= ", fk_stcommcontact = ".($this->stcomm_id > 0 || $this->stcomm_id == -1 ? $this->stcomm_id : "0"); } $sql .= ", statut = ".$this->db->escape($this->statut); @@ -598,8 +599,7 @@ class Contact extends CommonObject dol_syslog(get_class($this)."::update", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { unset($this->country_code); unset($this->country); unset($this->state_code); @@ -608,25 +608,21 @@ class Contact extends CommonObject $action = 'update'; // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } if (!$error) { $result = $this->updateRoles(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && $this->user_id > 0) - { + if (!$error && $this->user_id > 0) { // If contact is linked to a user $tmpobj = new User($this->db); $tmpobj->fetch($this->user_id); @@ -685,14 +681,18 @@ class Contact extends CommonObject // } if ($usermustbemodified) { $result = $tmpobj->update($user, 0, 1, 1, 1); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } } } if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CONTACT_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -759,34 +759,69 @@ class Contact extends CommonObject $this->fullname = $this->getFullName($langs); // Fields - if ($this->fullname && !empty($conf->global->LDAP_CONTACT_FIELD_FULLNAME)) $info[$conf->global->LDAP_CONTACT_FIELD_FULLNAME] = $this->fullname; - if ($this->lastname && !empty($conf->global->LDAP_CONTACT_FIELD_NAME)) $info[$conf->global->LDAP_CONTACT_FIELD_NAME] = $this->lastname; - if ($this->firstname && !empty($conf->global->LDAP_CONTACT_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_CONTACT_FIELD_FIRSTNAME] = $this->firstname; + if ($this->fullname && !empty($conf->global->LDAP_CONTACT_FIELD_FULLNAME)) { + $info[$conf->global->LDAP_CONTACT_FIELD_FULLNAME] = $this->fullname; + } + if ($this->lastname && !empty($conf->global->LDAP_CONTACT_FIELD_NAME)) { + $info[$conf->global->LDAP_CONTACT_FIELD_NAME] = $this->lastname; + } + if ($this->firstname && !empty($conf->global->LDAP_CONTACT_FIELD_FIRSTNAME)) { + $info[$conf->global->LDAP_CONTACT_FIELD_FIRSTNAME] = $this->firstname; + } - if ($this->poste) $info["title"] = $this->poste; + if ($this->poste) { + $info["title"] = $this->poste; + } if ($this->socid > 0) { $soc = new Societe($this->db); $soc->fetch($this->socid); $info[$conf->global->LDAP_CONTACT_FIELD_COMPANY] = $soc->name; - if ($soc->client == 1) $info["businessCategory"] = "Customers"; - if ($soc->client == 2) $info["businessCategory"] = "Prospects"; - if ($soc->fournisseur == 1) $info["businessCategory"] = "Suppliers"; + if ($soc->client == 1) { + $info["businessCategory"] = "Customers"; + } + if ($soc->client == 2) { + $info["businessCategory"] = "Prospects"; + } + if ($soc->fournisseur == 1) { + $info["businessCategory"] = "Suppliers"; + } + } + if ($this->address && !empty($conf->global->LDAP_CONTACT_FIELD_ADDRESS)) { + $info[$conf->global->LDAP_CONTACT_FIELD_ADDRESS] = $this->address; + } + if ($this->zip && !empty($conf->global->LDAP_CONTACT_FIELD_ZIP)) { + $info[$conf->global->LDAP_CONTACT_FIELD_ZIP] = $this->zip; + } + if ($this->town && !empty($conf->global->LDAP_CONTACT_FIELD_TOWN)) { + $info[$conf->global->LDAP_CONTACT_FIELD_TOWN] = $this->town; + } + if ($this->country_code && !empty($conf->global->LDAP_CONTACT_FIELD_COUNTRY)) { + $info[$conf->global->LDAP_CONTACT_FIELD_COUNTRY] = $this->country_code; + } + if ($this->phone_pro && !empty($conf->global->LDAP_CONTACT_FIELD_PHONE)) { + $info[$conf->global->LDAP_CONTACT_FIELD_PHONE] = $this->phone_pro; + } + if ($this->phone_perso && !empty($conf->global->LDAP_CONTACT_FIELD_HOMEPHONE)) { + $info[$conf->global->LDAP_CONTACT_FIELD_HOMEPHONE] = $this->phone_perso; + } + if ($this->phone_mobile && !empty($conf->global->LDAP_CONTACT_FIELD_MOBILE)) { + $info[$conf->global->LDAP_CONTACT_FIELD_MOBILE] = $this->phone_mobile; + } + if ($this->fax && !empty($conf->global->LDAP_CONTACT_FIELD_FAX)) { + $info[$conf->global->LDAP_CONTACT_FIELD_FAX] = $this->fax; + } + if ($this->skype && !empty($conf->global->LDAP_CONTACT_FIELD_SKYPE)) { + $info[$conf->global->LDAP_CONTACT_FIELD_SKYPE] = $this->skype; + } + if ($this->note_private && !empty($conf->global->LDAP_CONTACT_FIELD_DESCRIPTION)) { + $info[$conf->global->LDAP_CONTACT_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2); + } + if ($this->email && !empty($conf->global->LDAP_CONTACT_FIELD_MAIL)) { + $info[$conf->global->LDAP_CONTACT_FIELD_MAIL] = $this->email; } - if ($this->address && !empty($conf->global->LDAP_CONTACT_FIELD_ADDRESS)) $info[$conf->global->LDAP_CONTACT_FIELD_ADDRESS] = $this->address; - if ($this->zip && !empty($conf->global->LDAP_CONTACT_FIELD_ZIP)) $info[$conf->global->LDAP_CONTACT_FIELD_ZIP] = $this->zip; - if ($this->town && !empty($conf->global->LDAP_CONTACT_FIELD_TOWN)) $info[$conf->global->LDAP_CONTACT_FIELD_TOWN] = $this->town; - if ($this->country_code && !empty($conf->global->LDAP_CONTACT_FIELD_COUNTRY)) $info[$conf->global->LDAP_CONTACT_FIELD_COUNTRY] = $this->country_code; - if ($this->phone_pro && !empty($conf->global->LDAP_CONTACT_FIELD_PHONE)) $info[$conf->global->LDAP_CONTACT_FIELD_PHONE] = $this->phone_pro; - if ($this->phone_perso && !empty($conf->global->LDAP_CONTACT_FIELD_HOMEPHONE)) $info[$conf->global->LDAP_CONTACT_FIELD_HOMEPHONE] = $this->phone_perso; - if ($this->phone_mobile && !empty($conf->global->LDAP_CONTACT_FIELD_MOBILE)) $info[$conf->global->LDAP_CONTACT_FIELD_MOBILE] = $this->phone_mobile; - if ($this->fax && !empty($conf->global->LDAP_CONTACT_FIELD_FAX)) $info[$conf->global->LDAP_CONTACT_FIELD_FAX] = $this->fax; - if ($this->skype && !empty($conf->global->LDAP_CONTACT_FIELD_SKYPE)) $info[$conf->global->LDAP_CONTACT_FIELD_SKYPE] = $this->skype; - if ($this->note_private && !empty($conf->global->LDAP_CONTACT_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_CONTACT_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2); - if ($this->email && !empty($conf->global->LDAP_CONTACT_FIELD_MAIL)) $info[$conf->global->LDAP_CONTACT_FIELD_MAIL] = $this->email; - if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') - { + if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') { $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware $info['uidnumber'] = $this->id; @@ -805,8 +840,12 @@ class Contact extends CommonObject $info["phpgwContactOwner"] = $this->egroupware_id; - if ($this->email) $info["rfc822Mailbox"] = $this->email; - if ($this->phone_mobile) $info["phpgwCellTelephoneNumber"] = $this->phone_mobile; + if ($this->email) { + $info["rfc822Mailbox"] = $this->email; + } + if ($this->phone_mobile) { + $info["phpgwCellTelephoneNumber"] = $this->phone_mobile; + } } return $info; @@ -834,13 +873,14 @@ class Contact extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET"; $sql .= " birthday=".($this->birthday ? "'".$this->db->idate($this->birthday)."'" : "null"); $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null"); - if ($user) $sql .= ", fk_user_modif=".$user->id; + if ($user) { + $sql .= ", fk_user_modif=".$user->id; + } $sql .= " WHERE rowid=".$this->db->escape($id); dol_syslog(get_class($this)."::update_perso this->birthday=".$this->birthday." -", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = $this->db->lasterror(); } @@ -875,7 +915,9 @@ class Contact extends CommonObject if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CONTACT_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -906,8 +948,7 @@ class Contact extends CommonObject dol_syslog(get_class($this)."::fetch id=".$id." ref_ext=".$ref_ext." email=".$email, LOG_DEBUG); - if (empty($id) && empty($ref_ext) && empty($email)) - { + if (empty($id) && empty($ref_ext) && empty($email)) { $this->error = 'BadParameter'; return -1; } @@ -936,8 +977,9 @@ class Contact extends CommonObject $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON c.rowid = u.fk_socpeople"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcommcontact as st ON c.fk_stcommcontact = st.id'; - if ($id) $sql .= " WHERE c.rowid = ".((int) $id); - else { + if ($id) { + $sql .= " WHERE c.rowid = ".((int) $id); + } else { $sql .= " WHERE c.entity IN (".getEntity($this->element).")"; if ($ref_ext) { $sql .= " AND c.ref_ext = '".$this->db->escape($ref_ext)."'"; @@ -948,17 +990,14 @@ class Contact extends CommonObject } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num > 1) - { + if ($num > 1) { $this->error = 'Fetch found several records. Rename one of contact to avoid duplicate.'; dol_syslog($this->error, LOG_ERR); return 2; - } elseif ($num) // $num = 1 - { + } elseif ($num) { // $num = 1 $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -1030,10 +1069,8 @@ class Contact extends CommonObject $sql .= " WHERE u.fk_socpeople = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $uobj = $this->db->fetch_object($resql); $this->user_id = $uobj->rowid; @@ -1049,17 +1086,14 @@ class Contact extends CommonObject $this->fetch_optionals(); // Load also alerts of this user - if ($user) - { + if ($user) { $sql = "SELECT fk_user"; $sql .= " FROM ".MAIN_DB_PREFIX."user_alert"; $sql .= " WHERE fk_user = ".$user->id." AND fk_contact = ".$this->db->escape($id); $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->birthday_alert = 1; @@ -1102,11 +1136,9 @@ class Contact extends CommonObject { unset($this->gender); - if (in_array($this->civility_id, array('MR')) || in_array($this->civility_code, array('MR'))) - { + if (in_array($this->civility_id, array('MR')) || in_array($this->civility_code, array('MR'))) { $this->gender = 'man'; - } elseif (in_array($this->civility_id, array('MME', 'MLE')) || in_array($this->civility_code, array('MME', 'MLE'))) - { + } elseif (in_array($this->civility_id, array('MME', 'MLE')) || in_array($this->civility_code, array('MME', 'MLE'))) { $this->gender = 'woman'; } } @@ -1135,16 +1167,18 @@ class Contact extends CommonObject dol_syslog(get_class($this)."::load_ref_elements", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { - if ($obj->nb) - { - if ($obj->element == 'facture') $this->ref_facturation = $obj->nb; - elseif ($obj->element == 'contrat') $this->ref_contrat = $obj->nb; - elseif ($obj->element == 'commande') $this->ref_commande = $obj->nb; - elseif ($obj->element == 'propal') $this->ref_propal = $obj->nb; + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { + if ($obj->nb) { + if ($obj->element == 'facture') { + $this->ref_facturation = $obj->nb; + } elseif ($obj->element == 'contrat') { + $this->ref_contrat = $obj->nb; + } elseif ($obj->element == 'commande') { + $this->ref_commande = $obj->nb; + } elseif ($obj->element == 'propal') { + $this->ref_propal = $obj->nb; + } } } $this->db->free($resql); @@ -1169,8 +1203,7 @@ class Contact extends CommonObject $this->db->begin(); - if (!$error) - { + if (!$error) { // Get all rowid of element_contact linked to a type that is link to llx_socpeople $sql = "SELECT ec.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."element_contact ec,"; @@ -1180,21 +1213,18 @@ class Contact extends CommonObject $sql .= " AND tc.source='external'"; dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num && !$error) - { + while ($i < $num && !$error) { $obj = $this->db->fetch_object($resql); $sqldel = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; $sqldel .= " WHERE rowid = ".$obj->rowid; dol_syslog(__METHOD__, LOG_DEBUG); $result = $this->db->query($sqldel); - if (!$result) - { + if (!$result) { $error++; $this->error = $this->db->error().' sql='.$sqldel; } @@ -1207,56 +1237,48 @@ class Contact extends CommonObject } } - if (!$error) - { + if (!$error) { // Remove Roles $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople = ".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error .= $this->db->lasterror(); $errorflag = -1; } } - if (!$error) - { + if (!$error) { // Remove Roles $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople = ".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error .= $this->db->lasterror(); $errorflag = -1; } } - if (!$error) - { + if (!$error) { // Remove category $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_contact WHERE fk_socpeople = ".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error .= $this->db->lasterror(); $errorflag = -1; } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."socpeople"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(__METHOD__, LOG_DEBUG); $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $error++; $this->error = $this->db->error().' sql='.$sql; } @@ -1266,19 +1288,21 @@ class Contact extends CommonObject if (!$error) { // For avoid conflicts if trigger used $result = $this->deleteExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CONTACT_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1303,10 +1327,8 @@ class Contact extends CommonObject $sql .= " WHERE c.rowid = ".$this->db->escape($id); $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; @@ -1346,8 +1368,7 @@ class Contact extends CommonObject $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $nb = $obj->nb; @@ -1377,8 +1398,7 @@ class Contact extends CommonObject $result = ''; $label = ''; - if (!empty($this->photo) && class_exists('Form')) - { + if (!empty($this->photo) && class_exists('Form')) { $label .= '
    '; $label .= Form::showphoto('contact', $this, 0, 40, 0, '', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip. $label .= '
    '; @@ -1388,67 +1408,87 @@ class Contact extends CommonObject $label .= ' '.$this->getLibStatut(4); $label .= '
    '.$langs->trans("Name").': '.$this->getFullName($langs); //if ($this->civility_id) $label.= '
    ' . $langs->trans("Civility") . ': '.$this->civility_id; // TODO Translate cibilty_id code - if (!empty($this->poste)) $label .= '
    '.$langs->trans("Poste").': '.$this->poste; + if (!empty($this->poste)) { + $label .= '
    '.$langs->trans("Poste").': '.$this->poste; + } $label .= '
    '.$langs->trans("EMail").': '.$this->email; $phonelist = array(); $country_code = empty($this->country_code) ? '': $this->country_code; - if ($this->phone_pro) $phonelist[] = dol_print_phone($this->phone_pro, $country_code, $this->id, 0, '', ' ', 'phone'); - if ($this->phone_mobile) $phonelist[] = dol_print_phone($this->phone_mobile, $country_code, $this->id, 0, '', ' ', 'mobile'); - if ($this->phone_perso) $phonelist[] = dol_print_phone($this->phone_perso, $country_code, $this->id, 0, '', ' ', 'phone'); + if ($this->phone_pro) { + $phonelist[] = dol_print_phone($this->phone_pro, $country_code, $this->id, 0, '', ' ', 'phone'); + } + if ($this->phone_mobile) { + $phonelist[] = dol_print_phone($this->phone_mobile, $country_code, $this->id, 0, '', ' ', 'mobile'); + } + if ($this->phone_perso) { + $phonelist[] = dol_print_phone($this->phone_perso, $country_code, $this->id, 0, '', ' ', 'phone'); + } $label .= '
    '.$langs->trans("Phone").': '.implode(' ', $phonelist); $label .= '
    '.$langs->trans("Address").': '.dol_format_address($this, 1, ' ', $langs); $url = DOL_URL_ROOT.'/contact/card.php?id='.$this->id; - if ($option !== 'nolink') - { + 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'; + } } $url .= $moreparam; $linkclose = ""; if (empty($notooltip)) { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowContact"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; - /* - $hookmanager->initHooks(array('contactdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ + /* + $hookmanager->initHooks(array('contactdao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $linkclose = $hookmanager->resPrint; + */ } $linkstart = ''; $linkend = ''; - if ($option == 'xxx') - { + if ($option == 'xxx') { $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->getFullName($langs), $maxlen) : $this->getFullName($langs)); + if ($withpicto) { + if ($withpicto == -2) { + $result .= ''.Form::showphoto('contact', $this, 0, 0, 0, 'userphoto'.($withpicto == -3 ? 'small' : ''), 'mini', 0, 1).''; + } else { + $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 && $withpicto != -2) { + $result .= ($maxlen ?dol_trunc($this->getFullName($langs), $maxlen) : $this->getFullName($langs)); + } $result .= $linkend; global $action; $hookmanager->initHooks(array('contactdao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -1463,7 +1503,9 @@ class Contact extends CommonObject global $langs; $code = ($this->civility_code ? $this->civility_code : (!empty($this->civility_id) ? $this->civility : (!empty($this->civilite) ? $this->civilite : ''))); - if (empty($code)) return ''; + if (empty($code)) { + return ''; + } $langs->load("dict"); return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code); @@ -1507,7 +1549,9 @@ class Contact extends CommonObject ); $statusType = 'status4'; - if ($status == 0 || $status == 5) $statusType = 'status5'; + if ($status == 0 || $status == 5) { + $statusType = 'status5'; + } $label = $langs->trans($labelStatus[$status]); $labelshort = $langs->trans($labelStatusShort[$status]); @@ -1527,8 +1571,11 @@ class Contact extends CommonObject { // phpcs:enable global $langs; - if ($status == '1') return $langs->trans('ContactPrivate'); - else return $langs->trans('ContactPublic'); + if ($status == '1') { + return $langs->trans('ContactPrivate'); + } else { + return $langs->trans('ContactPublic'); + } } @@ -1547,7 +1594,9 @@ class Contact extends CommonObject $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) $socid = $obj->rowid; + if ($obj) { + $socid = $obj->rowid; + } } // Initialise parameters @@ -1592,8 +1641,11 @@ class Contact extends CommonObject $error = 0; // Check parameters - if ($this->statut == $status) return 0; - else $this->statut = $status; + if ($this->statut == $status) { + return 0; + } else { + $this->statut = $status; + } $this->db->begin(); @@ -1604,16 +1656,16 @@ class Contact extends CommonObject $result = $this->db->query($sql); dol_syslog(get_class($this)."::setstatus", LOG_DEBUG); - if ($result) - { + if ($result) { // Call trigger $result = $this->call_trigger('CONTACT_ENABLEDISABLE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if ($error) - { + if ($error) { $this->db->rollback(); return -$error; } else { @@ -1725,12 +1777,10 @@ class Contact extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $tab[] = array('fk_socpeople'=>$obj->id, 'type_contact'=>$obj->fk_c_type_contact); @@ -1758,11 +1808,13 @@ class Contact extends CommonObject $error = 0; - if (!isset($this->roles)) return; // Avoid to loose roles when property not set + if (!isset($this->roles)) { + return; // Avoid to loose roles when property not set + } $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople=".$this->id." AND entity IN (".getEntity("societe_contact").")"; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople=".((int) $this->id)." AND entity IN (".getEntity("societe_contact").")"; $result = $this->db->query($sql); if (!$result) { @@ -1800,8 +1852,7 @@ class Contact extends CommonObject $sql .= ")"; $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $this->errors[] = $this->db->lasterror().' sql='.$sql; $error++; } @@ -1830,12 +1881,13 @@ class Contact extends CommonObject global $langs; $sql = "SELECT id, code, libelle as label, picto FROM ".MAIN_DB_PREFIX."c_stcommcontact"; - if ($active >= 0) $sql .= " WHERE active = ".$active; + if ($active >= 0) { + $sql .= " WHERE active = ".$active; + } $resql = $this->db->query($sql); $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $this->cacheprospectstatus[$obj->id] = array('id' => $obj->id, 'code' => $obj->code, 'label' => ($langs->trans("ST_".strtoupper($obj->code)) == "ST_".strtoupper($obj->code)) ? $obj->label : $langs->trans("ST_".strtoupper($obj->code)), 'picto' => $obj->picto); $i++; @@ -1865,8 +1917,7 @@ class Contact extends CommonObject $lib = $langs->trans("ProspectLevel".$fk_prospectlevel); // If lib not found in language file, we get label from cache/databse - if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) - { + if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) { $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label'); } return $lib; @@ -1915,36 +1966,48 @@ class Contact extends CommonObject global $langs; $langs->load('customers'); - if ($mode == 2) - { - if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1"); - elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0"); - elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1"); - elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2"); - elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3"); - else { + if ($mode == 2) { + if ($statut == '-1' || $statut == 'ST_NO') { + return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1"); + } elseif ($statut == '0' || $statut == 'ST_NEVER') { + return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0"); + } elseif ($statut == '1' || $statut == 'ST_TODO') { + return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1"); + } elseif ($statut == '2' || $statut == 'ST_PEND') { + return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2"); + } elseif ($statut == '3' || $statut == 'ST_DONE') { + return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3"); + } else { return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label); } } - if ($mode == 3) - { - if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto); - elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto); - elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto); - elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto); - elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto); - else { + if ($mode == 3) { + if ($statut == '-1' || $statut == 'ST_NO') { + return img_action($langs->trans("StatusProspect-1"), -1, $picto); + } elseif ($statut == '0' || $statut == 'ST_NEVER') { + return img_action($langs->trans("StatusProspect0"), 0, $picto); + } elseif ($statut == '1' || $statut == 'ST_TODO') { + return img_action($langs->trans("StatusProspect1"), 1, $picto); + } elseif ($statut == '2' || $statut == 'ST_PEND') { + return img_action($langs->trans("StatusProspect2"), 2, $picto); + } elseif ($statut == '3' || $statut == 'ST_DONE') { + return img_action($langs->trans("StatusProspect3"), 3, $picto); + } else { return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto); } } - if ($mode == 4) - { - if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1"); - elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0"); - elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1"); - elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2"); - elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3"); - else { + if ($mode == 4) { + if ($statut == '-1' || $statut == 'ST_NO') { + return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1"); + } elseif ($statut == '0' || $statut == 'ST_NEVER') { + return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0"); + } elseif ($statut == '1' || $statut == 'ST_TODO') { + return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1"); + } elseif ($statut == '2' || $statut == 'ST_PEND') { + return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2"); + } elseif ($statut == '3' || $statut == 'ST_DONE') { + return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3"); + } else { return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label); } } @@ -1964,24 +2027,19 @@ class Contact extends CommonObject $error = 0; // Update mass emailing flag into table mailing_unsubscribe - if ($this->email) - { + if ($this->email) { $this->db->begin(); - if ($no_email) - { + if ($no_email) { $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing', 0).") AND email = '".$this->db->escape($this->email)."'"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $noemail = $obj->nb; - if (empty($noemail)) - { + if (empty($noemail)) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe(email, entity, date_creat) VALUES ('".$this->db->escape($this->email)."', ".$this->db->escape(getEntity('mailing', 0)).", '".$this->db->idate(dol_now())."')"; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = $this->db->lasterror(); $this->errors[] = $this->error; @@ -1995,8 +2053,7 @@ class Contact extends CommonObject } else { $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity = ".$this->db->escape(getEntity('mailing', 0)); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = $this->db->lasterror(); $this->errors[] = $this->error; @@ -2024,8 +2081,7 @@ class Contact extends CommonObject */ public function getNoEmail() { - if ($this->email) - { + if ($this->email) { $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'"; $resql = $this->db->query($sql); if ($resql) { diff --git a/htdocs/contact/consumption.php b/htdocs/contact/consumption.php index da00374cc2a..1e0f5b06094 100644 --- a/htdocs/contact/consumption.php +++ b/htdocs/contact/consumption.php @@ -37,8 +37,12 @@ $id = GETPOST('id', 'int'); $result = restrictedArea($user, 'contact', $id, 'socpeople&societe'); $object = new Contact($db); -if ($id > 0) $object->fetch($id); -if (empty($object->thirdparty)) $object->fetch_thirdparty(); +if ($id > 0) { + $object->fetch($id); +} +if (empty($object->thirdparty)) { + $object->fetch_thirdparty(); +} $socid = $object->thirdparty->id; // Sort & Order fields @@ -46,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 = 'DESC'; -if (!$sortfield) $sortfield = 'dateprint'; +if (!$sortorder) { + $sortorder = 'DESC'; +} +if (!$sortfield) { + $sortfield = 'dateprint'; +} // Search fields $sref = GETPOST("sref"); @@ -60,8 +70,7 @@ $month = GETPOST('month', 'int'); $year = GETPOST('year', 'int'); // Clean up on purge search criteria ? -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $sref = ''; $sprod_fulldescr = ''; $year = ''; @@ -84,7 +93,9 @@ $hookmanager->initHooks(array('consumptioncontact')); $parameters = array('id'=>$id); $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'); +} /* @@ -99,8 +110,7 @@ $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("C $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if (empty($id)) -{ +if (empty($id)) { dol_print_error($db); exit; } @@ -111,13 +121,15 @@ print dol_get_fiche_head($head, 'consumption', $langs->trans("ContactsAddresses" $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
    '; -if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) -{ +if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $objsoc->fetch($socid); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '; - if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1, 'contact'); - else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + if ($objsoc->id > 0) { + $morehtmlref .= $objsoc->getNomUrl(1, 'contact'); + } else { + $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + } } $morehtmlref .= '
    '; @@ -133,22 +145,34 @@ print '
    '.$langs->trans("UserTitle").''; print $object->getCivilityLabel(); print '
    '; @@ -415,8 +460,7 @@ if ($sql_select) // Status print ''; - if ($type_element == 'contract') - { + if ($type_element == 'contract') { print $documentstaticline->getLibStatut(2); } else { print $documentstatic->getLibStatut(2); @@ -429,8 +473,7 @@ if ($sql_select) $text = ''; $description = ''; $type = 0; // Code to show product duplicated from commonobject->printObjectLine - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { $product_static = new Product($db); $product_static->type = $objp->fk_product_type; @@ -441,20 +484,21 @@ if ($sql_select) } // Product - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { // Define output language - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $prod = new Product($db); $prod->fetch($objp->fk_product); $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) $newlang = $object->default_lang; - if (!empty($newlang)) - { + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if (empty($newlang)) { + $newlang = $object->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -468,42 +512,42 @@ if ($sql_select) $description = (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($objp->description)); } - if (($objp->info_bits & 2) == 2) - { + if (($objp->info_bits & 2) == 2) { print ''; $txt = ''; print img_object($langs->trans("ShowReduc"), 'reduc').' '; - if ($objp->description == '(DEPOSIT)') $txt = $langs->trans("Deposit"); - elseif ($objp->description == '(EXCESS RECEIVED)') $txt = $langs->trans("ExcessReceived"); - elseif ($objp->description == '(EXCESS PAID)') $txt = $langs->trans("ExcessPaid"); + if ($objp->description == '(DEPOSIT)') { + $txt = $langs->trans("Deposit"); + } elseif ($objp->description == '(EXCESS RECEIVED)') { + $txt = $langs->trans("ExcessReceived"); + } elseif ($objp->description == '(EXCESS PAID)') { + $txt = $langs->trans("ExcessPaid"); + } //else $txt=$langs->trans("Discount"); print $txt; print ''; - if ($objp->description) - { - if ($objp->description == '(CREDIT_NOTE)' && $objp->fk_remise_except > 0) - { + if ($objp->description) { + if ($objp->description == '(CREDIT_NOTE)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); echo ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0)); } - if ($objp->description == '(EXCESS RECEIVED)' && $objp->fk_remise_except > 0) - { + if ($objp->description == '(EXCESS RECEIVED)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); echo ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0)); - } elseif ($objp->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) - { + } elseif ($objp->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); echo ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0)); - } elseif ($objp->description == '(DEPOSIT)' && $objp->fk_remise_except > 0) - { + } elseif ($objp->description == '(DEPOSIT)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); echo ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0)); // Add date of deposit - if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec).')'; + if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) { + echo ' ('.dol_print_date($discount->datec).')'; + } } else { echo ($txt ? ' - ' : '').dol_htmlentitiesbr($objp->description); } @@ -516,15 +560,16 @@ if ($sql_select) echo get_date_range($objp->date_start, $objp->date_end); // Add description in form - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { print (!empty($objp->description) && $objp->description != $objp->product_label) ? '
    '.dol_htmlentitiesbr($objp->description) : ''; } } else { - if (!empty($objp->label) || !empty($objp->description)) - { - if ($type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if (!empty($objp->label) || !empty($objp->description)) { + if ($type == 1) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($objp->label)) { $text .= ' '.$objp->label.''; diff --git a/htdocs/contact/document.php b/htdocs/contact/document.php index 2065ab772e6..cbe1d1a6194 100644 --- a/htdocs/contact/document.php +++ b/htdocs/contact/document.php @@ -1,7 +1,7 @@ - * Copyright (C) 2015 Frederic France - * Copyright (C) 2017 Regis Houssin +/* Copyright (C) 2014 Alexandre Spangaro + * Copyright (C) 2015-2021 Frederic France + * Copyright (C) 2017 Regis Houssin * * 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,15 +43,16 @@ $object = new Contact($db); $object->getCanvas($id); $objcanvas = null; $canvas = (!empty($object->canvas) ? $object->canvas : GETPOST("canvas")); -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('contact', 'contactcard', $canvas); } // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', 0); // If we create a contact with no company (shared contacts), no check on write permission // Get parameters @@ -59,18 +60,30 @@ $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 (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; } -if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; } +if (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { + $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; +} +if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { + $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; +} -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} -if ($id > 0) $object->fetch($id); +if ($id > 0) { + $object->fetch($id); +} $upload_dir = $conf->societe->multidir_output[$object->entity].'/contact/'.dol_sanitizeFileName($object->ref); $modulepart = 'contact'; @@ -90,12 +103,13 @@ include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; $form = new Form($db); $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title = $object->lastname; +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) { + $title = $object->lastname; +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; -llxHeader('', $title, $helpurl); +llxHeader('', $title, $help_url); -if ($object->id) -{ +if ($object->id) { $head = contact_prepare_head($object); $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); @@ -105,22 +119,23 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
    '; - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $objsoc = new Societe($db); $objsoc->fetch($object->socid); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '; - if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1); - else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + if ($objsoc->id > 0) { + $morehtmlref .= $objsoc->getNomUrl(1); + } else { + $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + } } $morehtmlref .= '
    '; @@ -133,23 +148,23 @@ if ($object->id) // Company /* - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { - if ($object->socid > 0) - { - $objsoc = new Societe($db); - $objsoc->fetch($object->socid); + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) + { + if ($object->socid > 0) + { + $objsoc = new Societe($db); + $objsoc->fetch($object->socid); - print '
    '.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).'
    '.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).'
    '.$langs->trans("ThirdParty").''; - print $langs->trans("ContactNotLinkedToCompany"); - print '
    '.$langs->trans("ThirdParty").''; + print $langs->trans("ContactNotLinkedToCompany"); + print '
    '.$langs->trans("UserTitle").''; diff --git a/htdocs/contact/info.php b/htdocs/contact/info.php index c39c20d3d25..4cea1cae85b 100644 --- a/htdocs/contact/info.php +++ b/htdocs/contact/info.php @@ -34,7 +34,9 @@ $langs->load("companies"); // Security check $id = GETPOST("id", 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe'); $object = new Contact($db); @@ -51,8 +53,7 @@ $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("C llxHeader('', $title, 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Módulo_Empresas'); -if ($id > 0) -{ +if ($id > 0) { $result = $object->fetch($id, $user); $object->info($id); diff --git a/htdocs/contact/ldap.php b/htdocs/contact/ldap.php index 78934c5857e..6677a7b17d7 100644 --- a/htdocs/contact/ldap.php +++ b/htdocs/contact/ldap.php @@ -36,12 +36,13 @@ $action = GETPOST('action', 'aZ09'); // Security check $id = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe'); $object = new Contact($db); -if ($id > 0) -{ +if ($id > 0) { $object->fetch($id, $user); } @@ -50,8 +51,7 @@ if ($id > 0) * Actions */ -if ($action == 'dolibarr2ldap') -{ +if ($action == 'dolibarr2ldap') { $db->begin(); $ldap = new Ldap(); @@ -63,8 +63,7 @@ if ($action == 'dolibarr2ldap') $result = $ldap->update($dn, $info, $user, $olddn); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans("ContactSynchronized"), null, 'mesgs'); $db->commit(); } else { @@ -98,8 +97,7 @@ print '
    '; print ''; // Company -if ($object->socid > 0) -{ +if ($object->socid > 0) { $thirdparty = new Societe($db); $thirdparty->fetch($object->socid); @@ -134,19 +132,19 @@ print dol_get_fiche_end(); /* - * Barre d'actions + * Action bar */ - print '
    '; -if (!empty($conf->global->LDAP_CONTACT_ACTIVE) && $conf->global->LDAP_CONTACT_ACTIVE != 'ldap2dolibarr') -{ +if (!empty($conf->global->LDAP_CONTACT_ACTIVE) && $conf->global->LDAP_CONTACT_ACTIVE != 'ldap2dolibarr') { print ''.$langs->trans("ForceSynchronize").''; } print "
    \n"; -if (!empty($conf->global->LDAP_CONTACT_ACTIVE) && $conf->global->LDAP_CONTACT_ACTIVE != 'ldap2dolibarr') print "
    \n"; +if (!empty($conf->global->LDAP_CONTACT_ACTIVE) && $conf->global->LDAP_CONTACT_ACTIVE != 'ldap2dolibarr') { + print "
    \n"; +} @@ -163,8 +161,7 @@ print ''; // Lecture LDAP $ldap = new Ldap(); $result = $ldap->connect_bind(); -if ($result > 0) -{ +if ($result > 0) { $info = $object->_load_ldap_info(); $dn = $object->_load_ldap_dn($info, 1); $search = "(".$object->_load_ldap_dn($info, 2).")"; @@ -174,10 +171,8 @@ if ($result > 0) //var_dump($records); // Show tree - if (((!is_numeric($records)) || $records != 0) && (!isset($records['count']) || $records['count'] > 0)) - { - if (!is_array($records)) - { + if (((!is_numeric($records)) || $records != 0) && (!isset($records['count']) || $records['count'] > 0)) { + if (!is_array($records)) { print ''; } else { $result = show_ldap_content($records, 0, $records['count'], true); diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index c33867fed7f..53ebbdfddd9 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -55,7 +55,9 @@ $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'con $id = GETPOST('id', 'int'); $contactid = GETPOST('id', 'int'); $ref = ''; // There is no ref for contacts -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $contactid, ''); $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); @@ -95,7 +97,9 @@ $search_roles = GETPOST("search_roles", 'array'); $search_level = GETPOST("search_level", "array"); $search_stcomm = GETPOST('search_stcomm', 'int'); -if ($search_status == '') $search_status = 1; // always display active customer first +if ($search_status == '') { + $search_status = 1; // always display active customer first +} $optioncss = GETPOST('optioncss', 'alpha'); @@ -109,31 +113,41 @@ $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $userid = GETPOST('userid', 'int'); $begin = GETPOST('begin'); -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "p.lastname"; -if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "p.lastname"; +} +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} $offset = $limit * $page; $titre = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); -if ($type == "p") -{ - if (empty($contextpage) || $contextpage == 'contactlist') $contextpage = 'contactprospectlist'; +if ($type == "p") { + if (empty($contextpage) || $contextpage == 'contactlist') { + $contextpage = 'contactprospectlist'; + } $titre .= ' ('.$langs->trans("ThirdPartyProspects").')'; $urlfiche = "card.php"; } -if ($type == "c") -{ - if (empty($contextpage) || $contextpage == 'contactlist') $contextpage = 'contactcustomerlist'; +if ($type == "c") { + if (empty($contextpage) || $contextpage == 'contactlist') { + $contextpage = 'contactcustomerlist'; + } $titre .= ' ('.$langs->trans("ThirdPartyCustomers").')'; $urlfiche = "card.php"; -} elseif ($type == "f") -{ - if (empty($contextpage) || $contextpage == 'contactlist') $contextpage = 'contactsupplierlist'; +} elseif ($type == "f") { + if (empty($contextpage) || $contextpage == 'contactlist') { + $contextpage = 'contactsupplierlist'; + } $titre .= ' ('.$langs->trans("ThirdPartySuppliers").')'; $urlfiche = "card.php"; -} elseif ($type == "o") -{ - if (empty($contextpage) || $contextpage == 'contactlist') $contextpage = 'contactotherlist'; +} elseif ($type == "o") { + if (empty($contextpage) || $contextpage == 'contactlist') { + $contextpage = 'contactotherlist'; + } $titre .= ' ('.$langs->trans("OthersNotLinkedToThirdParty").')'; $urlfiche = ""; } @@ -150,8 +164,7 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // don't allow search in private notes for external users when doing "search in all" if (!empty($user->socid) && $key == "note_private") { continue; @@ -209,10 +222,11 @@ $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); -if (($id > 0 || !empty($ref)) && $action != 'add') -{ +if (($id > 0 || !empty($ref)) && $action != 'add') { $result = $object->fetch($id, $ref); - if ($result < 0) dol_print_error($db); + if ($result < 0) { + dol_print_error($db); + } } @@ -220,21 +234,25 @@ if (($id > 0 || !empty($ref)) && $action != 'add') * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Did we click on 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 $sall = ""; $search_id = ''; $search_firstlast_only = ""; @@ -281,19 +299,22 @@ if (empty($reshook)) $uploaddir = $conf->societe->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - if ($action == 'setstcomm') - { + if ($action == 'setstcomm') { $object = new Contact($db); $result = $object->fetch(GETPOST('stcommcontactid')); $object->stcomm_id = dol_getIdFromCode($db, GETPOST('stcomm', 'alpha'), 'c_stcommcontact'); $result = $object->update($object->id, $user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } $action = ''; } } -if ($search_priv < 0) $search_priv = ''; +if ($search_priv < 0) { + $search_priv = ''; +} /* @@ -318,17 +339,18 @@ $sql .= " FROM ".MAIN_DB_PREFIX."c_prospectcontactlevel"; $sql .= " WHERE active > 0"; $sql .= " ORDER BY sortorder"; $resql = $db->query($sql); -if ($resql) -{ - while ($obj = $db->fetch_object($resql)) - { +if ($resql) { + while ($obj = $db->fetch_object($resql)) { // Compute level text $level = $langs->trans($obj->code); - if ($level == $obj->code) $level = $langs->trans($obj->label); + if ($level == $obj->code) { + $level = $langs->trans($obj->label); + } $tab_level[$obj->code] = $level; } +} else { + dol_print_error($db); } -else dol_print_error($db); $sql = "SELECT s.rowid as socid, s.nom as name,"; $sql .= " p.rowid, p.lastname as lastname, p.statut, p.firstname, p.zip, p.town, p.poste, p.email, p.no_email,"; @@ -338,64 +360,121 @@ $sql .= " st.libelle as stcomm, st.picto as stcomm_picto, p.fk_stcommcontact as $sql .= " co.label as country, co.code as country_code"; // 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 : ''); + 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 $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as p"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (p.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (p.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON co.rowid = p.fk_pays"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_stcommcontact as st ON st.id = p.fk_stcommcontact"; -if (!empty($search_categ)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_contact as cc ON p.rowid = cc.fk_socpeople"; // We need this table joined to the select in order to filter by categ -if (!empty($search_categ_thirdparty)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_soc"; // We need this table joined to the select in order to filter by categ -if (!empty($search_categ_supplier)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cs2 ON s.rowid = cs2.fk_soc"; // We need this table joined to the select in order to filter by categ -if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; +if (!empty($search_categ)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_contact as cc ON p.rowid = cc.fk_socpeople"; // We need this table joined to the select in order to filter by categ +} +if (!empty($search_categ_thirdparty)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_soc"; // We need this table joined to the select in order to filter by categ +} +if (!empty($search_categ_supplier)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cs2 ON s.rowid = cs2.fk_soc"; // We need this table joined to the select in order to filter by categ +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; +} $sql .= ' WHERE p.entity IN ('.getEntity('socpeople').')'; -if (!$user->rights->societe->client->voir && !$socid) //restriction -{ +if (!$user->rights->societe->client->voir && !$socid) { //restriction $sql .= " AND (sc.fk_user = ".$user->id." OR p.fk_soc IS NULL)"; } -if (!empty($userid)) // propre au commercial -{ +if (!empty($userid)) { // propre au commercial $sql .= " AND p.fk_user_creat=".$db->escape($userid); } -if ($search_level) $sql .= natural_search("p.fk_prospectcontactlevel", join(',', $search_level), 3); -if ($search_stcomm != '' && $search_stcomm != -2) $sql .= natural_search("p.fk_stcommcontact", $search_stcomm, 2); - -// Filter to exclude not owned private contacts -if ($search_priv != '0' && $search_priv != '1') -{ - $sql .= " AND (p.priv='0' OR (p.priv='1' AND p.fk_user_creat=".$user->id."))"; -} else { - if ($search_priv == '0') $sql .= " AND p.priv='0'"; - if ($search_priv == '1') $sql .= " AND (p.priv='1' AND p.fk_user_creat=".$user->id.")"; +if ($search_level) { + $sql .= natural_search("p.fk_prospectcontactlevel", join(',', $search_level), 3); +} +if ($search_stcomm != '' && $search_stcomm != -2) { + $sql .= natural_search("p.fk_stcommcontact", $search_stcomm, 2); } -if ($search_categ > 0) $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ); -if ($search_categ == -2) $sql .= " AND cc.fk_categorie IS NULL"; -if ($search_categ_thirdparty > 0) $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ_thirdparty); -if ($search_categ_thirdparty == -2) $sql .= " AND cs.fk_categorie IS NULL"; -if ($search_categ_supplier > 0) $sql .= " AND cs2.fk_categorie = ".$db->escape($search_categ_supplier); -if ($search_categ_supplier == -2) $sql .= " AND cs2.fk_categorie IS NULL"; +// Filter to exclude not owned private contacts +if ($search_priv != '0' && $search_priv != '1') { + $sql .= " AND (p.priv='0' OR (p.priv='1' AND p.fk_user_creat=".$user->id."))"; +} else { + if ($search_priv == '0') { + $sql .= " AND p.priv='0'"; + } + if ($search_priv == '1') { + $sql .= " AND (p.priv='1' AND p.fk_user_creat=".$user->id.")"; + } +} -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if (strlen($search_phone)) $sql .= natural_search(array('p.phone', 'p.phone_perso', 'p.phone_mobile'), $search_phone); -if (strlen($search_cti)) $sql .= natural_search(array('p.phone', 'p.phone_perso', 'p.phone_mobile'), $search_cti); -if (strlen($search_firstlast_only)) $sql .= natural_search(array('p.lastname', 'p.firstname'), $search_firstlast_only); +if ($search_categ > 0) { + $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ); +} +if ($search_categ == -2) { + $sql .= " AND cc.fk_categorie IS NULL"; +} +if ($search_categ_thirdparty > 0) { + $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ_thirdparty); +} +if ($search_categ_thirdparty == -2) { + $sql .= " AND cs.fk_categorie IS NULL"; +} +if ($search_categ_supplier > 0) { + $sql .= " AND cs2.fk_categorie = ".$db->escape($search_categ_supplier); +} +if ($search_categ_supplier == -2) { + $sql .= " AND cs2.fk_categorie IS NULL"; +} -if ($search_id > 0) $sql .= natural_search('p.rowid', $search_id, 1); -if ($search_lastname) $sql .= natural_search('p.lastname', $search_lastname); -if ($search_firstname) $sql .= natural_search('p.firstname', $search_firstname); -if ($search_societe) $sql .= natural_search(empty($conf->global->SOCIETE_DISABLE_CONTACTS) ? 's.nom' : 'p.fk_soc', $search_societe); -if ($search_country) $sql .= " AND p.fk_pays IN (".$search_country.')'; -if (strlen($search_poste)) $sql .= natural_search('p.poste', $search_poste); -if (strlen($search_phone_perso)) $sql .= natural_search('p.phone_perso', $search_phone_perso); -if (strlen($search_phone_pro)) $sql .= natural_search('p.phone', $search_phone_pro); -if (strlen($search_phone_mobile)) $sql .= natural_search('p.phone_mobile', $search_phone_mobile); -if (strlen($search_fax)) $sql .= natural_search('p.fax', $search_fax); +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} +if (strlen($search_phone)) { + $sql .= natural_search(array('p.phone', 'p.phone_perso', 'p.phone_mobile'), $search_phone); +} +if (strlen($search_cti)) { + $sql .= natural_search(array('p.phone', 'p.phone_perso', 'p.phone_mobile'), $search_cti); +} +if (strlen($search_firstlast_only)) { + $sql .= natural_search(array('p.lastname', 'p.firstname'), $search_firstlast_only); +} + +if ($search_id > 0) { + $sql .= natural_search('p.rowid', $search_id, 1); +} +if ($search_lastname) { + $sql .= natural_search('p.lastname', $search_lastname); +} +if ($search_firstname) { + $sql .= natural_search('p.firstname', $search_firstname); +} +if ($search_societe) { + $sql .= natural_search(empty($conf->global->SOCIETE_DISABLE_CONTACTS) ? 's.nom' : 'p.fk_soc', $search_societe); +} +if ($search_country) { + $sql .= " AND p.fk_pays IN (".$search_country.')'; +} +if (strlen($search_poste)) { + $sql .= natural_search('p.poste', $search_poste); +} +if (strlen($search_phone_perso)) { + $sql .= natural_search('p.phone_perso', $search_phone_perso); +} +if (strlen($search_phone_pro)) { + $sql .= natural_search('p.phone', $search_phone_pro); +} +if (strlen($search_phone_mobile)) { + $sql .= natural_search('p.phone_mobile', $search_phone_mobile); +} +if (strlen($search_fax)) { + $sql .= natural_search('p.fax', $search_fax); +} if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active'] && strlen($search_[$key])) { @@ -403,31 +482,38 @@ if (!empty($conf->socialnetworks->enabled)) { } } } -if (strlen($search_email)) $sql .= natural_search('p.email', $search_email); -if (strlen($search_zip)) $sql .= natural_search("p.zip", $search_zip); -if (strlen($search_town)) $sql .= natural_search("p.town", $search_town); +if (strlen($search_email)) { + $sql .= natural_search('p.email', $search_email); +} +if (strlen($search_zip)) { + $sql .= natural_search("p.zip", $search_zip); +} +if (strlen($search_town)) { + $sql .= natural_search("p.town", $search_town); +} if (count($search_roles) > 0) { $sql .= " AND p.rowid IN (SELECT sc.fk_socpeople FROM ".MAIN_DB_PREFIX."societe_contacts as sc WHERE sc.fk_c_type_contact IN (".implode(',', $search_roles)."))"; } -if ($search_no_email != '' && $search_no_email >= 0) $sql .= " AND p.no_email = ".$db->escape($search_no_email); -if ($search_status != '' && $search_status >= 0) $sql .= " AND p.statut = ".$db->escape($search_status); -if ($search_import_key) $sql .= natural_search("p.import_key", $search_import_key); -if ($type == "o") // filtre sur type -{ +if ($search_no_email != '' && $search_no_email >= 0) { + $sql .= " AND p.no_email = ".$db->escape($search_no_email); +} +if ($search_status != '' && $search_status >= 0) { + $sql .= " AND p.statut = ".$db->escape($search_status); +} +if ($search_import_key) { + $sql .= natural_search("p.import_key", $search_import_key); +} +if ($type == "o") { // filtre sur type $sql .= " AND p.fk_soc IS NULL"; -} elseif ($type == "f") // filtre sur type -{ +} elseif ($type == "f") { // filtre sur type $sql .= " AND s.fournisseur = 1"; -} elseif ($type == "c") // filtre sur type -{ +} elseif ($type == "c") { // filtre sur type $sql .= " AND s.client IN (1, 3)"; -} elseif ($type == "p") // filtre sur type -{ +} elseif ($type == "p") { // filtre sur type $sql .= " AND s.client IN (2, 3)"; } -if (!empty($socid)) -{ +if (!empty($socid)) { $sql .= " AND s.rowid = ".$socid; } // Add where from extra fields @@ -437,8 +523,7 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; // Add order -if ($view == "recent") -{ +if ($view == "recent") { $sql .= $db->order("p.datec", "DESC"); } else { $sql .= $db->order($sortfield, $sortorder); @@ -446,12 +531,10 @@ if ($view == "recent") // 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 resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -460,8 +543,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if (!$resql) -{ +if (!$resql) { dol_print_error($db); exit; } @@ -470,8 +552,7 @@ $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && ($sall != '' || $search_cti != '')) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && ($sall != '' || $search_cti != '')) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/contact/card.php?id='.$id); @@ -482,39 +563,91 @@ $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Módulo_Empresas'; llxHeader('', $title, $help_url); $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; +} $param .= '&begin='.urlencode($begin).'&userid='.urlencode($userid).'&contactname='.urlencode($sall); $param .= '&type='.urlencode($type).'&view='.urlencode($view); -if (!empty($search_categ)) $param .= '&search_categ='.urlencode($search_categ); -if (!empty($search_categ_thirdparty)) $param .= '&search_categ_thirdparty='.urlencode($search_categ_thirdparty); -if (!empty($search_categ_supplier)) $param .= '&search_categ_supplier='.urlencode($search_categ_supplier); -if ($sall != '') $param .= '&sall='.urlencode($sall); -if ($search_id > 0) $param .= "&search_id=".urlencode($search_id); -if ($search_lastname != '') $param .= '&search_lastname='.urlencode($search_lastname); -if ($search_firstname != '') $param .= '&search_firstname='.urlencode($search_firstname); -if ($search_societe != '') $param .= '&search_societe='.urlencode($search_societe); -if ($search_zip != '') $param .= '&search_zip='.urlencode($search_zip); -if ($search_town != '') $param .= '&search_town='.urlencode($search_town); -if ($search_country != '') $param .= "&search_country=".urlencode($search_country); -if ($search_poste != '') $param .= '&search_poste='.urlencode($search_poste); -if ($search_phone_pro != '') $param .= '&search_phone_pro='.urlencode($search_phone_pro); -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_fax != '') $param .= '&search_fax='.urlencode($search_fax); -if ($search_email != '') $param .= '&search_email='.urlencode($search_email); -if ($search_no_email != '') $param .= '&search_no_email='.urlencode($search_no_email); -if ($search_status != '') $param .= '&search_status='.urlencode($search_status); -if ($search_priv == '0' || $search_priv == '1') $param .= "&search_priv=".urlencode($search_priv); -if ($search_stcomm != '') $param .= '&search_stcomm='.urlencode($search_stcomm); +if (!empty($search_categ)) { + $param .= '&search_categ='.urlencode($search_categ); +} +if (!empty($search_categ_thirdparty)) { + $param .= '&search_categ_thirdparty='.urlencode($search_categ_thirdparty); +} +if (!empty($search_categ_supplier)) { + $param .= '&search_categ_supplier='.urlencode($search_categ_supplier); +} +if ($sall != '') { + $param .= '&sall='.urlencode($sall); +} +if ($search_id > 0) { + $param .= "&search_id=".urlencode($search_id); +} +if ($search_lastname != '') { + $param .= '&search_lastname='.urlencode($search_lastname); +} +if ($search_firstname != '') { + $param .= '&search_firstname='.urlencode($search_firstname); +} +if ($search_societe != '') { + $param .= '&search_societe='.urlencode($search_societe); +} +if ($search_zip != '') { + $param .= '&search_zip='.urlencode($search_zip); +} +if ($search_town != '') { + $param .= '&search_town='.urlencode($search_town); +} +if ($search_country != '') { + $param .= "&search_country=".urlencode($search_country); +} +if ($search_poste != '') { + $param .= '&search_poste='.urlencode($search_poste); +} +if ($search_phone_pro != '') { + $param .= '&search_phone_pro='.urlencode($search_phone_pro); +} +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_fax != '') { + $param .= '&search_fax='.urlencode($search_fax); +} +if ($search_email != '') { + $param .= '&search_email='.urlencode($search_email); +} +if ($search_no_email != '') { + $param .= '&search_no_email='.urlencode($search_no_email); +} +if ($search_status != '') { + $param .= '&search_status='.urlencode($search_status); +} +if ($search_priv == '0' || $search_priv == '1') { + $param .= "&search_priv=".urlencode($search_priv); +} +if ($search_stcomm != '') { + $param .= '&search_stcomm='.urlencode($search_stcomm); +} if (is_array($search_level) && count($search_level)) { foreach ($search_level as $slevel) { $param .= '&search_level[]='.urlencode($slevel); } } -if ($search_import_key != '') $param .= '&search_import_key='.urlencode($search_import_key); -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); -if (count($search_roles) > 0) $param .= implode('&search_roles[]=', $search_roles); +if ($search_import_key != '') { + $param .= '&search_import_key='.urlencode($search_import_key); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} +if (count($search_roles) > 0) { + $param .= implode('&search_roles[]=', $search_roles); +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -525,15 +658,23 @@ $arrayofmassactions = array( // 'builddoc'=>$langs->trans("PDFMerge"), ); //if($user->rights->societe->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); -if ($user->rights->societe->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->societe->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 = dolGetButtonTitle($langs->trans('NewContactAddress'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/contact/card.php?action=create', '', $user->rights->societe->contact->creer); print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -550,35 +691,36 @@ $objecttmp = new Contact($db); $trackid = 'ctc'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($sall) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } -if ($search_firstlast_only) -{ +if ($search_firstlast_only) { print '
    '.$langs->trans("FilterOnInto", $search_firstlast_only).$langs->trans("Lastname").", ".$langs->trans("Firstname").'
    '; } $moreforfilter = ''; -if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) -{ +if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('Categories').': '; $moreforfilter .= $formother->select_categories(Categorie::TYPE_CONTACT, $search_categ, 'search_categ', 1); $moreforfilter .= '
    '; - if (empty($type) || $type == 'c' || $type == 'p') - { + if (empty($type) || $type == 'c' || $type == 'p') { $moreforfilter .= '
    '; - if ($type == 'c') $moreforfilter .= $langs->trans('CustomersCategoriesShort').': '; - elseif ($type == 'p') $moreforfilter .= $langs->trans('ProspectsCategoriesShort').': '; - else $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; + if ($type == 'c') { + $moreforfilter .= $langs->trans('CustomersCategoriesShort').': '; + } elseif ($type == 'p') { + $moreforfilter .= $langs->trans('ProspectsCategoriesShort').': '; + } else { + $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; + } $moreforfilter .= $formother->select_categories(Categorie::TYPE_CUSTOMER, $search_categ_thirdparty, 'search_categ_thirdparty', 1); $moreforfilter .= '
    '; } - if (empty($type) || $type == 'f') - { + if (empty($type) || $type == 'f') { $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('SuppliersCategoriesShort').': '; $moreforfilter .= $formother->select_categories(Categorie::TYPE_SUPPLIER, $search_categ_supplier, 'search_categ_supplier', 1); @@ -600,45 +742,41 @@ print '
    '; $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("ErrorFailedToReadLDAP").'
    '."\n"; // Lines for filter fields print ''; -if (!empty($arrayfields['p.rowid']['checked'])) -{ +if (!empty($arrayfields['p.rowid']['checked'])) { print ''; } -if (!empty($arrayfields['p.lastname']['checked'])) -{ +if (!empty($arrayfields['p.lastname']['checked'])) { print ''; } -if (!empty($arrayfields['p.firstname']['checked'])) -{ +if (!empty($arrayfields['p.firstname']['checked'])) { print ''; } -if (!empty($arrayfields['p.poste']['checked'])) -{ +if (!empty($arrayfields['p.poste']['checked'])) { print ''; } -if (!empty($arrayfields['p.zip']['checked'])) -{ +if (!empty($arrayfields['p.zip']['checked'])) { print ''; } -if (!empty($arrayfields['p.town']['checked'])) -{ +if (!empty($arrayfields['p.town']['checked'])) { print ''; @@ -658,44 +796,37 @@ if (!empty($arrayfields['p.town']['checked'])) print ''; }*/ // Country -if (!empty($arrayfields['country.code_iso']['checked'])) -{ +if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; } -if (!empty($arrayfields['p.phone']['checked'])) -{ +if (!empty($arrayfields['p.phone']['checked'])) { print ''; } -if (!empty($arrayfields['p.phone_perso']['checked'])) -{ +if (!empty($arrayfields['p.phone_perso']['checked'])) { print ''; } -if (!empty($arrayfields['p.phone_mobile']['checked'])) -{ +if (!empty($arrayfields['p.phone_mobile']['checked'])) { print ''; } -if (!empty($arrayfields['p.fax']['checked'])) -{ +if (!empty($arrayfields['p.fax']['checked'])) { print ''; } -if (!empty($arrayfields['p.email']['checked'])) -{ +if (!empty($arrayfields['p.email']['checked'])) { print ''; } -if (!empty($arrayfields['p.no_email']['checked'])) -{ +if (!empty($arrayfields['p.no_email']['checked'])) { print ''; @@ -703,8 +834,7 @@ if (!empty($arrayfields['p.no_email']['checked'])) if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active']) { - if (!empty($arrayfields['p.'.$key]['checked'])) - { + if (!empty($arrayfields['p.'.$key]['checked'])) { print ''; @@ -712,33 +842,28 @@ if (!empty($conf->socialnetworks->enabled)) { } } } -if (!empty($arrayfields['p.fk_soc']['checked']) || !empty($arrayfields['s.nom']['checked'])) -{ +if (!empty($arrayfields['p.fk_soc']['checked']) || !empty($arrayfields['s.nom']['checked'])) { print ''; } -if (!empty($arrayfields['p.priv']['checked'])) -{ +if (!empty($arrayfields['p.priv']['checked'])) { print ''; } // Prospect level -if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) -{ +if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) { print ''; } // Prospect status -if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) -{ +if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) { print ''; } // Date modification -if (!empty($arrayfields['p.tms']['checked'])) -{ +if (!empty($arrayfields['p.tms']['checked'])) { print ''; } // Status -if (!empty($arrayfields['p.statut']['checked'])) -{ +if (!empty($arrayfields['p.statut']['checked'])) { print ''; } -if (!empty($arrayfields['p.import_key']['checked'])) -{ +if (!empty($arrayfields['p.import_key']['checked'])) { print ''; @@ -786,23 +907,47 @@ print ''; // Ligne des titres print ''; -if (!empty($arrayfields['p.rowid']['checked'])) print_liste_field_titre($arrayfields['p.rowid']['label'], $_SERVER["PHP_SELF"], "p.rowid", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['p.lastname']['checked'])) print_liste_field_titre($arrayfields['p.lastname']['label'], $_SERVER["PHP_SELF"], "p.lastname", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.firstname']['checked'])) print_liste_field_titre($arrayfields['p.firstname']['label'], $_SERVER["PHP_SELF"], "p.firstname", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.poste']['checked'])) print_liste_field_titre($arrayfields['p.poste']['label'], $_SERVER["PHP_SELF"], "p.poste", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.zip']['checked'])) print_liste_field_titre($arrayfields['p.zip']['label'], $_SERVER["PHP_SELF"], "p.zip", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.town']['checked'])) print_liste_field_titre($arrayfields['p.town']['label'], $_SERVER["PHP_SELF"], "p.town", $begin, $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['p.rowid']['checked'])) { + print_liste_field_titre($arrayfields['p.rowid']['label'], $_SERVER["PHP_SELF"], "p.rowid", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['p.lastname']['checked'])) { + print_liste_field_titre($arrayfields['p.lastname']['label'], $_SERVER["PHP_SELF"], "p.lastname", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.firstname']['checked'])) { + print_liste_field_titre($arrayfields['p.firstname']['label'], $_SERVER["PHP_SELF"], "p.firstname", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.poste']['checked'])) { + print_liste_field_titre($arrayfields['p.poste']['label'], $_SERVER["PHP_SELF"], "p.poste", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.zip']['checked'])) { + print_liste_field_titre($arrayfields['p.zip']['label'], $_SERVER["PHP_SELF"], "p.zip", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.town']['checked'])) { + print_liste_field_titre($arrayfields['p.town']['label'], $_SERVER["PHP_SELF"], "p.town", $begin, $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['region.nom']['checked'])) print_liste_field_titre($arrayfields['region.nom']['label'],$_SERVER["PHP_SELF"],"region.nom","",$param,'',$sortfield,$sortorder); if (!empty($arrayfields['country.code_iso']['checked'])) { print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "co.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); } -if (!empty($arrayfields['p.phone']['checked'])) print_liste_field_titre($arrayfields['p.phone']['label'], $_SERVER["PHP_SELF"], "p.phone", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.phone_perso']['checked'])) print_liste_field_titre($arrayfields['p.phone_perso']['label'], $_SERVER["PHP_SELF"], "p.phone_perso", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.phone_mobile']['checked'])) print_liste_field_titre($arrayfields['p.phone_mobile']['label'], $_SERVER["PHP_SELF"], "p.phone_mobile", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.fax']['checked'])) print_liste_field_titre($arrayfields['p.fax']['label'], $_SERVER["PHP_SELF"], "p.fax", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.email']['checked'])) print_liste_field_titre($arrayfields['p.email']['label'], $_SERVER["PHP_SELF"], "p.email", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.no_email']['checked'])) print_liste_field_titre($arrayfields['p.no_email']['label'], $_SERVER["PHP_SELF"], "p.no_email", $begin, $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['p.phone']['checked'])) { + print_liste_field_titre($arrayfields['p.phone']['label'], $_SERVER["PHP_SELF"], "p.phone", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.phone_perso']['checked'])) { + print_liste_field_titre($arrayfields['p.phone_perso']['label'], $_SERVER["PHP_SELF"], "p.phone_perso", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.phone_mobile']['checked'])) { + print_liste_field_titre($arrayfields['p.phone_mobile']['label'], $_SERVER["PHP_SELF"], "p.phone_mobile", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.fax']['checked'])) { + print_liste_field_titre($arrayfields['p.fax']['label'], $_SERVER["PHP_SELF"], "p.fax", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.email']['checked'])) { + print_liste_field_titre($arrayfields['p.email']['label'], $_SERVER["PHP_SELF"], "p.email", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.no_email']['checked'])) { + print_liste_field_titre($arrayfields['p.no_email']['label'], $_SERVER["PHP_SELF"], "p.no_email", $begin, $param, '', $sortfield, $sortorder, 'center '); +} if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active'] && !empty($arrayfields['p.'.$key]['checked'])) { @@ -810,11 +955,21 @@ if (!empty($conf->socialnetworks->enabled)) { } } } -if (!empty($arrayfields['p.fk_soc']['checked'])) print_liste_field_titre($arrayfields['p.fk_soc']['label'], $_SERVER["PHP_SELF"], "p.fk_soc", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.priv']['checked'])) print_liste_field_titre($arrayfields['p.priv']['label'], $_SERVER["PHP_SELF"], "p.priv", $begin, $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) print_liste_field_titre($arrayfields['p.fk_prospectcontactlevel']['label'], $_SERVER["PHP_SELF"], "p.fk_prospectcontactlevel", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) print_liste_field_titre($arrayfields['p.fk_stcommcontact']['label'], $_SERVER["PHP_SELF"], "p.fk_stcommcontact", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['p.fk_soc']['checked'])) { + print_liste_field_titre($arrayfields['p.fk_soc']['label'], $_SERVER["PHP_SELF"], "p.fk_soc", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.priv']['checked'])) { + print_liste_field_titre($arrayfields['p.priv']['label'], $_SERVER["PHP_SELF"], "p.priv", $begin, $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) { + print_liste_field_titre($arrayfields['p.fk_prospectcontactlevel']['label'], $_SERVER["PHP_SELF"], "p.fk_prospectcontactlevel", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) { + print_liste_field_titre($arrayfields['p.fk_stcommcontact']['label'], $_SERVER["PHP_SELF"], "p.fk_stcommcontact", "", $param, '', $sortfield, $sortorder, 'center '); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields @@ -844,8 +999,7 @@ print "\n"; $i = 0; $totalarray = array(); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $arraysocialnetworks = (array) json_decode($obj->socialnetworks, true); @@ -870,44 +1024,50 @@ while ($i < min($num, $limit)) print ''; // ID - if (!empty($arrayfields['p.rowid']['checked'])) - { + if (!empty($arrayfields['p.rowid']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Name - if (!empty($arrayfields['p.lastname']['checked'])) - { + if (!empty($arrayfields['p.lastname']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Firstname - if (!empty($arrayfields['p.firstname']['checked'])) - { + if (!empty($arrayfields['p.firstname']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Job position - if (!empty($arrayfields['p.poste']['checked'])) - { + if (!empty($arrayfields['p.poste']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['p.zip']['checked'])) - { + if (!empty($arrayfields['p.zip']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['p.town']['checked'])) - { + if (!empty($arrayfields['p.town']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State /*if (! empty($arrayfields['state.nom']['checked'])) @@ -922,101 +1082,119 @@ while ($i < min($num, $limit)) if (! $i) $totalarray['nbfield']++; }*/ // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Phone - if (!empty($arrayfields['p.phone']['checked'])) - { + if (!empty($arrayfields['p.phone']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Phone perso - if (!empty($arrayfields['p.phone_perso']['checked'])) - { + if (!empty($arrayfields['p.phone_perso']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Phone mobile - if (!empty($arrayfields['p.phone_mobile']['checked'])) - { + if (!empty($arrayfields['p.phone_mobile']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Fax - if (!empty($arrayfields['p.fax']['checked'])) - { + if (!empty($arrayfields['p.fax']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // EMail - if (!empty($arrayfields['p.email']['checked'])) - { + if (!empty($arrayfields['p.email']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // No EMail - if (!empty($arrayfields['p.no_email']['checked'])) - { + if (!empty($arrayfields['p.no_email']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active'] && !empty($arrayfields['p.'.$key]['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } } } // Company - if (!empty($arrayfields['p.fk_soc']['checked']) || !empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['p.fk_soc']['checked']) || !empty($arrayfields['s.nom']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Private/Public - if (!empty($arrayfields['p.priv']['checked'])) - { + if (!empty($arrayfields['p.priv']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) - { + if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) { // Prospect level print '"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) - { + if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) { // Prospect status print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -1026,45 +1204,52 @@ while ($i < min($num, $limit)) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['p.datec']['checked'])) - { + if (!empty($arrayfields['p.datec']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['p.tms']['checked'])) - { + if (!empty($arrayfields['p.tms']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['p.statut']['checked'])) - { + if (!empty($arrayfields['p.statut']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['p.import_key']['checked'])) - { + if (!empty($arrayfields['p.import_key']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; $i++; diff --git a/htdocs/contact/note.php b/htdocs/contact/note.php index ae32ef5c95e..9a90cafdd9a 100644 --- a/htdocs/contact/note.php +++ b/htdocs/contact/note.php @@ -36,11 +36,15 @@ $langs->load("companies"); // Security check $id = GETPOST('id', 'int'); -if ($user->socid) $id = $user->socid; +if ($user->socid) { + $id = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe'); $object = new Contact($db); -if ($id > 0) $object->fetch($id); +if ($id > 0) { + $object->fetch($id); +} $permissionnote = $user->rights->societe->creer; // Used by the include of actions_setnotes.inc.php @@ -65,12 +69,13 @@ $form = new Form($db); $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($id > 0) -{ +if ($id > 0) { /* - * Affichage onglets - */ - if (!empty($conf->notification->enabled)) $langs->load("mails"); + * Affichage onglets + */ + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = contact_prepare_head($object); @@ -79,14 +84,16 @@ if ($id > 0) $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
    '; - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $objsoc = new Societe($db); $objsoc->fetch($object->socid); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '; - if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1); - else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + if ($objsoc->id > 0) { + $morehtmlref .= $objsoc->getNomUrl(1); + } else { + $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + } } $morehtmlref .= '
    '; diff --git a/htdocs/contact/perso.php b/htdocs/contact/perso.php index 0555eb84719..5c7356fae00 100644 --- a/htdocs/contact/perso.php +++ b/htdocs/contact/perso.php @@ -35,7 +35,9 @@ $id = GETPOST('id', 'int'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe'); $object = new Contact($db); @@ -43,47 +45,43 @@ $object = new Contact($db); * Action */ -if ($action == 'update' && !$_POST["cancel"] && $user->rights->societe->contact->creer) -{ +if ($action == 'update' && !$_POST["cancel"] && $user->rights->societe->contact->creer) { $ret = $object->fetch($id); // Note: Correct date should be completed with location to have exact GM time of birth. $object->birthday = dol_mktime(0, 0, 0, $_POST["birthdaymonth"], $_POST["birthdayday"], $_POST["birthdayyear"]); $object->birthday_alert = $_POST["birthday_alert"]; - if (GETPOST('deletephoto')) $object->photo = ''; - elseif (!empty($_FILES['photo']['name'])) $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); + if (GETPOST('deletephoto')) { + $object->photo = ''; + } elseif (!empty($_FILES['photo']['name'])) { + $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); + } $result = $object->update_perso($id, $user); - if ($result > 0) - { + if ($result > 0) { $object->old_name = ''; $object->old_firstname = ''; // Logo/Photo save $dir = $conf->societe->dir_output.'/contact/'.get_exdir($object->id, 0, 0, 1, $object, 'contact').'/photos'; $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']); - if ($file_OK) - { + if ($file_OK) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; - if (GETPOST('deletephoto')) - { + if (GETPOST('deletephoto')) { $fileimg = $conf->societe->dir_output.'/contact/'.get_exdir($object->id, 0, 0, 1, $object, 'contact').'/photos/'.$object->photo; $dirthumbs = $conf->societe->dir_output.'/contact/'.get_exdir($object->id, 0, 0, 1, $object, 'contact').'/photos/thumbs'; dol_delete_file($fileimg); dol_delete_dir_recursive($dirthumbs); } - if (image_format_supported($_FILES['photo']['name']) > 0) - { + if (image_format_supported($_FILES['photo']['name']) > 0) { dol_mkdir($dir); - if (@is_dir($dir)) - { + if (@is_dir($dir)) { $newfile = $dir.'/'.dol_sanitizeFileName($_FILES['photo']['name']); - if (!dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1, 0, $_FILES['photo']['error']) > 0) - { + if (!dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1, 0, $_FILES['photo']['error']) > 0) { setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors'); } else { // Create thumbs @@ -94,8 +92,7 @@ if ($action == 'update' && !$_POST["cancel"] && $user->rights->societe->contact- setEventMessages("ErrorBadImageFormat", null, 'errors'); } } else { - switch ($_FILES['photo']['error']) - { + switch ($_FILES['photo']['error']) { case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form $errors[] = "ErrorFileSizeTooLarge"; @@ -118,7 +115,9 @@ if ($action == 'update' && !$_POST["cancel"] && $user->rights->societe->contact- $now = dol_now(); $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title = $object->lastname; +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) { + $title = $object->lastname; +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $helpurl); @@ -128,8 +127,7 @@ $object->fetch($id, $user); $head = contact_prepare_head($object); -if ($action == 'edit') -{ +if ($action == 'edit') { /* * Fiche en mode edition */ @@ -151,11 +149,15 @@ if ($action == 'edit') // Photo print ''; // Company - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { - if ($object->socid > 0) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { + if ($object->socid > 0) { $objsoc = new Societe($db); $objsoc->fetch($object->socid); @@ -194,8 +194,7 @@ if ($action == 'edit') print ''; print ''; } else { print ''; @@ -221,14 +220,16 @@ if ($action == 'edit') $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
    '; - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $objsoc = new Societe($db); $objsoc->fetch($object->socid); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '; - if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1); - else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + if ($objsoc->id > 0) { + $morehtmlref .= $objsoc->getNomUrl(1); + } else { + $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + } } $morehtmlref .= '
    '; @@ -243,23 +244,23 @@ if ($action == 'edit') // Company /* - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { - if ($object->socid > 0) - { - $objsoc = new Societe($db); - $objsoc->fetch($object->socid); + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) + { + if ($object->socid > 0) + { + $objsoc = new Societe($db); + $objsoc->fetch($object->socid); - print ''; - } + print ''; + } - else - { - print ''; - } - }*/ + else + { + print ''; + } + }*/ // Civility print ''; - if (!empty($object->birthday)) - { + if (!empty($object->birthday)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; print ''; } else { print ''; @@ -300,15 +307,14 @@ if ($action == 'edit') } -if ($action != 'edit') -{ - // Barre d'actions - if ($user->socid == 0) - { +if ($action != 'edit') { + /* + * Action bar + */ + if ($user->socid == 0) { print '
    '; - if ($user->rights->societe->contact->creer) - { + if ($user->rights->societe->contact->creer) { print ''.$langs->trans('Modify').''; } diff --git a/htdocs/contact/vcard.php b/htdocs/contact/vcard.php index 05426db19a6..1fba506e910 100644 --- a/htdocs/contact/vcard.php +++ b/htdocs/contact/vcard.php @@ -39,8 +39,7 @@ $result = restrictedArea($user, 'contact', $id, 'socpeople&societe'); $result = $contact->fetch($id); -if ($result <= 0) -{ +if ($result <= 0) { dol_print_error($contact->error); exit; } @@ -48,8 +47,7 @@ if ($result <= 0) $physicalperson = 1; $company = new Societe($db); -if ($contact->socid) -{ +if ($contact->socid) { $result = $company->fetch($contact->socid); } @@ -76,33 +74,32 @@ $v->setNote($contact->note); $v->setTitle($contact->poste); // Data from linked company -if ($company->id) -{ +if ($company->id) { $v->setURL($company->url, "TYPE=WORK"); - if (!$contact->phone_pro) $v->setPhoneNumber($company->phone, "TYPE=WORK;VOICE"); - if (!$contact->fax) $v->setPhoneNumber($company->fax, "TYPE=WORK;FAX"); - if (!$contact->zip) $v->setAddress("", "", $company->address, $company->town, $company->state, $company->zip, $company->country, "TYPE=WORK;POSTAL"); + if (!$contact->phone_pro) { + $v->setPhoneNumber($company->phone, "TYPE=WORK;VOICE"); + } + if (!$contact->fax) { + $v->setPhoneNumber($company->fax, "TYPE=WORK;FAX"); + } + if (!$contact->zip) { + $v->setAddress("", "", $company->address, $company->town, $company->state, $company->zip, $company->country, "TYPE=WORK;POSTAL"); + } // when company e-mail is empty, use only contact e-mail - if (empty(trim($company->email))) - { + if (empty(trim($company->email))) { // was set before, don't set twice - } - // when contact e-mail is empty, use only company e-mail - elseif (empty(trim($contact->email))) - { + } elseif (empty(trim($contact->email))) { + // when contact e-mail is empty, use only company e-mail $v->setEmail($company->email); - } - // when e-mail domain of contact and company are the same, use contact e-mail at first (and company e-mail at second) - elseif (strtolower(end(explode("@", $contact->email))) == strtolower(end(explode("@", $company->email)))) - { + } elseif (strtolower(end(explode("@", $contact->email))) == strtolower(end(explode("@", $company->email)))) { + // when e-mail domain of contact and company are the same, use contact e-mail at first (and company e-mail at second) $v->setEmail($contact->email); // support by Microsoft Outlook (2019 and possible earlier) $v->setEmail($company->email, 'INTERNET'); - } - // when e-mail of contact and company complete different use company e-mail at first (and contact e-mail at second) - else { + } else { + // when e-mail of contact and company complete different use company e-mail at first (and contact e-mail at second) $v->setEmail($company->email); // support by Microsoft Outlook (2019 and possible earlier) @@ -110,12 +107,16 @@ if ($company->id) } // Si contact lie a un tiers non de type "particulier" - if ($contact->typent_code != 'TE_PRIVATE') $v->setOrg($company->name); + if ($contact->typent_code != 'TE_PRIVATE') { + $v->setOrg($company->name); + } } // Personal informations $v->setPhoneNumber($contact->phone_perso, "TYPE=HOME;VOICE"); -if ($contact->birthday) $v->setBirthday($contact->birthday); +if ($contact->birthday) { + $v->setBirthday($contact->birthday); +} $db->close(); diff --git a/htdocs/contrat/admin/contract_extrafields.php b/htdocs/contrat/admin/contract_extrafields.php index 8571856362a..dc361a1f0b6 100644 --- a/htdocs/contrat/admin/contract_extrafields.php +++ b/htdocs/contrat/admin/contract_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 = 'contrat'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -78,8 +82,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -92,8 +95,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '
    '; print load_fiche_titre($langs->trans('NewAttribute')); @@ -105,8 +107,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print '

    '; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/contrat/admin/contractdet_extrafields.php b/htdocs/contrat/admin/contractdet_extrafields.php index 4b3f03ffedf..6e83f0a4c1b 100644 --- a/htdocs/contrat/admin/contractdet_extrafields.php +++ b/htdocs/contrat/admin/contractdet_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 = 'contratdet'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -78,8 +82,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -92,8 +95,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '
    '; print load_fiche_titre($langs->trans('NewAttribute')); @@ -105,8 +107,7 @@ if ($action == 'create') /* Edition d'un champ optionnel */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
    "; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/contrat/agenda.php b/htdocs/contrat/agenda.php index f88b470215c..94232aa6afd 100644 --- a/htdocs/contrat/agenda.php +++ b/htdocs/contrat/agenda.php @@ -35,10 +35,11 @@ if (!empty($conf->projet->enabled)) { // Load translation files required by the page $langs->loadLangs(array("companies", "contracts")); -if (GETPOST('actioncode', 'array')) -{ +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)); } @@ -50,19 +51,27 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $id, ''); $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,DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC'; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('agendacontract', 'globalcard')); @@ -74,20 +83,19 @@ $hookmanager->initHooks(array('agendacontract', 'globalcard')); $parameters = array('id'=>$id); $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 (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // 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 $actioncode = ''; $search_agenda_label = ''; } @@ -102,19 +110,18 @@ if (empty($reshook)) $form = new Form($db); $formfile = new FormFile($db); -if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} -if ($id > 0) -{ +if ($id > 0) { // Load object modContract $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis'); - if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') - { + if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $result = dol_include_once('/core/modules/contract/'.$module.'.php'); - if ($result > 0) - { + if ($result > 0) { $modCodeContract = new $module(); } @@ -126,10 +133,14 @@ if ($id > 0) $object->fetch_thirdparty(); $title = $langs->trans("Agenda"); - if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contractrefonly/', $conf->global->MAIN_HTML_TITLE) && $object->ref) $title = $object->ref." - ".$title; + if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contractrefonly/', $conf->global->MAIN_HTML_TITLE) && $object->ref) { + $title = $object->ref." - ".$title; + } llxHeader('', $title); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = contract_prepare_head($object); print dol_get_fiche_head($head, 'agenda', $langs->trans("Contract"), -1, 'contract'); @@ -156,14 +167,14 @@ if ($id > 0) $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $permtoedit, 'string', '', null, null, '', 1, 'getFormatedSupplierRef'); // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherContracts").')'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' ('.$langs->trans("OtherContracts").')'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->contrat->creer) - { + if ($user->rights->contrat->creer) { if ($action != 'classify') { //$morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).''; $morehtmlref .= ' : '; @@ -231,21 +242,22 @@ if ($id > 0) $newcardbutton = ''; - if (!empty($conf->agenda->enabled)) - { - if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) - { + if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { $newcardbutton .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out); } } - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { 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 load_fiche_titre($langs->trans("ActionsOnContract"), $newcardbutton, ''); //print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $newcardbutton, '', 0, 1, 1); diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 8d78b410329..217414aa30c 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -9,7 +9,7 @@ * Copyright (C) 2014-2020 Ferran Marcet * Copyright (C) 2014-2016 Marcos García * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2018-2020 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 @@ -40,7 +40,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +if (!empty($conf->propal->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +} if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; @@ -62,7 +64,9 @@ $datecontrat = ''; $usehm = (!empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $id); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -74,10 +78,12 @@ $extrafields = new ExtraFields($db); // Load object if ($id > 0 || !empty($ref) && $action != 'add') { $ret = $object->fetch($id, $ref); - if ($ret > 0) + if ($ret > 0) { $ret = $object->fetch_thirdparty(); - if ($ret < 0) + } + if ($ret < 0) { dol_print_error('', $object->error); + } } // fetch optionals attributes and labels @@ -98,36 +104,31 @@ $error = 0; $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 (empty($reshook)) -{ +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} +if (empty($reshook)) { include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once - if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer) - { + if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer) { $result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment')); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer) - { - if (!GETPOST('dateend')) - { + } elseif ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer) { + if (!GETPOST('dateend')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors'); } - if (!$error) - { + if (!$error) { $result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment'))); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -137,16 +138,13 @@ if (empty($reshook)) } // Si ajout champ produit predefini - if (GETPOST('mode') == 'predefined') - { + if (GETPOST('mode') == 'predefined') { $date_start = ''; $date_end = ''; - if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear')) - { + if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear')) { $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); } - if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear')) - { + if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear')) { $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); } } @@ -156,40 +154,32 @@ if (empty($reshook)) $date_end_update = ''; $date_start_real_update = ''; $date_end_real_update = ''; - if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear')) - { + if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear')) { $date_start_update = dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear')); } - if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear')) - { + if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear')) { $date_end_update = dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear')); } - if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear')) - { + if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear')) { $date_start_real_update = dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear')); } - if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear')) - { + if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear')) { $date_end_real_update = dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear')); } - if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear')) - { + if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear')) { $datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); } // Add contract - if ($action == 'add' && $user->rights->contrat->creer) - { + if ($action == 'add' && $user->rights->contrat->creer) { // Check - if (empty($datecontrat)) - { + if (empty($datecontrat)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); $action = 'create'; } - if ($socid < 1) - { + if ($socid < 1) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors'); $action = 'create'; $error++; @@ -202,8 +192,7 @@ if (empty($reshook)) $action = 'create'; } - if (!$error) - { + if (!$error) { $object->socid = $socid; $object->date_contrat = $datecontrat; @@ -219,27 +208,28 @@ if (empty($reshook)) $object->ref_supplier = GETPOST('ref_supplier', 'alpha'); // If creation from another object of another module (Example: origin=propal, originid=1) - if (!empty($origin) && !empty($originid)) - { + if (!empty($origin) && !empty($originid)) { // Parse element/subelement (ex: project_task) $element = $subelement = $origin; - if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) - { + if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) { $element = $regs[1]; $subelement = $regs[2]; } // For compatibility - if ($element == 'order') { $element = $subelement = 'commande'; } - if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } + if ($element == 'order') { + $element = $subelement = 'commande'; + } + if ($element == 'propal') { + $element = 'comm/propal'; $subelement = 'propal'; + } $object->origin = $origin; $object->origin_id = $originid; // Possibility to add external linked objects with hooks $object->linked_objects[$object->origin] = $object->origin_id; - if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) - { + if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) { $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); } @@ -248,8 +238,7 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } - if ($id > 0) - { + if ($id > 0) { dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); @@ -257,12 +246,10 @@ if (empty($reshook)) dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); $result = $srcobject->fetch($object->origin_id); - if ($result > 0) - { + if ($result > 0) { $srcobject->fetch_thirdparty(); $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject, 'fetch_lines')) - { + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) { $srcobject->fetch_lines(); $lines = $srcobject->lines; } @@ -270,29 +257,29 @@ if (empty($reshook)) $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); if ($product_type == 1 || (!empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0, 1)))) { // TODO Exclude also deee // service prédéfini - if ($lines[$i]->fk_product > 0) - { + if ($lines[$i]->fk_product > 0) { $product_static = new Product($db); // Define output language - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $prod = new Product($db); $prod->id = $lines[$i]->fk_product; $prod->getMultiLangs(); $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) $newlang = $srcobject->thirdparty->default_lang; - if (!empty($newlang)) - { + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if (empty($newlang)) { + $newlang = $srcobject->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -340,8 +327,7 @@ if (empty($reshook)) $lines[$i]->fk_unit ); - if ($result < 0) - { + if ($result < 0) { $error++; break; } @@ -356,16 +342,16 @@ if (empty($reshook)) $parameters = array('objFrom' => $srcobject); $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if ($reshook < 0) + if ($reshook < 0) { $error++; + } } else { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } else { $result = $object->create($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -376,18 +362,14 @@ if (empty($reshook)) } } elseif ($action == 'classin' && $user->rights->contrat->creer) { $object->setProject(GETPOST('projectid')); - } - - // Add a new line - elseif ($action == 'addline' && $user->rights->contrat->creer) - { + } elseif ($action == 'addline' && $user->rights->contrat->creer) { + // Add a new line // 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')); - if (GETPOST('prod_entry_mode', 'alpha') == 'free') - { + $price_ht = price2num(GETPOST('price_ht'), 'MU', 2); + $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2); + if (GETPOST('prod_entry_mode', 'alpha') == 'free') { $idprod = 0; $tva_tx = (GETPOST('tva_tx', 'alpha') ? GETPOST('tva_tx', 'alpha') : 0); } else { @@ -398,21 +380,18 @@ if (empty($reshook)) $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS'); $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef), 2) : 0); - if ($qty == '') - { + if ($qty == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); $error++; } - if (GETPOST('prod_entry_mode', 'alpha') == 'free' && empty($idprod) && empty($product_desc)) - { + if (GETPOST('prod_entry_mode', 'alpha') == 'free' && empty($idprod) && empty($product_desc)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors'); $error++; } $date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); - if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) - { + if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) { setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); $error++; } @@ -428,8 +407,7 @@ if (empty($reshook)) } } - if (!$error) - { + if (!$error) { // Clean parameters $date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); @@ -439,15 +417,16 @@ if (empty($reshook)) // Ecrase $desc par celui du produit // Ecrase $tva_tx par celui du produit // Ecrase $base_price_type par celui du produit - if ($idprod > 0) - { + if ($idprod > 0) { $prod = new Product($db); $prod->fetch($idprod); // Update if prices fields are defined $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $pu_ht = $prod->price; $pu_ttc = $prod->price_ttc; @@ -455,14 +434,12 @@ if (empty($reshook)) $price_base_type = $prod->price_base_type; // On defini prix unitaire - if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level) - { + if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level) { $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; - } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) - { + } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; $prodcustprice = new Productcustomerprice($db); @@ -476,9 +453,13 @@ if (empty($reshook)) $pu_ttc = price($prodcustprice->lines [0]->price_ttc); $price_base_type = $prodcustprice->lines [0]->price_base_type; $tva_tx = $prodcustprice->lines [0]->tva_tx; - if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; + if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) { + $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; + } $tva_npr = $prodcustprice->lines[0]->recuperableonly; - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } } } } @@ -488,25 +469,26 @@ if (empty($reshook)) // 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 ($tmpvat != $tmpprodvat) - { - if ($price_base_type != 'HT') - { + if ($tmpvat != $tmpprodvat) { + if ($price_base_type != 'HT') { $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); } else { $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); } } - $desc = $prod->description; + $desc = $prod->description; //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time if ($product_desc==$desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) { $product_desc=''; } - if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $desc = $product_desc; - else $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) { + $desc = $product_desc; + } else { + $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + } $fk_unit = $prod->fk_unit; } else { @@ -523,16 +505,19 @@ if (empty($reshook)) // ajout prix achat $fk_fournprice = $_POST['fournprice']; - if (!empty($_POST['buying_price'])) - $pa_ht = $_POST['buying_price']; - else $pa_ht = null; + if (!empty($_POST['buying_price'])) { + $pa_ht = $_POST['buying_price']; + } else { + $pa_ht = null; + } $info_bits = 0; - if ($tva_npr) $info_bits |= 0x01; + if ($tva_npr) { + $info_bits |= 0x01; + } if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) - || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && ($price_min && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) - { + || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && ($price_min && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) { $object->error = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency)); $result = -1; } else { @@ -551,22 +536,24 @@ if (empty($reshook)) $price_base_type, $pu_ttc, $info_bits, - $fk_fournprice, - $pa_ht, + $fk_fournprice, + $pa_ht, $array_options, $fk_unit ); } - if ($result > 0) - { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && !empty($conf->global->CONTRACT_ADDON_PDF)) // No generation if default type not defined - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && !empty($conf->global->CONTRACT_ADDON_PDF)) { // No generation if default type not defined $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -615,19 +602,16 @@ if (empty($reshook)) } elseif ($action == 'updateline' && $user->rights->contrat->creer && !GETPOST('cancel', 'alpha')) { $error = 0; - if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) - { + if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) { setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); $action = 'editline'; $_GET['rowid'] = GETPOST('elrowid'); $error++; } - if (!$error) - { + if (!$error) { $objectline = new ContratLigne($db); - if ($objectline->fetch(GETPOST('elrowid', 'int')) < 0) - { + if ($objectline->fetch(GETPOST('elrowid', 'int')) < 0) { setEventMessages($objectline->error, $objectline->errors, 'errors'); $error++; } @@ -636,16 +620,20 @@ if (empty($reshook)) $db->begin(); - if (!$error) - { - if ($date_start_real_update == '') $date_start_real_update = $objectline->date_ouverture; - if ($date_end_real_update == '') $date_end_real_update = $objectline->date_cloture; + if (!$error) { + if ($date_start_real_update == '') { + $date_start_real_update = $objectline->date_ouverture; + } + if ($date_end_real_update == '') { + $date_end_real_update = $objectline->date_cloture; + } $vat_rate = GETPOST('eltva_tx'); // Define info_bits $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) + if (preg_match('/\*/', $vat_rate)) { $info_bits |= 0x01; + } // Define vat_rate $vat_rate = str_replace('*', '', $vat_rate); @@ -657,17 +645,17 @@ if (empty($reshook)) // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } // ajout prix d'achat - $fk_fournprice = $_POST['fournprice']; - if (!empty($_POST['buying_price'])) - $pa_ht = $_POST['buying_price']; - else $pa_ht = null; + if (GETPOST('buying_price')) { + $pa_ht = price2num(GETPOST('buying_price'), '', 2); + } else { + $pa_ht = null; + } $fk_unit = GETPOST('unit', 'alpha'); @@ -709,43 +697,40 @@ if (empty($reshook)) // TODO verifier price_min si fk_product et multiprix $result = $objectline->update($user); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($objectline->error, $objectline->errors, 'errors'); } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); } - } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer) - { + } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer) { $result = $object->deleteline(GETPOST('lineid'), $user); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer) - { + } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer) { $result = $object->validate($user); - if ($result > 0) - { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -758,53 +743,38 @@ if (empty($reshook)) } else { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'reopen' && $user->rights->contrat->creer) - { + } elseif ($action == 'reopen' && $user->rights->contrat->creer) { $result = $object->reopen($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Close all lines - elseif ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer) - { + } elseif ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer) { + // Close all lines $result = $object->closeAll($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Close all lines - elseif ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer) - { + } elseif ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer) { + // Close all lines $result = $object->activateAll($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer) - { + } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer) { $result = $object->delete($user); - if ($result >= 0) - { + if ($result >= 0) { header("Location: list.php?restore_lastsearch_values=1"); return; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contrat->creer) - { - if (GETPOST('newcid') > 0) - { + } elseif ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contrat->creer) { + if (GETPOST('newcid') > 0) { $contractline = new ContratLigne($db); - $result = $contractline->fetch(GETPOST('lineid')); - $contractline->fk_contrat = GETPOST('newcid'); + $result = $contractline->fetch(GETPOSTINT('lineid')); + $contractline->fk_contrat = GETPOSTINT('newcid'); $result = $contractline->update($user, 1); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); return; } else { @@ -813,18 +783,18 @@ if (empty($reshook)) } else { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("RefNewContract")), null, 'errors'); } - } elseif ($action == 'update_extras') - { + } elseif ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } if (!$error) { $result = $object->insertExtraFields('CONTRACT_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -833,8 +803,7 @@ if (empty($reshook)) if ($error) { $action = 'edit_extras'; } - } elseif ($action == 'setref_supplier') - { + } elseif ($action == 'setref_supplier') { $cancelbutton = GETPOST('cancel', 'alpha'); if (!$cancelbutton) { $object->oldcopy = dol_clone($object); @@ -851,12 +820,10 @@ if (empty($reshook)) header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); exit; } - } elseif ($action == 'setref_customer') - { + } elseif ($action == 'setref_customer') { $cancelbutton = GETPOST('cancel', 'alpha'); - if (!$cancelbutton) - { + if (!$cancelbutton) { $object->oldcopy = dol_clone($object); $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); @@ -871,8 +838,7 @@ if (empty($reshook)) header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); exit; } - } elseif ($action == 'setref') - { + } elseif ($action == 'setref') { $cancelbutton = GETPOST('cancel', 'alpha'); if (!$cancelbutton) { @@ -889,15 +855,15 @@ if (empty($reshook)) $action = 'editref'; } else { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $old_filedir = $conf->contrat->dir_output.'/'.dol_sanitizeFileName($old_ref); - $new_filedir = $conf->contrat->dir_output.'/'.dol_sanitizeFileName($object->ref); + $old_filedir = $conf->contrat->multidir_output[$object->entity].'/'.dol_sanitizeFileName($old_ref); + $new_filedir = $conf->contrat->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); $files = dol_dir_list($old_filedir); - if (!empty($files)) - { - if (!is_dir($new_filedir)) dol_mkdir($new_filedir); - foreach ($files as $file) - { + if (!empty($files)) { + if (!is_dir($new_filedir)) { + dol_mkdir($new_filedir); + } + foreach ($files as $file) { dol_move($file['fullname'], $new_filedir.'/'.$file['name']); } } @@ -909,8 +875,7 @@ if (empty($reshook)) header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); exit; } - } elseif ($action == 'setdate_contrat') - { + } elseif ($action == 'setdate_contrat') { $cancelbutton = GETPOST('cancel', 'alpha'); if (!$cancelbutton) { @@ -935,7 +900,7 @@ if (empty($reshook)) // Actions to build doc - $upload_dir = $conf->contrat->dir_output; + $upload_dir = $conf->contrat->multidir_output[$object->entity]; $permissiontoadd = $user->rights->contrat->creer; include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; @@ -947,42 +912,31 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer) - { - if ($action == 'addcontact') - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer) { + if ($action == 'addcontact') { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // bascule du statut d'un contact - elseif ($action == 'swapstatut') - { + } elseif ($action == 'swapstatut') { + // bascule du statut d'un contact $result = $object->swapContactStatus(GETPOST('ligne')); - } - - // Efface un contact - elseif ($action == 'deletecontact') - { + } elseif ($action == 'deletecontact') { + // Efface un contact $result = $object->delete_contact(GETPOST('lineid')); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -992,10 +946,8 @@ if (empty($reshook)) } // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes') - { - if (!GETPOST('socid', 3)) - { + if ($action == 'confirm_clone' && $confirm == 'yes') { + if (!GETPOST('socid', 3)) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { if ($object->id > 0) { @@ -1004,7 +956,9 @@ if (empty($reshook)) header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit(); } else { - if (count($object->errors) > 0) setEventMessages($object->error, $object->errors, 'errors'); + if (count($object->errors) > 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } $action = ''; } } @@ -1017,57 +971,64 @@ if (empty($reshook)) * View */ -llxHeader('', $langs->trans("Contract"), ""); + +$help_url = 'EN:Module_Contracts|FR:Module_Contrat'; + +llxHeader('', $langs->trans("Contract"), $help_url); $form = new Form($db); $formfile = new FormFile($db); -if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} // Load object modContract $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis'); -if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') -{ +if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $result = dol_include_once('/core/modules/contract/'.$module.'.php'); -if ($result > 0) -{ +if ($result > 0) { $modCodeContract = new $module(); } // Create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans('AddContract'), '', 'contract'); $soc = new Societe($db); - if ($socid > 0) $soc->fetch($socid); + if ($socid > 0) { + $soc->fetch($socid); + } - if (GETPOST('origin') && GETPOST('originid')) - { + if (GETPOST('origin') && GETPOST('originid')) { // Parse element/subelement (ex: project_task) $regs = array(); $element = $subelement = GETPOST('origin'); - if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'), $regs)) - { + if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'), $regs)) { $element = $regs[1]; $subelement = $regs[2]; } - if ($element == 'project') - { + if ($element == 'project') { $projectid = GETPOST('originid'); } else { // For compatibility - if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; } - if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } + if ($element == 'order' || $element == 'commande') { + $element = $subelement = 'commande'; + } + if ($element == 'propal') { + $element = 'comm/propal'; $subelement = 'propal'; + } dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); $objectsrc = new $classname($db); $objectsrc->fetch($originid); - if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) $objectsrc->fetch_lines(); + if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) { + $objectsrc->fetch_lines(); + } $objectsrc->fetch_thirdparty(); // Replicate extrafields @@ -1124,8 +1085,7 @@ if ($action == 'create') // Thirdparty print '
    '; print ''; - if ($socid > 0) - { + if ($socid > 0) { print ''."\n"; - if ($socid > 0) - { + if ($socid > 0) { // Ligne info remises tiers print ''; } @@ -1167,8 +1132,7 @@ if ($action == 'create') print ""; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load('projects'); $formproject = new FormProjets($db); @@ -1184,8 +1148,7 @@ if ($action == 'create') print $doleditor->Create(1); print ''; - if (empty($user->socid)) - { + if (empty($user->socid)) { print ''; @@ -1411,22 +1376,19 @@ if ($action == 'create') print ''; - if (!empty($object->brouillon) && $user->rights->contrat->creer) - { + if (!empty($object->brouillon) && $user->rights->contrat->creer) { print ''; } echo '
    '; - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $blocname = 'contacts'; $title = $langs->trans('ContactsAddresses'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } - if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $blocname = 'notes'; $title = $langs->trans('Notes'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; @@ -1436,19 +1398,20 @@ if ($action == 'create') $arrayothercontracts = $object->getListOfContracts('others'); /* - * Lines of contracts - */ + * Lines of contracts + */ $productstatic = new Product($db); $usemargins = 0; - if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'propal', 'commande'))) $usemargins = 1; + if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'propal', 'commande'))) { + $usemargins = 1; + } // Title line for service $cursorline = 1; print '
    '; - while ($cursorline <= $nbofservices) - { + while ($cursorline <= $nbofservices) { print '
    '; print '
    '; print ''; @@ -1472,8 +1435,7 @@ if ($action == 'create') $sql .= " WHERE cd.rowid = ".$object->lines[$cursorline - 1]->id; $result = $db->query($sql); - if ($result) - { + if ($result) { $total = 0; print '
    '; @@ -1484,23 +1446,27 @@ if ($action == 'create') // print ''; //} print ''; - if (!empty($conf->global->PRODUCT_USE_UNITS)) print ''; + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + print ''; + } print ''; - if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print ''; + if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) { + print ''; + } print ''; print "\n"; $objp = $db->fetch_object($result); // Line in view mode - if ($action != 'editline' || GETPOST('rowid') != $objp->rowid) - { + if ($action != 'editline' || GETPOST('rowid') != $objp->rowid) { $moreparam = ''; - if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $objp->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') $moreparam = 'style="display: none;"'; + if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $objp->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') { + $moreparam = 'style="display: none;"'; + } print ''; // Label - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { $productstatic->id = $objp->fk_product; $productstatic->type = $objp->ptype; $productstatic->ref = $objp->pref; @@ -1512,16 +1478,14 @@ if ($action == 'create') print ''; // Unit - if (!empty($conf->global->PRODUCT_USE_UNITS)) print ''; + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + print ''; + } // Discount - if ($objp->remise_percent > 0) - { + if ($objp->remise_percent > 0) { print '\n"; } else { print ''; } // Margin - if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print ''; + if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) { + print ''; + } // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme) print '\n"; // Dates of service planed and real - if ($objp->subprice >= 0) - { + if ($objp->subprice >= 0) { $colspan = 6; if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) { @@ -1598,8 +1561,7 @@ if ($action == 'create') // Date planned print $langs->trans("DateStartPlanned").': '; - if ($objp->date_debut) - { + if ($objp->date_debut) { print dol_print_date($db->jdate($objp->date_debut), 'day'); // Warning si date prevu passee et pas en service if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) { @@ -1607,18 +1569,21 @@ if ($action == 'create') $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); print " ".img_warning($textlate); } - } else print $langs->trans("Unknown"); + } else { + print $langs->trans("Unknown"); + } print '  -  '; print $langs->trans("DateEndPlanned").': '; - if ($objp->date_fin) - { + if ($objp->date_fin) { print dol_print_date($db->jdate($objp->date_fin), 'day'); if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) { $warning_delay = $conf->contrat->services->expires->warning_delay / 3600 / 24; $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); print " ".img_warning($textlate); } - } else print $langs->trans("Unknown"); + } else { + print $langs->trans("Unknown"); + } print ''; print ''; @@ -1631,14 +1596,12 @@ if ($action == 'create') $line->fetch_optionals(); print $line->showOptionals($extrafields, 'view', array('class'=>'oddeven', 'style'=>$moreparam, 'colspan'=>$colspan), '', '', 1); } - } - // Line in mode update - else { + } else { + // Line in mode update // Ligne carac print ''; print ''; // Unit - if (!empty($conf->global->PRODUCT_USE_UNITS)) - { + if (!empty($conf->global->PRODUCT_USE_UNITS)) { print ''; @@ -1699,10 +1663,11 @@ if ($action == 'create') // Discount print ''; - if (!empty($usemargins)) - { + if (!empty($usemargins)) { print ''; } print ''; $colspan = 6; - if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++; - if (!empty($conf->global->PRODUCT_USE_UNITS)) $colspan++; + if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) { + $colspan++; + } + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $colspan++; + } // Ligne dates prevues print ''; @@ -1738,10 +1707,11 @@ if ($action == 'create') dol_print_error($db); } - if ($object->statut > 0) - { + if ($object->statut > 0) { $moreparam = ''; - if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->lines[$cursorline - 1]->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') $moreparam = 'style="display: none;"'; + if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->lines[$cursorline - 1]->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') { + $moreparam = 'style="display: none;"'; + } print ''; print ''; print "\n"; @@ -1754,22 +1724,21 @@ if ($action == 'create') /* - * Confirmation to delete service line of contract - */ - if ($action == 'deleteline' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid')) - { + * Confirmation to delete service line of contract + */ + if ($action == 'deleteline' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid')) { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'), $langs->trans("DeleteContractLine"), $langs->trans("ConfirmDeleteContractLine"), "confirm_deleteline", '', 0, 1); - if ($ret == 'html') print '
    '; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print $form->selectarray('search_no_email', array('-1'=>'', '0'=>$langs->trans('No'), '1'=>$langs->trans('Yes')), $search_no_email); print ''; print ''; print ''; print ''; print ''; $selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate")); print $form->selectarray('search_priv', $selectarray, $search_priv, 1); print ''; print $form->multiselectarray('search_level', $tab_level, $search_level, 0, 0, 'width75', 0, 0, '', '', '', 2); print ''; $arraystcomm = array(); - foreach ($contactstatic->cacheprospectstatus as $key => $val) - { + foreach ($contactstatic->cacheprospectstatus as $key => $val) { $arraystcomm[$val['id']] = ($langs->trans("StatusProspect".$val['id']) != "StatusProspect".$val['id'] ? $langs->trans("StatusProspect".$val['id']) : $val['label']); } print $form->selectarray('search_stcomm', $arraystcomm, $search_stcomm, -2, 0, 0, '', 0, 0, 0, '', 'nowrap '); @@ -752,26 +877,22 @@ $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation -if (!empty($arrayfields['p.datec']['checked'])) -{ +if (!empty($arrayfields['p.datec']['checked'])) { print ''; print ''; print ''; print $form->selectarray('search_status', array('-1'=>'', '0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), $search_status); print ''; print ''; print '
    '; print $obj->rowid; print "'; print $contactstatic->getNomUrl(1); print ''.$obj->firstname.''.$obj->poste.''.$obj->zip.''.$obj->town.''; $tmparray = getCountry($obj->fk_pays, 'all'); print $tmparray['label']; print ''.dol_print_phone($obj->phone_pro, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL', ' ', 'phone').''.dol_print_phone($obj->phone_perso, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL', ' ', 'phone').''.dol_print_phone($obj->phone_mobile, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL', ' ', 'mobile').''.dol_print_phone($obj->fax, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL', ' ', 'fax').''.dol_print_email($obj->email, $obj->rowid, $obj->socid, 'AC_EMAIL', 18, 0, 1).''.yn($obj->no_email).''.dol_print_socialnetworks($arraysocialnetworks[$key], $obj->rowid, $obj->socid, $key, $socialnetworks).''; - if ($obj->socid) - { + if ($obj->socid) { $objsoc = new Societe($db); $objsoc->fetch($obj->socid); print $objsoc->getNomUrl(1); - } else print ' '; + } else { + print ' '; + } print ''.$contactstatic->LibPubPriv($obj->priv).''; print $contactstatic->getLibProspLevel(); print "
    '; print '
    '.$contactstatic->libProspCommStatut($obj->stcomm_id, 2, $contactstatic->cacheprospectstatus[$obj->stcomm_id]['label'], $obj->stcomm_picto); print '
    -
    '; foreach ($contactstatic->cacheprospectstatus as $key => $val) { $titlealt = 'default'; - if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt = $val['label']; - if ($obj->stcomm_id != $val['id']) print ''.img_action($titlealt, $val['code'], $val['picto']).''; + if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) { + $titlealt = $val['label']; + } + if ($obj->stcomm_id != $val['id']) { + print ''.img_action($titlealt, $val['code'], $val['picto']).''; + } } print '
    '; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print ''.$contactstatic->getLibStatut(5).''; print $obj->import_key; print "'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '
    '; print $form->showphoto('contact', $object)."\n"; - 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").'
    '; @@ -167,10 +169,8 @@ if ($action == 'edit') print '
    '.$langs->trans("Firstname").''.$object->firstname.''.$langs->trans("Alert").': '; - if (!empty($object->birthday_alert)) - { + if (!empty($object->birthday_alert)) { print '
    '.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).'
    '.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).'
    '.$langs->trans("ThirdParty").''; - print $langs->trans("ContactNotLinkedToCompany"); - print '
    '.$langs->trans("ThirdParty").''; + print $langs->trans("ContactNotLinkedToCompany"); + print '
    '.$langs->trans("UserTitle").''; @@ -268,8 +269,7 @@ if ($action == 'edit') // Date To Birth print '
    '.$langs->trans("DateOfBirth").''.dol_print_date($object->birthday, "day"); @@ -278,14 +278,21 @@ if ($action == 'edit') //var_dump($birthdatearray); $ageyear = convertSecondToTime($now - $object->birthday, 'year') - 1970; $agemonth = convertSecondToTime($now - $object->birthday, 'month') - 1; - if ($ageyear >= 2) print '('.$ageyear.' '.$langs->trans("DurationYears").')'; - elseif ($agemonth >= 2) print '('.$agemonth.' '.$langs->trans("DurationMonths").')'; - else print '('.$agemonth.' '.$langs->trans("DurationMonth").')'; + if ($ageyear >= 2) { + print '('.$ageyear.' '.$langs->trans("DurationYears").')'; + } elseif ($agemonth >= 2) { + print '('.$agemonth.' '.$langs->trans("DurationMonths").')'; + } else { + print '('.$agemonth.' '.$langs->trans("DurationMonth").')'; + } print '   -   '; - if ($object->birthday_alert) print $langs->trans("BirthdayAlertOn"); - else print $langs->trans("BirthdayAlertOff"); + if ($object->birthday_alert) { + print $langs->trans("BirthdayAlertOn"); + } else { + print $langs->trans("BirthdayAlertOff"); + } print ''.$langs->trans("DateOfBirth").'
    '.$langs->trans('ThirdParty').''; print $soc->getNomUrl(1); print ''; @@ -1138,16 +1098,21 @@ if ($action == 'create') } print '
    '.$langs->trans('Discounts').''; - if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); + if ($soc->remise_percent) { + print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); + } else { + print $langs->trans("CompanyHasNoRelativeDiscount"); + } print '. '; $absolute_discount = $soc->getAvailableDiscounts(); - if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); - else print $langs->trans("CompanyHasNoAbsoluteDiscount"); + if ($absolute_discount) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); + } else { + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + } print '.'; print '
    '.$langs->trans("NotePrivate").''; $doleditor = new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); @@ -1212,13 +1175,11 @@ if ($action == 'create') print ''; print ''; - if (is_object($objectsrc)) - { + if (is_object($objectsrc)) { print ''; print ''; - if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) - { + if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) { print '
    '.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed"); } } @@ -1232,8 +1193,7 @@ if ($action == 'create') { $now = dol_now(); - if ($object->id > 0) - { + if ($object->id > 0) { $object->fetch_thirdparty(); $soc = $object->thirdparty; // $soc is used later @@ -1305,10 +1265,9 @@ if ($action == 'create') print $formconfirm; /* - * Contrat - */ - if (!empty($object->brouillon) && $user->rights->contrat->creer) - { + * Contrat + */ + if (!empty($object->brouillon) && $user->rights->contrat->creer) { print ''; print ''; print ''; @@ -1337,14 +1296,14 @@ if ($action == 'create') $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1, 'getFormatedSupplierRef'); // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherContracts").')'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' ('.$langs->trans("OtherContracts").')'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->contrat->creer) - { + if ($user->rights->contrat->creer) { if ($action != 'classify') { $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; } @@ -1385,12 +1344,18 @@ if ($action == 'create') // Line info of thirdparty discounts print '
    '.$langs->trans('Discount').''; - if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); + if ($object->thirdparty->remise_percent) { + print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent); + } else { + print $langs->trans("CompanyHasNoRelativeDiscount"); + } $absolute_discount = $object->thirdparty->getAvailableDiscounts(); print '. '; - if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); - else print $langs->trans("CompanyHasNoAbsoluteDiscount"); + if ($absolute_discount) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); + } else { + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + } print '.'; print '
    '.$langs->trans("PriceUHTCurrency").''.$langs->trans("Qty").''.$langs->trans("Unit").''.$langs->trans("Unit").''.$langs->trans("ReductionShort").''.$langs->trans("BuyingPrice").''.$langs->trans("BuyingPrice").' 
    '; $text = $productstatic->getNomUrl(1, '', 32); - if ($objp->plabel) - { + if ($objp->plabel) { $text .= ' - '; $text .= $objp->plabel; } $description = $objp->description; // Add description in form - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { $text .= (!empty($objp->description) && $objp->description != $objp->plabel) ? '
    '.dol_htmlentitiesbr($objp->description) : ''; $description = ''; // Already added into main visible desc } @@ -1545,35 +1509,35 @@ if ($action == 'create') // Quantity print '
    '.$objp->qty.''.$langs->trans($object->lines[$cursorline - 1]->getLabelOfUnit()).''.$langs->trans($object->lines[$cursorline - 1]->getLabelOfUnit()).''.$objp->remise_percent."% '.price($objp->pa_ht).''.price($objp->pa_ht).''; - if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) - { + if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) { print ''; print ''; print img_picto($langs->trans("MoveToAnotherContract"), 'uparrow'); print ''; } - if ($user->rights->contrat->creer && ($object->statut >= 0)) - { + if ($user->rights->contrat->creer && ($object->statut >= 0)) { print ''; print img_edit(); print ''; } - if ($user->rights->contrat->creer && ($object->statut >= 0)) - { + if ($user->rights->contrat->creer && ($object->statut >= 0)) { print ''; print img_delete(); print ''; @@ -1583,8 +1547,7 @@ if ($action == 'create') print "
    '; - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { $canchangeproduct = 1; if (empty($canchangeproduct)) { $productstatic->id = $objp->fk_product; @@ -1665,7 +1628,9 @@ if ($action == 'create') // editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $nbrows = ROWS_2; - if (!empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows = $conf->global->MAIN_INPUT_DESC_HEIGHT; + if (!empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) { + $nbrows = $conf->global->MAIN_INPUT_DESC_HEIGHT; + } $enable = (isset($conf->global->FCKEDITOR_ENABLE_DETAILS) ? $conf->global->FCKEDITOR_ENABLE_DETAILS : 0); $doleditor = new DolEditor('product_desc', $objp->description, '', 92, 'dolibarr_details', '', false, true, $enable, $nbrows, '90%'); $doleditor->Create(); @@ -1689,8 +1654,7 @@ if ($action == 'create') print ''; print $form->selectUnits($objp->fk_unit, "unit"); print '%'; - if ($objp->fk_product) print ''; + if ($objp->fk_product) { + print ''; + } print ''; @@ -1712,8 +1677,12 @@ if ($action == 'create') print '

    '; + if ($ret == 'html') { + print '
    '; + } } /* - * Confirmation to move service toward another contract - */ - if ($action == 'move' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid')) - { + * Confirmation to move service toward another contract + */ + if ($action == 'move' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid')) { $arraycontractid = array(); - foreach ($arrayothercontracts as $contractcursor) - { + foreach ($arrayothercontracts as $contractcursor) { $arraycontractid[$contractcursor->id] = $contractcursor->ref; } //var_dump($arraycontractid); @@ -1783,10 +1752,9 @@ if ($action == 'create') } /* - * Confirmation de la validation activation - */ - if ($action == 'active' && !$_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) - { + * Confirmation de la validation activation + */ + if ($action == 'active' && !$_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) { $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); $comment = GETPOST('comment', 'alpha'); @@ -1795,16 +1763,14 @@ if ($action == 'create') } /* - * Confirmation de la validation fermeture - */ - if ($action == 'closeline' && !$_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) - { + * Confirmation de la validation fermeture + */ + if ($action == 'closeline' && !$_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) { $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); $comment = GETPOST('comment', 'alpha'); - if (empty($dateactend)) - { + if (empty($dateactend)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors'); } else { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne', 'int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService", dol_print_date($dateactend, "%A %d %B %Y")), "confirm_closeline", '', 0, 1); @@ -1814,28 +1780,23 @@ if ($action == 'create') // Area with status and activation info of line - if ($object->statut > 0) - { + if ($object->statut > 0) { print ''; print ''; print ''; print ''; print ''; @@ -1877,8 +1843,7 @@ if ($action == 'create') } // Form to activate line - if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) - { + if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) { print ''; print ''; @@ -1886,15 +1851,17 @@ if ($action == 'create') // Definie date debut et fin par defaut $dateactstart = $objp->date_debut; - if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - elseif (!$dateactstart) $dateactstart = time(); + if (GETPOST('remonth')) { + $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + } elseif (!$dateactstart) { + $dateactstart = time(); + } $dateactend = $objp->date_fin; - if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - elseif (!$dateactend) - { - if ($objp->fk_product > 0) - { + if (GETPOST('endmonth')) { + $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + } elseif (!$dateactend) { + if ($objp->fk_product > 0) { $product = new Product($db); $product->fetch($objp->fk_product); $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); @@ -1926,8 +1893,7 @@ if ($action == 'create') print ''; } - if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) - { + if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) { /** * Disable a contract line */ @@ -1941,28 +1907,30 @@ if ($action == 'create') // Definie date debut et fin par defaut $dateactstart = $objp->date_debut_reelle; - if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - elseif (!$dateactstart) $dateactstart = time(); + if (GETPOST('remonth')) { + $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + } elseif (!$dateactstart) { + $dateactstart = time(); + } $dateactend = $objp->date_fin_reelle; - if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - elseif (!$dateactend) - { - if ($objp->fk_product > 0) - { + if (GETPOST('endmonth')) { + $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + } elseif (!$dateactend) { + if ($objp->fk_product > 0) { $product = new Product($db); $product->fetch($objp->fk_product); $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); } } $now = dol_now(); - if ($dateactend > $now) $dateactend = $now; + if ($dateactend > $now) { + $dateactend = $now; + } print ''; print ''; print ''; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($resqllist); print ''; @@ -7281,7 +7713,12 @@ class Form print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; $i++; @@ -7295,23 +7732,24 @@ class Form dol_print_error($this->db); } print ''; - if ($num > 0) - { - } //$linktoelem.=($linktoelem?'   ':''); - if ($num > 0) $linktoelemlist .= '
  • '.$langs->trans($possiblelink['label']).' ('.$num.')
  • '; - //else $linktoelem.=$langs->trans($possiblelink['label']); - else $linktoelemlist .= '
  • '.$langs->trans($possiblelink['label']).' (0)
  • '; + if ($num > 0) { + $linktoelemlist .= '
  • '.$langs->trans($possiblelink['label']).' ('.$num.')
  • '; + // } else $linktoelem.=$langs->trans($possiblelink['label']); + } else { + $linktoelemlist .= '
  • '.$langs->trans($possiblelink['label']).' (0)
  • '; + } } } - if ($linktoelemlist) - { + if ($linktoelemlist) { $linktoelem = '
    '.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline - 1]->getLibStatut(4).''; - if ($user->socid == 0) - { - if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline') - { + if ($user->socid == 0) { + if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline') { $tmpaction = 'activateline'; $tmpactionpicto = 'play'; $tmpactiontext = $langs->trans("Activate"); - if ($objp->statut == 4) - { + if ($objp->statut == 4) { $tmpaction = 'unactivateline'; $tmpactionpicto = 'playstop'; $tmpactiontext = $langs->trans("Disable"); } - if (($tmpaction == 'activateline' && $user->rights->contrat->activer) || ($tmpaction == 'unactivateline' && $user->rights->contrat->desactiver)) - { + if (($tmpaction == 'activateline' && $user->rights->contrat->activer) || ($tmpaction == 'unactivateline' && $user->rights->contrat->desactiver)) { print ''; print img_picto($tmpactiontext, $tmpactionpicto); print ''; @@ -1851,8 +1812,11 @@ if ($action == 'create') // Si pas encore active if (!$objp->date_debut_reelle) { print $langs->trans("DateStartReal").': '; - if ($objp->date_debut_reelle) print dol_print_date($db->jdate($objp->date_debut_reelle), 'day'); - else print $langs->trans("ContractStatusNotRunning"); + if ($objp->date_debut_reelle) { + print dol_print_date($db->jdate($objp->date_debut_reelle), 'day'); + } else { + print $langs->trans("ContractStatusNotRunning"); + } } // Si active et en cours if ($objp->date_debut_reelle && !$objp->date_fin_reelle) { @@ -1867,7 +1831,9 @@ if ($action == 'create') print $langs->trans("DateEndReal").': '; print dol_print_date($db->jdate($objp->date_fin_reelle), 'day'); } - if (!empty($objp->comment)) print "  -  ".$objp->comment; + if (!empty($objp->comment)) { + print "  -  ".$objp->comment; + } print ' 
    '; - if ($objp->statut >= 4) - { - if ($objp->statut == 4) - { + if ($objp->statut >= 4) { + if ($objp->statut == 4) { print $langs->trans("DateEndReal").' '; print $form->selectDate($dateactend, "end", $usehm, $usehm, ($objp->date_fin_reelle > 0 ? 0 : 1), "closeline", 1, 1); } @@ -1989,8 +1957,7 @@ if ($action == 'create') print ''; // Form to add new line - if ($user->rights->contrat->creer && ($object->statut == 0)) - { + if ($user->rights->contrat->creer && ($object->statut == 0)) { $dateSelector = 1; print "\n"; @@ -2005,10 +1972,11 @@ if ($action == 'create') print ''; // Array with (n*2)+1 lines // Form to add new line - if ($action != 'editline') - { + if ($action != 'editline') { $forcetoshowtitlelines = 1; - if (empty($object->multicurrency_code)) $object->multicurrency_code = $conf->currency; // TODO Remove this when multicurrency supported on contracts + if (empty($object->multicurrency_code)) { + $object->multicurrency_code = $conf->currency; // TODO Remove this when multicurrency supported on contracts + } // Add free products/services $object->formAddObjectLine(1, $mysoc, $soc); @@ -2026,65 +1994,69 @@ if ($action == 'create') /* - * Buttons - */ + * Buttons + */ - if ($user->socid == 0) - { + if ($user->socid == 0) { print '
    '; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { // Send if (empty($user->socid)) { if ($object->statut == 1) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->contrat->creer)) { print ''; - } else print ''; + } else { + print ''; + } } } - if ($object->statut == 0 && $nbofservices) - { - if ($user->rights->contrat->creer) print ''; - else print ''; + if ($object->statut == 0 && $nbofservices) { + if ($user->rights->contrat->creer) { + print ''; + } else { + print ''; + } } - if ($object->statut == 1) - { - if ($user->rights->contrat->creer) print ''; - else print ''; + if ($object->statut == 1) { + if ($user->rights->contrat->creer) { + print ''; + } else { + print ''; + } } - if (!empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) - { + if (!empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) { $langs->load("orders"); - if ($user->rights->commande->creer) print ''; - else print ''; + if ($user->rights->commande->creer) { + print ''; + } else { + print ''; + } } - if (!empty($conf->facture->enabled) && $object->statut > 0) - { + if (!empty($conf->facture->enabled) && $object->statut > 0) { $langs->load("bills"); - if ($user->rights->facture->creer) print ''; - else print ''; + if ($user->rights->facture->creer) { + print ''; + } else { + print ''; + } } - if ($object->nbofservicesclosed > 0 || $object->nbofserviceswait > 0) - { - if ($user->rights->contrat->activer) - { + if ($object->nbofservicesclosed > 0 || $object->nbofserviceswait > 0) { + if ($user->rights->contrat->activer) { print ''; } else { print ''; } } - if ($object->nbofservicesclosed < $nbofservices) - { - if ($user->rights->contrat->desactiver) - { + if ($object->nbofservicesclosed < $nbofservices) { + if ($user->rights->contrat->desactiver) { print ''; } else { print ''; @@ -2099,10 +2071,12 @@ if ($action == 'create') //} } - if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->nbofservicesclosed > 0) - { - if ($action == 'showclosedlines') print ''; - else print ''; + if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->nbofservicesclosed > 0) { + if ($action == 'showclosedlines') { + print ''; + } else { + print ''; + } } // Clone @@ -2113,8 +2087,7 @@ if ($action == 'create') // On peut supprimer entite si // - Droit de creer + mode brouillon (erreur creation) // - Droit de supprimer - if (($user->rights->contrat->creer && $object->statut == $object::STATUS_DRAFT) || $user->rights->contrat->supprimer) - { + if (($user->rights->contrat->creer && $object->statut == $object::STATUS_DRAFT) || $user->rights->contrat->supprimer) { print ''; } else { print ''; @@ -2129,27 +2102,31 @@ if ($action == 'create') $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '
    '; /* - * Documents generes - */ + * Generated documents + */ $filename = dol_sanitizeFileName($object->ref); - $filedir = $conf->contrat->dir_output."/".dol_sanitizeFileName($object->ref); + $filedir = $conf->contrat->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref); $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; $genallowed = $user->rights->contrat->lire; $delallowed = $user->rights->contrat->creer; - print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); + print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, ($object->model_pdf ? $object->model_pdf : $conf->global->CONTRACT_ADDON_PDF), 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang, '', $object); // Show links to link elements $linktoelem = $form->showLinkToObjectBlock($object, null, array('contrat')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show direct download link + if ($object->statut != Contrat::STATUS_DRAFT && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) { + print '
    '."\n"; + print showDirectDownloadLink($object).'
    '; + } print '
    '; @@ -2168,7 +2145,7 @@ if ($action == 'create') // Presend form $modelmail = 'contract'; $defaulttopic = 'SendContractRef'; - $diroutput = $conf->contrat->dir_output; + $diroutput = $conf->contrat->multidir_output[$object->entity]; $trackid = 'con'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; @@ -2182,8 +2159,7 @@ $db->close(); ?> margin->enabled) && $action == 'editline') -{ +if (!empty($conf->margin->enabled) && $action == 'editline') { // TODO Why this ? To manage margin on contracts ? ?> rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."contrat as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= ' WHERE t.entity IN ('.getEntity('contrat').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -143,8 +152,7 @@ class Contracts extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -155,13 +163,11 @@ class Contracts extends DolibarrApi dol_syslog("API Rest request"); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $contrat_static = new Contrat($this->db); if ($contrat_static->fetch($obj->rowid)) { @@ -196,12 +202,12 @@ class Contracts extends DolibarrApi $this->contract->$field = $value; } /*if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->contract->lines = $lines; - }*/ + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->contract->lines = $lines; + }*/ if ($this->contract->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating contract", array_merge(array($this->contract->error), $this->contract->errors)); } @@ -491,7 +497,9 @@ class Contracts extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->contract->$field = $value; } @@ -667,8 +675,9 @@ class Contracts extends DolibarrApi { $contrat = array(); foreach (Contracts::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $contrat[$field] = $data[$field]; } return $contrat; diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index 36edee80669..02929f281a8 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -9,7 +9,7 @@ * Copyright (C) 2013 Florian Henry * Copyright (C) 2014-2015 Marcos García * Copyright (C) 2018 Nicolas ZABOURI - * Copyright (C) 2018-2020 Frédéric France + * Copyright (C) 2018-2021 Frédéric France * Copyright (C) 2015-2018 Ferran Marcet * * This program is free software; you can redistribute it and/or modify @@ -269,8 +269,7 @@ class Contrat extends CommonObject global $db, $langs, $conf; $langs->load("contracts"); - if (!empty($conf->global->CONTRACT_ADDON)) - { + if (!empty($conf->global->CONTRACT_ADDON)) { $mybool = false; $file = $conf->global->CONTRACT_ADDON.".php"; @@ -286,8 +285,7 @@ class Contrat extends CommonObject $mybool |= @include_once $dir.$file; } - if (!$mybool) - { + if (!$mybool) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -295,8 +293,7 @@ class Contrat extends CommonObject $obj = new $classname(); $numref = $obj->getNextValue($soc, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -325,8 +322,7 @@ class Contrat extends CommonObject { // phpcs:enable $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date, $date_end, $comment); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error; $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors; } @@ -348,8 +344,7 @@ class Contrat extends CommonObject { // phpcs:enable $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error; $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors; } @@ -369,7 +364,9 @@ class Contrat extends CommonObject */ public function activateAll($user, $date_start = '', $notrigger = 0, $comment = '') { - if (empty($date_start)) $date_start = dol_now(); + if (empty($date_start)) { + $date_start = dol_now(); + } $this->db->begin(); @@ -378,16 +375,13 @@ class Contrat extends CommonObject // Load lines $this->fetch_lines(); - foreach ($this->lines as $contratline) - { + foreach ($this->lines as $contratline) { // Open lines not already open - if ($contratline->statut != ContratLigne::STATUS_OPEN) - { + if ($contratline->statut != ContratLigne::STATUS_OPEN) { $contratline->context = $this->context; $result = $contratline->active_line($user, $date_start, -1, $comment); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $contratline->error; $this->errors = $contratline->errors; @@ -396,14 +390,14 @@ class Contrat extends CommonObject } } - if (!$error && $this->statut == 0) - { + if (!$error && $this->statut == 0) { $result = $this->validate($user, '', $notrigger); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -432,17 +426,14 @@ class Contrat extends CommonObject $error = 0; - foreach ($this->lines as $contratline) - { + foreach ($this->lines as $contratline) { // Close lines not already closed - if ($contratline->statut != ContratLigne::STATUS_CLOSED) - { + if ($contratline->statut != ContratLigne::STATUS_CLOSED) { $contratline->date_cloture = $now; $contratline->fk_user_cloture = $user->id; $contratline->statut = ContratLigne::STATUS_CLOSED; $result = $contratline->close_line($user, $now, $comment, $notrigger); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $contratline->error; $this->errors = $contratline->errors; @@ -451,14 +442,14 @@ class Contrat extends CommonObject } } - if (!$error && $this->statut == 0) - { + if (!$error && $this->statut == 0) { $result = $this->validate($user, '', $notrigger); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -491,76 +482,69 @@ class Contrat extends CommonObject $this->fetch_thirdparty(); // A contract is validated so we can move thirdparty to status customer - if (empty($conf->global->CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION)) - { + if (empty($conf->global->CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION)) { $result = $this->thirdparty->set_as_client(); } // Define new ref - if ($force_number) - { + if ($force_number) { $num = $force_number; - } elseif (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + } elseif (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($this->thirdparty); } else { $num = $this->ref; } $this->newref = dol_sanitizeFileName($num); - if ($num) - { + if ($num) { $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$this->db->escape($num)."', statut = 1"; //$sql.= ", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'"; $sql .= " WHERE rowid = ".$this->id." AND statut = 0"; dol_syslog(get_class($this)."::validate", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $error++; $this->error = $this->db->lasterror(); } // Trigger calls - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CONTRACT_VALIDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'contract/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->contract->dir_output.'/'.$oldref; $dirdest = $conf->contract->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -573,8 +557,7 @@ class Contrat extends CommonObject } // Set new ref and define current statut - if (!$error) - { + if (!$error) { $this->ref = $num; $this->statut = 1; $this->brouillon = 0; @@ -584,8 +567,7 @@ class Contrat extends CommonObject $error++; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -621,16 +603,14 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::validate", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $error++; $this->error = $this->db->lasterror(); } // Trigger calls - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CONTRACT_REOPEN', $user); if ($result < 0) { @@ -640,15 +620,13 @@ class Contrat extends CommonObject } // Set new ref and define current status - if (!$error) - { + if (!$error) { $this->statut = 0; $this->brouillon = 1; $this->date_validation = $now; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -678,36 +656,32 @@ class Contrat extends CommonObject $sql .= " fk_commercial_signature, fk_commercial_suivi,"; $sql .= " note_private, note_public, model_pdf, extraparams"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat"; - if (!$id) $sql .= " WHERE entity IN (".getEntity('contract').")"; - else $sql .= " WHERE rowid=".(int) $id; - if ($ref_customer) - { + if (!$id) { + $sql .= " WHERE entity IN (".getEntity('contract').")"; + } else { + $sql .= " WHERE rowid=".(int) $id; + } + if ($ref_customer) { $sql .= " AND ref_customer = '".$this->db->escape($ref_customer)."'"; } - if ($ref_supplier) - { + if ($ref_supplier) { $sql .= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'"; } - if ($ref) - { + if ($ref) { $sql .= " AND ref='".$this->db->escape($ref)."'"; } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num > 1) - { + if ($num > 1) { $this->error = 'Fetch found several records.'; dol_syslog($this->error, LOG_ERR); $result = -2; - } elseif ($num) // $num = 1 - { + } elseif ($num) { // $num = 1 $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $this->id = $obj->rowid; $this->ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref; $this->ref_customer = $obj->ref_customer; @@ -745,8 +719,7 @@ class Contrat extends CommonObject // Lines $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->db->lasterror(); return -3; } @@ -791,8 +764,7 @@ class Contrat extends CommonObject $now = dol_now(); - if (!is_object($extrafields)) - { + if (!is_object($extrafields)) { require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); } @@ -825,13 +797,11 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($result); $line = new ContratLigne($this->db); @@ -908,10 +878,18 @@ class Contrat extends CommonObject //dol_syslog("1 ".$line->desc); //dol_syslog("2 ".$line->product_desc); - if ($line->statut == ContratLigne::STATUS_INITIAL) $this->nbofserviceswait++; - if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) $this->nbofservicesopened++; - if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) $this->nbofservicesexpired++; - if ($line->statut == ContratLigne::STATUS_CLOSED) $this->nbofservicesclosed++; + if ($line->statut == ContratLigne::STATUS_INITIAL) { + $this->nbofserviceswait++; + } + if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) { + $this->nbofservicesopened++; + } + if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) { + $this->nbofservicesexpired++; + } + if ($line->statut == ContratLigne::STATUS_CLOSED) { + $this->nbofservicesclosed++; + } $total_ttc += $objp->total_ttc; // TODO Not saved into database $total_vat += $objp->total_tva; @@ -946,20 +924,20 @@ class Contrat extends CommonObject // Check parameters $paramsok = 1; - if ($this->commercial_signature_id <= 0) - { + if ($this->commercial_signature_id <= 0) { $langs->load("commercial"); $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeSignature")); $paramsok = 0; } - if ($this->commercial_suivi_id <= 0) - { + if ($this->commercial_suivi_id <= 0) { $langs->load("commercial"); $this->error .= ($this->error ? "
    " : ''); $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeFollowUp")); $paramsok = 0; } - if (!$paramsok) return -1; + if (!$paramsok) { + return -1; + } $this->db->begin(); @@ -985,76 +963,66 @@ class Contrat extends CommonObject $sql .= ")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $error = 0; $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat"); // Load object modContract $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis'); - if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') - { + if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $result = dol_include_once('/core/modules/contract/'.$module.'.php'); - if ($result > 0) - { + if ($result > 0) { $modCodeContract = new $module(); if (!empty($modCodeContract->code_auto)) { // Force the ref to a draft value if numbering module is an automatic numbering - $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".$this->id; - if ($this->db->query($sql)) - { - if ($this->id) - { + $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".((int) $this->id); + if ($this->db->query($sql)) { + if ($this->id) { $this->ref = "(PROV".$this->id.")"; } } } } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } // Insert business contacts ('SALESREPSIGN','contrat') - if (!$error) - { + if (!$error) { $result = $this->add_contact($this->commercial_signature_id, 'SALESREPSIGN', 'internal'); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } // Insert business contacts ('SALESREPFOLL','contrat') if (!$error) { $result = $this->add_contact($this->commercial_suivi_id, 'SALESREPFOLL', 'internal'); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } if (!$error) { - if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects - { + if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) - { - foreach ($this->linked_objects as $origin => $tmp_origin_id) - { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { + if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) { + foreach ($this->linked_objects as $origin => $tmp_origin_id) { + if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { $this->error = $this->db->lasterror(); $error++; } @@ -1063,8 +1031,7 @@ class Contrat extends CommonObject { $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { $this->error = $this->db->lasterror(); $error++; } @@ -1072,20 +1039,16 @@ class Contrat extends CommonObject } } - if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) // Get contact from origin object - { + if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object $originforcontact = $this->origin; $originidforcontact = $this->origin_id; - if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order - { + if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; $exp = new Expedition($this->db); $exp->fetch($this->origin_id); $exp->fetchObjectLinked(); - if (count($exp->linkedObjectsIds['commande']) > 0) - { - foreach ($exp->linkedObjectsIds['commande'] as $key => $value) - { + if (count($exp->linkedObjectsIds['commande']) > 0) { + foreach ($exp->linkedObjectsIds['commande'] as $key => $value) { $originforcontact = 'commande'; $originidforcontact = $value->id; break; // We take first one @@ -1097,28 +1060,30 @@ class Contrat extends CommonObject $sqlcontact .= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'"; $resqlcontact = $this->db->query($sqlcontact); - if ($resqlcontact) - { - while ($objcontact = $this->db->fetch_object($resqlcontact)) - { - if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) continue; // ignore this, already forced previously + if ($resqlcontact) { + while ($objcontact = $this->db->fetch_object($resqlcontact)) { + if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) { + continue; // ignore this, already forced previously + } //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n"; $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object } - } else dol_print_error($resqlcontact); + } else { + dol_print_error($resqlcontact); + } } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('CONTRACT_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -1158,29 +1123,29 @@ class Contrat extends CommonObject // Call trigger $result = $this->call_trigger('CONTRACT_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers - if (!$error) - { + if (!$error) { // Delete linked contacts $res = $this->delete_linked_contact(); - if ($res < 0) - { + if ($res < 0) { dol_syslog(get_class($this)."::delete error", LOG_ERR); $error++; } } - if (!$error) - { + if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { // Delete contratdet_log /* $sql = "DELETE cdl"; @@ -1193,17 +1158,14 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->error(); $error++; } $numressql = $this->db->num_rows($resql); - if (!$error && $numressql) - { + if (!$error && $numressql) { $tab_resql = array(); - for ($i = 0; $i < $numressql; $i++) - { + for ($i = 0; $i < $numressql; $i++) { $objresql = $this->db->fetch_object($resql); $tab_resql[] = $objresql->cdlrowid; } @@ -1214,8 +1176,7 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->error(); $error++; } @@ -1231,23 +1192,20 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::delete contratdet_extrafields", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->error(); $error++; } } - if (!$error) - { + if (!$error) { // Delete contratdet $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet"; $sql .= " WHERE fk_contrat=".$this->id; dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->error(); $error++; } @@ -1257,8 +1215,7 @@ class Contrat extends CommonObject if (!$error) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".$this->id; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->lasterror(); $this->errors[] = $this->error; $error++; @@ -1266,15 +1223,13 @@ class Contrat extends CommonObject } // Delete contract - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->error(); $error++; } @@ -1283,25 +1238,20 @@ class Contrat extends CommonObject // Removed extrafields if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR); } } - if (!$error) - { + if (!$error) { // We remove directory $ref = dol_sanitizeFileName($this->ref); - if ($conf->contrat->dir_output) - { - $dir = $conf->contrat->dir_output."/".$ref; - if (file_exists($dir)) - { + if ($conf->contrat->dir_output) { + $dir = $conf->contrat->multidir_output[$this->entity]."/".$ref; + if (file_exists($dir)) { $res = @dol_delete_dir_recursive($dir); - if (!$res) - { + if (!$res) { $this->error = 'ErrorFailToDeleteDir'; $error++; } @@ -1309,8 +1259,7 @@ class Contrat extends CommonObject } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1333,23 +1282,55 @@ class Contrat extends CommonObject $error = 0; // Clean parameters - if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) $this->fk_commercial_signature = $this->commercial_signature_id; - if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) $this->fk_commercial_suivi = $this->commercial_suivi_id; - if (empty($this->fk_soc) && $this->socid > 0) $this->fk_soc = (int) $this->socid; - if (empty($this->fk_project) && $this->projet > 0) $this->fk_project = (int) $this->projet; + if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) { + $this->fk_commercial_signature = $this->commercial_signature_id; + } + if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) { + $this->fk_commercial_suivi = $this->commercial_suivi_id; + } + if (empty($this->fk_soc) && $this->socid > 0) { + $this->fk_soc = (int) $this->socid; + } + if (empty($this->fk_project) && $this->projet > 0) { + $this->fk_project = (int) $this->projet; + } - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->ref_customer)) $this->ref_customer = trim($this->ref_customer); - if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier); - if (isset($this->ref_ext)) $this->ref_ext = trim($this->ref_ext); - if (isset($this->entity)) $this->entity = (int) $this->entity; - if (isset($this->statut)) $this->statut = (int) $this->statut; - if (isset($this->fk_soc)) $this->fk_soc = (int) $this->fk_soc; - if (isset($this->fk_commercial_signature)) $this->fk_commercial_signature = trim($this->fk_commercial_signature); - if (isset($this->fk_commercial_suivi)) $this->fk_commercial_suivi = trim($this->fk_commercial_suivi); - if (isset($this->note_private)) $this->note_private = trim($this->note_private); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->import_key)) $this->import_key = trim($this->import_key); + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->ref_customer)) { + $this->ref_customer = trim($this->ref_customer); + } + if (isset($this->ref_supplier)) { + $this->ref_supplier = trim($this->ref_supplier); + } + if (isset($this->ref_ext)) { + $this->ref_ext = trim($this->ref_ext); + } + if (isset($this->entity)) { + $this->entity = (int) $this->entity; + } + if (isset($this->statut)) { + $this->statut = (int) $this->statut; + } + if (isset($this->fk_soc)) { + $this->fk_soc = (int) $this->fk_soc; + } + if (isset($this->fk_commercial_signature)) { + $this->fk_commercial_signature = trim($this->fk_commercial_signature); + } + if (isset($this->fk_commercial_suivi)) { + $this->fk_commercial_suivi = trim($this->fk_commercial_suivi); + } + if (isset($this->note_private)) { + $this->note_private = trim($this->note_private); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->import_key)) { + $this->import_key = trim($this->import_key); + } //if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams); // Check parameters @@ -1372,35 +1353,34 @@ class Contrat extends CommonObject $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").","; $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").""; //$sql.= " extraparams=".(isset($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null").""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call triggers $result = $this->call_trigger('CONTRACT_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -1444,14 +1424,12 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang"); // Check parameters - if ($fk_product <= 0 && empty($desc)) - { + if ($fk_product <= 0 && empty($desc)) { $this->error = "ErrorDescRequiredForFreeProductLines"; return -1; } - if ($this->statut >= 0) - { + if ($this->statut >= 0) { // Clean parameters $pu_ht = price2num($pu_ht); $pu_ttc = price2num($pu_ttc); @@ -1460,8 +1438,7 @@ class Contrat extends CommonObject // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -1471,23 +1448,38 @@ class Contrat extends CommonObject $remise_percent = price2num($remise_percent); $qty = price2num($qty); - if (empty($qty)) $qty = 1; - if (empty($info_bits)) $info_bits = 0; - if (empty($pu_ht) || !is_numeric($pu_ht)) $pu_ht = 0; - if (empty($pu_ttc)) $pu_ttc = 0; - if (empty($txtva) || !is_numeric($txtva)) $txtva = 0; - if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) $txlocaltax2 = 0; + if (empty($qty)) { + $qty = 1; + } + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($pu_ht) || !is_numeric($pu_ht)) { + $pu_ht = 0; + } + if (empty($pu_ttc)) { + $pu_ttc = 0; + } + if (empty($txtva) || !is_numeric($txtva)) { + $txtva = 0; + } + if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) { + $txlocaltax2 = 0; + } - if ($price_base_type == 'HT') - { + if ($price_base_type == 'HT') { $pu = $pu_ht; } else { $pu = $pu_ttc; } // Check parameters - if (empty($remise_percent)) $remise_percent = 0; + if (empty($remise_percent)) { + $remise_percent = 0; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); @@ -1518,20 +1510,19 @@ class Contrat extends CommonObject // Anciens indicateurs: $price, $remise (a ne plus utiliser) $remise = 0; $price = price2num(round($pu_ht, 2)); - if (dol_strlen($remise_percent) > 0) - { + if (dol_strlen($remise_percent) > 0) { $remise = round(($pu_ht * $remise_percent / 100), 2); $price = $pu_ht - $remise; } - if (empty($pa_ht)) $pa_ht = 0; + if (empty($pa_ht)) { + $pa_ht = 0; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0) - { - if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0) - { + if ($this->pa_ht == 0) { + if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0) { return $result; } else { $pa_ht = $result; @@ -1545,8 +1536,12 @@ class Contrat extends CommonObject $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,"; $sql .= " info_bits,"; $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht"; - if ($date_start > 0) { $sql .= ",date_ouverture_prevue"; } - if ($date_end > 0) { $sql .= ",date_fin_validite"; } + if ($date_start > 0) { + $sql .= ",date_ouverture_prevue"; + } + if ($date_end > 0) { + $sql .= ",date_fin_validite"; + } $sql .= ", fk_unit"; $sql .= ") VALUES ("; $sql .= $this->id.", '', '".$this->db->escape($desc)."',"; @@ -1563,28 +1558,35 @@ class Contrat extends CommonObject $sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).","; $sql .= " '".$this->db->escape($info_bits)."',"; $sql .= " ".price2num($price).",".price2num($remise).","; - if (isset($fk_fournprice)) $sql .= ' '.$fk_fournprice.','; - else $sql .= ' null,'; - if (isset($pa_ht)) $sql .= ' '.price2num($pa_ht); - else $sql .= ' null'; - if ($date_start > 0) { $sql .= ",'".$this->db->idate($date_start)."'"; } - if ($date_end > 0) { $sql .= ",'".$this->db->idate($date_end)."'"; } + if (isset($fk_fournprice)) { + $sql .= ' '.$fk_fournprice.','; + } else { + $sql .= ' null,'; + } + if (isset($pa_ht)) { + $sql .= ' '.price2num($pa_ht); + } else { + $sql .= ' null'; + } + if ($date_start > 0) { + $sql .= ",'".$this->db->idate($date_start)."'"; + } + if ($date_end > 0) { + $sql .= ",'".$this->db->idate($date_end)."'"; + } $sql .= ", ".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null"); $sql .= ")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet"); - if (!$error) - { + if (!$error) { $contractline = new ContratLigne($this->db); $contractline->array_options = $array_options; $contractline->id = $contractlineid; $result = $contractline->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->error[] = $contractline->error; $error++; } @@ -1593,15 +1595,13 @@ class Contrat extends CommonObject if (empty($error)) { // Call trigger $result = $this->call_trigger('LINECONTRACT_INSERT', $user); - if ($result < 0) - { + if ($result < 0) { $error++; } // End call triggers } - if ($error) - { + if ($error) { $this->db->rollback(); return -1; } else { @@ -1657,12 +1657,13 @@ class Contrat extends CommonObject $localtax1tx = price2num($localtax1tx); $localtax2tx = price2num($localtax2tx); $pa_ht = price2num($pa_ht); - if (empty($fk_fournprice)) $fk_fournprice = 0; + if (empty($fk_fournprice)) { + $fk_fournprice = 0; + } $subprice = $price; $remise = 0; - if (dol_strlen($remise_percent) > 0) - { + if (dol_strlen($remise_percent) > 0) { $remise = round(($pu * $remise_percent / 100), 2); $price = $pu - $remise; } else { @@ -1701,19 +1702,18 @@ class Contrat extends CommonObject // Anciens indicateurs: $price, $remise (a ne plus utiliser) $remise = 0; $price = price2num(round($pu, 2)); - if (dol_strlen($remise_percent) > 0) - { + if (dol_strlen($remise_percent) > 0) { $remise = round(($pu * $remise_percent / 100), 2); $price = $pu - $remise; } - if (empty($pa_ht)) $pa_ht = 0; + if (empty($pa_ht)) { + $pa_ht = 0; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0) - { - if (($result = $this->defineBuyPrice($pu, $remise_percent)) < 0) - { + if ($this->pa_ht == 0) { + if (($result = $this->defineBuyPrice($pu, $remise_percent)) < 0) { return $result; } else { $pa_ht = $result; @@ -1738,22 +1738,35 @@ class Contrat extends CommonObject $sql .= ", total_ttc='".price2num($total_ttc)."'"; $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null"); $sql .= ", buy_price_ht='".price2num($pa_ht)."'"; - if ($date_start > 0) { $sql .= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; } else { $sql .= ",date_ouverture_prevue=null"; } - if ($date_end > 0) { $sql .= ",date_fin_validite='".$this->db->idate($date_end)."'"; } else { $sql .= ",date_fin_validite=null"; } - if ($date_debut_reel > 0) { $sql .= ",date_ouverture='".$this->db->idate($date_debut_reel)."'"; } else { $sql .= ",date_ouverture=null"; } - if ($date_fin_reel > 0) { $sql .= ",date_cloture='".$this->db->idate($date_fin_reel)."'"; } else { $sql .= ",date_cloture=null"; } + if ($date_start > 0) { + $sql .= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; + } else { + $sql .= ",date_ouverture_prevue=null"; + } + if ($date_end > 0) { + $sql .= ",date_fin_validite='".$this->db->idate($date_end)."'"; + } else { + $sql .= ",date_fin_validite=null"; + } + if ($date_debut_reel > 0) { + $sql .= ",date_ouverture='".$this->db->idate($date_debut_reel)."'"; + } else { + $sql .= ",date_ouverture=null"; + } + if ($date_fin_reel > 0) { + $sql .= ",date_cloture='".$this->db->idate($date_fin_reel)."'"; + } else { + $sql .= ",date_cloture=null"; + } $sql .= ", fk_unit=".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null"); $sql .= " WHERE rowid = ".$rowid; dol_syslog(get_class($this)."::updateline", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $result = $this->update_statut($user); - if ($result >= 0) - { - if (is_array($array_options) && count($array_options) > 0) // For avoid conflicts if trigger used - { + if ($result >= 0) { + if (is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used $contractline = new ContratLigne($this->db); $contractline->fetch($rowid); $contractline->fetch_optionals(); @@ -1764,8 +1777,7 @@ class Contrat extends CommonObject } $result = $contractline->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->error[] = $contractline->error; $error++; } @@ -1774,8 +1786,7 @@ class Contrat extends CommonObject if (empty($error)) { // Call trigger $result = $this->call_trigger('LINECONTRACT_UPDATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -3; } @@ -1810,11 +1821,12 @@ class Contrat extends CommonObject $error = 0; - if ($this->statut >= 0) - { + if ($this->statut >= 0) { // Call trigger $result = $this->call_trigger('LINECONTRACT_DELETE', $user); - if ($result < 0) return -1; + if ($result < 0) { + return -1; + } // End call triggers $this->db->begin(); @@ -1824,8 +1836,7 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::deleteline", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = "Error ".$this->db->lasterror(); $error++; } @@ -1835,8 +1846,7 @@ class Contrat extends CommonObject $contractline = new ContratLigne($this->db); $contractline->id = $idline; $result = $contractline->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = "Error ".get_class($this)."::deleteline deleteExtraFields error -4 ".$contractline->error; } @@ -1871,7 +1881,9 @@ class Contrat extends CommonObject dol_syslog(__METHOD__." is deprecated", LOG_WARNING); // If draft, we keep it (should not happen) - if ($this->statut == 0) return 1; + if ($this->statut == 0) { + return 1; + } // Load $this->lines array // $this->fetch_lines(); @@ -1910,8 +1922,7 @@ class Contrat extends CommonObject // phpcs:enable global $langs; - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; $langs->load("contracts"); $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft'); @@ -1923,10 +1934,11 @@ class Contrat extends CommonObject } $statusType = 'status'.$status; - if ($status == self::STATUS_VALIDATED) $statusType = 'status6'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status6'; + } - if ($mode == 4 || $mode == 6 || $mode == 7) - { + if ($mode == 4 || $mode == 6 || $mode == 7) { $text = ''; if ($mode == 4) { $text = ''; @@ -1972,8 +1984,12 @@ class Contrat extends CommonObject //{ // 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'; + } //} $label = ''; @@ -1985,7 +2001,8 @@ class Contrat extends CommonObject $label .= ' '.$this->getLibStatut(5); }*/ $label .= '
    '.$langs->trans('Ref').': '.($this->ref ? $this->ref : $this->id); - $label .= '
    '.$langs->trans('RefCustomer').': '.($this->ref_customer ? $this->ref_customer : $this->ref_client); + $ref_customer = (!empty($this->ref_customer) ? $this->ref_customer : (empty($this->ref_client) ? '' : $this->ref_client)); + $label .= '
    '.$langs->trans('RefCustomer').': '.$ref_customer; $label .= '
    '.$langs->trans('RefSupplier').': '.$this->ref_supplier; if (!empty($this->total_ht)) { $label .= '
    '.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); @@ -1999,10 +2016,8 @@ class Contrat extends CommonObject } $linkclose = ''; - if (empty($notooltip) && $user->rights->contrat->lire) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip) && $user->rights->contrat->lire) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowOrder"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -2015,8 +2030,12 @@ class Contrat extends CommonObject $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= ($this->ref ? $this->ref : $this->id); + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= ($this->ref ? $this->ref : $this->id); + } $result .= $linkend; global $action; @@ -2047,10 +2066,8 @@ class Contrat extends CommonObject $sql .= " WHERE c.rowid = ".((int) $id); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -2087,16 +2104,16 @@ class Contrat extends CommonObject $sql = "SELECT cd.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= " WHERE fk_contrat =".$this->id; - if ($status >= 0) $sql .= " AND statut = ".$status; + if ($status >= 0) { + $sql .= " AND statut = ".$status; + } dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $tab[$i] = $obj->rowid; $i++; @@ -2121,16 +2138,16 @@ class Contrat extends CommonObject $sql = "SELECT c.rowid, c.ref"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c"; $sql .= " WHERE fk_soc =".$this->socid; - if ($option == 'others') $sql .= " AND c.rowid != ".$this->id; + if ($option == 'others') { + $sql .= " AND c.rowid != ".$this->id; + } dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $contrat = new Contrat($this->db); $contrat->fetch($obj->rowid); @@ -2161,25 +2178,24 @@ class Contrat extends CommonObject $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c"; $this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $this->from .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$user->socid) $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$user->socid) { + $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } - if ($mode == 'inactive') - { + if ($mode == 'inactive') { $sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin"; $sql .= $this->from; $sql .= " WHERE c.statut = 1"; $sql .= " AND c.rowid = cd.fk_contrat"; $sql .= " AND cd.statut = 0"; - } elseif ($mode == 'expired') - { + } elseif ($mode == 'expired') { $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin"; $sql .= $this->from; $sql .= " WHERE c.statut = 1"; $sql .= " AND c.rowid = cd.fk_contrat"; $sql .= " AND cd.statut = 4"; $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'"; - } elseif ($mode == 'active') - { + } elseif ($mode == 'active') { $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin"; $sql .= $this->from; $sql .= " WHERE c.statut = 1"; @@ -2190,12 +2206,15 @@ class Contrat extends CommonObject } $sql .= " AND c.fk_soc = s.rowid"; $sql .= " AND c.entity = ".$conf->entity; - if ($user->socid) $sql .= " AND c.fk_soc = ".$user->socid; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) { + $sql .= " AND c.fk_soc = ".$user->socid; + } + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $langs->load("contracts"); $now = dol_now(); @@ -2225,8 +2244,7 @@ class Contrat extends CommonObject $response->url = $url; $response->img = img_object('', "contract"); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) { @@ -2259,8 +2277,7 @@ class Contrat extends CommonObject $sql = "SELECT count(c.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -2268,10 +2285,8 @@ class Contrat extends CommonObject $sql .= " ".$clause." c.entity = ".$conf->entity; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["contracts"] = $obj->nb; } $this->db->free($resql); @@ -2328,12 +2343,10 @@ class Contrat extends CommonObject $sql .= $this->db->plimit(100); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -2359,8 +2372,7 @@ class Contrat extends CommonObject // Lines $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new ContratLigne($this->db); $line->qty = 1; $line->subprice = 100; @@ -2374,8 +2386,7 @@ class Contrat extends CommonObject $line->date_start_real = dol_now() - 200000; $line->date_end = dol_now() + 500000; $line->date_end_real = dol_now() - 100000; - if ($num_prods > 0) - { + if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; } @@ -2478,15 +2489,12 @@ class Contrat extends CommonObject // Clean data $clonedObj->statut = 0; // Clean extrafields - if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) - { + if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) { $extrafields->fetch_name_optionals_label($this->table_element); - foreach ($clonedObj->array_options as $key => $option) - { + foreach ($clonedObj->array_options as $key => $option) { $shortkey = preg_replace('/options_/', '', $key); //var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]); - if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) - { + if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) { //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; unset($clonedObj->array_options[$key]); } @@ -2546,8 +2554,9 @@ class Contrat extends CommonObject ); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) + if ($reshook < 0) { $error++; + } } } @@ -2756,12 +2765,15 @@ class ContratLigne extends CommonObjectLine } $statusType = 'status'.$status; - if ($status == self::STATUS_OPEN && $expired == 1) $statusType = 'status1'; - if ($status == self::STATUS_CLOSED) $statusType = 'status6'; + if ($status == self::STATUS_OPEN && $expired == 1) { + $statusType = 'status1'; + } + if ($status == self::STATUS_CLOSED) { + $statusType = 'status6'; + } $params = array(); $reg = array(); - if (preg_match('/class="(.*)"/', $moreatt, $reg)) - { + if (preg_match('/class="(.*)"/', $moreatt, $reg)) { $params = array('badgeParams'=>array('css' => $reg[1])); } return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $params); @@ -2780,17 +2792,27 @@ class ContratLigne extends CommonObjectLine $result = ''; $label = $langs->trans("ShowContractOfService").': '.$this->label; - if (empty($label)) $label = $this->description; + if (empty($label)) { + $label = $this->description; + } $link = ''; $linkend = ''; $picto = 'service'; - if ($this->type == 0) $picto = 'product'; + if ($this->type == 0) { + $picto = 'product'; + } - if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); - if ($withpicto && $withpicto != 2) $result .= ' '; - if ($withpicto != 2) $result .= $link.($this->product_ref ? $this->product_ref.' ' : '').($this->label ? $this->label : $this->description).$linkend; + if ($withpicto) { + $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + if ($withpicto != 2) { + $result .= $link.($this->product_ref ? $this->product_ref.' ' : '').($this->label ? $this->label : $this->description).$linkend; + } return $result; } @@ -2804,7 +2826,9 @@ class ContratLigne extends CommonObjectLine public function fetch($id, $ref = '') { // Check parameters - if (empty($id) && empty($ref)) return -1; + if (empty($id) && empty($ref)) { + return -1; + } $sql = "SELECT"; $sql .= " t.rowid,"; @@ -2849,15 +2873,17 @@ class ContratLigne extends CommonObjectLine $sql .= " t.commentaire,"; $sql .= " t.fk_unit"; $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product"; - if ($id) $sql .= " WHERE t.rowid = ".$id; - if ($ref) $sql .= " WHERE t.rowid = '".$this->db->escape($ref)."'"; + if ($id) { + $sql .= " WHERE t.rowid = ".((int) $id); + } + if ($ref) { + $sql .= " WHERE t.rowid = '".$this->db->escape($ref)."'"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -2966,18 +2992,40 @@ class ContratLigne extends CommonObjectLine $this->fk_user_cloture = (int) $this->fk_user_cloture; $this->commentaire = trim($this->commentaire); //if (empty($this->subprice)) $this->subprice = 0; - if (empty($this->price_ht)) $this->price_ht = 0; - if (empty($this->total_ht)) $this->total_ht = 0; - if (empty($this->total_tva)) $this->total_tva = 0; - if (empty($this->total_ttc)) $this->total_ttc = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->remise_percent)) $this->remise_percent = 0; + if (empty($this->price_ht)) { + $this->price_ht = 0; + } + if (empty($this->total_ht)) { + $this->total_ht = 0; + } + if (empty($this->total_tva)) { + $this->total_tva = 0; + } + if (empty($this->total_ttc)) { + $this->total_ttc = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } // For backward compatibility - if (empty($this->date_start)) $this->date_start = $this->date_ouverture_prevue; - if (empty($this->date_start_real)) $this->date_start = $this->date_ouverture; - if (empty($this->date_end)) $this->date_start = $this->date_fin_validite; - if (empty($this->date_end_real)) $this->date_start = $this->date_cloture; + if (empty($this->date_start)) { + $this->date_start = $this->date_ouverture_prevue; + } + if (empty($this->date_start_real)) { + $this->date_start = $this->date_ouverture; + } + if (empty($this->date_end)) { + $this->date_start = $this->date_fin_validite; + } + if (empty($this->date_end_real)) { + $this->date_start = $this->date_cloture; + } // Check parameters @@ -2996,13 +3044,13 @@ class ContratLigne extends CommonObjectLine $this->total_localtax1 = $tabprice[9]; $this->total_localtax2 = $tabprice[10]; - if (empty($this->pa_ht)) $this->pa_ht = 0; + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0) - { - if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) - { + if ($this->pa_ht == 0) { + if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { return $result; } else { $this->pa_ht = $result; @@ -3051,50 +3099,42 @@ class ContratLigne extends CommonObjectLine $sql .= " fk_user_cloture=".($this->fk_user_cloture > 0 ? $this->fk_user_cloture : "NULL").","; $sql .= " commentaire='".$this->db->escape($this->commentaire)."',"; $sql .= " fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); - $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) - { + if (!$resql) { $this->error = "Error ".$this->db->lasterror(); $error++; } - if (!$error) // For avoid conflicts if trigger used - { + if (!$error) { // For avoid conflicts if trigger used $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } // If we change a planned date (start or end), sync dates for all services - if (!$error && !empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES)) - { - if ($this->date_ouverture_prevue != $this->oldcopy->date_ouverture_prevue) - { + if (!$error && !empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES)) { + if ($this->date_ouverture_prevue != $this->oldcopy->date_ouverture_prevue) { $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET'; $sql .= " date_ouverture_prevue = ".($this->date_ouverture_prevue != '' ? "'".$this->db->idate($this->date_ouverture_prevue)."'" : "null"); $sql .= " WHERE fk_contrat = ".$this->fk_contrat; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = "Error ".$this->db->lasterror(); } } - if ($this->date_fin_validite != $this->oldcopy->date_fin_validite) - { + if ($this->date_fin_validite != $this->oldcopy->date_fin_validite) { $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET'; $sql .= " date_fin_validite = ".($this->date_fin_validite != '' ? "'".$this->db->idate($this->date_fin_validite)."'" : "null"); $sql .= " WHERE fk_contrat = ".$this->fk_contrat; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = "Error ".$this->db->lasterror(); } @@ -3111,8 +3151,7 @@ class ContratLigne extends CommonObjectLine // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -3147,8 +3186,7 @@ class ContratLigne extends CommonObjectLine dol_syslog(get_class($this)."::update_total", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { @@ -3178,8 +3216,12 @@ class ContratLigne extends CommonObjectLine $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,"; $sql .= " info_bits,"; $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht"; - if ($this->date_ouverture_prevue > 0) { $sql .= ",date_ouverture_prevue"; } - if ($this->date_fin_validite > 0) { $sql .= ",date_fin_validite"; } + if ($this->date_ouverture_prevue > 0) { + $sql .= ",date_ouverture_prevue"; + } + if ($this->date_fin_validite > 0) { + $sql .= ",date_fin_validite"; + } $sql .= ") VALUES ($this->fk_contrat, '', '".$this->db->escape($this->description)."',"; $sql .= ($this->fk_product > 0 ? $this->fk_product : "null").","; $sql .= " '".$this->db->escape($this->qty)."',"; @@ -3193,34 +3235,40 @@ class ContratLigne extends CommonObjectLine $sql .= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).","; $sql .= " '".$this->db->escape($this->info_bits)."',"; $sql .= " ".price2num($this->price_ht).",".price2num($this->remise).","; - if ($this->fk_fournprice > 0) $sql .= ' '.$this->fk_fournprice.','; - else $sql .= ' null,'; - if ($this->pa_ht > 0) $sql .= ' '.price2num($this->pa_ht); - else $sql .= ' null'; - if ($this->date_ouverture > 0) { $sql .= ",'".$this->db->idate($this->date_ouverture)."'"; } - if ($this->date_cloture > 0) { $sql .= ",'".$this->db->idate($this->date_cloture)."'"; } + if ($this->fk_fournprice > 0) { + $sql .= ' '.$this->fk_fournprice.','; + } else { + $sql .= ' null,'; + } + if ($this->pa_ht > 0) { + $sql .= ' '.price2num($this->pa_ht); + } else { + $sql .= ' null'; + } + if ($this->date_ouverture > 0) { + $sql .= ",'".$this->db->idate($this->date_ouverture)."'"; + } + if ($this->date_cloture > 0) { + $sql .= ",'".$this->db->idate($this->date_cloture)."'"; + } $sql .= ")"; dol_syslog(get_class($this)."::insert", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'contratdet'); // Insert of extrafields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } } - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINECONTRACT_INSERT', $user); if ($result < 0) { @@ -3260,7 +3308,9 @@ class ContratLigne extends CommonObjectLine $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".ContratLigne::STATUS_OPEN.","; $sql .= " date_ouverture = ".(dol_strlen($date) != 0 ? "'".$this->db->idate($date)."'" : "null").","; - if ($date_end >= 0) $sql .= " date_fin_validite = ".(dol_strlen($date_end) != 0 ? "'".$this->db->idate($date_end)."'" : "null").","; + if ($date_end >= 0) { + $sql .= " date_fin_validite = ".(dol_strlen($date_end) != 0 ? "'".$this->db->idate($date_end)."'" : "null").","; + } $sql .= " fk_user_ouverture = ".$user->id.","; $sql .= " date_cloture = null,"; $sql .= " commentaire = '".$this->db->escape($comment)."'"; @@ -3271,11 +3321,12 @@ class ContratLigne extends CommonObjectLine if ($resql) { // Call trigger $result = $this->call_trigger('LINECONTRACT_ACTIVATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if (!$error) - { + if (!$error) { $this->statut = ContratLigne::STATUS_OPEN; $this->date_ouverture = $date; $this->date_fin_validite = $date_end; @@ -3329,10 +3380,8 @@ class ContratLigne extends CommonObjectLine $sql .= " WHERE rowid = ".$this->id." AND statut = ".ContratLigne::STATUS_OPEN; $resql = $this->db->query($sql); - if ($resql) - { - if (!$notrigger) - { + if ($resql) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINECONTRACT_CLOSE', $user); if ($result < 0) { diff --git a/htdocs/contrat/contact.php b/htdocs/contrat/contact.php index c837769819a..35b7268109b 100644 --- a/htdocs/contrat/contact.php +++ b/htdocs/contrat/contact.php @@ -43,7 +43,9 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $id); $object = new Contrat($db); @@ -56,19 +58,16 @@ $hookmanager->initHooks(array('contractcard', 'globalcard')); * Actions */ -if ($action == 'addcontact' && $user->rights->contrat->creer) -{ +if ($action == 'addcontact' && $user->rights->contrat->creer) { $result = $object->fetch($id); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -84,10 +83,8 @@ if ($action == 'addcontact' && $user->rights->contrat->creer) } // bascule du statut d'un contact -if ($action == 'swapstatut' && $user->rights->contrat->creer) -{ - if ($object->fetch($id)) - { +if ($action == 'swapstatut' && $user->rights->contrat->creer) { + if ($object->fetch($id)) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { dol_print_error($db, $object->error); @@ -95,13 +92,11 @@ if ($action == 'swapstatut' && $user->rights->contrat->creer) } // Delete contact -if ($action == 'deletecontact' && $user->rights->contrat->creer) -{ +if ($action == 'deletecontact' && $user->rights->contrat->creer) { $object->fetch($id); $result = $object->delete_contact($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } @@ -125,10 +120,8 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref) > 0) - { +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { $object->fetch_thirdparty(); $head = contract_prepare_head($object); @@ -146,9 +139,9 @@ if ($id > 0 || !empty($ref)) //if (! empty($modCodeContract->code_auto)) { $morehtmlref .= $object->ref; /*} else { - $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3); - $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2); - }*/ + $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3); + $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2); + }*/ $morehtmlref .= '
    '; // Ref customer @@ -213,8 +206,11 @@ if ($id > 0 || !empty($ref)) } $absolute_discount = $object->thirdparty->getAvailableDiscounts(); print '. '; - if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); - else print $langs->trans("CompanyHasNoAbsoluteDiscount"); + if ($absolute_discount) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); + } else { + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + } print '.'; print ''; diff --git a/htdocs/contrat/document.php b/htdocs/contrat/document.php index b68da3170ed..8e5b1281c47 100644 --- a/htdocs/contrat/document.php +++ b/htdocs/contrat/document.php @@ -46,8 +46,7 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { unset($_GET["action"]); $action = ''; $socid = $user->socid; @@ -59,22 +58,27 @@ $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"; +} $object = new Contrat($db); $object->fetch($id, $ref); -if ($object->id > 0) -{ +if ($object->id > 0) { $object->fetch_thirdparty(); } -$upload_dir = $conf->contrat->dir_output.'/'.dol_sanitizeFileName($object->ref); +$upload_dir = $conf->contrat->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); $modulepart = 'contract'; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -85,7 +89,7 @@ $hookmanager->initHooks(array('contractcard', 'globalcard')); * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -97,8 +101,7 @@ $form = new Form($db); llxHeader('', $langs->trans("Contract"), ""); -if ($object->id) -{ +if ($object->id) { $head = contract_prepare_head($object); print dol_get_fiche_head($head, 'documents', $langs->trans("Contract"), -1, 'contract'); @@ -107,8 +110,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -136,17 +138,18 @@ if ($object->id) $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1, 'getFormatedSupplierRef'); // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherContracts").')'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' ('.$langs->trans("OtherContracts").')'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->contrat->creer) - { - if ($action != 'classify') + if ($user->rights->contrat->creer) { + if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; $morehtmlref .= ' : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '
    '; diff --git a/htdocs/contrat/index.php b/htdocs/contrat/index.php index 5ea558c9689..6b1aecf1162 100644 --- a/htdocs/contrat/index.php +++ b/htdocs/contrat/index.php @@ -46,7 +46,9 @@ $statut = GETPOST('statut') ?GETPOST('statut') : 1; // Security check $socid = 0; $id = GETPOST('id', 'int'); -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $id); $staticcompany = new Societe($db); @@ -78,11 +80,9 @@ print load_fiche_titre($langs->trans("ContractsArea"), '', 'contract'); print '
    '; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo // Search contract - if (!empty($conf->contrat->enabled)) - { + if (!empty($conf->contrat->enabled)) { print ''; print ''; @@ -112,26 +112,28 @@ $vals = array(); $sql = "SELECT count(cd.rowid) as nb, cd.statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE cd.fk_contrat = c.rowid AND c.fk_soc = s.rowid"; $sql .= " AND (cd.statut != 4 OR (cd.statut = 4 AND (cd.date_fin_validite is null or cd.date_fin_validite >= '".$db->idate($now)."')))"; $sql .= " AND c.entity IN (".getEntity('contract', 0).")"; -if ($user->socid) $sql .= ' AND c.fk_soc = '.$user->socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($user->socid) { + $sql .= ' AND c.fk_soc = '.$user->socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " GROUP BY cd.statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $nb[$obj->status] = $obj->nb; - if ($obj->status != 5) - { + if ($obj->status != 5) { $vals[$obj->status] = $obj->nb; $totalinprocess += $obj->nb; } @@ -147,28 +149,30 @@ if ($resql) $sql = "SELECT count(cd.rowid) as nb, cd.statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE cd.fk_contrat = c.rowid AND c.fk_soc = s.rowid"; $sql .= " AND (cd.statut = 4 AND cd.date_fin_validite < '".$db->idate($now)."')"; $sql .= " AND c.entity IN (".getEntity('contract', 0).")"; -if ($user->socid) $sql .= ' AND c.fk_soc = '.$user->socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($user->socid) { + $sql .= ' AND c.fk_soc = '.$user->socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " GROUP BY cd.statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); // 0 inactive, 4 active, 5 closed $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $nb[$obj->status.true] = $obj->nb; - if ($obj->status != 5) - { + if ($obj->status != 5) { $vals[$obj->status.true] = $obj->nb; $totalinprocess += $obj->nb; } @@ -189,26 +193,34 @@ print '
    '; print '
    '; print ''."\n"; $listofstatus = array(0, 4, 4, 5); $bool = false; -foreach ($listofstatus as $status) -{ +foreach ($listofstatus as $status) { $dataseries[] = array($staticcontratligne->LibStatut($status, 1, ($bool ? 1 : 0)), (isset($nb[$status.$bool]) ? (int) $nb[$status.$bool] : 0)); - if ($status == ContratLigne::STATUS_INITIAL) $colorseries[$status.$bool] = '-'.$badgeStatus0; - if ($status == ContratLigne::STATUS_OPEN && !$bool) $colorseries[$status.$bool] = $badgeStatus4; - if ($status == ContratLigne::STATUS_OPEN && $bool) $colorseries[$status.$bool] = $badgeStatus1; - if ($status == ContratLigne::STATUS_CLOSED) $colorseries[$status.$bool] = $badgeStatus6; + if ($status == ContratLigne::STATUS_INITIAL) { + $colorseries[$status.$bool] = '-'.$badgeStatus0; + } + if ($status == ContratLigne::STATUS_OPEN && !$bool) { + $colorseries[$status.$bool] = $badgeStatus4; + } + if ($status == ContratLigne::STATUS_OPEN && $bool) { + $colorseries[$status.$bool] = $badgeStatus1; + } + if ($status == ContratLigne::STATUS_CLOSED) { + $colorseries[$status.$bool] = $badgeStatus6; + } - if (empty($conf->use_javascript_ajax)) - { + if (empty($conf->use_javascript_ajax)) { print ''; print ''; print ''; print "\n"; } - if ($status == 4 && !$bool) $bool = true; - else $bool = false; + if ($status == 4 && !$bool) { + $bool = true; + } else { + $bool = false; + } } -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print ''; } $listofstatus = array(0, 4, 4, 5); $bool = false; -foreach ($listofstatus as $status) -{ - if (empty($conf->use_javascript_ajax)) - { +foreach ($listofstatus as $status) { + if (empty($conf->use_javascript_ajax)) { print ''; print ''; print ''; - if ($status == 4 && !$bool) $bool = true; - else $bool = false; + if ($status == 4 && !$bool) { + $bool = true; + } else { + $bool = false; + } print "\n"; } } @@ -245,36 +258,38 @@ print "
    '.$langs->trans("Statistics").' - '.$langs->trans("Services").'
    '.$staticcontratligne->LibStatut($status, 0, ($bool ? 1 : 0)).''.($nb[$status.$bool] ? $nb[$status.$bool] : 0).' '.$staticcontratligne->LibStatut($status, 3, ($bool ? 1 : 0)).'
    '; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -225,15 +237,16 @@ if (!empty($conf->use_javascript_ajax)) print '
    '.$staticcontratligne->LibStatut($status, 0, ($bool ? 1 : 0)).''.($nb[$status.$bool] ? $nb[$status.$bool] : 0).' '.$staticcontratligne->LibStatut($status, 3, ($bool ? 1 : 0)).'

    "; // Draft contracts -if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) -{ +if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) { $sql = "SELECT c.rowid, c.ref,"; $sql .= " s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c, ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE s.rowid = c.fk_soc"; $sql .= " AND c.entity IN (".getEntity('contract', 0).")"; $sql .= " AND c.statut = 0"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND c.fk_soc = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '
    '; print ''; print ''; print ''; - if ($num) - { + if ($num) { $companystatic = new Societe($db); $i = 0; //$tot_ttc = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $staticcontrat->ref = $obj->ref; @@ -319,22 +334,27 @@ $sql .= ' sum('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AN $sql .= ' sum('.$db->ifsql("cd.statut=5", 1, 0).') as nb_closed,'; $sql .= " c.rowid as cid, c.ref, c.datec, c.tms, c.statut, s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; +} $sql .= " ".MAIN_DB_PREFIX."contrat as c"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat"; $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity('contract', 0).")"; $sql .= " AND c.statut > 0"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND s.rowid = ".$socid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} $sql .= " GROUP BY c.rowid, c.ref, c.datec, c.tms, c.statut, s.nom, s.rowid"; $sql .= " ORDER BY c.tms DESC"; $sql .= " LIMIT ".$max; dol_syslog("contrat/index.php", LOG_DEBUG); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; @@ -347,8 +367,7 @@ if ($result) print ''; print "\n"; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); print ''; @@ -356,7 +375,9 @@ if ($result) $staticcontrat->ref = ($obj->ref ? $obj->ref : $obj->cid); $staticcontrat->id = $obj->cid; print $staticcontrat->getNomUrl(1, 16); - if ($obj->nb_late) print img_warning($langs->trans("Late")); + if ($obj->nb_late) { + print img_warning($langs->trans("Late")); + } print ''; print ''; print "\n"; - while ($i < min($num, $max)) - { + while ($i < min($num, $max)) { $obj = $db->fetch_object($resql); print ''; @@ -422,8 +447,7 @@ if ($resql) //if (1 == 1) print img_warning($langs->trans("Late")); print ''; print ''; print ''; print "\n"; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; @@ -498,8 +529,7 @@ if ($resql) print $staticcontrat->getNomUrl(1, 16); print ''; print ''; print ''; print "\n"; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; @@ -574,8 +611,7 @@ if ($resql) print $staticcontrat->getNomUrl(1, 16); print ''; print ''; print ''; } print '
    '.$langs->trans("DraftContracts").($num ? ''.$num.'' : '').'
    '.$langs->trans("Services").'
    '; $staticcompany->id = $obj->socid; @@ -388,19 +409,24 @@ $sql .= " s.nom as name,"; $sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; $sql .= " FROM (".MAIN_DB_PREFIX."contrat as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= ") LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; $sql .= " WHERE c.entity IN (".getEntity('contract', 0).")"; $sql .= " AND cd.fk_contrat = c.rowid"; $sql .= " AND c.fk_soc = s.rowid"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND s.rowid = ".$socid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} $sql .= " ORDER BY cd.tms DESC"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -410,8 +436,7 @@ if ($resql) print '
    '.$langs->trans("LastModifiedServices", $max).'
    '; - if ($obj->fk_product > 0) - { + if ($obj->fk_product > 0) { $productstatic->id = $obj->fk_product; $productstatic->type = $obj->ptype; $productstatic->ref = $obj->pref; @@ -431,8 +455,11 @@ if ($resql) print $productstatic->getNomUrl(1, '', 20); } else { print ''.img_object($langs->trans("ShowService"), "service"); - if ($obj->label) print ' '.dol_trunc($obj->label, 20).''; - else print ' '.dol_trunc($obj->note, 20); + if ($obj->label) { + print ' '.dol_trunc($obj->label, 20).''; + } else { + print ' '.dol_trunc($obj->note, 20); + } } print ''; @@ -462,7 +489,9 @@ $sql .= " s.nom as name,"; $sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; $sql .= " FROM (".MAIN_DB_PREFIX."contrat as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= " ) LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; $sql .= " WHERE c.entity IN (".getEntity('contract', 0).")"; @@ -470,13 +499,16 @@ $sql .= " AND c.statut = 1"; $sql .= " AND cd.statut = 0"; $sql .= " AND cd.fk_contrat = c.rowid"; $sql .= " AND c.fk_soc = s.rowid"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND s.rowid = ".$socid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} $sql .= " ORDER BY cd.tms DESC"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -486,8 +518,7 @@ if ($resql) print '
    '.$langs->trans("NotActivatedServices").' '.$num.'
    '; - if ($obj->fk_product > 0) - { + if ($obj->fk_product > 0) { $productstatic->id = $obj->fk_product; $productstatic->type = $obj->ptype; $productstatic->ref = $obj->pref; @@ -507,8 +537,11 @@ if ($resql) print $productstatic->getNomUrl(1, '', 20); } else { print ''.img_object($langs->trans("ShowService"), "service"); - if ($obj->label) print ' '.dol_trunc($obj->label, 20).''; - else print ' '.dol_trunc($obj->note, 20); + if ($obj->label) { + print ' '.dol_trunc($obj->label, 20).''; + } else { + print ' '.dol_trunc($obj->note, 20); + } } print ''; @@ -537,7 +570,9 @@ $sql .= " s.nom as name,"; $sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; $sql .= " FROM (".MAIN_DB_PREFIX."contrat as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= " ) LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; $sql .= " WHERE c.entity IN (".getEntity('contract', 0).")"; @@ -546,13 +581,16 @@ $sql .= " AND cd.statut = 4"; $sql .= " AND cd.date_fin_validite < '".$db->idate($now)."'"; $sql .= " AND cd.fk_contrat = c.rowid"; $sql .= " AND c.fk_soc = s.rowid"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND s.rowid = ".$socid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} $sql .= " ORDER BY cd.tms DESC"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -562,8 +600,7 @@ if ($resql) print '
    '.$langs->trans("ListOfExpiredServices").' '.$num.'
    '; - if ($obj->fk_product > 0) - { + if ($obj->fk_product > 0) { $productstatic->id = $obj->fk_product; $productstatic->type = $obj->ptype; $productstatic->ref = $obj->pref; @@ -583,8 +619,11 @@ if ($resql) print $productstatic->getNomUrl(1, '', 20); } else { print ''.img_object($langs->trans("ShowService"), "service"); - if ($obj->label) print ' '.dol_trunc($obj->label, 20).''; - else print ' '.dol_trunc($obj->note, 20); + if ($obj->label) { + print ' '.dol_trunc($obj->label, 20).''; + } else { + print ' '.dol_trunc($obj->note, 20); + } } print ''; diff --git a/htdocs/contrat/list.php b/htdocs/contrat/list.php index 1226d578f2f..27cbf5a3a70 100644 --- a/htdocs/contrat/list.php +++ b/htdocs/contrat/list.php @@ -76,16 +76,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 = 'c.ref'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'c.ref'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} // Security check $id = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $id); $diroutputmassaction = $conf->contrat->dir_output.'/temp/massgeneration/'.$user->id; @@ -93,7 +101,9 @@ $diroutputmassaction = $conf->contrat->dir_output.'/temp/massgeneration/'.$user- $staticcontrat = new Contrat($db); $staticcontratligne = new ContratLigne($db); -if ($search_status == '') $search_status = 1; +if ($search_status == '') { + $search_status = 1; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new Contrat($db); @@ -112,7 +122,9 @@ $fieldstosearchall = array( 's.nom'=>"ThirdParty", 'c.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["c.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["c.note_private"] = "NotePrivate"; +} $arrayfields = array( 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1, 'position'=>10), @@ -142,18 +154,23 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Action */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $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'); +} include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers $day = ''; $month = ''; $year = ''; @@ -180,8 +197,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_array_options = array(); } -if (empty($reshook)) -{ +if (empty($reshook)) { $objectclass = 'Contrat'; $objectlabel = 'Contracts'; $permissiontoread = $user->rights->contrat->lire; @@ -204,7 +220,7 @@ $formcompany = new FormCompany($db); $contracttmp = new Contrat($db); $sql = 'SELECT'; -$sql .= " c.rowid, c.ref, c.datec as date_creation, c.tms as date_update, c.date_contrat, c.statut, c.ref_customer, c.ref_supplier, c.note_private, c.note_public,"; +$sql .= " c.rowid, c.ref, c.datec as date_creation, c.tms as date_update, c.date_contrat, c.statut, c.ref_customer, c.ref_supplier, c.note_private, c.note_public, c.entity,"; $sql .= ' s.rowid as socid, s.nom as name, s.name_alias, s.email, s.town, s.zip, s.fk_pays as country_id, s.client, s.code_client, s.status as company_status, s.logo as company_logo,'; $sql .= " typent.code as typent_code,"; $sql .= " state.code_departement as state_code, state.nom as state_name,"; @@ -216,7 +232,9 @@ $sql .= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AN $sql .= ' SUM('.$db->ifsql("cd.statut=5", 1, 0).') as nb_closed'; // 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 : ''); + 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(); @@ -226,74 +244,102 @@ $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; -if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= ", ".MAIN_DB_PREFIX."contrat as c"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (c.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (c.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat"; -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; -if ($search_user > 0) -{ +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; +} +if ($search_user > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql .= " WHERE c.fk_soc = s.rowid "; $sql .= ' AND c.entity IN ('.getEntity('contract').')'; -if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; -if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; -if ($socid) $sql .= " AND s.rowid = ".$db->escape($socid); -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; +} +if ($search_product_category > 0) { + $sql .= " AND cp.fk_categorie = ".$search_product_category; +} +if ($socid) { + $sql .= " AND s.rowid = ".$db->escape($socid); +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= dolSqlDateFilter('c.date_contrat', $day, $month, $year); -if ($search_name) $sql .= natural_search('s.nom', $search_name); -if ($search_email) $sql .= natural_search('s.email', $search_email); -if ($search_contract) $sql .= natural_search(array('c.rowid', 'c.ref'), $search_contract); -if (!empty($search_ref_customer)) $sql .= natural_search(array('c.ref_customer'), $search_ref_customer); -if (!empty($search_ref_supplier)) $sql .= natural_search(array('c.ref_supplier'), $search_ref_supplier); -if ($search_sale > 0) -{ +if ($search_name) { + $sql .= natural_search('s.nom', $search_name); +} +if ($search_email) { + $sql .= natural_search('s.email', $search_email); +} +if ($search_contract) { + $sql .= natural_search(array('c.rowid', 'c.ref'), $search_contract); +} +if (!empty($search_ref_customer)) { + $sql .= natural_search(array('c.ref_customer'), $search_ref_customer); +} +if (!empty($search_ref_supplier)) { + $sql .= natural_search(array('c.ref_supplier'), $search_ref_supplier); +} +if ($search_sale > 0) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale; } -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if ($search_user > 0) $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='contrat' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} +if ($search_user > 0) { + $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='contrat' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; -$sql .= " GROUP BY c.rowid, c.ref, c.datec, c.tms, c.date_contrat, c.statut, c.ref_customer, c.ref_supplier, c.note_private, c.note_public,"; +$sql .= " GROUP BY c.rowid, c.ref, c.datec, c.tms, c.date_contrat, c.statut, c.ref_customer, c.ref_supplier, c.note_private, c.note_public, c.entity,"; $sql .= ' s.rowid, s.nom, s.name_alias, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client, s.status, s.logo,'; $sql .= " typent.code,"; $sql .= " state.code_departement, state.nom"; // 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 : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key : ''); + } } // Add where from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; -if ($search_dfyear > 0 && $search_op2df) -{ - if ($search_op2df == '<=') $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."'"; - elseif ($search_op2df == '>=') $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'"; - else $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."' AND MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'"; +if ($search_dfyear > 0 && $search_op2df) { + if ($search_op2df == '<=') { + $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."'"; + } elseif ($search_op2df == '>=') { + $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'"; + } else { + $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."' AND MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'"; + } } $sql .= $db->order($sortfield, $sortorder); $totalnboflines = 0; $result = $db->query($sql); -if ($result) -{ +if ($result) { $totalnboflines = $db->num_rows($result); } $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -302,8 +348,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if (!$resql) -{ +if (!$resql) { dol_print_error($db); exit; } @@ -311,8 +356,7 @@ if (!$resql) $num = $db->num_rows($resql); // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/contrat/card.php?id='.$id); @@ -329,31 +373,66 @@ $i = 0; $arrayofselected = is_array($toselect) ? $toselect : array(); -if ($socid > 0) -{ +if ($socid > 0) { $soc = new Societe($db); $soc->fetch($socid); - if (empty($search_name)) $search_name = $soc->name; + if (empty($search_name)) { + $search_name = $soc->name; + } } $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_contract != '') $param .= '&search_contract='.urlencode($search_contract); -if ($search_name != '') $param .= '&search_name='.urlencode($search_name); -if ($search_email != '') $param .= '&search_email='.urlencode($search_email); -if ($search_ref_customer != '') $param .= '&search_ref_customer='.urlencode($search_ref_customer); -if ($search_ref_supplier != '') $param .= '&search_ref_supplier='.urlencode($search_ref_supplier); -if ($search_op2df != '') $param .= '&search_op2df='.urlencode($search_op2df); -if ($search_dfyear != '') $param .= '&search_dfyear='.urlencode($search_dfyear); -if ($search_dfmonth != '') $param .= '&search_dfmonth='.urlencode($search_dfmonth); -if ($search_sale != '') $param .= '&search_sale='.urlencode($search_sale); -if ($search_user != '') $param .= '&search_user='.urlencode($search_user); -if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); -if ($search_product_category != '') $param .= '&search_product_category='.urlencode($search_product_category); -if ($show_files) $param .= '&show_files='.urlencode($show_files); -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_contract != '') { + $param .= '&search_contract='.urlencode($search_contract); +} +if ($search_name != '') { + $param .= '&search_name='.urlencode($search_name); +} +if ($search_email != '') { + $param .= '&search_email='.urlencode($search_email); +} +if ($search_ref_customer != '') { + $param .= '&search_ref_customer='.urlencode($search_ref_customer); +} +if ($search_ref_supplier != '') { + $param .= '&search_ref_supplier='.urlencode($search_ref_supplier); +} +if ($search_op2df != '') { + $param .= '&search_op2df='.urlencode($search_op2df); +} +if ($search_dfyear != '') { + $param .= '&search_dfyear='.urlencode($search_dfyear); +} +if ($search_dfmonth != '') { + $param .= '&search_dfmonth='.urlencode($search_dfmonth); +} +if ($search_sale != '') { + $param .= '&search_sale='.urlencode($search_sale); +} +if ($search_user != '') { + $param .= '&search_user='.urlencode($search_user); +} +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); +} +if ($search_product_category != '') { + $param .= '&search_product_category='.urlencode($search_product_category); +} +if ($show_files) { + $param .= '&show_files='.urlencode($show_files); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -363,16 +442,24 @@ $arrayofmassactions = array( 'builddoc'=>$langs->trans("PDFMerge"), 'presend'=>$langs->trans("SendByMail"), ); -if ($user->rights->contrat->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); -if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($user->rights->contrat->supprimer) { + $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); +} +if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $url = DOL_URL_ROOT.'/contrat/card.php?action=create'; -if (!empty($socid)) $url .= '&socid='.$socid; +if (!empty($socid)) { + $url .= '&socid='.$socid; +} $newcardbutton = dolGetButtonTitle($langs->trans('NewContractSubscription'), '', 'fa fa-plus-circle', $url, '', $user->rights->contrat->creer); print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -388,17 +475,17 @@ $objecttmp = new Contrat($db); $trackid = 'con'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($sall) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } $moreforfilter = ''; // If the user can view prospects other than his' -if ($user->rights->societe->client->voir || $socid) -{ +if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; @@ -406,16 +493,14 @@ if ($user->rights->societe->client->voir || $socid) $moreforfilter .= '
    '; } // If the user can view other users -if ($user->rights->user->user->lire) -{ +if ($user->rights->user->user->lire) { $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - $moreforfilter .= '
    '; + $moreforfilter .= ''; } // If the user can view categories of products -if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) -{ +if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; @@ -426,11 +511,13 @@ if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($use $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)) -{ +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; @@ -438,77 +525,75 @@ 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"; print ''; -if (!empty($arrayfields['c.ref']['checked'])) -{ +if (!empty($arrayfields['c.ref']['checked'])) { print ''; } -if (!empty($arrayfields['c.ref_customer']['checked'])) -{ +if (!empty($arrayfields['c.ref_customer']['checked'])) { print ''; } -if (!empty($arrayfields['c.ref_supplier']['checked'])) -{ +if (!empty($arrayfields['c.ref_supplier']['checked'])) { print ''; } -if (!empty($arrayfields['s.nom']['checked'])) -{ +if (!empty($arrayfields['s.nom']['checked'])) { print ''; } -if (!empty($arrayfields['s.email']['checked'])) -{ +if (!empty($arrayfields['s.email']['checked'])) { print ''; } // Town -if (!empty($arrayfields['s.town']['checked'])) print ''; +if (!empty($arrayfields['s.town']['checked'])) { + print ''; +} // Zip -if (!empty($arrayfields['s.zip']['checked'])) print ''; +if (!empty($arrayfields['s.zip']['checked'])) { + print ''; +} // State -if (!empty($arrayfields['state.nom']['checked'])) -{ +if (!empty($arrayfields['state.nom']['checked'])) { print ''; } // Country -if (!empty($arrayfields['country.code_iso']['checked'])) -{ +if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; } // Company type -if (!empty($arrayfields['typent.code']['checked'])) -{ +if (!empty($arrayfields['typent.code']['checked'])) { print ''; } -if (!empty($arrayfields['sale_representative']['checked'])) -{ +if (!empty($arrayfields['sale_representative']['checked'])) { print ''; } -if (!empty($arrayfields['c.date_contrat']['checked'])) -{ +if (!empty($arrayfields['c.date_contrat']['checked'])) { // Date contract print ''; } // Date modification -if (!empty($arrayfields['c.tms']['checked'])) -{ +if (!empty($arrayfields['c.tms']['checked'])) { print ''; } // First end date -if (!empty($arrayfields['lower_planned_end_date']['checked'])) -{ +if (!empty($arrayfields['lower_planned_end_date']['checked'])) { print ''; } // Status -if (!empty($arrayfields['status']['checked'])) -{ +if (!empty($arrayfields['status']['checked'])) { print ''; } print ''; print "\n"; print ''; -if (!empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['c.ref_customer']['checked'])) print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['c.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.email']['checked'])) print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['c.date_contrat']['checked'])) print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['c.ref']['checked'])) { + print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['c.ref_customer']['checked'])) { + print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['c.ref_supplier']['checked'])) { + print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.email']['checked'])) { + print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['sale_representative']['checked'])) { + print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['c.date_contrat']['checked'])) { + print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat", "", $param, '', $sortfield, $sortorder, 'center '); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields @@ -598,8 +703,7 @@ $totalarray = array(); $typenArray = array(); $cacheCountryIDCode = array(); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $contracttmp->ref = $obj->ref; @@ -632,11 +736,12 @@ while ($i < min($num, $limit)) print ''; // Ref - if (!empty($arrayfields['c.ref']['checked'])) - { + if (!empty($arrayfields['c.ref']['checked'])) { print ''; @@ -652,16 +757,13 @@ while ($i < min($num, $limit)) print ''; } - if (!empty($arrayfields['c.ref_customer']['checked'])) - { + if (!empty($arrayfields['c.ref_customer']['checked'])) { print ''; } - if (!empty($arrayfields['c.ref_supplier']['checked'])) - { + if (!empty($arrayfields['c.ref_supplier']['checked'])) { print ''; } - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; } - if (!empty($arrayfields['s.email']['checked'])) - { + if (!empty($arrayfields['s.email']['checked'])) { print ''; } // Town - if (!empty($arrayfields['s.town']['checked'])) - { + if (!empty($arrayfields['s.town']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { + if (!empty($arrayfields['s.zip']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['sale_representative']['checked'])) - { + if (!empty($arrayfields['sale_representative']['checked'])) { // Sales representatives print ''; } // Date - if (!empty($arrayfields['c.date_contrat']['checked'])) - { + if (!empty($arrayfields['c.date_contrat']['checked'])) { print ''; } // Extra fields @@ -767,32 +874,34 @@ while ($i < min($num, $limit)) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['c.datec']['checked'])) - { + if (!empty($arrayfields['c.datec']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['c.tms']['checked'])) - { + if (!empty($arrayfields['c.tms']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date lower end date - if (!empty($arrayfields['lower_planned_end_date']['checked'])) - { + if (!empty($arrayfields['lower_planned_end_date']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['status']['checked'])) - { + if (!empty($arrayfields['status']['checked'])) { print ''; print ''; print ''; @@ -800,14 +909,17 @@ while ($i < min($num, $limit)) } // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; $i++; @@ -824,7 +936,9 @@ print ''; print ''; $hidegeneratedfilelistifempty = 1; -if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; +if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; +} // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/contrat/note.php b/htdocs/contrat/note.php index c9000c4fb0d..d61ac357a40 100644 --- a/htdocs/contrat/note.php +++ b/htdocs/contrat/note.php @@ -41,7 +41,9 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $id); $object = new Contrat($db); @@ -70,8 +72,7 @@ llxHeader('', $langs->trans("Contract"), ""); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = contract_prepare_head($object); @@ -89,9 +90,9 @@ if ($id > 0 || !empty($ref)) //if (! empty($modCodeContract->code_auto)) { $morehtmlref .= $object->ref; /*} else { - $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3); - $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2); - }*/ + $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3); + $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2); + }*/ $morehtmlref .= '
    '; // Ref customer @@ -104,15 +105,14 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->contrat->creer) - { - if ($action != 'classify') + if ($user->rights->contrat->creer) { + if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; $morehtmlref .= ' : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '
    '; @@ -150,12 +150,18 @@ if ($id > 0 || !empty($ref)) // Ligne info remises tiers print '
    '; diff --git a/htdocs/contrat/services_list.php b/htdocs/contrat/services_list.php index 4de651a24f9..0d295357c09 100644 --- a/htdocs/contrat/services_list.php +++ b/htdocs/contrat/services_list.php @@ -39,12 +39,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 (!$sortfield) $sortfield = "c.rowid"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "c.rowid"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} $mode = GETPOST("mode"); $filter = GETPOST("filter"); @@ -90,22 +96,32 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Security check $contratid = GETPOST('id', 'int'); -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $contratid); -if ($search_status != '') -{ +if ($search_status != '') { $tmp = explode('&', $search_status); $mode = $tmp[0]; - if (empty($tmp[1])) $filter = ''; - else { - if ($tmp[1] == 'filter=notexpired') $filter = 'notexpired'; - if ($tmp[1] == 'filter=expired') $filter = 'expired'; + if (empty($tmp[1])) { + $filter = ''; + } else { + if ($tmp[1] == 'filter=notexpired') { + $filter = 'notexpired'; + } + if ($tmp[1] == 'filter=expired') { + $filter = 'expired'; + } } } else { $search_status = $mode; - if ($filter == 'expired') $search_status .= '&filter=expired'; - if ($filter == 'notexpired') $search_status .= '&filter=notexpired'; + if ($filter == 'expired') { + $search_status .= '&filter=expired'; + } + if ($filter == 'notexpired') { + $search_status .= '&filter=notexpired'; + } } $staticcontrat = new Contrat($db); @@ -115,19 +131,19 @@ $companystatic = new Societe($db); $arrayfields = array( 'c.ref'=>array('label'=>$langs->trans("Contract"), 'checked'=>1, 'position'=>80), 'p.description'=>array('label'=>$langs->trans("Service"), 'checked'=>1, 'position'=>80), - 'cd.qty'=>array('label'=>$langs->trans("Qty"), 'checked'=>0, 'position'=>100), - 'cd.total_ht'=>array('label'=>$langs->trans("TotalHT"), 'checked'=>0, 'position'=>100), - 'cd.total_tva'=>array('label'=>$langs->trans("TotalVAT"), 'checked'=>0, 'position'=>100), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>90), 'cd.tva_tx'=>array('label'=>$langs->trans("VAT"), 'checked'=>0, 'position'=>100), - 'cd.subprice'=>array('label'=>$langs->trans("PriceUHT"), 'checked'=>0, 'position'=>100), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>100), - 'cd.date_ouverture_prevue'=>array('label'=>$langs->trans("DateStartPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode == "0")), - 'cd.date_ouverture'=>array('label'=>$langs->trans("DateStartRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode > 0)), - 'cd.date_fin_validite'=>array('label'=>$langs->trans("DateEndPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode < 5)), - 'cd.date_cloture'=>array('label'=>$langs->trans("DateEndRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode >= 5)), - 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1), + 'cd.subprice'=>array('label'=>$langs->trans("PriceUHT"), 'checked'=>0, 'position'=>105), + 'cd.qty'=>array('label'=>$langs->trans("Qty"), 'checked'=>0, 'position'=>108), + 'cd.total_ht'=>array('label'=>$langs->trans("TotalHT"), 'checked'=>0, 'position'=>109), + 'cd.total_tva'=>array('label'=>$langs->trans("TotalVAT"), 'checked'=>0, 'position'=>110), + 'cd.date_ouverture_prevue'=>array('label'=>$langs->trans("DateStartPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode == "0"), 'position'=>150), + 'cd.date_ouverture'=>array('label'=>$langs->trans("DateStartRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode > 0), 'position'=>160), + 'cd.date_fin_validite'=>array('label'=>$langs->trans("DateEndPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode < 5), 'position'=>170), + 'cd.date_cloture'=>array('label'=>$langs->trans("DateEndRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode >= 5), 'position'=>180), //'cd.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'cd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500) + 'cd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000) ); // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; @@ -142,21 +158,25 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * 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)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers - { - $search_product_category = 0; + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers + $search_product_category = 0; $search_name = ""; $search_contract = ""; $search_service = ""; @@ -197,7 +217,9 @@ $sql = "SELECT c.rowid as cid, c.ref, c.statut as cstatut, c.ref_customer, c.ref $sql .= " s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur,"; $sql .= " cd.rowid, cd.description, cd.statut,"; $sql .= " p.rowid as pid, p.ref as pref, p.label as label, p.fk_product_type as ptype, p.entity as pentity,"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk_user,"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " sc.fk_soc, sc.fk_user,"; +} $sql .= " cd.date_ouverture_prevue,"; $sql .= " cd.date_ouverture,"; $sql .= " cd.date_fin_validite,"; @@ -211,7 +233,9 @@ $sql .= " cd.subprice,"; $sql .= " cd.tms as date_update"; // 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 : ''); + 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(); @@ -219,50 +243,102 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // N $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c,"; $sql .= " ".MAIN_DB_PREFIX."societe as s,"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; +} $sql .= " ".MAIN_DB_PREFIX."contratdet as cd"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cd.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cd.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; +} $sql .= " WHERE c.entity = ".$conf->entity; $sql .= " AND c.rowid = cd.fk_contrat"; -if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; +if ($search_product_category > 0) { + $sql .= " AND cp.fk_categorie = ".$search_product_category; +} $sql .= " AND c.fk_soc = s.rowid"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($mode == "0") $sql .= " AND cd.statut = 0"; -if ($mode == "4") $sql .= " AND cd.statut = 4"; -if ($mode == "5") $sql .= " AND cd.statut = 5"; -if ($filter == "expired") $sql .= " AND cd.date_fin_validite < '".$db->idate($now)."'"; -if ($filter == "notexpired") $sql .= " AND cd.date_fin_validite >= '".$db->idate($now)."'"; -if ($search_name) $sql .= " AND s.nom LIKE '%".$db->escape($search_name)."%'"; -if ($search_contract) $sql .= " AND c.ref LIKE '%".$db->escape($search_contract)."%' "; -if ($search_service) $sql .= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')"; -if ($socid > 0) $sql .= " AND s.rowid = ".$socid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($mode == "0") { + $sql .= " AND cd.statut = 0"; +} +if ($mode == "4") { + $sql .= " AND cd.statut = 4"; +} +if ($mode == "5") { + $sql .= " AND cd.statut = 5"; +} +if ($filter == "expired") { + $sql .= " AND cd.date_fin_validite < '".$db->idate($now)."'"; +} +if ($filter == "notexpired") { + $sql .= " AND cd.date_fin_validite >= '".$db->idate($now)."'"; +} +if ($search_name) { + $sql .= " AND s.nom LIKE '%".$db->escape($search_name)."%'"; +} +if ($search_contract) { + $sql .= " AND c.ref LIKE '%".$db->escape($search_contract)."%' "; +} +if ($search_service) { + $sql .= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')"; +} +if ($socid > 0) { + $sql .= " AND s.rowid = ".$socid; +} $filter_dateouvertureprevue_start = dol_mktime(0, 0, 0, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear); $filter_dateouvertureprevue_end = dol_mktime(23, 59, 59, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear); -if ($filter_dateouvertureprevue_start != '' && $filter_opouvertureprevue == -1) $filter_opouvertureprevue = ' BETWEEN '; +if ($filter_dateouvertureprevue_start != '' && $filter_opouvertureprevue == -1) { + $filter_opouvertureprevue = ' BETWEEN '; +} $filter_date1_start = dol_mktime(0, 0, 0, $op1month, $op1day, $op1year); $filter_date1_end = dol_mktime(23, 59, 59, $op1month, $op1day, $op1year); -if ($filter_date1_start != '' && $filter_op1 == -1) $filter_op1 = ' BETWEEN '; +if ($filter_date1_start != '' && $filter_op1 == -1) { + $filter_op1 = ' BETWEEN '; +} $filter_date2_start = dol_mktime(0, 0, 0, $op2month, $op2day, $op2year); $filter_date2_end = dol_mktime(23, 59, 59, $op2month, $op2day, $op2year); -if ($filter_date2_start != '' && $filter_op2 == -1) $filter_op2 = ' BETWEEN '; +if ($filter_date2_start != '' && $filter_op2 == -1) { + $filter_op2 = ' BETWEEN '; +} $filter_datecloture_start = dol_mktime(0, 0, 0, $opcloturemonth, $opclotureday, $opclotureyear); $filter_datecloture_end = dol_mktime(23, 59, 59, $opcloturemonth, $opclotureday, $opclotureyear); -if ($filter_datecloture_start != '' && $filter_opcloture == -1) $filter_opcloture = ' BETWEEN '; +if ($filter_datecloture_start != '' && $filter_opcloture == -1) { + $filter_opcloture = ' BETWEEN '; +} -if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $filter_opouvertureprevue != ' BETWEEN ' && $filter_dateouvertureprevue_start != '') $sql .= " AND cd.date_ouverture_prevue ".$filter_opouvertureprevue." '".$db->idate($filter_dateouvertureprevue_start)."'"; -if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue == ' BETWEEN ') $sql .= " AND '".$db->idate($filter_dateouvertureprevue_end)."'"; -if (!empty($filter_op1) && $filter_op1 != -1 && $filter_op1 != ' BETWEEN ' && $filter_date1_start != '') $sql .= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1_start)."'"; -if (!empty($filter_op1) && $filter_op1 == ' BETWEEN ') $sql .= " AND '".$db->idate($filter_date1_end)."'"; -if (!empty($filter_op2) && $filter_op2 != -1 && $filter_op2 != ' BETWEEN ' && $filter_date2_start != '') $sql .= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2_start)."'"; -if (!empty($filter_op2) && $filter_op2 == ' BETWEEN ') $sql .= " AND '".$db->idate($filter_date2_end)."'"; -if (!empty($filter_opcloture) && $filter_opcloture != ' BETWEEN ' && $filter_opcloture != -1 && $filter_datecloture_start != '') $sql .= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture_start)."'"; -if (!empty($filter_opcloture) && $filter_opcloture == ' BETWEEN ') $sql .= " AND '".$db->idate($filter_datecloture_end)."'"; +if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $filter_opouvertureprevue != ' BETWEEN ' && $filter_dateouvertureprevue_start != '') { + $sql .= " AND cd.date_ouverture_prevue ".$filter_opouvertureprevue." '".$db->idate($filter_dateouvertureprevue_start)."'"; +} +if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue == ' BETWEEN ') { + $sql .= " AND '".$db->idate($filter_dateouvertureprevue_end)."'"; +} +if (!empty($filter_op1) && $filter_op1 != -1 && $filter_op1 != ' BETWEEN ' && $filter_date1_start != '') { + $sql .= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1_start)."'"; +} +if (!empty($filter_op1) && $filter_op1 == ' BETWEEN ') { + $sql .= " AND '".$db->idate($filter_date1_end)."'"; +} +if (!empty($filter_op2) && $filter_op2 != -1 && $filter_op2 != ' BETWEEN ' && $filter_date2_start != '') { + $sql .= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2_start)."'"; +} +if (!empty($filter_op2) && $filter_op2 == ' BETWEEN ') { + $sql .= " AND '".$db->idate($filter_date2_end)."'"; +} +if (!empty($filter_opcloture) && $filter_opcloture != ' BETWEEN ' && $filter_opcloture != -1 && $filter_datecloture_start != '') { + $sql .= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture_start)."'"; +} +if (!empty($filter_opcloture) && $filter_opcloture == ' BETWEEN ') { + $sql .= " AND '".$db->idate($filter_datecloture_end)."'"; +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; $sql .= $db->order($sortfield, $sortorder); @@ -270,12 +346,10 @@ $sql .= $db->order($sortfield, $sortorder); //print $sql; $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -286,8 +360,7 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; dol_syslog("contrat/services_list.php", LOG_DEBUG); $resql = $db->query($sql); -if (!$resql) -{ +if (!$resql) { dol_print_error($db); exit; } @@ -297,31 +370,63 @@ $num = $db->num_rows($resql); /* if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { - $obj = $db->fetch_object($resql); - $id = $obj->id; - header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withprojet=1'); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->id; + header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withprojet=1'); + exit; }*/ llxHeader(null, $langs->trans("Services")); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; -if ($search_contract) $param .= '&search_contract='.urlencode($search_contract); -if ($search_name) $param .= '&search_name='.urlencode($search_name); -if ($search_service) $param .= '&search_service='.urlencode($search_service); -if ($mode) $param .= '&mode='.urlencode($mode); -if ($filter) $param .= '&filter='.urlencode($filter); -if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1) $param .= '&filter_opouvertureprevue='.urlencode($filter_opouvertureprevue); -if (!empty($filter_op1) && $filter_op1 != -1) $param .= '&filter_op1='.urlencode($filter_op1); -if (!empty($filter_op2) && $filter_op2 != -1) $param .= '&filter_op2='.urlencode($filter_op2); -if (!empty($filter_opcloture) && $filter_opcloture != -1) $param .= '&filter_opcloture='.urlencode($filter_opcloture); -if ($filter_dateouvertureprevue != '') $param .= '&opouvertureprevueday='.$opouvertureprevueday.'&opouvertureprevuemonth='.$opouvertureprevuemonth.'&opouvertureprevueyear='.$opouvertureprevueyear; -if ($filter_date1 != '') $param .= '&op1day='.$op1day.'&op1month='.$op1month.'&op1year='.$op1year; -if ($filter_date2 != '') $param .= '&op2day='.$op2day.'&op2month='.$op2month.'&op2year='.$op2year; -if ($filter_datecloture != '') $param .= '&opclotureday='.$op2day.'&opcloturemonth='.$op2month.'&opclotureyear='.$op2year; -if ($optioncss != '') $param .= '&optioncss='.$optioncss; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; +} +if ($search_contract) { + $param .= '&search_contract='.urlencode($search_contract); +} +if ($search_name) { + $param .= '&search_name='.urlencode($search_name); +} +if ($search_service) { + $param .= '&search_service='.urlencode($search_service); +} +if ($mode) { + $param .= '&mode='.urlencode($mode); +} +if ($filter) { + $param .= '&filter='.urlencode($filter); +} +if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1) { + $param .= '&filter_opouvertureprevue='.urlencode($filter_opouvertureprevue); +} +if (!empty($filter_op1) && $filter_op1 != -1) { + $param .= '&filter_op1='.urlencode($filter_op1); +} +if (!empty($filter_op2) && $filter_op2 != -1) { + $param .= '&filter_op2='.urlencode($filter_op2); +} +if (!empty($filter_opcloture) && $filter_opcloture != -1) { + $param .= '&filter_opcloture='.urlencode($filter_opcloture); +} +if ($filter_dateouvertureprevue != '') { + $param .= '&opouvertureprevueday='.$opouvertureprevueday.'&opouvertureprevuemonth='.$opouvertureprevuemonth.'&opouvertureprevueyear='.$opouvertureprevueyear; +} +if ($filter_date1 != '') { + $param .= '&op1day='.$op1day.'&op1month='.$op1month.'&op1year='.$op1year; +} +if ($filter_date2 != '') { + $param .= '&op2day='.$op2day.'&op2month='.$op2month.'&op2year='.$op2year; +} +if ($filter_datecloture != '') { + $param .= '&opclotureday='.$op2day.'&opcloturemonth='.$op2month.'&opclotureyear='.$op2year; +} +if ($optioncss != '') { + $param .= '&optioncss='.$optioncss; +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -335,7 +440,9 @@ $arrayofmassactions = array( $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -345,24 +452,32 @@ print ''; print ''; $title = $langs->trans("ListOfServices"); -if ($mode == "0") $title = $langs->trans("ListOfInactiveServices"); // Must use == "0" -if ($mode == "4" && $filter != "expired") $title = $langs->trans("ListOfRunningServices"); -if ($mode == "4" && $filter == "expired") $title = $langs->trans("ListOfExpiredServices"); -if ($mode == "5") $title = $langs->trans("ListOfClosedServices"); +if ($mode == "0") { + $title = $langs->trans("ListOfInactiveServices"); // Must use == "0" +} +if ($mode == "4" && $filter != "expired") { + $title = $langs->trans("ListOfRunningServices"); +} +if ($mode == "4" && $filter == "expired") { + $title = $langs->trans("ListOfExpiredServices"); +} +if ($mode == "5") { + $title = $langs->trans("ListOfClosedServices"); +} print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'contract', 0, '', '', $limit); -if ($sall) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } $morefilter = ''; // If the user can view categories of products -if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) -{ +if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; @@ -373,12 +488,14 @@ if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights- $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)) -{ +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; @@ -392,33 +509,62 @@ print '
    '; print '
    '; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print ''; print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); print ''; //print $langs->trans('Month').': '; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print ''; + } print ''; //print ' '.$langs->trans('Year').': '; $syear = $year; @@ -523,20 +608,17 @@ $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation -if (!empty($arrayfields['c.datec']['checked'])) -{ +if (!empty($arrayfields['c.datec']['checked'])) { print ''; print ''; print ''; $arrayofoperators = array('0'=>'', '='=>'=', '<='=>'<=', '>='=>'>='); print $form->selectarray('search_op2df', $arrayofoperators, $search_op2df, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth50imp'); @@ -547,8 +629,7 @@ if (!empty($arrayfields['lower_planned_end_date']['checked'])) print ''; @@ -558,18 +639,42 @@ print '
    '; print $contracttmp->getNomUrl(1); - if ($obj->nb_late) print img_warning($langs->trans("Late")); + if ($obj->nb_late) { + print img_warning($langs->trans("Late")); + } if (!empty($obj->note_private) || !empty($obj->note_public)) { print ' '; print ''.img_picto($langs->trans("ViewPrivateNote"), 'note').''; @@ -644,7 +749,7 @@ while ($i < min($num, $limit)) } $filename = dol_sanitizeFileName($obj->ref); - $filedir = $conf->contrat->dir_output.'/'.dol_sanitizeFileName($obj->ref); + $filedir = $conf->contrat->multidir_output[$obj->entity].'/'.dol_sanitizeFileName($obj->ref); $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid; print $formfile->getDocumentsLink($contracttmp->element, $filename, $filedir); print ''.$contracttmp->getFormatedCustomerRef($obj->ref_customer).''.$obj->ref_supplier.''; if ($obj->socid > 0) { // TODO Use a cache for this string @@ -669,57 +771,63 @@ while ($i < min($num, $limit)) } print ''.$obj->email.''; print $obj->town; print ''; print $obj->zip; print '".$obj->state_name."'; print $socstatic->country; print ''; - if (count($typenArray) == 0) $typenArray = $formcompany->typent_array(1); + if (count($typenArray) == 0) { + $typenArray = $formcompany->typent_array(1); + } print $typenArray[$obj->typent_code]; print ''; - if ($obj->socid > 0) - { + if ($obj->socid > 0) { $listsalesrepresentatives = $socstatic->getSalesRepresentatives($user); - if ($listsalesrepresentatives < 0) dol_print_error($db); + if ($listsalesrepresentatives < 0) { + dol_print_error($db); + } $nbofsalesrepresentative = count($listsalesrepresentatives); if ($nbofsalesrepresentative > 6) { // We print only number @@ -756,8 +864,7 @@ while ($i < min($num, $limit)) print ''.dol_print_date($db->jdate($obj->date_contrat), 'day', 'tzserver').''; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->lower_planned_end_date), 'day', 'tzuser'); print ''.($obj->nb_initial > 0 ? $obj->nb_initial : '').''.($obj->nb_running > 0 ? $obj->nb_running : '').''.($obj->nb_expired > 0 ? $obj->nb_expired : '').''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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('Discount').''; - if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); + if ($object->thirdparty->remise_percent) { + print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent); + } else { + print $langs->trans("CompanyHasNoRelativeDiscount"); + } $absolute_discount = $object->thirdparty->getAvailableDiscounts(); print '. '; - if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); - else print $langs->trans("CompanyHasNoAbsoluteDiscount"); + if ($absolute_discount) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); + } else { + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + } print '.'; print '
    '."\n"; print ''; -if (!empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['p.description']['checked'])) print_liste_field_titre($arrayfields['p.description']['label'], $_SERVER["PHP_SELF"], "p.description", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['cd.qty']['checked'])) print_liste_field_titre($arrayfields['cd.qty']['label'], $_SERVER["PHP_SELF"], "cd.qty", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['cd.total_ht']['checked'])) print_liste_field_titre($arrayfields['cd.total_ht']['label'], $_SERVER["PHP_SELF"], "cd.total_ht", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['cd.total_tva']['checked'])) print_liste_field_titre($arrayfields['cd.total_tva']['label'], $_SERVER["PHP_SELF"], "cd.total_tva", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['cd.tva_tx']['checked'])) print_liste_field_titre($arrayfields['cd.tva_tx']['label'], $_SERVER["PHP_SELF"], "cd.tva_tx", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['cd.subprice']['checked'])) print_liste_field_titre($arrayfields['cd.subprice']['label'], $_SERVER["PHP_SELF"], "cd.subprice", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture_prevue", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['cd.date_ouverture']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['cd.date_fin_validite']['checked'])) print_liste_field_titre($arrayfields['cd.date_fin_validite']['label'], $_SERVER["PHP_SELF"], "cd.date_fin_validite", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['cd.date_cloture']['checked'])) print_liste_field_titre($arrayfields['cd.date_cloture']['label'], $_SERVER["PHP_SELF"], "cd.date_cloture", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['c.ref']['checked'])) { + print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['p.description']['checked'])) { + print_liste_field_titre($arrayfields['p.description']['label'], $_SERVER["PHP_SELF"], "p.description", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['cd.qty']['checked'])) { + print_liste_field_titre($arrayfields['cd.qty']['label'], $_SERVER["PHP_SELF"], "cd.qty", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['cd.total_ht']['checked'])) { + print_liste_field_titre($arrayfields['cd.total_ht']['label'], $_SERVER["PHP_SELF"], "cd.total_ht", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['cd.total_tva']['checked'])) { + print_liste_field_titre($arrayfields['cd.total_tva']['label'], $_SERVER["PHP_SELF"], "cd.total_tva", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['cd.tva_tx']['checked'])) { + print_liste_field_titre($arrayfields['cd.tva_tx']['label'], $_SERVER["PHP_SELF"], "cd.tva_tx", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['cd.subprice']['checked'])) { + print_liste_field_titre($arrayfields['cd.subprice']['label'], $_SERVER["PHP_SELF"], "cd.subprice", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) { + print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture_prevue", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['cd.date_ouverture']['checked'])) { + print_liste_field_titre($arrayfields['cd.date_ouverture']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['cd.date_fin_validite']['checked'])) { + print_liste_field_titre($arrayfields['cd.date_fin_validite']['label'], $_SERVER["PHP_SELF"], "cd.date_fin_validite", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['cd.date_cloture']['checked'])) { + print_liste_field_titre($arrayfields['cd.date_cloture']['label'], $_SERVER["PHP_SELF"], "cd.date_cloture", "", $param, '', $sortfield, $sortorder, 'center '); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $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['cd.datec']['checked'])) print_liste_field_titre($arrayfields['cd.datec']['label'], $_SERVER["PHP_SELF"], "cd.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['cd.tms']['checked'])) print_liste_field_titre($arrayfields['cd.tms']['label'], $_SERVER["PHP_SELF"], "cd.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['status']['checked'])) print_liste_field_titre($arrayfields['status']['label'], $_SERVER["PHP_SELF"], "cd.statut,c.statut", "", $param, '', $sortfield, $sortorder, 'right '); +if (!empty($arrayfields['cd.datec']['checked'])) { + print_liste_field_titre($arrayfields['cd.datec']['label'], $_SERVER["PHP_SELF"], "cd.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['cd.tms']['checked'])) { + print_liste_field_titre($arrayfields['cd.tms']['label'], $_SERVER["PHP_SELF"], "cd.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['status']['checked'])) { + print_liste_field_titre($arrayfields['status']['label'], $_SERVER["PHP_SELF"], "cd.statut,c.statut", "", $param, '', $sortfield, $sortorder, 'right '); +} print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; print ''; -if (!empty($arrayfields['c.ref']['checked'])) -{ +if (!empty($arrayfields['c.ref']['checked'])) { print ''; } // Service label -if (!empty($arrayfields['p.description']['checked'])) -{ +if (!empty($arrayfields['p.description']['checked'])) { print ''; } // detail lines -if (!empty($arrayfields['cd.qty']['checked'])) -{ +if (!empty($arrayfields['cd.qty']['checked'])) { print ''; } -if (!empty($arrayfields['cd.total_ht']['checked'])) -{ +if (!empty($arrayfields['cd.total_ht']['checked'])) { print ''; } -if (!empty($arrayfields['cd.total_tva']['checked'])) -{ +if (!empty($arrayfields['cd.total_tva']['checked'])) { print ''; } -if (!empty($arrayfields['cd.tva_tx']['checked'])) -{ +if (!empty($arrayfields['cd.tva_tx']['checked'])) { print ''; } -if (!empty($arrayfields['cd.subprice']['checked'])) -{ +if (!empty($arrayfields['cd.subprice']['checked'])) { print ''; } // Third party -if (!empty($arrayfields['s.nom']['checked'])) -{ +if (!empty($arrayfields['s.nom']['checked'])) { print ''; } -if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) -{ +if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) { print ''; } -if (!empty($arrayfields['cd.date_ouverture']['checked'])) -{ +if (!empty($arrayfields['cd.date_ouverture']['checked'])) { print ''; } -if (!empty($arrayfields['cd.date_fin_validite']['checked'])) -{ +if (!empty($arrayfields['cd.date_fin_validite']['checked'])) { print ''; } -if (!empty($arrayfields['cd.date_cloture']['checked'])) -{ +if (!empty($arrayfields['cd.date_cloture']['checked'])) { print ''; } -if (!empty($arrayfields['cd.tms']['checked'])) -{ +if (!empty($arrayfields['cd.tms']['checked'])) { // Date modification print ''; } -if (!empty($arrayfields['status']['checked'])) -{ +if (!empty($arrayfields['status']['checked'])) { // Status print ''; // Ref - if (!empty($arrayfields['c.ref']['checked'])) - { + if (!empty($arrayfields['c.ref']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Service - if (!empty($arrayfields['p.description']['checked'])) - { + if (!empty($arrayfields['p.description']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cd.qty']['checked'])) - { + if (!empty($arrayfields['cd.qty']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cd.total_ht']['checked'])) - { + if (!empty($arrayfields['cd.total_ht']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cd.total_ht'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'cd.total_ht'; + } $totalarray['val']['cd.total_ht'] += $obj->total_ht; } - if (!empty($arrayfields['cd.total_tva']['checked'])) - { + if (!empty($arrayfields['cd.total_tva']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cd.total_tva'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'cd.total_tva'; + } $totalarray['val']['cd.total_tva'] += $obj->total_tva; } - if (!empty($arrayfields['cd.tva_tx']['checked'])) - { + if (!empty($arrayfields['cd.tva_tx']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cd.subprice']['checked'])) - { + if (!empty($arrayfields['cd.subprice']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Third party - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Start date - if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) - { + if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cd.date_ouverture']['checked'])) - { + if (!empty($arrayfields['cd.date_ouverture']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // End date - if (!empty($arrayfields['cd.date_fin_validite']['checked'])) - { + if (!empty($arrayfields['cd.date_fin_validite']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Close date (real end date) - if (!empty($arrayfields['cd.date_cloture']['checked'])) - { + if (!empty($arrayfields['cd.date_cloture']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -691,45 +846,50 @@ while ($i < min($num, $limit)) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['cd.datec']['checked'])) - { + if (!empty($arrayfields['cd.datec']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['cd.tms']['checked'])) - { + if (!empty($arrayfields['cd.tms']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['status']['checked'])) - { + if (!empty($arrayfields['status']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; $i++; diff --git a/htdocs/contrat/tpl/linkedobjectblock.tpl.php b/htdocs/contrat/tpl/linkedobjectblock.tpl.php index 339f51db22c..310e2bd00b9 100644 --- a/htdocs/contrat/tpl/linkedobjectblock.tpl.php +++ b/htdocs/contrat/tpl/linkedobjectblock.tpl.php @@ -17,8 +17,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -37,24 +36,24 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; $langs->load("contracts"); $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - - - + + + -
    '; print ''; print ''; @@ -426,49 +572,41 @@ if (!empty($arrayfields['c.ref']['checked'])) print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; $arrayofoperators = array('<'=>'<', '>'=>'>'); print $form->selectarray('filter_opouvertureprevue', $arrayofoperators, $filter_opouvertureprevue, 1); @@ -477,8 +615,7 @@ if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) print $form->selectDate($filter_dateouvertureprevue, 'opouvertureprevue', 0, 0, 1, '', 1, 0); print ''; $arrayofoperators = array('<'=>'<', '>'=>'>'); print $form->selectarray('filter_op1', $arrayofoperators, $filter_op1, 1); @@ -487,8 +624,7 @@ if (!empty($arrayfields['cd.date_ouverture']['checked'])) print $form->selectDate($filter_date1, 'op1', 0, 0, 1, '', 1, 0); print ''; $arrayofoperators = array('<'=>'<', '>'=>'>'); print $form->selectarray('filter_op2', $arrayofoperators, $filter_op2, 1); @@ -497,8 +633,7 @@ if (!empty($arrayfields['cd.date_fin_validite']['checked'])) print $form->selectDate($filter_date2, 'op2', 0, 0, 1, '', 1, 0); print ''; $arrayofoperators = array('<'=>'<', '>'=>'>'); print $form->selectarray('filter_opcloture', $arrayofoperators, $filter_opcloture, 1); @@ -514,20 +649,17 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (!empty($arrayfields['cd.datec']['checked'])) -{ +if (!empty($arrayfields['cd.datec']['checked'])) { // Date creation print ''; print ''; print ''; $arrayofstatus = array( @@ -552,8 +684,7 @@ $productstatic = new Product($db); $i = 0; $totalarray = array(); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $contractstatic->id = $obj->cid; @@ -570,118 +701,142 @@ while ($i < min($num, $limit)) print '
    '; print $contractstatic->getNomUrl(1, 16); print ''; - if ($obj->pid > 0) - { + if ($obj->pid > 0) { $productstatic->id = $obj->pid; $productstatic->type = $obj->ptype; $productstatic->ref = $obj->pref; $productstatic->entity = $obj->pentity; print $productstatic->getNomUrl(1, '', 24); print $obj->label ? ' - '.dol_trunc($obj->label, 16) : ''; - if (!empty($obj->description) && !empty($conf->global->PRODUCT_DESC_IN_LIST)) print '
    '.dol_nl2br($obj->description); + if (!empty($obj->description) && !empty($conf->global->PRODUCT_DESC_IN_LIST)) { + print '
    '.dol_nl2br($obj->description); + } } else { - if ($obj->type == 0) print img_object($obj->description, 'product').' '.dol_trunc($obj->description, 24); - if ($obj->type == 1) print img_object($obj->description, 'service').' '.dol_trunc($obj->description, 24); + if ($obj->type == 0) { + print img_object($obj->description, 'product').' '.dol_trunc($obj->description, 24); + } + if ($obj->type == 1) { + print img_object($obj->description, 'service').' '.dol_trunc($obj->description, 24); + } } print '
    '; print $obj->qty; print ''; print price($obj->total_ht); print ''; print price($obj->total_tva); print ''; print price2num($obj->tva_tx).'%'; print ''; print price($obj->subprice); print ''; print $companystatic->getNomUrl(1, 'customer', 28); print ''; print ($obj->date_ouverture_prevue ?dol_print_date($db->jdate($obj->date_ouverture_prevue), 'dayhour') : ' '); - if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0) - print ' '.img_picto($langs->trans("Late"), "warning"); - else print '    '; + if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0) { + print ' '.img_picto($langs->trans("Late"), "warning"); + } else { + print '    '; + } print ''.($obj->date_ouverture ?dol_print_date($db->jdate($obj->date_ouverture), 'dayhour') : ' ').''.($obj->date_fin_validite ?dol_print_date($db->jdate($obj->date_fin_validite), 'dayhour') : ' '); - if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5) - { + if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5) { $warning_delay = $conf->contrat->services->expires->warning_delay / 3600 / 24; $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); print img_warning($textlate); - } else print '    '; + } else { + print '    '; + } print ''.dol_print_date($db->jdate($obj->date_cloture), 'dayhour').''; 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 ($obj->cstatut == 0) - { + if ($obj->cstatut == 0) { // If contract is draft, we say line is also draft print $contractstatic->LibStatut(0, 5); } else { print $staticcontratligne->LibStatut($obj->statut, 5, ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now) ? 1 : 0); } print ''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '
    trans("Contract"); ?>getNomUrl(1); ?>trans("Contract"); ?>getNomUrl(1); ?> date_contrat, 'day'); ?>rights->contrat->lire && empty($conf->global->CONTRACT_SHOW_TOTAL_OF_PRODUCT_AS_PRICE)) - { + if ($user->rights->contrat->lire && empty($conf->global->CONTRACT_SHOW_TOTAL_OF_PRODUCT_AS_PRICE)) { $totalcontrat = 0; foreach ($objectlink->lines as $linecontrat) { $totalcontrat = $totalcontrat + $linecontrat->total_ht; diff --git a/htdocs/core/actions_addupdatedelete.inc.php b/htdocs/core/actions_addupdatedelete.inc.php index 1c874fd2418..f871ed73de8 100644 --- a/htdocs/core/actions_addupdatedelete.inc.php +++ b/htdocs/core/actions_addupdatedelete.inc.php @@ -30,18 +30,17 @@ // $backtopage may be defined // $triggermodname may be defined -if (!empty($permissionedit) && empty($permissiontoadd)) $permissiontoadd = $permissionedit; // For backward compatibility +if (!empty($permissionedit) && empty($permissiontoadd)) { + $permissiontoadd = $permissionedit; // For backward compatibility +} -if ($cancel) -{ +if ($cancel) { /*var_dump($cancel); var_dump($backtopage);exit;*/ - if (!empty($backtopageforcancel)) - { + if (!empty($backtopageforcancel)) { header("Location: ".$backtopageforcancel); exit; - } elseif (!empty($backtopage)) - { + } elseif (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -50,28 +49,34 @@ if ($cancel) // Action to add record -if ($action == 'add' && !empty($permissiontoadd)) -{ - foreach ($object->fields as $key => $val) - { +if ($action == 'add' && !empty($permissiontoadd)) { + foreach ($object->fields as $key => $val) { if ($object->fields[$key]['type'] == 'duration') { - if (GETPOST($key.'hour') == '' && GETPOST($key.'min') == '') continue; // The field was not submited to be edited + if (GETPOST($key.'hour') == '' && GETPOST($key.'min') == '') { + continue; // The field was not submited to be edited + } } else { - if (!GETPOSTISSET($key)) continue; // The field was not submited to be edited + if (!GETPOSTISSET($key)) { + continue; // The field was not submited to be edited + } } // Ignore special fields - if (in_array($key, array('rowid', 'entity', 'import_key'))) continue; + if (in_array($key, array('rowid', 'entity', 'import_key'))) { + continue; + } if (in_array($key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) { - if (!in_array(abs($val['visible']), array(1, 3))) continue; // Only 1 and 3 that are case to create + if (!in_array(abs($val['visible']), array(1, 3))) { + continue; // Only 1 and 3 that are case to create + } } // Set value to insert if (in_array($object->fields[$key]['type'], array('text', 'html'))) { $value = GETPOST($key, 'restricthtml'); } elseif ($object->fields[$key]['type'] == 'date') { - $value = dol_mktime(12, 0, 0, GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int')); + $value = dol_mktime(12, 0, 0, GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int')); // for date without hour, we use gmt } elseif ($object->fields[$key]['type'] == 'datetime') { - $value = dol_mktime(GETPOST($key.'hour', 'int'), GETPOST($key.'min', 'int'), 0, GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int')); + $value = dol_mktime(GETPOST($key.'hour', 'int'), GETPOST($key.'min', 'int'), GETPOST($key.'sec', 'int'), GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int'), 'tzuserrel'); } elseif ($object->fields[$key]['type'] == 'duration') { $value = 60 * 60 * GETPOST($key.'hour', 'int') + 60 * GETPOST($key.'min', 'int'); } elseif (preg_match('/^(integer|price|real|double)/', $object->fields[$key]['type'])) { @@ -84,17 +89,19 @@ if ($action == 'add' && !empty($permissiontoadd)) } else { $value = GETPOST($key, 'alphanohtml'); } - if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') $value = ''; // This is an implicit foreign key field - if (!empty($object->fields[$key]['foreignkey']) && $value == '-1') $value = ''; // This is an explicit foreign key field + if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') { + $value = ''; // This is an implicit foreign key field + } + if (!empty($object->fields[$key]['foreignkey']) && $value == '-1') { + $value = ''; // This is an explicit foreign key field + } //var_dump($key.' '.$value.' '.$object->fields[$key]['type']); $object->$key = $value; - if ($val['notnull'] > 0 && $object->$key == '' && !is_null($val['default']) && $val['default'] == '(PROV)') - { + if ($val['notnull'] > 0 && $object->$key == '' && !is_null($val['default']) && $val['default'] == '(PROV)') { $object->$key = '(PROV)'; } - if ($val['notnull'] > 0 && $object->$key == '' && is_null($val['default'])) - { + if ($val['notnull'] > 0 && $object->$key == '' && is_null($val['default'])) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val['label'])), null, 'errors'); } @@ -103,14 +110,14 @@ if ($action == 'add' && !empty($permissiontoadd)) // Fill array 'array_options' with data from add form if (!$error) { $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { $result = $object->create($user); - if ($result > 0) - { + if ($result > 0) { // Creation OK $urltogo = $backtopage ? str_replace('__ID__', $result, $backtopage) : $backurlforlist; $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $urltogo); // New method to autoselect project after a New on another form object creation @@ -118,8 +125,11 @@ if ($action == 'add' && !empty($permissiontoadd)) exit; } else { // Creation KO - if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); + if (!empty($object->errors)) { + setEventMessages(null, $object->errors, 'errors'); + } else { + setEventMessages($object->error, null, 'errors'); + } $action = 'create'; } } else { @@ -128,25 +138,31 @@ if ($action == 'add' && !empty($permissiontoadd)) } // Action to update record -if ($action == 'update' && !empty($permissiontoadd)) -{ - foreach ($object->fields as $key => $val) - { +if ($action == 'update' && !empty($permissiontoadd)) { + foreach ($object->fields as $key => $val) { // Check if field was submited to be edited if ($object->fields[$key]['type'] == 'duration') { - if (!GETPOSTISSET($key.'hour') || !GETPOSTISSET($key.'min')) continue; // The field was not submited to be edited + if (!GETPOSTISSET($key.'hour') || !GETPOSTISSET($key.'min')) { + continue; // The field was not submited to be edited + } } elseif ($object->fields[$key]['type'] == 'boolean') { if (!GETPOSTISSET($key)) { $object->$key = 0; // use 0 instead null if the field is defined as not null continue; } } else { - if (!GETPOSTISSET($key)) continue; // The field was not submited to be edited + if (!GETPOSTISSET($key)) { + continue; // The field was not submited to be edited + } } // Ignore special fields - if (in_array($key, array('rowid', 'entity', 'import_key'))) continue; + if (in_array($key, array('rowid', 'entity', 'import_key'))) { + continue; + } if (in_array($key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) { - if (!in_array(abs($val['visible']), array(1, 3, 4))) continue; // Only 1 and 3 and 4 that are case to update + if (!in_array(abs($val['visible']), array(1, 3, 4))) { + continue; // Only 1 and 3 and 4 that are case to update + } } // Set value to update @@ -158,9 +174,9 @@ if ($action == 'update' && !empty($permissiontoadd)) $value = GETPOST($key, 'restricthtml'); } } elseif ($object->fields[$key]['type'] == 'date') { - $value = dol_mktime(12, 0, 0, GETPOST($key.'month'), GETPOST($key.'day'), GETPOST($key.'year')); + $value = dol_mktime(12, 0, 0, GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int')); // for date without hour, we use gmt } elseif ($object->fields[$key]['type'] == 'datetime') { - $value = dol_mktime(GETPOST($key.'hour'), GETPOST($key.'min'), 0, GETPOST($key.'month'), GETPOST($key.'day'), GETPOST($key.'year')); + $value = dol_mktime(GETPOST($key.'hour', 'int'), GETPOST($key.'min', 'int'), GETPOST($key.'sec', 'int'), GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int'), 'tzuserrel'); } elseif ($object->fields[$key]['type'] == 'duration') { if (GETPOST($key.'hour', 'int') != '' || GETPOST($key.'min', 'int') != '') { $value = 60 * 60 * GETPOST($key.'hour', 'int') + 60 * GETPOST($key.'min', 'int'); @@ -176,12 +192,15 @@ if ($action == 'update' && !empty($permissiontoadd)) } else { $value = GETPOST($key, 'alpha'); } - if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') $value = ''; // This is an implicit foreign key field - if (!empty($object->fields[$key]['foreignkey']) && $value == '-1') $value = ''; // This is an explicit foreign key field + if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') { + $value = ''; // This is an implicit foreign key field + } + if (!empty($object->fields[$key]['foreignkey']) && $value == '-1') { + $value = ''; // This is an explicit foreign key field + } $object->$key = $value; - if ($val['notnull'] > 0 && $object->$key == '' && is_null($val['default'])) - { + if ($val['notnull'] > 0 && $object->$key == '' && is_null($val['default'])) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val['label'])), null, 'errors'); } @@ -190,14 +209,14 @@ if ($action == 'update' && !empty($permissiontoadd)) // Fill array 'array_options' with data from add form if (!$error) { $ret = $extrafields->setOptionalsFromPost(null, $object, '@GETPOSTISSET'); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { $result = $object->update($user); - if ($result > 0) - { + if ($result > 0) { $action = 'view'; } else { // Creation KO @@ -210,8 +229,7 @@ if ($action == 'update' && !empty($permissiontoadd)) } // Action to update one extrafield -if ($action == "update_extras" && !empty($permissiontoadd)) -{ +if ($action == "update_extras" && !empty($permissiontoadd)) { $object->fetch(GETPOST('id', 'int')); $attributekey = GETPOST('attribute', 'alpha'); @@ -226,8 +244,7 @@ if ($action == "update_extras" && !empty($permissiontoadd)) } $result = $object->insertExtraFields(empty($triggermodname) ? '' : $triggermodname, $user); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); $action = 'view'; } else { @@ -237,46 +254,42 @@ if ($action == "update_extras" && !empty($permissiontoadd)) } // Action to delete -if ($action == 'confirm_delete' && !empty($permissiontodelete)) -{ - if (!($object->id > 0)) - { +if ($action == 'confirm_delete' && !empty($permissiontodelete)) { + if (!($object->id > 0)) { dol_print_error('', 'Error, object must be fetched before being deleted'); exit; } $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { // Delete OK setEventMessages("RecordDeleted", null, 'mesgs'); header("Location: ".$backurlforlist); exit; } else { - if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); + if (!empty($object->errors)) { + setEventMessages(null, $object->errors, 'errors'); + } else { + setEventMessages($object->error, null, 'errors'); + } } } // Remove a line -if ($action == 'confirm_deleteline' && $confirm == 'yes' && !empty($permissiontoadd)) -{ +if ($action == 'confirm_deleteline' && $confirm == 'yes' && !empty($permissiontoadd)) { if (method_exists($object, 'deleteline')) { $result = $object->deleteline($user, $lineid); // For backward compatibility } else { $result = $object->deleteLine($user, $lineid); } - if ($result > 0) - { + if ($result > 0) { // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); } - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && is_object($object->thirdparty)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && is_object($object->thirdparty)) { $newlang = $object->thirdparty->default_lang; } if (!empty($newlang)) { @@ -299,18 +312,20 @@ if ($action == 'confirm_deleteline' && $confirm == 'yes' && !empty($permissionto } // Action validate object -if ($action == 'confirm_validate' && $confirm == 'yes' && $permissiontoadd) -{ +if ($action == 'confirm_validate' && $confirm == 'yes' && $permissiontoadd) { $result = $object->validate($user); - if ($result >= 0) - { + if ($result >= 0) { // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { if (method_exists($object, 'generateDocument')) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -332,18 +347,20 @@ if ($action == 'confirm_validate' && $confirm == 'yes' && $permissiontoadd) } // Action close object -if ($action == 'confirm_close' && $confirm == 'yes' && $permissiontoadd) -{ +if ($action == 'confirm_close' && $confirm == 'yes' && $permissiontoadd) { $result = $object->cancel($user); - if ($result >= 0) - { + if ($result >= 0) { // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { if (method_exists($object, 'generateDocument')) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -360,11 +377,9 @@ if ($action == 'confirm_close' && $confirm == 'yes' && $permissiontoadd) } // Action setdraft object -if ($action == 'confirm_setdraft' && $confirm == 'yes' && $permissiontoadd) -{ +if ($action == 'confirm_setdraft' && $confirm == 'yes' && $permissiontoadd) { $result = $object->setDraft($user); - if ($result >= 0) - { + if ($result >= 0) { // Nothing else done } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -372,18 +387,20 @@ if ($action == 'confirm_setdraft' && $confirm == 'yes' && $permissiontoadd) } // Action reopen object -if ($action == 'confirm_reopen' && $confirm == 'yes' && $permissiontoadd) -{ +if ($action == 'confirm_reopen' && $confirm == 'yes' && $permissiontoadd) { $result = $object->reopen($user); - if ($result >= 0) - { + if ($result >= 0) { // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { if (method_exists($object, 'generateDocument')) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -400,21 +417,21 @@ if ($action == 'confirm_reopen' && $confirm == 'yes' && $permissiontoadd) } // Action clone object -if ($action == 'confirm_clone' && $confirm == 'yes' && !empty($permissiontoadd)) -{ - if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) - { +if ($action == 'confirm_clone' && $confirm == 'yes' && !empty($permissiontoadd)) { + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone or if createFromClone modifies the object. We use native clone to keep this->db valid. //$objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int')); // ... $result = $objectutil->createFromClone($user, (($object->id > 0) ? $object->id : $id)); - if (is_object($result) || $result > 0) - { + if (is_object($result) || $result > 0) { $newid = 0; - if (is_object($result)) $newid = $result->id; - else $newid = $result; + if (is_object($result)) { + $newid = $result->id; + } else { + $newid = $result; + } header("Location: ".$_SERVER['PHP_SELF'].'?id='.$newid); // Open record of new object exit; } else { diff --git a/htdocs/core/actions_builddoc.inc.php b/htdocs/core/actions_builddoc.inc.php index 4ae83829fa4..63cac253976 100644 --- a/htdocs/core/actions_builddoc.inc.php +++ b/htdocs/core/actions_builddoc.inc.php @@ -29,27 +29,26 @@ // $upload_dir must be defined (example $conf->projet->dir_output . "/";) // $hidedetails, $hidedesc, $hideref and $moreparams may have been set or not. -if (!empty($permissioncreate) && empty($permissiontoadd)) $permissiontoadd = $permissioncreate; // For backward compatibility +if (!empty($permissioncreate) && empty($permissiontoadd)) { + $permissiontoadd = $permissioncreate; // For backward compatibility +} // Build doc -if ($action == 'builddoc' && $permissiontoadd) -{ - if (is_numeric(GETPOST('model', 'alpha'))) - { +if ($action == 'builddoc' && $permissiontoadd) { + if (is_numeric(GETPOST('model', 'alpha'))) { $error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Model")); } else { - // Reload to get all modified line records and be ready for hooks + // Reload to get all modified line records and be ready for hooks $ret = $object->fetch($id); $ret = $object->fetch_thirdparty(); /*if (empty($object->id) || ! $object->id > 0) - { - dol_print_error('Object must have been loaded by a fetch'); - exit; - }*/ + { + dol_print_error('Object must have been loaded by a fetch'); + exit; + }*/ // Save last template used to generate document - if (GETPOST('model', 'alpha')) - { + if (GETPOST('model', 'alpha')) { $object->setDocModel($user, GETPOST('model', 'alpha')); } @@ -67,29 +66,40 @@ if ($action == 'builddoc' && $permissiontoadd) $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->thirdparty->default_lang)) $newlang = $object->thirdparty->default_lang; // for proposal, order, invoice, ... - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->default_lang)) $newlang = $object->default_lang; // for thirdparty - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->thirdparty->default_lang)) { + $newlang = $object->thirdparty->default_lang; // for proposal, order, invoice, ... + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->default_lang)) { + $newlang = $object->default_lang; // for thirdparty + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } // To be sure vars is defined - if (empty($hidedetails)) $hidedetails = 0; - if (empty($hidedesc)) $hidedesc = 0; - if (empty($hideref)) $hideref = 0; - if (empty($moreparams)) $moreparams = null; + if (empty($hidedetails)) { + $hidedetails = 0; + } + if (empty($hidedesc)) { + $hidedesc = 0; + } + if (empty($hideref)) { + $hideref = 0; + } + if (empty($moreparams)) { + $moreparams = null; + } $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = ''; } else { - if (empty($donotredirect)) // This is set when include is done by bulk action "Bill Orders" - { + if (empty($donotredirect)) { // This is set when include is done by bulk action "Bill Orders" setEventMessages($langs->trans("FileGenerated"), null); $urltoredirect = $_SERVER['REQUEST_URI']; @@ -104,13 +114,11 @@ if ($action == 'builddoc' && $permissiontoadd) } // Delete file in doc form -if ($action == 'remove_file' && $permissiontoadd) -{ +if ($action == 'remove_file' && $permissiontoadd) { if (!empty($upload_dir)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if (empty($object->id) || !$object->id > 0) - { + if (empty($object->id) || !$object->id > 0) { // Reload to get all modified line records and be ready for hooks $ret = $object->fetch($id); $ret = $object->fetch_thirdparty(); @@ -120,8 +128,11 @@ if ($action == 'remove_file' && $permissiontoadd) $filetodelete = GETPOST('file', 'alpha'); $file = $upload_dir.'/'.$filetodelete; $ret = dol_delete_file($file, 0, 0, 0, $object); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", $filetodelete), null, 'errors'); + if ($ret) { + setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", $filetodelete), null, 'errors'); + } // Make a redirect to avoid to keep the remove_file into the url that create side effects $urltoredirect = $_SERVER['REQUEST_URI']; diff --git a/htdocs/core/actions_changeselectedfields.inc.php b/htdocs/core/actions_changeselectedfields.inc.php index 4daf53891cf..f0ead24e6b1 100644 --- a/htdocs/core/actions_changeselectedfields.inc.php +++ b/htdocs/core/actions_changeselectedfields.inc.php @@ -28,14 +28,16 @@ // $object must be defined (object is loaded in this file with fetch) // Save selection -if (GETPOST('formfilteraction', 'alphanohtml') == 'listafterchangingselectedfields') -{ +if (GETPOST('formfilteraction', 'alphanohtml') == 'listafterchangingselectedfields') { $tabparam = array(); $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - if (GETPOST("selectedfields")) $tabparam["MAIN_SELECTEDFIELDS_".$varpage] = GETPOST("selectedfields"); - else $tabparam["MAIN_SELECTEDFIELDS_".$varpage] = ''; + if (GETPOST("selectedfields")) { + $tabparam["MAIN_SELECTEDFIELDS_".$varpage] = GETPOST("selectedfields"); + } else { + $tabparam["MAIN_SELECTEDFIELDS_".$varpage] = ''; + } include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; diff --git a/htdocs/core/actions_comments.inc.php b/htdocs/core/actions_comments.inc.php index f590adee197..fc6bf11a115 100644 --- a/htdocs/core/actions_comments.inc.php +++ b/htdocs/core/actions_comments.inc.php @@ -33,19 +33,16 @@ $comment = new Comment($db); * Actions */ -if ($action == 'addcomment') -{ +if ($action == 'addcomment') { $description = GETPOST('comment_description', 'restricthtml'); - if (!empty($description)) - { + if (!empty($description)) { $comment->description = $description; $comment->datec = time(); $comment->fk_element = GETPOST('id', 'int'); $comment->element_type = GETPOST('comment_element_type', 'alpha'); $comment->fk_user_author = $user->id; $comment->entity = $conf->entity; - if ($comment->create($user) > 0) - { + if ($comment->create($user) > 0) { setEventMessages($langs->trans("CommentAdded"), null, 'mesgs'); header('Location: '.$varpage.'?id='.$id.($withproject ? '&withproject=1' : '')); exit; @@ -55,13 +52,10 @@ if ($action == 'addcomment') } } } -if ($action === 'updatecomment') -{ - if ($comment->fetch($idcomment) >= 0) - { +if ($action === 'updatecomment') { + if ($comment->fetch($idcomment) >= 0) { $comment->description = GETPOST('comment_description', 'restricthtml'); - if ($comment->update($user) > 0) - { + if ($comment->update($user) > 0) { setEventMessages($langs->trans("CommentAdded"), null, 'mesgs'); header('Location: '.$varpage.'?id='.$id.($withproject ? '&withproject=1#comment' : '')); exit; @@ -71,12 +65,9 @@ if ($action === 'updatecomment') } } } -if ($action == 'deletecomment') -{ - if ($comment->fetch($idcomment) >= 0) - { - if ($comment->delete($user) > 0) - { +if ($action == 'deletecomment') { + if ($comment->fetch($idcomment) >= 0) { + if ($comment->delete($user) > 0) { setEventMessages($langs->trans("CommentDeleted"), null, 'mesgs'); header('Location: '.$varpage.'?id='.$id.($withproject ? '&withproject=1' : '')); exit; diff --git a/htdocs/core/actions_dellink.inc.php b/htdocs/core/actions_dellink.inc.php index 2dd2588ca48..a7ac035506f 100644 --- a/htdocs/core/actions_dellink.inc.php +++ b/htdocs/core/actions_dellink.inc.php @@ -30,16 +30,16 @@ $dellinkid = GETPOST('dellinkid', 'int'); $addlinkid = GETPOST('idtolinkto', 'int'); // Link invoice to order -if ($action == 'addlink' && !empty($permissiondellink) && !GETPOST('cancel', 'alpha') && $id > 0 && $addlinkid > 0) -{ +if ($action == 'addlink' && !empty($permissiondellink) && !GETPOST('cancel', 'alpha') && $id > 0 && $addlinkid > 0) { $object->fetch($id); $object->fetch_thirdparty(); $result = $object->add_object_linked(GETPOST('addlink', 'alpha'), $addlinkid); } // Delete link -if ($action == 'dellink' && !empty($permissiondellink) && !GETPOST('cancel', 'alpha') && $dellinkid > 0) -{ +if ($action == 'dellink' && !empty($permissiondellink) && !GETPOST('cancel', 'alpha') && $dellinkid > 0) { $result = $object->deleteObjectLinked(0, '', 0, '', $dellinkid); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } diff --git a/htdocs/core/actions_extrafields.inc.php b/htdocs/core/actions_extrafields.inc.php index 7ba4d7d64b9..b03c2c3d192 100644 --- a/htdocs/core/actions_extrafields.inc.php +++ b/htdocs/core/actions_extrafields.inc.php @@ -31,91 +31,85 @@ $extrasize = GETPOST('size', 'intcomma'); $type = GETPOST('type', 'alpha'); $param = GETPOST('param', 'alpha'); -if ($type == 'double' && strpos($extrasize, ',') === false) $extrasize = '24,8'; -if ($type == 'date') $extrasize = ''; -if ($type == 'datetime') $extrasize = ''; -if ($type == 'select') $extrasize = ''; +if ($type == 'double' && strpos($extrasize, ',') === false) { + $extrasize = '24,8'; +} +if ($type == 'date') { + $extrasize = ''; +} +if ($type == 'datetime') { + $extrasize = ''; +} +if ($type == 'select') { + $extrasize = ''; +} // Add attribute -if ($action == 'add') -{ - if (GETPOST("button") != $langs->trans("Cancel")) - { +if ($action == 'add') { + if (GETPOST("button") != $langs->trans("Cancel")) { // Check values - if (!$type) - { + if (!$type) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")); $action = 'create'; } - if ($type == 'varchar' && $extrasize <= 0) - { + if ($type == 'varchar' && $extrasize <= 0) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Size")); $action = 'edit'; } - if ($type == 'varchar' && $extrasize > $maxsizestring) - { + if ($type == 'varchar' && $extrasize > $maxsizestring) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorSizeTooLongForVarcharType", $maxsizestring); $action = 'create'; } - if ($type == 'int' && $extrasize > $maxsizeint) - { + if ($type == 'int' && $extrasize > $maxsizeint) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorSizeTooLongForIntType", $maxsizeint); $action = 'create'; } - if ($type == 'select' && !$param) - { + if ($type == 'select' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForSelectType"); $action = 'create'; } - if ($type == 'sellist' && !$param) - { + if ($type == 'sellist' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForSelectListType"); $action = 'create'; } - if ($type == 'checkbox' && !$param) - { + if ($type == 'checkbox' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForCheckBoxType"); $action = 'create'; } - if ($type == 'link' && !$param) - { + if ($type == 'link' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForLinkType"); $action = 'create'; } - if ($type == 'radio' && !$param) - { + if ($type == 'radio' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForRadioType"); $action = 'create'; } - if ((($type == 'radio') || ($type == 'checkbox')) && $param) - { + if ((($type == 'radio') || ($type == 'checkbox')) && $param) { // Construct array for parameter (value of select list) $parameters = $param; $parameters_array = explode("\r\n", $parameters); - foreach ($parameters_array as $param_ligne) - { + foreach ($parameters_array as $param_ligne) { if (!empty($param_ligne)) { - if (preg_match_all('/,/', $param_ligne, $matches)) - { + if (preg_match_all('/,/', $param_ligne, $matches)) { if (count($matches[0]) > 1) { $error++; $langs->load("errors"); @@ -160,14 +154,12 @@ if ($action == 'add') $parameters_array = explode("\r\n", $parameters); //In sellist we have only one line and it can have come to do SQL expression if ($type == 'sellist' || $type == 'chkbxlst') { - foreach ($parameters_array as $param_ligne) - { + foreach ($parameters_array as $param_ligne) { $params['options'] = array($parameters=>null); } } else { // Else it's separated key/value and coma list - foreach ($parameters_array as $param_ligne) - { + foreach ($parameters_array as $param_ligne) { list($key, $value) = explode(',', $param_ligne); $params['options'][$key] = $value; } @@ -175,7 +167,9 @@ if ($action == 'add') // Visibility: -1=not visible by default in list, 1=visible, 0=hidden $visibility = GETPOST('list', 'alpha'); - if ($type == 'separate') $visibility = 3; + if ($type == 'separate') { + $visibility = 3; + } $result = $extrafields->addExtraField( GETPOST('attrname', 'aZ09'), @@ -199,8 +193,7 @@ if ($action == 'add') (GETPOST('totalizable', 'alpha') ? 1 : 0), GETPOST('printable', 'alpha') ); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans('SetupSaved'), null, 'mesgs'); header("Location: ".$_SERVER["PHP_SELF"]); exit; @@ -223,77 +216,64 @@ if ($action == 'add') } // Rename field -if ($action == 'update') -{ - if (GETPOST("button") != $langs->trans("Cancel")) - { +if ($action == 'update') { + if (GETPOST("button") != $langs->trans("Cancel")) { // Check values - if (!$type) - { + if (!$type) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")); $action = 'edit'; } - if ($type == 'varchar' && $extrasize <= 0) - { + if ($type == 'varchar' && $extrasize <= 0) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Size")); $action = 'edit'; } - if ($type == 'varchar' && $extrasize > $maxsizestring) - { + if ($type == 'varchar' && $extrasize > $maxsizestring) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorSizeTooLongForVarcharType", $maxsizestring); $action = 'edit'; } - if ($type == 'int' && $extrasize > $maxsizeint) - { + if ($type == 'int' && $extrasize > $maxsizeint) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorSizeTooLongForIntType", $maxsizeint); $action = 'edit'; } - if ($type == 'select' && !$param) - { + if ($type == 'select' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForSelectType"); $action = 'edit'; } - if ($type == 'sellist' && !$param) - { + if ($type == 'sellist' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForSelectListType"); $action = 'edit'; } - if ($type == 'checkbox' && !$param) - { + if ($type == 'checkbox' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForCheckBoxType"); $action = 'edit'; } - if ($type == 'radio' && !$param) - { + if ($type == 'radio' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForRadioType"); $action = 'edit'; } - if ((($type == 'radio') || ($type == 'checkbox')) && $param) - { + if ((($type == 'radio') || ($type == 'checkbox')) && $param) { // Construct array for parameter (value of select list) $parameters = $param; $parameters_array = explode("\r\n", $parameters); - foreach ($parameters_array as $param_ligne) - { + foreach ($parameters_array as $param_ligne) { if (!empty($param_ligne)) { - if (preg_match_all('/,/', $param_ligne, $matches)) - { + if (preg_match_all('/,/', $param_ligne, $matches)) { if (count($matches[0]) > 1) { $error++; $langs->load("errors"); @@ -329,24 +309,20 @@ if ($action == 'update') } } - if (!$error) - { - if (GETPOSTISSET("attrname") && preg_match("/^\w[a-zA-Z0-9-_]*$/", GETPOST('attrname', 'aZ09')) && !is_numeric(GETPOST('attrname', 'aZ09'))) - { + if (!$error) { + if (GETPOSTISSET("attrname") && preg_match("/^\w[a-zA-Z0-9-_]*$/", GETPOST('attrname', 'aZ09')) && !is_numeric(GETPOST('attrname', 'aZ09'))) { $pos = GETPOST('pos', 'int'); // Construct array for parameter (value of select list) $parameters = $param; $parameters_array = explode("\r\n", $parameters); //In sellist we have only one line and it can have come to do SQL expression if ($type == 'sellist' || $type == 'chkbxlst') { - foreach ($parameters_array as $param_ligne) - { + foreach ($parameters_array as $param_ligne) { $params['options'] = array($parameters=>null); } } else { //Esle it's separated key/value and coma list - foreach ($parameters_array as $param_ligne) - { + foreach ($parameters_array as $param_ligne) { list($key, $value) = explode(',', $param_ligne); $params['options'][$key] = $value; } @@ -354,7 +330,9 @@ if ($action == 'update') // Visibility: -1=not visible by default in list, 1=visible, 0=hidden $visibility = GETPOST('list', 'alpha'); - if ($type == 'separate') $visibility = 3; + if ($type == 'separate') { + $visibility = 3; + } // Example: is_object($object) ? ($object->id < 10 ? round($object->id / 2, 2) : (2 * $user->id) * (int) substr($mysoc->zip, 1, 2)) : 'objnotdefined' $computedvalue = GETPOST('computed_value', 'nohtml'); @@ -409,7 +387,9 @@ if ($action == 'delete') { if ($result >= 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; - } else $mesg = $extrafields->error; + } else { + $mesg = $extrafields->error; + } } else { $error++; $langs->load("errors"); diff --git a/htdocs/core/actions_fetchobject.inc.php b/htdocs/core/actions_fetchobject.inc.php index c881b335f18..3ca797a9bb3 100644 --- a/htdocs/core/actions_fetchobject.inc.php +++ b/htdocs/core/actions_fetchobject.inc.php @@ -28,20 +28,15 @@ // $cancel must be defined // $id or $ref must be defined (object is loaded in this file with fetch) -if (($id > 0 || (!empty($ref) && !in_array($action, array('create', 'createtask', 'add')))) && (empty($cancel) || $id > 0)) -{ - if (($id > 0 && is_numeric($id)) || !empty($ref)) // To discard case when id is list of ids like '1,2,3...' - { +if (($id > 0 || (!empty($ref) && !in_array($action, array('create', 'createtask', 'add')))) && (empty($cancel) || $id > 0)) { + if (($id > 0 && is_numeric($id)) || !empty($ref)) { // To discard case when id is list of ids like '1,2,3...' $ret = $object->fetch($id, $ref); - if ($ret > 0) - { + if ($ret > 0) { $object->fetch_thirdparty(); $id = $object->id; } else { - if (empty($object->error) && !count($object->errors)) - { - if ($ret < 0) // if $ret == 0, it means not found. - { + if (empty($object->error) && !count($object->errors)) { + if ($ret < 0) { // if $ret == 0, it means not found. setEventMessages('Fetch on object (type '.get_class($object).') return an error without filling $object->error nor $object->errors', null, 'errors'); } } else { diff --git a/htdocs/core/actions_lineupdown.inc.php b/htdocs/core/actions_lineupdown.inc.php index e5507eeafc0..5aee952292b 100644 --- a/htdocs/core/actions_lineupdown.inc.php +++ b/htdocs/core/actions_lineupdown.inc.php @@ -28,15 +28,18 @@ // $langs must be defined // $hidedetails, $hidedesc, $hideref must de defined -if ($action == 'up' && $permissiontoedit) -{ +if ($action == 'up' && $permissiontoedit) { $object->line_up(GETPOST('rowid')); // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -50,15 +53,18 @@ if ($action == 'up' && $permissiontoedit) exit(); } -if ($action == 'down' && $permissiontoedit) -{ +if ($action == 'down' && $permissiontoedit) { $object->line_down(GETPOST('rowid')); // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); diff --git a/htdocs/core/actions_linkedfiles.inc.php b/htdocs/core/actions_linkedfiles.inc.php index b0671bbf555..af60583118d 100644 --- a/htdocs/core/actions_linkedfiles.inc.php +++ b/htdocs/core/actions_linkedfiles.inc.php @@ -27,17 +27,16 @@ // Submit file/link -if (GETPOST('sendit', 'alpha') && !empty($conf->global->MAIN_UPLOAD_DOC)) -{ - if (!empty($_FILES)) - { - if (is_array($_FILES['userfile']['tmp_name'])) $userfiles = $_FILES['userfile']['tmp_name']; - else $userfiles = array($_FILES['userfile']['tmp_name']); +if (GETPOST('sendit', 'alpha') && !empty($conf->global->MAIN_UPLOAD_DOC)) { + if (!empty($_FILES)) { + if (is_array($_FILES['userfile']['tmp_name'])) { + $userfiles = $_FILES['userfile']['tmp_name']; + } else { + $userfiles = array($_FILES['userfile']['tmp_name']); + } - foreach ($userfiles as $key => $userfile) - { - if (empty($_FILES['userfile']['tmp_name'][$key])) - { + foreach ($userfiles as $key => $userfile) { + if (empty($_FILES['userfile']['tmp_name'][$key])) { $error++; if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2) { setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors'); @@ -47,27 +46,24 @@ if (GETPOST('sendit', 'alpha') && !empty($conf->global->MAIN_UPLOAD_DOC)) } } - if (!$error) - { + if (!$error) { // Define if we have to generate thumbs or not $generatethumbs = 1; - if (GETPOST('section_dir', 'alpha')) $generatethumbs = 0; + if (GETPOST('section_dir', 'alpha')) { + $generatethumbs = 0; + } $allowoverwrite = (GETPOST('overwritefile', 'int') ? 1 : 0); - if (!empty($upload_dirold) && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) - { + if (!empty($upload_dirold) && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { $result = dol_add_file_process($upload_dirold, $allowoverwrite, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs, $object); - } elseif (!empty($upload_dir)) - { + } elseif (!empty($upload_dir)) { $result = dol_add_file_process($upload_dir, $allowoverwrite, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs, $object); } } } -} elseif (GETPOST('linkit', 'restricthtml') && !empty($conf->global->MAIN_UPLOAD_DOC)) -{ +} elseif (GETPOST('linkit', 'restricthtml') && !empty($conf->global->MAIN_UPLOAD_DOC)) { $link = GETPOST('link', 'alpha'); - if ($link) - { + if ($link) { if (substr($link, 0, 7) != 'http://' && substr($link, 0, 8) != 'https://' && substr($link, 0, 7) != 'file://') { $link = 'http://'.$link; } @@ -77,17 +73,18 @@ if (GETPOST('sendit', 'alpha') && !empty($conf->global->MAIN_UPLOAD_DOC)) // Delete file/link -if ($action == 'confirm_deletefile' && $confirm == 'yes') -{ +if ($action == 'confirm_deletefile' && $confirm == 'yes') { $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP). if (GETPOST('section', 'alpha')) { // For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile; } else // For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile. { - $urlfile = basename($urlfile); - $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile; - if (!empty($upload_dirold)) $fileold = $upload_dirold."/".$urlfile; + $urlfile = basename($urlfile); + $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile; + if (!empty($upload_dirold)) { + $fileold = $upload_dirold."/".$urlfile; + } } $linkid = GETPOST('linkid', 'int'); @@ -97,21 +94,20 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette (if file is an image) $ret = dol_delete_file($file, 0, 0, 0, (is_object($object) ? $object : null)); - if (!empty($fileold)) dol_delete_file($fileold, 0, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path + if (!empty($fileold)) { + dol_delete_file($fileold, 0, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path + } // If it exists, remove thumb. $regs = array(); - if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i', $file, $regs)) - { + if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i', $file, $regs)) { $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_small'.$regs[0]); - if (file_exists(dol_osencode($dirthumb.$photo_vignette))) - { + if (file_exists(dol_osencode($dirthumb.$photo_vignette))) { dol_delete_file($dirthumb.$photo_vignette); } $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_mini'.$regs[0]); - if (file_exists(dol_osencode($dirthumb.$photo_vignette))) - { + if (file_exists(dol_osencode($dirthumb.$photo_vignette))) { dol_delete_file($dirthumb.$photo_vignette); } } @@ -149,33 +145,27 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') exit; } } -} elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha')) -{ +} elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha')) { require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $langs->load('link'); $link = new Link($db); $f = $link->fetch(GETPOST('linkid', 'int')); - if ($f) - { + if ($f) { $link->url = GETPOST('link', 'alpha'); - if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://') - { + if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://') { $link->url = 'http://'.$link->url; } $link->label = GETPOST('label', 'alphanohtml'); $res = $link->update($user); - if (!$res) - { + if (!$res) { setEventMessages($langs->trans("ErrorFailedToUpdateLink", $link->label), null, 'mesgs'); } } else { //error fetching } -} elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha')) -{ +} elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha')) { // For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile. - if (!empty($upload_dir)) - { + if (!empty($upload_dir)) { $filenamefrom = dol_sanitizeFileName(GETPOST('renamefilefrom', 'alpha'), '_', 0); // Do not remove accents $filenameto = dol_sanitizeFileName(GETPOST('renamefileto', 'alpha'), '_', 0); // Do not remove accents @@ -183,24 +173,23 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') // this function is also applied when we upload and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call). $filenameto = dol_string_nohtmltag($filenameto); - if ($filenamefrom != $filenameto) - { + if ($filenamefrom != $filenameto) { // Security: // Disallow file with some extensions. We rename them. // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code. - if (isAFileWithExecutableContent($filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) - { + if (isAFileWithExecutableContent($filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) { // $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too. $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity]; - if (!preg_match('/\/$/', $publicmediasdirwithslash)) $publicmediasdirwithslash .= '/'; + if (!preg_match('/\/$/', $publicmediasdirwithslash)) { + $publicmediasdirwithslash .= '/'; + } if (strpos($upload_dir, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory $filenameto .= '.noexe'; } } - if ($filenamefrom && $filenameto) - { + if ($filenamefrom && $filenameto) { $srcpath = $upload_dir.'/'.$filenamefrom; $destpath = $upload_dir.'/'.$filenameto; @@ -208,26 +197,24 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') $parameters = array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir); $reshook = $hookmanager->executeHooks('renameUploadedFile', $parameters, $object); - if (empty($reshook)) - { + if (empty($reshook)) { if (preg_match('/^\./', $filenameto)) { $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now. setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors'); } elseif (!file_exists($destpath)) { $result = dol_move($srcpath, $destpath); - if ($result) - { + if ($result) { // Define if we have to generate thumbs or not $generatethumbs = 1; // When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here) // When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case) // but when we rename from a tab "Documents", we must regenerate thumbs - if (GETPOST('modulepart') == 'medias') $generatethumbs = 0; + if (GETPOST('modulepart') == 'medias') { + $generatethumbs = 0; + } - if ($generatethumbs) - { - if ($object->id) - { + if ($generatethumbs) { + if ($object->id) { $object->addThumbs($destpath); } @@ -250,19 +237,15 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') } // Update properties in ECM table - if (GETPOST('ecmfileid', 'int') > 0) - { + if (GETPOST('ecmfileid', 'int') > 0) { $shareenabled = GETPOST('shareenabled', 'alpha'); include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile = new EcmFiles($db); $result = $ecmfile->fetch(GETPOST('ecmfileid', 'int')); - if ($result > 0) - { - if ($shareenabled) - { - if (empty($ecmfile->share)) - { + if ($result > 0) { + if ($shareenabled) { + if (empty($ecmfile->share)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; $ecmfile->share = getRandomPassword(true); } @@ -270,8 +253,7 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') $ecmfile->share = ''; } $result = $ecmfile->update($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); } } diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 95c5037c5fb..057443d09b4 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -3,7 +3,7 @@ * Copyright (C) 2018 Nicolas ZABOURI * Copyright (C) 2018 Juanjo Menent * Copyright (C) 2019 Ferran Marcet - * 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 @@ -37,37 +37,38 @@ // Protection -if (empty($objectclass) || empty($uploaddir)) -{ +if (empty($objectclass) || empty($uploaddir)) { dol_print_error(null, 'include of actions_massactions.inc.php is done but var $objectclass or $uploaddir was not defined'); exit; } // For backward compatibility -if (!empty($permtoread) && empty($permissiontoread)) $permissiontoread = $permtoread; -if (!empty($permtocreate) && empty($permissiontoadd)) $permissiontoadd = $permtocreate; -if (!empty($permtodelete) && empty($permissiontodelete)) $permissiontodelete = $permtodelete; +if (!empty($permtoread) && empty($permissiontoread)) { + $permissiontoread = $permtoread; +} +if (!empty($permtocreate) && empty($permissiontoadd)) { + $permissiontoadd = $permtocreate; +} +if (!empty($permtodelete) && empty($permissiontodelete)) { + $permissiontodelete = $permtodelete; +} // Mass actions. Controls on number of lines checked. $maxformassaction = (empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS) ? 1000 : $conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS); -if (!empty($massaction) && is_array($toselect) && count($toselect) < 1) -{ +if (!empty($massaction) && is_array($toselect) && count($toselect) < 1) { $error++; setEventMessages($langs->trans("NoRecordSelected"), null, "warnings"); } -if (!$error && is_array($toselect) && count($toselect) > $maxformassaction) -{ +if (!$error && is_array($toselect) && count($toselect) > $maxformassaction) { setEventMessages($langs->trans('TooManyRecordForMassAction', $maxformassaction), null, 'errors'); $error++; } -if (!$error && $massaction == 'confirm_presend' && !GETPOST('sendmail')) // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form -{ +if (!$error && $massaction == 'confirm_presend' && !GETPOST('sendmail')) { // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form $massaction = 'presend'; } -if (!$error && $massaction == 'confirm_presend') -{ +if (!$error && $massaction == 'confirm_presend') { $resaction = ''; $nbsent = 0; $nbignored = 0; @@ -82,27 +83,36 @@ if (!$error && $massaction == 'confirm_presend') $attachedfilesThirdpartyObj = array(); $oneemailperrecipient = (GETPOST('oneemailperrecipient') == 'on' ? 1 : 0); - if (!$error) - { + if (!$error) { $thirdparty = new Societe($db); $objecttmp = new $objectclass($db); - if ($objecttmp->element == 'expensereport') $thirdparty = new User($db); - if ($objecttmp->element == 'holiday') $thirdparty = new User($db); + if ($objecttmp->element == 'expensereport') { + $thirdparty = new User($db); + } + if ($objecttmp->element == 'holiday') { + $thirdparty = new User($db); + } - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $objecttmp = new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $listofobjectid[$toselectid] = $toselectid; $thirdpartyid = ($objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid); - if ($objecttmp->element == 'societe') $thirdpartyid = $objecttmp->id; - if ($objecttmp->element == 'expensereport') $thirdpartyid = $objecttmp->fk_user_author; - if ($objecttmp->element == 'holiday') $thirdpartyid = $objecttmp->fk_user; - if (empty($thirdpartyid)) $thirdpartyid = 0; + if ($objecttmp->element == 'societe') { + $thirdpartyid = $objecttmp->id; + } + if ($objecttmp->element == 'expensereport') { + $thirdpartyid = $objecttmp->fk_user_author; + } + if ($objecttmp->element == 'holiday') { + $thirdpartyid = $objecttmp->fk_user; + } + if (empty($thirdpartyid)) { + $thirdpartyid = 0; + } if ($objectclass == 'Facture') { $tmparraycontact = array(); @@ -121,41 +131,37 @@ if (!$error && $massaction == 'confirm_presend') } // Check mandatory parameters - if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email)) - { + if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email)) { $error++; setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings'); $massaction = 'presend'; } $receiver = $_POST['receiver']; - if (!is_array($receiver)) - { - if (empty($receiver) || $receiver == '-1') $receiver = array(); - else $receiver = array($receiver); + if (!is_array($receiver)) { + if (empty($receiver) || $receiver == '-1') { + $receiver = array(); + } else { + $receiver = array($receiver); + } } - if (!trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) // if only one recipient, receiver is mandatory - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings'); - $massaction = 'presend'; + if (!trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) { // if only one recipient, receiver is mandatory + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings'); + $massaction = 'presend'; } - if (!GETPOST('subject', 'restricthtml')) - { + if (!GETPOST('subject', 'restricthtml')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings'); $massaction = 'presend'; } // Loop on each recipient/thirdparty - if (!$error) - { - foreach ($listofobjectthirdparties as $thirdpartyid) - { + if (!$error) { + foreach ($listofobjectthirdparties as $thirdpartyid) { $result = $thirdparty->fetch($thirdpartyid); - if ($result < 0) - { + if ($result < 0) { dol_print_error($db); exit; } @@ -167,21 +173,16 @@ if (!$error && $massaction == 'confirm_presend') // Define $sendto $tmparray = array(); - if (trim($_POST['sendto'])) - { + if (trim($_POST['sendto'])) { // Recipients are provided into free text $tmparray[] = trim($_POST['sendto']); } - if (count($receiver) > 0) - { - foreach ($receiver as $key=>$val) - { + if (count($receiver) > 0) { + foreach ($receiver as $key => $val) { // Recipient was provided from combo list - if ($val == 'thirdparty') // Id of third party or user - { + if ($val == 'thirdparty') { // Id of third party or user $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; - } elseif ($val && method_exists($thirdparty, 'contact_get_property')) // Id of contact - { + } elseif ($val && method_exists($thirdparty, 'contact_get_property')) { // Id of contact $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email'); $sendtoid[] = $val; } @@ -191,26 +192,23 @@ if (!$error && $massaction == 'confirm_presend') // Define $sendtocc $receivercc = $_POST['receivercc']; - if (!is_array($receivercc)) - { - if ($receivercc == '-1') $receivercc = array(); - else $receivercc = array($receivercc); + if (!is_array($receivercc)) { + if ($receivercc == '-1') { + $receivercc = array(); + } else { + $receivercc = array($receivercc); + } } $tmparray = array(); - if (trim($_POST['sendtocc'])) - { + if (trim($_POST['sendtocc'])) { $tmparray[] = trim($_POST['sendtocc']); } - if (count($receivercc) > 0) - { - foreach ($receivercc as $key=>$val) - { + if (count($receivercc) > 0) { + foreach ($receivercc as $key => $val) { // Recipient was provided from combo list - if ($val == 'thirdparty') // Id of third party - { + if ($val == 'thirdparty') { // Id of third party $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; - } elseif ($val) // Id du contact - { + } elseif ($val) { // Id du contact $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email'); //$sendtoid[] = $val; TODO Add also id of contact in CC ? } @@ -223,25 +221,21 @@ if (!$error && $massaction == 'confirm_presend') $listofqualifiedref = array(); $thirdpartywithoutemail = array(); - foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj) - { + foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj) { //var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut); - if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT) - { + if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT) { $langs->load("errors"); $nbignored++; $resaction .= '
    '.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction', $objectobj->ref).'

    '; continue; // Payment done or started or canceled } - if ($objectclass == 'Commande' && $objectobj->statut == Commande::STATUS_DRAFT) - { + if ($objectclass == 'Commande' && $objectobj->statut == Commande::STATUS_DRAFT) { $langs->load("errors"); $nbignored++; $resaction .= '
    '.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction', $objectobj->ref).'

    '; continue; } - if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT) - { + if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT) { $langs->load("errors"); $nbignored++; $resaction .= '
    '.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction', $objectobj->ref).'

    '; @@ -249,23 +243,18 @@ if (!$error && $massaction == 'confirm_presend') } // Test recipient - if (empty($sendto)) // For the case, no recipient were set (multi thirdparties send) - { - if ($objectobj->element == 'societe') - { + if (empty($sendto)) { // For the case, no recipient were set (multi thirdparties send) + if ($objectobj->element == 'societe') { $sendto = $objectobj->email; - } elseif ($objectobj->element == 'expensereport') - { + } elseif ($objectobj->element == 'expensereport') { $fuser = new User($db); $fuser->fetch($objectobj->fk_user_author); $sendto = $fuser->email; - } elseif ($objectobj->element == 'holiday') - { + } elseif ($objectobj->element == 'holiday') { $fuser = new User($db); $fuser->fetch($objectobj->fk_user); $sendto = $fuser->email; - } elseif ($objectobj->element == 'facture' && !empty($listofobjectcontacts[$objectid])) - { + } elseif ($objectobj->element == 'facture' && !empty($listofobjectcontacts[$objectid])) { $emails_to_sends = array(); $objectobj->fetch_thirdparty(); $contactidtosend = array(); @@ -284,25 +273,22 @@ if (!$error && $massaction == 'confirm_presend') } } - if (empty($sendto)) - { + if (empty($sendto)) { if ($objectobj->element == 'societe') { $objectobj->thirdparty = $objectobj; // Hack so following code is comaptible when objectobj is a thirdparty } - //print "No recipient for thirdparty ".$objectobj->thirdparty->name; - $nbignored++; - if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id])) - { + //print "No recipient for thirdparty ".$objectobj->thirdparty->name; + $nbignored++; + if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id])) { $resaction .= '
    '.$langs->trans('NoRecipientEmail', $objectobj->thirdparty->name).'

    '; } dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING); $thirdpartywithoutemail[$objectobj->thirdparty->id] = 1; - continue; + continue; } - if ($_POST['addmaindocfile']) - { + if ($_POST['addmaindocfile']) { // TODO Use future field $objectobj->fullpathdoc to know where is stored default file // TODO If not defined, use $objectobj->model_pdf (or defaut invoice config) to know what is template to use to regenerate doc. $filename = dol_sanitizeFileName($objectobj->ref).'.pdf'; @@ -313,16 +299,14 @@ if (!$error && $massaction == 'confirm_presend') $file = $filedir.'/'.$filename; // For supplier invoices, we use the file provided by supplier, not the one we generate - if ($objectobj->element == 'invoice_supplier') - { + if ($objectobj->element == 'invoice_supplier') { $fileparams = dol_most_recent_file($uploaddir.'/'.get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element).$objectobj->ref, preg_quote($objectobj->ref, '/').'([^\-])+'); $file = $fileparams['fullname']; } $mime = dol_mimetype($file); - if (dol_is_file($file)) - { + if (dol_is_file($file)) { // Create form object $attachedfilesThirdpartyObj[$thirdpartyid][$objectid] = array( 'paths'=>array($file), @@ -347,8 +331,7 @@ if (!$error && $massaction == 'confirm_presend') } // Send email if there is at least one qualified object for current thirdparty - if (count($listofqualifiedobj) > 0) - { + if (count($listofqualifiedobj) > 0) { $langs->load("commercial"); $reg = array(); @@ -367,8 +350,7 @@ if (!$error && $massaction == 'confirm_presend') $sql = 'SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1]; $resql = $db->query($sql); $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $from = $obj->label.' <'.$obj->email.'>'; } } else { @@ -380,22 +362,34 @@ if (!$error && $massaction == 'confirm_presend') $message = GETPOST('message', 'restricthtml'); $sendtobcc = GETPOST('sendtoccc'); - if ($objectclass == 'Propal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)); - if ($objectclass == 'Commande') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)); - if ($objectclass == 'Facture') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)); - if ($objectclass == 'Supplier_Proposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)); - if ($objectclass == 'CommandeFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)); - if ($objectclass == 'FactureFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)); - if ($objectclass == 'Project') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO)); + if ($objectclass == 'Propal') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)); + } + if ($objectclass == 'Commande') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)); + } + if ($objectclass == 'Facture') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)); + } + if ($objectclass == 'Supplier_Proposal') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)); + } + if ($objectclass == 'CommandeFournisseur') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)); + } + if ($objectclass == 'FactureFournisseur') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)); + } + if ($objectclass == 'Project') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO)); + } // $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet) // $looparray will be an array with number of email to send for the current thirdparty (so 1 or n if n object for same thirdparty) $looparray = array(); - if (!$oneemailperrecipient) - { + if (!$oneemailperrecipient) { $looparray = $listofqualifiedobj; - foreach ($looparray as $key => $objecttmp) - { + foreach ($looparray as $key => $objecttmp) { $looparray[$key]->thirdparty = $thirdparty; // Force thirdparty on object } } else { @@ -406,11 +400,9 @@ if (!$error && $massaction == 'confirm_presend') //var_dump($looparray);exit; dol_syslog("We have set an array of ".count($looparray)." emails to send. oneemailperrecipient=".$oneemailperrecipient); //var_dump($oneemailperrecipient); var_dump($listofqualifiedobj); var_dump($listofqualifiedref); - foreach ($looparray as $objectid => $objecttmp) // $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per object - { + foreach ($looparray as $objectid => $objecttmp) { // $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per object // Make substitution in email content - if (!empty($conf->projet->enabled) && method_exists($objecttmp, 'fetch_projet') && is_null($objecttmp->project)) - { + if (!empty($conf->projet->enabled) && method_exists($objecttmp, 'fetch_projet') && is_null($objecttmp->project)) { $objecttmp->fetch_projet(); } $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp); @@ -434,12 +426,10 @@ if (!$error && $massaction == 'confirm_presend') $messagereplaced = make_substitutions($message, $substitutionarray); $attachedfiles = array('paths'=>array(), 'names'=>array(), 'mimes'=>array()); - if ($oneemailperrecipient) - { + if ($oneemailperrecipient) { // if "one email per recipient" is check we must collate $attachedfiles by thirdparty - if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id])) - { - foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) { + if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id])) { + foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) { // Create form object $attachedfiles = array( 'paths'=>array_merge($attachedfiles['paths'], $objAttachedFiles['paths']), @@ -459,20 +449,37 @@ if (!$error && $massaction == 'confirm_presend') $mimetype = $attachedfiles['mimes']; // Define the trackid when emails sent from the mass action - if ($oneemailperrecipient) - { + if ($oneemailperrecipient) { $trackid = 'thi'.$thirdparty->id; - if ($objecttmp->element == 'expensereport') $trackid = 'use'.$thirdparty->id; - if ($objecttmp->element == 'holiday') $trackid = 'use'.$thirdparty->id; + if ($objecttmp->element == 'expensereport') { + $trackid = 'use'.$thirdparty->id; + } + if ($objecttmp->element == 'holiday') { + $trackid = 'use'.$thirdparty->id; + } } else { $trackid = strtolower(get_class($objecttmp)); - if (get_class($objecttmp) == 'Contrat') $trackid = 'con'; - if (get_class($objecttmp) == 'Propal') $trackid = 'pro'; - if (get_class($objecttmp) == 'Commande') $trackid = 'ord'; - if (get_class($objecttmp) == 'Facture') $trackid = 'inv'; - if (get_class($objecttmp) == 'Supplier_Proposal') $trackid = 'spr'; - if (get_class($objecttmp) == 'CommandeFournisseur') $trackid = 'sor'; - if (get_class($objecttmp) == 'FactureFournisseur') $trackid = 'sin'; + if (get_class($objecttmp) == 'Contrat') { + $trackid = 'con'; + } + if (get_class($objecttmp) == 'Propal') { + $trackid = 'pro'; + } + if (get_class($objecttmp) == 'Commande') { + $trackid = 'ord'; + } + if (get_class($objecttmp) == 'Facture') { + $trackid = 'inv'; + } + if (get_class($objecttmp) == 'Supplier_Proposal') { + $trackid = 'spr'; + } + if (get_class($objecttmp) == 'CommandeFournisseur') { + $trackid = 'sor'; + } + if (get_class($objecttmp) == 'FactureFournisseur') { + $trackid = 'sin'; + } $trackid .= $objecttmp->id; } @@ -480,40 +487,42 @@ if (!$error && $massaction == 'confirm_presend') //var_dump($trackid);exit; //var_dump($subjectreplaced); - if (empty($sendcontext)) $sendcontext = 'standard'; + if (empty($sendcontext)) { + $sendcontext = 'standard'; + } // Send mail (substitutionarray must be done just before this) require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $mailfile = new CMailFile($subjectreplaced, $sendto, $from, $messagereplaced, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext); - if ($mailfile->error) - { + if ($mailfile->error) { $resaction .= '
    '.$mailfile->error.'
    '; } else { $result = $mailfile->sendfile(); - if ($result) - { + if ($result) { $resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 2)).'
    '; // Must not contain " $error = 0; // Insert logs into agenda - foreach ($listofqualifiedobj as $objid2 => $objectobj2) - { - if ((!$oneemailperrecipient) && $objid2 != $objectid) continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level + foreach ($listofqualifiedobj as $objid2 => $objectobj2) { + if ((!$oneemailperrecipient) && $objid2 != $objectid) { + continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level + } dol_syslog("Try to insert email event into agenda for objid=".$objid2." => objectobj=".get_class($objectobj2)); /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP'; - if ($objectclass == 'Commande') $actiontypecode='AC_COM'; - if ($objectclass == 'Facture') $actiontypecode='AC_FAC'; - if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO'; - if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD'; - if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/ + if ($objectclass == 'Commande') $actiontypecode='AC_COM'; + if ($objectclass == 'Facture') $actiontypecode='AC_FAC'; + if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO'; + if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD'; + if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/ $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; - if ($message) - { - if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc); + if ($message) { + if ($sendtocc) { + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc); + } $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subjectreplaced); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":"); $actionmsg = dol_concatdesc($actionmsg, $messagereplaced); @@ -528,24 +537,40 @@ if (!$error && $massaction == 'confirm_presend') $objectobj2->elementtype = $objectobj2->element; $triggername = strtoupper(get_class($objectobj2)).'_SENTBYMAIL'; - if ($triggername == 'SOCIETE_SENTBYMAIL') $triggername = 'COMPANY_SENTBYMAIL'; - if ($triggername == 'CONTRAT_SENTBYMAIL') $triggername = 'CONTRACT_SENTBYMAIL'; - if ($triggername == 'COMMANDE_SENTBYMAIL') $triggername = 'ORDER_SENTBYMAIL'; - if ($triggername == 'FACTURE_SENTBYMAIL') $triggername = 'BILL_SENTBYMAIL'; - if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYMAIL'; - if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL'; - if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYMAIL'; - if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL'; + if ($triggername == 'SOCIETE_SENTBYMAIL') { + $triggername = 'COMPANY_SENTBYMAIL'; + } + if ($triggername == 'CONTRAT_SENTBYMAIL') { + $triggername = 'CONTRACT_SENTBYMAIL'; + } + if ($triggername == 'COMMANDE_SENTBYMAIL') { + $triggername = 'ORDER_SENTBYMAIL'; + } + if ($triggername == 'FACTURE_SENTBYMAIL') { + $triggername = 'BILL_SENTBYMAIL'; + } + if ($triggername == 'EXPEDITION_SENTBYMAIL') { + $triggername = 'SHIPPING_SENTBYMAIL'; + } + if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') { + $triggername = 'ORDER_SUPPLIER_SENTBYMAIL'; + } + if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') { + $triggername = 'BILL_SUPPLIER_SENTBYMAIL'; + } + if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') { + $triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL'; + } - if (!empty($triggername)) - { + if (!empty($triggername)) { // Call trigger $result = $objectobj2->call_trigger($triggername, $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if ($error) - { + if ($error) { setEventMessages($db->lasterror(), $errors, 'errors'); dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR); } @@ -555,8 +580,7 @@ if (!$error && $massaction == 'confirm_presend') } } else { $langs->load("other"); - if ($mailfile->error) - { + if ($mailfile->error) { $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto); $resaction .= '
    '.$mailfile->error.'
    '; } else { @@ -574,8 +598,7 @@ if (!$error && $massaction == 'confirm_presend') $resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n
    "; $resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n
    "; - if ($nbsent) - { + if ($nbsent) { $action = ''; // Do not show form post if there was at least one successfull sent //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs'); setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs'); @@ -591,8 +614,7 @@ if (!$error && $massaction == 'confirm_presend') } // TODO Move this action into commande/list.php if called only by this page. -if ($massaction == 'confirm_createbills') // Create bills from orders. -{ +if ($massaction == 'confirm_createbills') { // Create bills from orders. $orders = GETPOST('toselect', 'array'); $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); $validate_invoices = GETPOST('validate_invoices', 'int'); @@ -606,10 +628,11 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $db->begin(); - foreach ($orders as $id_order) - { + foreach ($orders as $id_order) { $cmd = new Commande($db); - if ($cmd->fetch($id_order) <= 0) continue; + if ($cmd->fetch($id_order) <= 0) { + continue; + } $objecttmp = new Facture($db); if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) { @@ -624,11 +647,12 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $objecttmp->mode_reglement_id = $cmd->mode_reglement_id; $objecttmp->fk_project = $cmd->fk_project; $objecttmp->multicurrency_code = $cmd->multicurrency_code; - if (empty($createbills_onebythird)) $objecttmp->ref_client = $cmd->ref_client; + if (empty($createbills_onebythird)) { + $objecttmp->ref_client = $cmd->ref_client; + } $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - if (empty($datefacture)) - { + if (empty($datefacture)) { $datefacture = dol_now(); } @@ -647,8 +671,7 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. } } - if ($objecttmp->id > 0) - { + if ($objecttmp->id > 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; $sql .= "fk_source"; $sql .= ", sourcetype"; @@ -661,16 +684,13 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $sql .= ", '".$db->escape($objecttmp->element)."'"; $sql .= ")"; - if (!$db->query($sql)) - { + if (!$db->query($sql)) { $error++; } - if (!$error) - { + if (!$error) { $lines = $cmd->lines; - if (empty($lines) && method_exists($cmd, 'fetch_lines')) - { + if (empty($lines) && method_exists($cmd, 'fetch_lines')) { $cmd->fetch_lines(); $lines = $cmd->lines; } @@ -678,17 +698,14 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $desc = ($lines[$i]->desc ? $lines[$i]->desc : ''); // If we build one invoice for several order, we must put the invoice of order on the line - if (!empty($createbills_onebythird)) - { + if (!empty($createbills_onebythird)) { $desc = dol_concatdesc($desc, $langs->trans("Order").' '.$cmd->ref.' - '.dol_print_date($cmd->date, 'day')); } - if ($lines[$i]->subprice < 0) - { + if ($lines[$i]->subprice < 0) { // Negative line, we create a discount line $discount = new DiscountAbsolute($db); $discount->fk_soc = $objecttmp->socid; @@ -699,8 +716,7 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $discount->fk_user = $user->id; $discount->description = $desc; $discountid = $discount->create($user); - if ($discountid > 0) - { + if ($discountid > 0) { $result = $objecttmp->insert_discount($discountid); //$result=$discount->link_to_invoice($lineid,$id); } else { @@ -713,17 +729,28 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); // Date start $date_start = false; - if ($lines[$i]->date_debut_prevue) $date_start = $lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) $date_start = $lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) $date_start = $lines[$i]->date_start; + if ($lines[$i]->date_debut_prevue) { + $date_start = $lines[$i]->date_debut_prevue; + } + if ($lines[$i]->date_debut_reel) { + $date_start = $lines[$i]->date_debut_reel; + } + if ($lines[$i]->date_start) { + $date_start = $lines[$i]->date_start; + } //Date end $date_end = false; - if ($lines[$i]->date_fin_prevue) $date_end = $lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) $date_end = $lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) $date_end = $lines[$i]->date_end; + if ($lines[$i]->date_fin_prevue) { + $date_end = $lines[$i]->date_fin_prevue; + } + if ($lines[$i]->date_fin_reel) { + $date_end = $lines[$i]->date_fin_reel; + } + if ($lines[$i]->date_end) { + $date_end = $lines[$i]->date_end; + } // Reset fk_parent_line for no child products and special product - if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) - { + if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) { $fk_parent_line = 0; } @@ -762,9 +789,8 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. 100, 0, $lines[$i]->fk_unit - ); - if ($result > 0) - { + ); + if ($result > 0) { $lineid = $result; } else { $lineid = 0; @@ -772,8 +798,7 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. break; } // Defined the new fk_parent_line - if ($result > 0 && $lines[$i]->product_type == 9) - { + if ($result > 0 && $lines[$i]->product_type == 9) { $fk_parent_line = $result; } } @@ -783,23 +808,23 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module. - if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp; - else $TFact[$objecttmp->id] = $objecttmp; + if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) { + $TFactThird[$cmd->socid] = $objecttmp; + } else { + $TFact[$objecttmp->id] = $objecttmp; + } } // Build doc with all invoices $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; $toselect = array(); - if (!$error && $validate_invoices) - { + if (!$error && $validate_invoices) { $massaction = $action = 'builddoc'; - foreach ($TAllFact as &$objecttmp) - { + foreach ($TAllFact as &$objecttmp) { $result = $objecttmp->validate($user); - if ($result <= 0) - { + if ($result <= 0) { $error++; setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); break; @@ -815,7 +840,7 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. // Call action to build doc $savobject = $object; - $object = $objecttmp; + $object = $objecttmp; include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; $object = $savobject; } @@ -823,8 +848,7 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $massaction = $action = 'confirm_createbills'; } - if (!$error) - { + if (!$error) { $db->commit(); if ($nb_bills_created == 1) { @@ -837,29 +861,75 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. // Make a redirect to avoid to bill twice if we make a refresh or back $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 ($socid > 0) $param .= '&socid='.urlencode($socid); - if ($search_status != '') $param .= '&search_status='.urlencode($search_status); - if ($search_orderday) $param .= '&search_orderday='.urlencode($search_orderday); - if ($search_ordermonth) $param .= '&search_ordermonth='.urlencode($search_ordermonth); - if ($search_orderyear) $param .= '&search_orderyear='.urlencode($search_orderyear); - if ($search_deliveryday) $param .= '&search_deliveryday='.urlencode($search_deliveryday); - if ($search_deliverymonth) $param .= '&search_deliverymonth='.urlencode($search_deliverymonth); - if ($search_deliveryyear) $param .= '&search_deliveryyear='.urlencode($search_deliveryyear); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_company) $param .= '&search_company='.urlencode($search_company); - if ($search_ref_customer) $param .= '&search_ref_customer='.urlencode($search_ref_customer); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); - if ($search_total_ht != '') $param .= '&search_total_ht='.urlencode($search_total_ht); - if ($search_total_vat != '') $param .= '&search_total_vat='.urlencode($search_total_vat); - if ($search_total_ttc != '') $param .= '&search_total_ttc='.urlencode($search_total_ttc); - if ($search_project_ref >= 0) $param .= "&search_project_ref=".urlencode($search_project_ref); - if ($show_files) $param .= '&show_files='.urlencode($show_files); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($billed != '') $param .= '&billed='.urlencode($billed); + 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 ($socid > 0) { + $param .= '&socid='.urlencode($socid); + } + if ($search_status != '') { + $param .= '&search_status='.urlencode($search_status); + } + if ($search_orderday) { + $param .= '&search_orderday='.urlencode($search_orderday); + } + if ($search_ordermonth) { + $param .= '&search_ordermonth='.urlencode($search_ordermonth); + } + if ($search_orderyear) { + $param .= '&search_orderyear='.urlencode($search_orderyear); + } + if ($search_deliveryday) { + $param .= '&search_deliveryday='.urlencode($search_deliveryday); + } + if ($search_deliverymonth) { + $param .= '&search_deliverymonth='.urlencode($search_deliverymonth); + } + if ($search_deliveryyear) { + $param .= '&search_deliveryyear='.urlencode($search_deliveryyear); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_company) { + $param .= '&search_company='.urlencode($search_company); + } + if ($search_ref_customer) { + $param .= '&search_ref_customer='.urlencode($search_ref_customer); + } + if ($search_user > 0) { + $param .= '&search_user='.urlencode($search_user); + } + if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); + } + if ($search_total_ht != '') { + $param .= '&search_total_ht='.urlencode($search_total_ht); + } + if ($search_total_vat != '') { + $param .= '&search_total_vat='.urlencode($search_total_vat); + } + if ($search_total_ttc != '') { + $param .= '&search_total_ttc='.urlencode($search_total_ttc); + } + if ($search_project_ref >= 0) { + $param .= "&search_project_ref=".urlencode($search_project_ref); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($billed != '') { + $param .= '&billed='.urlencode($billed); + } header("Location: ".$_SERVER['PHP_SELF'].'?'.$param); exit; @@ -873,22 +943,20 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. } } -if (!$error && $massaction == 'cancelorders') -{ +if (!$error && $massaction == 'cancelorders') { $db->begin(); $nbok = 0; $orders = GETPOST('toselect', 'array'); - foreach ($orders as $id_order) - { + foreach ($orders as $id_order) { $cmd = new Commande($db); - if ($cmd->fetch($id_order) <= 0) + if ($cmd->fetch($id_order) <= 0) { continue; + } - if ($cmd->statut != Commande::STATUS_VALIDATED) - { + if ($cmd->statut != Commande::STATUS_VALIDATED) { $langs->load('errors'); setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors'); $error++; @@ -898,18 +966,20 @@ if (!$error && $massaction == 'cancelorders') $result = $cmd->cancel(); } - if ($result < 0) - { + if ($result < 0) { setEventMessages($cmd->error, $cmd->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } - if (!$error) - { - if ($nbok > 1) + if (!$error) { + if ($nbok > 1) { setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -917,10 +987,8 @@ if (!$error && $massaction == 'cancelorders') } -if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) -{ - if (empty($diroutputmassaction)) - { +if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) { + if (empty($diroutputmassaction)) { dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined'); exit; } @@ -933,12 +1001,10 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto $listofobjectid = array(); $listofobjectthirdparties = array(); $listofobjectref = array(); - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $listofobjectid[$toselectid] = $toselectid; $thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid; $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid; @@ -947,19 +1013,20 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto } $arrayofinclusion = array(); - foreach ($listofobjectref as $tmppdf) $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$'; - foreach ($listofobjectref as $tmppdf) $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9-_]+\.pdf$'; // To include PDF generated from ODX files + foreach ($listofobjectref as $tmppdf) { + $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$'; + } + foreach ($listofobjectref as $tmppdf) { + $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9-_]+\.pdf$'; // To include PDF generated from ODX files + } $listoffiles = dol_dir_list($uploaddir, 'all', 1, implode('|', $arrayofinclusion), '\.meta$|\.png', 'date', SORT_DESC, 0, true); // build list of files with full path $files = array(); - foreach ($listofobjectref as $basename) - { + foreach ($listofobjectref as $basename) { $basename = dol_sanitizeFileName($basename); - foreach ($listoffiles as $filefound) - { - if (strstr($filefound["name"], $basename)) - { + foreach ($listoffiles as $filefound) { + if (strstr($filefound["name"], $basename)) { $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"]; break; } @@ -969,15 +1036,18 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto // Define output language (Here it is not used because we do only merging existing PDF) $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $objecttmp->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $objecttmp->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) - { + if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) { // Create output dir if not exists dol_mkdir($diroutputmassaction); @@ -986,16 +1056,21 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto $filename = preg_replace('/\s/', '_', $filename); // Save merged file - if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) - { - if ($option == 'late') $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); - else $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); + if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) { + if ($option == 'late') { + $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); + } else { + $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); + } + } + if ($year) { + $filename .= '_'.$year; + } + if ($month) { + $filename .= '_'.$month; } - if ($year) $filename .= '_'.$year; - if ($month) $filename .= '_'.$month; - if (count($files) > 0) - { + if (count($files) > 0) { $now = dol_now(); $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf'; @@ -1009,8 +1084,9 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto // check if pdftk is installed if (file_exists($file)) { - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); + } $langs->load("exports"); setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs'); @@ -1029,22 +1105,21 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto $pdf = pdf_getInstance($format); - if (class_exists('TCPDF')) - { + if (class_exists('TCPDF')) { $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); } $pdf->SetFont(pdf_getPDFFont($outputlangs)); - if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) { + $pdf->SetCompression(false); + } // Add all others - foreach ($files as $file) - { + foreach ($files as $file) { // Charge un document PDF depuis un fichier. $pagecount = $pdf->setSourceFile($file); - for ($i = 1; $i <= $pagecount; $i++) - { + for ($i = 1; $i <= $pagecount; $i++) { $tplidx = $pdf->importPage($i); $s = $pdf->getTemplatesize($tplidx); $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); @@ -1060,20 +1135,26 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto $filename = preg_replace('/\s/', '_', $filename); // Save merged file - if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) - { - if ($option == 'late') $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); - else $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); + if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) { + if ($option == 'late') { + $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); + } else { + $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); + } } - if ($year) $filename .= '_'.$year; - if ($month) $filename .= '_'.$month; - if ($pagecount) - { + if ($year) { + $filename .= '_'.$year; + } + if ($month) { + $filename .= '_'.$month; + } + if ($pagecount) { $now = dol_now(); $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf'; $pdf->Output($file, 'F'); - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); + } $langs->load("exports"); setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs'); @@ -1084,59 +1165,85 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto } // Remove a file from massaction area -if ($action == 'remove_file') -{ +if ($action == 'remove_file') { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $langs->load("other"); $upload_dir = $diroutputmassaction; $file = $upload_dir.'/'.GETPOST('file'); $ret = dol_delete_file($file); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + if ($ret) { + setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + } $action = ''; } + // Validate records -if (!$error && $massaction == 'validate' && $permissiontoadd) -{ +if (!$error && $massaction == 'validate' && $permissiontoadd) { $objecttmp = new $objectclass($db); - if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) - { + if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) { $langs->load("errors"); setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors'); $error++; } - if ($objecttmp->element == 'invoice_supplier' && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) - { + if ($objecttmp->element == 'invoice_supplier' && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) { $langs->load("errors"); setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $db->begin(); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $result = $objecttmp->validate($user); - if ($result == 0) - { + if ($result == 0) { $langs->load("errors"); setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors'); $error++; break; - } elseif ($result < 0) - { + } elseif ($result < 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + // validate() rename pdf but do not regenerate + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $objecttmp->thirdparty->default_lang; + } + if (!empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + $outputlangs->load('products'); + } + $model = $objecttmp->model_pdf; + $ret = $objecttmp->fetch($objecttmp->id); // Reload to get new records + // To be sure vars is defined + $hidedetails = !empty($hidedetails) ? $hidedetails : 0; + $hidedesc = !empty($hidedesc) ? $hidedesc : 0; + $hideref = !empty($hideref) ? $hideref : 0; + $moreparams = !empty($moreparams) ? $moreparams : null; + + $result = $objecttmp->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + } + } + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -1144,10 +1251,12 @@ if (!$error && $massaction == 'validate' && $permissiontoadd) } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -1170,7 +1279,9 @@ if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permissio setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -1179,9 +1290,11 @@ if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permissio } if (!$error) { - if ($nbok > 1) + if ($nbok > 1) { setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -1191,47 +1304,45 @@ if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permissio //var_dump($_POST);var_dump($massaction);exit; // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before) -if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) -{ +if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) { $db->begin(); $objecttmp = new $objectclass($db); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { // Refuse deletion for some objects/status - if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT) - { + if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT) { $langs->load("errors"); $nbignored++; $resaction .= '
    '.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'

    '; continue; } - if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) - { + if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) { $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".$objecttmp->id; $res = $db->query($sql); - if (!$res) - { + if (!$res) { setEventMessage('ErrorRecordParentingNotModified', 'errors'); $error++; } } - if (in_array($objecttmp->element, array('societe', 'member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1); - else $result = $objecttmp->delete($user); + if (in_array($objecttmp->element, array('societe', 'member'))) { + $result = $objecttmp->delete($objecttmp->id, $user, 1); + } else { + $result = $objecttmp->delete($user); + } - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -1239,10 +1350,12 @@ if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == ' } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -1252,43 +1365,54 @@ if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == ' // Generate document foreach object according to model linked to object // @todo : propose model selection -if (!$error && $massaction == 'generate_doc' && $permissiontoread) -{ +if (!$error && $massaction == 'generate_doc' && $permissiontoread) { $db->begin(); $objecttmp = new $objectclass($db); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ... - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang = $objecttmp->default_lang; // for thirdparty - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) { + $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ... + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) { + $newlang = $objecttmp->default_lang; // for thirdparty + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } // To be sure vars is defined - if (empty($hidedetails)) $hidedetails = 0; - if (empty($hidedesc)) $hidedesc = 0; - if (empty($hideref)) $hideref = 0; - if (empty($moreparams)) $moreparams = null; + if (empty($hidedetails)) { + $hidedetails = 0; + } + if (empty($hidedesc)) { + $hidedesc = 0; + } + if (empty($hideref)) { + $hideref = 0; + } + if (empty($moreparams)) { + $moreparams = null; + } $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -1296,10 +1420,12 @@ if (!$error && $massaction == 'generate_doc' && $permissiontoread) } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -1353,10 +1479,12 @@ if (!$error && ($action == 'affecttag' && $confirm == 'yes') && $permissiontoadd } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null); - else setEventMessages($langs->trans("RecordsModified", $nbok), null); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsModified", $nbok), null); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null); + } $db->commit(); $toselect=array(); } else { @@ -1370,4 +1498,6 @@ $parameters['massaction'] = $massaction; $parameters['diroutputmassaction'] = $diroutputmassaction; $reshook = $hookmanager->executeHooks('doMassActions', $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'); +} diff --git a/htdocs/core/actions_printing.inc.php b/htdocs/core/actions_printing.inc.php index 3838e6963ab..de415bb4ba3 100644 --- a/htdocs/core/actions_printing.inc.php +++ b/htdocs/core/actions_printing.inc.php @@ -55,16 +55,15 @@ if ($action == 'print_file' && $user->rights->printing->read) { $subdir = ''; $module = GETPOST('printer', 'alpha'); - switch ($module) - { - case 'livraison' : + switch ($module) { + case 'livraison': $subdir = 'receipt'; $module = 'expedition'; break; - case 'expedition' : + case 'expedition': $subdir = 'sending'; break; - case 'commande_fournisseur' : + case 'commande_fournisseur': $module = 'fournisseur'; $subdir = 'commande'; break; @@ -75,20 +74,20 @@ if ($action == 'print_file' && $user->rights->printing->read) { //print '
    '.print_r($printer->errors, true).'
    '; setEventMessages($printer->error, $printer->errors, 'errors'); } - if ($ret == 0) - { + if ($ret == 0) { //print '
    '.print_r($printer->errors, true).'
    '; setEventMessages($printer->error, $printer->errors); setEventMessages($langs->transnoentitiesnoconv("FileWasSentToPrinter", basename(GETPOST('file', 'alpha'))).' '.$langs->transnoentitiesnoconv("ViaModule").' '.$printer->name, null); } - } catch (Exception $e) - { + } catch (Exception $e) { $ret = 1; setEventMessages($e->getMessage(), null, 'errors'); } } } - if ($printerfound == 0) setEventMessages($langs->trans("NoActivePrintingModuleFound", $langs->transnoentities("Module64000Name")), null, 'warnings'); + if ($printerfound == 0) { + setEventMessages($langs->trans("NoActivePrintingModuleFound", $langs->transnoentities("Module64000Name")), null, 'warnings'); + } } else { setEventMessages($langs->trans("NoModuleFound"), null, 'warnings'); } diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index 1bea255bda2..d05985b1aa3 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -108,7 +108,9 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST $trackid = GETPOST('trackid', 'aZ09'); } - $subject = ''; $actionmsg = ''; $actionmsg2 = ''; + $subject = ''; + $actionmsg = ''; + $actionmsg2 = ''; $langs->load('mails'); diff --git a/htdocs/core/actions_setmoduleoptions.inc.php b/htdocs/core/actions_setmoduleoptions.inc.php index d662d3c85c9..5f0d6823978 100644 --- a/htdocs/core/actions_setmoduleoptions.inc.php +++ b/htdocs/core/actions_setmoduleoptions.inc.php @@ -27,93 +27,91 @@ // $nomessageinupdate can be set to 1 // $nomessageinsetmoduleoptions can be set to 1 -if ($action == 'update' && is_array($arrayofparameters)) -{ +if ($action == 'update' && is_array($arrayofparameters)) { $db->begin(); - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { // Modify constant only if key was posted (avoid resetting key to the null value) - if (GETPOSTISSET($key)) - { + if (GETPOSTISSET($key)) { $result = dolibarr_set_const($db, $key, GETPOST($key, 'alpha'), 'chaine', 0, '', $conf->entity); - if ($result < 0) - { + if ($result < 0) { $error++; break; } } } - if (!$error) - { + if (!$error) { $db->commit(); - if (empty($nomessageinupdate)) setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + if (empty($nomessageinupdate)) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } } else { $db->rollback(); - if (empty($nomessageinupdate)) setEventMessages($langs->trans("SetupNotSaved"), null, 'errors'); + if (empty($nomessageinupdate)) { + setEventMessages($langs->trans("SetupNotSaved"), null, 'errors'); + } } } // Define constants for submodules that contains parameters (forms with param1, param2, ... and value1, value2, ...) -if ($action == 'setModuleOptions') -{ +if ($action == 'setModuleOptions') { $db->begin(); // Process common param fields - if (is_array($_POST)) - { - foreach ($_POST as $key => $val) - { + if (is_array($_POST)) { + foreach ($_POST as $key => $val) { $reg = array(); - if (preg_match('/^param(\d*)$/', $key, $reg)) // Works for POST['param'], POST['param1'], POST['param2'], ... - { + if (preg_match('/^param(\d*)$/', $key, $reg)) { // Works for POST['param'], POST['param1'], POST['param2'], ... $param = GETPOST("param".$reg[1], 'alpha'); $value = GETPOST("value".$reg[1], 'alpha'); - if ($param) - { + if ($param) { $res = dolibarr_set_const($db, $param, $value, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } } } } } // Process upload fields - if (GETPOST('upload', 'alpha') && GETPOST('keyforuploaddir', 'aZ09')) - { + if (GETPOST('upload', 'alpha') && GETPOST('keyforuploaddir', 'aZ09')) { include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $keyforuploaddir = GETPOST('keyforuploaddir', 'aZ09'); $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->$keyforuploaddir))); - foreach ($listofdir as $key=>$tmpdir) - { + foreach ($listofdir as $key => $tmpdir) { $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)) { if (empty($nomessageinsetmoduleoptions)) { setEventMessages($langs->trans("ErrorDirNotFound", $tmpdir), null, 'warnings'); } - } - else { + } else { $upload_dir = $tmpdir; } } - if ($upload_dir) - { + if ($upload_dir) { $result = dol_add_file_process($upload_dir, 1, 1, 'uploadfile', ''); - if ($result <= 0) $error++; + if ($result <= 0) { + $error++; + } } } - if (!$error) - { + if (!$error) { $db->commit(); - if (empty($nomessageinsetmoduleoptions)) setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + if (empty($nomessageinsetmoduleoptions)) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } } else { $db->rollback(); - if (empty($nomessageinsetmoduleoptions)) setEventMessages($langs->trans("SetupNotSaved"), null, 'errors'); + if (empty($nomessageinsetmoduleoptions)) { + setEventMessages($langs->trans("SetupNotSaved"), null, 'errors'); + } } } diff --git a/htdocs/core/actions_setnotes.inc.php b/htdocs/core/actions_setnotes.inc.php index b9dd4194268..f2426f6523f 100644 --- a/htdocs/core/actions_setnotes.inc.php +++ b/htdocs/core/actions_setnotes.inc.php @@ -28,23 +28,29 @@ // $id must be defined (object is loaded in this file with fetch) // Set public note -if ($action == 'setnote_public' && !empty($permissionnote) && !GETPOST('cancel', 'alpha')) -{ - if (empty($action) || !is_object($object) || empty($id)) dol_print_error('', 'Include of actions_setnotes.inc.php was done but required variable was not set before'); - if (empty($object->id)) $object->fetch($id); // Fetch may not be already done +if ($action == 'setnote_public' && !empty($permissionnote) && !GETPOST('cancel', 'alpha')) { + if (empty($action) || !is_object($object) || empty($id)) { + dol_print_error('', 'Include of actions_setnotes.inc.php was done but required variable was not set before'); + } + if (empty($object->id)) { + $object->fetch($id); // Fetch may not be already done + } $result_update = $object->update_note(dol_html_entity_decode(GETPOST('note_public', 'restricthtml'), ENT_QUOTES | ENT_HTML5, 'UTF-8', 1), '_public'); - if ($result_update < 0) setEventMessages($object->error, $object->errors, 'errors'); - elseif (in_array($object->table_element, array('supplier_proposal', 'propal', 'commande_fournisseur', 'commande', 'facture_fourn', 'facture'))) - { + if ($result_update < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } elseif (in_array($object->table_element, array('supplier_proposal', 'propal', 'commande_fournisseur', 'commande', 'facture_fourn', 'facture'))) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -56,13 +62,21 @@ if ($action == 'setnote_public' && !empty($permissionnote) && !GETPOST('cancel', $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } } } elseif ($action == 'setnote_private' && !empty($permissionnote) && !GETPOST('cancel', 'alpha')) { // Set public note - if (empty($action) || !is_object($object) || empty($id)) dol_print_error('', 'Include of actions_setnotes.inc.php was done but required variable was not set before'); - if (empty($object->id)) $object->fetch($id); // Fetch may not be already done + if (empty($action) || !is_object($object) || empty($id)) { + dol_print_error('', 'Include of actions_setnotes.inc.php was done but required variable was not set before'); + } + if (empty($object->id)) { + $object->fetch($id); // Fetch may not be already done + } $result = $object->update_note(dol_html_entity_decode(GETPOST('note_private', 'restricthtml'), ENT_QUOTES | ENT_HTML5), '_private'); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } diff --git a/htdocs/core/ajax/ajaxdirpreview.php b/htdocs/core/ajax/ajaxdirpreview.php index 9575208f485..cf619f70de6 100644 --- a/htdocs/core/ajax/ajaxdirpreview.php +++ b/htdocs/core/ajax/ajaxdirpreview.php @@ -27,13 +27,20 @@ * ajaxdirpreview.php?mode=nojs&action=preview&module=ecm§ion=0&file=xxx */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} -if (!isset($mode) || $mode != 'noajax') // For ajax call -{ +if (!isset($mode) || $mode != 'noajax') { // For ajax call require_once '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; @@ -50,12 +57,18 @@ if (!isset($mode) || $mode != 'noajax') // For ajax call $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"; + } $rootdirfordoc = $conf->ecm->dir_output; @@ -64,8 +77,7 @@ if (!isset($mode) || $mode != 'noajax') // For ajax call $ecmdir = new EcmDirectory($db); if ($section > 0) { $result = $ecmdir->fetch($section); - if (!$result > 0) - { + if (!$result > 0) { //dol_print_error($db,$ecmdir->error); //exit; } @@ -76,18 +88,15 @@ if (!isset($mode) || $mode != 'noajax') // For ajax call $ecmdir = new EcmDirectory($db); $relativepath = ''; - if ($section > 0) - { + if ($section > 0) { $result = $ecmdir->fetch($section); - if (!$result > 0) - { + if (!$result > 0) { dol_print_error($db, $ecmdir->error); exit; } $relativepath = $ecmdir->getRelativePath(); // Example 'mydir/' - } elseif (GETPOST('section_dir')) - { + } elseif (GETPOST('section_dir')) { $relativepath = GETPOST('section_dir'); } //var_dump($section.'-'.GETPOST('section_dir').'-'.$relativepath); @@ -95,24 +104,27 @@ if (!isset($mode) || $mode != 'noajax') // For ajax call $upload_dir = $rootdirfordoc.'/'.$relativepath; } -if (empty($url)) -{ - if (GETPOSTISSET('website')) $url = DOL_URL_ROOT.'/website/index.php'; - else $url = DOL_URL_ROOT.'/ecm/index.php'; +if (empty($url)) { + if (GETPOSTISSET('website')) { + $url = DOL_URL_ROOT.'/website/index.php'; + } else { + $url = DOL_URL_ROOT.'/ecm/index.php'; + } } // Load translation files required by the page $langs->loadLangs(array("ecm", "companies", "other")); // Security check -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} //print 'xxx'.$upload_dir; // Security: // On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers. -if (preg_match('/\.\./', $upload_dir) || preg_match('/[<>|]/', $upload_dir)) -{ +if (preg_match('/\.\./', $upload_dir) || preg_match('/[<>|]/', $upload_dir)) { dol_syslog("Refused to deliver file ".$upload_dir); // Do no show plain path in shown error message dol_print_error(0, $langs->trans("ErrorFileNameInvalid", $upload_dir)); @@ -120,12 +132,12 @@ if (preg_match('/\.\./', $upload_dir) || preg_match('/[<>|]/', $upload_dir)) } // Check permissions -if ($modulepart == 'ecm') -{ - if (!$user->rights->ecm->read) accessforbidden(); +if ($modulepart == 'ecm') { + if (!$user->rights->ecm->read) { + accessforbidden(); + } } -if ($modulepart == 'medias') -{ +if ($modulepart == 'medias') { // Always allowed } @@ -142,8 +154,7 @@ if ($modulepart == 'medias') * View */ -if (!isset($mode) || $mode != 'noajax') -{ +if (!isset($mode) || $mode != 'noajax') { // Ajout directives pour resoudre bug IE header('Cache-Control: Public, must-revalidate'); header('Pragma: public'); @@ -154,25 +165,27 @@ if (!isset($mode) || $mode != 'noajax') $type = 'directory'; // This test if file exists should be useless. We keep it to find bug more easily -if (!dol_is_dir($upload_dir)) -{ +if (!dol_is_dir($upload_dir)) { //dol_mkdir($upload_dir); /*$langs->load("install"); - dol_print_error(0,$langs->trans("ErrorDirDoesNotExists",$upload_dir)); - exit;*/ + dol_print_error(0,$langs->trans("ErrorDirDoesNotExists",$upload_dir)); + exit;*/ } print ''."\n"; //print ''."\n"; $param = ($sortfield ? '&sortfield='.urlencode($sortfield) : '').($sortorder ? '&sortorder='.urlencode($sortorder) : ''); -if (!empty($websitekey)) $param .= '&website='.urlencode($websitekey); -if (!empty($pageid)) $param .= '&pageid='.urlencode($pageid); +if (!empty($websitekey)) { + $param .= '&website='.urlencode($websitekey); +} +if (!empty($pageid)) { + $param .= '&pageid='.urlencode($pageid); +} // Dir scan -if ($type == 'directory') -{ +if ($type == 'directory') { $formfile = new FormFile($db); $maxlengthname = 40; @@ -203,31 +216,48 @@ if ($type == 'directory') $parameters = array('modulepart'=>$module); $reshook = $hookmanager->executeHooks('addSectionECMAuto', $parameters); - if ($reshook > 0 && is_array($hookmanager->resArray) && count($hookmanager->resArray)>0) - { + if ($reshook > 0 && is_array($hookmanager->resArray) && count($hookmanager->resArray)>0) { $automodules[]=$hookmanager->resArray['module']; } // TODO change for multicompany sharing - if ($module == 'company') $upload_dir = $conf->societe->dir_output; - elseif ($module == 'invoice') $upload_dir = $conf->facture->dir_output; - elseif ($module == 'invoice_supplier') $upload_dir = $conf->fournisseur->facture->dir_output; - elseif ($module == 'propal') $upload_dir = $conf->propal->dir_output; - elseif ($module == 'supplier_proposal') $upload_dir = $conf->supplier_proposal->dir_output; - elseif ($module == 'order') $upload_dir = $conf->commande->dir_output; - elseif ($module == 'order_supplier') $upload_dir = $conf->fournisseur->commande->dir_output; - elseif ($module == 'contract') $upload_dir = $conf->contrat->dir_output; - elseif ($module == 'product') $upload_dir = $conf->product->dir_output; - elseif ($module == 'tax') $upload_dir = $conf->tax->dir_output; - elseif ($module == 'project') $upload_dir = $conf->projet->dir_output; - elseif ($module == 'fichinter') $upload_dir = $conf->ficheinter->dir_output; - elseif ($module == 'user') $upload_dir = $conf->user->dir_output; - elseif ($module == 'expensereport') $upload_dir = $conf->expensereport->dir_output; - elseif ($module == 'holiday') $upload_dir = $conf->holiday->dir_output; - elseif ($module == 'recruitment-recruitmentcandidature') $upload_dir = $conf->recruitment->dir_output.'/recruitmentcandidature'; - elseif ($module == 'banque') $upload_dir = $conf->bank->dir_output; - elseif ($module == 'mrp-mo') $upload_dir = $conf->mrp->dir_output.'/mo'; - else { + if ($module == 'company') { + $upload_dir = $conf->societe->dir_output; + } elseif ($module == 'invoice') { + $upload_dir = $conf->facture->dir_output; + } elseif ($module == 'invoice_supplier') { + $upload_dir = $conf->fournisseur->facture->dir_output; + } elseif ($module == 'propal') { + $upload_dir = $conf->propal->dir_output; + } elseif ($module == 'supplier_proposal') { + $upload_dir = $conf->supplier_proposal->dir_output; + } elseif ($module == 'order') { + $upload_dir = $conf->commande->dir_output; + } elseif ($module == 'order_supplier') { + $upload_dir = $conf->fournisseur->commande->dir_output; + } elseif ($module == 'contract') { + $upload_dir = $conf->contrat->dir_output; + } elseif ($module == 'product') { + $upload_dir = $conf->product->dir_output; + } elseif ($module == 'tax') { + $upload_dir = $conf->tax->dir_output; + } elseif ($module == 'project') { + $upload_dir = $conf->projet->dir_output; + } elseif ($module == 'fichinter') { + $upload_dir = $conf->ficheinter->dir_output; + } elseif ($module == 'user') { + $upload_dir = $conf->user->dir_output; + } elseif ($module == 'expensereport') { + $upload_dir = $conf->expensereport->dir_output; + } elseif ($module == 'holiday') { + $upload_dir = $conf->holiday->dir_output; + } elseif ($module == 'recruitment-recruitmentcandidature') { + $upload_dir = $conf->recruitment->dir_output.'/recruitmentcandidature'; + } elseif ($module == 'banque') { + $upload_dir = $conf->bank->dir_output; + } elseif ($module == 'mrp-mo') { + $upload_dir = $conf->mrp->dir_output.'/mo'; + } else { $parameters = array('modulepart'=>$module); $reshook = $hookmanager->executeHooks('addSectionECMAuto', $parameters); if ($reshook > 0 && is_array($hookmanager->resArray) && count($hookmanager->resArray) > 0) { @@ -236,14 +266,17 @@ if ($type == 'directory') } // Automatic list - if (in_array($module, $automodules)) - { + if (in_array($module, $automodules)) { $param .= '&module='.$module; - if (isset($search_doc_ref) && $search_doc_ref != '') $param .= '&search_doc_ref='.urlencode($search_doc_ref); + if (isset($search_doc_ref) && $search_doc_ref != '') { + $param .= '&search_doc_ref='.urlencode($search_doc_ref); + } $textifempty = ($section ? $langs->trans("NoFileFound") : ($showonrightsize == 'featurenotyetavailable' ? $langs->trans("FeatureNotYetAvailable") : $langs->trans("NoFileFound"))); - if ($module == 'company') $excludefiles[] = '^contact$'; // The subdir 'contact' contains files of contacts with no id of thirdparty. + if ($module == 'company') { + $excludefiles[] = '^contact$'; // The subdir 'contact' contains files of contacts with no id of thirdparty. + } $filter = preg_quote($search_doc_ref, '/'); $filearray = dol_dir_list($upload_dir, "files", 1, $filter, $excludefiles, $sortfield, $sorting, 1); @@ -251,14 +284,12 @@ if ($type == 'directory') $perm = $user->rights->ecm->upload; $formfile->list_of_autoecmfiles($upload_dir, $filearray, $module, $param, 1, '', $perm, 1, $textifempty, $maxlengthname, $url, 1); - } - // Manual list - else { - if ($module == 'medias') - { + } else { + // Manual list + if ($module == 'medias') { /* - $_POST is array like - 'token' => string '062380e11b7dcd009d07318b57b71750' (length=32) + $_POST is array like + 'token' => string '062380e11b7dcd009d07318b57b71750' (length=32) 'action' => string 'file_manager' (length=12) 'website' => string 'template' (length=8) 'pageid' => string '124' (length=3) @@ -266,15 +297,20 @@ if ($type == 'directory') 'section_id' => string '0' (length=1) 'max_file_size' => string '2097152' (length=7) 'sendit' => string 'Envoyer fichier' (length=15) - */ + */ $relativepath = GETPOST('file', 'alpha') ?GETPOST('file', 'alpha') : GETPOST('section_dir', 'alpha'); - if ($relativepath && $relativepath != '/') $relativepath .= '/'; + if ($relativepath && $relativepath != '/') { + $relativepath .= '/'; + } $upload_dir = $dolibarr_main_data_root.'/'.$module.'/'.$relativepath; - if (GETPOSTISSET('website') || GETPOSTISSET('file_manager')) - { + if (GETPOSTISSET('website') || GETPOSTISSET('file_manager')) { $param .= '&file_manager=1'; - if (!preg_match('/website=/', $param)) $param .= '&website='.urlencode(GETPOST('website', 'alpha')); - if (!preg_match('/pageid=/', $param)) $param .= '&pageid='.urlencode(GETPOST('pageid', 'int')); + if (!preg_match('/website=/', $param)) { + $param .= '&website='.urlencode(GETPOST('website', 'alpha')); + } + if (!preg_match('/pageid=/', $param)) { + $param .= '&pageid='.urlencode(GETPOST('pageid', 'int')); + } //if (!preg_match('/backtopage=/',$param)) $param.='&backtopage='.urlencode($_SERVER["PHP_SELF"].'?file_manager=1&website='.$websitekey.'&pageid='.$pageid); } } else { @@ -283,47 +319,46 @@ if ($type == 'directory') } // If $section defined with value 0 - if (($section === '0' || empty($section)) && ($module != 'medias')) - { + if (($section === '0' || empty($section)) && ($module != 'medias')) { $filearray = array(); } else { $filearray = dol_dir_list($upload_dir, "files", 0, '', array('^\.', '(\.meta|_preview.*\.png)$', '^temp$', '^CVS$'), $sortfield, $sorting, 1); } - if ($section) - { + if ($section) { $param .= '§ion='.$section; - if (isset($search_doc_ref) && $search_doc_ref != '') $param .= '&search_doc_ref='.$search_doc_ref; + if (isset($search_doc_ref) && $search_doc_ref != '') { + $param .= '&search_doc_ref='.$search_doc_ref; + } $textifempty = $langs->trans('NoFileFound'); - } elseif ($section === '0') - { - if ($module == 'ecm') $textifempty = '
    '.$langs->trans("DirNotSynchronizedSyncFirst").'

    '; - else $textifempty = $langs->trans('NoFileFound'); - } else $textifempty = ($showonrightsize == 'featurenotyetavailable' ? $langs->trans("FeatureNotYetAvailable") : $langs->trans("ECMSelectASection")); + } elseif ($section === '0') { + if ($module == 'ecm') { + $textifempty = '
    '.$langs->trans("DirNotSynchronizedSyncFirst").'

    '; + } else { + $textifempty = $langs->trans('NoFileFound'); + } + } else { + $textifempty = ($showonrightsize == 'featurenotyetavailable' ? $langs->trans("FeatureNotYetAvailable") : $langs->trans("ECMSelectASection")); + } - if ($module == 'medias') - { + if ($module == 'medias') { $useinecm = 6; $modulepart = 'medias'; $perm = ($user->rights->website->write || $user->rights->emailing->creer); $title = 'none'; - } elseif ($module == 'ecm') // DMS/ECM -> manual structure - { - if ($user->rights->ecm->read) - { + } elseif ($module == 'ecm') { // DMS/ECM -> manual structure + if ($user->rights->ecm->read) { // Buttons: Preview $useinecm = 2; } - if ($user->rights->ecm->upload) - { + if ($user->rights->ecm->upload) { // Buttons: Preview + Delete $useinecm = 4; } - if ($user->rights->ecm->setup) - { + if ($user->rights->ecm->setup) { // Buttons: Preview + Delete + Edit $useinecm = 5; } @@ -349,18 +384,27 @@ if ($type == 'directory') // Bottom of page $useajax = 1; -if (!empty($conf->dol_use_jmobile)) $useajax = 0; -if (empty($conf->use_javascript_ajax)) $useajax = 0; -if (!empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax = 0; +if (!empty($conf->dol_use_jmobile)) { + $useajax = 0; +} +if (empty($conf->use_javascript_ajax)) { + $useajax = 0; +} +if (!empty($conf->global->MAIN_ECM_DISABLE_JS)) { + $useajax = 0; +} //$param.=($param?'?':'').(preg_replace('/^&/','',$param)); -if ($useajax || $action == 'delete') -{ +if ($useajax || $action == 'delete') { $urlfile = ''; - if ($action == 'delete') $urlfile = GETPOST('urlfile', 'alpha'); + if ($action == 'delete') { + $urlfile = GETPOST('urlfile', 'alpha'); + } - if (empty($section_dir)) $section_dir = GETPOST("file", "alpha"); + if (empty($section_dir)) { + $section_dir = GETPOST("file", "alpha"); + } $section_id = $section; require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; @@ -372,22 +416,26 @@ if ($useajax || $action == 'delete') $formquestion['section_dir'] = array('type'=>'hidden', 'value'=>$section_dir, 'name'=>'section_dir'); // We must always put field, even if empty because it is filled by javascript later $formquestion['sortfield'] = array('type'=>'hidden', 'value'=>$sortfield, 'name'=>'sortfield'); // We must always put field, even if empty because it is filled by javascript later $formquestion['sortorder'] = array('type'=>'hidden', 'value'=>$sortorder, 'name'=>'sortorder'); // We must always put field, even if empty because it is filled by javascript later - if (!empty($action) && $action == 'file_manager') $formquestion['file_manager'] = array('type'=>'hidden', 'value'=>1, 'name'=>'file_manager'); - if (!empty($websitekey)) $formquestion['website'] = array('type'=>'hidden', 'value'=>$websitekey, 'name'=>'website'); - if (!empty($pageid) && $pageid > 0) $formquestion['pageid'] = array('type'=>'hidden', 'value'=>$pageid, 'name'=>'pageid'); + if (!empty($action) && $action == 'file_manager') { + $formquestion['file_manager'] = array('type'=>'hidden', 'value'=>1, 'name'=>'file_manager'); + } + if (!empty($websitekey)) { + $formquestion['website'] = array('type'=>'hidden', 'value'=>$websitekey, 'name'=>'website'); + } + if (!empty($pageid) && $pageid > 0) { + $formquestion['pageid'] = array('type'=>'hidden', 'value'=>$pageid, 'name'=>'pageid'); + } print $form->formconfirm($url, $langs->trans("DeleteFile"), $langs->trans("ConfirmDeleteFile"), 'confirm_deletefile', $formquestion, "no", ($useajax ? 'deletefile' : 0)); } -if ($useajax) -{ +if ($useajax) { print ''; + $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 9f0f5ece978..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 @@ -75,7 +77,9 @@ class box_graph_orders_permonth extends ModeleBoxes //$commandestatic=new Commande($this->db); $startmonth = $conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1; - if (empty($conf->global->GRAPH_USE_FISCAL_YEAR)) $startmonth = 1; + if (empty($conf->global->GRAPH_USE_FISCAL_YEAR)) { + $startmonth = 1; + } $text = $langs->trans("BoxCustomersOrdersPerMonth", $max); $this->info_box_head = array( @@ -92,11 +96,14 @@ class box_graph_orders_permonth extends ModeleBoxes $dir = ''; // We don't need a path because image file will not be saved into disk $prefix = ''; $socid = 0; - if ($user->socid) $socid = $user->socid; - if (!$user->rights->societe->client->voir || $socid) $prefix .= 'private-'.$user->id.'-'; // If user has no permission to see all, output dir is specific to user + if ($user->socid) { + $socid = $user->socid; + } + if (!$user->rights->societe->client->voir || $socid) { + $prefix .= 'private-'.$user->id.'-'; // If user has no permission to see all, output dir is specific to user + } - if ($user->rights->commande->lire) - { + if ($user->rights->commande->lire) { $langs->load("orders"); $param_year = 'DOLUSERCOOKIE_box_'.$this->boxcode.'_year'; @@ -106,21 +113,25 @@ class box_graph_orders_permonth extends ModeleBoxes include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; include_once DOL_DOCUMENT_ROOT.'/commande/class/commandestats.class.php'; $autosetarray = preg_split("/[,;:]+/", GETPOST('DOL_AUTOSET_COOKIE')); - if (in_array('DOLUSERCOOKIE_box_'.$this->boxcode, $autosetarray)) - { + if (in_array('DOLUSERCOOKIE_box_'.$this->boxcode, $autosetarray)) { $endyear = GETPOST($param_year, 'int'); $shownb = GETPOST($param_shownb, 'alpha'); $showtot = GETPOST($param_showtot, 'alpha'); } else { - $tmparray = (!empty($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode]) ? json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true) : array()); - $endyear = (!empty($tmparray['year']) ? $tmparray['year'] : ''); - $shownb = (!empty($tmparray['shownb']) ? $tmparray['shownb'] : ''); - $showtot = (!empty($tmparray['showtot']) ? $tmparray['showtot'] : ''); + $tmparray = (!empty($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode]) ? json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true) : array()); + $endyear = (!empty($tmparray['year']) ? $tmparray['year'] : ''); + $shownb = (!empty($tmparray['shownb']) ? $tmparray['shownb'] : ''); + $showtot = (!empty($tmparray['showtot']) ? $tmparray['showtot'] : ''); + } + if (empty($shownb) && empty($showtot)) { + $shownb = 1; + $showtot = 1; } - if (empty($shownb) && empty($showtot)) { $shownb = 1; $showtot = 1; } $nowarray = dol_getdate(dol_now(), true); - if (empty($endyear)) $endyear = $nowarray['year']; - $startyear = $endyear - (empty($conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH) ? 1 : $conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH); + if (empty($endyear)) { + $endyear = $nowarray['year']; + } + $startyear = $endyear - (empty($conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH) ? 2 : ($conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH - 1)); $mode = 'customer'; $WIDTH = (($shownb && $showtot) || !empty($conf->dol_optimize_smallscreen)) ? '256' : '320'; @@ -129,27 +140,25 @@ class box_graph_orders_permonth extends ModeleBoxes $stats = new CommandeStats($this->db, $socid, $mode, 0); // Build graphic number of object. $data = array(array('Lib',val1,val2,val3),...) - if ($shownb) - { + if ($shownb) { $data1 = $stats->getNbByMonthWithPrevYear($endyear, $startyear, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24)), ($WIDTH < 300 ? 2 : 0), $startmonth); $filenamenb = $dir."/".$prefix."ordersnbinyear-".$endyear.".png"; // default value for customer mode $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersnbinyear-'.$endyear.'.png'; - if ($mode == 'supplier') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersnbinyear-'.$endyear.'.png'; + if ($mode == 'supplier') { + $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersnbinyear-'.$endyear.'.png'; + } $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); - if (!$mesg) - { + if (!$mesg) { $px1->SetData($data1); unset($data1); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { - if ($startmonth != 1) - { + while ($i <= $endyear) { + if ($startmonth != 1) { $legend[] = sprintf("%d/%d", $i - 2001, $i - 2000); } else { $legend[] = $i; @@ -172,26 +181,25 @@ class box_graph_orders_permonth extends ModeleBoxes } // Build graphic number of object. $data = array(array('Lib',val1,val2,val3),...) - if ($showtot) - { + if ($showtot) { $data2 = $stats->getAmountByMonthWithPrevYear($endyear, $startyear, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24)), ($WIDTH < 300 ? 2 : 0), $startmonth); $filenamenb = $dir."/".$prefix."ordersamountinyear-".$endyear.".png"; // default value for customer mode $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersamountinyear-'.$endyear.'.png'; - if ($mode == 'supplier') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersamountinyear-'.$endyear.'.png'; + if ($mode == 'supplier') { + $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersamountinyear-'.$endyear.'.png'; + } $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); - if (!$mesg) - { + if (!$mesg) { $px2->SetData($data2); unset($data2); - $i = $startyear; $legend = array(); - while ($i <= $endyear) - { - if ($startmonth != 1) - { + $i = $startyear; + $legend = array(); + while ($i <= $endyear) { + if ($startmonth != 1) { $legend[] = sprintf("%d/%d", $i - 2001, $i - 2000); } else { $legend[] = $i; @@ -213,14 +221,12 @@ class box_graph_orders_permonth extends ModeleBoxes } } - if (empty($conf->use_javascript_ajax)) - { + if (empty($conf->use_javascript_ajax)) { $langs->load("errors"); $mesg = $langs->trans("WarningFeatureDisabledWithDisplayOptimizedForBlindNoJs"); } - if (!$mesg) - { + if (!$mesg) { $stringtoshow = ''; $stringtoshow .= ''."\n"; - } - - $out .= ' '."\n"; - } - } - - $out .= $hookmanager->resPrint; - return $out; } - /** * Returns the rights used for this class * @return stdClass @@ -7209,7 +7620,9 @@ abstract class CommonObject global $user; $element = $this->element; - if ($element == 'facturerec') $element = 'facture'; + if ($element == 'facturerec') { + $element = 'facture'; + } return $user->rights->{$element}; } @@ -7228,13 +7641,13 @@ abstract class CommonObject */ public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0) { - foreach ($tables as $table) - { + foreach ($tables as $table) { $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id; - if (!$db->query($sql)) - { - if ($ignoreerrors) return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B. + if (!$db->query($sql)) { + if ($ignoreerrors) { + return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B. + } //$this->errors = $db->lasterror(); return false; } @@ -7261,55 +7674,43 @@ abstract class CommonObject $buyPrice = 0; - if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false - { + if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) { // In most cases, test here is false $buyPrice = $unitPrice * (1 - $discountPercent / 100); } else { // Get cost price for margin calculation - if (!empty($fk_product)) - { - if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') - { + if (!empty($fk_product)) { + if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $product = new Product($this->db); $result = $product->fetch($fk_product); - if ($result <= 0) - { + if ($result <= 0) { $this->errors[] = 'ErrorProductIdDoesNotExists'; return -1; } - if ($product->cost_price > 0) - { + if ($product->cost_price > 0) { $buyPrice = $product->cost_price; - } elseif ($product->pmp > 0) - { + } elseif ($product->pmp > 0) { $buyPrice = $product->pmp; } - } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') - { + } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $product = new Product($this->db); $result = $product->fetch($fk_product); - if ($result <= 0) - { + if ($result <= 0) { $this->errors[] = 'ErrorProductIdDoesNotExists'; return -1; } - if ($product->pmp > 0) - { + if ($product->pmp > 0) { $buyPrice = $product->pmp; } } - if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) - { + if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $productFournisseur = new ProductFournisseur($this->db); - if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) - { + if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) { $buyPrice = $productFournisseur->fourn_unitprice; - } elseif ($result < 0) - { + } elseif ($result < 0) { $this->errors[] = $productFournisseur->error; return -2; } @@ -7406,34 +7807,45 @@ abstract class CommonObject if ($size == 1 || $size == 'small') { // Format vignette // Find name of thumb file $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small')); - if (!dol_is_file($dirthumb.$photo_vignette)) $photo_vignette = ''; + if (!dol_is_file($dirthumb.$photo_vignette)) { + $photo_vignette = ''; + } // Get filesize of original file $imgarray = dol_getImageSize($dir.$photo); - if ($nbbyrow > 0) - { - if ($nbphoto == 1) $return .= ''; + if ($nbbyrow > 0) { + if ($nbphoto == 1) { + $return .= '
    '; + } - if ($nbphoto % $nbbyrow == 1) $return .= ''; + if ($nbphoto % $nbbyrow == 1) { + $return .= ''; + } $return .= ''; - if (($nbphoto % $nbbyrow) == 0) $return .= ''; - } elseif ($nbbyrow < 0) $return .= ''; + if (($nbphoto % $nbbyrow) == 0) { + $return .= ''; + } + } elseif ($nbbyrow < 0) { + $return .= ''; + } } if (empty($size)) { // Format origine $return .= ''; - if ($showfilename) $return .= '
    '.$viewfilename; - if ($showaction) - { + if ($showfilename) { + $return .= '
    '.$viewfilename; + } + if ($showaction) { // Special case for product - if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) - { + if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) { // Link to resize $return .= ''.img_picto($langs->trans("Resize"), 'resize', '').'   '; @@ -7510,22 +7926,23 @@ abstract class CommonObject } // On continue ou on arrete de boucler ? - if ($nbmax && $nbphoto >= $nbmax) break; + if ($nbmax && $nbphoto >= $nbmax) { + break; + } } } - if ($size == 1 || $size == 'small') - { - if ($nbbyrow > 0) - { + if ($size == 1 || $size == 'small') { + if ($nbbyrow > 0) { // Ferme tableau - while ($nbphoto % $nbbyrow) - { + while ($nbphoto % $nbbyrow) { $return .= ''; $nbphoto++; } - if ($nbphoto) $return .= '
    '; - } elseif ($nbbyrow < 0) $return .= '
    '; + } elseif ($nbbyrow < 0) { + $return .= '
    '; + } $return .= "\n"; $relativefile = preg_replace('/^\//', '', $pdir.$photo); - if (empty($nolink)) - { + if (empty($nolink)) { $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity); - if ($urladvanced) $return .= ''; - else $return .= ''; + if ($urladvanced) { + $return .= ''; + } else { + $return .= ''; + } } // Show image (width height=$maxHeight) // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile; $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height']; - if ($notitle) $alt = ''; + if ($notitle) { + $alt = ''; + } if ($usesharelink) { if ($val['share']) { @@ -7458,21 +7870,22 @@ abstract class CommonObject } } - if (empty($nolink)) $return .= ''; + if (empty($nolink)) { + $return .= ''; + } $return .= "\n"; - if ($showfilename) $return .= '
    '.$viewfilename; - if ($showaction) - { + if ($showfilename) { + $return .= '
    '.$viewfilename; + } + if ($showaction) { $return .= '
    '; // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites - if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) - { + if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) { $return .= ''.img_picto($langs->trans('GenerateThumb'), 'refresh').'  '; } // Special cas for product - if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) - { + if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) { // Link to resize $return .= ''.img_picto($langs->trans("Resize"), 'resize', '').'   '; @@ -7483,22 +7896,25 @@ abstract class CommonObject } $return .= "\n"; - if ($nbbyrow > 0) - { + if ($nbbyrow > 0) { $return .= '
     
    '; + if ($nbphoto) { + $return .= '
    '; + } } } } @@ -7545,8 +7962,11 @@ abstract class CommonObject protected function isArray($info) { if (is_array($info)) { - if (isset($info['type']) && $info['type'] == 'array') return true; - else return false; + if (isset($info['type']) && $info['type'] == 'array') { + return true; + } else { + return false; + } } return false; } @@ -7559,7 +7979,9 @@ abstract class CommonObject */ public function isDate($info) { - if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) return true; + if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) { + return true; + } return false; } @@ -7572,9 +7994,14 @@ abstract class CommonObject public function isDuration($info) { if (is_array($info)) { - if (isset($info['type']) && ($info['type'] == 'duration')) return true; - else return false; - } else return false; + if (isset($info['type']) && ($info['type'] == 'duration')) { + return true; + } else { + return false; + } + } else { + return false; + } } /** @@ -7586,9 +8013,14 @@ abstract class CommonObject public function isInt($info) { if (is_array($info)) { - if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) return true; - else return false; - } else return false; + if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) { + return true; + } else { + return false; + } + } else { + return false; + } } /** @@ -7600,8 +8032,11 @@ abstract class CommonObject public function isFloat($info) { if (is_array($info)) { - if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) return true; - else return false; + if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) { + return true; + } else { + return false; + } } return false; } @@ -7615,8 +8050,11 @@ abstract class CommonObject public function isText($info) { if (is_array($info)) { - if (isset($info['type']) && $info['type'] == 'text') return true; - else return false; + if (isset($info['type']) && $info['type'] == 'text') { + return true; + } else { + return false; + } } return false; } @@ -7630,8 +8068,11 @@ abstract class CommonObject protected function canBeNull($info) { if (is_array($info)) { - if (isset($info['notnull']) && $info['notnull'] != '1') return true; - else return false; + if (isset($info['notnull']) && $info['notnull'] != '1') { + return true; + } else { + return false; + } } return true; } @@ -7645,8 +8086,11 @@ abstract class CommonObject protected function isForcedToNullIfZero($info) { if (is_array($info)) { - if (isset($info['notnull']) && $info['notnull'] == '-1') return true; - else return false; + if (isset($info['notnull']) && $info['notnull'] == '-1') { + return true; + } else { + return false; + } } return false; } @@ -7660,8 +8104,11 @@ abstract class CommonObject protected function isIndex($info) { if (is_array($info)) { - if (isset($info['index']) && $info['index'] == true) return true; - else return false; + if (isset($info['index']) && $info['index'] == true) { + return true; + } else { + return false; + } } return false; } @@ -7679,18 +8126,15 @@ abstract class CommonObject global $conf; $queryarray = array(); - foreach ($this->fields as $field => $info) // Loop on definition of fields - { + foreach ($this->fields as $field => $info) { // Loop on definition of fields // Depending on field type ('datetime', ...) - if ($this->isDate($info)) - { + if ($this->isDate($info)) { if (empty($this->{$field})) { $queryarray[$field] = null; } else { $queryarray[$field] = $this->db->idate($this->{$field}); } - } elseif ($this->isArray($info)) - { + } elseif ($this->isArray($info)) { if (!empty($this->{$field})) { if (!is_array($this->{$field})) { $this->{$field} = array($this->{$field}); @@ -7699,8 +8143,7 @@ abstract class CommonObject } else { $queryarray[$field] = null; } - } elseif ($this->isDuration($info)) - { + } elseif ($this->isDuration($info)) { // $this->{$field} may be null, '', 0, '0', 123, '123' if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) { if (!isset($this->{$field})) { @@ -7708,12 +8151,13 @@ abstract class CommonObject } else { $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 } + } else { + $queryarray[$field] = null; } - else $queryarray[$field] = null; - } elseif ($this->isInt($info) || $this->isFloat($info)) - { - if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field] = $conf->entity; - else { + } elseif ($this->isInt($info) || $this->isFloat($info)) { + if ($field == 'entity' && is_null($this->{$field})) { + $queryarray[$field] = $conf->entity; + } else { // $this->{$field} may be null, '', 0, '0', 123, '123' if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) { if (!isset($this->{$field})) { @@ -7723,14 +8167,20 @@ abstract class CommonObject } elseif ($this->isFloat($info)) { $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 } - } else $queryarray[$field] = null; + } else { + $queryarray[$field] = null; + } } } else { $queryarray[$field] = $this->{$field}; } - if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]); - if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null; // May force 0 to null + if ($info['type'] == 'timestamp' && empty($queryarray[$field])) { + unset($queryarray[$field]); + } + if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) { + $queryarray[$field] = null; // May force 0 to null + } } return $queryarray; @@ -7744,26 +8194,35 @@ abstract class CommonObject */ public function setVarsFromFetchObj(&$obj) { - foreach ($this->fields as $field => $info) - { + global $db; + + foreach ($this->fields as $field => $info) { if ($this->isDate($info)) { - if (empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0; - else $this->{$field} = strtotime($obj->{$field}); - } elseif ($this->isArray($info)) - { + if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') { + $this->{$field} = ''; + } else { + $this->{$field} = $db->jdate($obj->{$field}); + } + } elseif ($this->isArray($info)) { if (!empty($obj->{$field})) { $this->{$field} = @unserialize($obj->{$field}); // Hack for data not in UTF8 - if ($this->{$field } === false) @unserialize(utf8_decode($obj->{$field})); + if ($this->{$field } === false) { + @unserialize(utf8_decode($obj->{$field})); + } } else { $this->{$field} = array(); } } elseif ($this->isInt($info)) { - if ($field == 'rowid') $this->id = (int) $obj->{$field}; - else { + if ($field == 'rowid') { + $this->id = (int) $obj->{$field}; + } else { if ($this->isForcedToNullIfZero($info)) { - if (empty($obj->{$field})) $this->{$field} = null; - else $this->{$field} = (double) $obj->{$field}; + if (empty($obj->{$field})) { + $this->{$field} = null; + } else { + $this->{$field} = (double) $obj->{$field}; + } } else { if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) { $this->{$field} = (int) $obj->{$field}; @@ -7774,8 +8233,11 @@ abstract class CommonObject } } elseif ($this->isFloat($info)) { if ($this->isForcedToNullIfZero($info)) { - if (empty($obj->{$field})) $this->{$field} = null; - else $this->{$field} = (double) $obj->{$field}; + if (empty($obj->{$field})) { + $this->{$field} = null; + } else { + $this->{$field} = (double) $obj->{$field}; + } } else { if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) { $this->{$field} = (double) $obj->{$field}; @@ -7789,18 +8251,29 @@ abstract class CommonObject } // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions. - if (!isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id; + if (!isset($this->fields['ref']) && isset($this->id)) { + $this->ref = $this->id; + } } /** * Function to concat keys of fields * - * @return string + * @param string $alias String of alias of table for fields. For example 't'. + * @return string list of alias fields */ - protected function getFieldList() + public function getFieldList($alias = '') { $keys = array_keys($this->fields); - return implode(',', $keys); + if (!empty($alias)) { + $keys_with_alias = array(); + foreach ($keys as $fieldname) { + $keys_with_alias[] = $alias . '.' . $fieldname; + } + return implode(',', $keys_with_alias); + } else { + return implode(',', $keys); + } } /** @@ -7812,13 +8285,19 @@ abstract class CommonObject */ protected function quote($value, $fieldsentry) { - if (is_null($value)) return 'NULL'; - elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) return $this->db->escape("$value"); - elseif ($fieldsentry['type'] == 'boolean') { - if ($value) return 'true'; - else return 'false'; + if (is_null($value)) { + return 'NULL'; + } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) { + return $this->db->escape("$value"); + } elseif ($fieldsentry['type'] == 'boolean') { + if ($value) { + return 'true'; + } else { + return 'false'; + } + } else { + return "'".$this->db->escape($value)."'"; } - else return "'".$this->db->escape($value)."'"; } @@ -7840,10 +8319,16 @@ abstract class CommonObject $fieldvalues = $this->setSaveQuery(); - if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation'] = $this->db->idate($now); - if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat'] = $user->id; + if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) { + $fieldvalues['date_creation'] = $this->db->idate($now); + } + if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) { + $fieldvalues['fk_user_creat'] = $user->id; + } unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert. - if (array_key_exists('ref', $fieldvalues)) $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data + if (array_key_exists('ref', $fieldvalues)) { + $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data + } $keys = array(); $values = array(); // Array to store string forged for SQL syntax @@ -7854,38 +8339,45 @@ abstract class CommonObject } // Clean and check mandatory - foreach ($keys as $key) - { + foreach ($keys as $key) { // If field is an implicit foreign key field - if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = ''; - if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = ''; + if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') { + $values[$key] = ''; + } + if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') { + $values[$key] = ''; + } - if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) - { + if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) { $error++; $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']); } // If value is null and there is a default value for field - if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) - { + if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) { $values[$key] = $this->fields[$key]['default']; } // If field is an implicit foreign key field if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) { - if (isset($this->fields[$key]['default'])) $values[$key] = $this->fields[$key]['default']; - else $values[$key] = 'null'; + if (isset($this->fields[$key]['default'])) { + $values[$key] = $this->fields[$key]['default']; + } else { + $values[$key] = 'null'; + } + } + if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) { + $values[$key] = 'null'; } - if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key] = 'null'; } - if ($error) return -1; + if ($error) { + return -1; + } $this->db->begin(); - if (!$error) - { + if (!$error) { $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' ('.implode(", ", $keys).')'; $sql .= ' VALUES ('.implode(", ", $values).')'; @@ -7897,21 +8389,17 @@ abstract class CommonObject } } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); } // If we have a field ref with a default value of (PROV) - if (!$error) - { - if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && !is_null($this->fields['ref']['default']) && $this->fields['ref']['default'] == '(PROV)') - { + if (!$error) { + if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && !is_null($this->fields['ref']['default']) && $this->fields['ref']['default'] == '(PROV)') { $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".$this->id.")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".$this->id; $resqlupdate = $this->db->query($sql); - if ($resqlupdate === false) - { + if ($resqlupdate === false) { $error++; $this->errors[] = $this->db->lasterror(); } else { @@ -7921,18 +8409,17 @@ abstract class CommonObject } // Create extrafields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } // Create lines - if (!empty($this->table_element_line) && !empty($this->fk_element)) - { + if (!empty($this->table_element_line) && !empty($this->fk_element)) { $num = (is_array($this->lines) ? count($this->lines) : 0); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $line = $this->lines[$i]; $keyforparent = $this->fk_element; @@ -7940,11 +8427,12 @@ abstract class CommonObject // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. - if (!is_object($line)) $line = (object) $line; + if (!is_object($line)) { + $line = (object) $line; + } $result = $line->create($user, 1); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; @@ -7953,11 +8441,12 @@ abstract class CommonObject } // Triggers - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call triggers $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -7982,27 +8471,37 @@ abstract class CommonObject */ public function fetchCommon($id, $ref = null, $morewhere = '') { - if (empty($id) && empty($ref) && empty($morewhere)) return -1; + if (empty($id) && empty($ref) && empty($morewhere)) { + return -1; + } - $fieldlist = $this->getFieldList(); - if (empty($fieldlist)) return 0; + $fieldlist = $this->getFieldList('t'); + if (empty($fieldlist)) { + return 0; + } $sql = 'SELECT '.$fieldlist; - $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if (!empty($id)) $sql .= ' WHERE rowid = '.$id; - elseif (!empty($ref)) $sql .= " WHERE ref = ".$this->quote($ref, $this->fields['ref']); - else $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare - if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' AND entity IN ('.getEntity($this->table_element).')'; - if ($morewhere) $sql .= $morewhere; + if (!empty($id)) { + $sql .= ' WHERE t.rowid = '.((int) $id); + } elseif (!empty($ref)) { + $sql .= " WHERE t.ref = ".$this->quote($ref, $this->fields['ref']); + } else { + $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare + } + if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { + $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')'; + } + if ($morewhere) { + $sql .= $morewhere; + } $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record $res = $this->db->query($sql); - if ($res) - { + if ($res) { $obj = $this->db->fetch_object($res); - if ($obj) - { + if ($obj) { $this->setVarsFromFetchObj($obj); // Retrieve all extrafield @@ -8029,32 +8528,30 @@ abstract class CommonObject public function fetchLinesCommon($morewhere = '') { $objectlineclassname = get_class($this).'Line'; - if (!class_exists($objectlineclassname)) - { + if (!class_exists($objectlineclassname)) { $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon'; return -1; } $objectline = new $objectlineclassname($this->db); - $sql = 'SELECT '.$objectline->getFieldList(); - $sql .= ' FROM '.MAIN_DB_PREFIX.$objectline->table_element; - $sql .= ' WHERE fk_'.$this->element.' = '.$this->id; - if ($morewhere) $sql .= $morewhere; + $sql = 'SELECT '.$objectline->getFieldList('l'); + $sql .= ' FROM '.MAIN_DB_PREFIX.$objectline->table_element.' as l'; + $sql .= ' WHERE l.fk_'.$this->element.' = '.$this->id; + if ($morewhere) { + $sql .= $morewhere; + } if (isset($objectline->fields['position'])) { $sql .= $this->db->order('position', 'ASC'); } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_rows = $this->db->num_rows($resql); $i = 0; - while ($i < $num_rows) - { + while ($i < $num_rows) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $newline = new $objectlineclassname($this->db); $newline->setVarsFromFetchObj($obj); @@ -8089,10 +8586,16 @@ abstract class CommonObject $fieldvalues = $this->setSaveQuery(); - if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification'] = $this->db->idate($now); - if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif'] = $user->id; + if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) { + $fieldvalues['date_modification'] = $this->db->idate($now); + } + if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) { + $fieldvalues['fk_user_modif'] = $user->id; + } unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update. - if (array_key_exists('ref', $fieldvalues)) $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data + if (array_key_exists('ref', $fieldvalues)) { + $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data + } // Add quotes and escape on fields with type string $keys = array(); @@ -8106,10 +8609,13 @@ abstract class CommonObject } // Clean and check mandatory fields - foreach ($keys as $key) - { - if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = ''; // This is an implicit foreign key field - if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = ''; // This is an explicit foreign key field + foreach ($keys as $key) { + if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') { + $values[$key] = ''; // This is an implicit foreign key field + } + if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') { + $values[$key] = ''; // This is an explicit foreign key field + } //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1)); /* @@ -8120,35 +8626,32 @@ abstract class CommonObject }*/ } - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id); $this->db->begin(); - if (!$error) - { + if (!$error) { $res = $this->db->query($sql); - if ($res === false) - { + if ($res === false) { $error++; $this->errors[] = $this->db->lasterror(); } } // Update extrafield - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } // Triggers - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call triggers $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user); - if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail + if ($result < 0) { + $error++; + } //Do also here what you must do to rollback action if trigger fail // End call triggers } @@ -8178,25 +8681,20 @@ abstract class CommonObject $this->db->begin(); - if ($forcechilddeletion) // Force also delete of childtables that should lock deletion in standard case when option force is off - { - foreach ($this->childtables as $table) - { + if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off + foreach ($this->childtables as $table) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->lasterror(); $this->errors[] = $this->error; $this->db->rollback(); return -1; } } - } elseif (!empty($this->fk_element) && !empty($this->childtables)) // If object has childs linked with a foreign key field, we check all child tables. - { + } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables. $objectisused = $this->isObjectUsed($this->id); - if (!empty($objectisused)) - { + if (!empty($objectisused)) { dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING); $this->error = 'ErrorRecordHasChildren'; $this->errors[] = $this->error; @@ -8207,8 +8705,7 @@ abstract class CommonObject // Delete cascade first if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) { - foreach ($this->childtablesoncascade as $table) - { + foreach ($this->childtablesoncascade as $table) { $deleteFromObject = explode(':', $table); if (count($deleteFromObject) >= 2) { $className = str_replace('@', '', $deleteFromObject[0]); @@ -8252,7 +8749,9 @@ abstract class CommonObject if (!$notrigger) { // Call triggers $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user); - if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail + if ($result < 0) { + $error++; + } // Do also here what you must do to rollback action if trigger fail // End call triggers } } @@ -8265,15 +8764,15 @@ abstract class CommonObject } } - if (!$error && !empty($this->isextrafieldmanaged)) - { + if (!$error && !empty($this->isextrafieldmanaged)) { $result = $this->deleteExtraFields(); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } } - if (!$error) - { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; + if (!$error) { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id); $res = $this->db->query($sql); if ($res === false) { @@ -8371,7 +8870,9 @@ abstract class CommonObject // Call trigger $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user); - if ($result < 0) return -1; + if ($result < 0) { + return -1; + } // End call triggers $this->db->begin(); @@ -8381,8 +8882,7 @@ abstract class CommonObject dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = "Error ".$this->db->lasterror(); $error++; } @@ -8393,8 +8893,7 @@ abstract class CommonObject if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) { $tmpobjectline->id = $idline; $result = $tmpobjectline->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error; } @@ -8428,23 +8927,25 @@ abstract class CommonObject $this->db->begin(); $statusfield = 'status'; - if ($this->element == 'don' || $this->element == 'donation') $statusfield = 'fk_statut'; + if ($this->element == 'don' || $this->element == 'donation') { + $statusfield = 'fk_statut'; + } $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql .= " SET ".$statusfield." = ".((int) $status); $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { - if (!$error) - { + if ($this->db->query($sql)) { + if (!$error) { $this->oldcopy = clone $this; } if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger($triggercode, $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } if (!$error) { @@ -8489,7 +8990,9 @@ abstract class CommonObject 'date' => dol_now(), ); foreach ($fields as $key => $value) { - if (array_key_exists($key, $this->fields)) $this->{$key} = $value; + if (array_key_exists($key, $this->fields)) { + $this->{$key} = $value; + } } return 1; } @@ -8534,7 +9037,9 @@ abstract class CommonObject */ public function trimParameters($parameters) { - if (!is_array($parameters)) return; + if (!is_array($parameters)) { + return; + } foreach ($parameters as $parameter) { if (isset($this->$parameter)) { $this->$parameter = trim($this->$parameter); @@ -8617,8 +9122,7 @@ abstract class CommonObject foreach ($to_del as $del) { if ($c->fetch($del) > 0) { $result=$c->del_type($this, $type_categ); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $c->error; $this->errors = $c->errors; @@ -8629,11 +9133,9 @@ abstract class CommonObject } } foreach ($to_add as $add) { - if ($c->fetch($add) > 0) - { + if ($c->fetch($add) > 0) { $result = $c->add_type($this, $type_categ); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $c->error; $this->errors = $c->errors; @@ -8659,7 +9161,9 @@ abstract class CommonObject { $this->db->begin(); - if (empty($type)) $type = $this->table_element; + if (empty($type)) { + $type = $this->table_element; + } require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $categorystatic = new Categorie($this->db); @@ -8668,8 +9172,7 @@ abstract class CommonObject $sql .= " SELECT fk_categorie, $toId FROM ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]); $sql .= " WHERE fk_product = ".((int) $fromId); - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; diff --git a/htdocs/core/class/commonobjectline.class.php b/htdocs/core/class/commonobjectline.class.php index 0d4cfbe4f34..f821e5050b1 100644 --- a/htdocs/core/class/commonobjectline.class.php +++ b/htdocs/core/class/commonobjectline.class.php @@ -80,15 +80,21 @@ abstract class CommonObjectLine extends CommonObject $label_type = 'label'; $label_type = 'label'; - if ($type == 'short') $label_type = 'short_label'; - elseif ($type == 'code') $label_type = 'code'; + if ($type == 'short') { + $label_type = 'short_label'; + } elseif ($type == 'code') { + $label_type = 'code'; + } $sql = 'select '.$label_type.', code from '.MAIN_DB_PREFIX.'c_units where rowid='.$this->fk_unit; $resql = $this->db->query($sql); if ($resql && $this->db->num_rows($resql) > 0) { $res = $this->db->fetch_array($resql); - if ($label_type == 'code') $label = 'unit'.$res['code']; - else $label = $res[$label_type]; + if ($label_type == 'code') { + $label = 'unit'.$res['code']; + } else { + $label = $res[$label_type]; + } $this->db->free($resql); return $label; } else { diff --git a/htdocs/core/class/commonstickergenerator.class.php b/htdocs/core/class/commonstickergenerator.class.php index 3a8712ad67d..284b41ee4ba 100644 --- a/htdocs/core/class/commonstickergenerator.class.php +++ b/htdocs/core/class/commonstickergenerator.class.php @@ -121,7 +121,7 @@ abstract class CommonStickerGenerator * @param string $outputdir Output directory for pdf file * @return int 1=OK, 0=KO */ - public abstract function write_file($arrayofrecords, $outputlangs, $srctemplatepath, $outputdir = ''); + abstract public function write_file($arrayofrecords, $outputlangs, $srctemplatepath, $outputdir = ''); // phpcs:enable /** @@ -132,7 +132,7 @@ abstract class CommonStickerGenerator * @param array $param Associative array containing label content and optional parameters * @return void */ - public abstract function addSticker(&$pdf, $outputlangs, $param); + abstract public function addSticker(&$pdf, $outputlangs, $param); // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index 1eb3b9911ba..0eab527bc6b 100644 --- a/htdocs/core/class/conf.class.php +++ b/htdocs/core/class/conf.class.php @@ -80,6 +80,9 @@ class Conf 'syslog' => array(), ); + // An array to store cache results ->cache['nameofcache']=... + public $cache = array(); + public $logbuffer = array(); /** @@ -98,7 +101,7 @@ class Conf public $dol_hide_leftmenu; // Set if we force param dol_hide_leftmenu into login url public $dol_optimize_smallscreen; // Set if we force param dol_optimize_smallscreen into login url or if browser is smartphone public $dol_no_mouse_hover; // Set if we force param dol_no_mouse_hover into login url or if browser is smartphone - public $dol_use_jmobile; // Set if we force param dol_use_jmobile into login url + public $dol_use_jmobile; // Set if we force param dol_use_jmobile into login url. 0=default, 1=to say we use app from a webview app, 2=to say we use app from a webview app and keep ajax public $liste_limit; @@ -168,17 +171,14 @@ class Conf $sql .= " ORDER BY entity"; // This is to have entity 0 first, then entity 1 that overwrite. $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $numr = $db->num_rows($resql); - while ($i < $numr) - { + while ($i < $numr) { $objp = $db->fetch_object($resql); $key = $objp->name; $value = $objp->value; - if ($key) - { + if ($key) { // Allow constants values to be overridden by environment variables if (isset($_SERVER['DOLIBARR_'.$key])) { $value = $_SERVER['DOLIBARR_'.$key]; @@ -189,42 +189,53 @@ class Conf //if (! defined("$key")) define("$key", $value); // In some cases, the constant might be already forced (Example: SYSLOG_HANDLERS during install) $this->global->$key = $value; - if ($value && strpos($key, 'MAIN_MODULE_') === 0) - { + if ($value && strpos($key, 'MAIN_MODULE_') === 0) { $reg = array(); // If this is constant for a new tab page activated by a module. It initializes modules_parts['tabs']. - if (preg_match('/^MAIN_MODULE_([0-9A-Z_]+)_TABS_/i', $key)) - { + if (preg_match('/^MAIN_MODULE_([0-9A-Z_]+)_TABS_/i', $key)) { $partname = 'tabs'; $params = explode(':', $value, 2); - if (!is_array($this->modules_parts[$partname])) { $this->modules_parts[$partname] = array(); } + if (!is_array($this->modules_parts[$partname])) { + $this->modules_parts[$partname] = array(); + } $this->modules_parts[$partname][$params[0]][] = $value; // $value may be a string or an array - } - // If this is constant for all generic part activated by a module. It initializes - // modules_parts['login'], modules_parts['menus'], modules_parts['substitutions'], modules_parts['triggers'], modules_parts['tpl'], - // modules_parts['models'], modules_parts['theme'] - // modules_parts['sms'], - // modules_parts['css'], ... - elseif (preg_match('/^MAIN_MODULE_([0-9A-Z_]+)_([A-Z]+)$/i', $key, $reg)) - { + } elseif (preg_match('/^MAIN_MODULE_([0-9A-Z_]+)_([A-Z]+)$/i', $key, $reg)) { + // If this is constant for all generic part activated by a module. It initializes + // modules_parts['login'], modules_parts['menus'], modules_parts['substitutions'], modules_parts['triggers'], modules_parts['tpl'], + // modules_parts['models'], modules_parts['theme'] + // modules_parts['sms'], + // modules_parts['css'], ... + $modulename = strtolower($reg[1]); $partname = strtolower($reg[2]); - if (!isset($this->modules_parts[$partname]) || !is_array($this->modules_parts[$partname])) { $this->modules_parts[$partname] = array(); } + if (!isset($this->modules_parts[$partname]) || !is_array($this->modules_parts[$partname])) { + $this->modules_parts[$partname] = array(); + } $arrValue = json_decode($value, true); - if (is_array($arrValue) && !empty($arrValue)) $value = $arrValue; - elseif (in_array($partname, array('login', 'menus', 'substitutions', 'triggers', 'tpl'))) $value = '/'.$modulename.'/core/'.$partname.'/'; - elseif (in_array($partname, array('models', 'theme'))) $value = '/'.$modulename.'/'; - elseif (in_array($partname, array('sms'))) $value = '/'.$modulename.'/'; - elseif ($value == 1) $value = '/'.$modulename.'/core/modules/'.$partname.'/'; // ex: partname = societe + if (is_array($arrValue) && !empty($arrValue)) { + $value = $arrValue; + } elseif (in_array($partname, array('login', 'menus', 'substitutions', 'triggers', 'tpl'))) { + $value = '/'.$modulename.'/core/'.$partname.'/'; + } elseif (in_array($partname, array('models', 'theme'))) { + $value = '/'.$modulename.'/'; + } elseif (in_array($partname, array('sms'))) { + $value = '/'.$modulename.'/'; + } elseif ($value == 1) { + $value = '/'.$modulename.'/core/modules/'.$partname.'/'; // ex: partname = societe + } $this->modules_parts[$partname] = array_merge($this->modules_parts[$partname], array($modulename => $value)); // $value may be a string or an array - } - // If this is a module constant (must be at end) - elseif (preg_match('/^MAIN_MODULE_([0-9A-Z_]+)$/i', $key, $reg)) - { + } elseif (preg_match('/^MAIN_MODULE_([0-9A-Z_]+)$/i', $key, $reg)) { + // If this is a module constant (must be at end) $modulename = strtolower($reg[1]); - if ($modulename == 'propale') $modulename = 'propal'; - if ($modulename == 'supplierproposal') $modulename = 'supplier_proposal'; - if (!isset($this->$modulename) || !is_object($this->$modulename)) $this->$modulename = new stdClass(); + if ($modulename == 'propale') { + $modulename = 'propal'; + } + if ($modulename == 'supplierproposal') { + $modulename = 'supplier_proposal'; + } + if (!isset($this->$modulename) || !is_object($this->$modulename)) { + $this->$modulename = new stdClass(); + } $this->$modulename->enabled = true; $this->modules[] = $modulename; // Add this module in list of enabled modules } @@ -251,12 +262,10 @@ class Conf // If you can't set timezone of your PHP, set this constant. Better is to set it to UTC. // In future, this constant will be forced to 'UTC' so PHP server timezone will not have effect anymore. //$this->global->MAIN_SERVER_TZ='Europe/Paris'; - if (!empty($this->global->MAIN_SERVER_TZ) && $this->global->MAIN_SERVER_TZ != 'auto') - { + if (!empty($this->global->MAIN_SERVER_TZ) && $this->global->MAIN_SERVER_TZ != 'auto') { try { date_default_timezone_set($this->global->MAIN_SERVER_TZ); - } catch (Exception $e) - { + } catch (Exception $e) { dol_syslog("Error: Bad value for parameter MAIN_SERVER_TZ=".$this->global->MAIN_SERVER_TZ, LOG_ERR); } } @@ -272,36 +281,58 @@ class Conf } // Clean some variables - if (empty($this->global->MAIN_MENU_STANDARD)) $this->global->MAIN_MENU_STANDARD = "eldy_menu.php"; - if (empty($this->global->MAIN_MENUFRONT_STANDARD)) $this->global->MAIN_MENUFRONT_STANDARD = "eldy_menu.php"; - if (empty($this->global->MAIN_MENU_SMARTPHONE)) $this->global->MAIN_MENU_SMARTPHONE = "eldy_menu.php"; // Use eldy by default because smartphone does not work on all phones - if (empty($this->global->MAIN_MENUFRONT_SMARTPHONE)) $this->global->MAIN_MENUFRONT_SMARTPHONE = "eldy_menu.php"; // Use eldy by default because smartphone does not work on all phones - if (!isset($this->global->FACTURE_TVAOPTION)) $this->global->FACTURE_TVAOPTION = 1; + if (empty($this->global->MAIN_MENU_STANDARD)) { + $this->global->MAIN_MENU_STANDARD = "eldy_menu.php"; + } + if (empty($this->global->MAIN_MENUFRONT_STANDARD)) { + $this->global->MAIN_MENUFRONT_STANDARD = "eldy_menu.php"; + } + if (empty($this->global->MAIN_MENU_SMARTPHONE)) { + $this->global->MAIN_MENU_SMARTPHONE = "eldy_menu.php"; // Use eldy by default because smartphone does not work on all phones + } + if (empty($this->global->MAIN_MENUFRONT_SMARTPHONE)) { + $this->global->MAIN_MENUFRONT_SMARTPHONE = "eldy_menu.php"; // Use eldy by default because smartphone does not work on all phones + } + if (!isset($this->global->FACTURE_TVAOPTION)) { + $this->global->FACTURE_TVAOPTION = 1; + } // Variable globales LDAP - if (empty($this->global->LDAP_FIELD_FULLNAME)) $this->global->LDAP_FIELD_FULLNAME = ''; - if (!isset($this->global->LDAP_KEY_USERS)) $this->global->LDAP_KEY_USERS = $this->global->LDAP_FIELD_FULLNAME; - if (!isset($this->global->LDAP_KEY_GROUPS)) $this->global->LDAP_KEY_GROUPS = $this->global->LDAP_FIELD_FULLNAME; - if (!isset($this->global->LDAP_KEY_CONTACTS)) $this->global->LDAP_KEY_CONTACTS = $this->global->LDAP_FIELD_FULLNAME; - if (!isset($this->global->LDAP_KEY_MEMBERS)) $this->global->LDAP_KEY_MEMBERS = $this->global->LDAP_FIELD_FULLNAME; - if (!isset($this->global->LDAP_KEY_MEMBERS_TYPES)) $this->global->LDAP_KEY_MEMBERS_TYPES = $this->global->LDAP_FIELD_FULLNAME; + if (empty($this->global->LDAP_FIELD_FULLNAME)) { + $this->global->LDAP_FIELD_FULLNAME = ''; + } + if (!isset($this->global->LDAP_KEY_USERS)) { + $this->global->LDAP_KEY_USERS = $this->global->LDAP_FIELD_FULLNAME; + } + if (!isset($this->global->LDAP_KEY_GROUPS)) { + $this->global->LDAP_KEY_GROUPS = $this->global->LDAP_FIELD_FULLNAME; + } + if (!isset($this->global->LDAP_KEY_CONTACTS)) { + $this->global->LDAP_KEY_CONTACTS = $this->global->LDAP_FIELD_FULLNAME; + } + if (!isset($this->global->LDAP_KEY_MEMBERS)) { + $this->global->LDAP_KEY_MEMBERS = $this->global->LDAP_FIELD_FULLNAME; + } + if (!isset($this->global->LDAP_KEY_MEMBERS_TYPES)) { + $this->global->LDAP_KEY_MEMBERS_TYPES = $this->global->LDAP_FIELD_FULLNAME; + } // Load translation object with current language - if (empty($this->global->MAIN_LANG_DEFAULT)) $this->global->MAIN_LANG_DEFAULT = "en_US"; + if (empty($this->global->MAIN_LANG_DEFAULT)) { + $this->global->MAIN_LANG_DEFAULT = "en_US"; + } $rootfordata = DOL_DATA_ROOT; $rootforuser = DOL_DATA_ROOT; // If multicompany module is enabled, we redefine the root of data - if (!empty($this->multicompany->enabled) && !empty($this->entity) && $this->entity > 1) - { + if (!empty($this->multicompany->enabled) && !empty($this->entity) && $this->entity > 1) { $rootfordata .= '/'.$this->entity; } // Set standard temporary folder name or global override $rootfortemp = empty($this->global->MAIN_TEMP_DIR) ? $rootfordata : $this->global->MAIN_TEMP_DIR; // Define default dir_output and dir_temp for directories of modules - foreach ($this->modules as $module) - { + foreach ($this->modules as $module) { //var_dump($module); // For multicompany sharings $this->$module->multidir_output = array($this->entity => $rootfordata."/".$module); @@ -312,19 +343,14 @@ class Conf } // External modules storage - if (!empty($this->modules_parts['dir'])) - { - foreach ($this->modules_parts['dir'] as $module => $dirs) - { - if (!empty($this->$module->enabled)) - { - foreach ($dirs as $type => $name) // $type is 'output' or 'temp' - { + if (!empty($this->modules_parts['dir'])) { + foreach ($this->modules_parts['dir'] as $module => $dirs) { + if (!empty($this->$module->enabled)) { + foreach ($dirs as $type => $name) { // $type is 'output' or 'temp' $multidirname = 'multidir_'.$type; $dirname = 'dir_'.$type; - if ($type != 'temp') - { + if ($type != 'temp') { // For multicompany sharings $this->$module->$multidirname = array($this->entity => $rootfordata."/".$name); @@ -380,8 +406,7 @@ class Conf $this->delivery_note->enabled = (!empty($this->global->MAIN_SUBMODULE_DELIVERY) ? $this->global->MAIN_SUBMODULE_DELIVERY : 0); // Module fournisseur - if (!empty($this->fournisseur)) - { + if (!empty($this->fournisseur)) { $this->fournisseur->commande = new stdClass(); $this->fournisseur->commande->multidir_output = array($this->entity => $rootfordata."/fournisseur/commande"); $this->fournisseur->commande->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/commande/temp"); @@ -407,8 +432,7 @@ class Conf $this->fournisseur->payment->dir_temp = $rootfortemp."/fournisseur/payment/temp"; // For backward compatibility // To prepare split of module fournisseur into module 'fournisseur' + supplier_order + supplier_invoice - if (!empty($this->fournisseur->enabled) && empty($this->global->MAIN_USE_NEW_SUPPLIERMOD)) // By default, if module supplier is on, and we don't use yet the new modules, we set artificialy the module properties - { + if (!empty($this->fournisseur->enabled) && empty($this->global->MAIN_USE_NEW_SUPPLIERMOD)) { // By default, if module supplier is on, and we don't use yet the new modules, we set artificialy the module properties $this->supplier_order = new stdClass(); $this->supplier_order->enabled = 1; $this->supplier_order->multidir_output = array($this->entity => $rootfordata."/fournisseur/commande"); @@ -437,8 +461,8 @@ class Conf $this->service->dir_temp = $rootfortemp."/produit/temp"; // Module productbatch - $this->productbatch->multidir_output = array($this->entity => $rootfordata."/produitlot"); - $this->productbatch->multidir_temp = array($this->entity => $rootfortemp."/produitlot/temp"); + $this->productbatch->multidir_output = array($this->entity => $rootfordata."/productlot"); + $this->productbatch->multidir_temp = array($this->entity => $rootfortemp."/productlot/temp"); // Module contrat $this->contrat->multidir_output = array($this->entity => $rootfordata."/contract"); @@ -459,30 +483,42 @@ class Conf $this->global->MAIN_MAIL_USE_MULTI_PART = 1; // societe - if (empty($this->global->SOCIETE_CODECLIENT_ADDON)) $this->global->SOCIETE_CODECLIENT_ADDON = "mod_codeclient_leopard"; - if (empty($this->global->SOCIETE_CODECOMPTA_ADDON)) $this->global->SOCIETE_CODECOMPTA_ADDON = "mod_codecompta_panicum"; + if (empty($this->global->SOCIETE_CODECLIENT_ADDON)) { + $this->global->SOCIETE_CODECLIENT_ADDON = "mod_codeclient_leopard"; + } + if (empty($this->global->SOCIETE_CODECOMPTA_ADDON)) { + $this->global->SOCIETE_CODECOMPTA_ADDON = "mod_codecompta_panicum"; + } - if (empty($this->global->CHEQUERECEIPTS_ADDON)) $this->global->CHEQUERECEIPTS_ADDON = 'mod_chequereceipt_mint'; - if (empty($this->global->TICKET_ADDON)) $this->global->TICKET_ADDON = 'mod_ticket_simple'; + if (empty($this->global->CHEQUERECEIPTS_ADDON)) { + $this->global->CHEQUERECEIPTS_ADDON = 'mod_chequereceipt_mint'; + } + if (empty($this->global->TICKET_ADDON)) { + $this->global->TICKET_ADDON = 'mod_ticket_simple'; + } // Security - if (empty($this->global->USER_PASSWORD_GENERATED)) $this->global->USER_PASSWORD_GENERATED = 'standard'; // Default password generator - if (empty($this->global->MAIN_UMASK)) $this->global->MAIN_UMASK = '0664'; // Default mask + if (empty($this->global->USER_PASSWORD_GENERATED)) { + $this->global->USER_PASSWORD_GENERATED = 'standard'; // Default password generator + } + if (empty($this->global->MAIN_UMASK)) { + $this->global->MAIN_UMASK = '0664'; // Default mask + } // conf->use_javascript_ajax $this->use_javascript_ajax = 1; - if (isset($this->global->MAIN_DISABLE_JAVASCRIPT)) $this->use_javascript_ajax = !$this->global->MAIN_DISABLE_JAVASCRIPT; + if (isset($this->global->MAIN_DISABLE_JAVASCRIPT)) { + $this->use_javascript_ajax = !$this->global->MAIN_DISABLE_JAVASCRIPT; + } // If no javascript_ajax, Ajax features are disabled. - if (empty($this->use_javascript_ajax)) - { + if (empty($this->use_javascript_ajax)) { unset($this->global->PRODUIT_USE_SEARCH_TO_SELECT); unset($this->global->COMPANY_USE_SEARCH_TO_SELECT); unset($this->global->CONTACT_USE_SEARCH_TO_SELECT); unset($this->global->PROJECT_USE_SEARCH_TO_SELECT); } - if (!empty($this->productbatch->enabled)) - { + if (!empty($this->productbatch->enabled)) { $this->global->STOCK_CALCULATE_ON_BILL = 0; $this->global->STOCK_CALCULATE_ON_VALIDATE_ORDER = 0; $this->global->STOCK_CALCULATE_ON_SHIPMENT = 1; @@ -491,59 +527,88 @@ class Conf $this->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER = 0; if (empty($this->reception->enabled)) { $this->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER = 1; - } - else { + } else { $this->global->STOCK_CALCULATE_ON_RECEPTION = 1; $this->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE = 0; } } // conf->currency - if (empty($this->global->MAIN_MONNAIE)) $this->global->MAIN_MONNAIE = 'EUR'; + if (empty($this->global->MAIN_MONNAIE)) { + $this->global->MAIN_MONNAIE = 'EUR'; + } $this->currency = $this->global->MAIN_MONNAIE; - if (empty($this->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY)) $this->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY = 30; // Less than 1 minutes to be sure + if (empty($this->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY)) { + $this->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY = 30; // Less than 1 minutes to be sure + } // conf->global->ACCOUNTING_MODE = Option des modules Comptabilites (simple ou expert). Defini le mode de calcul des etats comptables (CA,...) - if (empty($this->global->ACCOUNTING_MODE)) $this->global->ACCOUNTING_MODE = 'RECETTES-DEPENSES'; // By default. Can be 'RECETTES-DEPENSES' ou 'CREANCES-DETTES' + if (empty($this->global->ACCOUNTING_MODE)) { + $this->global->ACCOUNTING_MODE = 'RECETTES-DEPENSES'; // By default. Can be 'RECETTES-DEPENSES' ou 'CREANCES-DETTES' + } // By default, suppliers objects can be linked to all projects - if (!isset($this->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)) $this->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS = 1; + if (!isset($this->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)) { + $this->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS = 1; + } // By default we enable feature to bill time spent - if (!isset($this->global->PROJECT_BILL_TIME_SPENT)) $this->global->PROJECT_BILL_TIME_SPENT = 1; + if (!isset($this->global->PROJECT_BILL_TIME_SPENT)) { + $this->global->PROJECT_BILL_TIME_SPENT = 1; + } // MAIN_HTML_TITLE - if (!isset($this->global->MAIN_HTML_TITLE)) $this->global->MAIN_HTML_TITLE = 'noapp,thirdpartynameonly,contactnameonly,projectnameonly'; + if (!isset($this->global->MAIN_HTML_TITLE)) { + $this->global->MAIN_HTML_TITLE = 'noapp,thirdpartynameonly,contactnameonly,projectnameonly'; + } // conf->liste_limit = constante de taille maximale des listes - if (empty($this->global->MAIN_SIZE_LISTE_LIMIT)) $this->global->MAIN_SIZE_LISTE_LIMIT = 25; + if (empty($this->global->MAIN_SIZE_LISTE_LIMIT)) { + $this->global->MAIN_SIZE_LISTE_LIMIT = 25; + } $this->liste_limit = $this->global->MAIN_SIZE_LISTE_LIMIT; // conf->product->limit_size = constante de taille maximale des select de produit - if (!isset($this->global->PRODUIT_LIMIT_SIZE)) $this->global->PRODUIT_LIMIT_SIZE = 1000; + if (!isset($this->global->PRODUIT_LIMIT_SIZE)) { + $this->global->PRODUIT_LIMIT_SIZE = 1000; + } $this->product->limit_size = $this->global->PRODUIT_LIMIT_SIZE; // conf->theme et $this->css - if (empty($this->global->MAIN_THEME)) $this->global->MAIN_THEME = "eldy"; - if (!empty($this->global->MAIN_FORCETHEME)) $this->global->MAIN_THEME = $this->global->MAIN_FORCETHEME; + if (empty($this->global->MAIN_THEME)) { + $this->global->MAIN_THEME = "eldy"; + } + if (!empty($this->global->MAIN_FORCETHEME)) { + $this->global->MAIN_THEME = $this->global->MAIN_FORCETHEME; + } $this->theme = $this->global->MAIN_THEME; $this->css = "/theme/".$this->theme."/style.css.php"; // conf->email_from = email pour envoi par dolibarr des mails automatiques $this->email_from = "robot@example.com"; - if (!empty($this->global->MAIN_MAIL_EMAIL_FROM)) $this->email_from = $this->global->MAIN_MAIL_EMAIL_FROM; + if (!empty($this->global->MAIN_MAIL_EMAIL_FROM)) { + $this->email_from = $this->global->MAIN_MAIL_EMAIL_FROM; + } // conf->notification->email_from = email pour envoi par Dolibarr des notifications $this->notification->email_from = $this->email_from; - if (!empty($this->global->NOTIFICATION_EMAIL_FROM)) $this->notification->email_from = $this->global->NOTIFICATION_EMAIL_FROM; + if (!empty($this->global->NOTIFICATION_EMAIL_FROM)) { + $this->notification->email_from = $this->global->NOTIFICATION_EMAIL_FROM; + } // conf->mailing->email_from = email pour envoi par Dolibarr des mailings $this->mailing->email_from = $this->email_from; - if (!empty($this->global->MAILING_EMAIL_FROM)) $this->mailing->email_from = $this->global->MAILING_EMAIL_FROM; - if (!isset($this->global->MAIN_EMAIL_ADD_TRACK_ID)) $this->global->MAIN_EMAIL_ADD_TRACK_ID = 1; + if (!empty($this->global->MAILING_EMAIL_FROM)) { + $this->mailing->email_from = $this->global->MAILING_EMAIL_FROM; + } + if (!isset($this->global->MAIN_EMAIL_ADD_TRACK_ID)) { + $this->global->MAIN_EMAIL_ADD_TRACK_ID = 1; + } - if (!isset($this->global->MAIN_HIDE_WARNING_TO_ENCOURAGE_SMTP_SETUP)) $this->global->MAIN_HIDE_WARNING_TO_ENCOURAGE_SMTP_SETUP = 1; + if (!isset($this->global->MAIN_HIDE_WARNING_TO_ENCOURAGE_SMTP_SETUP)) { + $this->global->MAIN_HIDE_WARNING_TO_ENCOURAGE_SMTP_SETUP = 1; + } // Format for date (used by default when not found or not searched in lang) $this->format_date_short = "%d/%m/%Y"; // Format of day with PHP/C tags (strftime functions) @@ -558,54 +623,93 @@ class Conf $this->format_date_hour_text = "%d %B %Y %H:%M"; // Duration of workday - if (!isset($this->global->MAIN_DURATION_OF_WORKDAY)) $this->global->MAIN_DURATION_OF_WORKDAY = 86400; + if (!isset($this->global->MAIN_DURATION_OF_WORKDAY)) { + $this->global->MAIN_DURATION_OF_WORKDAY = 86400; + } // Limites decimales si non definie (peuvent etre egale a 0) - if (!isset($this->global->MAIN_MAX_DECIMALS_UNIT)) $this->global->MAIN_MAX_DECIMALS_UNIT = 5; - if (!isset($this->global->MAIN_MAX_DECIMALS_TOT)) $this->global->MAIN_MAX_DECIMALS_TOT = 2; - if (!isset($this->global->MAIN_MAX_DECIMALS_SHOWN)) $this->global->MAIN_MAX_DECIMALS_SHOWN = 8; + if (!isset($this->global->MAIN_MAX_DECIMALS_UNIT)) { + $this->global->MAIN_MAX_DECIMALS_UNIT = 5; + } + if (!isset($this->global->MAIN_MAX_DECIMALS_TOT)) { + $this->global->MAIN_MAX_DECIMALS_TOT = 2; + } + if (!isset($this->global->MAIN_MAX_DECIMALS_SHOWN)) { + $this->global->MAIN_MAX_DECIMALS_SHOWN = 8; + } // Default pdf option - if (!isset($this->global->MAIN_PDF_DASH_BETWEEN_LINES)) $this->global->MAIN_PDF_DASH_BETWEEN_LINES = 1; // use dash between lines - if (!isset($this->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) $this->global->PDF_ALLOW_HTML_FOR_FREE_TEXT = 1; // allow html content into free footer text + if (!isset($this->global->MAIN_PDF_DASH_BETWEEN_LINES)) { + $this->global->MAIN_PDF_DASH_BETWEEN_LINES = 1; // use dash between lines + } + if (!isset($this->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { + $this->global->PDF_ALLOW_HTML_FOR_FREE_TEXT = 1; // allow html content into free footer text + } // Default max file size for upload $this->maxfilesize = (empty($this->global->MAIN_UPLOAD_DOC) ? 0 : (int) $this->global->MAIN_UPLOAD_DOC * 1024); // By default, we propagate contacts - if (!isset($this->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN)) $this->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN = '*'; // Can be also '*' or '^(BILLING|SHIPPING|CUSTOMER|.*)$' (regex not yet implemented) + if (!isset($this->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN)) { + $this->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN = '*'; // Can be also '*' or '^(BILLING|SHIPPING|CUSTOMER|.*)$' (regex not yet implemented) + } // By default, we do not use the zip town table but the table of third parties - if (!isset($this->global->MAIN_USE_ZIPTOWN_DICTIONNARY)) $this->global->MAIN_USE_ZIPTOWN_DICTIONNARY = 0; + if (!isset($this->global->MAIN_USE_ZIPTOWN_DICTIONNARY)) { + $this->global->MAIN_USE_ZIPTOWN_DICTIONNARY = 0; + } // By default, we open card if one found - if (!isset($this->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE)) $this->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE = 1; + if (!isset($this->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE)) { + $this->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE = 1; + } // By default, we show state code in combo list - if (!isset($this->global->MAIN_SHOW_STATE_CODE)) $this->global->MAIN_SHOW_STATE_CODE = 1; + if (!isset($this->global->MAIN_SHOW_STATE_CODE)) { + $this->global->MAIN_SHOW_STATE_CODE = 1; + } // Use a SCA ready workflow with Stripe module (STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION by default if nothing defined) - if (!isset($this->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION) && empty($this->global->STRIPE_USE_NEW_CHECKOUT)) $this->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION = 1; + if (!isset($this->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION) && empty($this->global->STRIPE_USE_NEW_CHECKOUT)) { + $this->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION = 1; + } // Define list of limited modules (value must be key found for "name" property of module, so for example 'supplierproposal' for Module "Supplier Proposal" - if (!isset($this->global->MAIN_MODULES_FOR_EXTERNAL)) $this->global->MAIN_MODULES_FOR_EXTERNAL = 'user,societe,propal,commande,facture,categorie,supplierproposal,fournisseur,contact,projet,contrat,ficheinter,expedition,agenda,resource,adherent,blockedlog'; // '' means 'all'. Note that contact is added here as it should be a module later. - if (!empty($this->modules_parts['moduleforexternal'])) // Module part to include an external module into the MAIN_MODULES_FOR_EXTERNAL list - { - foreach ($this->modules_parts['moduleforexternal'] as $key=>$value) $this->global->MAIN_MODULES_FOR_EXTERNAL .= ",".$key; + if (!isset($this->global->MAIN_MODULES_FOR_EXTERNAL)) { + $this->global->MAIN_MODULES_FOR_EXTERNAL = 'user,societe,propal,commande,facture,categorie,supplierproposal,fournisseur,contact,projet,contrat,ficheinter,expedition,agenda,resource,adherent,blockedlog'; // '' means 'all'. Note that contact is added here as it should be a module later. + } + if (!empty($this->modules_parts['moduleforexternal'])) { // Module part to include an external module into the MAIN_MODULES_FOR_EXTERNAL list + foreach ($this->modules_parts['moduleforexternal'] as $key => $value) { + $this->global->MAIN_MODULES_FOR_EXTERNAL .= ",".$key; + } } // Enable select2 - if (empty($this->global->MAIN_USE_JQUERY_MULTISELECT) || $this->global->MAIN_USE_JQUERY_MULTISELECT == '1') $this->global->MAIN_USE_JQUERY_MULTISELECT = 'select2'; + if (empty($this->global->MAIN_USE_JQUERY_MULTISELECT) || $this->global->MAIN_USE_JQUERY_MULTISELECT == '1') { + $this->global->MAIN_USE_JQUERY_MULTISELECT = 'select2'; + } // Timeouts - if (empty($this->global->MAIN_USE_CONNECT_TIMEOUT)) $this->global->MAIN_USE_CONNECT_TIMEOUT = 10; - if (empty($this->global->MAIN_USE_RESPONSE_TIMEOUT)) $this->global->MAIN_USE_RESPONSE_TIMEOUT = 30; + if (empty($this->global->MAIN_USE_CONNECT_TIMEOUT)) { + $this->global->MAIN_USE_CONNECT_TIMEOUT = 10; + } + if (empty($this->global->MAIN_USE_RESPONSE_TIMEOUT)) { + $this->global->MAIN_USE_RESPONSE_TIMEOUT = 30; + } // Set default variable to calculate VAT as if option tax_mode was 0 (standard) - if (empty($this->global->TAX_MODE_SELL_PRODUCT)) $this->global->TAX_MODE_SELL_PRODUCT = 'invoice'; - if (empty($this->global->TAX_MODE_BUY_PRODUCT)) $this->global->TAX_MODE_BUY_PRODUCT = 'invoice'; - if (empty($this->global->TAX_MODE_SELL_SERVICE)) $this->global->TAX_MODE_SELL_SERVICE = 'payment'; - if (empty($this->global->TAX_MODE_BUY_SERVICE)) $this->global->TAX_MODE_BUY_SERVICE = 'payment'; + if (empty($this->global->TAX_MODE_SELL_PRODUCT)) { + $this->global->TAX_MODE_SELL_PRODUCT = 'invoice'; + } + if (empty($this->global->TAX_MODE_BUY_PRODUCT)) { + $this->global->TAX_MODE_BUY_PRODUCT = 'invoice'; + } + if (empty($this->global->TAX_MODE_SELL_SERVICE)) { + $this->global->TAX_MODE_SELL_SERVICE = 'payment'; + } + if (empty($this->global->TAX_MODE_BUY_SERVICE)) { + $this->global->TAX_MODE_BUY_SERVICE = 'payment'; + } // Delay before warnings // Avoid strict errors. TODO: Replace xxx->warning_delay with a property ->warning_delay_xxx @@ -616,8 +720,7 @@ class Conf if (isset($this->agenda)) { $this->agenda->warning_delay = (isset($this->global->MAIN_DELAY_ACTIONS_TODO) ? $this->global->MAIN_DELAY_ACTIONS_TODO : 7) * 86400; } - if (isset($this->projet)) - { + if (isset($this->projet)) { $this->projet->warning_delay = (isset($this->global->MAIN_DELAY_PROJECT_TO_CLOSE) ? $this->global->MAIN_DELAY_PROJECT_TO_CLOSE : 7) * 86400; $this->projet->task = new StdClass(); $this->projet->task->warning_delay = (isset($this->global->MAIN_DELAY_TASKS_TODO) ? $this->global->MAIN_DELAY_TASKS_TODO : 7) * 86400; @@ -644,9 +747,9 @@ class Conf if (isset($this->contrat)) { $this->contrat->services = new stdClass(); $this->contrat->services->inactifs = new stdClass(); - $this->contrat->services->expires = new stdClass(); - $this->contrat->services->inactifs->warning_delay = (isset($this->global->MAIN_DELAY_NOT_ACTIVATED_SERVICES) ? $this->global->MAIN_DELAY_NOT_ACTIVATED_SERVICES : 0) * 86400; - $this->contrat->services->expires->warning_delay = (isset($this->global->MAIN_DELAY_RUNNING_SERVICES) ? $this->global->MAIN_DELAY_RUNNING_SERVICES : 0) * 86400; + $this->contrat->services->expires = new stdClass(); + $this->contrat->services->inactifs->warning_delay = (isset($this->global->MAIN_DELAY_NOT_ACTIVATED_SERVICES) ? $this->global->MAIN_DELAY_NOT_ACTIVATED_SERVICES : 0) * 86400; + $this->contrat->services->expires->warning_delay = (isset($this->global->MAIN_DELAY_RUNNING_SERVICES) ? $this->global->MAIN_DELAY_RUNNING_SERVICES : 0) * 86400; } if (isset($this->commande)) { $this->bank->rappro = new stdClass(); @@ -665,37 +768,57 @@ class Conf $this->holiday->approve->warning_delay = (isset($this->global->MAIN_DELAY_HOLIDAYS) ? $this->global->MAIN_DELAY_HOLIDAYS : 0) * 86400; } - if (!empty($this->global->PRODUIT_MULTIPRICES) && empty($this->global->PRODUIT_MULTIPRICES_LIMIT)) - { + if (!empty($this->global->PRODUIT_MULTIPRICES) && empty($this->global->PRODUIT_MULTIPRICES_LIMIT)) { $this->global->PRODUIT_MULTIPRICES_LIMIT = 5; } // For modules that want to disable top or left menu - if (!empty($this->global->MAIN_HIDE_TOP_MENU)) $this->dol_hide_topmenu = $this->global->MAIN_HIDE_TOP_MENU; - if (!empty($this->global->MAIN_HIDE_LEFT_MENU)) $this->dol_hide_leftmenu = $this->global->MAIN_HIDE_LEFT_MENU; + if (!empty($this->global->MAIN_HIDE_TOP_MENU)) { + $this->dol_hide_topmenu = $this->global->MAIN_HIDE_TOP_MENU; + } + if (!empty($this->global->MAIN_HIDE_LEFT_MENU)) { + $this->dol_hide_leftmenu = $this->global->MAIN_HIDE_LEFT_MENU; + } - if (empty($this->global->MAIN_SIZE_SHORTLIST_LIMIT)) $this->global->MAIN_SIZE_SHORTLIST_LIMIT = 3; + if (empty($this->global->MAIN_SIZE_SHORTLIST_LIMIT)) { + $this->global->MAIN_SIZE_SHORTLIST_LIMIT = 3; + } - if (!isset($this->global->THEME_HIDE_BORDER_ON_INPUT)) $this->global->THEME_HIDE_BORDER_ON_INPUT = 0; + if (!isset($this->global->THEME_HIDE_BORDER_ON_INPUT)) { + $this->global->THEME_HIDE_BORDER_ON_INPUT = 0; + } // Save inconsistent option - if (empty($this->global->AGENDA_USE_EVENT_TYPE) && (!isset($this->global->AGENDA_DEFAULT_FILTER_TYPE) || $this->global->AGENDA_DEFAULT_FILTER_TYPE == 'AC_NON_AUTO')) - { + if (empty($this->global->AGENDA_USE_EVENT_TYPE) && (!isset($this->global->AGENDA_DEFAULT_FILTER_TYPE) || $this->global->AGENDA_DEFAULT_FILTER_TYPE == 'AC_NON_AUTO')) { $this->global->AGENDA_DEFAULT_FILTER_TYPE = '0'; // 'AC_NON_AUTO' does not exists when AGENDA_DEFAULT_FILTER_TYPE is not on. } - if (!isset($this->global->MAIN_JS_GRAPH)) $this->global->MAIN_JS_GRAPH = 'chart'; // Use chart.js library + if (!isset($this->global->MAIN_JS_GRAPH)) { + $this->global->MAIN_JS_GRAPH = 'chart'; // Use chart.js library + } - if (empty($this->global->MAIN_MODULE_DOLISTORE_API_SRV)) $this->global->MAIN_MODULE_DOLISTORE_API_SRV = 'https://www.dolistore.com'; - if (empty($this->global->MAIN_MODULE_DOLISTORE_API_KEY)) $this->global->MAIN_MODULE_DOLISTORE_API_KEY = 'dolistorecatalogpublickey1234567'; + if (empty($this->global->MAIN_MODULE_DOLISTORE_API_SRV)) { + $this->global->MAIN_MODULE_DOLISTORE_API_SRV = 'https://www.dolistore.com'; + } + if (empty($this->global->MAIN_MODULE_DOLISTORE_API_KEY)) { + $this->global->MAIN_MODULE_DOLISTORE_API_KEY = 'dolistorecatalogpublickey1234567'; + } // If we are in develop mode, we activate the option MAIN_SECURITY_CSRF_WITH_TOKEN to 1 if not already defined. - if (!isset($this->global->MAIN_SECURITY_CSRF_WITH_TOKEN) && $this->global->MAIN_FEATURES_LEVEL >= 2) $this->global->MAIN_SECURITY_CSRF_WITH_TOKEN = 1; + if (!isset($this->global->MAIN_SECURITY_CSRF_WITH_TOKEN) && $this->global->MAIN_FEATURES_LEVEL >= 2) { + $this->global->MAIN_SECURITY_CSRF_WITH_TOKEN = 1; + } - if (defined('MAIN_ANTIVIRUS_COMMAND')) $this->global->MAIN_ANTIVIRUS_COMMAND = constant('MAIN_ANTIVIRUS_COMMAND'); - if (defined('MAIN_ANTIVIRUS_PARAM')) $this->global->MAIN_ANTIVIRUS_PARAM = constant('MAIN_ANTIVIRUS_PARAM'); + if (defined('MAIN_ANTIVIRUS_COMMAND')) { + $this->global->MAIN_ANTIVIRUS_COMMAND = constant('MAIN_ANTIVIRUS_COMMAND'); + } + if (defined('MAIN_ANTIVIRUS_PARAM')) { + $this->global->MAIN_ANTIVIRUS_PARAM = constant('MAIN_ANTIVIRUS_PARAM'); + } - if (!empty($this->global->MAIN_TZUSERINPUTKEY)) $this->tzuserinputkey = $this->global->MAIN_TZUSERINPUTKEY; // 'tzserver' or 'tzuserrel' + if (!empty($this->global->MAIN_TZUSERINPUTKEY)) { + $this->tzuserinputkey = $this->global->MAIN_TZUSERINPUTKEY; // 'tzserver' or 'tzuserrel' + } if (!empty($this->global->PRODUIT_AUTOFILL_DESC)) { $this->global->MAIN_NO_CONCAT_DESCRIPTION = 1; @@ -703,18 +826,37 @@ class Conf unset($this->global->MAIN_NO_CONCAT_DESCRIPTION); } - // For backward compatibility - if (isset($this->product)) $this->produit = $this->product; - if (isset($this->facture)) $this->invoice = $this->facture; - if (isset($this->commande)) $this->order = $this->commande; - if (isset($this->contrat)) $this->contract = $this->contrat; - if (isset($this->categorie)) $this->category = $this->categorie; - if (isset($this->project)) $this->project = $this->projet; + // product is new use + if (isset($this->product)) { + // For backward compatibility + $this->produit = $this->product; + } + // invoice is new use, facture is old use still initialised + if (isset($this->facture)) { + $this->invoice = $this->facture; + } + // order is new use, commande is old use still initialised + if (isset($this->commande)) { + $this->order = $this->commande; + } + // contract is new use, contrat is old use still initialised + if (isset($this->contrat)) { + $this->contract = $this->contrat; + } + // category is new use, categorie is old use still initialised + if (isset($this->categorie)) { + $this->category = $this->categorie; + } + // project is new use, projet is old use still initialised + if (isset($this->projet) && !isset($this->project)) { + $this->project = $this->projet; + } // Object $mc - if (!defined('NOREQUIREMC') && !empty($this->multicompany->enabled)) - { - if (is_object($mc)) $mc->setValues($this); + if (!defined('NOREQUIREMC') && !empty($this->multicompany->enabled)) { + if (is_object($mc)) { + $mc->setValues($this); + } } if (!empty($this->syslog->enabled)) { diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index ad7d93506f4..45018cb1d8f 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -59,15 +59,19 @@ class CoreObject extends CommonObject $this->datec = 0; $this->tms = 0; - if (!empty($this->fields)) - { - foreach ($this->fields as $field=>$info) - { - if ($this->isDate($info)) $this->{$field} = time(); - elseif ($this->isArray($info)) $this->{$field} = array(); - elseif ($this->isInt($info)) $this->{$field} = (int) 0; - elseif ($this->isFloat($info)) $this->{$field} = (double) 0; - else $this->{$field} = ''; + if (!empty($this->fields)) { + foreach ($this->fields as $field => $info) { + if ($this->isDate($info)) { + $this->{$field} = time(); + } elseif ($this->isArray($info)) { + $this->{$field} = array(); + } elseif ($this->isInt($info)) { + $this->{$field} = (int) 0; + } elseif ($this->isFloat($info)) { + $this->{$field} = (double) 0; + } else { + $this->{$field} = ''; + } } $this->to_delete = false; @@ -88,8 +92,7 @@ class CoreObject extends CommonObject */ private function checkFieldType($field, $type) { - if (isset($this->fields[$field]) && method_exists($this, 'is_'.$type)) - { + if (isset($this->fields[$field]) && method_exists($this, 'is_'.$type)) { return $this->{'is_'.$type}($this->fields[$field]); } else { return false; @@ -107,7 +110,9 @@ class CoreObject extends CommonObject { $res = $this->fetchCommon($id); if ($res > 0) { - if ($loadChild) $this->fetchChild(); + if ($loadChild) { + $this->fetchChild(); + } } return $res; @@ -125,11 +130,11 @@ class CoreObject extends CommonObject */ public function addChild($tabName, $id = 0, $key = 'id', $try_to_load = false) { - if (!empty($id)) - { - foreach ($this->{$tabName} as $k=>&$object) - { - if ($object->{$key} === $id) return $k; + if (!empty($id)) { + foreach ($this->{$tabName} as $k => &$object) { + if ($object->{$key} === $id) { + return $k; + } } } @@ -137,8 +142,7 @@ class CoreObject extends CommonObject $className = ucfirst($tabName); $this->{$tabName}[$k] = new $className($this->db); - if ($id > 0 && $key === 'id' && $try_to_load) - { + if ($id > 0 && $key === 'id' && $try_to_load) { $this->{$tabName}[$k]->fetch($id); } @@ -156,10 +160,8 @@ class CoreObject extends CommonObject */ public function removeChild($tabName, $id, $key = 'id') { - foreach ($this->{$tabName} as &$object) - { - if ($object->{$key} == $id) - { + foreach ($this->{$tabName} as &$object) { + if ($object->{$key} == $id) { $object->to_delete = true; return true; } @@ -175,10 +177,8 @@ class CoreObject extends CommonObject */ public function fetchChild() { - if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) - { - foreach ($this->childtables as &$childTable) - { + if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) { + foreach ($this->childtables as &$childTable) { $className = ucfirst($childTable); $this->{$className} = array(); @@ -186,10 +186,8 @@ class CoreObject extends CommonObject $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$childTable.' WHERE '.$this->fk_element.' = '.$this->id; $res = $this->db->query($sql); - if ($res) - { - while ($obj = $this->db->fetch_object($res)) - { + if ($res) { + while ($obj = $this->db->fetch_object($res)) { $o = new $className($this->db); $o->fetch($obj->rowid); @@ -210,19 +208,17 @@ class CoreObject extends CommonObject */ public function saveChild(User &$user) { - if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) - { - foreach ($this->childtables as &$childTable) - { + if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) { + foreach ($this->childtables as &$childTable) { $className = ucfirst($childTable); - if (!empty($this->{$className})) - { - foreach ($this->{$className} as $i => &$object) - { + if (!empty($this->{$className})) { + foreach ($this->{$className} as $i => &$object) { $object->{$this->fk_element} = $this->id; $object->update($user); - if ($this->unsetChildDeleted && isset($object->to_delete) && $object->to_delete == true) unset($this->{$className}[$i]); + if ($this->unsetChildDeleted && isset($object->to_delete) && $object->to_delete == true) { + unset($this->{$className}[$i]); + } } } } @@ -238,26 +234,30 @@ class CoreObject extends CommonObject */ public function update(User &$user) { - if (empty($this->id)) return $this->create($user); // To test, with that, no need to test on high level object, the core decide it, update just needed - elseif (isset($this->to_delete) && $this->to_delete == true) return $this->delete($user); + if (empty($this->id)) { + return $this->create($user); // To test, with that, no need to test on high level object, the core decide it, update just needed + } elseif (isset($this->to_delete) && $this->to_delete == true) { + return $this->delete($user); + } $error = 0; $this->db->begin(); $res = $this->updateCommon($user); - if ($res) - { + if ($res) { $result = $this->call_trigger(strtoupper($this->element).'_UPDATE', $user); - if ($result < 0) $error++; - else $this->saveChild($user); + if ($result < 0) { + $error++; + } else { + $this->saveChild($user); + } } else { $error++; $this->error = $this->db->lasterror(); $this->errors[] = $this->error; } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return $this->id; } else { @@ -274,27 +274,30 @@ class CoreObject extends CommonObject */ public function create(User $user) { - if ($this->id > 0) return $this->update($user); + if ($this->id > 0) { + return $this->update($user); + } $error = 0; $this->db->begin(); $res = $this->createCommon($user); - if ($res) - { + if ($res) { $this->id = $this->db->last_insert_id($this->table_element); $result = $this->call_trigger(strtoupper($this->element).'_CREATE', $user); - if ($result < 0) $error++; - else $this->saveChild($user); + if ($result < 0) { + $error++; + } else { + $this->saveChild($user); + } } else { $error++; $this->error = $this->db->lasterror(); $this->errors[] = $this->error; } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return $this->id; } else { @@ -311,26 +314,25 @@ class CoreObject extends CommonObject */ public function delete(User &$user) { - if ($this->id <= 0) return 0; + if ($this->id <= 0) { + return 0; + } $error = 0; $this->db->begin(); $result = $this->call_trigger(strtoupper($this->element).'_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } - if (!$error) - { + if (!$error) { $this->deleteCommon($user); - if ($this->withChild && !empty($this->childtables)) - { - foreach ($this->childtables as &$childTable) - { + if ($this->withChild && !empty($this->childtables)) { + foreach ($this->childtables as &$childTable) { $className = ucfirst($childTable); - if (!empty($this->{$className})) - { - foreach ($this->{$className} as &$object) - { + if (!empty($this->{$className})) { + foreach ($this->{$className} as &$object) { $object->delete($user); } } @@ -338,8 +340,7 @@ class CoreObject extends CommonObject } } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -360,8 +361,9 @@ class CoreObject extends CommonObject */ public function getDate($field, $format = '') { - if (empty($this->{$field})) return ''; - else { + if (empty($this->{$field})) { + return ''; + } else { return dol_print_date($this->{$field}, $format); } } @@ -375,8 +377,7 @@ class CoreObject extends CommonObject */ public function setDate($field, $date) { - if (empty($date)) - { + if (empty($date)) { $this->{$field} = 0; } else { require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; @@ -395,13 +396,10 @@ class CoreObject extends CommonObject */ public function setValues(&$Tab) { - foreach ($Tab as $key => $value) - { - if ($this->checkFieldType($key, 'date')) - { + foreach ($Tab as $key => $value) { + if ($this->checkFieldType($key, 'date')) { $this->setDate($key, $value); - } elseif ($this->checkFieldType($key, 'float')) - { + } elseif ($this->checkFieldType($key, 'float')) { $this->{$key} = (double) price2num($value); } elseif ($this->checkFieldType($key, 'int')) { $this->{$key} = (int) price2num($value); diff --git a/htdocs/core/class/cproductnature.class.php b/htdocs/core/class/cproductnature.class.php index eb16cff53ea..6c3a1f7bb9d 100644 --- a/htdocs/core/class/cproductnature.class.php +++ b/htdocs/core/class/cproductnature.class.php @@ -116,7 +116,7 @@ class CProductNature // extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::create", LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); // Commit or rollback if (!$resql) { @@ -150,17 +150,19 @@ class CProductNature // extends CommonObject $sql .= " t.active"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; $sql_where = array(); - if ($id) $sql_where[] = " t.rowid = ".$id; - if ($code >= 0) $sql_where[] = " t.code = ".((int) $code); + if ($id) { + $sql_where[] = " t.rowid = ".((int) $id); + } + if ($code >= 0) { + $sql_where[] = " t.code = ".((int) $code); + } if (count($sql_where) > 0) { $sql .= ' WHERE '.implode(' AND ', $sql_where); } $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; @@ -172,7 +174,7 @@ class CProductNature // extends CommonObject return 1; } else { - $this->error = "Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -232,8 +234,7 @@ class CProductNature // extends CommonObject $this->records = array(); $num = $this->db->num_rows($resql); if ($num > 0) { - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $record = new self($this->db); $record->id = $obj->rowid; @@ -289,13 +290,13 @@ class CProductNature // extends CommonObject } - /** - * Delete object in database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + /** + * Delete object in database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function delete($user, $notrigger = 0) { global $conf, $langs; diff --git a/htdocs/core/class/cstate.class.php b/htdocs/core/class/cstate.class.php index 75ef9cc7f77..2b9b1d6880e 100644 --- a/htdocs/core/class/cstate.class.php +++ b/htdocs/core/class/cstate.class.php @@ -92,9 +92,15 @@ class Cstate // extends CommonObject $error = 0; // Clean parameters - if (isset($this->code_departement)) $this->code_departement = trim($this->code_departement); - if (isset($this->nom)) $this->nom = trim($this->nom); - if (isset($this->active)) $this->active = trim($this->active); + if (isset($this->code_departement)) { + $this->code_departement = trim($this->code_departement); + } + if (isset($this->nom)) { + $this->nom = trim($this->nom); + } + if (isset($this->active)) { + $this->active = trim($this->active); + } // Check parameters // Put here code to add control on parameters values @@ -114,19 +120,20 @@ class Cstate // extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::create", LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_departements"); } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -155,15 +162,16 @@ class Cstate // extends CommonObject $sql .= " t.nom,"; $sql .= " t.active"; $sql .= " FROM ".MAIN_DB_PREFIX."c_departements as t"; - if ($id) $sql .= " WHERE t.rowid = ".$id; - elseif ($code) $sql .= " WHERE t.code_departement = '".$this->db->escape($code)."'"; + if ($id) { + $sql .= " WHERE t.rowid = ".((int) $id); + } elseif ($code) { + $sql .= " WHERE t.code_departement = '".$this->db->escape($code)."'"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -177,7 +185,7 @@ class Cstate // extends CommonObject return 1; } else { - $this->error = "Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -196,9 +204,15 @@ class Cstate // extends CommonObject $error = 0; // Clean parameters - if (isset($this->code_departement)) $this->code_departement = trim($this->code_departement); - if (isset($this->nom)) $this->nom = trim($this->nom); - if (isset($this->active)) $this->active = trim($this->active); + if (isset($this->code_departement)) { + $this->code_departement = trim($this->code_departement); + } + if (isset($this->nom)) { + $this->nom = trim($this->nom); + } + if (isset($this->active)) { + $this->active = trim($this->active); + } // Check parameters @@ -209,13 +223,16 @@ class Cstate // extends CommonObject $sql .= " code_departement=".(isset($this->code_departement) ? "'".$this->db->escape($this->code_departement)."'" : "null").","; $sql .= " nom=".(isset($this->nom) ? "'".$this->db->escape($this->nom)."'" : "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(); } + if (!$resql) { + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback if ($error) { @@ -231,32 +248,33 @@ class Cstate // extends CommonObject } } - /** - * Delete object in database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + /** + * Delete object in database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function delete($user, $notrigger = 0) { global $conf, $langs; $error = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_departements"; - $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(); } + if (!$resql) { + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } diff --git a/htdocs/core/class/ctypent.class.php b/htdocs/core/class/ctypent.class.php index fccdec72ab6..01a6eb5e697 100644 --- a/htdocs/core/class/ctypent.class.php +++ b/htdocs/core/class/ctypent.class.php @@ -83,11 +83,21 @@ class Ctypent // extends CommonObject // Clean parameters - if (isset($this->id)) $this->id = trim($this->id); - if (isset($this->code)) $this->code = trim($this->code); - if (isset($this->libelle)) $this->libelle = trim($this->libelle); - if (isset($this->active)) $this->active = trim($this->active); - if (isset($this->module)) $this->module = trim($this->module); + if (isset($this->id)) { + $this->id = trim($this->id); + } + if (isset($this->code)) { + $this->code = trim($this->code); + } + if (isset($this->libelle)) { + $this->libelle = trim($this->libelle); + } + if (isset($this->active)) { + $this->active = trim($this->active); + } + if (isset($this->module)) { + $this->module = trim($this->module); + } @@ -117,20 +127,20 @@ class Ctypent // extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::create", LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_typent"); } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -162,15 +172,17 @@ class Ctypent // extends CommonObject $sql .= " t.active,"; $sql .= " t.module"; $sql .= " FROM ".MAIN_DB_PREFIX."c_typent as t"; - if ($id) $sql .= " WHERE t.id = ".$id; - elseif ($code) $sql .= " WHERE t.code = '".$this->db->escape($code)."'"; - elseif ($label) $sql .= " WHERE t.libelle = '".$this->db->escape($label)."'"; + if ($id) { + $sql .= " WHERE t.id = ".$id; + } elseif ($code) { + $sql .= " WHERE t.code = '".$this->db->escape($code)."'"; + } elseif ($label) { + $sql .= " WHERE t.libelle = '".$this->db->escape($label)."'"; + } $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->id; @@ -184,7 +196,7 @@ class Ctypent // extends CommonObject return 1; } else { - $this->error = "Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -203,10 +215,18 @@ class Ctypent // extends CommonObject $error = 0; // Clean parameters - if (isset($this->code)) $this->code = trim($this->code); - if (isset($this->libelle)) $this->libelle = trim($this->libelle); - if (isset($this->active)) $this->active = trim($this->active); - if (isset($this->module)) $this->module = trim($this->module); + if (isset($this->code)) { + $this->code = trim($this->code); + } + if (isset($this->libelle)) { + $this->libelle = trim($this->libelle); + } + if (isset($this->active)) { + $this->active = trim($this->active); + } + if (isset($this->module)) { + $this->module = trim($this->module); + } // Check parameters @@ -224,13 +244,14 @@ class Ctypent // extends CommonObject dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -243,13 +264,13 @@ class Ctypent // extends CommonObject } - /** - * Delete object in database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + /** + * Delete object in database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function delete($user, $notrigger = 0) { global $conf, $langs; @@ -262,13 +283,14 @@ class Ctypent // extends CommonObject dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } diff --git a/htdocs/core/class/ctyperesource.class.php b/htdocs/core/class/ctyperesource.class.php index 9d1e5c53de1..6ba04c044e9 100644 --- a/htdocs/core/class/ctyperesource.class.php +++ b/htdocs/core/class/ctyperesource.class.php @@ -172,9 +172,13 @@ class Ctyperesource $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if ($id) $sql .= " WHERE t.id = ".$id; - elseif ($code) $sql .= " WHERE t.code = '".$this->db->escape($code)."'"; - elseif ($label) $sql .= " WHERE t.label = '".$this->db->escape($label)."'"; + if ($id) { + $sql .= " WHERE t.id = ".$id; + } elseif ($code) { + $sql .= " WHERE t.code = '".$this->db->escape($code)."'"; + } elseif ($label) { + $sql .= " WHERE t.label = '".$this->db->escape($label)."'"; + } $resql = $this->db->query($sql); @@ -316,7 +320,7 @@ class Ctyperesource $sql .= ' active = '.(isset($this->active) ? $this->active : "null"); - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); $this->db->begin(); @@ -379,7 +383,7 @@ class Ctyperesource if (!$error) { $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) { diff --git a/htdocs/core/class/cunits.class.php b/htdocs/core/class/cunits.class.php index c94919eb1dc..ed3981d243d 100644 --- a/htdocs/core/class/cunits.class.php +++ b/htdocs/core/class/cunits.class.php @@ -86,13 +86,27 @@ class CUnits // extends CommonObject // Clean parameters - if (isset($this->id)) $this->id = (int) $this->id; - if (isset($this->code)) $this->code = trim($this->code); - if (isset($this->label)) $this->libelle = trim($this->label); - if (isset($this->short_label)) $this->libelle = trim($this->short_label); - if (isset($this->unit_type)) $this->active = trim($this->unit_type); - if (isset($this->active)) $this->active = trim($this->active); - if (isset($this->scale)) $this->scale = trim($this->scale); + if (isset($this->id)) { + $this->id = (int) $this->id; + } + if (isset($this->code)) { + $this->code = trim($this->code); + } + if (isset($this->label)) { + $this->libelle = trim($this->label); + } + if (isset($this->short_label)) { + $this->libelle = trim($this->short_label); + } + if (isset($this->unit_type)) { + $this->active = trim($this->unit_type); + } + if (isset($this->active)) { + $this->active = trim($this->active); + } + if (isset($this->scale)) { + $this->scale = trim($this->scale); + } // Check parameters // Put here code to add control on parameters values @@ -116,20 +130,20 @@ class CUnits // extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::create", LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_units"); } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -166,19 +180,25 @@ class CUnits // extends CommonObject $sql .= " t.active"; $sql .= " FROM ".MAIN_DB_PREFIX."c_units as t"; $sql_where = array(); - if ($id) $sql_where[] = " t.rowid = ".$id; - if ($unit_type) $sql_where[] = " t.unit_type = '".$this->db->escape($unit_type)."'"; - if ($code) $sql_where[] = " t.code = '".$this->db->escape($code)."'"; - if ($short_label) $sql_where[] = " t.short_label = '".$this->db->escape($short_label)."'"; + if ($id) { + $sql_where[] = " t.rowid = ".((int) $id); + } + if ($unit_type) { + $sql_where[] = " t.unit_type = '".$this->db->escape($unit_type)."'"; + } + if ($code) { + $sql_where[] = " t.code = '".$this->db->escape($code)."'"; + } + if ($short_label) { + $sql_where[] = " t.short_label = '".$this->db->escape($short_label)."'"; + } if (count($sql_where) > 0) { $sql .= ' WHERE '.implode(' AND ', $sql_where); } $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; @@ -194,7 +214,7 @@ class CUnits // extends CommonObject return 1; } else { - $this->error = "Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -295,12 +315,24 @@ class CUnits // extends CommonObject $error = 0; // Clean parameters - if (isset($this->code)) $this->code = trim($this->code); - if (isset($this->label)) $this->libelle = trim($this->label); - if (isset($this->short_label)) $this->libelle = trim($this->short_label); - if (isset($this->unit_type)) $this->libelle = trim($this->unit_type); - if (isset($this->scale)) $this->scale = trim($this->scale); - if (isset($this->active)) $this->active = trim($this->active); + if (isset($this->code)) { + $this->code = trim($this->code); + } + if (isset($this->label)) { + $this->libelle = trim($this->label); + } + if (isset($this->short_label)) { + $this->libelle = trim($this->short_label); + } + if (isset($this->unit_type)) { + $this->libelle = trim($this->unit_type); + } + if (isset($this->scale)) { + $this->scale = trim($this->scale); + } + if (isset($this->active)) { + $this->active = trim($this->active); + } // Check parameters // Put here code to add control on parameters values @@ -313,19 +345,20 @@ class CUnits // extends CommonObject $sql .= " unit_type=".(isset($this->unit_type) ? "'".$this->db->escape($this->unit_type)."'" : "null").","; $sql .= " scale=".(isset($this->scale) ? "'".$this->db->escape($this->scale)."'" : "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(); } + if (!$resql) { + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -338,32 +371,33 @@ class CUnits // extends CommonObject } - /** - * Delete object in database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + /** + * Delete object in database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function delete($user, $notrigger = 0) { global $conf, $langs; $error = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_units"; - $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(); } + if (!$resql) { + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -414,8 +448,7 @@ class CUnits // extends CommonObject if ($fk_new_unit != 0) { // Calcul en unité de base $scaleUnitPow = $this->scaleOfUnitPow($fk_new_unit); - if (!empty($scaleUnitPow)) - { + if (!empty($scaleUnitPow)) { // convert to new unit $value = $value / $scaleUnitPow; } diff --git a/htdocs/core/class/defaultvalues.class.php b/htdocs/core/class/defaultvalues.class.php new file mode 100644 index 00000000000..da9d0ad9f19 --- /dev/null +++ b/htdocs/core/class/defaultvalues.class.php @@ -0,0 +1,350 @@ + + * Copyright (C) 2021 Florian HENRY + * + * 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/code/class/defaultvalues.class.php + * \brief This file is a CRUD class file for DefaultValues (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +/** + * Class for MyObject + */ +class DefaultValues extends CommonObject +{ + /** + * @var string ID to identify managed object. + */ + public $element = 'defaultvalues'; + + /** + * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management. + */ + public $table_element = 'default_values'; + + /** + * @var int Does this object support multicompany module ? + * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table + */ + public $ismultientitymanaged = 1; + + /** + * @var int Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 0; + + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = ''; + + /** + * '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. + * '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) + * '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_...). + * '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' 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 + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>15, 'index'=>1), + 'type' =>array('type'=>'varchar(10)', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'position'=>20), + 'user_id' =>array('type'=>'integer', 'label'=>'Userid', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25), + 'page' =>array('type'=>'varchar(255)', 'label'=>'RelativeURL', 'enabled'=>1, 'visible'=>-1, 'position'=>30), + 'param' =>array('type'=>'varchar(255)', 'label'=>'Field', 'enabled'=>1, 'visible'=>-1, 'position'=>35), + 'value' =>array('type'=>'varchar(128)', 'label'=>'Value', 'enabled'=>1, 'visible'=>-1, 'position'=>40), + ); + + /** + * @var int ID + */ + public $rowid; + + /** + * @var int Entity + */ + public $entity; + + /** + * @var string Type + */ + public $type; + + /** + * @var int User Id + */ + public $user_id; + + /** + * @var string Page + */ + public $page; + + /** + * @var string Param + */ + public $param; + + /** + * @var string Value + */ + public $value; + // END MODULEBUILDER PROPERTIES + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf, $langs; + + $this->db = $db; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; + + // Unset fields that are disabled + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { + unset($this->fields[$key]); + } + } + + // Translate some data of arrayofkeyval + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); + } + } + } + } + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + return $this->createCommon($user, $notrigger); + } + + /** + * Clone an object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return mixed New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $langs, $extrafields; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $result = $object->fetchCommon($fromid); + + // Reset some properties + unset($object->id); + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->error = $object->error; + $this->errors = $object->errors; + } + + unset($object->context['createfromclone']); + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id) + { + $result = $this->fetchCommon($id, null); + return $result; + } + + /** + * Load list of objects in memory from the database. + * + * @param string $sortorder Sort Order + * @param string $sortfield Sort field + * @param int $limit limit + * @param int $offset Offset + * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...) + * @param string $filtermode Filter mode (AND or OR) + * @return array|int int <0 if KO, array of pages if OK + */ + public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') + { + global $conf; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $records = array(); + + $sql = 'SELECT '; + $sql .= $this->getFieldList(); + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + $sql .= ' WHERE 1 = 1'; + // Manage filter + $sqlwhere = array(); + if (count($filter) > 0) { + foreach ($filter as $key => $value) { + if ($key == 't.rowid' || ($key == 't.entity' && !is_array($value)) || ($key == 't.user_id' && !is_array($value))) { + $sqlwhere[] = $key.'='.$value; + } elseif (isset($this->fields[$key]) && in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) { + $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\''; + } elseif ($key == 't.page' || $key == 't.param' || $key == 't.type') { + $sqlwhere[] = $key.' = \''.$this->db->escape($value).'\''; + } elseif ($key == 'customsql') { + $sqlwhere[] = $value; + } elseif (is_array($value)) { + $sqlwhere[] = $key.' IN ('.implode(',', $value).')'; + } else { + $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; + } + } + } + if (count($sqlwhere) > 0) { + $sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')'; + } + + if (!empty($sortfield)) { + $sql .= $this->db->order($sortfield, $sortorder); + } + if (!empty($limit)) { + $sql .= ' '.$this->db->plimit($limit, $offset); + } + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < ($limit ? min($limit, $num) : $num)) { + $obj = $this->db->fetch_object($resql); + + $record = new self($this->db); + $record->setVarsFromFetchObj($obj); + + $records[$record->id] = $record; + + $i++; + } + $this->db->free($resql); + + return $records; + } else { + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); + + return -1; + } + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + return $this->deleteCommon($user, $notrigger); + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->initAsSpecimenCommon(); + } +} diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index 9f901ed3452..310f141fc1c 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -126,8 +126,7 @@ class DiscountAbsolute global $conf; // Check parameters - if (!$rowid && !$fk_facture_source && !$fk_invoice_supplier_source) - { + if (!$rowid && !$fk_facture_source && !$fk_invoice_supplier_source) { $this->error = 'ErrorBadParameters'; return -1; } @@ -144,16 +143,20 @@ class DiscountAbsolute $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON sr.fk_facture_source = f.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fsup ON sr.fk_invoice_supplier_source = fsup.rowid"; $sql .= " WHERE sr.entity IN (".getEntity('invoice').")"; - if ($rowid) $sql .= " AND sr.rowid=".$rowid; - if ($fk_facture_source) $sql .= " AND sr.fk_facture_source=".$fk_facture_source; - if ($fk_invoice_supplier_source) $sql .= " AND sr.fk_invoice_supplier_source=".$fk_invoice_supplier_source; + if ($rowid) { + $sql .= " AND sr.rowid=".$rowid; + } + if ($fk_facture_source) { + $sql .= " AND sr.fk_facture_source=".$fk_facture_source; + } + if ($fk_invoice_supplier_source) { + $sql .= " AND sr.fk_invoice_supplier_source=".$fk_invoice_supplier_source; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -219,21 +222,28 @@ class DiscountAbsolute $this->multicurrency_amount_tva = price2num($this->multicurrency_amount_tva); $this->multicurrency_amount_ttc = price2num($this->multicurrency_amount_ttc); - if (empty($this->multicurrency_amount_ht)) $this->multicurrency_amount_ht = 0; - if (empty($this->multicurrency_amount_tva)) $this->multicurrency_amount_tva = 0; - if (empty($this->multicurrency_amount_ttc)) $this->multicurrency_amount_ttc = 0; + if (empty($this->multicurrency_amount_ht)) { + $this->multicurrency_amount_ht = 0; + } + if (empty($this->multicurrency_amount_tva)) { + $this->multicurrency_amount_tva = 0; + } + if (empty($this->multicurrency_amount_ttc)) { + $this->multicurrency_amount_ttc = 0; + } + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } // Check parameters - if (empty($this->description)) - { + if (empty($this->description)) { $this->error = 'BadValueForPropertyDescription'; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -1; } $userid = $user->id; - if (!($userid > 0)) // For example when record is saved into an anonymous context with a not loaded object $user. - { + if (!($userid > 0)) { // For example when record is saved into an anonymous context with a not loaded object $user. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $tmpinvoice = new Facture($this->db); $tmpinvoice->fetch($this->fk_facture_source); @@ -256,8 +266,7 @@ class DiscountAbsolute dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe_remise_except"); return $this->id; } else { @@ -278,8 +287,7 @@ class DiscountAbsolute global $conf, $langs; // Check if we can remove the discount - if ($this->fk_facture_source) - { + if ($this->fk_facture_source) { $sql = "SELECT COUNT(rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except"; $sql .= " WHERE (fk_facture_line IS NOT NULL"; // Not used as absolute simple discount @@ -289,11 +297,9 @@ class DiscountAbsolute dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj->nb > 0) - { + if ($obj->nb > 0) { $this->error = 'ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved'; return -2; } @@ -304,8 +310,7 @@ class DiscountAbsolute } // Check if we can remove the discount - if ($this->fk_invoice_supplier_source) - { + if ($this->fk_invoice_supplier_source) { $sql = "SELECT COUNT(rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except"; $sql .= " WHERE (fk_invoice_supplier_line IS NOT NULL"; // Not used as absolute simple discount @@ -315,11 +320,9 @@ class DiscountAbsolute dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj->nb > 0) - { + if ($obj->nb > 0) { $this->error = 'ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved'; return -2; } @@ -333,9 +336,13 @@ class DiscountAbsolute // Delete but only if not used $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except "; - if ($this->fk_facture_source) $sql .= " WHERE fk_facture_source = ".$this->fk_facture_source; // Delete all lines of same serie - elseif ($this->fk_invoice_supplier_source) $sql .= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; // Delete all lines of same serie - else $sql .= " WHERE rowid = ".$this->id; // Delete only line + if ($this->fk_facture_source) { + $sql .= " WHERE fk_facture_source = ".$this->fk_facture_source; // Delete all lines of same serie + } elseif ($this->fk_invoice_supplier_source) { + $sql .= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; // Delete all lines of same serie + } else { + $sql .= " WHERE rowid = ".$this->id; // Delete only line + } $sql .= " AND (fk_facture_line IS NULL"; // Not used as absolute simple discount $sql .= " AND fk_facture IS NULL)"; // Not used as credit note and not used as deposit $sql .= " AND (fk_invoice_supplier_line IS NULL"; // Not used as absolute simple discount @@ -343,19 +350,16 @@ class DiscountAbsolute dol_syslog(get_class($this)."::delete Delete discount", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { // If source of discount was a credit note or deposit, we change source statut. - if ($this->fk_facture_source) - { + if ($this->fk_facture_source) { $sql = "UPDATE ".MAIN_DB_PREFIX."facture"; $sql .= " set paye=0, fk_statut=1"; $sql .= " WHERE (type = 2 or type = 3) AND rowid=".$this->fk_facture_source; dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->db->commit(); return 1; } else { @@ -370,8 +374,7 @@ class DiscountAbsolute dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->db->commit(); return 1; } else { @@ -406,31 +409,36 @@ class DiscountAbsolute { // phpcs:enable // Check parameters - if (!$rowidline && !$rowidinvoice) - { + if (!$rowidline && !$rowidinvoice) { $this->error = 'ErrorBadParameters'; return -1; } - if ($rowidline && $rowidinvoice) - { + if ($rowidline && $rowidinvoice) { $this->error = 'ErrorBadParameters'; return -2; } $sql = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; if (!empty($this->discount_type)) { - if ($rowidline) $sql .= " SET fk_invoice_supplier_line = ".$rowidline; - if ($rowidinvoice) $sql .= " SET fk_invoice_supplier = ".$rowidinvoice; + if ($rowidline) { + $sql .= " SET fk_invoice_supplier_line = ".$rowidline; + } + if ($rowidinvoice) { + $sql .= " SET fk_invoice_supplier = ".$rowidinvoice; + } } else { - if ($rowidline) $sql .= " SET fk_facture_line = ".$rowidline; - if ($rowidinvoice) $sql .= " SET fk_facture = ".$rowidinvoice; + if ($rowidline) { + $sql .= " SET fk_facture_line = ".$rowidline; + } + if ($rowidinvoice) { + $sql .= " SET fk_facture = ".$rowidinvoice; + } } $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::link_to_invoice", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { if (!empty($this->discount_type)) { $this->fk_invoice_supplier_line = $rowidline; $this->fk_invoice_supplier = $rowidinvoice; @@ -466,8 +474,7 @@ class DiscountAbsolute dol_syslog(get_class($this)."::unlink_invoice", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { return 1; } else { $this->error = $this->db->error(); @@ -502,22 +509,28 @@ class DiscountAbsolute } else { $sql .= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer } - if (is_object($company)) $sql .= " AND rc.fk_soc = ".$company->id; - if (is_object($user)) $sql .= " AND rc.fk_user = ".$user->id; - if ($filter) $sql .= ' AND ('.$filter.')'; - if ($maxvalue) $sql .= ' AND rc.amount_ttc <= '.price2num($maxvalue); + if (is_object($company)) { + $sql .= " AND rc.fk_soc = ".$company->id; + } + if (is_object($user)) { + $sql .= " AND rc.fk_user = ".$user->id; + } + if ($filter) { + $sql .= ' AND ('.$filter.')'; + } + if ($maxvalue) { + $sql .= ' AND rc.amount_ttc <= '.price2num($maxvalue); + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); //while ($obj) //{ //print 'zz'.$obj->amount; //$obj = $this->db->fetch_object($resql); //} - if ($multicurrency) - { + if ($multicurrency) { return $obj->amount_multicurrency; } @@ -539,14 +552,12 @@ class DiscountAbsolute { dol_syslog(get_class($this)."::getSumDepositsUsed", LOG_DEBUG); - if ($invoice->element == 'facture' || $invoice->element == 'invoice') - { + if ($invoice->element == 'facture' || $invoice->element == 'invoice') { $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f'; $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id; $sql .= ' AND f.type = 3'; - } elseif ($invoice->element == 'invoice_supplier') - { + } elseif ($invoice->element == 'invoice_supplier') { $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f'; $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id; @@ -558,11 +569,13 @@ class DiscountAbsolute } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($multicurrency == 1) return $obj->multicurrency_amount; - else return $obj->amount; + if ($multicurrency == 1) { + return $obj->multicurrency_amount; + } else { + return $obj->amount; + } } else { $this->error = $this->db->lasterror(); return -1; @@ -580,14 +593,12 @@ class DiscountAbsolute { dol_syslog(get_class($this)."::getSumCreditNotesUsed", LOG_DEBUG); - if ($invoice->element == 'facture' || $invoice->element == 'invoice') - { + if ($invoice->element == 'facture' || $invoice->element == 'invoice') { $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f'; $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id; $sql .= ' AND f.type IN ('.$invoice::TYPE_STANDARD.', '.$invoice::TYPE_CREDIT_NOTE.', '.$invoice::TYPE_SITUATION.')'; // Find discount coming from credit note or excess received - } elseif ($invoice->element == 'invoice_supplier') - { + } elseif ($invoice->element == 'invoice_supplier') { $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f'; $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id; @@ -599,11 +610,13 @@ class DiscountAbsolute } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($multicurrency == 1) return $obj->multicurrency_amount; - else return $obj->amount; + if ($multicurrency == 1) { + return $obj->multicurrency_amount; + } else { + return $obj->amount; + } } else { $this->error = $this->db->lasterror(); return -1; @@ -620,13 +633,11 @@ class DiscountAbsolute { dol_syslog(get_class($this)."::getSumCreditNotesUsed", LOG_DEBUG); - if ($invoice->element == 'facture' || $invoice->element == 'invoice') - { + if ($invoice->element == 'facture' || $invoice->element == 'invoice') { $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc'; $sql .= ' WHERE rc.fk_facture IS NULL AND rc.fk_facture_source = '.$invoice->id; - } elseif ($invoice->element == 'invoice_supplier') - { + } elseif ($invoice->element == 'invoice_supplier') { $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc'; $sql .= ' WHERE rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_source = '.$invoice->id; @@ -637,11 +648,13 @@ class DiscountAbsolute } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($multicurrency) return $obj->multicurrency_amount; - else return $obj->amount; + if ($multicurrency) { + return $obj->multicurrency_amount; + } else { + return $obj->amount; + } } else { $this->error = $this->db->lasterror(); return -1; @@ -684,8 +697,12 @@ class DiscountAbsolute } - if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); - if ($withpicto && $withpicto != 2) $result .= ' '; + if ($withpicto) { + $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } $result .= $link.$ref.$linkend; return $result; } diff --git a/htdocs/core/class/doleditor.class.php b/htdocs/core/class/doleditor.class.php index a5405fd7158..25b1a43486a 100644 --- a/htdocs/core/class/doleditor.class.php +++ b/htdocs/core/class/doleditor.class.php @@ -70,8 +70,12 @@ class DolEditor dol_syslog(get_class($this)."::DolEditor htmlname=".$htmlname." width=".$width." height=".$height." toolbarname=".$toolbarname); - if (!$rows) $rows = round($height / 20); - if (!$cols) $cols = ($width ?round($width / 6) : 80); + if (!$rows) { + $rows = round($height / 20); + } + if (!$cols) { + $cols = ($width ?round($width / 6) : 80); + } $shorttoolbarname = preg_replace('/_encoded$/', '', $toolbarname); // Name of extended editor to use (FCKEDITOR_EDITORNAME can be 'ckeditor' or 'fckeditor') @@ -81,17 +85,19 @@ class DolEditor $this->readonly = $readonly; // Check if extended editor is ok. If not we force textarea - if ((empty($conf->fckeditor->enabled) && $okforextendededitor != 'ace') || empty($okforextendededitor)) $this->tool = 'textarea'; - if ($okforextendededitor === 'ace') $this->tool = 'ace'; + if ((empty($conf->fckeditor->enabled) && $okforextendededitor != 'ace') || empty($okforextendededitor)) { + $this->tool = 'textarea'; + } + if ($okforextendededitor === 'ace') { + $this->tool = 'ace'; + } //if ($conf->dol_use_jmobile) $this->tool = 'textarea'; // ckeditor and ace seems ok with mobile // Define some properties - if (in_array($this->tool, array('textarea', 'ckeditor', 'ace'))) - { + if (in_array($this->tool, array('textarea', 'ckeditor', 'ace'))) { if ($this->tool == 'ckeditor' && !dol_textishtml($content)) { // We force content to be into HTML if we are using an advanced editor if content is not HTML. $this->content = dol_nl2br($content); - } - else { + } else { $this->content = $content; } $this->htmlname = $htmlname; @@ -122,16 +128,14 @@ class DolEditor global $conf, $langs; $fullpage = false; - if (isset($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT)) - { + if (isset($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT)) { $disallowAnyContent = empty($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT); // Only predefined list of html tags are allowed or all } $found = 0; $out = ''; - if (in_array($this->tool, array('textarea', 'ckeditor'))) - { + if (in_array($this->tool, array('textarea', 'ckeditor'))) { $found = 1; //$out.= ''; - if ($this->tool == 'ckeditor' && !empty($conf->use_javascript_ajax) && !empty($conf->fckeditor->enabled)) - { - if (!defined('REQUIRE_CKEDITOR')) define('REQUIRE_CKEDITOR', '1'); + if ($this->tool == 'ckeditor' && !empty($conf->use_javascript_ajax) && !empty($conf->fckeditor->enabled)) { + if (!defined('REQUIRE_CKEDITOR')) { + define('REQUIRE_CKEDITOR', '1'); + } if (!empty($conf->global->FCKEDITOR_SKIN)) { $skin = $conf->global->FCKEDITOR_SKIN; @@ -165,7 +170,8 @@ class DolEditor readOnly : '.($this->readonly ? 'true' : 'false').', htmlEncodeOutput :'.$htmlencode_force.', allowedContent :'.($disallowAnyContent ? 'false' : 'true').', - extraAllowedContent : \'\', + extraAllowedContent : \'a[target];div{float,display}\', /* Add the style float and display into div to default other allowed tags */ + disallowedContent : '.($disallowAnyContent ? '\'\'' : '\'\'').', fullPage : '.($fullpage ? 'true' : 'false').', toolbar: \''.$this->toolbarname.'\', toolbarStartupExpanded: '.($this->toolbarstartexpanded ? 'true' : 'false').', @@ -191,8 +197,7 @@ class DolEditor }, disableNativeSpellChecker: '.(empty($conf->global->CKEDITOR_NATIVE_SPELLCHECKER) ? 'true' : 'false'); - if ($this->uselocalbrowser) - { + if ($this->uselocalbrowser) { $out .= ','."\n"; // To use filemanager with old fckeditor (GPL) $out .= ' filebrowserBrowseUrl : ckeditorFilebrowserBrowseUrl,'; @@ -202,11 +207,11 @@ class DolEditor $out .= "\n"; // To use filemanager with ckfinder (Non free) and ckfinder directory is inside htdocs/includes /* $out.= ' filebrowserBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html\', - filebrowserImageBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html?Type=Images\', - filebrowserFlashBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html?Type=Flash\', - filebrowserUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files\', - filebrowserImageUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images\', - filebrowserFlashUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash\','."\n"; + filebrowserImageBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html?Type=Images\', + filebrowserFlashBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html?Type=Flash\', + filebrowserUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files\', + filebrowserImageUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images\', + filebrowserFlashUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash\','."\n"; */ $out .= ' filebrowserWindowWidth : \'900\', filebrowserWindowHeight : \'500\', @@ -221,15 +226,13 @@ class DolEditor // Output editor ACE // Warning: ace.js and ext-statusbar.js must be loaded by the parent page. - if (preg_match('/^ace/', $this->tool)) - { + if (preg_match('/^ace/', $this->tool)) { $found = 1; $format = $option; $out .= "\n".''."\n"; - if ($titlecontent) - { + if ($titlecontent) { $out .= '
    '.$titlecontent; $out .= '   -   '.dol_escape_htmltag($langs->trans("ShowMoreLines")).'     '; $out .= '
    '; @@ -304,12 +307,14 @@ class DolEditor $out .= ''."\n"; } - if (empty($found)) - { + if (empty($found)) { $out .= 'Error, unknown value for tool '.$this->tool.' in DolEditor Create function.'; } - if ($noprint) return $out; - else print $out; + if ($noprint) { + return $out; + } else { + print $out; + } } } diff --git a/htdocs/core/class/dolgeoip.class.php b/htdocs/core/class/dolgeoip.class.php index 98fbe62e4c5..b4218bbfd40 100644 --- a/htdocs/core/class/dolgeoip.class.php +++ b/htdocs/core/class/dolgeoip.class.php @@ -46,54 +46,49 @@ class DolGeoIP global $conf; $geoipversion = '2'; // 'php', or '2' - if (!empty($conf->global->GEOIP_VERSION)) $geoipversion = $conf->global->GEOIP_VERSION; + if (!empty($conf->global->GEOIP_VERSION)) { + $geoipversion = $conf->global->GEOIP_VERSION; + } - if ($type == 'country') - { + if ($type == 'country') { // geoip may have been already included with PEAR - if ($geoipversion == '2' || ($geoipversion != 'php' && !function_exists('geoip_country_code_by_name'))) - { + if ($geoipversion == '2' || ($geoipversion != 'php' && !function_exists('geoip_country_code_by_name'))) { require_once DOL_DOCUMENT_ROOT.'/includes/geoip2/geoip2.phar'; } - } elseif ($type == 'city') - { + } elseif ($type == 'city') { // geoip may have been already included with PEAR - if ($geoipversion == '2' || ($geoipversion != 'php' && !function_exists('geoip_country_code_by_name'))) - { + if ($geoipversion == '2' || ($geoipversion != 'php' && !function_exists('geoip_country_code_by_name'))) { require_once DOL_DOCUMENT_ROOT.'/includes/geoip2/geoip2.phar'; } - } else { print 'ErrorBadParameterInConstructor'; return 0; } + } else { + print 'ErrorBadParameterInConstructor'; + return 0; + } // Here, function exists (embedded into PHP or exists because we made include) - if (empty($type) || empty($datfile)) - { + if (empty($type) || empty($datfile)) { $this->errorlabel = 'Constructor was called with no datafile parameter'; dol_syslog('DolGeoIP '.$this->errorlabel, LOG_ERR); return 0; } - if (!file_exists($datfile) || !is_readable($datfile)) - { + if (!file_exists($datfile) || !is_readable($datfile)) { $this->error = 'ErrorGeoIPClassNotInitialized'; $this->errorlabel = "Datafile ".$datfile." not found"; dol_syslog('DolGeoIP '.$this->errorlabel, LOG_ERR); return 0; } - if ($geoipversion == '2') - { + if ($geoipversion == '2') { try { $this->gi = new GeoIp2\Database\Reader($datfile); // '/usr/local/share/GeoIP/GeoIP2-City.mmdb' - } catch (Exception $e) - { + } catch (Exception $e) { $this->error = $e->getMessage(); dol_syslog('DolGeoIP '.$this->errorlabel, LOG_ERR); return 0; } - } elseif (function_exists('geoip_open')) - { + } elseif (function_exists('geoip_open')) { $this->gi = geoip_open($datfile, GEOIP_STANDARD); - } - elseif (function_exists('geoip_country_code_by_name')) { + } elseif (function_exists('geoip_country_code_by_name')) { $this->gi = 'NOGI'; // We are using embedded php geoip functions //print 'function_exists(geoip_country_code_by_name))='.function_exists('geoip_country_code_by_name'); //print geoip_database_info(); @@ -113,21 +108,19 @@ class DolGeoIP global $conf; $geoipversion = '2'; // 'php', or '2' - if (!empty($conf->global->GEOIP_VERSION)) $geoipversion = $conf->global->GEOIP_VERSION; + if (!empty($conf->global->GEOIP_VERSION)) { + $geoipversion = $conf->global->GEOIP_VERSION; + } - if (empty($this->gi)) - { + if (empty($this->gi)) { return ''; } - if ($this->gi == 'NOGI') - { + if ($this->gi == 'NOGI') { // geoip_country_code_by_addr does not exists return strtolower(geoip_country_code_by_name($ip)); } else { - if (preg_match('/^[0-9]+.[0-9]+\.[0-9]+\.[0-9]+/', $ip)) - { - if ($geoipversion == '2') - { + if (preg_match('/^[0-9]+.[0-9]+\.[0-9]+\.[0-9]+/', $ip)) { + if ($geoipversion == '2') { try { $record = $this->gi->country($ip); return strtolower($record->country->isoCode); @@ -136,12 +129,13 @@ class DolGeoIP return ''; } } else { - if (!function_exists('geoip_country_code_by_addr')) return strtolower(geoip_country_code_by_name($this->gi, $ip)); + if (!function_exists('geoip_country_code_by_addr')) { + return strtolower(geoip_country_code_by_name($ip)); + } return strtolower(geoip_country_code_by_addr($this->gi, $ip)); } } else { - if ($geoipversion == '2') - { + if ($geoipversion == '2') { try { $record = $this->gi->country($ip); return strtolower($record->country->isoCode); @@ -150,7 +144,9 @@ class DolGeoIP return ''; } } else { - if (!function_exists('geoip_country_code_by_addr_v6')) return strtolower(geoip_country_code_by_name_v6($this->gi, $ip)); + if (!function_exists('geoip_country_code_by_addr_v6')) { + return strtolower(geoip_country_code_by_name_v6($this->gi, $ip)); + } return strtolower(geoip_country_code_by_addr_v6($this->gi, $ip)); } } @@ -168,15 +164,15 @@ class DolGeoIP global $conf; $geoipversion = '2'; // 'php', or '2' - if (!empty($conf->global->GEOIP_VERSION)) $geoipversion = $conf->global->GEOIP_VERSION; + if (!empty($conf->global->GEOIP_VERSION)) { + $geoipversion = $conf->global->GEOIP_VERSION; + } - if (empty($this->gi)) - { + if (empty($this->gi)) { return ''; } - if ($geoipversion == '2') - { + if ($geoipversion == '2') { try { $record = $this->gi->country($name); return $record->country->isoCode; @@ -199,12 +195,16 @@ class DolGeoIP global $conf; $geoipversion = '2'; // 'php', or '2' - if (!empty($conf->global->GEOIP_VERSION)) $geoipversion = $conf->global->GEOIP_VERSION; + if (!empty($conf->global->GEOIP_VERSION)) { + $geoipversion = $conf->global->GEOIP_VERSION; + } - if ($geoipversion == 'php') - { - if ($this->gi == 'NOGI') return geoip_database_info(); - else return 'geoip_database_info() function not available'; + if ($geoipversion == 'php') { + if ($this->gi == 'NOGI') { + return geoip_database_info(); + } else { + return 'geoip_database_info() function not available'; + } } return 'Not available (not using PHP internal geo functions - We are using embedded Geoip v'.$geoipversion.')'; diff --git a/htdocs/core/class/dolgraph.class.php b/htdocs/core/class/dolgraph.class.php index fada0975938..3672f7faa07 100644 --- a/htdocs/core/class/dolgraph.class.php +++ b/htdocs/core/class/dolgraph.class.php @@ -114,9 +114,15 @@ class DolGraph $color_file = DOL_DOCUMENT_ROOT . '/theme/' . $conf->theme . '/theme_vars.inc.php'; if (is_readable($color_file)) { include_once $color_file; - if (isset($theme_bordercolor)) $this->bordercolor = $theme_bordercolor; - if (isset($theme_datacolor)) $this->datacolor = $theme_datacolor; - if (isset($theme_bgcolor)) $this->bgcolor = $theme_bgcolor; + if (isset($theme_bordercolor)) { + $this->bordercolor = $theme_bordercolor; + } + if (isset($theme_datacolor)) { + $this->datacolor = $theme_datacolor; + } + if (isset($theme_bgcolor)) { + $this->bgcolor = $theme_bgcolor; + } } //print 'bgcolor: '.join(',',$this->bgcolor).'
    '; @@ -597,7 +603,9 @@ class DolGraph public function GetMaxValueInData() { // phpcs:enable - if (!is_array($this->data)) return 0; + if (!is_array($this->data)) { + return 0; + } $k = 0; $vals = array(); @@ -624,7 +632,9 @@ class DolGraph public function GetMinValueInData() { // phpcs:enable - if (!is_array($this->data)) return 0; + if (!is_array($this->data)) { + return 0; + } $k = 0; $vals = array(); @@ -652,7 +662,9 @@ class DolGraph { // phpcs:enable $max = $this->GetMaxValueInData(); - if ($max != 0) $max++; + if ($max != 0) { + $max++; + } $size = dol_strlen(abs(ceil($max))); $factor = 1; for ($i = 0; $i < ($size - 1); $i++) { @@ -660,7 +672,9 @@ class DolGraph } $res = 0; - if (is_numeric($max)) $res = ceil($max / $factor) * $factor; + if (is_numeric($max)) { + $res = ceil($max / $factor) * $factor; + } //print "max=".$max." res=".$res; return $res; @@ -676,8 +690,12 @@ class DolGraph { // phpcs:enable $min = $this->GetMinValueInData(); - if ($min == '') $min = 0; - if ($min != 0) $min--; + if ($min == '') { + $min = 0; + } + if ($min != 0) { + $min--; + } $size = dol_strlen(abs(floor($min))); $factor = 1; for ($i = 0; $i < ($size - 1); $i++) { @@ -751,22 +769,22 @@ class DolGraph if (is_array($this->data) && is_array($this->data[0])) { $nblot = count($this->data[0]) - 1; // -1 to remove legend } - if ($nblot < 0) dol_syslog('Bad value for property ->data. Must be set by mydolgraph->SetData before calling mydolgrapgh->draw', LOG_WARNING); + if ($nblot < 0) { + dol_syslog('Bad value for property ->data. Must be set by mydolgraph->SetData before calling mydolgrapgh->draw', LOG_WARNING); + } $firstlot = 0; // Works with line but not with bars //if ($nblot > 2) $firstlot = ($nblot - 2); // We limit nblot to 2 because jflot can't manage more than 2 bars on same x $i = $firstlot; $serie = array(); - while ($i < $nblot) // Loop on each serie - { + while ($i < $nblot) { // Loop on each serie $values = array(); // Array with horizontal y values (specific values of a serie) for each abscisse x $serie[$i] = "var d" . $i . " = [];\n"; // Fill array $values $x = 0; - foreach ($this->data as $valarray) // Loop on each x - { + foreach ($this->data as $valarray) { // Loop on each x $legends[$x] = $valarray[0]; $values[$x] = (is_numeric($valarray[$i + 1]) ? $valarray[$i + 1] : null); $x++; @@ -774,11 +792,15 @@ class DolGraph if (isset($this->type[$firstlot]) && in_array($this->type[$firstlot], array('pie', 'piesemicircle', 'polar'))) { foreach ($values as $x => $y) { - if (isset($y)) $serie[$i] .= 'd' . $i . '.push({"label":"' . dol_escape_js($legends[$x]) . '", "data":' . $y . '});' . "\n"; + if (isset($y)) { + $serie[$i] .= 'd' . $i . '.push({"label":"' . dol_escape_js($legends[$x]) . '", "data":' . $y . '});' . "\n"; + } } } else { foreach ($values as $x => $y) { - if (isset($y)) $serie[$i] .= 'd' . $i . '.push([' . $x . ', ' . $y . ']);' . "\n"; + if (isset($y)) { + $serie[$i] .= 'd' . $i . '.push([' . $x . ', ' . $y . ']);' . "\n"; + } } } @@ -788,7 +810,9 @@ class DolGraph $tag = dol_escape_htmltag(dol_string_unaccent(dol_string_nospecial(basename($file), '_', array('-', '.')))); $this->stringtoshow = '' . "\n"; - if (!empty($this->title)) $this->stringtoshow .= '
    ' . $this->title . '
    '; + if (!empty($this->title)) { + $this->stringtoshow .= '
    ' . $this->title . '
    '; + } if (!empty($this->shownographyet)) { $this->stringtoshow .= '
    '; $this->stringtoshow .= '
    ' . $langs->trans("NotEnoughDataYet") . '...
    '; @@ -797,7 +821,9 @@ class DolGraph // Start the div that will contains all the graph $dolxaxisvertical = ''; - if (count($this->data) > 20) $dolxaxisvertical = 'dol-xaxis-vertical'; + if (count($this->data) > 20) { + $dolxaxisvertical = 'dol-xaxis-vertical'; + } $this->stringtoshow .= '
    ' . "\n"; $this->stringtoshow .= '";*/ + $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"'); + $retstring.="";*/ } else { $retstringbutton = ''; $retsring = $retstringbutton.$retstring; @@ -5808,33 +6161,28 @@ class Form } else { $retstring .= "Bad value of MAIN_POPUP_CALENDAR"; } - } - // Show date with combo selects - else { + } else { + // Show date with combo selects // Day $retstring .= ''; - if ($emptydate || $set_time == -1) - { + if ($emptydate || $set_time == -1) { $retstring .= ''; } - for ($day = 1; $day <= 31; $day++) - { + for ($day = 1; $day <= 31; $day++) { $retstring .= ''; } $retstring .= ""; $retstring .= ''; - if ($emptydate || $set_time == -1) - { + if ($emptydate || $set_time == -1) { $retstring .= ''; } // Month - for ($month = 1; $month <= 12; $month++) - { + for ($month = 1; $month <= 12; $month++) { $retstring .= '"; @@ -5842,14 +6190,12 @@ class Form $retstring .= ""; // Year - if ($emptydate || $set_time == -1) - { + if ($emptydate || $set_time == -1) { $retstring .= ''; } else { $retstring .= ''; - for ($year = $syear - 10; $year < $syear + 10; $year++) - { + for ($year = $syear - 10; $year < $syear + 10; $year++) { $retstring .= ''; } $retstring .= "\n"; @@ -5862,39 +6208,47 @@ class Form $retstring .= ''; } - if ($h) - { + if ($h) { $hourstart = 0; $hourend = 24; if ($openinghours != '') { $openinghours = explode(',', $openinghours); $hourstart = $openinghours[0]; $hourend = $openinghours[1]; - if ($hourend < $hourstart) $hourend = $hourstart; + if ($hourend < $hourstart) { + $hourend = $hourstart; + } } // Show hour $retstring .= ''; - if ($emptyhours) $retstring .= ''; - for ($hour = $hourstart; $hour < $hourend; $hour++) - { - if (strlen($hour) < 2) $hour = "0".$hour; + if ($emptyhours) { + $retstring .= ''; + } + for ($hour = $hourstart; $hour < $hourend; $hour++) { + if (strlen($hour) < 2) { + $hour = "0".$hour; + } $retstring .= ''; } $retstring .= ''; //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":"; - if ($m) $retstring .= ":"; + if ($m) { + $retstring .= ":"; + } } - if ($m) - { + if ($m) { // Show minutes $retstring .= ''; - if ($emptyhours) $retstring .= ''; - for ($min = 0; $min < 60; $min += $stepminutes) - { - if (strlen($min) < 2) $min = "0".$min; + if ($emptyhours) { + $retstring .= ''; + } + for ($min = 0; $min < 60; $min += $stepminutes) { + if (strlen($min) < 2) { + $min = "0".$min; + } $retstring .= ''; } $retstring .= ''; @@ -5907,12 +6261,10 @@ class Form } // Add a "Now" link - if ($conf->use_javascript_ajax && $addnowlink) - { + if ($conf->use_javascript_ajax && $addnowlink) { // Script which will be inserted in the onClick of the "Now" link $reset_scripts = ""; - if ($addnowlink == 2) // local computer time - { + if ($addnowlink == 2) { // local computer time // pad add leading 0 on numbers $reset_scripts .= "Number.prototype.pad = function(size) { var s = String(this); @@ -5923,73 +6275,72 @@ class Form } // Generate the date part, depending on the use or not of the javascript calendar - if ($addnowlink == 1) // server time expressed in user time setup - { - $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day', 'tzuser').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d', 'tzuser').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m', 'tzuser').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y', 'tzuser').'\');'; - } elseif ($addnowlink == 2) - { + if ($addnowlink == 1) { // server time expressed in user time setup + $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');'; + } elseif ($addnowlink == 2) { /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix. - * This break application for foreign languages. - $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());'; - */ - $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day', 'tzuser').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d', 'tzuser').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m', 'tzuser').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y', 'tzuser').'\');'; + * This break application for foreign languages. + $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());'; + */ + $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');'; } /*if ($usecalendar == "eldy") - { - $base=DOL_URL_ROOT.'/core/'; - $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');'; - } - else - { - $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); '; - $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); '; - $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); '; - }*/ - // Update the hour part - if ($h) { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + $base=DOL_URL_ROOT.'/core/'; + $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');'; + } + else + { + $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); '; + $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); '; + $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); '; + }*/ + // Update the hour part + if ($h) { + if ($fullday) { + $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + } //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); '; - if ($addnowlink == 1) - { - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H', 'tzuser').'\');'; + if ($addnowlink == 1) { + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');'; $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();'; - } elseif ($addnowlink == 2) - { + } elseif ($addnowlink == 2) { $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());'; $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();'; } - if ($fullday) $reset_scripts .= ' } '; + if ($fullday) { + $reset_scripts .= ' } '; + } } // Update the minute part - if ($m) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + if ($m) { + if ($fullday) { + $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + } //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); '; - if ($addnowlink == 1) - { - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M', 'tzuser').'\');'; + if ($addnowlink == 1) { + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');'; $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();'; - } elseif ($addnowlink == 2) - { + } elseif ($addnowlink == 2) { $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());'; $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();'; } - if ($fullday) $reset_scripts .= ' } '; + if ($fullday) { + $reset_scripts .= ' } '; + } } // If reset_scripts is not empty, print the link with the reset_scripts in the onClick - if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) - { + if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) { $retstring .= ' '; @@ -5997,45 +6348,50 @@ class Form } // Add a "Plus one hour" link - if ($conf->use_javascript_ajax && $addplusone) - { + if ($conf->use_javascript_ajax && $addplusone) { // Script which will be inserted in the onClick of the "Add plusone" link $reset_scripts = ""; // Generate the date part, depending on the use or not of the javascript calendar - $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');'; // Update the hour part - if ($h) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H').'\');'; - if ($fullday) $reset_scripts .= ' } '; + if ($h) { + if ($fullday) { + $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + } + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');'; + if ($fullday) { + $reset_scripts .= ' } '; + } } // Update the minute part - if ($m) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M').'\');'; - if ($fullday) $reset_scripts .= ' } '; + if ($m) { + if ($fullday) { + $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + } + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');'; + if ($fullday) { + $reset_scripts .= ' } '; + } } // If reset_scripts is not empty, print the link with the reset_scripts in the onClick - if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) - { + if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) { $retstring .= ' '; } } - // Add a "Plus one hour" link - if ($conf->use_javascript_ajax && $adddateof) - { + // Add a link to set data + if ($conf->use_javascript_ajax && $adddateof) { $tmparray = dol_getdate($adddateof); - if (empty($labeladddateof)) $labeladddateof = $langs->trans("DateInvoice"); - $retstring .= ' -
    '.$langs->trans("None").'
    '; - if (!empty($compatibleImportElementsList)) - { + if (!empty($compatibleImportElementsList)) { $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php'); } @@ -7186,19 +7621,23 @@ class Form $linktoelemlist = ''; $listofidcompanytoscan = ''; - if (!is_object($object->thirdparty)) $object->fetch_thirdparty(); + if (!is_object($object->thirdparty)) { + $object->fetch_thirdparty(); + } $possiblelinks = array(); - if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) - { + if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) { $listofidcompanytoscan = $object->thirdparty->id; - if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan .= ','.$object->thirdparty->parent; - if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) - { + if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) { + $listofidcompanytoscan .= ','.$object->thirdparty->parent; + } + if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) { include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $tmpproject = new Project($this->db); $tmpproject->fetch($object->fk_project); - if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan .= ','.$tmpproject->socid; + if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) { + $listofidcompanytoscan .= ','.$tmpproject->socid; + } unset($tmpproject); } @@ -7208,7 +7647,7 @@ class Form 'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'), 'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'), 'contrat'=>array('enabled'=>$conf->contrat->enabled, 'perms'=>1, 'label'=>'LinkToContract', - 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_customer as ref_client, t.ref_supplier, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'), + 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_customer as ref_client, t.ref_supplier, SUM(td.total_ht) as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t, ".MAIN_DB_PREFIX."contratdet as td WHERE t.fk_soc = s.rowid AND td.fk_contrat = t.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'), 'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'), 'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled, 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'), 'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled, 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'), @@ -7221,39 +7660,33 @@ class Form $hookmanager->initHooks(array('commonobject')); $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan); - if (!empty($listofidcompanytoscan)) // If empty, we don't have criteria to scan the object we can link to - { + if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook } - if (empty($reshook)) - { - if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) - { + if (empty($reshook)) { + if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) { $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray); } - } elseif ($reshook > 0) - { - if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) - { + } elseif ($reshook > 0) { + if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) { $possiblelinks = $hookmanager->resArray; } } - foreach ($possiblelinks as $key => $possiblelink) - { + foreach ($possiblelinks as $key => $possiblelink) { $num = 0; - if (empty($possiblelink['enabled'])) continue; + if (empty($possiblelink['enabled'])) { + continue; + } - if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) - { + if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) { print '
    use_javascript_ajax) ? '' : ' style="display:none"').'>'; $sql = $possiblelink['sql']; $resqllist = $this->db->query($sql); - if ($resqllist) - { + if ($resqllist) { $num = $this->db->num_rows($resqllist); $i = 0; @@ -7271,8 +7704,7 @@ class Form print '
    '.$langs->trans("AmountHTShort").''.$langs->trans("Company").'
    '.$objp->ref.''.$objp->ref_client.''.price($objp->total_ht).''; + if ($possiblelink['label'] == 'LinkToContract') { + $form = new Form($this->db); + print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")).' '; + } + print price($objp->total_ht).''.$objp->name.'
    '; @@ -225,14 +246,14 @@ class FormActions print ''; print "\n"; - if (is_array($listofactions) && count($listofactions)) - { + if (is_array($listofactions) && count($listofactions)) { $cacheusers = array(); $cursorevent = 0; - foreach ($listofactions as $actioncomm) - { - if ($max && $cursorevent >= $max) break; + foreach ($listofactions as $actioncomm) { + if ($max && $cursorevent >= $max) { + break; + } $ref = $actioncomm->getNomUrl(1, -1); $label = $actioncomm->getNomUrl(0, 36); @@ -244,47 +265,39 @@ class FormActions // Onwer print ''; + $actionstatic = $actioncomm; // Type - print ''; // Label @@ -292,14 +305,16 @@ class FormActions // Date print ''; print ''; } - if ($max && $num > $max) - { + if ($max && $num > $max) { print ''; } @@ -345,7 +359,9 @@ class FormActions // phpcs:enable global $langs, $user, $form, $conf; - if (!is_object($form)) $form = new Form($this->db); + if (!is_object($form)) { + $form = new Form($this->db); + } require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; @@ -359,28 +375,37 @@ class FormActions } //asort($arraylist); - if ($selected == 'manual') $selected = 'AC_OTH'; - if ($selected == 'auto') $selected = 'AC_OTH_AUTO'; - - if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) unset($arraylist['AC_OTH_AUTO']); - - $out = ''; - - if (!empty($multiselect)) - { - if (!is_array($selected) && !empty($selected)) $selected = explode(',', $selected); - $out .= $form->multiselectarray($htmlname, $arraylist, $selected, 0, 0, 'centpercent', 0, 0); - } else { - $out .= $form->selectarray($htmlname, $arraylist, $selected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth200'.($morecss ? ' '.$morecss : ''), 1); + if ($selected == 'manual') { + $selected = 'AC_OTH'; + } + if ($selected == 'auto') { + $selected = 'AC_OTH_AUTO'; } - if ($user->admin && empty($onlyautoornot) && $hideinfohelp <= 0) - { + if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) { + unset($arraylist['AC_OTH_AUTO']); + } + + $out = ''; + + if (!empty($multiselect)) { + if (!is_array($selected) && !empty($selected)) { + $selected = explode(',', $selected); + } + $out .= $form->multiselectarray($htmlname, $arraylist, $selected, 0, 0, 'centpercent', 0, 0); + } else { + $out .= $form->selectarray($htmlname, $arraylist, $selected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth300'.($morecss ? ' '.$morecss : ''), 1); + } + + if ($user->admin && empty($onlyautoornot) && $hideinfohelp <= 0) { $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup").($hideinfohelp == -1 ? ". ".$langs->trans("YouCanSetDefaultValueInModuleSetup") : ''), 1); } - if ($nooutput) return $out; - else print $out; + if ($nooutput) { + return $out; + } else { + print $out; + } return ''; } } diff --git a/htdocs/core/class/html.formadmin.class.php b/htdocs/core/class/html.formadmin.class.php index 3e8eb04c430..7f83b5f1bac 100644 --- a/htdocs/core/class/html.formadmin.class.php +++ b/htdocs/core/class/html.formadmin.class.php @@ -67,45 +67,59 @@ class FormAdmin // phpcs:enable global $conf, $langs; - if (!empty($conf->global->MAIN_DEFAULT_LANGUAGE_FILTER)) $filter[$conf->global->MAIN_DEFAULT_LANGUAGE_FILTER] = 1; + if (!empty($conf->global->MAIN_DEFAULT_LANGUAGE_FILTER)) { + $filter[$conf->global->MAIN_DEFAULT_LANGUAGE_FILTER] = 1; + } $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 12, 0, $mainlangonly); $out = ''; $out .= ''; // Make select dynamic - if (!$forcecombo) - { + if (!$forcecombo) { include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $out .= ajax_combobox($htmlname); } @@ -152,38 +165,45 @@ class FormAdmin // Check parameters - if (!is_array($dirmenuarray)) return -1; + if (!is_array($dirmenuarray)) { + return -1; + } $menuarray = array(); - foreach ($conf->file->dol_document_root as $dirroot) - { - foreach ($dirmenuarray as $dirtoscan) - { + foreach ($conf->file->dol_document_root as $dirroot) { + foreach ($dirmenuarray as $dirtoscan) { $dir = $dirroot.$dirtoscan; //print $dir.'
    '; - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && substr($file, 0, 5) != 'index') - { - if (preg_match('/lib\.php$/i', $file)) continue; // We exclude library files - if (preg_match('/eldy_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files - if (preg_match('/auguria_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files - if (preg_match('/smartphone_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && substr($file, 0, 5) != 'index') { + if (preg_match('/lib\.php$/i', $file)) { + continue; // We exclude library files + } + if (preg_match('/eldy_(backoffice|frontoffice)\.php$/i', $file)) { + continue; // We exclude all menu manager files + } + if (preg_match('/auguria_(backoffice|frontoffice)\.php$/i', $file)) { + continue; // We exclude all menu manager files + } + if (preg_match('/smartphone_(backoffice|frontoffice)\.php$/i', $file)) { + continue; // We exclude all menu manager files + } $filelib = preg_replace('/\.php$/i', '', $file); $prefix = ''; // 0=Recommanded, 1=Experimental, 2=Developpement, 3=Other - if (preg_match('/^eldy/i', $file)) $prefix = '0'; - elseif (preg_match('/^smartphone/i', $file)) $prefix = '2'; - else $prefix = '3'; + if (preg_match('/^eldy/i', $file)) { + $prefix = '0'; + } elseif (preg_match('/^smartphone/i', $file)) { + $prefix = '2'; + } else { + $prefix = '3'; + } - if ($file == $selected) - { + if ($file == $selected) { $menuarray[$prefix.'_'.$file] = ''; } else { $menuarray[$prefix.'_'.$file] = ''; @@ -200,20 +220,30 @@ class FormAdmin // Output combo list of menus print ''; $oldprefix = ''; - foreach ($menuarray as $key => $val) - { + foreach ($menuarray as $key => $val) { $tab = explode('_', $key); $newprefix = $tab[0]; print ''."\n"; } print ''; @@ -340,7 +375,9 @@ class FormAdmin ); foreach ($arraytz as $lib => $gmt) { print ''."\n"; } print ''; @@ -368,15 +405,15 @@ class FormAdmin $sql = "SELECT code, label, width, height, unit"; $sql .= " FROM ".MAIN_DB_PREFIX."c_paper_format"; $sql .= " WHERE active=1"; - if ($filter) $sql .= " AND code LIKE '%".$this->db->escape($filter)."%'"; + if ($filter) { + $sql .= " AND code LIKE '%".$this->db->escape($filter)."%'"; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $unitKey = $langs->trans('SizeUnit'.$obj->unit); @@ -391,16 +428,15 @@ class FormAdmin $out = ''; $out .= ''; print ''; print ''; - if ($conf->global->MARGIN_TYPE == "1") + if ($conf->global->MARGIN_TYPE == "1") { print ''; - else print ''; + } else { + print ''; + } print ''; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print ''; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print ''; + } print ''; - if (!empty($conf->product->enabled)) - { + if (!empty($conf->product->enabled)) { //if ($marginInfo['margin_on_products'] != 0 && $marginInfo['margin_on_services'] != 0) { print ''; print ''; print ''; print ''; print ''; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print ''; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print ''; + } print ''; } - if (!empty($conf->service->enabled)) - { + if (!empty($conf->service->enabled)) { print ''; print ''; print ''; print ''; print ''; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print ''; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print ''; + } print ''; } - if (!empty($conf->product->enabled) && !empty($conf->service->enabled)) - { + if (!empty($conf->product->enabled) && !empty($conf->service->enabled)) { print ''; print ''; print ''; print ''; print ''; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print ''; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print ''; + } print ''; } print '
    '; - if (!empty($actioncomm->userownerid)) - { - if (isset($cacheusers[$actioncomm->userownerid]) && is_object($cacheusers[$actioncomm->userownerid])) - { + if (!empty($actioncomm->userownerid)) { + if (isset($cacheusers[$actioncomm->userownerid]) && is_object($cacheusers[$actioncomm->userownerid])) { $tmpuser = $cacheusers[$actioncomm->userownerid]; } else { $tmpuser = new User($this->db); $tmpuser->fetch($actioncomm->userownerid); $cacheusers[$actioncomm->userownerid] = $tmpuser; } - if ($tmpuser->id > 0) - { + if ($tmpuser->id > 0) { print $tmpuser->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', ''); } } print ''; - // TODO Code common with code into comm/action/list.php - $imgpicto = ''; - if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) - { - if ($actioncomm->type_picto) { - $imgpicto = img_picto('', $actioncomm->type_picto); - } else { - if ($actioncomm->type_code == 'AC_RDV') $imgpicto = img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright'); - elseif ($actioncomm->type_code == 'AC_TEL') $imgpicto = img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright'); - elseif ($actioncomm->type_code == 'AC_FAX') $imgpicto = img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright'); - elseif ($actioncomm->type_code == 'AC_EMAIL') $imgpicto = img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright'); - elseif ($actioncomm->type_code == 'AC_INT') $imgpicto = img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright'); - elseif ($actioncomm->type_code == 'AC_OTH' && $actioncomm->code == 'TICKET_MSG') $imgpicto = img_picto('', 'object_conversation', '', false, 0, 0, '', 'paddingright'); - elseif (!preg_match('/_AUTO/', $actioncomm->type_code)) $imgpicto = img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright'); + $labeltype = $actionstatic->type_code; + if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) { + $labeltype = 'AC_OTH'; + } + if ($actionstatic->type_code == 'AC_OTH' && $actionstatic->code == 'TICKET_MSG') { + $labeltype = $langs->trans("Message"); + } else { + if (!empty($arraylist[$labeltype])) { + $labeltype = $arraylist[$labeltype]; + } + if ($actionstatic->type_code == 'AC_OTH_AUTO' && ($actionstatic->type_code != $actionstatic->code) && $labeltype && !empty($arraylist[$actionstatic->code])) { + $labeltype .= ' - '.$arraylist[$actionstatic->code]; // Use code in priority on type_code } } - print $imgpicto; - if ($actioncomm->type_code == 'AC_OTH' && $actioncomm->code == 'TICKET_MSG') { - print $langs->trans("Message"); - } else { - print $actioncomm->type_short ? $actioncomm->type_short : $actioncomm->type; - } + print ''; + print $actioncomm->getTypePicto(); + print $labeltype; print ''.dol_print_date($actioncomm->datep, 'dayhour', 'tzuserrel'); - if ($actioncomm->datef) - { + if ($actioncomm->datef) { $tmpa = dol_getdate($actioncomm->datep); $tmpb = dol_getdate($actioncomm->datef); - if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) - { - if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) print '-'.dol_print_date($actioncomm->datef, 'hour', 'tzuserrel'); - } else print '-'.dol_print_date($actioncomm->datef, 'dayhour', 'tzuserrel'); + if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) { + if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) { + print '-'.dol_print_date($actioncomm->datef, 'hour', 'tzuserrel'); + } + } else { + print '-'.dol_print_date($actioncomm->datef, 'dayhour', 'tzuserrel'); + } } print ''; @@ -313,8 +328,7 @@ class FormActions print '
    '.$langs->trans("None").'
    '.$langs->trans("More").'...
    '.$langs->trans('Margins').''.$langs->trans('SellingPrice').''.$langs->trans('BuyingPrice').''.$langs->trans('CostPrice').''.$langs->trans('CostPrice').''.$langs->trans('Margin').''.$langs->trans('MarginRate').''.$langs->trans('MarkRate').'
    '.$langs->trans('MarginOnProducts').''.price($marginInfo['pv_products']).''.price($marginInfo['pa_products']).''.price($marginInfo['margin_on_products']).''.(($marginInfo['margin_rate_products'] == '') ? '' : price($marginInfo['margin_rate_products'], null, null, null, null, 2).'%').''.(($marginInfo['mark_rate_products'] == '') ? '' : price($marginInfo['mark_rate_products'], null, null, null, null, 2).'%').'
    '.$langs->trans('MarginOnServices').''.price($marginInfo['pv_services']).''.price($marginInfo['pa_services']).''.price($marginInfo['margin_on_services']).''.(($marginInfo['margin_rate_services'] == '') ? '' : price($marginInfo['margin_rate_services'], null, null, null, null, 2).'%').''.(($marginInfo['mark_rate_services'] == '') ? '' : price($marginInfo['mark_rate_services'], null, null, null, null, 2).'%').'
    '.$langs->trans('TotalMargin').''.price($marginInfo['pv_total']).''.price($marginInfo['pa_total']).''.price($marginInfo['total_margin']).''.(($marginInfo['total_margin_rate'] == '') ? '' : price($marginInfo['total_margin_rate'], null, null, null, null, 2).'%').''.(($marginInfo['total_mark_rate'] == '') ? '' : price($marginInfo['total_mark_rate'], null, null, null, null, 2).'%').'
    '; diff --git a/htdocs/core/class/html.formorder.class.php b/htdocs/core/class/html.formorder.class.php index be169106621..9c75d15bae5 100644 --- a/htdocs/core/class/html.formorder.class.php +++ b/htdocs/core/class/html.formorder.class.php @@ -62,8 +62,11 @@ class FormOrder extends Form $options[$value] = $tmpsupplierorder->getLibStatut($short); } - if (is_array($selected)) $selectedarray = $selected; - else $selectedarray = explode(',', $selected); + if (is_array($selected)) { + $selectedarray = $selected; + } else { + $selectedarray = explode(',', $selected); + } print Form::multiselectarray($hmlname, $options, $selectedarray, 0); } diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php index dc6820c56fc..78212ca3580 100644 --- a/htdocs/core/class/html.formother.class.php +++ b/htdocs/core/class/html.formother.class.php @@ -76,21 +76,20 @@ class FormOther $sql = "SELECT rowid, label, fk_user"; $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; $sql .= " WHERE type = '".$this->db->escape($type)."'"; - if (!empty($fk_user)) $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model + if (!empty($fk_user)) { + $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model + } $sql .= " ORDER BY label"; $result = $this->db->query($sql); - if ($result) - { + if ($result) { print ''; - if ($useempty) - { + if ($useempty) { print ''; } $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $label = $obj->label; @@ -165,8 +162,7 @@ class FormOther $label .= ' ('.$tmpuser->getFullName($langs).')'; } - if ($selected == $obj->rowid) - { + if ($selected == $obj->rowid) { print ''."\n"; - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $this->db->fetch_object($resql); - if (($selected && $selected == $obj->taux) || $num == 1) - { + if (($selected && $selected == $obj->taux) || $num == 1) { $out .= ''."\n"; + if (!empty($conf->use_javascript_ajax)) { + $textforempty = ' '; // If we use ajaxcombo, we need   here to avoid to have an empty element that is too small. + } + if (!is_numeric($showempty)) { + $textforempty = $showempty; + } + $moreforfilter .= ''."\n"; //$moreforfilter .= ''; // Should use -1 to say nothing } - if (is_array($tab_categs)) - { - foreach ($tab_categs as $categ) - { + if (is_array($tab_categs)) { + foreach ($tab_categs as $categ) { $moreforfilter .= ''; } @@ -418,13 +407,11 @@ class FormOther $out = ''; // Enhance with select2 - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $comboenhancement = ajax_combobox($htmlname); - if ($comboenhancement) - { + if ($comboenhancement) { $out .= $comboenhancement; } } @@ -435,8 +422,12 @@ class FormOther $out .= ''; - if ($useempty) print ''; + if ($useempty) { + print ''; + } $j = 0; $level = 0; $this->_pLineSelect($j, 0, $tasksarray, $level, $selectedtask, $projectid, $disablechildoftaskid); @@ -620,13 +618,15 @@ class FormOther //var_dump($selectedproject."--".$selectedtask."--".$lines[$i]->fk_project."_".$lines[$i]->id); // $lines[$i]->id may be empty if project has no lines // Break on a new project - if ($parent == 0) // We are on a task at first level - { - if ($lines[$i]->fk_project != $lastprojectid) // Break found on project - { - if ($i > 0) print ''; + if ($parent == 0) { // We are on a task at first level + if ($lines[$i]->fk_project != $lastprojectid) { // Break found on project + if ($i > 0) { + print ''; + } print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''.img_picto($langs->trans("Refresh"), 'refresh', 'id="captcha_refresh_img"').''; + print ''; + print '
    '; print 'withnotifytiersatcreate ? ' checked="checked"' : '').'>'; print '
    '; print img_picto('', 'project').$formproject->select_projects(-1, GETPOST('projectid', 'int'), 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500'); @@ -415,14 +429,15 @@ class FormTicket // Other attributes $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $ticketstat, $this->action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { print $ticketstat->showOptionals($extrafields, 'create'); } print '
    '; - if ($withdolfichehead) print dol_get_fiche_end(); + if ($withdolfichehead) { + print dol_get_fiche_end(); + } print '
    '; print ''; @@ -503,7 +518,7 @@ class FormTicket print ' selected="selected"'; } elseif ($selected == $id) { print ' selected="selected"'; - } elseif ($arraytypes['use_default'] == "1" && !$empty) { + } elseif ($arraytypes['use_default'] == "1" && !$selected && !$empty) { print ' selected="selected"'; } @@ -598,7 +613,7 @@ class FormTicket print ' selected="selected"'; } elseif ($selected == $id) { print ' selected="selected"'; - } elseif ($arraycategories['use_default'] == "1" && !$empty) { + } elseif ($arraycategories['use_default'] == "1" && !$selected && !$empty) { print ' selected="selected"'; } @@ -699,7 +714,7 @@ class FormTicket print ' selected="selected"'; } elseif ($selected == $id) { print ' selected="selected"'; - } elseif ($arrayseverities['use_default'] == "1" && !$empty) { + } elseif ($arrayseverities['use_default'] == "1" && !$selected && !$empty) { print ' selected="selected"'; } @@ -747,7 +762,9 @@ class FormTicket // Set tmp user directory $vardir = $conf->user->dir_output."/".$user->id; $upload_dir = $vardir.'/temp/'; // TODO Add $keytoavoidconflict in upload_dir path - if (is_dir($upload_dir)) dol_delete_dir_recursive($upload_dir); + if (is_dir($upload_dir)) { + dol_delete_dir_recursive($upload_dir); + } $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined unset($_SESSION["listofpaths".$keytoavoidconflict]); @@ -768,23 +785,25 @@ class FormTicket $formmail = new FormMail($this->db); $addfileaction = 'addfile'; - if (!is_object($form)) $form = new Form($this->db); + if (!is_object($form)) { + $form = new Form($this->db); + } // Load translation files required by the page $langs->loadLangs(array('other', 'mails')); // Clear temp files. Must be done at beginning, before call of triggers - if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) - { + if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) { $this->clear_attached_files(); } // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $this->param['langsmodels']; - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $this->param['langsmodels']; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('other'); @@ -792,11 +811,9 @@ class FormTicket // Get message template for $this->param["models"] into c_email_templates $arraydefaultmessage = -1; - if ($this->param['models'] != 'none') - { + if ($this->param['models'] != 'none') { $model_id = 0; - if (array_key_exists('models_id', $this->param)) - { + if (array_key_exists('models_id', $this->param)) { $model_id = $this->param["models_id"]; } @@ -809,20 +826,23 @@ class FormTicket $listofmimes = array(); $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined - if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) - { - if (!empty($arraydefaultmessage->joinfiles) && is_array($this->param['fileinit'])) - { - foreach ($this->param['fileinit'] as $file) - { + if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) { + if (!empty($arraydefaultmessage->joinfiles) && is_array($this->param['fileinit'])) { + foreach ($this->param['fileinit'] as $file) { $this->add_attached_files($file, basename($file), dol_mimetype($file)); } } } - if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]); - if (!empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]); - if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]); + if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) { + $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]); + } + if (!empty($_SESSION["listofnames".$keytoavoidconflict])) { + $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]); + } + if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) { + $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]); + } // Define output language $outputlangs = $langs; @@ -888,8 +908,7 @@ class FormTicket print ''; // External users can't send message email - if ($user->rights->ticket->write && !$user->socid) - { + if ($user->rights->ticket->write && !$user->socid) { print ''."\n"; } @@ -1238,40 +1242,52 @@ function complete_dictionary_with_modules(&$taborder, &$tabname, &$tablib, &$tab //var_dump($objMod->dictionaries['tabname']); $nbtabname = $nbtablib = $nbtabsql = $nbtabsqlsort = $nbtabfield = $nbtabfieldvalue = $nbtabfieldinsert = $nbtabrowid = $nbtabcond = $nbtabfieldcheck = $nbtabhelp = 0; foreach ($objMod->dictionaries['tabname'] as $val) { - $nbtabname++; $taborder[] = max($taborder) + 1; $tabname[] = $val; + $nbtabname++; + $taborder[] = max($taborder) + 1; + $tabname[] = $val; } // Position foreach ($objMod->dictionaries['tablib'] as $val) { - $nbtablib++; $tablib[] = $val; + $nbtablib++; + $tablib[] = $val; } foreach ($objMod->dictionaries['tabsql'] as $val) { - $nbtabsql++; $tabsql[] = $val; + $nbtabsql++; + $tabsql[] = $val; } foreach ($objMod->dictionaries['tabsqlsort'] as $val) { - $nbtabsqlsort++; $tabsqlsort[] = $val; + $nbtabsqlsort++; + $tabsqlsort[] = $val; } foreach ($objMod->dictionaries['tabfield'] as $val) { - $nbtabfield++; $tabfield[] = $val; + $nbtabfield++; + $tabfield[] = $val; } foreach ($objMod->dictionaries['tabfieldvalue'] as $val) { - $nbtabfieldvalue++; $tabfieldvalue[] = $val; + $nbtabfieldvalue++; + $tabfieldvalue[] = $val; } foreach ($objMod->dictionaries['tabfieldinsert'] as $val) { - $nbtabfieldinsert++; $tabfieldinsert[] = $val; + $nbtabfieldinsert++; + $tabfieldinsert[] = $val; } foreach ($objMod->dictionaries['tabrowid'] as $val) { - $nbtabrowid++; $tabrowid[] = $val; + $nbtabrowid++; + $tabrowid[] = $val; } foreach ($objMod->dictionaries['tabcond'] as $val) { - $nbtabcond++; $tabcond[] = $val; + $nbtabcond++; + $tabcond[] = $val; } if (!empty($objMod->dictionaries['tabhelp'])) { foreach ($objMod->dictionaries['tabhelp'] as $val) { - $nbtabhelp++; $tabhelp[] = $val; + $nbtabhelp++; + $tabhelp[] = $val; } } if (!empty($objMod->dictionaries['tabfieldcheck'])) { foreach ($objMod->dictionaries['tabfieldcheck'] as $val) { - $nbtabfieldcheck++; $tabfieldcheck[] = $val; + $nbtabfieldcheck++; + $tabfieldcheck[] = $val; } } @@ -1438,15 +1454,15 @@ function complete_elementList_with_modules(&$elementList) $dirmod[$i] = $dir; //print "x".$modName." ".$orders[$i]."\n
    "; - if (!empty($objMod->module_parts['contactelement'])) { - if (is_array($objMod->module_parts['contactelement'])) { + if (!empty($objMod->module_parts['contactelement'])) { + if (is_array($objMod->module_parts['contactelement'])) { foreach ($objMod->module_parts['contactelement'] as $elem => $title) { $elementList[$elem] = $langs->trans($title); } } else { $elementList[$objMod->name] = $langs->trans($objMod->name); } - } + } $j++; $i++; diff --git a/htdocs/core/lib/agenda.lib.php b/htdocs/core/lib/agenda.lib.php index c30d0c3d392..939e6514c13 100644 --- a/htdocs/core/lib/agenda.lib.php +++ b/htdocs/core/lib/agenda.lib.php @@ -69,14 +69,12 @@ function print_actions_filter($form, $canedit, $status, $year, $month, $day, $sh } print ''; - if ($canedit) - { + if ($canedit) { print '
    '; // Type print ''; $multiselect = 0; - if (!empty($conf->global->MAIN_ENABLE_MULTISELECT_TYPE)) // We use an option here because it adds bugs when used on agenda page "peruser" and "list" - { + if (!empty($conf->global->MAIN_ENABLE_MULTISELECT_TYPE)) { // We use an option here because it adds bugs when used on agenda page "peruser" and "list" $multiselect = (!empty($conf->global->AGENDA_USE_EVENT_TYPE)); } print $formactions->select_type_actions($actioncode, "search_actioncode", $excludetype, (empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1), 0, $multiselect, 0, 'maxwidth500'); @@ -92,8 +90,7 @@ function print_actions_filter($form, $canedit, $status, $year, $month, $day, $sh print $form->select_dolgroups($usergroupid, 'usergroup', 1, '', !$canedit, '', '', '0', false, 'maxwidth500'); print '
    '; - if ($conf->resource->enabled) - { + if ($conf->resource->enabled) { include_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php'; $formresource = new FormResource($db); @@ -105,16 +102,14 @@ function print_actions_filter($form, $canedit, $status, $year, $month, $day, $sh } } - if (!empty($conf->societe->enabled) && $user->rights->societe->lire) - { + if (!empty($conf->societe->enabled) && $user->rights->societe->lire) { print '
    '; print img_picto($langs->trans("ThirdParty"), 'company', 'class="fawidth30 inline-block"'); print $form->select_company($socid, 'search_socid', '', ' ', 0, 0, null, 0, 'minwidth100 maxwidth500'); print '
    '; } - if (!empty($conf->projet->enabled) && $user->rights->projet->lire) - { + if (!empty($conf->projet->enabled) && $user->rights->projet->lire) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; $formproject = new FormProjets($db); @@ -124,8 +119,7 @@ function print_actions_filter($form, $canedit, $status, $year, $month, $day, $sh print ''; } - if ($canedit && !preg_match('/list/', $_SERVER["PHP_SELF"])) - { + if ($canedit && !preg_match('/list/', $_SERVER["PHP_SELF"])) { // Status print '
    '; print img_picto($langs->trans("Status"), 'setup', 'class="fawidth30 inline-block"'); @@ -165,17 +159,22 @@ function show_array_actions_to_do($max = 5) $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a LEFT JOIN "; $sql .= " ".MAIN_DB_PREFIX."c_actioncomm as c ON c.id = a.fk_action"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep2 > '".$db->idate($now)."'))"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } $sql .= " ORDER BY a.datep DESC, a.id DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '
    '; @@ -189,8 +188,7 @@ function show_array_actions_to_do($max = 5) $staticaction = new ActionComm($db); $customerstatic = new Client($db); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); @@ -204,8 +202,7 @@ function show_array_actions_to_do($max = 5) // print '
    '; print '"; // Statut @@ -268,17 +275,22 @@ function show_array_last_actions_done($max = 5) $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a LEFT JOIN "; $sql .= " ".MAIN_DB_PREFIX."c_actioncomm as c ON c.id = a.fk_action "; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; $sql .= " AND (a.percent >= 100 OR (a.percent = -1 AND a.datep2 <= '".$db->idate($now)."'))"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } $sql .= " ORDER BY a.datep2 DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '
    '; @@ -292,8 +304,7 @@ function show_array_last_actions_done($max = 5) $staticaction = new ActionComm($db); $customerstatic = new Societe($db); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); @@ -307,8 +318,7 @@ function show_array_last_actions_done($max = 5) //print '
    '; print '
    '; $checkbox_selected = (GETPOST('send_email') == "1" ? ' checked' : ''); print ' '; diff --git a/htdocs/core/class/html.formwebsite.class.php b/htdocs/core/class/html.formwebsite.class.php index 8cbb7967415..4210113f990 100644 --- a/htdocs/core/class/html.formwebsite.class.php +++ b/htdocs/core/class/html.formwebsite.class.php @@ -68,21 +68,17 @@ class FormWebsite $sql .= " WHERE 1 = 1"; $sql .= " ORDER BY rowid"; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $out .= ''; - if ($useempty == 1 || ($useempty == 2 && $num > 1)) - { + if ($useempty == 1 || ($useempty == 2 && $num > 1)) { print ''; } - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); - if ($selected == $obj->rowid || $selected == $obj->code) - { + if ($selected == $obj->rowid || $selected == $obj->code) { print '
    '.dol_trunc($obj->label,22).''; - if ($obj->socid > 0) - { + if ($obj->socid > 0) { $customerstatic->id = $obj->socid; $customerstatic->name = $obj->name; //$customerstatic->name_alias = $obj->name_alias; @@ -225,11 +222,21 @@ function show_array_actions_to_do($max = 5) // Date print ''.dol_print_date($datep, 'day').' '; $late = 0; - if ($obj->percent == 0 && $datep && $datep < time()) $late = 1; - if ($obj->percent == 0 && !$datep && $datep2 && $datep2 < time()) $late = 1; - if ($obj->percent > 0 && $obj->percent < 100 && $datep2 && $datep2 < time()) $late = 1; - if ($obj->percent > 0 && $obj->percent < 100 && !$datep2 && $datep && $datep < time()) $late = 1; - if ($late) print img_warning($langs->trans("Late")); + if ($obj->percent == 0 && $datep && $datep < time()) { + $late = 1; + } + if ($obj->percent == 0 && !$datep && $datep2 && $datep2 < time()) { + $late = 1; + } + if ($obj->percent > 0 && $obj->percent < 100 && $datep2 && $datep2 < time()) { + $late = 1; + } + if ($obj->percent > 0 && $obj->percent < 100 && !$datep2 && $datep && $datep < time()) { + $late = 1; + } + if ($late) { + print img_warning($langs->trans("Late")); + } print "'.dol_trunc($obj->label,24).''; - if ($obj->socid > 0) - { + if ($obj->socid > 0) { $customerstatic->id = $obj->socid; $customerstatic->name = $obj->name; //$customerstatic->name_alias = $obj->name_alias; @@ -411,8 +421,7 @@ function actions_prepare_head($object) $h++; // Tab to link resources - if ($conf->resource->enabled) - { + if ($conf->resource->enabled) { include_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php'; $resource = new DolResource($db); @@ -420,7 +429,9 @@ function actions_prepare_head($object) $listofresourcelinked = $resource->getElementResources($object->element, $object->id); $nbResources = (is_array($listofresourcelinked) ?count($listofresourcelinked) : 0); $head[$h][1] = $langs->trans("Resources"); - if ($nbResources > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.($nbResources).'' : ''); + if ($nbResources > 0) { + $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.($nbResources).'' : ''); + } $head[$h][2] = 'resources'; $h++; } @@ -433,7 +444,9 @@ function actions_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/comm/action/document.php?id='.$object->id; $head[$h][1] = $langs->trans("Documents"); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.($nbFiles + $nbLinks).'' : ''); + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.($nbFiles + $nbLinks).'' : ''); + } $head[$h][2] = 'documents'; $h++; @@ -484,8 +497,7 @@ function calendars_prepare_head($param) $h++; //if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) - if (!empty($conf->global->AGENDA_SHOW_PERTYPE)) - { + if (!empty($conf->global->AGENDA_SHOW_PERTYPE)) { $head[$h][0] = DOL_URL_ROOT.'/comm/action/pertype.php'.($param ? '?'.$param : ''); $head[$h][1] = $langs->trans("ViewPerType"); $head[$h][2] = 'cardpertype'; diff --git a/htdocs/core/lib/ajax.lib.php b/htdocs/core/lib/ajax.lib.php index f8dd34ce0ac..658d7816001 100644 --- a/htdocs/core/lib/ajax.lib.php +++ b/htdocs/core/lib/ajax.lib.php @@ -46,13 +46,19 @@ */ function ajax_autocompleter($selected, $htmlname, $url, $urloption = '', $minLength = 2, $autoselect = 0, $ajaxoptions = array(), $moreparams = '') { - if (empty($minLength)) $minLength = 1; + if (empty($minLength)) { + $minLength = 1; + } $dataforrenderITem = 'ui-autocomplete'; $dataforitem = 'ui-autocomplete-item'; // Allow two constant to use other values for backward compatibility - if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) $dataforrenderITem = constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM'); - if (defined('JS_QUERY_AUTOCOMPLETE_ITEM')) $dataforitem = constant('JS_QUERY_AUTOCOMPLETE_ITEM'); + if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) { + $dataforrenderITem = constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM'); + } + if (defined('JS_QUERY_AUTOCOMPLETE_ITEM')) { + $dataforitem = constant('JS_QUERY_AUTOCOMPLETE_ITEM'); + } // Input search_htmlname is original field // Input htmlname is a second input field used when using ajax autocomplete. @@ -137,9 +143,10 @@ function ajax_autocompleter($selected, $htmlname, $url, $urloption = '', $minLen update: update, textarea: textarea, pbq: item.pbq, type: item.type, qty: item.qty, discount: item.discount, - pricebasetype: item.pricebasetype, price_ht: item.price_ht, + pricebasetype: item.pricebasetype, + price_ht: item.price_ht, price_ttc: item.price_ttc, - up: item.up, description : item.description, + description : item.description, ref_customer: item.ref_customer } })); } @@ -152,32 +159,24 @@ function ajax_autocompleter($selected, $htmlname, $url, $urloption = '', $minLen console.log("We will trigger change on input '.$htmlname.' because of the select definition of autocomplete code for input#search_'.$htmlname.'"); console.log("Selected id = "+ui.item.id+" - If this value is null, it means you select a record with key that is null so selection is not effective"); - console.log("Propagate before some properties"); + console.log("Propagate before some properties retrieved by ajax into data-xxx properties"); - //console.log(ui.item); - //For supplier price - $("#'.$htmlname.'").attr("data-up", ui.item.up); - $("#'.$htmlname.'").attr("data-discount", ui.item.discount); + // For supplier price and customer when price by quantity is off + $("#'.$htmlname.'").attr("data-up", ui.item.price_ht); + $("#'.$htmlname.'").attr("data-base", ui.item.pricebasetype); $("#'.$htmlname.'").attr("data-qty", ui.item.qty); + $("#'.$htmlname.'").attr("data-discount", ui.item.discount); $("#'.$htmlname.'").attr("data-description", ui.item.description); $("#'.$htmlname.'").attr("data-ref-customer", ui.item.ref_customer); - - //For customer price - '; + '; if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { $script .= ' - $("#' . $htmlname . '").attr("data-pbq", ui.item.pbq); - $("#' . $htmlname . '").attr("data-pbqup", ui.item.price_ht); - $("#' . $htmlname . '").attr("data-pbqbase", ui.item.pricebasetype); - $("#' . $htmlname . '").attr("data-pbqqty", ui.item.qty); - $("#' . $htmlname . '").attr("data-pbqpercent", ui.item.discount); - '; - } else { - $script .= ' - $("#' . $htmlname . '").attr("data-up", ui.item.price_ht); - $("#' . $htmlname . '").attr("data-base", ui.item.pricebasetype); - $("#' . $htmlname . '").attr("data-qty", ui.item.qty); - $("#' . $htmlname . '").attr("data-discount", ui.item.discount); + // For customer price when PRODUIT_CUSTOMER_PRICES_BY_QTY is on + $("#'.$htmlname.'").attr("data-pbq", ui.item.pbq); + $("#'.$htmlname.'").attr("data-pbqup", ui.item.price_ht); + $("#'.$htmlname.'").attr("data-pbqbase", ui.item.pricebasetype); + $("#'.$htmlname.'").attr("data-pbqqty", ui.item.qty); + $("#'.$htmlname.'").attr("data-pbqpercent", ui.item.discount); '; } $script .= ' @@ -217,6 +216,7 @@ function ajax_autocompleter($selected, $htmlname, $url, $urloption = '', $minLen console.log("Make action update on each ui.item.update") // loop on each "update" fields $.each(ui.item.update, function(key, value) { + console.log("Set value "+value+" into #"+key); $("#" + key).val(value).trigger("change"); }); } @@ -419,14 +419,26 @@ function ajax_combobox($htmlname, $events = array(), $minLengthToAutocomplete = global $conf; // select2 can be disabled for smartphones - if (!empty($conf->browser->layout) && $conf->browser->layout == 'phone' && !empty($conf->global->MAIN_DISALLOW_SELECT2_WITH_SMARTPHONE)) return ''; + if (!empty($conf->browser->layout) && $conf->browser->layout == 'phone' && !empty($conf->global->MAIN_DISALLOW_SELECT2_WITH_SMARTPHONE)) { + return ''; + } - if (!empty($conf->global->MAIN_DISABLE_AJAX_COMBOX)) return ''; - if (empty($conf->use_javascript_ajax)) return ''; - if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) return ''; - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return ''; + if (!empty($conf->global->MAIN_DISABLE_AJAX_COMBOX)) { + return ''; + } + if (empty($conf->use_javascript_ajax)) { + return ''; + } + if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) { + return ''; + } + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + return ''; + } - if (empty($minLengthToAutocomplete)) $minLengthToAutocomplete = 0; + if (empty($minLengthToAutocomplete)) { + $minLengthToAutocomplete = 0; + } $tmpplugin = 'select2'; $msg = "\n".' @@ -456,11 +468,12 @@ function ajax_combobox($htmlname, $events = array(), $minLengthToAutocomplete = }, dropdownCssClass: \'ui-dialog\' })'; - if ($forcefocus) $msg .= '.select2(\'focus\')'; + if ($forcefocus) { + $msg .= '.select2(\'focus\')'; + } $msg .= ';'."\n"; - if (is_array($events) && count($events)) // If an array of js events to do were provided. - { + if (is_array($events) && count($events)) { // If an array of js events to do were provided. $msg .= ' jQuery("#'.$htmlname.'").change(function () { var obj = '.json_encode($events).'; @@ -500,7 +513,9 @@ function ajax_combobox($htmlname, $events = array(), $minLengthToAutocomplete = if (response.num) { var selecthtml_str = response.value; var selecthtml_dom=$.parseHTML(selecthtml_str); - $("#inputautocomplete"+htmlname).val(selecthtml_dom[0][0].innerHTML); + if (typeof(selecthtml_dom[0][0]) !== \'undefined\') { + $("#inputautocomplete"+htmlname).val(selecthtml_dom[0][0].innerHTML); + } } else { $("#inputautocomplete"+htmlname).val(""); } @@ -520,13 +535,13 @@ function ajax_combobox($htmlname, $events = array(), $minLengthToAutocomplete = * On/off button for constant * * @param string $code Name of constant - * @param array $input Array of options. ("disabled"|"enabled'|'set'|'del') => CSS element to switch, 'alert' => message to show, ... Example: array('disabled'=>array(0=>'cssid')) - * @param int $entity Entity to set. Use current entity if null. + * @param array $input Array of complementary actions to do if success ("disabled"|"enabled'|'set'|'del') => CSS element to switch, 'alert' => message to show, ... Example: array('disabled'=>array(0=>'cssid')) + * @param int $entity Entity. Current entity is used if null. * @param int $revertonoff Revert on/off * @param int $strict Use only "disabled" with delConstant and "enabled" with setConstant * @param int $forcereload Force to reload page if we click/change value (this is supported only when there is no 'alert' option in input) * @param string $marginleftonlyshort 1 = Add a short left margin on picto, 2 = Add a larger left margin on picto, 0 = No left margin. Works for fontawesome picto only. - * @param int $forcenoajax 1=Force to use a ahref link instead of ajax code. + * @param int $forcenoajax 1 = Force to use a ahref link instead of ajax code. * @return string */ function ajax_constantonoff($code, $input = array(), $entity = null, $revertonoff = 0, $strict = 0, $forcereload = 0, $marginleftonlyshort = 2, $forcenoajax = 0) @@ -534,12 +549,16 @@ function ajax_constantonoff($code, $input = array(), $entity = null, $revertonof global $conf, $langs, $user; $entity = ((isset($entity) && is_numeric($entity) && $entity >= 0) ? $entity : $conf->entity); - if (!isset($input)) $input = array(); + if (!isset($input)) { + $input = array(); + } - if (empty($conf->use_javascript_ajax) || $forcenoajax) - { - if (empty($conf->global->$code)) print ''.img_picto($langs->trans("Disabled"), 'off').''; - else print ''.img_picto($langs->trans("Enabled"), 'on').''; + if (empty($conf->use_javascript_ajax) || $forcenoajax) { + if (empty($conf->global->$code)) { + print ''.img_picto($langs->trans("Disabled"), 'off').''; + } else { + print ''.img_picto($langs->trans("Enabled"), 'on').''; + } } else { $out = "\n".' '; - if ($addlink) $out .= ' '.$langs->trans("Link").''; + if ($addlink) { + $out .= ' '.$langs->trans("Link").''; + } return $out; } @@ -8296,15 +8900,21 @@ function dolIsAllowedForPreview($file) global $conf; // Check .noexe extension in filename - if (preg_match('/\.noexe$/i', $file)) return 0; + if (preg_match('/\.noexe$/i', $file)) { + return 0; + } // Check mime types $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp'); - if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) $mime_preview[] = 'svg+xml'; + if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) { + $mime_preview[] = 'svg+xml'; + } //$mime_preview[]='vnd.oasis.opendocument.presentation'; //$mime_preview[]='archive'; $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview); - if ($num_mime !== false) return 1; + if ($num_mime !== false) { + return 1; + } // By default, not allowed for preview return 0; @@ -8330,102 +8940,377 @@ function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0) $tmpfile = preg_replace('/\.noexe$/', '', $file); // Plain text files - if (preg_match('/\.txt$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; } - if (preg_match('/\.rtx$/i', $tmpfile)) { $mime = 'text/richtext'; $imgmime = 'text.png'; $famime = 'file-text-o'; } - if (preg_match('/\.csv$/i', $tmpfile)) { $mime = 'text/csv'; $imgmime = 'text.png'; $famime = 'file-text-o'; } - if (preg_match('/\.tsv$/i', $tmpfile)) { $mime = 'text/tab-separated-values'; $imgmime = 'text.png'; $famime = 'file-text-o'; } - if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; } - if (preg_match('/\.ini$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'ini'; $famime = 'file-text-o'; } - if (preg_match('/\.md$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'md'; $famime = 'file-text-o'; } - if (preg_match('/\.css$/i', $tmpfile)) { $mime = 'text/css'; $imgmime = 'css.png'; $srclang = 'css'; $famime = 'file-text-o'; } - if (preg_match('/\.lang$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'lang'; $famime = 'file-text-o'; } + if (preg_match('/\.txt$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $famime = 'file-text-o'; + } + if (preg_match('/\.rtx$/i', $tmpfile)) { + $mime = 'text/richtext'; + $imgmime = 'text.png'; + $famime = 'file-text-o'; + } + if (preg_match('/\.csv$/i', $tmpfile)) { + $mime = 'text/csv'; + $imgmime = 'text.png'; + $famime = 'file-text-o'; + } + if (preg_match('/\.tsv$/i', $tmpfile)) { + $mime = 'text/tab-separated-values'; + $imgmime = 'text.png'; + $famime = 'file-text-o'; + } + if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $famime = 'file-text-o'; + } + if (preg_match('/\.ini$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $srclang = 'ini'; + $famime = 'file-text-o'; + } + if (preg_match('/\.md$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $srclang = 'md'; + $famime = 'file-text-o'; + } + if (preg_match('/\.css$/i', $tmpfile)) { + $mime = 'text/css'; + $imgmime = 'css.png'; + $srclang = 'css'; + $famime = 'file-text-o'; + } + if (preg_match('/\.lang$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $srclang = 'lang'; + $famime = 'file-text-o'; + } // Certificate files - if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; } + if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $famime = 'file-text-o'; + } // XML based (HTML/XML/XAML) - if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) { $mime = 'text/html'; $imgmime = 'html.png'; $srclang = 'html'; $famime = 'file-text-o'; } - if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) { $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xml'; $famime = 'file-text-o'; } - if (preg_match('/\.xaml$/i', $tmpfile)) { $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xaml'; $famime = 'file-text-o'; } + if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) { + $mime = 'text/html'; + $imgmime = 'html.png'; + $srclang = 'html'; + $famime = 'file-text-o'; + } + if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) { + $mime = 'text/xml'; + $imgmime = 'other.png'; + $srclang = 'xml'; + $famime = 'file-text-o'; + } + if (preg_match('/\.xaml$/i', $tmpfile)) { + $mime = 'text/xml'; + $imgmime = 'other.png'; + $srclang = 'xaml'; + $famime = 'file-text-o'; + } // Languages - if (preg_match('/\.bas$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'bas'; $famime = 'file-code-o'; } - if (preg_match('/\.(c)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'c'; $famime = 'file-code-o'; } - if (preg_match('/\.(cpp)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cpp'; $famime = 'file-code-o'; } - if (preg_match('/\.cs$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cs'; $famime = 'file-code-o'; } - if (preg_match('/\.(h)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'h'; $famime = 'file-code-o'; } - if (preg_match('/\.(java|jsp)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'java'; $famime = 'file-code-o'; } - if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o'; } - if (preg_match('/\.phtml$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o'; } - if (preg_match('/\.(pl|pm)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'pl.png'; $srclang = 'perl'; $famime = 'file-code-o'; } - if (preg_match('/\.sql$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'sql'; $famime = 'file-code-o'; } - if (preg_match('/\.js$/i', $tmpfile)) { $mime = 'text/x-javascript'; $imgmime = 'jscript.png'; $srclang = 'js'; $famime = 'file-code-o'; } + if (preg_match('/\.bas$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $srclang = 'bas'; + $famime = 'file-code-o'; + } + if (preg_match('/\.(c)$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $srclang = 'c'; + $famime = 'file-code-o'; + } + if (preg_match('/\.(cpp)$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $srclang = 'cpp'; + $famime = 'file-code-o'; + } + if (preg_match('/\.cs$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $srclang = 'cs'; + $famime = 'file-code-o'; + } + if (preg_match('/\.(h)$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $srclang = 'h'; + $famime = 'file-code-o'; + } + if (preg_match('/\.(java|jsp)$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $srclang = 'java'; + $famime = 'file-code-o'; + } + if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'php.png'; + $srclang = 'php'; + $famime = 'file-code-o'; + } + if (preg_match('/\.phtml$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'php.png'; + $srclang = 'php'; + $famime = 'file-code-o'; + } + if (preg_match('/\.(pl|pm)$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'pl.png'; + $srclang = 'perl'; + $famime = 'file-code-o'; + } + if (preg_match('/\.sql$/i', $tmpfile)) { + $mime = 'text/plain'; + $imgmime = 'text.png'; + $srclang = 'sql'; + $famime = 'file-code-o'; + } + if (preg_match('/\.js$/i', $tmpfile)) { + $mime = 'text/x-javascript'; + $imgmime = 'jscript.png'; + $srclang = 'js'; + $famime = 'file-code-o'; + } // Open office - if (preg_match('/\.odp$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.presentation'; $imgmime = 'ooffice.png'; $famime = 'file-powerpoint-o'; } - if (preg_match('/\.ods$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.spreadsheet'; $imgmime = 'ooffice.png'; $famime = 'file-excel-o'; } - if (preg_match('/\.odt$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.text'; $imgmime = 'ooffice.png'; $famime = 'file-word-o'; } + if (preg_match('/\.odp$/i', $tmpfile)) { + $mime = 'application/vnd.oasis.opendocument.presentation'; + $imgmime = 'ooffice.png'; + $famime = 'file-powerpoint-o'; + } + if (preg_match('/\.ods$/i', $tmpfile)) { + $mime = 'application/vnd.oasis.opendocument.spreadsheet'; + $imgmime = 'ooffice.png'; + $famime = 'file-excel-o'; + } + if (preg_match('/\.odt$/i', $tmpfile)) { + $mime = 'application/vnd.oasis.opendocument.text'; + $imgmime = 'ooffice.png'; + $famime = 'file-word-o'; + } // MS Office - if (preg_match('/\.mdb$/i', $tmpfile)) { $mime = 'application/msaccess'; $imgmime = 'mdb.png'; $famime = 'file-o'; } - if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) { $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o'; } - if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) { $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o'; } - if (preg_match('/\.xlt(x)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; } - if (preg_match('/\.xla(m)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; } - if (preg_match('/\.xls$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; } - if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) { $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; } - if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-powerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o'; } - if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) { $mime = 'application/x-mspowerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o'; } + if (preg_match('/\.mdb$/i', $tmpfile)) { + $mime = 'application/msaccess'; + $imgmime = 'mdb.png'; + $famime = 'file-o'; + } + if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) { + $mime = 'application/msword'; + $imgmime = 'doc.png'; + $famime = 'file-word-o'; + } + if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) { + $mime = 'application/msword'; + $imgmime = 'doc.png'; + $famime = 'file-word-o'; + } + if (preg_match('/\.xlt(x)?$/i', $tmpfile)) { + $mime = 'application/vnd.ms-excel'; + $imgmime = 'xls.png'; + $famime = 'file-excel-o'; + } + if (preg_match('/\.xla(m)?$/i', $tmpfile)) { + $mime = 'application/vnd.ms-excel'; + $imgmime = 'xls.png'; + $famime = 'file-excel-o'; + } + if (preg_match('/\.xls$/i', $tmpfile)) { + $mime = 'application/vnd.ms-excel'; + $imgmime = 'xls.png'; + $famime = 'file-excel-o'; + } + if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) { + $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + $imgmime = 'xls.png'; + $famime = 'file-excel-o'; + } + if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) { + $mime = 'application/vnd.ms-powerpoint'; + $imgmime = 'ppt.png'; + $famime = 'file-powerpoint-o'; + } + if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) { + $mime = 'application/x-mspowerpoint'; + $imgmime = 'ppt.png'; + $famime = 'file-powerpoint-o'; + } // Other - if (preg_match('/\.pdf$/i', $tmpfile)) { $mime = 'application/pdf'; $imgmime = 'pdf.png'; $famime = 'file-pdf-o'; } + if (preg_match('/\.pdf$/i', $tmpfile)) { + $mime = 'application/pdf'; + $imgmime = 'pdf.png'; + $famime = 'file-pdf-o'; + } // Scripts - if (preg_match('/\.bat$/i', $tmpfile)) { $mime = 'text/x-bat'; $imgmime = 'script.png'; $srclang = 'dos'; $famime = 'file-code-o'; } - if (preg_match('/\.sh$/i', $tmpfile)) { $mime = 'text/x-sh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; } - if (preg_match('/\.ksh$/i', $tmpfile)) { $mime = 'text/x-ksh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; } - if (preg_match('/\.bash$/i', $tmpfile)) { $mime = 'text/x-bash'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; } + if (preg_match('/\.bat$/i', $tmpfile)) { + $mime = 'text/x-bat'; + $imgmime = 'script.png'; + $srclang = 'dos'; + $famime = 'file-code-o'; + } + if (preg_match('/\.sh$/i', $tmpfile)) { + $mime = 'text/x-sh'; + $imgmime = 'script.png'; + $srclang = 'bash'; + $famime = 'file-code-o'; + } + if (preg_match('/\.ksh$/i', $tmpfile)) { + $mime = 'text/x-ksh'; + $imgmime = 'script.png'; + $srclang = 'bash'; + $famime = 'file-code-o'; + } + if (preg_match('/\.bash$/i', $tmpfile)) { + $mime = 'text/x-bash'; + $imgmime = 'script.png'; + $srclang = 'bash'; + $famime = 'file-code-o'; + } // Images - if (preg_match('/\.ico$/i', $tmpfile)) { $mime = 'image/x-icon'; $imgmime = 'image.png'; $famime = 'file-image-o'; } - if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) { $mime = 'image/jpeg'; $imgmime = 'image.png'; $famime = 'file-image-o'; } - if (preg_match('/\.png$/i', $tmpfile)) { $mime = 'image/png'; $imgmime = 'image.png'; $famime = 'file-image-o'; } - if (preg_match('/\.gif$/i', $tmpfile)) { $mime = 'image/gif'; $imgmime = 'image.png'; $famime = 'file-image-o'; } - if (preg_match('/\.bmp$/i', $tmpfile)) { $mime = 'image/bmp'; $imgmime = 'image.png'; $famime = 'file-image-o'; } - if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) { $mime = 'image/tiff'; $imgmime = 'image.png'; $famime = 'file-image-o'; } - if (preg_match('/\.svg$/i', $tmpfile)) { $mime = 'image/svg+xml'; $imgmime = 'image.png'; $famime = 'file-image-o'; } - if (preg_match('/\.webp$/i', $tmpfile)) { $mime = 'image/webp'; $imgmime = 'image.png'; $famime = 'file-image-o'; } + if (preg_match('/\.ico$/i', $tmpfile)) { + $mime = 'image/x-icon'; + $imgmime = 'image.png'; + $famime = 'file-image-o'; + } + if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) { + $mime = 'image/jpeg'; + $imgmime = 'image.png'; + $famime = 'file-image-o'; + } + if (preg_match('/\.png$/i', $tmpfile)) { + $mime = 'image/png'; + $imgmime = 'image.png'; + $famime = 'file-image-o'; + } + if (preg_match('/\.gif$/i', $tmpfile)) { + $mime = 'image/gif'; + $imgmime = 'image.png'; + $famime = 'file-image-o'; + } + if (preg_match('/\.bmp$/i', $tmpfile)) { + $mime = 'image/bmp'; + $imgmime = 'image.png'; + $famime = 'file-image-o'; + } + if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) { + $mime = 'image/tiff'; + $imgmime = 'image.png'; + $famime = 'file-image-o'; + } + if (preg_match('/\.svg$/i', $tmpfile)) { + $mime = 'image/svg+xml'; + $imgmime = 'image.png'; + $famime = 'file-image-o'; + } + if (preg_match('/\.webp$/i', $tmpfile)) { + $mime = 'image/webp'; + $imgmime = 'image.png'; + $famime = 'file-image-o'; + } // Calendar - if (preg_match('/\.vcs$/i', $tmpfile)) { $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o'; } - if (preg_match('/\.ics$/i', $tmpfile)) { $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o'; } + if (preg_match('/\.vcs$/i', $tmpfile)) { + $mime = 'text/calendar'; + $imgmime = 'other.png'; + $famime = 'file-text-o'; + } + if (preg_match('/\.ics$/i', $tmpfile)) { + $mime = 'text/calendar'; + $imgmime = 'other.png'; + $famime = 'file-text-o'; + } // Other - if (preg_match('/\.torrent$/i', $tmpfile)) { $mime = 'application/x-bittorrent'; $imgmime = 'other.png'; $famime = 'file-o'; } + if (preg_match('/\.torrent$/i', $tmpfile)) { + $mime = 'application/x-bittorrent'; + $imgmime = 'other.png'; + $famime = 'file-o'; + } // Audio - if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) { $mime = 'audio'; $imgmime = 'audio.png'; $famime = 'file-audio-o'; } + if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) { + $mime = 'audio'; + $imgmime = 'audio.png'; + $famime = 'file-audio-o'; + } // Video - if (preg_match('/\.ogv$/i', $tmpfile)) { $mime = 'video/ogg'; $imgmime = 'video.png'; $famime = 'file-video-o'; } - if (preg_match('/\.webm$/i', $tmpfile)) { $mime = 'video/webm'; $imgmime = 'video.png'; $famime = 'file-video-o'; } - if (preg_match('/\.avi$/i', $tmpfile)) { $mime = 'video/x-msvideo'; $imgmime = 'video.png'; $famime = 'file-video-o'; } - if (preg_match('/\.divx$/i', $tmpfile)) { $mime = 'video/divx'; $imgmime = 'video.png'; $famime = 'file-video-o'; } - if (preg_match('/\.xvid$/i', $tmpfile)) { $mime = 'video/xvid'; $imgmime = 'video.png'; $famime = 'file-video-o'; } - if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) { $mime = 'video'; $imgmime = 'video.png'; $famime = 'file-video-o'; } + if (preg_match('/\.mp4$/i', $tmpfile)) { + $mime = 'video/mp4'; + $imgmime = 'video.png'; + $famime = 'file-video-o'; + } + if (preg_match('/\.ogv$/i', $tmpfile)) { + $mime = 'video/ogg'; + $imgmime = 'video.png'; + $famime = 'file-video-o'; + } + if (preg_match('/\.webm$/i', $tmpfile)) { + $mime = 'video/webm'; + $imgmime = 'video.png'; + $famime = 'file-video-o'; + } + if (preg_match('/\.avi$/i', $tmpfile)) { + $mime = 'video/x-msvideo'; + $imgmime = 'video.png'; + $famime = 'file-video-o'; + } + if (preg_match('/\.divx$/i', $tmpfile)) { + $mime = 'video/divx'; + $imgmime = 'video.png'; + $famime = 'file-video-o'; + } + if (preg_match('/\.xvid$/i', $tmpfile)) { + $mime = 'video/xvid'; + $imgmime = 'video.png'; + $famime = 'file-video-o'; + } + if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) { + $mime = 'video'; + $imgmime = 'video.png'; + $famime = 'file-video-o'; + } // Archive - if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh)$/i', $tmpfile)) { $mime = 'archive'; $imgmime = 'archive.png'; $famime = 'file-archive-o'; } // application/xxx where zzz is zip, ... + if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) { + $mime = 'archive'; + $imgmime = 'archive.png'; + $famime = 'file-archive-o'; + } // application/xxx where zzz is zip, ... // Exe - if (preg_match('/\.(exe|com)$/i', $tmpfile)) { $mime = 'application/octet-stream'; $imgmime = 'other.png'; $famime = 'file-o'; } + if (preg_match('/\.(exe|com)$/i', $tmpfile)) { + $mime = 'application/octet-stream'; + $imgmime = 'other.png'; + $famime = 'file-o'; + } // Lib - if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) { $mime = 'library'; $imgmime = 'library.png'; $famime = 'file-o'; } + if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) { + $mime = 'library'; + $imgmime = 'library.png'; + $famime = 'file-o'; + } // Err - if (preg_match('/\.err$/i', $tmpfile)) { $mime = 'error'; $imgmime = 'error.png'; $famime = 'file-text-o'; } + if (preg_match('/\.err$/i', $tmpfile)) { + $mime = 'error'; + $imgmime = 'error.png'; + $famime = 'file-text-o'; + } // Return string - if ($mode == 1) - { + if ($mode == 1) { $tmp = explode('/', $mime); return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]); } - if ($mode == 2) - { + if ($mode == 2) { return $imgmime; } - if ($mode == 3) - { + if ($mode == 3) { return $srclang; } - if ($mode == 4) - { + if ($mode == 4) { return $famime; } return $mime; @@ -8445,17 +9330,16 @@ function getDictvalue($tablename, $field, $id, $checkentity = false, $rowidfield { global $dictvalues, $db, $langs; - if (!isset($dictvalues[$tablename])) - { + if (!isset($dictvalues[$tablename])) { $dictvalues[$tablename] = array(); $sql = 'SELECT * FROM '.$tablename.' WHERE 1'; // Here select * is allowed as it is generic code and we don't have list of fields - if ($checkentity) $sql .= ' AND entity IN (0,'.getEntity($tablename).')'; + if ($checkentity) { + $sql .= ' AND entity IN (0,'.getEntity($tablename).')'; + } $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $db->fetch_object($resql)) { $dictvalues[$tablename][$obj->{$rowidfield}] = $obj; } } else { @@ -8463,10 +9347,13 @@ function getDictvalue($tablename, $field, $id, $checkentity = false, $rowidfield } } - if (!empty($dictvalues[$tablename][$id])) return $dictvalues[$tablename][$id]->{$field}; // Found - else // Not found + if (!empty($dictvalues[$tablename][$id])) { + return $dictvalues[$tablename][$id]->{$field}; // Found + } else // Not found { - if ($id > 0) return $id; + if ($id > 0) { + return $id; + } return ''; } } @@ -8481,12 +9368,10 @@ function colorIsLight($stringcolor) { $stringcolor = str_replace('#', '', $stringcolor); $res = -1; - if (!empty($stringcolor)) - { + if (!empty($stringcolor)) { $res = 0; $tmp = explode(',', $stringcolor); - if (count($tmp) > 1) // This is a comma RGB ('255','255','255') - { + if (count($tmp) > 1) { // This is a comma RGB ('255','255','255') $r = $tmp[0]; $g = $tmp[1]; $b = $tmp[2]; @@ -8499,7 +9384,9 @@ function colorIsLight($stringcolor) $b = hexdec($hexb); } $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm - if ($bright > 0.6) $res = 1; + if ($bright > 0.6) { + $res = 1; + } } return $res; } @@ -8518,22 +9405,31 @@ function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms']; //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal); - if (empty($menuentry['enabled'])) return 0; // Entry disabled by condition - if ($type_user && $menuentry['module']) - { + if (empty($menuentry['enabled'])) { + return 0; // Entry disabled by condition + } + if ($type_user && $menuentry['module']) { $tmploops = explode('|', $menuentry['module']); $found = 0; - foreach ($tmploops as $tmploop) - { + foreach ($tmploops as $tmploop) { if (in_array($tmploop, $listofmodulesforexternal)) { - $found++; break; + $found++; + break; } } - if (!$found) return 0; // Entry is for menus all excluded to external users + if (!$found) { + return 0; // Entry is for menus all excluded to external users + } + } + if (!$menuentry['perms'] && $type_user) { + return 0; // No permissions and user is external + } + if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) { + return 0; // No permissions and option to hide when not allowed, even for internal user, is on + } + if (!$menuentry['perms']) { + return 2; // No permissions and user is external } - if (!$menuentry['perms'] && $type_user) return 0; // No permissions and user is external - if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) return 0; // No permissions and option to hide when not allowed, even for internal user, is on - if (!$menuentry['perms']) return 2; // No permissions and user is external return 1; } @@ -8583,7 +9479,7 @@ function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = ' // Override attr if (!empty($params['attr']) && is_array($params['attr'])) { - foreach ($params['attr']as $key => $value) { + foreach ($params['attr'] as $key => $value) { if ($key == 'class') { $attr['class'] .= ' '.$value; } elseif ($key == 'classOverride') { @@ -8640,18 +9536,21 @@ function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $st $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)); } elseif ($displayMode == 1) { $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort); - } // Use status with images (for backward compatibility) - elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) { + } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) { + // Use status with images (for backward compatibility) $return = ''; $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '' : ''); $htmlLabelShort = (in_array($displayMode, array(1, 2, 5)) ? '' : '').(!empty($html) ? $html : (!empty($statusLabelShort) ? $statusLabelShort : $statusLabel)).(in_array($displayMode, array(1, 2, 5)) ? '' : ''); // For small screen, we always use the short label instead of long label. - if (!empty($conf->dol_optimize_smallscreen)) - { - if ($displayMode == 0) $displayMode = 1; - elseif ($displayMode == 4) $displayMode = 2; - elseif ($displayMode == 6) $displayMode = 5; + if (!empty($conf->dol_optimize_smallscreen)) { + if ($displayMode == 0) { + $displayMode = 1; + } elseif ($displayMode == 4) { + $displayMode = 2; + } elseif ($displayMode == 6) { + $displayMode = 5; + } } // For backward compatibility. Image's filename are still in French, so we use this array to convert @@ -8685,8 +9584,8 @@ function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $st } else { // $displayMode >= 6 $return = $htmlLabel.' '.$htmlImg; } - } // Use new badge - elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) { + } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) { + // Use new badge $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort); $dolGetBadgeParams['attr']['class'] = 'badge-status'; @@ -8800,10 +9699,14 @@ function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $u } $class = 'btnTitle'; - if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-comment-dots'))) $class .= ' btnTitlePlus'; + if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-comment-dots'))) { + $class .= ' btnTitlePlus'; + } $useclassfortooltip = 1; - if (!empty($params['morecss'])) $class .= ' '.$params['morecss']; + if (!empty($params['morecss'])) { + $class .= ' '.$params['morecss']; + } $attr = array( 'class' => $class, @@ -8989,9 +9892,15 @@ function getElementProperties($element_type) $subelement = 'product'; } - if (empty($classfile)) $classfile = strtolower($subelement); - if (empty($classname)) $classname = ucfirst($subelement); - if (empty($classpath)) $classpath = $module.'/class'; + if (empty($classfile)) { + $classfile = strtolower($subelement); + } + if (empty($classname)) { + $classname = ucfirst($subelement); + } + if (empty($classpath)) { + $classpath = $module.'/class'; + } $element_properties = array( 'module' => $module, @@ -9018,14 +9927,12 @@ function fetchObjectByElement($element_id, $element_type, $element_ref = '') global $conf, $db; $element_prop = getElementProperties($element_type); - if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled) - { + if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled) { dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php'); $objecttmp = new $element_prop['classname']($db); $ret = $objecttmp->fetch($element_id, $element_ref); - if ($ret >= 0) - { + if ($ret >= 0) { return $objecttmp; } } @@ -9040,8 +9947,7 @@ function fetchObjectByElement($element_id, $element_type, $element_ref = '') */ function isAFileWithExecutableContent($filename) { - if (preg_match('/\.(htm|html|js|phar|php|php\d+|phtml|pht|pl|py|cgi|ksh|sh|shtml|bash|bat|cmd|wpk|exe|dmg)$/i', $filename)) - { + if (preg_match('/\.(htm|html|js|phar|php|php\d+|phtml|pht|pl|py|cgi|ksh|sh|shtml|bash|bat|cmd|wpk|exe|dmg)$/i', $filename)) { return true; } @@ -9173,16 +10079,14 @@ function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, return; } - if ($nbofloop === 0) - { + if ($nbofloop === 0) { // don't show a summary line return; } if ($num === 0) { $colspan = $tableColumnCount; - } - elseif ($num > $nbofloop) { + } elseif ($num > $nbofloop) { $colspan = $tableColumnCount; } else { $colspan = $tableColumnCount - 1; @@ -9222,27 +10126,31 @@ function readfileLowMemory($fullpath_original_file_osencoded, $method = -1) if ($method == -1) { $method = 0; - if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) $method = 1; - if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) $method = 2; + if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) { + $method = 1; + } + if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) { + $method = 2; + } } // Be sure we don't have output buffering enabled to have readfile working correctly - while (ob_get_level()) ob_end_flush(); + while (ob_get_level()) { + ob_end_flush(); + } // Solution 0 if ($method == 0) { readfile($fullpath_original_file_osencoded); - } - // Solution 1 - elseif ($method == 1) { + } elseif ($method == 1) { + // Solution 1 $handle = fopen($fullpath_original_file_osencoded, "rb"); while (!feof($handle)) { print fread($handle, 8192); } fclose($handle); - } - // Solution 2 - elseif ($method == 2) { + } elseif ($method == 2) { + // Solution 2 $handle1 = fopen($fullpath_original_file_osencoded, "rb"); $handle2 = fopen("php://output", "wb"); stream_copy_to_stream($handle1, $handle2); diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php index fcac069183e..9fd7f5e7e8a 100644 --- a/htdocs/core/lib/functions2.lib.php +++ b/htdocs/core/lib/functions2.lib.php @@ -83,8 +83,7 @@ function dolGetModulesDirs($subdir = '') $modulesdir = array(); - foreach ($conf->file->dol_document_root as $type => $dirroot) - { + foreach ($conf->file->dol_document_root as $type => $dirroot) { // Default core/modules dir if ($type === 'main') { $modulesdir[$dirroot.'/core/modules'.$subdir.'/'] = $dirroot.'/core/modules'.$subdir.'/'; @@ -92,16 +91,14 @@ function dolGetModulesDirs($subdir = '') // Scan dir from external modules $handle = @opendir($dirroot); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/disabled/', $file)) continue; // We discard module if it contains disabled into name. + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/disabled/', $file)) { + continue; // We discard module if it contains disabled into name. + } - if (is_dir($dirroot.'/'.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && $file != 'includes') - { - if (is_dir($dirroot.'/'.$file.'/core/modules'.$subdir.'/')) - { + if (is_dir($dirroot.'/'.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && $file != 'includes') { + if (is_dir($dirroot.'/'.$file.'/core/modules'.$subdir.'/')) { $modulesdir[$dirroot.'/'.$file.'/core/modules'.$subdir.'/'] = $dirroot.'/'.$file.'/core/modules'.$subdir.'/'; } } @@ -128,8 +125,12 @@ function dol_getDefaultFormat(Translate $outputlangs = null) $outputlangs = $langs; } - if ($outputlangs->defaultlang == 'ca_CA') $selected = 'CAP4'; // Canada - if ($outputlangs->defaultlang == 'en_US') $selected = 'USLetter'; // US + if ($outputlangs->defaultlang == 'ca_CA') { + $selected = 'CAP4'; // Canada + } + if ($outputlangs->defaultlang == 'en_US') { + $selected = 'USLetter'; // US + } return $selected; } @@ -146,35 +147,47 @@ function dol_print_file($langs, $filename, $searchalt = 0) global $conf; // Test if file is in lang directory - foreach ($langs->dir as $searchdir) - { + foreach ($langs->dir as $searchdir) { $formfile = ($searchdir."/langs/".$langs->defaultlang."/".$filename); dol_syslog('functions2::dol_print_file search file '.$formfile, LOG_DEBUG); - if (is_readable($formfile)) - { + if (is_readable($formfile)) { $content = file_get_contents($formfile); $isutf8 = utf8_check($content); - if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content); - elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content); - else print $content; + if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') { + print utf8_encode($content); + } elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') { + print utf8_decode($content); + } else { + print $content; + } return true; - } else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG); + } else { + dol_syslog('functions2::dol_print_file not found', LOG_DEBUG); + } if ($searchalt) { // Test si fichier dans repertoire de la langue alternative - if ($langs->defaultlang != "en_US") $formfilealt = $searchdir."/langs/en_US/".$filename; - else $formfilealt = $searchdir."/langs/fr_FR/".$filename; + if ($langs->defaultlang != "en_US") { + $formfilealt = $searchdir."/langs/en_US/".$filename; + } else { + $formfilealt = $searchdir."/langs/fr_FR/".$filename; + } dol_syslog('functions2::dol_print_file search alt file '.$formfilealt, LOG_DEBUG); //print 'getcwd='.getcwd().' htmlfilealt='.$formfilealt.' X '.file_exists(getcwd().'/'.$formfilealt); - if (is_readable($formfilealt)) - { + if (is_readable($formfilealt)) { $content = file_get_contents($formfilealt); $isutf8 = utf8_check($content); - if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content); - elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content); - else print $content; + if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') { + print utf8_encode($content); + } elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') { + print utf8_decode($content); + } else { + print $content; + } return true; - } else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG); + } else { + dol_syslog('functions2::dol_print_file not found', LOG_DEBUG); + } } } @@ -204,268 +217,437 @@ function dol_print_object_info($object, $usetable = 0) $deltadateforuser = round($deltadateforclient - $deltadateforserver); //print "x".$deltadateforserver." - ".$deltadateforclient." - ".$deltadateforuser; - if ($usetable) print ''; + if ($usetable) { + print '
    '; + } // Import key - if (!empty($object->import_key)) - { - if ($usetable) print ''; - else print '
    '; + if ($usetable) { + print ''; + } else { + print '
    '; + } } // User creation (old method using already loaded object and not id is kept for backward compatibility) - if (!empty($object->user_creation) || !empty($object->user_creation_id)) - { - if ($usetable) print ''; + } else { + print '
    '; } - if ($usetable) print ''; - else print '
    '; } // Date creation - if (!empty($object->date_creation)) - { - if ($usetable) print ''; - else print '
    '; + if ($deltadateforuser) { + print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_creation, "dayhour", "tzuserrel").'  '.$langs->trans("ClientHour"); + } + if ($usetable) { + print ''; + } else { + print '
    '; + } } // User change (old method using already loaded object and not id is kept for backward compatibility) - if (!empty($object->user_modification) || !empty($object->user_modification_id)) - { - if ($usetable) print ''; + } else { + print '
    '; } - if ($usetable) print ''; - else print '
    '; } // Date change - if (!empty($object->date_modification)) - { - if ($usetable) print ''; - else print '
    '; + if ($deltadateforuser) { + print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_modification, "dayhour", "tzuserrel").'  '.$langs->trans("ClientHour"); + } + if ($usetable) { + print ''; + } else { + print '
    '; + } } // User validation (old method using already loaded object and not id is kept for backward compatibility) - if (!empty($object->user_validation) || !empty($object->user_validation_id)) - { - if ($usetable) print ''; + } else { + print '
    '; } - if ($usetable) print ''; - else print '
    '; } // Date validation - if (!empty($object->date_validation)) - { - if ($usetable) print ''; - else print '
    '; + if ($deltadateforuser) { + print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_validation, "dayhour", 'tzuserrel').'  '.$langs->trans("ClientHour"); + } + if ($usetable) { + print ''; + } else { + print '
    '; + } } // User approve (old method using already loaded object and not id is kept for backward compatibility) - if (!empty($object->user_approve) || !empty($object->user_approve_id)) - { - if ($usetable) print ''; + } else { + print '
    '; } - if ($usetable) print ''; - else print '
    '; } // Date approve - if (!empty($object->date_approve)) - { - if ($usetable) print ''; - else print '
    '; + if ($deltadateforuser) { + print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_approve, "dayhour", 'tzuserrel').'  '.$langs->trans("ClientHour"); + } + if ($usetable) { + print ''; + } else { + print '
    '; + } } // User approve - if (!empty($object->user_approve_id2)) - { - if ($usetable) print ''; - else print '
    '; + if ($userstatic->id) { + print $userstatic->getNomUrl(-1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } + if ($usetable) { + print ''; + } else { + print '
    '; + } } // Date approve - if (!empty($object->date_approve2)) - { - if ($usetable) print ''; - else print '
    '; + if ($deltadateforuser) { + print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_approve2, "dayhour", 'tzuserrel').'  '.$langs->trans("ClientHour"); + } + if ($usetable) { + print ''; + } else { + print '
    '; + } } // User close - if (!empty($object->user_cloture) || !empty($object->user_closing)) - { - if (isset($object->user_cloture) && !empty($object->user_cloture)) $object->user_closing = $object->user_cloture; - if ($usetable) print ''; + } else { + print '
    '; } - if ($usetable) print ''; - else print '
    '; } // Date close - if (!empty($object->date_cloture) || !empty($object->date_closing)) - { - if (isset($object->date_cloture) && !empty($object->date_cloture)) $object->date_closing = $object->date_cloture; - if ($usetable) print ''; - else print '
    '; + if ($deltadateforuser) { + print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_closing, "dayhour", 'tzuserrel').'  '.$langs->trans("ClientHour"); + } + if ($usetable) { + print ''; + } else { + print '
    '; + } } // User conciliate - if (!empty($object->user_rappro)) - { - if ($usetable) print ''; + } else { + print '
    '; } - if ($usetable) print ''; - else print '
    '; } // Date conciliate - if (!empty($object->date_rappro)) - { - if ($usetable) print ''; - else print '
    '; + if ($deltadateforuser) { + print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_rappro, "dayhour", 'tzuserrel').'  '.$langs->trans("ClientHour"); + } + if ($usetable) { + print ''; + } else { + print '
    '; + } } // Date send - if (!empty($object->date_envoi)) - { - if ($usetable) print ''; - else print '
    '; + if ($deltadateforuser) { + print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_envoi, "dayhour", 'tzuserrel').'  '.$langs->trans("ClientHour"); + } + if ($usetable) { + print ''; + } else { + print '
    '; + } } - if ($usetable) print '
    '; + if (!empty($object->import_key)) { + if ($usetable) { + print '
    '; + } print $langs->trans("ImportedWithSet"); - if ($usetable) print ''; - else print ': '; + if ($usetable) { + print ''; + } else { + print ': '; + } print $object->import_key; - if ($usetable) print '
    '; + if (!empty($object->user_creation) || !empty($object->user_creation_id)) { + if ($usetable) { + print '
    '; + } print $langs->trans("CreatedBy"); - if ($usetable) print ''; - else print ': '; - if (is_object($object->user_creation)) - { - if ($object->user_creation->id) print $object->user_creation->getNomUrl(-1, '', 0, 0, 0); - else print $langs->trans("Unknown"); + if ($usetable) { + print ''; + } else { + print ': '; + } + if (is_object($object->user_creation)) { + if ($object->user_creation->id) { + print $object->user_creation->getNomUrl(-1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } } else { $userstatic = new User($db); $userstatic->fetch($object->user_creation_id ? $object->user_creation_id : $object->user_creation); - if ($userstatic->id) print $userstatic->getNomUrl(-1, '', 0, 0, 0); - else print $langs->trans("Unknown"); + if ($userstatic->id) { + print $userstatic->getNomUrl(-1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } + } + if ($usetable) { + print '
    '; + if (!empty($object->date_creation)) { + if ($usetable) { + print '
    '; + } print $langs->trans("DateCreation"); - if ($usetable) print ''; - else print ': '; + if ($usetable) { + print ''; + } else { + print ': '; + } print dol_print_date($object->date_creation, 'dayhour', 'tzserver'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_creation, "dayhour", "tzuserrel").'  '.$langs->trans("ClientHour"); - if ($usetable) print '
    '; + if (!empty($object->user_modification) || !empty($object->user_modification_id)) { + if ($usetable) { + print '
    '; + } print $langs->trans("ModifiedBy"); - if ($usetable) print ''; - else print ': '; - if (is_object($object->user_modification)) - { - if ($object->user_modification->id) print $object->user_modification->getNomUrl(-1, '', 0, 0, 0); - else print $langs->trans("Unknown"); + if ($usetable) { + print ''; + } else { + print ': '; + } + if (is_object($object->user_modification)) { + if ($object->user_modification->id) { + print $object->user_modification->getNomUrl(-1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } } else { $userstatic = new User($db); $userstatic->fetch($object->user_modification_id ? $object->user_modification_id : $object->user_modification); - if ($userstatic->id) print $userstatic->getNomUrl(-1, '', 0, 0, 0); - else print $langs->trans("Unknown"); + if ($userstatic->id) { + print $userstatic->getNomUrl(-1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } + } + if ($usetable) { + print '
    '; + if (!empty($object->date_modification)) { + if ($usetable) { + print '
    '; + } print $langs->trans("DateLastModification"); - if ($usetable) print ''; - else print ': '; + if ($usetable) { + print ''; + } else { + print ': '; + } print dol_print_date($object->date_modification, 'dayhour', 'tzserver'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_modification, "dayhour", "tzuserrel").'  '.$langs->trans("ClientHour"); - if ($usetable) print '
    '; + if (!empty($object->user_validation) || !empty($object->user_validation_id)) { + if ($usetable) { + print '
    '; + } print $langs->trans("ValidatedBy"); - if ($usetable) print ''; - else print ': '; - if (is_object($object->user_validation)) - { - if ($object->user_validation->id) print $object->user_validation->getNomUrl(-1, '', 0, 0, 0); - else print $langs->trans("Unknown"); + if ($usetable) { + print ''; + } else { + print ': '; + } + if (is_object($object->user_validation)) { + if ($object->user_validation->id) { + print $object->user_validation->getNomUrl(-1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } } else { $userstatic = new User($db); $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation); - if ($userstatic->id) print $userstatic->getNomUrl(-1, '', 0, 0, 0); - else print $langs->trans("Unknown"); + if ($userstatic->id) { + print $userstatic->getNomUrl(-1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } + } + if ($usetable) { + print '
    '; + if (!empty($object->date_validation)) { + if ($usetable) { + print '
    '; + } print $langs->trans("DateValidation"); - if ($usetable) print ''; - else print ': '; + if ($usetable) { + print ''; + } else { + print ': '; + } print dol_print_date($object->date_validation, 'dayhour', 'tzserver'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_validation, "dayhour", 'tzuserrel').'  '.$langs->trans("ClientHour"); - if ($usetable) print '
    '; + if (!empty($object->user_approve) || !empty($object->user_approve_id)) { + if ($usetable) { + print '
    '; + } print $langs->trans("ApprovedBy"); - if ($usetable) print ''; - else print ': '; - if (is_object($object->user_approve)) - { - if ($object->user_approve->id) print $object->user_approve->getNomUrl(-1, '', 0, 0, 0); - else print $langs->trans("Unknown"); + if ($usetable) { + print ''; + } else { + print ': '; + } + if (is_object($object->user_approve)) { + if ($object->user_approve->id) { + print $object->user_approve->getNomUrl(-1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } } else { $userstatic = new User($db); $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve); - if ($userstatic->id) print $userstatic->getNomUrl(-1, '', 0, 0, 0); - else print $langs->trans("Unknown"); + if ($userstatic->id) { + print $userstatic->getNomUrl(-1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } + } + if ($usetable) { + print '
    '; + if (!empty($object->date_approve)) { + if ($usetable) { + print '
    '; + } print $langs->trans("DateApprove"); - if ($usetable) print ''; - else print ': '; + if ($usetable) { + print ''; + } else { + print ': '; + } print dol_print_date($object->date_approve, 'dayhour', 'tzserver'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_approve, "dayhour", 'tzuserrel').'  '.$langs->trans("ClientHour"); - if ($usetable) print '
    '; + if (!empty($object->user_approve_id2)) { + if ($usetable) { + print '
    '; + } print $langs->trans("ApprovedBy"); - if ($usetable) print ''; - else print ': '; + if ($usetable) { + print ''; + } else { + print ': '; + } $userstatic = new User($db); $userstatic->fetch($object->user_approve_id2); - if ($userstatic->id) print $userstatic->getNomUrl(-1, '', 0, 0, 0); - else print $langs->trans("Unknown"); - if ($usetable) print '
    '; + if (!empty($object->date_approve2)) { + if ($usetable) { + print '
    '; + } print $langs->trans("DateApprove2"); - if ($usetable) print ''; - else print ': '; + if ($usetable) { + print ''; + } else { + print ': '; + } print dol_print_date($object->date_approve2, 'dayhour', 'tzserver'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_approve2, "dayhour", 'tzuserrel').'  '.$langs->trans("ClientHour"); - if ($usetable) print '
    '; + if (!empty($object->user_cloture) || !empty($object->user_closing)) { + if (isset($object->user_cloture) && !empty($object->user_cloture)) { + $object->user_closing = $object->user_cloture; + } + if ($usetable) { + print '
    '; + } print $langs->trans("ClosedBy"); - if ($usetable) print ''; - else print ': '; - if (is_object($object->user_closing)) - { - if ($object->user_closing->id) print $object->user_closing->getNomUrl(-1, '', 0, 0, 0); - else print $langs->trans("Unknown"); + if ($usetable) { + print ''; + } else { + print ': '; + } + if (is_object($object->user_closing)) { + if ($object->user_closing->id) { + print $object->user_closing->getNomUrl(-1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } } else { $userstatic = new User($db); $userstatic->fetch($object->user_closing); - if ($userstatic->id) print $userstatic->getNomUrl(-1, '', 0, 0, 0); - else print $langs->trans("Unknown"); + if ($userstatic->id) { + print $userstatic->getNomUrl(-1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } + } + if ($usetable) { + print '
    '; + if (!empty($object->date_cloture) || !empty($object->date_closing)) { + if (isset($object->date_cloture) && !empty($object->date_cloture)) { + $object->date_closing = $object->date_cloture; + } + if ($usetable) { + print '
    '; + } print $langs->trans("DateClosing"); - if ($usetable) print ''; - else print ': '; + if ($usetable) { + print ''; + } else { + print ': '; + } print dol_print_date($object->date_closing, 'dayhour', 'tzserver'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_closing, "dayhour", 'tzuserrel').'  '.$langs->trans("ClientHour"); - if ($usetable) print '
    '; + if (!empty($object->user_rappro)) { + if ($usetable) { + print '
    '; + } print $langs->trans("ConciliatedBy"); - if ($usetable) print ''; - else print ': '; - if (is_object($object->user_rappro)) - { - if ($object->user_rappro->id) print $object->user_rappro->getNomUrl(-1, '', 0, 0, 0); - else print $langs->trans("Unknown"); + if ($usetable) { + print ''; + } else { + print ': '; + } + if (is_object($object->user_rappro)) { + if ($object->user_rappro->id) { + print $object->user_rappro->getNomUrl(-1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } } else { $userstatic = new User($db); $userstatic->fetch($object->user_rappro); - if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0); - else print $langs->trans("Unknown"); + if ($userstatic->id) { + print $userstatic->getNomUrl(1, '', 0, 0, 0); + } else { + print $langs->trans("Unknown"); + } + } + if ($usetable) { + print '
    '; + if (!empty($object->date_rappro)) { + if ($usetable) { + print '
    '; + } print $langs->trans("DateConciliating"); - if ($usetable) print ''; - else print ': '; + if ($usetable) { + print ''; + } else { + print ': '; + } print dol_print_date($object->date_rappro, 'dayhour', 'tzserver'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_rappro, "dayhour", 'tzuserrel').'  '.$langs->trans("ClientHour"); - if ($usetable) print '
    '; + if (!empty($object->date_envoi)) { + if ($usetable) { + print '
    '; + } print $langs->trans("DateLastSend"); - if ($usetable) print ''; - else print ': '; + if ($usetable) { + print ''; + } else { + print ': '; + } print dol_print_date($object->date_envoi, 'dayhour', 'tzserver'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_envoi, "dayhour", 'tzuserrel').'  '.$langs->trans("ClientHour"); - if ($usetable) print '
    '; + if ($usetable) { + print '
    '; + } } @@ -514,10 +696,14 @@ function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0 $urlregex = ''; // SCHEME - if ($http) $urlregex .= "^(http:\/\/|https:\/\/)"; + if ($http) { + $urlregex .= "^(http:\/\/|https:\/\/)"; + } // USER AND PASS - if ($pass) $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)"; + if ($pass) { + $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)"; + } // HOSTNAME OR IP //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*"; // x allowed (ex. http://localhost, http://routerlogin) @@ -526,17 +712,24 @@ function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0 //use only one of the above // PORT - if ($port) $urlregex .= "(\:[0-9]{2,5})"; + if ($port) { + $urlregex .= "(\:[0-9]{2,5})"; + } // PATH - if ($path) $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/"; + if ($path) { + $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/"; + } // GET Query - if ($query) $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)"; + if ($query) { + $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)"; + } // ANCHOR - if ($anchor) $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$"; + if ($anchor) { + $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$"; + } // check - if (preg_match('/'.$urlregex.'/i', $url)) - { + if (preg_match('/'.$urlregex.'/i', $url)) { $ValidUrl = 1; } //print $urlregex.' - '.$url.' - '.$ValidUrl; @@ -552,16 +745,14 @@ function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0 */ function isValidVATID($company) { - if ($company->isInEEC()) // Syntax check rules for EEC countries - { + if ($company->isInEEC()) { // Syntax check rules for EEC countries /* Disabled because some companies can have an address in Irland and a vat number in France. - $vatprefix = $company->country_code; - if ($vatprefix == 'GR') $vatprefix = '(EL|GR)'; - elseif ($vatprefix == 'MC') $vatprefix = 'FR'; // Monaco is using french VAT numbers - else $vatprefix = preg_quote($vatprefix, '/');*/ + $vatprefix = $company->country_code; + if ($vatprefix == 'GR') $vatprefix = '(EL|GR)'; + elseif ($vatprefix == 'MC') $vatprefix = 'FR'; // Monaco is using french VAT numbers + else $vatprefix = preg_quote($vatprefix, '/');*/ $vatprefix = '[a-zA-Z][a-zA-Z]'; - if (!preg_match('/^'.$vatprefix.'[a-zA-Z0-9\-\.]{5,14}$/i', str_replace(' ', '', $company->tva_intra))) - { + if (!preg_match('/^'.$vatprefix.'[a-zA-Z0-9\-\.]{5,14}$/i', str_replace(' ', '', $company->tva_intra))) { return 0; } } @@ -582,8 +773,7 @@ function clean_url($url, $http = 1) // To include the minus sign in a char class, we must not escape it but put it at the end of the class // Also, there's no need of escape a dot sign in a class $regs = array(); - if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs)) - { + if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs)) { $proto = $regs[1]; $domain = $regs[2]; $port = isset($regs[3]) ? $regs[3] : ''; @@ -593,10 +783,8 @@ function clean_url($url, $http = 1) // Si http: defini on supprime le http (Si https on ne supprime pas) $newproto = $proto; - if ($http == 0) - { - if (preg_match('/^http:[\\/]+/i', $url)) - { + if ($http == 0) { + if (preg_match('/^http:[\\/]+/i', $url)) { $url = preg_replace('/^http:[\\/]+/i', '', $url); $newproto = ''; } @@ -606,7 +794,9 @@ function clean_url($url, $http = 1) $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain, '/').'/i', $newproto.strtolower($domain), $url); return $CleanUrl; - } else return $url; + } else { + return $url; + } } @@ -624,7 +814,9 @@ function clean_url($url, $http = 1) */ function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail = 4, $nbdisplaydomain = 3, $displaytld = true) { - if (!isValidEmail($mail))return ''; + if (!isValidEmail($mail)) { + return ''; + } $tab = explode('@', $mail); $tab2 = explode('.', $tab[1]); $string_replace = ''; @@ -633,8 +825,7 @@ function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail $mail_tld = ''; $nbofelem = count($tab2); - for ($i = 1; $i < $nbofelem && $displaytld; $i++) - { + for ($i = 1; $i < $nbofelem && $displaytld; $i++) { $mail_tld .= '.'.$tab2[$i]; } @@ -686,7 +877,9 @@ function array2tr($data, $troptions = '', $tdoptions = '') function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = '', $tdoptions = '') { $text = ''; - if ($tableMarkup) $text = ''; + if ($tableMarkup) { + $text = '
    '; + } foreach ($data as $key => $item) { if (is_array($item)) { $text .= array2tr($item, $troptions, $tdoptions); @@ -697,7 +890,9 @@ function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = ' $text .= ''; } } - if ($tableMarkup) $text .= '
    '; + if ($tableMarkup) { + $text .= '
    '; + } return $text; } @@ -721,15 +916,23 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ { global $conf, $user; - if (!is_object($objsoc)) $valueforccc = $objsoc; - elseif ($table == "commande_fournisseur" || $table == "facture_fourn") $valueforccc = dol_string_unaccent($objsoc->code_fournisseur); - else $valueforccc = dol_string_unaccent($objsoc->code_client); + if (!is_object($objsoc)) { + $valueforccc = $objsoc; + } elseif ($table == "commande_fournisseur" || $table == "facture_fourn") { + $valueforccc = dol_string_unaccent($objsoc->code_fournisseur); + } else { + $valueforccc = dol_string_unaccent($objsoc->code_client); + } $sharetable = $table; - if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function + if ($table == 'facture' || $table == 'invoice') { + $sharetable = 'invoicenumber'; // for getEntity function + } // Clean parameters - if ($date == '') $date = dol_now(); // We use local year and month of PHP server to search numbers + if ($date == '') { + $date = dol_now(); // We use local year and month of PHP server to search numbers + } // but we should use local year and month of user // For debugging @@ -742,8 +945,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $hasglobalcounter = false; $reg = array(); // Extract value for mask counter, mask raz and mask offset - if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg)) - { + if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg)) { $masktri = $reg[1].(!empty($reg[2]) ? $reg[2] : '').(!empty($reg[3]) ? $reg[3] : ''); $maskcounter = $reg[1]; $hasglobalcounter = true; @@ -756,12 +958,13 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskraz = -1; $maskoffset = 0; $resetEveryMonth = false; - if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits'; + if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) { + return 'ErrorCounterMustHaveMoreThan3Digits'; + } // Extract value for third party mask counter $regClientRef = array(); - if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) - { + if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) { $maskrefclient = $regClientRef[1].$regClientRef[2]; $maskrefclient_maskclientcode = $regClientRef[1]; $maskrefclient_maskcounter = $regClientRef[2]; @@ -769,19 +972,21 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskrefclient_clientcode = substr($valueforccc, 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code where n is length in mask $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like - if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits'; - } else $maskrefclient = ''; + if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) { + return 'ErrorCounterMustHaveMoreThan3Digits'; + } + } else { + $maskrefclient = ''; + } // fail if there is neither a global nor a third party counter - if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) - { + if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) { return 'ErrorBadMask'; } // Extract value for third party type $regType = array(); - if (preg_match('/\{(t+)\}/i', $mask, $regType)) - { + if (preg_match('/\{(t+)\}/i', $mask, $regType)) { $masktype = $regType[1]; $masktype_value = substr(preg_replace('/^TE_/', '', $objsoc->typent_code), 0, dol_strlen($regType[1])); // get n first characters of thirdpaty typent_code (where n is length in mask) $masktype_value = str_pad($masktype_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask @@ -791,10 +996,12 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ } // Extract value for user - $regType = array(); + $regType = array(); if (preg_match('/\{(u+)\}/i', $mask, $regType)) { $lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; - if (is_object($objuser)) $lastname = $objuser->lastname; + if (is_object($objuser)) { + $lastname = $objuser->lastname; + } $maskuser = $regType[1]; $maskuser_value = substr($lastname, 0, dol_strlen($regType[1])); // get n first characters of user firstname (where n is length in mask) @@ -809,15 +1016,13 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskpersonew = array(); $tmpmask = $mask; $regKey = array(); - while (preg_match('/\{([A-Z]+)\-([1-9])\}/', $tmpmask, $regKey)) - { + while (preg_match('/\{([A-Z]+)\-([1-9])\}/', $tmpmask, $regKey)) { $maskperso[$regKey[1]] = '{'.$regKey[1].'-'.$regKey[2].'}'; $maskpersonew[$regKey[1]] = str_pad('', $regKey[2], '_', STR_PAD_RIGHT); $tmpmask = preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask); } - if (strstr($mask, 'user_extra_')) - { + if (strstr($mask, 'user_extra_')) { $start = "{user_extra_"; $end = "\}"; $extra = get_string_between($mask, "user_extra_", "}"); @@ -831,8 +1036,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode); $maskwithonlyymcode = preg_replace('/\{(t+)\}/i', $masktype_value, $maskwithonlyymcode); $maskwithonlyymcode = preg_replace('/\{(u+)\}/i', $maskuser_value, $maskwithonlyymcode); - foreach ($maskperso as $key => $val) - { + foreach ($maskperso as $key => $val) { $maskwithonlyymcode = preg_replace('/'.preg_quote($val, '/').'/i', $maskpersonew[$key], $maskwithonlyymcode); } $maskwithnocode = $maskwithonlyymcode; @@ -846,8 +1050,12 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ //var_dump($reg); // If an offset is asked - if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]); - if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]); + if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) { + $maskoffset = preg_replace('/^\+/', '', $reg[2]); + } + if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) { + $maskoffset = preg_replace('/^\+/', '', $reg[3]); + } // Define $sqlwhere $sqlwhere = ''; @@ -855,14 +1063,19 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $yearoffsettype = false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x // If a restore to zero after a month is asked we check if there is already a value for this year. - if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) $yearoffsettype = preg_replace('/^@/', '', $reg[2]); - if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) $yearoffsettype = preg_replace('/^@/', '', $reg[3]); + if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) { + $yearoffsettype = preg_replace('/^@/', '', $reg[2]); + } + if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) { + $yearoffsettype = preg_replace('/^@/', '', $reg[3]); + } //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype; - if (is_numeric($yearoffsettype) && $yearoffsettype >= 1) + if (is_numeric($yearoffsettype) && $yearoffsettype >= 1) { $maskraz = $yearoffsettype; // For backward compatibility - elseif ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1)) + } elseif ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1)) { $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START; + } //print "maskraz=".$maskraz; // -1=no reset if ($maskraz > 0) { // A reset is required @@ -870,27 +1083,49 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskraz = date('m', $date); $resetEveryMonth = true; } - if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth'; + if ($maskraz > 12) { + return 'ErrorBadMaskBadRazMonth'; + } // Define posy, posm and reg - if ($maskraz > 1) // if reset is not first month, we need month and year into mask - { - if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; } elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; } else return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask'; + if ($maskraz > 1) { // if reset is not first month, we need month and year into mask + if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { + $posy = 2; + $posm = 3; + } elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { + $posy = 3; + $posm = 2; + } else { + return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask'; + } - if (dol_strlen($reg[$posy]) < 2) return 'ErrorCantUseRazWithYearOnOneDigit'; + if (dol_strlen($reg[$posy]) < 2) { + return 'ErrorCantUseRazWithYearOnOneDigit'; + } } else // if reset is for a specific month in year, we need year { - if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; } elseif (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; } elseif (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 0; } else return 'ErrorCantUseRazIfNoYearInMask'; + if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { + $posy = 3; + $posm = 2; + } elseif (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { + $posy = 2; + $posm = 3; + } elseif (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) { + $posy = 2; + $posm = 0; + } else { + return 'ErrorCantUseRazIfNoYearInMask'; + } } // Define length $yearlen = $posy ?dol_strlen($reg[$posy]) : 0; $monthlen = $posm ?dol_strlen($reg[$posm]) : 0; // Define pos - $yearpos = (dol_strlen($reg[1]) + 1); + $yearpos = (dol_strlen($reg[1]) + 1); $monthpos = ($yearpos + $yearlen); if ($posy == 3 && $posm == 2) { // if month is before year - $monthpos = (dol_strlen($reg[1]) + 1); - $yearpos = ($monthpos + $monthlen); + $monthpos = (dol_strlen($reg[1]) + 1); + $yearpos = ($monthpos + $monthlen); } //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n"; @@ -898,8 +1133,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $monthcomp = $maskraz; $yearcomp = 0; - if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') // $yearoffsettype is - or + - { + if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') { // $yearoffsettype is - or + $currentyear = date("Y", $date); $fiscaldate = dol_mktime('0', '0', '0', $maskraz, '1', $currentyear); $newyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear); @@ -907,22 +1141,33 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ //echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'
    '; // If after or equal of current fiscal date - if ($date >= $fiscaldate) - { + if ($date >= $fiscaldate) { // If before of next new year date - if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset = 1; - } // If after or equal of current new year date - elseif ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset = -1; - } // For backward compatibility - elseif (date("m", $date) < $maskraz && empty($resetEveryMonth)) { $yearoffset = -1; } // If current month lower that month of return to zero, year is previous year + if ($date < $nextnewyeardate && $yearoffsettype == '+') { + $yearoffset = 1; + } + } elseif ($date >= $newyeardate && $yearoffsettype == '-') { + // If after or equal of current new year date + $yearoffset = -1; + } + } elseif (date("m", $date) < $maskraz && empty($resetEveryMonth)) { + // For backward compatibility + $yearoffset = -1; + } // If current month lower that month of return to zero, year is previous year - if ($yearlen == 4) $yearcomp = sprintf("%04d", date("Y", $date) + $yearoffset); - elseif ($yearlen == 2) $yearcomp = sprintf("%02d", date("y", $date) + $yearoffset); - elseif ($yearlen == 1) $yearcomp = substr(date("y", $date), 2, 1) + $yearoffset; - if ($monthcomp > 1 && empty($resetEveryMonth)) // Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0) - { - if ($yearlen == 4) $yearcomp1 = sprintf("%04d", date("Y", $date) + $yearoffset + 1); - elseif ($yearlen == 2) $yearcomp1 = sprintf("%02d", date("y", $date) + $yearoffset + 1); + if ($yearlen == 4) { + $yearcomp = sprintf("%04d", date("Y", $date) + $yearoffset); + } elseif ($yearlen == 2) { + $yearcomp = sprintf("%02d", date("y", $date) + $yearoffset); + } elseif ($yearlen == 1) { + $yearcomp = substr(date("y", $date), 2, 1) + $yearoffset; + } + if ($monthcomp > 1 && empty($resetEveryMonth)) { // Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0) + if ($yearlen == 4) { + $yearcomp1 = sprintf("%04d", date("Y", $date) + $yearoffset + 1); + } elseif ($yearlen == 2) { + $yearcomp1 = sprintf("%02d", date("y", $date) + $yearoffset + 1); + } $sqlwhere .= "("; $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."'"; @@ -947,7 +1192,9 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ } else { $posnumstart = strrpos($maskwithnocode, $maskcounter); } // Pos of counter in final string (from 0 to ...) - if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence'; + if ($posnumstart < 0) { + return 'ErrorBadMaskFailedToLocatePosOfSequence'; + } $sqlstring = 'SUBSTRING('.$field.', '.($posnumstart + 1).', '.dol_strlen($maskcounter).')'; // Define $maskLike @@ -961,11 +1208,16 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike); $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike); $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskLike); - if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike); - if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike); - if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike); - foreach ($maskperso as $key => $val) - { + if ($maskrefclient) { + $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike); + } + if ($masktype) { + $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike); + } + if ($maskuser) { + $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike); + } + foreach ($maskperso as $key => $val) { $maskLike = str_replace(dol_string_nospecial($maskperso[$key]), $maskpersonew[$key], $maskLike); } @@ -975,32 +1227,39 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $sql .= " FROM ".MAIN_DB_PREFIX.$table; $sql .= " WHERE ".$field." LIKE '".$db->escape($maskLike)."'"; $sql .= " AND ".$field." NOT LIKE '(PROV%)'"; - if ($bentityon) // only if entity enable + if ($bentityon) { // only if entity enable $sql .= " AND entity IN (".getEntity($sharetable).")"; - elseif (!empty($forceentity)) + } elseif (!empty($forceentity)) { $sql .= " AND entity IN (".$forceentity.")"; - if ($where) $sql .= $where; - if ($sqlwhere) $sql .= ' AND '.$sqlwhere; + } + if ($where) { + $sql .= $where; + } + if ($sqlwhere) { + $sql .= ' AND '.$sqlwhere; + } //print $sql.'
    '; dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $counter = $obj->val; - } else dol_print_error($db); + } else { + dol_print_error($db); + } // Check if we must force counter to maskoffset - if (empty($counter)) $counter = $maskoffset; - elseif (preg_match('/[^0-9]/i', $counter)) - { + if (empty($counter)) { + $counter = $maskoffset; + } elseif (preg_match('/[^0-9]/i', $counter)) { $counter = 0; dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR); - } elseif ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter = $maskoffset; + } elseif ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) { + $counter = $maskoffset; + } - if ($mode == 'last') // We found value for counter = last counter value. Now need to get corresponding ref of invoice. - { + if ($mode == 'last') { // We found value for counter = last counter value. Now need to get corresponding ref of invoice. $counterpadded = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT); // Define $maskLike @@ -1013,47 +1272,61 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike); $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike); $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), $counterpadded, $maskLike); - if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike); - if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike); - if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike); + if ($maskrefclient) { + $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike); + } + if ($masktype) { + $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike); + } + if ($maskuser) { + $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike); + } $ref = ''; $sql = "SELECT ".$field." as ref"; $sql .= " FROM ".MAIN_DB_PREFIX.$table; $sql .= " WHERE ".$field." LIKE '".$db->escape($maskLike)."'"; $sql .= " AND ".$field." NOT LIKE '%PROV%'"; - if ($bentityon) // only if entity enable + if ($bentityon) { // only if entity enable $sql .= " AND entity IN (".getEntity($sharetable).")"; - elseif (!empty($forceentity)) + } elseif (!empty($forceentity)) { $sql .= " AND entity IN (".$forceentity.")"; - if ($where) $sql .= $where; - if ($sqlwhere) $sql .= ' AND '.$sqlwhere; + } + if ($where) { + $sql .= $where; + } + if ($sqlwhere) { + $sql .= ' AND '.$sqlwhere; + } dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $ref = $obj->ref; - } else dol_print_error($db); + if ($obj) { + $ref = $obj->ref; + } + } else { + dol_print_error($db); + } $numFinal = $ref; } elseif ($mode == 'next') { $counter++; // If value for $counter has a length higher than $maskcounter chars - if ($counter >= pow(10, dol_strlen($maskcounter))) - { + if ($counter >= pow(10, dol_strlen($maskcounter))) { $counter = 'ErrorMaxNumberReachForThisMask'; } - if (!empty($maskrefclient_maskcounter)) - { + if (!empty($maskrefclient_maskcounter)) { //print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n
    "; // Define $sqlstring $maskrefclient_posnumstart = strpos($maskwithnocode, $maskrefclient_maskcounter, strpos($maskwithnocode, $maskrefclient)); // Pos of counter in final string (from 0 to ...) - if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask'; + if ($maskrefclient_posnumstart <= 0) { + return 'ErrorBadMask'; + } $maskrefclient_sqlstring = 'SUBSTRING('.$field.', '.($maskrefclient_posnumstart + 1).', '.dol_strlen($maskrefclient_maskcounter).')'; //print "x".$sqlstring; @@ -1075,23 +1348,31 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskrefclient_sql .= " FROM ".MAIN_DB_PREFIX.$table; //$sql.= " WHERE ".$field." not like '(%'"; $maskrefclient_sql .= " WHERE ".$field." LIKE '".$db->escape($maskrefclient_maskLike)."'"; - if ($bentityon) // only if entity enable + if ($bentityon) { // only if entity enable $maskrefclient_sql .= " AND entity IN (".getEntity($sharetable).")"; - elseif (!empty($forceentity)) + } elseif (!empty($forceentity)) { $sql .= " AND entity IN (".$forceentity.")"; - if ($where) $maskrefclient_sql .= $where; //use the same optional where as general mask - if ($sqlwhere) $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask + } + if ($where) { + $maskrefclient_sql .= $where; //use the same optional where as general mask + } + if ($sqlwhere) { + $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask + } $maskrefclient_sql .= ' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode, $maskrefclient) + 1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$db->escape($maskrefclient_clientcode)."')"; dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG); $maskrefclient_resql = $db->query($maskrefclient_sql); - if ($maskrefclient_resql) - { + if ($maskrefclient_resql) { $maskrefclient_obj = $db->fetch_object($maskrefclient_resql); $maskrefclient_counter = $maskrefclient_obj->val; - } else dol_print_error($db); + } else { + dol_print_error($db); + } - if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) $maskrefclient_counter = $maskrefclient_maskoffset; + if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) { + $maskrefclient_counter = $maskrefclient_maskoffset; + } $maskrefclient_counter++; } @@ -1099,8 +1380,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $numFinal = $mask; // We replace special codes except refclient - if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') // yearoffsettype is - or +, so we don't want current year - { + if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') { // yearoffsettype is - or +, so we don't want current year $numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date) + $yearoffset, $numFinal); $numFinal = preg_replace('/\{yy\}/i', date("y", $date) + $yearoffset, $numFinal); $numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1) + $yearoffset, $numFinal); @@ -1120,8 +1400,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $numFinal = str_replace($maskbefore, $maskafter, $numFinal); // Now we replace the refclient - if ($maskrefclient) - { + if ($maskrefclient) { //print "maskrefclient=".$maskrefclient." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskrefclient_clientcode=".$maskrefclient_clientcode."\n
    ";exit; $maskrefclient_maskbefore = '{'.$maskrefclient.'}'; $maskrefclient_maskafter = $maskrefclient_clientcode.str_pad($maskrefclient_counter, dol_strlen($maskrefclient_maskcounter), "0", STR_PAD_LEFT); @@ -1129,16 +1408,14 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ } // Now we replace the type - if ($masktype) - { + if ($masktype) { $masktype_maskbefore = '{'.$masktype.'}'; $masktype_maskafter = $masktype_value; $numFinal = str_replace($masktype_maskbefore, $masktype_maskafter, $numFinal); } // Now we replace the user - if ($maskuser) - { + if ($maskuser) { $maskuser_maskbefore = '{'.$maskuser.'}'; $maskuser_maskafter = $maskuser_value; $numFinal = str_replace($maskuser_maskbefore, $maskuser_maskafter, $numFinal); @@ -1161,7 +1438,9 @@ function get_string_between($string, $start, $end) { $string = " ".$string; $ini = strpos($string, $start); - if ($ini == 0) return ""; + if ($ini == 0) { + return ""; + } $ini += strlen($start); $len = strpos($string, $end, $ini) - $ini; return substr($string, $ini, $len); @@ -1192,12 +1471,13 @@ function check_value($mask, $value) } $maskraz = -1; $maskoffset = 0; - if (dol_strlen($maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits'; + if (dol_strlen($maskcounter) < 3) { + return 'ErrorCounterMustHaveMoreThan3Digits'; + } // Extract value for third party mask counter $regClientRef = array(); - if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) - { + if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) { $maskrefclient = $regClientRef[1].$regClientRef[2]; $maskrefclient_maskclientcode = $regClientRef[1]; $maskrefclient_maskcounter = $regClientRef[2]; @@ -1205,12 +1485,15 @@ function check_value($mask, $value) $maskrefclient_clientcode = substr('', 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code to form maskrefclient_clientcode $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like - if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits'; - } else $maskrefclient = ''; + if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) { + return 'ErrorCounterMustHaveMoreThan3Digits'; + } + } else { + $maskrefclient = ''; + } // fail if there is neither a global nor a third party counter - if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) - { + if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) { return 'ErrorBadMask'; } @@ -1228,46 +1511,62 @@ function check_value($mask, $value) //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n
    "; // If an offset is asked - if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]); - if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]); + if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) { + $maskoffset = preg_replace('/^\+/', '', $reg[2]); + } + if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) { + $maskoffset = preg_replace('/^\+/', '', $reg[3]); + } // Define $sqlwhere // If a restore to zero after a month is asked we check if there is already a value for this year. - if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) $maskraz = preg_replace('/^@/', '', $reg[2]); - if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) $maskraz = preg_replace('/^@/', '', $reg[3]); - if ($maskraz >= 0) - { + if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) { + $maskraz = preg_replace('/^@/', '', $reg[2]); + } + if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) { + $maskraz = preg_replace('/^@/', '', $reg[3]); + } + if ($maskraz >= 0) { if ($maskraz == 99) { $maskraz = date('m'); $resetEveryMonth = true; } - if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth'; + if ($maskraz > 12) { + return 'ErrorBadMaskBadRazMonth'; + } // Define reg - if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask'; - if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazIfNoYearInMask'; + if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { + return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask'; + } + if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) { + return 'ErrorCantUseRazIfNoYearInMask'; + } //print "x".$maskwithonlyymcode." ".$maskraz; } //print "masktri=".$masktri." maskcounter=".$maskcounter." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskraz=".$maskraz." maskoffset=".$maskoffset."
    \n"; if (function_exists('mb_strrpos')) { $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 0, 'UTF-8'); - } - else { + } else { $posnumstart = strrpos($maskwithnocode, $maskcounter); } // Pos of counter in final string (from 0 to ...) - if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence'; + if ($posnumstart < 0) { + return 'ErrorBadMaskFailedToLocatePosOfSequence'; + } // Check we have a number in $value at position ($posnumstart+1).', '.dol_strlen($maskcounter) // TODO - // Check length - $len = dol_strlen($maskwithnocode); - if (dol_strlen($value) != $len) $result = -1; + // Check length + $len = dol_strlen($maskwithnocode); + if (dol_strlen($value) != $len) { + $result = -1; + } - dol_syslog("functions2::check_value result=".$result, LOG_DEBUG); - return $result; + dol_syslog("functions2::check_value result=".$result, LOG_DEBUG); + return $result; } /** @@ -1281,10 +1580,18 @@ function check_value($mask, $value) function binhex($bin, $pad = false, $upper = false) { $last = dol_strlen($bin) - 1; - for ($i = 0; $i <= $last; $i++) { $x += $bin[$last - $i] * pow(2, $i); } + for ($i = 0; $i <= $last; $i++) { + $x += $bin[$last - $i] * pow(2, $i); + } $x = dechex($x); - if ($pad) { while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) { $x = "0$x"; } } - if ($upper) { $x = strtoupper($x); } + if ($pad) { + while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) { + $x = "0$x"; + } + } + if ($upper) { + $x = strtoupper($x); + } return $x; } @@ -1298,8 +1605,7 @@ function hexbin($hexa) { $bin = ''; $strLength = dol_strlen($hexa); - for ($i = 0; $i < $strLength; $i++) - { + for ($i = 0; $i < $strLength; $i++) { $bin .= str_pad(decbin(hexdec($hexa[$i])), 4, '0', STR_PAD_LEFT); } return $bin; @@ -1315,8 +1621,7 @@ function numero_semaine($time) { $stime = strftime('%Y-%m-%d', $time); - if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg)) - { + if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg)) { // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS' $annee = $reg[1]; $mois = $reg[2]; @@ -1324,31 +1629,29 @@ function numero_semaine($time) } /* - * Norme ISO-8601: - * - La semaine 1 de toute annee est celle qui contient le 4 janvier ou que la semaine 1 de toute annee est celle qui contient le 1er jeudi de janvier. - * - La majorite des annees ont 52 semaines mais les annees qui commence un jeudi et les annees bissextiles commencant un mercredi en possede 53. - * - Le 1er jour de la semaine est le Lundi - */ + * Norme ISO-8601: + * - La semaine 1 de toute annee est celle qui contient le 4 janvier ou que la semaine 1 de toute annee est celle qui contient le 1er jeudi de janvier. + * - La majorite des annees ont 52 semaines mais les annees qui commence un jeudi et les annees bissextiles commencant un mercredi en possede 53. + * - Le 1er jour de la semaine est le Lundi + */ // Definition du Jeudi de la semaine - if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) // Dimanche - $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60; - elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) // du Lundi au Mercredi - $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60; - elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) // du Vendredi au Samedi - $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60; - else // Jeudi - $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee); + if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) { // Dimanche + $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60; + } elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) { // du Lundi au Mercredi + $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60; + } elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) { // du Vendredi au Samedi + $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60; + } else { // Jeudi + $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee); + } // Definition du premier Jeudi de l'annee - if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 0) // Dimanche - { + if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 0) { // Dimanche $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + 4 * 24 * 60 * 60; - } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) < 4) // du Lundi au Mercredi - { + } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) < 4) { // du Lundi au Mercredi $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (4 - date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)))) * 24 * 60 * 60; - } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) > 4) // du Vendredi au Samedi - { + } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) > 4) { // du Vendredi au Samedi $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (7 - (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) - 4)) * 24 * 60 * 60; } else // Jeudi { @@ -1365,11 +1668,9 @@ function numero_semaine($time) ) + 1; // Cas particulier de la semaine 53 - if ($numeroSemaine == 53) - { + if ($numeroSemaine == 53) { // Les annees qui commence un Jeudi et les annees bissextiles commencant un Mercredi en possede 53 - if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 4 || (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 3 && date("z", mktime(12, 0, 0, 12, 31, date("Y", $jeudiSemaine))) == 365)) - { + if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 4 || (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 3 && date("z", mktime(12, 0, 0, 12, 31, date("Y", $jeudiSemaine))) == 365)) { $numeroSemaine = 53; } else { $numeroSemaine = 1; @@ -1392,20 +1693,17 @@ function numero_semaine($time) function weight_convert($weight, &$from_unit, $to_unit) { /* Pour convertire 320 gr en Kg appeler - * $f = -3 - * weigh_convert(320, $f, 0) retournera 0.32 - * - */ - while ($from_unit <> $to_unit) - { - if ($from_unit > $to_unit) - { + * $f = -3 + * weigh_convert(320, $f, 0) retournera 0.32 + * + */ + while ($from_unit <> $to_unit) { + if ($from_unit > $to_unit) { $weight = $weight * 10; $from_unit = $from_unit - 1; $weight = weight_convert($weight, $from_unit, $to_unit); } - if ($from_unit < $to_unit) - { + if ($from_unit < $to_unit) { $weight = $weight / 10; $from_unit = $from_unit + 1; $weight = weight_convert($weight, $from_unit, $to_unit); @@ -1429,7 +1727,9 @@ function weight_convert($weight, &$from_unit, $to_unit) function dol_set_user_param($db, $conf, &$user, $tab) { // Verification parametres - if (count($tab) < 1) return -1; + if (count($tab) < 1) { + return -1; + } $db->begin(); @@ -1439,9 +1739,10 @@ function dol_set_user_param($db, $conf, &$user, $tab) $sql .= " AND entity = ".$conf->entity; $sql .= " AND param in ("; $i = 0; - foreach ($tab as $key => $value) - { - if ($i > 0) $sql .= ','; + foreach ($tab as $key => $value) { + if ($i > 0) { + $sql .= ','; + } $sql .= "'".$db->escape($key)."'"; $i++; } @@ -1449,26 +1750,22 @@ function dol_set_user_param($db, $conf, &$user, $tab) dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); $db->rollback(); return -1; } - foreach ($tab as $key => $value) - { + foreach ($tab as $key => $value) { // Set new parameters - if ($value) - { + if ($value) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,entity,param,value)"; $sql .= " VALUES (".$user->id.",".$conf->entity.","; $sql .= " '".$db->escape($key)."','".$db->escape($value)."')"; dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG); $result = $db->query($sql); - if (!$result) - { + if (!$result) { dol_print_error($db); $db->rollback(); return -1; @@ -1494,8 +1791,7 @@ function dol_set_user_param($db, $conf, &$user, $tab) function dol_print_reduction($reduction, $langs) { $string = ''; - if ($reduction == 100) - { + if ($reduction == 100) { $string = $langs->transnoentities("Offered"); } else { $string = vatrate($reduction, true); @@ -1513,8 +1809,11 @@ function dol_print_reduction($reduction, $langs) */ function version_os($option = '') { - if ($option == 'smr') $osversion = php_uname('s').' '.php_uname('m').' '.php_uname('r'); - else $osversion = php_uname(); + if ($option == 'smr') { + $osversion = php_uname('s').' '.php_uname('m').' '.php_uname('r'); + } else { + $osversion = php_uname(); + } return $osversion; } @@ -1573,20 +1872,17 @@ function getListOfModels($db, $type, $maxfilenamelength = 0) dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $found = 1; $obj = $db->fetch_object($resql); // If this generation module needs to scan a directory, then description field is filled // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...). - if (!empty($obj->description)) // A list of directories to scan is defined - { + if (!empty($obj->description)) { // A list of directories to scan is defined include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $const = $obj->description; @@ -1597,23 +1893,24 @@ function getListOfModels($db, $type, $maxfilenamelength = 0) // Now we add models found in directories scanned $listofdir = explode(',', $dirtoscan); - foreach ($listofdir as $key=>$tmpdir) - { + foreach ($listofdir as $key => $tmpdir) { $tmpdir = trim($tmpdir); $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); - if (!$tmpdir) { unset($listofdir[$key]); continue; } - if (is_dir($tmpdir)) - { + if (!$tmpdir) { + unset($listofdir[$key]); + continue; + } + if (is_dir($tmpdir)) { // all type of template is allowed $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0); - if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); + if (count($tmpfiles)) { + $listoffiles = array_merge($listoffiles, $tmpfiles); + } } } - if (count($listoffiles)) - { - foreach ($listoffiles as $record) - { + if (count($listoffiles)) { + foreach ($listoffiles as $record) { $max = ($maxfilenamelength ? $maxfilenamelength : 28); $liste[$obj->id.':'.$record['fullname']] = dol_trunc($record['name'], $max, 'middle'); } @@ -1621,12 +1918,10 @@ function getListOfModels($db, $type, $maxfilenamelength = 0) $liste[0] = $obj->label.': '.$langs->trans("None"); } } else { - if ($type == 'member' && $obj->doc_template_name == 'standard') // Special case, if member template, we add variant per format - { + if ($type == 'member' && $obj->doc_template_name == 'standard') { // Special case, if member template, we add variant per format global $_Avery_Labels; include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php'; - foreach ($_Avery_Labels as $key => $val) - { + foreach ($_Avery_Labels as $key => $val) { $liste[$obj->id.':'.$key] = ($obj->label ? $obj->label : $obj->doc_template_name).' '.$val['name']; } } else { @@ -1641,8 +1936,11 @@ function getListOfModels($db, $type, $maxfilenamelength = 0) return -1; } - if ($found) return $liste; - else return 0; + if ($found) { + return $liste; + } else { + return 0; + } } /** @@ -1657,10 +1955,14 @@ function is_ip($ip) // First we test if it is a valid IPv4 if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { // Then we test if it is a private range - if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2; + if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) { + return 2; + } // Then we test if it is a reserved range - if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0; + if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) { + return 0; + } return 1; } @@ -1715,8 +2017,7 @@ function getSoapParams() $timeout = (empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 10 : $conf->global->MAIN_USE_CONNECT_TIMEOUT); // Connection timeout $response_timeout = (empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT); // Response timeout //print extension_loaded('soap'); - if ($proxyuse) - { + if ($proxyuse) { $params = array('connection_timeout'=>$timeout, 'response_timeout'=>$response_timeout, 'proxy_use' => 1, @@ -1761,12 +2062,10 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '') if (preg_match('/^([^@]+)@([^@]+)$/i', $objecttype, $regs)) { $myobject = $regs[1]; $module = $regs[2]; - } - else { + } else { // Parse $objecttype (ex: project_task) $module = $myobject = $objecttype; - if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) - { + if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) { $module = $regs[1]; $myobject = $regs[2]; } @@ -1828,10 +2127,15 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '') $classpath = 'mrp/class'; $module = 'mrp'; $myobject = 'mo'; + } elseif ($objecttype == 'productlot') { + $classpath = 'product/stock/class'; + $module = 'stock'; + $myobject = 'productlot'; } // Generic case for $classfile and $classname - $classfile = strtolower($myobject); $classname = ucfirst($myobject); + $classfile = strtolower($myobject); + $classname = ucfirst($myobject); //print "objecttype=".$objecttype." module=".$module." subelement=".$subelement." classfile=".$classfile." classname=".$classname." classpath=".$classpath; if ($objecttype == 'invoice_supplier') { @@ -1844,26 +2148,21 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '') $classname = 'CommandeFournisseur'; $classpath = 'fourn/class'; $module = 'fournisseur'; - } - elseif ($objecttype == 'supplier_proposal') { + } elseif ($objecttype == 'supplier_proposal') { $classfile = 'supplier_proposal'; $classname = 'SupplierProposal'; $classpath = 'supplier_proposal/class'; $module = 'supplier_proposal'; - } - elseif ($objecttype == 'stock') { + } elseif ($objecttype == 'stock') { $classpath = 'product/stock/class'; $classfile = 'entrepot'; $classname = 'Entrepot'; } - if (!empty($conf->$module->enabled)) - { + if (!empty($conf->$module->enabled)) { $res = dol_include_once('/'.$classpath.'/'.$classfile.'.class.php'); - if ($res) - { - if (class_exists($classname)) - { + if ($res) { + if (class_exists($classname)) { $object = new $classname($db); $res = $object->fetch($objectid); if ($res > 0) { @@ -1872,7 +2171,9 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '') $ret = $langs->trans('Deleted'); } unset($object); - } else dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR); + } else { + dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR); + } } } return $ret; @@ -1896,33 +2197,30 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) // Get list of all id in array listofid and all parents in array listofparentid $sql = 'SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $listofid[] = $obj->rowid; - if ($obj->parent_id > 0) $listofparentid[$obj->rowid] = $obj->parent_id; + if ($obj->parent_id > 0) { + $listofparentid[$obj->rowid] = $obj->parent_id; + } $i++; } } else { dol_print_error($db); } - if (count($listofid)) - { + if (count($listofid)) { print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."
    \n"; // Check loops on each other $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid"; // So we update only records linked to themself $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $nb = $db->affected_rows($sql); - if ($nb > 0) - { + if ($nb > 0) { print '
    Some record that were parent of themself were cleaned.'; } @@ -1932,17 +2230,15 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) // Check other loops $listofidtoclean = array(); - foreach ($listofparentid as $id => $pid) - { + foreach ($listofparentid as $id => $pid) { // Check depth //print 'Analyse record id='.$id.' with parent '.$pid.'
    '; - $cursor = $id; $arrayidparsed = array(); // We start from child $id - while ($cursor > 0) - { + $cursor = $id; + $arrayidparsed = array(); // We start from child $id + while ($cursor > 0) { $arrayidparsed[$cursor] = 1; - if ($arrayidparsed[$listofparentid[$cursor]]) // We detect a loop. A record with a parent that was already into child - { + if ($arrayidparsed[$listofparentid[$cursor]]) { // We detect a loop. A record with a parent that was already into child print 'Found a loop between id '.$id.' - '.$cursor.'
    '; unset($arrayidparsed); $listofidtoclean[$cursor] = $id; @@ -1951,18 +2247,18 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) $cursor = $listofparentid[$cursor]; } - if (count($listofidtoclean)) break; + if (count($listofidtoclean)) { + break; + } } $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree; $sql .= " SET ".$fieldfkparent." = 0"; $sql .= " WHERE rowid IN (".join(',', $listofidtoclean).")"; // So we update only records detected wrong $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $nb = $db->affected_rows($sql); - if ($nb > 0) - { + if ($nb > 0) { // Removed orphelins records print '
    Some records were detected to have parent that is a child, we set them as root record for id: '; print join(',', $listofidtoclean); @@ -1977,11 +2273,9 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) $sql .= " SET ".$fieldfkparent." = 0"; $sql .= " WHERE ".$fieldfkparent." NOT IN (".join(',', $listofid).")"; // So we update only records linked to a non existing parent $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $nb = $db->affected_rows($sql); - if ($nb > 0) - { + if ($nb > 0) { // Removed orphelins records print '
    Some orphelins were found and modified to be parent so records are visible again for id: '; print join(',', $listofid); @@ -2008,8 +2302,12 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) */ function colorArrayToHex($arraycolor, $colorifnotfound = '888888') { - if (!is_array($arraycolor)) return $colorifnotfound; - if (empty($arraycolor)) return $colorifnotfound; + if (!is_array($arraycolor)) { + return $colorifnotfound; + } + if (empty($arraycolor)) { + return $colorifnotfound; + } return sprintf("%02s", dechex($arraycolor[0])).sprintf("%02s", dechex($arraycolor[1])).sprintf("%02s", dechex($arraycolor[2])); } @@ -2025,13 +2323,16 @@ function colorArrayToHex($arraycolor, $colorifnotfound = '888888') */ function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88)) { - if (is_array($stringcolor)) return $stringcolor; // If already into correct output format, we return as is + if (is_array($stringcolor)) { + return $stringcolor; // If already into correct output format, we return as is + } $reg = array(); $tmp = preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/', $stringcolor, $reg); - if (!$tmp) - { + if (!$tmp) { $tmp = explode(',', $stringcolor); - if (count($tmp) < 3) return $colorifnotfound; + if (count($tmp) < 3) { + return $colorifnotfound; + } return $tmp; } return array(hexdec($reg[1]), hexdec($reg[2]), hexdec($reg[3])); @@ -2044,10 +2345,11 @@ function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88)) */ function colorValidateHex($color, $allow_white = true) { - if (!$allow_white && ($color === '#fff' || $color === '#ffffff')) return false; + if (!$allow_white && ($color === '#fff' || $color === '#ffffff')) { + return false; + } - if (preg_match('/^#[a-f0-9]{6}$/i', $color)) //hex color is valid - { + if (preg_match('/^#[a-f0-9]{6}$/i', $color)) { //hex color is valid return true; } return false; @@ -2064,7 +2366,9 @@ function colorValidateHex($color, $allow_white = true) */ function colorAgressiveness($hex, $ratio = -50, $brightness = 0) { - if (empty($ratio)) $ratio = 0; // To avoid null + if (empty($ratio)) { + $ratio = 0; // To avoid null + } // Steps should be between -255 and 255. Negative = darker, positive = lighter $ratio = max(-100, min(100, $ratio)); @@ -2081,17 +2385,23 @@ function colorAgressiveness($hex, $ratio = -50, $brightness = 0) foreach ($color_parts as $color) { $color = hexdec($color); // Convert to decimal - if ($ratio > 0) // We increase aggressivity - { - if ($color > 127) $color += ((255 - $color) * ($ratio / 100)); - if ($color < 128) $color -= ($color * ($ratio / 100)); + if ($ratio > 0) { // We increase aggressivity + if ($color > 127) { + $color += ((255 - $color) * ($ratio / 100)); + } + if ($color < 128) { + $color -= ($color * ($ratio / 100)); + } } else // We decrease agressiveness { - if ($color > 128) $color -= (($color - 128) * (abs($ratio) / 100)); - if ($color < 127) $color += ((128 - $color) * (abs($ratio) / 100)); + if ($color > 128) { + $color -= (($color - 128) * (abs($ratio) / 100)); + } + if ($color < 127) { + $color += ((128 - $color) * (abs($ratio) / 100)); + } } - if ($brightness > 0) - { + if ($brightness > 0) { $color = ($color * (100 + abs($brightness)) / 100); } else { $color = ($color * (100 - abs($brightness)) / 100); @@ -2228,7 +2538,9 @@ function cartesianArray(array $input) function getModuleDirForApiClass($moduleobject) { $moduledirforclass = $moduleobject; - if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass); + if ($moduledirforclass != 'api') { + $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass); + } if ($moduleobject == 'contracts') { $moduledirforclass = 'contrat'; @@ -2298,8 +2610,7 @@ function randomColor($min = 0, $max = 255) } -if (!function_exists('dolEscapeXML')) -{ +if (!function_exists('dolEscapeXML')) { /** * Encode string for xml usage * @@ -2324,26 +2635,42 @@ if (!function_exists('dolEscapeXML')) function autoOrManual($automaticmanual, $case = 1, $color = 0) { global $langs; - $result = 'unknown'; $classname = ''; - if ($automaticmanual == 1 || strtolower($automaticmanual) == 'automatic' || strtolower($automaticmanual) == 'true') // A mettre avant test sur no a cause du == 0 - { + $result = 'unknown'; + $classname = ''; + if ($automaticmanual == 1 || strtolower($automaticmanual) == 'automatic' || strtolower($automaticmanual) == 'true') { // A mettre avant test sur no a cause du == 0 $result = $langs->trans('automatic'); - if ($case == 1 || $case == 3) $result = $langs->trans("Automatic"); - if ($case == 2) $result = ''; - if ($case == 3) $result = ' '.$result; + if ($case == 1 || $case == 3) { + $result = $langs->trans("Automatic"); + } + if ($case == 2) { + $result = ''; + } + if ($case == 3) { + $result = ' '.$result; + } $classname = 'ok'; - } elseif ($automaticmanual == 0 || strtolower($automaticmanual) == 'manual' || strtolower($automaticmanual) == 'false') - { + } elseif ($automaticmanual == 0 || strtolower($automaticmanual) == 'manual' || strtolower($automaticmanual) == 'false') { $result = $langs->trans("manual"); - if ($case == 1 || $case == 3) $result = $langs->trans("Manual"); - if ($case == 2) $result = ''; - if ($case == 3) $result = ' '.$result; + if ($case == 1 || $case == 3) { + $result = $langs->trans("Manual"); + } + if ($case == 2) { + $result = ''; + } + if ($case == 3) { + $result = ' '.$result; + } - if ($color == 2) $classname = 'ok'; - else $classname = 'error'; + if ($color == 2) { + $classname = 'ok'; + } else { + $classname = 'error'; + } + } + if ($color) { + return ''.$result.''; } - if ($color) return ''.$result.''; return $result; } @@ -2378,7 +2705,9 @@ function price2fec($amount) global $conf; // Clean parameters - if (empty($amount)) $amount = 0; // To have a numeric value if amount not defined or = '' + if (empty($amount)) { + $amount = 0; // To have a numeric value if amount not defined or = '' + } $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number) // Output decimal number by default @@ -2402,9 +2731,15 @@ function price2fec($amount) */ function phpSyntaxError($code) { - if (!defined("CR")) define("CR", "\r"); - if (!defined("LF")) define("LF", "\n"); - if (!defined("CRLF")) define("CRLF", "\r\n"); + if (!defined("CR")) { + define("CR", "\r"); + } + if (!defined("LF")) { + define("LF", "\n"); + } + if (!defined("CRLF")) { + define("CRLF", "\r\n"); + } $braces = 0; $inString = 0; @@ -2413,27 +2748,39 @@ function phpSyntaxError($code) switch ($token[0]) { case T_CURLY_OPEN: case T_DOLLAR_OPEN_CURLY_BRACES: - case T_START_HEREDOC: ++$inString; break; - case T_END_HEREDOC: --$inString; break; + case T_START_HEREDOC: + ++$inString; + break; + case T_END_HEREDOC: + --$inString; + break; } } elseif ($inString & 1) { switch ($token) { case '`': case '\'': - case '"': --$inString; break; + case '"': + --$inString; + break; } } else { switch ($token) { case '`': case '\'': - case '"': ++$inString; break; - case '{': ++$braces; break; + case '"': + ++$inString; + break; + case '{': + ++$braces; + break; case '}': if ($inString) { --$inString; } else { --$braces; - if ($braces < 0) break 2; + if ($braces < 0) { + break 2; + } } break; } @@ -2458,7 +2805,9 @@ function phpSyntaxError($code) $code = $code[2] <= $braces ? array($code[1], $code[2]) : array('unexpected $end'.substr($code[1], 14), $braces); - } else $code = array('syntax error', 0); + } else { + $code = array('syntax error', 0); + } } else { ob_end_clean(); $code = false; diff --git a/htdocs/core/lib/functions_ch.lib.php b/htdocs/core/lib/functions_ch.lib.php index 04e74837853..cb683ceec1f 100644 --- a/htdocs/core/lib/functions_ch.lib.php +++ b/htdocs/core/lib/functions_ch.lib.php @@ -158,8 +158,7 @@ function dol_ch_controle_bvrb($bvrb) // Make control $report = 0; - while (dol_strlen($bv) > 1) - { + while (dol_strlen($bv) > 1) { $match = substr($bv, 0, 1); $report = $tableau[$report][$match]; $bv = substr($bv, 1); diff --git a/htdocs/core/lib/functionsnumtoword.lib.php b/htdocs/core/lib/functionsnumtoword.lib.php index 930c6d06a9e..6de1e69de1f 100644 --- a/htdocs/core/lib/functionsnumtoword.lib.php +++ b/htdocs/core/lib/functionsnumtoword.lib.php @@ -142,10 +142,14 @@ function dol_convertToWord($num, $langs, $currency = '', $centimes = false) $decimalpart = empty($TNum[1]) ? '' : preg_replace('/0+$/', '', $TNum[1]); if ($decimalpart) { - if (!empty($currency)) $concatWords .= ' '.$langs->transnoentities('and'); + if (!empty($currency)) { + $concatWords .= ' '.$langs->transnoentities('and'); + } $concatWords .= ' '.dol_convertToWord($decimalpart, $langs, '', true); - if (!empty($currency)) $concatWords .= ' '.$langs->transnoentities('centimes'); + if (!empty($currency)) { + $concatWords .= ' '.$langs->transnoentities('centimes'); + } } return $concatWords; } @@ -164,7 +168,9 @@ function dol_convertToWord($num, $langs, $currency = '', $centimes = false) function dolNumberToWord($numero, $langs, $numorcurrency = 'number') { // If the number is negative convert to positive and return -1 if it is too long - if ($numero < 0) $numero *= -1; + if ($numero < 0) { + $numero *= -1; + } if ($numero >= 1000000000001) { return -1; } @@ -172,8 +178,7 @@ function dolNumberToWord($numero, $langs, $numorcurrency = 'number') // Get 2 decimals to cents, another functions round or truncate $strnumber = number_format($numero, 10); $len = strlen($strnumber); - for ($i = 0; $i < $len; $i++) - { + for ($i = 0; $i < $len; $i++) { if ($strnumber[$i] == '.') { $parte_decimal = $strnumber[$i + 1].$strnumber[$i + 2]; break; @@ -182,8 +187,7 @@ function dolNumberToWord($numero, $langs, $numorcurrency = 'number') /*In dolibarr 3.6.2 (my current version) doesn't have $langs->default and in case exist why ask $lang like a parameter?*/ - if (((is_object($langs) && $langs->default == 'es_MX') || (!is_object($langs) && $langs == 'es_MX')) && $numorcurrency == 'currency') - { + if (((is_object($langs) && $langs->default == 'es_MX') || (!is_object($langs) && $langs == 'es_MX')) && $numorcurrency == 'currency') { if ($numero >= 1 && $numero < 2) { return ("UN PESO ".$parte_decimal." / 100 M.N."); } elseif ($numero >= 0 && $numero < 1) { @@ -213,9 +217,11 @@ function dolNumberToWord($numero, $langs, $numorcurrency = 'number') $udMILLON = (int) ($numero / 1000000); $numero = $numero - $udMILLON * 1000000; $entexto .= hundreds2text($CdMILLON, $DdMILLON, $udMILLON); - if (!$CdMMillon && !$DdMMillon && !$UdMMillon && !$CdMILLON && !$DdMILLON && $udMILLON == 1) + if (!$CdMMillon && !$DdMMillon && !$UdMMillon && !$CdMILLON && !$DdMILLON && $udMILLON == 1) { $entexto .= " MILLÓN "; - else $entexto .= " MILLONES "; + } else { + $entexto .= " MILLONES "; + } } if ($number >= 1000) { $cdm = (int) ($numero / 100000); @@ -225,16 +231,18 @@ function dolNumberToWord($numero, $langs, $numorcurrency = 'number') $udm = (int) ($numero / 1000); $numero = $numero - $udm * 1000; $entexto .= hundreds2text($cdm, $ddm, $udm); - if ($cdm || $ddm || $udm) + if ($cdm || $ddm || $udm) { $entexto .= " MIL "; + } } $c = (int) ($numero / 100); $numero = $numero - $c * 100; $d = (int) ($numero / 10); $u = (int) $numero - $d * 10; $entexto .= hundreds2text($c, $d, $u); - if (!$cdm && !$ddm && !$udm && !$c && !$d && !$u && $number > 1000000) + if (!$cdm && !$ddm && !$udm && !$c && !$d && !$u && $number > 1000000) { $entexto .= " DE"; + } $entexto .= " PESOS ".$parte_decimal." / 100 M.N."; } return $entexto; @@ -264,7 +272,9 @@ function hundreds2text($hundreds, $tens, $units) $entexto .= $centenas[$hundreds - 1]; } if ($tens > 2) { - if ($hundreds != 0) $entexto .= " "; + if ($hundreds != 0) { + $entexto .= " "; + } $entexto .= $decenas[$tens - 1]; if ($units != 0) { $entexto .= " Y "; @@ -272,16 +282,22 @@ function hundreds2text($hundreds, $tens, $units) } return $entexto; } elseif ($tens == 2) { - if ($hundreds != 0) $entexto .= " "; + if ($hundreds != 0) { + $entexto .= " "; + } $entexto .= " ".$veintis[$units]; return $entexto; } elseif ($tens == 1) { - if ($hundreds != 0) $entexto .= " "; + if ($hundreds != 0) { + $entexto .= " "; + } $entexto .= $diecis[$units]; return $entexto; } if ($units != 0) { - if ($hundreds != 0 || $tens != 0) $entexto .= " "; + if ($hundreds != 0 || $tens != 0) { + $entexto .= " "; + } $entexto .= $unidades[$units - 1]; } return $entexto; diff --git a/htdocs/core/lib/geturl.lib.php b/htdocs/core/lib/geturl.lib.php index 7e93623f3c1..d624e2e0ace 100644 --- a/htdocs/core/lib/geturl.lib.php +++ b/htdocs/core/lib/geturl.lib.php @@ -51,9 +51,9 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = $ch = curl_init(); /*print $API_Endpoint."-".$API_version."-".$PAYPAL_API_USER."-".$PAYPAL_API_PASSWORD."-".$PAYPAL_API_SIGNATURE."
    "; - print $USE_PROXY."-".$gv_ApiErrorURL."
    "; - print $nvpStr; - exit;*/ + print $USE_PROXY."-".$gv_ApiErrorURL."
    "; + print $nvpStr; + exit;*/ curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_USERAGENT, 'Dolibarr geturl function'); @@ -61,12 +61,16 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = // We force value to false so we will manage redirection ourself later. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); - if (is_array($addheaders) && count($addheaders)) curl_setopt($ch, CURLOPT_HTTPHEADER, $addheaders); + if (is_array($addheaders) && count($addheaders)) { + curl_setopt($ch, CURLOPT_HTTPHEADER, $addheaders); + } curl_setopt($ch, CURLINFO_HEADER_OUT, true); // To be able to retrieve request header and log it // By default use tls decied by PHP. // You can force, if supported a version like TLSv1 or TLSv1.2 - if (!empty($conf->global->MAIN_CURL_SSLVERSION)) curl_setopt($ch, CURLOPT_SSLVERSION, $conf->global->MAIN_CURL_SSLVERSION); + if (!empty($conf->global->MAIN_CURL_SSLVERSION)) { + curl_setopt($ch, CURLOPT_SSLVERSION, $conf->global->MAIN_CURL_SSLVERSION); + } //curl_setopt($ch, CURLOPT_SSLVERSION, 6); for tls 1.2 // Turning off the server and peer verification(TrustManager Concept). @@ -77,8 +81,12 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = $protocols = 0; if (is_array($allowedschemes)) { foreach ($allowedschemes as $allowedscheme) { - if ($allowedscheme == 'http') $protocols |= CURLPROTO_HTTP; - if ($allowedscheme == 'https') $protocols |= CURLPROTO_HTTPS; + if ($allowedscheme == 'http') { + $protocols |= CURLPROTO_HTTP; + } + if ($allowedscheme == 'https') { + $protocols |= CURLPROTO_HTTPS; + } } curl_setopt($ch, CURLOPT_PROTOCOLS, $protocols); curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS, $protocols); @@ -98,8 +106,9 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = } elseif ($postorget == 'PUT') { $array_param = null; curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // HTTP request is 'PUT' - if (!is_array($param)) parse_str($param, $array_param); - else { + if (!is_array($param)) { + parse_str($param, $array_param); + } else { dol_syslog("parameter param must be a string", LOG_WARNING); $array_param = $param; } @@ -121,7 +130,9 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = dol_syslog("getURLContent set proxy to ".$PROXY_HOST.":".$PROXY_PORT." - ".$PROXY_USER.":".$PROXY_PASS); //curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Curl 7.10 curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT); - if ($PROXY_USER) curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS); + if ($PROXY_USER) { + curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS); + } } $newUrl = $url; @@ -130,7 +141,9 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = $response = ''; do { - if ($maxRedirection < 1) break; + if ($maxRedirection < 1) { + break; + } curl_setopt($ch, CURLOPT_URL, $newUrl); @@ -185,8 +198,7 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = } else { $http_code = 0; } - } - while ($http_code); + } while ($http_code); $request = curl_getinfo($ch, CURLINFO_HEADER_OUT); // Reading of request must be done after sending request @@ -263,7 +275,9 @@ function getRootURLFromURL($url) $prefix = ''; $tmpurl = $url; $reg = null; - if (preg_match('/^(https?:\/\/)/i', $tmpurl, $reg)) $prefix = $reg[1]; + if (preg_match('/^(https?:\/\/)/i', $tmpurl, $reg)) { + $prefix = $reg[1]; + } $tmpurl = preg_replace('/^https?:\/\//i', '', $tmpurl); // Remove http(s):// $tmpurl = preg_replace('/\/.*$/i', '', $tmpurl); // Remove part after domain diff --git a/htdocs/core/lib/holiday.lib.php b/htdocs/core/lib/holiday.lib.php index 7b9c5d46da2..4f6da9f6d51 100644 --- a/htdocs/core/lib/holiday.lib.php +++ b/htdocs/core/lib/holiday.lib.php @@ -47,7 +47,9 @@ function holiday_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/holiday/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; diff --git a/htdocs/core/lib/images.lib.php b/htdocs/core/lib/images.lib.php index bd392760cc5..7041eabfc5e 100644 --- a/htdocs/core/lib/images.lib.php +++ b/htdocs/core/lib/images.lib.php @@ -23,8 +23,10 @@ */ // Define size of logo small and mini -$maxwidthsmall = 480; $maxheightsmall = 270; // Near 16/9eme -$maxwidthmini = 128; $maxheightmini = 72; // 16/9eme +$maxwidthsmall = 480; +$maxheightsmall = 270; // Near 16/9eme +$maxwidthmini = 128; +$maxheightmini = 72; // 16/9eme $quality = 80; @@ -47,23 +49,41 @@ function image_format_supported($file, $acceptsvg = 0) // Case filename is not a format image $reg = array(); - if (!preg_match('/('.$regeximgext.')$/i', $file, $reg)) return -1; + if (!preg_match('/('.$regeximgext.')$/i', $file, $reg)) { + return -1; + } // Case filename is a format image but not supported by this PHP $imgfonction = ''; - if (strtolower($reg[1]) == '.gif') $imgfonction = 'imagecreatefromgif'; - if (strtolower($reg[1]) == '.jpg') $imgfonction = 'imagecreatefromjpeg'; - if (strtolower($reg[1]) == '.jpeg') $imgfonction = 'imagecreatefromjpeg'; - if (strtolower($reg[1]) == '.png') $imgfonction = 'imagecreatefrompng'; - if (strtolower($reg[1]) == '.bmp') $imgfonction = 'imagecreatefromwbmp'; - if (strtolower($reg[1]) == '.webp') $imgfonction = 'imagecreatefromwebp'; - if (strtolower($reg[1]) == '.xpm') $imgfonction = 'imagecreatefromxpm'; - if (strtolower($reg[1]) == '.xbm') $imgfonction = 'imagecreatefromxbm'; - if (strtolower($reg[1]) == '.svg') $imgfonction = 'imagecreatefromsvg'; // Never available - if ($imgfonction) - { - if (!function_exists($imgfonction)) - { + if (strtolower($reg[1]) == '.gif') { + $imgfonction = 'imagecreatefromgif'; + } + if (strtolower($reg[1]) == '.jpg') { + $imgfonction = 'imagecreatefromjpeg'; + } + if (strtolower($reg[1]) == '.jpeg') { + $imgfonction = 'imagecreatefromjpeg'; + } + if (strtolower($reg[1]) == '.png') { + $imgfonction = 'imagecreatefrompng'; + } + if (strtolower($reg[1]) == '.bmp') { + $imgfonction = 'imagecreatefromwbmp'; + } + if (strtolower($reg[1]) == '.webp') { + $imgfonction = 'imagecreatefromwebp'; + } + if (strtolower($reg[1]) == '.xpm') { + $imgfonction = 'imagecreatefromxpm'; + } + if (strtolower($reg[1]) == '.xbm') { + $imgfonction = 'imagecreatefromxbm'; + } + if (strtolower($reg[1]) == '.svg') { + $imgfonction = 'imagecreatefromsvg'; // Never available + } + if ($imgfonction) { + if (!function_exists($imgfonction)) { // Fonctions of conversion not available in this PHP return 0; } @@ -87,16 +107,16 @@ function dol_getImageSize($file, $url = false) { $ret = array(); - if (image_format_supported($file) < 0) return $ret; + if (image_format_supported($file) < 0) { + return $ret; + } $filetoread = $file; - if (!$url) - { + if (!$url) { $filetoread = realpath(dol_osencode($file)); // Chemin canonique absolu de l'image } - if ($filetoread) - { + if ($filetoread) { $infoImg = getimagesize($filetoread); // Recuperation des infos de l'image $ret['width'] = $infoImg[0]; // Largeur de l'image $ret['height'] = $infoImg[1]; // Hauteur de l'image @@ -129,25 +149,19 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, $file = trim($file); // Check parameters - if (!$file) - { + if (!$file) { // Si le fichier n'a pas ete indique return 'Bad parameter file'; - } elseif (!file_exists($file)) - { + } elseif (!file_exists($file)) { // Si le fichier passe en parametre n'existe pas return $langs->trans("ErrorFileNotFound", $file); - } elseif (image_format_supported($file) < 0) - { + } elseif (image_format_supported($file) < 0) { return 'This filename '.$file.' does not seem to be an image filename.'; - } elseif (!is_numeric($newWidth) && !is_numeric($newHeight)) - { + } elseif (!is_numeric($newWidth) && !is_numeric($newHeight)) { return 'Wrong value for parameter newWidth or newHeight'; - } elseif ($mode == 0 && $newWidth <= 0 && $newHeight <= 0) - { + } elseif ($mode == 0 && $newWidth <= 0 && $newHeight <= 0) { return 'At least newHeight or newWidth must be defined for resizing'; - } elseif ($mode == 1 && ($newWidth <= 0 || $newHeight <= 0)) - { + } elseif ($mode == 1 && ($newWidth <= 0 || $newHeight <= 0)) { return 'Both newHeight or newWidth must be defined for croping'; } @@ -157,21 +171,17 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, $imgWidth = $infoImg[0]; // Largeur de l'image $imgHeight = $infoImg[1]; // Hauteur de l'image - if ($mode == 0) // If resize, we check parameters - { - if ($newWidth <= 0) - { + if ($mode == 0) { // If resize, we check parameters + if ($newWidth <= 0) { $newWidth = intval(($newHeight / $imgHeight) * $imgWidth); // Keep ratio } - if ($newHeight <= 0) - { + if ($newHeight <= 0) { $newHeight = intval(($newWidth / $imgWidth) * $imgHeight); // Keep ratio } } $imgfonction = ''; - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case 1: // IMG_GIF $imgfonction = 'imagecreatefromgif'; break; @@ -188,18 +198,15 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, $imgfonction = 'imagecreatefromwebp'; break; } - if ($imgfonction) - { - if (!function_exists($imgfonction)) - { + if ($imgfonction) { + if (!function_exists($imgfonction)) { // Fonctions de conversion non presente dans ce PHP return 'Resize not possible. This PHP does not support GD functions '.$imgfonction; } } // Initialisation des variables selon l'extension de l'image - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case 1: // Gif $img = imagecreatefromgif($filetoread); $extImg = '.gif'; // File name extension of image @@ -228,8 +235,7 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, } // Create empty image - if ($infoImg[2] == 1) - { + if ($infoImg[2] == 1) { // Compatibilite image GIF $imgThumb = imagecreate($newWidth, $newHeight); } else { @@ -237,20 +243,17 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, } // Activate antialiasing for better quality - if (function_exists('imageantialias')) - { + if (function_exists('imageantialias')) { imageantialias($imgThumb, true); } // This is to keep transparent alpha channel if exists (PHP >= 4.2) - if (function_exists('imagesavealpha')) - { + if (function_exists('imagesavealpha')) { imagesavealpha($imgThumb, true); } // Initialisation des variables selon l'extension de l'image - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case 1: // Gif $trans_colour = imagecolorallocate($imgThumb, 255, 255, 255); // On procede autrement pour le format GIF imagecolortransparent($imgThumb, $trans_colour); @@ -269,7 +272,9 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, $trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 127); break; } - if (function_exists("imagefill")) imagefill($imgThumb, 0, 0, $trans_colour); + if (function_exists("imagefill")) { + imagefill($imgThumb, 0, 0, $trans_colour); + } dol_syslog("dol_imageResizeOrCrop: convert image from ($imgWidth x $imgHeight) at position ($src_x x $src_y) to ($newWidth x $newHeight) as $extImg, newquality=$newquality"); //imagecopyresized($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee @@ -282,8 +287,7 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, //fclose($fp); // Create image on disk - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case 1: // Gif imagegif($imgThumb, $imgThumbName); break; @@ -302,7 +306,9 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, } // Set permissions on file - if (!empty($conf->global->MAIN_UMASK)) @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK)); + if (!empty($conf->global->MAIN_UMASK)) { + @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK)); + } // Free memory. This does not delete image. imagedestroy($img); @@ -359,8 +365,7 @@ function correctExifImageOrientation($fileSource, $fileDest, $quality = 95) break; } if ($deg) { - if ($infoImg[2] === 'IMAGETYPE_PNG') // In fact there is no exif on PNG but just in case - { + if ($infoImg[2] === 'IMAGETYPE_PNG') { // In fact there is no exif on PNG but just in case imagealphablending($img, false); imagesavealpha($img, true); $img = imagerotate($img, $deg, imageColorAllocateAlpha($img, 0, 0, 0, 127)); @@ -378,8 +383,7 @@ function correctExifImageOrientation($fileSource, $fileDest, $quality = 95) // Create image on disk $image = false; - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case IMAGETYPE_GIF: // 1 $image = imagegif($img, $fileDest); break; @@ -434,17 +438,14 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', $file = trim($file); // Check parameters - if (!$file) - { + if (!$file) { // Si le fichier n'a pas ete indique return 'ErrorBadParameters'; - } elseif (!file_exists($file)) - { + } elseif (!file_exists($file)) { // Si le fichier passe en parametre n'existe pas dol_syslog($langs->trans("ErrorFileNotFound", $file), LOG_ERR); return $langs->trans("ErrorFileNotFound", $file); - } elseif (image_format_supported($file) < 0) - { + } elseif (image_format_supported($file) < 0) { dol_syslog('This file '.$file.' does not seem to be an image format file name.', LOG_WARNING); return 'ErrorBadImageFormat'; } elseif (!is_numeric($maxWidth) || empty($maxWidth) || $maxWidth < -1) { @@ -471,20 +472,22 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', } } - if ($maxWidth == -1) $maxWidth = $infoImg[0]; // If size is -1, we keep unchanged - if ($maxHeight == -1) $maxHeight = $infoImg[1]; // If size is -1, we keep unchanged + if ($maxWidth == -1) { + $maxWidth = $infoImg[0]; // If size is -1, we keep unchanged + } + if ($maxHeight == -1) { + $maxHeight = $infoImg[1]; // If size is -1, we keep unchanged + } // Si l'image est plus petite que la largeur et la hauteur max, on ne cree pas de vignette - if ($infoImg[0] < $maxWidth && $infoImg[1] < $maxHeight) - { + if ($infoImg[0] < $maxWidth && $infoImg[1] < $maxHeight) { // On cree toujours les vignettes dol_syslog("File size is smaller than thumb size", LOG_DEBUG); //return 'Le fichier '.$file.' ne necessite pas de creation de vignette'; } $imgfonction = ''; - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case IMAGETYPE_GIF: // 1 $imgfonction = 'imagecreatefromgif'; break; @@ -501,10 +504,8 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', $imgfonction = 'imagecreatefromwbmp'; break; } - if ($imgfonction) - { - if (!function_exists($imgfonction)) - { + if ($imgfonction) { + if (!function_exists($imgfonction)) { // Fonctions de conversion non presente dans ce PHP return 'Error: Creation of thumbs not possible. This PHP does not support GD function '.$imgfonction; } @@ -516,8 +517,7 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', // Initialisation des variables selon l'extension de l'image $img = null; - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case IMAGETYPE_GIF: // 1 $img = imagecreatefromgif($filetoread); $extImg = '.gif'; // Extension de l'image @@ -540,16 +540,14 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', break; } - if (!is_resource($img)) - { + if (!is_resource($img)) { dol_syslog('Failed to detect type of image. We found infoImg[2]='.$infoImg[2], LOG_WARNING); return 0; } $exifAngle = false; if ($ort && !empty($conf->global->MAIN_USE_EXIF_ROTATION)) { - switch ($ort) - { + switch ($ort) { case 3: // 180 rotate left $exifAngle = 180; break; @@ -568,12 +566,10 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', } } - if ($exifAngle) - { + if ($exifAngle) { $rotated = false; - if ($infoImg[2] === 'IMAGETYPE_PNG') // In fact there is no exif on PNG but just in case - { + if ($infoImg[2] === 'IMAGETYPE_PNG') { // In fact there is no exif on PNG but just in case imagealphablending($img, false); imagesavealpha($img, true); $rotated = imagerotate($img, $exifAngle, imageColorAllocateAlpha($img, 0, 0, 0, 127)); @@ -592,15 +588,18 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', } // Initialisation des dimensions de la vignette si elles sont superieures a l'original - if ($maxWidth > $imgWidth) { $maxWidth = $imgWidth; } - if ($maxHeight > $imgHeight) { $maxHeight = $imgHeight; } + if ($maxWidth > $imgWidth) { + $maxWidth = $imgWidth; + } + if ($maxHeight > $imgHeight) { + $maxHeight = $imgHeight; + } $whFact = $maxWidth / $maxHeight; // Facteur largeur/hauteur des dimensions max de la vignette $imgWhFact = $imgWidth / $imgHeight; // Facteur largeur/hauteur de l'original // Fixe les dimensions de la vignette - if ($whFact < $imgWhFact) - { + if ($whFact < $imgWhFact) { // Si largeur determinante $thumbWidth = $maxWidth; $thumbHeight = $thumbWidth / $imgWhFact; @@ -613,11 +612,12 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', $thumbWidth = round($thumbWidth); // Define target format - if (empty($targetformat)) $targetformat = $infoImg[2]; + if (empty($targetformat)) { + $targetformat = $infoImg[2]; + } // Create empty image - if ($targetformat == IMAGETYPE_GIF) - { + if ($targetformat == IMAGETYPE_GIF) { // Compatibilite image GIF $imgThumb = imagecreate($thumbWidth, $thumbHeight); } else { @@ -625,21 +625,18 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', } // Activate antialiasing for better quality - if (function_exists('imageantialias')) - { + if (function_exists('imageantialias')) { imageantialias($imgThumb, true); } // This is to keep transparent alpha channel if exists (PHP >= 4.2) - if (function_exists('imagesavealpha')) - { + if (function_exists('imagesavealpha')) { imagesavealpha($imgThumb, true); } // Initialisation des variables selon l'extension de l'image // $targetformat is 0 by default, in such case, we keep original extension - switch ($targetformat) - { + switch ($targetformat) { case IMAGETYPE_GIF: // 1 $trans_colour = imagecolorallocate($imgThumb, 255, 255, 255); // On procede autrement pour le format GIF imagecolortransparent($imgThumb, $trans_colour); @@ -669,7 +666,9 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', $newquality = 'NU'; break; } - if (function_exists("imagefill")) imagefill($imgThumb, 0, 0, $trans_colour); + if (function_exists("imagefill")) { + imagefill($imgThumb, 0, 0, $trans_colour); + } dol_syslog("vignette: convert image from ($imgWidth x $imgHeight) to ($thumbWidth x $thumbHeight) as $extImg, newquality=$newquality"); //imagecopyresized($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee @@ -686,8 +685,7 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', //fclose($fp); // Create image on disk - switch ($targetformat) - { + switch ($targetformat) { case IMAGETYPE_GIF: // 1 imagegif($imgThumb, $imgThumbName); break; @@ -706,7 +704,9 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', } // Set permissions on file - if (!empty($conf->global->MAIN_UMASK)) @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK)); + if (!empty($conf->global->MAIN_UMASK)) { + @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK)); + } // Free memory. This does not delete image. imagedestroy($img); diff --git a/htdocs/core/lib/import.lib.php b/htdocs/core/lib/import.lib.php index 385dee32a86..a9663795988 100644 --- a/htdocs/core/lib/import.lib.php +++ b/htdocs/core/lib/import.lib.php @@ -36,13 +36,14 @@ function import_prepare_head($param, $maxstep = 0) { global $langs; - if (empty($maxstep)) $maxstep = 6; + if (empty($maxstep)) { + $maxstep = 6; + } $h = 0; $head = array(); $i = 1; - while ($i <= $maxstep) - { + while ($i <= $maxstep) { if ($i < 6) { $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step='.$i.$param; } else { diff --git a/htdocs/core/lib/invoice.lib.php b/htdocs/core/lib/invoice.lib.php index 453bc34be8a..89e7f8c8e55 100644 --- a/htdocs/core/lib/invoice.lib.php +++ b/htdocs/core/lib/invoice.lib.php @@ -45,32 +45,37 @@ function facture_prepare_head($object) $head[$h][2] = 'compta'; $h++; - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/compta/facture/contact.php?facid='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } - if (!empty($conf->prelevement->enabled)) - { + if (!empty($conf->prelevement->enabled)) { $nbStandingOrders = 0; $sql = "SELECT COUNT(pfd.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; $sql .= " WHERE pfd.fk_facture = ".$object->id; $sql .= " AND pfd.ext_payment_id IS NULL"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $nbStandingOrders = $obj->nb; - } else dol_print_error($db); + if ($obj) { + $nbStandingOrders = $obj->nb; + } + } else { + dol_print_error($db); + } $head[$h][0] = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$object->id; $head[$h][1] = $langs->trans('StandingOrders'); - if ($nbStandingOrders > 0) $head[$h][1] .= ''.$nbStandingOrders.''; + if ($nbStandingOrders > 0) { + $head[$h][1] .= ''.$nbStandingOrders.''; + } $head[$h][2] = 'standingorders'; $h++; } @@ -81,14 +86,19 @@ function facture_prepare_head($object) // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'invoice'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/compta/facture/note.php?facid='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; } @@ -100,7 +110,9 @@ function facture_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/compta/facture/document.php?facid='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; @@ -189,7 +201,7 @@ function invoice_rec_prepare_head($object) $head = array(); $head[$h][0] = DOL_URL_ROOT.'/compta/facture/card-rec.php?id='.$object->id; - $head[$h][1] = $langs->trans("CardBill"); + $head[$h][1] = $langs->trans("RepeatableInvoice"); $head[$h][2] = 'card'; $h++; diff --git a/htdocs/core/lib/invoice2.lib.php b/htdocs/core/lib/invoice2.lib.php index f38292cb50d..ca5fc61b60a 100644 --- a/htdocs/core/lib/invoice2.lib.php +++ b/htdocs/core/lib/invoice2.lib.php @@ -53,85 +53,106 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte $sql .= " FROM ".MAIN_DB_PREFIX."facture as f"; $sqlwhere = ''; $sqlorder = ''; - if (in_array('all', $filter)) - { + if (in_array('all', $filter)) { $sqlorder = " ORDER BY f.ref ASC"; } - if (in_array('date', $filter)) - { - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('date', $filter)) { + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= " f.fk_statut > 0"; $sqlwhere .= " AND f.datef >= '".$db->idate($dateafterdate)."'"; $sqlwhere .= " AND f.datef <= '".$db->idate($datebeforedate)."'"; $sqlorder = " ORDER BY f.datef ASC"; } - if (in_array('nopayment', $filter)) - { + if (in_array('nopayment', $filter)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture"; - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= " f.fk_statut > 0"; $sqlwhere .= " AND pf.fk_paiement IS NULL"; } - if (in_array('payments', $filter) || in_array('bank', $filter)) - { + if (in_array('payments', $filter) || in_array('bank', $filter)) { $sql .= ", ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."paiement as p"; - if (in_array('bank', $filter)) $sql .= ", ".MAIN_DB_PREFIX."bank as b"; - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('bank', $filter)) { + $sql .= ", ".MAIN_DB_PREFIX."bank as b"; + } + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= " f.fk_statut > 0"; $sqlwhere .= " AND f.rowid = pf.fk_facture"; $sqlwhere .= " AND pf.fk_paiement = p.rowid"; - if (in_array('payments', $filter)) - { + if (in_array('payments', $filter)) { $sqlwhere .= " AND p.datep >= '".$db->idate($paymentdateafter)."'"; $sqlwhere .= " AND p.datep <= '".$db->idate($paymentdatebefore)."'"; } - if (in_array('bank', $filter)) - { + if (in_array('bank', $filter)) { $sqlwhere .= " AND p.fk_bank = b.rowid"; $sqlwhere .= " AND b.fk_account = ".$paymentbankid; } $sqlorder = " ORDER BY p.datep ASC"; } - if (in_array('nodeposit', $filter)) - { - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('nodeposit', $filter)) { + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= ' type <> 3'; } - if (in_array('noreplacement', $filter)) - { - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('noreplacement', $filter)) { + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= ' type <> 1'; } - if (in_array('nocreditnote', $filter)) - { - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('nocreditnote', $filter)) { + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= ' type <> 2'; } - if (in_array('excludethirdparties', $filter) && is_array($thirdpartiesid)) - { - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('excludethirdparties', $filter) && is_array($thirdpartiesid)) { + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= ' f.fk_soc NOT IN ('.join(',', $thirdpartiesid).')'; } - if (in_array('onlythirdparties', $filter) && is_array($thirdpartiesid)) - { - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('onlythirdparties', $filter) && is_array($thirdpartiesid)) { + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= ' f.fk_soc IN ('.join(',', $thirdpartiesid).')'; } - if ($sqlwhere) $sql .= $sqlwhere; - if ($sqlorder) $sql .= $sqlorder; + if ($sqlwhere) { + $sql .= $sqlwhere; + } + if ($sqlorder) { + $sql .= $sqlorder; + } //print $sql; exit; dol_syslog("scripts/invoices/rebuild_merge.php:", LOG_DEBUG); - if ($usestdout) print '--- start'."\n"; + if ($usestdout) { + print '--- start'."\n"; + } // Start of transaction //$db->begin(); @@ -141,54 +162,53 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte $files = array(); // liste les fichiers dol_syslog("scripts/invoices/rebuild_merge.php", LOG_DEBUG); - if ($resql = $db->query($sql)) - { + if ($resql = $db->query($sql)) { $num = $db->num_rows($resql); $cpt = 0; $oldemail = ''; $message = ''; $total = ''; - if ($num) - { + if ($num) { // First loop on each resultset to build PDF // ----------------------------------------- - while ($cpt < $num) - { + while ($cpt < $num) { $obj = $db->fetch_object($resql); $fac = new Facture($db); $result = $fac->fetch($obj->rowid); - if ($result > 0) - { + if ($result > 0) { $outputlangs = $langs; - if (!empty($newlangid)) - { - if ($outputlangs->defaultlang != $newlangid) - { + if (!empty($newlangid)) { + if ($outputlangs->defaultlang != $newlangid) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlangid); } } $filename = $conf->facture->dir_output.'/'.$fac->ref.'/'.$fac->ref.'.pdf'; - if ($regenerate || !dol_is_file($filename)) - { - if ($usestdout) print "Build PDF for invoice ".$obj->ref." - Lang = ".$outputlangs->defaultlang."\n"; + if ($regenerate || !dol_is_file($filename)) { + if ($usestdout) { + print "Build PDF for invoice ".$obj->ref." - Lang = ".$outputlangs->defaultlang."\n"; + } $result = $fac->generateDocument($regenerate ? $regenerate : $fac->model_pdf, $outputlangs); } else { - if ($usestdout) print "PDF for invoice ".$obj->ref." already exists\n"; + if ($usestdout) { + print "PDF for invoice ".$obj->ref." already exists\n"; + } } // Add file into files array $files[] = $filename; } - if ($result <= 0) - { + if ($result <= 0) { $error++; - if ($usestdout) print "Error: Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid)."\n"; - else dol_syslog("Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid), LOG_ERR); + if ($usestdout) { + print "Error: Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid)."\n"; + } else { + dol_syslog("Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid), LOG_ERR); + } } $cpt++; @@ -201,8 +221,11 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte $page_hauteur = $formatarray['height']; $format = array($page_largeur, $page_hauteur); - if ($usestdout) print "Using output PDF format ".join('x', $format)."\n"; - else dol_syslog("Using output PDF format ".join('x', $format), LOG_ERR); + if ($usestdout) { + print "Using output PDF format ".join('x', $format)."\n"; + } else { + dol_syslog("Using output PDF format ".join('x', $format), LOG_ERR); + } // Now, build a merged files with all files in $files array @@ -210,26 +233,28 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte // Create empty PDF $pdf = pdf_getInstance($format); - if (class_exists('TCPDF')) - { + if (class_exists('TCPDF')) { $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); } $pdf->SetFont(pdf_getPDFFont($langs)); - if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false); + if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) { + $pdf->SetCompression(false); + } //$pdf->SetCompression(false); // Add all others - foreach ($files as $file) - { - if ($usestdout) print "Merge PDF file for invoice ".$file."\n"; - else dol_syslog("Merge PDF file for invoice ".$file); + foreach ($files as $file) { + if ($usestdout) { + print "Merge PDF file for invoice ".$file."\n"; + } else { + dol_syslog("Merge PDF file for invoice ".$file); + } // Charge un document PDF depuis un fichier. $pagecount = $pdf->setSourceFile($file); - for ($i = 1; $i <= $pagecount; $i++) - { + for ($i = 1; $i <= $pagecount; $i++) { $tplidx = $pdf->importPage($i); $s = $pdf->getTemplatesize($tplidx); $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); @@ -242,27 +267,36 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte // Save merged file $filename = $fileprefix; - if (empty($filename)) $filename = 'mergedpdf'; - if (!empty($filesuffix)) $filename .= '_'.$filesuffix; + if (empty($filename)) { + $filename = 'mergedpdf'; + } + if (!empty($filesuffix)) { + $filename .= '_'.$filesuffix; + } $file = $diroutputpdf.'/'.$filename.'.pdf'; - if (!$error && $pagecount) - { + if (!$error && $pagecount) { $pdf->Output($file, 'F'); - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); + } } - if ($usestdout) - { - if (!$error) print "Merged PDF has been built in ".$file."\n"; - else print "Can't build PDF ".$file."\n"; + if ($usestdout) { + if (!$error) { + print "Merged PDF has been built in ".$file."\n"; + } else { + print "Can't build PDF ".$file."\n"; + } } $result = 1; } else { - if ($usestdout) print "No invoices found for criteria.\n"; - else dol_syslog("No invoices found for criteria"); + if ($usestdout) { + print "No invoices found for criteria.\n"; + } else { + dol_syslog("No invoices found for criteria"); + } $result = 0; } } else { @@ -271,6 +305,9 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte $error++; } - if ($error) return -1; - else return $result; + if ($error) { + return -1; + } else { + return $result; + } } diff --git a/htdocs/core/lib/json.lib.php b/htdocs/core/lib/json.lib.php index cd48bbcb3c7..fe50503ed99 100644 --- a/htdocs/core/lib/json.lib.php +++ b/htdocs/core/lib/json.lib.php @@ -23,8 +23,7 @@ * \ingroup core */ -if (!function_exists('json_encode')) -{ +if (!function_exists('json_encode')) { /** * Implement json_encode for PHP that does not have module enabled. * @@ -50,26 +49,32 @@ function dol_json_encode($elements) dol_syslog("For better performance, enable the native json in your PHP", LOG_WARNING); $num = 0; - if (is_object($elements)) // Count number of properties for an object - { - foreach ($elements as $key => $value) $num++; + if (is_object($elements)) { // Count number of properties for an object + foreach ($elements as $key => $value) { + $num++; + } } else { $num = count($elements); } //var_dump($num); // determine type - if (is_numeric(key($elements)) && key($elements) == 0) - { + if (is_numeric(key($elements)) && key($elements) == 0) { // indexed (list) $keysofelements = array_keys($elements); // Elements array mus have key that does not start with 0 and end with num-1, so we will use this later. $output = '['; - for ($i = 0, $last = ($num - 1); $i < $num; $i++) - { - if (!isset($elements[$keysofelements[$i]])) continue; - if (is_array($elements[$keysofelements[$i]]) || is_object($elements[$keysofelements[$i]])) $output .= json_encode($elements[$keysofelements[$i]]); - else $output .= _val($elements[$keysofelements[$i]]); - if ($i !== $last) $output .= ','; + for ($i = 0, $last = ($num - 1); $i < $num; $i++) { + if (!isset($elements[$keysofelements[$i]])) { + continue; + } + if (is_array($elements[$keysofelements[$i]]) || is_object($elements[$keysofelements[$i]])) { + $output .= json_encode($elements[$keysofelements[$i]]); + } else { + $output .= _val($elements[$keysofelements[$i]]); + } + if ($i !== $last) { + $output .= ','; + } } $output .= ']'; } else { @@ -78,14 +83,22 @@ function dol_json_encode($elements) $last = $num - 1; $i = 0; $tmpelements = array(); - if (is_array($elements)) $tmpelements = $elements; - if (is_object($elements)) $tmpelements = get_object_vars($elements); - foreach ($tmpelements as $key => $value) - { + if (is_array($elements)) { + $tmpelements = $elements; + } + if (is_object($elements)) { + $tmpelements = get_object_vars($elements); + } + foreach ($tmpelements as $key => $value) { $output .= '"'.$key.'":'; - if (is_array($value)) $output .= json_encode($value); - else $output .= _val($value); - if ($i !== $last) $output .= ','; + if (is_array($value)) { + $output .= json_encode($value); + } else { + $output .= _val($value); + } + if ($i !== $last) { + $output .= ','; + } ++$i; } $output .= '}'; @@ -109,9 +122,9 @@ function _val($val) $strlen_var = strlen($val); /* - * Iterate over every character in the string, - * escaping with a slash or encoding to UTF-8 where necessary - */ + * Iterate over every character in the string, + * escaping with a slash or encoding to UTF-8 where necessary + */ for ($c = 0; $c < $strlen_var; ++$c) { $ord_var_c = ord($val[$c]); @@ -192,14 +205,18 @@ function _val($val) } return '"'.$ascii.'"'; - } elseif (is_int($val)) return sprintf('%d', $val); - elseif (is_float($val)) return sprintf('%F', $val); - elseif (is_bool($val)) return ($val ? 'true' : 'false'); - else return 'null'; + } elseif (is_int($val)) { + return sprintf('%d', $val); + } elseif (is_float($val)) { + return sprintf('%F', $val); + } elseif (is_bool($val)) { + return ($val ? 'true' : 'false'); + } else { + return 'null'; + } } -if (!function_exists('json_decode')) -{ +if (!function_exists('json_decode')) { /** * Implement json_decode for PHP that does not support it * @@ -230,16 +247,23 @@ function dol_json_decode($json, $assoc = false) $out = ''; $strLength = strlen($json); // Must stay strlen and not dol_strlen because we want technical length, not visible length - for ($i = 0; $i < $strLength; $i++) - { - if (!$comment) - { - if (($json[$i] == '{') || ($json[$i] == '[')) $out .= 'array('; - elseif (($json[$i] == '}') || ($json[$i] == ']')) $out .= ')'; - elseif ($json[$i] == ':') $out .= ' => '; - else $out .= $json[$i]; - } else $out .= $json[$i]; - if ($json[$i] == '"' && $json[($i - 1)] != "\\") $comment = !$comment; + for ($i = 0; $i < $strLength; $i++) { + if (!$comment) { + if (($json[$i] == '{') || ($json[$i] == '[')) { + $out .= 'array('; + } elseif (($json[$i] == '}') || ($json[$i] == ']')) { + $out .= ')'; + } elseif ($json[$i] == ':') { + $out .= ' => '; + } else { + $out .= $json[$i]; + } + } else { + $out .= $json[$i]; + } + if ($json[$i] == '"' && $json[($i - 1)] != "\\") { + $comment = !$comment; + } } $out = _unval($out); @@ -256,17 +280,16 @@ function dol_json_decode($json, $assoc = false) } // Return an object - if (!$assoc) - { - if (!empty($array)) - { + if (!$assoc) { + if (!empty($array)) { $object = false; if (count($array) > 0) { $object = (object) array(); } - foreach ($array as $key => $value) - { - if ($key) $object->{$key} = $value; + foreach ($array as $key => $value) { + if ($key) { + $object->{$key} = $value; + } } return $object; @@ -287,8 +310,7 @@ function dol_json_decode($json, $assoc = false) function _unval($val) { $reg = array(); - while (preg_match('/\\\u([0-9A-F]{2})([0-9A-F]{2})/i', $val, $reg)) - { + while (preg_match('/\\\u([0-9A-F]{2})([0-9A-F]{2})/i', $val, $reg)) { // single, escaped unicode character $utf16 = chr(hexdec($reg[1])).chr(hexdec($reg[2])); $utf8 = utf162utf8($utf16); @@ -320,18 +342,18 @@ function utf162utf8($utf16) case ((0x7F & $bytes) == $bytes): // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr($bytes); + return chr($bytes); case (0x07FF & $bytes) == $bytes: // return a 2-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0xC0 | (($bytes >> 6) & 0x1F)) + return chr(0xC0 | (($bytes >> 6) & 0x1F)) . chr(0x80 | ($bytes & 0x3F)); case (0xFFFF & $bytes) == $bytes: // return a 3-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0xE0 | (($bytes >> 12) & 0x0F)) + return chr(0xE0 | (($bytes >> 12) & 0x0F)) . chr(0x80 | (($bytes >> 6) & 0x3F)) . chr(0x80 | ($bytes & 0x3F)); } diff --git a/htdocs/core/lib/ldap.lib.php b/htdocs/core/lib/ldap.lib.php index 640152d5999..9d6e0193108 100644 --- a/htdocs/core/lib/ldap.lib.php +++ b/htdocs/core/lib/ldap.lib.php @@ -43,40 +43,35 @@ function ldap_prepare_head() $head[$h][2] = 'ldap'; $h++; - if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE)) - { + if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE)) { $head[$h][0] = DOL_URL_ROOT."/admin/ldap_users.php"; $head[$h][1] = $langs->trans("LDAPUsersSynchro"); $head[$h][2] = 'users'; $h++; } - if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE)) - { + if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE)) { $head[$h][0] = DOL_URL_ROOT."/admin/ldap_groups.php"; $head[$h][1] = $langs->trans("LDAPGroupsSynchro"); $head[$h][2] = 'groups'; $h++; } - if (!empty($conf->societe->enabled) && !empty($conf->global->LDAP_CONTACT_ACTIVE)) - { + if (!empty($conf->societe->enabled) && !empty($conf->global->LDAP_CONTACT_ACTIVE)) { $head[$h][0] = DOL_URL_ROOT."/admin/ldap_contacts.php"; $head[$h][1] = $langs->trans("LDAPContactsSynchro"); $head[$h][2] = 'contacts'; $h++; } - if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_ACTIVE)) - { + if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_ACTIVE)) { $head[$h][0] = DOL_URL_ROOT."/admin/ldap_members.php"; $head[$h][1] = $langs->trans("LDAPMembersSynchro"); $head[$h][2] = 'members'; $h++; } - if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE)) - { + if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE)) { $head[$h][0] = DOL_URL_ROOT."/admin/ldap_members_types.php"; $head[$h][1] = $langs->trans("LDAPMembersTypesSynchro"); $head[$h][2] = 'memberstypes'; @@ -111,14 +106,11 @@ function show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass) //print 'key='.$key.' dn='.$dn.' objectclass='.$objectclass; print '
    '; - if (!function_exists("ldap_connect")) - { + if (!function_exists("ldap_connect")) { print ''.$butlabel.''; - } elseif (empty($conf->global->LDAP_SERVER_HOST)) - { + } elseif (empty($conf->global->LDAP_SERVER_HOST)) { print ''.$butlabel.''; - } elseif (empty($key) || empty($dn) || empty($objectclass)) - { + } elseif (empty($key) || empty($dn) || empty($objectclass)) { $langs->load("errors"); print ''.$butlabel.''; } else { @@ -144,39 +136,54 @@ function show_ldap_content($result, $level, $count, $var, $hide = 0, $subcount = global $bc, $conf; $count--; - if ($count == 0) return -1; // To stop loop - if (!is_array($result)) return -1; + if ($count == 0) { + return -1; // To stop loop + } + if (!is_array($result)) { + return -1; + } - foreach ($result as $key => $val) - { - if ("$key" == "objectclass") continue; - if ("$key" == "count") continue; - if ("$key" == "dn") continue; - if ("$val" == "objectclass") continue; + foreach ($result as $key => $val) { + if ("$key" == "objectclass") { + continue; + } + if ("$key" == "count") { + continue; + } + if ("$key" == "dn") { + continue; + } + if ("$val" == "objectclass") { + continue; + } $lastkey[$level] = $key; - if (is_array($val)) - { + if (is_array($val)) { $hide = 0; - if (!is_numeric($key)) - { + if (!is_numeric($key)) { print '
    '; print $key; print ''; - if (strtolower($key) == 'userpassword') $hide = 1; + if (strtolower($key) == 'userpassword') { + $hide = 1; + } } show_ldap_content($val, $level + 1, $count, $var, $hide, $val["count"]); - } elseif ($subcount) - { + } elseif ($subcount) { $subcount--; $newstring = dol_htmlentitiesbr($val); - if ($hide) print preg_replace('/./i', '*', $newstring); - else print $newstring; + if ($hide) { + print preg_replace('/./i', '*', $newstring); + } else { + print $newstring; + } print '
    '; } - if ("$val" != $lastkey[$level] && !$subcount) print '
    '; - print ''.img_object('', 'propal').' '.$langs->trans("Proposals").''; + print ''.img_object('', 'propal', 'class="paddingright"').$langs->trans("Proposals").''; print ''; print $product->stats_propale['customers']; print ''; @@ -376,14 +387,15 @@ function show_stats_for_company($product, $socid) print '
    '; - print ''.img_object('', 'supplier_proposal').' '.$langs->trans("SupplierProposals").''; + print ''.img_object('', 'supplier_proposal', 'class="paddingright"').$langs->trans("SupplierProposals").''; print ''; print $product->stats_proposal_supplier['suppliers']; print ''; @@ -394,14 +406,15 @@ function show_stats_for_company($product, $socid) print '
    '; - print ''.img_object('', 'order').' '.$langs->trans("CustomersOrders").''; + print ''.img_object('', 'order', 'class="paddingright"').$langs->trans("CustomersOrders").''; print ''; print $product->stats_commande['customers']; print ''; @@ -412,14 +425,15 @@ function show_stats_for_company($product, $socid) print '
    '; - print ''.img_object('', 'supplier_order').' '.$langs->trans("SuppliersOrders").''; + print ''.img_object('', 'supplier_order', 'class="paddingright"').$langs->trans("SuppliersOrders").''; print ''; print $product->stats_commande_fournisseur['suppliers']; print ''; @@ -430,11 +444,12 @@ function show_stats_for_company($product, $socid) print '
    '; print ''.img_object('', 'bill').' '.$langs->trans("CustomersInvoices").''; @@ -448,14 +463,15 @@ function show_stats_for_company($product, $socid) print '
    '; - print ''.img_object('', 'supplier_invoice').' '.$langs->trans("SuppliersInvoices").''; + print ''.img_object('', 'supplier_invoice', 'class="paddingright"').$langs->trans("SuppliersInvoices").''; print ''; print $product->stats_facture_fournisseur['suppliers']; print ''; @@ -467,14 +483,15 @@ function show_stats_for_company($product, $socid) } // Contracts - if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) - { + if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) { $nblines++; $ret = $product->load_stats_contrat($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("contracts"); print '
    '; - print ''.img_object('', 'contract').' '.$langs->trans("Contracts").''; + print ''.img_object('', 'contract', 'class="paddingright"').$langs->trans("Contracts").''; print ''; print $product->stats_contrat['customers']; print ''; @@ -486,8 +503,7 @@ function show_stats_for_company($product, $socid) } // BOM - if (!empty($conf->bom->enabled) && $user->rights->bom->read) - { + if (!empty($conf->bom->enabled) && $user->rights->bom->read) { $nblines++; $ret = $product->load_stats_bom($socid); if ($ret < 0) { @@ -496,22 +512,21 @@ function show_stats_for_company($product, $socid) $langs->load("mrp"); print '
    '; - print ''.img_object('', 'mrp').' '.$langs->trans("BOM").''; + print ''.img_object('', 'bom', 'class="paddingright"').$langs->trans("BOM").''; print ''; print ''; - print $form->textwithpicto($product->stats_bom['nb_toproduce'], $langs->trans("QtyToProduce")); - print $form->textwithpicto($product->stats_bom['nb_toconsume'], $langs->trans("ToConsume")); + print $form->textwithpicto($product->stats_bom['nb_toconsume'], $langs->trans("RowMaterial")); + print $form->textwithpicto($product->stats_bom['nb_toproduce'], $langs->trans("Finished")); print ''; - print $form->textwithpicto($product->stats_bom['qty_toproduce'], $langs->trans("QtyToProduce")); - print $form->textwithpicto($product->stats_bom['qty_toconsume'], $langs->trans("ToConsume")); + print $form->textwithpicto($product->stats_bom['qty_toconsume'], $langs->trans("RowMaterial")); + print $form->textwithpicto($product->stats_bom['qty_toproduce'], $langs->trans("Finished")); print '
    '; - print ''.img_object('', 'mrp').' '.$langs->trans("MO").''; + print ''.img_object('', 'mrp', 'class="paddingright"').$langs->trans("MO").''; print ''; print $form->textwithpicto($product->stats_mo['customers_toconsume'], $langs->trans("ToConsume")); print $form->textwithpicto($product->stats_mo['customers_consumed'], $langs->trans("QtyAlreadyConsumed")); @@ -579,19 +594,16 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho $outputlangs = $langs; } - if (empty($measuring_unit_cache[$unit.'_'.$measuring_style.'_'.$scale.'_'.$use_short_label])) - { + if (empty($measuring_unit_cache[$unit.'_'.$measuring_style.'_'.$scale.'_'.$use_short_label])) { require_once DOL_DOCUMENT_ROOT.'/core/class/cunits.class.php'; $measuringUnits = new CUnits($db); - if ($measuring_style == '' && $scale == '') - { + if ($measuring_style == '' && $scale == '') { $arrayforfilter = array( 't.rowid' => $unit, 't.active' => 1 ); - } elseif ($scale !== '') - { + } elseif ($scale !== '') { $arrayforfilter = array( 't.scale' => $scale, 't.unit_type' => $measuring_style, @@ -610,8 +622,11 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho return -1; } else { if (is_array($measuringUnits->records) && count($measuringUnits->records) > 0) { - if ($use_short_label) $labeltoreturn = $measuringUnits->records[key($measuringUnits->records)]->short_label; - else $labeltoreturn = $outputlangs->transnoentitiesnoconv($measuringUnits->records[key($measuringUnits->records)]->label); + if ($use_short_label) { + $labeltoreturn = $measuringUnits->records[key($measuringUnits->records)]->short_label; + } else { + $labeltoreturn = $outputlangs->transnoentitiesnoconv($measuringUnits->records[key($measuringUnits->records)]->label); + } } else { $labeltoreturn = ''; } diff --git a/htdocs/core/lib/project.lib.php b/htdocs/core/lib/project.lib.php index 9bbfe1322e9..f2dbacc3ab4 100644 --- a/htdocs/core/lib/project.lib.php +++ b/htdocs/core/lib/project.lib.php @@ -2,7 +2,7 @@ /* Copyright (C) 2006-2015 Laurent Destailleur * Copyright (C) 2010 Regis Houssin * Copyright (C) 2011 Juanjo Menent - * 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 @@ -44,44 +44,80 @@ function project_prepare_head(Project $project) $head[$h][1] = $langs->trans("Project"); $head[$h][2] = 'project'; $h++; + $nbContacts = 0; + // Enable caching of project count Contacts + require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php'; + $cachekey = 'count_contacts_project_'.$project->id; + $dataretrieved = dol_getcache($cachekey); - $nbContact = count($project->liste_contact(-1, 'internal')) + count($project->liste_contact(-1, 'external')); + if (!is_null($dataretrieved)) { + $nbContacts = $dataretrieved; + } else { + $nbContacts = count($project->liste_contact(-1, 'internal')) + count($project->liste_contact(-1, 'external')); + dol_setcache($cachekey, $nbContacts, 120); // If setting cache fails, this is not a problem, so we do not test result. + } $head[$h][0] = DOL_URL_ROOT.'/projet/contact.php?id='.$project->id; $head[$h][1] = $langs->trans("ProjectContact"); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContacts > 0) { + $head[$h][1] .= ''.$nbContacts.''; + } $head[$h][2] = 'contact'; $h++; - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { // Then tab for sub level of projet, i mean tasks + $nbTasks = 0; + // Enable caching of project count Tasks + require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php'; + $cachekey = 'count_tasks_project_'.$project->id; + $dataretrieved = dol_getcache($cachekey); + + if (!is_null($dataretrieved)) { + $nbTasks = $dataretrieved; + } else { + require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; + $taskstatic = new Task($db); + $nbTasks = count($taskstatic->getTasksArray(0, 0, $project->id, 0, 0)); + dol_setcache($cachekey, $nbTasks, 120); // If setting cache fails, this is not a problem, so we do not test result. + } $head[$h][0] = DOL_URL_ROOT.'/projet/tasks.php?id='.$project->id; $head[$h][1] = $langs->trans("Tasks"); - - require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; - $taskstatic = new Task($db); - $nbTasks = count($taskstatic->getTasksArray(0, 0, $project->id, 0, 0)); - if ($nbTasks > 0) $head[$h][1] .= ''.($nbTasks).''; + if ($nbTasks > 0) { + $head[$h][1] .= ''.($nbTasks).''; + } $head[$h][2] = 'tasks'; $h++; $nbTimeSpent = 0; - $sql = "SELECT t.rowid"; - //$sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."user as u"; - //$sql .= " WHERE t.fk_user = u.rowid AND t.fk_task = pt.rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt"; - $sql .= " WHERE t.fk_task = pt.rowid"; - $sql .= " AND pt.fk_projet =".$project->id; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - if ($obj) $nbTimeSpent = 1; - } else dol_print_error($db); + // Enable caching of project count Timespent + $cachekey = 'count_timespent_project_'.$project->id; + $dataretrieved = dol_getcache($cachekey); + if (!is_null($dataretrieved)) { + $nbTimeSpent = $dataretrieved; + } else { + $sql = "SELECT t.rowid"; + //$sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."user as u"; + //$sql .= " WHERE t.fk_user = u.rowid AND t.fk_task = pt.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt"; + $sql .= " WHERE t.fk_task = pt.rowid"; + $sql .= " AND pt.fk_projet =".$project->id; + $resql = $db->query($sql); + if ($resql) { + $obj = $db->fetch_object($resql); + if ($obj) { + $nbTimeSpent = 1; + dol_setcache($cachekey, $nbTimeSpent, 120); // If setting cache fails, this is not a problem, so we do not test result. + } + } else { + dol_print_error($db); + } + } $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?withproject=1&projectid='.$project->id; $head[$h][1] = $langs->trans("TimeSpent"); - if ($nbTimeSpent > 0) $head[$h][1] .= '...'; + if ($nbTimeSpent > 0) { + $head[$h][1] .= '...'; + } $head[$h][2] = 'timespent'; $h++; } @@ -89,38 +125,98 @@ function project_prepare_head(Project $project) if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) || !empty($conf->propal->enabled) || !empty($conf->commande->enabled) || !empty($conf->facture->enabled) || !empty($conf->contrat->enabled) - || !empty($conf->ficheinter->enabled) || !empty($conf->agenda->enabled) || !empty($conf->deplacement->enabled)) - { - $count = 0; - - if (!empty($conf->propal->enabled)) $count += $project->getElementCount('propal', 'propal'); - if (!empty($conf->commande->enabled)) $count += $project->getElementCount('order', 'commande'); - if (!empty($conf->facture->enabled)) $count += $project->getElementCount('invoice', 'facture'); - if (!empty($conf->facture->enabled)) $count += $project->getElementCount('invoice_predefined', 'facture_rec'); - if (!empty($conf->supplier_proposal->enabled)) $count += $project->getElementCount('proposal_supplier', 'supplier_proposal'); - if (!empty($conf->supplier_order->enabled)) $count += $project->getElementCount('order_supplier', 'commande_fournisseur'); - if (!empty($conf->supplier_invoice->enabled)) $count += $project->getElementCount('invoice_supplier', 'facture_fourn'); - if (!empty($conf->contrat->enabled)) $count += $project->getElementCount('contract', 'contrat'); - if (!empty($conf->ficheinter->enabled)) $count += $project->getElementCount('intervention', 'fichinter'); - if (!empty($conf->expedition->enabled)) $count += $project->getElementCount('shipping', 'expedition'); - if (!empty($conf->mrp->enabled)) $count += $project->getElementCount('mrp', 'mrp_mo', 'fk_project'); - if (!empty($conf->deplacement->enabled)) $count += $project->getElementCount('trip', 'deplacement'); - if (!empty($conf->expensereport->enabled)) $count += $project->getElementCount('expensereport', 'expensereport'); - if (!empty($conf->don->enabled)) $count += $project->getElementCount('donation', 'don'); - if (!empty($conf->loan->enabled)) $count += $project->getElementCount('loan', 'loan'); - if (!empty($conf->tax->enabled)) $count += $project->getElementCount('chargesociales', 'chargesociales'); - if (!empty($conf->projet->enabled)) $count += $project->getElementCount('project_task', 'projet_task'); - if (!empty($conf->stock->enabled)) $count += $project->getElementCount('stock_mouvement', 'stock'); - if (!empty($conf->salaries->enabled)) $count += $project->getElementCount('salaries', 'payment_salary'); - if (!empty($conf->banque->enabled)) $count += $project->getElementCount('variouspayment', 'payment_various'); - + || !empty($conf->ficheinter->enabled) || !empty($conf->agenda->enabled) || !empty($conf->deplacement->enabled)) { + $nbElements = 0; + // Enable caching of thirdrparty count Contacts + $cachekey = 'count_elements_project_'.$project->id; + $dataretrieved = dol_getcache($cachekey); + if (!is_null($dataretrieved)) { + $nbElements = $dataretrieved; + } else { + if (!empty($conf->propal->enabled)) { + $nbElements += $project->getElementCount('propal', 'propal'); + } + if (!empty($conf->commande->enabled)) { + $nbElements += $project->getElementCount('order', 'commande'); + } + if (!empty($conf->facture->enabled)) { + $nbElements += $project->getElementCount('invoice', 'facture'); + } + if (!empty($conf->facture->enabled)) { + $nbElements += $project->getElementCount('invoice_predefined', 'facture_rec'); + } + if (!empty($conf->supplier_proposal->enabled)) { + $nbElements += $project->getElementCount('proposal_supplier', 'supplier_proposal'); + } + if (!empty($conf->supplier_order->enabled)) { + $nbElements += $project->getElementCount('order_supplier', 'commande_fournisseur'); + } + if (!empty($conf->supplier_invoice->enabled)) { + $nbElements += $project->getElementCount('invoice_supplier', 'facture_fourn'); + } + if (!empty($conf->contrat->enabled)) { + $nbElements += $project->getElementCount('contract', 'contrat'); + } + if (!empty($conf->ficheinter->enabled)) { + $nbElements += $project->getElementCount('intervention', 'fichinter'); + } + if (!empty($conf->expedition->enabled)) { + $nbElements += $project->getElementCount('shipping', 'expedition'); + } + if (!empty($conf->mrp->enabled)) { + $nbElements += $project->getElementCount('mrp', 'mrp_mo', 'fk_project'); + } + if (!empty($conf->deplacement->enabled)) { + $nbElements += $project->getElementCount('trip', 'deplacement'); + } + if (!empty($conf->expensereport->enabled)) { + $nbElements += $project->getElementCount('expensereport', 'expensereport'); + } + if (!empty($conf->don->enabled)) { + $nbElements += $project->getElementCount('donation', 'don'); + } + if (!empty($conf->loan->enabled)) { + $nbElements += $project->getElementCount('loan', 'loan'); + } + if (!empty($conf->tax->enabled)) { + $nbElements += $project->getElementCount('chargesociales', 'chargesociales'); + } + if (!empty($conf->projet->enabled)) { + $nbElements += $project->getElementCount('project_task', 'projet_task'); + } + if (!empty($conf->stock->enabled)) { + $nbElements += $project->getElementCount('stock_mouvement', 'stock'); + } + if (!empty($conf->salaries->enabled)) { + $nbElements += $project->getElementCount('salaries', 'payment_salary'); + } + if (!empty($conf->banque->enabled)) { + $nbElements += $project->getElementCount('variouspayment', 'payment_various'); + } + dol_setcache($cachekey, $nbElements, 120); // If setting cache fails, this is not a problem, so we do not test result. + } $head[$h][0] = DOL_URL_ROOT.'/projet/element.php?id='.$project->id; $head[$h][1] = $langs->trans("ProjectOverview"); - if ($count > 0) $head[$h][1] .= ''.$count.''; + if ($nbElements > 0) { + $head[$h][1] .= ''.$nbElements.''; + } $head[$h][2] = 'element'; $h++; } + if ($conf->eventorganization->enabled) { + $langs->load('eventorganization'); + //TODO : Count + $nbConfOrBooth = 1; + $head[$h][0] = DOL_URL_ROOT . '/eventorganization/conferenceorbooth_list.php?projectid=' . $project->id; + $head[$h][1] = $langs->trans("ConferenceOrBoothTab"); + if ($nbContact > 0) { + $head[$h][1] .= '' . $nbConfOrBooth . ''; + } + $head[$h][2] = 'eventorganisation'; + $h++; + } + // Show more tabs from modules // Entries must be declared in modules descriptor with line // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab @@ -128,44 +224,73 @@ function project_prepare_head(Project $project) complete_head_from_modules($conf, $langs, $project, $head, $h, 'project'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($project->note_private)) $nbNote++; - if (!empty($project->note_public)) $nbNote++; + if (!empty($project->note_private)) { + $nbNote++; + } + if (!empty($project->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/projet/note.php?id='.$project->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'notes'; $h++; } - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($project->ref); - $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $project->element, $project->id); + // Attached files and Links + $totalAttached = 0; + // Enable caching of thirdrparty count attached files and links + require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php'; + $cachekey = 'count_attached_project_'.$project->id; + $dataretrieved = dol_getcache($cachekey); + if (!is_null($dataretrieved)) { + $totalAttached = $dataretrieved; + } else { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($project->ref); + $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); + $nbLinks = Link::count($db, $project->element, $project->id); + $totalAttached = $nbFiles + $nbLinks; + dol_setcache($cachekey, $totalAttached, 120); // If setting cache fails, this is not a problem, so we do not test result. + } $head[$h][0] = DOL_URL_ROOT.'/projet/document.php?id='.$project->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($totalAttached) > 0) { + $head[$h][1] .= ''.($totalAttached).''; + } $head[$h][2] = 'document'; $h++; // Manage discussion - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT)) - { - $nbComments = $project->getNbComments(); + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT)) { + $nbComments = 0; + // Enable caching of thirdrparty count attached files and links + require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php'; + $cachekey = 'count_attached_project_'.$project->id; + $dataretrieved = dol_getcache($cachekey); + if (!is_null($dataretrieved)) { + $nbComments = $dataretrieved; + } else { + $nbComments = $project->getNbComments(); + dol_setcache($cachekey, $nbComments, 120); // If setting cache fails, this is not a problem, so we do not test result. + } $head[$h][0] = DOL_URL_ROOT.'/projet/comment.php?id='.$project->id; $head[$h][1] = $langs->trans("CommentLink"); - if ($nbComments > 0) $head[$h][1] .= ''.$nbComments.''; + if ($nbComments > 0) { + $head[$h][1] .= ''.$nbComments.''; + } $head[$h][2] = 'project_comment'; $h++; } $head[$h][0] = DOL_URL_ROOT.'/projet/info.php?id='.$project->id; $head[$h][1] .= $langs->trans("Events"); - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $head[$h][1] .= '/'; $head[$h][1] .= $langs->trans("Agenda"); } @@ -198,7 +323,9 @@ function task_prepare_head($object) $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/contact.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : ''); $head[$h][1] = $langs->trans("TaskRessourceLinks"); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'task_contact'; $h++; @@ -210,15 +337,20 @@ function task_prepare_head($object) $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t"; $sql .= " WHERE t.fk_task =".$object->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $nbTimeSpent = 1; - } else dol_print_error($db); + if ($obj) { + $nbTimeSpent = 1; + } + } else { + dol_print_error($db); + } $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : ''); $head[$h][1] = $langs->trans("TimeSpent"); - if ($nbTimeSpent > 0) $head[$h][1] .= '...'; + if ($nbTimeSpent > 0) { + $head[$h][1] .= '...'; + } $head[$h][2] = 'task_time'; $h++; @@ -228,14 +360,19 @@ function task_prepare_head($object) // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'task'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/note.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : ''); $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'task_notes'; $h++; } @@ -247,17 +384,20 @@ function task_prepare_head($object) $nbFiles = count(dol_dir_list($filesdir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'task_document'; $h++; // Manage discussion - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK)) - { + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK)) { $nbComments = $object->getNbComments(); $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/comment.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : ''); $head[$h][1] = $langs->trans("CommentLink"); - if ($nbComments > 0) $head[$h][1] .= ''.$nbComments.''; + if ($nbComments > 0) { + $head[$h][1] .= ''.$nbComments.''; + } $head[$h][2] = 'task_comment'; $h++; } @@ -284,26 +424,25 @@ function project_timesheet_prepare_head($mode, $fuser = null) $param = ''; $param .= ($mode ? '&mode='.$mode : ''); - if (is_object($fuser) && $fuser->id > 0 && $fuser->id != $user->id) $param .= '&search_usertoprocessid='.$fuser->id; + if (is_object($fuser) && $fuser->id > 0 && $fuser->id != $user->id) { + $param .= '&search_usertoprocessid='.$fuser->id; + } - if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERMONTH)) - { + if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERMONTH)) { $head[$h][0] = DOL_URL_ROOT."/projet/activity/permonth.php".($param ? '?'.$param : ''); $head[$h][1] = $langs->trans("InputPerMonth"); $head[$h][2] = 'inputpermonth'; $h++; } - if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERWEEK)) - { + if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERWEEK)) { $head[$h][0] = DOL_URL_ROOT."/projet/activity/perweek.php".($param ? '?'.$param : ''); $head[$h][1] = $langs->trans("InputPerWeek"); $head[$h][2] = 'inputperweek'; $h++; } - if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERTIME)) - { + if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERTIME)) { $head[$h][0] = DOL_URL_ROOT."/projet/activity/perday.php".($param ? '?'.$param : ''); $head[$h][1] = $langs->trans("InputPerDay"); $head[$h][2] = 'inputperday'; @@ -356,6 +495,15 @@ function project_admin_prepare_head() $head[$h][2] = 'attributes_task'; $h++; + if (! empty($conf->global->MAIN_FEATURES_LEVEL) && $conf->global->MAIN_FEATURES_LEVEL >= 2) { + $langs->load("members"); + + $head[$h][0] = DOL_URL_ROOT.'/projet/admin/website.php'; + $head[$h][1] = $langs->trans("BlankSubscriptionForm"); + $head[$h][2] = 'website'; + $h++; + } + complete_head_from_modules($conf, $langs, null, $head, $h, 'project_admin', 'remove'); return $head; @@ -389,7 +537,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t $projectsArrayId = explode(',', $projectsListId); if ($filterprogresscalc !== '') { - foreach ($lines as $key=>$line) { + foreach ($lines as $key => $line) { if (!empty($line->planned_workload) && !empty($line->duration)) { $filterprogresscalc = str_replace(' = ', ' == ', $filterprogresscalc); if (!eval($filterprogresscalc)) { @@ -404,8 +552,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t // We declare counter as global because we want to edit them into recursive call global $total_projectlinesa_spent, $total_projectlinesa_planned, $total_projectlinesa_spent_if_planned, $total_projectlinesa_declared_if_planned, $total_projectlinesa_tobill, $total_projectlinesa_billed; - if ($level == 0) - { + if ($level == 0) { $total_projectlinesa_spent = 0; $total_projectlinesa_planned = 0; $total_projectlinesa_spent_if_planned = 0; @@ -414,31 +561,28 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t $total_projectlinesa_billed = 0; } - for ($i = 0; $i < $numlines; $i++) - { - if ($parent == 0 && $level >= 0) $level = 0; // if $level = -1, we dont' use sublevel recursion, we show all lines + for ($i = 0; $i < $numlines; $i++) { + if ($parent == 0 && $level >= 0) { + $level = 0; // if $level = -1, we dont' use sublevel recursion, we show all lines + } // Process line // print "i:".$i."-".$lines[$i]->fk_project.'
    '; - if ($lines[$i]->fk_parent == $parent || $level < 0) // if $level = -1, we dont' use sublevel recursion, we show all lines - { + if ($lines[$i]->fk_parent == $parent || $level < 0) { // if $level = -1, we dont' use sublevel recursion, we show all lines // Show task line. $showline = 1; $showlineingray = 0; // If there is filters to use - if (is_array($taskrole)) - { + if (is_array($taskrole)) { // If task not legitimate to show, search if a legitimate task exists later in tree - if (!isset($taskrole[$lines[$i]->id]) && $lines[$i]->id != $lines[$i]->fk_parent) - { + if (!isset($taskrole[$lines[$i]->id]) && $lines[$i]->id != $lines[$i]->fk_parent) { // So search if task has a subtask legitimate to show $foundtaskforuserdeeper = 0; searchTaskInChild($foundtaskforuserdeeper, $lines[$i]->id, $lines, $taskrole); //print '$foundtaskforuserpeeper='.$foundtaskforuserdeeper.'
    '; - if ($foundtaskforuserdeeper > 0) - { + if ($foundtaskforuserdeeper > 0) { $showlineingray = 1; // We will show line but in gray } else { $showline = 0; // No reason to show line @@ -447,11 +591,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } else { // Caller did not ask to filter on tasks of a specific user (this probably means he want also tasks of all users, into public project // or into all other projects if user has permission to). - if (empty($user->rights->projet->all->lire)) - { + if (empty($user->rights->projet->all->lire)) { // User is not allowed on this project and project is not public, so we hide line - if (!in_array($lines[$i]->fk_project, $projectsArrayId)) - { + if (!in_array($lines[$i]->fk_project, $projectsArrayId)) { // Note that having a user assigned to a task into a project user has no permission on, should not be possible // because assignement on task can be done only on contact of project. // If assignement was done and after, was removed from contact of project, then we can hide the line. @@ -460,11 +602,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } } - if ($showline) - { + if ($showline) { // Break on a new project - if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) - { + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) { $var = !$var; $lastprojectid = $lines[$i]->fk_project; } @@ -491,13 +631,15 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t $taskstatic->duration_effective = $lines[$i]->duration; - if ($showproject) - { + if ($showproject) { // Project ref print "
    "; //if ($showlineingray) print ''; - if ($lines[$i]->public || in_array($lines[$i]->fk_project, $projectsArrayId) || !empty($user->rights->projet->all->lire)) print $projectstatic->getNomUrl(1); - else print $projectstatic->getNomUrl(1, 'nolink'); + if ($lines[$i]->public || in_array($lines[$i]->fk_project, $projectsArrayId) || !empty($user->rights->projet->all->lire)) { + print $projectstatic->getNomUrl(1); + } else { + print $projectstatic->getNomUrl(1, 'nolink'); + } //if ($showlineingray) print ''; print ""; - if ($showlineingray) + if ($showlineingray) { print ''; + } //else print ''; for ($k = 0; $k < $level; $k++) { print '
    '; @@ -532,8 +675,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t for ($k = 0; $k < $level; $k++) { print '
    '; } - if ($showlineingray) + if ($showlineingray) { print '
    '; + } //else print ''; print "
    '; print dol_print_date($lines[$i]->date_end, 'dayhour'); - if ($taskstatic->hasDelay()) + if ($taskstatic->hasDelay()) { print img_warning($langs->trans("Late")); + } print ''; - if ($showlineingray) + if ($showlineingray) { print ''; - else print ''; - if ($lines[$i]->duration) + } else { + print ''; + } + if ($lines[$i]->duration) { print convertSecondToTime($lines[$i]->duration, $timespentoutputformat); - else print '--:--'; - if ($showlineingray) + } else { + print '--:--'; + } + if ($showlineingray) { print ''; - else print ''; + } else { + print ''; + } print ''; if ($lines[$i]->planned_workload || $lines[$i]->duration) { - if ($lines[$i]->planned_workload) + if ($lines[$i]->planned_workload) { print round(100 * $lines[$i]->duration / $lines[$i]->planned_workload, 2).' %'; - else print ''.$langs->trans('WorkloadNotDefined').''; + } else { + print ''.$langs->trans('WorkloadNotDefined').''; + } } print ''; @@ -650,25 +806,57 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } } - // Contacts of task - if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) - { + // Contacts of tasks. Disabled, because available by default just after + /* + if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) { print ''; - foreach (array('internal', 'external') as $source) - { + foreach (array('internal', 'external') as $source) { $tab = $lines[$i]->liste_contact(-1, $source); $num = count($tab); if (!empty($num)) { foreach ($tab as $contacttask) { //var_dump($contacttask); - if ($source == 'internal') $c = new User($db); - else $c = new Contact($db); + if ($source == 'internal') { + $c = new User($db); + } else { + $c = new Contact($db); + } $c->fetch($contacttask['id']); print $c->getNomUrl(1).' ('.$contacttask['libelle'].')
    '; } } } print '
    '; + foreach (array('internal', 'external') as $source) { + $tab = $lines[$i]->liste_contact(-1, $source); + $num = count($tab); + if (!empty($num)) { + foreach ($tab as $contacttask) { + //var_dump($contacttask); + if ($source == 'internal') { + $c = new User($db); + } else { + $c = new Contact($db); + } + $c->fetch($contacttask['id']); + if (!empty($c->photo)) { + print $c->getNomUrl(-2).' '; + } else { + if (get_class($c) == 'User') { + print $c->getNomUrl(2, '', 0, 0, 24, 1);//.' '; + } else { + print $c->getNomUrl(2);//.' '; + } + } + } + } + } + print '
    '.$langs->trans("Total").''; print convertSecondToTime($total_projectlinesa_planned, 'allhourmin'); @@ -720,11 +922,13 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } if (count($arrayfields) > 0 && !empty($arrayfields['t.duration_effective']['checked'])) { print ''; - if ($projectidfortotallink > 0) + if ($projectidfortotallink > 0) { print ''; + } print convertSecondToTime($total_projectlinesa_spent, 'allhourmin'); - if ($projectidfortotallink > 0) + if ($projectidfortotallink > 0) { print ''; + } print ''; - if ($total_projectlinesa_planned) + if ($total_projectlinesa_planned) { print $totalCalculatedProgress.' %'; + } print ''; - if ($total_projectlinesa_planned) + if ($total_projectlinesa_planned) { print ''.$totalAverageDeclaredProgress.' %'; + } print ''; print convertSecondToTime($total_projectlinesa_tobill, 'allhourmin'); @@ -791,9 +996,12 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t print '
    '; print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); - if ($projectstatic->title) - { + if ($projectstatic->title) { print ' - '; print $projectstatic->title; } @@ -908,7 +1109,9 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec print '
    "; - if ($oldprojectforbreak == -1) - { + if ($oldprojectforbreak == -1) { print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); print '
    '.$projectstatic->title; } @@ -930,17 +1132,23 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec // Thirdparty print '
    '; - if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project', 10); + if ($thirdpartystatic->id > 0) { + print $thirdpartystatic->getNomUrl(1, 'project', 10); + } print ''; print ''; - for ($k = 0; $k < $level; $k++) print "   "; + for ($k = 0; $k < $level; $k++) { + print "   "; + } print $taskstatic->getNomUrl(1, 'withproject', 'time'); // Label task print '
    '; - for ($k = 0; $k < $level; $k++) print "   "; + for ($k = 0; $k < $level; $k++) { + print "   "; + } print $taskstatic->label; //print "
    "; //for ($k = 0 ; $k < $level ; $k++) print "   "; @@ -952,19 +1160,18 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec print dol_print_date($lines[$i]->timespent_datehour, 'day'); print '
    '; @@ -985,7 +1196,9 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec $totalforeachline[$preselectedday] += $lines[$i]->timespent_duration; $alreadyspent = ''; - if ($dayWorkLoad > 0) $alreadyspent = convertSecondToTime($lines[$i]->timespent_duration, 'allhourmin'); + if ($dayWorkLoad > 0) { + $alreadyspent = convertSecondToTime($lines[$i]->timespent_duration, 'allhourmin'); + } print convertSecondToTime($lines[$i]->timespent_duration, 'allhourmin'); @@ -1063,54 +1276,47 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $numlines = count($lines); // Create a smaller array with sublevels only to be used later. This increase dramatically performances. - if ($parent == 0) // Always and only if at first level - { - for ($i = 0; $i < $numlines; $i++) - { - if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i]; + if ($parent == 0) { // Always and only if at first level + for ($i = 0; $i < $numlines; $i++) { + if ($lines[$i]->fk_task_parent) { + $lineswithoutlevel0[] = $lines[$i]; + } } } - if (empty($oldprojectforbreak)) - { + if (empty($oldprojectforbreak)) { $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : -1); // 0 to start break , -1 no break } //dol_syslog('projectLinesPerDay inc='.$inc.' preselectedday='.$preselectedday.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); - for ($i = 0; $i < $numlines; $i++) - { - if ($parent == 0) $level = 0; + for ($i = 0; $i < $numlines; $i++) { + if ($parent == 0) { + $level = 0; + } - if ($lines[$i]->fk_task_parent == $parent) - { + if ($lines[$i]->fk_task_parent == $parent) { $obj = &$lines[$i]; // To display extrafields // If we want all or we have a role on task, we show it - if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) - { + if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) { //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); - if ($restricteditformytask == 2 && empty($tasksrole[$lines[$i]->id])) // we have no role on task and we request to hide such cases - { + if ($restricteditformytask == 2 && empty($tasksrole[$lines[$i]->id])) { // we have no role on task and we request to hide such cases continue; } // Break on a new project - if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) - { + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) { $lastprojectid = $lines[$i]->fk_project; - if ($preselectedday) - { + if ($preselectedday) { $projectstatic->id = $lines[$i]->fk_project; } } - if (empty($workloadforid[$projectstatic->id])) - { - if ($preselectedday) - { + if (empty($workloadforid[$projectstatic->id])) { + if ($preselectedday) { $projectstatic->loadTimeSpent($preselectedday, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week - $workloadforid[$projectstatic->id] = 1; + $workloadforid[$projectstatic->id] = 1; } } @@ -1130,91 +1336,98 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $thirdpartystatic->name = $lines[$i]->thirdparty_name; $thirdpartystatic->email = $lines[$i]->thirdparty_email; - if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) - { + if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) { $addcolspan = 0; - if (!empty($arrayfields['t.planned_workload']['checked'])) $addcolspan++; - if (!empty($arrayfields['t.progress']['checked'])) $addcolspan++; - foreach ($arrayfields as $key => $val) - { - if ($val['checked'] && substr($key, 0, 5) == 'efpt.') $addcolspan++; + if (!empty($arrayfields['t.planned_workload']['checked'])) { + $addcolspan++; + } + if (!empty($arrayfields['t.progress']['checked'])) { + $addcolspan++; + } + foreach ($arrayfields as $key => $val) { + if ($val['checked'] && substr($key, 0, 5) == 'efpt.') { + $addcolspan++; + } } print '
    '; print $projectstatic->getNomUrl(1, '', 0, ''.$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); - if ($thirdpartystatic->id > 0) print ' - '.$thirdpartystatic->getNomUrl(1); - if ($projectstatic->title) - { + if ($thirdpartystatic->id > 0) { + print ' - '.$thirdpartystatic->getNomUrl(1); + } + if ($projectstatic->title) { print ' - '; print ''.$projectstatic->title.''; } /* - $colspan=5+(empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:2); - print ''; + $colspan=5+(empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:2); + print '
    '; - print ''; + print ''; - // PROJECT fields - if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right '); + // PROJECT fields + if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center '); + if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right '); - $extrafieldsobjectkey='projet'; - $extrafieldsobjectprefix='efp.'; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; + $extrafieldsobjectkey='projet'; + $extrafieldsobjectprefix='efp.'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; - print ''; - print ''; + print ''; + print ''; - // PROJECT fields - if (! empty($arrayfields['p.fk_opp_status']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['p.opp_amount']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['p.opp_percent']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['p.budget_amount']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['p.usage_bill_time']['checked'])) - { - print '\n"; - } + // PROJECT fields + if (! empty($arrayfields['p.fk_opp_status']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['p.opp_amount']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['p.opp_percent']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['p.budget_amount']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['p.usage_bill_time']['checked'])) + { + print '\n"; + } - $extrafieldsobjectkey='projet'; - $extrafieldsobjectprefix='efp.'; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + $extrafieldsobjectkey='projet'; + $extrafieldsobjectprefix='efp.'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - print ''; - print '
    '; - $code = dol_getIdFromCode($db, $lines[$i]->fk_opp_status, 'c_lead_status', 'rowid', 'code'); - if ($code) print $langs->trans("OppStatus".$code); - print "'; - print price($lines[$i]->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); - print "'; - print price($lines[$i]->opp_percent, 0, $langs, 1, 0).' %'; - print "'; - print price($lines[$i]->budget_amount, 0, $langs, 1, 0, 0, $conf->currency); - print "'; - print yn($lines[$i]->usage_bill_time); - print "'; + $code = dol_getIdFromCode($db, $lines[$i]->fk_opp_status, 'c_lead_status', 'rowid', 'code'); + if ($code) print $langs->trans("OppStatus".$code); + print "'; + print price($lines[$i]->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); + print "'; + print price($lines[$i]->opp_percent, 0, $langs, 1, 0).' %'; + print "'; + print price($lines[$i]->budget_amount, 0, $langs, 1, 0, 0, $conf->currency); + print "'; + print yn($lines[$i]->usage_bill_time); + print "
    '; + print '
    '; */ print '
    "; - if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + if ($oldprojectforbreak == -1) { + print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + } print "'; - if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project', 10); + if ($thirdpartystatic->id > 0) { + print $thirdpartystatic->getNomUrl(1, 'project', 10); + } print ''; print ''; - for ($k = 0; $k < $level; $k++) print '
    '; + for ($k = 0; $k < $level; $k++) { + print '
    '; + } print $taskstatic->getNomUrl(1, 'withproject', 'time'); // Label task print '
    '; print ''.$taskstatic->label.''; - for ($k = 0; $k < $level; $k++) print "
    "; + for ($k = 0; $k < $level; $k++) { + print "
    "; + } print "
    '; - if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); - else print '--:--'; + if ($lines[$i]->planned_workload) { + print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); + } else { + print '--:--'; + } print ''; print $formother->select_percent($lines[$i]->progress, $lines[$i]->id.'progress'); print ''; // $lines[$i]->duration is a denormalised field = summ of time spent by everybody for task. What we need is time consummed by user - if ($lines[$i]->duration) - { + if ($lines[$i]->duration) { print ''; print convertSecondToTime($lines[$i]->duration, 'allhourmin'); print ''; - } else print '--:--'; + } else { + print '--:--'; + } print "'; $tmptimespent = $taskstatic->getSummaryOfTimeSpent($fuser->id); - if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); - else print '--:--'; + if ($tmptimespent['total_duration']) { + print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); + } else { + print '--:--'; + } print "'; - if ((!$lines[$i]->public) && $disabledproject) print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); - elseif ($disabledtask) - { - $titleassigntask = $langs->trans("AssignTaskToMe"); - if ($fuser->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + if ((!$lines[$i]->public) && $disabledproject) { + print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); + } elseif ($disabledtask) { + $titleassigntask = $langs->trans("AssignTaskToMe"); + if ($fuser->id != $user->id) { + $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + } - print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask)); - } + print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask)); + } print '
    '; print $projectstatic->getNomUrl(1, '', 0, ''.$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); - if ($thirdpartystatic->id > 0) print ' - '.$thirdpartystatic->getNomUrl(1); - if ($projectstatic->title) - { + if ($thirdpartystatic->id > 0) { + print ' - '.$thirdpartystatic->getNomUrl(1); + } + if ($projectstatic->title) { print ' - '; print ''.$projectstatic->title.''; } @@ -1530,65 +1758,67 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ print '
    '; - $code = dol_getIdFromCode($db, $lines[$i]->fk_opp_status, 'c_lead_status', 'rowid', 'code'); - if ($code) print $langs->trans("OppStatus".$code); - print "'; - print price($lines[$i]->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); - print "'; - print price($lines[$i]->opp_percent, 0, $langs, 1, 0).' %'; - print "'; - print price($lines[$i]->budget_amount, 0, $langs, 1, 0, 0, $conf->currency); - print "'; - print yn($lines[$i]->usage_bill_time); - print "'; + $code = dol_getIdFromCode($db, $lines[$i]->fk_opp_status, 'c_lead_status', 'rowid', 'code'); + if ($code) print $langs->trans("OppStatus".$code); + print "'; + print price($lines[$i]->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); + print "'; + print price($lines[$i]->opp_percent, 0, $langs, 1, 0).' %'; + print "'; + print price($lines[$i]->budget_amount, 0, $langs, 1, 0, 0, $conf->currency); + print "'; + print yn($lines[$i]->usage_bill_time); + print "
    '; + print ''; + print ''; */ print ''; print ''; } - if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; + if ($oldprojectforbreak != -1) { + $oldprojectforbreak = $projectstatic->id; + } print ''."\n"; @@ -1600,30 +1830,36 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ */ // Project - if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) - { + if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { print ''; - if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + if ($oldprojectforbreak == -1) { + print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + } print ""; } // Thirdparty - if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) - { + if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { print ''; - if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project'); + if ($thirdpartystatic->id > 0) { + print $thirdpartystatic->getNomUrl(1, 'project'); + } print ''; } // Ref print ''; print ''; - for ($k = 0; $k < $level; $k++) print '
    '; + for ($k = 0; $k < $level; $k++) { + print '
    '; + } print $taskstatic->getNomUrl(1, 'withproject', 'time'); // Label task print '
    '; print ''.$taskstatic->label.''; - for ($k = 0; $k < $level; $k++) print "
    "; + for ($k = 0; $k < $level; $k++) { + print "
    "; + } print "\n"; // TASK extrafields @@ -1632,16 +1868,17 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Planned Workload - if (!empty($arrayfields['t.planned_workload']['checked'])) - { + if (!empty($arrayfields['t.planned_workload']['checked'])) { print ''; - if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); - else print '--:--'; + if ($lines[$i]->planned_workload) { + print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); + } else { + print '--:--'; + } print ''; } - if (!empty($arrayfields['t.progress']['checked'])) - { + if (!empty($arrayfields['t.progress']['checked'])) { // Progress declared % print ''; print $formother->select_percent($lines[$i]->progress, $lines[$i]->id.'progress'); @@ -1651,92 +1888,101 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ // Time spent by everybody print ''; // $lines[$i]->duration is a denormalised field = summ of time spent by everybody for task. What we need is time consummed by user - if ($lines[$i]->duration) - { + if ($lines[$i]->duration) { print ''; print convertSecondToTime($lines[$i]->duration, 'allhourmin'); print ''; - } else print '--:--'; + } else { + print '--:--'; + } print "\n"; // Time spent by user print ''; $tmptimespent = $taskstatic->getSummaryOfTimeSpent($fuser->id); - if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); - else print '--:--'; + if ($tmptimespent['total_duration']) { + print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); + } else { + print '--:--'; + } print "\n"; - $disabledproject = 1; $disabledtask = 1; + $disabledproject = 1; + $disabledtask = 1; //print "x".$lines[$i]->fk_project; //var_dump($lines[$i]); //var_dump($projectsrole[$lines[$i]->fk_project]); // If at least one role for project - if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) - { + if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) { $disabledproject = 0; $disabledtask = 0; } // If $restricteditformytask is on and I have no role on task, i disable edit - if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) - { + if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) { $disabledtask = 1; } //var_dump($projectstatic->weekWorkLoadPerTask); // Fields to show current time - $tableCell = ''; $modeinput = 'hours'; - for ($idw = 0; $idw < 7; $idw++) - { + $tableCell = ''; + $modeinput = 'hours'; + for ($idw = 0; $idw < 7; $idw++) { $tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); $cssonholiday = ''; - if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayallday '; - elseif (!$isavailable[$tmpday]['morning']) $cssonholiday .= 'onholidaymorning '; - elseif (!$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; + if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) { + $cssonholiday .= 'onholidayallday '; + } elseif (!$isavailable[$tmpday]['morning']) { + $cssonholiday .= 'onholidaymorning '; + } elseif (!$isavailable[$tmpday]['afternoon']) { + $cssonholiday .= 'onholidayafternoon '; + } $tmparray = dol_getdate($tmpday); $dayWorkLoad = $projectstatic->weekWorkLoadPerTask[$tmpday][$lines[$i]->id]; $totalforeachday[$tmpday] += $dayWorkLoad; $alreadyspent = ''; - if ($dayWorkLoad > 0) $alreadyspent = convertSecondToTime($dayWorkLoad, 'allhourmin'); + if ($dayWorkLoad > 0) { + $alreadyspent = convertSecondToTime($dayWorkLoad, 'allhourmin'); + } $alttitle = $langs->trans("AddHereTimeSpentForDay", $tmparray['day'], $tmparray['mon']); global $numstartworkingday, $numendworkingday; $cssweekend = ''; - if (($idw + 1 < $numstartworkingday) || ($idw + 1 > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. - { + if (($idw + 1 < $numstartworkingday) || ($idw + 1 > $numendworkingday)) { // This is a day is not inside the setup of working days, so we use a week-end css. $cssweekend = 'weekend'; } $tableCell = ''; //$tableCell .= 'idw='.$idw.' '.$conf->global->MAIN_START_WEEK.' '.$numstartworkingday.'-'.$numendworkingday; $placeholder = ''; - if ($alreadyspent) - { + if ($alreadyspent) { $tableCell .= ''; //$placeholder=' placeholder="00:00"'; - //$tableCell.='+'; + //$tableCell.='+'; } - $tableCell .= ''; - $tableCell .= ''; + $tableCell .= ' onkeyup="updateTotal('.$idw.',\''.$modeinput.'\')"'; + $tableCell .= ' onblur="regexEvent(this,event,\''.$modeinput.'\'); updateTotal('.$idw.',\''.$modeinput.'\')" />'; + $tableCell .= ''; print $tableCell; } // Warning print ''; - if ((!$lines[$i]->public) && $disabledproject) print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); - elseif ($disabledtask) - { - $titleassigntask = $langs->trans("AssignTaskToMe"); - if ($fuser->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + if ((!$lines[$i]->public) && $disabledproject) { + print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); + } elseif ($disabledtask) { + $titleassigntask = $langs->trans("AssignTaskToMe"); + if ($fuser->id != $user->id) { + $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + } - print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask)); - } + print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask)); + } print ''; print "\n"; @@ -1745,15 +1991,13 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ // Call to show task with a lower level (task under the current task) $inc++; $level++; - if ($lines[$i]->id > 0) - { + if ($lines[$i]->id > 0) { //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level); //var_dump($totalforeachday); $ret = projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, ($parent == 0 ? $lineswithoutlevel0 : $lines), $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable, $oldprojectforbreak, $arrayfields, $extrafields); //var_dump('ret with parent='.$lines[$i]->id.' level='.$level); //var_dump($ret); - foreach ($ret as $key => $val) - { + foreach ($ret as $key => $val) { $totalforeachday[$key] += $val; } //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level.' + subtasks'); @@ -1799,43 +2043,39 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & $lineswithoutlevel0 = array(); // Create a smaller array with sublevels only to be used later. This increase dramatically performances. - if ($parent == 0) // Always and only if at first level - { - for ($i = 0; $i < $numlines; $i++) - { - if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i]; + if ($parent == 0) { // Always and only if at first level + for ($i = 0; $i < $numlines; $i++) { + if ($lines[$i]->fk_task_parent) { + $lineswithoutlevel0[] = $lines[$i]; + } } } //dol_syslog('projectLinesPerWeek inc='.$inc.' firstdaytoshow='.$firstdaytoshow.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); - if (empty($oldprojectforbreak)) - { + if (empty($oldprojectforbreak)) { $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : -1); // 0 = start break, -1 = never break } - for ($i = 0; $i < $numlines; $i++) - { - if ($parent == 0) $level = 0; + for ($i = 0; $i < $numlines; $i++) { + if ($parent == 0) { + $level = 0; + } - if ($lines[$i]->fk_task_parent == $parent) - { + if ($lines[$i]->fk_task_parent == $parent) { // If we want all or we have a role on task, we show it - if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) - { + if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) { //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); // Break on a new project - if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) - { + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) { $lastprojectid = $lines[$i]->fk_project; $projectstatic->id = $lines[$i]->fk_project; } //var_dump('--- '.$level.' '.$firstdaytoshow.' '.$fuser->id.' '.$projectstatic->id.' '.$workloadforid[$projectstatic->id]); //var_dump($projectstatic->weekWorkLoadPerTask); - if (empty($workloadforid[$projectstatic->id])) - { + if (empty($workloadforid[$projectstatic->id])) { $projectstatic->loadTimeSpentMonth($firstdaytoshow, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week $workloadforid[$projectstatic->id] = 1; } @@ -1859,14 +2099,14 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & $thirdpartystatic->name = $lines[$i]->thirdparty_name; $thirdpartystatic->email = $lines[$i]->thirdparty_email; - if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) - { + if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) { print ''."\n"; print ''; print $projectstatic->getNomUrl(1, '', 0, ''.$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); - if ($thirdpartystatic->id > 0) print ' - '.$thirdpartystatic->getNomUrl(1); - if ($projectstatic->title) - { + if ($thirdpartystatic->id > 0) { + print ' - '.$thirdpartystatic->getNomUrl(1); + } + if ($projectstatic->title) { print ' - '; print ''.$projectstatic->title.''; } @@ -1874,7 +2114,9 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & print ''; } - if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; + if ($oldprojectforbreak != -1) { + $oldprojectforbreak = $projectstatic->id; + } print ''."\n"; // User @@ -1897,18 +2139,25 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & // Ref print ''; print ''; - for ($k = 0; $k < $level; $k++) print '
    '; + for ($k = 0; $k < $level; $k++) { + print '
    '; + } print $taskstatic->getNomUrl(1, 'withproject', 'time'); // Label task print '
    '; print ''.$taskstatic->label.''; - for ($k = 0; $k < $level; $k++) print "
    "; + for ($k = 0; $k < $level; $k++) { + print "
    "; + } print "\n"; // Planned Workload print ''; - if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); - else print '--:--'; + if ($lines[$i]->planned_workload) { + print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); + } else { + print '--:--'; + } print ''; // Progress declared % @@ -1919,60 +2168,64 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & // Time spent by everybody print ''; // $lines[$i]->duration is a denormalised field = summ of time spent by everybody for task. What we need is time consummed by user - if ($lines[$i]->duration) - { + if ($lines[$i]->duration) { print ''; print convertSecondToTime($lines[$i]->duration, 'allhourmin'); print ''; - } else print '--:--'; + } else { + print '--:--'; + } print "\n"; // Time spent by user print ''; $tmptimespent = $taskstatic->getSummaryOfTimeSpent($fuser->id); - if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); - else print '--:--'; + if ($tmptimespent['total_duration']) { + print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); + } else { + print '--:--'; + } print "\n"; - $disabledproject = 1; $disabledtask = 1; + $disabledproject = 1; + $disabledtask = 1; //print "x".$lines[$i]->fk_project; //var_dump($lines[$i]); //var_dump($projectsrole[$lines[$i]->fk_project]); // If at least one role for project - if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) - { + if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) { $disabledproject = 0; $disabledtask = 0; } // If $restricteditformytask is on and I have no role on task, i disable edit - if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) - { + if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) { $disabledtask = 1; } //var_dump($projectstatic->weekWorkLoadPerTask); //TODO // Fields to show current time - $tableCell = ''; $modeinput = 'hours'; + $tableCell = ''; + $modeinput = 'hours'; $TFirstDay = getFirstDayOfEachWeek($TWeek, date('Y', $firstdaytoshow)); $TFirstDay[reset($TWeek)] = 1; foreach ($TFirstDay as &$fday) { $fday--; } - foreach ($TWeek as $weekNb) - { + foreach ($TWeek as $weekNb) { $weekWorkLoad = $projectstatic->monthWorkLoadPerTask[$weekNb][$lines[$i]->id]; $totalforeachweek[$weekNb] += $weekWorkLoad; $alreadyspent = ''; - if ($weekWorkLoad > 0) $alreadyspent = convertSecondToTime($weekWorkLoad, 'allhourmin'); + if ($weekWorkLoad > 0) { + $alreadyspent = convertSecondToTime($weekWorkLoad, 'allhourmin'); + } $alttitle = $langs->trans("AddHereTimeSpentForWeek", $weekNb); $tableCell = ''; $placeholder = ''; - if ($alreadyspent) - { + if ($alreadyspent) { $tableCell .= ''; //$placeholder=' placeholder="00:00"'; //$tableCell.='+'; @@ -1988,11 +2241,13 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & // Warning print ''; - if ((!$lines[$i]->public) && $disabledproject) print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); - elseif ($disabledtask) - { + if ((!$lines[$i]->public) && $disabledproject) { + print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); + } elseif ($disabledtask) { $titleassigntask = $langs->trans("AssignTaskToMe"); - if ($fuser->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + if ($fuser->id != $user->id) { + $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + } print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask)); } @@ -2004,15 +2259,13 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & // Call to show task with a lower level (task under the current task) $inc++; $level++; - if ($lines[$i]->id > 0) - { + if ($lines[$i]->id > 0) { //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level); //var_dump($totalforeachday); $ret = projectLinesPerMonth($inc, $firstdaytoshow, $fuser, $lines[$i]->id, ($parent == 0 ? $lineswithoutlevel0 : $lines), $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable, $oldprojectforbreak, $TWeek); //var_dump('ret with parent='.$lines[$i]->id.' level='.$level); //var_dump($ret); - foreach ($ret as $key => $val) - { + foreach ($ret as $key => $val) { $totalforeachweek[$key] += $val; } //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level.' + subtasks'); @@ -2041,14 +2294,11 @@ function searchTaskInChild(&$inc, $parent, &$lines, &$taskrole) { //print 'Search in line with parent id = '.$parent.'
    '; $numlines = count($lines); - for ($i = 0; $i < $numlines; $i++) - { + for ($i = 0; $i < $numlines; $i++) { // Process line $lines[$i] - if ($lines[$i]->fk_parent == $parent && $lines[$i]->id != $lines[$i]->fk_parent) - { + if ($lines[$i]->fk_parent == $parent && $lines[$i]->id != $lines[$i]->fk_parent) { // If task is legitimate to show, no more need to search deeper - if (isset($taskrole[$lines[$i]->id])) - { + if (isset($taskrole[$lines[$i]->id])) { //print 'Found a legitimate task id='.$lines[$i]->id.'
    '; $inc++; return $inc; @@ -2057,7 +2307,9 @@ function searchTaskInChild(&$inc, $parent, &$lines, &$taskrole) searchTaskInChild($inc, $lines[$i]->id, $lines, $taskrole); //print 'Found inc='.$inc.'
    '; - if ($inc > 0) return $inc; + if ($inc > 0) { + return $inc; + } } } @@ -2108,7 +2360,9 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks $project_year_filter = 0; $title = $langs->trans("Projects"); - if (strcmp($status, '') && $status >= 0) $title = $langs->trans("Projects").' '.$langs->trans($projectstatic->statuts_long[$status]); + if (strcmp($status, '') && $status >= 0) { + $title = $langs->trans("Projects").' '.$langs->trans($projectstatic->statuts_long[$status]); + } $arrayidtypeofcontact = array(); @@ -2116,8 +2370,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks print ''; $sql = " FROM ".MAIN_DB_PREFIX."projet as p"; - if ($mytasks) - { + if ($mytasks) { $sql .= ", ".MAIN_DB_PREFIX."projet_task as t"; $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc"; @@ -2126,27 +2379,24 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks } $sql .= " WHERE p.entity IN (".getEntity('project').")"; $sql .= " AND p.rowid IN (".$projectsListId.")"; - if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; - if ($mytasks) - { + if ($socid) { + $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + } + if ($mytasks) { $sql .= " AND p.rowid = t.fk_projet"; $sql .= " AND ec.element_id = t.rowid"; $sql .= " AND ec.fk_socpeople = ".$user->id; $sql .= " AND ec.fk_c_type_contact = ctc.rowid"; // Replace the 2 lines with ec.fk_c_type_contact in $arrayidtypeofcontact $sql .= " AND ctc.element = 'project_task'"; } - if ($status >= 0) - { + if ($status >= 0) { $sql .= " AND p.fk_statut = ".(int) $status; } - if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE)) - { + if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE)) { $project_year_filter = GETPOST("project_year_filter"); //Check if empty or invalid year. Wildcard ignores the sql check - if ($project_year_filter != "*") - { - if (empty($project_year_filter) || !ctype_digit($project_year_filter)) - { + if ($project_year_filter != "*") { + if (empty($project_year_filter) || !ctype_digit($project_year_filter)) { $project_year_filter = date("Y"); } $sql .= " AND (p.dateo IS NULL OR p.dateo <= ".$db->idate(dol_get_last_day($project_year_filter, 12, false)).")"; @@ -2159,18 +2409,20 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks $sql1 = "SELECT p.rowid as projectid"; $sql1 .= $sql; $resql = $db->query($sql1); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $arrayidofprojects[$objp->projectid] = $objp->projectid; $i++; } - } else dol_print_error($db); - if (empty($arrayidofprojects)) $arrayidofprojects[0] = -1; + } else { + dol_print_error($db); + } + if (empty($arrayidofprojects)) { + $arrayidofprojects[0] = -1; + } // Get list of project with calculation on tasks $sql2 = "SELECT p.rowid as projectid, p.ref, p.title, p.fk_soc,"; @@ -2190,8 +2442,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks $sql2 .= " ORDER BY p.title, p.ref"; $resql = $db->query($sql2); - if ($resql) - { + if ($resql) { $total_task = 0; $total_opp_amount = 0; $ponderated_opp_amount = 0; @@ -2202,25 +2453,30 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks print ''; print_liste_field_titre($title.''.$num.'', $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder); print_liste_field_titre("ThirdParty", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder); - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { - if (!in_array('prospectionstatus', $hiddenfields)) print_liste_field_titre("OpportunityStatus", "", "", "", "", '', $sortfield, $sortorder, 'right '); - print_liste_field_titre("OpportunityAmount", "", "", "", "", 'align="right"', $sortfield, $sortorder); + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { + if (!in_array('prospectionstatus', $hiddenfields)) { + print_liste_field_titre("OpportunityStatus", "", "", "", "", 'style="max-width: 100px"', $sortfield, $sortorder, 'right '); + } + print_liste_field_titre("OpportunityAmount", "", "", "", "", 'style="max-width: 100px"', $sortfield, $sortorder, 'right '); //print_liste_field_titre('OpportunityWeightedAmount', '', '', '', '', 'align="right"', $sortfield, $sortorder); } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print_liste_field_titre("Tasks", "", "", "", "", 'align="right"', $sortfield, $sortorder); - if (!in_array('plannedworkload', $hiddenfields)) print_liste_field_titre("PlannedWorkload", "", "", "", "", '', $sortfield, $sortorder, 'right '); - if (!in_array('declaredprogress', $hiddenfields)) print_liste_field_titre("ProgressDeclared", "", "", "", "", '', $sortfield, $sortorder, 'right '); + if (!in_array('plannedworkload', $hiddenfields)) { + print_liste_field_titre("PlannedWorkload", "", "", "", "", 'style="max-width: 100px"', $sortfield, $sortorder, 'right '); + } + if (!in_array('declaredprogress', $hiddenfields)) { + print_liste_field_titre("%", "", "", "", "", '', $sortfield, $sortorder, 'right ', $langs->trans("ProgressDeclared")); + } + } + if (!in_array('projectstatus', $hiddenfields)) { + print_liste_field_titre("Status", "", "", "", "", '', $sortfield, $sortorder, 'right '); } - if (!in_array('projectstatus', $hiddenfields)) print_liste_field_titre("Status", "", "", "", "", '', $sortfield, $sortorder, 'right '); print "\n"; $total_plannedworkload = 0; $total_declaredprogressworkload = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $projectstatic->id = $objp->projectid; @@ -2229,8 +2485,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks // Check is user has read permission on project $userAccess = $projectstatic->restrictedProjectArea($user); - if ($userAccess >= 0) - { + if ($userAccess >= 0) { $projectstatic->ref = $objp->ref; $projectstatic->status = $objp->status; $projectstatic->title = $objp->title; @@ -2241,12 +2496,13 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks print ''; print ''; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { if (!in_array('prospectionstatus', $hiddenfields)) { print ''; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print ''; $plannedworkload = $objp->planned_workload; $total_plannedworkload += $plannedworkload; - if (!in_array('plannedworkload', $hiddenfields)) - { + if (!in_array('plannedworkload', $hiddenfields)) { print ''; } - if (!in_array('declaredprogress', $hiddenfields)) - { + if (!in_array('declaredprogress', $hiddenfields)) { $declaredprogressworkload = $objp->declared_progess_workload; $total_declaredprogressworkload += $declaredprogressworkload; print ''; print '"; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { if (!in_array('prospectionstatus', $hiddenfields)) { print ''; } @@ -2350,11 +2603,14 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks print $form->textwithpicto(price($total_opp_amount, 0, '', 1, -1, 0, $conf->currency), $langs->trans("OpportunityPonderatedAmountDesc").' : '.price($ponderated_opp_amount, 0, '', 1, -1, 0, $conf->currency)); print ''; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print ''; - if (!in_array('plannedworkload', $hiddenfields)) print ''; - if (!in_array('declaredprogress', $hiddenfields)) print ''; + if (!in_array('plannedworkload', $hiddenfields)) { + print ''; + } + if (!in_array('declaredprogress', $hiddenfields)) { + print ''; + } } if (!in_array('projectstatus', $hiddenfields)) { print ''; @@ -2369,8 +2625,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks print "
    '; print $projectstatic->getNomUrl(1, '', 0, '', '-', 0, -1, 'nowraponall'); - if (!in_array('projectlabel', $hiddenfields)) print '
    '.dol_trunc($objp->title, 24).''; + if (!in_array('projectlabel', $hiddenfields)) { + print '
    '.dol_trunc($objp->title, 24).''; + } print '
    '; - if ($objp->fk_soc > 0) - { + if ($objp->fk_soc > 0) { $thirdpartystatic->id = $objp->socid; $thirdpartystatic->name = $objp->socname; //$thirdpartystatic->name_alias = $objp->name_alias; @@ -2263,8 +2519,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks } print ''; // Because color of prospection status has no meaning yet, it is used if hidden constant is set @@ -2298,22 +2553,21 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks $alttext = $langs->trans("OpportunityWeightedAmount").' '.price($opp_weighted_amount, 0, '', 1, -1, 0, $conf->currency); $ponderated_opp_amount += price2num($opp_weighted_amount); } - if ($objp->opp_amount) print ''.price($objp->opp_amount, 0, '', 1, -1, 0, $conf->currency).''; + if ($objp->opp_amount) { + print ''.price($objp->opp_amount, 0, '', 1, -1, 0, $conf->currency).''; + } print ''.$objp->nb.''.($plannedworkload ?convertSecondToTime($plannedworkload) : '').''; @@ -2340,8 +2594,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks print '
    '.$langs->trans("Total")."'.$total_task.''.($total_plannedworkload ?convertSecondToTime($total_plannedworkload) : '').''.($total_plannedworkload ?round(100 * $total_declaredprogressworkload / $total_plannedworkload, 0).'%' : '').''.($total_plannedworkload ?convertSecondToTime($total_plannedworkload) : '').''.($total_plannedworkload ?round(100 * $total_declaredprogressworkload / $total_plannedworkload, 0).'%' : '').'
    "; print '
    '; - if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE)) - { + if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE)) { //Add the year filter input print ''; print ''; @@ -2399,8 +2654,12 @@ function getTaskProgressView($task, $label = true, $progressNumber = true, $hide $plannedworkloadoutputformat = 'allhourmin'; $timespentoutputformat = 'allhourmin'; - if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; - if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT; + if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) { + $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; + } + if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) { + $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT; + } if (empty($task->progress) && !empty($hideOnProgressNull)) { return ''; @@ -2439,8 +2698,7 @@ function getTaskProgressView($task, $label = true, $progressNumber = true, $hide $out .= '
    '; - if ($label !== false) - { + if ($label !== false) { $out .= ' '; if ($label !== true) { @@ -2452,21 +2710,25 @@ function getTaskProgressView($task, $label = true, $progressNumber = true, $hide } - if ($progressNumber !== false) - { + if ($progressNumber !== false) { $out .= ' '; if ($progressNumber !== true) { $out .= $progressNumber; // replace label by param } else { - if ($task->hasDelay()) $out .= img_warning($langs->trans("Late")).' '; + if ($task->hasDelay()) { + $out .= img_warning($langs->trans("Late")).' '; + } $url = DOL_URL_ROOT.'/projet/tasks/time.php?id='.$task->id; $out .= !empty($diff) ? $diff.' ' : ''; $out .= ''; $out .= ''; - if ($task->duration_effective) $out .= convertSecondToTime($task->duration_effective, $timespentoutputformat); - else $out .= '--:--'; + if ($task->duration_effective) { + $out .= convertSecondToTime($task->duration_effective, $timespentoutputformat); + } else { + $out .= '--:--'; + } $out .= ''; $out .= ''; @@ -2474,8 +2736,11 @@ function getTaskProgressView($task, $label = true, $progressNumber = true, $hide $out .= ''; $out .= ''; - if ($task->planned_workload) $out .= convertSecondToTime($task->planned_workload, $plannedworkloadoutputformat); - else $out .= '--:--'; + if ($task->planned_workload) { + $out .= convertSecondToTime($task->planned_workload, $plannedworkloadoutputformat); + } else { + $out .= '--:--'; + } $out .= ''; } $out .= ' '; @@ -2518,8 +2783,7 @@ function getTaskProgressBadge($task, $label = '', $tooltip = '') $out = ''; $badgeClass = ''; - if ($task->progress != '') - { + if ($task->progress != '') { // TODO : manage 100% // define color according to time spend vs workload @@ -2537,10 +2801,14 @@ function getTaskProgressBadge($task, $label = '', $tooltip = '') } } elseif (doubleval($progressCalculated) > doubleval($task->progress)) { // warning if close at 10% $badgeClass .= 'badge-warning'; - if (empty($tooltip)) $tooltip = $task->progress.'% < '.$langs->trans("TimeConsumed").' '.$progressCalculated.'%'; + if (empty($tooltip)) { + $tooltip = $task->progress.'% < '.$langs->trans("TimeConsumed").' '.$progressCalculated.'%'; + } } else { $badgeClass .= 'badge-success'; - if (empty($tooltip)) $tooltip = $task->progress.'% >= '.$langs->trans("TimeConsumed").' '.$progressCalculated.'%'; + if (empty($tooltip)) { + $tooltip = $task->progress.'% >= '.$langs->trans("TimeConsumed").' '.$progressCalculated.'%'; + } } } } diff --git a/htdocs/core/lib/propal.lib.php b/htdocs/core/lib/propal.lib.php index bd3a30151da..3ddd3ab1b2b 100644 --- a/htdocs/core/lib/propal.lib.php +++ b/htdocs/core/lib/propal.lib.php @@ -43,24 +43,28 @@ function propal_prepare_head($object) $h++; if ((empty($conf->commande->enabled) && ((!empty($conf->expedition->enabled) && !empty($conf->expedition_bon->enabled) && $user->rights->expedition->lire) - || (!empty($conf->expedition->enabled) && !empty($conf->delivery_note->enabled) && $user->rights->expedition->delivery->lire)))) - { + || (!empty($conf->expedition->enabled) && !empty($conf->delivery_note->enabled) && $user->rights->expedition->delivery->lire)))) { $langs->load("sendings"); $text = ''; $head[$h][0] = DOL_URL_ROOT.'/expedition/propal.php?id='.$object->id; - if ($conf->expedition_bon->enabled) $text = $langs->trans("Shipment"); - if ($conf->delivery_note->enabled) $text .= '/'.$langs->trans("Receivings"); + if ($conf->expedition_bon->enabled) { + $text = $langs->trans("Shipment"); + } + if ($conf->delivery_note->enabled) { + $text .= '/'.$langs->trans("Receivings"); + } $head[$h][1] = $text; $head[$h][2] = 'shipping'; $h++; } - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/comm/propal/contact.php?id='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -71,14 +75,19 @@ function propal_prepare_head($object) // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'propal'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/comm/propal/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; } @@ -90,7 +99,9 @@ function propal_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/comm/propal/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'document'; $h++; diff --git a/htdocs/core/lib/receiptprinter.lib.php b/htdocs/core/lib/receiptprinter.lib.php index e5589f30707..7bbfbc66387 100644 --- a/htdocs/core/lib/receiptprinter.lib.php +++ b/htdocs/core/lib/receiptprinter.lib.php @@ -47,8 +47,7 @@ function receiptprinteradmin_prepare_head($mode) $head[$h][2] = 'template'; $h++; - if ($mode == 'test') - { + if ($mode == 'test') { $head[$h][0] = DOL_URL_ROOT."/admin/receiptprinter.php?mode=test"; $head[$h][1] = $langs->trans("TargetedPrinter"); $head[$h][2] = 'test'; diff --git a/htdocs/core/lib/reception.lib.php b/htdocs/core/lib/reception.lib.php index f36295e31f3..42355497286 100644 --- a/htdocs/core/lib/reception.lib.php +++ b/htdocs/core/lib/reception.lib.php @@ -47,18 +47,18 @@ function reception_prepare_head(Reception $object) $head[$h][2] = 'reception'; $h++; - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $objectsrc = $object; - if ($object->origin == 'commande' && $object->origin_id > 0) - { + if ($object->origin == 'commande' && $object->origin_id > 0) { $objectsrc = new Commande($db); $objectsrc->fetch($object->origin_id); } $nbContact = count($objectsrc->liste_contact(-1, 'internal')) + count($objectsrc->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT."/reception/contact.php?id=".$object->id; $head[$h][1] = $langs->trans("ContactsAddresses"); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -70,11 +70,17 @@ function reception_prepare_head(Reception $object) complete_head_from_modules($conf, $langs, $object, $head, $h, 'reception'); $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT."/reception/note.php?id=".$object->id; $head[$h][1] = $langs->trans("Notes"); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; @@ -103,16 +109,14 @@ function reception_admin_prepare_head() complete_head_from_modules($conf, $langs, null, $head, $h, 'reception_admin'); - if (!empty($conf->global->MAIN_SUBMODULE_RECEPTION)) - { + if (!empty($conf->global->MAIN_SUBMODULE_RECEPTION)) { $head[$h][0] = DOL_URL_ROOT.'/admin/reception_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFields"); $head[$h][2] = 'attributes_reception'; $h++; } - if (!empty($conf->global->MAIN_SUBMODULE_RECEPTION)) - { + if (!empty($conf->global->MAIN_SUBMODULE_RECEPTION)) { $head[$h][0] = DOL_URL_ROOT.'/admin/commande_fournisseur_dispatch_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFieldsLines"); $head[$h][2] = 'attributeslines_reception'; diff --git a/htdocs/core/lib/report.lib.php b/htdocs/core/lib/report.lib.php index b23acd76a5b..a4279d27a95 100644 --- a/htdocs/core/lib/report.lib.php +++ b/htdocs/core/lib/report.lib.php @@ -44,7 +44,9 @@ function report_header($reportname, $notused, $period, $periodlink, $description print "\n\n\n"; - if (!empty($varlink)) $varlink = '?'.$varlink; + if (!empty($varlink)) { + $varlink = '?'.$varlink; + } $head = array(); @@ -58,8 +60,7 @@ function report_header($reportname, $notused, $period, $periodlink, $description print dol_get_fiche_head($head, 'report'); - foreach ($moreparam as $key => $value) - { + foreach ($moreparam as $key => $value) { print ''."\n"; } @@ -73,17 +74,20 @@ function report_header($reportname, $notused, $period, $periodlink, $description print '
    '; - if ($variante) print ''; + if ($variante) { + print ''; + } print ''."\n"; // Calculation mode - if ($calcmode) - { + if ($calcmode) { print ''; print ''; print ''; + if ($variante) { + print ''; + } print ''; print ''."\n"; } @@ -92,8 +96,12 @@ function report_header($reportname, $notused, $period, $periodlink, $description print ''; print ''; print ''; + if ($period) { + print $period; + } + if ($variante) { + print ''; + } print ''; print ''."\n"; @@ -101,7 +109,9 @@ function report_header($reportname, $notused, $period, $periodlink, $description print ''; print ''; print ''; - if ($variante) print ''; + if ($variante) { + print ''; + } print ''."\n"; // Ligne d'export @@ -110,7 +120,9 @@ function report_header($reportname, $notused, $period, $periodlink, $description print ''; - if ($variante) print ''; + if ($variante) { + print ''; + } print ''."\n"; print '
    '; print $reportname; print '
    '.$langs->trans("CalculationMode").''; print $calcmode; - if ($variante) print '
    '.$langs->trans("ReportPeriod").''; - if ($period) print $period; - if ($variante) print ''.$periodlink.''.$periodlink.'
    '.$langs->trans("ReportDescription").''.$description.'
    '; print dol_print_date($builddate, 'dayhour'); print ''.($exportlink ? $langs->trans("Export").': '.$exportlink : '').''.($exportlink ? $langs->trans("Export").': '.$exportlink : '').'
    '."\n"; diff --git a/htdocs/core/lib/resource.lib.php b/htdocs/core/lib/resource.lib.php index a4ba796078f..29cd8a5b089 100644 --- a/htdocs/core/lib/resource.lib.php +++ b/htdocs/core/lib/resource.lib.php @@ -40,12 +40,13 @@ function resource_prepare_head($object) $head[$h][2] = 'resource'; $h++; - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && (empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_USER) || empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_THIPARTY))) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && (empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_USER) || empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_THIPARTY))) { $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/resource/contact.php?id='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -56,14 +57,19 @@ function resource_prepare_head($object) // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'resource'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/resource/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; } @@ -73,14 +79,15 @@ function resource_prepare_head($object) $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); $head[$h][0] = DOL_URL_ROOT.'/resource/document.php?id='.$object->id; $head[$h][1] = $langs->trans("Documents"); - if ($nbFiles > 0) $head[$h][1] .= ''.$nbFiles.''; + if ($nbFiles > 0) { + $head[$h][1] .= ''.$nbFiles.''; + } $head[$h][2] = 'documents'; $h++; $head[$h][0] = DOL_URL_ROOT.'/resource/agenda.php?id='.$object->id; $head[$h][1] = $langs->trans("Events"); - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $head[$h][1] .= '/'; $head[$h][1] .= $langs->trans("Agenda"); } diff --git a/htdocs/core/lib/salaries.lib.php b/htdocs/core/lib/salaries.lib.php index f4662f43991..57cb9675e3f 100644 --- a/htdocs/core/lib/salaries.lib.php +++ b/htdocs/core/lib/salaries.lib.php @@ -2,6 +2,7 @@ /** * Copyright (C) 2015 Charlie BENKE * Copyright (C) 2019 Alexandre Spangaro + * 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 @@ -33,7 +34,7 @@ function salaries_prepare_head($object) $head = array(); $head[$h][0] = DOL_URL_ROOT.'/salaries/card.php?id='.$object->id; - $head[$h][1] = $langs->trans("SalaryPayment"); + $head[$h][1] = $langs->trans("Salary"); $head[$h][2] = 'card'; $h++; @@ -50,7 +51,9 @@ function salaries_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/salaries/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; diff --git a/htdocs/core/lib/security.lib.php b/htdocs/core/lib/security.lib.php index 381745a5359..66496aa9089 100644 --- a/htdocs/core/lib/security.lib.php +++ b/htdocs/core/lib/security.lib.php @@ -37,21 +37,17 @@ */ function dol_encode($chain, $key = '1') { - if (is_numeric($key) && $key == '1') // rule 1 is offset of 17 for char - { + if (is_numeric($key) && $key == '1') { // rule 1 is offset of 17 for char $output_tab = array(); $strlength = dol_strlen($chain); - for ($i = 0; $i < $strlength; $i++) - { + for ($i = 0; $i < $strlength; $i++) { $output_tab[$i] = chr(ord(substr($chain, $i, 1)) + 17); } $chain = implode("", $output_tab); - } elseif ($key) - { + } elseif ($key) { $result = ''; $strlength = dol_strlen($chain); - for ($i = 0; $i < $strlength; $i++) - { + for ($i = 0; $i < $strlength; $i++) { $keychar = substr($key, ($i % strlen($key)) - 1, 1); $result .= chr(ord(substr($chain, $i, 1)) + (ord($keychar) - 65)); } @@ -74,22 +70,18 @@ function dol_decode($chain, $key = '1') { $chain = base64_decode($chain); - if (is_numeric($key) && $key == '1') // rule 1 is offset of 17 for char - { + if (is_numeric($key) && $key == '1') { // rule 1 is offset of 17 for char $output_tab = array(); $strlength = dol_strlen($chain); - for ($i = 0; $i < $strlength; $i++) - { + for ($i = 0; $i < $strlength; $i++) { $output_tab[$i] = chr(ord(substr($chain, $i, 1)) - 17); } $chain = implode("", $output_tab); - } elseif ($key) - { + } elseif ($key) { $result = ''; $strlength = dol_strlen($chain); - for ($i = 0; $i < $strlength; $i++) - { + for ($i = 0; $i < $strlength; $i++) { $keychar = substr($key, ($i % strlen($key)) - 1, 1); $result .= chr(ord(substr($chain, $i, 1)) - (ord($keychar) - 65)); } @@ -115,21 +107,30 @@ function dol_hash($chain, $type = '0') global $conf; // No need to add salt for password_hash - if (($type == '0' || $type == 'auto') && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash')) - { + if (($type == '0' || $type == 'auto') && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash')) { return password_hash($chain, PASSWORD_DEFAULT); } // Salt value - if (!empty($conf->global->MAIN_SECURITY_SALT) && $type != '4' && $type !== 'md5openldap') $chain = $conf->global->MAIN_SECURITY_SALT.$chain; + if (!empty($conf->global->MAIN_SECURITY_SALT) && $type != '4' && $type !== 'md5openldap') { + $chain = $conf->global->MAIN_SECURITY_SALT.$chain; + } - if ($type == '1' || $type == 'sha1') return sha1($chain); - elseif ($type == '2' || $type == 'sha1md5') return sha1(md5($chain)); - elseif ($type == '3' || $type == 'md5') return md5($chain); - elseif ($type == '4' || $type == 'md5openldap') return '{md5}'.base64_encode(mhash(MHASH_MD5, $chain)); // For OpenLdap with md5 (based on an unencrypted password in base) - elseif ($type == '5') return hash('sha256', $chain); - elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') return sha1($chain); - elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') return sha1(md5($chain)); + if ($type == '1' || $type == 'sha1') { + return sha1($chain); + } elseif ($type == '2' || $type == 'sha1md5') { + return sha1(md5($chain)); + } elseif ($type == '3' || $type == 'md5') { + return md5($chain); + } elseif ($type == '4' || $type == 'md5openldap') { + return '{md5}'.base64_encode(mhash(MHASH_MD5, $chain)); // For OpenLdap with md5 (based on an unencrypted password in base) + } elseif ($type == '5') { + return hash('sha256', $chain); + } elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') { + return sha1($chain); + } elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') { + return sha1(md5($chain)); + } // No particular encoding defined, use default return md5($chain); @@ -151,9 +152,13 @@ function dol_verifyHash($chain, $hash, $type = '0') global $conf; if ($type == '0' && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_verify')) { - if ($hash[0] == '$') return password_verify($chain, $hash); - elseif (strlen($hash) == 32) return dol_verifyHash($chain, $hash, '3'); // md5 - elseif (strlen($hash) == 40) return dol_verifyHash($chain, $hash, '2'); // sha1md5 + if ($hash[0] == '$') { + return password_verify($chain, $hash); + } elseif (strlen($hash) == 32) { + return dol_verifyHash($chain, $hash, '3'); // md5 + } elseif (strlen($hash) == 40) { + return dol_verifyHash($chain, $hash, '2'); // sha1md5 + } return false; } @@ -165,6 +170,7 @@ function dol_verifyHash($chain, $hash, $type = '0') /** * Check permissions of a user to show a page and an object. Check read permission. * If GETPOST('action','aZ09') defined, we also check write and delete permission. + * This method check permission on module then call checkUserAccessToObject() for permission on object (according to entity and socid of user). * * @param User $user User to check * @param string $features Features to check (it must be module $object->element. Examples: 'societe', 'contact', 'produit&service', 'produit|service', ...) @@ -175,83 +181,147 @@ function dol_verifyHash($chain, $hash, $type = '0') * @param string $dbt_select Field name for select if not rowid. Not used if objectid is null (optional) * @param int $isdraft 1=The object with id=$objectid is a draft * @return int Always 1, die process if not allowed - * @see dol_check_secure_access_document() + * @see dol_check_secure_access_document(), checkUserAccessToObject() */ function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid', $isdraft = 0) { global $db, $conf; global $hookmanager; - //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename,$feature2,$dbt_socfield,$dbt_select"); + //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft"); //print "user_id=".$user->id.", features=".$features.", feature2=".$feature2.", objectid=".$objectid; //print ", dbtablename=".$dbtablename.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select; //print ", perm: ".$features."->".$feature2."=".($user->rights->$features->$feature2->lire)."
    "; $parentfortableentity = ''; - if ($features == 'facturerec') $features = 'facture'; - if ($features == 'mo') $features = 'mrp'; - if ($features == 'member') $features = 'adherent'; - if ($features == 'subscription') { $features = 'adherent'; $feature2 = 'cotisation'; }; - if ($features == 'websitepage') { $features = 'website'; $tableandshare = 'website_page'; $parentfortableentity = 'fk_website@website'; } - if ($features == 'project') $features = 'projet'; - if ($features == 'product') $features = 'produit'; + // Fix syntax of $features param + $originalfeatures = $features; + if ($features == 'facturerec') { + $features = 'facture'; + } + if ($features == 'mo') { + $features = 'mrp'; + } + if ($features == 'member') { + $features = 'adherent'; + } + if ($features == 'subscription') { + $features = 'adherent'; + $feature2 = 'cotisation'; + }; + if ($features == 'websitepage') { + $features = 'website'; + $tableandshare = 'website_page'; + $parentfortableentity = 'fk_website@website'; + } + if ($features == 'project') { + $features = 'projet'; + } + if ($features == 'product') { + $features = 'produit'; + } // Get more permissions checks from hooks - $parameters = array('features'=>$features, 'objectid'=>$objectid, 'idtype'=>$dbt_select); + $parameters = array('features'=>$features, 'originalfeatures'=>$originalfeatures, 'objectid'=>$objectid, 'dbt_select'=>$dbt_select, 'idtype'=>$dbt_select, 'isdraft'=>$isdraft); $reshook = $hookmanager->executeHooks('restrictedArea', $parameters); if (isset($hookmanager->resArray['result'])) { - if ($hookmanager->resArray['result'] == 0) accessforbidden(); // Module returns 0, so access forbidden + if ($hookmanager->resArray['result'] == 0) { + accessforbidden(); // Module returns 0, so access forbidden + } } if ($reshook > 0) { // No other test done. return 1; } - if ($dbt_select != 'rowid' && $dbt_select != 'id') $objectid = "'".$objectid."'"; + if ($dbt_select != 'rowid' && $dbt_select != 'id') { + $objectid = "'".$objectid."'"; + } // Features/modules to check $featuresarray = array($features); - if (preg_match('/&/', $features)) $featuresarray = explode("&", $features); - elseif (preg_match('/\|/', $features)) $featuresarray = explode("|", $features); + if (preg_match('/&/', $features)) { + $featuresarray = explode("&", $features); + } elseif (preg_match('/\|/', $features)) { + $featuresarray = explode("|", $features); + } // More subfeatures to check - if (!empty($feature2)) $feature2 = explode("|", $feature2); - - // More parameters - $params = explode('&', $tableandshare); - $dbtablename = (!empty($params[0]) ? $params[0] : ''); - $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); + if (!empty($feature2)) { + $feature2 = explode("|", $feature2); + } $listofmodules = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); // Check read permission from module - $readok = 1; $nbko = 0; + $readok = 1; + $nbko = 0; foreach ($featuresarray as $feature) { // first we check nb of test ko $featureforlistofmodule = $feature; - if ($featureforlistofmodule == 'produit') $featureforlistofmodule = 'product'; + if ($featureforlistofmodule == 'produit') { + $featureforlistofmodule = 'product'; + } if (!empty($user->socid) && !empty($conf->global->MAIN_MODULES_FOR_EXTERNAL) && !in_array($featureforlistofmodule, $listofmodules)) { // If limits on modules for external users, module must be into list of modules for external users - $readok = 0; $nbko++; + $readok = 0; + $nbko++; continue; } if ($feature == 'societe') { - if (!$user->rights->societe->lire && !$user->rights->fournisseur->lire) { $readok = 0; $nbko++; } + if (!$user->rights->societe->lire && !$user->rights->fournisseur->lire) { + $readok = 0; + $nbko++; + } } elseif ($feature == 'contact') { - if (!$user->rights->societe->contact->lire) { $readok = 0; $nbko++; } + if (!$user->rights->societe->contact->lire) { + $readok = 0; + $nbko++; + } } elseif ($feature == 'produit|service') { - if (!$user->rights->produit->lire && !$user->rights->service->lire) { $readok = 0; $nbko++; } + if (!$user->rights->produit->lire && !$user->rights->service->lire) { + $readok = 0; + $nbko++; + } } elseif ($feature == 'prelevement') { - if (!$user->rights->prelevement->bons->lire) { $readok = 0; $nbko++; } + if (!$user->rights->prelevement->bons->lire) { + $readok = 0; + $nbko++; + } } elseif ($feature == 'cheque') { - if (!$user->rights->banque->cheque) { $readok = 0; $nbko++; } + if (!$user->rights->banque->cheque) { + $readok = 0; + $nbko++; + } } elseif ($feature == 'projet') { - if (!$user->rights->projet->lire && !$user->rights->projet->all->lire) { $readok = 0; $nbko++; } + if (!$user->rights->projet->lire && !$user->rights->projet->all->lire) { + $readok = 0; + $nbko++; + } + } elseif ($feature == 'payment') { + if (!$user->rights->facture->lire) { + $readok = 0; + $nbko++; + } + } elseif ($feature == 'payment_supplier') { + if (!$user->rights->fournisseur->facture->lire) { + $readok = 0; + $nbko++; + } } elseif (!empty($feature2)) { // This is for permissions on 2 levels $tmpreadok = 1; foreach ($feature2 as $subfeature) { - if ($subfeature == 'user' && $user->id == $objectid) continue; // A user can always read its own card - if (!empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) { $tmpreadok = 0; } elseif (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) { $tmpreadok = 0; } else { $tmpreadok = 1; break; } // Break is to bypass second test if the first is ok + if ($subfeature == 'user' && $user->id == $objectid) { + continue; // A user can always read its own card + } + if (!empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) { + $tmpreadok = 0; + } elseif (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) { + $tmpreadok = 0; + } else { + $tmpreadok = 1; + break; + } // Break is to bypass second test if the first is ok } if (!$tmpreadok) { // We found a test on feature that is ko $readok = 0; // All tests are ko (we manage here the and, the or will be managed later using $nbko). @@ -260,45 +330,79 @@ function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $f } elseif (!empty($feature) && ($feature != 'user' && $feature != 'usergroup')) { // This is permissions on 1 level if (empty($user->rights->$feature->lire) && empty($user->rights->$feature->read) - && empty($user->rights->$feature->run)) { $readok = 0; $nbko++; } + && empty($user->rights->$feature->run)) { + $readok = 0; + $nbko++; + } } } // If a or and at least one ok - if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $readok = 1; + if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) { + $readok = 1; + } - if (!$readok) accessforbidden(); + if (!$readok) { + accessforbidden(); + } //print "Read access is ok"; // Check write permission from module (we need to know write permission to create but also to delete drafts record or to upload files) - $createok = 1; $nbko = 0; + $createok = 1; + $nbko = 0; $wemustcheckpermissionforcreate = (GETPOST('sendit', 'alpha') || GETPOST('linkit', 'alpha') || GETPOST('action', 'aZ09') == 'create' || GETPOST('action', 'aZ09') == 'update'); $wemustcheckpermissionfordeletedraft = ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete'); - if ($wemustcheckpermissionforcreate || $wemustcheckpermissionfordeletedraft) - { - foreach ($featuresarray as $feature) - { + if ($wemustcheckpermissionforcreate || $wemustcheckpermissionfordeletedraft) { + foreach ($featuresarray as $feature) { if ($feature == 'contact') { - if (!$user->rights->societe->contact->creer) { $createok = 0; $nbko++; } + if (!$user->rights->societe->contact->creer) { + $createok = 0; + $nbko++; + } } elseif ($feature == 'produit|service') { - if (!$user->rights->produit->creer && !$user->rights->service->creer) { $createok = 0; $nbko++; } + if (!$user->rights->produit->creer && !$user->rights->service->creer) { + $createok = 0; + $nbko++; + } } elseif ($feature == 'prelevement') { - if (!$user->rights->prelevement->bons->creer) { $createok = 0; $nbko++; } + if (!$user->rights->prelevement->bons->creer) { + $createok = 0; + $nbko++; + } } elseif ($feature == 'commande_fournisseur') { - if (!$user->rights->fournisseur->commande->creer) { $createok = 0; $nbko++; } + if (!$user->rights->fournisseur->commande->creer) { + $createok = 0; + $nbko++; + } } elseif ($feature == 'banque') { - if (!$user->rights->banque->modifier) { $createok = 0; $nbko++; } + if (!$user->rights->banque->modifier) { + $createok = 0; + $nbko++; + } } elseif ($feature == 'cheque') { - if (!$user->rights->banque->cheque) { $createok = 0; $nbko++; } + if (!$user->rights->banque->cheque) { + $createok = 0; + $nbko++; + } } elseif ($feature == 'import') { - if (!$user->rights->import->run) { $createok = 0; $nbko++; } + if (!$user->rights->import->run) { + $createok = 0; + $nbko++; + } } elseif ($feature == 'ecm') { - if (!$user->rights->ecm->upload) { $createok = 0; $nbko++; } + if (!$user->rights->ecm->upload) { + $createok = 0; + $nbko++; + } } elseif (!empty($feature2)) { // This is for permissions on one level foreach ($feature2 as $subfeature) { - if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->creer) continue; // User can edit its own card - if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->password) continue; // User can edit its own password + if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->creer) { + continue; // User can edit its own card + } + if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->password) { + continue; // User can edit its own password + } if (empty($user->rights->$feature->$subfeature->creer) && empty($user->rights->$feature->$subfeature->write) @@ -323,82 +427,103 @@ function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $f } // If a or and at least one ok - if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $createok = 1; + if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) { + $createok = 1; + } - if ($wemustcheckpermissionforcreate && !$createok) accessforbidden(); + if ($wemustcheckpermissionforcreate && !$createok) { + accessforbidden(); + } //print "Write access is ok"; } // Check create user permission $createuserok = 1; - if (GETPOST('action', 'aZ09') == 'confirm_create_user' && GETPOST("confirm", 'aZ09') == 'yes') - { - if (!$user->rights->user->user->creer) $createuserok = 0; + if (GETPOST('action', 'aZ09') == 'confirm_create_user' && GETPOST("confirm", 'aZ09') == 'yes') { + if (!$user->rights->user->user->creer) { + $createuserok = 0; + } - if (!$createuserok) accessforbidden(); + if (!$createuserok) { + accessforbidden(); + } //print "Create user access is ok"; } // Check delete permission from module - $deleteok = 1; $nbko = 0; - if ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete') - { - foreach ($featuresarray as $feature) - { - if ($feature == 'contact') - { - if (!$user->rights->societe->contact->supprimer) $deleteok = 0; - } elseif ($feature == 'produit|service') - { - if (!$user->rights->produit->supprimer && !$user->rights->service->supprimer) $deleteok = 0; - } elseif ($feature == 'commande_fournisseur') - { - if (!$user->rights->fournisseur->commande->supprimer) $deleteok = 0; - } elseif ($feature == 'banque') - { - if (!$user->rights->banque->modifier) $deleteok = 0; - } elseif ($feature == 'cheque') - { - if (!$user->rights->banque->cheque) $deleteok = 0; - } elseif ($feature == 'ecm') - { - if (!$user->rights->ecm->upload) $deleteok = 0; - } elseif ($feature == 'ftp') - { - if (!$user->rights->ftp->write) $deleteok = 0; - } elseif ($feature == 'salaries') - { - if (!$user->rights->salaries->delete) $deleteok = 0; - } elseif ($feature == 'salaries') - { - if (!$user->rights->salaries->delete) $deleteok = 0; - } elseif (!empty($feature2)) // This is for permissions on 2 levels - { - foreach ($feature2 as $subfeature) - { - if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) $deleteok = 0; - else { $deleteok = 1; break; } // For bypass the second test if the first is ok + $deleteok = 1; + $nbko = 0; + if ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete') { + foreach ($featuresarray as $feature) { + if ($feature == 'contact') { + if (!$user->rights->societe->contact->supprimer) { + $deleteok = 0; } - } elseif (!empty($feature)) // This is used for permissions on 1 level - { + } elseif ($feature == 'produit|service') { + if (!$user->rights->produit->supprimer && !$user->rights->service->supprimer) { + $deleteok = 0; + } + } elseif ($feature == 'commande_fournisseur') { + if (!$user->rights->fournisseur->commande->supprimer) { + $deleteok = 0; + } + } elseif ($feature == 'banque') { + if (!$user->rights->banque->modifier) { + $deleteok = 0; + } + } elseif ($feature == 'cheque') { + if (!$user->rights->banque->cheque) { + $deleteok = 0; + } + } elseif ($feature == 'ecm') { + if (!$user->rights->ecm->upload) { + $deleteok = 0; + } + } elseif ($feature == 'ftp') { + if (!$user->rights->ftp->write) { + $deleteok = 0; + } + } elseif ($feature == 'salaries') { + if (!$user->rights->salaries->delete) { + $deleteok = 0; + } + } elseif ($feature == 'salaries') { + if (!$user->rights->salaries->delete) { + $deleteok = 0; + } + } elseif (!empty($feature2)) { // This is for permissions on 2 levels + foreach ($feature2 as $subfeature) { + if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) { + $deleteok = 0; + } else { + $deleteok = 1; + break; + } // For bypass the second test if the first is ok + } + } elseif (!empty($feature)) { // This is used for permissions on 1 level //print '
    feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete; if (empty($user->rights->$feature->supprimer) && empty($user->rights->$feature->delete) - && empty($user->rights->$feature->run)) $deleteok = 0; + && empty($user->rights->$feature->run)) { + $deleteok = 0; + } } } // If a or and at least one ok - if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $deleteok = 1; + if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) { + $deleteok = 1; + } - if (!$deleteok && !($isdraft && $createok)) accessforbidden(); + if (!$deleteok && !($isdraft && $createok)) { + accessforbidden(); + } //print "Delete access is ok"; } // If we have a particular object to check permissions on, we check this object // is linked to a company allowed to $user. - if (!empty($objectid) && $objectid > 0) - { + if (!empty($objectid) && $objectid > 0) { $ok = checkUserAccessToObject($user, $featuresarray, $objectid, $tableandshare, $feature2, $dbt_keyfield, $dbt_select, $parentfortableentity); $params = array('objectid' => $objectid, 'features' => join(',', $featuresarray), 'features2' => $feature2); return $ok ? 1 : accessforbidden('', 1, 1, 0, $params); @@ -426,46 +551,50 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand { global $db, $conf; + //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft"); + //print "user_id=".$user->id.", features=".join(',', $featuresarray).", feature2=".$feature2.", objectid=".$objectid; + //print ", tableandshare=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select."
    "; + // More parameters $params = explode('&', $tableandshare); $dbtablename = (!empty($params[0]) ? $params[0] : ''); $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); - foreach ($featuresarray as $feature) - { + foreach ($featuresarray as $feature) { $sql = ''; // For backward compatibility - if ($feature == 'member') $feature = 'adherent'; - if ($feature == 'project') $feature = 'projet'; - if ($feature == 'task') $feature = 'projet_task'; + if ($feature == 'member') { + $feature = 'adherent'; + } + if ($feature == 'project') { + $feature = 'projet'; + } + if ($feature == 'task') { + $feature = 'projet_task'; + } - $check = array('adherent', 'banque', 'bom', 'don', 'mrp', 'user', 'usergroup', 'product', 'produit', 'service', 'produit|service', 'categorie', 'resource', 'expensereport', 'holiday', 'website'); // Test on entity only (Objects with no link to company) + $check = array('adherent', 'banque', 'bom', 'don', 'mrp', 'user', 'usergroup', 'payment', 'payment_supplier', 'product', 'produit', 'service', 'produit|service', 'categorie', 'resource', 'expensereport', 'holiday', 'website'); // Test on entity only (Objects with no link to company) $checksoc = array('societe'); // Test for societe object - $checkother = array('contact', 'agenda'); // Test on entity and link to third party. Allowed if link is empty (Ex: contacts...). + $checkother = array('contact', 'agenda'); // Test on entity + link to third party on field $dbt_keyfield. Allowed if link is empty (Ex: contacts...). $checkproject = array('projet', 'project'); // Test for project object $checktask = array('projet_task'); // Test for task object $nocheck = array('barcode', 'stock'); // No test - //$checkdefault = 'all other not already defined'; // Test on entity and link to third party. Not allowed if link is empty (Ex: invoice, orders...). + //$checkdefault = 'all other not already defined'; // Test on entity + link to third party on field $dbt_keyfield. Not allowed if link is empty (Ex: invoice, orders...). // If dbtablename not defined, we use same name for table than module name - if (empty($dbtablename)) - { + if (empty($dbtablename)) { $dbtablename = $feature; $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too. } - // Check permission for object with entity - if (in_array($feature, $check)) - { + // Check permission for object on entity only + if (in_array($feature, $check)) { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; - if (($feature == 'user' || $feature == 'usergroup') && !empty($conf->multicompany->enabled)) - { - if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - if ($conf->entity == 1 && $user->admin && !$user->entity) - { + if (($feature == 'user' || $feature == 'usergroup') && !empty($conf->multicompany->enabled)) { // Special for multicompany + if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + if ($conf->entity == 1 && $user->admin && !$user->entity) { $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND dbt.entity IS NOT NULL"; } else { @@ -490,15 +619,14 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; } } - } elseif (in_array($feature, $checksoc)) // We check feature = checksoc - { + } elseif (in_array($feature, $checksoc)) { // We check feature = checksoc // If external user: Check permission for external users - if ($user->socid > 0) - { - if ($user->socid <> $objectid) return false; - } // If internal user: Check permission for internal users that are restricted on their objects - elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) - { + if ($user->socid > 0 && empty($conf->global->MAIN_EXTERNAL_USERS_CAN_SEE_SUBSIDIARY_COMPANIES)) { + if ($user->socid <> $objectid) { + return false; + } + } elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) { + // If internal user: Check permission for internal users that are restricted on their objects $sql = "SELECT COUNT(sc.fk_soc) as nb"; $sql .= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= ", ".MAIN_DB_PREFIX."societe as s)"; @@ -506,42 +634,37 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand $sql .= " AND sc.fk_user = ".$user->id; $sql .= " AND sc.fk_soc = s.rowid"; $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")"; - } // If multicompany and internal users with all permissions, check user is in correct entity - elseif (!empty($conf->multicompany->enabled)) - { + } elseif (!empty($conf->multicompany->enabled)) { + // If multicompany and internal users with all permissions, check user is in correct entity $sql = "SELECT COUNT(s.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " WHERE s.rowid IN (".$objectid.")"; $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")"; } - } elseif (in_array($feature, $checkother)) // Test on entity and link to societe. Allowed if link is empty (Ex: contacts...). - { + } elseif (in_array($feature, $checkother)) { // Test on entity + link to thirdparty. Allowed if link is empty (Ex: contacts...). // If external user: Check permission for external users - if ($user->socid > 0) - { + if ($user->socid > 0) { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND dbt.fk_soc = ".$user->socid; - } // If internal user: Check permission for internal users that are restricted on their objects - elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) - { + } elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) { + // If internal user: Check permission for internal users that are restricted on their objects $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id); $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND (dbt.fk_soc IS NULL OR sc.fk_soc IS NOT NULL)"; // Contact not linked to a company or to a company of user $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; - } // If multicompany and internal users with all permissions, check user is in correct entity - elseif (!empty($conf->multicompany->enabled)) - { + } elseif (!empty($conf->multicompany->enabled)) { + // If multicompany and internal users with all permissions, check user is in correct entity $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; } - if ($feature == 'agenda')// Also check owner or attendee for users without allactions->read - { + if ($feature == 'agenda') { + // Also check owner or attendee for users without allactions->read if ($objectid > 0 && empty($user->rights->agenda->allactions->read)) { require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; $action = new ActionComm($db); @@ -552,13 +675,14 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand } } } elseif (in_array($feature, $checkproject)) { - if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) - { + if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) { include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $projectstatic = new Project($db); $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0); $tmparray = explode(',', $tmps); - if (!in_array($objectid, $tmparray)) return false; + if (!in_array($objectid, $tmparray)) { + return false; + } } else { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; @@ -566,8 +690,7 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; } } elseif (in_array($feature, $checktask)) { - if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) - { + if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) { $task = new Task($db); $task->fetch($objectid); @@ -575,7 +698,9 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand $projectstatic = new Project($db); $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0); $tmparray = explode(',', $tmps); - if (!in_array($task->fk_project, $tmparray)) return false; + if (!in_array($task->fk_project, $tmparray)) { + return false; + } } else { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; @@ -584,17 +709,20 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand } } elseif (!in_array($feature, $nocheck)) { // By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield // If external user: Check permission for external users - if ($user->socid > 0 && empty($conf->global->MAIN_EXTERNAL_USERS_CAN_SEE_SUBSIDIARY_COMPANIES)) - { - if (empty($dbt_keyfield)) dol_print_error('', 'Param dbt_keyfield is required but not defined'); + if ($user->socid > 0 && empty($conf->global->MAIN_EXTERNAL_USERS_CAN_SEE_SUBSIDIARY_COMPANIES)) { + if (empty($dbt_keyfield)) { + dol_print_error('', 'Param dbt_keyfield is required but not defined'); + } $sql = "SELECT COUNT(dbt.".$dbt_keyfield.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " WHERE dbt.rowid IN (".$objectid.")"; $sql .= " AND dbt.".$dbt_keyfield." = ".$user->socid; - } elseif (!empty($conf->societe->enabled)) { + } elseif (!empty($conf->societe->enabled) && !$user->rights->societe->client->voir) { // If internal user: Check permission for internal users that are restricted on their objects - if ($feature != 'ticket' && !$user->rights->societe->client->voir) { - if (empty($dbt_keyfield)) dol_print_error('', 'Param dbt_keyfield is required but not defined'); + if ($feature != 'ticket') { + if (empty($dbt_keyfield)) { + dol_print_error('', 'Param dbt_keyfield is required but not defined'); + } $sql = "SELECT COUNT(sc.fk_soc) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -602,9 +730,8 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; $sql .= " AND sc.fk_soc = dbt.".$dbt_keyfield; $sql .= " AND sc.fk_user = ".$user->id; - } - // On ticket, the thirdparty is not mandatory, so we need a special test to accept record with no thirdparties. - if ($feature == 'ticket' && !$user->rights->societe->client->voir) { + } else { + // On ticket, the thirdparty is not mandatory, so we need a special test to accept record with no thirdparties. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = dbt.".$dbt_keyfield." AND sc.fk_user = ".$user->id; @@ -612,9 +739,8 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; $sql .= " AND (sc.fk_user = ".$user->id." OR sc.fk_user IS NULL)"; } - } // If multicompany and internal users with all permissions, check user is in correct entity - elseif (!empty($conf->multicompany->enabled)) - { + } elseif (!empty($conf->multicompany->enabled)) { + // If multicompany and internal users with all permissions, check user is in correct entity $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; @@ -622,13 +748,13 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand } } - if ($sql) - { + if ($sql) { $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if (!$obj || $obj->nb < count(explode(',', $objectid))) return false; + if (!$obj || $obj->nb < count(explode(',', $objectid))) { + return false; + } } else { return false; } @@ -652,8 +778,7 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null) { global $conf, $db, $user, $langs, $hookmanager; - if (!is_object($langs)) - { + if (!is_object($langs)) { include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; $langs = new Translate('', $conf); $langs->setDefaultLang(); @@ -661,21 +786,24 @@ function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $sho $langs->load("errors"); - if ($printheader) - { - if (function_exists("llxHeader")) llxHeader(''); - elseif (function_exists("llxHeaderVierge")) llxHeaderVierge(''); + if ($printheader) { + if (function_exists("llxHeader")) { + llxHeader(''); + } elseif (function_exists("llxHeaderVierge")) { + llxHeaderVierge(''); + } } print '
    '; - if (!$message) print $langs->trans("ErrorForbidden"); - else print $message; + if (!$message) { + print $langs->trans("ErrorForbidden"); + } else { + print $message; + } print '
    '; print '
    '; - if (empty($showonlymessage)) - { + if (empty($showonlymessage)) { global $action, $object; - if (empty($hookmanager)) - { + if (empty($hookmanager)) { $hookmanager = new HookManager($db); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('main')); @@ -683,10 +811,8 @@ function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $sho $parameters = array('message'=>$message, 'params'=>$params); $reshook = $hookmanager->executeHooks('getAccessForbiddenMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks print $hookmanager->resPrint; - if (empty($reshook)) - { - if ($user->login) - { + if (empty($reshook)) { + if ($user->login) { print $langs->trans("CurrentLogin").': '.$user->login.'
    '; print $langs->trans("ErrorForbidden2", $langs->transnoentitiesnoconv("Home"), $langs->transnoentitiesnoconv("Users")); } else { @@ -694,6 +820,8 @@ function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $sho } } } - if ($printfooter && function_exists("llxFooter")) llxFooter(); + if ($printfooter && function_exists("llxFooter")) { + llxFooter(); + } exit(0); } diff --git a/htdocs/core/lib/security2.lib.php b/htdocs/core/lib/security2.lib.php index 3527d132cde..523b8ccf2cb 100644 --- a/htdocs/core/lib/security2.lib.php +++ b/htdocs/core/lib/security2.lib.php @@ -35,8 +35,12 @@ function dol_getwebuser($mode) { $t = '?'; - if ($mode == 'user') $t = getenv('APACHE_RUN_USER'); // $_ENV['APACHE_RUN_USER'] is empty - if ($mode == 'group') $t = getenv('APACHE_RUN_GROUP'); + if ($mode == 'user') { + $t = getenv('APACHE_RUN_USER'); // $_ENV['APACHE_RUN_USER'] is empty + } + if ($mode == 'group') { + $t = getenv('APACHE_RUN_GROUP'); + } return $t; } @@ -56,44 +60,44 @@ function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $auth //global $dolauthmode; // To return authentication finally used // Check parameters - if ($entitytotest == '') $entitytotest = 1; + if ($entitytotest == '') { + $entitytotest = 1; + } dol_syslog("checkLoginPassEntity usertotest=".$usertotest." entitytotest=".$entitytotest." authmode=".join(',', $authmode)); $login = ''; // Validation of login/pass/entity with standard modules - if (empty($login)) - { + if (empty($login)) { $test = true; - foreach ($authmode as $mode) - { - if ($test && $mode && !$login) - { + foreach ($authmode as $mode) { + if ($test && $mode && !$login) { // Validation of login/pass/entity for mode $mode $mode = trim($mode); $authfile = 'functions_'.$mode.'.php'; $fullauthfile = ''; $dirlogin = array_merge(array("/core/login"), (array) $conf->modules_parts['login']); - foreach ($dirlogin as $reldir) - { + foreach ($dirlogin as $reldir) { $dir = dol_buildpath($reldir, 0); $newdir = dol_osencode($dir); // Check if file found (do not use dol_is_file to avoid loading files.lib.php) $tmpnewauthfile = $newdir.(preg_match('/\/$/', $newdir) ? '' : '/').$authfile; - if (is_file($tmpnewauthfile)) $fullauthfile = $tmpnewauthfile; + if (is_file($tmpnewauthfile)) { + $fullauthfile = $tmpnewauthfile; + } } $result = false; - if ($fullauthfile) $result = include_once $fullauthfile; - if ($fullauthfile && $result) - { + if ($fullauthfile) { + $result = include_once $fullauthfile; + } + if ($fullauthfile && $result) { // Call function to check user/password $function = 'check_user_password_'.$mode; $login = call_user_func($function, $usertotest, $passwordtotest, $entitytotest, $context); - if ($login && $login != '--bad-login-validity--') // Login is successfull - { + if ($login && $login != '--bad-login-validity--') { // Login is successfull $test = false; // To stop once at first login success $conf->authmode = $mode; // This properties is defined only when logged to say what mode was successfully used $dol_tz = GETPOST('tz'); @@ -117,8 +121,7 @@ function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $auth } -if (!function_exists('dol_loginfunction')) -{ +if (!function_exists('dol_loginfunction')) { /** * Show Dolibarr default login page. * Part of this code is also duplicated into main.inc.php::top_htmlhead @@ -147,7 +150,9 @@ if (!function_exists('dol_loginfunction')) // Title $appli = constant('DOL_APPLICATION_TITLE'); $title = $appli.' '.constant('DOL_VERSION'); - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $title = $conf->global->MAIN_APPLICATION_TITLE; + } $titletruedolibarrversion = constant('DOL_VERSION'); // $title used by login template after the @ to inform of true Dolibarr version // Note: $conf->css looks like '/theme/eldy/style.css.php' @@ -169,13 +174,14 @@ if (!function_exists('dol_loginfunction')) */ // Select templates dir - if (!empty($conf->modules_parts['tpl'])) // Using this feature slow down application - { + if (!empty($conf->modules_parts['tpl'])) { // Using this feature slow down application $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl/')); - foreach ($dirtpls as $reldir) - { + foreach ($dirtpls as $reldir) { $tmp = dol_buildpath($reldir.'login.tpl.php'); - if (file_exists($tmp)) { $template_dir = preg_replace('/login\.tpl\.php$/', '', $tmp); break; } + if (file_exists($tmp)) { + $template_dir = preg_replace('/login\.tpl\.php$/', '', $tmp); + break; + } } } else { $template_dir = DOL_DOCUMENT_ROOT."/core/tpl/"; @@ -184,18 +190,25 @@ if (!function_exists('dol_loginfunction')) // Set cookie for timeout management $prefix = dol_getprefix(''); $sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix; - if (!empty($conf->global->MAIN_SESSION_TIMEOUT)) setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", null, (empty($dolibarr_main_force_https) ? false : true), true); + if (!empty($conf->global->MAIN_SESSION_TIMEOUT)) { + setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", null, (empty($dolibarr_main_force_https) ? false : true), true); + } - if (GETPOST('urlfrom', 'alpha')) $_SESSION["urlfrom"] = GETPOST('urlfrom', 'alpha'); - else unset($_SESSION["urlfrom"]); + if (GETPOST('urlfrom', 'alpha')) { + $_SESSION["urlfrom"] = GETPOST('urlfrom', 'alpha'); + } else { + unset($_SESSION["urlfrom"]); + } - if (!GETPOST("username", 'alpha')) $focus_element = 'username'; - else $focus_element = 'password'; + if (!GETPOST("username", 'alpha')) { + $focus_element = 'username'; + } else { + $focus_element = 'password'; + } $demologin = ''; $demopassword = ''; - if (!empty($dolibarr_main_demo)) - { + if (!empty($dolibarr_main_demo)) { $tab = explode(',', $dolibarr_main_demo); $demologin = $tab[0]; $demopassword = $tab[1]; @@ -233,8 +246,7 @@ if (!function_exists('dol_loginfunction')) // Security graphical code $captcha = 0; $captcha_refresh = ''; - if (function_exists("imagecreatefrompng") && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA)) - { + if (function_exists("imagecreatefrompng") && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA)) { $captcha = 1; $captcha_refresh = img_picto($langs->trans("Refresh"), 'refresh', 'id="captcha_refresh_img"'); } @@ -242,23 +254,19 @@ if (!function_exists('dol_loginfunction')) // Extra link $forgetpasslink = 0; $helpcenterlink = 0; - if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK) || empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) - { - if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK)) - { + if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK) || empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) { + if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK)) { $forgetpasslink = 1; } - if (empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) - { + if (empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) { $helpcenterlink = 1; } } // Home message $main_home = ''; - if (!empty($conf->global->MAIN_HOME)) - { + if (!empty($conf->global->MAIN_HOME)) { $substitutionarray = getCommonSubstitutionArray($langs); complete_substitutions_array($substitutionarray, $langs); $texttoshow = make_substitutions($conf->global->MAIN_HOME, $substitutionarray, $langs); @@ -273,11 +281,17 @@ if (!function_exists('dol_loginfunction')) $dol_loginmesg = (!empty($_SESSION["dol_loginmesg"]) ? $_SESSION["dol_loginmesg"] : ''); $favicon = DOL_URL_ROOT.'/theme/dolibarr_256x256_color.png'; - if (!empty($mysoc->logo_squarred_mini)) $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini); - if (!empty($conf->global->MAIN_FAVICON_URL)) $favicon = $conf->global->MAIN_FAVICON_URL; + if (!empty($mysoc->logo_squarred_mini)) { + $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini); + } + if (!empty($conf->global->MAIN_FAVICON_URL)) { + $favicon = $conf->global->MAIN_FAVICON_URL; + } $jquerytheme = 'base'; - if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME; + if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) { + $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME; + } // Set dol_hide_topmenu, dol_hide_leftmenu, dol_optimize_smallscreen, dol_no_mouse_hover $dol_hide_topmenu = GETPOST('dol_hide_topmenu', 'int'); @@ -307,18 +321,28 @@ if (!function_exists('dol_loginfunction')) function makesalt($type = CRYPT_SALT_LENGTH) { dol_syslog("makesalt type=".$type); - switch ($type) - { + switch ($type) { case 12: // 8 + 4 - $saltlen = 8; $saltprefix = '$1$'; $saltsuffix = '$'; break; + $saltlen = 8; + $saltprefix = '$1$'; + $saltsuffix = '$'; + break; case 8: // 8 (Pour compatibilite, ne devrait pas etre utilise) - $saltlen = 8; $saltprefix = '$1$'; $saltsuffix = '$'; break; + $saltlen = 8; + $saltprefix = '$1$'; + $saltsuffix = '$'; + break; case 2: // 2 default: // by default, fall back on Standard DES (should work everywhere) - $saltlen = 2; $saltprefix = ''; $saltsuffix = ''; break; + $saltlen = 2; + $saltprefix = ''; + $saltsuffix = ''; + break; } $salt = ''; - while (dol_strlen($salt) < $saltlen) $salt .= chr(mt_rand(64, 126)); + while (dol_strlen($salt) < $saltlen) { + $salt .= chr(mt_rand(64, 126)); + } $result = $saltprefix.$salt.$saltsuffix; dol_syslog("makesalt return=".$result); @@ -338,33 +362,27 @@ function encodedecode_dbpassconf($level = 0) $passwd = ''; $passwd_crypted = ''; - if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php', 'r')) - { - while (!feof($fp)) - { + if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php', 'r')) { + while (!feof($fp)) { $buffer = fgets($fp, 4096); $lineofpass = 0; - if (preg_match('/^[^#]*dolibarr_main_db_encrypted_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) // Old way to save crypted value - { + if (preg_match('/^[^#]*dolibarr_main_db_encrypted_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) { // Old way to save crypted value $val = trim($reg[1]); // This also remove CR/LF $val = preg_replace('/^["\']/', '', $val); $val = preg_replace('/["\'][\s;]*$/', '', $val); - if (!empty($val)) - { + if (!empty($val)) { $passwd_crypted = $val; $val = dol_decode($val); $passwd = $val; $lineofpass = 1; } - } elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) - { + } elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) { $val = trim($reg[1]); // This also remove CR/LF $val = preg_replace('/^["\']/', '', $val); $val = preg_replace('/["\'][\s;]*$/', '', $val); - if (preg_match('/crypted:/i', $buffer)) - { + if (preg_match('/crypted:/i', $buffer)) { $val = preg_replace('/crypted:/i', '', $val); $passwd_crypted = $val; $val = dol_decode($val); @@ -378,15 +396,12 @@ function encodedecode_dbpassconf($level = 0) } // Output line - if ($lineofpass) - { + if ($lineofpass) { // Add value at end of file - if ($level == 0) - { + if ($level == 0) { $config .= '$dolibarr_main_db_pass=\''.$passwd.'\';'."\n"; } - if ($level == 1) - { + if ($level == 1) { $config .= '$dolibarr_main_db_pass=\'crypted:'.$passwd_crypted.'\';'."\n"; } @@ -400,8 +415,7 @@ function encodedecode_dbpassconf($level = 0) // Write new conf file $file = DOL_DOCUMENT_ROOT.'/conf/conf.php'; - if ($fp = @fopen($file, 'w')) - { + if ($fp = @fopen($file, 'w')) { fputs($fp, $config); fflush($fp); fclose($fp); @@ -436,8 +450,7 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len global $db, $conf, $langs, $user; $generated_password = ''; - if ($generic) - { + if ($generic) { $lowercase = "qwertyuiopasdfghjklzxcvbnm"; $uppercase = "ASDFGHJKLZXCVBNMQWERTYUIOP"; $numbers = "1234567890"; @@ -445,8 +458,7 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len $nbofchar = round($length / 3); $nbofcharlast = ($length - 2 * $nbofchar); //var_dump($nbofchar.'-'.$nbofcharlast); - if (function_exists('random_int')) // Cryptographic random - { + if (function_exists('random_int')) { // Cryptographic random $max = strlen($lowercase) - 1; for ($x = 0; $x < $nbofchar; $x++) { $tmp = random_int(0, $max); @@ -484,8 +496,7 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len $generated_password = str_shuffle($randomCode); } - } elseif (!empty($conf->global->USER_PASSWORD_GENERATED)) - { + } elseif (!empty($conf->global->USER_PASSWORD_GENERATED)) { $nomclass = "modGeneratePass".ucfirst($conf->global->USER_PASSWORD_GENERATED); $nomfichier = $nomclass.".class.php"; //print DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomclass; @@ -496,8 +507,7 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len } // Do we have to discard some alphabetic characters ? - if (is_array($replaceambiguouschars) && count($replaceambiguouschars) > 0) - { + if (is_array($replaceambiguouschars) && count($replaceambiguouschars) > 0) { $numbers = "ABCDEF"; $max = strlen($numbers) - 1; if (function_exists('random_int')) { // Cryptographic random diff --git a/htdocs/core/lib/sendings.lib.php b/htdocs/core/lib/sendings.lib.php index 0bb0db6afd1..15e7286ab08 100644 --- a/htdocs/core/lib/sendings.lib.php +++ b/htdocs/core/lib/sendings.lib.php @@ -47,12 +47,10 @@ function shipping_prepare_head($object) $head[$h][2] = 'shipping'; $h++; - if ($conf->delivery_note->enabled && $user->rights->expedition->delivery->lire) - { + if ($conf->delivery_note->enabled && $user->rights->expedition->delivery->lire) { // delivery link $object->fetchObjectLinked($object->id, $object->element); - if (is_array($object->linkedObjectsIds['delivery']) && count($object->linkedObjectsIds['delivery']) > 0) // If there is a delivery - { + if (is_array($object->linkedObjectsIds['delivery']) && count($object->linkedObjectsIds['delivery']) > 0) { // If there is a delivery // Take first one element of array $tmp = reset($object->linkedObjectsIds['delivery']); @@ -63,18 +61,18 @@ function shipping_prepare_head($object) } } - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $objectsrc = $object; - if ($object->origin == 'commande' && $object->origin_id > 0) - { + if ($object->origin == 'commande' && $object->origin_id > 0) { $objectsrc = new Commande($db); $objectsrc->fetch($object->origin_id); } $nbContact = count($objectsrc->liste_contact(-1, 'internal')) + count($objectsrc->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT."/expedition/contact.php?id=".$object->id; $head[$h][1] = $langs->trans("ContactsAddresses"); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -86,16 +84,24 @@ function shipping_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/expedition/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT."/expedition/note.php?id=".$object->id; $head[$h][1] = $langs->trans("Notes"); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; @@ -127,8 +133,7 @@ function delivery_prepare_head($object) $h = 0; $head = array(); - if ($conf->expedition_bon->enabled && $user->rights->expedition->lire) - { + if ($conf->expedition_bon->enabled && $user->rights->expedition->lire) { $head[$h][0] = DOL_URL_ROOT."/expedition/card.php?id=".$object->origin_id; $head[$h][1] = $langs->trans("SendingCard"); $head[$h][2] = 'shipping'; @@ -157,18 +162,18 @@ function delivery_prepare_head($object) $tmpobject = $object; } - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $objectsrc = $tmpobject; - if ($tmpobject->origin == 'commande' && $tmpobject->origin_id > 0) - { + if ($tmpobject->origin == 'commande' && $tmpobject->origin_id > 0) { $objectsrc = new Commande($db); $objectsrc->fetch($tmpobject->origin_id); } $nbContact = count($objectsrc->liste_contact(-1, 'internal')) + count($objectsrc->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT."/expedition/contact.php?id=".$tmpobject->id; $head[$h][1] = $langs->trans("ContactsAddresses"); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -180,16 +185,24 @@ function delivery_prepare_head($object) $nbLinks = Link::count($db, $tmpobject->element, $tmpobject->id); $head[$h][0] = DOL_URL_ROOT.'/expedition/document.php?id='.$tmpobject->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; $nbNote = 0; - if (!empty($tmpobject->note_private)) $nbNote++; - if (!empty($tmpobject->note_public)) $nbNote++; + if (!empty($tmpobject->note_private)) { + $nbNote++; + } + if (!empty($tmpobject->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT."/expedition/note.php?id=".$tmpobject->id; $head[$h][1] = $langs->trans("Notes"); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; @@ -236,21 +249,24 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') $sql .= " AND obj.fk_".$origin." = ".$origin_id; $sql .= " AND obj.rowid = ed.fk_origin_line"; $sql .= " AND ed.fk_expedition = e.rowid"; - if ($filter) $sql .= $filter; + if ($filter) { + $sql .= $filter; + } $sql .= " ORDER BY obj.fk_product"; dol_syslog("show_list_sending_receive", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num) - { - if ($filter) print load_fiche_titre($langs->trans("OtherSendingsForSameOrder")); - else print load_fiche_titre($langs->trans("SendingsAndReceivingForSameOrder")); + if ($num) { + if ($filter) { + print load_fiche_titre($langs->trans("OtherSendingsForSameOrder")); + } else { + print load_fiche_titre($langs->trans("SendingsAndReceivingForSameOrder")); + } print ''; print ''; @@ -260,26 +276,23 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') print ''; print ''; print ''; - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print ''; } /*TODO Add link to expeditiondet_batch if (! empty($conf->productbatch->enabled)) { - print ''; + print ''; }*/ - if (!empty($conf->delivery_note->enabled)) - { + if (!empty($conf->delivery_note->enabled)) { print ''; //print ''; print ''; } print "\n"; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); print ''; @@ -290,11 +303,9 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') print ''; // Description - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { // Define output language - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $object = new $origin($db); $object->fetch($origin_id); $object->fetch_thirdparty(); @@ -305,10 +316,13 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && !empty($_REQUEST['lang_id'])) $newlang = $_REQUEST['lang_id']; - if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + if (empty($newlang) && !empty($_REQUEST['lang_id'])) { + $newlang = $_REQUEST['lang_id']; + } + if (empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -334,16 +348,18 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') print_date_range($objp->date_start, $objp->date_end); // Add description in form - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { print (!empty($objp->description) && $objp->description != $objp->product) ? '
    '.dol_htmlentitiesbr($objp->description) : ''; } print ''; } else { print "'; // Warehouse - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print ''; - } else { - print ''; - } + } + print $form->textwithtooltip(img_picto('', 'object_barcode').' '.$langs->trans("DetailBatchNumber"),$detail); + } + else + { + print $langs->trans("NA"); + } + print ''; + } else { + print ''; + } }*/ // Informations on receipt - if (!empty($conf->delivery_note->enabled)) - { + if (!empty($conf->delivery_note->enabled)) { include_once DOL_DOCUMENT_ROOT.'/delivery/class/delivery.class.php'; $expedition->id = $objp->sendingid; $expedition->fetchObjectLinked($expedition->id, $expedition->element); //var_dump($expedition->linkedObjects); $receiving = ''; - if (!empty($expedition->linkedObjects['delivery'])) $receiving = reset($expedition->linkedObjects['delivery']); // Take first link + if (!empty($expedition->linkedObjects['delivery'])) { + $receiving = reset($expedition->linkedObjects['delivery']); // Take first link + } - if (!empty($receiving)) - { + if (!empty($receiving)) { // $expedition->fk_origin_line = id of det line of order // $receiving->fk_origin_line = id of det line of order // $receiving->origin may be 'shipping' diff --git a/htdocs/core/lib/signature.lib.php b/htdocs/core/lib/signature.lib.php index 14ca70926d3..8b49b01ae35 100644 --- a/htdocs/core/lib/signature.lib.php +++ b/htdocs/core/lib/signature.lib.php @@ -56,18 +56,24 @@ function getOnlineSignatureUrl($mode, $type, $ref = '') $ref = str_replace(' ', '', $ref); $out = ''; - if ($type == 'proposal') - { + if ($type == 'proposal') { $out = DOL_MAIN_URL_ROOT.'/public/onlinesign/newonlinesign.php?source=proposal&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'proposal_ref'; - if ($mode == 0) $out .= urlencode($ref); + if ($mode == 1) { + $out .= 'proposal_ref'; + } + if ($mode == 0) { + $out .= urlencode($ref); + } $out .= ($mode ? '' : ''); - if ($mode == 1) $out .= '&hashp=hash_of_file'; - else { + if ($mode == 1) { + $out .= '&hashp=hash_of_file'; + } else { include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $propaltmp = new Propal($db); $res = $propaltmp->fetch(0, $ref); - if ($res <= 0) return 'FailedToGetProposal'; + if ($res <= 0) { + return 'FailedToGetProposal'; + } include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile = new EcmFiles($db); @@ -75,8 +81,7 @@ function getOnlineSignatureUrl($mode, $type, $ref = '') $ecmfile->fetch(0, '', $propaltmp->last_main_doc); $hashp = $ecmfile->share; - if (empty($hashp)) - { + if (empty($hashp)) { $out = $langs->trans("FeatureOnlineSignDisabled"); return $out; } else { @@ -86,7 +91,9 @@ function getOnlineSignatureUrl($mode, $type, $ref = '') } // For multicompany - if (!empty($out)) $out .= "&entity=".$conf->entity; // Check the entity because He may be the same reference in several entities + if (!empty($out)) { + $out .= "&entity=".$conf->entity; // Check the entity because He may be the same reference in several entities + } return $out; } diff --git a/htdocs/core/lib/stock.lib.php b/htdocs/core/lib/stock.lib.php index 2d6768010fb..2e58e6c8082 100644 --- a/htdocs/core/lib/stock.lib.php +++ b/htdocs/core/lib/stock.lib.php @@ -39,8 +39,7 @@ function stock_prepare_head($object) $head[$h][2] = 'card'; $h++; - if (!empty($user->rights->stock->mouvement->lire)) - { + if (!empty($user->rights->stock->mouvement->lire)) { $head[$h][0] = DOL_URL_ROOT.'/product/stock/movement_list.php?id='.$object->id; $head[$h][1] = $langs->trans("StockMovements"); $head[$h][2] = 'movements'; diff --git a/htdocs/core/lib/supplier_proposal.lib.php b/htdocs/core/lib/supplier_proposal.lib.php index ec782350c9d..a7720bd9ef4 100644 --- a/htdocs/core/lib/supplier_proposal.lib.php +++ b/htdocs/core/lib/supplier_proposal.lib.php @@ -44,12 +44,13 @@ function supplier_proposal_prepare_head($object) $head[$h][2] = 'comm'; $h++; - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/supplier_proposal/contact.php?id='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -60,14 +61,19 @@ function supplier_proposal_prepare_head($object) // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_proposal'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/supplier_proposal/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; } @@ -79,7 +85,9 @@ function supplier_proposal_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'document'; $h++; diff --git a/htdocs/core/lib/takepos.lib.php b/htdocs/core/lib/takepos.lib.php index dfddc95d733..db1623387c1 100644 --- a/htdocs/core/lib/takepos.lib.php +++ b/htdocs/core/lib/takepos.lib.php @@ -54,8 +54,7 @@ function takepos_admin_prepare_head() $h++; $numterminals = max(1, $conf->global->TAKEPOS_NUM_TERMINALS); - for ($i = 1; $i <= $numterminals; $i++) - { + for ($i = 1; $i <= $numterminals; $i++) { $head[$h][0] = DOL_URL_ROOT.'/takepos/admin/terminal.php?terminal='.$i; $head[$h][1] = $langs->trans("Terminal")." ".$i; $head[$h][2] = 'terminal'.$i; diff --git a/htdocs/core/lib/tax.lib.php b/htdocs/core/lib/tax.lib.php index 36ce55f7c85..c66d16b6736 100644 --- a/htdocs/core/lib/tax.lib.php +++ b/htdocs/core/lib/tax.lib.php @@ -1,11 +1,12 @@ - * Copyright (C) 2006-2007 Yannick Warnier - * Copyright (C) 2011 Regis Houssin - * Copyright (C) 2012-2017 Juanjo Menent - * Copyright (C) 2012 Cédric Salvador - * Copyright (C) 2012-2014 Raphaël Doursenaud - * Copyright (C) 2015 Marcos García +/* Copyright (C) 2004-2009 Laurent Destailleur + * Copyright (C) 2006-2007 Yannick Warnier + * Copyright (C) 2011 Regis Houssin + * Copyright (C) 2012-2017 Juanjo Menent + * Copyright (C) 2012 Cédric Salvador + * Copyright (C) 2012-2014 Raphaël Doursenaud + * Copyright (C) 2015 Marcos García + * 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 @@ -59,7 +60,9 @@ function tax_prepare_head(ChargeSociales $object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/compta/sociales/document.php?id='.$object->id; $head[$h][1] = $langs->trans("Documents"); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; @@ -93,14 +96,12 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di global $conf; // If we use date_start and date_end, we must not use $y, $m, $q - if (($date_start || $date_end) && (!empty($y) || !empty($m) || !empty($q))) - { + if (($date_start || $date_end) && (!empty($y) || !empty($m) || !empty($q))) { dol_print_error('', 'Bad value of input parameter for tax_by_rate'); } $list = array(); - if ($direction == 'sell') - { + if ($direction == 'sell') { $invoicetable = 'facture'; $invoicedettable = 'facturedet'; $fk_facture = 'fk_facture'; @@ -110,8 +111,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di $paymenttable = 'paiement'; $paymentfacturetable = 'paiement_facture'; $invoicefieldref = 'ref'; - } elseif ($direction == 'buy') - { + } elseif ($direction == 'buy') { $invoicetable = 'facture_fourn'; $invoicedettable = 'facture_fourn_det'; $fk_facture = 'fk_facture_fourn'; @@ -138,8 +138,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di // Define sql request $sql = ''; if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')) - { + || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')) { // Count on delivery date (use invoice date as delivery is unknown) $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; @@ -153,24 +152,31 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } $sql .= " AND f.rowid = d.".$fk_facture; $sql .= " AND s.rowid = f.fk_soc"; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 0"; // Limit to products $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture; } else { // Count on payments date @@ -189,49 +195,64 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } $sql .= " AND f.rowid = d.".$fk_facture; $sql .= " AND s.rowid = f.fk_soc"; $sql .= " AND pf.".$fk_facture2." = f.rowid"; $sql .= " AND pa.rowid = pf.".$fk_payment; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 0"; // Limit to products $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; } - if (!$sql) return -1; - if ($sql == 'TODO') return -2; - if ($sql != 'TODO') - { + if (!$sql) { + return -1; + } + if ($sql == 'TODO') { + return -2; + } + if ($sql != 'TODO') { dol_syslog("Tax.lib.php::tax_by_thirdparty", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $company_id = -1; $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { - if (!isset($list[$assoc['company_id']]['totalht'])) $list[$assoc['company_id']]['totalht'] = 0; - if (!isset($list[$assoc['company_id']]['vat'])) $list[$assoc['company_id']]['vat'] = 0; - if (!isset($list[$assoc['company_id']]['localtax1'])) $list[$assoc['company_id']]['localtax1'] = 0; - if (!isset($list[$assoc['company_id']]['localtax2'])) $list[$assoc['company_id']]['localtax2'] = 0; + while ($assoc = $db->fetch_array($resql)) { + if (!isset($list[$assoc['company_id']]['totalht'])) { + $list[$assoc['company_id']]['totalht'] = 0; + } + if (!isset($list[$assoc['company_id']]['vat'])) { + $list[$assoc['company_id']]['vat'] = 0; + } + if (!isset($list[$assoc['company_id']]['localtax1'])) { + $list[$assoc['company_id']]['localtax1'] = 0; + } + if (!isset($list[$assoc['company_id']]['localtax2'])) { + $list[$assoc['company_id']]['localtax2'] = 0; + } - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { + if ($assoc['rowid'] != $oldrowid) { // Si rupture sur d.rowid $oldrowid = $assoc['rowid']; $list[$assoc['company_id']]['totalht'] += $assoc['total_ht']; $list[$assoc['company_id']]['vat'] += $assoc['total_vat']; @@ -280,8 +301,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di // Define sql request $sql = ''; if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice') - || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) - { + || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) { // Count on invoice date $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; @@ -295,24 +315,31 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } $sql .= " AND f.rowid = d.".$fk_facture; $sql .= " AND s.rowid = f.fk_soc"; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 1"; // Limit to services $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture; } else { // Count on payments date @@ -331,52 +358,64 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } $sql .= " AND f.rowid = d.".$fk_facture; $sql .= " AND s.rowid = f.fk_soc"; $sql .= " AND pf.".$fk_facture2." = f.rowid"; $sql .= " AND pa.rowid = pf.".$fk_payment; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 1"; // Limit to services $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; } - if (!$sql) - { + if (!$sql) { dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); return -1; // -1 = Not accountancy module enabled } - if ($sql == 'TODO') return -2; // -2 = Feature not yet available - if ($sql != 'TODO') - { + if ($sql == 'TODO') { + return -2; // -2 = Feature not yet available + } + if ($sql != 'TODO') { dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $company_id = -1; $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { - if (!isset($list[$assoc['company_id']]['totalht'])) $list[$assoc['company_id']]['totalht'] = 0; - if (!isset($list[$assoc['company_id']]['vat'])) $list[$assoc['company_id']]['vat'] = 0; - if (!isset($list[$assoc['company_id']]['localtax1'])) $list[$assoc['company_id']]['localtax1'] = 0; - if (!isset($list[$assoc['company_id']]['localtax2'])) $list[$assoc['company_id']]['localtax2'] = 0; + while ($assoc = $db->fetch_array($resql)) { + if (!isset($list[$assoc['company_id']]['totalht'])) { + $list[$assoc['company_id']]['totalht'] = 0; + } + if (!isset($list[$assoc['company_id']]['vat'])) { + $list[$assoc['company_id']]['vat'] = 0; + } + if (!isset($list[$assoc['company_id']]['localtax1'])) { + $list[$assoc['company_id']]['localtax1'] = 0; + } + if (!isset($list[$assoc['company_id']]['localtax2'])) { + $list[$assoc['company_id']]['localtax2'] = 0; + } - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { + if ($assoc['rowid'] != $oldrowid) { // Si rupture sur d.rowid $oldrowid = $assoc['rowid']; $list[$assoc['company_id']]['totalht'] += $assoc['total_ht']; $list[$assoc['company_id']]['vat'] += $assoc['total_vat']; @@ -422,8 +461,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di // CASE OF EXPENSE REPORT - if ($direction == 'buy') // buy only for expense reports - { + if ($direction == 'buy') { // buy only for expense reports // Define sql request $sql = ''; @@ -438,45 +476,54 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_expensereport as p ON p.fk_expensereport = e.rowid "; $sql .= " WHERE e.entity = ".$conf->entity; $sql .= " AND e.fk_statut in (6)"; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(p.datep,'%m') > ".(($q - 1) * 3)." AND date_format(p.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(p.datep,'%m') > ".(($q - 1) * 3)." AND date_format(p.datep,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = -1"; $sql .= " OR e.date_debut is NOT null OR e.date_fin IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; + } $sql .= " ORDER BY e.rowid"; - if (!$sql) - { + if (!$sql) { dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); return -1; // -1 = Not accountancy module enabled } - if ($sql == 'TODO') return -2; // -2 = Feature not yet available - if ($sql != 'TODO') - { + if ($sql == 'TODO') { + return -2; // -2 = Feature not yet available + } + if ($sql != 'TODO') { dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $company_id = -1; $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { - if (!isset($list[$assoc['company_id']]['totalht'])) $list[$assoc['company_id']]['totalht'] = 0; - if (!isset($list[$assoc['company_id']]['vat'])) $list[$assoc['company_id']]['vat'] = 0; - if (!isset($list[$assoc['company_id']]['localtax1'])) $list[$assoc['company_id']]['localtax1'] = 0; - if (!isset($list[$assoc['company_id']]['localtax2'])) $list[$assoc['company_id']]['localtax2'] = 0; + while ($assoc = $db->fetch_array($resql)) { + if (!isset($list[$assoc['company_id']]['totalht'])) { + $list[$assoc['company_id']]['totalht'] = 0; + } + if (!isset($list[$assoc['company_id']]['vat'])) { + $list[$assoc['company_id']]['vat'] = 0; + } + if (!isset($list[$assoc['company_id']]['localtax1'])) { + $list[$assoc['company_id']]['localtax1'] = 0; + } + if (!isset($list[$assoc['company_id']]['localtax2'])) { + $list[$assoc['company_id']]['localtax2'] = 0; + } - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { + if ($assoc['rowid'] != $oldrowid) { // Si rupture sur d.rowid $oldrowid = $assoc['rowid']; $list[$assoc['company_id']]['totalht'] += $assoc['total_ht']; $list[$assoc['company_id']]['vat'] += $assoc['total_vat']; @@ -545,15 +592,13 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire global $conf; // If we use date_start and date_end, we must not use $y, $m, $q - if (($date_start || $date_end) && (!empty($y) || !empty($m) || !empty($q))) - { + if (($date_start || $date_end) && (!empty($y) || !empty($m) || !empty($q))) { dol_print_error('', 'Bad value of input parameter for tax_by_rate'); } $list = array(); - if ($direction == 'sell') - { + if ($direction == 'sell') { $invoicetable = 'facture'; $invoicedettable = 'facturedet'; $fk_facture = 'fk_facture'; @@ -590,8 +635,7 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire // Define sql request $sql = ''; if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')) - { + || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')) { // Count on delivery date (use invoice date as delivery is unknown) $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; @@ -599,30 +643,35 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; $sql .= " 0 as payment_id, 0 as payment_amount"; - $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s,"; - $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; + $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$invoicedettable." as d ON d.".$fk_facture."=f.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; - $sql .= " AND f.rowid = d.".$fk_facture; - $sql .= " AND s.rowid = f.fk_soc"; - if ($y && $m) - { + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } + if ($y && $m) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 0"; // Limit to products $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture; } else { // Count on payments date @@ -633,58 +682,69 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; $sql .= " pf.".$fk_payment." as payment_id, pf.amount as payment_amount,"; $sql .= " pa.datep as datep"; - $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; - $sql .= " ".MAIN_DB_PREFIX.$paymentfacturetable." as pf,"; - $sql .= " ".MAIN_DB_PREFIX.$paymenttable." as pa,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s,"; - $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; + $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$paymentfacturetable." as pf ON pf.".$fk_facture2." = f.rowid";; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$paymenttable." as pa ON pa.rowid = pf.".$fk_payment; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$invoicedettable." as d ON d.".$fk_facture." = f.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; - $sql .= " AND f.rowid = d.".$fk_facture; - $sql .= " AND s.rowid = f.fk_soc"; - $sql .= " AND pf.".$fk_facture2." = f.rowid"; - $sql .= " AND pa.rowid = pf.".$fk_payment; - if ($y && $m) - { + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } + if ($y && $m) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 0"; // Limit to products $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; } - if (!$sql) return -1; - if ($sql == 'TODO') return -2; - if ($sql != 'TODO') - { + if (!$sql) { + return -1; + } + if ($sql == 'TODO') { + return -2; + } + if ($sql != 'TODO') { dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $rate = -1; $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { + while ($assoc = $db->fetch_array($resql)) { // Code to avoid warnings when array entry not defined - if (!isset($list[$assoc['rate']]['totalht'])) $list[$assoc['rate']]['totalht'] = 0; - if (!isset($list[$assoc['rate']]['vat'])) $list[$assoc['rate']]['vat'] = 0; - if (!isset($list[$assoc['rate']]['localtax1'])) $list[$assoc['rate']]['localtax1'] = 0; - if (!isset($list[$assoc['rate']]['localtax2'])) $list[$assoc['rate']]['localtax2'] = 0; + if (!isset($list[$assoc['rate']]['totalht'])) { + $list[$assoc['rate']]['totalht'] = 0; + } + if (!isset($list[$assoc['rate']]['vat'])) { + $list[$assoc['rate']]['vat'] = 0; + } + if (!isset($list[$assoc['rate']]['localtax1'])) { + $list[$assoc['rate']]['localtax1'] = 0; + } + if (!isset($list[$assoc['rate']]['localtax2'])) { + $list[$assoc['rate']]['localtax2'] = 0; + } - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { + if ($assoc['rowid'] != $oldrowid) { // Si rupture sur d.rowid $oldrowid = $assoc['rowid']; $list[$assoc['rate']]['totalht'] += $assoc['total_ht']; $list[$assoc['rate']]['vat'] += $assoc['total_vat']; @@ -732,8 +792,7 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire // Define sql request $sql = ''; if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice') - || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) - { + || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) { // Count on invoice date $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; @@ -741,30 +800,35 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; $sql .= " 0 as payment_id, 0 as payment_amount"; - $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s,"; - $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; + $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$invoicedettable." as d ON d.".$fk_facture." = f.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; - $sql .= " AND f.rowid = d.".$fk_facture; - $sql .= " AND s.rowid = f.fk_soc"; - if ($y && $m) - { + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } + if ($y && $m) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 1"; // Limit to services $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture; } else { // Count on payments date @@ -775,61 +839,69 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; $sql .= " pf.".$fk_payment." as payment_id, pf.amount as payment_amount,"; $sql .= " pa.datep as datep"; - $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; - $sql .= " ".MAIN_DB_PREFIX.$paymentfacturetable." as pf,"; - $sql .= " ".MAIN_DB_PREFIX.$paymenttable." as pa,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s,"; - $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; + $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$paymentfacturetable." as pf ON pf.".$fk_facture2." = f.rowid"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$paymenttable." as pa ON pa.rowid = pf.".$fk_payment; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$invoicedettable." as d ON d.".$fk_facture." = f.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; - $sql .= " AND f.rowid = d.".$fk_facture; - $sql .= " AND s.rowid = f.fk_soc"; - $sql .= " AND pf.".$fk_facture2." = f.rowid"; - $sql .= " AND pa.rowid = pf.".$fk_payment; - if ($y && $m) - { + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } + if ($y && $m) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 1"; // Limit to services $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; } - if (!$sql) - { + if (!$sql) { dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); return -1; // -1 = Not accountancy module enabled } - if ($sql == 'TODO') return -2; // -2 = Feature not yet available - if ($sql != 'TODO') - { + if ($sql == 'TODO') { + return -2; // -2 = Feature not yet available + } + if ($sql != 'TODO') { dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $rate = -1; $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { + while ($assoc = $db->fetch_array($resql)) { // Code to avoid warnings when array entry not defined - if (!isset($list[$assoc['rate']]['totalht'])) $list[$assoc['rate']]['totalht'] = 0; - if (!isset($list[$assoc['rate']]['vat'])) $list[$assoc['rate']]['vat'] = 0; - if (!isset($list[$assoc['rate']]['localtax1'])) $list[$assoc['rate']]['localtax1'] = 0; - if (!isset($list[$assoc['rate']]['localtax2'])) $list[$assoc['rate']]['localtax2'] = 0; + if (!isset($list[$assoc['rate']]['totalht'])) { + $list[$assoc['rate']]['totalht'] = 0; + } + if (!isset($list[$assoc['rate']]['vat'])) { + $list[$assoc['rate']]['vat'] = 0; + } + if (!isset($list[$assoc['rate']]['localtax1'])) { + $list[$assoc['rate']]['localtax1'] = 0; + } + if (!isset($list[$assoc['rate']]['localtax2'])) { + $list[$assoc['rate']]['localtax2'] = 0; + } - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { + if ($assoc['rowid'] != $oldrowid) { // Si rupture sur d.rowid $oldrowid = $assoc['rowid']; $list[$assoc['rate']]['totalht'] += $assoc['total_ht']; $list[$assoc['rate']]['vat'] += $assoc['total_vat']; @@ -874,8 +946,7 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire // CASE OF EXPENSE REPORT - if ($direction == 'buy') // buy only for expense reports - { + if ($direction == 'buy') { // buy only for expense reports // Define sql request $sql = ''; @@ -885,51 +956,60 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire $sql .= " e.date_debut as date_start, e.date_fin as date_end, e.fk_user_author,"; $sql .= " e.ref as facnum, e.total_ttc as ftotal_ttc, e.date_create, d.fk_c_type_fees as type,"; $sql .= " p.fk_bank as payment_id, p.amount as payment_amount, p.rowid as pid, e.ref as pref"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as e "; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expensereport_det as d ON d.fk_expensereport = e.rowid "; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_expensereport as p ON p.fk_expensereport = e.rowid "; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as e"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expensereport_det as d ON d.fk_expensereport = e.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_expensereport as p ON p.fk_expensereport = e.rowid"; $sql .= " WHERE e.entity = ".$conf->entity; $sql .= " AND e.fk_statut in (6)"; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(p.datep,'%m') > ".(($q - 1) * 3)." AND date_format(p.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(p.datep,'%m') > ".(($q - 1) * 3)." AND date_format(p.datep,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = -1"; $sql .= " OR e.date_debut is NOT null OR e.date_fin IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; + } $sql .= " ORDER BY e.rowid"; - if (!$sql) - { + if (!$sql) { dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); return -1; // -1 = Not accountancy module enabled } - if ($sql == 'TODO') return -2; // -2 = Feature not yet available - if ($sql != 'TODO') - { + if ($sql == 'TODO') { + return -2; // -2 = Feature not yet available + } + if ($sql != 'TODO') { dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $rate = -1; $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { + while ($assoc = $db->fetch_array($resql)) { // Code to avoid warnings when array entry not defined - if (!isset($list[$assoc['rate']]['totalht'])) $list[$assoc['rate']]['totalht'] = 0; - if (!isset($list[$assoc['rate']]['vat'])) $list[$assoc['rate']]['vat'] = 0; - if (!isset($list[$assoc['rate']]['localtax1'])) $list[$assoc['rate']]['localtax1'] = 0; - if (!isset($list[$assoc['rate']]['localtax2'])) $list[$assoc['rate']]['localtax2'] = 0; + if (!isset($list[$assoc['rate']]['totalht'])) { + $list[$assoc['rate']]['totalht'] = 0; + } + if (!isset($list[$assoc['rate']]['vat'])) { + $list[$assoc['rate']]['vat'] = 0; + } + if (!isset($list[$assoc['rate']]['localtax1'])) { + $list[$assoc['rate']]['localtax1'] = 0; + } + if (!isset($list[$assoc['rate']]['localtax2'])) { + $list[$assoc['rate']]['localtax2'] = 0; + } - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { + if ($assoc['rowid'] != $oldrowid) { // Si rupture sur d.rowid $oldrowid = $assoc['rowid']; $list[$assoc['rate']]['totalht'] += $assoc['total_ht']; $list[$assoc['rate']]['vat'] += $assoc['total_vat']; diff --git a/htdocs/core/lib/ticket.lib.php b/htdocs/core/lib/ticket.lib.php index c90892d603c..472cf19e45d 100644 --- a/htdocs/core/lib/ticket.lib.php +++ b/htdocs/core/lib/ticket.lib.php @@ -88,7 +88,9 @@ function ticket_prepare_head($object) $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/ticket/contact.php?track_id='.$object->track_id; $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -124,8 +126,7 @@ function ticket_prepare_head($object) $head[$h][0] = DOL_URL_ROOT.'/ticket/agenda.php?track_id='.$object->track_id; } $head[$h][1] = $langs->trans('Events'); - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $head[$h][1] .= '/'; $head[$h][1] .= $langs->trans("Agenda"); } @@ -150,8 +151,7 @@ function showDirectPublicLink($object) require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $email = CMailFile::getValidAddress($object->origin_email, 2); $url = ''; - if ($email) - { + if ($email) { $url = dol_buildpath('/public/ticket/view.php', 3).'?track_id='.$object->track_id.'&email='.$email; } @@ -278,14 +278,14 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no dol_include_once('/comm/action/class/actioncomm.class.php'); // Check parameters - if (!is_object($filterobj) && !is_object($objcon)) dol_print_error('', 'BadParameter'); + if (!is_object($filterobj) && !is_object($objcon)) { + dol_print_error('', 'BadParameter'); + } - $out = ''; $histo = array(); $numaction = 0; $now = dol_now(); - // Open DSI -- Fix order by -- Begin $sortfield_list = explode(',', $sortfield); $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent'); $sortfield_new_list = array(); @@ -294,9 +294,8 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no } $sortfield_new = implode(',', $sortfield_new_list); - if (!empty($conf->agenda->enabled)) - { - // Recherche histo sur actioncomm + if (!empty($conf->agenda->enabled)) { + // Search histo on actioncomm if (is_object($objcon) && $objcon->id > 0) { $sql = "SELECT DISTINCT a.id, a.label as label,"; } else { @@ -365,22 +364,34 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $sql .= " AND a.fk_project = ".$filterobj->id; } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') { $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + if ($filterobj->id) { + $sql .= " AND a.fk_element = ".$filterobj->id; + } } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + if ($filterobj->id) { + $sql .= " AND a.fk_element = ".$filterobj->id; + } } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + if ($filterobj->id) { + $sql .= " AND a.fk_element = ".$filterobj->id; + } } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + if ($filterobj->id) { + $sql .= " AND a.fk_element = ".$filterobj->id; + } } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + if ($filterobj->id) { + $sql .= " AND a.fk_element = ".$filterobj->id; + } } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + if ($filterobj->id) { + $sql .= " AND a.fk_element = ".$filterobj->id; + } } } @@ -399,20 +410,28 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no } } } else { - if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; - else $sql .= " AND c.code = '".$db->escape($actioncode)."'"; + if ($actioncode == 'AC_NON_AUTO') { + $sql .= " AND c.type != 'systemauto'"; + } elseif ($actioncode == 'AC_ALL_AUTO') { + $sql .= " AND c.type = 'systemauto'"; + } else { + $sql .= " AND c.code = '".$db->escape($actioncode)."'"; + } } } - if ($donetodo == 'todo') $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; - elseif ($donetodo == 'done') $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; - if (is_array($filters) && $filters['search_agenda_label']) $sql .= natural_search('a.label', $filters['search_agenda_label']); + if ($donetodo == 'todo') { + $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; + } elseif ($donetodo == 'done') { + $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; + } + if (is_array($filters) && $filters['search_agenda_label']) { + $sql .= natural_search('a.label', $filters['search_agenda_label']); + } } // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing. if (!empty($conf->mailing->enabled) && !empty($objcon->email) - && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) - { + && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) { $langs->load("mails"); $sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type"; @@ -443,85 +462,97 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $sql = $sql2; } - //TODO Add limit in nb of results - $sql .= $db->order($sortfield_new, $sortorder); + // TODO Add limit in nb of results + if ($sql) { // May not be defined if module Agenda is not enabled and mailing module disabled too + $sql .= $db->order($sortfield_new, $sortorder); - dol_syslog("company.lib::show_actions_done", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) { - $i = 0; - $num = $db->num_rows($resql); + dol_syslog("company.lib::show_actions_done", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) { + $i = 0; + $num = $db->num_rows($resql); - while ($i < $num) { - $obj = $db->fetch_object($resql); + while ($i < $num) { + $obj = $db->fetch_object($resql); - if ($obj->type == 'action') { - $contactaction = new ActionComm($db); - $contactaction->id = $obj->id; - $result = $contactaction->fetchResources(); - if ($result < 0) { - dol_print_error($db); - setEventMessage("company.lib::show_actions_done Error fetch ressource", 'errors'); + if ($obj->type == 'action') { + $contactaction = new ActionComm($db); + $contactaction->id = $obj->id; + $result = $contactaction->fetchResources(); + if ($result < 0) { + dol_print_error($db); + setEventMessage("company.lib::show_actions_done Error fetch ressource", 'errors'); + } + + //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; + //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; + $tododone = ''; + if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->datep > $now)) { + $tododone = 'todo'; + } + + $histo[$numaction] = array( + 'type'=>$obj->type, + 'tododone'=>$tododone, + 'id'=>$obj->id, + 'datestart'=>$db->jdate($obj->dp), + 'dateend'=>$db->jdate($obj->dp2), + 'note'=>$obj->label, + 'message'=>$obj->message, + 'percent'=>$obj->percent, + + 'userid'=>$obj->user_id, + 'login'=>$obj->user_login, + 'userfirstname'=>$obj->user_firstname, + 'userlastname'=>$obj->user_lastname, + 'userphoto'=>$obj->user_photo, + + 'contact_id'=>$obj->fk_contact, + 'socpeopleassigned' => $contactaction->socpeopleassigned, + 'lastname'=>$obj->lastname, + 'firstname'=>$obj->firstname, + 'fk_element'=>$obj->fk_element, + 'elementtype'=>$obj->elementtype, + // Type of event + 'acode'=>$obj->acode, + 'alabel'=>$obj->alabel, + 'libelle'=>$obj->alabel, // deprecated + 'apicto'=>$obj->apicto + ); + } else { + $histo[$numaction] = array( + 'type'=>$obj->type, + 'tododone'=>'done', + 'id'=>$obj->id, + 'datestart'=>$db->jdate($obj->dp), + 'dateend'=>$db->jdate($obj->dp2), + 'note'=>$obj->label, + 'message'=>$obj->message, + 'percent'=>$obj->percent, + 'acode'=>$obj->acode, + + 'userid'=>$obj->user_id, + 'login'=>$obj->user_login, + 'userfirstname'=>$obj->user_firstname, + 'userlastname'=>$obj->user_lastname, + 'userphoto'=>$obj->user_photo + ); } - //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; - //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; - $tododone = ''; - if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->datep > $now)) $tododone = 'todo'; - - $histo[$numaction] = array( - 'type'=>$obj->type, - 'tododone'=>$tododone, - 'id'=>$obj->id, - 'datestart'=>$db->jdate($obj->dp), - 'dateend'=>$db->jdate($obj->dp2), - 'note'=>$obj->label, - 'message'=>$obj->message, - 'percent'=>$obj->percent, - - 'userid'=>$obj->user_id, - 'login'=>$obj->user_login, - 'userfirstname'=>$obj->user_firstname, - 'userlastname'=>$obj->user_lastname, - 'userphoto'=>$obj->user_photo, - - 'contact_id'=>$obj->fk_contact, - 'socpeopleassigned' => $contactaction->socpeopleassigned, - 'lastname'=>$obj->lastname, - 'firstname'=>$obj->firstname, - 'fk_element'=>$obj->fk_element, - 'elementtype'=>$obj->elementtype, - // Type of event - 'acode'=>$obj->acode, - 'alabel'=>$obj->alabel, - 'libelle'=>$obj->alabel, // deprecated - 'apicto'=>$obj->apicto - ); - } else { - $histo[$numaction] = array( - 'type'=>$obj->type, - 'tododone'=>'done', - 'id'=>$obj->id, - 'datestart'=>$db->jdate($obj->dp), - 'dateend'=>$db->jdate($obj->dp2), - 'note'=>$obj->label, - 'message'=>$obj->message, - 'percent'=>$obj->percent, - 'acode'=>$obj->acode, - - 'userid'=>$obj->user_id, - 'login'=>$obj->user_login, - 'userfirstname'=>$obj->user_firstname, - 'userlastname'=>$obj->user_lastname, - 'userphoto'=>$obj->user_photo - ); + $numaction++; + $i++; } - - $numaction++; - $i++; + } else { + dol_print_error($db); } - } else { - dol_print_error($db); + } + + // Set $out to sow events + $out = ''; + + if (empty($conf->agenda->enabled)) { + $langs->loadLangs(array("admin", "errors")); + $out = info_admin($langs->trans("WarningModuleXDisabledSoYouMayMissEventHere", $langs->transnoentitiesnoconv("Module2400Name")), 0, 0, 'warning'); } if (!empty($conf->agenda->enabled) || (!empty($conf->mailing->enabled) && !empty($objcon->email))) { @@ -549,7 +580,9 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no } else { $out .= ''; } - if ($filterobj && get_class($filterobj) == 'Societe') $out .= ''; + if ($filterobj && get_class($filterobj) == 'Societe') { + $out .= ''; + } $out .= "\n"; @@ -591,12 +624,16 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no if ($donetodo) { $tmp = ''; - if (get_class($filterobj) == 'Societe') $tmp .= ''; + if (get_class($filterobj) == 'Societe') { + $tmp .= ''; + } $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : ''); $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : ''); $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : ''); //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort"); - if (get_class($filterobj) == 'Societe') $tmp .= ''; + if (get_class($filterobj) == 'Societe') { + $tmp .= ''; + } $out .= getTitleFieldOfList($tmp); } @@ -607,8 +644,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $actualCycleDate = false; - foreach ($histo as $key=>$value) - { + foreach ($histo as $key => $value) { $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo $actionstatic->type_picto = $histo[$key]['apicto']; @@ -652,8 +688,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no //} if ($user->rights->agenda->allactions->create || - (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && $user->rights->agenda->myactions->create)) - { + (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && $user->rights->agenda->myactions->create)) { $out .= ''; } @@ -671,11 +706,21 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no } } $late = 0; - if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) $late = 1; - if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) $late = 1; - if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) $late = 1; - if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) $late = 1; - if ($late) $out .= img_warning($langs->trans("Late")).' '; + if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) { + $late = 1; + } + if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) { + $late = 1; + } + if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) { + $late = 1; + } + if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) { + $late = 1; + } + if ($late) { + $out .= img_warning($langs->trans("Late")).' '; + } $out .= "\n"; // Ref @@ -683,8 +728,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no // Author of event $out .= ''; - if ($histo[$key]['userid'] > 0) - { + if ($histo[$key]['userid'] > 0) { if (!isset($userGetNomUrlCache[$histo[$key]['userid']])) { // is in cache ? $userstatic->fetch($histo[$key]['userid']); $userGetNomUrlCache[$histo[$key]['userid']] = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', ''); @@ -723,8 +767,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no if (!empty($histo[$key]['message']) && $actionstatic->code != 'AC_TICKET_CREATE' && $actionstatic->code != 'AC_TICKET_MODIFY' - ) - { + ) { $out .= '
    '; $out .= $histo[$key]['message']; $out .= '
    '; @@ -748,8 +791,9 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $contactList .= !empty($contactList) ? ', ' : ''; $contactList .= $contact->getNomUrl(1); if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') { - if (!empty($contact->phone_pro)) + if (!empty($contact->phone_pro)) { $contactList .= '('.dol_print_phone($contact->phone_pro).')'; + } } } } @@ -759,24 +803,24 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $contact = new Contact($db); $result = $contact->fetch($histo[$key]['contact_id']); - if ($result < 0) + if ($result < 0) { dol_print_error($db, $contact->error); + } if ($result > 0) { $footer .= $contact->getNomUrl(1); if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') { - if (!empty($contact->phone_pro)) + if (!empty($contact->phone_pro)) { $footer .= '('.dol_print_phone($contact->phone_pro).')'; + } } } } $documents = getTicketActionCommEcmList($actionstatic); - if (!empty($documents)) - { + if (!empty($documents)) { $footer .= '
    '; - foreach ($documents as $doc) - { + foreach ($documents as $doc) { $footer .= 'id.'" '; $footer .= ' data-path="'.$doc->filepath.'"'; @@ -819,8 +863,11 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $out .= "\n"; } - if ($noprint) return $out; - else print $out; + if ($noprint) { + return $out; + } else { + print $out; + } } /** diff --git a/htdocs/core/lib/treeview.lib.php b/htdocs/core/lib/treeview.lib.php index 9df0f8d9ddf..255bc47d9a9 100644 --- a/htdocs/core/lib/treeview.lib.php +++ b/htdocs/core/lib/treeview.lib.php @@ -38,8 +38,7 @@ function tree_showpad(&$fulltree, $key, $silent = 0) $pos = 1; // Loop on each pos, because we will output an img for each pos - while ($pos <= $fulltree[$key]['level'] && $fulltree[$key]['level'] > 0) - { + while ($pos <= $fulltree[$key]['level'] && $fulltree[$key]['level'] > 0) { // Process for column $pos $atleastoneofthislevelafter = 0; @@ -47,41 +46,41 @@ function tree_showpad(&$fulltree, $key, $silent = 0) $nbofdocinsub = 0; $found = 0; //print 'x'.$key; - foreach ($fulltree as $key2 => $val2) - { + foreach ($fulltree as $key2 => $val2) { //print "x".$pos." ".$key2." ".$found." ".$fulltree[$key2]['level']; - if ($found == 1) // We are after the entry to show - { - if ($fulltree[$key2]['level'] > $pos) - { + if ($found == 1) { // We are after the entry to show + if ($fulltree[$key2]['level'] > $pos) { $nbofdirinsub++; - if (isset($fulltree[$key2]['cachenbofdoc']) && $fulltree[$key2]['cachenbofdoc'] > 0) $nbofdocinsub += $fulltree[$key2]['cachenbofdoc']; + if (isset($fulltree[$key2]['cachenbofdoc']) && $fulltree[$key2]['cachenbofdoc'] > 0) { + $nbofdocinsub += $fulltree[$key2]['cachenbofdoc']; + } } - if ($fulltree[$key2]['level'] == $pos) - { + if ($fulltree[$key2]['level'] == $pos) { $atleastoneofthislevelafter = 1; } - if ($fulltree[$key2]['level'] <= $pos) - { + if ($fulltree[$key2]['level'] <= $pos) { break; } } - if ($key2 == $key) // We found ourself, so now every lower level will be counted - { + if ($key2 == $key) { // We found ourself, so now every lower level will be counted $found = 1; } } //print $atleastoneofthislevelafter; - if (!$silent) - { - if ($atleastoneofthislevelafter) - { - if ($fulltree[$key]['level'] == $pos) print img_picto_common('', 'treemenu/branch.gif'); - else print img_picto_common('', 'treemenu/line.gif'); + if (!$silent) { + if ($atleastoneofthislevelafter) { + if ($fulltree[$key]['level'] == $pos) { + print img_picto_common('', 'treemenu/branch.gif'); + } else { + print img_picto_common('', 'treemenu/line.gif'); + } } else { - if ($fulltree[$key]['level'] == $pos) print img_picto_common('', 'treemenu/branchbottom.gif'); - else print img_picto_common('', 'treemenu/linebottom.gif'); + if ($fulltree[$key]['level'] == $pos) { + print img_picto_common('', 'treemenu/branchbottom.gif'); + } else { + print img_picto_common('', 'treemenu/linebottom.gif'); + } } } $pos++; @@ -116,10 +115,11 @@ function tree_recur($tab, $pere, $rang, $iddivjstree = 'iddivjstree', $donoreset { global $tree_recur_alreadyadded, $menu_handler_to_search; - if ($rang == 0 && empty($donoresetalreadyloaded)) $tree_recur_alreadyadded = array(); + if ($rang == 0 && empty($donoresetalreadyloaded)) { + $tree_recur_alreadyadded = array(); + } - if ($rang == 0) - { + if ($rang == 0) { // Test also done with jstree and dynatree (not able to have inside label) print ''."\n"; - } elseif ($type == 'organization') - { + } elseif ($type == 'organization') { $companyname = $mysoc->name; $url = $mysoc->url; @@ -601,16 +596,16 @@ function getStructuredData($type, $data = array()) $ret .= '"https://www.'.$key.'.com/'.dol_escape_json($value).'"'; } $i++; - if ($i < count($mysoc->socialnetworks)) $ret .= ', '; + if ($i < count($mysoc->socialnetworks)) { + $ret .= ', '; + } } $ret .= ']'."\n"; } $ret .= '}'."\n"; $ret .= ''."\n"; - } elseif ($type == 'blogpost') - { - if (!empty($websitepage->author_alias)) - { + } elseif ($type == 'blogpost') { + if (!empty($websitepage->author_alias)) { //include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; //$tmpuser = new User($db); //$restmpuser = $tmpuser->fetch($websitepage->fk_user_creat); @@ -662,7 +657,9 @@ function getStructuredData($type, $data = array()) foreach ($arrayofkeywords as $keyword) { $ret .= '"'.dol_escape_json($keyword).'"'; $i++; - if ($i < count($arrayofkeywords)) $ret .= ', '; + if ($i < count($arrayofkeywords)) { + $ret .= ', '; + } } $ret .= '],'."\n"; } @@ -670,8 +667,7 @@ function getStructuredData($type, $data = array()) $ret .= "\n".'}'."\n"; $ret .= ''."\n"; } - } elseif ($type == 'product') - { + } elseif ($type == 'product') { $ret = ''."\n"; $ret .= ''."\n"; - } elseif ($type == 'qa') - { + } elseif ($type == 'qa') { $ret = ''."\n"; $ret .= ' " method="post"> @@ -163,18 +160,18 @@ $listofexamplesforlink = 'Societe:societe/class/societe.class.php
    Contact:con trans("Value"); ?>
    @@ -207,10 +204,10 @@ $listofexamplesforlink = 'Societe:societe/class/societe.class.php
    Contact:con
    - -multicompany->enabled) { ?> + +multicompany->enabled)) { ?> - +
    '.$langs->trans("DateCreation").''.$langs->trans("DateDeliveryPlanned").''.$langs->trans("QtyPreparedOrShipped").''.$langs->trans("Warehouse").''; - print ''; + print ''.$langs->trans("DeliveryOrder").''.$langs->trans("QtyReceived").''.$langs->trans("DeliveryDate").'
    "; - if ($objp->fk_product_type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if ($objp->fk_product_type == 1) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($objp->label)) { $text .= ' '.$objp->label.''; @@ -369,11 +385,9 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') print ''.$objp->qty_shipped.''; - if ($objp->warehouse_id > 0) - { + if ($objp->warehouse_id > 0) { $warehousestatic->fetch($objp->warehouse_id); print $warehousestatic->getNomUrl(1); } @@ -384,47 +398,47 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') /*TODO Add link to expeditiondet_batch if (! empty($conf->productbatch->enabled)) { - var_dump($objp->edrowid); - $lines[$i]->detail_batch - if (isset($lines[$i]->detail_batch)) - { - print ''; - if ($lines[$i]->product_tobatch) - { - $detail = ''; - foreach ($lines[$i]->detail_batch as $dbatch) - { + var_dump($objp->edrowid); + $lines[$i]->detail_batch + if (isset($lines[$i]->detail_batch)) + { + print ''; + if ($lines[$i]->product_tobatch) + { + $detail = ''; + foreach ($lines[$i]->detail_batch as $dbatch) + { $detail.= $langs->trans("Batch").': '.$dbatch->batch; $detail.= ' - '.$langs->trans("SellByDate").': '.dol_print_date($dbatch->sellby,"day"); $detail.= ' - '.$langs->trans("EatByDate").': '.dol_print_date($dbatch->eatby,"day"); $detail.= ' - '.$langs->trans("Qty").': '.$dbatch->qty; $detail.= '
    '; - } - print $form->textwithtooltip(img_picto('', 'object_barcode').' '.$langs->trans("DetailBatchNumber"),$detail); - } - else - { - print $langs->trans("NA"); - } - print '
    - - -
    - - - textwithpicto('', $langs->trans("ExtrafieldParamHelpselect"), 1, 0, '', 0, 2, 'helpvalue1')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpsellist"), 1, 0, '', 0, 2, 'helpvalue2')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpchkbxlst"), 1, 0, '', 0, 2, 'helpvalue3')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelplink").'

    '.$langs->trans("Examples").':
    '.$listofexamplesforlink, 1, 0, '', 0, 2, 'helpvalue4')?>
    - textwithpicto('', $langs->trans("ExtrafieldParamHelpPassword"), 1, 0, '', 0, 2, 'helpvalue5')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpSeparator"), 1, 0, '', 0, 2, 'helpvalue6')?> -
    + + +
    + + + textwithpicto('', $langs->trans("ExtrafieldParamHelpselect"), 1, 0, '', 0, 2, 'helpvalue1')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpsellist"), 1, 0, '', 0, 2, 'helpvalue2')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpchkbxlst"), 1, 0, '', 0, 2, 'helpvalue3')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelplink").'

    '.$langs->trans("Examples").':
    '.$listofexamplesforlink, 1, 0, '', 0, 2, 'helpvalue4')?>
    + textwithpicto('', $langs->trans("ExtrafieldParamHelpPassword"), 1, 0, '', 0, 2, 'helpvalue5')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpSeparator"), 1, 0, '', 0, 2, 'helpvalue6')?> +
    trans("Totalizable"); ?>>
    textwithpicto($langs->trans("HelpOnTooltip"), $langs->trans("HelpOnTooltipDesc")); ?>
    textwithpicto($langs->trans("HelpOnTooltip"), $langs->trans("HelpOnTooltipDesc")); ?>
    trans("AllEntities"); ?>>
    trans("AllEntities"); ?>>
    diff --git a/htdocs/core/tpl/admin_extrafields_edit.tpl.php b/htdocs/core/tpl/admin_extrafields_edit.tpl.php index 9e893bf93e3..73721d4c0c4 100644 --- a/htdocs/core/tpl/admin_extrafields_edit.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_edit.tpl.php @@ -27,8 +27,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -42,60 +41,58 @@ $listofexamplesforlink = 'Societe:societe/class/societe.class.php
    Contact:con @@ -144,7 +141,7 @@ $listofexamplesforlink = 'Societe:societe/class/societe.class.php
    Contact:con - + @@ -169,19 +166,16 @@ $totalizable = $extrafields->attributes[$elementtype]['totalizable'][$attrname]; $help = $extrafields->attributes[$elementtype]['help'][$attrname]; $entitycurrentorall = $extrafields->attributes[$elementtype]['entityid'][$attrname]; $printable = $extrafields->attributes[$elementtype]['printable'][$attrname]; +$enabled = $extrafields->attributes[$elementtype]['enabled'][$attrname]; -if ((($type == 'select') || ($type == 'checkbox') || ($type == 'radio')) && is_array($param)) -{ +if ((($type == 'select') || ($type == 'checkbox') || ($type == 'radio')) && is_array($param)) { $param_chain = ''; - foreach ($param['options'] as $key => $value) - { - if (strlen($key)) - { + foreach ($param['options'] as $key => $value) { + if (strlen($key)) { $param_chain .= $key.','.$value."\n"; } } -} elseif (($type == 'sellist') || ($type == 'chkbxlst') || ($type == 'link') || ($type == 'password') || ($type == 'separate')) -{ +} elseif (($type == 'sellist') || ($type == 'chkbxlst') || ($type == 'link') || ($type == 'password') || ($type == 'separate')) { $paramlist = array_keys($param['options']); $param_chain = $paramlist[0]; } @@ -214,16 +208,19 @@ if ($size <= 255 && in_array($type, array('text', 'html'))) { $typewecanchangeinto['text'][] = 'varchar'; }*/ -if (in_array($type, array_keys($typewecanchangeinto))) -{ +if (in_array($type, array_keys($typewecanchangeinto))) { $newarray = array(); print ''; print ajax_combobox('type'); @@ -243,18 +240,18 @@ if (in_array($type, array_keys($typewecanchangeinto))) trans("Value"); ?> - - -
    - - - textwithpicto('', $langs->trans("ExtrafieldParamHelpselect"), 1, 0, '', 0, 2, 'helpvalue1')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpsellist"), 1, 0, '', 0, 2, 'helpvalue2')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpchkbxlst"), 1, 0, '', 0, 2, 'helpvalue3')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelplink").'

    '.$langs->trans("Examples").':
    '.$listofexamplesforlink, 1, 0, '', 0, 2, 'helpvalue4')?>
    - textwithpicto('', $langs->trans("ExtrafieldParamHelpPassword"), 1, 0, '', 0, 2, 'helpvalue5')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpSeparator"), 1, 0, '', 0, 2, 'helpvalue6')?> -
    + + +
    + + + textwithpicto('', $langs->trans("ExtrafieldParamHelpselect"), 1, 0, '', 0, 2, 'helpvalue1')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpsellist"), 1, 0, '', 0, 2, 'helpvalue2')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpchkbxlst"), 1, 0, '', 0, 2, 'helpvalue3')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelplink").'

    '.$langs->trans("Examples").':
    '.$listofexamplesforlink, 1, 0, '', 0, 2, 'helpvalue4')?>
    + textwithpicto('', $langs->trans("ExtrafieldParamHelpPassword"), 1, 0, '', 0, 2, 'helpvalue5')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpSeparator"), 1, 0, '', 0, 2, 'helpvalue6')?> +
    @@ -298,10 +295,18 @@ if (in_array($type, array_keys($typewecanchangeinto))) textwithpicto($langs->trans("HelpOnTooltip"), $langs->trans("HelpOnTooltipDesc")); ?> -multicompany->enabled) { ?> +multicompany->enabled)) { ?> - trans("AllEntities"); ?>> + trans("AllEntities"); ?>> + + + + trans("EnabledCondition"); ?> + + + + diff --git a/htdocs/core/tpl/admin_extrafields_view.tpl.php b/htdocs/core/tpl/admin_extrafields_view.tpl.php index fb542f9037e..82b5db4f74b 100644 --- a/htdocs/core/tpl/admin_extrafields_view.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_view.tpl.php @@ -1,6 +1,6 @@ - * Copyright (C) 2012-2017 Regis Houssin + * Copyright (C) 2012-2021 Regis Houssin * Copyright (C) 2018-2019 Frédéric France * * This program is free software; you can redistribute it and/or modify @@ -25,8 +25,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } @@ -66,16 +65,19 @@ print ''.$langs->trans("AlwaysEditable").''; print ''.$form->textwithpicto($langs->trans("Visible"), $langs->trans("VisibleDesc")).''; print ''.$form->textwithpicto($langs->trans("DisplayOnPdf"), $langs->trans("DisplayOnPdfDesc")).''; print ''.$form->textwithpicto($langs->trans("Totalizable"), $langs->trans("TotalizableDesc")).''; -if ($conf->multicompany->enabled) { +if (empty($conf->multicompany->enabled)) { print ''.$langs->trans("Entities").''; } print ' '; print "\n"; -if (is_array($extrafields->attributes[$elementtype]['type']) && count($extrafields->attributes[$elementtype]['type'])) -{ - foreach ($extrafields->attributes[$elementtype]['type'] as $key => $value) - { +if (isset($extrafields->attributes[$elementtype]['type']) && is_array($extrafields->attributes[$elementtype]['type']) && count($extrafields->attributes[$elementtype]['type'])) { + foreach ($extrafields->attributes[$elementtype]['type'] as $key => $value) { + /*if (! dol_eval($extrafields->attributes[$elementtype]['enabled'][$key], 1)) { + // TODO Uncomment this to exclude extrafields of modules not enabled. Add a link to "Show extrafields disabled" + // continue; + }*/ + // Load language if required if (!empty($extrafields->attributes[$elementtype]['langfile'][$key])) { $langs->load($extrafields->attributes[$elementtype]['langfile'][$key]); @@ -97,12 +99,13 @@ if (is_array($extrafields->attributes[$elementtype]['type']) && count($extrafiel print ''.yn($extrafields->attributes[$elementtype]['totalizable'][$key])."\n"; if (!empty($conf->multicompany->enabled)) { print ''; - if (empty($extrafields->attributes[$elementtype]['entityid'][$key])) - { + if (empty($extrafields->attributes[$elementtype]['entityid'][$key])) { print $langs->trans("All"); } else { global $multicompanylabel_cache; - if (!is_array($multicompanylabel_cache)) $multicompanylabel_cache = array(); + if (!is_array($multicompanylabel_cache)) { + $multicompanylabel_cache = array(); + } if (empty($multicompanylabel_cache[$extrafields->attributes[$elementtype]['entityid'][$key]])) { global $mc; $mc->getInfo($extrafields->attributes[$elementtype]['entityid'][$key]); @@ -118,7 +121,9 @@ if (is_array($extrafields->attributes[$elementtype]['type']) && count($extrafiel } } else { $colspan = 13; - if (!empty($conf->multicompany->enabled)) $colspan++; + if (!empty($conf->multicompany->enabled)) { + $colspan++; + } print ''; print ''; diff --git a/htdocs/core/tpl/advtarget.tpl.php b/htdocs/core/tpl/advtarget.tpl.php index 590a65f1286..86292ec0ff4 100644 --- a/htdocs/core/tpl/advtarget.tpl.php +++ b/htdocs/core/tpl/advtarget.tpl.php @@ -154,7 +154,8 @@ if (!empty($array_query['cust_status'])) { } print ''; print $formadvtargetemaling->advMultiselectarray( - 'cust_status', array( + 'cust_status', + array( '0' => $langs->trans('ActivityCeased'), '1' => $langs->trans('InActivity') ), @@ -473,8 +474,9 @@ if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) { $extrafields->fetch_name_optionals_label($elementype); if (!empty($extrafields->attributes[$elementtype]['type'])) { foreach ($extrafields->attributes[$elementtype]['type'] as $key => &$value) { - if ($value == 'radio') + if ($value == 'radio') { $value = 'select'; + } } } if (!empty($extrafields->attributes[$elementtype]['label'])) { diff --git a/htdocs/core/tpl/ajax/fileupload_main.tpl.php b/htdocs/core/tpl/ajax/fileupload_main.tpl.php index 6b7e21b5261..a4563c7536a 100644 --- a/htdocs/core/tpl/ajax/fileupload_main.tpl.php +++ b/htdocs/core/tpl/ajax/fileupload_main.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -27,20 +26,20 @@ if (empty($conf) || !is_object($conf))
    diff --git a/htdocs/core/tpl/ajax/objectlinked_lineimport.tpl.php b/htdocs/core/tpl/ajax/objectlinked_lineimport.tpl.php index 119e27a705b..3193f3db96d 100644 --- a/htdocs/core/tpl/ajax/objectlinked_lineimport.tpl.php +++ b/htdocs/core/tpl/ajax/objectlinked_lineimport.tpl.php @@ -16,15 +16,13 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } $objectUrl = $object->getNomUrl(0, '', 0, 1); -if ($object->element == 'propal') -{ +if ($object->element == 'propal') { $objectUrl = DOL_URL_ROOT.'/comm/propal/card.php?id='.$object->id; } @@ -36,67 +34,67 @@ if ($object->element == 'propal') $(document).ready(function(){ $('.objectlinked_importbtn').click(function (e) { - e.preventDefault(); - var page = $(this).attr("href"); + e.preventDefault(); + var page = $(this).attr("href"); - var fromelement = $(this).attr("data-element"); - var fromelementid = $(this).attr("data-id"); + var fromelement = $(this).attr("data-element"); + var fromelementid = $(this).attr("data-id"); if( page != undefined && fromelement != undefined && fromelementid != undefined) { - var windowWidth = $(window).width()*0.8; //retrieve current window width - var windowHeight = $(window).height()*0.8; //retrieve current window height + var windowWidth = $(window).width()*0.8; //retrieve current window width + var windowHeight = $(window).height()*0.8; //retrieve current window height var htmlLines; var formId = "ajaxloaded_tablelinesform_" + fromelement + "_" + fromelementid; - $.get(page, function (data) { - htmlLines = $(data).find('#tablelines') ; - }); + $.get(page, function (data) { + htmlLines = $(data).find('#tablelines') ; + }); - var $dialog = $('') - .load( page + " #tablelines", function() { + var $dialog = $('
    ') + .load( page + " #tablelines", function() { - $("#" + formId + " #tablelines").prop("id", "ajaxloaded_tablelines"); // change id attribute + $("#" + formId + " #tablelines").prop("id", "ajaxloaded_tablelines"); // change id attribute - $("#" + formId + " .linecheckbox,#" + formId + " .linecheckboxtoggle").prop("checked", true); // checked by default + $("#" + formId + " .linecheckbox,#" + formId + " .linecheckboxtoggle").prop("checked", true); // checked by default - // reload checkbox toggle function - $("#" + formId + " .linecheckboxtoggle").click(function(){ - var checkBoxes = $("#" + formId + " .linecheckbox"); - checkBoxes.prop("checked", this.checked); - }); + // reload checkbox toggle function + $("#" + formId + " .linecheckboxtoggle").click(function(){ + var checkBoxes = $("#" + formId + " .linecheckbox"); + checkBoxes.prop("checked", this.checked); + }); - }) - .html(htmlLines) - .dialog({ - autoOpen: false, - modal: true, - height: windowHeight, - width: windowWidth, - title: "transnoentities('LinesToImport'); ?>", - buttons: { - "trans('Import'); ?>": function() { - $( this ).dialog( "close" ); - $("#" + formId).append(''); - $("#" + formId).append(''); - $("#" + formId).append(''); - $("#" + formId).submit(); - }, - "trans("Cancel"); ?>": function() { - $( this ).dialog( "close" ); - } - } - }); + }) + .html(htmlLines) + .dialog({ + autoOpen: false, + modal: true, + height: windowHeight, + width: windowWidth, + title: "transnoentities('LinesToImport'); ?>", + buttons: { + "trans('Import'); ?>": function() { + $( this ).dialog( "close" ); + $("#" + formId).append(''); + $("#" + formId).append(''); + $("#" + formId).append(''); + $("#" + formId).submit(); + }, + "trans("Cancel"); ?>": function() { + $( this ).dialog( "close" ); + } + } + }); - $dialog.dialog('open'); + $dialog.dialog('open'); } else { $.jnotify("trans('ErrorNoUrl'); ?>", "error", true); } - }); + }); @@ -106,7 +104,7 @@ $(document).ready(function(){ diff --git a/htdocs/core/tpl/ajaxrow.tpl.php b/htdocs/core/tpl/ajaxrow.tpl.php index 25d5f6f3526..6d6df3a5408 100644 --- a/htdocs/core/tpl/ajaxrow.tpl.php +++ b/htdocs/core/tpl/ajaxrow.tpl.php @@ -26,9 +26,8 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ - print "Error, template page can't be called as URL"; +if (empty($object) || !is_object($object)) { + print "Error, template page ".basename(__FILE__)." can't be called with no object defined."; exit; } @@ -50,13 +49,13 @@ if (GETPOST('action', 'aZ09') != 'editline' && $nboflines > 1 && $conf->browser- $(document).ready(function(){ $(".imgupforline").hide(); $(".imgdownforline").hide(); - $(".lineupdown").removeAttr('href'); - $(".tdlineupdown").css("background-image",'url(theme.'/img/grip.png'; ?>)'); - $(".tdlineupdown").css("background-repeat","no-repeat"); - $(".tdlineupdown").css("background-position","center center"); + $(".lineupdown").removeAttr('href'); + $(".tdlineupdown").css("background-image",'url(theme.'/img/grip.png'; ?>)'); + $(".tdlineupdown").css("background-repeat","no-repeat"); + $(".tdlineupdown").css("background-position","center center"); - console.log("Prepare tableDnd for #"); - $("#").tableDnD({ + console.log("Prepare tableDnd for #"); + $("#").tableDnD({ onDrop: function(table, row) { var reloadpage = ""; console.log("tableDND onDrop"); @@ -100,9 +99,9 @@ $(document).ready(function(){ onDragClass: "dragClass", dragHandle: "td.tdlineupdown" }); - $(".tdlineupdown").hover( function() { $(this).addClass('showDragHandle'); }, - function() { $(this).removeClass('showDragHandle'); } - ); + $(".tdlineupdown").hover( function() { $(this).addClass('showDragHandle'); }, + function() { $(this).removeClass('showDragHandle'); } + ); }); @@ -110,7 +109,7 @@ $(document).ready(function(){ $(document).ready(function(){ $(".imgupforline").hide(); $(".imgdownforline").hide(); - $(".lineupdown").removeAttr('href'); + $(".lineupdown").removeAttr('href'); }); diff --git a/htdocs/core/tpl/bloc_comment.tpl.php b/htdocs/core/tpl/bloc_comment.tpl.php index 6dae2c713f2..bf148c2124f 100644 --- a/htdocs/core/tpl/bloc_comment.tpl.php +++ b/htdocs/core/tpl/bloc_comment.tpl.php @@ -1,8 +1,7 @@ '; print ''; print "\n"; -if ($action !== 'editcomment') -{ +if ($action !== 'editcomment') { print ''; // Description @@ -58,21 +56,17 @@ if ($action !== 'editcomment') print ''; // List of comments -if (!empty($object->comments)) -{ +if (!empty($object->comments)) { // Default color for current user $TColors = array($user->id => array('bgcolor'=>'efefef', 'color'=>'555')); $first = true; - foreach ($object->comments as $comment) - { + foreach ($object->comments as $comment) { $fk_user = $comment->fk_user_author; $userstatic->fetch($fk_user); - if (empty($TColors[$fk_user])) - { + if (empty($TColors[$fk_user])) { $bgcolor = randomColor(180, 240); - if (!empty($userstatic->color)) - { + if (!empty($userstatic->color)) { $bgcolor = $userstatic->color; } $color = (colorIsLight($bgcolor)) ? '555' : 'fff'; @@ -85,8 +79,7 @@ if (!empty($object->comments)) print '
    '; print '
    '; - if (!empty($user->photo)) - { + if (!empty($user->photo)) { print Form::showphoto('userphoto', $userstatic, 80, 0, 0, '', 'small', 0, 1).'
    '; } print $langs->trans('User').' : '.$userstatic->getNomUrl().'
    '; @@ -96,8 +89,7 @@ if (!empty($object->comments)) print '
    '; print '
    '; - if ($action === 'editcomment' && $comment->id == $idcomment) - { + if ($action === 'editcomment' && $comment->id == $idcomment) { print '
    '; print ''; print ''; @@ -107,8 +99,7 @@ if (!empty($object->comments)) } print '
    '; - if ($action === 'editcomment' && $comment->id == $idcomment) - { + if ($action === 'editcomment' && $comment->id == $idcomment) { $doleditor = new DolEditor('comment_description', $comment->description, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%'); print $doleditor->Create(1); } else { @@ -116,15 +107,13 @@ if (!empty($object->comments)) } print '
    '; // End comment-description - if ($action === 'editcomment' && $comment->id == $idcomment) - { + if ($action === 'editcomment' && $comment->id == $idcomment) { print ''; print ''; print '
    '; } else { - if ($fk_user == $user->id || $user->admin == 1) - { + if ($fk_user == $user->id || $user->admin == 1) { print '
    '; print img_picto('', 'edit.png'); print ''; diff --git a/htdocs/core/tpl/bloc_showhide.tpl.php b/htdocs/core/tpl/bloc_showhide.tpl.php index d654f2b97b3..ee67fa6b74a 100644 --- a/htdocs/core/tpl/bloc_showhide.tpl.php +++ b/htdocs/core/tpl/bloc_showhide.tpl.php @@ -18,15 +18,18 @@ */ // Protection to avoid direct call of template -if (empty($blocname)) -{ +if (empty($blocname)) { print "Error, template page can't be called as URL"; exit; } $hide = true; // Hide by default -if (isset($parameters['showblocbydefault'])) $hide = (empty($parameters['showblocbydefault']) ? true : false); -if (isset($object->extraparams[$blocname]['showhide'])) $hide = (empty($object->extraparams[$blocname]['showhide']) ? true : false); +if (isset($parameters['showblocbydefault'])) { + $hide = (empty($parameters['showblocbydefault']) ? true : false); +} +if (isset($object->extraparams[$blocname]['showhide'])) { + $hide = (empty($object->extraparams[$blocname]['showhide']) ? true : false); +} ?> diff --git a/htdocs/core/tpl/card_presend.tpl.php b/htdocs/core/tpl/card_presend.tpl.php index 5d3381b2719..de10465a736 100644 --- a/htdocs/core/tpl/card_presend.tpl.php +++ b/htdocs/core/tpl/card_presend.tpl.php @@ -33,23 +33,20 @@ if (empty($conf) || !is_object($conf)) { } -if ($action == 'presend') -{ +if ($action == 'presend') { $langs->load("mails"); $titreform = 'SendMail'; $object->fetch_projet(); - if (!in_array($object->element, array('societe', 'user', 'member'))) - { + if (!in_array($object->element, array('societe', 'user', 'member'))) { // TODO get also the main_lastdoc field of $object. If not found, try to guess with following code $ref = dol_sanitizeFileName($object->ref); include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Special case - if ($object->element == 'invoice_supplier') - { + if ($object->element == 'invoice_supplier') { $fileparams = dol_most_recent_file($diroutput.'/'.get_exdir($object->id, 2, 0, 0, $object, $object->element).$ref, preg_quote($ref, '/').'([^\-])+'); } else { $fileparams = dol_most_recent_file($diroutput.'/'.$ref, preg_quote($ref, '/').'[^\-]+'); @@ -61,17 +58,14 @@ if ($action == 'presend') // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($_REQUEST['lang_id'])) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($_REQUEST['lang_id'])) { $newlang = $_REQUEST['lang_id']; } - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; } - if (!empty($newlang)) - { + if (!empty($newlang)) { $outputlangs = new Translate('', $conf); $outputlangs->setDefaultLang($newlang); // Load traductions files required by page @@ -87,19 +81,20 @@ if ($action == 'presend') // Build document if it not exists $forcebuilddoc = true; - if (in_array($object->element, array('societe', 'user', 'member'))) $forcebuilddoc = false; - if ($object->element == 'invoice_supplier' && empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)) $forcebuilddoc = false; - if ($forcebuilddoc) // If there is no default value for supplier invoice, we do not generate file, even if modelpdf was set by a manual generation - { - if ((!$file || !is_readable($file)) && method_exists($object, 'generateDocument')) - { + if (in_array($object->element, array('societe', 'user', 'member'))) { + $forcebuilddoc = false; + } + if ($object->element == 'invoice_supplier' && empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)) { + $forcebuilddoc = false; + } + if ($forcebuilddoc) { // If there is no default value for supplier invoice, we do not generate file, even if modelpdf was set by a manual generation + if ((!$file || !is_readable($file)) && method_exists($object, 'generateDocument')) { $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) { dol_print_error($db, $object->error, $object->errors); exit(); } - if ($object->element == 'invoice_supplier') - { + if ($object->element == 'invoice_supplier') { $fileparams = dol_most_recent_file($diroutput.'/'.get_exdir($object->id, 2, 0, 0, $object, $object->element).$ref, preg_quote($ref, '/').'([^\-])+'); } else { $fileparams = dol_most_recent_file($diroutput.'/'.$ref, preg_quote($ref, '/').'[^\-]+'); @@ -123,8 +118,7 @@ if ($action == 'presend') $formmail->param['langsmodels'] = (empty($newlang) ? $langs->defaultlang : $newlang); $formmail->fromtype = (GETPOST('fromtype') ?GETPOST('fromtype') : (!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE) ? $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE : 'user')); - if ($formmail->fromtype === 'user') - { + if ($formmail->fromtype === 'user') { $formmail->fromid = $user->id; } @@ -145,8 +139,7 @@ if ($action == 'presend') } $formmail->trackid = $trackid; - if (!empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { + if (!empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) { // If bit 2 is set include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $formmail->frommail = dolAddEmailTrackId($formmail->frommail, $trackid); } @@ -170,8 +163,7 @@ if ($action == 'presend') if (!empty($object->socid) && $object->socid > 0 && !is_object($object->thirdparty) && method_exists($object, 'fetch_thirdparty')) { $object->fetch_thirdparty(); } - if (is_object($object->thirdparty)) - { + if (is_object($object->thirdparty)) { foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key => $value) { $liste[$key] = $value; } @@ -206,7 +198,9 @@ if ($action == 'presend') $formmail->withcancel = 1; //$arrayoffamiliestoexclude=array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...); - if (!isset($arrayoffamiliestoexclude)) $arrayoffamiliestoexclude = null; + if (!isset($arrayoffamiliestoexclude)) { + $arrayoffamiliestoexclude = null; + } // Make substitution in email content $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, $arrayoffamiliestoexclude, $object); @@ -275,6 +269,9 @@ if ($action == 'presend') foreach ($contactarr as $contact) { $contactstatic->fetch($contact['id']); $substitutionarray['__CONTACT_NAME_'.$contact['code'].'__'] = $contactstatic->getFullName($outputlangs, 1); + $substitutionarray['__CONTACT_LASTNAME_'.$contact['code'].'__'] = $contactstatic->lastname; + $substitutionarray['__CONTACT_FIRSTNAME_'.$contact['code'].'__'] = $contactstatic->firstname; + $substitutionarray['__CONTACT_TITLE_'.$contact['code'].'__'] = $contactstatic->getCivilityLabel(); } } diff --git a/htdocs/core/tpl/commonfields_add.tpl.php b/htdocs/core/tpl/commonfields_add.tpl.php index 388b4b63926..639be537dba 100644 --- a/htdocs/core/tpl/commonfields_add.tpl.php +++ b/htdocs/core/tpl/commonfields_add.tpl.php @@ -23,8 +23,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -35,34 +34,59 @@ if (empty($conf) || !is_object($conf)) $object->fields = dol_sort_array($object->fields, 'position'); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // Discard if extrafield is a hidden field on form - if (abs($val['visible']) != 1 && abs($val['visible']) != 3) continue; + if (abs($val['visible']) != 1 && abs($val['visible']) != 3) { + continue; + } - if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) continue; // We don't want this field + if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) { + continue; // We don't want this field + } - print ''; + print ''; print ''; - if (!empty($val['help'])) print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); - else print $langs->trans($val['label']); + if (!empty($val['help'])) { + print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); + } else { + print $langs->trans($val['label']); + } print ''; - print ''; - if (!empty($val['picto'])) { print img_picto('', $val['picto']); } - if (in_array($val['type'], array('int', 'integer'))) $value = GETPOST($key, 'int'); - elseif ($val['type'] == 'double') $value = price2num(GETPOST($key, 'alphanohtml')); - elseif ($val['type'] == 'text' || $val['type'] == 'html') $value = GETPOST($key, 'restricthtml'); - elseif ($val['type'] == 'date') $value = dol_mktime(12, 0, 0, GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int')); - elseif ($val['type'] == 'datetime') $value = dol_mktime(GETPOST($key.'hour', 'int'), GETPOST($key.'min', 'int'), 0, GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int')); - elseif ($val['type'] == 'boolean') $value = (GETPOST($key) == 'on' ? 1 : 0); - else $value = GETPOST($key, 'alphanohtml'); - if ($val['noteditable']) print $object->showOutputField($val, $key, $value, '', '', '', 0); - else print $object->showInputField($val, $key, $value, '', '', '', 0); + print ''; + if (!empty($val['picto'])) { + print img_picto('', $val['picto']); + } + if (in_array($val['type'], array('int', 'integer'))) { + $value = GETPOST($key, 'int'); + } elseif ($val['type'] == 'double') { + $value = price2num(GETPOST($key, 'alphanohtml')); + } elseif ($val['type'] == 'text' || $val['type'] == 'html') { + $value = GETPOST($key, 'restricthtml'); + } elseif ($val['type'] == 'date') { + $value = dol_mktime(12, 0, 0, GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int')); + } elseif ($val['type'] == 'datetime') { + $value = dol_mktime(GETPOST($key.'hour', 'int'), GETPOST($key.'min', 'int'), 0, GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int')); + } elseif ($val['type'] == 'boolean') { + $value = (GETPOST($key) == 'on' ? 1 : 0); + } elseif ($val['type'] == 'price') { + $value = price2num(GETPOST($key)); + } else { + $value = GETPOST($key, 'alphanohtml'); + } + if ($val['noteditable']) { + print $object->showOutputField($val, $key, $value, '', '', '', 0); + } else { + print $object->showInputField($val, $key, $value, '', '', '', 0); + } print ''; print ''; } diff --git a/htdocs/core/tpl/commonfields_edit.tpl.php b/htdocs/core/tpl/commonfields_edit.tpl.php index 76a9fafe417..65b8b566180 100644 --- a/htdocs/core/tpl/commonfields_edit.tpl.php +++ b/htdocs/core/tpl/commonfields_edit.tpl.php @@ -22,12 +22,13 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } -if (!is_object($form)) $form = new Form($db); +if (!is_object($form)) { + $form = new Form($db); +} ?> @@ -35,26 +36,40 @@ if (!is_object($form)) $form = new Form($db); $object->fields = dol_sort_array($object->fields, 'position'); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // Discard if extrafield is a hidden field on form - if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4) continue; + if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4) { + continue; + } - if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) continue; // We don't want this field + if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) { + continue; // We don't want this field + } - print ''; - if (!empty($val['help'])) print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); - else print $langs->trans($val['label']); + if (!empty($val['help'])) { + print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); + } else { + print $langs->trans($val['label']); + } print ''; - print ''; - if (!empty($val['picto'])) { print img_picto('', $val['picto']); } - if (in_array($val['type'], array('int', 'integer'))) $value = GETPOSTISSET($key) ?GETPOST($key, 'int') : $object->$key; - elseif ($val['type'] == 'double') $value = GETPOSTISSET($key) ? price2num(GETPOST($key, 'alphanohtml')) : $object->$key; - elseif (preg_match('/^(text|html)/', $val['type'])) { + print ''; + if (!empty($val['picto'])) { + print img_picto('', $val['picto']); + } + if (in_array($val['type'], array('int', 'integer'))) { + $value = GETPOSTISSET($key) ?GETPOST($key, 'int') : $object->$key; + } elseif ($val['type'] == 'double') { + $value = GETPOSTISSET($key) ? price2num(GETPOST($key, 'alphanohtml')) : $object->$key; + } elseif (preg_match('/^(text|html)/', $val['type'])) { $tmparray = explode(':', $val['type']); if (!empty($tmparray[1])) { $check = $tmparray[1]; @@ -62,11 +77,17 @@ foreach ($object->fields as $key => $val) $check = 'restricthtml'; } $value = GETPOSTISSET($key) ? GETPOST($key, $check) : $object->$key; + } elseif ($val['type'] == 'price') { + $value = price2num(GETPOST($key)); + } else { + $value = GETPOSTISSET($key) ? GETPOST($key, 'alpha') : $object->$key; } - else $value = GETPOSTISSET($key) ? GETPOST($key, 'alpha') : $object->$key; //var_dump($val.' '.$key.' '.$value); - if ($val['noteditable']) print $object->showOutputField($val, $key, $value, '', '', '', 0); - else print $object->showInputField($val, $key, $value, '', '', '', 0); + if ($val['noteditable']) { + print $object->showOutputField($val, $key, $value, '', '', '', 0); + } else { + print $object->showInputField($val, $key, $value, '', '', '', 0); + } print ''; print ''; } diff --git a/htdocs/core/tpl/commonfields_view.tpl.php b/htdocs/core/tpl/commonfields_view.tpl.php index 5f58ba9e7e9..0e661c6e078 100644 --- a/htdocs/core/tpl/commonfields_view.tpl.php +++ b/htdocs/core/tpl/commonfields_view.tpl.php @@ -24,12 +24,13 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } -if (!is_object($form)) $form = new Form($db); +if (!is_object($form)) { + $form = new Form($db); +} ?> @@ -37,34 +38,54 @@ if (!is_object($form)) $form = new Form($db); $object->fields = dol_sort_array($object->fields, 'position'); -foreach ($object->fields as $key => $val) -{ - if (!empty($keyforbreak) && $key == $keyforbreak) break; // key used for break on second column +foreach ($object->fields as $key => $val) { + if (!empty($keyforbreak) && $key == $keyforbreak) { + break; // key used for break on second column + } // Discard if extrafield is a hidden field on form - if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4 && abs($val['visible']) != 5) continue; + if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4 && abs($val['visible']) != 5) { + continue; + } - if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) continue; // We don't want this field - if (in_array($key, array('ref', 'status'))) continue; // Ref and status are already in dol_banner + if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) { + continue; // We don't want this field + } + if (in_array($key, array('ref', 'status'))) { + continue; // Ref and status are already in dol_banner + } $value = $object->$key; - print ''; - if (!empty($val['help'])) print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); - else print $langs->trans($val['label']); + if (!empty($val['help'])) { + print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); + } else { + print $langs->trans($val['label']); + } print ''; - print ''; - if (in_array($val['type'], array('text', 'html'))) print '
    '; + if (in_array($val['type'], array('text', 'html'))) { + print '
    '; + } print $object->showOutputField($val, $key, $value, '', '', '', 0); //print dol_escape_htmltag($object->$key, 1, 1); - if (in_array($val['type'], array('text', 'html'))) print '
    '; + if (in_array($val['type'], array('text', 'html'))) { + print '
    '; + } print ''; print ''; } @@ -79,10 +100,8 @@ print '
    '; print ''; $alreadyoutput = 1; -foreach ($object->fields as $key => $val) -{ - if ($alreadyoutput) - { +foreach ($object->fields as $key => $val) { + if ($alreadyoutput) { if (!empty($keyforbreak) && $key == $keyforbreak) { $alreadyoutput = 0; // key used for break on second column } else { @@ -91,29 +110,48 @@ foreach ($object->fields as $key => $val) } // Discard if extrafield is a hidden field on form - if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4 && abs($val['visible']) != 5) continue; + if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4 && abs($val['visible']) != 5) { + continue; + } - if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) continue; // We don't want this field - if (in_array($key, array('ref', 'status'))) continue; // Ref and status are already in dol_banner + if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) { + continue; // We don't want this field + } + if (in_array($key, array('ref', 'status'))) { + continue; // Ref and status are already in dol_banner + } $value = $object->$key; print ''; - if (!empty($val['help'])) print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); - else print $langs->trans($val['label']); + if (!empty($val['help'])) { + print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); + } else { + print $langs->trans($val['label']); + } print ''; print ''; print ''; } diff --git a/htdocs/core/tpl/contacts.tpl.php b/htdocs/core/tpl/contacts.tpl.php index e3c45b788c6..4c57ec953d4 100644 --- a/htdocs/core/tpl/contacts.tpl.php +++ b/htdocs/core/tpl/contacts.tpl.php @@ -24,8 +24,7 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page can't be called as URL"; exit; } @@ -73,8 +72,7 @@ $userstatic = new User($db); '."\n"; print '
    '."\n"; @@ -91,15 +89,16 @@ if ($permission)
    " /> - '; ?> + '; + } ?>
    global->MAIN_INFO_SOCIETE_NOM; ?>
    @@ -107,14 +106,16 @@ if ($permission)
    element == 'shipping' || $object->element == 'reception') && is_object($objectsrc)) $tmpobject = $objectsrc; + if (($object->element == 'shipping' || $object->element == 'reception') && is_object($objectsrc)) { + $tmpobject = $objectsrc; + } $formcompany->selectTypeContact($tmpobject, '', 'type', 'internal'); ?>
     
    ">
    - id; ?>" /> - '; ?> + '; + } ?>
    socid; ?> @@ -145,8 +147,7 @@ if ($permission) $nbofcontacts = $form->num; $newcardbutton = ''; - if (!empty($object->socid) && $object->socid > 1 && $user->rights->societe->creer) - { + if (!empty($object->socid) && $object->socid > 1 && $user->rights->societe->creer) { $newcardbutton .= ''; } print $newcardbutton; @@ -155,17 +156,21 @@ if ($permission)
    element == 'shipping' || $object->element == 'reception') && is_object($objectsrc)) $tmpobject = $objectsrc; + if (($object->element == 'shipping' || $object->element == 'reception') && is_object($objectsrc)) { + $tmpobject = $objectsrc; + } $formcompany->selectTypeContact($tmpobject, $preselectedtypeofcontact, 'typecontact', 'external', 'position', 0, 'minwidth100imp'); ?>
     
    - "> + ">
    - "; @@ -179,17 +184,14 @@ if ($permission) // TODO: replace this with direct SQL string to use $db->sort($sortfield, $sortorder) $list = array(); -foreach (array('internal', 'external') as $source) -{ - if (($object->element == 'shipping' || $object->element == 'reception') && is_object($objectsrc)) - { +foreach (array('internal', 'external') as $source) { + if (($object->element == 'shipping' || $object->element == 'reception') && is_object($objectsrc)) { $contactlist = $objectsrc->liste_contact(-1, $source); } else { $contactlist = $object->liste_contact(-1, $source); } - foreach ($contactlist as $contact) - { + foreach ($contactlist as $contact) { $entry = new stdClass(); $entry->id = $contact['rowid']; $entry->type = $contact['libelle']; @@ -200,15 +202,13 @@ foreach (array('internal', 'external') as $source) $entry->contact_name = ""; $entry->status = ""; - if ($contact['source'] == 'internal') - { + if ($contact['source'] == 'internal') { $entry->nature = $langs->trans("User"); } elseif ($contact['source'] == 'external') { $entry->nature = $langs->trans("ThirdPartyContact"); } - if ($contact['socid'] > 0) - { + if ($contact['socid'] > 0) { $companystatic->fetch($contact['socid']); $entry->thirdparty_html = $companystatic->getNomUrl(1); $entry->thirdparty_name = strtolower($companystatic->getFullName($langs)); @@ -217,8 +217,7 @@ foreach (array('internal', 'external') as $source) $entry->thirdparty_name = strtolower($conf->global->MAIN_INFO_SOCIETE_NOM); } - if ($contact['source'] == 'internal') - { + if ($contact['source'] == 'internal') { $userstatic->fetch($contact['id']); $entry->contact_html = $userstatic->getNomUrl(-1, '', 0, 0, 0, 0, '', 'valignmiddle'); $entry->contact_name = strtolower($userstatic->getFullName($langs)); @@ -228,8 +227,7 @@ foreach (array('internal', 'external') as $source) $entry->contact_name = strtolower($contactstatic->getFullName($langs)); } - if ($contact['source'] == 'internal') - { + if ($contact['source'] == 'internal') { $entry->status = $userstatic->LibStatut($contact['statuscontact'], 3); } elseif ($contact['source'] == 'external') { $entry->status = $contactstatic->LibStatut($contact['statuscontact'], 3); @@ -243,8 +241,12 @@ foreach (array('internal', 'external') as $source) $sortfield = GETPOST("sortfield", "aZ09comma"); $sortorder = GETPOST("sortorder", 'aZ09comma'); -if (!$sortfield) $sortfield = "nature"; -if (!$sortorder) $sortorder = "asc"; +if (!$sortfield) { + $sortfield = "nature"; +} +if (!$sortorder) { + $sortorder = "asc"; +} // Re-sort list $list = dol_sort_array($list, $sortfield, $sortorder, 1, 0, 1); @@ -286,8 +288,7 @@ print_liste_field_titre($arrayfields['status']['label'], $_SERVER["PHP_SELF"], " print_liste_field_titre('', $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder, 'center maxwidthsearch '); print ""; -foreach ($list as $entry) -{ +foreach ($list as $entry) { print '
    '; print ''; @@ -296,8 +297,7 @@ foreach ($list as $entry) print ''; print ''; - if ($permission) - { + if ($permission) { $href = $_SERVER["PHP_SELF"]; $href .= '?id='.$object->id; $href .= '&action=deletecontact&token='.newToken(); diff --git a/htdocs/core/tpl/document_actions_post_headers.tpl.php b/htdocs/core/tpl/document_actions_post_headers.tpl.php index 80fd0d7df12..0dc0962af56 100644 --- a/htdocs/core/tpl/document_actions_post_headers.tpl.php +++ b/htdocs/core/tpl/document_actions_post_headers.tpl.php @@ -30,25 +30,32 @@ // $savingdocmask = dol_sanitizeFileName($object->ref).'-__file__'; // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } $langs->load("link"); -if (empty($relativepathwithnofile)) $relativepathwithnofile = ''; +if (empty($relativepathwithnofile)) { + $relativepathwithnofile = ''; +} -if (!isset($permission)) $permission = $permissiontoadd; -if (!isset($permtoedit)) $permtoedit = $permissiontoadd; +if (!isset($permission)) { + $permission = $permissiontoadd; +} +if (!isset($permtoedit)) { + $permtoedit = $permissiontoadd; +} // Drag and drop for up and down allowed on product, thirdparty, ... // The drag and drop call the page core/ajax/row.php // If you enable the move up/down of files here, check that page that include template set its sortorder on 'position_name' instead of 'name' // Also the object->fk_element must be defined. $disablemove = 1; -if (in_array($modulepart, array('product', 'produit', 'societe', 'user', 'ticket', 'holiday', 'expensereport'))) $disablemove = 0; +if (in_array($modulepart, array('product', 'produit', 'societe', 'user', 'ticket', 'holiday', 'expensereport'))) { + $disablemove = 0; +} @@ -56,17 +63,16 @@ if (in_array($modulepart, array('product', 'produit', 'societe', 'user', 'ticket * Confirm form to delete */ -if ($action == 'delete') -{ +if ($action == 'delete') { $langs->load("companies"); // Need for string DeleteFile+ConfirmDeleteFiles print $form->formconfirm( - $_SERVER["PHP_SELF"].'?id='.$object->id.'&urlfile='.urlencode(GETPOST("urlfile")).'&linkid='.GETPOST('linkid', 'int').(empty($param) ? '' : $param), - $langs->trans('DeleteFile'), - $langs->trans('ConfirmDeleteFile'), - 'confirm_deletefile', - '', - 0, - 1 + $_SERVER["PHP_SELF"].'?id='.$object->id.'&urlfile='.urlencode(GETPOST("urlfile")).'&linkid='.GETPOST('linkid', 'int').(empty($param) ? '' : $param), + $langs->trans('DeleteFile'), + $langs->trans('ConfirmDeleteFile'), + 'confirm_deletefile', + '', + 0, + 1 ); } @@ -99,8 +105,7 @@ if (!isset($savingdocmask) || !empty($conf->global->MAIN_DISABLE_SUGGEST_REF_AS_ 'product_batch', 'bom', 'mrp' - ))) - { + ))) { $savingdocmask = dol_sanitizeFileName($object->ref).'-__file__'; } /*if (in_array($modulepart,array('member'))) diff --git a/htdocs/core/tpl/extrafields_add.tpl.php b/htdocs/core/tpl/extrafields_add.tpl.php index 53cbe3d99cf..f194a177178 100644 --- a/htdocs/core/tpl/extrafields_add.tpl.php +++ b/htdocs/core/tpl/extrafields_add.tpl.php @@ -26,8 +26,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -37,13 +36,17 @@ if (empty($conf) || !is_object($conf)) executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { $params = array(); - if (isset($tpl_context)) $params['tpl_context'] = $tpl_context; + if (isset($tpl_context)) { + $params['tpl_context'] = $tpl_context; + } $params['cols'] = $parameters['colspanvalue']; print $object->showOptionals($extrafields, 'create', $params); } diff --git a/htdocs/core/tpl/extrafields_edit.tpl.php b/htdocs/core/tpl/extrafields_edit.tpl.php index dbc2b9745cd..5915fb8a633 100644 --- a/htdocs/core/tpl/extrafields_edit.tpl.php +++ b/htdocs/core/tpl/extrafields_edit.tpl.php @@ -26,8 +26,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -37,7 +36,9 @@ if (empty($conf) || !is_object($conf)) executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { diff --git a/htdocs/core/tpl/extrafields_list_array_fields.tpl.php b/htdocs/core/tpl/extrafields_list_array_fields.tpl.php index d2d77cf3b5c..ebab4e8608a 100644 --- a/htdocs/core/tpl/extrafields_list_array_fields.tpl.php +++ b/htdocs/core/tpl/extrafields_list_array_fields.tpl.php @@ -1,24 +1,26 @@ '."\n"; +// This tpl file is included into the init part of pages, so before action. +// So no output must be done. // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } -if (empty($extrafieldsobjectkey) && is_object($object)) $extrafieldsobjectkey = $object->table_element; +if (empty($extrafieldsobjectkey) && is_object($object)) { + $extrafieldsobjectkey = $object->table_element; +} // Loop to show all columns of extrafields from $obj, $extrafields and $db -if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... -{ - if (is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label']) > 0) { - if (empty($extrafieldsobjectprefix)) $extrafieldsobjectprefix = 'ef.'; +if (!empty($extrafieldsobjectkey)) { // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... + if (isset($extrafields->attributes[$extrafieldsobjectkey]['label']) && is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label']) > 0) { + if (empty($extrafieldsobjectprefix)) { + $extrafieldsobjectprefix = 'ef.'; + } foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) { - if (!empty($extrafields->attributes[$extrafieldsobjectkey]['list'][$key])) + if (!empty($extrafields->attributes[$extrafieldsobjectkey]['list'][$key])) { $arrayfields[$extrafieldsobjectprefix.$key] = array( 'label' => $extrafields->attributes[$extrafieldsobjectkey]['label'][$key], 'checked' => (($extrafields->attributes[$extrafieldsobjectkey]['list'][$key] < 0) ? 0 : 1), @@ -27,6 +29,7 @@ if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_e 'langfile' => $extrafields->attributes[$extrafieldsobjectkey]['langfile'][$key], 'help' => $extrafields->attributes[$extrafieldsobjectkey]['help'][$key], ); + } } } } diff --git a/htdocs/core/tpl/extrafields_list_print_fields.tpl.php b/htdocs/core/tpl/extrafields_list_print_fields.tpl.php index 8c46e34b428..5ea0e4821d6 100644 --- a/htdocs/core/tpl/extrafields_list_print_fields.tpl.php +++ b/htdocs/core/tpl/extrafields_list_print_fields.tpl.php @@ -1,37 +1,36 @@ table_element; +if (empty($extrafieldsobjectkey) && is_object($object)) { + $extrafieldsobjectkey = $object->table_element; +} // Loop to show all columns of extrafields from $obj, $extrafields and $db -if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... -{ - if (is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) - { - if (empty($extrafieldsobjectprefix)) $extrafieldsobjectprefix = 'ef.'; +if (!empty($extrafieldsobjectkey)) { // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... + if (is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) { + if (empty($extrafieldsobjectprefix)) { + $extrafieldsobjectprefix = 'ef.'; + } - foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) - { - if (!empty($arrayfields[$extrafieldsobjectprefix.$key]['checked'])) - { + foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) { + if (!empty($arrayfields[$extrafieldsobjectprefix.$key]['checked'])) { $align = $extrafields->getAlignFlag($key, $extrafieldsobjectkey); print ''; $tmpkey = 'options_'.$key; - if (in_array($extrafields->attributes[$extrafieldsobjectkey]['type'][$key], array('date', 'datetime', 'timestamp')) && !is_numeric($obj->$tmpkey)) - { + if (in_array($extrafields->attributes[$extrafieldsobjectkey]['type'][$key], array('date', 'datetime', 'timestamp')) && !is_numeric($obj->$tmpkey)) { $datenotinstring = $obj->$tmpkey; - if (!is_numeric($obj->$tmpkey)) // For backward compatibility - { + if (!is_numeric($obj->$tmpkey)) { // For backward compatibility $datenotinstring = $db->jdate($datenotinstring); } $value = $datenotinstring; @@ -39,8 +38,7 @@ if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_e $value = $obj->$tmpkey; } // If field is a computed field, we make computation to get value - if ($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key]) - { + if ($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key]) { //global $obj, $object; //var_dump($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key]); //var_dump($obj); @@ -51,18 +49,23 @@ if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_e print $extrafields->showOutputField($key, $value, '', $extrafieldsobjectkey); print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } if ($extrafields->attributes[$extrafieldsobjectkey]['totalizable'][$key]) { if (!$i) { // we keep position for the first line $totalarray['totalizable'][$key]['pos'] = $totalarray['nbfield']; } - if (is_numeric($obj->$tmpkey)) $totalarray['totalizable'][$key]['total'] += $obj->$tmpkey; + if (is_numeric($obj->$tmpkey)) { + $totalarray['totalizable'][$key]['total'] += $obj->$tmpkey; + } } - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = $extrafieldsobjectprefix.$tmpkey; + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = $extrafieldsobjectprefix.$tmpkey; + } $totalarray['val'][$extrafieldsobjectprefix.$tmpkey] += $obj->$tmpkey; } } diff --git a/htdocs/core/tpl/extrafields_list_search_input.tpl.php b/htdocs/core/tpl/extrafields_list_search_input.tpl.php index d69c045641d..77329eb06a4 100644 --- a/htdocs/core/tpl/extrafields_list_search_input.tpl.php +++ b/htdocs/core/tpl/extrafields_list_search_input.tpl.php @@ -3,44 +3,50 @@ print ''."\n"; // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } -if (empty($extrafieldsobjectkey) && is_object($object)) $extrafieldsobjectkey = $object->table_element; +if (empty($extrafieldsobjectkey) && is_object($object)) { + $extrafieldsobjectkey = $object->table_element; +} // Loop to show all columns of extrafields for the search title line -if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... -{ - if (!empty($extrafields->attributes[$extrafieldsobjectkey]['label']) && is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) - { - if (empty($extrafieldsobjectprefix)) $extrafieldsobjectprefix = 'ef.'; - if (empty($search_options_pattern)) $search_options_pattern = 'search_options_'; +if (!empty($extrafieldsobjectkey)) { // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... + if (!empty($extrafields->attributes[$extrafieldsobjectkey]['label']) && is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) { + if (empty($extrafieldsobjectprefix)) { + $extrafieldsobjectprefix = 'ef.'; + } + if (empty($search_options_pattern)) { + $search_options_pattern = 'search_options_'; + } - foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) - { + foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) { if (!empty($arrayfields[$extrafieldsobjectprefix.$key]['checked'])) { $align = $extrafields->getAlignFlag($key); $typeofextrafield = $extrafields->attributes[$extrafieldsobjectkey]['type'][$key]; print ''; diff --git a/htdocs/core/tpl/extrafields_list_search_param.tpl.php b/htdocs/core/tpl/extrafields_list_search_param.tpl.php index 5fca6bc70a9..56652b87dd3 100644 --- a/htdocs/core/tpl/extrafields_list_search_param.tpl.php +++ b/htdocs/core/tpl/extrafields_list_search_param.tpl.php @@ -1,19 +1,18 @@ table_element like 'societe', 'socpeople', ... -{ - if (empty($search_options_pattern)) $search_options_pattern = 'search_options_'; +if (!empty($search_array_options) && is_array($search_array_options)) { // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... + if (empty($search_options_pattern)) { + $search_options_pattern = 'search_options_'; + } - foreach ($search_array_options as $key => $val) - { + foreach ($search_array_options as $key => $val) { $crit = $val; $tmpkey = preg_replace('/'.$search_options_pattern.'/', '', $key); if (is_array($val) && array_key_exists('start', $val) && array_key_exists('end', $val)) { @@ -32,6 +31,8 @@ if (!empty($search_array_options) && is_array($search_array_options)) // $extraf $param .= '&' . $search_options_pattern.$tmpkey.'_endmin=' . dol_print_date($val['end'], '%M'); $val = ''; } - if ($val != '') $param .= '&'.$search_options_pattern.$tmpkey.'='.urlencode($val); + if ($val != '') { + $param .= '&'.$search_options_pattern.$tmpkey.'='.urlencode($val); + } } } diff --git a/htdocs/core/tpl/extrafields_list_search_sql.tpl.php b/htdocs/core/tpl/extrafields_list_search_sql.tpl.php index b0fb03f2709..7268da76007 100644 --- a/htdocs/core/tpl/extrafields_list_search_sql.tpl.php +++ b/htdocs/core/tpl/extrafields_list_search_sql.tpl.php @@ -1,28 +1,30 @@ table_element; +if (empty($extrafieldsobjectkey) && is_object($object)) { + $extrafieldsobjectkey = $object->table_element; +} // Loop to complete the sql search criterias from extrafields -if (!empty($extrafieldsobjectkey) && !empty($search_array_options) && is_array($search_array_options)) // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... -{ - if (empty($extrafieldsobjectprefix)) $extrafieldsobjectprefix = 'ef.'; - if (empty($search_options_pattern)) $search_options_pattern = 'search_options_'; +if (!empty($extrafieldsobjectkey) && !empty($search_array_options) && is_array($search_array_options)) { // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... + if (empty($extrafieldsobjectprefix)) { + $extrafieldsobjectprefix = 'ef.'; + } + if (empty($search_options_pattern)) { + $search_options_pattern = 'search_options_'; + } - foreach ($search_array_options as $key => $val) - { + foreach ($search_array_options as $key => $val) { $crit = $val; $tmpkey = preg_replace('/'.$search_options_pattern.'/', '', $key); $typ = $extrafields->attributes[$extrafieldsobjectkey]['type'][$tmpkey]; - if ($crit != '' && in_array($typ, array('date', 'datetime', 'timestamp'))) - { + if ($crit != '' && in_array($typ, array('date', 'datetime', 'timestamp'))) { if (is_numeric($crit)) { $sql .= " AND ".$extrafieldsobjectprefix.$tmpkey." = '".$db->idate($crit)."'"; } elseif (is_array($crit)) { @@ -34,22 +36,31 @@ if (!empty($extrafieldsobjectkey) && !empty($search_array_options) && is_array($ $sql .= ' AND ('.$extrafieldsobjectprefix.$tmpkey." <= '". $db->idate($crit['end'])."')"; } } - } elseif (in_array($typ, array('boolean'))) - { + } elseif (in_array($typ, array('boolean'))) { if ($crit !== '-1' && $crit !== '') { $sql .= " AND (".$extrafieldsobjectprefix.$tmpkey." = '".$db->escape($crit)."'"; - if ($crit == '0') $sql .= " OR ".$extrafieldsobjectprefix.$tmpkey." IS NULL"; + if ($crit == '0') { + $sql .= " OR ".$extrafieldsobjectprefix.$tmpkey." IS NULL"; + } $sql .= ")"; } - } elseif ($crit != '' && (!in_array($typ, array('select', 'sellist')) || $crit != '0') && (!in_array($typ, array('link')) || $crit != '-1')) - { + } elseif ($crit != '' && (!in_array($typ, array('select', 'sellist')) || $crit != '0') && (!in_array($typ, array('link')) || $crit != '-1')) { $mode_search = 0; - if (in_array($typ, array('int', 'double', 'real', 'price'))) $mode_search = 1; // Search on a numeric - if (in_array($typ, array('sellist', 'link')) && $crit != '0' && $crit != '-1') $mode_search = 2; // Search on a foreign key int - if (in_array($typ, array('sellist')) && !is_numeric($crit)) $mode_search = 0;// Search on a foreign key string - if (in_array($typ, array('chkbxlst', 'checkbox'))) $mode_search = 4; // Search on a multiselect field with sql type = text - if (is_array($crit)) $crit = implode(' ', $crit); // natural_search() expects a string - elseif ($typ === 'select' and is_string($crit) and strpos($crit, ' ') === false) { + if (in_array($typ, array('int', 'double', 'real', 'price'))) { + $mode_search = 1; // Search on a numeric + } + if (in_array($typ, array('sellist', 'link')) && $crit != '0' && $crit != '-1') { + $mode_search = 2; // Search on a foreign key int + } + if (in_array($typ, array('sellist')) && !is_numeric($crit)) { + $mode_search = 0;// Search on a foreign key string + } + if (in_array($typ, array('chkbxlst', 'checkbox'))) { + $mode_search = 4; // Search on a multiselect field with sql type = text + } + if (is_array($crit)) { + $crit = implode(' ', $crit); // natural_search() expects a string + } elseif ($typ === 'select' and is_string($crit) and strpos($crit, ' ') === false) { $sql .= ' AND ('.$extrafieldsobjectprefix.$tmpkey.' = "'.$db->escape($crit).'")'; continue; } diff --git a/htdocs/core/tpl/extrafields_list_search_title.tpl.php b/htdocs/core/tpl/extrafields_list_search_title.tpl.php index f1ea80871b8..0a61e51d33d 100644 --- a/htdocs/core/tpl/extrafields_list_search_title.tpl.php +++ b/htdocs/core/tpl/extrafields_list_search_title.tpl.php @@ -1,29 +1,32 @@ table_element; -if (!isset($disablesortlink)) $disablesortlink = 0; +if (empty($extrafieldsobjectkey) && is_object($object)) { + $extrafieldsobjectkey = $object->table_element; +} +if (!isset($disablesortlink)) { + $disablesortlink = 0; +} // Loop to show all columns of extrafields for the title line -if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... -{ - if (!empty($extrafields->attributes[$extrafieldsobjectkey]['label']) && is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) - { - if (empty($extrafieldsobjectprefix)) $extrafieldsobjectprefix = 'ef.'; +if (!empty($extrafieldsobjectkey)) { // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... + if (!empty($extrafields->attributes[$extrafieldsobjectkey]['label']) && is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) { + if (empty($extrafieldsobjectprefix)) { + $extrafieldsobjectprefix = 'ef.'; + } - foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) - { - if (!empty($arrayfields[$extrafieldsobjectprefix.$key]['checked'])) - { + foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) { + if (!empty($arrayfields[$extrafieldsobjectprefix.$key]['checked'])) { $align = $extrafields->getAlignFlag($key); $sortonfield = $extrafieldsobjectprefix.$key; - if (!empty($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key])) $sortonfield = ''; + if (!empty($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key])) { + $sortonfield = ''; + } if ($extrafields->attributes[$extrafieldsobjectkey]['type'][$key] == 'separate') { print ''; } else { diff --git a/htdocs/core/tpl/extrafields_view.tpl.php b/htdocs/core/tpl/extrafields_view.tpl.php index f8d86f2abee..3940f0c38e5 100644 --- a/htdocs/core/tpl/extrafields_view.tpl.php +++ b/htdocs/core/tpl/extrafields_view.tpl.php @@ -26,74 +26,86 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page can't be called as URL"; exit; } -if (!is_object($form)) $form = new Form($db); +if (!is_object($form)) { + $form = new Form($db); +} ?> fk_soc)) $parameters['socid'] = $object->fk_soc; +if (!is_array($parameters)) { + $parameters = array(); +} +if (!empty($cols)) { + $parameters['colspan'] = ' colspan="'.$cols.'"'; +} +if (!empty($cols)) { + $parameters['cols'] = $cols; +} +if (!empty($object->fk_soc)) { + $parameters['socid'] = $object->fk_soc; +} $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); print $hookmanager->resPrint; -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} //var_dump($extrafields->attributes[$object->table_element]); -if (empty($reshook) && is_array($extrafields->attributes[$object->table_element]['label'])) -{ +if (empty($reshook) && is_array($extrafields->attributes[$object->table_element]['label'])) { $lastseparatorkeyfound = ''; $extrafields_collapse_num = ''; $extrafields_collapse_num_old = ''; $i = 0; - foreach ($extrafields->attributes[$object->table_element]['label'] as $tmpkeyextra => $tmplabelextra) - { + foreach ($extrafields->attributes[$object->table_element]['label'] as $tmpkeyextra => $tmplabelextra) { $i++; // Discard if extrafield is a hidden field on form $enabled = 1; - if ($enabled && isset($extrafields->attributes[$object->table_element]['enabled'][$tmpkeyextra])) - { + if ($enabled && isset($extrafields->attributes[$object->table_element]['enabled'][$tmpkeyextra])) { $enabled = dol_eval($extrafields->attributes[$object->table_element]['enabled'][$tmpkeyextra], 1); } - if ($enabled && isset($extrafields->attributes[$object->table_element]['list'][$tmpkeyextra])) - { + if ($enabled && isset($extrafields->attributes[$object->table_element]['list'][$tmpkeyextra])) { $enabled = dol_eval($extrafields->attributes[$object->table_element]['list'][$tmpkeyextra], 1); } $perms = 1; - if ($perms && isset($extrafields->attributes[$object->table_element]['perms'][$tmpkeyextra])) - { + if ($perms && isset($extrafields->attributes[$object->table_element]['perms'][$tmpkeyextra])) { $perms = dol_eval($extrafields->attributes[$object->table_element]['perms'][$tmpkeyextra], 1); } //print $tmpkeyextra.'-'.$enabled.'-'.$perms.'-'.$tmplabelextra.$_POST["options_" . $tmpkeyextra].'
    '."\n"; - if (empty($enabled)) continue; // 0 = Never visible field - if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list <> 4 = not visible at the creation - if (empty($perms)) continue; // 0 = Not visible + if (empty($enabled)) { + continue; // 0 = Never visible field + } + if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) { + continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list <> 4 = not visible at the creation + } + if (empty($perms)) { + continue; // 0 = Not visible + } // Load language if required - if (!empty($extrafields->attributes[$object->table_element]['langfile'][$tmpkeyextra])) $langs->load($extrafields->attributes[$object->table_element]['langfile'][$tmpkeyextra]); - if ($action == 'edit_extras') - { + if (!empty($extrafields->attributes[$object->table_element]['langfile'][$tmpkeyextra])) { + $langs->load($extrafields->attributes[$object->table_element]['langfile'][$tmpkeyextra]); + } + if ($action == 'edit_extras') { $value = (GETPOSTISSET("options_".$tmpkeyextra) ? GETPOST("options_".$tmpkeyextra) : $object->array_options["options_".$tmpkeyextra]); } else { - $value = (!empty($object->array_options["options_".$tmpkeyextra]) ? $object->array_options["options_".$tmpkeyextra] : ''); + $value = (!empty($object->array_options["options_".$tmpkeyextra]) ? $object->array_options["options_".$tmpkeyextra] : ''); //var_dump($tmpkeyextra.' - '.$value); } // Print line tr of extra field - if ($extrafields->attributes[$object->table_element]['type'][$tmpkeyextra] == 'separate') - { + if ($extrafields->attributes[$object->table_element]['type'][$tmpkeyextra] == 'separate') { $extrafields_collapse_num = ''; $extrafield_param = $extrafields->attributes[$object->table_element]['param'][$tmpkeyextra]; if (!empty($extrafield_param) && is_array($extrafield_param)) { @@ -126,7 +138,9 @@ if (empty($reshook) && is_array($extrafields->attributes[$object->table_element] print ''; print ''; } print '
    '; - if (in_array($val['type'], array('text', 'html'))) print '
    '; + if (in_array($val['type'], array('text', 'html'))) { + print '
    '; + } print $object->showOutputField($val, $key, $value, '', '', '', 0); //print dol_escape_htmltag($object->$key, 1, 1); - if (in_array($val['type'], array('text', 'html'))) print '
    '; + if (in_array($val['type'], array('text', 'html'))) { + print '
    '; + } print '
    '.$entry->thirdparty_html.''.$entry->type.''.$entry->status.''; $tmpkey = preg_replace('/'.$search_options_pattern.'/', '', $key); - if (in_array($typeofextrafield, array('varchar', 'int', 'double')) && empty($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key])) - { + if (in_array($typeofextrafield, array('varchar', 'int', 'double')) && empty($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key])) { $searchclass = ''; - if (in_array($typeofextrafield, array('varchar'))) $searchclass = 'searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass = 'searchnum'; + if (in_array($typeofextrafield, array('varchar'))) { + $searchclass = 'searchstring'; + } + if (in_array($typeofextrafield, array('int', 'double'))) { + $searchclass = 'searchnum'; + } print ''; - } elseif (in_array($typeofextrafield, array('datetime', 'timestamp'))) - { + } elseif (in_array($typeofextrafield, array('datetime', 'timestamp'))) { $morecss = ''; echo $extrafields->showInputField($key, $search_array_options[$search_options_pattern.$tmpkey], '', '', $search_options_pattern, $morecss, 0, $extrafieldsobjectkey, 1); } else { // for the type as 'checkbox', 'chkbxlst', 'sellist' we should use code instead of id (example: I declare a 'chkbxlst' to have a link with dictionnairy, I have to extend it with the 'code' instead 'rowid') $morecss = ''; - if (in_array($typeofextrafield, array('link', 'sellist', 'text', 'html'))) $morecss = 'maxwidth200'; + if (in_array($typeofextrafield, array('link', 'sellist', 'text', 'html'))) { + $morecss = 'maxwidth200'; + } echo $extrafields->showInputField($key, $search_array_options[$search_options_pattern.$tmpkey], '', '', $search_options_pattern, $morecss, 0, $extrafieldsobjectkey, 1); } print '
    '; if (!empty($extrafields->attributes[$object->table_element]['help'][$tmpkeyextra])) { // You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click. @@ -141,23 +155,42 @@ if (empty($reshook) && is_array($extrafields->attributes[$object->table_element] //var_dump($user->rights); $permok = false; $keyforperm = $object->element; - if ($object->element == 'fichinter') $keyforperm = 'ficheinter'; - if (isset($user->rights->$keyforperm)) $permok = $user->rights->$keyforperm->creer || $user->rights->$keyforperm->create || $user->rights->$keyforperm->write; - if ($object->element == 'order_supplier') $permok = $user->rights->fournisseur->commande->creer; - if ($object->element == 'invoice_supplier') $permok = $user->rights->fournisseur->facture->creer; - if ($object->element == 'shipping') $permok = $user->rights->expedition->creer; - if ($object->element == 'delivery') $permok = $user->rights->expedition->delivery->creer; - if ($object->element == 'productlot') $permok = $user->rights->stock->creer; - if ($object->element == 'facturerec') $permok = $user->rights->facture->creer; - if ($object->element == 'mo') $permok = $user->rights->mrp->write; + if ($object->element == 'fichinter') { + $keyforperm = 'ficheinter'; + } + if (isset($user->rights->$keyforperm)) { + $permok = !empty($user->rights->$keyforperm->creer) || !empty($user->rights->$keyforperm->create) || !empty($user->rights->$keyforperm->write); + } + if ($object->element == 'order_supplier') { + $permok = $user->rights->fournisseur->commande->creer; + } + if ($object->element == 'invoice_supplier') { + $permok = $user->rights->fournisseur->facture->creer; + } + if ($object->element == 'shipping') { + $permok = $user->rights->expedition->creer; + } + if ($object->element == 'delivery') { + $permok = $user->rights->expedition->delivery->creer; + } + if ($object->element == 'productlot') { + $permok = $user->rights->stock->creer; + } + if ($object->element == 'facturerec') { + $permok = $user->rights->facture->creer; + } + if ($object->element == 'mo') { + $permok = $user->rights->mrp->write; + } $isdraft = ((isset($object->statut) && $object->statut == 0) || (isset($object->status) && $object->status == 0)); if (($isdraft || !empty($extrafields->attributes[$object->table_element]['alwayseditable'][$tmpkeyextra])) && $permok && $enabled != 5 && ($action != 'edit_extras' || GETPOST('attribute') != $tmpkeyextra) - && empty($extrafields->attributes[$object->table_element]['computed'][$tmpkeyextra])) - { + && empty($extrafields->attributes[$object->table_element]['computed'][$tmpkeyextra])) { $fieldid = 'id'; - if ($object->table_element == 'societe') $fieldid = 'socid'; + if ($object->table_element == 'societe') { + $fieldid = 'socid'; + } print ''.img_edit().'
    '; @@ -165,26 +198,34 @@ if (empty($reshook) && is_array($extrafields->attributes[$object->table_element] $html_id = !empty($object->id) ? $object->element.'_extras_'.$tmpkeyextra.'_'.$object->id : ''; - print ''; + print ''; // Convert date into timestamp format - if (in_array($extrafields->attributes[$object->table_element]['type'][$tmpkeyextra], array('date', 'datetime'))) - { + if (in_array($extrafields->attributes[$object->table_element]['type'][$tmpkeyextra], array('date'))) { $datenotinstring = $object->array_options['options_'.$tmpkeyextra]; // print 'X'.$object->array_options['options_' . $tmpkeyextra].'-'.$datenotinstring.'x'; - if (!is_numeric($object->array_options['options_'.$tmpkeyextra])) // For backward compatibility - { + if (!is_numeric($object->array_options['options_'.$tmpkeyextra])) { // For backward compatibility $datenotinstring = $db->jdate($datenotinstring); } //print 'x'.$object->array_options['options_' . $tmpkeyextra].'-'.$datenotinstring.' - '.dol_print_date($datenotinstring, 'dayhour'); - $value = GETPOSTISSET("options_".$tmpkeyextra) ? dol_mktime(GETPOST("options_".$tmpkeyextra."hour", 'int'), GETPOST("options_".$tmpkeyextra."min", 'int'), 0, GETPOST("options_".$tmpkeyextra."month", 'int'), GETPOST("options_".$tmpkeyextra."day", 'int'), GETPOST("options_".$tmpkeyextra."year", 'int')) : $datenotinstring; + $value = GETPOSTISSET("options_".$tmpkeyextra) ? dol_mktime(12, 0, 0, GETPOST("options_".$tmpkeyextra."month", 'int'), GETPOST("options_".$tmpkeyextra."day", 'int'), GETPOST("options_".$tmpkeyextra."year", 'int')) : $datenotinstring; + } + if (in_array($extrafields->attributes[$object->table_element]['type'][$tmpkeyextra], array('datetime'))) { + $datenotinstring = $object->array_options['options_'.$tmpkeyextra]; + // print 'X'.$object->array_options['options_' . $tmpkeyextra].'-'.$datenotinstring.'x'; + if (!is_numeric($object->array_options['options_'.$tmpkeyextra])) { // For backward compatibility + $datenotinstring = $db->jdate($datenotinstring); + } + //print 'x'.$object->array_options['options_' . $tmpkeyextra].'-'.$datenotinstring.' - '.dol_print_date($datenotinstring, 'dayhour'); + $value = GETPOSTISSET("options_".$tmpkeyextra) ? dol_mktime(GETPOST("options_".$tmpkeyextra."hour", 'int'), GETPOST("options_".$tmpkeyextra."min", 'int'), GETPOST("options_".$tmpkeyextra."sec", 'int'), GETPOST("options_".$tmpkeyextra."month", 'int'), GETPOST("options_".$tmpkeyextra."day", 'int'), GETPOST("options_".$tmpkeyextra."year", 'int'), 'tzuserrel') : $datenotinstring; } //TODO Improve element and rights detection - if ($action == 'edit_extras' && $permok && GETPOST('attribute', 'restricthtml') == $tmpkeyextra) - { + if ($action == 'edit_extras' && $permok && GETPOST('attribute', 'restricthtml') == $tmpkeyextra) { $fieldid = 'id'; - if ($object->table_element == 'societe') $fieldid = 'socid'; + if ($object->table_element == 'societe') { + $fieldid = 'socid'; + } print '
    '; print ''; print ''; @@ -208,8 +249,7 @@ if (empty($reshook) && is_array($extrafields->attributes[$object->table_element] // Add code to manage list depending on others // TODO Test/enhance this with a more generic solution - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print "\n"; print ' + }); + use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE include_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); $formfile->form_attach_new_file($_SERVER["PHP_SELF"], 'none', 0, ($section ? $section : -1), $permtoupload, 48, null, '', 0, '', 0, $nameforformuserfile, '', $sectiondir); -} else print ' '; +} else { + print ' '; +} print '
    '; // End "Add new file" area @@ -131,15 +127,13 @@ print '
    '; // Ask confirmation of deletion of directory -if ($action == 'delete_section') -{ +if ($action == 'delete_section') { print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.$section, $langs->trans('DeleteSection'), $langs->trans('ConfirmDeleteSection', $ecmdir->label), 'confirm_deletesection', '', '', 1); } // End confirm -if (empty($action) || $action == 'editfile' || $action == 'file_manager' || preg_match('/refresh/i', $action) || $action == 'delete') -{ +if (empty($action) || $action == 'editfile' || $action == 'file_manager' || preg_match('/refresh/i', $action) || $action == 'delete') { $langs->load("ecm"); print ''."\n"; @@ -155,14 +149,15 @@ if (empty($action) || $action == 'editfile' || $action == 'file_manager' || preg // Manual section $htmltooltip = $langs->trans("ECMAreaDesc2"); - if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) - { + if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) { // Show the link to "Root" - if ($showroot) - { + if ($showroot) { print ''; } @@ -171,7 +166,9 @@ if (empty($action) || $action == 'editfile' || $action == 'file_manager' || preg // Show filemanager tree (will be filled by a call of ajax /ecm/tpl/enablefiletreeajax.tpl.php, later, that executes ajaxdirtree.php) print '
    '; - if ($action == 'deletefile') print $form->formconfirm('eeeee', $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', '', 'deletefile'); + if ($action == 'deletefile') { + print $form->formconfirm('eeeee', $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', '', 'deletefile'); + } print ''; } else { // Show filtree when ajax is disabled (rare) @@ -188,7 +185,9 @@ if (empty($action) || $action == 'editfile' || $action == 'file_manager' || preg // $_GET['modulepart'], $_GET['openeddir'], $_GET['sortfield'], $_GET['sortorder'] // $_POST['dir'] $mode = 'noajax'; - if (empty($url)) $url = DOL_URL_ROOT.'/ecm/index.php'; + if (empty($url)) { + $url = DOL_URL_ROOT.'/ecm/index.php'; + } include DOL_DOCUMENT_ROOT.'/core/ajax/ajaxdirtree.php'; print ''; @@ -211,7 +210,9 @@ if (empty($action) || $action == 'editfile' || $action == 'file_manager' || preg $mode = 'noajax'; -if (empty($url)) $url = DOL_URL_ROOT.'/ecm/index.php'; +if (empty($url)) { + $url = DOL_URL_ROOT.'/ecm/index.php'; +} include DOL_DOCUMENT_ROOT.'/core/ajax/ajaxdirpreview.php'; // Show content of a directory on right side @@ -225,14 +226,15 @@ include DOL_DOCUMENT_ROOT.'/core/ajax/ajaxdirpreview.php'; // Show content of a use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) // Show filtree when ajax is enabled -{ +if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) { // Show filtree when ajax is enabled //var_dump($modulepart); // Variables that may be defined: // $_GET['modulepart'], $_GET['openeddir'], $_GET['sortfield'], $_GET['sortorder'] // $_POST['dir'] // $_POST['section_dir'], $_POST['section_id'], $_POST['token'], $_POST['max_file_size'], $_POST['sendit'] - if (GETPOST('section_dir', 'alpha')) { $preopened = GETPOST('section_dir', 'alpha'); } + if (GETPOST('section_dir', 'alpha')) { + $preopened = GETPOST('section_dir', 'alpha'); + } include DOL_DOCUMENT_ROOT.'/ecm/tpl/enablefiletreeajax.tpl.php'; } diff --git a/htdocs/core/tpl/list_print_total.tpl.php b/htdocs/core/tpl/list_print_total.tpl.php index 2cd485a9510..d7252f891ae 100644 --- a/htdocs/core/tpl/list_print_total.tpl.php +++ b/htdocs/core/tpl/list_print_total.tpl.php @@ -7,20 +7,29 @@ if (is_array($totalarray['totalizable'])) { } } // Show total line -if (isset($totalarray['pos'])) -{ +if (isset($totalarray['pos'])) { print ''; $i = 0; - while ($i < $totalarray['nbfield']) - { + while ($i < $totalarray['nbfield']) { $i++; - if (!empty($totalarray['pos'][$i])) print ''; - else { - if ($i == 1) - { - if ($num < $limit) print ''; - else print ''; - } else print ''; + if (!empty($totalarray['pos'][$i])) { + print ''; + } else { + if ($i == 1) { + if ($num < $limit) { + print ''; + } else { + print ''; + } + } else { + print ''; + } } } print ''; diff --git a/htdocs/core/tpl/login.tpl.php b/htdocs/core/tpl/login.tpl.php index 8d9c79f807d..b5dc9b90be0 100644 --- a/htdocs/core/tpl/login.tpl.php +++ b/htdocs/core/tpl/login.tpl.php @@ -20,7 +20,9 @@ // Caller can also set $morelogincontent = array(['options']=>array('js'=>..., 'table'=>...); -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', 1); +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', 1); +} // Protection to avoid direct call of template if (empty($conf) || !is_object($conf)) { @@ -34,18 +36,32 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; header('Cache-Control: Public, must-revalidate'); header("Content-type: text/html; charset=".$conf->file->character_set_client); -if (GETPOST('dol_hide_topmenu')) $conf->dol_hide_topmenu = 1; -if (GETPOST('dol_hide_leftmenu')) $conf->dol_hide_leftmenu = 1; -if (GETPOST('dol_optimize_smallscreen')) $conf->dol_optimize_smallscreen = 1; -if (GETPOST('dol_no_mouse_hover')) $conf->dol_no_mouse_hover = 1; -if (GETPOST('dol_use_jmobile')) $conf->dol_use_jmobile = 1; +if (GETPOST('dol_hide_topmenu')) { + $conf->dol_hide_topmenu = 1; +} +if (GETPOST('dol_hide_leftmenu')) { + $conf->dol_hide_leftmenu = 1; +} +if (GETPOST('dol_optimize_smallscreen')) { + $conf->dol_optimize_smallscreen = 1; +} +if (GETPOST('dol_no_mouse_hover')) { + $conf->dol_no_mouse_hover = 1; +} +if (GETPOST('dol_use_jmobile')) { + $conf->dol_use_jmobile = 1; +} // If we force to use jmobile, then we reenable javascript -if (!empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax = 1; +if (!empty($conf->dol_use_jmobile)) { + $conf->use_javascript_ajax = 1; +} $php_self = dol_escape_htmltag($_SERVER['PHP_SELF']); $php_self .= dol_escape_htmltag($_SERVER["QUERY_STRING"]) ? '?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]) : ''; -if (!preg_match('/mainmenu=/', $php_self)) $php_self .= (preg_match('/\?/', $php_self) ? '&' : '?').'mainmenu=home'; +if (!preg_match('/mainmenu=/', $php_self)) { + $php_self .= (preg_match('/\?/', $php_self) ? '&' : '?').'mainmenu=home'; +} // Javascript code on logon page only to detect user tz, dst_observed, dst_first, dst_second $arrayofjs = array( @@ -62,14 +78,20 @@ if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { $titleofloginpage .= ' @ '.$titletruedolibarrversion; // $titletruedolibarrversion is defined by dol_loginfunction in security2.lib.php. We must keep the @, some tools use it to know it is login page and find true dolibarr version. $disablenofollow = 1; -if (!preg_match('/'.constant('DOL_APPLICATION_TITLE').'/', $title)) $disablenofollow = 0; -if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $disablenofollow = 0; +if (!preg_match('/'.constant('DOL_APPLICATION_TITLE').'/', $title)) { + $disablenofollow = 0; +} +if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $disablenofollow = 0; +} print top_htmlhead('', $titleofloginpage, 0, 0, $arrayofjs, array(), 0, $disablenofollow); $colorbackhmenu1 = '60,70,100'; // topmenu -if (!isset($conf->global->THEME_ELDY_TOPMENU_BACK1)) $conf->global->THEME_ELDY_TOPMENU_BACK1 = $colorbackhmenu1; +if (!isset($conf->global->THEME_ELDY_TOPMENU_BACK1)) { + $conf->global->THEME_ELDY_TOPMENU_BACK1 = $colorbackhmenu1; +} $colorbackhmenu1 = empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED) ? (empty($conf->global->THEME_ELDY_TOPMENU_BACK1) ? $colorbackhmenu1 : $conf->global->THEME_ELDY_TOPMENU_BACK1) : (empty($user->conf->THEME_ELDY_TOPMENU_BACK1) ? $colorbackhmenu1 : $user->conf->THEME_ELDY_TOPMENU_BACK1); $colorbackhmenu1 = join(',', colorStringToArray($colorbackhmenu1)); // Normalize value to 'x,y,z' @@ -91,7 +113,9 @@ if (!empty($conf->global->ADD_UNSPLASH_LOGIN_BACKGROUND)) { @@ -122,9 +146,13 @@ $(document).ready(function () { @@ -147,7 +175,9 @@ if ($disablenofollow) echo '';
    -global->MAIN_OPTIMIZEFORTEXTBROWSER)) { ?> +global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + ?> " name="username" class="flat input-icon-user minwidth150" value="" tabindex="1" autofocus="autofocus" /> @@ -157,7 +187,9 @@ if ($disablenofollow) echo '';
    -global->MAIN_OPTIMIZEFORTEXTBROWSER)) { ?> +global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + ?> " name="password" class="flat input-icon-password minwidth150" type="password" value="" tabindex="2" autocomplete="global->MAIN_LOGIN_ENABLE_PASSWORD_AUTOCOMPLETE) ? 'off' : 'on'; ?>" /> @@ -167,8 +199,11 @@ if ($disablenofollow) echo ''; if ($captcha) { // Add a variable param to force not using cache (jmobile) $php_self = preg_replace('/[&\?]time=(\d+)/', '', $php_self); // Remove param time - if (preg_match('/\?/', $php_self)) $php_self .= '&time='.dol_print_date(dol_now(), 'dayhourlog'); - else $php_self .= '?time='.dol_print_date(dol_now(), 'dayhourlog'); + if (preg_match('/\?/', $php_self)) { + $php_self .= '&time='.dol_print_date(dol_now(), 'dayhourlog'); + } else { + $php_self .= '?time='.dol_print_date(dol_now(), 'dayhourlog'); + } // TODO: provide accessible captcha variants ?> @@ -190,8 +225,7 @@ if ($captcha) { if (!empty($morelogincontent)) { if (is_array($morelogincontent)) { - foreach ($morelogincontent as $format => $option) - { + foreach ($morelogincontent as $format => $option) { if ($format == 'table') { echo ''; echo $option; @@ -221,29 +255,42 @@ if (!empty($morelogincontent)) {
    '; echo '
    '; if ($forgetpasslink) { $url = DOL_URL_ROOT.'/user/passwordforgotten.php'.$moreparam; - if (!empty($conf->global->MAIN_PASSWORD_FORGOTLINK)) $url = $conf->global->MAIN_PASSWORD_FORGOTLINK; + if (!empty($conf->global->MAIN_PASSWORD_FORGOTLINK)) { + $url = $conf->global->MAIN_PASSWORD_FORGOTLINK; + } echo ''; echo $langs->trans('PasswordForgotten'); echo ''; } - if ($forgetpasslink && $helpcenterlink) echo ' - '; + if ($forgetpasslink && $helpcenterlink) { + echo ' - '; + } if ($helpcenterlink) { $url = DOL_URL_ROOT.'/support/index.php'.$moreparam; - if (!empty($conf->global->MAIN_HELPCENTER_LINKTOUSE)) $url = $conf->global->MAIN_HELPCENTER_LINKTOUSE; + if (!empty($conf->global->MAIN_HELPCENTER_LINKTOUSE)) { + $url = $conf->global->MAIN_HELPCENTER_LINKTOUSE; + } echo ''; echo $langs->trans('NeedHelpCenter'); echo ''; @@ -251,8 +298,7 @@ if ($forgetpasslink || $helpcenterlink) echo '
    '; } -if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->file->main_authentication)) -{ +if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->file->main_authentication)) { $langs->load("users"); //if (! empty($conf->global->MAIN_OPENIDURL_PERUSER)) $url= @@ -260,8 +306,9 @@ if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->fil echo '
    '; $url = $conf->global->MAIN_AUTHENTICATION_OPENID_URL; - if (!empty($url)) print ''.$langs->trans("LoginUsingOpenID").''; - else { + if (!empty($url)) { + print ''.$langs->trans("LoginUsingOpenID").''; + } else { $langs->load("errors"); print ''.$langs->trans("ErrorOpenIDSetupNotComplete", 'MAIN_AUTHENTICATION_OPENID_URL').''; } @@ -282,8 +329,7 @@ if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->fil
    '; // Multicurrency -if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print ''; +if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) { + print ''; +} -if ($inputalsopricewithtax) print ''; +if ($inputalsopricewithtax) { + print ''; +} // Qty print ''; -if (!empty($conf->global->PRODUCT_USE_UNITS)) -{ +// Unit +if (!empty($conf->global->PRODUCT_USE_UNITS)) { print ''; } @@ -104,10 +110,9 @@ if ($this->situation_cycle_ref) { print ''; } -if ($usemargins && !empty($conf->margin->enabled) && empty($user->socid)) -{ - if (!empty($user->rights->margins->creer)) - { +// Purchase price +if ($usemargins && !empty($conf->margin->enabled) && empty($user->socid)) { + if (!empty($user->rights->margins->creer)) { if ($conf->global->MARGIN_TYPE == "1") { print ''; } else { @@ -127,9 +132,13 @@ if ($usemargins && !empty($conf->margin->enabled) && empty($user->socid)) print ''; // Multicurrency -if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print ''; +if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) { + print ''; +} -if ($outputalsopricetotalwithtax) print ''; +if ($outputalsopricetotalwithtax) { + print ''; +} print ''; // No width to allow autodim @@ -137,8 +146,7 @@ print ''; print ''; -if ($action == 'selectlines') -{ +if ($action == 'selectlines') { print ''; -if ($object->element == 'supplier_proposal' || $object->element == 'order_supplier' || $object->element == 'invoice_supplier') // We must have same test in printObjectLines -{ +if ($object->element == 'supplier_proposal' || $object->element == 'order_supplier' || $object->element == 'invoice_supplier') { // We must have same test in printObjectLines print ''; @@ -203,10 +229,18 @@ if ($object->element == 'supplier_proposal' || $object->element == 'order_suppli print ' @@ -229,11 +263,12 @@ if ((($line->info_bits & 2) != 2) && $line->special_code != 3) { // must also not be output for most entities (proposal, intervention, ...) //if($line->qty > $line->stock) print img_picto($langs->trans("StockTooLow"),"warning", 'style="vertical-align: bottom;"')." "; print price($line->qty, 0, '', 0, 0); // Yes, it is a quantity, not a price, but we just want the formating role of function price -} else print ' '; +} else { + print ' '; +} print ''; -if (!empty($conf->global->PRODUCT_USE_UNITS)) -{ +if (!empty($conf->global->PRODUCT_USE_UNITS)) { print ''; @@ -264,8 +298,7 @@ if ($this->situation_cycle_ref) print ''; } -if ($usemargins && !empty($conf->margin->enabled) && empty($user->socid)) -{ +if ($usemargins && !empty($conf->margin->enabled) && empty($user->socid)) { if (!empty($user->rights->margins->creer)) { ?> margin->enabled) && empty($user->socid)) global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) {?> - - marque_tx, 'MT')).'%'; ?> + special_code == 3) { ?> @@ -282,8 +315,7 @@ if ($line->special_code == 3) { ?> '; $coldisplay++; - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $tooltiponprice = $langs->transcountry("TotalHT", $mysoc->country_code).'='.price($line->total_ht); $tooltiponprice .= '
    '.$langs->transcountry("TotalVAT", ($senderissupplier ? $object->thirdparty->country_code : $mysoc->country_code)).'='.price($line->total_tva); if (!$senderissupplier && is_object($object->thirdparty)) { @@ -307,8 +339,7 @@ if ($line->special_code == 3) { ?> print ''; } print price($sign * $line->total_ht); - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { print ''; } print ''; diff --git a/htdocs/core/tpl/onlinepaymentlinks.tpl.php b/htdocs/core/tpl/onlinepaymentlinks.tpl.php index 959bf7fd6ad..c4b2ad5e3e4 100644 --- a/htdocs/core/tpl/onlinepaymentlinks.tpl.php +++ b/htdocs/core/tpl/onlinepaymentlinks.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -30,13 +29,11 @@ print ''; print ''.$langs->trans("FollowingUrlAreAvailableToMakePayments").':

    '; print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnFreeAmount", $servicename).':
    '; print ''.getOnlinePaymentUrl(1, 'free')."

    \n"; -if (!empty($conf->commande->enabled)) -{ +if (!empty($conf->commande->enabled)) { print '
    '; print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnOrder", $servicename).':
    '; print ''.getOnlinePaymentUrl(1, 'order')."
    \n"; - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $langs->load("orders"); print ''; print ''; @@ -44,8 +41,7 @@ if (!empty($conf->commande->enabled)) print $langs->trans("EnterRefToBuildUrl", $langs->transnoentitiesnoconv("Order")).': '; print ''; print ''; - if (GETPOST('generate_order_ref', 'alpha')) - { + if (GETPOST('generate_order_ref', 'alpha')) { print '
    -> '; $url = getOnlinePaymentUrl(0, 'order', GETPOST('generate_order_ref', 'alpha')); print $url; @@ -55,13 +51,11 @@ if (!empty($conf->commande->enabled)) } print '
    '; } -if (!empty($conf->facture->enabled)) -{ +if (!empty($conf->facture->enabled)) { print '
    '; print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnInvoice", $servicename).':
    '; print ''.getOnlinePaymentUrl(1, 'invoice')."
    \n"; - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $langs->load("bills"); print ''; print ''; @@ -69,8 +63,7 @@ if (!empty($conf->facture->enabled)) print $langs->trans("EnterRefToBuildUrl", $langs->transnoentitiesnoconv("Invoice")).': '; print ''; print ''; - if (GETPOST('generate_invoice_ref', 'alpha')) - { + if (GETPOST('generate_invoice_ref', 'alpha')) { print '
    -> '; $url = getOnlinePaymentUrl(0, 'invoice', GETPOST('generate_invoice_ref', 'alpha')); print $url; @@ -80,13 +73,11 @@ if (!empty($conf->facture->enabled)) } print '
    '; } -if (!empty($conf->contrat->enabled)) -{ +if (!empty($conf->contrat->enabled)) { print '
    '; print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnContractLine", $servicename).':
    '; print ''.getOnlinePaymentUrl(1, 'contractline')."
    \n"; - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $langs->load("contracts"); print ''; print ''; @@ -94,8 +85,7 @@ if (!empty($conf->contrat->enabled)) print $langs->trans("EnterRefToBuildUrl", $langs->transnoentitiesnoconv("ContractLine")).': '; print ''; print ''; - if (GETPOST('generate_contract_ref')) - { + if (GETPOST('generate_contract_ref')) { print '
    -> '; $url = getOnlinePaymentUrl(0, 'contractline', GETPOST('generate_contract_ref', 'alpha')); print $url; @@ -105,13 +95,11 @@ if (!empty($conf->contrat->enabled)) } print '
    '; } -if (!empty($conf->adherent->enabled)) -{ +if (!empty($conf->adherent->enabled)) { print '
    '; print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnMemberSubscription", $servicename).':
    '; print ''.getOnlinePaymentUrl(1, 'membersubscription')."
    \n"; - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $langs->load("members"); print ''; print ''; @@ -119,8 +107,7 @@ if (!empty($conf->adherent->enabled)) print $langs->trans("EnterRefToBuildUrl", $langs->transnoentitiesnoconv("Member")).': '; print ''; print ''; - if (GETPOST('generate_member_ref')) - { + if (GETPOST('generate_member_ref')) { print '
    -> '; $url = getOnlinePaymentUrl(0, 'membersubscription', GETPOST('generate_member_ref', 'alpha')); print $url; @@ -130,13 +117,11 @@ if (!empty($conf->adherent->enabled)) } print '
    '; } -if (!empty($conf->don->enabled)) -{ +if (!empty($conf->don->enabled)) { print '
    '; print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnDonation", $servicename).':
    '; print ''.getOnlinePaymentUrl(1, 'donation')."
    \n"; - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $langs->load("members"); print ''; print ''; @@ -144,8 +129,7 @@ if (!empty($conf->don->enabled)) print $langs->trans("EnterRefToBuildUrl", $langs->transnoentitiesnoconv("Don")).': '; print ''; print ''; - if (GETPOST('generate_donation_ref')) - { + if (GETPOST('generate_donation_ref')) { print '
    -> '; $url = getOnlinePaymentUrl(0, 'donation', GETPOST('generate_donation_ref', 'alpha')); print $url; @@ -156,8 +140,7 @@ if (!empty($conf->don->enabled)) print '
    '; } -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print "\n".' @@ -81,9 +98,13 @@ $(document).ready(function () { @@ -116,8 +137,11 @@ if (!empty($disablenofollow)) echo ''; if (!empty($captcha)) { // Add a variable param to force not using cache (jmobile) $php_self = preg_replace('/[&\?]time=(\d+)/', '', $php_self); // Remove param time - if (preg_match('/\?/', $php_self)) $php_self .= '&time='.dol_print_date(dol_now(), 'dayhourlog'); - else $php_self .= '?time='.dol_print_date(dol_now(), 'dayhourlog'); + if (preg_match('/\?/', $php_self)) { + $php_self .= '&time='.dol_print_date(dol_now(), 'dayhourlog'); + } else { + $php_self .= '?time='.dol_print_date(dol_now(), 'dayhourlog'); + } // TODO: provide accessible captcha variants ?> @@ -139,8 +163,7 @@ if (!empty($captcha)) { if (!empty($morelogincontent)) { if (is_array($morelogincontent)) { - foreach ($morelogincontent as $format => $option) - { + foreach ($morelogincontent as $format => $option) { if ($format == 'table') { echo ''; echo $option; @@ -169,10 +192,18 @@ if (!empty($morelogincontent)) {
    dol_hide_topmenu)) $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_hide_topmenu='.$conf->dol_hide_topmenu; - if (!empty($conf->dol_hide_leftmenu)) $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_hide_leftmenu='.$conf->dol_hide_leftmenu; - if (!empty($conf->dol_no_mouse_hover)) $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_no_mouse_hover='.$conf->dol_no_mouse_hover; - if (!empty($conf->dol_use_jmobile)) $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_use_jmobile='.$conf->dol_use_jmobile; + if (!empty($conf->dol_hide_topmenu)) { + $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_hide_topmenu='.$conf->dol_hide_topmenu; + } + if (!empty($conf->dol_hide_leftmenu)) { + $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_hide_leftmenu='.$conf->dol_hide_leftmenu; + } + if (!empty($conf->dol_no_mouse_hover)) { + $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_no_mouse_hover='.$conf->dol_no_mouse_hover; + } + if (!empty($conf->dol_use_jmobile)) { + $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_use_jmobile='.$conf->dol_use_jmobile; + } print ''.$langs->trans('BackToLoginPage').''; ?> @@ -210,11 +241,12 @@ if (!empty($morelogincontent)) { global->MAIN_HTML_FOOTER)) print $conf->global->MAIN_HTML_FOOTER; +if (!empty($conf->global->MAIN_HTML_FOOTER)) { + print $conf->global->MAIN_HTML_FOOTER; +} if (!empty($morelogincontent) && is_array($morelogincontent)) { - foreach ($morelogincontent as $format => $option) - { + foreach ($morelogincontent as $format => $option) { if ($format == 'js') { echo "\n".''; echo $option."\n"; @@ -227,8 +259,7 @@ if (!empty($morelogincontent) && is_array($morelogincontent)) { // Google Analytics // TODO Add a hook here -if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) -{ +if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) { $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID); foreach ($tmptagarray as $tmptag) { print "\n"; @@ -249,10 +280,8 @@ if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) // TODO Replace this with a hook // Google Adsense (need Google module) -if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && !empty($conf->global->MAIN_GOOGLE_AD_SLOT)) -{ - if (empty($conf->dol_use_jmobile)) - { +if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && !empty($conf->global->MAIN_GOOGLE_AD_SLOT)) { + if (empty($conf->dol_use_jmobile)) { ?>

    '."\n"; } -if ($action == 'delete') -{ +if ($action == 'delete') { print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("CronDelete"), $langs->trans("CronConfirmDelete"), "confirm_delete", '', '', 1); $action = ''; @@ -290,13 +276,11 @@ if ($action == 'execute') { * Create Template */ -if (empty($object->status) && $action != 'create') -{ +if (empty($object->status) && $action != 'create') { setEventMessages($langs->trans("CronTaskInactive"), null, 'warnings'); } -if (($action == "create") || ($action == "edit")) -{ +if (($action == "create") || ($action == "edit")) { print ''; print ''."\n"; print ''."\n"; @@ -307,8 +291,11 @@ if (($action == "create") || ($action == "edit")) print ''."\n"; } - if ($action == "edit") print dol_get_fiche_head($head, 'card', $langs->trans("CronTask"), 0, 'cron'); - else print dol_get_fiche_head(''); + if ($action == "edit") { + print dol_get_fiche_head($head, 'card', $langs->trans("CronTask"), 0, 'cron'); + } else { + print dol_get_fiche_head(''); + } print '
    '.price($totalarray['val'][$totalarray['pos'][$i]]).''.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['val'][$totalarray['pos'][$i]]).''.$langs->trans("Total").''; + if (is_object($form)) { + print $form->textwithpicto($langs->trans("Total"), $langs->transnoentitiesnoconv("Totalforthispage")); + } else { + print $langs->trans("Totalforthispage"); + } + print '
    '.$langs->trans('PriceUHT').''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''.$langs->trans('PriceUTTC').''.$langs->trans('PriceUTTC').''.$langs->trans('Qty').''.$langs->trans('Unit').''.$form->textwithpicto($langs->trans('TotalHT100Short'), $langs->trans('UnitPriceXQtyLessDiscount')).''.$langs->trans('BuyingPrice').''.$langs->trans('TotalHTShort').''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''.$langs->trans('TotalTTCShort').''.$langs->trans('TotalTTCShort').''; print ''; print ''; diff --git a/htdocs/core/tpl/objectline_view.tpl.php b/htdocs/core/tpl/objectline_view.tpl.php index e3516b8b2fc..8e9d72d40b4 100644 --- a/htdocs/core/tpl/objectline_view.tpl.php +++ b/htdocs/core/tpl/objectline_view.tpl.php @@ -39,8 +39,7 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page can't be called as URL"; exit; } @@ -49,13 +48,25 @@ global $mysoc; global $forceall, $senderissupplier, $inputalsopricewithtax, $outputalsopricetotalwithtax; $usemargins = 0; -if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'facturerec', 'propal', 'commande'))) $usemargins = 1; +if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'facturerec', 'propal', 'commande'))) { + $usemargins = 1; +} -if (empty($dateSelector)) $dateSelector = 0; -if (empty($forceall)) $forceall = 0; -if (empty($senderissupplier)) $senderissupplier = 0; -if (empty($inputalsopricewithtax)) $inputalsopricewithtax = 0; -if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax = 0; +if (empty($dateSelector)) { + $dateSelector = 0; +} +if (empty($forceall)) { + $forceall = 0; +} +if (empty($senderissupplier)) { + $senderissupplier = 0; +} +if (empty($inputalsopricewithtax)) { + $inputalsopricewithtax = 0; +} +if (empty($outputalsopricetotalwithtax)) { + $outputalsopricetotalwithtax = 0; +} // add html5 elements $domData = ' data-element="'.$line->element.'"'; @@ -81,34 +92,38 @@ if (($line->info_bits & 2) == 2) { print ''; $txt = ''; print img_object($langs->trans("ShowReduc"), 'reduc').' '; - if ($line->description == '(DEPOSIT)') $txt = $langs->trans("Deposit"); - elseif ($line->description == '(EXCESS RECEIVED)') $txt = $langs->trans("ExcessReceived"); - elseif ($line->description == '(EXCESS PAID)') $txt = $langs->trans("ExcessPaid"); + if ($line->description == '(DEPOSIT)') { + $txt = $langs->trans("Deposit"); + } elseif ($line->description == '(EXCESS RECEIVED)') { + $txt = $langs->trans("ExcessReceived"); + } elseif ($line->description == '(EXCESS PAID)') { + $txt = $langs->trans("ExcessPaid"); + } //else $txt=$langs->trans("Discount"); print $txt; print ''; - if ($line->description) - { - if ($line->description == '(CREDIT_NOTE)' && $line->fk_remise_except > 0) - { + if ($line->description) { + if ($line->description == '(CREDIT_NOTE)' && $line->fk_remise_except > 0) { + include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); print ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0)); - } elseif ($line->description == '(DEPOSIT)' && $line->fk_remise_except > 0) - { + } elseif ($line->description == '(DEPOSIT)' && $line->fk_remise_except > 0) { + include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); print ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0)); // Add date of deposit - if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) + if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) { print ' ('.dol_print_date($discount->datec).')'; - } elseif ($line->description == '(EXCESS RECEIVED)' && $objp->fk_remise_except > 0) - { + } + } elseif ($line->description == '(EXCESS RECEIVED)' && $objp->fk_remise_except > 0) { + include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); print ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0)); - } elseif ($line->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) - { + } elseif ($line->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) { + include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); print ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0)); @@ -123,14 +138,19 @@ if (($line->info_bits & 2) == 2) { print $form->textwithtooltip($text, $description, 3, '', '', $i, 0, (!empty($line->fk_parent_line) ?img_picto('', 'rightarrow') : '')); } else { $type = (!empty($line->product_type) ? $line->product_type : $line->fk_product_type); - if ($type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if ($type == 1) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($line->label)) { $text .= ' '.$line->label.''; print $form->textwithtooltip($text, dol_htmlentitiesbr($line->description), 3, '', '', $i, 0, (!empty($line->fk_parent_line) ?img_picto('', 'rightarrow') : '')); } else { - if (!empty($line->fk_parent_line)) print img_picto('', 'rightarrow'); + if (!empty($line->fk_parent_line)) { + print img_picto('', 'rightarrow'); + } if (preg_match('/^\(DEPOSIT\)/', $line->description)) { $newdesc = preg_replace('/^\(DEPOSIT\)/', $langs->trans("Deposit"), $line->description); print $text.' '.dol_htmlentitiesbr($newdesc); @@ -142,24 +162,34 @@ if (($line->info_bits & 2) == 2) { // Show date range if ($line->element == 'facturedetrec') { - if ($line->date_start_fill || $line->date_end_fill) print '
    '; - if ($line->date_start_fill) print $langs->trans('AutoFillDateFromShort').': '.yn($line->date_start_fill); - if ($line->date_start_fill && $line->date_end_fill) print ' - '; - if ($line->date_end_fill) print $langs->trans('AutoFillDateToShort').': '.yn($line->date_end_fill); - if ($line->date_start_fill || $line->date_end_fill) print '
    '; + if ($line->date_start_fill || $line->date_end_fill) { + print '
    '; + } + if ($line->date_start_fill) { + print $langs->trans('AutoFillDateFromShort').': '.yn($line->date_start_fill); + } + if ($line->date_start_fill && $line->date_end_fill) { + print ' - '; + } + if ($line->date_end_fill) { + print $langs->trans('AutoFillDateToShort').': '.yn($line->date_end_fill); + } + if ($line->date_start_fill || $line->date_end_fill) { + print '
    '; + } } else { - if ($line->date_start || $line->date_end) print '
    '.get_date_range($line->date_start, $line->date_end, $format).'
    '; + if ($line->date_start || $line->date_end) { + print '
    '.get_date_range($line->date_start, $line->date_end, $format).'
    '; + } //print get_date_range($line->date_start, $line->date_end, $format); } // Add description in form - if ($line->fk_product > 0 && !empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if ($line->fk_product > 0 && !empty($conf->global->PRODUIT_DESC_IN_FORM)) { print (!empty($line->description) && $line->description != $line->product_label) ? '
    '.dol_htmlentitiesbr($line->description) : ''; } //Line extrafield - if (!empty($extrafields)) - { + if (!empty($extrafields)) { $temps = $line->showOptionals($extrafields, 'view', array(), '', '', 1, 'line'); if (!empty($temps)) { print '
    '; @@ -169,32 +199,28 @@ if (($line->info_bits & 2) == 2) { } } -if ($user->rights->fournisseur->lire && $line->fk_fournprice > 0 && empty($conf->global->SUPPLIER_HIDE_SUPPLIER_OBJECTLINES)) -{ +if ($user->rights->fournisseur->lire && $line->fk_fournprice > 0 && empty($conf->global->SUPPLIER_HIDE_SUPPLIER_OBJECTLINES)) { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $productfourn = new ProductFournisseur($this->db); $productfourn->fetch_product_fournisseur_price($line->fk_fournprice); print '
    '; print ''.$langs->trans('Supplier').' : '.$productfourn->getSocNomUrl(1, 'supplier').' - '.$langs->trans('Ref').' : '; // Supplier ref - if ($user->rights->produit->creer || $user->rights->service->creer) // change required right here - { + if ($user->rights->produit->creer || $user->rights->service->creer) { // change required right here print $productfourn->getNomUrl(); } else { print $productfourn->ref_supplier; } } -if (!empty($conf->accounting->enabled) && $line->fk_accounting_account > 0) -{ +if (!empty($conf->accounting->enabled) && $line->fk_accounting_account > 0) { $accountingaccount = new AccountingAccount($this->db); $accountingaccount->fetch($line->fk_accounting_account); print '

    '.$langs->trans('AccountingAffectation').' : '.$accountingaccount->getNomUrl(0, 1, 1); } print '
    '; print ($line->ref_fourn ? $line->ref_fourn : $line->ref_supplier); print ''; $coldisplay++; $positiverates = ''; -if (price2num($line->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($line->tva_tx); -if (price2num($line->total_localtax1)) $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax1_tx); -if (price2num($line->total_localtax2)) $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax2_tx); -if (empty($positiverates)) $positiverates = '0'; +if (price2num($line->tva_tx)) { + $positiverates .= ($positiverates ? '/' : '').price2num($line->tva_tx); +} +if (price2num($line->total_localtax1)) { + $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax1_tx); +} +if (price2num($line->total_localtax2)) { + $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax2_tx); +} +if (empty($positiverates)) { + $positiverates = '0'; +} print vatrate($positiverates.($line->vat_src_code ? ' ('.$line->vat_src_code.')' : ''), '%', $line->info_bits); //print vatrate($line->tva_tx.($line->vat_src_code?(' ('.$line->vat_src_code.')'):''), '%', $line->info_bits); ?>'; $label = $line->getLabelOfUnit('short'); if ($label !== '') { @@ -253,8 +288,7 @@ if (!empty($line->remise_percent) && $line->special_code != 3) { } // Fields for situation invoices -if ($this->situation_cycle_ref) -{ +if ($this->situation_cycle_ref) { include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; $coldisplay++; print ''.$line->situation_percent.'%'.price($sign * $tmp[0]).'pa_ht); ?> pa_ht == 0) ? 'n/a' : price(price2num($line->marge_tx, 'MT')).'%'); ?> marque_tx, 'MT')).'%'; ?>
    '; @@ -395,10 +382,8 @@ if (($action == "create") || ($action == "edit")) print $langs->trans('CronEvery').""; print ""; - if (!empty($conf->multicompany->enabled)) - { + if (!empty($conf->multicompany->enabled)) { print '"; print ""; print '"; print ""; print ""; @@ -672,19 +671,31 @@ if (($action == "create") || ($action == "edit")) print '"; print '"; print '"; print '\n"; -if ($num > 0) -{ +if ($num > 0) { // Loop on each job $now = dol_now(); $i = 0; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($result); - if (empty($obj)) break; - if (!verifCond($obj->test)) continue; // Discard line with test = false + if (empty($obj)) { + break; + } + if (!verifCond($obj->test)) { + continue; // Discard line with test = false + } $object->id = $obj->rowid; $object->ref = $obj->rowid; @@ -450,8 +500,7 @@ if ($num > 0) // Label print ''; - print ''; print ''; print ''; print ''; print ''; // Date start last run print ''; // Duration @@ -521,27 +588,38 @@ if ($num > 0) // Return code of last run print ''; // Output of last run print ''; print ''; @@ -553,20 +631,17 @@ if ($num > 0) print ''; diff --git a/htdocs/datapolicy/admin/setup.php b/htdocs/datapolicy/admin/setup.php index d50f544449d..a334b36929e 100644 --- a/htdocs/datapolicy/admin/setup.php +++ b/htdocs/datapolicy/admin/setup.php @@ -33,7 +33,9 @@ $langs->load('members'); $langs->load('datapolicy@datapolicy'); // Access control -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Parameters $action = GETPOST('action', 'aZ09'); @@ -104,8 +106,7 @@ print dol_get_fiche_head($head, 'settings', '', -1, "datapolicy@datapolicy"); echo ''.$langs->trans("datapolicySetupPage").'

    '; -if ($action == 'edit') -{ +if ($action == 'edit') { print ''; print ''; print ''; @@ -113,11 +114,9 @@ if ($action == 'edit') print '
    "; print '"; $input = " unitfrequency == "60") - { + if ($object->unitfrequency == "60") { $input .= ' checked />'; } else { $input .= ' />'; @@ -448,8 +432,7 @@ if (($action == "create") || ($action == "edit")) print "
    "; print $langs->trans('CronDtStart').""; - if (!empty($object->datestart)) - { + if (!empty($object->datestart)) { print $form->selectDate($object->datestart, 'datestart', 1, 1, '', "cronform"); } else { print $form->selectDate('', 'datestart', 1, 1, '', "cronform"); @@ -499,8 +482,7 @@ if (($action == "create") || ($action == "edit")) print $langs->trans('CronDtNextLaunch'); print ' ('.$langs->trans('CronFrom').')'; print ""; - if (!empty($object->datenextrun)) - { + if (!empty($object->datenextrun)) { print $form->selectDate($object->datenextrun, 'datenextrun', 1, 1, '', "cronform"); } else { print $form->selectDate(-1, 'datenextrun', 1, 1, '', "cronform"); @@ -588,12 +570,10 @@ if (($action == "create") || ($action == "edit")) } print "
    '; print $langs->trans('Entity').""; - if (!$object->entity) - { + if (!$object->entity) { print $langs->trans("AllEntities"); } else { $mc->getInfo($object->entity); @@ -615,20 +595,32 @@ if (($action == "create") || ($action == "edit")) print '
    '; print $langs->trans('CronEvery').""; - if ($object->unitfrequency == "60") print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Minutes'); - if ($object->unitfrequency == "3600") print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Hours'); - if ($object->unitfrequency == "86400") print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Days'); - if ($object->unitfrequency == "604800") print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Weeks'); + if ($object->unitfrequency == "60") { + print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Minutes'); + } + if ($object->unitfrequency == "3600") { + print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Hours'); + } + if ($object->unitfrequency == "86400") { + print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Days'); + } + if ($object->unitfrequency == "604800") { + print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Weeks'); + } print "
    '; print $langs->trans('CronDtStart').""; - if (!empty($object->datestart)) {print $form->textwithpicto(dol_print_date($object->datestart, 'dayhoursec'), $langs->trans("CurrentTimeZone")); } + if (!empty($object->datestart)) { + print $form->textwithpicto(dol_print_date($object->datestart, 'dayhoursec'), $langs->trans("CurrentTimeZone")); + } print "
    "; print $langs->trans('CronDtEnd').""; - if (!empty($object->dateend)) {print $form->textwithpicto(dol_print_date($object->dateend, 'dayhoursec'), $langs->trans("CurrentTimeZone")); } + if (!empty($object->dateend)) { + print $form->textwithpicto(dol_print_date($object->dateend, 'dayhoursec'), $langs->trans("CurrentTimeZone")); + } print "
    "; @@ -652,12 +644,19 @@ if (($action == "create") || ($action == "edit")) print $langs->trans('CronDtNextLaunch'); print ' ('.$langs->trans('CronFrom').')'; print ""; - if (!$object->status) print $langs->trans("Disabled"); - elseif (!empty($object->datenextrun)) { print img_picto('', 'object_calendarday').' '.$form->textwithpicto(dol_print_date($object->datenextrun, 'dayhoursec'), $langs->trans("CurrentTimeZone")); } else { print $langs->trans('CronNone'); } - if ($object->status == Cronjob::STATUS_ENABLED) - { - if ($object->maxrun && $object->nbrun >= $object->maxrun) print img_warning($langs->trans("MaxRunReached")); - elseif ($object->datenextrun && $object->datenextrun < $now) print img_warning($langs->trans("Late")); + if (!$object->status) { + print $langs->trans("Disabled"); + } elseif (!empty($object->datenextrun)) { + print img_picto('', 'object_calendarday').' '.$form->textwithpicto(dol_print_date($object->datenextrun, 'dayhoursec'), $langs->trans("CurrentTimeZone")); + } else { + print $langs->trans('CronNone'); + } + if ($object->status == Cronjob::STATUS_ENABLED) { + if ($object->maxrun && $object->nbrun >= $object->maxrun) { + print img_warning($langs->trans("MaxRunReached")); + } elseif ($object->datenextrun && $object->datenextrun < $now) { + print img_warning($langs->trans("Late")); + } } print "
    '; print $langs->trans('CronDtLastLaunch').""; - if (!empty($object->datelastrun)) {print $form->textwithpicto(dol_print_date($object->datelastrun, 'dayhoursec'), $langs->trans("CurrentTimeZone")); } else {print $langs->trans('CronNone'); } + if (!empty($object->datelastrun)) { + print $form->textwithpicto(dol_print_date($object->datelastrun, 'dayhoursec'), $langs->trans("CurrentTimeZone")); + } else { + print $langs->trans('CronNone'); + } print "
    '; print $langs->trans('CronDtLastResult').""; - if (!empty($object->datelastresult)) {print $form->textwithpicto(dol_print_date($object->datelastresult, 'dayhoursec'), $langs->trans("CurrentTimeZone")); } else {print $langs->trans('CronNone'); } + if (!empty($object->datelastresult)) { + print $form->textwithpicto(dol_print_date($object->datelastresult, 'dayhoursec'), $langs->trans("CurrentTimeZone")); + } else { + print $langs->trans('CronNone'); + } print "
    '; print $langs->trans('CronLastResult').""; - if ($object->lastresult) print ''; + if ($object->lastresult) { + print ''; + } print $object->lastresult; - if ($object->lastresult) print ''; + if ($object->lastresult) { + print ''; + } print "
    '; @@ -705,11 +716,9 @@ if (($action == "create") || ($action == "edit")) print ''.$langs->trans("Edit").''; } - if ((empty($user->rights->cron->execute))) - { + if ((empty($user->rights->cron->execute))) { print ''.$langs->trans("CronExecute").''; - } elseif (empty($object->status)) - { + } elseif (empty($object->status)) { print ''.$langs->trans("CronExecute").''; } else { print ''.$langs->trans("CronExecute").''; diff --git a/htdocs/cron/class/cronjob.class.php b/htdocs/cron/class/cronjob.class.php index 9d084ec4f24..0b926f6a802 100644 --- a/htdocs/cron/class/cronjob.class.php +++ b/htdocs/cron/class/cronjob.class.php @@ -50,8 +50,19 @@ class Cronjob extends CommonObject */ public $entity; + /** + * @var string Job type + */ public $jobtype; + + /** + * @var string|int Date for last cron object update + */ public $tms = ''; + + /** + * @var string|int Date for cron job create + */ public $datec = ''; /** @@ -59,6 +70,9 @@ class Cronjob extends CommonObject */ public $label; + /** + * @var string Job command + */ public $command; public $classesname; public $objectname; @@ -67,20 +81,50 @@ class Cronjob extends CommonObject public $md5params; public $module_name; public $priority; + /** * @var string|int Date for last job execution */ public $datelastrun = ''; + /** * @var string|int Date for next job execution */ public $datenextrun = ''; + + /** + * @var string|int Date for end job execution + */ public $dateend = ''; + + /** + * @var string|int Date for first start job execution + */ public $datestart = ''; + + /** + * @var string|int Date for last result job execution + */ public $datelastresult = ''; + + /** + * @var string Last result from end job execution + */ public $lastresult; + + /** + * @var string Last output from end job execution + */ public $lastoutput; + + /** + * @var string Unit frequency of job execution + */ public $unitfrequency; + + /** + * @var int Frequency of job execution + */ public $frequency; /** @@ -88,6 +132,9 @@ class Cronjob extends CommonObject */ public $status; + /** + * @var int Is job processing + */ public $processing; /** @@ -100,9 +147,25 @@ class Cronjob extends CommonObject */ public $fk_user_mod; + /** + * @var int Number of run job execution + */ public $nbrun; + + /** + * @var int Maximum run job execution + */ + public $maxrun; + + /** + * @var string Libname + */ public $libname; - public $test; // A test condition to know if job is visible/qualified + + /** + * @var string A test condition to know if job is visible/qualified + */ + public $test; const STATUS_DISABLED = 0; const STATUS_ENABLED = 1; @@ -136,25 +199,66 @@ class Cronjob extends CommonObject // Clean parameters - if (isset($this->label)) $this->label = trim($this->label); - if (isset($this->jobtype)) $this->jobtype = trim($this->jobtype); - if (isset($this->command)) $this->command = trim($this->command); - if (isset($this->classesname)) $this->classesname = trim($this->classesname); - if (isset($this->objectname)) $this->objectname = trim($this->objectname); - if (isset($this->methodename)) $this->methodename = trim($this->methodename); - if (isset($this->params)) $this->params = trim($this->params); - if (isset($this->md5params)) $this->md5params = trim($this->md5params); - if (isset($this->module_name)) $this->module_name = trim($this->module_name); - if (isset($this->priority)) $this->priority = trim($this->priority); - if (isset($this->lastoutput)) $this->lastoutput = trim($this->lastoutput); - if (isset($this->lastresult)) $this->lastresult = trim($this->lastresult); - if (isset($this->unitfrequency)) $this->unitfrequency = trim($this->unitfrequency); - if (isset($this->frequency)) $this->frequency = trim($this->frequency); - if (isset($this->status)) $this->status = trim($this->status); - if (isset($this->note_private)) $this->note_private = trim($this->note_private); - if (isset($this->nbrun)) $this->nbrun = trim($this->nbrun); - if (isset($this->libname)) $this->libname = trim($this->libname); - if (isset($this->test)) $this->test = trim($this->test); + if (isset($this->label)) { + $this->label = trim($this->label); + } + if (isset($this->jobtype)) { + $this->jobtype = trim($this->jobtype); + } + if (isset($this->command)) { + $this->command = trim($this->command); + } + if (isset($this->classesname)) { + $this->classesname = trim($this->classesname); + } + if (isset($this->objectname)) { + $this->objectname = trim($this->objectname); + } + if (isset($this->methodename)) { + $this->methodename = trim($this->methodename); + } + if (isset($this->params)) { + $this->params = trim($this->params); + } + if (isset($this->md5params)) { + $this->md5params = trim($this->md5params); + } + if (isset($this->module_name)) { + $this->module_name = trim($this->module_name); + } + if (isset($this->priority)) { + $this->priority = trim($this->priority); + } + if (isset($this->lastoutput)) { + $this->lastoutput = trim($this->lastoutput); + } + if (isset($this->lastresult)) { + $this->lastresult = trim($this->lastresult); + } + if (isset($this->unitfrequency)) { + $this->unitfrequency = trim($this->unitfrequency); + } + if (isset($this->frequency)) { + $this->frequency = trim($this->frequency); + } + if (isset($this->status)) { + $this->status = trim($this->status); + } + if (isset($this->note_private)) { + $this->note_private = trim($this->note_private); + } + if (isset($this->nbrun)) { + $this->nbrun = (int) $this->nbrun; + } + if (isset($this->maxrun)) { + $this->maxrun = (int) $this->maxrun; + } + if (isset($this->libname)) { + $this->libname = trim($this->libname); + } + if (isset($this->test)) { + $this->test = trim($this->test); + } // Check parameters // Put here code to add a control on parameters values @@ -260,20 +364,20 @@ class Cronjob extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::create", LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."cronjob"); } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -331,7 +435,7 @@ class Cronjob extends CommonObject $sql .= " t.test"; $sql .= " FROM ".MAIN_DB_PREFIX."cronjob as t"; if ($id > 0) { - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".((int) $id); } else { $sql .= " WHERE t.entity IN(0, ".getEntity('cron').")"; $sql .= " AND t.objectname = '".$this->db->escape($objectname)."'"; @@ -340,10 +444,8 @@ class Cronjob extends CommonObject dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -384,7 +486,7 @@ class Cronjob extends CommonObject return 1; } else { - $this->error = "Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -443,15 +545,22 @@ class Cronjob extends CommonObject $sql .= " t.test"; $sql .= " FROM ".MAIN_DB_PREFIX."cronjob as t"; $sql .= " WHERE 1 = 1"; - if ($processing >= 0) $sql .= " AND t.processing = ".(empty($processing) ? '0' : '1'); - if ($status >= 0 && $status < 2) $sql .= " AND t.status = ".(empty($status) ? '0' : '1'); - elseif ($status == 2) $sql .= " AND t.status = 2"; + if ($processing >= 0) { + $sql .= " AND t.processing = ".(empty($processing) ? '0' : '1'); + } + if ($status >= 0 && $status < 2) { + $sql .= " AND t.status = ".(empty($status) ? '0' : '1'); + } elseif ($status == 2) { + $sql .= " AND t.status = 2"; + } //Manage filter if (is_array($filter) && count($filter) > 0) { - foreach ($filter as $key => $value) - { - if ($key == 't.rowid') $sql .= ' AND '.$key.' = '.$this->db->escape($value); - else $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\''; + foreach ($filter as $key => $value) { + if ($key == 't.rowid') { + $sql .= ' AND '.$key.' = '.$this->db->escape($value); + } else { + $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\''; + } } } @@ -468,15 +577,12 @@ class Cronjob extends CommonObject dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $line = new Cronjobline(); $obj = $this->db->fetch_object($resql); @@ -544,28 +650,70 @@ class Cronjob extends CommonObject $error = 0; // Clean parameters - if (isset($this->label)) $this->label = trim($this->label); - if (isset($this->jobtype)) $this->jobtype = trim($this->jobtype); - if (isset($this->command)) $this->command = trim($this->command); - if (isset($this->classesname)) $this->classesname = trim($this->classesname); - if (isset($this->objectname)) $this->objectname = trim($this->objectname); - if (isset($this->methodename)) $this->methodename = trim($this->methodename); - if (isset($this->params)) $this->params = trim($this->params); - if (isset($this->md5params)) $this->md5params = trim($this->md5params); - if (isset($this->module_name)) $this->module_name = trim($this->module_name); - if (isset($this->priority)) $this->priority = trim($this->priority); - if (isset($this->lastoutput)) $this->lastoutput = trim($this->lastoutput); - if (isset($this->lastresult)) $this->lastresult = trim($this->lastresult); - if (isset($this->unitfrequency)) $this->unitfrequency = trim($this->unitfrequency); - if (isset($this->frequency)) $this->frequency = trim($this->frequency); - if (isset($this->status)) $this->status = trim($this->status); - if (isset($this->note_private)) $this->note_private = trim($this->note_private); - if (isset($this->nbrun)) $this->nbrun = trim($this->nbrun); - if (isset($this->libname)) $this->libname = trim($this->libname); - if (isset($this->test)) $this->test = trim($this->test); + if (isset($this->label)) { + $this->label = trim($this->label); + } + if (isset($this->jobtype)) { + $this->jobtype = trim($this->jobtype); + } + if (isset($this->command)) { + $this->command = trim($this->command); + } + if (isset($this->classesname)) { + $this->classesname = trim($this->classesname); + } + if (isset($this->objectname)) { + $this->objectname = trim($this->objectname); + } + if (isset($this->methodename)) { + $this->methodename = trim($this->methodename); + } + if (isset($this->params)) { + $this->params = trim($this->params); + } + if (isset($this->md5params)) { + $this->md5params = trim($this->md5params); + } + if (isset($this->module_name)) { + $this->module_name = trim($this->module_name); + } + if (isset($this->priority)) { + $this->priority = trim($this->priority); + } + if (isset($this->lastoutput)) { + $this->lastoutput = trim($this->lastoutput); + } + if (isset($this->lastresult)) { + $this->lastresult = trim($this->lastresult); + } + if (isset($this->unitfrequency)) { + $this->unitfrequency = trim($this->unitfrequency); + } + if (isset($this->frequency)) { + $this->frequency = trim($this->frequency); + } + if (isset($this->status)) { + $this->status = trim($this->status); + } + if (isset($this->note_private)) { + $this->note_private = trim($this->note_private); + } + if (isset($this->nbrun)) { + $this->nbrun = trim($this->nbrun); + } + if (isset($this->libname)) { + $this->libname = trim($this->libname); + } + if (isset($this->test)) { + $this->test = trim($this->test); + } - if (empty($this->maxrun)) $this->maxrun = 0; - if (empty($this->processing)) $this->processing = 0; + if (empty($this->maxrun)) { + $this->maxrun = 0; + } + if (empty($this->processing)) { + $this->processing = 0; + } // Check parameters // Put here code to add a control on parameters values @@ -638,19 +786,19 @@ class Cronjob extends CommonObject $sql .= " maxrun=".((isset($this->maxrun) && $this->maxrun > 0) ? $this->maxrun : "0").","; $sql .= " libname=".(isset($this->libname) ? "'".$this->db->escape($this->libname)."'" : "null").","; $sql .= " test=".(isset($this->test) ? "'".$this->db->escape($this->test)."'" : "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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -663,13 +811,13 @@ class Cronjob extends CommonObject } - /** - * Delete object in database - * - * @param User $user User that deletes - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + /** + * Delete object in database + * + * @param User $user User that deletes + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function delete($user, $notrigger = 0) { $error = 0; @@ -677,7 +825,7 @@ class Cronjob extends CommonObject $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); @@ -687,10 +835,8 @@ class Cronjob extends CommonObject } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -732,8 +878,7 @@ class Cronjob extends CommonObject $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $error++; } @@ -746,8 +891,7 @@ class Cronjob extends CommonObject unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { @@ -816,7 +960,9 @@ class Cronjob extends CommonObject global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -829,33 +975,40 @@ class Cronjob extends CommonObject $url = DOL_URL_ROOT.'/cron/card.php?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowCronJob"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -874,14 +1027,12 @@ class Cronjob extends CommonObject $sql = "SELECT"; $sql .= " f.rowid, f.datec, f.tms, f.fk_user_mod, f.fk_user_author"; $sql .= " FROM ".MAIN_DB_PREFIX."cronjob as f"; - $sql .= " WHERE f.rowid = ".$id; + $sql .= " WHERE f.rowid = ".((int) $id); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; $this->date_creation = $this->db->jdate($obj->datec); @@ -921,8 +1072,7 @@ class Cronjob extends CommonObject $langs->load('cron'); - if (empty($userlogin)) - { + if (empty($userlogin)) { $this->error = "User login is mandatory"; dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); return -1; @@ -930,8 +1080,7 @@ class Cronjob extends CommonObject // Force the environment of running to the environment declared for job, so jobs launched from command line will run into correct environment // When job is ran from GUI, the environment should already be same, except if job has entity 0 (visible into all environments) - if ($conf->entity != $this->entity && $this->entity > 0) - { + if ($conf->entity != $this->entity && $this->entity > 0) { dol_syslog("We try to run a job in entity ".$this->entity." when we are in entity ".$conf->entity, LOG_WARNING); } $savcurrententity = $conf->entity; @@ -941,15 +1090,13 @@ class Cronjob extends CommonObject require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; $user = new User($this->db); $result = $user->fetch('', $userlogin); - if ($result < 0) - { + if ($result < 0) { $this->error = "User Error:".$user->error; dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); $conf->entity = $savcurrententity; return -1; } else { - if (empty($user->id)) - { + if (empty($user->id)) { $this->error = " User user login:".$userlogin." do not exists"; dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); $conf->entity = $savcurrententity; @@ -961,16 +1108,14 @@ class Cronjob extends CommonObject // Increase limit of time. Works only if we are not in safe mode $ExecTimeLimit = 600; - if (!empty($ExecTimeLimit)) - { + if (!empty($ExecTimeLimit)) { $err = error_reporting(); error_reporting(0); // Disable all errors //error_reporting(E_ALL); @set_time_limit($ExecTimeLimit); // Need more than 240 on Windows 7/64 error_reporting($err); } - if (!empty($MemoryLimit)) - { + if (!empty($MemoryLimit)) { @ini_set('memory_limit', $MemoryLimit); } @@ -989,16 +1134,16 @@ class Cronjob extends CommonObject } // Run a method - if ($this->jobtype == 'method') - { + if ($this->jobtype == 'method') { // load classes - if (!$error) - { + if (!$error) { $ret = dol_include_once($this->classesname); - if ($ret === false || (!class_exists($this->objectname))) - { - if ($ret === false) $this->error = $langs->trans('CronCannotLoadClass', $this->classesname, $this->objectname); - else $this->error = $langs->trans('CronCannotLoadObject', $this->classesname, $this->objectname); + if ($ret === false || (!class_exists($this->objectname))) { + if ($ret === false) { + $this->error = $langs->trans('CronCannotLoadClass', $this->classesname, $this->objectname); + } else { + $this->error = $langs->trans('CronCannotLoadObject', $this->classesname, $this->objectname); + } dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); $this->lastoutput = $this->error; $this->lastresult = -1; @@ -1008,10 +1153,8 @@ class Cronjob extends CommonObject } // test if method exists - if (!$error) - { - if (!method_exists($this->objectname, $this->methodename)) - { + if (!$error) { + if (!method_exists($this->objectname, $this->methodename)) { $this->error = $langs->trans('CronMethodDoesNotExists', $this->objectname, $this->methodename); dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); $this->lastoutput = $this->error; @@ -1019,8 +1162,7 @@ class Cronjob extends CommonObject $retval = $this->lastresult; $error++; } - if (in_array(strtolower(trim($this->methodename)), array('executecli'))) - { + if (in_array(strtolower(trim($this->methodename)), array('executecli'))) { $this->error = $langs->trans('CronMethodNotAllowed', $this->methodename, $this->objectname); dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); $this->lastoutput = $this->error; @@ -1031,13 +1173,11 @@ class Cronjob extends CommonObject } // Load langs - if (!$error) - { + if (!$error) { $result = $langs->load($this->module_name); $result = $langs->load($this->module_name.'@'.$this->module_name, 0, 0, '', 0, 1); - if ($result < 0) // If technical error - { + if ($result < 0) { // If technical error dol_syslog(get_class($this)."::run_jobs Cannot load module lang file - ".$langs->error, LOG_ERR); $this->error = $langs->error; $this->lastoutput = $this->error; @@ -1047,34 +1187,39 @@ class Cronjob extends CommonObject } } - if (!$error) - { + if (!$error) { dol_syslog(get_class($this)."::run_jobs START ".$this->objectname."->".$this->methodename."(".$this->params.");", LOG_DEBUG); // Create Object for the called module $object = new $this->objectname($this->db); - if ($this->entity > 0) $object->entity = $this->entity; // We work on a dedicated entity + if ($this->entity > 0) { + $object->entity = $this->entity; // We work on a dedicated entity + } $params_arr = array(); if (!empty($this->params) || $this->params === '0') { $params_arr = array_map('trim', explode(",", $this->params)); } - if (!is_array($params_arr)) - { + if (!is_array($params_arr)) { $result = call_user_func(array($object, $this->methodename), $this->params); } else { $result = call_user_func_array(array($object, $this->methodename), $params_arr); } - if ($result === false || (!is_bool($result) && $result != 0)) - { + if ($result === false || (!is_bool($result) && $result != 0)) { $langs->load("errors"); $errmsg = ''; - if (!is_array($object->errors) || !in_array($object->error, $object->errors)) $errmsg .= $object->error; - if (is_array($object->errors) && count($object->errors)) $errmsg .= (($errmsg ? ', ' : '').join(', ', $object->errors)); - if (empty($errmsg)) $errmsg = $langs->trans('ErrorUnknown'); + if (!is_array($object->errors) || !in_array($object->error, $object->errors)) { + $errmsg .= $object->error; + } + if (is_array($object->errors) && count($object->errors)) { + $errmsg .= (($errmsg ? ', ' : '').join(', ', $object->errors)); + } + if (empty($errmsg)) { + $errmsg = $langs->trans('ErrorUnknown'); + } dol_syslog(get_class($this)."::run_jobs END result=".$result." error=".$errmsg, LOG_ERR); @@ -1096,8 +1241,7 @@ class Cronjob extends CommonObject //load lib $libpath = '/'.strtolower($this->module_name).'/lib/'.$this->libname; $ret = dol_include_once($libpath); - if ($ret === false) - { + if ($ret === false) { $this->error = $langs->trans('CronCannotLoadLib').': '.$libpath; dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); $conf->entity = $savcurrententity; @@ -1107,8 +1251,7 @@ class Cronjob extends CommonObject // Load langs $result = $langs->load($this->module_name); $result = $langs->load($this->module_name.'@'.$this->module_name); // If this->module_name was an existing language file, this will make nothing - if ($result < 0) // If technical error - { + if ($result < 0) { // If technical error dol_syslog(get_class($this)."::run_jobs Cannot load module langs".$langs->error, LOG_ERR); $conf->entity = $savcurrententity; return -1; @@ -1116,15 +1259,13 @@ class Cronjob extends CommonObject dol_syslog(get_class($this)."::run_jobs ".$this->libname."::".$this->methodename."(".$this->params.");", LOG_DEBUG); $params_arr = explode(", ", $this->params); - if (!is_array($params_arr)) - { + if (!is_array($params_arr)) { $result = call_user_func($this->methodename, $this->params); } else { $result = call_user_func_array($this->methodename, $params_arr); } - if ($result === false || (!is_bool($result) && $result != 0)) - { + if ($result === false || (!is_bool($result) && $result != 0)) { $langs->load("errors"); dol_syslog(get_class($this)."::run_jobs result=".$result, LOG_ERR); $this->error = $langs->trans('ErrorUnknown'); @@ -1140,8 +1281,7 @@ class Cronjob extends CommonObject } // Run a command line - if ($this->jobtype == 'command') - { + if ($this->jobtype == 'command') { global $dolibarr_cron_allow_cli; if (empty($dolibarr_cron_allow_cli)) { @@ -1151,10 +1291,11 @@ class Cronjob extends CommonObject $this->lastresult = $langs->trans("ErrorParameterMustBeEnabledToAllwoThisFeature", 'dolibarr_cron_allow_cli'); } else { $outputdir = $conf->cron->dir_temp; - if (empty($outputdir)) $outputdir = $conf->cronjob->dir_temp; + if (empty($outputdir)) { + $outputdir = $conf->cronjob->dir_temp; + } - if (!empty($outputdir)) - { + if (!empty($outputdir)) { dol_mkdir($outputdir); $outputfile = $outputdir.'/cronjob.'.$userlogin.'.out'; // File used with popen method @@ -1176,8 +1317,7 @@ class Cronjob extends CommonObject $this->datelastresult = dol_now(); $this->processing = 0; $result = $this->update($user); // This include begin/commit - if ($result < 0) - { + if ($result < 0) { dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); $conf->entity = $savcurrententity; return -1; @@ -1204,14 +1344,12 @@ class Cronjob extends CommonObject require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; $user = new User($this->db); $result = $user->fetch('', $userlogin); - if ($result < 0) - { + if ($result < 0) { $this->error = "User Error : ".$user->error; dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR); return -1; } else { - if (empty($user->id)) - { + if (empty($user->id)) { $this->error = " User user login:".$userlogin." do not exists"; dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR); return -1; @@ -1220,17 +1358,17 @@ class Cronjob extends CommonObject dol_syslog(get_class($this)."::reprogram_jobs datenextrun=".$this->datenextrun." ".dol_print_date($this->datenextrun, 'dayhourrfc')." frequency=".$this->frequency." unitfrequency=".$this->unitfrequency, LOG_DEBUG); - if (empty($this->datenextrun)) - { - if (empty($this->datestart)) $this->datenextrun = $now + ($this->frequency * $this->unitfrequency); - else $this->datenextrun = $this->datestart + ($this->frequency * $this->unitfrequency); + if (empty($this->datenextrun)) { + if (empty($this->datestart)) { + $this->datenextrun = $now + ($this->frequency * $this->unitfrequency); + } else { + $this->datenextrun = $this->datestart + ($this->frequency * $this->unitfrequency); + } } - if ($this->datenextrun < $now && $this->frequency > 0 && $this->unitfrequency > 0) - { + if ($this->datenextrun < $now && $this->frequency > 0 && $this->unitfrequency > 0) { // Loop until date is after future - while ($this->datenextrun < $now) - { + while ($this->datenextrun < $now) { $this->datenextrun += ($this->frequency * $this->unitfrequency); // TODO For exact frequency (every month, every year, ...), use instead a dol_time_plus_duree($time, $duration_value, $duration_unit) @@ -1242,19 +1380,16 @@ class Cronjob extends CommonObject // Archive job - if ($this->autodelete == 2) - { + if ($this->autodelete == 2) { if (($this->maxrun > 0 && ($this->nbrun >= $this->maxrun)) - || ($this->dateend && ($this->datenextrun > $this->dateend))) - { + || ($this->dateend && ($this->datenextrun > $this->dateend))) { $this->status = self::STATUS_ARCHIVED; dol_syslog(get_class($this)."::reprogram_jobs Job will be set to archived", LOG_ERR); } } $result = $this->update($user); - if ($result < 0) - { + if ($result < 0) { dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR); return -1; } @@ -1289,14 +1424,16 @@ class Cronjob extends CommonObject $this->labelStatus = array(); // Force reset o array because label depends on other fields $this->labelStatusShort = array(); - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; $langs->load('users'); $moretext = ''; - if ($processing) $moretext = ' ('.$langs->trans("Running").')'; - elseif ($lastresult) $moretext .= ' ('.$langs->trans("Error").')'; + if ($processing) { + $moretext = ' ('.$langs->trans("Running").')'; + } elseif ($lastresult) { + $moretext .= ' ('.$langs->trans("Error").')'; + } $this->labelStatus[self::STATUS_DISABLED] = $langs->trans('Disabled').$moretext; $this->labelStatus[self::STATUS_ENABLED] = $langs->trans('Scheduled').$moretext; @@ -1305,9 +1442,15 @@ class Cronjob extends CommonObject } $statusType = 'status4'; - if ($status == 1 && $processing) $statusType = 'status1'; - if ($status == 0) $statusType = 'status5'; - if ($this->lastresult) $statusType = 'status8'; + if ($status == 1 && $processing) { + $statusType = 'status1'; + } + if ($status == 0) { + $statusType = 'status5'; + } + if ($this->lastresult) { + $statusType = 'status8'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } diff --git a/htdocs/cron/info.php b/htdocs/cron/info.php index 98319e51295..3f0e46e0104 100644 --- a/htdocs/cron/info.php +++ b/htdocs/cron/info.php @@ -30,7 +30,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $langs->loadLangs(array('admin', 'cron')); // Security check -if (!$user->rights->cron->read) accessforbidden(); +if (!$user->rights->cron->read) { + accessforbidden(); +} $id = GETPOST('id', 'int'); diff --git a/htdocs/cron/list.php b/htdocs/cron/list.php index 587bd1b28d1..712b2ceb163 100644 --- a/htdocs/cron/list.php +++ b/htdocs/cron/list.php @@ -34,7 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "cron", "bills", "members")); -if (!$user->rights->cron->read) accessforbidden(); +if (!$user->rights->cron->read) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) @@ -48,13 +50,19 @@ $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 = 't.status,t.priority'; -if (!$sortorder) $sortorder = 'DESC,ASC'; - +if (!$sortfield) { + $sortfield = 't.status,t.priority'; +} +if (!$sortorder) { + $sortorder = 'DESC,ASC'; +} +$optioncss = GETPOST('optioncss', 'alpha'); $mode = GETPOST('mode', 'aZ09'); //Search criteria $search_status = (GETPOSTISSET('search_status') ?GETPOST('search_status', 'int') : GETPOST('status', 'int')); @@ -63,7 +71,11 @@ $search_module_name = GETPOST("search_module_name", 'alpha'); $search_lastresult = GETPOST("search_lastresult", "alpha"); $securitykey = GETPOST('securitykey', 'alpha'); -$diroutputmassaction = $conf->cronjob->dir_output.'/temp/massgeneration/'.$user->id; +$outputdir = $conf->cron->dir_output; +if (empty($outputdir)) { + $outputdir = $conf->cronjob->dir_output; +} +$diroutputmassaction = $outputdir.'/temp/massgeneration/'.$user->id; $object = new Cronjob($db); @@ -82,21 +94,25 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_label = ''; $search_status = -1; $search_lastresult = ''; @@ -104,20 +120,17 @@ if (empty($reshook)) $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } $filter = array(); - if (!empty($search_label)) - { + if (!empty($search_label)) { $filter['t.label'] = $search_label; } // Delete jobs - if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->cron->delete) - { + if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->cron->delete) { //Delete cron task $object = new Cronjob($db); $object->id = $id; @@ -129,10 +142,8 @@ if (empty($reshook)) } // Execute jobs - if ($action == 'confirm_execute' && $confirm == "yes" && $user->rights->cron->execute) - { - if (!empty($conf->global->CRON_KEY) && $conf->global->CRON_KEY != $securitykey) - { + if ($action == 'confirm_execute' && $confirm == "yes" && $user->rights->cron->execute) { + if (!empty($conf->global->CRON_KEY) && $conf->global->CRON_KEY != $securitykey) { setEventMessages('Security key '.$securitykey.' is wrong', null, 'errors'); $action = ''; } else { @@ -148,12 +159,13 @@ if (empty($reshook)) // Programm next run $res = $object->reprogram_jobs($user->login, $now); - if ($res > 0) - { - if ($resrunjob >= 0) // We show the result of reprogram only if no error message already reported - { - if ($object->lastresult >= 0) setEventMessages($langs->trans("JobFinished"), null, 'mesgs'); - else setEventMessages($langs->trans("JobFinished"), null, 'errors'); + if ($res > 0) { + if ($resrunjob >= 0) { // We show the result of reprogram only if no error message already reported + if ($object->lastresult >= 0) { + setEventMessages($langs->trans("JobFinished"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("JobFinished"), null, 'errors'); + } } $action = ''; } else { @@ -162,10 +174,18 @@ if (empty($reshook)) } $param = '&search_status='.urlencode($search_status); - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($search_label) $param .= '&search_label='.urlencode($search_label); - 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 ($search_label) { + $param .= '&search_label='.urlencode($search_label); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -182,19 +202,21 @@ if (empty($reshook)) $permissiontodelete = $user->rights->cron->delete; $uploaddir = $conf->cron->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - if ($permissiontoadd) - { + if ($permissiontoadd) { $tmpcron = new Cronjob($db); - foreach ($toselect as $id) - { + foreach ($toselect as $id) { $result = $tmpcron->fetch($id); - if ($result) - { + if ($result) { $result = 0; - if ($massaction == 'disable') $result = $tmpcron->setStatut(Cronjob::STATUS_DISABLED); - elseif ($massaction == 'enable') $result = $tmpcron->setStatut(Cronjob::STATUS_ENABLED); + if ($massaction == 'disable') { + $result = $tmpcron->setStatut(Cronjob::STATUS_DISABLED); + } elseif ($massaction == 'enable') { + $result = $tmpcron->setStatut(Cronjob::STATUS_ENABLED); + } //else dol_print_error($db, 'Bad value for massaction'); - if ($result < 0) setEventMessages($tmpcron->error, $tmpcron->errors, 'errors'); + if ($result < 0) { + setEventMessages($tmpcron->error, $tmpcron->errors, 'errors'); + } } else { $error++; } @@ -248,8 +270,12 @@ $sql .= " t.libname,"; $sql .= " t.test"; $sql .= " FROM ".MAIN_DB_PREFIX."cronjob as t"; $sql .= " WHERE entity IN (0,".$conf->entity.")"; -if ($search_status >= 0 && $search_status < 2 && $search_status != '') $sql .= " AND t.status = ".(empty($search_status) ? '0' : '1'); -if ($search_lastresult != '') $sql .= natural_search("t.lastresult", $search_lastresult, 1); +if ($search_status >= 0 && $search_status < 2 && $search_status != '') { + $sql .= " AND t.status = ".(empty($search_status) ? '0' : '1'); +} +if ($search_lastresult != '') { + $sql .= natural_search("t.lastresult", $search_lastresult, 1); +} //Manage filter if (is_array($filter) && count($filter) > 0) { foreach ($filter as $key => $value) { @@ -274,12 +300,10 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -288,32 +312,48 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); -if (!$result) dol_print_error($db); +if (!$result) { + dol_print_error($db); +} $num = $db->num_rows($result); $arrayofselected = is_array($toselect) ? $toselect : array(); $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_status) $param .= '&search_status='.urlencode($search_status); -if ($search_label) $param .= '&search_label='.urlencode($search_label); -if ($search_module_name) $param .= '&search_module_name='.urlencode($search_module_name); -if ($search_lastresult) $param .= '&search_lastresult='.urlencode($search_lastresult); -if ($mode) $param .= '&mode='.urlencode($mode); -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 ($search_status) { + $param .= '&search_status='.urlencode($search_status); +} +if ($search_label) { + $param .= '&search_label='.urlencode($search_label); +} +if ($search_module_name) { + $param .= '&search_module_name='.urlencode($search_module_name); +} +if ($search_lastresult) { + $param .= '&search_lastresult='.urlencode($search_lastresult); +} +if ($mode) { + $param .= '&mode='.urlencode($mode); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; $stringcurrentdate = $langs->trans("CurrentHour").': '.dol_print_date(dol_now(), 'dayhour'); -if ($action == 'delete') -{ +if ($action == 'delete') { print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$id.$param, $langs->trans("CronDelete"), $langs->trans("CronConfirmDelete"), "confirm_delete", '', '', 1); } -if ($action == 'execute') -{ +if ($action == 'execute') { print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$id.'&securitykey='.$securitykey.$param, $langs->trans("CronExecute"), $langs->trans("CronConfirmExecute"), "confirm_execute", '', '', 1); } @@ -324,8 +364,12 @@ $arrayofmassactions = array( 'enable'=>$langs->trans("CronStatusActiveBtn"), 'disable'=>$langs->trans("CronStatusInactiveBtn"), ); -if ($user->rights->mymodule->delete) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); -if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($user->rights->cron->delete) { + $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); +} +if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); if ($mode == 'modulesetup') { @@ -337,7 +381,9 @@ if ($mode == 'modulesetup') { } print ''."\n"; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -362,7 +408,9 @@ print_barre_liste($pagetitle, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $ $text = $langs->trans("HoursOnThisPageAreOnServerTZ").' '.$stringcurrentdate.'
    '; -if (!empty($conf->global->CRON_WARNING_DELAY_HOURS)) $text .= $langs->trans("WarningCronDelayed", $conf->global->CRON_WARNING_DELAY_HOURS); +if (!empty($conf->global->CRON_WARNING_DELAY_HOURS)) { + $text .= $langs->trans("WarningCronDelayed", $conf->global->CRON_WARNING_DELAY_HOURS); +} print info_admin($text); print '
    '; @@ -417,18 +465,20 @@ print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", "", $param, ' print "
    '; - if (!empty($obj->label)) - { + if (!empty($obj->label)) { $object->ref = $langs->trans($obj->label); print ''.$object->getNomUrl(0, '', 1).''; $object->ref = $obj->rowid; @@ -465,9 +514,8 @@ if ($num > 0) print $object->priority; print ''; - if ($obj->jobtype == 'method') - { + print ''; + if ($obj->jobtype == 'method') { $text = $langs->trans("CronClass"); $texttoshow = $langs->trans('CronModule').': '.$obj->module_name.'
    '; $texttoshow .= $langs->trans('CronClass').': '.$obj->classesname.'
    '; @@ -475,8 +523,7 @@ if ($num > 0) $texttoshow .= $langs->trans('CronMethod').': '.$obj->methodename; $texttoshow .= '
    '.$langs->trans('CronArgs').': '.$obj->params; $texttoshow .= '
    '.$langs->trans('Comment').': '.$langs->trans($obj->note); - } elseif ($obj->jobtype == 'command') - { + } elseif ($obj->jobtype == 'command') { $text = $langs->trans('CronCommand'); $texttoshow = $langs->trans('CronCommand').': '.dol_trunc($obj->command); $texttoshow .= '
    '.$langs->trans('CronArgs').': '.$obj->params; @@ -486,28 +533,48 @@ if ($num > 0) print '
    '; - if ($obj->unitfrequency == "60") print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Minutes'); - if ($obj->unitfrequency == "3600") print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Hours'); - if ($obj->unitfrequency == "86400") print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Days'); - if ($obj->unitfrequency == "604800") print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Weeks'); + if ($obj->unitfrequency == "60") { + print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Minutes'); + } + if ($obj->unitfrequency == "3600") { + print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Hours'); + } + if ($obj->unitfrequency == "86400") { + print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Days'); + } + if ($obj->unitfrequency == "604800") { + print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Weeks'); + } print ''; - if (!empty($obj->datestart)) { print dol_print_date($db->jdate($obj->datestart), 'dayhour'); } + if (!empty($obj->datestart)) { + print dol_print_date($db->jdate($obj->datestart), 'dayhour', 'tzserver'); + } print ''; - if (!empty($obj->dateend)) { print dol_print_date($db->jdate($obj->dateend), 'dayhour'); } + if (!empty($obj->dateend)) { + print dol_print_date($db->jdate($obj->dateend), 'dayhour', 'tzserver'); + } print ''; - if (!empty($obj->nbrun)) { print $obj->nbrun; } else {print '0'; } - if (!empty($obj->maxrun)) { print ' / '.$obj->maxrun.''; } + if (!empty($obj->nbrun)) { + print $obj->nbrun; + } else { + print '0'; + } + if (!empty($obj->maxrun)) { + print ' / '.$obj->maxrun.''; + } print ''; - if (!empty($datelastrun)) { print dol_print_date($datelastrun, 'dayhoursec'); } + if (!empty($datelastrun)) { + print dol_print_date($datelastrun, 'dayhoursec', 'tzserver'); + } print ''; if ($obj->lastresult != '') { - if (empty($obj->lastresult)) print $obj->lastresult; - else print ''.dol_trunc($obj->lastresult).''; + if (empty($obj->lastresult)) { + print $obj->lastresult; + } else { + print ''.dol_trunc($obj->lastresult).''; + } } print ''; - if (!empty($obj->lastoutput)) {print dol_trunc(nl2br($obj->lastoutput), 50); } + if (!empty($obj->lastoutput)) { + print dol_trunc(nl2br($obj->lastoutput), 50); + } print ''; if (!empty($obj->datenextrun)) { $datenextrun = $db->jdate($obj->datenextrun); - if (empty($obj->status)) print ''; - print dol_print_date($datenextrun, 'dayhoursec'); - if ($obj->status == Cronjob::STATUS_ENABLED) - { - if ($obj->maxrun && $obj->nbrun >= $obj->maxrun) print img_warning($langs->trans("MaxRunReached")); - elseif ($datenextrun && $datenextrun < $now) print img_warning($langs->trans("Late")); + if (empty($obj->status)) { + print ''; + } + print dol_print_date($datenextrun, 'dayhoursec'); + if ($obj->status == Cronjob::STATUS_ENABLED) { + if ($obj->maxrun && $obj->nbrun >= $obj->maxrun) { + print img_warning($langs->trans("MaxRunReached")); + } elseif ($datenextrun && $datenextrun < $now) { + print img_warning($langs->trans("Late")); + } + } + if (empty($obj->status)) { + print ''; } - if (empty($obj->status)) print ''; } print ''; $backtopage = urlencode($_SERVER["PHP_SELF"].'?'.$param.($sortfield ? '&sortfield='.$sortfield : '').($sortorder ? '&sortorder='.$sortorder : '')); - if ($user->rights->cron->create) - { + if ($user->rights->cron->create) { print 'trans('Edit'))."\">".img_picto($langs->trans('Edit'), 'edit')."  "; } - if ($user->rights->cron->delete) - { + if ($user->rights->cron->delete) { print 'trans('CronDelete'))."\">".img_picto($langs->trans('CronDelete'), 'delete', '', false, 0, 0, '', 'marginleftonly')."   "; } else { print "trans('NotEnoughPermissions'))."\">".img_picto($langs->trans('NotEnoughPermissions'), 'delete', '', false, 0, 0, '', 'marginleftonly')."   "; } - if ($user->rights->cron->execute) - { + if ($user->rights->cron->execute) { if (!empty($obj->status)) { print 'global->CRON_KEY) ? '' : '&securitykey='.$conf->global->CRON_KEY); @@ -579,10 +654,11 @@ if ($num > 0) } else { print ''.img_picto($langs->trans('NotEnoughPermissions'), "playdisabled", '', false, 0, 0, '', 'marginleftonly').''; } - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '
    '; print ''; - foreach ($arrayofparameters as $title => $tab) - { + foreach ($arrayofparameters as $title => $tab) { print ''; - foreach ($tab as $key => $val) - { + foreach ($tab as $key => $val) { print ''; // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print ''; print ''; - print '"; + print ''; + print '"; // Note Private - print ''; - print '"; - */ + print ''; + print '"; + */ // Statut /*print ''; print '\n"; print '';*/ - if (!$conf->expedition_bon->enabled && !empty($conf->stock->enabled)) - { + if (!$conf->expedition_bon->enabled && !empty($conf->stock->enabled)) { // Entrepot $entrepot = new Entrepot($db); $entrepot->fetch($object->entrepot_id); @@ -524,8 +516,7 @@ if ($action == 'create') // Create. Seems to no be used print '
    '.$langs->trans("Parameter").''.$langs->trans("Value").'
    '.$langs->trans($title).'
    '; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); print ''; @@ -144,11 +143,9 @@ if ($action == 'edit') print ''; print ''; - foreach ($arrayofparameters as $title => $tab) - { + foreach ($arrayofparameters as $title => $tab) { print ''; - foreach ($tab as $key => $val) - { + foreach ($tab as $key => $val) { print ''; diff --git a/htdocs/datapolicy/admin/setupmail.php b/htdocs/datapolicy/admin/setupmail.php index 7076608898e..c25d4c2263d 100644 --- a/htdocs/datapolicy/admin/setupmail.php +++ b/htdocs/datapolicy/admin/setupmail.php @@ -39,8 +39,9 @@ if (GETPOST('l')) { $l = $langs->defaultlang; } // Access control -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} /* * Actions @@ -62,8 +63,9 @@ if ($action == 'setvalue' && $user->admin) { $result = dolibarr_set_const($db, $sub, GETPOST($sub), 'chaine', 0, '', $conf->entity); $sub = "DATAPOLICIESREFUSE_".$l; $result = dolibarr_set_const($db, $sub, GETPOST($sub), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } if (!$error) { $db->commit(); setEventMessage($langs->trans("SetupSaved")); diff --git a/htdocs/datapolicy/class/actions_datapolicy.class.php b/htdocs/datapolicy/class/actions_datapolicy.class.php index d6c16a6be4e..8dcfcdadb1c 100644 --- a/htdocs/datapolicy/class/actions_datapolicy.class.php +++ b/htdocs/datapolicy/class/actions_datapolicy.class.php @@ -332,8 +332,7 @@ class ActionsDatapolicy global $conf, $user, $langs; $langs->load('datapolicy@datapolicy'); - if (!empty($conf->global->DATAPOLICIES_ENABLE_EMAILS)) - { + if (!empty($conf->global->DATAPOLICIES_ENABLE_EMAILS)) { $dialog = '"; diff --git a/htdocs/datapolicy/class/datapolicy.class.php b/htdocs/datapolicy/class/datapolicy.class.php index 6d7b71129f7..a7ed08d7e6f 100644 --- a/htdocs/datapolicy/class/datapolicy.class.php +++ b/htdocs/datapolicy/class/datapolicy.class.php @@ -194,8 +194,9 @@ class DataPolicy $actiontypecode = 'AC_EMAIL'; $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; if ($message) { - if ($sendtocc) + if ($sendtocc) { $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc); + } $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subject); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":"); $actionmsg = dol_concatdesc($actionmsg, $message); diff --git a/htdocs/datapolicy/class/datapolicycron.class.php b/htdocs/datapolicy/class/datapolicycron.class.php index e1d8f7c36d4..28a713fb733 100644 --- a/htdocs/datapolicy/class/datapolicycron.class.php +++ b/htdocs/datapolicy/class/datapolicycron.class.php @@ -464,43 +464,36 @@ class DataPolicyCron $this->db->begin(); - foreach ($arrayofparameters as $key => $params) - { - if ($conf->global->$key != '' && is_numeric($conf->global->$key) && (int) $conf->global->$key > 0) - { + foreach ($arrayofparameters as $key => $params) { + if ($conf->global->$key != '' && is_numeric($conf->global->$key) && (int) $conf->global->$key > 0) { $sql = sprintf($params['sql'], (int) $conf->entity, (int) $conf->global->$key, (int) $conf->global->$key); $resql = $this->db->query($sql); - if ($resql && $this->db->num_rows($resql) > 0) - { + if ($resql && $this->db->num_rows($resql) > 0) { $num = $this->db->num_rows($resql); $i = 0; require_once $params['file']; $object = new $params['class']($this->db); - while ($i < $num && !$error) - { + while ($i < $num && !$error) { $obj = $this->db->fetch_object($resql); $object->fetch($obj->rowid); $object->id = $obj->rowid; - if ($object->isObjectUsed($obj->rowid) > 0) // If object to clean is used - { + if ($object->isObjectUsed($obj->rowid) > 0) { // If object to clean is used foreach ($params['fields_anonym'] as $fields => $val) { $object->$fields = $val; } $result = $object->update($obj->rowid, $user); - if ($result > 0) - { + if ($result > 0) { if ($params['class'] == 'Societe') { // We delete contacts of thirdparty $sql = "DELETE FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$obj->rowid; $result = $this->db->query($sql); - if ($result < 0) - { + if ($result < 0) { $errormsg = $this->db->lasterror(); $error++; } @@ -516,8 +509,7 @@ class DataPolicyCron } else { $result = $object->delete($user); } - if ($result < 0) - { + if ($result < 0) { $errormsg = $object->error; $error++; } @@ -533,8 +525,7 @@ class DataPolicyCron $this->db->commit(); - if (!$error) - { + if (!$error) { $this->output = $nbupdated.' record updated, '.$nbdeleted.' record deleted'; } else { $this->error = $errormsg; diff --git a/htdocs/datapolicy/mailing.php b/htdocs/datapolicy/mailing.php index 40597cc3e70..7e2dccaf7d4 100644 --- a/htdocs/datapolicy/mailing.php +++ b/htdocs/datapolicy/mailing.php @@ -29,13 +29,13 @@ require_once DOL_DOCUMENT_ROOT.'/datapolicy/class/datapolicy.class.php'; $idcontact = GETPOST('idc'); if (!empty($idcontact)) { - $contact = new Contact($db); - $contact->fetch($idcontact); - DataPolicy::sendMailDataPolicyContact($contact); + $contact = new Contact($db); + $contact->fetch($idcontact); + DataPolicy::sendMailDataPolicyContact($contact); } else { - $contacts = new DataPolicy($db); - $contacts->getAllContactNotInformed(); - $contacts->getAllCompaniesNotInformed(); - $contacts->getAllAdherentsNotInformed(); - echo $langs->trans('AllAgreementSend'); + $contacts = new DataPolicy($db); + $contacts->getAllContactNotInformed(); + $contacts->getAllCompaniesNotInformed(); + $contacts->getAllAdherentsNotInformed(); + echo $langs->trans('AllAgreementSend'); } diff --git a/htdocs/datapolicy/public/index.php b/htdocs/datapolicy/public/index.php index 0930d7d07d7..104b393bf7e 100644 --- a/htdocs/datapolicy/public/index.php +++ b/htdocs/datapolicy/public/index.php @@ -22,12 +22,15 @@ * \brief datapolicy setup page. */ -if (!defined('NOLOGIN')) +if (!defined('NOLOGIN')) { define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) +} +if (!defined('NOCSRFCHECK')) { define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test -if (!defined('NOREQUIREMENU')) +} +if (!defined('NOREQUIREMENU')) { define('NOREQUIREMENU', '1'); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; diff --git a/htdocs/dav/dav.class.php b/htdocs/dav/dav.class.php index 3a73f61c70c..6ff9e58b73a 100644 --- a/htdocs/dav/dav.class.php +++ b/htdocs/dav/dav.class.php @@ -82,8 +82,7 @@ class CdavLib LEFT OUTER JOIN '.MAIN_DB_PREFIX.'user AS u ON (u.rowid=fk_element) WHERE ar.element_type=\'user\' AND fk_actioncomm=a.id) AS other_users FROM '.MAIN_DB_PREFIX.'actioncomm AS a'; - if (!$this->user->rights->societe->client->voir)//FIXME si 'voir' on voit plus de chose ? - { + if (!$this->user->rights->societe->client->voir) {//FIXME si 'voir' on voit plus de chose ? $sql .= ' LEFT OUTER JOIN '.MAIN_DB_PREFIX.'societe_commerciaux AS sc ON (a.fk_soc = sc.fk_soc AND sc.fk_user='.$this->user->id.') LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON (s.rowid = sc.fk_soc) LEFT JOIN '.MAIN_DB_PREFIX.'socpeople AS sp ON (sp.fk_soc = sc.fk_soc AND sp.rowid = a.fk_contact) @@ -100,8 +99,7 @@ class CdavLib AND a.code IN (SELECT cac.code FROM '.MAIN_DB_PREFIX.'c_actioncomm cac WHERE cac.type<>\'systemauto\') AND a.entity IN ('.getEntity('societe', 1).')'; if ($oid !== false) { - if ($ouri === false) - { + if ($ouri === false) { $sql .= ' AND a.id = '.intval($oid); } else { $sql .= ' AND (a.id = '.intval($oid).' OR ac.uuidext = \''.$this->db->escape($ouri).'\')'; @@ -130,8 +128,7 @@ class CdavLib $location = $obj->location; // contact address - if (empty($location) && !empty($obj->address)) - { + if (empty($location) && !empty($obj->address)) { $location = trim(str_replace(array("\r", "\t", "\n"), ' ', $obj->address)); $location = trim($location.', '.$obj->zip); $location = trim($location.' '.$obj->town); @@ -139,8 +136,7 @@ class CdavLib } // contact address - if (empty($location) && !empty($obj->soc_address)) - { + if (empty($location) && !empty($obj->soc_address)) { $location = trim(str_replace(array("\r", "\t", "\n"), ' ', $obj->soc_address)); $location = trim($location.', '.$obj->soc_zip); $location = trim($location.' '.$obj->soc_town); @@ -148,16 +144,17 @@ class CdavLib } $address = explode("\n", $obj->address, 2); - foreach ($address as $kAddr => $vAddr) - { + foreach ($address as $kAddr => $vAddr) { $address[$kAddr] = trim(str_replace(array("\r", "\t"), ' ', str_replace("\n", ' | ', trim($vAddr)))); } $address[] = ''; $address[] = ''; - if ($obj->percent == -1 && trim($obj->datep) != '') + if ($obj->percent == -1 && trim($obj->datep) != '') { $type = 'VEVENT'; - else $type = 'VTODO'; + } else { + $type = 'VTODO'; + } $timezone = date_default_timezone_get(); @@ -169,60 +166,72 @@ class CdavLib $caldata .= "CREATED:".gmdate('Ymd\THis', strtotime($obj->datec))."Z\n"; $caldata .= "LAST-MODIFIED:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n"; $caldata .= "DTSTAMP:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n"; - if ($obj->sourceuid == '') + if ($obj->sourceuid == '') { $caldata .= "UID:".$obj->id.'-ev-'.$calid.'-cal-'.constant('CDAV_URI_KEY')."\n"; - else $caldata .= "UID:".$obj->sourceuid."\n"; + } else { + $caldata .= "UID:".$obj->sourceuid."\n"; + } $caldata .= "SUMMARY:".$obj->label."\n"; $caldata .= "LOCATION:".$location."\n"; $caldata .= "PRIORITY:".$obj->priority."\n"; - if ($obj->fulldayevent) - { + if ($obj->fulldayevent) { $caldata .= "DTSTART;VALUE=DATE:".date('Ymd', strtotime($obj->datep))."\n"; - if ($type == 'VEVENT') - { - if (trim($obj->datep2) != '') + if ($type == 'VEVENT') { + if (trim($obj->datep2) != '') { $caldata .= "DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep2) + 1)."\n"; - else $caldata .= "DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep) + (25 * 3600))."\n"; - } elseif (trim($obj->datep2) != '') + } else { + $caldata .= "DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep) + (25 * 3600))."\n"; + } + } elseif (trim($obj->datep2) != '') { $caldata .= "DUE;VALUE=DATE:".date('Ymd', strtotime($obj->datep2) + 1)."\n"; + } } else { $caldata .= "DTSTART;TZID=".$timezone.":".strtr($obj->datep, array(" "=>"T", ":"=>"", "-"=>""))."\n"; - if ($type == 'VEVENT') - { - if (trim($obj->datep2) != '') + if ($type == 'VEVENT') { + if (trim($obj->datep2) != '') { $caldata .= "DTEND;TZID=".$timezone.":".strtr($obj->datep2, array(" "=>"T", ":"=>"", "-"=>""))."\n"; - else $caldata .= "DTEND;TZID=".$timezone.":".strtr($obj->datep, array(" "=>"T", ":"=>"", "-"=>""))."\n"; - } elseif (trim($obj->datep2) != '') + } else { + $caldata .= "DTEND;TZID=".$timezone.":".strtr($obj->datep, array(" "=>"T", ":"=>"", "-"=>""))."\n"; + } + } elseif (trim($obj->datep2) != '') { $caldata .= "DUE;TZID=".$timezone.":".strtr($obj->datep2, array(" "=>"T", ":"=>"", "-"=>""))."\n"; + } } $caldata .= "CLASS:PUBLIC\n"; - if ($obj->transparency == 1) + if ($obj->transparency == 1) { $caldata .= "TRANSP:TRANSPARENT\n"; - else $caldata .= "TRANSP:OPAQUE\n"; + } else { + $caldata .= "TRANSP:OPAQUE\n"; + } - if ($type == 'VEVENT') + if ($type == 'VEVENT') { $caldata .= "STATUS:CONFIRMED\n"; - elseif ($obj->percent == 0) + } elseif ($obj->percent == 0) { $caldata .= "STATUS:NEEDS-ACTION\n"; - elseif ($obj->percent == 100) + } elseif ($obj->percent == 100) { $caldata .= "STATUS:COMPLETED\n"; - else { + } else { $caldata .= "STATUS:IN-PROCESS\n"; $caldata .= "PERCENT-COMPLETE:".$obj->percent."\n"; } $caldata .= "DESCRIPTION:"; $caldata .= strtr($obj->note, array("\n"=>"\\n", "\r"=>"")); - if (!empty($obj->soc_nom)) + if (!empty($obj->soc_nom)) { $caldata .= "\\n*DOLIBARR-SOC: ".$obj->soc_nom; - if (!empty($obj->soc_phone)) + } + if (!empty($obj->soc_phone)) { $caldata .= "\\n*DOLIBARR-SOC-TEL: ".$obj->soc_phone; - if (!empty($obj->firstname) || !empty($obj->lastname)) + } + if (!empty($obj->firstname) || !empty($obj->lastname)) { $caldata .= "\\n*DOLIBARR-CTC: ".trim($obj->firstname.' '.$obj->lastname); - if (!empty($obj->phone) || !empty($obj->phone_perso) || !empty($obj->phone_mobile)) + } + if (!empty($obj->phone) || !empty($obj->phone_perso) || !empty($obj->phone_mobile)) { $caldata .= "\\n*DOLIBARR-CTC-TEL: ".trim($obj->phone.' '.$obj->phone_perso.' '.$obj->phone_mobile); - if (strpos($obj->other_users, ',')) // several + } + if (strpos($obj->other_users, ',')) { // several $caldata .= "\\n*DOLIBARR-USR: ".$obj->other_users; + } $caldata .= "\n"; $caldata .= "END:".$type."\n"; @@ -243,24 +252,23 @@ class CdavLib $calid = ($calendarId * 1); $calevents = array(); - if (!$this->user->rights->agenda->myactions->read) + if (!$this->user->rights->agenda->myactions->read) { return $calevents; + } - if ($calid != $this->user->id && (!isset($this->user->rights->agenda->allactions->read) || !$this->user->rights->agenda->allactions->read)) + if ($calid != $this->user->id && (!isset($this->user->rights->agenda->allactions->read) || !$this->user->rights->agenda->allactions->read)) { return $calevents; + } $sql = $this->getSqlCalEvents($calid); $result = $this->db->query($sql); - if ($result) - { - while ($obj = $this->db->fetch_object($result)) - { + if ($result) { + while ($obj = $this->db->fetch_object($result)) { $calendardata = $this->toVCalendar($calid, $obj); - if ($bCalendarData) - { + if ($bCalendarData) { $calevents[] = array( 'calendardata' => $calendardata, 'uri' => $obj->id.'-ev-'.constant('CDAV_URI_KEY'), diff --git a/htdocs/dav/dav.lib.php b/htdocs/dav/dav.lib.php index bb4835c4d52..2861b8744bf 100644 --- a/htdocs/dav/dav.lib.php +++ b/htdocs/dav/dav.lib.php @@ -22,19 +22,21 @@ */ // define CDAV_CONTACT_TAG if not -if (!defined('CDAV_CONTACT_TAG')) -{ - if (isset($conf->global->CDAV_CONTACT_TAG)) +if (!defined('CDAV_CONTACT_TAG')) { + if (isset($conf->global->CDAV_CONTACT_TAG)) { define('CDAV_CONTACT_TAG', $conf->global->CDAV_CONTACT_TAG); - else define('CDAV_CONTACT_TAG', ''); + } else { + define('CDAV_CONTACT_TAG', ''); + } } // define CDAV_URI_KEY if not -if (!defined('CDAV_URI_KEY')) -{ - if (isset($conf->global->CDAV_URI_KEY)) +if (!defined('CDAV_URI_KEY')) { + if (isset($conf->global->CDAV_URI_KEY)) { define('CDAV_URI_KEY', $conf->global->CDAV_URI_KEY); - else define('CDAV_URI_KEY', substr(md5($_SERVER['HTTP_HOST']), 0, 8)); + } else { + define('CDAV_URI_KEY', substr(md5($_SERVER['HTTP_HOST']), 0, 8)); + } } diff --git a/htdocs/dav/fileserver.php b/htdocs/dav/fileserver.php index bd6df769553..c77d4d02226 100644 --- a/htdocs/dav/fileserver.php +++ b/htdocs/dav/fileserver.php @@ -25,12 +25,24 @@ * \brief Server DAV */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no menu to show -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); // If there is no menu to show +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} require "../main.inc.php"; require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; @@ -41,8 +53,7 @@ require_once DOL_DOCUMENT_ROOT.'/includes/sabre/autoload.php'; $user = new User($db); -if (isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER'] != '') -{ +if (isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER'] != '') { $user->fetch('', $_SERVER['PHP_AUTH_USER']); $user->getrights(); } @@ -51,17 +62,16 @@ if (isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER'] != '') $langs->loadLangs(array("main", "other")); -if (empty($conf->dav->enabled)) +if (empty($conf->dav->enabled)) { accessforbidden(); +} // Restrict API to some IPs -if (!empty($conf->global->DAV_RESTRICT_ON_IP)) -{ +if (!empty($conf->global->DAV_RESTRICT_ON_IP)) { $allowedip = explode(' ', $conf->global->DAV_RESTRICT_ON_IP); $ipremote = getUserRemoteIP(); - if (!in_array($ipremote, $allowedip)) - { + if (!in_array($ipremote, $allowedip)) { dol_syslog('Remote ip is '.$ipremote.', not into list '.$conf->global->DAV_RESTRICT_ON_IP); print 'DAV not allowed from the IP '.$ipremote; header('HTTP/1.1 503 DAV not allowed from your IP '.$ipremote); @@ -87,31 +97,30 @@ $authBackend = new \Sabre\DAV\Auth\Backend\BasicCallBack(function ($username, $p global $conf; global $dolibarr_main_authentication, $dolibarr_auto_user; - if (empty($user->login)) - { + if (empty($user->login)) { dol_syslog("Failed to authenticate to DAV, login is not provided", LOG_WARNING); return false; } - if ($user->socid > 0) - { + if ($user->socid > 0) { dol_syslog("Failed to authenticate to DAV, use is an external user", LOG_WARNING); return false; } - if ($user->login != $username) - { + if ($user->login != $username) { dol_syslog("Failed to authenticate to DAV, login does not match the login of loaded user", LOG_WARNING); return false; } // Authentication mode - if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'dolibarr'; + if (empty($dolibarr_main_authentication)) { + $dolibarr_main_authentication = 'dolibarr'; + } // Authentication mode: forceuser - if ($dolibarr_main_authentication == 'forceuser') - { - if (empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto'; - if ($dolibarr_auto_user != $username) - { + if ($dolibarr_main_authentication == 'forceuser') { + if (empty($dolibarr_auto_user)) { + $dolibarr_auto_user = 'auto'; + } + if ($dolibarr_auto_user != $username) { dol_syslog("Warning: your instance is set to use the automatic forced login '".$dolibarr_auto_user."' that is not the requested login. DAV usage is forbidden in this mode."); return false; } @@ -120,8 +129,9 @@ $authBackend = new \Sabre\DAV\Auth\Backend\BasicCallBack(function ($username, $p $authmode = explode(',', $dolibarr_main_authentication); $entity = (GETPOST('entity', 'int') ? GETPOST('entity', 'int') : (!empty($conf->entity) ? $conf->entity : 1)); - if (checkLoginPassEntity($username, $password, $entity, $authmode, 'dav') != $username) + if (checkLoginPassEntity($username, $password, $entity, $authmode, 'dav') != $username) { return false; + } return true; }); @@ -142,15 +152,13 @@ $nodes = array(); // Enable directories and features according to DAV setup // Public dir -if (!empty($conf->global->DAV_ALLOW_PUBLIC_DIR)) -{ +if (!empty($conf->global->DAV_ALLOW_PUBLIC_DIR)) { $nodes[] = new \Sabre\DAV\FS\Directory($publicDir); } // Private dir $nodes[] = new \Sabre\DAV\FS\Directory($privateDir); // ECM dir -if (!empty($conf->ecm->enabled) && !empty($conf->global->DAV_ALLOW_ECM_DIR)) -{ +if (!empty($conf->ecm->enabled) && !empty($conf->global->DAV_ALLOW_ECM_DIR)) { $nodes[] = new \Sabre\DAV\FS\Directory($ecmDir); } @@ -175,14 +183,15 @@ $server = new \Sabre\DAV\Server($nodes); // If you want to run the SabreDAV server in a custom location (using mod_rewrite for instance) // You can override the baseUri here. $baseUri = DOL_URL_ROOT.'/dav/fileserver.php/'; -if (isset($baseUri)) $server->setBaseUri($baseUri); +if (isset($baseUri)) { + $server->setBaseUri($baseUri); +} // Add authentication function if ((empty($conf->global->DAV_ALLOW_PUBLIC_DIR) || !preg_match('/'.preg_quote(DOL_URL_ROOT.'/dav/fileserver.php/public', '/').'/', $_SERVER["PHP_SELF"])) && !preg_match('/^sabreAction=asset&assetName=[a-zA-Z0-9%\-\/]+\.(png|css|woff|ico|ttf)$/', $_SERVER["QUERY_STRING"]) // URL for Sabre browser resources - ) -{ + ) { //var_dump($_SERVER["QUERY_STRING"]);exit; $server->addPlugin(new \Sabre\DAV\Auth\Plugin($authBackend)); } @@ -192,8 +201,7 @@ $lockPlugin = new \Sabre\DAV\Locks\Plugin($lockBackend); $server->addPlugin($lockPlugin); // Support for html frontend -if (empty($conf->global->DAV_DISABLE_BROWSER)) -{ +if (empty($conf->global->DAV_DISABLE_BROWSER)) { $browser = new \Sabre\DAV\Browser\Plugin(); $server->addPlugin($browser); } @@ -213,4 +221,6 @@ $server->addPlugin($tempFF); // And off we go! $server->exec(); -if (is_object($db)) $db->close(); +if (is_object($db)) { + $db->close(); +} diff --git a/htdocs/debugbar/class/DataCollector/DolLogsCollector.php b/htdocs/debugbar/class/DataCollector/DolLogsCollector.php index 626b4ec2613..520a0a20a72 100644 --- a/htdocs/debugbar/class/DataCollector/DolLogsCollector.php +++ b/htdocs/debugbar/class/DataCollector/DolLogsCollector.php @@ -2,6 +2,7 @@ use DebugBar\DataCollector\MessagesCollector; use Psr\Log\LogLevel; + //use ReflectionClass; /** @@ -74,15 +75,13 @@ class DolLogsCollector extends MessagesCollector $uselogfile = $conf->global->DEBUGBAR_USE_LOGFILE; - if ($uselogfile) - { + if ($uselogfile) { $this->getStorageLogs($this->path); } else { $log_levels = $this->getLevels(); foreach ($conf->logbuffer as $line) { - if ($this->nboflines >= $this->maxnboflines) - { + if ($this->nboflines >= $this->maxnboflines) { break; } foreach ($log_levels as $level_key => $level) { diff --git a/htdocs/debugbar/class/DataCollector/DolRequestDataCollector.php b/htdocs/debugbar/class/DataCollector/DolRequestDataCollector.php index 5f3e43a0d60..938643802d5 100644 --- a/htdocs/debugbar/class/DataCollector/DolRequestDataCollector.php +++ b/htdocs/debugbar/class/DataCollector/DolRequestDataCollector.php @@ -22,11 +22,11 @@ class DolRequestDataCollector extends RequestDataCollector if (isset($GLOBALS[$var])) { $arrayofvalues = $GLOBALS[$var]; - if ($var == '_COOKIE') - { - foreach ($arrayofvalues as $key => $val) - { - if (preg_match('/^DOLSESSID_/', $key)) $arrayofvalues[$key] = '*****hidden*****'; + if ($var == '_COOKIE') { + foreach ($arrayofvalues as $key => $val) { + if (preg_match('/^DOLSESSID_/', $key)) { + $arrayofvalues[$key] = '*****hidden*****'; + } } //var_dump($arrayofvalues); } diff --git a/htdocs/debugbar/class/DataCollector/DolTimeDataCollector.php b/htdocs/debugbar/class/DataCollector/DolTimeDataCollector.php index ae69b16eba7..ed5e979d539 100644 --- a/htdocs/debugbar/class/DataCollector/DolTimeDataCollector.php +++ b/htdocs/debugbar/class/DataCollector/DolTimeDataCollector.php @@ -2,7 +2,6 @@ use \DebugBar\DataCollector\TimeDataCollector; - /** * DolTimeDataCollector class */ diff --git a/htdocs/debugbar/class/DebugBar.php b/htdocs/debugbar/class/DebugBar.php index e3f2ac159f7..15bb2360ed8 100644 --- a/htdocs/debugbar/class/DebugBar.php +++ b/htdocs/debugbar/class/DebugBar.php @@ -4,6 +4,7 @@ dol_include_once('/debugbar/class/autoloader.php'); use \DebugBar\DebugBar; use \DebugBar\DataCollector\PhpInfoCollector; + dol_include_once('/debugbar/class/DataCollector/DolMessagesCollector.php'); dol_include_once('/debugbar/class/DataCollector/DolRequestDataCollector.php'); dol_include_once('/debugbar/class/DataCollector/DolConfigCollector.php'); diff --git a/htdocs/delivery/card.php b/htdocs/delivery/card.php index 8b0b53bd37d..69fd5a9bec0 100644 --- a/htdocs/delivery/card.php +++ b/htdocs/delivery/card.php @@ -34,12 +34,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/sendings.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) +if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -if (!empty($conf->expedition_bon->enabled)) +} +if (!empty($conf->expedition_bon->enabled)) { require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; -if (!empty($conf->stock->enabled)) +} +if (!empty($conf->stock->enabled)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; +} if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; @@ -48,7 +51,9 @@ if (!empty($conf->projet->enabled)) { // Load translation files required by the page $langs->loadLangs(array("sendings", "bills", 'deliveries', 'orders')); -if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); +if (!empty($conf->incoterm->enabled)) { + $langs->load('incoterm'); +} $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); @@ -56,7 +61,9 @@ $backtopage = GETPOST('backtopage', 'alpha'); // Security check $id = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expedition', $id, 'delivery', 'delivery'); $object = new Delivery($db); @@ -84,8 +91,7 @@ $error = 0; $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($action == 'add') -{ +if ($action == 'add') { $db->begin(); $object->date_delivery = dol_now(); @@ -103,13 +109,11 @@ if ($action == 'add') $commande->fetch($object->commande_id); $commande->fetch_lines(); $num = count($commande->lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $qty = "qtyl".$i; $idl = "idl".$i; $qtytouse = price2num(GETPOST($qty)); - if ($qtytouse > 0) - { + if ($qtytouse > 0) { $object->addline(GETPOST($idl), price2num($qtytouse)); } } @@ -128,17 +132,19 @@ if ($action == 'add') } elseif ($action == 'confirm_valid' && $confirm == 'yes' && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery->creer)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery_advance->validate))) -) -{ +) { $result = $object->valid($user); // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -147,74 +153,70 @@ if ($action == 'add') $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } } -if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->expedition->delivery->supprimer) -{ +if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->expedition->delivery->supprimer) { $db->begin(); $result = $object->delete(); - if ($result > 0) - { + if ($result > 0) { $db->commit(); - if (!empty($backtopage)) header("Location: ".$backtopage); - else header("Location: ".DOL_URL_ROOT.'/expedition/list.php?restore_lastsearch_values=1'); + if (!empty($backtopage)) { + header("Location: ".$backtopage); + } else { + header("Location: ".DOL_URL_ROOT.'/expedition/list.php?restore_lastsearch_values=1'); + } exit; } else { $db->rollback(); } } -if ($action == 'setdate_delivery' && $user->rights->expedition->delivery->creer) -{ +if ($action == 'setdate_delivery' && $user->rights->expedition->delivery->creer) { $datedelivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int')); $result = $object->setDeliveryDate($user, $datedelivery); - if ($result < 0) - { + if ($result < 0) { $mesg = '
    '.$object->error.'
    '; } -} - -// Set incoterm -elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) -{ +} elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) { + // Set incoterm $result = $object->setIncoterms((int) GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); } // Update extrafields -if ($action == 'update_extras') -{ +if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('DELIVERY_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } // Extrafields line -if ($action == 'update_extras_line') -{ +if ($action == 'update_extras_line') { $array_options = array(); $num = count($object->lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { // Extrafields $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line); $array_options[$i] = $extrafields->getOptionalsFromPost($extralabelsline, $i); @@ -227,8 +229,7 @@ if ($action == 'update_extras_line') } $ret = $object->update_line($object->lines[$i]->id, $array_options[$i]); // extrafields update - if ($ret < 0) - { + if ($ret < 0) { $mesg = '
    '.$object->error.'
    '; $error++; } @@ -253,24 +254,20 @@ llxHeader('', $langs->trans('Delivery'), 'Livraison'); $form = new Form($db); $formfile = new FormFile($db); -if ($action == 'create') // Create. Seems to no be used -{ +if ($action == 'create') { // Create. Seems to no be used } else // View { - if ($object->id > 0) - { + if ($object->id > 0) { // Origin of a 'livraison' (delivery receipt) is ALWAYS 'expedition' (shipment). // However, origin of shipment in future may differs (commande, proposal, ...) $expedition = new Expedition($db); $result = $expedition->fetch($object->origin_id); $typeobject = $expedition->origin; // example: commande - if ($object->origin_id > 0) - { + if ($object->origin_id > 0) { $object->fetch_origin(); } - if ($object->id > 0) - { + if ($object->id > 0) { $soc = new Societe($db); $soc->fetch($object->socid); @@ -289,8 +286,7 @@ if ($action == 'create') // Create. Seems to no be used * Confirmation de la suppression * */ - if ($action == 'delete') - { + if ($action == 'delete') { $expedition_id = GETPOST("expid"); print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id.'&expid='.$expedition_id.'&backtopage='.urlencode($backtopage), $langs->trans("DeleteDeliveryReceipt"), $langs->trans("DeleteDeliveryReceiptConfirm", $object->ref), 'confirm_delete', '', '', 1); } @@ -298,8 +294,7 @@ if ($action == 'create') // Create. Seems to no be used /* * Confirmation de la validation */ - if ($action == 'valid') - { + if ($action == 'valid') { print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans("ValidateDeliveryReceipt"), $langs->trans("ValidateDeliveryReceiptConfirm", $object->ref), 'confirm_valid', '', '', 1); } @@ -308,13 +303,11 @@ if ($action == 'create') // Create. Seems to no be used * Delivery */ - if ($typeobject == 'commande' && $expedition->origin_id > 0 && !empty($conf->commande->enabled)) - { + if ($typeobject == 'commande' && $expedition->origin_id > 0 && !empty($conf->commande->enabled)) { $objectsrc = new Commande($db); $objectsrc->fetch($expedition->origin_id); } - if ($typeobject == 'propal' && $expedition->origin_id > 0 && !empty($conf->propal->enabled)) - { + if ($typeobject == 'propal' && $expedition->origin_id > 0 && !empty($conf->propal->enabled)) { $objectsrc = new Propal($db); $objectsrc->fetch($expedition->origin_id); } @@ -390,19 +383,18 @@ if ($action == 'create') // Create. Seems to no be used // Ref print ''; - print ''; + print ''; // Client print ''; print ''; print ""; - */ + */ // Document origine - if ($typeobject == 'commande' && $expedition->origin_id && !empty($conf->commande->enabled)) - { + if ($typeobject == 'commande' && $expedition->origin_id && !empty($conf->commande->enabled)) { print ''; $order = new Commande($db); $order->fetch($expedition->origin_id); @@ -411,8 +403,7 @@ if ($action == 'create') // Create. Seems to no be used print "\n"; print ''; } - if ($typeobject == 'propal' && $expedition->origin_id && !empty($conf->propal->enabled)) - { + if ($typeobject == 'propal' && $expedition->origin_id && !empty($conf->propal->enabled)) { $propal = new Propal($db); $propal->fetch($expedition->origin_id); print ''; @@ -433,11 +424,12 @@ if ($action == 'create') // Create. Seems to no be used print $langs->trans('DateReceived'); print ''; - if ($action != 'editdate_delivery') print ''; + if ($action != 'editdate_delivery') { + print ''; + } print '
    '.$langs->trans("Parameter").''.$langs->trans("Value").'
    '.$langs->trans($title).'
    '; print $form->textwithpicto($langs->trans($key), $langs->trans('DATAPOLICY_Tooltip_SETUP')); print ''.($conf->global->$key == '' ? $langs->trans('None') : $valTab[$conf->global->$key]).'
    '.$langs->trans("Ref").''; - print $object->ref; - print '
    '; + print $object->ref; + print '
    '.$langs->trans("Customer").''.$soc->getNomUrl(1).'
    '.$langs->trans("RefOrder").'
    '.$langs->trans("RefProposal").'id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).'id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).'
    '; print '
    '; - if ($action == 'editdate_delivery') - { + if ($action == 'editdate_delivery') { print ''; print ''; print ''; @@ -451,19 +443,20 @@ if ($action == 'create') // Create. Seems to no be used print '
    '; print '
    '; print $langs->trans('IncotermLabel'); print ''; - if ($user->rights->expedition->delivery->creer) print ''.img_edit().''; - else print ' '; + if ($user->rights->expedition->delivery->creer) { + print ''.img_edit().''; + } else { + print ' '; + } print '
    '; print '
    '; - if ($action != 'editincoterm') - { + if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1); } else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); @@ -473,25 +466,24 @@ if ($action == 'create') // Create. Seems to no be used /* A delivery note should be just more properties of a shipment, so notes are on shipment // Note Public - print '
    '.$langs->trans("NotePublic").''; - print nl2br($object->note_public); - print "
    '.$langs->trans("NotePublic").''; + print nl2br($object->note_public); + print "
    '.$langs->trans("NotePrivate").''; - print nl2br($object->note_private); - print "
    '.$langs->trans("NotePrivate").''; + print nl2br($object->note_private); + print "
    '.$langs->trans("Status").''.$object->getLibStatut(4)."
    '; - if ($num_prod) - { + if ($num_prod) { $i = 0; print ''; @@ -534,29 +525,30 @@ if ($action == 'create') // Create. Seems to no be used print ''; print "\n"; } - while ($i < $num_prod) - { + while ($i < $num_prod) { $parameters = array('i' => $i, 'line' => $object->lines[$i], 'num' => $num_prod); $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $object, $action); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { print ''; - if ($object->lines[$i]->fk_product > 0) - { + if ($object->lines[$i]->fk_product > 0) { $product = new Product($db); $product->fetch($object->lines[$i]->fk_product); // Define output language - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && !empty($_REQUEST['lang_id'])) $newlang = $_REQUEST['lang_id']; - if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + if (empty($newlang) && !empty($_REQUEST['lang_id'])) { + $newlang = $_REQUEST['lang_id']; + } + if (empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -570,22 +562,27 @@ if ($action == 'create') // Create. Seems to no be used // Affiche ligne produit $text = ''; - if ($object->lines[$i]->fk_product_type == 1) $text .= img_object($langs->trans('ShowService'), 'service'); - else $text .= img_object($langs->trans('ShowProduct'), 'product'); + if ($object->lines[$i]->fk_product_type == 1) { + $text .= img_object($langs->trans('ShowService'), 'service'); + } else { + $text .= img_object($langs->trans('ShowProduct'), 'product'); + } $text .= ' '.$object->lines[$i]->product_ref.''; $text .= ' - '.$label; $description = (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($object->lines[$i]->description)); //print $description; print $form->textwithtooltip($text, $description, 3, '', '', $i); print_date_range($object->lines[$i]->date_start, $object->lines[$i]->date_end); - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { print (!empty($object->lines[$i]->description) && $object->lines[$i]->description != $object->lines[$i]->product_label) ? '
    '.dol_htmlentitiesbr($object->lines[$i]->description) : ''; } } else { print "
    '; - if ($object->socid) { + if (!empty($conf->societe->enabled) && !empty($conf->global->DONATION_USE_THIRDPARTIES)) { $company = new Societe($db); - $result = $company->fetch($object->socid); - print ''; + print ''; } else { print ''; print ''; @@ -749,8 +759,7 @@ if (!empty($id) && $action != 'edit') //print $sql; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; $total = 0; print '
    '.$langs->trans("QtyReceived").'
    "; - if ($object->lines[$i]->fk_product_type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if ($object->lines[$i]->fk_product_type == 1) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($object->lines[$i]->label)) { $text .= ' '.$object->lines[$i]->label.''; @@ -640,23 +637,18 @@ if ($action == 'create') // Create. Seems to no be used * Boutons actions */ - if ($user->socid == 0) - { + if ($user->socid == 0) { print '
    '; - if ($object->statut == 0 && $num_prod > 0) - { + if ($object->statut == 0 && $num_prod > 0) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery_advance->validate))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery_advance->validate))) { print ''.$langs->trans("Validate").''; } } - if ($user->rights->expedition->delivery->supprimer) - { - if ($conf->expedition_bon->enabled) - { + if ($user->rights->expedition->delivery->supprimer) { + if ($conf->expedition_bon->enabled) { print ''.$langs->trans("Delete").''; } else { print ''.$langs->trans("Delete").''; @@ -670,7 +662,7 @@ if ($action == 'create') // Create. Seems to no be used print ''; } print ''."\n"; @@ -408,8 +414,7 @@ if ($action == 'create') print $form->selectyesno("public", $public_donation, 1); print "\n"; - if (empty($conf->societe->enabled) || empty($conf->global->DONATION_USE_THIRDPARTIES)) - { + if (empty($conf->societe->enabled) || empty($conf->global->DONATION_USE_THIRDPARTIES)) { print "".''; print "".''; print "".''; @@ -426,7 +431,9 @@ if ($action == 'create') // Country print ''; print "".''; @@ -458,8 +465,7 @@ if ($action == 'create') print ''; } - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { print "\n"; @@ -469,8 +475,7 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } @@ -495,8 +500,7 @@ if ($action == 'create') /* */ /* ************************************************************ */ -if (!empty($id) && $action == 'edit') -{ +if (!empty($id) && $action == 'edit') { $result = $object->fetch($id); if ($result < 0) { dol_print_error($db, $object->error); exit; @@ -545,11 +549,15 @@ if (!empty($id) && $action == 'edit') print ""; print "\n"; - if ($object->socid && !empty($conf->societe->enabled) && !empty($conf->global->DONATION_USE_THIRDPARTIES)) { + if (!empty($conf->societe->enabled) && !empty($conf->global->DONATION_USE_THIRDPARTIES)) { $company = new Societe($db); - $result = $company->fetch($object->socid); - print ''; + print ''; } else { $langs->load("companies"); print ''; @@ -577,8 +585,11 @@ if (!empty($id) && $action == 'edit') } // Payment mode print "\n"; @@ -599,9 +610,8 @@ if (!empty($id) && $action == 'edit') $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { - print $object->showOptionals($extrafields, 'edit', $parameters); + if (empty($reshook)) { + print $object->showOptionals($extrafields, 'edit', $parameters); } print "
    '; /* - * Documents generated + * Documents generated */ $objectref = dol_sanitizeFileName($object->ref); @@ -683,10 +675,9 @@ if ($action == 'create') // Create. Seems to no be used print $formfile->showdocuments('delivery', $objectref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); /* - * Linked object block (of linked shipment) - */ - if ($object->origin == 'expedition') - { + * Linked object block (of linked shipment) + */ + if ($object->origin == 'expedition') { $shipment = new Expedition($db); $shipment->fetch($object->origin_id); diff --git a/htdocs/delivery/class/delivery.class.php b/htdocs/delivery/class/delivery.class.php index 9c1e9682a10..5b14b509de4 100644 --- a/htdocs/delivery/class/delivery.class.php +++ b/htdocs/delivery/class/delivery.class.php @@ -31,8 +31,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; -if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; -if (!empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +if (!empty($conf->propal->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +} +if (!empty($conf->commande->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +} /** @@ -132,7 +136,9 @@ class Delivery extends CommonObject dol_syslog("Delivery::create"); - if (empty($this->model_pdf)) $this->model_pdf = $conf->global->DELIVERY_ADDON_PDF; + if (empty($this->model_pdf)) { + $this->model_pdf = $conf->global->DELIVERY_ADDON_PDF; + } $error = 0; @@ -176,8 +182,7 @@ class Delivery extends CommonObject dol_syslog("Delivery::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."delivery"); $numref = "(PROV".$this->id.")"; @@ -188,10 +193,8 @@ class Delivery extends CommonObject dol_syslog("Delivery::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$conf->expedition_bon->enabled) - { + if ($resql) { + if (!$conf->expedition_bon->enabled) { $commande = new Commande($this->db); $commande->id = $this->commande_id; $commande->fetch_lines(); @@ -202,38 +205,33 @@ class Delivery extends CommonObject * Inserting products into the database */ $num = count($this->lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $origin_id = $this->lines[$i]->origin_line_id; - if (!$origin_id) $origin_id = $this->lines[$i]->commande_ligne_id; // For backward compatibility + if (!$origin_id) { + $origin_id = $this->lines[$i]->commande_ligne_id; // For backward compatibility + } - if (!$this->create_line($origin_id, $this->lines[$i]->qty, $this->lines[$i]->fk_product, $this->lines[$i]->description)) - { + if (!$this->create_line($origin_id, $this->lines[$i]->qty, $this->lines[$i]->fk_product, $this->lines[$i]->description)) { $error++; } } - if (!$error && $this->id && $this->origin_id) - { + if (!$error && $this->id && $this->origin_id) { $ret = $this->add_object_linked(); - if (!$ret) - { + if (!$ret) { $error++; } - if (!$conf->expedition_bon->enabled) - { + if (!$conf->expedition_bon->enabled) { // TODO standardize status uniformiser les statuts $ret = $this->setStatut(2, $this->origin_id, $this->origin); - if (!$ret) - { + if (!$ret) { $error++; } } } - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -281,13 +279,11 @@ class Delivery extends CommonObject $sql .= $qty.")"; dol_syslog(get_class($this)."::create_line", LOG_DEBUG); - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $error++; } - if ($error == 0) - { + if ($error == 0) { return 1; } } @@ -311,14 +307,12 @@ class Delivery extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."delivery as l"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = l.rowid AND el.targettype = '".$this->db->escape($this->element)."'"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON l.fk_incoterms = i.rowid'; - $sql .= " WHERE l.rowid = ".$id; + $sql .= " WHERE l.rowid = ".((int) $id); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -346,7 +340,9 @@ class Delivery extends CommonObject $this->label_incoterms = $obj->label_incoterms; $this->db->free($result); - if ($this->statut == 0) $this->draft = 1; + if ($this->statut == 0) { + $this->draft = 1; + } // Retrieve all extrafields // fetch optionals attributes and labels @@ -354,8 +350,7 @@ class Delivery extends CommonObject // Load lines $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { return -3; } @@ -390,15 +385,12 @@ class Delivery extends CommonObject $error = 0; if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery_advance->validate))) - { - if (!empty($conf->global->DELIVERY_ADDON_NUMBER)) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery_advance->validate))) { + if (!empty($conf->global->DELIVERY_ADDON_NUMBER)) { // Setting the command numbering module name $modName = $conf->global->DELIVERY_ADDON_NUMBER; - if (is_readable(DOL_DOCUMENT_ROOT.'/core/modules/delivery/'.$modName.'.php')) - { + if (is_readable(DOL_DOCUMENT_ROOT.'/core/modules/delivery/'.$modName.'.php')) { require_once DOL_DOCUMENT_ROOT.'/core/modules/delivery/'.$modName.'.php'; $now = dol_now(); @@ -408,8 +400,7 @@ class Delivery extends CommonObject $soc = new Societe($this->db); $soc->fetch($this->socid); - if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life - { + if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life $numref = $objMod->delivery_get_num($soc, $this); } else { $numref = $this->ref; @@ -424,11 +415,9 @@ class Delivery extends CommonObject $sql .= " AND entity = ".$conf->entity; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { return 0; } } @@ -442,50 +431,47 @@ class Delivery extends CommonObject $sql .= " AND fk_statut = 0"; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $this->error = $this->db->lasterror(); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('DELIVERY_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expedition/receipt/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expedition/receipt/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($numref); $dirsource = $conf->expedition->dir_output.'/receipt/'.$oldref; $dirdest = $conf->expedition->dir_output.'/receipt/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->expedition->dir_output.'/receipt/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -497,8 +483,7 @@ class Delivery extends CommonObject } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $numref; $this->statut = 1; } @@ -506,8 +491,7 @@ class Delivery extends CommonObject dol_syslog(get_class($this)."::valid ok"); } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -540,8 +524,7 @@ class Delivery extends CommonObject $this->lines = array(); $num = count($expedition->lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $line = new DeliveryLine($this->db); $line->origin_line_id = $expedition->lines[$i]->origin_line_id; $line->label = $expedition->lines[$i]->label; @@ -583,22 +566,23 @@ class Delivery extends CommonObject global $conf; $error = 0; - if ($id > 0 && !$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) // For avoid conflicts if trigger used - { + if ($id > 0 && !$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used $line = new DeliveryLine($this->db); $line->array_options = $array_options; $line->id = $id; $result = $line->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->error[] = $line->error; $error++; } } - if (!$error) return 1; - else return -1; + if (!$error) { + return 1; + } else { + return -1; + } } @@ -628,13 +612,11 @@ class Delivery extends CommonObject */ public function deleteline($lineid) { - if ($this->statut == 0) - { + if ($this->statut == 0) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet"; $sql .= " WHERE rowid = ".$lineid; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->update_price(); return 1; @@ -660,37 +642,31 @@ class Delivery extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."deliverydet"; $sql .= " WHERE fk_delivery = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."delivery"; $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->db->commit(); // Deleting pdf folder's draft On efface le repertoire de pdf provisoire $ref = dol_sanitizeFileName($this->ref); - if (!empty($conf->expedition->dir_output)) - { + if (!empty($conf->expedition->dir_output)) { $dir = $conf->expedition->dir_output.'/receipt/'.$ref; $file = $dir.'/'.$ref.'.pdf'; - if (file_exists($file)) - { - if (!dol_delete_file($file)) - { + if (file_exists($file)) { + if (!dol_delete_file($file)) { return 0; } } - if (file_exists($dir)) - { - if (!dol_delete_dir($dir)) - { + if (file_exists($dir)) { + if (!dol_delete_dir($dir)) { $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir); return 0; } @@ -699,8 +675,7 @@ class Delivery extends CommonObject // Call trigger $result = $this->call_trigger('DELIVERY_DELETE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -4; } @@ -746,16 +721,24 @@ class Delivery extends CommonObject //{ // 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 = ''; $linkend = ''; - if ($withpicto) $result .= ($linkstart.img_object($label, $this->picto, 'class="classfortooltip"').$linkend); - if ($withpicto && $withpicto != 2) $result .= ' '; + if ($withpicto) { + $result .= ($linkstart.img_object($label, $this->picto, 'class="classfortooltip"').$linkend); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } $result .= $linkstart.$this->ref.$linkend; return $result; } @@ -782,12 +765,10 @@ class Delivery extends CommonObject dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $line = new DeliveryLine($this->db); $obj = $this->db->fetch_object($resql); @@ -862,8 +843,7 @@ class Delivery extends CommonObject // phpcs:enable global $langs; - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[-1] = $langs->trans('StatusDeliveryCanceled'); @@ -875,8 +855,12 @@ class Delivery extends CommonObject } $statusType = 'status0'; - if ($status == -1) $statusType = 'status5'; - if ($status == 1) $statusType = 'status4'; + if ($status == -1) { + $statusType = 'status5'; + } + if ($status == 1) { + $statusType = 'status4'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -905,12 +889,10 @@ class Delivery extends CommonObject $sql .= $this->db->plimit(100); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -961,13 +943,11 @@ class Delivery extends CommonObject $sqlSourceLine .= " WHERE fk_".$this->linked_object[0]['type']." = ".$this->linked_object[0]['linkid']; $resultSourceLine = $this->db->query($sqlSourceLine); - if ($resultSourceLine) - { + if ($resultSourceLine) { $num_lines = $this->db->num_rows($resultSourceLine); $i = 0; $resultArray = array(); - while ($i < $num_lines) - { + while ($i < $num_lines) { $objSourceLine = $this->db->fetch_object($resultSourceLine); // Get lines of sources alread delivered @@ -985,10 +965,8 @@ class Delivery extends CommonObject $result = $this->db->query($sql); $row = $this->db->fetch_row($result); - if ($objSourceLine->qty - $row[1] > 0) - { - if ($row[0] == $objSourceLine->rowid) - { + if ($objSourceLine->qty - $row[1] > 0) { + if ($row[0] == $objSourceLine->rowid) { $array[$i]['qty'] = $objSourceLine->qty - $row[1]; } else { $array[$i]['qty'] = $objSourceLine->qty; @@ -996,8 +974,7 @@ class Delivery extends CommonObject $array[$i]['ref'] = $objSourceLine->ref; $array[$i]['label'] = $objSourceLine->label ? $objSourceLine->label : $objSourceLine->description; - } elseif ($objSourceLine->qty - $row[1] < 0) - { + } elseif ($objSourceLine->qty - $row[1] < 0) { $array[$i]['qty'] = $objSourceLine->qty - $row[1]." Erreur livraison !"; $array[$i]['ref'] = $objSourceLine->ref; $array[$i]['label'] = $objSourceLine->label ? $objSourceLine->label : $objSourceLine->description; @@ -1021,16 +998,14 @@ class Delivery extends CommonObject */ public function setDeliveryDate($user, $delivery_date) { - if ($user->rights->expedition->creer) - { + if ($user->rights->expedition->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."delivery"; $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null'); $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->date_delivery = $delivery_date; return 1; } else { diff --git a/htdocs/document.php b/htdocs/document.php index 060722e8d5b..59501cc4701 100644 --- a/htdocs/document.php +++ b/htdocs/document.php @@ -32,24 +32,42 @@ //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} // For direct external download link, we don't need to load/check we are into a login session -if (isset($_GET["hashp"]) && !defined("NOLOGIN")) -{ - if (!defined("NOLOGIN")) define("NOLOGIN", 1); - if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. - if (!defined("NOIPCHECK")) define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (isset($_GET["hashp"]) && !defined("NOLOGIN")) { + if (!defined("NOLOGIN")) { + define("NOLOGIN", 1); + } + if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. + } + if (!defined("NOIPCHECK")) { + define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip + } } // Some value of modulepart can be used to get resources that are public so no login are required. -if ((isset($_GET["modulepart"]) && $_GET["modulepart"] == 'medias')) -{ - if (!defined("NOLOGIN")) define("NOLOGIN", 1); - if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. - if (!defined("NOIPCHECK")) define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if ((isset($_GET["modulepart"]) && $_GET["modulepart"] == 'medias')) { + if (!defined("NOLOGIN")) { + define("NOLOGIN", 1); + } + if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. + } + if (!defined("NOIPCHECK")) { + define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip + } } /** @@ -84,17 +102,26 @@ $urlsource = GETPOST('urlsource', 'alpha'); $entity = GETPOST('entity', 'int') ?GETPOST('entity', 'int') : $conf->entity; // Security check -if (empty($modulepart) && empty($hashp)) accessforbidden('Bad link. Bad value for parameter modulepart', 0, 0, 1); -if (empty($original_file) && empty($hashp)) accessforbidden('Bad link. Missing identification to find file (original_file or hashp)', 0, 0, 1); -if ($modulepart == 'fckeditor') $modulepart = 'medias'; // For backward compatibility +if (empty($modulepart) && empty($hashp)) { + accessforbidden('Bad link. Bad value for parameter modulepart', 0, 0, 1); +} +if (empty($original_file) && empty($hashp)) { + accessforbidden('Bad link. Missing identification to find file (original_file or hashp)', 0, 0, 1); +} +if ($modulepart == 'fckeditor') { + $modulepart = 'medias'; // For backward compatibility +} $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} // For some module part, dir may be privates -if (in_array($modulepart, array('facture_paiement', 'unpaid'))) -{ - if (!$user->rights->societe->client->voir || $socid) $original_file = 'private/'.$user->id.'/'.$original_file; // If user has no permission to see all, output dir is specific to user +if (in_array($modulepart, array('facture_paiement', 'unpaid'))) { + if (!$user->rights->societe->client->voir || $socid) { + $original_file = 'private/'.$user->id.'/'.$original_file; // If user has no permission to see all, output dir is specific to user + } } @@ -111,25 +138,20 @@ if (in_array($modulepart, array('facture_paiement', 'unpaid'))) */ // If we have a hash public (hashp), we guess the original_file. -if (!empty($hashp)) -{ +if (!empty($hashp)) { include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile = new EcmFiles($db); $result = $ecmfile->fetch(0, '', '', '', $hashp); - if ($result > 0) - { + if ($result > 0) { $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory // filepath can be 'users/X' or 'X/propale/PR11111' - if (is_numeric($tmp[0])) // If first tmp is numeric, it is subdir of company for multicompany, we take next part. - { + if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part. $tmp = explode('/', $tmp[1], 2); } $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path - if ($modulepart) // Not required, so often not defined, for link using public hashp parameter. - { - if ($moduleparttocheck == $modulepart) - { + if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter. + if ($moduleparttocheck == $modulepart) { // We remove first level of directory $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir //var_dump($original_file); exit; @@ -148,14 +170,23 @@ if (!empty($hashp)) // Define attachment (attachment=true to force choice popup 'open'/'save as') $attachment = true; -if (preg_match('/\.(html|htm)$/i', $original_file)) $attachment = false; -if (isset($_GET["attachment"])) $attachment = GETPOST("attachment", 'alpha') ?true:false; -if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS)) $attachment = false; +if (preg_match('/\.(html|htm)$/i', $original_file)) { + $attachment = false; +} +if (isset($_GET["attachment"])) { + $attachment = GETPOST("attachment", 'alpha') ?true:false; +} +if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS)) { + $attachment = false; +} // Define mime type $type = 'application/octet-stream'; // By default -if (GETPOST('type', 'alpha')) $type = GETPOST('type', 'alpha'); -else $type = dol_mimetype($original_file); +if (GETPOST('type', 'alpha')) { + $type = GETPOST('type', 'alpha'); +} else { + $type = dol_mimetype($original_file); +} // Security: Force to octet-stream if file is a dangerous file. For example when it is a .noexe file // We do not force if file is a javascript to be able to get js from website module with '; } - print ' '.$langs->trans("AddThirdParty").''; + print ' '; print '
    '.$langs->trans("Company").'
    '.$langs->trans("Lastname").'
    '.$langs->trans("Firstname").'
    '; print img_picto('', 'globe-americas', 'class="paddingrightonly"').$form->select_country(GETPOST('country_id') != '' ?GETPOST('country_id') : $object->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("EMail").''.img_picto('', 'object_email', 'class="paddingrightonly"').'
    ".$langs->trans("Project").""; $formproject->select_projects(-1, $projectid, 'fk_project', 0, 0, 1, 1, 0, 0, 0, '', 0, 0, 'maxwidth500'); print "
    '.$langs->trans("LinkedToDolibarrThirdParty").''.$company->getNomUrl(1).'
    '.$langs->trans("ThirdParty").''; + if ($object->socid > 0) { + $result = $company->fetch($object->socid); + print $company->getNomUrl(1); + } + print '
    '.$langs->trans("Company").'
    ".$langs->trans("PaymentMode")."\n"; - if ($object->mode_reglement_id) $selected = $object->mode_reglement_id; - else $selected = ''; + if ($object->mode_reglement_id) { + $selected = $object->mode_reglement_id; + } else { + $selected = ''; + } $form->select_types_paiements($selected, 'modepayment', 'CRDT', 0, 1); print "
    \n"; @@ -620,11 +630,9 @@ if (!empty($id) && $action == 'edit') /* Donation card in view mode */ /* */ /* ************************************************************ */ -if (!empty($id) && $action != 'edit') -{ +if (!empty($id) && $action != 'edit') { // Confirmation delete - if ($action == 'delete') - { + if ($action == 'delete') { $text = $langs->trans("ConfirmDeleteADonation"); print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("DeleteADonation"), $text, "confirm_delete", '', '', 1); } @@ -650,12 +658,10 @@ if (!empty($id) && $action != 'edit') $morehtmlref = '
    '; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= $langs->trans('Project').' '; - if ($user->rights->don->creer) - { + if ($user->rights->don->creer) { if ($action != 'classify') { $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; } @@ -707,11 +713,15 @@ if (!empty($id) && $action != 'edit') print yn($object->public); print '
    '.$langs->trans("LinkedToDolibarrThirdParty").''.$company->getNomUrl(1).'
    '.$langs->trans("ThirdParty").''; + if ($object->socid > 0) { + $result = $company->fetch($object->socid); + print $company->getNomUrl(1); + } + print '
    '.$langs->trans("Company").''.$object->societe.'
    '.$langs->trans("Lastname").''.$object->lastname.'
    '; @@ -758,11 +767,10 @@ if (!empty($id) && $action != 'edit') print ''; print ''; print ''; - print ''; - print ''; + print ''; + print ''; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); print '\n"; print "\n"; @@ -807,28 +814,23 @@ if (!empty($id) && $action != 'edit') print '
    '; // Re-open - if ($permissiontoadd && $object->statut == $object::STATUS_CANCELED) - { + if ($permissiontoadd && $object->statut == $object::STATUS_CANCELED) { print ''.$langs->trans("ReOpen").''; } print ''; - if ($object->statut == $object::STATUS_DRAFT) - { + if ($object->statut == $object::STATUS_DRAFT) { print ''; } - if (($object->statut == $object::STATUS_DRAFT || $object->statut == $object::STATUS_VALIDATED) && $totalpaid == 0 && $object->paid == 0) - { + if (($object->statut == $object::STATUS_DRAFT || $object->statut == $object::STATUS_VALIDATED) && $totalpaid == 0 && $object->paid == 0) { print '"; } // Create payment - if ($object->statut == $object::STATUS_VALIDATED && $object->paid == 0 && $user->rights->don->creer) - { - if ($remaintopay == 0) - { + if ($object->statut == $object::STATUS_VALIDATED && $object->paid == 0 && $user->rights->don->creer) { + if ($remaintopay == 0) { print '
    '.$langs->trans('DoPayment').'
    '; } else { print ''; @@ -836,16 +838,13 @@ if (!empty($id) && $action != 'edit') } // Classify 'paid' - if ($object->statut == $object::STATUS_VALIDATED && round($remaintopay) == 0 && $object->paid == 0 && $user->rights->don->creer) - { + if ($object->statut == $object::STATUS_VALIDATED && round($remaintopay) == 0 && $object->paid == 0 && $user->rights->don->creer) { print '"; } // Delete - if ($user->rights->don->supprimer) - { - if ($object->statut == $object::STATUS_CANCELED || $object->statut == $object::STATUS_DRAFT) - { + if ($user->rights->don->supprimer) { + if ($object->statut == $object::STATUS_CANCELED || $object->statut == $object::STATUS_DRAFT) { print '"; } else { print '"; @@ -860,7 +859,7 @@ if (!empty($id) && $action != 'edit') print '
    '; /* - * Documents generes + * Generated documents */ $filename = dol_sanitizeFileName($object->id); $filedir = $conf->don->dir_output."/".dol_sanitizeFileName($object->id); @@ -877,8 +876,7 @@ if (!empty($id) && $action != 'edit') // Show online payment link $useonlinepayment = (!empty($conf->paypal->enabled) || !empty($conf->stripe->enabled) || !empty($conf->paybox->enabled)); - if ($useonlinepayment) //$object->statut != Facture::STATUS_DRAFT && - { + if ($useonlinepayment) { //$object->statut != Facture::STATUS_DRAFT && print '
    '."\n"; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; print showOnlinePaymentUrl('donation', $object->ref).'
    '; diff --git a/htdocs/don/class/api_donations.class.php b/htdocs/don/class/api_donations.class.php index 18a8563fd89..ab0d6e5f483 100644 --- a/htdocs/don/class/api_donations.class.php +++ b/htdocs/don/class/api_donations.class.php @@ -32,7 +32,7 @@ class Donations extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'socid' ); @@ -109,18 +109,22 @@ class Donations extends DolibarrApi $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids)) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids)) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."don as t"; $sql .= ' WHERE t.entity IN ('.getEntity('don').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids)) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($thirdparty_ids) $sql .= " AND t.fk_soc = ".$thirdparty_ids." "; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids)) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($thirdparty_ids) { + $sql .= " AND t.fk_soc = ".$thirdparty_ids." "; + } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -129,8 +133,7 @@ class Donations extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -141,13 +144,11 @@ class Donations extends DolibarrApi dol_syslog("API Rest request"); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $don_static = new Don($this->db); if ($don_static->fetch($obj->rowid)) { @@ -185,12 +186,12 @@ class Donations extends DolibarrApi $this->don->$field = $value; } /*if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->don->lines = $lines; - }*/ + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->don->lines = $lines; + }*/ if ($this->don->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating order", array_merge(array($this->don->error), $this->don->errors)); @@ -222,12 +223,13 @@ class Donations extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->don->$field = $value; } - if ($this->don->update(DolibarrApiAccess::$user) > 0) - { + if ($this->don->update(DolibarrApiAccess::$user) > 0) { return $this->get($id); } else { throw new RestException(500, $this->don->error); @@ -356,8 +358,9 @@ class Donations extends DolibarrApi { $don = array(); foreach (Orders::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, $field." field missing"); + } $don[$field] = $data[$field]; } return $don; diff --git a/htdocs/don/class/don.class.php b/htdocs/don/class/don.class.php index 7e9b913312a..a5fb676e314 100644 --- a/htdocs/don/class/don.class.php +++ b/htdocs/don/class/don.class.php @@ -171,8 +171,7 @@ class Don extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; $langs->load("donations"); $this->labelStatus[-1] = $langs->transnoentitiesnoconv("Canceled"); @@ -186,8 +185,12 @@ class Don extends CommonObject } $statusType = 'status'.$status; - if ($status == self::STATUS_CANCELED) $statusType = 'status9'; - if ($status == self::STATUS_PAID) $statusType = 'status6'; + if ($status == self::STATUS_CANCELED) { + $statusType = 'status9'; + } + if ($status == self::STATUS_PAID) { + $statusType = 'status6'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -216,12 +219,10 @@ class Don extends CommonObject $sql .= " LIMIT 10"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_socs = $this->db->num_rows($resql); $i = 0; - while ($i < $num_socs) - { + while ($i < $num_socs) { $i++; $row = $this->db->fetch_row($resql); @@ -269,35 +270,29 @@ class Don extends CommonObject $error_string = array(); $err = 0; - if (dol_strlen(trim($this->societe)) == 0) - { - if ((dol_strlen(trim($this->lastname)) + dol_strlen(trim($this->firstname))) == 0) - { + if (dol_strlen(trim($this->societe)) == 0) { + if ((dol_strlen(trim($this->lastname)) + dol_strlen(trim($this->firstname))) == 0) { $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Company').'/'.$langs->transnoentitiesnoconv('Firstname').'-'.$langs->transnoentitiesnoconv('Lastname')); $err++; } } - if (dol_strlen(trim($this->address)) == 0) - { + if (dol_strlen(trim($this->address)) == 0) { $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Address')); $err++; } - if (dol_strlen(trim($this->zip)) == 0) - { + if (dol_strlen(trim($this->zip)) == 0) { $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Zip')); $err++; } - if (dol_strlen(trim($this->town)) == 0) - { + if (dol_strlen(trim($this->town)) == 0) { $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Town')); $err++; } - if (dol_strlen(trim($this->email)) == 0) - { + if (dol_strlen(trim($this->email)) == 0) { $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('EMail')); $err++; } @@ -306,10 +301,8 @@ class Don extends CommonObject $map = range(0, 9); $len = dol_strlen($this->amount); - for ($i = 0; $i < $len; $i++) - { - if (!isset($map[substr($this->amount, $i, 1)])) - { + for ($i = 0; $i < $len; $i++) { + if (!isset($map[substr($this->amount, $i, 1)])) { $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Amount')); $err++; $amount_invalid = 1; @@ -317,23 +310,19 @@ class Don extends CommonObject } } - if (!$amount_invalid) - { - if ($this->amount == 0) - { + if (!$amount_invalid) { + if ($this->amount == 0) { $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Amount')); $err++; } else { - if ($this->amount < $minimum && $minimum > 0) - { + if ($this->amount < $minimum && $minimum > 0) { $error_string[] = $langs->trans('MinimumAmount', $langs->transnoentitiesnoconv('$minimum')); $err++; } } } - if ($err) - { + if ($err) { $this->errors = $error_string; return 0; } else { @@ -404,7 +393,7 @@ class Don extends CommonObject $sql .= ", ".(int) ($this->country_id > 0 ? $this->country_id : 0); $sql .= ", ".(int) $this->public; $sql .= ", ".($this->fk_project > 0 ? (int) $this->fk_project : "null"); - $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL"); + $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL"); $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL"); $sql .= ", ".$user->id; $sql .= ", null"; @@ -415,16 +404,16 @@ class Don extends CommonObject $sql .= ")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."don"); $ret = $this->id; - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('DON_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } else { @@ -441,14 +430,12 @@ class Don extends CommonObject } } - if (!$error && !empty($conf->global->MAIN_DISABLEDRAFTSTATUS)) - { + if (!$error && !empty($conf->global->MAIN_DISABLEDRAFTSTATUS)) { //$res = $this->setValid($user); //if ($res < 0) $error++; } - if (!$error) - { + if (!$error) { $this->db->commit(); return $ret; } else { @@ -503,28 +490,25 @@ class Don extends CommonObject dol_syslog(get_class($this)."::Update", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$notrigger) - { + if ($resql) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('DON_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } // Update extrafield - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } + if (!$error) { + $result = $this->insertExtraFields(); + if ($result < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { $this->db->commit(); $result = 1; } else { @@ -557,7 +541,7 @@ class Don extends CommonObject $this->db->begin(); - if (!$error && !$notrigger) { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('DON_DELETE', $user); @@ -568,39 +552,33 @@ class Don extends CommonObject } // Delete donation - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."don_extrafields"; $sql .= " WHERE fk_object=".$this->id; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->lasterror(); $error++; } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."don"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->lasterror(); $error++; } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -633,20 +611,16 @@ class Don extends CommonObject $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON cp.id = d.fk_payment"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON d.fk_country = c.rowid"; $sql .= " WHERE d.entity IN (".getEntity('donation').")"; - if (!empty($id)) - { + if (!empty($id)) { $sql .= " AND d.rowid=".$id; - } elseif (!empty($ref)) - { + } elseif (!empty($ref)) { $sql .= " AND d.ref='".$this->db->escape($ref)."'"; } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -731,14 +705,14 @@ class Don extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX."don SET fk_statut = 1, fk_user_valid = ".$userid." WHERE rowid = ".$id." AND fk_statut = 0"; $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->affected_rows($resql)) - { + if ($resql) { + if ($this->db->affected_rows($resql)) { if (!$notrigger) { // Call trigger $result = $this->call_trigger('DON_VALIDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } @@ -784,8 +758,7 @@ class Don extends CommonObject public function setPaid($id, $modepayment = 0) { $sql = "UPDATE ".MAIN_DB_PREFIX."don SET fk_statut = 2"; - if ($modepayment) - { + if ($modepayment) { $sql .= ", fk_payment=".$modepayment; } $sql .= " WHERE rowid = ".$id." AND fk_statut = 1"; @@ -814,7 +787,7 @@ class Don extends CommonObject public function set_cancel($id) { // phpcs:enable - $sql = "UPDATE ".MAIN_DB_PREFIX."don SET fk_statut = -1 WHERE rowid = ".$id; + $sql = "UPDATE ".MAIN_DB_PREFIX."don SET fk_statut = -1 WHERE rowid = ".((int) $id); $resql = $this->db->query($sql); if ($resql) { @@ -874,8 +847,7 @@ class Don extends CommonObject $sql .= " AND entity = ".$conf->entity; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $result = $obj->total; } @@ -902,10 +874,8 @@ class Don extends CommonObject $sql .= " AND d.entity IN (".getEntity('donation').")"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["donations"] = $obj->nb; } $this->db->free($resql); @@ -930,7 +900,9 @@ class Don extends CommonObject { global $conf, $langs; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; $label = img_picto('', $this->picto).' '.$langs->trans("Donation").''; @@ -941,20 +913,30 @@ class Don extends CommonObject $label .= '
    '.$langs->trans('Ref').': '.$this->id; $label .= '
    '.$langs->trans('Date').': '.dol_print_date($this->date, 'day'); } - if ($moretitle) $label .= ' - '.$moretitle; + if ($moretitle) { + $label .= ' - '.$moretitle; + } $url = DOL_URL_ROOT.'/don/card.php?id='.$this->id; - $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'; + $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'; + } $linkstart = ''; $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; return $result; @@ -971,25 +953,21 @@ class Don extends CommonObject $sql = 'SELECT d.rowid, d.datec, d.fk_user_author, d.fk_user_valid,'; $sql .= ' d.tms'; $sql .= ' FROM '.MAIN_DB_PREFIX.'don as d'; - $sql .= ' WHERE d.rowid = '.$id; + $sql .= ' WHERE d.rowid = '.((int) $id); dol_syslog(get_class($this).'::info', LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_modification = $vuser; @@ -1045,8 +1023,7 @@ class Don extends CommonObject // If selected modele is a filename template (then $modele="modelname:filename") $tmp = explode(':', $modele, 2); - if (!empty($tmp[1])) - { + if (!empty($tmp[1])) { $modele = $tmp[0]; $srctemplatepath = $tmp[1]; } @@ -1054,28 +1031,28 @@ class Don extends CommonObject // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array('/'); - if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { - foreach (array('html', 'doc', 'pdf') as $prefix) - { + if (is_array($conf->modules_parts['models'])) { + $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']); + } + foreach ($dirmodels as $reldir) { + foreach (array('html', 'doc', 'pdf') as $prefix) { $file = $prefix."_".preg_replace('/^html_/', '', $modele).".modules.php"; // On verifie l'emplacement du modele $file = dol_buildpath($reldir."core/modules/dons/".$file, 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = $prefix.'_'.$modele; break; } } - if ($filefound) break; + if ($filefound) { + break; + } } // Charge le modele - if ($filefound) - { + if ($filefound) { require_once $file; $object = $this; @@ -1086,8 +1063,7 @@ class Don extends CommonObject // We save charset_output to restore it because write_file can change it if needed for // output format that does not support UTF8. $sav_charset_output = $outputlangs->charset_output; - if ($obj->write_file($object, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref) > 0) - { + if ($obj->write_file($object, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref) > 0) { $outputlangs->charset_output = $sav_charset_output; // we delete preview files @@ -1105,4 +1081,21 @@ class Don extends CommonObject return 0; } } + + /** + * Function used to replace a thirdparty id with another one. + * + * @param DoliDB $db Database handler + * @param int $origin_id Old third-party id + * @param int $dest_id New third-party id + * @return bool + */ + public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id) + { + $tables = array( + 'don' + ); + + return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); + } } diff --git a/htdocs/don/class/donstats.class.php b/htdocs/don/class/donstats.class.php index 684c04ead44..e3deff2dc2d 100644 --- a/htdocs/don/class/donstats.class.php +++ b/htdocs/don/class/donstats.class.php @@ -84,7 +84,9 @@ class DonationStats extends Stats //$this->where.= " AND c.fk_soc = s.rowid AND c.entity = ".$conf->entity; $this->where .= " AND d.entity = ".$conf->entity; - if ($this->userid > 0) $this->where .= ' WHERE c.fk_user_author = '.$this->userid; + if ($this->userid > 0) { + $this->where .= ' WHERE c.fk_user_author = '.$this->userid; + } } /** diff --git a/htdocs/don/class/paymentdonation.class.php b/htdocs/don/class/paymentdonation.class.php index 710e21f76b7..7c8bd71ccd2 100644 --- a/htdocs/don/class/paymentdonation.class.php +++ b/htdocs/don/class/paymentdonation.class.php @@ -120,25 +120,39 @@ class PaymentDonation extends CommonObject $now = dol_now(); // Validate parameters - if (!$this->datepaid) - { + if (!$this->datepaid) { $this->error = 'ErrorBadValueForParameterCreatePaymentDonation'; return -1; } // Clean parameters - if (isset($this->fk_donation)) $this->fk_donation = (int) $this->fk_donation; - if (isset($this->amount)) $this->amount = trim($this->amount); - if (isset($this->fk_typepayment)) $this->fk_typepayment = trim($this->fk_typepayment); - if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; - if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; - if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + if (isset($this->fk_donation)) { + $this->fk_donation = (int) $this->fk_donation; + } + if (isset($this->amount)) { + $this->amount = trim($this->amount); + } + if (isset($this->fk_typepayment)) { + $this->fk_typepayment = trim($this->fk_typepayment); + } + if (isset($this->num_payment)) { + $this->num_payment = trim($this->num_payment); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->fk_bank)) { + $this->fk_bank = (int) $this->fk_bank; + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = (int) $this->fk_user_creat; + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = (int) $this->fk_user_modif; + } $totalamount = 0; - foreach ($this->amounts as $key => $value) // How payment is dispatch - { + foreach ($this->amounts as $key => $value) { // How payment is dispatch $newvalue = price2num($value, 'MT'); $this->amounts[$key] = $newvalue; $totalamount += $newvalue; @@ -146,13 +160,14 @@ class PaymentDonation extends CommonObject $totalamount = price2num($totalamount); // Check parameters - if ($totalamount == 0) return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null + if ($totalamount == 0) { + return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null + } $this->db->begin(); - if ($totalamount != 0) - { + if ($totalamount != 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_donation (fk_donation, datec, datep, amount,"; $sql .= " fk_typepayment, num_payment, note, fk_user_creat, fk_bank)"; $sql .= " VALUES ($this->chid, '".$this->db->idate($now)."',"; @@ -163,8 +178,7 @@ class PaymentDonation extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_donation"); $this->ref = $this->id; } else { @@ -172,16 +186,16 @@ class PaymentDonation extends CommonObject } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call triggers $result = $this->call_trigger('DONATION_PAYMENT_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if ($totalamount != 0 && !$error) - { + if ($totalamount != 0 && !$error) { $this->amount = $totalamount; $this->total = $totalamount; // deprecated $this->db->commit(); @@ -220,14 +234,12 @@ class PaymentDonation extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."payment_donation as t"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = 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); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -275,14 +287,30 @@ class PaymentDonation extends CommonObject // Clean parameters - if (isset($this->fk_donation)) $this->fk_donation = (int) $this->fk_donation; - if (isset($this->amount)) $this->amount = trim($this->amount); - if (isset($this->fk_typepayment)) $this->fk_typepayment = trim($this->fk_typepayment); - if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; - if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; - if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + if (isset($this->fk_donation)) { + $this->fk_donation = (int) $this->fk_donation; + } + if (isset($this->amount)) { + $this->amount = trim($this->amount); + } + if (isset($this->fk_typepayment)) { + $this->fk_typepayment = trim($this->fk_typepayment); + } + if (isset($this->num_payment)) { + $this->num_payment = trim($this->num_payment); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->fk_bank)) { + $this->fk_bank = (int) $this->fk_bank; + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = (int) $this->fk_user_creat; + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = (int) $this->fk_user_modif; + } // Check parameters // Put here code to add control on parameters values @@ -311,25 +339,22 @@ class PaymentDonation extends CommonObject $this->errors[] = "Error ".$this->db->lasterror(); } - if (!$error) - { - if (!$notrigger) - { - if (!$error && !$notrigger) - { + if (!$error) { + if (!$notrigger) { + if (!$error && !$notrigger) { // Call triggers $result = $this->call_trigger('DONATION_PAYMENT_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -356,20 +381,20 @@ class PaymentDonation extends CommonObject $this->db->begin(); - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url"; $sql .= " WHERE type='payment_donation' AND url_id=".(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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_donation"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); @@ -379,25 +404,22 @@ class PaymentDonation extends CommonObject } } - if (!$error) - { - if (!$notrigger) - { - if (!$error && !$notrigger) - { + if (!$error) { + if (!$notrigger) { + if (!$error && !$notrigger) { // Call triggers $result = $this->call_trigger('DONATION_PAYMENT_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -439,21 +461,18 @@ class PaymentDonation extends CommonObject $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $error++; } - if (!$error) - { + if (!$error) { } unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { @@ -534,15 +553,16 @@ class PaymentDonation extends CommonObject $error = 0; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $acc = new Account($this->db); $acc->fetch($accountid); $total = $this->total; - if ($mode == 'payment_donation') $amount = $total; + if ($mode == 'payment_donation') { + $amount = $total; + } // Insert payment into llx_bank $bank_line_id = $acc->addline( @@ -559,23 +579,21 @@ class PaymentDonation extends CommonObject // Update fk_bank in llx_paiement. // On connait ainsi le paiement qui a genere l'ecriture bancaire - if ($bank_line_id > 0) - { + if ($bank_line_id > 0) { $result = $this->update_fk_bank($bank_line_id); - if ($result <= 0) - { + if ($result <= 0) { $error++; dol_print_error($this->db); } // Add link 'payment', 'payment_supplier', 'payment_donation' in bank_url between payment and bank transaction $url = ''; - if ($mode == 'payment_donation') $url = DOL_URL_ROOT.'/don/payment/card.php?rowid='; - if ($url) - { + if ($mode == 'payment_donation') { + $url = DOL_URL_ROOT.'/don/payment/card.php?rowid='; + } + if ($url) { $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); - if ($result <= 0) - { + if ($result <= 0) { $error++; dol_print_error($this->db); } @@ -586,8 +604,7 @@ class PaymentDonation extends CommonObject } } - if (!$error) - { + if (!$error) { return 1; } else { return -1; @@ -609,8 +626,7 @@ class PaymentDonation extends CommonObject dol_syslog(get_class($this)."::update_fk_bank", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { return 1; } else { $this->error = $this->db->error(); @@ -635,14 +651,19 @@ class PaymentDonation extends CommonObject $label .= '
    '; $label .= ''.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->id)) - { + if (!empty($this->id)) { $link = ''; $linkend = ''; - if ($withpicto) $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); - if ($withpicto && $withpicto != 2) $result .= ' '; - if ($withpicto != 2) $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + if ($withpicto) { + $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + if ($withpicto != 2) { + $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + } } return $result; diff --git a/htdocs/don/document.php b/htdocs/don/document.php index 9ff1fa98ea2..08667c6ab4c 100644 --- a/htdocs/don/document.php +++ b/htdocs/don/document.php @@ -34,8 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/donation.lib.php'; require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } @@ -50,7 +49,9 @@ $confirm = GETPOST('confirm', 'alpha'); $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'don', $id, ''); @@ -59,12 +60,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) { $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"; +} $object = new Don($db); @@ -78,10 +85,9 @@ $modulepart = 'don'; * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; -if ($action == 'classin' && $user->rights->don->creer) -{ +if ($action == 'classin' && $user->rights->don->creer) { $object->fetch($id); $object->setProject($projectid); } @@ -91,15 +97,16 @@ if ($action == 'classin' && $user->rights->don->creer) */ $form = new Form($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $title = $langs->trans('Donation')." - ".$langs->trans('Documents'); $helpurl = ""; llxHeader('', $title, $helpurl); -if ($object->id) -{ +if ($object->id) { $object->fetch_thirdparty(); $head = donation_prepare_head($object); @@ -110,8 +117,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -119,12 +125,10 @@ if ($object->id) $morehtmlref = '
    '; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= $langs->trans('Project').' '; - if ($user->rights->don->creer) - { + if ($user->rights->don->creer) { if ($action != 'classify') { // $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; } @@ -166,7 +170,7 @@ if ($object->id) print '
    '; - */ + */ // Societe //print ""; diff --git a/htdocs/don/index.php b/htdocs/don/index.php index ce47e6ca89b..9415a1e928b 100644 --- a/htdocs/don/index.php +++ b/htdocs/don/index.php @@ -66,12 +66,10 @@ $sql .= " GROUP BY d.fk_statut"; $sql .= " ORDER BY d.fk_statut"; $result = $db->query($sql); -if ($result) -{ +if ($result) { $i = 0; $num = $db->num_rows($result); - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($result); $somme[$objp->fk_statut] = $objp->somme; @@ -90,25 +88,25 @@ print load_fiche_titre($langs->trans("DonationsArea"), '', 'object_donation'); print '
    '; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ - if (!empty($conf->don->enabled) && $user->rights->don->lire) - { +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo + if (!empty($conf->don->enabled) && $user->rights->don->lire) { $listofsearchfields['search_donation'] = array('text'=>'Donation'); } - if (count($listofsearchfields)) - { + if (count($listofsearchfields)) { print ''; print ''; print '
    '.$langs->trans("RefPayment").''.$langs->trans("Date").''.$langs->trans("Type").''.$langs->trans("Amount").'
    '.$langs->trans("Amount").'
    '; @@ -776,8 +784,7 @@ if (!empty($id) && $action != 'edit') $i++; } - if ($object->paid == 0) - { + if ($object->paid == 0) { print "
    ".$langs->trans("AlreadyPaid")." :".price($totalpaid)."
    ".$langs->trans("AmountExpected")." :".price($object->amount)."
    '.$langs->trans("Ref").''; print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'ref', ''); print '
    ".$langs->trans("Company")."".$object->client->getNomUrl(1)."
    '; $i = 0; - foreach ($listofsearchfields as $key => $value) - { - if ($i == 0) print ''; + foreach ($listofsearchfields as $key => $value) { + if ($i == 0) { + print ''; + } print ''; print ''; - if ($i == 0) print ''; + if ($i == 0) { + print ''; + } print ''; $i++; } @@ -129,17 +127,23 @@ print ''; print "\n"; $listofstatus = array(0, 1, -1, 2); -foreach ($listofstatus as $status) -{ +foreach ($listofstatus as $status) { $dataseries[] = array($donstatic->LibStatut($status, 1), (isset($nb[$status]) ? (int) $nb[$status] : 0)); - if ($status == Don::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; - if ($status == Don::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus1; - if ($status == Don::STATUS_CANCELED) $colorseries[$status] = $badgeStatus9; - if ($status == Don::STATUS_PAID) $colorseries[$status] = $badgeStatus6; + if ($status == Don::STATUS_DRAFT) { + $colorseries[$status] = '-'.$badgeStatus0; + } + if ($status == Don::STATUS_VALIDATED) { + $colorseries[$status] = $badgeStatus1; + } + if ($status == Don::STATUS_CANCELED) { + $colorseries[$status] = $badgeStatus9; + } + if ($status == Don::STATUS_PAID) { + $colorseries[$status] = $badgeStatus6; + } } -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print ''; $total = 0; $totalnb = 0; -foreach ($listofstatus as $status) -{ +foreach ($listofstatus as $status) { print ''; print ''; print ''; @@ -203,18 +206,15 @@ $sql .= " ORDER BY c.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { print '
    '.$langs->trans("Search").'
    '.$langs->trans("Search").'
    '.$langs->trans("Statistics").'
    '; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -165,8 +169,7 @@ print '
    '.$donstatic->LibStatut($status, 4).''.(!empty($nb[$status]) ? $nb[$status] : ' ').'
    '; print ''; print ''; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; @@ -246,7 +246,9 @@ if ($resql) } } print "
    '.$langs->trans("LastModifiedDonations", $max).'

    "; -} else dol_print_error($db); +} else { + dol_print_error($db); +} print '
    '; diff --git a/htdocs/don/info.php b/htdocs/don/info.php index 1e7e18c9baf..866ff4baf22 100644 --- a/htdocs/don/info.php +++ b/htdocs/don/info.php @@ -25,8 +25,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/donation.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } @@ -39,7 +38,9 @@ $action = GETPOST('action', 'aZ09'); $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'don', $id, ''); $object = new Don($db); @@ -47,8 +48,7 @@ $object->fetch($id); /* * Actions */ -if ($action == 'classin' && $user->rights->don->creer) -{ +if ($action == 'classin' && $user->rights->don->creer) { $object->fetch($id); $object->setProject($projectid); } @@ -61,7 +61,9 @@ $helpurl = ""; llxHeader('', $title, $helpurl); $form = new Form($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $object->info($id); @@ -73,12 +75,10 @@ $linkback = ''; // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= $langs->trans('Project').' '; - if ($user->rights->don->creer) - { + if ($user->rights->don->creer) { if ($action != 'classify') { // $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; } diff --git a/htdocs/don/list.php b/htdocs/don/list.php index b81b5eaa231..9798cd02eea 100644 --- a/htdocs/don/list.php +++ b/htdocs/don/list.php @@ -27,7 +27,9 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; -if (!empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +if (!empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +} // Load translation files required by the page $langs->loadLangs(array("companies", "donations")); @@ -38,12 +40,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.datedon"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "d.datedon"; +} $search_status = (GETPOST("search_status", 'intcomma') != '') ? GETPOST("search_status", 'intcomma') : "-4"; $search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); @@ -53,10 +61,11 @@ $search_name = GETPOST('search_name', 'alpha'); $search_amount = GETPOST('search_amount', 'alpha'); $optioncss = GETPOST('optioncss', 'alpha'); -if (!$user->rights->don->lire) accessforbidden(); +if (!$user->rights->don->lire) { + accessforbidden(); +} -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $search_all = ""; $search_ref = ""; $search_company = ""; @@ -84,7 +93,9 @@ $fieldstosearchall = array( $donationstatic = new Don($db); $form = new Form($db); -if (!empty($conf->projet->enabled)) $projectstatic = new Project($db); +if (!empty($conf->projet->enabled)) { + $projectstatic = new Project($db); +} llxHeader('', $langs->trans("Donations"), 'EN:Module_Donations|FR:Module_Dons|ES:Módulo_Donaciones'); @@ -94,37 +105,32 @@ $sql .= " d.amount, d.fk_statut as status,"; $sql .= " p.rowid as pid, p.ref, p.title, p.public"; $sql .= " FROM ".MAIN_DB_PREFIX."don as d LEFT JOIN ".MAIN_DB_PREFIX."projet AS p"; $sql .= " ON p.rowid = d.fk_projet WHERE d.entity IN (".getEntity('donation').")"; -if ($search_status != '' && $search_status != '-4') -{ +if ($search_status != '' && $search_status != '-4') { $sql .= " AND d.fk_statut IN (".$db->sanitize($db->escape($search_status)).")"; } -if (trim($search_ref) != '') -{ +if (trim($search_ref) != '') { $sql .= natural_search('d.ref', $search_ref); } -if (trim($search_all) != '') -{ +if (trim($search_all) != '') { $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if (trim($search_company) != '') -{ +if (trim($search_company) != '') { $sql .= natural_search('d.societe', $search_company); } -if (trim($search_name) != '') -{ +if (trim($search_name) != '') { $sql .= natural_search(array('d.lastname', 'd.firstname'), $search_name); } -if ($search_amount) $sql .= natural_search('d.amount', $search_amount, 1); +if ($search_amount) { + $sql .= natural_search('d.amount', $search_amount, 1); +} $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -133,29 +139,45 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 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 ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($search_status && $search_status != -1) $param .= '&search_status='.urlencode($search_status); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_company) $param .= '&search_company='.urlencode($search_company); - if ($search_name) $param .= '&search_name='.urlencode($search_name); - if ($search_amount) $param .= '&search_amount='.urlencode($search_amount); + 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 ($search_status && $search_status != -1) { + $param .= '&search_status='.urlencode($search_status); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_company) { + $param .= '&search_company='.urlencode($search_company); + } + if ($search_name) { + $param .= '&search_name='.urlencode($search_name); + } + if ($search_amount) { + $param .= '&search_amount='.urlencode($search_amount); + } $newcardbutton = ''; - if ($user->rights->don->creer) - { + if ($user->rights->don->creer) { $newcardbutton .= dolGetButtonTitle($langs->trans('NewDonation'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/don/card.php?action=create'); } print ''."\n"; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; @@ -165,9 +187,10 @@ if ($resql) print_barre_liste($langs->trans("Donations"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'object_donation', 0, $newcardbutton, '', $limit, 0, 0, 1); - if ($search_all) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; } @@ -194,8 +217,7 @@ if ($resql) print ''; print ' '; print ''; - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { print ''; print ' '; print ''; @@ -225,8 +247,7 @@ if ($resql) } print_liste_field_titre("Name", $_SERVER["PHP_SELF"], "d.lastname", "", $param, "", $sortfield, $sortorder); print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "d.datedon", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); print_liste_field_titre("Project", $_SERVER["PHP_SELF"], "d.fk_projet", "", $param, "", $sortfield, $sortorder); } @@ -235,8 +256,7 @@ if ($resql) print_liste_field_titre(''); print "\n"; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($resql); print ''; @@ -258,18 +278,18 @@ if ($resql) } print "".$donationstatic->getFullName($langs).""; print ''.dol_print_date($db->jdate($objp->datedon), 'day').''; - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { print ""; - if ($objp->pid) - { + if ($objp->pid) { $projectstatic->id = $objp->pid; $projectstatic->ref = $objp->ref; $projectstatic->id = $objp->pid; $projectstatic->public = $objp->public; $projectstatic->title = $objp->title; print $projectstatic->getNomUrl(1); - } else print ' '; + } else { + print ' '; + } print "\n"; } print ''.price($objp->amount).''; diff --git a/htdocs/don/note.php b/htdocs/don/note.php index d1bbd0642d9..fa0122eaba2 100644 --- a/htdocs/don/note.php +++ b/htdocs/don/note.php @@ -29,8 +29,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/donation.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } @@ -45,7 +44,9 @@ $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0); // Security check $socid = 0; -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'don', $id, ''); $object = new Don($db); @@ -59,8 +60,7 @@ $permissionnote = $user->rights->don->creer; // Used by the include of actions_s */ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once -if ($action == 'classin' && $user->rights->don->creer) -{ +if ($action == 'classin' && $user->rights->don->creer) { $object->fetch($id); $object->setProject($projectid); } @@ -74,10 +74,11 @@ $helpurl = ""; llxHeader('', $title, $helpurl); $form = new Form($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object = new Don($db); $object->fetch($id, $ref); @@ -89,12 +90,10 @@ if ($id > 0 || !empty($ref)) $morehtmlref = '
    '; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= $langs->trans('Project').' '; - if ($user->rights->don->creer) - { + if ($user->rights->don->creer) { if ($action != 'classify') { // $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; } diff --git a/htdocs/don/payment/card.php b/htdocs/don/payment/card.php index e827bca338d..40cf0298895 100644 --- a/htdocs/don/payment/card.php +++ b/htdocs/don/payment/card.php @@ -27,7 +27,9 @@ require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; require_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; -if (!empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +if (!empty($conf->banque->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +} // Load translation files required by the page $langs->loadLangs(array("bills", "banks", "companies", "donations")); @@ -36,15 +38,18 @@ $langs->loadLangs(array("bills", "banks", "companies", "donations")); $id = GETPOST('rowid') ? GETPOST('rowid', 'int') : GETPOST('id', 'int'); $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} // TODO Add rule to restrict access payment //$result = restrictedArea($user, 'facture', $id,''); $object = new PaymentDonation($db); -if ($id > 0) -{ +if ($id > 0) { $result = $object->fetch($id); - if (!$result) dol_print_error($db, 'Failed to get payment id '.$id); + if (!$result) { + dol_print_error($db, 'Failed to get payment id '.$id); + } } @@ -53,13 +58,11 @@ if ($id > 0) */ // Delete payment -if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->don->supprimer) -{ +if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->don->supprimer) { $db->begin(); $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { $db->commit(); header("Location: ".DOL_URL_ROOT."/don/index.php"); exit; @@ -93,8 +96,7 @@ print dol_get_fiche_head($head, $hselected, $langs->trans("DonationPayment"), -1 /* * Confirm deleting of the payment */ -if ($action == 'delete') -{ +if ($action == 'delete') { print $form->formconfirm('card.php?id='.$object->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete', '', 0, 2); } @@ -122,10 +124,8 @@ print ''.$langs->trans('Amount').''.price($object->amount, 0, $ print ''.$langs->trans('Note').''.nl2br($object->note_public).''; // Bank account -if (!empty($conf->banque->enabled)) -{ - if ($object->bank_account) - { +if (!empty($conf->banque->enabled)) { + if ($object->bank_account) { $bankline = new AccountLine($db); $bankline->fetch($object->bank_line); @@ -150,12 +150,11 @@ $sql = 'SELECT d.rowid as did, d.paid, d.amount as d_amount, pd.amount'; $sql .= ' FROM '.MAIN_DB_PREFIX.'payment_donation as pd,'.MAIN_DB_PREFIX.'don as d'; $sql .= ' WHERE pd.fk_donation = d.rowid'; $sql .= ' AND d.entity = '.$conf->entity; -$sql .= ' AND pd.rowid = '.$id; +$sql .= ' AND pd.rowid = '.((int) $id); dol_syslog("don/payment/card.php", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -168,10 +167,8 @@ if ($resql) print ''.$langs->trans('PayedByThisPayment').''; print "\n"; - if ($num > 0) - { - while ($i < $num) - { + if ($num > 0) { + while ($i < $num) { $objp = $db->fetch_object($resql); print ''; @@ -213,12 +210,9 @@ print dol_get_fiche_end(); */ print '
    '; -if (empty($action)) -{ - if ($user->rights->don->supprimer) - { - if (!$disable_delete) - { +if (empty($action)) { + if ($user->rights->don->supprimer) { + if (!$disable_delete) { print ''.$langs->trans('Delete').''; } else { print ''.$langs->trans('Delete').''; diff --git a/htdocs/don/payment/payment.php b/htdocs/don/payment/payment.php index 9f944fe65b3..ca33d6ffc23 100644 --- a/htdocs/don/payment/payment.php +++ b/htdocs/don/payment/payment.php @@ -46,12 +46,10 @@ $object = new Don($db); * Actions */ -if ($action == 'add_payment') -{ +if ($action == 'add_payment') { $error = 0; - if ($_POST["cancel"]) - { + if ($_POST["cancel"]) { $loc = DOL_URL_ROOT.'/don/card.php?rowid='.$chid; header("Location: ".$loc); exit; @@ -59,45 +57,37 @@ if ($action == 'add_payment') $datepaid = dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); - if (!$_POST["paymenttype"] > 0) - { + if (!$_POST["paymenttype"] > 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")), null, 'errors'); $error++; } - if ($datepaid == '') - { + if ($datepaid == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors'); $error++; } - if (!empty($conf->banque->enabled) && !$_POST["accountid"] > 0) - { + if (!empty($conf->banque->enabled) && !$_POST["accountid"] > 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountToCredit")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $paymentid = 0; // Read possible payments - foreach ($_POST as $key => $value) - { - if (substr($key, 0, 7) == 'amount_') - { + foreach ($_POST as $key => $value) { + if (substr($key, 0, 7) == 'amount_') { $other_chid = substr($key, 7); $amounts[$other_chid] = price2num($_POST[$key]); } } - if (count($amounts) <= 0) - { + if (count($amounts) <= 0) { $error++; $errmsg = 'ErrorNoPaymentDefined'; setEventMessages($errmsg, null, 'errors'); } - if (!$error) - { + if (!$error) { $db->begin(); // Create a line of payments @@ -109,30 +99,25 @@ if ($action == 'add_payment') $payment->num_payment = GETPOST("num_payment", 'alphanohtml'); $payment->note_public = GETPOST("note_public", 'restricthtml'); - if (!$error) - { + if (!$error) { $paymentid = $payment->create($user); - if ($paymentid < 0) - { + if ($paymentid < 0) { $errmsg = $payment->error; setEventMessages($errmsg, null, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { $result = $payment->addPaymentToBank($user, 'payment_donation', '(DonationPayment)', $_POST['accountid'], '', ''); - if (!$result > 0) - { + if (!$result > 0) { $errmsg = $payment->error; setEventMessages($errmsg, null, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { $db->commit(); $loc = DOL_URL_ROOT.'/don/card.php?rowid='.$chid; header('Location: '.$loc); @@ -160,8 +145,7 @@ $sql = "SELECT sum(p.amount) as total"; $sql .= " FROM ".MAIN_DB_PREFIX."payment_donation as p"; $sql .= " WHERE p.fk_donation = ".$chid; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $obj = $db->fetch_object($resql); $sumpaid = $obj->total; $db->free(); @@ -169,16 +153,14 @@ if ($resql) // Form to create donation payment -if ($action == 'create') -{ +if ($action == 'create') { $object->fetch($chid); $total = $object->amount; print load_fiche_titre($langs->trans("DoPayment")); - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print "\n".''."\n"; llxHeader($moreheadcss.$moreheadjs, $langs->trans("ECMArea"), '', '', '', '', $morejs, '', 0, 0); $head = ecm_prepare_dasboard_head(''); -print dol_get_fiche_head($head, 'index', $langs->trans("ECMArea").' - '.$langs->trans("ECMFileManager"), -1, ''); +print dol_get_fiche_head($head, 'index', '', -1, ''); // Add filemanager component diff --git a/htdocs/ecm/index_auto.php b/htdocs/ecm/index_auto.php index ae7aa840ab9..f20985d45fb 100644 --- a/htdocs/ecm/index_auto.php +++ b/htdocs/ecm/index_auto.php @@ -34,7 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php'; $langs->loadLangs(array("ecm", "companies", "other", "users", "orders", "propal", "bills", "contracts")); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ecm', 0); // Get parameters @@ -42,7 +44,9 @@ $socid = GETPOST('socid', 'int'); $action = GETPOST('action', 'aZ09'); $section = GETPOST('section', 'int') ?GETPOST('section', 'int') : GETPOST('section_id', 'int'); $module = GETPOST('module', 'alpha'); -if (!$section) $section = 0; +if (!$section) { + $section = 0; +} $section_dir = GETPOST('section_dir', 'alpha'); $search_doc_ref = GETPOST('search_doc_ref', 'alpha'); @@ -51,20 +55,26 @@ $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 = "fullname"; -if ($module == 'invoice_supplier' && $sortfield == "fullname") $sortfield = "level1name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "fullname"; +} +if ($module == 'invoice_supplier' && $sortfield == "fullname") { + $sortfield = "level1name"; +} $ecmdir = new EcmDirectory($db); -if ($section) -{ +if ($section) { $result = $ecmdir->fetch($section); - if (!$result > 0) - { + if (!$result > 0) { dol_print_error($db, $ecmdir->error); exit; } @@ -85,8 +95,7 @@ $error = 0; $hookmanager->initHooks(array('ecmautocard', 'globalcard')); // 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_doc_ref = ''; } @@ -94,15 +103,13 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' // Add directory -if ($action == 'add' && $user->rights->ecm->setup) -{ +if ($action == 'add' && $user->rights->ecm->setup) { $ecmdir->ref = 'NOTUSEDYET'; $ecmdir->label = GETPOST("label"); $ecmdir->description = GETPOST("desc"); $id = $ecmdir->create($user); - if ($id > 0) - { + if ($id > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -114,38 +121,38 @@ if ($action == 'add' && $user->rights->ecm->setup) } // Remove file -if ($action == 'confirm_deletefile') -{ - if (GETPOST('confirm') == 'yes') - { +if ($action == 'confirm_deletefile') { + if (GETPOST('confirm') == 'yes') { $langs->load("other"); - if ($section) - { + if ($section) { $result = $ecmdir->fetch($section); - if (!($result > 0)) - { + if (!($result > 0)) { dol_print_error($db, $ecmdir->error); exit; } $relativepath = $ecmdir->getRelativePath(); - } else $relativepath = ''; + } else { + $relativepath = ''; + } $upload_dir = $conf->ecm->dir_output.($relativepath ? '/'.$relativepath : ''); $file = $upload_dir."/".GETPOST('urlfile'); // Do not use urldecode here ($_GET and $_POST are already decoded by PHP). $ret = dol_delete_file($file); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors'); + if ($ret) { + setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors'); + } $result = $ecmdir->changeNbOfFiles('-'); clearstatcache(); } - $action = 'file_manager'; + $action = 'file_manager'; } // Remove directory -if ($action == 'confirm_deletesection' && GETPOST('confirm') == 'yes') -{ +if ($action == 'confirm_deletesection' && GETPOST('confirm') == 'yes') { $result = $ecmdir->delete($user); setEventMessages($langs->trans("ECMSectionWasRemoved", $ecmdir->label), null, 'mesgs'); @@ -155,8 +162,7 @@ if ($action == 'confirm_deletesection' && GETPOST('confirm') == 'yes') // Refresh directory view // This refresh list of dirs, not list of files (for preformance reason). List of files is refresh only if dir was not synchronized. // To refresh content of dir with cache, just open the dir in edit mode. -if ($action == 'refreshmanual') -{ +if ($action == 'refreshmanual') { $ecmdirtmp = new EcmDirectory($db); // This part of code is same than into file ecm/ajax/ecmdatabase.php TODO Remove duplicate @@ -176,20 +182,16 @@ if ($action == 'refreshmanual') // Now we compare both trees to complete missing trees into database //var_dump($disktree); //var_dump($sqltree); - foreach ($disktree as $dirdesc) // Loop on tree onto disk - { + foreach ($disktree as $dirdesc) { // Loop on tree onto disk $dirisindatabase = 0; - foreach ($sqltree as $dirsqldesc) - { - if ($conf->ecm->dir_output.'/'.$dirsqldesc['fullrelativename'] == $dirdesc['fullname']) - { + foreach ($sqltree as $dirsqldesc) { + if ($conf->ecm->dir_output.'/'.$dirsqldesc['fullrelativename'] == $dirdesc['fullname']) { $dirisindatabase = 1; break; } } - if (!$dirisindatabase) - { + if (!$dirisindatabase) { $txt = "Directory found on disk ".$dirdesc['fullname'].", not found into database so we add it"; dol_syslog($txt); //print $txt."
    \n"; @@ -199,24 +201,20 @@ if ($action == 'refreshmanual') $relativepathmissing = str_replace($diroutputslash, '', $dirdesc['fullname']); $relativepathtosearchparent = $relativepathmissing; //dol_syslog("Try to find parent id for directory ".$relativepathtosearchparent); - if (preg_match('/\//', $relativepathtosearchparent)) - //while (preg_match('/\//',$relativepathtosearchparent)) - { + if (preg_match('/\//', $relativepathtosearchparent)) { + //while (preg_match('/\//',$relativepathtosearchparent)) $relativepathtosearchparent = preg_replace('/\/[^\/]*$/', '', $relativepathtosearchparent); $txt = "Is relative parent path ".$relativepathtosearchparent." for ".$relativepathmissing." found in sql tree ?"; dol_syslog($txt); //print $txt." -> "; $parentdirisindatabase = 0; - foreach ($sqltree as $dirsqldesc) - { - if ($dirsqldesc['fullrelativename'] == $relativepathtosearchparent) - { + foreach ($sqltree as $dirsqldesc) { + if ($dirsqldesc['fullrelativename'] == $relativepathtosearchparent) { $parentdirisindatabase = $dirsqldesc['id']; break; } } - if ($parentdirisindatabase > 0) - { + if ($parentdirisindatabase > 0) { dol_syslog("Yes with id ".$parentdirisindatabase); //print "Yes with id ".$parentdirisindatabase."
    \n"; $fk_parent = $parentdirisindatabase; @@ -230,8 +228,7 @@ if ($action == 'refreshmanual') $fk_parent = 0; // Parent is root } - if ($fk_parent >= 0) - { + if ($fk_parent >= 0) { $ecmdirtmp->ref = 'NOTUSEDYET'; $ecmdirtmp->label = dol_basename($dirdesc['fullname']); $ecmdirtmp->description = ''; @@ -241,8 +238,7 @@ if ($action == 'refreshmanual') dol_syslog($txt); //print $ecmdirtmp->cachenbofdoc."
    \n";exit; $id = $ecmdirtmp->create($user); - if ($id > 0) - { + if ($id > 0) { $newdirsql = array('id'=>$id, 'id_mere'=>$ecmdirtmp->fk_parent, 'label'=>$ecmdirtmp->label, @@ -263,11 +259,9 @@ if ($action == 'refreshmanual') } // Loop now on each sql tree to check if dir exists - foreach ($sqltree as $dirdesc) // Loop on each sqltree to check dir is on disk - { + foreach ($sqltree as $dirdesc) { // Loop on each sqltree to check dir is on disk $dirtotest = $conf->ecm->dir_output.'/'.$dirdesc['fullrelativename']; - if (!dol_is_dir($dirtotest)) - { + if (!dol_is_dir($dirtotest)) { $ecmdirtmp->id = $dirdesc['id']; $ecmdirtmp->delete($user, 'databaseonly'); //exit; @@ -280,7 +274,9 @@ if ($action == 'refreshmanual') // If a directory was added, the fulltree array is not correctly completed and sorted, so we clean // it to be sure that fulltree array is not used without reloading it. - if ($adirwascreated) $sqltree = null; + if ($adirwascreated) { + $sqltree = null; + } } @@ -298,7 +294,9 @@ $moreheadjs = ''; //$morejs=array(); $morejs = array('includes/jquery/plugins/blockUI/jquery.blockUI.js', 'core/js/blockUI.js'); // Used by ecm/tpl/enabledfiletreeajax.tpl.pgp -if (empty($conf->global->MAIN_ECM_DISABLE_JS)) $morejs[] = "includes/jquery/plugins/jqueryFileTree/jqueryFileTree.js"; +if (empty($conf->global->MAIN_ECM_DISABLE_JS)) { + $morejs[] = "includes/jquery/plugins/jqueryFileTree/jqueryFileTree.js"; +} $moreheadjs .= '';*/ + + +// Part to create +if ($action == 'create') { + print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("ConferenceOrBooth")), '', 'object_'.$object->picto); + + print ''; + print ''; + print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } + + print dol_get_fiche_head(array(), ''); + + // Set some default values + //if (! GETPOSTISSET('fieldname')) $_POST['fieldname'] = 'myvalue'; + + print ''."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; + + print '
    '."\n"; + + print dol_get_fiche_end(); + + print '
    '; + print ''; + print '  '; + print ''; // Cancel for create does not post form if we don't know the backtopage + print '
    '; + + print ''; + + //dol_set_focus('input[name="ref"]'); +} + +// Part to edit record +if (($id || $ref) && $action == 'edit') { + print load_fiche_titre($langs->trans("ConferenceOrBooth"), '', 'object_'.$object->picto); + + print '
    '; + print ''; + print ''; + print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } + + print dol_get_fiche_head(); + + print ''."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; + + print '
    '; + + print dol_get_fiche_end(); + + print '
    '; + print '   '; + print '
    '; + + print '
    '; +} + +// Part to show record +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { + $res = $object->fetch_optionals(); + + $head = conferenceorboothPrepareHead($object); + print dol_get_fiche_head($head, 'card', $langs->trans("ConferenceOrBooth"), -1, $object->picto); + + $formconfirm = ''; + + // Confirmation to delete + if ($action == 'delete') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteConferenceOrBooth'), $langs->trans('ConfirmDeleteObject'), 'confirm_delete', '', 0, 1); + } + // Confirmation to delete line + if ($action == 'deleteline') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); + } + // Clone confirmation + if ($action == 'clone') { + // Create an array for form + $formquestion = array(); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneAsk', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + } + + // Confirmation of action xxxx + if ($action == 'xxx') { + $formquestion = array(); + /* + $forcecombo=0; + if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + $formquestion = array( + // 'text' => $langs->trans("ConfirmClone"), + // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), + // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), + // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) + ); + */ + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); + } + + // Call Hook formConfirm + $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); + $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } + + // Print form confirm + print $formconfirm; + + + // Object card + // ------------------------------------------------------------ + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + // Project + if (! empty($conf->projet->enabled)) { + $langs->load("projects"); + $morehtmlref .= '
    '.$langs->trans('Project') . ' '; + if ($permissiontoadd) { + //if ($action != 'classify') $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' '; + $morehtmlref .= ' : '; + if ($action == 'classify') { + //$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= '
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + }*/ + $morehtmlref .= '
    '; + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + print '
    '; + print ''."\n"; + + // Common attributes + //$keyforbreak='fieldkeytoswitchonsecondcolumn'; // We change column just before this field + //unset($object->fields['fk_project']); // Hide field already shown in banner + //unset($object->fields['fk_soc']); // Hide field already shown in banner + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; + + // Other attributes. Fields from hook formObjectOptions and Extrafields. + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; + + print dol_get_fiche_end(); + + + /* + * Lines + */ + + if (!empty($object->table_element_line)) { + // Show object lines + $result = $object->getLinesArray(); + + print '
    + + + + + '; + + if (!empty($conf->use_javascript_ajax) && $object->status == 0) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; + } + + print '
    '; + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { + print ''; + } + + if (!empty($object->lines)) { + $object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1); + } + + // Form to add new line + if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') { + if ($action != 'editline') { + // Add products/services form + $object->formAddObjectLine(1, $mysoc, $soc); + + $parameters = array(); + $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + } + } + + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { + print '
    '; + } + print '
    '; + + print "
    \n"; + } + + + // Buttons for actions + + if ($action != 'presend' && $action != 'editline') { + print '
    '."\n"; + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } + + if (empty($reshook)) { + // Send + if (empty($user->socid)) { + print dolGetButtonAction($langs->trans('SendMail'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle'); + } + + // Back to draft + if ($object->status == $object::STATUS_CONFIRMED) { + print dolGetButtonAction($langs->trans('SetToDraft'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes', '', $permissiontoadd); + } + + print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit', '', $permissiontoadd); + + // Validate + if ($object->status == $object::STATUS_DRAFT) { + if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) { + print dolGetButtonAction($langs->trans('Validate'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes', '', $permissiontoadd); + } else { + $langs->load("errors"); + //print dolGetButtonAction($langs->trans('Validate'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes', '', 0); + print ''.$langs->trans("Validate").''; + } + } + + // Clone + print dolGetButtonAction($langs->trans('ToClone'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->socid.'&action=clone&object=scrumsprint', '', $permissiontoadd); + + /* + if ($permissiontoadd) { + if ($object->status == $object::STATUS_ENABLED) { + print ''.$langs->trans("Disable").''."\n"; + } else { + print ''.$langs->trans("Enable").''."\n"; + } + } + if ($permissiontoadd) { + if ($object->status == $object::STATUS_VALIDATED) { + print ''.$langs->trans("Cancel").''."\n"; + } else { + print ''.$langs->trans("Re-Open").''."\n"; + } + } + */ + + // Delete (need delete permission, or if draft, just need create/modify permission) + print dolGetButtonAction($langs->trans('Delete'), '', 'delete', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=delete', '', $permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)); + } + print '
    '."\n"; + } + + + // Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } + + if ($action != 'presend') { + print '
    '; + print ''; // ancre + + $includedocgeneration = 0; + + // Documents + if ($includedocgeneration) { + $objref = dol_sanitizeFileName($object->ref); + $relativepath = $objref.'/'.$objref.'.pdf'; + $filedir = $conf->eventorganization->dir_output.'/'.$object->element.'/'.$objref; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $user->rights->eventorganization->conferenceorbooth->read; // If you can read, you can build the PDF to read content + $delallowed = $user->rights->eventorganization->conferenceorbooth->write; // If you can create/edit, you can remove a file on card + print $formfile->showdocuments('eventorganization:ConferenceOrBooth', $object->element.'/'.$objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang); + } + + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('conferenceorbooth')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + + + print '
    '; + + $MAXEVENT = 10; + + $morehtmlright = ''; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= ''; + + // List of actions on element + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, $object->element.'@'.$object->module, (is_object($object->thirdparty) ? $object->thirdparty->id : 0), 1, '', $MAXEVENT, '', $morehtmlright); + + print '
    '; + } + + //Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } + + // Presend form + $modelmail = 'conferenceorbooth'; + $defaulttopic = 'InformationMessage'; + $diroutput = $conf->eventorganization->dir_output; + $trackid = 'conferenceorbooth'.$object->id; + + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/eventorganization/conferenceorbooth_contact.php b/htdocs/eventorganization/conferenceorbooth_contact.php new file mode 100644 index 00000000000..e29252aef1e --- /dev/null +++ b/htdocs/eventorganization/conferenceorbooth_contact.php @@ -0,0 +1,213 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * 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 conferenceorbooth_contact.php + * \ingroup eventorganization + * \brief Tab for contacts linked to ConferenceOrBooth + */ + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} + +require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +dol_include_once('/eventorganization/class/conferenceorbooth.class.php'); +dol_include_once('/eventorganization/lib/eventorganization_conferenceorbooth.lib.php'); + +// Load translation files required by the page +$langs->loadLangs(array("eventorganization@eventorganization", "companies", "other", "mails")); + +$id = (GETPOST('id') ?GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility +$ref = GETPOST('ref', 'alpha'); +$lineid = GETPOST('lineid', 'int'); +$socid = GETPOST('socid', 'int'); +$action = GETPOST('action', 'aZ09'); + +// Initialize technical objects +$object = new ConferenceOrBooth($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->eventorganization->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('conferenceorboothcontact', 'globalcard')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals + +// Security check - Protection if external user +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +//$result = restrictedArea($user, 'eventorganization', $object->id); + +$permission = $user->rights->eventorganization->conferenceorbooth->write; + +/* + * Add a new contact + */ + +if ($action == 'addcontact' && $permission) { + $contactid = (GETPOST('userid') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); + $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); + $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } else { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + $langs->load("errors"); + setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } +} elseif ($action == 'swapstatut' && $permission) { + // Toggle the status of a contact + $result = $object->swapContactStatus(GETPOST('ligne')); +} elseif ($action == 'deletecontact' && $permission) { + // Deletes a contact + $result = $object->delete_contact($lineid); + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } else { + dol_print_error($db); + } +} + + +/* + * View + */ + +$title = $langs->trans('ConferenceOrBooth')." - ".$langs->trans('ContactsAddresses'); +$help_url = ''; +//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +llxHeader('', $title, $help_url); + +$form = new Form($db); +$formcompany = new FormCompany($db); +$contactstatic = new Contact($db); +$userstatic = new User($db); + + +/* *************************************************************************** */ +/* */ +/* View and edit mode */ +/* */ +/* *************************************************************************** */ + +if ($object->id) { + /* + * Show tabs + */ + $head = conferenceorboothPrepareHead($object); + + print dol_get_fiche_head($head, 'contact', $langs->trans("ConferenceOrBooth"), -1, $object->picto); + + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($permissiontoadd) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + }*/ + $morehtmlref .= '
    '; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); + + print dol_get_fiche_end(); + + print '
    '; + + // Contacts lines (modules that overwrite templates must declare this into descriptor) + $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); + foreach ($dirtpls as $reldir) { + $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); + if ($res) { + break; + } + } +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/eventorganization/conferenceorbooth_document.php b/htdocs/eventorganization/conferenceorbooth_document.php new file mode 100644 index 00000000000..7b8094e3034 --- /dev/null +++ b/htdocs/eventorganization/conferenceorbooth_document.php @@ -0,0 +1,250 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * 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 conferenceorbooth_document.php + * \ingroup eventorganization + * \brief Tab for documents linked to ConferenceOrBooth + */ + +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} + +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +dol_include_once('/eventorganization/class/conferenceorbooth.class.php'); +dol_include_once('/eventorganization/lib/eventorganization_conferenceorbooth.lib.php'); + +// Load translation files required by the page +$langs->loadLangs(array("eventorganization@eventorganization", "companies", "other", "mails")); + + +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm'); +$id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); +$ref = GETPOST('ref', 'alpha'); + +// Get parameters +$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 +$offset = $liste_limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} +//if (! $sortfield) $sortfield="position_name"; + +// Initialize technical objects +$object = new ConferenceOrBooth($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->eventorganization->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('conferenceorboothdocument', 'globalcard')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals + +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->eventorganization->multidir_output[$object->entity ? $object->entity : $conf->entity]."/conferenceorbooth/".get_exdir(0, 0, 0, 1, $object); +} + +// Security check - Protection if external user +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +//$result = restrictedArea($user, 'eventorganization', $object->id); + +$permissiontoadd = $user->rights->eventorganization->conferenceorbooth->write; // Used by the include of actions_addupdatedelete.inc.php + + + +/* + * Actions + */ + +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; + + +/* + * View + */ + +$form = new Form($db); + +$title = $langs->trans("ConferenceOrBooth").' - '.$langs->trans("Files"); +$help_url = ''; +//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +llxHeader('', $title, $help_url); + +if ($object->id) { + /* + * Show tabs + */ + $head = conferenceorboothPrepareHead($object); + + print dol_get_fiche_head($head, 'document', $langs->trans("ConferenceOrBooth"), -1, $object->picto); + + + // Build file list + $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); + $totalsize = 0; + foreach ($filearray as $key => $file) { + $totalsize += $file['size']; + } + + // Object card + // ------------------------------------------------------------ + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($permissiontoadd) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + }*/ + $morehtmlref .= '
    '; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + + print '
    '; + print ''; + + // Number of files + print ''; + + // Total size + print ''; + + print '
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    '; + + print '
    '; + + print dol_get_fiche_end(); + + $modulepart = 'eventorganization'; + //$permission = $user->rights->eventorganization->conferenceorbooth->write; + $permission = 1; + //$permtoedit = $user->rights->eventorganization->conferenceorbooth->write; + $permtoedit = 1; + $param = '&id='.$object->id; + + //$relativepathwithnofile='conferenceorbooth/' . dol_sanitizeFileName($object->id).'/'; + $relativepathwithnofile = 'conferenceorbooth/'.dol_sanitizeFileName($object->ref).'/'; + + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; +} else { + accessforbidden('', 0, 1); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/eventorganization/conferenceorbooth_list.php b/htdocs/eventorganization/conferenceorbooth_list.php new file mode 100644 index 00000000000..6632e8a1f29 --- /dev/null +++ b/htdocs/eventorganization/conferenceorbooth_list.php @@ -0,0 +1,821 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * 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 conferenceorbooth_list.php + * \ingroup eventorganization + * \brief List page for conferenceorbooth + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php'; +if ($conf->categorie->enabled) { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +} + +// for other modules +//dol_include_once('/othermodule/class/otherobject.class.php'); + +// Load translation files required by the page +$langs->loadLangs(array("eventorganization", "other")); + +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'conferenceorboothlist'; // To manage different context of search +$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') + +$id = GETPOST('id', 'int'); +$projectid = GETPOST('projectid', 'int'); + +// 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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +// Initialize technical objects +$object = new ConferenceOrBooth($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->eventorganization->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('conferenceorboothlist')); // Note that conf->hooks_modules contains array + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); +//$extrafields->fetch_name_optionals_label($object->table_element_line); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (!$sortfield) { + reset($object->fields); // Reset is required to avoid key() to return null. + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} + +// Initialize array of search criterias +$search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOST('search_'.$key.'_dtstartmonth', 'int'), GETPOST('search_'.$key.'_dtstartday', 'int'), GETPOST('search_'.$key.'_dtstartyear', 'int')); + $search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOST('search_'.$key.'_dtendmonth', 'int'), GETPOST('search_'.$key.'_dtendday', 'int'), GETPOST('search_'.$key.'_dtendyear', 'int')); + } +} + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array(); +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } +} + +// Definition of array of fields for columns +$arrayfields = array(); +foreach ($object->fields as $key => $val) { + // If $val['visible']==0, then we never show the field + if (!empty($val['visible'])) { + $visible = (int) dol_eval($val['visible'], 1); + $arrayfields['t.'.$key] = array( + 'label'=>$val['label'], + 'checked'=>(($visible < 0) ? 0 : 1), + 'enabled'=>($visible != 3 && dol_eval($val['enabled'], 1)), + 'position'=>$val['position'], + 'help'=>$val['help'] + ); + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + +$object->fields = dol_sort_array($object->fields, 'position'); +$arrayfields = dol_sort_array($arrayfields, 'position'); + +$permissiontoread = $user->rights->eventorganization->read; +$permissiontoadd = $user->rights->eventorganization->write; +$permissiontodelete = $user->rights->eventorganization->delete; + +// Security check +if (empty($conf->eventorganization->enabled)) { + accessforbidden('Module not enabled'); +} +$socid = 0; +if ($user->socid > 0) { // Protection if external user + //$socid = $user->socid; + accessforbidden(); +} +//$result = restrictedArea($user, 'eventorganization', $id, ''); +//if (!$permissiontoread) accessforbidden(); + + + +/* + * Actions + */ + +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; + $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} + +$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 (empty($reshook)) { + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // 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 + foreach ($object->fields as $key => $val) { + $search[$key] = ''; + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = ''; + $search[$key.'_dtend'] = ''; + } + } + $toselect = ''; + $search_array_options = array(); + } + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + // Mass actions + $objectclass = 'ConferenceOrBooth'; + $objectlabel = 'ConferenceOrBooth'; + $uploaddir = $conf->eventorganization->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; +} + + + +/* + * View + */ +$form = new Form($db); +$now = dol_now(); + +//$help_url="EN:Module_ConferenceOrBooth|FR:Module_ConferenceOrBooth_FR|ES:Módulo_ConferenceOrBooth"; +$help_url = ''; +$title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("ConferenceOrBooths")); + +if ($projectid > 0) { + $project = new Project($db); + $result = $project->fetch($projectid); + if ($result < 0) { + setEventMessages(null, $project->errors, 'errors'); + } + $result = $project->fetch_thirdparty(); + if ($result < 0) { + setEventMessages(null, $project->errors, 'errors'); + } + $result = $project->fetch_optionals(); + if ($result < 0) { + setEventMessages(null, $project->errors, 'errors'); + } + + $help_url = "EN:Module_Projects|FR:Module_Projets|ES:Módulo_Proyectos"; + $title = $langs->trans("Project") . ' - ' . $langs->trans("ConferenceOrBooths") . ' - ' . $project->ref . ' ' . $project->name; + if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $project->name) { + $title = $project->ref . ' ' . $project->name . ' - ' . $langs->trans("ConferenceOrBooths"); + } +} + +// Output page +// -------------------------------------------------------------------- + +llxHeader('', $title, $help_url); + +// Example : Adding jquery code +print ''; + +if ($projectid > 0) { + // To verify role of users + //$userAccess = $object->restrictedProjectArea($user,'read'); + $userWrite = $project->restrictedProjectArea($user, 'write'); + //$userDelete = $object->restrictedProjectArea($user,'delete'); + //print "userAccess=".$userAccess." userWrite=".$userWrite." userDelete=".$userDelete; + + $head = project_prepare_head($project); + print dol_get_fiche_head($head, 'eventorganisation', $langs->trans("Project"), -1, ($project->public ? 'projectpub' : 'project')); + + // Project card + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + // Title + $morehtmlref .= $project->title; + // Thirdparty + if ($project->thirdparty->id > 0) { + $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$project->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref .= '
    '; + + // Define a complementary filter for search of next/prev ref. + if (!$user->rights->project->all->lire) { + $objectsListId = $project->getProjectsAuthorizedForUser($user, 0, 0); + $project->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; + } + + dol_banner_tab($project, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Usage + print ''; + print ''; + + // Visibility + print ''; + + // Date start - end + print ''; + + // Budget + print ''; + + // Other attributes + $cols = 2; + $objectconf=$object; + $object = $project; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + $object = $objectconf; + + print '
    '; + print $langs->trans("Usage"); + print ''; + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { + print 'usage_opportunity ? ' checked="checked"' : '').'"> '; + $htmltext = $langs->trans("ProjectFollowOpportunity"); + print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); + print '
    '; + } + if (empty($conf->global->PROJECT_HIDE_TASKS)) { + print 'usage_task ? ' checked="checked"' : '').'"> '; + $htmltext = $langs->trans("ProjectFollowTasks"); + print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); + print '
    '; + } + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { + print 'usage_bill_time ? ' checked="checked"' : '').'"> '; + $htmltext = $langs->trans("ProjectBillTimeDescription"); + print $form->textwithpicto($langs->trans("BillTime"), $htmltext); + print '
    '; + } + if (!empty($conf->eventorganization->enabled)) { + print 'usage_organize_event ? ' checked="checked"' : '').'"> '; + $htmltext = $langs->trans("EventOrganizationDescriptionLong"); + print $form->textwithpicto($langs->trans("ManageOrganizeEvent"), $htmltext); + } + print '
    '.$langs->trans("Visibility").''; + if ($project->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } + print '
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; + $start = dol_print_date($project->date_start, 'day'); + print ($start ? $start : '?'); + $end = dol_print_date($project->date_end, 'day'); + print ' - '; + print ($end ? $end : '?'); + if ($object->hasDelay()) { + print img_warning("Late"); + } + print '
    '.$langs->trans("Budget").''; + if (strcmp($project->budget_amount, '')) { + print price($project->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + } + print '
    '; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Description + print ''; + + // Categories + if ($conf->categorie->enabled) { + print '"; + } + + print '
    '.$langs->trans("Description").''; + print nl2br($project->description); + print '
    '.$langs->trans("Categories").''; + print $form->showCategories($project->id, Categorie::TYPE_PROJECT, 1); + print "
    '; + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; + + + print dol_get_fiche_end(); +} + +// Build and execute select +// -------------------------------------------------------------------- +$sql = 'SELECT '; +$sql .= $object->getFieldList('t'); +// 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.', ' : ''); + } +} +// Add fields from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= preg_replace('/^,/', '', $hookmanager->resPrint); +$sql = preg_replace('/,\s*$/', '', $sql); +$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.id = ef.fk_object)"; +} +$sql .= " INNER JOIN ".MAIN_DB_PREFIX."c_actioncomm as cact ON cact.id=t.fk_action AND cact.module LIKE '%@eventorganization'"; +// Add table from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} + +foreach ($search as $key => $val) { + if (array_key_exists($key, $object->fields)) { + //var_dump($key,$object->fields); + if ($key == 'status' && $search[$key] == -1) { + continue; + } + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + if ((strpos($object->fields[$key]['type'], 'integer:') === 0) || (strpos($object->fields[$key]['type'], 'sellist:') === 0)) { + if ($search[$key] == '-1' || $search[$key] === '0') { + $search[$key] = ''; + } + $mode_search = 2; + } + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } + } else { + //var_dump($key,$object->fields); + if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') { + $columnName=preg_replace('/(_dtstart|_dtend)$/', '', $key); + if (preg_match('/^(date|timestamp|datetime)/', $object->fields[$columnName]['type'])) { + if (preg_match('/_dtstart$/', $key)) { + $sql .= " AND t." . $columnName . " >= '" . $db->idate($search[$key]) . "'"; + } + if (preg_match('/_dtend$/', $key)) { + $sql .= " AND t." . $columnName . " <= '" . $db->idate($search[$key]) . "'"; + } + } + } + } +} + +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} +//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); +// Add where from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; +// Add where from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; + +/* If a group by is required +$sql.= " GROUP BY "; +foreach($object->fields as $key => $val) { + $sql.='t.'.$key.', '; +} +// 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.', ' : ''); +} +// Add where from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters, $object); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; +$sql=preg_replace('/,\s*$/','', $sql); +*/ + +$sql .= $db->order($sortfield, $sortorder); + +// Count total nb of records +$nbtotalofrecords = ''; +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 + $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 || empty($limit))) { + $num = $nbtotalofrecords; +} else { + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } + + $resql = $db->query($sql); + if (!$resql) { + dol_print_error($db); + exit; + } + + $num = $db->num_rows($resql); +} + +// Direct jump if only one record found +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".dol_buildpath('/eventorganization/conferenceorbooth_card.php', 1).'?id='.$id); + exit; +} + +$arrayofselected = is_array($toselect) ? $toselect : array(); + +$param = ''; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} +// Add $param from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; +// Add $param from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object); // Note that $action and $object may have been modified by hook +$param .= $hookmanager->resPrint; + +// List of mass actions available +$arrayofmassactions = array( + //'validate'=>$langs->trans("Validate"), + //'generate_doc'=>$langs->trans("ReGeneratePDF"), + //'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(); +} +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); + +print '
    '."\n"; +if ($optioncss != '') { + print ''; +} +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +$newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/eventorganization/conferenceorbooth_card.php', 1).'?action=create'.(!empty($project->id)?'&fk_project='.$project->id:'').(!empty($project->socid)?'&fk_soc='.$project->socid:'').'&backtopage='.urlencode($_SERVER['PHP_SELF']).(!empty($project->id)?'?projectid='.$project->id:''), '', $permissiontoadd); + +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_'.$object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); + +// Add code for pre mass action (confirmation or email presend form) +$topicmail = "SendConferenceOrBoothRef"; +$modelmail = "conferenceorbooth"; +$objecttmp = new ConferenceOrBooth($db); +$trackid = 'xxxx'.$object->id; +include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; + +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } + print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; +} + +$moreforfilter = ''; +/*$moreforfilter.='
    '; +$moreforfilter.= $langs->trans('MyFilter') . ': '; +$moreforfilter.= '
    ';*/ + +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +if (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; +} else { + $moreforfilter = $hookmanager->resPrint; +} + +if (!empty($moreforfilter)) { + print '
    '; + print $moreforfilter; + print '
    '; +} + +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + +print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print ''."\n"; + + +// Fields title search +// -------------------------------------------------------------------- +print ''; +foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['css']) ? '' : $val['css']); + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { + print ''; + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + +// Fields from hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Action column +print ''; +print ''."\n"; + + +// Fields title label +// -------------------------------------------------------------------- +print ''; +foreach ($object->fields as $key => $val) { + $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'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; +// Hook fields +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Action column +print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; +print ''."\n"; + + +// Detect if we need a fetch on each output line +$needToFetchEachLine = 0; +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } + } +} + + +// Loop on record +// -------------------------------------------------------------------- +$i = 0; +$totalarray = array(); +while ($i < ($limit ? min($num, $limit) : $num)) { + $obj = $db->fetch_object($resql); + if (empty($obj)) { + break; // Should not happen + } + + // Store properties in $object + $object->setVarsFromFetchObj($obj); + + // Show here line of result + print ''; + foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['css']) ? '' : $val['css']); + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } + + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } + + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; + + if (!empty($arrayfields['t.'.$key]['checked'])) { + print ''; + if ($key == 'status') { + print $object->getLibStatut(5); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } + $totalarray['val']['t.'.$key] += $object->$key; + } + } + } + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + // Fields from hook + $parameters = array('arrayfields'=>$arrayfields, 'object'=>$object, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Action column + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + + print ''."\n"; + + $i++; +} + +// Show total line +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++; + } + } + print ''; +} + + +$db->free($resql); + +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print '
    '; + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif ((strpos($val['type'], 'integer:') === 0) || (strpos($val['type'], 'sellist:')=== 0)) { + print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth125', 1); + } elseif (!preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + print ''; + } elseif (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + print '
    '; + print $form->selectDate($search[$key.'_dtstart'] ? $search[$key.'_dtstart'] : '', "search_".$key."_dtstart", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); + print '
    '; + print '
    '; + print $form->selectDate($search[$key.'_dtend'] ? $search[$key.'_dtend'] : '', "search_".$key."_dtend", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); + print '
    '; + } + print '
    '; +$searchpicto = $form->showFilterButtons(); +print $searchpicto; +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($object->id, $arrayofselected)) { + $selected = 1; + } + print ''; + } + print '
    '.$langs->trans("NoRecordFound").'
    '."\n"; +print '
    '."\n"; + +print '
    '."\n"; + +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { + $hidegeneratedfilelistifempty = 1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } + + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; + $formfile = new FormFile($db); + + // Show list of available documents + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); + + $filedir = $diroutputmassaction; + $genallowed = $permissiontoread; + $delallowed = $permissiontoadd; + + print $formfile->showdocuments('massfilesarea_eventorganization', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/eventorganization/conferenceorbooth_note.php b/htdocs/eventorganization/conferenceorbooth_note.php new file mode 100644 index 00000000000..61c8ba957e6 --- /dev/null +++ b/htdocs/eventorganization/conferenceorbooth_note.php @@ -0,0 +1,200 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * 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 conferenceorbooth_note.php + * \ingroup eventorganization + * \brief Tab for notes on ConferenceOrBooth + */ + +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} + +dol_include_once('/eventorganization/class/conferenceorbooth.class.php'); +dol_include_once('/eventorganization/lib/eventorganization_conferenceorbooth.lib.php'); + +// Load translation files required by the page +$langs->loadLangs(array("eventorganization@eventorganization", "companies")); + +// Get parameters +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$cancel = GETPOST('cancel', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); + +// Initialize technical objects +$object = new ConferenceOrBooth($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->eventorganization->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('conferenceorboothnote', 'globalcard')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +// Security check - Protection if external user +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +//$result = restrictedArea($user, 'eventorganization', $id); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->eventorganization->multidir_output[$object->entity]."/".$object->id; +} + +$permissionnote = $user->rights->eventorganization->conferenceorbooth->write; // Used by the include of actions_setnotes.inc.php +$permissiontoadd = $user->rights->eventorganization->conferenceorbooth->write; // Used by the include of actions_addupdatedelete.inc.php + + + +/* + * Actions + */ + +include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + + +/* + * View + */ + +$form = new Form($db); + +//$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes'; +$help_url = ''; +llxHeader('', $langs->trans('ConferenceOrBooth'), $help_url); + +if ($id > 0 || !empty($ref)) { + $object->fetch_thirdparty(); + + $head = conferenceorboothPrepareHead($object); + + print dol_get_fiche_head($head, 'note', $langs->trans("ConferenceOrBooth"), -1, $object->picto); + + // Object card + // ------------------------------------------------------------ + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($permissiontoadd) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + }*/ + $morehtmlref .= '
    '; + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + + + $cssclass = "titlefield"; + include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; + + print '
    '; + + print dol_get_fiche_end(); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/eventorganization/eventorganizationindex.php b/htdocs/eventorganization/eventorganizationindex.php new file mode 100644 index 00000000000..999d85255d0 --- /dev/null +++ b/htdocs/eventorganization/eventorganizationindex.php @@ -0,0 +1,241 @@ + + * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2015 Jean-François Ferry + * + * 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 eventorganization/eventorganizationindex.php + * \ingroup eventorganization + * \brief Home page of eventorganization top menu + */ + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} + +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("eventorganization@eventorganization")); + +$action = GETPOST('action', 'aZ09'); + + +// Security check +// if (! $user->rights->eventorganization->myobject->read) { +// accessforbidden(); +// } +$socid = GETPOST('socid', 'int'); +if (isset($user->socid) && $user->socid > 0) { + $action = ''; + $socid = $user->socid; +} + +$max = 5; +$now = dol_now(); + + +/* + * Actions + */ + +// None + + +/* + * View + */ + +$form = new Form($db); +$formfile = new FormFile($db); + +llxHeader("", $langs->trans("EventOrganizationArea")); + +print load_fiche_titre($langs->trans("EventOrganizationArea"), '', 'eventorganization.png@eventorganization'); + +print '
    '; + + +/* BEGIN MODULEBUILDER DRAFT MYOBJECT +// Draft MyObject +if (! empty($conf->eventorganization->enabled) && $user->rights->eventorganization->read) +{ + $langs->load("orders"); + + $sql = "SELECT c.rowid, c.ref, c.ref_client, c.total_ht, c.tva as total_tva, c.total_ttc, s.rowid as socid, s.nom as name, s.client, s.canvas"; + $sql.= ", s.code_client"; + $sql.= " FROM ".MAIN_DB_PREFIX."commande as c"; + $sql.= ", ".MAIN_DB_PREFIX."societe as s"; + if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql.= " WHERE c.fk_soc = s.rowid"; + $sql.= " AND c.fk_statut = 0"; + $sql.= " AND c.entity IN (".getEntity('commande').")"; + if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + if ($socid) $sql.= " AND c.fk_soc = ".$socid; + + $resql = $db->query($sql); + if ($resql) + { + $total = 0; + $num = $db->num_rows($resql); + + print ''; + print ''; + print ''; + + $var = true; + if ($num > 0) + { + $i = 0; + while ($i < $num) + { + + $obj = $db->fetch_object($resql); + print ''; + print ''; + print ''; + $i++; + $total += $obj->total_ttc; + } + if ($total>0) + { + + print '"; + } + } + else + { + + print ''; + } + print "
    '.$langs->trans("DraftMyObjects").($num?''.$num.'':'').'
    '; + + $myobjectstatic->id=$obj->rowid; + $myobjectstatic->ref=$obj->ref; + $myobjectstatic->ref_client=$obj->ref_client; + $myobjectstatic->total_ht = $obj->total_ht; + $myobjectstatic->total_tva = $obj->total_tva; + $myobjectstatic->total_ttc = $obj->total_ttc; + + print $myobjectstatic->getNomUrl(1); + print ''; + print ''.price($obj->total_ttc).'
    '.$langs->trans("Total").''.price($total)."
    '.$langs->trans("NoOrder").'

    "; + + $db->free($resql); + } + else + { + dol_print_error($db); + } +} +END MODULEBUILDER DRAFT MYOBJECT */ + + +print '
    '; + + +$NBMAX = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; +$max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; + +/* BEGIN MODULEBUILDER LASTMODIFIED MYOBJECT +// Last modified myobject +if (! empty($conf->eventorganization->enabled) && $user->rights->eventorganization->read) +{ + $sql = "SELECT s.rowid, s.ref, s.label, s.date_creation, s.tms"; + $sql.= " FROM ".MAIN_DB_PREFIX."eventorganization_myobject as s"; + //if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql.= " WHERE s.entity IN (".getEntity($myobjectstatic->element).")"; + //if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + //if ($socid) $sql.= " AND s.rowid = $socid"; + $sql .= " ORDER BY s.tms DESC"; + $sql .= $db->plimit($max, 0); + + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + + print ''; + print ''; + print ''; + print ''; + print ''; + if ($num) + { + while ($i < $num) + { + $objp = $db->fetch_object($resql); + + $myobjectstatic->id=$objp->rowid; + $myobjectstatic->ref=$objp->ref; + $myobjectstatic->label=$objp->label; + $myobjectstatic->status = $objp->status; + + print ''; + print ''; + print '"; + print '"; + print ''; + $i++; + } + + $db->free($resql); + } else { + print ''; + } + print "
    '; + print $langs->trans("BoxTitleLatestModifiedMyObjects", $max); + print ''.$langs->trans("DateModificationShort").'
    '.$myobjectstatic->getNomUrl(1).''; + print "'.dol_print_date($db->jdate($objp->tms), 'day')."
    '.$langs->trans("None").'

    "; + } +} +*/ + +print '
    '; + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/eventorganization/index.html b/htdocs/eventorganization/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/eventorganization/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/eventorganization/lib/eventorganization_conferenceorbooth.lib.php b/htdocs/eventorganization/lib/eventorganization_conferenceorbooth.lib.php new file mode 100644 index 00000000000..541915fc953 --- /dev/null +++ b/htdocs/eventorganization/lib/eventorganization_conferenceorbooth.lib.php @@ -0,0 +1,70 @@ +. + */ + +/** + * \file lib/eventorganization_conferenceorbooth.lib.php + * \ingroup eventorganization + * \brief Library files with common functions for ConferenceOrBooth + */ + +/** + * Prepare array of tabs for ConferenceOrBooth + * + * @param ConferenceOrBooth $object ConferenceOrBooth + * @return array Array of tabs + */ +function conferenceorboothPrepareHead($object) +{ + global $db, $langs, $conf; + + $langs->load("eventorganization@eventorganization"); + + $h = 0; + $head = array(); + + $head[$h][0] = dol_buildpath("/eventorganization/conferenceorbooth_card.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Card"); + $head[$h][2] = 'card'; + $h++; + + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->eventorganization->dir_output."/conferenceorbooth/".dol_sanitizeFileName($object->ref); + $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); + $nbLinks = Link::count($db, $object->element, $object->id); + $head[$h][0] = dol_buildpath("/eventorganization/conferenceorbooth_document.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans('Documents'); + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } + $head[$h][2] = 'document'; + $h++; + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@eventorganization:/eventorganization/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@eventorganization:/eventorganization/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'conferenceorbooth@eventorganization'); + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'conferenceorbooth@eventorganization', 'remove'); + + return $head; +} diff --git a/htdocs/eventorganization/lib/index.html b/htdocs/eventorganization/lib/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/eventorganization/lib/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/eventorganization/modulebuilder.txt b/htdocs/eventorganization/modulebuilder.txt new file mode 100644 index 00000000000..670a1774929 --- /dev/null +++ b/htdocs/eventorganization/modulebuilder.txt @@ -0,0 +1,3 @@ +# DO NOT DELETE THIS FILE MANUALLY +# File to flag module built using official module template. +# When this file is present into a module directory, you can edit it with the module builder tool. \ No newline at end of file diff --git a/htdocs/expedition/card.php b/htdocs/expedition/card.php index 0652424d919..f46891b6847 100644 --- a/htdocs/expedition/card.php +++ b/htdocs/expedition/card.php @@ -46,9 +46,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; -if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; -if (!empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; +if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +} +if (!empty($conf->propal->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +} +if (!empty($conf->productbatch->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; +} if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; @@ -57,25 +63,38 @@ if (!empty($conf->projet->enabled)) { // Load translation files required by the page $langs->loadLangs(array("sendings", "companies", "bills", 'deliveries', 'orders', 'stocks', 'other', 'propal')); -if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); -if (!empty($conf->productbatch->enabled)) $langs->load('productbatch'); +if (!empty($conf->incoterm->enabled)) { + $langs->load('incoterm'); +} +if (!empty($conf->productbatch->enabled)) { + $langs->load('productbatch'); +} $origin = GETPOST('origin', 'alpha') ?GETPOST('origin', 'alpha') : 'expedition'; // Example: commande, propal $origin_id = GETPOST('id', 'int') ?GETPOST('id', 'int') : ''; $id = $origin_id; -if (empty($origin_id)) $origin_id = GETPOST('origin_id', 'int'); // Id of order or propal -if (empty($origin_id)) $origin_id = GETPOST('object_id', 'int'); // Id of order or propal +if (empty($origin_id)) { + $origin_id = GETPOST('origin_id', 'int'); // Id of order or propal +} +if (empty($origin_id)) { + $origin_id = GETPOST('object_id', 'int'); // Id of order or propal +} $ref = GETPOST('ref', 'alpha'); $line_id = GETPOST('lineid', 'int') ?GETPOST('lineid', 'int') : ''; // Security check $socid = ''; -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} -if ($origin == 'expedition') $result = restrictedArea($user, $origin, $id); -else { +if ($origin == 'expedition') { + $result = restrictedArea($user, $origin, $id); +} else { $result = restrictedArea($user, 'expedition'); - if (empty($user->rights->{$origin}->lire) && empty($user->rights->{$origin}->read)) accessforbidden(); + if (empty($user->rights->{$origin}->lire) && empty($user->rights->{$origin}->read)) { + accessforbidden(); + } } $action = GETPOST('action', 'alpha'); @@ -114,12 +133,12 @@ $date_delivery = dol_mktime(GETPOST('date_deliveryhour', 'int'), GETPOST('date_d $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 ($cancel) - { +if (empty($reshook)) { + if ($cancel) { $action = ''; $object->fetch($id); // show shipment also after canceling modification } @@ -132,20 +151,17 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; // Reopen - if ($action == 'reopen' && $user->rights->expedition->creer) - { + if ($action == 'reopen' && $user->rights->expedition->creer) { $object->fetch($id); $result = $object->reOpen(); } // Set incoterm - if ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { + if ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) { $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); } - if ($action == 'setref_customer') - { + if ($action == 'setref_customer') { $result = $object->fetch($id); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -161,32 +177,31 @@ if (empty($reshook)) } } - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('SHIPMENT_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } // Create shipment - if ($action == 'add' && $user->rights->expedition->creer) - { + if ($action == 'add' && $user->rights->expedition->creer) { $error = 0; $db->begin(); @@ -226,8 +241,7 @@ if (empty($reshook)) $num = count($objectsrc->lines); $totalqty = 0; - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $idl = "idl".$i; $sub_qty = array(); @@ -238,14 +252,11 @@ if (empty($reshook)) $stockLocation = "ent1".$i."_0"; $qty = "qtyl".$i; - if (!empty($conf->productbatch->enabled) && $objectsrc->lines[$i]->product_tobatch) // If product need a batch number - { - if (GETPOSTISSET($batch)) - { + if (!empty($conf->productbatch->enabled) && $objectsrc->lines[$i]->product_tobatch) { // If product need a batch number + if (GETPOSTISSET($batch)) { //shipment line with batch-enable product $qty .= '_'.$j; - while (GETPOSTISSET($batch)) - { + while (GETPOSTISSET($batch)) { // save line of detail into sub_qty $sub_qty[$j]['q'] = GETPOST($qty, 'int'); // the qty we want to move for this stock record $sub_qty[$j]['id_batch'] = GETPOST($batch, 'int'); // the id into llx_product_batch of stock record to move @@ -265,8 +276,7 @@ if (empty($reshook)) $totalqty += $subtotalqty; } else { // No detail were provided for lots - if (!empty($_POST[$qty])) - { + if (!empty($_POST[$qty])) { // We try to set an amount // Case we dont use the list of available qty for each warehouse/lot // GUI does not allow this yet @@ -276,8 +286,7 @@ if (empty($reshook)) } elseif (GETPOSTISSET($stockLocation)) { //shipment line from multiple stock locations $qty .= '_'.$j; - while (GETPOSTISSET($stockLocation)) - { + while (GETPOSTISSET($stockLocation)) { // save sub line of warehouse $stockLine[$i][$j]['qty'] = price2num(GETPOST($qty, 'alpha'), 'MS'); $stockLine[$i][$j]['warehouse_id'] = GETPOST($stockLocation, 'int'); @@ -292,7 +301,9 @@ if (empty($reshook)) } else { //var_dump(GETPOST($qty,'alpha')); var_dump($_POST); var_dump($batch);exit; //shipment line for product with no batch management and no multiple stock location - if (GETPOST($qty, 'int') > 0) $totalqty += price2num(GETPOST($qty, 'alpha'), 'MS'); + if (GETPOST($qty, 'int') > 0) { + $totalqty += price2num(GETPOST($qty, 'alpha'), 'MS'); + } } // Extrafields @@ -308,43 +319,38 @@ if (empty($reshook)) //var_dump($batch_line[2]); - if ($totalqty > 0) // There is at least one thing to ship - { + if ($totalqty > 0) { // There is at least one thing to ship //var_dump($_POST);exit; - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $qty = "qtyl".$i; - if (!isset($batch_line[$i])) - { + if (!isset($batch_line[$i])) { // not batch mode - if (isset($stockLine[$i])) - { + if (isset($stockLine[$i])) { //shipment from multiple stock locations $nbstockline = count($stockLine[$i]); - for ($j = 0; $j < $nbstockline; $j++) - { - if ($stockLine[$i][$j]['qty'] > 0) - { + for ($j = 0; $j < $nbstockline; $j++) { + if ($stockLine[$i][$j]['qty'] > 0) { $ret = $object->addline($stockLine[$i][$j]['warehouse_id'], $stockLine[$i][$j]['ix_l'], $stockLine[$i][$j]['qty'], $array_options[$i]); - if ($ret < 0) - { + if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } } } else { - if (GETPOST($qty, 'int') > 0 || (GETPOST($qty, 'int') == 0 && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS)) - { + if (GETPOST($qty, 'int') > 0 || (GETPOST($qty, 'int') == 0 && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS)) { $ent = "entl".$i; $idl = "idl".$i; $entrepot_id = is_numeric(GETPOST($ent, 'int')) ?GETPOST($ent, 'int') : GETPOST('entrepot_id', 'int'); - if ($entrepot_id < 0) $entrepot_id = ''; - if (!($objectsrc->lines[$i]->fk_product > 0)) $entrepot_id = 0; + if ($entrepot_id < 0) { + $entrepot_id = ''; + } + if (!($objectsrc->lines[$i]->fk_product > 0)) { + $entrepot_id = 0; + } $ret = $object->addline($entrepot_id, GETPOST($idl, 'int'), GETPOST($qty, 'int'), $array_options[$i]); - if ($ret < 0) - { + if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -352,11 +358,9 @@ if (empty($reshook)) } } else { // batch mode - if ($batch_line[$i]['qty'] > 0) - { + if ($batch_line[$i]['qty'] > 0) { $ret = $object->addline_batch($batch_line[$i], $array_options[$i]); - if ($ret < 0) - { + if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -365,13 +369,13 @@ 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++; + } - if (!$error) - { + if (!$error) { $ret = $object->create($user); // This create shipment (like Odoo picking) and lines of shipments. Stock movement will be done when validating shipment. - if ($ret <= 0) - { + if ($ret <= 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -381,8 +385,7 @@ if (empty($reshook)) $error++; } - if (!$error) - { + if (!$error) { $db->commit(); header("Location: card.php?id=".$object->id); exit; @@ -391,16 +394,10 @@ if (empty($reshook)) $_GET["commande_id"] = GETPOST('commande_id', 'int'); $action = 'create'; } - } - - /* - * Build a receiving receipt - */ - elseif ($action == 'create_delivery' && $conf->delivery_note->enabled && $user->rights->expedition->delivery->creer) - { + } elseif ($action == 'create_delivery' && $conf->delivery_note->enabled && $user->rights->expedition->delivery->creer) { + // Build a receiving receipt $result = $object->create_delivery($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".DOL_URL_ROOT.'/delivery/card.php?action=create_delivery&id='.$result); exit; } else { @@ -408,9 +405,8 @@ if (empty($reshook)) } } elseif ($action == 'confirm_valid' && $confirm == 'yes' && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->shipping_advance->validate))) - ) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->shipping_advance->validate))) + ) { $object->fetch_thirdparty(); $result = $object->valid($user); @@ -419,12 +415,15 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } else { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -433,57 +432,47 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } } - } elseif ($action == 'confirm_cancel' && $confirm == 'yes' && $user->rights->expedition->supprimer) - { + } elseif ($action == 'confirm_cancel' && $confirm == 'yes' && $user->rights->expedition->supprimer) { $also_update_stock = (GETPOST('alsoUpdateStock', 'alpha') ? 1 : 0); $result = $object->cancel(0, $also_update_stock); - if ($result > 0) - { + if ($result > 0) { $result = $object->setStatut(-1); } else { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->expedition->supprimer) - { + } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->expedition->supprimer) { $also_update_stock = (GETPOST('alsoUpdateStock', 'alpha') ? 1 : 0); $result = $object->delete(0, $also_update_stock); - if ($result > 0) - { + if ($result > 0) { header("Location: ".DOL_URL_ROOT.'/expedition/index.php'); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } - // TODO add alternative status - /*elseif ($action == 'reopen' && (! empty($user->rights->expedition->creer) || ! empty($user->rights->expedition->shipping_advance->validate))) - { - $result = $object->setStatut(0); - if ($result < 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } - }*/ - - elseif ($action == 'setdate_livraison' && $user->rights->expedition->creer) - { + // TODO add alternative status + //} elseif ($action == 'reopen' && (! empty($user->rights->expedition->creer) || ! empty($user->rights->expedition->shipping_advance->validate))) + //{ + // $result = $object->setStatut(0); + // if ($result < 0) + // { + // setEventMessages($object->error, $object->errors, 'errors'); + // } + //} + } elseif ($action == 'setdate_livraison' && $user->rights->expedition->creer) { //print "x ".$_POST['liv_month'].", ".$_POST['liv_day'].", ".$_POST['liv_year']; $datedelivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int')); $object->fetch($id); $result = $object->setDeliveryDate($user, $datedelivery); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Action update - elseif ( - ($action == 'settracking_number' + } elseif (($action == 'settracking_number' || $action == 'settracking_url' || $action == 'settrueWeight' || $action == 'settrueWidth' @@ -491,28 +480,36 @@ if (empty($reshook)) || $action == 'settrueDepth' || $action == 'setshipping_method_id') && $user->rights->expedition->creer - ) - { + ) { + // Action update $error = 0; - if ($action == 'settracking_number') $object->tracking_number = trim(GETPOST('tracking_number', 'alpha')); - if ($action == 'settracking_url') $object->tracking_url = trim(GETPOST('tracking_url', 'int')); + if ($action == 'settracking_number') { + $object->tracking_number = trim(GETPOST('tracking_number', 'alpha')); + } + if ($action == 'settracking_url') { + $object->tracking_url = trim(GETPOST('tracking_url', 'int')); + } if ($action == 'settrueWeight') { $object->trueWeight = trim(GETPOST('trueWeight', 'int')); $object->weight_units = GETPOST('weight_units', 'int'); } - if ($action == 'settrueWidth') $object->trueWidth = trim(GETPOST('trueWidth', 'int')); + if ($action == 'settrueWidth') { + $object->trueWidth = trim(GETPOST('trueWidth', 'int')); + } if ($action == 'settrueHeight') { $object->trueHeight = trim(GETPOST('trueHeight', 'int')); $object->size_units = GETPOST('size_units', 'int'); } - if ($action == 'settrueDepth') $object->trueDepth = trim(GETPOST('trueDepth', 'int')); - if ($action == 'setshipping_method_id') $object->shipping_method_id = trim(GETPOST('shipping_method_id', 'int')); + if ($action == 'settrueDepth') { + $object->trueDepth = trim(GETPOST('trueDepth', 'int')); + } + if ($action == 'setshipping_method_id') { + $object->shipping_method_id = trim(GETPOST('shipping_method_id', 'int')); + } - if (!$error) - { - if ($object->update($user) >= 0) - { + if (!$error) { + if ($object->update($user) >= 0) { header("Location: card.php?id=".$object->id); exit; } @@ -520,8 +517,7 @@ if (empty($reshook)) } $action = ""; - } elseif ($action == 'classifybilled') - { + } elseif ($action == 'classifybilled') { $object->fetch($id); $result = $object->setBilled(); if ($result >= 0) { @@ -529,8 +525,7 @@ if (empty($reshook)) exit(); } setEventMessages($object->error, $object->errors, 'errors'); - } elseif ($action == 'classifyclosed') - { + } elseif ($action == 'classifyclosed') { $object->fetch($id); $result = $object->setClosed(); if ($result >= 0) { @@ -538,37 +533,27 @@ if (empty($reshook)) exit(); } setEventMessages($object->error, $object->errors, 'errors'); - } - - /* - * delete a line - */ - elseif ($action == 'deleteline' && !empty($line_id)) - { + } elseif ($action == 'deleteline' && !empty($line_id)) { + // delete a line $object->fetch($id); $lines = $object->lines; $line = new ExpeditionLigne($db); $num_prod = count($lines); - for ($i = 0; $i < $num_prod; $i++) - { - if ($lines[$i]->id == $line_id) - { - if (count($lines[$i]->details_entrepot) > 1) - { + for ($i = 0; $i < $num_prod; $i++) { + if ($lines[$i]->id == $line_id) { + if (count($lines[$i]->details_entrepot) > 1) { // delete multi warehouse lines foreach ($lines[$i]->details_entrepot as $details_entrepot) { $line->id = $details_entrepot->line_id; - if (!$error && $line->delete($user) < 0) - { + if (!$error && $line->delete($user) < 0) { $error++; } } } else { // delete single warehouse line $line->id = $line_id; - if (!$error && $line->delete($user) < 0) - { + if (!$error && $line->delete($user) < 0) { $error++; } } @@ -582,13 +567,8 @@ if (empty($reshook)) } else { setEventMessages($line->error, $line->errors, 'errors'); } - } - - /* - * Update a line - */ - elseif ($action == 'updateline' && $user->rights->expedition->creer && GETPOST('save')) - { + } elseif ($action == 'updateline' && $user->rights->expedition->creer && GETPOST('save')) { + // Update a line // Clean parameters $qty = 0; $entrepot_id = 0; @@ -596,10 +576,8 @@ if (empty($reshook)) $lines = $object->lines; $num_prod = count($lines); - for ($i = 0; $i < $num_prod; $i++) - { - if ($lines[$i]->id == $line_id) // we have found line to update - { + for ($i = 0; $i < $num_prod; $i++) { + if ($lines[$i]->id == $line_id) { // we have found line to update $line = new ExpeditionLigne($db); // Extrafields Lines @@ -611,28 +589,25 @@ if (empty($reshook)) } } $line->fk_product = $lines[$i]->fk_product; - if (is_array($lines[$i]->detail_batch) && count($lines[$i]->detail_batch) > 0) - { + if (is_array($lines[$i]->detail_batch) && count($lines[$i]->detail_batch) > 0) { // line with lot - foreach ($lines[$i]->detail_batch as $detail_batch) - { + foreach ($lines[$i]->detail_batch as $detail_batch) { $lotStock = new Productbatch($db); $batch = "batchl".$detail_batch->fk_expeditiondet."_".$detail_batch->fk_origin_stock; $qty = "qtyl".$detail_batch->fk_expeditiondet.'_'.$detail_batch->id; $batch_id = GETPOST($batch, 'int'); $batch_qty = GETPOST($qty, 'int'); - if (!empty($batch_id) && ($batch_id != $detail_batch->fk_origin_stock || $batch_qty != $detail_batch->qty)) - { - if ($lotStock->fetch($batch_id) > 0 && $line->fetch($detail_batch->fk_expeditiondet) > 0) // $line is ExpeditionLine - { - if ($lines[$i]->entrepot_id != 0) - { + if (!empty($batch_id) && ($batch_id != $detail_batch->fk_origin_stock || $batch_qty != $detail_batch->qty)) { + if ($lotStock->fetch($batch_id) > 0 && $line->fetch($detail_batch->fk_expeditiondet) > 0) { // $line is ExpeditionLine + if ($lines[$i]->entrepot_id != 0) { // allow update line entrepot_id if not multi warehouse shipping $line->entrepot_id = $lotStock->warehouseid; } // detail_batch can be an object with keys, or an array of ExpeditionLineBatch - if (empty($line->detail_batch)) $line->detail_batch = new stdClass(); + if (empty($line->detail_batch)) { + $line->detail_batch = new stdClass(); + } $line->detail_batch->fk_origin_stock = $batch_id; $line->detail_batch->batch = $lotStock->batch; @@ -658,34 +633,25 @@ if (empty($reshook)) $batch_id = GETPOST($batch, 'int'); $batch_qty = GETPOST($qty, 'int'); $lineIdToAddLot = 0; - if ($batch_qty > 0 && !empty($batch_id)) - { - if ($lotStock->fetch($batch_id) > 0) - { + if ($batch_qty > 0 && !empty($batch_id)) { + if ($lotStock->fetch($batch_id) > 0) { // check if lotStock warehouse id is same as line warehouse id - if ($lines[$i]->entrepot_id > 0) - { + if ($lines[$i]->entrepot_id > 0) { // single warehouse shipment line - if ($lines[$i]->entrepot_id == $lotStock->warehouseid) - { + if ($lines[$i]->entrepot_id == $lotStock->warehouseid) { $lineIdToAddLot = $line_id; } - } elseif (count($lines[$i]->details_entrepot) > 1) - { + } elseif (count($lines[$i]->details_entrepot) > 1) { // multi warehouse shipment lines - foreach ($lines[$i]->details_entrepot as $detail_entrepot) - { - if ($detail_entrepot->entrepot_id == $lotStock->warehouseid) - { + foreach ($lines[$i]->details_entrepot as $detail_entrepot) { + if ($detail_entrepot->entrepot_id == $lotStock->warehouseid) { $lineIdToAddLot = $detail_entrepot->line_id; } } } - if ($lineIdToAddLot) - { + if ($lineIdToAddLot) { // add lot to existing line - if ($line->fetch($lineIdToAddLot) > 0) - { + if ($line->fetch($lineIdToAddLot) > 0) { $line->detail_batch->fk_origin_stock = $batch_id; $line->detail_batch->batch = $lotStock->batch; $line->detail_batch->entrepot_id = $lotStock->warehouseid; @@ -707,8 +673,7 @@ if (empty($reshook)) $line->detail_batch[0]->batch = $lotStock->batch; $line->detail_batch[0]->entrepot_id = $lotStock->warehouseid; $line->detail_batch[0]->qty = $batch_qty; - if ($object->create_line_batch($line, $line->array_options) < 0) - { + if ($object->create_line_batch($line, $line->array_options) < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -719,11 +684,9 @@ if (empty($reshook)) } } } else { - if ($lines[$i]->fk_product > 0) - { + if ($lines[$i]->fk_product > 0) { // line without lot - if ($lines[$i]->entrepot_id > 0) - { + if ($lines[$i]->entrepot_id > 0) { // single warehouse shipment line $stockLocation = "entl".$line_id; $qty = "qtyl".$line_id; @@ -736,17 +699,14 @@ if (empty($reshook)) } unset($_POST[$stockLocation]); unset($_POST[$qty]); - } elseif (count($lines[$i]->details_entrepot) > 1) - { + } elseif (count($lines[$i]->details_entrepot) > 1) { // multi warehouse shipment lines - foreach ($lines[$i]->details_entrepot as $detail_entrepot) - { + foreach ($lines[$i]->details_entrepot as $detail_entrepot) { if (!$error) { $stockLocation = "entl".$detail_entrepot->line_id; $qty = "qtyl".$detail_entrepot->line_id; $warehouse = GETPOST($stockLocation, 'int'); - if (!empty($warehouse)) - { + if (!empty($warehouse)) { $line->id = $detail_entrepot->line_id; $line->entrepot_id = $warehouse; $line->qty = GETPOST($qty, 'int'); @@ -783,10 +743,12 @@ if (empty($reshook)) // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -807,7 +769,9 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - if (empty($id)) $id = $facid; + if (empty($id)) { + $id = $facid; + } $triggersendname = 'SHIPPING_SENTBYMAIL'; $paramname = 'id'; $mode = 'emailfromshipment'; @@ -820,19 +784,22 @@ if (empty($reshook)) * View */ -llxHeader('', $langs->trans('Shipment'), 'Expedition'); +$help_url = 'EN:Module_Shipments|FR:Module_Expéditions|ES:Módulo_Expediciones|DE:Modul_Lieferungen'; + +llxHeader('', $langs->trans('Shipment'), 'Expedition', $help_url); $form = new Form($db); $formfile = new FormFile($db); $formproduct = new FormProduct($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $product_static = new Product($db); $shipment_static = new Expedition($db); $warehousestatic = new Entrepot($db); -if ($action == 'create2') -{ +if ($action == 'create2') { print load_fiche_titre($langs->trans("CreateShipment"), '', 'dolly'); print '
    '.$langs->trans("ShipmentCreationIsDoneFromOrder"); @@ -840,31 +807,29 @@ if ($action == 'create2') } // Mode creation. -if ($action == 'create') -{ +if ($action == 'create') { $expe = new Expedition($db); print load_fiche_titre($langs->trans("CreateShipment"), '', 'dolly'); - if (!$origin) - { + if (!$origin) { setEventMessages($langs->trans("ErrorBadParameters"), null, 'errors'); } - if ($origin) - { + if ($origin) { $classname = ucfirst($origin); $object = new $classname($db); - if ($object->fetch($origin_id)) // This include the fetch_lines - { + if ($object->fetch($origin_id)) { // This include the fetch_lines $soc = new Societe($db); $soc->fetch($object->socid); $author = new User($db); $author->fetch($object->user_author_id); - if (!empty($conf->stock->enabled)) $entrepot = new Entrepot($db); + if (!empty($conf->stock->enabled)) { + $entrepot = new Entrepot($db); + } print '
    '; print ''; @@ -872,8 +837,7 @@ if ($action == 'create') print ''; print ''; print ''; - if (GETPOST('entrepot_id', 'int')) - { + if (GETPOST('entrepot_id', 'int')) { print ''; } @@ -883,12 +847,10 @@ if ($action == 'create') // Ref print ''; - if ($origin == 'commande' && !empty($conf->commande->enabled)) - { + if ($origin == 'commande' && !empty($conf->commande->enabled)) { print $langs->trans("RefOrder"); } - if ($origin == 'propal' && !empty($conf->propal->enabled)) - { + if ($origin == 'propal' && !empty($conf->propal->enabled)) { print $langs->trans("RefProposal"); } print ''; @@ -898,9 +860,13 @@ if ($action == 'create') // Ref client print ''; - if ($origin == 'commande') print $langs->trans('RefCustomerOrder'); - elseif ($origin == 'propal') print $langs->trans('RefCustomerOrder'); - else print $langs->trans('RefCustomer'); + if ($origin == 'commande') { + print $langs->trans('RefCustomerOrder'); + } elseif ($origin == 'propal') { + print $langs->trans('RefCustomerOrder'); + } else { + print $langs->trans('RefCustomer'); + } print ''; print ''; print ''; @@ -912,11 +878,14 @@ if ($action == 'create') print ''; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $projectid = GETPOST('projectid', 'int') ?GETPOST('projectid', 'int') : 0; - if (empty($projectid) && !empty($object->fk_project)) $projectid = $object->fk_project; - if ($origin == 'project') $projectid = ($originid ? $originid : 0); + if (empty($projectid) && !empty($object->fk_project)) { + $projectid = $object->fk_project; + } + if ($origin == 'project') { + $projectid = ($originid ? $originid : 0); + } $langs->load("projects"); print ''; @@ -944,8 +913,7 @@ if ($action == 'create') print ""; // Note Private - if ($object->note_private && !$user->socid) - { + if ($object->note_private && !$user->socid) { print ''.$langs->trans("NotePrivate").''; print ''; $doleditor = new DolEditor('note_private', $object->note_private, '', 60, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%'); @@ -978,7 +946,9 @@ if ($action == 'create') print ''; $expe->fetch_delivery_methods(); print $form->selectarray("shipping_method_id", $expe->meths, GETPOST('shipping_method_id', 'int'), 1, 0, 0, "", 1); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print "\n"; // Tracking number @@ -1002,8 +972,7 @@ if ($action == 'create') // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print ''; print ''; print ''; @@ -1014,8 +983,7 @@ if ($action == 'create') // Document model include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php'; $list = ModelePdfExpedition::liste_modeles($db); - if (count($list) > 1) - { + if (count($list) > 1) { print "".$langs->trans("DefaultModel").""; print ''; print $form->selectarray('model', $list, $conf->global->EXPEDITION_ADDON_PDF); @@ -1035,22 +1003,15 @@ if ($action == 'create') jQuery(document).ready(function() { jQuery("#autofill").click(function() {'; $i = 0; - while ($i < $numAsked) - { + while ($i < $numAsked) { print 'jQuery("#qtyl'.$i.'").val(jQuery("#qtyasked'.$i.'").val() - jQuery("#qtydelivered'.$i.'").val());'."\n"; - if (!empty($conf->productbatch->enabled)) print 'jQuery("#qtyl'.$i.'_'.$i.'").val(jQuery("#qtyasked'.$i.'").val() - jQuery("#qtydelivered'.$i.'").val());'."\n"; - $i++; - } - print '}); - jQuery("#autoreset").click(function() { console.log("Reset values to 0"); '; - $i = 0; - while ($i < $numAsked) - { - print 'jQuery("#qtyl'.$i.'").val(0);'."\n"; - if (!empty($conf->productbatch->enabled)) print 'jQuery("#qtyl'.$i.'_'.$i.'").val(0);'."\n"; + if (!empty($conf->productbatch->enabled)) { + print 'jQuery("#qtyl'.$i.'_'.$i.'").val(jQuery("#qtyasked'.$i.'").val() - jQuery("#qtydelivered'.$i.'").val());'."\n"; + } $i++; } print '}); + jQuery("#autoreset").click(function() { console.log("Reset values to 0"); jQuery(".qtyl").val(0); }); }); '; @@ -1061,15 +1022,13 @@ if ($action == 'create') // Load shipments already done for same order $object->loadExpeditions(); - if ($numAsked) - { + if ($numAsked) { print ''; print ''.$langs->trans("Description").''; print ''.$langs->trans("QtyOrdered").''; print ''.$langs->trans("QtyShipped").''; print ''.$langs->trans("QtyToShip"); - if (empty($conf->productbatch->enabled)) - { + if (empty($conf->productbatch->enabled)) { print '
    '.$langs->trans("Fill").''; print ' / '; } else { @@ -1077,10 +1036,8 @@ if ($action == 'create') } print ''.img_picto($langs->trans("Reset"), 'eraser').''; print ''; - if (!empty($conf->stock->enabled)) - { - if (empty($conf->productbatch->enabled)) - { + if (!empty($conf->stock->enabled)) { + if (empty($conf->productbatch->enabled)) { print ''.$langs->trans("Warehouse").' ('.$langs->trans("Stock").')'; } else { print ''.$langs->trans("Warehouse").' / '.$langs->trans("Batch").' ('.$langs->trans("Stock").')'; @@ -1090,31 +1047,34 @@ if ($action == 'create') } $indiceAsked = 0; - while ($indiceAsked < $numAsked) - { + while ($indiceAsked < $numAsked) { $product = new Product($db); $line = $object->lines[$indiceAsked]; $parameters = array('i' => $indiceAsked, 'line' => $line, 'num' => $numAsked); $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $object, $action); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Show product and description $type = $line->product_type ? $line->product_type : $line->fk_product_type; // Try to enhance type detection using date_start and date_end for free lines where type // was not saved. - if (!empty($line->date_start)) $type = 1; - if (!empty($line->date_end)) $type = 1; + if (!empty($line->date_start)) { + $type = 1; + } + if (!empty($line->date_end)) { + $type = 1; + } print ''."\n"; print ''."\n"; // Product label - if ($line->fk_product > 0) // If predefined product - { + if ($line->fk_product > 0) { // If predefined product $product->fetch($line->fk_product); $product->load_stock('warehouseopen'); // Load all $product->stock_warehouse[idwarehouse]->detail_batch //var_dump($product->stock_warehouse[1]); @@ -1139,16 +1099,18 @@ if ($action == 'create') print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end)); // Add description in form - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { print ($line->desc && $line->desc != $line->product_label) ? '
    '.dol_htmlentitiesbr($line->desc) : ''; } print ''; } else { print ""; - if ($type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if ($type == 1) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($line->label)) { $text .= ' '.$line->label.''; @@ -1177,8 +1139,7 @@ if ($action == 'create') // Qty to ship $quantityAsked = $line->qty; - if ($line->product_type == 1 && empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if ($line->product_type == 1 && empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $quantityToBeDelivered = 0; } else { $quantityToBeDelivered = $quantityAsked - $quantityDelivered; @@ -1186,37 +1147,37 @@ if ($action == 'create') $warehouse_id = GETPOST('entrepot_id', 'int'); $warehouseObject = null; - if ($warehouse_id > 0 || !($line->fk_product > 0) || empty($conf->stock->enabled)) // If warehouse was already selected or if product is not a predefined, we go into this part with no multiwarehouse selection - { + if ($warehouse_id > 0 || !($line->fk_product > 0) || empty($conf->stock->enabled)) { // If warehouse was already selected or if product is not a predefined, we go into this part with no multiwarehouse selection print ''; //ship from preselected location $stock = + $product->stock_warehouse[$warehouse_id]->real; // Convert to number $deliverableQty = min($quantityToBeDelivered, $stock); - if ($deliverableQty < 0) $deliverableQty = 0; - if (empty($conf->productbatch->enabled) || !$product->hasbatch()) - { + if ($deliverableQty < 0) { + $deliverableQty = 0; + } + if (empty($conf->productbatch->enabled) || !$product->hasbatch()) { // Quantity to send print ''; - if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - if (GETPOST('qtyl'.$indiceAsked, 'int')) $deliverableQty = GETPOST('qtyl'.$indiceAsked, 'int'); + if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + if (GETPOST('qtyl'.$indiceAsked, 'int')) { + $deliverableQty = GETPOST('qtyl'.$indiceAsked, 'int'); + } print ''; print ''; - } else print $langs->trans("NA"); + } else { + print $langs->trans("NA"); + } print ''; // Stock - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print ''; - if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) // Type of product need stock change ? - { + if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { // Type of product need stock change ? // Show warehouse combo list $ent = "entl".$indiceAsked; $idl = "idl".$indiceAsked; $tmpentrepot_id = is_numeric(GETPOST($ent, 'int')) ?GETPOST($ent, 'int') : $warehouse_id; - if ($line->fk_product > 0) - { + if ($line->fk_product > 0) { print ''; $stockMin = false; @@ -1225,11 +1186,9 @@ if ($action == 'create') } print $formproduct->selectWarehouses($tmpentrepot_id, 'entl'.$indiceAsked, '', 1, 0, $line->fk_product, '', 1, 0, array(), 'minwidth200', '', 1, $stockMin, 'stock DESC, e.ref'); - if ($tmpentrepot_id > 0 && $tmpentrepot_id == $warehouse_id) - { + if ($tmpentrepot_id > 0 && $tmpentrepot_id == $warehouse_id) { //print $stock.' '.$quantityToBeDelivered; - if ($stock < $quantityToBeDelivered) - { + if ($stock < $quantityToBeDelivered) { print ' '.img_warning($langs->trans("StockTooLow")); // Stock too low for this $warehouse_id but you can change warehouse } } @@ -1243,18 +1202,14 @@ if ($action == 'create') print "\n"; // Show subproducts of product - if (!empty($conf->global->PRODUIT_SOUSPRODUITS) && $line->fk_product > 0) - { + if (!empty($conf->global->PRODUIT_SOUSPRODUITS) && $line->fk_product > 0) { $product->get_sousproduits_arbo(); $prods_arbo = $product->get_arbo_each_prod($qtyProdCom); - if (count($prods_arbo) > 0) - { - foreach ($prods_arbo as $key => $value) - { + if (count($prods_arbo) > 0) { + foreach ($prods_arbo as $key => $value) { //print $value[0]; $img = ''; - if ($value['stock'] < $value['stock_alert']) - { + if ($value['stock'] < $value['stock_alert']) { $img = img_warning($langs->trans("StockTooLow")); } print "      -> @@ -1270,29 +1225,27 @@ if ($action == 'create') print ''; $staticwarehouse = new Entrepot($db); - if ($warehouse_id > 0) $staticwarehouse->fetch($warehouse_id); + if ($warehouse_id > 0) { + $staticwarehouse->fetch($warehouse_id); + } $subj = 0; // Define nb of lines suggested for this order line $nbofsuggested = 0; - if (is_object($product->stock_warehouse[$warehouse_id]) && count($product->stock_warehouse[$warehouse_id]->detail_batch)) - { - foreach ($product->stock_warehouse[$warehouse_id]->detail_batch as $dbatch) - { + if (is_object($product->stock_warehouse[$warehouse_id]) && count($product->stock_warehouse[$warehouse_id]->detail_batch)) { + foreach ($product->stock_warehouse[$warehouse_id]->detail_batch as $dbatch) { $nbofsuggested++; } } print ''; - if (is_object($product->stock_warehouse[$warehouse_id]) && count($product->stock_warehouse[$warehouse_id]->detail_batch)) - { - foreach ($product->stock_warehouse[$warehouse_id]->detail_batch as $dbatch) // $dbatch is instance of Productbatch - { + if (is_object($product->stock_warehouse[$warehouse_id]) && count($product->stock_warehouse[$warehouse_id]->detail_batch)) { + foreach ($product->stock_warehouse[$warehouse_id]->detail_batch as $dbatch) { // $dbatch is instance of Productbatch //var_dump($dbatch); $batchStock = + $dbatch->qty; // To get a numeric $deliverableQty = min($quantityToBeDelivered, $batchStock); print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -1315,8 +1268,7 @@ if ($action == 'create') print $detail; $quantityToBeDelivered -= $deliverableQty; - if ($quantityToBeDelivered < 0) - { + if ($quantityToBeDelivered < 0) { $quantityToBeDelivered = 0; } $subj++; @@ -1325,7 +1277,7 @@ if ($action == 'create') } else { print ''; print ''; - print ' '; + print ' '; print ''; print ''; @@ -1335,8 +1287,7 @@ if ($action == 'create') } } else { // ship from multiple locations - if (empty($conf->productbatch->enabled) || !$product->hasbatch()) - { + if (empty($conf->productbatch->enabled) || !$product->hasbatch()) { print ''; print ''."\n"; // end line and start a new one for each warehouse @@ -1344,38 +1295,33 @@ if ($action == 'create') $subj = 0; // Define nb of lines suggested for this order line $nbofsuggested = 0; - foreach ($product->stock_warehouse as $warehouse_id=>$stock_warehouse) - { - if ($stock_warehouse->real > 0) - { + foreach ($product->stock_warehouse as $warehouse_id => $stock_warehouse) { + if ($stock_warehouse->real > 0) { $nbofsuggested++; } } $tmpwarehouseObject = new Entrepot($db); - foreach ($product->stock_warehouse as $warehouse_id=>$stock_warehouse) // $stock_warehouse is product_stock - { + foreach ($product->stock_warehouse as $warehouse_id => $stock_warehouse) { // $stock_warehouse is product_stock $tmpwarehouseObject->fetch($warehouse_id); - if ($stock_warehouse->real > 0) - { + if ($stock_warehouse->real > 0) { $stock = + $stock_warehouse->real; // Convert it to number $deliverableQty = min($quantityToBeDelivered, $stock); $deliverableQty = max(0, $deliverableQty); // Quantity to send print ''; print ''; - if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { print ''; print ''; - } else print $langs->trans("NA"); + } else { + print $langs->trans("NA"); + } print ''; // Stock - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print ''; - if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { print $tmpwarehouseObject->getNomUrl(0).' '; print ''; @@ -1386,8 +1332,7 @@ if ($action == 'create') print ''; } $quantityToBeDelivered -= $deliverableQty; - if ($quantityToBeDelivered < 0) - { + if ($quantityToBeDelivered < 0) { $quantityToBeDelivered = 0; } $subj++; @@ -1395,18 +1340,14 @@ if ($action == 'create') } } // Show subproducts of product (not recommanded) - if (!empty($conf->global->PRODUIT_SOUSPRODUITS) && $line->fk_product > 0) - { + if (!empty($conf->global->PRODUIT_SOUSPRODUITS) && $line->fk_product > 0) { $product->get_sousproduits_arbo(); $prods_arbo = $product->get_arbo_each_prod($qtyProdCom); - if (count($prods_arbo) > 0) - { - foreach ($prods_arbo as $key => $value) - { + if (count($prods_arbo) > 0) { + foreach ($prods_arbo as $key => $value) { //print $value[0]; $img = ''; - if ($value['stock'] < $value['stock_alert']) - { + if ($value['stock'] < $value['stock_alert']) { $img = img_warning($langs->trans("StockTooLow")); } print ''; @@ -1429,27 +1370,25 @@ if ($action == 'create') $productlotObject = new Productlot($db); // Define nb of lines suggested for this order line $nbofsuggested = 0; - foreach ($product->stock_warehouse as $warehouse_id=>$stock_warehouse) - { + foreach ($product->stock_warehouse as $warehouse_id => $stock_warehouse) { if (($stock_warehouse->real > 0) && (count($stock_warehouse->detail_batch))) { - foreach ($stock_warehouse->detail_batch as $dbatch) - { + foreach ($stock_warehouse->detail_batch as $dbatch) { $nbofsuggested++; } } } - foreach ($product->stock_warehouse as $warehouse_id=>$stock_warehouse) - { + foreach ($product->stock_warehouse as $warehouse_id => $stock_warehouse) { $tmpwarehouseObject->fetch($warehouse_id); if (($stock_warehouse->real > 0) && (count($stock_warehouse->detail_batch))) { - foreach ($stock_warehouse->detail_batch as $dbatch) - { + foreach ($stock_warehouse->detail_batch as $dbatch) { //var_dump($dbatch); $batchStock = + $dbatch->qty; // To get a numeric $deliverableQty = min($quantityToBeDelivered, $batchStock); - if ($deliverableQty < 0) $deliverableQty = 0; + if ($deliverableQty < 0) { + $deliverableQty = 0; + } print ''; - print ''; + print ''; print ''; print ''; @@ -1462,12 +1401,14 @@ if ($action == 'create') //print '|'.$line->fk_product.'|'.$dbatch->batch.'|
    '; print $langs->trans("Batch").': '; $result = $productlotObject->fetch(0, $line->fk_product, $dbatch->batch); - if ($result > 0) print $productlotObject->getNomUrl(1); - else print 'TableLotIncompleteRunRepairWithParamStandardEqualConfirmed'; + if ($result > 0) { + print $productlotObject->getNomUrl(1); + } else { + print 'TableLotIncompleteRunRepairWithParamStandardEqualConfirmed'; + } print ' ('.$dbatch->qty.')'; $quantityToBeDelivered -= $deliverableQty; - if ($quantityToBeDelivered < 0) - { + if ($quantityToBeDelivered < 0) { $quantityToBeDelivered = 0; } //dol_syslog('deliverableQty = '.$deliverableQty.' batchStock = '.$batchStock); @@ -1477,40 +1418,38 @@ if ($action == 'create') } } } - if ($subj == 0) // Line not shown yet, we show it - { + if ($subj == 0) { // Line not shown yet, we show it $warehouse_selected_id = GETPOST('entrepot_id', 'int'); print ''; print ''; - if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $disabled = ''; - if (!empty($conf->productbatch->enabled) && $product->hasbatch()) - { + if (!empty($conf->productbatch->enabled) && $product->hasbatch()) { $disabled = 'disabled="disabled"'; } if ($warehouse_selected_id <= 0) { // We did not force a given warehouse, so we won't have no warehouse to change qty. $disabled = 'disabled="disabled"'; } - print ' '; + print ' '; } else { print $langs->trans("NA"); } print ''; print ''; - if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - if ($warehouse_selected_id > 0) - { + if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + if ($warehouse_selected_id > 0) { $warehouseObject = new Entrepot($db); $warehouseObject->fetch($warehouse_selected_id); print img_warning().' '.$langs->trans("NoProductToShipFoundIntoStock", $warehouseObject->label); } else { - if ($line->fk_product) print img_warning().' '.$langs->trans("StockTooLow"); - else print ''; + if ($line->fk_product) { + print img_warning().' '.$langs->trans("StockTooLow"); + } else { + print ''; + } } } else { print $langs->trans("Service"); @@ -1521,8 +1460,7 @@ if ($action == 'create') } // Line extrafield - if (!empty($extrafields)) - { + if (!empty($extrafields)) { //var_dump($line); $colspan = 5; $expLine = new ExpeditionLigne($db); @@ -1556,21 +1494,18 @@ if ($action == 'create') dol_print_error($db); } } -} elseif ($id || $ref) -/* *************************************************************************** */ -/* */ -/* Edit and view mode */ -/* */ -/* *************************************************************************** */ -{ +} elseif ($id || $ref) { + /* *************************************************************************** */ + /* */ + /* Edit and view mode */ + /* */ + /* *************************************************************************** */ $lines = $object->lines; $num_prod = count($lines); - if ($object->id > 0) - { - if (!empty($object->origin) && $object->origin_id > 0) - { + if ($object->id > 0) { + if (!empty($object->origin) && $object->origin_id > 0) { $typeobject = $object->origin; $origin = $object->origin; $origin_id = $object->origin_id; @@ -1588,8 +1523,7 @@ if ($action == 'create') $formconfirm = ''; // Confirm deleteion - if ($action == 'delete') - { + if ($action == 'delete') { $formquestion = array(); if ($object->statut == Expedition::STATUS_CLOSED && !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { $formquestion = array( @@ -1613,11 +1547,9 @@ if ($action == 'create') } // Confirmation validation - if ($action == 'valid') - { + if ($action == 'valid') { $objectref = substr($object->ref, 1, 4); - if ($objectref == 'PROV') - { + if ($objectref == 'PROV') { $numref = $object->getNextNumRef($soc); } else { $numref = $object->ref; @@ -1625,8 +1557,7 @@ if ($action == 'create') $text = $langs->trans("ConfirmValidateSending", $numref); - if (!empty($conf->notification->enabled)) - { + if (!empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; $notify = new Notify($db); $text .= '
    '; @@ -1636,16 +1567,18 @@ if ($action == 'create') $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('ValidateSending'), $text, 'confirm_valid', '', 0, 1); } // Confirm cancelation - if ($action == 'cancel') - { + if ($action == 'cancel') { $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('CancelSending'), $langs->trans("ConfirmCancelSending", $object->ref), 'confirm_cancel', '', 0, 1); } // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -1657,13 +1590,11 @@ if ($action == 'create') $totalVolume = $tmparray['volume']; - if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) - { + if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) { $objectsrc = new Commande($db); $objectsrc->fetch($object->$typeobject->id); } - if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) - { + if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) { $objectsrc = new Propal($db); $objectsrc->fetch($object->$typeobject->id); } @@ -1723,8 +1654,7 @@ if ($action == 'create') print ''; // Linked documents - if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) - { + if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) { print ''; print '\n"; print ''; } - if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) - { + if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) { print ''; print ''; - if ($action != 'editdate_livraison') print ''; + if ($action != 'editdate_livraison') { + print ''; + } print '
    '; print $langs->trans("RefOrder").''; @@ -1732,8 +1662,7 @@ if ($action == 'create') print "
    '; print $langs->trans("RefProposal").''; @@ -1753,11 +1682,12 @@ if ($action == 'create') print $langs->trans('DateDeliveryPlanned'); print 'id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).'id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).'
    '; print ''; - if ($action == 'editdate_livraison') - { + if ($action == 'editdate_livraison') { print ''; print ''; print ''; @@ -1775,8 +1705,7 @@ if ($action == 'create') print $form->editfieldkey("Weight", 'trueWeight', $object->trueWeight, $object, $user->rights->expedition->creer); print ''; - if ($action == 'edittrueWeight') - { + if ($action == 'edittrueWeight') { print ''; print ''; print ''; @@ -1792,11 +1721,14 @@ if ($action == 'create') } // Calculated - if ($totalWeight > 0) - { - if (!empty($object->trueWeight)) print ' ('.$langs->trans("SumOfProductWeights").': '; + if ($totalWeight > 0) { + if (!empty($object->trueWeight)) { + print ' ('.$langs->trans("SumOfProductWeights").': '; + } print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND) ? $conf->global->MAIN_WEIGHT_DEFAULT_ROUND : -1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? $conf->global->MAIN_WEIGHT_DEFAULT_UNIT : 'no'); - if (!empty($object->trueWeight)) print ')'; + if (!empty($object->trueWeight)) { + print ')'; + } } print ''; @@ -1808,8 +1740,7 @@ if ($action == 'create') // Height print ''.$form->editfieldkey("Height", 'trueHeight', $object->trueHeight, $object, $user->rights->expedition->creer).''; - if ($action == 'edittrueHeight') - { + if ($action == 'edittrueHeight') { print ''; print ''; print ''; @@ -1839,25 +1770,27 @@ if ($action == 'create') print ''; $calculatedVolume = 0; $volumeUnit = 0; - if ($object->trueWidth && $object->trueHeight && $object->trueDepth) - { + if ($object->trueWidth && $object->trueHeight && $object->trueDepth) { $calculatedVolume = ($object->trueWidth * $object->trueHeight * $object->trueDepth); $volumeUnit = $object->size_units * 3; } // If sending volume not defined we use sum of products - if ($calculatedVolume > 0) - { - if ($volumeUnit < 50) - { + if ($calculatedVolume > 0) { + if ($volumeUnit < 50) { print showDimensionInBestUnit($calculatedVolume, $volumeUnit, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND) ? $conf->global->MAIN_VOLUME_DEFAULT_ROUND : -1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT) ? $conf->global->MAIN_VOLUME_DEFAULT_UNIT : 'no'); - } else print $calculatedVolume.' '.measuringUnitString(0, "volume", $volumeUnit); + } else { + print $calculatedVolume.' '.measuringUnitString(0, "volume", $volumeUnit); + } } - if ($totalVolume > 0) - { - if ($calculatedVolume) print ' ('.$langs->trans("SumOfProductVolumes").': '; + if ($totalVolume > 0) { + if ($calculatedVolume) { + print ' ('.$langs->trans("SumOfProductVolumes").': '; + } print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND) ? $conf->global->MAIN_VOLUME_DEFAULT_ROUND : -1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT) ? $conf->global->MAIN_VOLUME_DEFAULT_UNIT : 'no'); //if (empty($calculatedVolume)) print ' ('.$langs->trans("Calculated").')'; - if ($calculatedVolume) print ')'; + if ($calculatedVolume) { + print ')'; + } } print "\n"; print ''; @@ -1881,22 +1814,24 @@ if ($action == 'create') print $langs->trans('SendingMethod'); print ''; - if ($action != 'editshipping_method_id') print 'id.'">'.img_edit($langs->trans('SetSendingMethod'), 1).''; + if ($action != 'editshipping_method_id') { + print 'id.'">'.img_edit($langs->trans('SetSendingMethod'), 1).''; + } print ''; print ''; - if ($action == 'editshipping_method_id') - { + if ($action == 'editshipping_method_id') { print ''; print ''; print ''; $object->fetch_delivery_methods(); print $form->selectarray("shipping_method_id", $object->meths, $object->shipping_method_id, 1, 0, 0, "", 1); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print ''; print '
    '; } else { - if ($object->shipping_method_id > 0) - { + if ($object->shipping_method_id > 0) { // Get code using getLabelFromKey $code = $langs->getLabelFromKey($db, $object->shipping_method_id, 'c_shipment_mode', 'rowid', 'code'); print $langs->trans("SendingMethod".strtoupper($code)); @@ -1911,19 +1846,20 @@ if ($action == 'create') print ''; // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print ''; print '
    '; print $langs->trans('IncotermLabel'); print ''; - if ($user->rights->expedition->creer) print ''.img_edit().''; - else print ' '; + if ($user->rights->expedition->creer) { + print ''.img_edit().''; + } else { + print ' '; + } print '
    '; print ''; print ''; - if ($action != 'editincoterm') - { + if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1); } else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); @@ -1947,8 +1883,7 @@ if ($action == 'create') // Lines of products - if ($action == 'editline') - { + if ($action == 'editline') { print '
    @@ -1963,76 +1898,72 @@ if ($action == 'create') print ''; print ''; // Adds a line numbering column - if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) - { + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { print ' '; } // Product/Service print ''.$langs->trans("Products").''; // Qty print ''.$langs->trans("QtyOrdered").''; - if ($origin && $origin_id > 0) - { + if ($origin && $origin_id > 0) { print ''.$langs->trans("QtyInOtherShipments").''; } - if ($action == 'editline') - { + if ($action == 'editline') { $editColspan = 3; - if (empty($conf->stock->enabled)) $editColspan--; - if (empty($conf->productbatch->enabled)) $editColspan--; + if (empty($conf->stock->enabled)) { + $editColspan--; + } + if (empty($conf->productbatch->enabled)) { + $editColspan--; + } print ''; - if ($object->statut <= 1) - { + if ($object->statut <= 1) { print $langs->trans("QtyToShip").' - '; } else { print $langs->trans("QtyShipped").' - '; } - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print $langs->trans("WarehouseSource").' - '; } - if (!empty($conf->productbatch->enabled)) - { + if (!empty($conf->productbatch->enabled)) { print $langs->trans("Batch"); } print ''; } else { - if ($object->statut <= 1) - { + if ($object->statut <= 1) { print ''.$langs->trans("QtyToShip").''; } else { print ''.$langs->trans("QtyShipped").''; } - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print ''.$langs->trans("WarehouseSource").''; } - if (!empty($conf->productbatch->enabled)) - { + if (!empty($conf->productbatch->enabled)) { print ''.$langs->trans("Batch").''; } } print ''.$langs->trans("CalculatedWeight").''; print ''.$langs->trans("CalculatedVolume").''; //print ''.$langs->trans("Size").''; - if ($object->statut == 0) - { + if ($object->statut == 0) { print ''; print ''; } print "\n"; print ''; - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $object->fetch_thirdparty(); $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if (empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -2040,8 +1971,7 @@ if ($action == 'create') // Get list of products already sent for same source object into $alreadysent $alreadysent = array(); - if ($origin && $origin_id > 0) - { + if ($origin && $origin_id > 0) { $sql = "SELECT obj.rowid, obj.fk_product, obj.label, obj.description, obj.product_type as fk_product_type, obj.qty as qty_asked, obj.date_start, obj.date_end"; $sql .= ", ed.rowid as shipmentline_id, ed.qty as qty_shipped, ed.fk_expedition as expedition_id, ed.fk_origin_line, ed.fk_entrepot"; $sql .= ", e.rowid as shipment_id, e.ref as shipment_ref, e.date_creation, e.date_valid, e.date_delivery, e.date_expedition"; @@ -2062,16 +1992,13 @@ if ($action == 'create') dol_syslog("get list of shipment lines", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { // $obj->rowid is rowid in $origin."det" table $alreadysent[$obj->rowid][$obj->shipmentline_id] = array( 'shipment_ref'=>$obj->shipment_ref, 'shipment_id'=>$obj->shipment_id, 'warehouse'=>$obj->fk_entrepot, 'qty_shipped'=>$obj->qty_shipped, @@ -2087,33 +2014,32 @@ if ($action == 'create') print ''; // Loop on each product to send/sent - for ($i = 0; $i < $num_prod; $i++) - { + for ($i = 0; $i < $num_prod; $i++) { $parameters = array('i' => $i, 'line' => $lines[$i], 'line_id' => $line_id, 'num' => $num_prod, 'alreadysent' => $alreadysent, 'editColspan' => $editColspan, 'outputlangs' => $outputlangs); $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $object, $action); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { print ''; // id of order line print ''; // # - if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) - { + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { print ''.($i + 1).''; } // Predefined product or service - if ($lines[$i]->fk_product > 0) - { + if ($lines[$i]->fk_product > 0) { // Define output language - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $prod = new Product($db); $prod->fetch($lines[$i]->fk_product); $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $lines[$i]->product_label; - } else $label = (!empty($lines[$i]->label) ? $lines[$i]->label : $lines[$i]->product_label); + } else { + $label = (!empty($lines[$i]->label) ? $lines[$i]->label : $lines[$i]->product_label); + } print ''; @@ -2143,15 +2069,17 @@ if ($action == 'create') $description = (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($lines[$i]->description)); print $form->textwithtooltip($text, $description, 3, '', '', $i); print_date_range($lines[$i]->date_start, $lines[$i]->date_end); - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { print (!empty($lines[$i]->description) && $lines[$i]->description != $lines[$i]->product) ? '
    '.dol_htmlentitiesbr($lines[$i]->description) : ''; } print "\n"; } else { print ''; - if ($lines[$i]->product_type == Product::TYPE_SERVICE) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if ($lines[$i]->product_type == Product::TYPE_SERVICE) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($lines[$i]->label)) { $text .= ' '.$lines[$i]->label.''; @@ -2168,26 +2096,25 @@ if ($action == 'create') print ''.$lines[$i]->qty_asked.''; // Qty in other shipments (with shipment and warehouse used) - if ($origin && $origin_id > 0) - { + if ($origin && $origin_id > 0) { print ''; - foreach ($alreadysent as $key => $val) - { - if ($lines[$i]->fk_origin_line == $key) - { + foreach ($alreadysent as $key => $val) { + if ($lines[$i]->fk_origin_line == $key) { $j = 0; - foreach ($val as $shipmentline_id=> $shipmentline_var) - { - if ($shipmentline_var['shipment_id'] == $lines[$i]->fk_expedition) continue; // We want to show only "other shipments" + foreach ($val as $shipmentline_id => $shipmentline_var) { + if ($shipmentline_var['shipment_id'] == $lines[$i]->fk_expedition) { + continue; // We want to show only "other shipments" + } $j++; - if ($j > 1) print '
    '; + if ($j > 1) { + print '
    '; + } $shipment_static->fetch($shipmentline_var['shipment_id']); print $shipment_static->getNomUrl(1); print ' - '.$shipmentline_var['qty_shipped']; $htmltext = $langs->trans("DateValidation").' : '.(empty($shipmentline_var['date_valid']) ? $langs->trans("Draft") : dol_print_date($shipmentline_var['date_valid'], 'dayhour')); - if (!empty($conf->stock->enabled) && $shipmentline_var['warehouse'] > 0) - { + if (!empty($conf->stock->enabled) && $shipmentline_var['warehouse'] > 0) { $warehousestatic->fetch($shipmentline_var['warehouse']); $htmltext .= '
    '.$langs->trans("FromLocation").' : '.$warehousestatic->getNomUrl(1, '', 0, 1); } @@ -2198,22 +2125,18 @@ if ($action == 'create') print ''; } - if ($action == 'editline' && $lines[$i]->id == $line_id) - { + if ($action == 'editline' && $lines[$i]->id == $line_id) { // edit mode print ''; - if (is_array($lines[$i]->detail_batch) && count($lines[$i]->detail_batch) > 0) - { + if (is_array($lines[$i]->detail_batch) && count($lines[$i]->detail_batch) > 0) { print ''; $line = new ExpeditionLigne($db); - foreach ($lines[$i]->detail_batch as $detail_batch) - { + foreach ($lines[$i]->detail_batch as $detail_batch) { print ''; // Qty to ship or shipped - print ''; + print ''; // Batch number managment - if ($lines[$i]->entrepot_id == 0) - { + if ($lines[$i]->entrepot_id == 0) { // only show lot numbers from src warehouse when shipping from multiple warehouses $line->fetch($detail_batch->fk_expeditiondet); } @@ -2223,33 +2146,28 @@ if ($action == 'create') // add a 0 qty lot row to be able to add a lot print ''; // Qty to ship or shipped - print ''; + print ''; // Batch number managment print ''; print ''; - } elseif (!empty($conf->stock->enabled)) - { - if ($lines[$i]->fk_product > 0) - { - if ($lines[$i]->entrepot_id > 0) - { + } elseif (!empty($conf->stock->enabled)) { + if ($lines[$i]->fk_product > 0) { + if ($lines[$i]->entrepot_id > 0) { print ''; print ''; // Qty to ship or shipped - print ''; + print ''; // Warehouse source print ''; // Batch number managment print ''; print ''; - } elseif (count($lines[$i]->details_entrepot) > 1) - { + } elseif (count($lines[$i]->details_entrepot) > 1) { print ''; - foreach ($lines[$i]->details_entrepot as $detail_entrepot) - { + foreach ($lines[$i]->details_entrepot as $detail_entrepot) { print ''; // Qty to ship or shipped - print ''; + print ''; // Warehouse source print ''; // Batch number managment @@ -2264,7 +2182,7 @@ if ($action == 'create') print ''; print ''; // Qty to ship or shipped - print ''; + print ''; // Warehouse source print ''; // Batch number managment @@ -2279,21 +2197,16 @@ if ($action == 'create') print ''; // Warehouse source - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print ''; // Volume print ''; // Size //print ''; - if ($action == 'editline' && $lines[$i]->id == $line_id) - { + if ($action == 'editline' && $lines[$i]->id == $line_id) { print ''; - } elseif ($object->statut == Expedition::STATUS_DRAFT) - { + } elseif ($object->statut == Expedition::STATUS_DRAFT) { // edit-delete buttons print ''; // Display lines extrafields - if (!empty($rowExtrafieldsStart)) - { + if (!empty($rowExtrafieldsStart)) { print $rowExtrafieldsStart; print $rowExtrafieldsView; print $rowEnd; @@ -2381,15 +2293,20 @@ if ($action == 'create') // Display lines extrafields if (!empty($extrafields)) { $colspan = 6; - if ($origin && $origin_id > 0) $colspan++; - if (!empty($conf->productbatch->enabled)) $colspan++; - if (!empty($conf->stock->enabled)) $colspan++; + if ($origin && $origin_id > 0) { + $colspan++; + } + if (!empty($conf->productbatch->enabled)) { + $colspan++; + } + if (!empty($conf->stock->enabled)) { + $colspan++; + } $line = $lines[$i]; $line->fetch_optionals(); - if ($action == 'editline' && $line->id == $line_id) - { + if ($action == 'editline' && $line->id == $line_id) { print $lines[$i]->showOptionals($extrafields, 'edit', array('colspan'=>$colspan), $indiceAsked); } else { print $lines[$i]->showOptionals($extrafields, 'view', array('colspan'=>$colspan), $indiceAsked); @@ -2416,20 +2333,16 @@ if ($action == 'create') * Boutons actions */ - if (($user->socid == 0) && ($action != 'presend')) - { + if (($user->socid == 0) && ($action != 'presend')) { print '
    '; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { - if ($object->statut == Expedition::STATUS_DRAFT && $num_prod > 0) - { + if (empty($reshook)) { + if ($object->statut == Expedition::STATUS_DRAFT && $num_prod > 0) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->shipping_advance->validate))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->shipping_advance->validate))) { print ''.$langs->trans("Validate").''; } else { print ''.$langs->trans("Validate").''; @@ -2438,10 +2351,8 @@ if ($action == 'create') // TODO add alternative status // 0=draft, 1=validated, 2=billed, we miss a status "delivered" (only available on order) - if ($object->statut == Expedition::STATUS_CLOSED && $user->rights->expedition->creer) - { - if (!empty($conf->facture->enabled) && !empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) // Quand l'option est on, il faut avoir le bouton en plus et non en remplacement du Close ? - { + if ($object->statut == Expedition::STATUS_CLOSED && $user->rights->expedition->creer) { + if (!empty($conf->facture->enabled) && !empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) { // Quand l'option est on, il faut avoir le bouton en plus et non en remplacement du Close ? print ''.$langs->trans("ClassifyUnbilled").''; } else { print ''.$langs->trans("ReOpen").''; @@ -2450,20 +2361,18 @@ if ($action == 'create') // Send if (empty($user->socid)) { - if ($object->statut > 0) - { - if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->expedition->shipping_advance->send) - { + if ($object->statut > 0) { + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->expedition->shipping_advance->send) { print ''.$langs->trans('SendMail').''; - } else print ''.$langs->trans('SendMail').''; + } else { + print ''.$langs->trans('SendMail').''; + } } } // Create bill - if (!empty($conf->facture->enabled) && ($object->statut == Expedition::STATUS_VALIDATED || $object->statut == Expedition::STATUS_CLOSED)) - { - if ($user->rights->facture->creer) - { + if (!empty($conf->facture->enabled) && ($object->statut == Expedition::STATUS_VALIDATED || $object->statut == Expedition::STATUS_CLOSED)) { + if ($user->rights->facture->creer) { // TODO show button only if (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) // If we do that, we must also make this option official. print ''.$langs->trans("CreateBill").''; @@ -2472,19 +2381,15 @@ if ($action == 'create') // This is just to generate a delivery receipt //var_dump($object->linkedObjectsIds['delivery']); - if ($conf->delivery_note->enabled && ($object->statut == Expedition::STATUS_VALIDATED || $object->statut == Expedition::STATUS_CLOSED) && $user->rights->expedition->delivery->creer && empty($object->linkedObjectsIds['delivery'])) - { + if ($conf->delivery_note->enabled && ($object->statut == Expedition::STATUS_VALIDATED || $object->statut == Expedition::STATUS_CLOSED) && $user->rights->expedition->delivery->creer && empty($object->linkedObjectsIds['delivery'])) { print ''.$langs->trans("CreateDeliveryOrder").''; } // Close - if ($object->statut == Expedition::STATUS_VALIDATED) - { - if ($user->rights->expedition->creer && $object->statut > 0 && !$object->billed) - { + if ($object->statut == Expedition::STATUS_VALIDATED) { + if ($user->rights->expedition->creer && $object->statut > 0 && !$object->billed) { $label = "Close"; $paramaction = 'classifyclosed'; // = Transferred/Received // Label here should be "Close" or "ClassifyBilled" if we decided to make bill on shipments instead of orders - if (!empty($conf->facture->enabled) && !empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) // Quand l'option est on, il faut avoir le bouton en plus et non en remplacement du Close ? - { + if (!empty($conf->facture->enabled) && !empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) { // Quand l'option est on, il faut avoir le bouton en plus et non en remplacement du Close ? $label = "ClassifyBilled"; $paramaction = 'classifybilled'; } @@ -2493,17 +2398,14 @@ if ($action == 'create') } // Cancel - if ($object->statut == Expedition::STATUS_VALIDATED) - { - if ($user->rights->expedition->supprimer) - { + if ($object->statut == Expedition::STATUS_VALIDATED) { + if ($user->rights->expedition->supprimer) { print ''.$langs->trans("Cancel").''; } } // Delete - if ($user->rights->expedition->supprimer) - { + if ($user->rights->expedition->supprimer) { print ''.$langs->trans("Delete").''; } } @@ -2516,8 +2418,7 @@ if ($action == 'create') * Documents generated */ - if ($action != 'presend' && $action != 'editline') - { + if ($action != 'presend' && $action != 'editline') { print '
    '; $objectref = dol_sanitizeFileName($object->ref); diff --git a/htdocs/expedition/class/api_shipments.class.php b/htdocs/expedition/class/api_shipments.class.php index 22acaeaa26b..42564f7dd72 100644 --- a/htdocs/expedition/class/api_shipments.class.php +++ b/htdocs/expedition/class/api_shipments.class.php @@ -32,7 +32,7 @@ class Shipments extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'socid', 'origin_id', 'origin_type', @@ -110,28 +110,37 @@ class Shipments extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."expedition as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= ' WHERE t.entity IN ('.getEntity('expedition').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -140,8 +149,7 @@ class Shipments extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -152,13 +160,11 @@ class Shipments extends DolibarrApi dol_syslog("API Rest request"); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $shipment_static = new Expedition($this->db); if ($shipment_static->fetch($obj->rowid)) { @@ -217,28 +223,28 @@ class Shipments extends DolibarrApi // * @return int // */ /* - public function getLines($id) - { - if(! DolibarrApiAccess::$user->rights->expedition->lire) { - throw new RestException(401); - } + public function getLines($id) + { + if(! DolibarrApiAccess::$user->rights->expedition->lire) { + throw new RestException(401); + } - $result = $this->shipment->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Shipment not found'); - } + $result = $this->shipment->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Shipment not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expedition',$this->shipment->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->shipment->getLinesArray(); - $result = array(); - foreach ($this->shipment->lines as $line) { - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } - */ + if( ! DolibarrApi::_checkAccessToResource('expedition',$this->shipment->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->shipment->getLinesArray(); + $result = array(); + foreach ($this->shipment->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + */ // /** // * Add a line to given shipment @@ -251,56 +257,56 @@ class Shipments extends DolibarrApi // * @return int // */ /* - public function postLine($id, $request_data = null) - { - if(! DolibarrApiAccess::$user->rights->expedition->creer) { - throw new RestException(401); - } + public function postLine($id, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->expedition->creer) { + throw new RestException(401); + } - $result = $this->shipment->fetch($id); - if ( ! $result ) { - throw new RestException(404, 'Shipment not found'); - } + $result = $this->shipment->fetch($id); + if ( ! $result ) { + throw new RestException(404, 'Shipment not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expedition',$this->shipment->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->shipment->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - $request_data->info_bits, - $request_data->fk_remise_except, - 'HT', - 0, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->array_options, - $request_data->fk_unit, - $request_data->origin, - $request_data->origin_id, - $request_data->multicurrency_subprice - ); + if( ! DolibarrApi::_checkAccessToResource('expedition',$this->shipment->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->shipment->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + $request_data->info_bits, + $request_data->fk_remise_except, + 'HT', + 0, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->array_options, + $request_data->fk_unit, + $request_data->origin, + $request_data->origin_id, + $request_data->multicurrency_subprice + ); - if ($updateRes > 0) { - return $updateRes; + if ($updateRes > 0) { + return $updateRes; - } - return false; - }*/ + } + return false; + }*/ // /** // * Update a line to given shipment @@ -314,53 +320,53 @@ class Shipments extends DolibarrApi // * @return object // */ /* - public function putLine($id, $lineid, $request_data = null) - { - if (! DolibarrApiAccess::$user->rights->expedition->creer) { - throw new RestException(401); - } + public function putLine($id, $lineid, $request_data = null) + { + if (! DolibarrApiAccess::$user->rights->expedition->creer) { + throw new RestException(401); + } - $result = $this->shipment->fetch($id); - if ( ! $result ) { - throw new RestException(404, 'Shipment not found'); - } + $result = $this->shipment->fetch($id); + if ( ! $result ) { + throw new RestException(404, 'Shipment not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expedition',$this->shipment->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->shipment->updateline( - $lineid, - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->remise_percent, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - 'HT', - $request_data->info_bits, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->fk_parent_line, - 0, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->special_code, - $request_data->array_options, - $request_data->fk_unit, - $request_data->multicurrency_subprice - ); + if( ! DolibarrApi::_checkAccessToResource('expedition',$this->shipment->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->shipment->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + 'HT', + $request_data->info_bits, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->fk_parent_line, + 0, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->special_code, + $request_data->array_options, + $request_data->fk_unit, + $request_data->multicurrency_subprice + ); - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } - return false; - }*/ + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; + }*/ /** * Delete a line to given shipment @@ -425,12 +431,13 @@ class Shipments extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->shipment->$field = $value; } - if ($this->shipment->update(DolibarrApiAccess::$user) > 0) - { + if ($this->shipment->update(DolibarrApiAccess::$user) > 0) { return $this->get($id); } else { throw new RestException(500, $this->shipment->error); @@ -539,27 +546,27 @@ class Shipments extends DolibarrApi // * @throws RestException 405 // */ /* - public function setinvoiced($id) - { + public function setinvoiced($id) + { - if(! DolibarrApiAccess::$user->rights->expedition->creer) { - throw new RestException(401); - } - if(empty($id)) { - throw new RestException(400, 'Shipment ID is mandatory'); - } - $result = $this->shipment->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Shipment not found'); - } + if(! DolibarrApiAccess::$user->rights->expedition->creer) { + throw new RestException(401); + } + if(empty($id)) { + throw new RestException(400, 'Shipment ID is mandatory'); + } + $result = $this->shipment->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Shipment not found'); + } - $result = $this->shipment->classifyBilled(DolibarrApiAccess::$user); - if( $result < 0) { - throw new RestException(400, $this->shipment->error); - } - return $result; - } - */ + $result = $this->shipment->classifyBilled(DolibarrApiAccess::$user); + if( $result < 0) { + throw new RestException(400, $this->shipment->error); + } + return $result; + } + */ // /** @@ -576,35 +583,35 @@ class Shipments extends DolibarrApi // * @throws RestException 405 // */ /* - public function createShipmentFromOrder($orderid) - { + public function createShipmentFromOrder($orderid) + { - require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php'; + require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php'; - if(! DolibarrApiAccess::$user->rights->expedition->lire) { - throw new RestException(401); - } - if(! DolibarrApiAccess::$user->rights->expedition->creer) { - throw new RestException(401); - } - if(empty($proposalid)) { - throw new RestException(400, 'Order ID is mandatory'); - } + if(! DolibarrApiAccess::$user->rights->expedition->lire) { + throw new RestException(401); + } + if(! DolibarrApiAccess::$user->rights->expedition->creer) { + throw new RestException(401); + } + if(empty($proposalid)) { + throw new RestException(400, 'Order ID is mandatory'); + } - $order = new Commande($this->db); - $result = $order->fetch($proposalid); - if( ! $result ) { - throw new RestException(404, 'Order not found'); - } + $order = new Commande($this->db); + $result = $order->fetch($proposalid); + if( ! $result ) { + throw new RestException(404, 'Order not found'); + } - $result = $this->shipment->createFromOrder($order, DolibarrApiAccess::$user); - if( $result < 0) { - throw new RestException(405, $this->shipment->error); - } - $this->shipment->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->shipment); - } - */ + $result = $this->shipment->createFromOrder($order, DolibarrApiAccess::$user); + if( $result < 0) { + throw new RestException(405, $this->shipment->error); + } + $this->shipment->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->shipment); + } + */ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore /** @@ -627,10 +634,8 @@ class Shipments extends DolibarrApi unset($object->barcode_type_label); unset($object->barcode_type_coder); - if (!empty($object->lines) && is_array($object->lines)) - { - foreach ($object->lines as $line) - { + if (!empty($object->lines) && is_array($object->lines)) { + foreach ($object->lines as $line) { unset($line->tva_tx); unset($line->vat_src_code); unset($line->total_ht); @@ -656,8 +661,9 @@ class Shipments extends DolibarrApi { $shipment = array(); foreach (Shipments::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $shipment[$field] = $data[$field]; } return $shipment; diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php index df2e3f347e0..c251fdaf7cd 100644 --- a/htdocs/expedition/class/expedition.class.php +++ b/htdocs/expedition/class/expedition.class.php @@ -37,9 +37,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php"; require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php'; -if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; -if (!empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; -if (!empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php'; +if (!empty($conf->propal->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +} +if (!empty($conf->commande->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +} +if (!empty($conf->productbatch->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php'; +} /** @@ -231,8 +237,7 @@ class Expedition extends CommonObject global $langs, $conf; $langs->load("sendings"); - if (!empty($conf->global->EXPEDITION_ADDON_NUMBER)) - { + if (!empty($conf->global->EXPEDITION_ADDON_NUMBER)) { $mybool = false; $file = $conf->global->EXPEDITION_ADDON_NUMBER.".php"; @@ -248,8 +253,7 @@ class Expedition extends CommonObject $mybool |= @include_once $dir.$file; } - if (!$mybool) - { + if (!$mybool) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -258,8 +262,7 @@ class Expedition extends CommonObject $numref = ""; $numref = $obj->getNextValue($soc, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { dol_print_error($this->db, get_class($this)."::getNextNumRef ".$obj->error); @@ -290,7 +293,9 @@ class Expedition extends CommonObject // Clean parameters $this->brouillon = 1; $this->tracking_number = dol_sanitizeFileName($this->tracking_number); - if (empty($this->fk_project)) $this->fk_project = 0; + if (empty($this->fk_project)) { + $this->fk_project = 0; + } $this->user = $user; @@ -353,8 +358,7 @@ class Expedition extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."expedition"); $sql = "UPDATE ".MAIN_DB_PREFIX."expedition"; @@ -362,59 +366,49 @@ class Expedition extends CommonObject $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::create", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { // Insert of lines $num = count($this->lines); - for ($i = 0; $i < $num; $i++) - { - if (!isset($this->lines[$i]->detail_batch)) - { // no batch management - if (!$this->create_line($this->lines[$i]->entrepot_id, $this->lines[$i]->origin_line_id, $this->lines[$i]->qty, $this->lines[$i]->rang, $this->lines[$i]->array_options) > 0) - { + for ($i = 0; $i < $num; $i++) { + if (!isset($this->lines[$i]->detail_batch)) { // no batch management + if (!$this->create_line($this->lines[$i]->entrepot_id, $this->lines[$i]->origin_line_id, $this->lines[$i]->qty, $this->lines[$i]->rang, $this->lines[$i]->array_options) > 0) { $error++; } } else { // with batch management - if (!$this->create_line_batch($this->lines[$i], $this->lines[$i]->array_options) > 0) - { + if (!$this->create_line_batch($this->lines[$i], $this->lines[$i]->array_options) > 0) { $error++; } } } - if (!$error && $this->id && $this->origin_id) - { + if (!$error && $this->id && $this->origin_id) { $ret = $this->add_object_linked(); - if (!$ret) - { + if (!$ret) { $error++; } } // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('SHIPPING_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -465,8 +459,7 @@ class Expedition extends CommonObject $expeditionline->rang = $rang; $expeditionline->array_options = $array_options; - if (($lineId = $expeditionline->insert($user)) < 0) - { + if (($lineId = $expeditionline->insert($user)) < 0) { $this->errors[] = $expeditionline->error; } return $lineId; @@ -489,26 +482,21 @@ class Expedition extends CommonObject $tab = $line_ext->detail_batch; // create stockLocation Qty array - foreach ($tab as $detbatch) - { - if ($detbatch->entrepot_id) - { + foreach ($tab as $detbatch) { + if ($detbatch->entrepot_id) { $stockLocationQty[$detbatch->entrepot_id] += $detbatch->qty; } } // create shipment lines - foreach ($stockLocationQty as $stockLocation => $qty) - { + foreach ($stockLocationQty as $stockLocation => $qty) { $line_id = $this->create_line($stockLocation, $line_ext->origin_line_id, $qty, $line_ext->rang, $array_options); if ($line_id < 0) { $error++; } else { // create shipment batch lines for stockLocation - foreach ($tab as $detbatch) - { + foreach ($tab as $detbatch) { if ($detbatch->entrepot_id == $stockLocation) { - if (!($detbatch->create($line_id) > 0)) // Create an expeditionlinebatch - { + if (!($detbatch->create($line_id) > 0)) { // Create an expeditionlinebatch $error++; } } @@ -516,8 +504,11 @@ class Expedition extends CommonObject } } - if (!$error) return 1; - else return -1; + if (!$error) { + return 1; + } else { + return -1; + } } /** @@ -534,7 +525,9 @@ class Expedition extends CommonObject global $conf; // Check parameters - if (empty($id) && empty($ref) && empty($ref_ext)) return -1; + if (empty($id) && empty($ref) && empty($ref_ext)) { + return -1; + } $sql = "SELECT e.rowid, e.entity, e.ref, e.fk_soc as socid, e.date_creation, e.ref_customer, e.ref_ext, e.ref_int, e.fk_user_author, e.fk_statut, e.fk_projet as fk_project, e.billed"; $sql .= ", e.date_valid"; @@ -551,17 +544,23 @@ class Expedition extends CommonObject $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON e.fk_incoterms = i.rowid'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_shipment_mode as s ON e.fk_shipping_method = s.rowid'; $sql .= " WHERE e.entity IN (".getEntity('expedition').")"; - if ($id) $sql .= " AND e.rowid=".$id; - if ($ref) $sql .= " AND e.ref='".$this->db->escape($ref)."'"; - if ($ref_ext) $sql .= " AND e.ref_ext='".$this->db->escape($ref_ext)."'"; - if ($notused) $sql .= " AND e.ref_int='".$this->db->escape($notused)."'"; + if ($id) { + $sql .= " AND e.rowid=".$id; + } + if ($ref) { + $sql .= " AND e.ref='".$this->db->escape($ref)."'"; + } + if ($ref_ext) { + $sql .= " AND e.ref_ext='".$this->db->escape($ref_ext)."'"; + } + if ($notused) { + $sql .= " AND e.ref_int='".$this->db->escape($notused)."'"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -614,7 +613,9 @@ class Expedition extends CommonObject $this->db->free($result); - if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; + if ($this->statut == self::STATUS_DRAFT) { + $this->brouillon = 1; + } // Tracking url $this->getUrlTrackingStatus($obj->tracking_number); @@ -626,18 +627,20 @@ class Expedition extends CommonObject $this->fetch_optionals(); // Fix Get multicurrency param for transmited - if (!empty($conf->multicurrency->enabled)) - { - if (!empty($this->multicurrency_code)) $this->multicurrency_code = $this->thirdparty->multicurrency_code; - if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($this->thirdparty->multicurrency_tx)) $this->multicurrency_tx = $this->thirdparty->multicurrency_tx; + if (!empty($conf->multicurrency->enabled)) { + if (!empty($this->multicurrency_code)) { + $this->multicurrency_code = $this->thirdparty->multicurrency_code; + } + if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($this->thirdparty->multicurrency_tx)) { + $this->multicurrency_tx = $this->thirdparty->multicurrency_tx; + } } /* * Lines */ $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { return -3; } @@ -669,15 +672,13 @@ class Expedition extends CommonObject dol_syslog(get_class($this)."::valid"); // Protection - if ($this->statut) - { + if ($this->statut) { dol_syslog(get_class($this)."::valid not in draft status", LOG_WARNING); return 0; } if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->shipping_advance->validate)))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->shipping_advance->validate)))) { $this->error = 'Permission denied'; dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); return -1; @@ -695,8 +696,7 @@ class Expedition extends CommonObject $result = $soc->set_as_client(); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $numref = $this->getNextNumRef($soc); } else { $numref = "EXP".$this->id; @@ -715,15 +715,13 @@ class Expedition extends CommonObject dol_syslog(get_class($this)."::valid update expedition", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->lasterror(); $error++; } // If stock increment is done on sending (recommanded choice) - if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) - { + if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); @@ -740,27 +738,25 @@ class Expedition extends CommonObject dol_syslog(get_class($this)."::valid select details", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $cpt = $this->db->num_rows($resql); - for ($i = 0; $i < $cpt; $i++) - { + for ($i = 0; $i < $cpt; $i++) { $obj = $this->db->fetch_object($resql); - if (empty($obj->edbrowid)) - { + if (empty($obj->edbrowid)) { $qty = $obj->qty; } else { $qty = $obj->edbqty; } - if ($qty <= 0) continue; + if ($qty <= 0) { + continue; + } dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid); //var_dump($this->lines[$i]); $mouvS = new MouvementStock($this->db); $mouvS->origin = dol_clone($this, 1); - if (empty($obj->edbrowid)) - { + if (empty($obj->edbrowid)) { // line without batch detail // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record. @@ -795,48 +791,45 @@ class Expedition extends CommonObject // Change status of order to "shipment in process" $ret = $this->setStatut(Commande::STATUS_SHIPMENTONPROCESS, $this->origin_id, $this->origin); - if (!$ret) - { + if (!$ret) { $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('SHIPPING_VALIDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expedition/sending/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expedition/sending/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($numref); $dirsource = $conf->expedition->dir_output.'/sending/'.$oldref; $dirdest = $conf->expedition->dir_output.'/sending/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->expedition->dir_output.'/sending/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -849,14 +842,12 @@ class Expedition extends CommonObject } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $numref; $this->statut = self::STATUS_VALIDATED; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -878,23 +869,24 @@ class Expedition extends CommonObject // phpcs:enable global $conf; - if ($conf->delivery_note->enabled) - { - if ($this->statut == self::STATUS_VALIDATED || $this->statut == self::STATUS_CLOSED) - { + if ($conf->delivery_note->enabled) { + if ($this->statut == self::STATUS_VALIDATED || $this->statut == self::STATUS_CLOSED) { // Expedition validee include_once DOL_DOCUMENT_ROOT.'/delivery/class/delivery.class.php'; $delivery = new Delivery($this->db); $result = $delivery->create_from_sending($user, $this->id); - if ($result > 0) - { + if ($result > 0) { return $result; } else { $this->error = $delivery->error; return $result; } - } else return 0; - } else return 0; + } else { + return 0; + } + } else { + return 0; + } } /** @@ -926,8 +918,7 @@ class Expedition extends CommonObject // Copy the rang of the order line to the expedition line $line->rang = $orderline->rang; - if (!empty($conf->stock->enabled) && !empty($orderline->fk_product)) - { + if (!empty($conf->stock->enabled) && !empty($orderline->fk_product)) { $fk_product = $orderline->fk_product; if (!($entrepot_id > 0) && empty($conf->global->STOCK_WAREHOUSE_NOT_REQUIRED_FOR_SHIPMENTS)) { @@ -967,15 +958,15 @@ class Expedition extends CommonObject } // If product need a batch number, we should not have called this function but addline_batch instead. - if (!empty($conf->productbatch->enabled) && !empty($orderline->fk_product) && !empty($orderline->product_tobatch)) - { + if (!empty($conf->productbatch->enabled) && !empty($orderline->fk_product) && !empty($orderline->product_tobatch)) { $this->error = 'ADDLINE_WAS_CALLED_INSTEAD_OF_ADDLINEBATCH'; return -4; } // extrafields - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) // For avoid conflicts if trigger used + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used $line->array_options = $array_options; + } $this->lines[$num] = $line; } @@ -994,36 +985,30 @@ class Expedition extends CommonObject global $conf, $langs; $num = count($this->lines); - if ($dbatch['qty'] > 0) - { + if ($dbatch['qty'] > 0) { $line = new ExpeditionLigne($this->db); $tab = array(); - foreach ($dbatch['detail'] as $key=>$value) - { - if ($value['q'] > 0) - { + foreach ($dbatch['detail'] as $key => $value) { + if ($value['q'] > 0) { // $value['q']=qty to move // $value['id_batch']=id into llx_product_batch of record to move //var_dump($value); $linebatch = new ExpeditionLineBatch($this->db); $ret = $linebatch->fetchFromStock($value['id_batch']); // load serial, sellby, eatby - if ($ret < 0) - { + if ($ret < 0) { $this->error = $linebatch->error; return -1; } $linebatch->qty = $value['q']; $tab[] = $linebatch; - if ($conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT) - { + if ($conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT) { require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; $prod_batch = new Productbatch($this->db); $prod_batch->fetch($value['id_batch']); - if ($prod_batch->qty < $linebatch->qty) - { + if ($prod_batch->qty < $linebatch->qty) { $langs->load("errors"); $this->errors[] = $langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $prod_batch->fk_product); dol_syslog(get_class($this)."::addline_batch error=Product ".$prod_batch->batch.": ".$this->errorsToString(), LOG_ERR); @@ -1042,8 +1027,9 @@ class Expedition extends CommonObject $line->detail_batch = $tab; // extrafields - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) // For avoid conflicts if trigger used + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used $line->array_options = $array_options; + } //var_dump($line); $this->lines[$num] = $line; @@ -1065,25 +1051,63 @@ class Expedition extends CommonObject // Clean parameters - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->entity)) $this->entity = (int) $this->entity; - if (isset($this->ref_customer)) $this->ref_customer = trim($this->ref_customer); - if (isset($this->socid)) $this->socid = (int) $this->socid; - if (isset($this->fk_user_author)) $this->fk_user_author = (int) $this->fk_user_author; - if (isset($this->fk_user_valid)) $this->fk_user_valid = (int) $this->fk_user_valid; - if (isset($this->fk_delivery_address)) $this->fk_delivery_address = (int) $this->fk_delivery_address; - if (isset($this->shipping_method_id)) $this->shipping_method_id = (int) $this->shipping_method_id; - if (isset($this->tracking_number)) $this->tracking_number = trim($this->tracking_number); - if (isset($this->statut)) $this->statut = (int) $this->statut; - if (isset($this->trueDepth)) $this->trueDepth = trim($this->trueDepth); - if (isset($this->trueWidth)) $this->trueWidth = trim($this->trueWidth); - if (isset($this->trueHeight)) $this->trueHeight = trim($this->trueHeight); - if (isset($this->size_units)) $this->size_units = trim($this->size_units); - if (isset($this->weight_units)) $this->weight_units = trim($this->weight_units); - if (isset($this->trueWeight)) $this->weight = trim($this->trueWeight); - if (isset($this->note_private)) $this->note_private = trim($this->note_private); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf); + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->entity)) { + $this->entity = (int) $this->entity; + } + if (isset($this->ref_customer)) { + $this->ref_customer = trim($this->ref_customer); + } + if (isset($this->socid)) { + $this->socid = (int) $this->socid; + } + if (isset($this->fk_user_author)) { + $this->fk_user_author = (int) $this->fk_user_author; + } + if (isset($this->fk_user_valid)) { + $this->fk_user_valid = (int) $this->fk_user_valid; + } + if (isset($this->fk_delivery_address)) { + $this->fk_delivery_address = (int) $this->fk_delivery_address; + } + if (isset($this->shipping_method_id)) { + $this->shipping_method_id = (int) $this->shipping_method_id; + } + if (isset($this->tracking_number)) { + $this->tracking_number = trim($this->tracking_number); + } + if (isset($this->statut)) { + $this->statut = (int) $this->statut; + } + if (isset($this->trueDepth)) { + $this->trueDepth = trim($this->trueDepth); + } + if (isset($this->trueWidth)) { + $this->trueWidth = trim($this->trueWidth); + } + if (isset($this->trueHeight)) { + $this->trueHeight = trim($this->trueHeight); + } + if (isset($this->size_units)) { + $this->size_units = trim($this->size_units); + } + if (isset($this->weight_units)) { + $this->weight_units = trim($this->weight_units); + } + if (isset($this->trueWeight)) { + $this->weight = trim($this->trueWeight); + } + if (isset($this->note_private)) { + $this->note_private = trim($this->note_private); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->model_pdf)) { + $this->model_pdf = trim($this->model_pdf); + } @@ -1119,26 +1143,28 @@ class Expedition extends CommonObject $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").","; $sql .= " entity=".$conf->entity; - $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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('SHIPPING_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -1180,15 +1206,16 @@ class Expedition extends CommonObject if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('SHIPPING_CANCEL', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } // Stock control if (!$error && $conf->stock->enabled && (($conf->global->STOCK_CALCULATE_ON_SHIPMENT && $this->statut > self::STATUS_DRAFT) || - ($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE && $this->statut == self::STATUS_CLOSED && $also_update_stock))) - { + ($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE && $this->statut == self::STATUS_CLOSED && $also_update_stock))) { require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php"; $langs->load("agenda"); @@ -1202,11 +1229,9 @@ class Expedition extends CommonObject dol_syslog(get_class($this)."::delete select details", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $cpt = $this->db->num_rows($resql); - for ($i = 0; $i < $cpt; $i++) - { + for ($i = 0; $i < $cpt; $i++) { dol_syslog(get_class($this)."::delete movement index ".$i); $obj = $this->db->fetch_object($resql); @@ -1215,11 +1240,9 @@ class Expedition extends CommonObject $mouvS->origin = null; // get lot/serial $lotArray = null; - if ($conf->productbatch->enabled) - { + if ($conf->productbatch->enabled) { $lotArray = ExpeditionLineBatch::fetchAll($this->db, $obj->expeditiondet_id); - if (!is_array($lotArray)) - { + if (!is_array($lotArray)) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } } @@ -1228,24 +1251,23 @@ class Expedition extends CommonObject // We increment stock of product (and sub-products) // We use warehouse selected for each line $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, 0, $langs->trans("ShipmentCanceledInDolibarr", $this->ref)); // Price is set to 0, because we don't want to see WAP changed - if ($result < 0) - { + if ($result < 0) { $error++; $this->errors = $this->errors + $mouvS->errors; break; } } else { // We increment stock of batches // We use warehouse selected for each line - foreach ($lotArray as $lot) - { + foreach ($lotArray as $lot) { $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $lot->qty, 0, $langs->trans("ShipmentCanceledInDolibarr", $this->ref), $lot->eatby, $lot->sellby, $lot->batch); // Price is set to 0, because we don't want to see WAP changed - if ($result < 0) - { + if ($result < 0) { $error++; $this->errors = $this->errors + $mouvS->errors; break; } } - if ($error) break; // break for loop incase of error + if ($error) { + break; // break for loop incase of error + } } } } else { @@ -1254,71 +1276,58 @@ class Expedition extends CommonObject } // delete batch expedition line - if (!$error && $conf->productbatch->enabled) - { - if (ExpeditionLineBatch::deletefromexp($this->db, $this->id) < 0) - { + if (!$error && $conf->productbatch->enabled) { + if (ExpeditionLineBatch::deletefromexp($this->db, $this->id) < 0) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet"; $sql .= " WHERE fk_expedition = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } // No delete expedition - if (!$error) - { + if (!$error) { $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."expedition"; $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { - if (!empty($this->origin) && $this->origin_id > 0) - { + if ($this->db->query($sql)) { + if (!empty($this->origin) && $this->origin_id > 0) { $this->fetch_origin(); $origin = $this->origin; - if ($this->$origin->statut == Commande::STATUS_SHIPMENTONPROCESS) // If order source of shipment is "shipment in progress" - { + if ($this->$origin->statut == Commande::STATUS_SHIPMENTONPROCESS) { // If order source of shipment is "shipment in progress" // Check if there is no more shipment. If not, we can move back status of order to "validated" instead of "shipment in progress" $this->$origin->loadExpeditions(); //var_dump($this->$origin->expeditions);exit; - if (count($this->$origin->expeditions) <= 0) - { + if (count($this->$origin->expeditions) <= 0) { $this->$origin->setStatut(Commande::STATUS_VALIDATED); } } } - if (!$error) - { + if (!$error) { $this->db->commit(); // We delete PDFs $ref = dol_sanitizeFileName($this->ref); - if (!empty($conf->expedition->dir_output)) - { + if (!empty($conf->expedition->dir_output)) { $dir = $conf->expedition->dir_output.'/sending/'.$ref; $file = $dir.'/'.$ref.'.pdf'; - if (file_exists($file)) - { - if (!dol_delete_file($file)) - { + if (file_exists($file)) { + if (!dol_delete_file($file)) { return 0; } } - if (file_exists($dir)) - { - if (!dol_delete_dir_recursive($dir)) - { + if (file_exists($dir)) { + if (!dol_delete_dir_recursive($dir)) { $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir); return 0; } @@ -1373,8 +1382,7 @@ class Expedition extends CommonObject // Add a protection to refuse deleting if shipment has at least one delivery $this->fetchObjectLinked($this->id, 'shipping', 0, 'delivery'); // Get deliveries linked to this shipment - if (count($this->linkedObjectsIds) > 0) - { + if (count($this->linkedObjectsIds) > 0) { $this->error = 'ErrorThereIsSomeDeliveries'; $error++; } @@ -1382,15 +1390,16 @@ class Expedition extends CommonObject if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('SHIPPING_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } // Stock control if (!$error && $conf->stock->enabled && (($conf->global->STOCK_CALCULATE_ON_SHIPMENT && $this->statut > self::STATUS_DRAFT) || - ($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE && $this->statut == self::STATUS_CLOSED && $also_update_stock))) - { + ($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE && $this->statut == self::STATUS_CLOSED && $also_update_stock))) { require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php"; $langs->load("agenda"); @@ -1404,11 +1413,9 @@ class Expedition extends CommonObject dol_syslog(get_class($this)."::delete select details", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $cpt = $this->db->num_rows($resql); - for ($i = 0; $i < $cpt; $i++) - { + for ($i = 0; $i < $cpt; $i++) { dol_syslog(get_class($this)."::delete movement index ".$i); $obj = $this->db->fetch_object($resql); @@ -1417,11 +1424,9 @@ class Expedition extends CommonObject $mouvS->origin = null; // get lot/serial $lotArray = null; - if ($conf->productbatch->enabled) - { + if ($conf->productbatch->enabled) { $lotArray = ExpeditionLineBatch::fetchAll($this->db, $obj->expeditiondet_id); - if (!is_array($lotArray)) - { + if (!is_array($lotArray)) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } } @@ -1430,24 +1435,23 @@ class Expedition extends CommonObject // We increment stock of product (and sub-products) // We use warehouse selected for each line $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, 0, $langs->trans("ShipmentDeletedInDolibarr", $this->ref)); // Price is set to 0, because we don't want to see WAP changed - if ($result < 0) - { + if ($result < 0) { $error++; $this->errors = $this->errors + $mouvS->errors; break; } } else { // We increment stock of batches // We use warehouse selected for each line - foreach ($lotArray as $lot) - { + foreach ($lotArray as $lot) { $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $lot->qty, 0, $langs->trans("ShipmentDeletedInDolibarr", $this->ref), $lot->eatby, $lot->sellby, $lot->batch); // Price is set to 0, because we don't want to see WAP changed - if ($result < 0) - { + if ($result < 0) { $error++; $this->errors = $this->errors + $mouvS->errors; break; } } - if ($error) break; // break for loop incase of error + if ($error) { + break; // break for loop incase of error + } } } } else { @@ -1456,16 +1460,13 @@ class Expedition extends CommonObject } // delete batch expedition line - if (!$error && $conf->productbatch->enabled) - { - if (ExpeditionLineBatch::deletefromexp($this->db, $this->id) < 0) - { + if (!$error && $conf->productbatch->enabled) { + if (ExpeditionLineBatch::deletefromexp($this->db, $this->id) < 0) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } } - if (!$error) - { + if (!$error) { $main = MAIN_DB_PREFIX.'expeditiondet'; $ef = $main."_extrafields"; $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_expedition = ".$this->id.")"; @@ -1473,41 +1474,38 @@ class Expedition extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet"; $sql .= " WHERE fk_expedition = ".$this->id; - if ($this->db->query($sqlef) && $this->db->query($sql)) - { + if ($this->db->query($sqlef) && $this->db->query($sql)) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } // delete extrafields $res = $this->deleteExtraFields(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."expedition"; $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { - if (!empty($this->origin) && $this->origin_id > 0) - { + if ($this->db->query($sql)) { + if (!empty($this->origin) && $this->origin_id > 0) { $this->fetch_origin(); $origin = $this->origin; - if ($this->$origin->statut == Commande::STATUS_SHIPMENTONPROCESS) // If order source of shipment is "shipment in progress" - { + if ($this->$origin->statut == Commande::STATUS_SHIPMENTONPROCESS) { // If order source of shipment is "shipment in progress" // Check if there is no more shipment. If not, we can move back status of order to "validated" instead of "shipment in progress" $this->$origin->loadExpeditions(); //var_dump($this->$origin->expeditions);exit; - if (count($this->$origin->expeditions) <= 0) - { + if (count($this->$origin->expeditions) <= 0) { $this->$origin->setStatut(Commande::STATUS_VALIDATED); } } } - if (!$error) - { + if (!$error) { $this->db->commit(); // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive @@ -1515,21 +1513,16 @@ class Expedition extends CommonObject // We delete PDFs $ref = dol_sanitizeFileName($this->ref); - if (!empty($conf->expedition->dir_output)) - { + if (!empty($conf->expedition->dir_output)) { $dir = $conf->expedition->dir_output.'/sending/'.$ref; $file = $dir.'/'.$ref.'.pdf'; - if (file_exists($file)) - { - if (!dol_delete_file($file)) - { + if (file_exists($file)) { + if (!dol_delete_file($file)) { return 0; } } - if (file_exists($dir)) - { - if (!dol_delete_dir_recursive($dir)) - { + if (file_exists($dir)) { + if (!dol_delete_dir_recursive($dir)) { $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir); return 0; } @@ -1590,8 +1583,7 @@ class Expedition extends CommonObject dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; $num = $this->db->num_rows($resql); @@ -1607,8 +1599,7 @@ class Expedition extends CommonObject $line = new ExpeditionLigne($this->db); - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); if ($originline == $obj->fk_origin_line) { @@ -1699,21 +1690,17 @@ class Expedition extends CommonObject $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - if ($originline != $obj->fk_origin_line) - { + if ($originline != $obj->fk_origin_line) { $line->detail_batch = array(); } // Detail of batch - if (!empty($conf->productbatch->enabled) && $obj->line_id > 0 && $obj->product_tobatch > 0) - { + if (!empty($conf->productbatch->enabled) && $obj->line_id > 0 && $obj->product_tobatch > 0) { require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php'; $newdetailbatch = ExpeditionLineBatch::fetchAll($this->db, $obj->line_id, $obj->fk_product); - if (is_array($newdetailbatch)) - { - if ($originline != $obj->fk_origin_line) - { + if (is_array($newdetailbatch)) { + if ($originline != $obj->fk_origin_line) { $line->detail_batch = $newdetailbatch; } else { $line->detail_batch = array_merge($line->detail_batch, $newdetailbatch); @@ -1721,8 +1708,7 @@ class Expedition extends CommonObject } } - if ($originline != $obj->fk_origin_line) - { + if ($originline != $obj->fk_origin_line) { $this->lines[$lineindex] = $line; $lineindex++; } else { @@ -1755,8 +1741,7 @@ class Expedition extends CommonObject { global $user; - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { $this->db->begin(); $line = new ExpeditionLigne($this->db); @@ -1764,8 +1749,7 @@ class Expedition extends CommonObject // For triggers $line->fetch($lineid); - if ($line->delete($user) > 0) - { + if ($line->delete($user) > 0) { //$this->update_price(1); $this->db->commit(); @@ -1803,21 +1787,24 @@ class Expedition extends CommonObject $url = DOL_URL_ROOT.'/expedition/card.php?id='.$this->id; - if ($short) return $url; + if ($short) { + return $url; + } - if ($option !== 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("Shipment"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -1830,8 +1817,12 @@ class Expedition extends CommonObject $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; return $result; @@ -1865,9 +1856,15 @@ class Expedition extends CommonObject $labelStatusShort = $langs->trans($this->statutshorts[$status]); $statusType = 'status'.$status; - if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; - if ($status == self::STATUS_CLOSED) $statusType = 'status6'; - if ($status == self::STATUS_CANCELED) $statusType = 'status9'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } + if ($status == self::STATUS_CLOSED) { + $statusType = 'status6'; + } + if ($status == self::STATUS_CANCELED) { + $statusType = 'status9'; + } return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); } @@ -1894,12 +1891,10 @@ class Expedition extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."product"; $sql .= " WHERE entity IN (".getEntity('product').")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -1936,8 +1931,7 @@ class Expedition extends CommonObject $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new ExpeditionLigne($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; $line->libelle = $langs->trans("Description")." ".$xnbp; // deprecated @@ -1976,16 +1970,14 @@ class Expedition extends CommonObject */ public function setDeliveryDate($user, $delivery_date) { - if ($user->rights->expedition->creer) - { + if ($user->rights->expedition->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."expedition"; $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null'); $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->date_delivery = $delivery_date; return 1; } else { @@ -2015,10 +2007,8 @@ class Expedition extends CommonObject $sql .= " ORDER BY em.libelle ASC"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $label = $langs->trans('SendingMethod'.$obj->code); $this->meths[$obj->rowid] = ($label != 'SendingMethod'.$obj->code ? $label : $obj->label); } @@ -2042,13 +2032,13 @@ class Expedition extends CommonObject $sql = "SELECT em.rowid, em.code, em.libelle as label, em.description, em.tracking, em.active"; $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em"; - if ($id != '') $sql .= " WHERE em.rowid=".$id; + if ($id != '') { + $sql .= " WHERE em.rowid=".$id; + } $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->listmeths[$i]['rowid'] = $obj->rowid; $this->listmeths[$i]['code'] = $obj->code; $label = $langs->trans('SendingMethod'.$obj->code); @@ -2072,8 +2062,7 @@ class Expedition extends CommonObject public function update_delivery_method($id = '') { // phpcs:enable - if ($id == '') - { + if ($id == '') { $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_shipment_mode (code, libelle, description, tracking)"; $sql .= " VALUES ('".$this->db->escape($this->update['code'])."','".$this->db->escape($this->update['libelle'])."','".$this->db->escape($this->update['description'])."','".$this->db->escape($this->update['tracking'])."')"; $resql = $this->db->query($sql); @@ -2086,7 +2075,9 @@ class Expedition extends CommonObject $sql .= " WHERE rowid=".$id; $resql = $this->db->query($sql); } - if ($resql < 0) dol_print_error($this->db, ''); + if ($resql < 0) { + dol_print_error($this->db, ''); + } } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -2131,24 +2122,20 @@ class Expedition extends CommonObject */ public function getUrlTrackingStatus($value = '') { - if (!empty($this->shipping_method_id)) - { + if (!empty($this->shipping_method_id)) { $sql = "SELECT em.code, em.tracking"; $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em"; $sql .= " WHERE em.rowid = ".$this->shipping_method_id; $resql = $this->db->query($sql); - if ($resql) - { - if ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + if ($obj = $this->db->fetch_object($resql)) { $tracking = $obj->tracking; } } } - if (!empty($tracking) && !empty($value)) - { + if (!empty($tracking) && !empty($value)) { $url = str_replace('{TRACKID}', $value, $tracking); $this->tracking_url = sprintf(''.($value ? $value : 'url').'', $url, $url); } else { @@ -2168,8 +2155,7 @@ class Expedition extends CommonObject $error = 0; // Protection. This avoid to move stock later when we should not - if ($this->statut == self::STATUS_CLOSED) - { + if ($this->statut == self::STATUS_CLOSED) { return 0; } @@ -2179,31 +2165,26 @@ class Expedition extends CommonObject $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0'; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Set order billed if 100% of order is shipped (qty in shipment lines match qty in order lines) - if ($this->origin == 'commande' && $this->origin_id > 0) - { + if ($this->origin == 'commande' && $this->origin_id > 0) { $order = new Commande($this->db); $order->fetch($this->origin_id); $order->loadExpeditions(self::STATUS_CLOSED); // Fill $order->expeditions = array(orderlineid => qty) $shipments_match_order = 1; - foreach ($order->lines as $line) - { + foreach ($order->lines as $line) { $lineid = $line->id; $qty = $line->qty; - if (($line->product_type == 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) && $order->expeditions[$lineid] != $qty) - { + if (($line->product_type == 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) && $order->expeditions[$lineid] != $qty) { $shipments_match_order = 0; $text = 'Qty for order line id '.$lineid.' is '.$qty.'. However in the shipments with status Expedition::STATUS_CLOSED='.self::STATUS_CLOSED.' we have qty = '.$order->expeditions[$lineid].', so we can t close order'; dol_syslog($text); break; } } - if ($shipments_match_order) - { + if ($shipments_match_order) { dol_syslog("Qty for the ".count($order->lines)." lines of order have same value for shipments with status Expedition::STATUS_CLOSED=".self::STATUS_CLOSED.', so we close order'); $order->cloture($user); } @@ -2213,8 +2194,7 @@ class Expedition extends CommonObject // If stock increment is done on closing - if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) - { + if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); @@ -2232,26 +2212,24 @@ class Expedition extends CommonObject dol_syslog(get_class($this)."::valid select details", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $cpt = $this->db->num_rows($resql); - for ($i = 0; $i < $cpt; $i++) - { + for ($i = 0; $i < $cpt; $i++) { $obj = $this->db->fetch_object($resql); - if (empty($obj->edbrowid)) - { + if (empty($obj->edbrowid)) { $qty = $obj->qty; } else { $qty = $obj->edbqty; } - if ($qty <= 0) continue; + if ($qty <= 0) { + continue; + } dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid); $mouvS = new MouvementStock($this->db); $mouvS->origin = &$this; - if (empty($obj->edbrowid)) - { + if (empty($obj->edbrowid)) { // line without batch detail // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record @@ -2280,8 +2258,7 @@ class Expedition extends CommonObject } // Call trigger - if (!$error) - { + if (!$error) { $result = $this->call_trigger('SHIPPING_CLOSED', $user); if ($result < 0) { $error++; @@ -2292,8 +2269,7 @@ class Expedition extends CommonObject $error++; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -2334,8 +2310,7 @@ class Expedition extends CommonObject $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0'; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->statut = self::STATUS_CLOSED; $this->billed = 1; @@ -2372,8 +2347,7 @@ class Expedition extends CommonObject $error = 0; // Protection. This avoid to move stock later when we should not - if ($this->statut == self::STATUS_VALIDATED) - { + if ($this->statut == self::STATUS_VALIDATED) { return 0; } @@ -2385,14 +2359,12 @@ class Expedition extends CommonObject $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0'; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->statut = self::STATUS_VALIDATED; $this->billed = 0; // If stock increment is done on closing - if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) - { + if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); @@ -2410,27 +2382,25 @@ class Expedition extends CommonObject dol_syslog(get_class($this)."::valid select details", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $cpt = $this->db->num_rows($resql); - for ($i = 0; $i < $cpt; $i++) - { + for ($i = 0; $i < $cpt; $i++) { $obj = $this->db->fetch_object($resql); - if (empty($obj->edbrowid)) - { + if (empty($obj->edbrowid)) { $qty = $obj->qty; } else { $qty = $obj->edbqty; } - if ($qty <= 0) continue; + if ($qty <= 0) { + continue; + } dol_syslog(get_class($this)."::reopen expedition movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid); //var_dump($this->lines[$i]); $mouvS = new MouvementStock($this->db); $mouvS->origin = &$this; - if (empty($obj->edbrowid)) - { + if (empty($obj->edbrowid)) { // line without batch detail // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record @@ -2470,8 +2440,7 @@ class Expedition extends CommonObject $this->errors[] = $this->db->lasterror(); } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -2715,8 +2684,7 @@ class ExpeditionLigne extends CommonObjectLine $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as ed'; $sql .= ' WHERE ed.rowid = '.$rowid; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $objp = $this->db->fetch_object($result); $this->id = $objp->rowid; $this->fk_expedition = $objp->fk_expedition; @@ -2749,20 +2717,20 @@ class ExpeditionLigne extends CommonObjectLine $error = 0; // Check parameters - if (empty($this->fk_expedition) || empty($this->fk_origin_line) || !is_numeric($this->qty)) - { + if (empty($this->fk_expedition) || empty($this->fk_origin_line) || !is_numeric($this->qty)) { $this->error = 'ErrorMandatoryParametersNotProvided'; return -1; } $this->db->begin(); - if (empty($this->rang)) $this->rang = 0; + if (empty($this->rang)) { + $this->rang = 0; + } // Rank to use $ranktouse = $this->rang; - if ($ranktouse == -1) - { + if ($ranktouse == -1) { $rangmax = $this->line_max($this->fk_expedition); $ranktouse = $rangmax + 1; } @@ -2783,25 +2751,20 @@ class ExpeditionLigne extends CommonObjectLine dol_syslog(get_class($this)."::insert", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."expeditiondet"); - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINESHIPPING_INSERT', $user); - if ($result < 0) - { + if ($result < 0) { $error++; } // End call triggers @@ -2812,8 +2775,7 @@ class ExpeditionLigne extends CommonObjectLine return $this->id; } - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2841,13 +2803,11 @@ class ExpeditionLigne extends CommonObjectLine $this->db->begin(); // delete batch expedition line - if ($conf->productbatch->enabled) - { + if ($conf->productbatch->enabled) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch"; $sql .= " WHERE fk_expeditiondet = ".$this->id; - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $this->errors[] = $this->db->lasterror()." - sql=$sql"; $error++; } @@ -2856,24 +2816,19 @@ class ExpeditionLigne extends CommonObjectLine $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet"; $sql .= " WHERE rowid = ".$this->id; - if (!$error && $this->db->query($sql)) - { + if (!$error && $this->db->query($sql)) { // Remove extrafields - if (!$error) - { + if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->errors[] = $this->error; $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINESHIPPING_DELETE', $user); - if ($result < 0) - { + if ($result < 0) { $this->errors[] = $this->error; $error++; } @@ -2888,8 +2843,7 @@ class ExpeditionLigne extends CommonObjectLine $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2916,16 +2870,16 @@ class ExpeditionLigne extends CommonObjectLine $this->db->begin(); // Clean parameters - if (empty($this->qty)) $this->qty = 0; + if (empty($this->qty)) { + $this->qty = 0; + } $qty = price2num($this->qty); $remainingQty = 0; $batch = null; $batch_id = null; $expedition_batch_id = null; - if (is_array($this->detail_batch)) // array of ExpeditionLineBatch - { - if (count($this->detail_batch) > 1) - { + if (is_array($this->detail_batch)) { // array of ExpeditionLineBatch + if (count($this->detail_batch) > 1) { dol_syslog(get_class($this).'::update only possible for one batch', LOG_ERR); $this->errors[] = 'ErrorBadParameters'; $error++; @@ -2933,21 +2887,18 @@ class ExpeditionLigne extends CommonObjectLine $batch = $this->detail_batch[0]->batch; $batch_id = $this->detail_batch[0]->fk_origin_stock; $expedition_batch_id = $this->detail_batch[0]->id; - if ($this->entrepot_id != $this->detail_batch[0]->entrepot_id) - { + if ($this->entrepot_id != $this->detail_batch[0]->entrepot_id) { dol_syslog(get_class($this).'::update only possible for batch of same warehouse', LOG_ERR); $this->errors[] = 'ErrorBadParameters'; $error++; } $qty = price2num($this->detail_batch[0]->qty); } - } elseif (!empty($this->detail_batch)) - { + } elseif (!empty($this->detail_batch)) { $batch = $this->detail_batch->batch; $batch_id = $this->detail_batch->fk_origin_stock; $expedition_batch_id = $this->detail_batch->id; - if ($this->entrepot_id != $this->detail_batch->entrepot_id) - { + if ($this->entrepot_id != $this->detail_batch->entrepot_id) { dol_syslog(get_class($this).'::update only possible for batch of same warehouse', LOG_ERR); $this->errors[] = 'ErrorBadParameters'; $error++; @@ -2956,8 +2907,7 @@ class ExpeditionLigne extends CommonObjectLine } // check parameters - if (!isset($this->id) || !isset($this->entrepot_id)) - { + if (!isset($this->id) || !isset($this->entrepot_id)) { dol_syslog(get_class($this).'::update missing line id and/or warehouse id', LOG_ERR); $this->errors[] = 'ErrorMandatoryParametersNotProvided'; $error++; @@ -2966,8 +2916,7 @@ class ExpeditionLigne extends CommonObjectLine // update lot - if (!empty($batch) && $conf->productbatch->enabled) - { + if (!empty($batch) && $conf->productbatch->enabled) { dol_syslog(get_class($this)."::update expedition batch id=$expedition_batch_id, batch_id=$batch_id, batch=$batch"); if (empty($batch_id) || empty($this->fk_product)) { @@ -2978,16 +2927,13 @@ class ExpeditionLigne extends CommonObjectLine // fetch remaining lot qty require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php'; - if (!$error && ($lotArray = ExpeditionLineBatch::fetchAll($this->db, $this->id)) < 0) - { + if (!$error && ($lotArray = ExpeditionLineBatch::fetchAll($this->db, $this->id)) < 0) { $this->errors[] = $this->db->lasterror()." - ExpeditionLineBatch::fetchAll"; $error++; } else { // caculate new total line qty - foreach ($lotArray as $lot) - { - if ($expedition_batch_id != $lot->id) - { + foreach ($lotArray as $lot) { + if ($expedition_batch_id != $lot->id) { $remainingQty += $lot->qty; } } @@ -2998,29 +2944,24 @@ class ExpeditionLigne extends CommonObjectLine // fetch from product_lot require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; $lot = new Productlot($this->db); - if ($lot->fetch(0, $this->fk_product, $batch) < 0) - { + if ($lot->fetch(0, $this->fk_product, $batch) < 0) { $this->errors[] = $lot->errors; $error++; } - if (!$error && !empty($expedition_batch_id)) - { + if (!$error && !empty($expedition_batch_id)) { // delete lot expedition line $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch"; $sql .= " WHERE fk_expeditiondet = ".$this->id; $sql .= " AND rowid = ".$expedition_batch_id; - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $this->errors[] = $this->db->lasterror()." - sql=$sql"; $error++; } } - if (!$error && $this->detail_batch->qty > 0) - { + if (!$error && $this->detail_batch->qty > 0) { // create lot expedition line - if (isset($lot->id)) - { + if (isset($lot->id)) { $shipmentLot = new ExpeditionLineBatch($this->db); $shipmentLot->batch = $lot->batch; $shipmentLot->eatby = $lot->eatby; @@ -3028,8 +2969,7 @@ class ExpeditionLigne extends CommonObjectLine $shipmentLot->entrepot_id = $this->detail_batch->entrepot_id; $shipmentLot->qty = $this->detail_batch->qty; $shipmentLot->fk_origin_stock = $batch_id; - if ($shipmentLot->create($this->id) < 0) - { + if ($shipmentLot->create($this->id) < 0) { $this->errors[] = $shipmentLot->errors; $error++; } @@ -3037,40 +2977,33 @@ class ExpeditionLigne extends CommonObjectLine } } } - if (!$error) - { + if (!$error) { // update line $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; $sql .= " fk_entrepot = ".($this->entrepot_id > 0 ? $this->entrepot_id : 'null'); $sql .= " , qty = ".$qty; $sql .= " WHERE rowid = ".$this->id; - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $this->errors[] = $this->db->lasterror()." - sql=$sql"; $error++; } } - if (!$error) - { - if (!$error) - { + if (!$error) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->errors[] = $this->error; $error++; } } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINESHIPPING_UPDATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->errors[] = $this->error; $error++; } @@ -3080,8 +3013,7 @@ class ExpeditionLigne extends CommonObjectLine $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } diff --git a/htdocs/expedition/class/expeditionbatch.class.php b/htdocs/expedition/class/expeditionbatch.class.php index 637f9dd749c..f97d6b87a1b 100644 --- a/htdocs/expedition/class/expeditionbatch.class.php +++ b/htdocs/expedition/class/expeditionbatch.class.php @@ -75,10 +75,8 @@ class ExpeditionLineBatch extends CommonObject dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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->sellby = $this->db->jdate($obj->sellby); @@ -126,16 +124,16 @@ class ExpeditionLineBatch extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.self::$_table_element); $this->fk_expeditiondet = $id_line_expdet; return $this->id; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -159,8 +157,7 @@ class ExpeditionLineBatch extends CommonObject $sql .= " WHERE fk_expeditiondet in (SELECT rowid FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition=".$id_expedition.")"; dol_syslog(__METHOD__, LOG_DEBUG); - if ($db->query($sql)) - { + if ($db->query($sql)) { return 1; } else { return -1; @@ -185,27 +182,23 @@ class ExpeditionLineBatch extends CommonObject $sql .= " eb.batch,"; $sql .= " eb.qty,"; $sql .= " eb.fk_origin_stock"; - if ($fk_product > 0) - { + if ($fk_product > 0) { $sql .= ", pl.sellby"; $sql .= ", pl.eatby"; } $sql .= " FROM ".MAIN_DB_PREFIX.self::$_table_element." as eb"; - if ($fk_product > 0) - { + if ($fk_product > 0) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON pl.batch = eb.batch AND pl.fk_product = ".$fk_product; } $sql .= " WHERE fk_expeditiondet=".(int) $id_line_expdet; dol_syslog(__METHOD__."", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; $ret = array(); - while ($i < $num) - { + while ($i < $num) { $tmp = new self($db); $obj = $db->fetch_object($resql); diff --git a/htdocs/expedition/class/expeditionstats.class.php b/htdocs/expedition/class/expeditionstats.class.php index 49d37179eda..50382cef164 100644 --- a/htdocs/expedition/class/expeditionstats.class.php +++ b/htdocs/expedition/class/expeditionstats.class.php @@ -73,12 +73,15 @@ class ExpeditionStats extends Stats //$this->where.= " AND c.fk_soc = s.rowid AND c.entity = ".$conf->entity; $this->where .= " AND c.entity = ".$conf->entity; - if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($this->socid) - { + if (!$user->rights->societe->client->voir && !$this->socid) { + $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($this->socid) { $this->where .= " AND c.fk_soc = ".$this->socid; } - if ($this->userid > 0) $this->where .= ' AND c.fk_user_author = '.$this->userid; + if ($this->userid > 0) { + $this->where .= ' AND c.fk_user_author = '.$this->userid; + } } /** @@ -94,7 +97,9 @@ class ExpeditionStats extends Stats $sql = "SELECT date_format(c.date_valid,'%m') as dm, COUNT(*) as nb"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; $sql .= " GROUP BY dm"; @@ -116,7 +121,9 @@ class ExpeditionStats extends Stats $sql = "SELECT date_format(c.date_valid,'%Y') as dm, COUNT(*) as nb, SUM(c.".$this->field.")"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE ".$this->where; $sql .= " GROUP BY dm"; $sql .= $this->db->order('dm', 'DESC'); @@ -135,7 +142,9 @@ class ExpeditionStats extends Stats $sql = "SELECT date_format(c.date_valid,'%Y') as year, COUNT(*) as nb, SUM(c.".$this->field.") as total, AVG(".$this->field.") as avg"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE ".$this->where; $sql .= " GROUP BY year"; $sql .= $this->db->order('year', 'DESC'); diff --git a/htdocs/expedition/contact.php b/htdocs/expedition/contact.php index d15e267b285..a096b2155ce 100644 --- a/htdocs/expedition/contact.php +++ b/htdocs/expedition/contact.php @@ -42,30 +42,28 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expedition', $id, ''); $object = new Expedition($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch($id, $ref); $object->fetch_thirdparty(); - if (!empty($object->origin)) - { + if (!empty($object->origin)) { $typeobject = $object->origin; $origin = $object->origin; $object->fetch_origin(); } // Linked documents - if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) - { + if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) { $objectsrc = new Commande($db); $objectsrc->fetch($object->$typeobject->id); } - if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) - { + if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) { $objectsrc = new Propal($db); $objectsrc->fetch($object->$typeobject->id); } @@ -76,22 +74,18 @@ if ($id > 0 || !empty($ref)) * Actions */ -if ($action == 'addcontact' && $user->rights->expedition->creer) -{ - if ($result > 0 && $id > 0) - { +if ($action == 'addcontact' && $user->rights->expedition->creer) { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $objectsrc->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($objectsrc->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($objectsrc->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); $mesg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); } else { @@ -100,21 +94,14 @@ if ($action == 'addcontact' && $user->rights->expedition->creer) } setEventMessages($mesg, $mesgs, 'errors'); } -} - -// bascule du statut d'un contact -elseif ($action == 'swapstatut' && $user->rights->expedition->creer) -{ +} elseif ($action == 'swapstatut' && $user->rights->expedition->creer) { + // bascule du statut d'un contact $result = $objectsrc->swapContactStatus(GETPOST('ligne')); -} - -// Efface un contact -elseif ($action == 'deletecontact' && $user->rights->expedition->creer) -{ +} elseif ($action == 'deletecontact' && $user->rights->expedition->creer) { + // Efface un contact $result = $objectsrc->delete_contact(GETPOST("lineid")); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -149,8 +136,7 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $langs->trans("OrderCard"); $head = shipping_prepare_head($object); @@ -213,8 +199,7 @@ if ($id > 0 || !empty($ref)) print '
    '.$formproduct->selectLotStock('', 'batchl'.$line_id.'_0', '', 1, 0, $lines[$i]->fk_product).'
    '.$formproduct->selectWarehouses($lines[$i]->entrepot_id, 'entl'.$line_id, '', 1, 0, $lines[$i]->fk_product, '', 1).' - '.$langs->trans("NA").'
    '.$formproduct->selectWarehouses($detail_entrepot->entrepot_id, 'entl'.$detail_entrepot->line_id, '', 1, 0, $lines[$i]->fk_product, '', 1).'
    '.$lines[$i]->qty_shipped.''; - if ($lines[$i]->entrepot_id > 0) - { + if ($lines[$i]->entrepot_id > 0) { $entrepot = new Entrepot($db); $entrepot->fetch($lines[$i]->entrepot_id); print $entrepot->getNomUrl(1); - } elseif (count($lines[$i]->details_entrepot) > 1) - { + } elseif (count($lines[$i]->details_entrepot) > 1) { $detail = ''; - foreach ($lines[$i]->details_entrepot as $detail_entrepot) - { - if ($detail_entrepot->entrepot_id > 0) - { + foreach ($lines[$i]->details_entrepot as $detail_entrepot) { + if ($detail_entrepot->entrepot_id > 0) { $entrepot = new Entrepot($db); $entrepot->fetch($detail_entrepot->entrepot_id); $detail .= $langs->trans("DetailWarehouseFormat", $entrepot->libelle, $detail_entrepot->qty_shipped).'
    '; @@ -2305,17 +2218,13 @@ if ($action == 'create') } // Batch number managment - if (!empty($conf->productbatch->enabled)) - { - if (isset($lines[$i]->detail_batch)) - { + if (!empty($conf->productbatch->enabled)) { + if (isset($lines[$i]->detail_batch)) { print ''; print '
    '; - if ($lines[$i]->product_tobatch) - { + if ($lines[$i]->product_tobatch) { $detail = ''; - foreach ($lines[$i]->detail_batch as $dbatch) // $dbatch is instance of ExpeditionLineBatch - { + foreach ($lines[$i]->detail_batch as $dbatch) { // $dbatch is instance of ExpeditionLineBatch $detail .= $langs->trans("Batch").': '.$dbatch->batch; if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { $detail .= ' - '.$langs->trans("SellByDate").': '.dol_print_date($dbatch->sellby, "day"); @@ -2339,27 +2248,31 @@ if ($action == 'create') // Weight print ''; - if ($lines[$i]->fk_product_type == Product::TYPE_PRODUCT) print $lines[$i]->weight * $lines[$i]->qty_shipped.' '.measuringUnitString(0, "weight", $lines[$i]->weight_units); - else print ' '; + if ($lines[$i]->fk_product_type == Product::TYPE_PRODUCT) { + print $lines[$i]->weight * $lines[$i]->qty_shipped.' '.measuringUnitString(0, "weight", $lines[$i]->weight_units); + } else { + print ' '; + } print ''; - if ($lines[$i]->fk_product_type == Product::TYPE_PRODUCT) print $lines[$i]->volume * $lines[$i]->qty_shipped.' '.measuringUnitString(0, "volume", $lines[$i]->volume_units); - else print ' '; + if ($lines[$i]->fk_product_type == Product::TYPE_PRODUCT) { + print $lines[$i]->volume * $lines[$i]->qty_shipped.' '.measuringUnitString(0, "volume", $lines[$i]->volume_units); + } else { + print ' '; + } print ''.$lines[$i]->volume*$lines[$i]->qty_shipped.' '.measuringUnitString(0, "volume", $lines[$i]->volume_units).''; print '
    '; print '
    '; print '
    '; print 'id.'">'.img_edit().''; @@ -2369,8 +2282,7 @@ if ($action == 'create') print '
    '; // Linked documents - if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) - { + if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) { print '\n"; print ''; } - if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) - { + if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) { print ''; - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $shipment->id = $obj->rowid; @@ -123,7 +120,9 @@ if ($resql) print ''.$obj->name.''; print ''; print ''; $i++; } @@ -151,17 +150,22 @@ $sql .= " FROM ".MAIN_DB_PREFIX."expedition as e"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON e.rowid = el.fk_target AND el.targettype = 'shipping' AND el.sourcetype IN ('commande')"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON el.fk_source = c.rowid AND el.sourcetype IN ('commande') AND el.targettype = 'shipping'"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = e.fk_soc"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON e.fk_soc = sc.fk_soc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON e.fk_soc = sc.fk_soc"; +} $sql .= " WHERE e.entity IN (".getEntity('expedition').")"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND sc.fk_user = ".$user->id; +} $sql .= " AND e.fk_statut = ".Expedition::STATUS_VALIDATED; -if ($socid) $sql .= " AND c.fk_soc = ".$socid; +if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; +} $sql .= " ORDER BY e.date_delivery DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); print '
    '; @@ -175,11 +179,9 @@ if ($resql) print ''; print ''; - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $shipment->id = $obj->rowid; @@ -191,8 +193,7 @@ if ($resql) print ''; print '
    '; print '
    '; $objectsrc = new Commande($db); $objectsrc->fetch($object->$typeobject->id); @@ -224,8 +209,7 @@ if ($id > 0 || !empty($ref)) print "
    '; $objectsrc = new Propal($db); $objectsrc->fetch($object->$typeobject->id); @@ -260,10 +244,11 @@ if ($id > 0 || !empty($ref)) // Contacts lines (modules that overwrite templates must declare this into descriptor) $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); $preselectedtypeofcontact = dol_getIdFromCode($db, 'SHIPPING', 'c_type_contact', 'code', 'rowid'); - foreach ($dirtpls as $reldir) - { + foreach ($dirtpls as $reldir) { $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); - if ($res) break; + if ($res) { + break; + } } } diff --git a/htdocs/expedition/document.php b/htdocs/expedition/document.php index a9b19ede7c3..836b469cb77 100644 --- a/htdocs/expedition/document.php +++ b/htdocs/expedition/document.php @@ -46,8 +46,7 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref'); // Security check -if ($user->socid) -{ +if ($user->socid) { $socid = $user->socid; } $result = restrictedArea($user, 'expedition', $id, ''); @@ -57,12 +56,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"; +} $object = new Expedition($db); @@ -70,13 +75,12 @@ $object = new Expedition($db); /* * Actions */ -if ($object->fetch($id)) -{ +if ($object->fetch($id)) { $object->fetch_thirdparty(); $upload_dir = $conf->expedition->dir_output."/sending/".dol_sanitizeFileName($object->ref); } -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* diff --git a/htdocs/expedition/index.php b/htdocs/expedition/index.php index 4a84bfc6718..5ea3b923e91 100644 --- a/htdocs/expedition/index.php +++ b/htdocs/expedition/index.php @@ -54,8 +54,7 @@ print load_fiche_titre($langs->trans("SendingsArea"), '', 'dolly'); print '
    '; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo print ''; print ''; print '
    '; @@ -79,19 +78,19 @@ $sql .= " FROM ".MAIN_DB_PREFIX."expedition as e"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON e.rowid = el.fk_target AND el.targettype = 'shipping'"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON el.fk_source = c.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = e.fk_soc"; -if (!$user->rights->societe->client->voir && !$socid) -{ +if (!$user->rights->societe->client->voir && !$socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON e.fk_soc = sc.fk_soc"; $sql .= $clause." sc.fk_user = ".$user->id; $clause = " AND "; } $sql .= $clause." e.fk_statut = ".Expedition::STATUS_DRAFT; $sql .= " AND e.entity IN (".getEntity('expedition').")"; -if ($socid) $sql .= " AND c.fk_soc = ".$socid; +if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; +} $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); print '
    '; @@ -105,11 +104,9 @@ if ($resql) print ''; print '
    '; - if ($obj->commande_id) print ''.$obj->commande_ref.''; + if ($obj->commande_id) { + print ''.$obj->commande_ref.''; + } print '
    '.img_object($langs->trans("ShowCompany"), "company").' '.$obj->name.''; - if ($obj->commande_id > 0) - { + if ($obj->commande_id > 0) { $orderstatic->id = $obj->commande_id; $orderstatic->ref = $obj->commande_ref; print $orderstatic->getNomUrl(1); @@ -209,7 +210,9 @@ if ($resql) } print "

    "; $db->free($resql); -} else dol_print_error($db); +} else { + dol_print_error($db); +} /* * Open orders @@ -217,17 +220,22 @@ if ($resql) $sql = "SELECT c.rowid, c.ref, c.ref_client as ref_customer, c.fk_statut as status, c.facture as billed, s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."commande as c,"; $sql .= " ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity('order').")"; $sql .= " AND c.fk_statut IN (".Commande::STATUS_VALIDATED.", ".Commande::STATUS_ACCEPTED.")"; -if ($socid > 0) $sql .= " AND c.fk_soc = ".$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($socid > 0) { + $sql .= " AND c.fk_soc = ".$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " ORDER BY c.rowid ASC"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $langs->load("orders"); $num = $db->num_rows($resql); @@ -243,11 +251,9 @@ if ($resql) print ''; print ''; - if ($num) - { + if ($num) { $i = 0; - while ($i < $num && $i < 10) - { + while ($i < $num && $i < 10) { $obj = $db->fetch_object($resql); $orderstatic->id = $obj->rowid; @@ -284,7 +290,9 @@ if ($resql) } print "

    "; -} else dol_print_error($db); +} else { + dol_print_error($db); +} print ''; diff --git a/htdocs/expedition/list.php b/htdocs/expedition/list.php index a21ad170b09..327e9a030e0 100644 --- a/htdocs/expedition/list.php +++ b/htdocs/expedition/list.php @@ -49,7 +49,9 @@ $toselect = GETPOST('toselect', 'array'); // Security check $expeditionid = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expedition', $expeditionid, ''); $search_ref_exp = GETPOST("search_ref_exp", 'alpha'); @@ -79,9 +81,15 @@ $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 (!$sortfield) $sortfield = "e.ref"; -if (!$sortorder) $sortorder = "DESC"; -if (empty($page) || $page == -1 || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 +if (!$sortfield) { + $sortfield = "e.ref"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} +if (empty($page) || $page == -1 || (empty($toselect) && $massaction === '0')) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -109,7 +117,9 @@ $fieldstosearchall = array( 'e.note_public'=>'NotePublic', 'e.tracking_number'=>"TrackingNumber", ); -if (empty($user->socid)) $fieldstosearchall["e.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["e.note_private"] = "NotePrivate"; +} $checkedtypetiers = 0; $arrayfields = array( @@ -144,18 +154,23 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); */ $error = 0; -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $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'); +} include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_categ = ''; $search_user = ''; $search_sale = ''; @@ -182,8 +197,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_categ_cus = 0; } -if (empty($reshook)) -{ +if (empty($reshook)) { $objectclass = 'Expedition'; $objectlabel = 'Sendings'; $permissiontoread = $user->rights->expedition->lire; @@ -211,7 +225,9 @@ $helpurl = 'EN:Module_Shipments|FR:Module_Expéditions|ES:Módulo_Ex llxHeader('', $langs->trans('ListOfSendings'), $helpurl); $sql = 'SELECT'; -if ($sall || $search_product_category > 0 || $search_user > 0) $sql = 'SELECT DISTINCT'; +if ($sall || $search_product_category > 0 || $search_user > 0) { + $sql = 'SELECT DISTINCT'; +} $sql .= " e.rowid, e.ref, e.ref_customer, e.date_expedition as date_expedition, e.weight, e.weight_units, e.date_delivery as delivery_date, e.fk_statut, e.billed, e.tracking_number,"; $sql .= " l.date_delivery as date_reception,"; $sql .= " s.rowid as socid, s.nom as name, s.town, s.zip, s.fk_pays, s.client, s.code_client, "; @@ -219,24 +235,34 @@ $sql .= " typent.code as typent_code,"; $sql .= " state.code_departement as state_code, state.nom as state_name,"; $sql .= " e.date_creation as date_creation, e.tms as date_update,"; $sql .= " u.login"; -if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc"; +if ($search_categ_cus) { + $sql .= ", cc.fk_categorie, cc.fk_soc"; +} // 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 : ''); + 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 $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."expedition as e"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (e.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (e.rowid = ef.fk_object)"; +} if ($sall || $search_product_category > 0) { $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'expeditiondet as ed ON e.rowid=ed.fk_expedition'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON pd.rowid=ed.fk_origin_line'; } -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = e.fk_soc"; -if (!empty($search_categ_cus)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ +if (!empty($search_categ_cus)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; @@ -247,50 +273,91 @@ if ($search_user > 0) { // Get link to order to get the order id in eesource.fk $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as eesource ON eesource.fk_target = e.rowid AND eesource.targettype = 'shipping' AND eesource.sourcetype = 'commande'"; } // We'll need this table joined to the select in order to filter by sale -if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} if ($search_user > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql .= " WHERE e.entity IN (".getEntity('expedition').")"; -if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; -if ($socid > 0) $sql .= ' AND s.rowid = '.$socid; -if (!$user->rights->societe->client->voir && !$socid) // Internal user with no permission to see all -{ +if ($search_product_category > 0) { + $sql .= " AND cp.fk_categorie = ".$search_product_category; +} +if ($socid > 0) { + $sql .= ' AND s.rowid = '.$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { // Internal user with no permission to see all $sql .= " AND e.fk_soc = sc.fk_soc"; $sql .= " AND sc.fk_user = ".$user->id; } -if ($socid) -{ +if ($socid) { $sql .= " AND e.fk_soc = ".$socid; } if ($search_status <> '' && $search_status >= 0) { $sql .= " AND e.fk_statut = ".$search_status; } -if ($search_ref_customer != '') $sql .= natural_search('e.ref_customer', $search_ref_customer); -if ($search_billed != '' && $search_billed >= 0) $sql .= ' AND e.billed = '.$search_billed; -if ($search_town) $sql .= natural_search('s.town', $search_town); -if ($search_zip) $sql .= natural_search("s.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_country) $sql .= " AND s.fk_pays IN (".$search_country.')'; -if ($search_tracking) $sql .= natural_search("e.tracking_number", $search_tracking); -if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; -if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale; -if ($search_user > 0) -{ +if ($search_ref_customer != '') { + $sql .= natural_search('e.ref_customer', $search_ref_customer); +} +if ($search_billed != '' && $search_billed >= 0) { + $sql .= ' AND e.billed = '.$search_billed; +} +if ($search_town) { + $sql .= natural_search('s.town', $search_town); +} +if ($search_zip) { + $sql .= natural_search("s.zip", $search_zip); +} +if ($search_state) { + $sql .= natural_search("state.nom", $search_state); +} +if ($search_country) { + $sql .= " AND s.fk_pays IN (".$search_country.')'; +} +if ($search_tracking) { + $sql .= natural_search("e.tracking_number", $search_tracking); +} +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; +} +if ($search_sale > 0) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale; +} +if ($search_user > 0) { // The contact on a shipment is also the contact of the order. $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal' AND ec.element_id = eesource.fk_source AND ec.fk_socpeople = ".$db->escape($search_user); } -if ($search_ref_exp) $sql .= natural_search('e.ref', $search_ref_exp); -if ($search_ref_liv) $sql .= natural_search('l.ref', $search_ref_liv); -if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_datedelivery_start) $sql .= " AND e.date_delivery >= '".$db->idate($search_datedelivery_start)."'"; -if ($search_datedelivery_end) $sql .= " AND e.date_delivery <= '".$db->idate($search_datedelivery_end)."'"; -if ($search_datereceipt_start) $sql .= " AND l.date_delivery >= '".$db->idate($search_datereceipt_start)."'"; -if ($search_datereceipt_end) $sql .= " AND l.date_delivery <= '".$db->idate($search_datereceipt_end)."'"; -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if ($search_categ_cus > 0) $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); -if ($search_categ_cus == -2) $sql .= " AND cc.fk_categorie IS NULL"; +if ($search_ref_exp) { + $sql .= natural_search('e.ref', $search_ref_exp); +} +if ($search_ref_liv) { + $sql .= natural_search('l.ref', $search_ref_liv); +} +if ($search_company) { + $sql .= natural_search('s.nom', $search_company); +} +if ($search_datedelivery_start) { + $sql .= " AND e.date_delivery >= '".$db->idate($search_datedelivery_start)."'"; +} +if ($search_datedelivery_end) { + $sql .= " AND e.date_delivery <= '".$db->idate($search_datedelivery_end)."'"; +} +if ($search_datereceipt_start) { + $sql .= " AND l.date_delivery >= '".$db->idate($search_datereceipt_start)."'"; +} +if ($search_datereceipt_end) { + $sql .= " AND l.date_delivery <= '".$db->idate($search_datereceipt_end)."'"; +} +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} +if ($search_categ_cus > 0) { + $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); +} +if ($search_categ_cus == -2) { + $sql .= " AND cc.fk_categorie IS NULL"; +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -303,12 +370,10 @@ $sql .= $hookmanager->resPrint; $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -318,516 +383,611 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ - $num = $db->num_rows($resql); +if (!$resql) { + dol_print_error($db); + exit; +} - $arrayofselected = is_array($toselect) ? $toselect : array(); +$num = $db->num_rows($resql); - $expedition = new Expedition($db); +$arrayofselected = is_array($toselect) ? $toselect : array(); - $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_exp) $param .= "&search_ref_exp=".urlencode($search_ref_exp); - if ($search_ref_liv) $param .= "&search_ref_liv=".urlencode($search_ref_liv); - if ($search_ref_customer) $param .= "&search_ref_customer=".urlencode($search_ref_customer); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); - if ($search_company) $param .= "&search_company=".urlencode($search_company); - if ($search_tracking) $param .= "&search_tracking=".urlencode($search_tracking); - if ($search_town) $param .= '&search_town='.urlencode($search_town); - if ($search_zip) $param .= '&search_zip='.urlencode($search_zip); - if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); +$expedition = new Expedition($db); - if ($search_datedelivery_start) $param .= '&search_datedelivery_start='.urlencode($search_datedelivery_start); - if ($search_datedelivery_end) $param .= '&search_datedelivery_end='.urlencode($search_datedelivery_end); - if ($search_datereceipt_start) $param .= '&search_datereceipt_start='.urlencode($search_datereceipt_start); - if ($search_datereceipt_end) $param .= '&search_datereceipt_end='.urlencode($search_datereceipt_end); +$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_exp) { + $param .= "&search_ref_exp=".urlencode($search_ref_exp); +} +if ($search_ref_liv) { + $param .= "&search_ref_liv=".urlencode($search_ref_liv); +} +if ($search_ref_customer) { + $param .= "&search_ref_customer=".urlencode($search_ref_customer); +} +if ($search_user > 0) { + $param .= '&search_user='.urlencode($search_user); +} +if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); +} +if ($search_company) { + $param .= "&search_company=".urlencode($search_company); +} +if ($search_tracking) { + $param .= "&search_tracking=".urlencode($search_tracking); +} +if ($search_town) { + $param .= '&search_town='.urlencode($search_town); +} +if ($search_zip) { + $param .= '&search_zip='.urlencode($search_zip); +} +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); +} - if ($search_product_category != '') $param .= '&search_product_category='.urlencode($search_product_category); - if ($search_categ_cus > 0) $param .= '&search_categ_cus='.urlencode($search_categ_cus); - if ($search_status != '') $param .= '&search_status='.urlencode($search_status); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - // Add $param from extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; +if ($search_datedelivery_start) { + $param .= '&search_datedelivery_start='.urlencode($search_datedelivery_start); +} +if ($search_datedelivery_end) { + $param .= '&search_datedelivery_end='.urlencode($search_datedelivery_end); +} +if ($search_datereceipt_start) { + $param .= '&search_datereceipt_start='.urlencode($search_datereceipt_start); +} +if ($search_datereceipt_end) { + $param .= '&search_datereceipt_end='.urlencode($search_datereceipt_end); +} - $arrayofmassactions = array( - 'builddoc' => $langs->trans("PDFMerge"), - //'classifyclose'=>$langs->trans("Close"), TODO massive close shipment ie: when truck is charged - 'presend' => $langs->trans("SendByMail"), - ); - if (in_array($massaction, array('presend'))) $arrayofmassactions = array(); - $massactionbutton = $form->selectMassAction('', $arrayofmassactions); +if ($search_product_category != '') { + $param .= '&search_product_category='.urlencode($search_product_category); +} +if ($search_categ_cus > 0) { + $param .= '&search_categ_cus='.urlencode($search_categ_cus); +} +if ($search_status != '') { + $param .= '&search_status='.urlencode($search_status); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} +// Add $param from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; - // Currently: a sending can't create from sending list - // $url = DOL_URL_ROOT.'/expedition/card.php?action=create'; - // if (!empty($socid)) $url .= '&socid='.$socid; - // $newcardbutton = dolGetButtonTitle($langs->trans('NewSending'), '', 'fa fa-plus-circle', $url, '', $user->rights->expedition->creer); - $newcardbutton = dolGetButtonTitle($langs->trans('NewSending'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/expedition/card.php?action=create2', '', $user->rights->expedition->creer); +$arrayofmassactions = array( + 'builddoc' => $langs->trans("PDFMerge"), + //'classifyclose'=>$langs->trans("Close"), TODO massive close shipment ie: when truck is charged + 'presend' => $langs->trans("SendByMail"), +); +if (in_array($massaction, array('presend'))) { + $arrayofmassactions = array(); +} +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); - $i = 0; - print ''."\n"; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; +// Currently: a sending can't create from sending list +// $url = DOL_URL_ROOT.'/expedition/card.php?action=create'; +// if (!empty($socid)) $url .= '&socid='.$socid; +// $newcardbutton = dolGetButtonTitle($langs->trans('NewSending'), '', 'fa fa-plus-circle', $url, '', $user->rights->expedition->creer); +$newcardbutton = dolGetButtonTitle($langs->trans('NewSending'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/expedition/card.php?action=create2', '', $user->rights->expedition->creer); - print_barre_liste($langs->trans('ListOfSendings'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'dolly', 0, $newcardbutton, '', $limit, 0, 0, 1); +$i = 0; +print ''."\n"; +if ($optioncss != '') { + print ''; +} +print ''; +print ''; +print ''; +print ''; +print ''; - $topicmail = "SendShippingRef"; - $modelmail = "shipping_send"; - $objecttmp = new Expedition($db); - $trackid = 'shi'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; +print_barre_liste($langs->trans('ListOfSendings'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'dolly', 0, $newcardbutton, '', $limit, 0, 0, 1); - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); - print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; +$topicmail = "SendShippingRef"; +$modelmail = "shipping_send"; +$objecttmp = new Expedition($db); +$trackid = 'shi'.$object->id; +include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; + +if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); } + print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; +} - $moreforfilter = ''; +$moreforfilter = ''; - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { - $langs->load("commercial"); - $moreforfilter .= '
    '; - $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; - $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); - $moreforfilter .= '
    '; - } - // If the user can view other users - if ($user->rights->user->user->lire) - { - $moreforfilter .= '
    '; - $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; - $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - $moreforfilter .= '
    '; - } - // If the user can view prospects other than his' - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) - { - include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $moreforfilter .= '
    '; - $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); - $moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); - $moreforfilter .= '
    '; - } - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) - { - require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $moreforfilter .= '
    '; - $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; - $moreforfilter .= $formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1); - $moreforfilter .= '
    '; - } - $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 the user can view prospects other than his' +if ($user->rights->societe->client->voir || $socid) { + $langs->load("commercial"); + $moreforfilter .= '
    '; + $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; + $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); + $moreforfilter .= '
    '; +} +// If the user can view other users +if ($user->rights->user->user->lire) { + $moreforfilter .= '
    '; + $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; + $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter .= '
    '; +} +// If the user can view prospects other than his' +if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { + include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $moreforfilter .= '
    '; + $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); + $moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); + $moreforfilter .= '
    '; +} +if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $moreforfilter .= '
    '; + $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; + $moreforfilter .= $formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1); + $moreforfilter .= '
    '; +} +$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($moreforfilter)) - { - print '
    '; - print $moreforfilter; - print '
    '; - } +if (!empty($moreforfilter)) { + print '
    '; + print $moreforfilter; + print '
    '; +} - $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); - if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); // This also change content of $arrayfields +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); +if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); // This also change content of $arrayfields +} - print '
    '; - print ''."\n"; +print '
    '; +print '
    '."\n"; + +// Fields title search +print ''; +// Ref +if (!empty($arrayfields['e.ref']['checked'])) { + print ''; +} +// Ref customer +if (!empty($arrayfields['e.ref_customer']['checked'])) { + print ''; +} +// Thirdparty +if (!empty($arrayfields['s.nom']['checked'])) { + print ''; +} +// Town +if (!empty($arrayfields['s.town']['checked'])) { + print ''; +} +// Zip +if (!empty($arrayfields['s.zip']['checked'])) { + print ''; +} +// State +if (!empty($arrayfields['state.nom']['checked'])) { + print ''; +} +// Country +if (!empty($arrayfields['country.code_iso']['checked'])) { + print ''; +} +// Company type +if (!empty($arrayfields['typent.code']['checked'])) { + print ''; +} +// Weight +if (!empty($arrayfields['e.weight']['checked'])) { + print ''; +} +// Date delivery planned +if (!empty($arrayfields['e.date_delivery']['checked'])) { + print ''; +} +// Tracking number +if (!empty($arrayfields['e.tracking_number']['checked'])) { + print ''; +} +if (!empty($arrayfields['l.ref']['checked'])) { + // Delivery ref + print ''; +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + +// Fields from hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Date creation +if (!empty($arrayfields['e.datec']['checked'])) { + print ''; +} +// Date modification +if (!empty($arrayfields['e.tms']['checked'])) { + print ''; +} +// Status +if (!empty($arrayfields['e.fk_statut']['checked'])) { + print ''; +} +// Status billed +if (!empty($arrayfields['e.billed']['checked'])) { + print ''; +} +// Action column +print ''; +print "\n"; + +print ''; +if (!empty($arrayfields['e.ref']['checked'])) { + print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['e.ref_customer']['checked'])) { + print_liste_field_titre($arrayfields['e.ref_customer']['label'], $_SERVER["PHP_SELF"], "e.ref_customer", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder, 'left '); +} +if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['e.weight']['checked'])) { + print_liste_field_titre($arrayfields['e.weight']['label'], $_SERVER["PHP_SELF"], "e.weight", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['e.date_delivery']['checked'])) { + print_liste_field_titre($arrayfields['e.date_delivery']['label'], $_SERVER["PHP_SELF"], "e.date_delivery", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['e.tracking_number']['checked'])) { + print_liste_field_titre($arrayfields['e.tracking_number']['label'], $_SERVER["PHP_SELF"], "e.tracking_number", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['l.ref']['checked'])) { + print_liste_field_titre($arrayfields['l.ref']['label'], $_SERVER["PHP_SELF"], "l.ref", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['l.date_delivery']['checked'])) { + print_liste_field_titre($arrayfields['l.date_delivery']['label'], $_SERVER["PHP_SELF"], "l.date_delivery", "", $param, '', $sortfield, $sortorder, 'center '); +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; +// Hook fields +$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['e.datec']['checked'])) { + print_liste_field_titre($arrayfields['e.datec']['label'], $_SERVER["PHP_SELF"], "e.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['e.tms']['checked'])) { + print_liste_field_titre($arrayfields['e.tms']['label'], $_SERVER["PHP_SELF"], "e.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['e.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['e.fk_statut']['label'], $_SERVER["PHP_SELF"], "e.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['e.billed']['checked'])) { + print_liste_field_titre($arrayfields['e.billed']['label'], $_SERVER["PHP_SELF"], "e.billed", "", $param, '', $sortfield, $sortorder, 'center '); +} +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); +print "\n"; + +$typenArray = $formcompany->typent_array(1); +$i = 0; +$totalarray = array(); +while ($i < min($num, $limit)) { + $obj = $db->fetch_object($resql); + + $shipment->id = $obj->rowid; + $shipment->ref = $obj->ref; + + $companystatic->id = $obj->socid; + $companystatic->ref = $obj->name; + $companystatic->name = $obj->name; + + $object = new Expedition($db); + $object->fetch($obj->rowid); + + print ''; - // Fields title search - print ''; // Ref - if (!empty($arrayfields['e.ref']['checked'])) - { - print ''; + if (!empty($arrayfields['e.ref']['checked'])) { + print "\n"; + if (!$i) { + $totalarray['nbfield']++; + } } + // Ref customer - if (!empty($arrayfields['e.ref_customer']['checked'])) - { - print ''; + if (!empty($arrayfields['e.ref_customer']['checked'])) { + print "\n"; + if (!$i) { + $totalarray['nbfield']++; + } } - // Thirdparty - if (!empty($arrayfields['s.nom']['checked'])) - { - print ''; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['s.town']['checked'])) print ''; - // Zip - if (!empty($arrayfields['s.zip']['checked'])) print ''; - // State - if (!empty($arrayfields['state.nom']['checked'])) - { - print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } + // Zip + if (!empty($arrayfields['s.zip']['checked'])) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } + // State + if (!empty($arrayfields['state.nom']['checked'])) { + print "\n"; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { - print ''; + if (!$i) { + $totalarray['nbfield']++; + } } - // Company type - if (!empty($arrayfields['typent.code']['checked'])) - { - print ''; + if (!$i) { + $totalarray['nbfield']++; + } } // Weight - if (!empty($arrayfields['e.weight']['checked'])) - { - print ''; + if (!$i) { + $totalarray['nbfield']++; + } } - // Date delivery planned - if (!empty($arrayfields['e.date_delivery']['checked'])) - { - print ''; + // Date delivery planed + if (!empty($arrayfields['e.date_delivery']['checked'])) { + print '\n"; } // Tracking number - if (!empty($arrayfields['e.tracking_number']['checked'])) - { - print ''; + if (!empty($arrayfields['e.tracking_number']['checked'])) { + print '\n"; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['l.ref']['checked'])) - { - // Delivery ref - print ''; - } - // Extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + if (!empty($arrayfields['l.ref']['checked']) || !empty($arrayfields['l.date_delivery']['checked'])) { + $shipment->fetchObjectLinked($shipment->id, $shipment->element); + $receiving = ''; + if (is_array($shipment->linkedObjects['delivery']) && count($shipment->linkedObjects['delivery']) > 0) { + $receiving = reset($shipment->linkedObjects['delivery']); + } + + if (!empty($arrayfields['l.ref']['checked'])) { + // Ref + print ''; + } + + if (!empty($arrayfields['l.date_delivery']['checked'])) { + // Date received + print ''."\n"; + } + } + + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters = array('arrayfields'=>$arrayfields); - $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['e.datec']['checked'])) - { - print ''; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['e.tms']['checked'])) - { - print ''; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['e.fk_statut']['checked'])) - { - print ''; + if (!empty($arrayfields['e.fk_statut']['checked'])) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } } - // Status billed - if (!empty($arrayfields['e.billed']['checked'])) - { - print ''; + // Billed + if (!empty($arrayfields['e.billed']['checked'])) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } } + // Action column - print ''; - print "\n"; - - print ''; - if (!empty($arrayfields['e.ref']['checked'])) print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['e.ref_customer']['checked'])) print_liste_field_titre($arrayfields['e.ref_customer']['label'], $_SERVER["PHP_SELF"], "e.ref_customer", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder, 'left '); - if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['e.weight']['checked'])) print_liste_field_titre($arrayfields['e.weight']['label'], $_SERVER["PHP_SELF"], "e.weight", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['e.date_delivery']['checked'])) print_liste_field_titre($arrayfields['e.date_delivery']['label'], $_SERVER["PHP_SELF"], "e.date_delivery", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['e.tracking_number']['checked'])) print_liste_field_titre($arrayfields['e.tracking_number']['label'], $_SERVER["PHP_SELF"], "e.tracking_number", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['l.ref']['checked'])) print_liste_field_titre($arrayfields['l.ref']['label'], $_SERVER["PHP_SELF"], "l.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['l.date_delivery']['checked'])) print_liste_field_titre($arrayfields['l.date_delivery']['label'], $_SERVER["PHP_SELF"], "l.date_delivery", "", $param, '', $sortfield, $sortorder, 'center '); - // Extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; - // Hook fields - $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['e.datec']['checked'])) print_liste_field_titre($arrayfields['e.datec']['label'], $_SERVER["PHP_SELF"], "e.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['e.tms']['checked'])) print_liste_field_titre($arrayfields['e.tms']['label'], $_SERVER["PHP_SELF"], "e.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['e.fk_statut']['checked'])) print_liste_field_titre($arrayfields['e.fk_statut']['label'], $_SERVER["PHP_SELF"], "e.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['e.billed']['checked'])) print_liste_field_titre($arrayfields['e.billed']['label'], $_SERVER["PHP_SELF"], "e.billed", "", $param, '', $sortfield, $sortorder, 'center '); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); - print "\n"; - - $typenArray = $formcompany->typent_array(1); - $i = 0; - $totalarray = array(); - while ($i < min($num, $limit)) - { - $obj = $db->fetch_object($resql); - - $shipment->id = $obj->rowid; - $shipment->ref = $obj->ref; - - $companystatic->id = $obj->socid; - $companystatic->ref = $obj->name; - $companystatic->name = $obj->name; - - $object = new Expedition($db); - $object->fetch($obj->rowid); - - print ''; - - // Ref - if (!empty($arrayfields['e.ref']['checked'])) - { - print "\n"; - if (!$i) $totalarray['nbfield']++; + print '\n"; - if (!$i) $totalarray['nbfield']++; - } - - // Third party - if (!empty($arrayfields['s.nom']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - // Town - if (!empty($arrayfields['s.town']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - // State - if (!empty($arrayfields['state.nom']['checked'])) - { - print "\n"; - if (!$i) $totalarray['nbfield']++; - } - // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - // Weight - if (!empty($arrayfields['e.weight']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - // Date delivery planed - if (!empty($arrayfields['e.date_delivery']['checked'])) - { - print '\n"; - } - // Tracking number - if (!empty($arrayfields['e.tracking_number']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - } - - if (!empty($arrayfields['l.ref']['checked']) || !empty($arrayfields['l.date_delivery']['checked'])) - { - $shipment->fetchObjectLinked($shipment->id, $shipment->element); - $receiving = ''; - if (is_array($shipment->linkedObjects['delivery']) && count($shipment->linkedObjects['delivery']) > 0) $receiving = reset($shipment->linkedObjects['delivery']); - - if (!empty($arrayfields['l.ref']['checked'])) - { - // Ref - print ''; - } - - if (!empty($arrayfields['l.date_delivery']['checked'])) - { - // Date received - print ''."\n"; - } - } - - // Extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - // Fields from hook - $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); - $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (!empty($arrayfields['e.datec']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - // Date modification - if (!empty($arrayfields['e.tms']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - // Status - if (!empty($arrayfields['e.fk_statut']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - // Billed - if (!empty($arrayfields['e.billed']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - - // Action column - print ''; - if (!$i) $totalarray['nbfield']++; - - print "\n"; - - $i++; + print ''; + } + print ''; + if (!$i) { + $totalarray['nbfield']++; } - $db->free($resql); - $parameters = array('arrayfields'=>$arrayfields, 'totalarray' => $totalarray, 'sql'=>$sql); - $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print "\n"; - print "
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); + print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); + print ''; + + print ''; + print '
    '; + print $form->selectDate($search_datedelivery_start ? $search_datedelivery_start : -1, 'search_datedelivery_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); + print '
    '; + print '
    '; + print $form->selectDate($search_datedelivery_end ? $search_datedelivery_end : -1, 'search_datedelivery_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); + print '
    '; + print '
    '; + print ''; + print ''; + print ''; +} +if (!empty($arrayfields['l.date_delivery']['checked'])) { + // Date received + print ''; + print '
    '; + print $form->selectDate($search_datereceipt_start ? $search_datereceipt_start : -1, 'search_datereceipt_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); + print '
    '; + print '
    '; + print $form->selectDate($search_datereceipt_end ? $search_datereceipt_end : -1, 'search_datereceipt_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); + print '
    '; + print '
    '; + print ''; + print ''; + print $form->selectarray('search_status', array('0'=>$langs->trans('StatusSendingDraftShort'), '1'=>$langs->trans('StatusSendingValidatedShort'), '2'=>$langs->trans('StatusSendingProcessedShort')), $search_status, 1); + print ''; + print $form->selectyesno('search_billed', $search_billed, 1, 0, 1); + print ''; +$searchpicto = $form->showFilterAndCheckAddButtons(0); +print $searchpicto; +print '
    '; - print ''; - print '"; + print $shipment->getNomUrl(1); + print "'; - print ''; - print '"; + print $obj->ref_customer; + print "'; - print ''; + + // Third party + if (!empty($arrayfields['s.nom']['checked'])) { + print ''; + print $companystatic->getNomUrl(1); print ''; - print ''; + if (!empty($arrayfields['s.town']['checked'])) { + print ''; + print $obj->town; print ''; + print $obj->zip; + print '".$obj->state_name."'; - print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); + if (!empty($arrayfields['country.code_iso']['checked'])) { + print ''; + $tmparray = getCountry($obj->fk_pays, 'all'); + print $tmparray['label']; print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); + // Type ent + if (!empty($arrayfields['typent.code']['checked'])) { + print ''; + if (isset($typenArray[$obj->typent_code])) { + print $typenArray[$obj->typent_code]; + } print ''; - + if (!empty($arrayfields['e.weight']['checked'])) { + print ''; + if (empty($object->trueWeight)) { + $tmparray = $object->getTotalWeightVolume(); + print showDimensionInBestUnit($tmparray['weight'], 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND) ? $conf->global->MAIN_WEIGHT_DEFAULT_ROUND : -1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? $conf->global->MAIN_WEIGHT_DEFAULT_UNIT : 'no'); + print $form->textwithpicto('', $langs->trans('EstimatedWeight'), 1); + } else { + print $object->trueWeight; + print ($object->trueWeight && $object->weight_units != '') ? ' '.measuringUnitString(0, "weight", $object->weight_units) : ''; + } print ''; - print '
    '; - print $langs->trans('From').' '; - print $form->selectDate($search_delivery_start ? $search_delivery_start : -1, 'search_delivery_start', 0, 0, 1); - print '
    '; - print '
    '; - print $langs->trans('to').' '; - print $form->selectDate($search_delivery_end ? $search_delivery_end : -1, 'search_delivery_end', 0, 0, 1); - print '
    '; - print '
    '; + print dol_print_date($db->jdate($obj->delivery_date), "dayhour"); + /*$now = time(); + if ( ($now - $db->jdate($obj->date_expedition)) > $conf->warnings->lim && $obj->statutid == 1 ) + { + }*/ + print "'; - print ''; - print ''.$obj->tracking_number."'; - print ''; - } - if (!empty($arrayfields['l.date_delivery']['checked'])) - { - // Date received - print ''; - print '
    '; - print $langs->trans('From').' '; - print $form->selectDate($search_receipt_start ? $search_receipt_start : -1, 'search_receipt_start', 0, 0, 1); - print '
    '; - print '
    '; - print $langs->trans('to').' '; - print $form->selectDate($search_receipt_end ? $search_receipt_end : -1, 'search_receipt_end', 0, 0, 1); - print '
    '; - print '
    '; + print !empty($receiving) ? $receiving->getNomUrl($db) : ''; + print ''; + print dol_print_date($db->jdate($obj->date_reception), "day"); + print ''; + if (!empty($arrayfields['e.datec']['checked'])) { + print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print ''; + if (!empty($arrayfields['e.tms']['checked'])) { + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print ''; - print $form->selectarray('search_status', array('0'=>$langs->trans('StatusSendingDraftShort'), '1'=>$langs->trans('StatusSendingValidatedShort'), '2'=>$langs->trans('StatusSendingProcessedShort')), $search_status, 1); - print ''.$shipment->LibStatut($obj->fk_statut, 5).''; - print $form->selectyesno('search_billed', $search_billed, 1, 0, 1); - print ''.yn($obj->billed).''; - $searchpicto = $form->showFilterAndCheckAddButtons(0); - print $searchpicto; - print '
    "; - print $shipment->getNomUrl(1); - 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; } - - // Ref customer - if (!empty($arrayfields['e.ref_customer']['checked'])) - { - print ""; - print $obj->ref_customer; - print "'; - print $companystatic->getNomUrl(1); - print ''; - print $obj->town; - print ''; - print $obj->zip; - print '".$obj->state_name."'; - $tmparray = getCountry($obj->fk_pays, 'all'); - print $tmparray['label']; - print ''; - if (isset($typenArray[$obj->typent_code])) print $typenArray[$obj->typent_code]; - print ''; - if (empty($object->trueWeight)) - { - $tmparray = $object->getTotalWeightVolume(); - print showDimensionInBestUnit($tmparray['weight'], 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND) ? $conf->global->MAIN_WEIGHT_DEFAULT_ROUND : -1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? $conf->global->MAIN_WEIGHT_DEFAULT_UNIT : 'no'); - print $form->textwithpicto('', $langs->trans('EstimatedWeight'), 1); - } else { - print $object->trueWeight; - print ($object->trueWeight && $object->weight_units != '') ? ' '.measuringUnitString(0, "weight", $object->weight_units) : ''; - } - print ''; - print dol_print_date($db->jdate($obj->delivery_date), "dayhour"); - /*$now = time(); - if ( ($now - $db->jdate($obj->date_expedition)) > $conf->warnings->lim && $obj->statutid == 1 ) - { - }*/ - print "'.$obj->tracking_number."'; - print !empty($receiving) ? $receiving->getNomUrl($db) : ''; - print ''; - print dol_print_date($db->jdate($obj->date_reception), "day"); - print ''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print ''.$shipment->LibStatut($obj->fk_statut, 5).''.yn($obj->billed).''; - 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; - print ''; - } - print '
    "; - print "
    "; - print ''; - - $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; - - // Show list of available documents - $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource .= str_replace('&', '&', $param); - - $filedir = $diroutputmassaction; - $genallowed = $user->rights->expedition->lire; - $delallowed = $user->rights->expedition->creer; - $title = ''; - - print $formfile->showdocuments('massfilesarea_sendings', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); -} else { - dol_print_error($db); + $i++; } +// If no record found +if ($num == 0) { + $colspan = 1; + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } + print ''.$langs->trans("NoRecordFound").''; +} + +$db->free($resql); + +$parameters = array('arrayfields'=>$arrayfields, 'totalarray' => $totalarray, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print ""; +print ""; +print ''; + +$hidegeneratedfilelistifempty = 1; +if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; +} + +// Show list of available documents +$urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; +$urlsource .= str_replace('&', '&', $param); + +$filedir = $diroutputmassaction; +$genallowed = $user->rights->expedition->lire; +$delallowed = $user->rights->expedition->creer; +$title = ''; + +print $formfile->showdocuments('massfilesarea_sendings', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); + // End of page llxFooter(); $db->close(); diff --git a/htdocs/expedition/note.php b/htdocs/expedition/note.php index 6397a301e59..c8209910b48 100644 --- a/htdocs/expedition/note.php +++ b/htdocs/expedition/note.php @@ -41,30 +41,28 @@ $action = GETPOST('action', 'aZ09'); // Security check $socid = ''; -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, $origin, $origin_id); $object = new Expedition($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch($id, $ref); $object->fetch_thirdparty(); - if (!empty($object->origin)) - { + if (!empty($object->origin)) { $typeobject = $object->origin; $origin = $object->origin; $object->fetch_origin(); } // Linked documents - if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) - { + if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) { $objectsrc = new Commande($db); $objectsrc->fetch($object->$typeobject->id); } - if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) - { + if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) { $objectsrc = new Propal($db); $objectsrc->fetch($object->$typeobject->id); } @@ -88,8 +86,7 @@ llxHeader(); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $head = shipping_prepare_head($object); print dol_get_fiche_head($head, 'note', $langs->trans("Shipment"), -1, 'sending'); diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php index 1c4e5bf5c25..66efd5c4ca7 100644 --- a/htdocs/expedition/shipment.php +++ b/htdocs/expedition/shipment.php @@ -37,9 +37,15 @@ if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } -if (!empty($conf->stock->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; -if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; -if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +if (!empty($conf->stock->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; +} +if (!empty($conf->propal->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +} +if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('orders', "companies", "bills", 'propal', 'deliveries', 'stocks', "productbatch", 'incoterm', 'other')); @@ -53,7 +59,9 @@ $hookmanager->initHooks(array('ordershipmentcard')); // Security check $socid = 0; -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'commande', $id); $object = new Commande($db); @@ -74,93 +82,86 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ $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)) -{ +if (empty($reshook)) { // Categorisation dans projet - if ($action == 'classin') - { + if ($action == 'classin') { $object = new Commande($db); $object->fetch($id); $object->setProject(GETPOST('projectid', 'int')); } - if ($action == 'confirm_cloture' && GETPOST('confirm', 'alpha') == 'yes') - { + if ($action == 'confirm_cloture' && GETPOST('confirm', 'alpha') == 'yes') { $object = new Commande($db); $object->fetch($id); $result = $object->cloture($user); - } - - // Positionne ref commande client - elseif ($action == 'setref_client' && $user->rights->commande->creer) { + } elseif ($action == 'setref_client' && $user->rights->commande->creer) { + // Positionne ref commande client $result = $object->set_ref_client($user, GETPOST('ref_client')); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } } - if ($action == 'setdatedelivery' && $user->rights->commande->creer) - { + if ($action == 'setdatedelivery' && $user->rights->commande->creer) { //print "x ".$_POST['liv_month'].", ".$_POST['liv_day'].", ".$_POST['liv_year']; $datedelivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int')); $object->fetch($id); $result = $object->setDeliveryDate($user, $datedelivery); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } } /* - if ($action == 'setdeliveryaddress' && $user->rights->commande->creer) - { - $object = new Commande($db); - $object->fetch($id); - $object->setDeliveryAddress(GETPOST('delivery_address_id','int')); - if ($result < 0) - setEventMessages($object->error, $object->errors, 'errors'); - } - */ - if ($action == 'setmode' && $user->rights->commande->creer) + if ($action == 'setdeliveryaddress' && $user->rights->commande->creer) { $object = new Commande($db); $object->fetch($id); - $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); + $object->setDeliveryAddress(GETPOST('delivery_address_id','int')); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } + */ + if ($action == 'setmode' && $user->rights->commande->creer) { + $object = new Commande($db); + $object->fetch($id); + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } if ($action == 'setavailability' && $user->rights->commande->creer) { $object = new Commande($db); $object->fetch($id); $result = $object->availability(GETPOST('availability_id')); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } if ($action == 'setdemandreason' && $user->rights->commande->creer) { $object = new Commande($db); $object->fetch($id); $result = $object->demand_reason(GETPOST('demand_reason_id')); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } - if ($action == 'setconditions' && $user->rights->commande->creer) - { + if ($action == 'setconditions' && $user->rights->commande->creer) { $object = new Commande($db); $object->fetch($id); $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); - } - - // Set incoterm - elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { + } + } elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) { + // Set incoterm $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -172,8 +173,9 @@ if (empty($reshook)) $object = new Commande($db); $object->fetch($id); $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } // warehouse @@ -181,35 +183,35 @@ if (empty($reshook)) $object = new Commande($db); $object->fetch($id); $result = $object->setWarehouse(GETPOST('warehouse_id', 'int')); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('SHIPMENT_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } - if ($action == 'set_thirdparty' && $user->rights->commande->creer) - { + if ($action == 'set_thirdparty' && $user->rights->commande->creer) { $object->fetch($id); $object->setValueFrom('fk_soc', $socid, '', '', 'date', '', $user, 'ORDER_MODIFY'); @@ -227,16 +229,16 @@ if (empty($reshook)) $form = new Form($db); $formfile = new FormFile($db); $formproduct = new FormProduct($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} llxHeader('', $langs->trans('OrderCard'), ''); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object = new Commande($db); - if ($object->fetch($id, $ref) > 0) - { + if ($object->fetch($id, $ref) > 0) { $object->loadExpeditions(1); $product_static = new Product($db); @@ -256,16 +258,18 @@ if ($id > 0 || !empty($ref)) $formconfirm = ''; // Confirm validation - if ($action == 'cloture') - { + if ($action == 'cloture') { $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$id, $langs->trans("CloseShipment"), $langs->trans("ConfirmCloseShipment"), "confirm_cloture"); } // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -283,12 +287,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$soc->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { if ($action != 'classify') { $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; } @@ -366,11 +368,12 @@ if ($id > 0 || !empty($ref)) print $langs->trans('DateDeliveryPlanned'); print ''; - if ($action != 'editdate_livraison') print 'id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).''; + if ($action != 'editdate_livraison') { + print 'id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).''; + } print ''; print ''; - if ($action == 'editdate_livraison') - { + if ($action == 'editdate_livraison') { print '
    '; print ''; print ''; @@ -395,8 +398,9 @@ if ($id > 0 || !empty($ref)) print ''; - if ($action != 'editshippingmethod' && $user->rights->expedition->creer) + if ($action != 'editshippingmethod' && $user->rights->expedition->creer) { print ''; + } print '
    '; print $langs->trans('SendingMethod'); print 'id.'">'.img_edit($langs->trans('SetShippingMode'), 1).'
    '; print ''; if ($action == 'editshippingmethod') { @@ -415,8 +419,9 @@ if ($id > 0 || !empty($ref)) print ''; - if ($action != 'editwarehouse' && $user->rights->commande->creer) + if ($action != 'editwarehouse' && $user->rights->commande->creer) { print ''; + } print '
    '; print $langs->trans('Warehouse'); print 'id.'">'.img_edit($langs->trans('SetWarehouse'), 1).'
    '; print ''; if ($action == 'editwarehouse') { @@ -471,8 +476,9 @@ if ($id > 0 || !empty($ref)) print ''; - if ($action != 'editavailability') + if ($action != 'editavailability') { print ''; + } print '
    '; print $langs->trans('AvailabilityPeriod'); print 'id.'">'.img_edit($langs->trans('SetAvailability'), 1).'
    '; print ''; if ($action == 'editavailability') { @@ -487,8 +493,9 @@ if ($id > 0 || !empty($ref)) print ''; - if ($action != 'editdemandreason') + if ($action != 'editdemandreason') { print ''; + } print '
    '; print $langs->trans('Source'); print 'id.'">'.img_edit($langs->trans('SetDemandReason'), 1).'
    '; print ''; if ($action == 'editdemandreason') { @@ -500,8 +507,7 @@ if ($id > 0 || !empty($ref)) $tmparray = $object->getTotalWeightVolume(); $totalWeight = $tmparray['weight']; $totalVolume = $tmparray['volume']; - if ($totalWeight || $totalVolume) - { + if ($totalWeight || $totalVolume) { print ''.$langs->trans("CalculatedWeight").''; print ''; print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND) ? $conf->global->MAIN_WEIGHT_DEFAULT_ROUND : -1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? $conf->global->MAIN_WEIGHT_DEFAULT_UNIT : 'no'); @@ -515,19 +521,20 @@ if ($id > 0 || !empty($ref)) // TODO How record was recorded OrderMode (llx_c_input_method) // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print ''; print '
    '; print $langs->trans('IncotermLabel'); print ''; - if ($user->rights->commande->creer) print ''.img_edit().''; - else print ' '; + if ($user->rights->commande->creer) { + print ''.img_edit().''; + } else { + print ' '; + } print '
    '; print ''; print ''; - if ($action != 'editincoterm') - { + if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1); } else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); @@ -551,8 +558,7 @@ if ($id > 0 || !empty($ref)) print ''; - if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) - { + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { // Multicurrency Amount HT print ''; print ''; @@ -579,13 +585,11 @@ if ($id > 0 || !empty($ref)) print ''; // Amount Local Taxes - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) // Localtax1 - { + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { // Localtax1 print ''; print ''; } - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) // Localtax2 IRPF - { + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { // Localtax2 IRPF print ''; print ''; } @@ -627,8 +631,7 @@ if ($id > 0 || !empty($ref)) //print $sql; dol_syslog("shipment.php", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -637,8 +640,7 @@ if ($id > 0 || !empty($ref)) print ''; print ''; print ''; - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print ''; } else { print ''; @@ -647,32 +649,34 @@ if ($id > 0 || !empty($ref)) $toBeShipped = array(); $toBeShippedTotal = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $parameters = array('i' => $i, 'line' => $objp, 'num' => $num); $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $object, $action); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Show product and description $type = isset($objp->type) ? $objp->type : $objp->product_type; // Try to enhance type detection using date_start and date_end for free lines where type // was not saved. - if (!empty($objp->date_start)) $type = 1; - if (!empty($objp->date_end)) $type = 1; + if (!empty($objp->date_start)) { + $type = 1; + } + if (!empty($objp->date_end)) { + $type = 1; + } print ''; // Product label - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { // Define output language - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $object->fetch_thirdparty(); $prod = new Product($db); @@ -682,16 +686,21 @@ if ($id > 0 || !empty($ref)) $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && !empty($_REQUEST['lang_id'])) $newlang = $_REQUEST['lang_id']; - if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + if (empty($newlang) && !empty($_REQUEST['lang_id'])) { + $newlang = $_REQUEST['lang_id']; + } + if (empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $objp->product_label; - } else $label = (!empty($objp->label) ? $objp->label : $objp->product_label); + } else { + $label = (!empty($objp->label) ? $objp->label : $objp->product_label); + } print ''; } else { print "'; - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { $product = new Product($db); $product->fetch($objp->fk_product); $product->load_stock('warehouseopen'); } - if ($objp->fk_product > 0 && ($type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) && !empty($conf->stock->enabled)) - { + if ($objp->fk_product > 0 && ($type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) && !empty($conf->stock->enabled)) { print ''; @@ -793,8 +800,7 @@ if ($id > 0 || !empty($ref)) print "\n"; // Show subproducts lines - if ($objp->fk_product > 0 && !empty($conf->global->PRODUIT_SOUSPRODUITS)) - { + if ($objp->fk_product > 0 && !empty($conf->global->PRODUIT_SOUSPRODUITS)) { // Set tree of subproducts in product->sousprods $product->get_sousproduits_arbo(); //var_dump($product->sousprods);exit; @@ -802,13 +808,10 @@ if ($id > 0 || !empty($ref)) // Define a new tree with quantiies recalculated $prods_arbo = $product->get_arbo_each_prod($qtyProdCom); //var_dump($prods_arbo); - if (count($prods_arbo) > 0) - { - foreach ($prods_arbo as $key => $value) - { + if (count($prods_arbo) > 0) { + foreach ($prods_arbo as $key => $value) { $img = ''; - if ($value['stock'] < $value['stock_alert']) - { + if ($value['stock'] < $value['stock_alert']) { $img = img_warning($langs->trans("StockTooLow")); } print ''; @@ -824,8 +827,7 @@ if ($id > 0 || !empty($ref)) } $db->free($resql); - if (!$num) - { + if (!$num) { print ''; - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { //print ''; //print ''; } //print ''; diff --git a/htdocs/expedition/stats/index.php b/htdocs/expedition/stats/index.php index fcc0d26f81c..151edbdba2b 100644 --- a/htdocs/expedition/stats/index.php +++ b/htdocs/expedition/stats/index.php @@ -34,8 +34,7 @@ $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); $userid = GETPOST('userid', 'int'); $socid = GETPOST('socid', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -71,8 +70,7 @@ $data = $stats->getNbByMonthWithPrevYear($endyear, $startyear); // $data = array(array('Lib',val1,val2,val3),...) -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filenamenb = $dir.'/shipmentsnbinyear-'.$user->id.'-'.$year.'.png'; } else { $filenamenb = $dir.'/shipmentsnbinyear-'.$year.'.png'; @@ -80,12 +78,10 @@ if (!$user->rights->societe->client->voir || $user->socid) $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -111,36 +107,36 @@ $data = $stats->getAmountByMonthWithPrevYear($endyear,$startyear); if (!$user->rights->societe->client->voir || $user->socid) { - $filenameamount = $dir.'/shipmentsamountinyear-'.$user->id.'-'.$year.'.png'; + $filenameamount = $dir.'/shipmentsamountinyear-'.$user->id.'-'.$year.'.png'; } else { - $filenameamount = $dir.'/shipmentsamountinyear-'.$year.'.png'; + $filenameamount = $dir.'/shipmentsamountinyear-'.$year.'.png'; } $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); if (! $mesg) { - $px2->SetData($data); - $i=$startyear;$legend=array(); - while ($i <= $endyear) - { - $legend[]=$i; - $i++; - } - $px2->SetLegend($legend); - $px2->SetMaxValue($px2->GetCeilMaxValue()); - $px2->SetMinValue(min(0,$px2->GetFloorMinValue())); - $px2->SetWidth($WIDTH); - $px2->SetHeight($HEIGHT); - $px2->SetYLabel($langs->trans("AmountOfShipments")); - $px2->SetShading(3); - $px2->SetHorizTickIncrement(1); - $px2->mode='depth'; - $px2->SetTitle($langs->trans("AmountOfShipmentsByMonthHT")); + $px2->SetData($data); + $i=$startyear;$legend=array(); + while ($i <= $endyear) + { + $legend[]=$i; + $i++; + } + $px2->SetLegend($legend); + $px2->SetMaxValue($px2->GetCeilMaxValue()); + $px2->SetMinValue(min(0,$px2->GetFloorMinValue())); + $px2->SetWidth($WIDTH); + $px2->SetHeight($HEIGHT); + $px2->SetYLabel($langs->trans("AmountOfShipments")); + $px2->SetShading(3); + $px2->SetHorizTickIncrement(1); + $px2->mode='depth'; + $px2->SetTitle($langs->trans("AmountOfShipmentsByMonthHT")); - $px2->draw($filenameamount,$fileurlamount); + $px2->draw($filenameamount,$fileurlamount); } */ @@ -149,36 +145,36 @@ $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); if (!$user->rights->societe->client->voir || $user->socid) { - $filename_avg = $dir.'/shipmentsaverage-'.$user->id.'-'.$year.'.png'; + $filename_avg = $dir.'/shipmentsaverage-'.$user->id.'-'.$year.'.png'; } else { - $filename_avg = $dir.'/shipmentsaverage-'.$year.'.png'; + $filename_avg = $dir.'/shipmentsaverage-'.$year.'.png'; } $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); if (! $mesg) { - $px3->SetData($data); - $i=$startyear;$legend=array(); - while ($i <= $endyear) - { - $legend[]=$i; - $i++; - } - $px3->SetLegend($legend); - $px3->SetYLabel($langs->trans("AmountAverage")); - $px3->SetMaxValue($px3->GetCeilMaxValue()); - $px3->SetMinValue($px3->GetFloorMinValue()); - $px3->SetWidth($WIDTH); - $px3->SetHeight($HEIGHT); - $px3->SetShading(3); - $px3->SetHorizTickIncrement(1); - $px3->mode='depth'; - $px3->SetTitle($langs->trans("AmountAverage")); + $px3->SetData($data); + $i=$startyear;$legend=array(); + while ($i <= $endyear) + { + $legend[]=$i; + $i++; + } + $px3->SetLegend($legend); + $px3->SetYLabel($langs->trans("AmountAverage")); + $px3->SetMaxValue($px3->GetCeilMaxValue()); + $px3->SetMinValue($px3->GetFloorMinValue()); + $px3->SetWidth($WIDTH); + $px3->SetHeight($HEIGHT); + $px3->SetShading(3); + $px3->SetHorizTickIncrement(1); + $px3->mode='depth'; + $px3->SetTitle($langs->trans("AmountAverage")); - $px3->draw($filename_avg,$fileurl_avg); + $px3->draw($filename_avg,$fileurl_avg); } */ @@ -191,7 +187,9 @@ foreach ($data as $val) { $arrayyears[$val['year']] = $val['year']; } } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; $head = array(); @@ -228,8 +226,12 @@ print '
    '; print ''; // Year print '
    '; @@ -250,11 +252,9 @@ print '';*/ print ''; $oldyear = 0; -foreach ($data as $val) -{ +foreach ($data as $val) { $year = $val['year']; - while (!empty($year) && $oldyear > $year + 1) - { // If we have empty year + while (!empty($year) && $oldyear > $year + 1) { // If we have empty year $oldyear--; @@ -292,12 +292,14 @@ print '
    '; // Show graphs 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)).'
    '.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency).'
    '.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'
    '.$langs->trans("QtyOrdered").''.$langs->trans("QtyShipped").''.$langs->trans("KeepToShip").''.$langs->trans("RealStock").' 
    '; print ''; // ancre pour retourner sur la ligne @@ -725,16 +734,18 @@ if ($id > 0 || !empty($ref)) print_date_range($db->jdate($objp->date_start), $db->jdate($objp->date_end)); // Add description in form - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { print ($objp->description && $objp->description != $objp->product_label) ? '
    '.dol_htmlentitiesbr($objp->description) : ''; } print '
    "; - if ($type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if ($type == 1) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($objp->label)) { $text .= ' '.$objp->label.''; @@ -761,8 +772,7 @@ if ($id > 0 || !empty($ref)) // Qty remains to ship print ''; - if ($type == 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if ($type == 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $toBeShipped[$objp->fk_product] = $objp->qty - $qtyAlreadyShipped; $toBeShippedTotal += $toBeShipped[$objp->fk_product]; print $toBeShipped[$objp->fk_product]; @@ -771,19 +781,16 @@ if ($id > 0 || !empty($ref)) } print ''; print $product->stock_reel; - if ($product->stock_reel < $toBeShipped[$objp->fk_product]) - { + if ($product->stock_reel < $toBeShipped[$objp->fk_product]) { print ' '.img_warning($langs->trans("StockTooLow")); } print '
          -> '.$value['fullpath'].' ('.$value['nb'].')
    '.$langs->trans("NoArticleOfTypeProduct").'
    '; } @@ -841,18 +843,14 @@ if ($id > 0 || !empty($ref)) * Boutons Actions */ - if (empty($user->socid)) - { + if (empty($user->socid)) { print '
    '; // Bouton expedier sans gestion des stocks - if (empty($conf->stock->enabled) && ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED)) - { - if ($user->rights->expedition->creer) - { + if (empty($conf->stock->enabled) && ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED)) { + if ($user->rights->expedition->creer) { print ''.$langs->trans("CreateShipment").''; - if ($toBeShippedTotal <= 0) - { + if ($toBeShippedTotal <= 0) { print ' '.img_warning($langs->trans("WarningNoQtyLeftToSend")); } } else { @@ -865,15 +863,12 @@ if ($id > 0 || !empty($ref)) // Bouton expedier avec gestion des stocks - if (!empty($conf->stock->enabled) && $object->statut == Commande::STATUS_DRAFT) - { + if (!empty($conf->stock->enabled) && $object->statut == Commande::STATUS_DRAFT) { print $langs->trans("ValidateOrderFirstBeforeShipment"); } - if (!empty($conf->stock->enabled) && ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED)) - { - if ($user->rights->expedition->creer) - { + if (!empty($conf->stock->enabled) && ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED)) { + if ($user->rights->expedition->creer) { //print load_fiche_titre($langs->trans("CreateShipment")); print '
    '; @@ -890,23 +885,20 @@ if ($id > 0 || !empty($ref)) //print '
    '; print $langs->trans("WarehouseSource"); //print ''; print $formproduct->selectWarehouses(!empty($object->warehouse_id) ? $object->warehouse_id : 'ifone', 'entrepot_id', '', 1, 0, 0, '', 0, 0, array(), 'minwidth200'); - if (count($formproduct->cache_warehouses) <= 0) - { + if (count($formproduct->cache_warehouses) <= 0) { print '   '.$langs->trans("WarehouseSourceNotDefined").' '.$langs->trans("AddOne").''; } //print ''; print ''; - if ($toBeShippedTotal <= 0) - { + if ($toBeShippedTotal <= 0) { print ' '.img_warning($langs->trans("WarningNoQtyLeftToSend")); } //print '
    '.$langs->trans("Year").''; - if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; - if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} +if (!in_array($nowyear, $arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print '
    '.$langs->trans("AmountAverage").'
    '; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); print "
    \n"; /*print $px2->show(); - print "
    \n"; - print $px3->show();*/ + print "
    \n"; + print $px3->show();*/ } print '
    '; @@ -324,17 +326,17 @@ $sql.= " GROUP BY dm DESC"; $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $row = $db->fetch_row($resql); - $nbproduct = $row[0]; - $year = $row[1]; - print ""; - print ''.$year.''.$nbproduct.''; - $i++; - } + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $row = $db->fetch_row($resql); + $nbproduct = $row[0]; + $year = $row[1]; + print ""; + print ''.$year.''.$nbproduct.''; + $i++; + } } $db->free($resql); diff --git a/htdocs/expedition/tpl/linkedobjectblock.tpl.php b/htdocs/expedition/tpl/linkedobjectblock.tpl.php index 897e35b8813..b00d63eaba1 100644 --- a/htdocs/expedition/tpl/linkedobjectblock.tpl.php +++ b/htdocs/expedition/tpl/linkedobjectblock.tpl.php @@ -17,8 +17,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -37,48 +36,49 @@ $langs->load("sendings"); $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - - trans("Shipment"); ?> - getNomUrl(1); ?> - - date_delivery, 'day'); ?> - "> + trans("Shipment"); ?> + getNomUrl(1); ?> + + date_delivery, 'day'); ?> + rights->expedition->lire) { $total = $total + $objectlink->total_ht; echo price($objectlink->total_ht); } ?> - getLibStatut(3); ?> - - getLibStatut(3); ?> + + element != 'commande') { ?> - ">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?> - id.'&action=dellink&dellinkid='.$key; ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?> + - - + 1) { ?> - - trans("Total"); ?> - - - - - - - - "> + trans("Total"); ?> + + + + + + + + \n"; diff --git a/htdocs/expensereport/ajax/ajaxik.php b/htdocs/expensereport/ajax/ajaxik.php index 413bc061fbf..72c38959ef8 100644 --- a/htdocs/expensereport/ajax/ajaxik.php +++ b/htdocs/expensereport/ajax/ajaxik.php @@ -22,12 +22,24 @@ * \brief File to return Ajax response on third parties request */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} $res = 0; require '../../main.inc.php'; @@ -50,20 +62,25 @@ $fk_expense = GETPOST('fk_expense'); $fk_c_exp_tax_cat = GETPOST('fk_c_exp_tax_cat'); -if (empty($fk_expense) || $fk_expense < 0) echo json_encode(array('error' => $langs->transnoentitiesnoconv('ErrorBadValueForParameter', $fk_expense, 'fk_expense'))); -elseif (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) echo json_encode(array('error' => $langs->transnoentitiesnoconv('ErrorBadValueForParameter', $fk_c_exp_tax_cat, 'fk_c_exp_tax_cat'))); -else { +if (empty($fk_expense) || $fk_expense < 0) { + echo json_encode(array('error' => $langs->transnoentitiesnoconv('ErrorBadValueForParameter', $fk_expense, 'fk_expense'))); +} elseif (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) { + echo json_encode(array('error' => $langs->transnoentitiesnoconv('ErrorBadValueForParameter', $fk_c_exp_tax_cat, 'fk_c_exp_tax_cat'))); +} else { // @see ndfp.class.php:3576 (method: compute_total_km) $expense = new ExpenseReport($db); - if ($expense->fetch($fk_expense) <= 0) echo json_encode(array('error' => $langs->transnoentitiesnoconv('ErrorRecordNotFound'), 'fk_expense' => $fk_expense)); - else { + if ($expense->fetch($fk_expense) <= 0) { + echo json_encode(array('error' => $langs->transnoentitiesnoconv('ErrorRecordNotFound'), 'fk_expense' => $fk_expense)); + } else { $userauthor = new User($db); - if ($userauthor->fetch($expense->fk_user_author) <= 0) echo json_encode(array('error' => $langs->transnoentitiesnoconv('ErrorRecordNotFound'), 'fk_user_author' => $expense->fk_user_author)); - else { + if ($userauthor->fetch($expense->fk_user_author) <= 0) { + echo json_encode(array('error' => $langs->transnoentitiesnoconv('ErrorRecordNotFound'), 'fk_user_author' => $expense->fk_user_author)); + } else { $range = ExpenseReportIk::getRangeByUser($userauthor, $fk_c_exp_tax_cat); - if (empty($range)) echo json_encode(array('error' => $langs->transnoentitiesnoconv('ErrorRecordNotFound'), 'range' => $range)); - else { + if (empty($range)) { + echo json_encode(array('error' => $langs->transnoentitiesnoconv('ErrorRecordNotFound'), 'range' => $range)); + } else { $ikoffset = price($range->ikoffset, 0, $langs, 1, -1, -1, $conf->currency); echo json_encode(array('up' => $range->coef, 'ikoffset' => $range->ikoffset, 'title' => $langs->transnoentitiesnoconv('ExpenseRangeOffset', $offset), 'comment' => 'offset should be apply on addline or updateline')); } diff --git a/htdocs/expensereport/ajax/ajaxprojet.php b/htdocs/expensereport/ajax/ajaxprojet.php index 62ceb504dac..8549d62fa62 100644 --- a/htdocs/expensereport/ajax/ajaxprojet.php +++ b/htdocs/expensereport/ajax/ajaxprojet.php @@ -24,12 +24,24 @@ * \brief File to return Ajax response on third parties request */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} $res = 0; require '../../main.inc.php'; @@ -52,21 +64,20 @@ dol_syslog(join(',', $_GET)); // Generation liste des projets -if (GETPOST('fk_projet') != '') -{ +if (GETPOST('fk_projet') != '') { $return_arr = array(); $sql = "SELECT p.rowid, p.ref, p.title, s.nom"; $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; - if (!empty($_GET["fk_projet"])) $sql .= " WHERE p.ref LIKE '%".$db->escape($_GET["fk_projet"])."%' OR p.title LIKE '%".$db->escape($_GET["fk_projet"])."%' OR s.nom LIKE '%".$db->escape($_GET["fk_projet"])."%'"; // Add other filters + if (!empty($_GET["fk_projet"])) { + $sql .= " WHERE p.ref LIKE '%".$db->escape($_GET["fk_projet"])."%' OR p.title LIKE '%".$db->escape($_GET["fk_projet"])."%' OR s.nom LIKE '%".$db->escape($_GET["fk_projet"])."%'"; // Add other filters + } $sql .= " ORDER BY p.ref ASC"; $resql = $db->query($sql); - if ($resql) - { - while ($row = $db->fetch_array($resql)) - { + if ($resql) { + while ($row = $db->fetch_array($resql)) { $label = $row['ref'].' - '.$row['title']; $row_array['label'] = $label; $row_array['value'] = $label; diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php index 6ff4c418988..020c34dc0c6 100644 --- a/htdocs/expensereport/card.php +++ b/htdocs/expensereport/card.php @@ -69,7 +69,9 @@ $childids = $user->getAllChildIds(1); // Security check $id = GETPOST("id", 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', $id, 'expensereport'); @@ -77,8 +79,7 @@ $result = restrictedArea($user, 'expensereport', $id, 'expensereport'); $rootfordata = DOL_DATA_ROOT; $rootforuser = DOL_DATA_ROOT; // If multicompany module is enabled, we redefine the root of data -if (!empty($conf->multicompany->enabled) && !empty($conf->entity) && $conf->entity > 1) -{ +if (!empty($conf->multicompany->enabled) && !empty($conf->entity) && $conf->entity > 1) { $rootfordata .= '/'.$conf->entity; } $conf->expensereport->dir_output = $rootfordata.'/expensereport'; @@ -114,14 +115,16 @@ $permissiontoadd = $user->rights->expensereport->creer; // Used by the include o $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref); -if ($object->id > 0) -{ +if ($object->id > 0) { // Check current user can read this expense report $canread = 0; - if (!empty($user->rights->expensereport->readall)) $canread = 1; - if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) $canread = 1; - if (!$canread) - { + if (!empty($user->rights->expensereport->readall)) { + $canread = 1; + } + if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) { + $canread = 1; + } + if (!$canread) { accessforbidden(); } } @@ -133,14 +136,13 @@ if ($object->id > 0) $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)) -{ - if ($cancel) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -160,10 +162,12 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; - if (GETPOSTISSET('sendit')) // If we just submit a file - { - if ($action == 'updateline') $action = 'editline'; // To avoid to make the updateline now - else $action = ''; // To avoid to make the addline now + if (GETPOSTISSET('sendit')) { // If we just submit a file + if ($action == 'updateline') { + $action = 'editline'; // To avoid to make the updateline now + } else { + $action = ''; // To avoid to make the addline now + } } include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once @@ -173,20 +177,16 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->expensereport->creer) - { - if (1 == 0 && !GETPOST('clone_content', 'alpha') && !GETPOST('clone_receivers', 'alpha')) - { + if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->expensereport->creer) { + if (1 == 0 && !GETPOST('clone_content', 'alpha') && !GETPOST('clone_receivers', 'alpha')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { - if ($object->id > 0) - { + if ($object->id > 0) { // Because createFromClone modifies the object, we must clone it so that we can restore it later if it fails $orig = clone $object; $result = $object->createFromClone($user, GETPOST('fk_user_author', 'int')); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit; } else { @@ -198,13 +198,11 @@ if (empty($reshook)) } } - if ($action == 'confirm_delete' && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->supprimer) - { + if ($action == 'confirm_delete' && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->supprimer) { $object = new ExpenseReport($db); $result = $object->fetch($id); $result = $object->delete($user); - if ($result >= 0) - { + if ($result >= 0) { header("Location: index.php"); exit; } else { @@ -212,8 +210,7 @@ if (empty($reshook)) } } - if ($action == 'add' && $user->rights->expensereport->creer) - { + if ($action == 'add' && $user->rights->expensereport->creer) { $error = 0; $object = new ExpenseReport($db); @@ -222,13 +219,17 @@ if (empty($reshook)) $object->date_fin = $date_end; $object->fk_user_author = GETPOST('fk_user_author', 'int'); - if (!($object->fk_user_author > 0)) $object->fk_user_author = $user->id; + if (!($object->fk_user_author > 0)) { + $object->fk_user_author = $user->id; + } // Check that expense report is for a user inside the hierarchy or advanced permission for all is set - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->expensereport->creer)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->expensereport->writeall_advance))) { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->expensereport->creer)) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->expensereport->creer) && empty($user->rights->expensereport->writeall_advance))) { $error++; setEventMessages($langs->trans("NotEnoughPermission"), null, 'errors'); - } else { + } + if (!$error) { if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance)) { if (!in_array($object->fk_user_author, $childids)) { $error++; @@ -246,31 +247,28 @@ if (empty($reshook)) $object->note_public = GETPOST('note_public', 'restricthtml'); $object->note_private = GETPOST('note_private', 'restricthtml'); // Fill array 'array_options' with data from add form - if (!$error) - { + if (!$error) { $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } - if (!$error && empty($conf->global->EXPENSEREPORT_ALLOW_OVERLAPPING_PERIODS) && $object->periode_existe($fuser, $object->date_debut, $object->date_fin)) - { + if (!$error && empty($conf->global->EXPENSEREPORT_ALLOW_OVERLAPPING_PERIODS) && $object->periode_existe($fuser, $object->date_debut, $object->date_fin)) { $error++; setEventMessages($langs->trans("ErrorDoubleDeclaration"), null, 'errors'); $action = 'create'; } - if (!$error) - { + if (!$error) { $db->begin(); $id = $object->create($user); - if ($id <= 0) - { + if ($id <= 0) { $error++; } - if (!$error) - { + if (!$error) { $db->commit(); Header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; @@ -282,16 +280,14 @@ if (empty($reshook)) } } - if ($action == 'update' && $user->rights->expensereport->creer) - { + if ($action == 'update' && $user->rights->expensereport->creer) { $object = new ExpenseReport($db); $object->fetch($id); $object->date_debut = $date_start; $object->date_fin = $date_end; - if ($object->status < 3) - { + if ($object->status < 3) { $object->fk_user_validator = GETPOST('fk_user_validator', 'int'); } @@ -301,8 +297,7 @@ if (empty($reshook)) $object->fk_user_modif = $user->id; $result = $object->update($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".GETPOST('id', 'int')); exit; } else { @@ -310,31 +305,30 @@ if (empty($reshook)) } } - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields - $result = $object->insertExtraFields('EXPENSEREPORT_MODIFY'); - if ($result < 0) - { + $result = $object->insertExtraFields('EXPENSEREPORT_MODIFY'); + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } - if ($action == "confirm_validate" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) - { + if ($action == "confirm_validate" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) { $error = 0; $db->begin(); @@ -344,15 +338,17 @@ if (empty($reshook)) $result = $object->setValidate($user); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -367,8 +363,7 @@ if (empty($reshook)) $error++; } - if (!$error && $result > 0 && $object->fk_user_validator > 0) - { + if (!$error && $result > 0 && $object->fk_user_validator > 0) { $langs->load("mails"); // TO @@ -381,13 +376,14 @@ if (empty($reshook)) $expediteur->fetch($object->fk_user_author); $emailFrom = $expediteur->email; - if ($emailTo && $emailFrom) - { + if ($emailTo && $emailFrom) { $filename = array(); $filedir = array(); $mimetype = array(); // SUBJECT $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $societeName = $conf->global->MAIN_APPLICATION_TITLE; + } $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForApproval"); @@ -398,31 +394,28 @@ if (empty($reshook)) // Rebuild pdf /* - $object->setDocModel($user,""); - $resultPDF = expensereport_pdf_create($db,$id,'',"",$langs); + $object->setDocModel($user,""); + $resultPDF = expensereport_pdf_create($db,$id,'',"",$langs); - if($resultPDF): - // ATTACHMENT - array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); - array_push($filedir,$conf->expensereport->dir_output . "/" . dol_sanitizeFileName($object->ref) . "/" . dol_sanitizeFileName($object->ref).".pdf"); - array_push($mimetype,"application/pdf"); - */ + if($resultPDF): + // ATTACHMENT + array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); + array_push($filedir,$conf->expensereport->dir_output . "/" . dol_sanitizeFileName($object->ref) . "/" . dol_sanitizeFileName($object->ref).".pdf"); + array_push($mimetype,"application/pdf"); + */ // PREPARE SEND $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); - if ($mailfile) - { + if ($mailfile) { // SEND $result = $mailfile->sendfile(); - if ($result) - { + if ($result) { $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); setEventMessages($mesg, null, 'mesgs'); } else { $langs->load("other"); - if ($mailfile->error) - { + if ($mailfile->error) { $mesg = ''; $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); $mesg .= '
    '.$mailfile->error; @@ -441,8 +434,7 @@ if (empty($reshook)) } } - if (!$error) - { + if (!$error) { $db->commit(); header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; @@ -451,21 +443,22 @@ if (empty($reshook)) } } - if ($action == "confirm_save_from_refuse" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) - { + if ($action == "confirm_save_from_refuse" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) { $object = new ExpenseReport($db); $object->fetch($id); $result = $object->set_save_from_refuse($user); - if ($result > 0) - { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -477,27 +470,27 @@ if (empty($reshook)) } } - if ($result > 0) - { + if ($result > 0) { // Send mail - // TO - $destinataire = new User($db); - $destinataire->fetch($object->fk_user_validator); - $emailTo = $destinataire->email; + // TO + $destinataire = new User($db); + $destinataire->fetch($object->fk_user_validator); + $emailTo = $destinataire->email; // FROM $expediteur = new User($db); $expediteur->fetch($object->fk_user_author); $emailFrom = $expediteur->email; - if ($emailFrom && $emailTo) - { + if ($emailFrom && $emailTo) { $filename = array(); $filedir = array(); $mimetype = array(); - // SUBJECT + // SUBJECT $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $societeName = $conf->global->MAIN_APPLICATION_TITLE; + } $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForReApproval"); @@ -507,18 +500,18 @@ if (empty($reshook)) $dateRefusEx = explode(" ", $object->date_refuse); $message = $langs->transnoentities("ExpenseReportWaitingForReApprovalMessage", $dateRefusEx[0], $object->detail_refuse, $expediteur->getFullName($langs), $link); - // Rebuild pdf + // Rebuild pdf /* $object->setDocModel($user,""); $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); - if($resultPDF) - { - // ATTACHMENT - $filename=array(); $filedir=array(); $mimetype=array(); - array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); - array_push($filedir,$conf->expensereport->dir_output . "/" . dol_sanitizeFileName($object->ref) . "/" . dol_sanitizeFileName($object->ref_number).".pdf"); - array_push($mimetype,"application/pdf"); + if($resultPDF) + { + // ATTACHMENT + $filename=array(); $filedir=array(); $mimetype=array(); + array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); + array_push($filedir,$conf->expensereport->dir_output . "/" . dol_sanitizeFileName($object->ref) . "/" . dol_sanitizeFileName($object->ref_number).".pdf"); + array_push($mimetype,"application/pdf"); } */ @@ -526,20 +519,17 @@ if (empty($reshook)) // PREPARE SEND $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); - if ($mailfile) - { + if ($mailfile) { // SEND $result = $mailfile->sendfile(); - if ($result) - { + if ($result) { $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); setEventMessages($mesg, null, 'mesgs'); header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { $langs->load("other"); - if ($mailfile->error) - { + if ($mailfile->error) { $mesg = ''; $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); $mesg .= '
    '.$mailfile->error; @@ -562,22 +552,23 @@ if (empty($reshook)) } // Approve - if ($action == "confirm_approve" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve) - { + if ($action == "confirm_approve" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve) { $object = new ExpenseReport($db); $object->fetch($id); $result = $object->setApproved($user); - if ($result > 0) - { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -589,109 +580,109 @@ if (empty($reshook)) } } - if ($result > 0) - { + if ($result > 0) { // Send mail - // TO - $destinataire = new User($db); - $destinataire->fetch($object->fk_user_author); - $emailTo = $destinataire->email; + // TO + $destinataire = new User($db); + $destinataire->fetch($object->fk_user_author); + $emailTo = $destinataire->email; - // CC - $emailCC = $conf->global->NDF_CC_EMAILS; - if (empty($emailTo)) $emailTo = $emailCC; + // CC + $emailCC = $conf->global->NDF_CC_EMAILS; + if (empty($emailTo)) { + $emailTo = $emailCC; + } // FROM - $expediteur = new User($db); - $expediteur->fetch($object->fk_user_approve > 0 ? $object->fk_user_approve : $object->fk_user_validator); - $emailFrom = $expediteur->email; + $expediteur = new User($db); + $expediteur->fetch($object->fk_user_approve > 0 ? $object->fk_user_approve : $object->fk_user_validator); + $emailFrom = $expediteur->email; - if ($emailFrom && $emailTo) - { + if ($emailFrom && $emailTo) { $filename = array(); $filedir = array(); $mimetype = array(); - // SUBJECT + // SUBJECT $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $societeName = $conf->global->MAIN_APPLICATION_TITLE; + } $subject = $societeName." - ".$langs->transnoentities("ExpenseReportApproved"); - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; $link = ''.$link.''; - $message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); + $message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); - // Rebuilt pdf + // Rebuilt pdf /* - $object->setDocModel($user,""); - $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); + $object->setDocModel($user,""); + $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); - if($resultPDF - { - // ATTACHMENT - $filename=array(); $filedir=array(); $mimetype=array(); - array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); - array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf"); - array_push($mimetype,"application/pdf"); - } - */ + if($resultPDF + { + // ATTACHMENT + $filename=array(); $filedir=array(); $mimetype=array(); + array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); + array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf"); + array_push($mimetype,"application/pdf"); + } + */ $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); - if ($mailfile) - { - // SEND - $result = $mailfile->sendfile(); - if ($result) - { - $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); - setEventMessages($mesg, null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - $langs->load("other"); - if ($mailfile->error) - { - $mesg = ''; - $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); - $mesg .= '
    '.$mailfile->error; - setEventMessages($mesg, null, 'errors'); - } else { - setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); - } - } - } else { - setEventMessages($mailfile->error, $mailfile->errors, 'errors'); - $action = ''; - } - } else { + if ($mailfile) { + // SEND + $result = $mailfile->sendfile(); + if ($result) { + $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); + setEventMessages($mesg, null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + $langs->load("other"); + if ($mailfile->error) { + $mesg = ''; + $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); + $mesg .= '
    '.$mailfile->error; + setEventMessages($mesg, null, 'errors'); + } else { + setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); + } + } + } else { + setEventMessages($mailfile->error, $mailfile->errors, 'errors'); + $action = ''; + } + } else { setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); $action = ''; } } else { - setEventMessages($langs->trans("FailedtoSetToApprove"), null, 'warnings'); - $action = ''; - } - } + setEventMessages($langs->trans("FailedtoSetToApprove"), null, 'warnings'); + $action = ''; + } + } - if ($action == "confirm_refuse" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve) - { + if ($action == "confirm_refuse" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve) { $object = new ExpenseReport($db); $object->fetch($id); $detailRefuse = GETPOST('detail_refuse', 'alpha'); $result = $object->setDeny($user, $detailRefuse); - if ($result > 0) - { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -703,8 +694,7 @@ if (empty($reshook)) } } - if ($result > 0) - { + if ($result > 0) { // Send mail // TO @@ -717,53 +707,51 @@ if (empty($reshook)) $expediteur->fetch($object->fk_user_refuse); $emailFrom = $expediteur->email; - if ($emailFrom && $emailTo) - { + if ($emailFrom && $emailTo) { $filename = array(); $filedir = array(); $mimetype = array(); // SUBJECT $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $societeName = $conf->global->MAIN_APPLICATION_TITLE; + } $subject = $societeName." - ".$langs->transnoentities("ExpenseReportRefused"); - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; $link = ''.$link.''; $message = $langs->transnoentities("ExpenseReportRefusedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailRefuse, $link); - // Rebuilt pdf + // Rebuilt pdf /* - $object->setDocModel($user,""); - $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); + $object->setDocModel($user,""); + $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); - if($resultPDF - { - // ATTACHMENT - $filename=array(); $filedir=array(); $mimetype=array(); - array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); - array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf"); - array_push($mimetype,"application/pdf"); - } - */ + if($resultPDF + { + // ATTACHMENT + $filename=array(); $filedir=array(); $mimetype=array(); + array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); + array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf"); + array_push($mimetype,"application/pdf"); + } + */ // PREPARE SEND $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); - if ($mailfile) - { + if ($mailfile) { // SEND $result = $mailfile->sendfile(); - if ($result) - { + if ($result) { $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); setEventMessages($mesg, null, 'mesgs'); header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { $langs->load("other"); - if ($mailfile->error) - { + if ($mailfile->error) { $mesg = ''; $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); $mesg .= '
    '.$mailfile->error; @@ -787,29 +775,28 @@ if (empty($reshook)) } //var_dump($user->id == $object->fk_user_validator);exit; - if ($action == "confirm_cancel" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) - { - if (!GETPOST('detail_cancel', 'alpha')) - { + if ($action == "confirm_cancel" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) { + if (!GETPOST('detail_cancel', 'alpha')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors'); } else { $object = new ExpenseReport($db); $object->fetch($id); - if ($user->id == $object->fk_user_valid || $user->id == $object->fk_user_author) - { + if ($user->id == $object->fk_user_valid || $user->id == $object->fk_user_author) { $detailCancel = GETPOST('detail_cancel', 'alpha'); $result = $object->set_cancel($user, $detailCancel); - if ($result > 0) - { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -821,8 +808,7 @@ if (empty($reshook)) } } - if ($result > 0) - { + if ($result > 0) { // Send mail // TO @@ -835,13 +821,14 @@ if (empty($reshook)) $expediteur->fetch($object->fk_user_cancel); $emailFrom = $expediteur->email; - if ($emailFrom && $emailTo) - { + if ($emailFrom && $emailTo) { $filename = array(); $filedir = array(); $mimetype = array(); // SUBJECT $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $societeName = $conf->global->MAIN_APPLICATION_TITLE; + } $subject = $societeName." - ".$langs->transnoentities("ExpenseReportCanceled"); @@ -852,36 +839,33 @@ if (empty($reshook)) // Rebuilt pdf /* - $object->setDocModel($user,""); - $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); + $object->setDocModel($user,""); + $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); - if($resultPDF - { - // ATTACHMENT - $filename=array(); $filedir=array(); $mimetype=array(); - array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); - array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf"); - array_push($mimetype,"application/pdf"); - } - */ + if($resultPDF + { + // ATTACHMENT + $filename=array(); $filedir=array(); $mimetype=array(); + array_push($filename,dol_sanitizeFileName($object->ref).".pdf"); + array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf"); + array_push($mimetype,"application/pdf"); + } + */ // PREPARE SEND $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); - if ($mailfile) - { + if ($mailfile) { // SEND $result = $mailfile->sendfile(); - if ($result) - { + if ($result) { $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); setEventMessages($mesg, null, 'mesgs'); header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { $langs->load("other"); - if ($mailfile->error) - { + if ($mailfile->error) { $mesg = ''; $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); $mesg .= '
    '.$mailfile->error; @@ -908,23 +892,23 @@ if (empty($reshook)) } } - if ($action == "confirm_setdraft" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) - { + if ($action == "confirm_setdraft" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) { $object = new ExpenseReport($db); $object->fetch($id); - if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) - { + if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) { $result = $object->setStatut(0); - if ($result > 0) - { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -936,8 +920,7 @@ if (empty($reshook)) } } - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { @@ -948,22 +931,23 @@ if (empty($reshook)) } } - if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid) - { + if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid) { $object = new ExpenseReport($db); $object->fetch($id); $result = $object->setUnpaid($user); - if ($result > 0) - { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -976,22 +960,23 @@ if (empty($reshook)) } } - if ($action == 'set_paid' && $id > 0 && $user->rights->expensereport->to_paid) - { + if ($action == 'set_paid' && $id > 0 && $user->rights->expensereport->to_paid) { $object = new ExpenseReport($db); $object->fetch($id); $result = $object->setPaid($id, $user); - if ($result > 0) - { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -1003,8 +988,7 @@ if (empty($reshook)) } } - if ($result > 0) - { + if ($result > 0) { // Send mail // TO @@ -1017,13 +1001,14 @@ if (empty($reshook)) $expediteur->fetch($user->id); $emailFrom = $expediteur->email; - if ($emailFrom && $emailTo) - { + if ($emailFrom && $emailTo) { $filename = array(); $filedir = array(); $mimetype = array(); // SUBJECT $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $societeName = $conf->global->MAIN_APPLICATION_TITLE; + } $subject = $societeName." - ".$langs->transnoentities("ExpenseReportPaid"); @@ -1039,20 +1024,17 @@ if (empty($reshook)) // PREPARE SEND $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); - if ($mailfile) - { + if ($mailfile) { // SEND $result = $mailfile->sendfile(); - if ($result) - { + if ($result) { $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); setEventMessages($mesg, null, 'mesgs'); header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { $langs->load("other"); - if ($mailfile->error) - { + if ($mailfile->error) { $mesg = ''; $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); $mesg .= '
    '.$mailfile->error; @@ -1075,17 +1057,14 @@ if (empty($reshook)) } } - if ($action == "addline" && $user->rights->expensereport->creer) - { + if ($action == "addline" && $user->rights->expensereport->creer) { $error = 0; // First save uploaded file $fk_ecm_files = 0; - if (GETPOSTISSET('attachfile')) - { + if (GETPOSTISSET('attachfile')) { $arrayoffiles = GETPOST('attachfile', 'array'); - if (is_array($arrayoffiles) && !empty($arrayoffiles[0])) - { + if (is_array($arrayoffiles) && !empty($arrayoffiles[0])) { include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $relativepath = 'expensereport/'.$object->ref.'/'.$arrayoffiles[0]; $ecmfiles = new EcmFiles($db); @@ -1095,70 +1074,67 @@ if (empty($reshook)) } // if VAT is not used in Dolibarr, set VAT rate to 0 because VAT rate is necessary. - if (empty($vatrate)) $vatrate = "0.000"; + if (empty($vatrate)) { + $vatrate = "0.000"; + } $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate)); $value_unit_ht = price2num(GETPOST('value_unit_ht', 'alpha'), 'MU'); $value_unit = price2num(GETPOST('value_unit', 'alpha'), 'MU'); - if (empty($value_unit)) - { + if (empty($value_unit)) { $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU'); } $fk_c_exp_tax_cat = GETPOST('fk_c_exp_tax_cat', 'int'); $qty = GETPOST('qty', 'int'); - if (empty($qty)) $qty = 1; + if (empty($qty)) { + $qty = 1; + } - if (!($fk_c_type_fees > 0)) - { + if (!($fk_c_type_fees > 0)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); $action = ''; } - if ((int) $tmpvat < 0 || $tmpvat == '') - { + if ((int) $tmpvat < 0 || $tmpvat == '') { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("VAT")), null, 'errors'); $action = ''; } // Si aucune date n'est rentrée - if (empty($date) || $date == "--") - { + if (empty($date) || $date == "--") { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); } // Si aucun prix n'est rentré - if ($value_unit == 0) - { + if ($value_unit == 0) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PriceUTTC")), null, 'errors'); } // Warning if date out of range - if ($date < $object->date_debut || $date > ($object->date_fin + (24 * 3600 - 1))) - { + if ($date < $object->date_debut || $date > ($object->date_fin + (24 * 3600 - 1))) { $langs->load("errors"); setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings'); } - if (!$error) - { + if (!$error) { $type = 0; // TODO What if service ? We should take the type product/service from the type of expense report llx_c_type_fees // Insert line $result = $object->addline($qty, $value_unit, $fk_c_type_fees, $vatrate, $date, $comments, $fk_project, $fk_c_exp_tax_cat, $type, $fk_ecm_files); - if ($result > 0) - { + if ($result > 0) { $ret = $object->fetch($object->id); // Reload to get new records if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; $newlang = GETPOST('lang_id', 'alpha'); - if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) + if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -1184,8 +1160,7 @@ if (empty($reshook)) $action = ''; } - if ($action == 'confirm_delete_line' && GETPOST("confirm", 'alpha') == "yes" && $user->rights->expensereport->creer) - { + if ($action == 'confirm_delete_line' && GETPOST("confirm", 'alpha') == "yes" && $user->rights->expensereport->creer) { $object = new ExpenseReport($db); $object->fetch($id); @@ -1195,17 +1170,18 @@ if (empty($reshook)) $total_tva = $object_ligne->total_tva; $result = $object->deleteline(GETPOST("rowid", 'int'), $user); - if ($result >= 0) - { - if ($result > 0) - { + if ($result >= 0) { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -1225,18 +1201,15 @@ if (empty($reshook)) } } - if ($action == "updateline" && $user->rights->expensereport->creer) - { + if ($action == "updateline" && $user->rights->expensereport->creer) { $object = new ExpenseReport($db); $object->fetch($id); // First save uploaded file $fk_ecm_files = 0; - if (GETPOSTISSET('attachfile')) - { + if (GETPOSTISSET('attachfile')) { $arrayoffiles = GETPOST('attachfile', 'array'); - if (is_array($arrayoffiles) && !empty($arrayoffiles[0])) - { + if (is_array($arrayoffiles) && !empty($arrayoffiles[0])) { include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $relativepath = 'expensereport/'.$object->ref.'/'.$arrayoffiles[0]; $ecmfiles = new EcmFiles($db); @@ -1254,50 +1227,48 @@ if (empty($reshook)) $vatrate = GETPOST('vatrate', 'alpha'); // if VAT is not used in Dolibarr, set VAT rate to 0 because VAT rate is necessary. - if (empty($vatrate)) $vatrate = "0.000"; + if (empty($vatrate)) { + $vatrate = "0.000"; + } $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate)); $value_unit_ht = price2num(GETPOST('value_unit_ht', 'alpha'), 'MU'); $value_unit = price2num(GETPOST('value_unit', 'alpha'), 'MU'); - if (empty($value_unit)) - { + if (empty($value_unit)) { $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU'); } - if (!GETPOST('fk_c_type_fees', 'int') > 0) - { + if (!GETPOST('fk_c_type_fees', 'int') > 0) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); $action = ''; } - if ((int) $tmpvat < 0 || $tmpvat == '') - { + if ((int) $tmpvat < 0 || $tmpvat == '') { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Vat")), null, 'errors'); $action = ''; } // Warning if date out of range - if ($date < $object->date_debut || $date > ($object->date_fin + (24 * 3600 - 1))) - { + if ($date < $object->date_debut || $date > ($object->date_fin + (24 * 3600 - 1))) { $langs->load("errors"); setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings'); } - if (!$error) - { + if (!$error) { // TODO Use update method of ExpenseReportLine $result = $object->updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $id, $fk_c_exp_tax_cat, $fk_ecm_files); - if ($result >= 0) - { - if ($result > 0) - { + if ($result >= 0) { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -1340,9 +1311,9 @@ if (empty($reshook)) */ $title = $langs->trans("ExpenseReport")." - ".$langs->trans("Card"); -$helpurl = "EN:Module_Expense_Reports"; +$help_url = "EN:Module_Expense_Reports|FR:Module_Notes_de_frais"; -llxHeader("", $title, $helpurl); +llxHeader("", $title, $help_url); $form = new Form($db); $formfile = new FormFile($db); @@ -1354,8 +1325,7 @@ $ecmfilesstatic = new EcmFiles($db); $formexpensereport = new FormExpenseReport($db); // Create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewTrip"), '', 'trip'); print ''; @@ -1388,9 +1358,13 @@ if ($action == 'create') print ''.$langs->trans("User").''; print ''; $defaultselectuser = $user->id; - if (GETPOST('fk_user_author', 'int') > 0) $defaultselectuser = GETPOST('fk_user_author', 'int'); + if (GETPOST('fk_user_author', 'int') > 0) { + $defaultselectuser = GETPOST('fk_user_author', 'int'); + } $include_users = 'hierarchyme'; - if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expensereport->writeall_advance)) $include_users = array(); + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expensereport->writeall_advance)) { + $include_users = array(); + } $s = $form->select_dolusers($defaultselectuser, "fk_user_author", 0, "", 0, $include_users, '', '0,'.$conf->entity); print $s; print ''; @@ -1402,11 +1376,16 @@ if ($action == 'create') print ''; $object = new ExpenseReport($db); $include_users = $object->fetch_users_approver_expensereport(); - if (empty($include_users)) print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateExpenseReport"); - else { + if (empty($include_users)) { + print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateExpenseReport"); + } else { $defaultselectuser = (empty($user->fk_user_expense_validator) ? $user->fk_user : $user->fk_user_expense_validator); // Will work only if supervisor has permission to approve so is inside include_users - if (!empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR)) $defaultselectuser = $conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR; // Can force default approver - if (GETPOST('fk_user_validator', 'int') > 0) $defaultselectuser = GETPOST('fk_user_validator', 'int'); + if (!empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR)) { + $defaultselectuser = $conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR; // Can force default approver + } + if (GETPOST('fk_user_validator', 'int') > 0) { + $defaultselectuser = GETPOST('fk_user_validator', 'int'); + } $s = $form->select_dolusers($defaultselectuser, "fk_user_validator", 1, "", ((empty($defaultselectuser) || empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR_UNCHANGEABLE)) ? 0 : 1), $include_users); print $form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate")); } @@ -1414,8 +1393,7 @@ if ($action == 'create') print ''; // Payment mode - if (!empty($conf->global->EXPENSEREPORT_ASK_PAYMENTMODE_ON_CREATION)) - { + if (!empty($conf->global->EXPENSEREPORT_ASK_PAYMENTMODE_ON_CREATION)) { print ''; print ''.$langs->trans("ModePaiement").''; print ''; @@ -1469,13 +1447,10 @@ if ($action == 'create') $res = $object->fetch_optionals(); - if ($result > 0) - { - if (!in_array($object->fk_user_author, $user->getAllChildIds(1))) - { + if ($result > 0) { + if (!in_array($object->fk_user_author, $user->getAllChildIds(1))) { if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous) - && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) - { + && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) { print load_fiche_titre($langs->trans('TripCard'), '', 'trip'); print '
    '; @@ -1492,16 +1467,14 @@ if ($action == 'create') $head = expensereport_prepare_head($object); - if ($action == 'edit' && ($object->status < 3 || $object->status == 99)) - { + if ($action == 'edit' && ($object->status < 3 || $object->status == 99)) { print "\n"; print ''; print ''; print dol_get_fiche_head($head, 'card', $langs->trans("ExpenseReport"), 0, 'trip'); - if ($object->status == 99) - { + if ($object->status == 99) { print ''; } else { print ''; @@ -1515,8 +1488,7 @@ if ($action == 'create') print ''.$langs->trans("User").''; print ''; $userfee = new User($db); - if ($object->fk_user_author > 0) - { + if ($object->fk_user_author > 0) { $userfee->fetch($object->fk_user_author); print $userfee->getNomUrl(-1); } @@ -1540,8 +1512,7 @@ if ($action == 'create') print ''; print ''; - if (!empty($conf->global->EXPENSEREPORT_ASK_PAYMENTMODE_ON_CREATION)) - { + if (!empty($conf->global->EXPENSEREPORT_ASK_PAYMENTMODE_ON_CREATION)) { print ''; print ''.$langs->trans("ModePaiement").''; print ''; @@ -1550,8 +1521,7 @@ if ($action == 'create') print ''; } - if ($object->status < 3) - { + if ($object->status < 3) { print ''; print ''.$langs->trans("VALIDATOR").''; // Approbator print ''; @@ -1570,8 +1540,7 @@ if ($action == 'create') print ''; } - if ($object->status == 6) - { + if ($object->status == 6) { print ''; print ''.$langs->trans("AUTHORPAIEMENT").''; print ''; @@ -1602,7 +1571,9 @@ if ($action == 'create') if ($action == 'clone') { // Create an array for form $criteriaforfilter = 'hierarchyme'; - if (!empty($user->rights->expensereport->readall)) $criteriaforfilter = ''; + if (!empty($user->rights->expensereport->readall)) { + $criteriaforfilter = ''; + } $formquestion = array( 'text' => '', array('type' => 'other', 'name' => 'fk_user_author', 'label' => $langs->trans("SelectTargetUser"), 'value' => $form->select_dolusers((GETPOST('fk_user_author', 'int') > 0 ? GETPOST('fk_user_author', 'int') : $user->id), 'fk_user_author', 0, null, 0, $criteriaforfilter, '', '0', 0, 0, '', 0, '', 'maxwidth150')) @@ -1611,50 +1582,41 @@ if ($action == 'create') $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneExpenseReport', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } - if ($action == 'save') - { + if ($action == 'save') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("SaveTrip"), $langs->trans("ConfirmSaveTrip"), "confirm_validate", "", "", 1); } - if ($action == 'save_from_refuse') - { + if ($action == 'save_from_refuse') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("SaveTrip"), $langs->trans("ConfirmSaveTrip"), "confirm_save_from_refuse", "", "", 1); } - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("DeleteTrip"), $langs->trans("ConfirmDeleteTrip"), "confirm_delete", "", "", 1); } - if ($action == 'validate') - { + if ($action == 'validate') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("ValideTrip"), $langs->trans("ConfirmValideTrip"), "confirm_approve", "", "", 1); } - if ($action == 'paid') - { + if ($action == 'paid') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("PaidTrip"), $langs->trans("ConfirmPaidTrip"), "confirm_paid", "", "", 1); } - if ($action == 'cancel') - { + if ($action == 'cancel') { $array_input = array('text'=>$langs->trans("ConfirmCancelTrip"), array('type'=>"text", 'label'=>''.$langs->trans("Comment").'', 'name'=>"detail_cancel", 'value'=>"")); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("Cancel"), "", "confirm_cancel", $array_input, "", 1); } - if ($action == 'setdraft') - { + if ($action == 'setdraft') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("BrouillonnerTrip"), $langs->trans("ConfirmBrouillonnerTrip"), "confirm_setdraft", "", "", 1); } - if ($action == 'refuse') // Deny - { + if ($action == 'refuse') { // Deny $array_input = array('text'=>$langs->trans("ConfirmRefuseTrip"), array('type'=>"text", 'label'=>$langs->trans("Comment"), 'name'=>"detail_refuse", 'value'=>"")); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("Deny"), '', "confirm_refuse", $array_input, "yes", 1); } - if ($action == 'delete_line') - { + if ($action == 'delete_line') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id."&rowid=".GETPOST('rowid', 'int'), $langs->trans("DeleteLine"), $langs->trans("ConfirmDeleteLine"), "confirm_delete_line", '', 'yes', 1); } @@ -1674,34 +1636,34 @@ if ($action == 'create') // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; - if ($user->rights->commande->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->commande->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } }*/ $morehtmlref .= '
    '; @@ -1717,12 +1679,14 @@ if ($action == 'create') print ''; print ''.$langs->trans("User").''; print ''; - if ($object->fk_user_author > 0) - { + if ($object->fk_user_author > 0) { $userauthor = new User($db); $result = $userauthor->fetch($object->fk_user_author); - if ($result < 0) dol_print_error('', $userauthor->error); - elseif ($result > 0) print $userauthor->getNomUrl(-1); + if ($result < 0) { + dol_print_error('', $userauthor->error); + } elseif ($result > 0) { + print $userauthor->getNomUrl(-1); + } } print ''; @@ -1733,8 +1697,7 @@ if ($action == 'create') print get_date_range($object->date_debut, $object->date_fin, 'day', $langs, 0); print ''; print ''; - if (!empty($conf->global->EXPENSEREPORT_ASK_PAYMENTMODE_ON_CREATION)) - { + if (!empty($conf->global->EXPENSEREPORT_ASK_PAYMENTMODE_ON_CREATION)) { print ''; print ''.$langs->trans("ModePaiement").''; print ''.$object->fk_c_paiement.''; @@ -1745,39 +1708,42 @@ if ($action == 'create') print ''; print ''.$langs->trans("DATE_SAVE").''; print ''.dol_print_date($object->date_valid, 'dayhour', 'tzuser'); - if ($object->status == 2 && $object->hasDelay('toapprove')) print ' '.img_warning($langs->trans("Late").' - '.$langs->trans("ToApprove")); - if ($object->status == 5 && $object->hasDelay('topay')) print ' '.img_warning($langs->trans("Late").' - '.$langs->trans("ToPay")); + if ($object->status == 2 && $object->hasDelay('toapprove')) { + print ' '.img_warning($langs->trans("Late").' - '.$langs->trans("ToApprove")); + } + if ($object->status == 5 && $object->hasDelay('topay')) { + print ' '.img_warning($langs->trans("Late").' - '.$langs->trans("ToPay")); + } print ''; print ''; // User to inform for approval - if ($object->status <= ExpenseReport::STATUS_VALIDATED) // informed - { + if ($object->status <= ExpenseReport::STATUS_VALIDATED) { // informed print ''; print ''.$langs->trans("VALIDATOR").''; // approver print ''; - if ($object->fk_user_validator > 0) - { + if ($object->fk_user_validator > 0) { $userfee = new User($db); $result = $userfee->fetch($object->fk_user_validator); - if ($result > 0) print $userfee->getNomUrl(-1); - if (empty($userfee->email) || !isValidEmail($userfee->email)) - { + if ($result > 0) { + print $userfee->getNomUrl(-1); + } + if (empty($userfee->email) || !isValidEmail($userfee->email)) { $langs->load("errors"); print img_warning($langs->trans("ErrorBadEMail", $userfee->email)); } } print ''; - } elseif ($object->status == ExpenseReport::STATUS_CANCELED) - { + } elseif ($object->status == ExpenseReport::STATUS_CANCELED) { print ''; print ''.$langs->trans("CANCEL_USER").''; print ''; - if ($object->fk_user_cancel > 0) - { + if ($object->fk_user_cancel > 0) { $userfee = new User($db); $result = $userfee->fetch($object->fk_user_cancel); - if ($result > 0) print $userfee->getNomUrl(-1); + if ($result > 0) { + print $userfee->getNomUrl(-1); + } } print ''; @@ -1793,11 +1759,12 @@ if ($action == 'create') print ''; print ''.$langs->trans("ApprovedBy").''; print ''; - if ($object->fk_user_approve > 0) - { + if ($object->fk_user_approve > 0) { $userapp = new User($db); $result = $userapp->fetch($object->fk_user_approve); - if ($result > 0) print $userapp->getNomUrl(-1); + if ($result > 0) { + print $userapp->getNomUrl(-1); + } } print ''; @@ -1807,26 +1774,28 @@ if ($action == 'create') print ''; } - if ($object->status == 99 || !empty($object->detail_refuse)) - { + if ($object->status == 99 || !empty($object->detail_refuse)) { print ''; print ''.$langs->trans("REFUSEUR").''; print ''; $userfee = new User($db); $result = $userfee->fetch($object->fk_user_refuse); - if ($result > 0) print $userfee->getNomUrl(-1); + if ($result > 0) { + print $userfee->getNomUrl(-1); + } print ''; print ''; print ''.$langs->trans("DATE_REFUS").''; print ''.dol_print_date($object->date_refuse, 'dayhour', 'tzuser'); - if ($object->detail_refuse) print ' - '.$object->detail_refuse; + if ($object->detail_refuse) { + print ' - '.$object->detail_refuse; + } print ''; print ''; } - if ($object->status == $object::STATUS_CLOSED) - { + if ($object->status == $object::STATUS_CLOSED) { /* TODO this fields are not yet filled print ''; print ''.$langs->trans("AUTHORPAIEMENT").''; @@ -1860,11 +1829,19 @@ if ($action == 'create') print ''.$langs->trans("AmountHT").''; print ''.price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency).''; $rowspan = 5; - if ($object->status <= ExpenseReport::STATUS_VALIDATED) $rowspan++; - elseif ($object->status == ExpenseReport::STATUS_CANCELED) $rowspan += 2; - else $rowspan += 2; - if ($object->status == ExpenseReport::STATUS_REFUSED || !empty($object->detail_refuse)) $rowspan += 2; - if ($object->status == ExpenseReport::STATUS_CLOSED) $rowspan += 2; + if ($object->status <= ExpenseReport::STATUS_VALIDATED) { + $rowspan++; + } elseif ($object->status == ExpenseReport::STATUS_CANCELED) { + $rowspan += 2; + } else { + $rowspan += 2; + } + if ($object->status == ExpenseReport::STATUS_REFUSED || !empty($object->detail_refuse)) { + $rowspan += 2; + } + if ($object->status == ExpenseReport::STATUS_CLOSED) { + $rowspan += 2; + } print ""; print ''; @@ -1912,12 +1889,10 @@ if ($action == 'create') $sql .= " ORDER BY dp"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; $totalpaid = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $paymentexpensereportstatic->id = $objp->rowid; @@ -1933,8 +1908,7 @@ if ($action == 'create') print ''.dol_print_date($db->jdate($objp->dp), 'day')."\n"; $labeltype = $langs->trans("PaymentType".$objp->p_code) != ("PaymentType".$objp->p_code) ? $langs->trans("PaymentType".$objp->p_code) : $objp->payment_type; print "".$labeltype.' '.$objp->num_payment."\n"; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { $bankaccountstatic->id = $objp->baid; $bankaccountstatic->ref = $objp->baref; $bankaccountstatic->label = $objp->baref; @@ -1949,8 +1923,9 @@ if ($action == 'create') } print ''; - if ($bankaccountstatic->id) + if ($bankaccountstatic->id) { print $bankaccountstatic->getNomUrl(1, 'transactions'); + } print ''; } print ''.price($objp->amount).""; @@ -1959,8 +1934,7 @@ if ($action == 'create') $totalpaid += $objp->amount; $i++; } - if (!is_null($totalpaid)) - { + if (!is_null($totalpaid)) { $totalpaid = price2num($totalpaid); // Round $totalpaid to fix floating problem after addition into loop } @@ -1969,12 +1943,10 @@ if ($action == 'create') $cssforamountpaymentcomplete = 'amountpaymentcomplete'; - if ($object->status == ExpenseReport::STATUS_REFUSED) - { + if ($object->status == ExpenseReport::STATUS_REFUSED) { $cssforamountpaymentcomplete = 'amountpaymentneutral'; $resteapayeraffiche = 0; - } elseif ($object->paid == 0) - { + } elseif ($object->paid == 0) { $cssforamountpaymentcomplete = 'amountpaymentneutral'; } print ''.$langs->trans("AlreadyPaid").':'.price($totalpaid).''; @@ -1998,7 +1970,9 @@ if ($action == 'create') print '
    '; $actiontouse = 'updateline'; - if (($object->status == 0 || $object->status == 99) && $action != 'editline') $actiontouse = 'addline'; + if (($object->status == 0 || $object->status == 99) && $action != 'editline') { + $actiontouse = 'addline'; + } print '
    '; print ''; @@ -2009,24 +1983,26 @@ if ($action == 'create') print '
    '; print ''; - if (!empty($object->lines)) - { + if (!empty($object->lines)) { $i = 0; $total = 0; print ''; print ''; //print ''; print ''; - if (!empty($conf->projet->enabled)) print ''; + if (!empty($conf->projet->enabled)) { + print ''; + } print ''; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) print ''; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { + print ''; + } print ''; print ''; print ''; print ''; print ''; - if ($action != 'editline') - { + if ($action != 'editline') { print ''; print ''; } @@ -2034,18 +2010,15 @@ if ($action == 'create') print ''; // Ajout des boutons de modification/suppression - if (($object->status < 2 || $object->status == 99) && $user->rights->expensereport->creer) - { + if (($object->status < 2 || $object->status == 99) && $user->rights->expensereport->creer) { print ''; } print ''; - foreach ($object->lines as &$line) - { + foreach ($object->lines as &$line) { $numline = $i + 1; - if ($action != 'editline' || $line->rowid != GETPOST('rowid', 'int')) - { + if ($action != 'editline' || $line->rowid != GETPOST('rowid', 'int')) { print ''; // Num @@ -2057,11 +2030,9 @@ if ($action == 'create') print ''; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { print ''; // IK - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) - { + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { print ''; @@ -2090,8 +2060,7 @@ if ($action == 'create') print ''; // Unit price HT print ''; - if ($action != 'editline') - { + if ($action != 'editline') { print ''; print ''; } // Column with preview print ''; // Ajout des boutons de modification/suppression - if (($object->status < ExpenseReport::STATUS_VALIDATED || $object->status == ExpenseReport::STATUS_REFUSED) && $user->rights->expensereport->creer) - { + if (($object->status < ExpenseReport::STATUS_VALIDATED || $object->status == ExpenseReport::STATUS_REFUSED) && $user->rights->expensereport->creer) { print ''; } - if ($action == 'editline' && $line->rowid == GETPOST('rowid', 'int')) - { + if ($action == 'editline' && $line->rowid == GETPOST('rowid', 'int')) { // Add line with link to add new file or attach line to an existing file $colspan = 10; - if (!empty($conf->projet->enabled)) $colspan++; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++; + if (!empty($conf->projet->enabled)) { + $colspan++; + } + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { + $colspan++; + } print ''; @@ -2217,8 +2183,7 @@ if ($action == 'create') print ''.$langs->trans("UploadANewFileNow"); print img_picto($langs->trans("UploadANewFileNow"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); print ''; - if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) - { + if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) { print '   -   '.$langs->trans("AttachTheNewLineToTheDocument"); print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); print ''; @@ -2236,8 +2201,7 @@ if ($action == 'create') jQuery(".truploadnewfilenow").hide(); return false; });'; - if (is_array(GETPOST('attachfile', 'array')) && count(GETPOST('attachfile', 'array'))) - { + if (is_array(GETPOST('attachfile', 'array')) && count(GETPOST('attachfile', 'array'))) { print 'jQuery(".trattachnewfilenow").toggle();'."\n"; } print ' @@ -2247,11 +2211,9 @@ if ($action == 'create') print ''; $filenamelinked = ''; - if ($line->fk_ecm_files > 0) - { + if ($line->fk_ecm_files > 0) { $result = $ecmfilesstatic->fetch($line->fk_ecm_files); - if ($result > 0) - { + if ($result > 0) { $filenamelinked = $ecmfilesstatic->filename; } } @@ -2270,8 +2232,7 @@ if ($action == 'create') print ''; // Select project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { print ''; @@ -2282,8 +2243,7 @@ if ($action == 'create') print $formexpensereport->selectTypeExpenseReport($line->fk_c_type_fees, 'fk_c_type_fees'); print ''; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) - { + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { print ''; // Select project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { print ''; @@ -2441,8 +2402,7 @@ if ($action == 'create') print $formexpensereport->selectTypeExpenseReport($fk_c_type_fees, 'fk_c_type_fees', 1); print ''; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) - { + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { print ''; @@ -2479,8 +2441,7 @@ if ($action == 'create') // Picture print ''; - if ($action != 'editline') - { + if ($action != 'editline') { print ''; print ''; } @@ -2497,41 +2458,38 @@ if ($action == 'create') /* JQuery for product free or predefined select */ jQuery(document).ready(function() { - jQuery("#value_unit_ht").keyup(function(event) { - console.log(event.which); // discard event tag and arrows - if (event.which != 9 && (event.which < 37 ||event.which > 40) && jQuery("#value_unit_ht").val() != "") { - jQuery("#value_unit").val(""); - } - }); - jQuery("#value_unit").keyup(function(event) { - console.log(event.which); // discard event tag and arrows - if (event.which != 9 && (event.which < 37 || event.which > 40) && jQuery("#value_unit").val() != "") { - jQuery("#value_unit_ht").val(""); - } - }); + jQuery("#value_unit_ht").keyup(function(event) { + console.log(event.which); // discard event tag and arrows + if (event.which != 9 && (event.which < 37 ||event.which > 40) && jQuery("#value_unit_ht").val() != "") { + jQuery("#value_unit").val(""); + } + }); + jQuery("#value_unit").keyup(function(event) { + console.log(event.which); // discard event tag and arrows + if (event.which != 9 && (event.which < 37 || event.which > 40) && jQuery("#value_unit").val() != "") { + jQuery("#value_unit_ht").val(""); + } + }); }); - '; + '; print ''; print dol_get_fiche_end(); - } // end edit or not edit - } // end of if result - else { + } + } else { dol_print_error($db); } - } //fin si id > 0 + } } /* - * Barre d'actions + * Action bar */ - print '
    '; -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { $object = new ExpenseReport($db); $object->fetch($id, $ref); @@ -2550,16 +2508,13 @@ if ($action != 'create' && $action != 'edit') * ET fk_user_author == user courant * Afficher : "Enregistrer" / "Modifier" / "Supprimer" */ - if ($user->rights->expensereport->creer && $object->status == ExpenseReport::STATUS_DRAFT) - { - if (in_array($object->fk_user_author, $user->getAllChildIds(1)) || !empty($user->rights->expensereport->writeall_advance)) - { + if ($user->rights->expensereport->creer && $object->status == ExpenseReport::STATUS_DRAFT) { + if (in_array($object->fk_user_author, $user->getAllChildIds(1)) || !empty($user->rights->expensereport->writeall_advance)) { // Modify print ''; // Validate - if (count($object->lines) > 0) - { + if (count($object->lines) > 0) { print ''; } } @@ -2570,10 +2525,8 @@ if ($action != 'create' && $action != 'edit') * ET fk_user_author == user courant * Afficher : "Enregistrer" / "Modifier" / "Supprimer" */ - if ($user->rights->expensereport->creer && $object->status == ExpenseReport::STATUS_REFUSED) - { - if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) - { + if ($user->rights->expensereport->creer && $object->status == ExpenseReport::STATUS_REFUSED) { + if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) { // Modify print ''; @@ -2584,10 +2537,8 @@ if ($action != 'create' && $action != 'edit') } } - if ($user->rights->expensereport->to_paid && $object->status == ExpenseReport::STATUS_APPROVED) - { - if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) - { + if ($user->rights->expensereport->to_paid && $object->status == ExpenseReport::STATUS_APPROVED) { + if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) { // setdraft print ''; } @@ -2598,17 +2549,14 @@ if ($action != 'create' && $action != 'edit') * ET fk_user_validator == user courant * Afficher : "Valider" / "Refuser" / "Supprimer" */ - if ($object->status == ExpenseReport::STATUS_VALIDATED) - { - if (in_array($object->fk_user_author, $user->getAllChildIds(1))) - { + if ($object->status == ExpenseReport::STATUS_VALIDATED) { + if (in_array($object->fk_user_author, $user->getAllChildIds(1))) { // set draft print ''; } } - if ($user->rights->expensereport->approve && $object->status == ExpenseReport::STATUS_VALIDATED) - { + if ($user->rights->expensereport->approve && $object->status == ExpenseReport::STATUS_VALIDATED) { //if($object->fk_user_validator==$user->id) //{ // Validate @@ -2617,8 +2565,7 @@ if ($action != 'create' && $action != 'edit') print ''; //} - if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) - { + if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) { // Cancel print ''; } @@ -2628,17 +2575,14 @@ if ($action != 'create' && $action != 'edit') // If status is Approved // --------------------- - if ($user->rights->expensereport->approve && $object->status == ExpenseReport::STATUS_APPROVED) - { + if ($user->rights->expensereport->approve && $object->status == ExpenseReport::STATUS_APPROVED) { print ''; } // If bank module is used - if ($user->rights->expensereport->to_paid && !empty($conf->banque->enabled) && $object->status == ExpenseReport::STATUS_APPROVED) - { + if ($user->rights->expensereport->to_paid && !empty($conf->banque->enabled) && $object->status == ExpenseReport::STATUS_APPROVED) { // Pay - if ($remaintopay == 0) - { + if ($remaintopay == 0) { print '
    '.$langs->trans('DoPayment').'
    '; } else { print ''; @@ -2646,30 +2590,25 @@ if ($action != 'create' && $action != 'edit') } // If bank module is not used - if (($user->rights->expensereport->to_paid || empty($conf->banque->enabled)) && $object->status == ExpenseReport::STATUS_APPROVED) - { + if (($user->rights->expensereport->to_paid || empty($conf->banque->enabled)) && $object->status == ExpenseReport::STATUS_APPROVED) { //if ((round($remaintopay) == 0 || empty($conf->banque->enabled)) && $object->paid == 0) - if ($object->paid == 0) - { + if ($object->paid == 0) { print '"; } } - if ($user->rights->expensereport->creer && ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) && $object->status == ExpenseReport::STATUS_APPROVED) - { - // Cancel - print ''; - } - - // TODO Replace this. It should be SetUnpaid and should go back to status unpaid not canceled. - if (($user->rights->expensereport->approve || $user->rights->expensereport->to_paid) && $object->status == ExpenseReport::STATUS_CLOSED) - { + if ($user->rights->expensereport->creer && ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) && $object->status == ExpenseReport::STATUS_APPROVED) { // Cancel print ''; } - if ($user->rights->expensereport->to_paid && $object->paid && $object->status == ExpenseReport::STATUS_CLOSED) - { + // TODO Replace this. It should be SetUnpaid and should go back to status unpaid not canceled. + if (($user->rights->expensereport->approve || $user->rights->expensereport->to_paid) && $object->status == ExpenseReport::STATUS_CLOSED) { + // Cancel + print ''; + } + + if ($user->rights->expensereport->to_paid && $object->paid && $object->status == ExpenseReport::STATUS_CLOSED) { // Set unpaid print ''; } @@ -2680,12 +2619,10 @@ if ($action != 'create' && $action != 'edit') } /* If draft, validated, cancel, and user can create, he can always delete its card before it is approved */ - if ($user->rights->expensereport->creer && $user->id == $object->fk_user_author && $object->status < ExpenseReport::STATUS_APPROVED) - { + if ($user->rights->expensereport->creer && $user->id == $object->fk_user_author && $object->status < ExpenseReport::STATUS_APPROVED) { // Delete print ''; - } elseif ($user->rights->expensereport->supprimer && $object->status != ExpenseReport::STATUS_CLOSED) - { + } elseif ($user->rights->expensereport->supprimer && $object->status != ExpenseReport::STATUS_CLOSED) { // Delete print ''; } @@ -2702,8 +2639,7 @@ if (GETPOST('modelselected', 'alpha')) { $action = 'presend'; } -if ($action != 'presend') -{ +if ($action != 'presend') { /* * Generate documents */ @@ -2711,8 +2647,7 @@ if ($action != 'presend') print '
    '; print ''; // ancre - if ($user->rights->expensereport->creer && $action != 'create' && $action != 'edit') - { + if ($user->rights->expensereport->creer && $action != 'create' && $action != 'edit') { $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref); $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; @@ -2730,7 +2665,7 @@ if ($action != 'presend') $linktoelem = $form->showLinkToObjectBlock($object, null, array('expensereport')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); } - */ + */ print '
    '; // List of actions on element diff --git a/htdocs/expensereport/class/api_expensereports.class.php b/htdocs/expensereport/class/api_expensereports.class.php index aa892e50fc0..98da4534e0c 100644 --- a/htdocs/expensereport/class/api_expensereports.class.php +++ b/htdocs/expensereport/class/api_expensereports.class.php @@ -33,7 +33,7 @@ class ExpenseReports extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'fk_user_author' ); @@ -107,11 +107,12 @@ class ExpenseReports extends DolibarrApi $sql = "SELECT t.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as t"; $sql .= ' WHERE t.entity IN ('.getEntity('expensereport').')'; - if ($user_ids) $sql .= " AND t.fk_user_author IN (".$user_ids.")"; + if ($user_ids) { + $sql .= " AND t.fk_user_author IN (".$user_ids.")"; + } // Add sql filters - if ($sqlfilters) - { + if ($sqlfilters) { if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } @@ -131,13 +132,11 @@ class ExpenseReports extends DolibarrApi $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $expensereport_static = new ExpenseReport($this->db); if ($expensereport_static->fetch($obj->rowid)) { @@ -172,12 +171,12 @@ class ExpenseReports extends DolibarrApi $this->expensereport->$field = $value; } /*if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->expensereport->lines = $lines; - }*/ + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->expensereport->lines = $lines; + }*/ if ($this->expensereport->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating expensereport", array_merge(array($this->expensereport->error), $this->expensereport->errors)); } @@ -195,28 +194,28 @@ class ExpenseReports extends DolibarrApi * @return int */ /* - public function getLines($id) - { - if(! DolibarrApiAccess::$user->rights->expensereport->lire) { - throw new RestException(401); - } + public function getLines($id) + { + if(! DolibarrApiAccess::$user->rights->expensereport->lire) { + throw new RestException(401); + } - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->expensereport->getLinesArray(); - $result = array(); - foreach ($this->expensereport->lines as $line) { - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } - */ + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->expensereport->getLinesArray(); + $result = array(); + foreach ($this->expensereport->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + */ /** * Add a line to given Expense Report @@ -229,56 +228,56 @@ class ExpenseReports extends DolibarrApi * @return int */ /* - public function postLine($id, $request_data = null) - { - if(! DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } + public function postLine($id, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->expensereport->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - $request_data->info_bits, - $request_data->fk_remise_except, - 'HT', - 0, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->array_options, - $request_data->fk_unit, - $this->element, - $request_data->id - ); + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->expensereport->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + $request_data->info_bits, + $request_data->fk_remise_except, + 'HT', + 0, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->array_options, + $request_data->fk_unit, + $this->element, + $request_data->id + ); - if ($updateRes > 0) { - return $updateRes; + if ($updateRes > 0) { + return $updateRes; - } - return false; - } - */ + } + return false; + } + */ /** * Update a line to given Expense Report @@ -292,53 +291,53 @@ class ExpenseReports extends DolibarrApi * @return object */ /* - public function putLine($id, $lineid, $request_data = null) - { - if(! DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } + public function putLine($id, $lineid, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->expensereport->updateline( - $lineid, - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->remise_percent, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - 'HT', - $request_data->info_bits, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->fk_parent_line, - 0, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->special_code, - $request_data->array_options, - $request_data->fk_unit - ); + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->expensereport->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + 'HT', + $request_data->info_bits, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->fk_parent_line, + 0, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->special_code, + $request_data->array_options, + $request_data->fk_unit + ); - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } - return false; - } - */ + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; + } + */ /** * Delete a line of given Expense Report @@ -351,30 +350,30 @@ class ExpenseReports extends DolibarrApi * @return int */ /* - public function deleteLine($id, $lineid) - { - if(! DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } + public function deleteLine($id, $lineid) + { + if(! DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - // TODO Check the lineid $lineid is a line of ojbect + // TODO Check the lineid $lineid is a line of ojbect - $updateRes = $this->expensereport->deleteline($lineid); - if ($updateRes == 1) { - return $this->get($id); - } - return false; - } - */ + $updateRes = $this->expensereport->deleteline($lineid); + if ($updateRes == 1) { + return $this->get($id); + } + return false; + } + */ /** * Update Expense Report general fields (won't touch lines of expensereport) @@ -403,12 +402,13 @@ class ExpenseReports extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->expensereport->$field = $value; } - if ($this->expensereport->update(DolibarrApiAccess::$user) > 0) - { + if ($this->expensereport->update(DolibarrApiAccess::$user) > 0) { return $this->get($id); } else { throw new RestException(500, $this->expensereport->error); @@ -464,31 +464,31 @@ class ExpenseReports extends DolibarrApi * } */ /* - public function validate($id, $idwarehouse=0) - { - if(! DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } + public function validate($id, $idwarehouse=0) + { + if(! DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - if( ! $this->expensereport->valid(DolibarrApiAccess::$user, $idwarehouse)) { - throw new RestException(500, 'Error when validate expensereport'); - } + if( ! $this->expensereport->valid(DolibarrApiAccess::$user, $idwarehouse)) { + throw new RestException(500, 'Error when validate expensereport'); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'expensereport validated' - ) - ); - }*/ + return array( + 'success' => array( + 'code' => 200, + 'message' => 'expensereport validated' + ) + ); + }*/ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore /** @@ -555,8 +555,9 @@ class ExpenseReports extends DolibarrApi { $expensereport = array(); foreach (ExpenseReports::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $expensereport[$field] = $data[$field]; } return $expensereport; diff --git a/htdocs/expensereport/class/expensereport.class.php b/htdocs/expensereport/class/expensereport.class.php index cdc4fe4da5d..89178693a43 100644 --- a/htdocs/expensereport/class/expensereport.class.php +++ b/htdocs/expensereport/class/expensereport.class.php @@ -237,14 +237,15 @@ class ExpenseReport extends CommonObject $error = 0; // Check parameters - if (empty($this->date_debut) || empty($this->date_fin)) - { + if (empty($this->date_debut) || empty($this->date_fin)) { $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date')); return -1; } $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. - if (empty($fuserid)) $fuserid = $user->id; + if (empty($fuserid)) { + $fuserid = $user->id; + } $this->db->begin(); @@ -289,25 +290,20 @@ class ExpenseReport extends CommonObject $sql .= ")"; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); $this->ref = '(PROV'.$this->id.')'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->lasterror(); $error++; } - if (!$error) - { - if (is_array($this->lines) && count($this->lines) > 0) - { - foreach ($this->lines as $line) - { + if (!$error) { + if (is_array($this->lines) && count($this->lines) > 0) { + foreach ($this->lines as $line) { // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. if (!is_object($line)) { @@ -334,8 +330,7 @@ class ExpenseReport extends CommonObject //$newndfline=new ExpenseReportLine($this->db); $newndfline->fk_expensereport = $this->id; $result = $newndfline->insert(); - if ($result < 0) - { + if ($result < 0) { $this->error = $newndfline->error; $this->errors = $newndfline->errors; $error++; @@ -345,19 +340,17 @@ class ExpenseReport extends CommonObject } } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { $result = $this->update_price(); - if ($result > 0) - { - if (!$notrigger) - { + if ($result > 0) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_CREATE', $user); @@ -367,8 +360,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return $this->id; } else { @@ -405,7 +397,9 @@ class ExpenseReport extends CommonObject $error = 0; - if (empty($fk_user_author)) $fk_user_author = $user->id; + if (empty($fk_user_author)) { + $fk_user_author = $user->id; + } $this->db->begin(); @@ -430,10 +424,8 @@ class ExpenseReport extends CommonObject $this->date_validation = ''; // Remove link on lines to a joined file - if (is_array($this->lines) && count($this->lines) > 0) - { - foreach ($this->lines as $key => $line) - { + if (is_array($this->lines) && count($this->lines) > 0) { + foreach ($this->lines as $key => $line) { $this->lines[$key]->fk_ecm_files = 0; } } @@ -441,25 +433,26 @@ class ExpenseReport extends CommonObject // Create clone $this->context['createfromclone'] = 'createfromclone'; $result = $this->create($user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Hook of thirdparty module - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('objFrom'=>$objFrom); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } } } unset($this->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -490,8 +483,7 @@ class ExpenseReport extends CommonObject $sql .= " , total_tva = ".$this->total_tva; $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'"; $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'"; - if ($userofexpensereport && is_object($userofexpensereport)) - { + if ($userofexpensereport && is_object($userofexpensereport)) { $sql .= " , fk_user_author = ".($userofexpensereport->id > 0 ? $userofexpensereport->id : "null"); // Note fk_user_author is not the 'author' but the guy the expense report is for. } $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null"); @@ -507,10 +499,8 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if (!$notrigger) - { + if ($result) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_UPDATE', $user); @@ -520,8 +510,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -556,17 +545,18 @@ class ExpenseReport extends CommonObject $sql .= " d.fk_user_valid, d.fk_user_approve,"; $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d"; - if ($ref) $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'"; - else $sql .= " WHERE d.rowid = ".$id; + if ($ref) { + $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'"; + } else { + $sql .= " WHERE d.rowid = ".((int) $id); + } //$sql.= $restrict; dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $this->id = $obj->rowid; $this->ref = $obj->ref; @@ -599,13 +589,18 @@ class ExpenseReport extends CommonObject $this->fk_user_approve = $obj->fk_user_approve; $user_author = new User($this->db); - if ($this->fk_user_author > 0) $user_author->fetch($this->fk_user_author); + if ($this->fk_user_author > 0) { + $user_author->fetch($this->fk_user_author); + } $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname); $user_approver = new User($this->db); - if ($this->fk_user_approve > 0) $user_approver->fetch($this->fk_user_approve); - elseif ($this->fk_user_validator > 0) $user_approver->fetch($this->fk_user_validator); // For backward compatibility + if ($this->fk_user_approve > 0) { + $user_approver->fetch($this->fk_user_approve); + } elseif ($this->fk_user_validator > 0) { + $user_approver->fetch($this->fk_user_validator); // For backward compatibility + } $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname); $this->fk_statut = $obj->status; // deprecated @@ -613,10 +608,11 @@ class ExpenseReport extends CommonObject $this->fk_c_paiement = $obj->fk_c_paiement; $this->paid = $obj->paid; - if ($this->status == self::STATUS_APPROVED || $this->status == self::STATUS_CLOSED) - { + if ($this->status == self::STATUS_APPROVED || $this->status == self::STATUS_CLOSED) { $user_valid = new User($this->db); - if ($this->fk_user_valid > 0) $user_valid->fetch($this->fk_user_valid); + if ($this->fk_user_valid > 0) { + $user_valid->fetch($this->fk_user_valid); + } $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname); } @@ -671,12 +667,9 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::set_paid sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->affected_rows($resql)) - { - if (!$notrigger) - { + if ($resql) { + if ($this->db->affected_rows($resql)) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_PAID', $fuser); @@ -686,8 +679,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -759,14 +751,12 @@ class ExpenseReport extends CommonObject $sql .= " f.fk_user_valid,"; $sql .= " f.fk_user_approve"; $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f"; - $sql .= " WHERE f.rowid = ".$id; + $sql .= " WHERE f.rowid = ".((int) $id); $sql .= " AND f.entity = ".$conf->entity; $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; @@ -780,26 +770,22 @@ class ExpenseReport extends CommonObject $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; - if ($obj->fk_user_creation) - { + if ($obj->fk_user_creation) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_creation); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_modification) - { + if ($obj->fk_user_modification) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modification); $this->user_modification = $muser; } - if ($obj->fk_user_approve) - { + if ($obj->fk_user_approve) { $auser = new User($this->db); $auser->fetch($obj->fk_user_approve); $this->user_approve = $auser; @@ -898,15 +884,13 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; $total_HT = 0; $total_TTC = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($result); $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut as status"; @@ -953,13 +937,13 @@ class ExpenseReport extends CommonObject break; } /* - if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5'); - if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0'); - if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1'); - if ($status==2) return img_picto($langs->trans('StatusOrderOnProcess'),'statut3'); - if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4'); - if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6'); - */ + if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5'); + if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0'); + if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1'); + if ($status==2) return img_picto($langs->trans('StatusOrderOnProcess'),'statut3'); + if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4'); + if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6'); + */ print ''; print '
    '; @@ -994,11 +978,10 @@ class ExpenseReport extends CommonObject $total_ht = 0; $total_tva = 0; $total_ttc = 0; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num): + while ($i < $num) : $objp = $this->db->fetch_object($result); $total_ht += $objp->total_ht; $total_tva += $objp->total_tva; @@ -1010,9 +993,9 @@ class ExpenseReport extends CommonObject $sql .= " total_ht = ".$total_ht; $sql .= " , total_ttc = ".$total_ttc; $sql .= " , total_tva = ".$total_tva; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); $result = $this->db->query($sql); - if ($result): + if ($result) : $this->db->free($result); return 1; else : @@ -1049,20 +1032,17 @@ class ExpenseReport extends CommonObject $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid'; $sql .= ' WHERE de.'.$this->fk_element.' = '.$this->id; - if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID)) - { + if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID)) { $sql .= ' ORDER BY de.rang ASC, de.rowid ASC'; } else { $sql .= ' ORDER BY de.rang ASC, de.date ASC'; } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($resql); $deplig = new ExpenseReportLine($this->db); @@ -1128,7 +1108,9 @@ class ExpenseReport extends CommonObject if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSEREPORT_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -1148,13 +1130,17 @@ class ExpenseReport extends CommonObject if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } if (!$error) { // Delete linked contacts $res = $this->delete_linked_contact(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } // Removed extrafields of object @@ -1239,8 +1225,7 @@ class ExpenseReport extends CommonObject $now = dol_now(); // Protection - if ($this->status == self::STATUS_VALIDATED) - { + if ($this->status == self::STATUS_VALIDATED) { dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); return 0; } @@ -1248,13 +1233,14 @@ class ExpenseReport extends CommonObject $this->date_valid = $now; // Required for the getNextNum later. // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef(); } else { $num = $this->ref; } - if (empty($num) || $num < 0) return -1; + if (empty($num) || $num < 0) { + return -1; + } $this->newref = dol_sanitizeFileName($num); @@ -1269,10 +1255,8 @@ class ExpenseReport extends CommonObject $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { - if (!$error && !$notrigger) - { + if ($resql) { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_VALIDATE', $fuser); if ($result < 0) { @@ -1281,37 +1265,34 @@ class ExpenseReport extends CommonObject // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expensereport/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->expensereport->dir_output.'/'.$oldref; $dirdest = $conf->expensereport->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->expensereport->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -1324,14 +1305,12 @@ class ExpenseReport extends CommonObject } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $num; $this->status = self::STATUS_VALIDATED; } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -1369,16 +1348,14 @@ class ExpenseReport extends CommonObject $this->date_debut = $this->db->jdate($objp->date_debut); - if ($this->status != self::STATUS_VALIDATED) - { + if ($this->status != self::STATUS_VALIDATED) { $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= " SET fk_statut = ".self::STATUS_VALIDATED; $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::set_save_from_refuse sql=".$sql, LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { return 1; } else { $this->error = $this->db->lasterror(); @@ -1403,18 +1380,15 @@ class ExpenseReport extends CommonObject // date approval $this->date_approve = $now; - if ($this->status != self::STATUS_APPROVED) - { + if ($this->status != self::STATUS_APPROVED) { $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".$fuser->id.","; $sql .= " date_approve='".$this->db->idate($this->date_approve)."'"; $sql .= ' WHERE rowid = '.$this->id; - if ($this->db->query($sql)) - { - if (!$notrigger) - { + if ($this->db->query($sql)) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_APPROVE', $fuser); @@ -1424,8 +1398,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -1459,24 +1432,21 @@ class ExpenseReport extends CommonObject $error = 0; // date de refus - if ($this->status != self::STATUS_REFUSED) - { + if ($this->status != self::STATUS_REFUSED) { $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".$fuser->id.","; $sql .= " date_refuse='".$this->db->idate($now)."',"; $sql .= " detail_refuse='".$this->db->escape($details)."',"; $sql .= " fk_user_approve = NULL"; $sql .= ' WHERE rowid = '.$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->fk_statut = 99; // deprecated $this->status = 99; $this->fk_user_refuse = $fuser->id; $this->detail_refuse = $details; $this->date_refuse = $now; - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_DENY', $fuser); @@ -1486,8 +1456,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -1533,8 +1502,7 @@ class ExpenseReport extends CommonObject { $error = 0; - if ($this->paid) - { + if ($this->paid) { $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; @@ -1543,10 +1511,8 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::set_unpaid sql=".$sql, LOG_DEBUG); - if ($this->db->query($sql)) - { - if (!$notrigger) - { + if ($this->db->query($sql)) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_UNPAID', $fuser); @@ -1556,8 +1522,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -1589,8 +1554,7 @@ class ExpenseReport extends CommonObject // phpcs:enable $error = 0; $this->date_cancel = $this->db->idate(dol_now()); - if ($this->status != self::STATUS_CANCELED) - { + if ($this->status != self::STATUS_CANCELED) { $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; @@ -1601,10 +1565,8 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::set_cancel sql=".$sql, LOG_DEBUG); - if ($this->db->query($sql)) - { - if (!$notrigger) - { + if ($this->db->query($sql)) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_CANCEL', $fuser); @@ -1614,8 +1576,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -1643,8 +1604,7 @@ class ExpenseReport extends CommonObject global $langs, $conf; $langs->load("trips"); - if (!empty($conf->global->EXPENSEREPORT_ADDON)) - { + if (!empty($conf->global->EXPENSEREPORT_ADDON)) { $mybool = false; $file = $conf->global->EXPENSEREPORT_ADDON.".php"; @@ -1652,8 +1612,7 @@ class ExpenseReport extends CommonObject // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/expensereport/"); // Load file with numbering class (if found) @@ -1668,8 +1627,7 @@ class ExpenseReport extends CommonObject $obj = new $classname(); $numref = $obj->getNextValue($this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -1702,38 +1660,50 @@ class ExpenseReport extends CommonObject $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id; - if ($short) return $url; + if ($short) { + return $url; + } $label = img_picto('', $this->picto).' '.$langs->trans("ExpenseReport").''; if (isset($this->status)) { $label .= ' '.$this->getLibStatut(5); } - if (!empty($this->ref)) + if (!empty($this->ref)) { $label .= '
    '.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->total_ht)) + } + if (!empty($this->total_ht)) { $label .= '
    '.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_tva)) + } + if (!empty($this->total_tva)) { $label .= '
    '.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_ttc)) + } + if (!empty($this->total_ttc)) { $label .= '
    '.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - if ($moretitle) $label .= ' - '.$moretitle; + } + if ($moretitle) { + $label .= ' - '.$moretitle; + } //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'; + } //} $ref = $this->ref; - if (empty($ref)) $ref = $this->id; + if (empty($ref)) { + $ref = $this->id; + } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowExpenseReport"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -1746,8 +1716,12 @@ class ExpenseReport extends CommonObject $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= ($max ?dol_trunc($ref, $max) : $ref); + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= ($max ?dol_trunc($ref, $max) : $ref); + } $result .= $linkend; return $result; @@ -1775,7 +1749,7 @@ class ExpenseReport extends CommonObject $sql .= " WHERE rowid = ".$this->id; $result = $this->db->query($sql); - if ($result): + if ($result) : return 1; else : $this->error = $this->db->error(); @@ -1805,7 +1779,7 @@ class ExpenseReport extends CommonObject $sql .= " WHERE rowid = ".$this->id; $result = $this->db->query($sql); - if ($result): + if ($result) : return 1; else : $this->error = $this->db->error(); @@ -1834,14 +1808,25 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::addline qty=$qty, up=$up, fk_c_type_fees=$fk_c_type_fees, vatrate=$vatrate, date=$date, fk_project=$fk_project, type=$type, comments=$comments", LOG_DEBUG); - if ($this->status == self::STATUS_DRAFT) - { - if (empty($qty)) $qty = 0; - if (empty($fk_c_type_fees) || $fk_c_type_fees < 0) $fk_c_type_fees = 0; - if (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) $fk_c_exp_tax_cat = 0; - if (empty($vatrate) || $vatrate < 0) $vatrate = 0; - if (empty($date)) $date = ''; - if (empty($fk_project)) $fk_project = 0; + if ($this->status == self::STATUS_DRAFT) { + if (empty($qty)) { + $qty = 0; + } + if (empty($fk_c_type_fees) || $fk_c_type_fees < 0) { + $fk_c_type_fees = 0; + } + if (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) { + $fk_c_exp_tax_cat = 0; + } + if (empty($vatrate) || $vatrate < 0) { + $vatrate = 0; + } + if (empty($date)) { + $date = ''; + } + if (empty($fk_project)) { + $fk_project = 0; + } $qty = price2num($qty); if (!preg_match('/\s*\((.*)\)/', $vatrate)) { @@ -1857,8 +1842,7 @@ class ExpenseReport extends CommonObject $vat_src_code = ''; $reg = array(); - if (preg_match('/\s*\((.*)\)/', $vatrate, $reg)) - { + if (preg_match('/\s*\((.*)\)/', $vatrate, $reg)) { $vat_src_code = $reg[1]; $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. } @@ -1890,11 +1874,9 @@ class ExpenseReport extends CommonObject $this->checkRules($type, $seller); $result = $this->line->insert(0, true); - if ($result > 0) - { + if ($result > 0) { $result = $this->update_price(); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return $this->line->id; } else { @@ -1927,7 +1909,9 @@ class ExpenseReport extends CommonObject $langs->load('trips'); - if (empty($conf->global->MAIN_USE_EXPENSE_RULE)) return true; // if don't use rules + if (empty($conf->global->MAIN_USE_EXPENSE_RULE)) { + return true; // if don't use rules + } $rulestocheck = ExpenseReportRule::getAllRule($this->line->fk_c_type_fees, $this->line->date, $this->fk_user_author); @@ -1938,19 +1922,19 @@ class ExpenseReport extends CommonObject $new_current_total_ttc = $this->line->total_ttc; // check if one is violated - foreach ($rulestocheck as $rule) - { - if (in_array($rule->code_expense_rules_type, array('EX_DAY', 'EX_MON', 'EX_YEA'))) $amount_to_test = $this->line->getExpAmount($rule, $this->fk_user_author, $rule->code_expense_rules_type); - else $amount_to_test = $current_total_ttc; // EX_EXP + foreach ($rulestocheck as $rule) { + if (in_array($rule->code_expense_rules_type, array('EX_DAY', 'EX_MON', 'EX_YEA'))) { + $amount_to_test = $this->line->getExpAmount($rule, $this->fk_user_author, $rule->code_expense_rules_type); + } else { + $amount_to_test = $current_total_ttc; // EX_EXP + } $amount_to_test = $amount_to_test - $current_total_ttc + $new_current_total_ttc; // if amount as been modified by a previous rule - if ($amount_to_test > $rule->amount) - { + if ($amount_to_test > $rule->amount) { $violation++; - if ($rule->restrictive) - { + if ($rule->restrictive) { $this->error = 'ExpenseReportConstraintViolationError'; $this->errors[] = $this->error; @@ -1969,8 +1953,7 @@ class ExpenseReport extends CommonObject $this->line->rule_warning_message = implode('\n', $rule_warning_message_tab); - if ($violation > 0) - { + if ($violation > 0) { $tmp = calcul_price_total($this->line->qty, $new_current_total_ttc / $this->line->qty, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller); $this->line->value_unit = $tmp[5]; @@ -1979,7 +1962,9 @@ class ExpenseReport extends CommonObject $this->line->total_tva = $tmp[1]; return false; - } else return true; + } else { + return true; + } } /** @@ -1991,11 +1976,12 @@ class ExpenseReport extends CommonObject { global $conf; - if (empty($conf->global->MAIN_USE_EXPENSE_IK)) return false; + if (empty($conf->global->MAIN_USE_EXPENSE_IK)) { + return false; + } $userauthor = new User($this->db); - if ($userauthor->fetch($this->fk_user_author) <= 0) - { + if ($userauthor->fetch($this->fk_user_author) <= 0) { $this->error = 'ErrorCantFetchUser'; $this->errors[] = 'ErrorCantFetchUser'; return false; @@ -2003,19 +1989,20 @@ class ExpenseReport extends CommonObject $range = ExpenseReportIk::getRangeByUser($userauthor, $this->line->fk_c_exp_tax_cat); - if (empty($range)) - { + if (empty($range)) { $this->error = 'ErrorNoRangeAvailable'; $this->errors[] = 'ErrorNoRangeAvailable'; return false; } - if (!empty($conf->global->MAIN_EXPENSE_APPLY_ENTIRE_OFFSET)) $ikoffset = $range->ikoffset; - else $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year + if (!empty($conf->global->MAIN_EXPENSE_APPLY_ENTIRE_OFFSET)) { + $ikoffset = $range->ikoffset; + } else { + $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year + } // Test if ikoffset has been applied for the current month - if (!$this->offsetAlreadyGiven()) - { + if (!$this->offsetAlreadyGiven()) { $new_up = $range->coef + ($ikoffset / $this->line->qty); $tmp = calcul_price_total($this->line->qty, $new_up, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller); @@ -2042,14 +2029,17 @@ class ExpenseReport extends CommonObject $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'c_type_fees f ON (d.fk_c_type_fees = f.id AND f.code = "EX_KME")'; $sql .= ' WHERE e.fk_user_author = '.(int) $this->fk_user_author; $sql .= ' AND YEAR(d.date) = "'.dol_print_date($this->line->date, '%Y').'" AND MONTH(d.date) = "'.dol_print_date($this->line->date, '%m').'"'; - if (!empty($this->line->id)) $sql .= ' AND d.rowid <> '.$this->line->id; + if (!empty($this->line->id)) { + $sql .= ' AND d.rowid <> '.$this->line->id; + } dol_syslog(get_class($this)."::offsetAlreadyGiven sql=".$sql); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num > 0) return true; + if ($num > 0) { + return true; + } } else { dol_print_error($this->db); } @@ -2077,8 +2067,7 @@ class ExpenseReport extends CommonObject { global $user, $mysoc; - if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED) - { + if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED) { $this->db->begin(); $type = 0; // TODO What if type is service ? @@ -2092,8 +2081,7 @@ class ExpenseReport extends CommonObject // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $vatrate, $reg)) - { + if (preg_match('/\((.*)\)/', $vatrate, $reg)) { $vat_src_code = $reg[1]; $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. } @@ -2138,8 +2126,7 @@ class ExpenseReport extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c"; $sql .= " WHERE c.id = ".$type_fees_id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $objp_fees = $this->db->fetch_object($resql); $this->line->type_fees_code = $objp_fees->code_type_fees; $this->line->type_fees_libelle = $objp_fees->libelle_type_fees; @@ -2162,8 +2149,7 @@ class ExpenseReport extends CommonObject $this->checkRules(); $result = $this->line->update($user); - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return 1; } else { @@ -2191,8 +2177,7 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::deleteline sql=".$sql); $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $this->error = $this->db->error(); dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR); $this->db->rollback(); @@ -2225,27 +2210,30 @@ class ExpenseReport extends CommonObject if ($result) { $num_rows = $this->db->num_rows($result); $i = 0; - if ($num_rows > 0) - { + if ($num_rows > 0) { $date_d_form = $date_debut; $date_f_form = $date_fin; $existe = false; - while ($i < $num_rows) - { + while ($i < $num_rows) { $objp = $this->db->fetch_object($result); $date_d_req = $this->db->jdate($objp->date_debut); // 3 $date_f_req = $this->db->jdate($objp->date_fin); // 4 - if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) $existe = true; + if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) { + $existe = true; + } $i++; } - if ($existe) return 1; - else return 0; + if ($existe) { + return 1; + } else { + return 0; + } } else { return 0; } @@ -2280,11 +2268,9 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num_rows = $this->db->num_rows($result); $i = 0; - while ($i < $num_rows) - { + while ($i < $num_rows) { $objp = $this->db->fetch_object($result); array_push($users_validator, $objp->fk_user); $i++; @@ -2348,12 +2334,10 @@ class ExpenseReport extends CommonObject $sql .= " WHERE active = ".$active; dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $ret[$obj->code] = (($langs->transnoentitiesnoconv($obj->code) != $obj->code) ? $langs->transnoentitiesnoconv($obj->code) : $obj->label); $i++; @@ -2381,8 +2365,7 @@ class ExpenseReport extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; $sql .= " WHERE ex.fk_statut > 0"; $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; - if (empty($user->rights->expensereport->readall)) - { + if (empty($user->rights->expensereport->readall)) { $userchildids = $user->getAllChildIds(1); $sql .= " AND (ex.fk_user_author IN (".join(',', $userchildids).")"; $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))"; @@ -2415,30 +2398,32 @@ class ExpenseReport 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(); $sql = "SELECT ex.rowid, ex.date_valid"; $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; - if ($option == 'toapprove') $sql .= " WHERE ex.fk_statut = ".self::STATUS_VALIDATED; - else $sql .= " WHERE ex.fk_statut = ".self::STATUS_APPROVED; + if ($option == 'toapprove') { + $sql .= " WHERE ex.fk_statut = ".self::STATUS_VALIDATED; + } else { + $sql .= " WHERE ex.fk_statut = ".self::STATUS_APPROVED; + } $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; - if (empty($user->rights->expensereport->readall)) - { + if (empty($user->rights->expensereport->readall)) { $userchildids = $user->getAllChildIds(1); $sql .= " AND (ex.fk_user_author IN (".join(',', $userchildids).")"; $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))"; } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $langs->load("trips"); $response = new WorkboardResponse(); - if ($option == 'toapprove') - { + if ($option == 'toapprove') { $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24; $response->label = $langs->trans("ExpenseReportsToApprove"); $response->labelShort = $langs->trans("ToApprove"); @@ -2451,12 +2436,10 @@ class ExpenseReport extends CommonObject } $response->img = img_object('', "trip"); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; - if ($option == 'toapprove') - { + if ($option == 'toapprove') { if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) { $response->nbtodolate++; } @@ -2486,8 +2469,12 @@ class ExpenseReport extends CommonObject global $conf; // Only valid expenses reports - if ($option == 'toapprove' && $this->status != 2) return false; - if ($option == 'topay' && $this->status != 5) return false; + if ($option == 'toapprove' && $this->status != 2) { + return false; + } + if ($option == 'topay' && $this->status != 5) { + return false; + } $now = dol_now(); if ($option == 'toapprove') { @@ -2510,11 +2497,9 @@ class ExpenseReport extends CommonObject $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$this->db->escape($type)."' AND ab.fk_doc = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $alreadydispatched = $obj->nb; } } else { @@ -2522,8 +2507,7 @@ class ExpenseReport extends CommonObject return -1; } - if ($alreadydispatched) - { + if ($alreadydispatched) { return 1; } return 0; @@ -2545,8 +2529,7 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::getSumPayments", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $this->db->free($resql); return (empty($obj->amount) ? 0 : $obj->amount); @@ -2649,8 +2632,7 @@ class ExpenseReportLine $result = $this->db->query($sql); - if ($result) - { + if ($result) { $objp = $this->db->fetch_object($result); $this->rowid = $objp->rowid; @@ -2700,10 +2682,14 @@ class ExpenseReportLine // Clean parameters $this->comments = trim($this->comments); - if (empty($this->value_unit)) $this->value_unit = 0; + if (empty($this->value_unit)) { + $this->value_unit = 0; + } $this->qty = price2num($this->qty); $this->vatrate = price2num($this->vatrate); - if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0; + if (empty($this->fk_c_exp_tax_cat)) { + $this->fk_c_exp_tax_cat = 0; + } $this->db->begin(); @@ -2728,17 +2714,14 @@ class ExpenseReportLine $sql .= ")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det'); - if (!$fromaddline) - { + if (!$fromaddline) { $tmpparent = new ExpenseReport($this->db); $tmpparent->fetch($this->fk_expensereport); $result = $tmpparent->update_price(); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $tmpparent->error; $this->errors = $tmpparent->errors; @@ -2748,8 +2731,7 @@ class ExpenseReportLine $error++; } - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -2776,20 +2758,24 @@ class ExpenseReportLine $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det d'; $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'expensereport e ON (d.fk_expensereport = e.rowid)'; $sql .= ' WHERE e.fk_user_author = '.$fk_user; - if (!empty($this->id)) $sql .= ' AND d.rowid <> '.$this->id; + if (!empty($this->id)) { + $sql .= ' AND d.rowid <> '.$this->id; + } $sql .= ' AND d.fk_c_type_fees = '.$rule->fk_c_type_fees; - if ($mode == 'day' || $mode == 'EX_DAY') $sql .= ' AND d.date = \''.dol_print_date($this->date, '%Y-%m-%d').'\''; - elseif ($mode == 'mon' || $mode == 'EX_MON') $sql .= ' AND DATE_FORMAT(d.date, \'%Y-%m\') = \''.dol_print_date($this->date, '%Y-%m').'\''; // @todo DATE_FORMAT is forbidden - elseif ($mode == 'year' || $mode == 'EX_YEA') $sql .= ' AND DATE_FORMAT(d.date, \'%Y\') = \''.dol_print_date($this->date, '%Y').'\''; // @todo DATE_FORMAT is forbidden + if ($mode == 'day' || $mode == 'EX_DAY') { + $sql .= ' AND d.date = \''.dol_print_date($this->date, '%Y-%m-%d').'\''; + } elseif ($mode == 'mon' || $mode == 'EX_MON') { + $sql .= ' AND DATE_FORMAT(d.date, \'%Y-%m\') = \''.dol_print_date($this->date, '%Y-%m').'\''; // @todo DATE_FORMAT is forbidden + } elseif ($mode == 'year' || $mode == 'EX_YEA') { + $sql .= ' AND DATE_FORMAT(d.date, \'%Y\') = \''.dol_print_date($this->date, '%Y').'\''; // @todo DATE_FORMAT is forbidden + } dol_syslog('ExpenseReportLine::getExpAmount'); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { $obj = $this->db->fetch_object($resql); $amount = (double) $obj->total_amount; } @@ -2816,7 +2802,9 @@ class ExpenseReportLine $this->comments = trim($this->comments); $this->vatrate = price2num($this->vatrate); $this->value_unit = price2num($this->value_unit); - if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0; + if (empty($this->fk_c_exp_tax_cat)) { + $this->fk_c_exp_tax_cat = 0; + } $this->db->begin(); @@ -2834,24 +2822,27 @@ class ExpenseReportLine $sql .= ",rule_warning_message='".$this->db->escape($this->rule_warning_message)."'"; $sql .= ",fk_c_exp_tax_cat=".$this->db->escape($this->fk_c_exp_tax_cat); $sql .= ",fk_ecm_files=".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null'); - if ($this->fk_c_type_fees) $sql .= ",fk_c_type_fees=".$this->db->escape($this->fk_c_type_fees); - else $sql .= ",fk_c_type_fees=null"; - if ($this->fk_project > 0) $sql .= ",fk_projet=".$this->db->escape($this->fk_project); - else $sql .= ",fk_projet=null"; + if ($this->fk_c_type_fees) { + $sql .= ",fk_c_type_fees=".$this->db->escape($this->fk_c_type_fees); + } else { + $sql .= ",fk_c_type_fees=null"; + } + if ($this->fk_project > 0) { + $sql .= ",fk_projet=".$this->db->escape($this->fk_project); + } else { + $sql .= ",fk_projet=null"; + } $sql .= " WHERE rowid = ".$this->db->escape($this->rowid ? $this->rowid : $this->id); dol_syslog("ExpenseReportLine::update sql=".$sql); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $tmpparent = new ExpenseReport($this->db); $result = $tmpparent->fetch($this->fk_expensereport); - if ($result > 0) - { + if ($result > 0) { $result = $tmpparent->update_price(); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $tmpparent->error; $this->errors = $tmpparent->errors; @@ -2866,8 +2857,7 @@ class ExpenseReportLine dol_print_error($this->db); } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { diff --git a/htdocs/expensereport/class/expensereport_ik.class.php b/htdocs/expensereport/class/expensereport_ik.class.php index 55af1eb00ed..18a0503cdd7 100644 --- a/htdocs/expensereport/class/expensereport_ik.class.php +++ b/htdocs/expensereport/class/expensereport_ik.class.php @@ -111,15 +111,16 @@ class ExpenseReportIk extends CoreObject $sql = 'SELECT rowid, label, entity, active'; $sql .= ' FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat'; $sql .= ' WHERE entity IN ('.getEntity('c_exp_tax_cat').')'; - if ($mode == 1) $sql .= ' AND active = 1'; - elseif ($mode == 2) $sql .= 'AND active = 0'; + if ($mode == 1) { + $sql .= ' AND active = 1'; + } elseif ($mode == 2) { + $sql .= 'AND active = 0'; + } dol_syslog(get_called_class().'::getTaxCategories sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $db->fetch_object($resql)) { $categories[$obj->rowid] = $obj; } } else { @@ -142,8 +143,11 @@ class ExpenseReportIk extends CoreObject $ranges = self::getRangesByCategory($fk_c_exp_tax_cat); // substract 1 because array start from 0 - if (empty($ranges) || !isset($ranges[$default_range - 1])) return false; - else return $ranges[$default_range - 1]; + if (empty($ranges) || !isset($ranges[$default_range - 1])) { + return false; + } else { + return $ranges[$default_range - 1]; + } } /** @@ -160,20 +164,21 @@ class ExpenseReportIk extends CoreObject $ranges = array(); $sql = 'SELECT r.rowid FROM '.MAIN_DB_PREFIX.'c_exp_tax_range r'; - if ($active) $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'c_exp_tax_cat c ON (r.fk_c_exp_tax_cat = c.rowid)'; + if ($active) { + $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'c_exp_tax_cat c ON (r.fk_c_exp_tax_cat = c.rowid)'; + } $sql .= ' WHERE r.fk_c_exp_tax_cat = '.$fk_c_exp_tax_cat; - if ($active) $sql .= ' AND r.active = 1 AND c.active = 1'; + if ($active) { + $sql .= ' AND r.active = 1 AND c.active = 1'; + } $sql .= ' ORDER BY r.range_ik'; dol_syslog(get_called_class().'::getRangesByCategory sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num > 0) - { - while ($obj = $db->fetch_object($resql)) - { + if ($num > 0) { + while ($obj = $db->fetch_object($resql)) { $object = new ExpenseReportIk($db); $object->fetch($obj->rowid); @@ -207,15 +212,17 @@ class ExpenseReportIk extends CoreObject dol_syslog(get_called_class().'::getAllRanges sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $db->fetch_object($resql)) { $ik = new ExpenseReportIk($db); - if ($obj->fk_expense_ik > 0) $ik->fetch($obj->fk_expense_ik); + if ($obj->fk_expense_ik > 0) { + $ik->fetch($obj->fk_expense_ik); + } $obj->ik = $ik; - if (!isset($ranges[$obj->fk_c_exp_tax_cat])) $ranges[$obj->fk_c_exp_tax_cat] = array('label' => $obj->label, 'active' => $obj->cat_active, 'ranges' => array()); + if (!isset($ranges[$obj->fk_c_exp_tax_cat])) { + $ranges[$obj->fk_c_exp_tax_cat] = array('label' => $obj->label, 'active' => $obj->cat_active, 'ranges' => array()); + } $ranges[$obj->fk_c_exp_tax_cat]['ranges'][] = $obj; } } else { @@ -239,14 +246,15 @@ class ExpenseReportIk extends CoreObject $sql .= ' SELECT COUNT(*) as counted'; $sql .= ' FROM '.MAIN_DB_PREFIX.'c_exp_tax_range r'; $sql .= ' WHERE r.entity IN (0, '.$conf->entity.')'; - if ($default_c_exp_tax_cat > 0) $sql .= ' AND r.fk_c_exp_tax_cat = '.$default_c_exp_tax_cat; + if ($default_c_exp_tax_cat > 0) { + $sql .= ' AND r.fk_c_exp_tax_cat = '.$default_c_exp_tax_cat; + } $sql .= ' GROUP BY r.fk_c_exp_tax_cat'; $sql .= ') as counts'; dol_syslog(get_called_class().'::getMaxRangeNumber sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); return $obj->nbRange; } else { diff --git a/htdocs/expensereport/class/expensereport_rule.class.php b/htdocs/expensereport/class/expensereport_rule.class.php index 9a172cd7563..4e4d1009750 100644 --- a/htdocs/expensereport/class/expensereport_rule.class.php +++ b/htdocs/expensereport/class/expensereport_rule.class.php @@ -156,18 +156,15 @@ class ExpenseReportRule extends CoreObject $sql = 'SELECT er.rowid'; $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_rules er'; $sql .= ' WHERE er.entity IN (0,'.getEntity('').')'; - if (!empty($fk_c_type_fees)) - { + if (!empty($fk_c_type_fees)) { $sql .= ' AND er.fk_c_type_fees IN (-1, '.$fk_c_type_fees.')'; } - if (!empty($date)) - { + if (!empty($date)) { $date = dol_print_date($date, '%Y-%m-%d'); $sql .= ' AND er.dates <= \''.$date.'\''; $sql .= ' AND er.datee >= \''.$date.'\''; } - if ($fk_user > 0) - { + if ($fk_user > 0) { $sql .= ' AND (er.is_for_all = 1'; $sql .= ' OR er.fk_user = '.$fk_user; $sql .= ' OR er.fk_usergroup IN (SELECT ugu.fk_usergroup FROM '.MAIN_DB_PREFIX.'usergroup_user ugu WHERE ugu.fk_user = '.$fk_user.') )'; @@ -177,13 +174,14 @@ class ExpenseReportRule extends CoreObject dol_syslog("ExpenseReportRule::getAllRule sql=".$sql); $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $db->fetch_object($resql)) { $rule = new ExpenseReportRule($db); - if ($rule->fetch($obj->rowid) > 0) $rules[$rule->id] = $rule; - else dol_print_error($db); + if ($rule->fetch($obj->rowid) > 0) { + $rules[$rule->id] = $rule; + } else { + dol_print_error($db); + } } } else { dol_print_error($db); @@ -201,11 +199,9 @@ class ExpenseReportRule extends CoreObject { include_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php'; - if ($this->fk_usergroup > 0) - { + if ($this->fk_usergroup > 0) { $group = new UserGroup($this->db); - if ($group->fetch($this->fk_usergroup) > 0) - { + if ($group->fetch($this->fk_usergroup) > 0) { return $group->nom; } else { $this->error = $group->error; @@ -225,11 +221,9 @@ class ExpenseReportRule extends CoreObject { include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; - if ($this->fk_user > 0) - { + if ($this->fk_user > 0) { $u = new User($this->db); - if ($u->fetch($this->fk_user) > 0) - { + if ($u->fetch($this->fk_user) > 0) { return dolGetFirstLastname($u->firstname, $u->lastname); } else { $this->error = $u->error; diff --git a/htdocs/expensereport/class/expensereportstats.class.php b/htdocs/expensereport/class/expensereportstats.class.php index c4167e3002f..3d627cbce8d 100644 --- a/htdocs/expensereport/class/expensereportstats.class.php +++ b/htdocs/expensereport/class/expensereportstats.class.php @@ -70,20 +70,20 @@ class ExpenseReportStats extends Stats $this->where .= ' e.entity IN ('.getEntity('expensereport').')'; //$this->where.= " AND entity = ".$conf->entity; - if ($this->socid) - { + if ($this->socid) { $this->where .= " AND e.fk_soc = ".$this->socid; } // Only me and subordinates - if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) - { + if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) { $childids = $user->getAllChildIds(); $childids[] = $user->id; $this->where .= " AND e.fk_user_author IN (".(join(',', $childids)).")"; } - if ($this->userid > 0) $this->where .= ' AND e.fk_user_author = '.$this->userid; + if ($this->userid > 0) { + $this->where .= ' AND e.fk_user_author = '.$this->userid; + } } diff --git a/htdocs/expensereport/class/paymentexpensereport.class.php b/htdocs/expensereport/class/paymentexpensereport.class.php index be8693f223e..c9cf0cdaf41 100644 --- a/htdocs/expensereport/class/paymentexpensereport.class.php +++ b/htdocs/expensereport/class/paymentexpensereport.class.php @@ -119,19 +119,36 @@ class PaymentExpenseReport extends CommonObject } // Clean parameters - if (isset($this->fk_expensereport)) $this->fk_expensereport = trim($this->fk_expensereport); - if (isset($this->amount)) $this->amount = trim($this->amount); - if (isset($this->fk_typepayment)) $this->fk_typepayment = trim($this->fk_typepayment); - if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); - if (isset($this->note)) $this->note = trim($this->note); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->fk_bank)) $this->fk_bank = trim($this->fk_bank); - if (isset($this->fk_user_creat)) $this->fk_user_creat = trim($this->fk_user_creat); - if (isset($this->fk_user_modif)) $this->fk_user_modif = trim($this->fk_user_modif); + if (isset($this->fk_expensereport)) { + $this->fk_expensereport = trim($this->fk_expensereport); + } + if (isset($this->amount)) { + $this->amount = trim($this->amount); + } + if (isset($this->fk_typepayment)) { + $this->fk_typepayment = trim($this->fk_typepayment); + } + if (isset($this->num_payment)) { + $this->num_payment = trim($this->num_payment); + } + if (isset($this->note)) { + $this->note = trim($this->note); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->fk_bank)) { + $this->fk_bank = trim($this->fk_bank); + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = trim($this->fk_user_creat); + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = trim($this->fk_user_modif); + } $totalamount = 0; - foreach ($this->amounts as $key => $value) // How payment is dispatch - { + foreach ($this->amounts as $key => $value) { // How payment is dispatch $newvalue = price2num($value, 'MT'); $this->amounts[$key] = $newvalue; $totalamount += $newvalue; @@ -139,13 +156,14 @@ class PaymentExpenseReport extends CommonObject $totalamount = price2num($totalamount); // Check parameters - if ($totalamount == 0) return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null + if ($totalamount == 0) { + return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null + } $this->db->begin(); - if ($totalamount != 0) - { + if ($totalamount != 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_expensereport (fk_expensereport, datec, datep, amount,"; $sql .= " fk_typepayment, num_payment, note, fk_user_creat, fk_bank)"; $sql .= " VALUES ($this->fk_expensereport, '".$this->db->idate($now)."',"; @@ -156,16 +174,14 @@ class PaymentExpenseReport extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_expensereport"); } else { $error++; } } - if ($totalamount != 0 && !$error) - { + if ($totalamount != 0 && !$error) { $this->amount = $totalamount; $this->db->commit(); return $this->id; @@ -202,14 +218,12 @@ class PaymentExpenseReport extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."payment_expensereport as t"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = 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); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -258,14 +272,30 @@ class PaymentExpenseReport extends CommonObject // Clean parameters - if (isset($this->fk_expensereport)) $this->fk_expensereport = trim($this->fk_expensereport); - if (isset($this->amount)) $this->amount = trim($this->amount); - if (isset($this->fk_typepayment)) $this->fk_typepayment = trim($this->fk_typepayment); - if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); - if (isset($this->note)) $this->note = trim($this->note); - if (isset($this->fk_bank)) $this->fk_bank = trim($this->fk_bank); - if (isset($this->fk_user_creat)) $this->fk_user_creat = trim($this->fk_user_creat); - if (isset($this->fk_user_modif)) $this->fk_user_modif = trim($this->fk_user_modif); + if (isset($this->fk_expensereport)) { + $this->fk_expensereport = trim($this->fk_expensereport); + } + if (isset($this->amount)) { + $this->amount = trim($this->amount); + } + if (isset($this->fk_typepayment)) { + $this->fk_typepayment = trim($this->fk_typepayment); + } + if (isset($this->num_payment)) { + $this->num_payment = trim($this->num_payment); + } + if (isset($this->note)) { + $this->note = trim($this->note); + } + if (isset($this->fk_bank)) { + $this->fk_bank = trim($this->fk_bank); + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = trim($this->fk_user_creat); + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = trim($this->fk_user_modif); + } // Check parameters @@ -287,19 +317,19 @@ class PaymentExpenseReport 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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -327,20 +357,20 @@ class PaymentExpenseReport extends CommonObject $this->db->begin(); - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url"; $sql .= " WHERE type='payment_expensereport' AND url_id=".$this->id; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_expensereport"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); @@ -351,10 +381,8 @@ class PaymentExpenseReport extends CommonObject } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -396,8 +424,7 @@ class PaymentExpenseReport extends CommonObject $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $error++; } @@ -405,8 +432,7 @@ class PaymentExpenseReport extends CommonObject unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { @@ -487,8 +513,7 @@ class PaymentExpenseReport extends CommonObject $error = 0; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $acc = new Account($this->db); @@ -497,7 +522,9 @@ class PaymentExpenseReport extends CommonObject //Fix me field $total = $this->amount; - if ($mode == 'payment_expensereport') $amount = $total; + if ($mode == 'payment_expensereport') { + $amount = $total; + } // Insert payment into llx_bank $bank_line_id = $acc->addline( @@ -514,35 +541,30 @@ class PaymentExpenseReport extends CommonObject // Update fk_bank in llx_paiement. // On connait ainsi le paiement qui a genere l'ecriture bancaire - if ($bank_line_id > 0) - { + if ($bank_line_id > 0) { $result = $this->update_fk_bank($bank_line_id); - if ($result <= 0) - { + if ($result <= 0) { $error++; dol_print_error($this->db); } // Add link 'payment', 'payment_supplier', 'payment_expensereport' in bank_url between payment and bank transaction $url = ''; - if ($mode == 'payment_expensereport') $url = DOL_URL_ROOT.'/expensereport/payment/card.php?rowid='; - if ($url) - { + if ($mode == 'payment_expensereport') { + $url = DOL_URL_ROOT.'/expensereport/payment/card.php?rowid='; + } + if ($url) { $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); - if ($result <= 0) - { + if ($result <= 0) { $error++; dol_print_error($this->db); } } // Add link 'user' in bank_url between user and bank transaction - if (!$error) - { - foreach ($this->amounts as $key => $value) // We should have always same user but we loop in case of. - { - if ($mode == 'payment_expensereport') - { + if (!$error) { + foreach ($this->amounts as $key => $value) { // We should have always same user but we loop in case of. + if ($mode == 'payment_expensereport') { $fuser = new User($this->db); $fuser->fetch($key); @@ -553,8 +575,7 @@ class PaymentExpenseReport extends CommonObject $fuser->getFullName($langs), 'user' ); - if ($result <= 0) - { + if ($result <= 0) { $this->error = $this->db->lasterror(); dol_syslog(get_class($this).'::addPaymentToBank '.$this->error); $error++; @@ -568,8 +589,7 @@ class PaymentExpenseReport extends CommonObject } } - if (!$error) - { + if (!$error) { return 1; } else { return -1; @@ -591,8 +611,7 @@ class PaymentExpenseReport extends CommonObject dol_syslog(get_class($this)."::update_fk_bank", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { return 1; } else { $this->error = $this->db->error(); @@ -613,17 +632,24 @@ class PaymentExpenseReport extends CommonObject $result = ''; - if (empty($this->ref)) $this->ref = $this->label; + if (empty($this->ref)) { + $this->ref = $this->label; + } $label = $langs->trans("ShowPayment").': '.$this->ref; - if (!empty($this->id)) - { + if (!empty($this->id)) { $link = ''; $linkend = ''; - if ($withpicto) $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); - if ($withpicto && $withpicto != 2) $result .= ' '; - if ($withpicto != 2) $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + if ($withpicto) { + $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + if ($withpicto != 2) { + $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + } } return $result; @@ -639,25 +665,21 @@ class PaymentExpenseReport extends CommonObject { $sql = 'SELECT e.rowid, e.datec, e.fk_user_creat, e.fk_user_modif, e.tms'; $sql .= ' FROM '.MAIN_DB_PREFIX.'payment_expensereport 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); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_creat) - { + if ($obj->fk_user_creat) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_creat); $this->user_creation = $cuser; } - if ($obj->fk_user_modif) - { + if ($obj->fk_user_modif) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modif); $this->user_modification = $muser; diff --git a/htdocs/expensereport/document.php b/htdocs/expensereport/document.php index 55799b10589..7713745a0a3 100644 --- a/htdocs/expensereport/document.php +++ b/htdocs/expensereport/document.php @@ -45,7 +45,9 @@ $confirm = GETPOST('confirm', 'alpha'); $childids = $user->getAllChildIds(1); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', $id, 'expensereport'); @@ -54,17 +56,22 @@ $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 (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "position_name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "position_name"; +} $object = new ExpenseReport($db); -if (!$object->fetch($id, $ref) > 0) -{ +if (!$object->fetch($id, $ref) > 0) { dol_print_error($db); } @@ -74,14 +81,16 @@ $modulepart = 'trip'; // Load object //include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($object->id > 0) -{ +if ($object->id > 0) { // Check current user can read this expense report $canread = 0; - if (!empty($user->rights->expensereport->readall)) $canread = 1; - if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) $canread = 1; - if (!$canread) - { + if (!empty($user->rights->expensereport->readall)) { + $canread = 1; + } + if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) { + $canread = 1; + } + if (!$canread) { accessforbidden(); } } @@ -104,8 +113,7 @@ $title = $langs->trans("ExpenseReport")." - ".$langs->trans("Documents"); $helpurl = "EN:Module_Expense_Reports"; llxHeader("", $title, $helpurl); -if ($object->id) -{ +if ($object->id) { $object->fetch_thirdparty(); $head = expensereport_prepare_head($object); @@ -124,8 +132,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/expensereport/index.php b/htdocs/expensereport/index.php index 046bde4efa1..541c2c0738e 100644 --- a/htdocs/expensereport/index.php +++ b/htdocs/expensereport/index.php @@ -42,19 +42,27 @@ $langs->loadLangs(array('companies', 'users', 'trips')); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', '', ''); $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.date_create"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "d.date_create"; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; @@ -80,8 +88,7 @@ $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as d, ".MAIN_DB_PREFIX."expensere $sql .= " WHERE de.fk_expensereport = d.rowid AND d.entity IN (".getEntity('expensereport').") AND de.fk_c_type_fees = tf.id"; // RESTRICT RIGHTS if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous) - && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) -{ + && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) { $childids = $user->getAllChildIds(); $childids[] = $user->id; $sql .= " AND d.fk_user_author IN (".join(',', $childids).")\n"; @@ -90,12 +97,10 @@ if (empty($user->rights->expensereport->readall) && empty($user->rights->expense $sql .= " GROUP BY tf.code, tf.label"; $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($result); $somme[$objp->code] = $objp->km; @@ -123,13 +128,11 @@ print ''; print "\n"; $listoftype = $tripandexpense_static->listOfTypes(); -foreach ($listoftype as $code => $label) -{ +foreach ($listoftype as $code => $label) { $dataseries[] = array($label, (isset($somme[$code]) ? (int) $somme[$code] : 0)); } -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print ''; print ''; print ''; - if ($num) - { + if ($num) { $total_ttc = $totalam = $total = 0; $expensereportstatic = new ExpenseReport($db); $userstatic = new User($db); - while ($i < $num && $i < $max) - { + while ($i < $num && $i < $max) { $obj = $db->fetch_object($result); $expensereportstatic->id = $obj->rowid; @@ -241,7 +246,9 @@ if ($result) print ''; } print '
    '.$langs->trans('LineNb').''.$langs->trans('Piece').''.$langs->trans('Date').''.$langs->trans('Project').''.$langs->trans('Project').''.$langs->trans('Type').''.$langs->trans('CarCategory').''.$langs->trans('CarCategory').''.$langs->trans('Description').''.$langs->trans('VAT').''.$langs->trans('PriceUHT').''.$langs->trans('PriceUTTC').''.$langs->trans('Qty').''.$langs->trans('AmountHT').''.$langs->trans('AmountTTC').''; print '
    '.dol_print_date($db->jdate($line->date), 'day').''; - if ($line->fk_project > 0) - { + if ($line->fk_project > 0) { $projecttmp->id = $line->fk_project; $projecttmp->ref = $line->projet_ref; $projecttmp->title = $line->projet_title; @@ -2077,8 +2048,7 @@ if ($action == 'create') print ''; print dol_getIdFromCode($db, $line->fk_c_exp_tax_cat, 'c_exp_tax_cat', 'rowid', 'label'); print ''.vatrate($line->vatrate, true).''; - if (!empty($line->value_unit_ht)) - { + if (!empty($line->value_unit_ht)) { print price($line->value_unit_ht); } else { $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $line->vatrate)); @@ -2104,28 +2073,26 @@ if ($action == 'create') print ''.dol_escape_htmltag($line->qty).''.price($line->total_ht).''.price($line->total_ttc).''; - if ($line->fk_ecm_files > 0) - { + if ($line->fk_ecm_files > 0) { $modulepart = 'expensereport'; $maxheightmini = 32; $result = $ecmfilesstatic->fetch($line->fk_ecm_files); - if ($result > 0) - { + if ($result > 0) { $relativepath = preg_replace('/expensereport\//', '', $ecmfilesstatic->filepath); $fileinfo = pathinfo($ecmfilesstatic->filepath.'/'.$ecmfilesstatic->filename); - if (image_format_supported($fileinfo['basename']) > 0) - { + if (image_format_supported($fileinfo['basename']) > 0) { $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original - if (!dol_is_file($conf->expensereport->dir_output.'/'.$relativepath.'/'.$minifile)) $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension + if (!dol_is_file($conf->expensereport->dir_output.'/'.$relativepath.'/'.$minifile)) { + $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension + } //print $file['path'].'/'.$minifile.'
    '; $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.'/'.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity)); if (empty($urlforhref)) { @@ -2139,42 +2106,39 @@ if ($action == 'create') } else { $modulepart = 'expensereport'; $thumbshown = 0; - if (preg_match('/\.pdf$/i', $ecmfilesstatic->filename)) - { + if (preg_match('/\.pdf$/i', $ecmfilesstatic->filename)) { $filepdf = $conf->expensereport->dir_output.'/'.$relativepath.'/'.$ecmfilesstatic->filename; $fileimage = $conf->expensereport->dir_output.'/'.$relativepath.'/'.$ecmfilesstatic->filename.'_preview.png'; $relativepathimage = $relativepath.'/'.$ecmfilesstatic->filename.'_preview.png'; $pdfexists = file_exists($filepdf); - if ($pdfexists) - { + if ($pdfexists) { // Conversion du PDF en image png si fichier png non existant - if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) - { - if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here. - { + if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) { + if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } } } - if ($pdfexists && !$error) - { + if ($pdfexists && !$error) { $heightforphotref = 70; - if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60; + if (!empty($conf->dol_optimize_smallscreen)) { + $heightforphotref = 60; + } // If the preview file is found - if (file_exists($fileimage)) - { + if (file_exists($fileimage)) { $thumbshown = 1; print ''; } } } - if (!$thumbshown) - { + if (!$thumbshown) { print img_mime($ecmfilesstatic->filename); } } @@ -2183,8 +2147,7 @@ if ($action == 'create') print '
    '; print 'rowid.'">'; @@ -2200,12 +2163,15 @@ if ($action == 'create') print '
    '; $formproject->select_projects(-1, $line->fk_project, 'fk_project', 0, 0, 1, 1, 0, 0, 0, '', 0, 0, 'maxwidth300'); print ''; $params = array('fk_expense' => $object->id, 'fk_expense_det' => $line->rowid, 'date' => $line->dates); print $form->selectExpenseCategories($line->fk_c_exp_tax_cat, 'fk_c_exp_tax_cat', 1, array(), 'fk_c_type_fees', $userauthor->default_c_exp_tax_cat, $params); @@ -2339,17 +2299,21 @@ if ($action == 'create') // Add a new line if (($object->status == ExpenseReport::STATUS_DRAFT || $object->status == ExpenseReport::STATUS_REFUSED) && $action != 'editline' - && $user->rights->expensereport->creer) - { + && $user->rights->expensereport->creer) { $colspan = 11; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++; - if (!empty($conf->projet->enabled)) $colspan++; - if ($action != 'editline') $colspan++; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { + $colspan++; + } + if (!empty($conf->projet->enabled)) { + $colspan++; + } + if ($action != 'editline') { + $colspan++; + } $nbFiles = $nbLinks = 0; $arrayoffiles = array(); - if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) - { + if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; @@ -2365,8 +2329,7 @@ if ($action == 'create') print ''.$langs->trans("UploadANewFileNow"); print img_picto($langs->trans("UploadANewFileNow"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); print ''; - if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) - { + if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) { print '   -   '.$langs->trans("AttachTheNewLineToTheDocument"); print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); print ''; @@ -2384,8 +2347,7 @@ if ($action == 'create') jQuery(".truploadnewfilenow").hide(); return false; });'."\n"; - if (is_array(GETPOST('attachfile', 'array')) && count(GETPOST('attachfile', 'array')) && $action != 'updateline') - { + if (is_array(GETPOST('attachfile', 'array')) && count(GETPOST('attachfile', 'array')) && $action != 'updateline') { print 'jQuery(".trattachnewfilenow").show();'."\n"; } print ' @@ -2429,8 +2391,7 @@ if ($action == 'create') print ''; $formproject->select_projects(-1, $fk_project, 'fk_project', 0, 0, 1, -1, 0, 0, 0, '', 0, 0, 'maxwidth300'); print ''; $params = array('fk_expense' => $object->id); print $form->selectExpenseCategories('', 'fk_c_exp_tax_cat', 1, array(), 'fk_c_type_fees', $userauthor->default_c_exp_tax_cat, $params, 0); @@ -2457,7 +2417,9 @@ if ($action == 'create') // Select VAT print ''; $defaultvat = -1; - if (!empty($conf->global->EXPENSEREPORT_NO_DEFAULT_VAT)) $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS = 'none'; + if (!empty($conf->global->EXPENSEREPORT_NO_DEFAULT_VAT)) { + $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS = 'none'; + } print $form->load_tva('vatrate', ($vatrate != '' ? $vatrate : $defaultvat), $mysoc, '', 0, 0, '', false, 1); print '
    '.$langs->trans("Statistics").'
    '; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -168,25 +171,29 @@ $langs->load("boxes"); $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.statut as user_status, u.photo, u.email, u.admin,"; $sql .= " d.rowid, d.ref, d.date_debut as dated, d.date_fin as datef, d.date_create as dm, d.total_ht, d.total_ttc, d.fk_statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as d, ".MAIN_DB_PREFIX."user as u"; -if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE u.rowid = d.fk_user_author"; // RESTRICT RIGHTS if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous) - && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) -{ + && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) { $childids = $user->getAllChildIds(); $childids[] = $user->id; $sql .= " AND d.fk_user_author IN (".join(',', $childids).")\n"; } $sql .= ' AND d.entity IN ('.getEntity('expensereport').')'; -if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND d.fk_user_author = s.rowid AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND d.fk_user_author = ".$socid; +if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= " AND d.fk_user_author = s.rowid AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND d.fk_user_author = ".$socid; +} $sql .= $db->order($sortfield, $sortorder); $sql .= $db->plimit($max, 0); $result = $db->query($sql); -if ($result) -{ +if ($result) { $var = false; $num = $db->num_rows($result); @@ -201,14 +208,12 @@ if ($result) print ''.$langs->trans("DateModificationShort").' 
    '.$langs->trans("None").'

    '; -} else dol_print_error($db); +} else { + dol_print_error($db); +} print ''; diff --git a/htdocs/expensereport/info.php b/htdocs/expensereport/info.php index 53d1531f4b9..605197d14ac 100644 --- a/htdocs/expensereport/info.php +++ b/htdocs/expensereport/info.php @@ -37,23 +37,26 @@ $ref = GETPOST('ref', 'alpha'); $childids = $user->getAllChildIds(1); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', $id, 'expensereport'); $object = new ExpenseReport($db); -if (!$object->fetch($id, $ref) > 0) -{ +if (!$object->fetch($id, $ref) > 0) { dol_print_error($db); } -if ($object->id > 0) -{ +if ($object->id > 0) { // Check current user can read this expense report $canread = 0; - if (!empty($user->rights->expensereport->readall)) $canread = 1; - if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) $canread = 1; - if (!$canread) - { + if (!empty($user->rights->expensereport->readall)) { + $canread = 1; + } + if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) { + $canread = 1; + } + if (!$canread) { accessforbidden(); } } @@ -69,8 +72,7 @@ $title = $langs->trans("ExpenseReport")." - ".$langs->trans("Info"); $helpurl = "EN:Module_Expense_Reports"; llxHeader("", $title, $helpurl); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object = new ExpenseReport($db); $object->fetch($id, $ref); $object->info($object->id); diff --git a/htdocs/expensereport/list.php b/htdocs/expensereport/list.php index 7afb464e4f4..35642ead0c4 100644 --- a/htdocs/expensereport/list.php +++ b/htdocs/expensereport/list.php @@ -7,7 +7,7 @@ * Copyright (C) 2018 Ferran Marcet * Copyright (C) 2018 Charlene Benke * Copyright (C) 2019 Juanjo Menent - * 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 @@ -54,18 +54,24 @@ $childids = $user->getAllChildIds(1); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', '', ''); $id = GETPOST('id', 'int'); // If we are on the view of a specific user -if ($id > 0) -{ +if ($id > 0) { $canread = 0; - if ($id == $user->id) $canread = 1; - if (!empty($user->rights->expensereport->readall)) $canread = 1; - if (!empty($user->rights->expensereport->lire) && in_array($id, $childids)) $canread = 1; - if (!$canread) - { + if ($id == $user->id) { + $canread = 1; + } + if (!empty($user->rights->expensereport->readall)) { + $canread = 1; + } + if (!empty($user->rights->expensereport->lire) && in_array($id, $childids)) { + $canread = 1; + } + if (!$canread) { accessforbidden(); } } @@ -78,12 +84,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) { $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.date_debut"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "d.date_debut"; +} $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); @@ -101,8 +113,12 @@ $month_end = GETPOST("month_end", "int"); $year_end = GETPOST("year_end", "int"); $optioncss = GETPOST('optioncss', 'alpha'); -if ($search_status == '') $search_status = -1; -if ($search_user == '') $search_user = -1; +if ($search_status == '') { + $search_status = -1; +} +if ($search_user == '') { + $search_user = -1; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new ExpenseReport($db); @@ -123,7 +139,9 @@ $fieldstosearchall = array( 'u.firstname'=>"Firstname", 'u.login'=>"Login", ); -if (empty($user->socid)) $fieldstosearchall["d.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["d.note_private"] = "NotePrivate"; +} $arrayfields = array( 'd.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), @@ -151,21 +169,25 @@ $objectuser = new User($db); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $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)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_ref = ""; $search_user = ""; $search_amount_ht = ""; @@ -181,8 +203,7 @@ if (empty($reshook)) $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -216,8 +237,7 @@ $min_year = 10; // Get current user id $user_id = $user->id; -if ($id > 0) -{ +if ($id > 0) { // Charge utilisateur edite $fuser->fetch($id, '', '', 1); $fuser->getrights(); @@ -231,35 +251,50 @@ $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_v $sql .= " u.rowid as id_user, u.firstname, u.lastname, u.login, u.email, u.statut, u.photo"; // 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 : ''); + 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 $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as d"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (d.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (d.rowid = ef.fk_object)"; +} $sql .= ", ".MAIN_DB_PREFIX."user as u"; $sql .= " WHERE d.fk_user_author = u.rowid AND d.entity IN (".getEntity('expensereport').")"; // Search all -if (!empty($sall)) $sql .= natural_search(array_keys($fieldstosearchall), $sall); +if (!empty($sall)) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} // Ref -if (!empty($search_ref)) $sql .= natural_search('d.ref', $search_ref); +if (!empty($search_ref)) { + $sql .= natural_search('d.ref', $search_ref); +} // Date Start $sql .= dolSqlDateFilter("d.date_debut", $day_start, $month_start, $year_start); // Date End $sql .= dolSqlDateFilter("d.date_fin", $day_end, $month_end, $year_end); -if ($search_amount_ht != '') $sql .= natural_search('d.total_ht', $search_amount_ht, 1); -if ($search_amount_ttc != '') $sql .= natural_search('d.total_ttc', $search_amount_ttc, 1); +if ($search_amount_ht != '') { + $sql .= natural_search('d.total_ht', $search_amount_ht, 1); +} +if ($search_amount_ttc != '') { + $sql .= natural_search('d.total_ttc', $search_amount_ttc, 1); +} // User -if ($search_user != '' && $search_user >= 0) $sql .= " AND u.rowid = '".$db->escape($search_user)."'"; +if ($search_user != '' && $search_user >= 0) { + $sql .= " AND u.rowid = '".$db->escape($search_user)."'"; +} // Status -if ($search_status != '' && $search_status >= 0) $sql .= " AND d.fk_statut IN (".$db->sanitize($db->escape($search_status)).")"; +if ($search_status != '' && $search_status >= 0) { + $sql .= " AND d.fk_statut IN (".$db->sanitize($db->escape($search_status)).")"; +} // RESTRICT RIGHTS if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous) - && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) -{ + && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) { $sql .= " AND d.fk_user_author IN (".join(',', $childids).")\n"; } // Add where from extra fields @@ -273,12 +308,10 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -288,22 +321,39 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); $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_user) $param .= "&search_user=".urlencode($search_user); - if ($search_amount_ht) $param .= "&search_amount_ht=".urlencode($search_amount_ht); - if ($search_amount_ttc) $param .= "&search_amount_ttc=".urlencode($search_amount_ttc); - if ($search_status >= 0) $param .= "&search_status=".urlencode($search_status); - 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_user) { + $param .= "&search_user=".urlencode($search_user); + } + if ($search_amount_ht) { + $param .= "&search_amount_ht=".urlencode($search_amount_ht); + } + if ($search_amount_ttc) { + $param .= "&search_amount_ttc=".urlencode($search_amount_ttc); + } + if ($search_status >= 0) { + $param .= "&search_status=".urlencode($search_status); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -313,23 +363,30 @@ if ($resql) 'builddoc'=>$langs->trans("PDFMerge"), 'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->expensereport->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + if ($user->rights->expensereport->supprimer) { + $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); + } + if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); // Lines of title fields print '
    '."\n"; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; print ''; print ''; print ''; - if ($id > 0) print ''; + if ($id > 0) { + print ''; + } - if ($id > 0) // For user tab - { + if ($id > 0) { // For user tab $title = $langs->trans("User"); $linkback = ''.$langs->trans("BackToList").''; $head = user_prepare_head($fuser); @@ -340,8 +397,7 @@ if ($resql) print dol_get_fiche_end(); - if ($action != 'edit') - { + if ($action != 'edit') { print '
    '; $childids = $user->getAllChildIds(1); @@ -366,7 +422,9 @@ if ($resql) $title = $langs->trans("ListTripsAndExpenses"); $url = DOL_URL_ROOT.'/expensereport/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewTrip'), '', 'fa fa-plus-circle', $url, '', $user->rights->expensereport->creer); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'trip', 0, $newcardbutton, '', $limit, 0, 0, 1); @@ -378,9 +436,10 @@ if ($resql) $trackid = 'exp'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } @@ -388,11 +447,13 @@ if ($resql) $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)) - { + if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; @@ -407,17 +468,14 @@ if ($resql) // Filters print ''; - if (!empty($arrayfields['d.ref']['checked'])) - { + if (!empty($arrayfields['d.ref']['checked'])) { print ''; print ''; print ''; } // User - if (!empty($arrayfields['user']['checked'])) - { - if ($user->rights->expensereport->readall || $user->rights->expensereport->lire_tous) - { + if (!empty($arrayfields['user']['checked'])) { + if ($user->rights->expensereport->readall || $user->rights->expensereport->lire_tous) { print ''; print $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); print ''; @@ -426,8 +484,7 @@ if ($resql) } } // Date start - if (!empty($arrayfields['d.date_debut']['checked'])) - { + if (!empty($arrayfields['d.date_debut']['checked'])) { print ''; if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { print ''; @@ -438,8 +495,7 @@ if ($resql) print ''; } // Date end - if (!empty($arrayfields['d.date_fin']['checked'])) - { + if (!empty($arrayfields['d.date_fin']['checked'])) { print ''; if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { print ''; @@ -449,33 +505,28 @@ if ($resql) print ''; } // Date valid - if (!empty($arrayfields['d.date_valid']['checked'])) - { + if (!empty($arrayfields['d.date_valid']['checked'])) { print ''; //print ''; //$formother->select_year($year_end,'year_end',1, $min_year, $max_year); print ''; } // Date approve - if (!empty($arrayfields['d.date_approve']['checked'])) - { + if (!empty($arrayfields['d.date_approve']['checked'])) { print ''; //print ''; //$formother->select_year($year_end,'year_end',1, $min_year, $max_year); print ''; } // Amount with no tax - if (!empty($arrayfields['d.total_ht']['checked'])) - { + if (!empty($arrayfields['d.total_ht']['checked'])) { print ''; } - if (!empty($arrayfields['d.total_vat']['checked'])) - { + if (!empty($arrayfields['d.total_vat']['checked'])) { print ''; } // Amount with all taxes - if (!empty($arrayfields['d.total_ttc']['checked'])) - { + if (!empty($arrayfields['d.total_ttc']['checked'])) { print ''; } // Extra fields @@ -486,20 +537,17 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['d.date_create']['checked'])) - { + if (!empty($arrayfields['d.date_create']['checked'])) { print ''; print ''; } // Date modification - if (!empty($arrayfields['d.tms']['checked'])) - { + if (!empty($arrayfields['d.tms']['checked'])) { print ''; print ''; } // Status - if (!empty($arrayfields['d.fk_statut']['checked'])) - { + if (!empty($arrayfields['d.fk_statut']['checked'])) { print ''; $formexpensereport->selectExpensereportStatus($search_status, 'search_status', 1, 1); print ''; @@ -513,24 +561,48 @@ if ($resql) print "\n"; print ''; - 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['user']['checked'])) print_liste_field_titre($arrayfields['user']['label'], $_SERVER["PHP_SELF"], "u.lastname", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['d.date_debut']['checked'])) print_liste_field_titre($arrayfields['d.date_debut']['label'], $_SERVER["PHP_SELF"], "d.date_debut", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['d.date_fin']['checked'])) print_liste_field_titre($arrayfields['d.date_fin']['label'], $_SERVER["PHP_SELF"], "d.date_fin", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['d.date_valid']['checked'])) print_liste_field_titre($arrayfields['d.date_valid']['label'], $_SERVER["PHP_SELF"], "d.date_valid", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['d.date_approve']['checked'])) print_liste_field_titre($arrayfields['d.date_approve']['label'], $_SERVER["PHP_SELF"], "d.date_approve", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['d.total_ht']['checked'])) print_liste_field_titre($arrayfields['d.total_ht']['label'], $_SERVER["PHP_SELF"], "d.total_ht", "", $param, 'align="right"', $sortfield, $sortorder); - if (!empty($arrayfields['d.total_vat']['checked'])) print_liste_field_titre($arrayfields['d.total_vat']['label'], $_SERVER["PHP_SELF"], "d.total_tva", "", $param, 'align="right"', $sortfield, $sortorder); - if (!empty($arrayfields['d.total_ttc']['checked'])) print_liste_field_titre($arrayfields['d.total_ttc']['label'], $_SERVER["PHP_SELF"], "d.total_ttc", "", $param, 'align="right"', $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['user']['checked'])) { + print_liste_field_titre($arrayfields['user']['label'], $_SERVER["PHP_SELF"], "u.lastname", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.date_debut']['checked'])) { + print_liste_field_titre($arrayfields['d.date_debut']['label'], $_SERVER["PHP_SELF"], "d.date_debut", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.date_fin']['checked'])) { + print_liste_field_titre($arrayfields['d.date_fin']['label'], $_SERVER["PHP_SELF"], "d.date_fin", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.date_valid']['checked'])) { + print_liste_field_titre($arrayfields['d.date_valid']['label'], $_SERVER["PHP_SELF"], "d.date_valid", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.date_approve']['checked'])) { + print_liste_field_titre($arrayfields['d.date_approve']['label'], $_SERVER["PHP_SELF"], "d.date_approve", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.total_ht']['checked'])) { + print_liste_field_titre($arrayfields['d.total_ht']['label'], $_SERVER["PHP_SELF"], "d.total_ht", "", $param, 'align="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.total_vat']['checked'])) { + print_liste_field_titre($arrayfields['d.total_vat']['label'], $_SERVER["PHP_SELF"], "d.total_tva", "", $param, 'align="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['d.total_ttc']['label'], $_SERVER["PHP_SELF"], "d.total_ttc", "", $param, 'align="right"', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $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.date_create']['checked'])) print_liste_field_titre($arrayfields['d.date_create']['label'], $_SERVER["PHP_SELF"], "d.date_create", "", $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.fk_statut']['checked'])) print_liste_field_titre($arrayfields['d.fk_statut']['label'], $_SERVER["PHP_SELF"], "d.fk_statut", "", $param, 'align="right"', $sortfield, $sortorder); + if (!empty($arrayfields['d.date_create']['checked'])) { + print_liste_field_titre($arrayfields['d.date_create']['label'], $_SERVER["PHP_SELF"], "d.date_create", "", $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.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['d.fk_statut']['label'], $_SERVER["PHP_SELF"], "d.fk_statut", "", $param, 'align="right"', $sortfield, $sortorder); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; @@ -541,12 +613,16 @@ if ($resql) $expensereportstatic = new ExpenseReport($db); $usertmp = new User($db); - if ($num > 0) - { + if ($num > 0) { $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + $totalarray['nbfield'] = 0; + $totalarray['val'] = array(); + $totalarray['val']['d.total_ht'] = 0; + $totalarray['val']['d.total_tva'] = 0; + $totalarray['val']['d.total_ttc'] = 0; + $totalarray['totalizable'] = array(); + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $expensereportstatic->id = $obj->rowid; @@ -572,10 +648,13 @@ if ($resql) print ''; // Warning late icon and note print ''; - if ($expensereportstatic->status == 2 && $expensereportstatic->hasDelay('toappove')) print img_warning($langs->trans("Late")); - if ($expensereportstatic->status == 5 && $expensereportstatic->hasDelay('topay')) print img_warning($langs->trans("Late")); - if (!empty($obj->note_private) || !empty($obj->note_public)) - { + if ($expensereportstatic->status == 2 && $expensereportstatic->hasDelay('toappove')) { + print img_warning($langs->trans("Late")); + } + if ($expensereportstatic->status == 5 && $expensereportstatic->hasDelay('topay')) { + print img_warning($langs->trans("Late")); + } + if (!empty($obj->note_private) || !empty($obj->note_public)) { print ' '; print ''.img_picto($langs->trans("ViewPrivateNote"), 'object_generic').''; print ''; @@ -589,7 +668,9 @@ if ($resql) print ''; print ''; print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // User if (!empty($arrayfields['user']['checked'])) { @@ -603,50 +684,69 @@ if ($resql) $usertmp->email = $obj->email; print $usertmp->getNomUrl(-1); print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Start date if (!empty($arrayfields['d.date_debut']['checked'])) { print ''.($obj->date_debut > 0 ? dol_print_date($db->jdate($obj->date_debut), 'day') : '').''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // End date if (!empty($arrayfields['d.date_fin']['checked'])) { print ''.($obj->date_fin > 0 ? dol_print_date($db->jdate($obj->date_fin), 'day') : '').''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date validation if (!empty($arrayfields['d.date_valid']['checked'])) { print ''.($obj->date_valid > 0 ? dol_print_date($db->jdate($obj->date_valid), 'day') : '').''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date approval if (!empty($arrayfields['d.date_approve']['checked'])) { print ''.($obj->date_approve > 0 ? dol_print_date($db->jdate($obj->date_approve), 'day') : '').''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['d.total_ht']['checked'])) - { + if (!empty($arrayfields['d.total_ht']['checked'])) { print ''.price($obj->total_ht)."\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'd.total_ht'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'd.total_ht'; + } $totalarray['val']['d.total_ht'] += $obj->total_ht; } // Amount VAT - if (!empty($arrayfields['d.total_vat']['checked'])) - { + if (!empty($arrayfields['d.total_vat']['checked'])) { print ''.price($obj->total_tva)."\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'd.total_tva'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'd.total_tva'; + } $totalarray['val']['d.total_tva'] += $obj->total_tva; } // Amount TTC - if (!empty($arrayfields['d.total_ttc']['checked'])) - { + if (!empty($arrayfields['d.total_ttc']['checked'])) { print ''.price($obj->total_ttc)."\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'd.total_ttc'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'd.total_ttc'; + } $totalarray['val']['d.total_ttc'] += $obj->total_ttc; } @@ -658,37 +758,43 @@ if ($resql) print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['d.date_create']['checked'])) - { + if (!empty($arrayfields['d.date_create']['checked'])) { print ''; print dol_print_date($db->jdate($obj->date_create), 'dayhour'); print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['d.tms']['checked'])) - { + if (!empty($arrayfields['d.tms']['checked'])) { print ''; print dol_print_date($db->jdate($obj->date_modif), 'dayhour'); print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['d.fk_statut']['checked'])) - { + if (!empty($arrayfields['d.fk_statut']['checked'])) { print ''.$expensereportstatic->getLibStatut(5).''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print ''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; @@ -700,7 +806,11 @@ if ($resql) } } else { $colspan = 1; - foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } print ''.$langs->trans("NoRecordFound").''; } @@ -718,10 +828,11 @@ if ($resql) print ''."\n"; - if (empty($id)) - { + if (empty($id)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/expensereport/note.php b/htdocs/expensereport/note.php index ebb66ce42fd..b0156c6a475 100644 --- a/htdocs/expensereport/note.php +++ b/htdocs/expensereport/note.php @@ -41,26 +41,29 @@ $childids = $user->getAllChildIds(1); // Security check $socid = 0; -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', $id, 'expensereport'); $object = new ExpenseReport($db); -if (!$object->fetch($id, $ref) > 0) -{ +if (!$object->fetch($id, $ref) > 0) { dol_print_error($db); } $permissionnote = $user->rights->expensereport->creer; // Used by the include of actions_setnotes.inc.php -if ($object->id > 0) -{ +if ($object->id > 0) { // Check current user can read this expense report $canread = 0; - if (!empty($user->rights->expensereport->readall)) $canread = 1; - if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) $canread = 1; - if (!$canread) - { + if (!empty($user->rights->expensereport->readall)) { + $canread = 1; + } + if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) { + $canread = 1; + } + if (!$canread) { accessforbidden(); } } @@ -82,8 +85,7 @@ llxHeader("", $title, $helpurl); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object = new ExpenseReport($db); $object->fetch($id, $ref); $object->info($object->id); diff --git a/htdocs/expensereport/payment/card.php b/htdocs/expensereport/payment/card.php index 14c95f2d68a..7b86f295b5b 100644 --- a/htdocs/expensereport/payment/card.php +++ b/htdocs/expensereport/payment/card.php @@ -26,7 +26,9 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/expensereport.lib.php'; -if (!empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +if (!empty($conf->banque->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('bills', 'banks', 'companies', 'trips')); @@ -36,16 +38,19 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} // TODO Add rule to restrict access payment //$result = restrictedArea($user, 'facture', $id,''); $object = new PaymentExpenseReport($db); -if ($id > 0) -{ +if ($id > 0) { $result = $object->fetch($id); - if (!$result) dol_print_error($db, 'Failed to get payment id '.$id); + if (!$result) { + dol_print_error($db, 'Failed to get payment id '.$id); + } } @@ -54,13 +59,11 @@ if ($id > 0) */ // Delete payment -if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->expensereport->supprimer) -{ +if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->expensereport->supprimer) { $db->begin(); $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { $db->commit(); header("Location: ".DOL_URL_ROOT."/expensereport/index.php"); exit; @@ -86,8 +89,7 @@ print dol_get_fiche_head($head, 'payment', $langs->trans("ExpenseReportPayment") /* * Confirm deleting of the payment */ -if ($action == 'delete') -{ +if ($action == 'delete') { print $form->formconfirm('card.php?id='.$object->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete', '', 0, 2); } @@ -118,14 +120,11 @@ print ''.$langs->trans('Note').''.nl2 $disable_delete = 0; // Bank account -if (!empty($conf->banque->enabled)) -{ - if ($object->bank_account) - { +if (!empty($conf->banque->enabled)) { + if ($object->bank_account) { $bankline = new AccountLine($db); $bankline->fetch($object->bank_line); - if ($bankline->rappro) - { + if ($bankline->rappro) { $disable_delete = 1; $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemoveConciliatedPayment")); } @@ -163,12 +162,11 @@ $sql = 'SELECT er.rowid as eid, er.paid, er.total_ttc, per.amount'; $sql .= ' FROM '.MAIN_DB_PREFIX.'payment_expensereport as per,'.MAIN_DB_PREFIX.'expensereport as er'; $sql .= ' WHERE per.fk_expensereport = er.rowid'; $sql .= ' AND er.entity IN ('.getEntity('expensereport').')'; -$sql .= ' AND per.rowid = '.$id; +$sql .= ' AND per.rowid = '.((int) $id); dol_syslog("expensereport/payment/card.php", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -186,10 +184,8 @@ if ($resql) print ''.$langs->trans('Status').''; print "\n"; - if ($num > 0) - { - while ($i < $num) - { + if ($num > 0) { + while ($i < $num) { $objp = $db->fetch_object($resql); print ''; @@ -216,8 +212,7 @@ if ($resql) print "\n"; - if ($objp->paid == 1) // If at least one invoice is paid, disable delete - { + if ($objp->paid == 1) { // If at least one invoice is paid, disable delete $disable_delete = 2; $title_button = $langs->trans("CantRemovePaymentWithOneInvoicePaid"); } @@ -242,12 +237,9 @@ if ($resql) */ print '
    '; -if ($action == '') -{ - if ($user->rights->expensereport->supprimer) - { - if (!$disable_delete) - { +if ($action == '') { + if ($user->rights->expensereport->supprimer) { + if (!$disable_delete) { print ''.$langs->trans('Delete').''; } else { print ''.$langs->trans('Delete').''; diff --git a/htdocs/expensereport/payment/payment.php b/htdocs/expensereport/payment/payment.php index b66103f38f5..926559769b4 100644 --- a/htdocs/expensereport/payment/payment.php +++ b/htdocs/expensereport/payment/payment.php @@ -39,8 +39,7 @@ $accountid = GETPOST('accountid', 'int'); // Security check $socid = 0; -if ($user->socid > 0) -{ +if ($user->socid > 0) { $socid = $user->socid; } @@ -49,12 +48,10 @@ if ($user->socid > 0) * Actions */ -if ($action == 'add_payment') -{ +if ($action == 'add_payment') { $error = 0; - if ($_POST["cancel"]) - { + if ($_POST["cancel"]) { $loc = DOL_URL_ROOT.'/expensereport/card.php?id='.$id; header("Location: ".$loc); exit; @@ -62,53 +59,44 @@ if ($action == 'add_payment') $expensereport = new ExpenseReport($db); $result = $expensereport->fetch($id, $ref); - if (!$result) - { + if (!$result) { $error++; setEventMessages($expensereport->error, $expensereport->errors, 'errors'); } $datepaid = dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); - if (!($_POST["fk_typepayment"] > 0)) - { + if (!($_POST["fk_typepayment"] > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")), null, 'errors'); $error++; } - if ($datepaid == '') - { + if ($datepaid == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors'); $error++; } - if (!empty($conf->banque->enabled) && !($accountid > 0)) - { + if (!empty($conf->banque->enabled) && !($accountid > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountToDebit")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $paymentid = 0; $total = 0; // Read possible payments - foreach ($_POST as $key => $value) - { - if (substr($key, 0, 7) == 'amount_') - { + foreach ($_POST as $key => $value) { + if (substr($key, 0, 7) == 'amount_') { $amounts[$expensereport->fk_user_author] = price2num($_POST[$key]); $total += price2num($_POST[$key]); } } - if (count($amounts) <= 0) - { + if (count($amounts) <= 0) { $error++; $errmsg = 'ErrorNoPaymentDefined'; } - if (!$error) - { + if (!$error) { $db->begin(); // Create a line of payments @@ -121,21 +109,17 @@ if ($action == 'add_payment') $payment->num_payment = GETPOST("num_payment", 'alphanothtml'); $payment->note_public = GETPOST("note_public", 'restricthtml'); - if (!$error) - { + if (!$error) { $paymentid = $payment->create($user); - if ($paymentid < 0) - { + if ($paymentid < 0) { setEventMessages($payment->error, $payment->errors, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { $result = $payment->addPaymentToBank($user, 'payment_expensereport', '(ExpenseReportPayment)', $accountid, '', ''); - if (!$result > 0) - { + if (!$result > 0) { setEventMessages($payment->error, $payment->errors, 'errors'); $error++; } @@ -152,8 +136,7 @@ if ($action == 'add_payment') } } - if (!$error) - { + if (!$error) { $db->commit(); $loc = DOL_URL_ROOT.'/expensereport/card.php?id='.$id; header('Location: '.$loc); @@ -178,8 +161,7 @@ $form = new Form($db); // Form to create expense report payment -if ($action == 'create' || empty($action)) -{ +if ($action == 'create' || empty($action)) { $expensereport = new ExpenseReport($db); $expensereport->fetch($id, $ref); @@ -226,8 +208,7 @@ if ($action == 'create' || empty($action)) $sql .= " WHERE p.fk_expensereport = e.rowid AND p.fk_expensereport = ".$id; $sql .= ' AND e.entity IN ('.getEntity('expensereport').')'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $sumpaid = $obj->total; $db->free(); @@ -257,8 +238,7 @@ if ($action == 'create' || empty($action)) print "\n"; print ''; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print ''; print ''.$langs->trans('AccountToDebit').''; print ''; @@ -299,8 +279,7 @@ if ($action == 'create' || empty($action)) $total = 0; $totalrecu = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $expensereport; print ''; @@ -310,12 +289,12 @@ if ($action == 'create' || empty($action)) print ''.price($sumpaid).""; print ''.price($objp->total_ttc - $sumpaid).""; print ''; - if ($sumpaid < $objp->total_ttc) - { + if ($sumpaid < $objp->total_ttc) { $namef = "amount_".$objp->id; $nameRemain = "remain_".$objp->id; // autofill remainder amount - if (!empty($conf->use_javascript_ajax)) // autofill remainder amount + if (!empty($conf->use_javascript_ajax)) { // autofill remainder amount print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmount' data-rowid='".$namef."' data-value='".($objp->total_ttc - $sumpaid)."'"); // autofill remainder amount + } $remaintopay = $objp->total_ttc - $sumpaid; // autofill remainder amount print ''; // autofill remainder amount print ''; @@ -331,8 +310,7 @@ if ($action == 'create' || empty($action)) $totalrecu += $objp->am; $i++; } - if ($i > 1) - { + if ($i > 1) { // Print total print ''; print ''.$langs->trans("Total").':'; diff --git a/htdocs/expensereport/stats/index.php b/htdocs/expensereport/stats/index.php index f3a3e263fa7..87bac2dde1a 100644 --- a/htdocs/expensereport/stats/index.php +++ b/htdocs/expensereport/stats/index.php @@ -38,16 +38,19 @@ $mode = GETPOSTISSET("mode") ? GETPOST("mode", 'aZ09') : 'customer'; $object_status = GETPOST('object_status', 'intcomma'); $userid = GETPOST('userid', 'int'); -$socid = GETPOST('socid', 'int'); if ($socid < 0) $socid = 0; +$socid = GETPOST('socid', 'int'); if ($socid < 0) { + $socid = 0; +} $id = GETPOST('id', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', $id, ''); $nowyear = strftime("%Y", dol_now()); @@ -75,7 +78,9 @@ print load_fiche_titre($title, '', 'trip'); dol_mkdir($dir); $stats = new ExpenseReportStats($db, $socid, $userid); -if ($object_status != '' && $object_status >= -1) $stats->where .= ' AND e.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +if ($object_status != '' && $object_status >= -1) { + $stats->where .= ' AND e.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +} // Build graphic number of object // $data = array(array('Lib',val1,val2,val3),...) @@ -88,12 +93,10 @@ $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=tripsexpensesstats&file $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -120,12 +123,10 @@ $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=tripsexpensesstats& $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px2->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -146,25 +147,30 @@ if (!$mesg) $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filename_avg = $dir.'/ordersaverage-'.$user->id.'-'.$year.'.png'; - if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; - if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + if ($mode == 'customer') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + } } else { $filename_avg = $dir.'/ordersaverage-'.$year.'.png'; - if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; - if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; + if ($mode == 'customer') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; + } } $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px3->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -189,7 +195,9 @@ $arrayyears = array(); foreach ($data as $val) { $arrayyears[$val['year']] = $val['year']; } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; @@ -223,7 +231,9 @@ print ''; // User print ''.$langs->trans("User").''; $include = ''; -if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) $include = 'hierarchy'; +if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) { + $include = 'hierarchy'; +} print $form->select_dolusers($userid, 'userid', 1, '', 0, $include, '', 0, 0, 0, '', 0, '', 'maxwidth300'); print ''; // Status @@ -235,7 +245,9 @@ print ''; print ''; print $form->textwithpicto($langs->trans("Year"), $langs->trans("DateValidation")); print ''; -if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print ''; @@ -254,11 +266,9 @@ print ''.$langs->trans("AmountAverage").''; print ''; $oldyear = 0; -foreach ($data as $val) -{ +foreach ($data as $val) { $year = $val['year']; - while ($year && $oldyear > $year + 1) - { // If we have empty year + while ($year && $oldyear > $year + 1) { // If we have empty year $oldyear--; print ''; @@ -287,7 +297,9 @@ print '
    '; // Show graphs print ''; diff --git a/htdocs/expensereport/tpl/expensereport_linktofile.tpl.php b/htdocs/expensereport/tpl/expensereport_linktofile.tpl.php index 04bb2a71990..640f4c17b5d 100644 --- a/htdocs/expensereport/tpl/expensereport_linktofile.tpl.php +++ b/htdocs/expensereport/tpl/expensereport_linktofile.tpl.php @@ -1,7 +1,6 @@ global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) -{ +if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) { print ''."\n"; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -12,23 +11,20 @@ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) $nbFiles = count($arrayoffiles); $nbLinks = Link::count($db, $object->element, $object->id); - if ($nbFiles > 0) - { + if ($nbFiles > 0) { print 'global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ' style="display: none"' : '').'>'; print ' > - - + + "; diff --git a/htdocs/exports/export.php b/htdocs/exports/export.php index c80ee4d248f..dc23a8ab362 100644 --- a/htdocs/exports/export.php +++ b/htdocs/exports/export.php @@ -54,14 +54,14 @@ $entitytoicon = array( 'subscription' => 'payment', 'payment' => 'payment', 'tax' => 'generic', - 'tax_type' => 'generic', - 'other' => 'generic', + 'tax_type' => 'generic', + 'other' => 'generic', 'account' => 'account', 'product' => 'product', 'virtualproduct'=>'product', 'subproduct' => 'product', 'product_supplier_ref' => 'product', - 'stock' => 'stock', + 'stock' => 'stock', 'warehouse' => 'stock', 'batch' => 'stock', 'stockbatch' => 'stock', @@ -159,17 +159,16 @@ $usefilters = 1; * Actions */ -if ($action == 'selectfield') // Selection of field at step 2 -{ +if ($action == 'selectfield') { // Selection of field at step 2 $fieldsarray = $objexport->array_export_fields[0]; $fieldsentitiesarray = $objexport->array_export_entities[0]; $fieldsdependenciesarray = $objexport->array_export_dependencies[0]; - if ($field == 'all') - { - foreach ($fieldsarray as $key=>$val) - { - if (!empty($array_selected[$key])) continue; // If already selected, check next + if ($field == 'all') { + foreach ($fieldsarray as $key => $val) { + if (!empty($array_selected[$key])) { + continue; // If already selected, check next + } $array_selected[$key] = count($array_selected) + 1; //print_r($array_selected); $_SESSION["export_selected_fields"] = $array_selected; @@ -180,29 +179,30 @@ if ($action == 'selectfield') // Selection of field at step 2 $array_selected[$field] = count($array_selected) + 1; // We tag the key $field as "selected" // We check if there is a dependency to activate /*var_dump($field); - var_dump($fieldsentitiesarray[$field]); - var_dump($fieldsdependenciesarray);*/ + var_dump($fieldsentitiesarray[$field]); + var_dump($fieldsdependenciesarray);*/ $listofdependencies = array(); - if (!empty($fieldsentitiesarray[$field]) && !empty($fieldsdependenciesarray[$fieldsentitiesarray[$field]])) - { + if (!empty($fieldsentitiesarray[$field]) && !empty($fieldsdependenciesarray[$fieldsentitiesarray[$field]])) { // We found a dependency on the type of field $tmp = $fieldsdependenciesarray[$fieldsentitiesarray[$field]]; // $fieldsdependenciesarray=array('element'=>'fd.rowid') or array('element'=>array('fd.rowid','ab.rowid')) - if (is_array($tmp)) $listofdependencies = $tmp; - else $listofdependencies = array($tmp); - } elseif (!empty($field) && !empty($fieldsdependenciesarray[$field])) - { + if (is_array($tmp)) { + $listofdependencies = $tmp; + } else { + $listofdependencies = array($tmp); + } + } elseif (!empty($field) && !empty($fieldsdependenciesarray[$field])) { // We found a dependency on a dedicated field $tmp = $fieldsdependenciesarray[$field]; // $fieldsdependenciesarray=array('fd.fieldx'=>'fd.rowid') or array('fd.fieldx'=>array('fd.rowid','ab.rowid')) - if (is_array($tmp)) $listofdependencies = $tmp; - else $listofdependencies = array($tmp); + if (is_array($tmp)) { + $listofdependencies = $tmp; + } else { + $listofdependencies = array($tmp); + } } - if (count($listofdependencies)) - { - foreach ($listofdependencies as $fieldid) - { - if (empty($array_selected[$fieldid])) - { + if (count($listofdependencies)) { + foreach ($listofdependencies as $fieldid) { + if (empty($array_selected[$fieldid])) { $array_selected[$fieldid] = count($array_selected) + 1; // We tag the key $fieldid as "selected" $warnings[] = $langs->trans("ExportFieldAutomaticallyAdded", $langs->transnoentitiesnoconv($fieldsarray[$fieldid])); } @@ -214,10 +214,8 @@ if ($action == 'selectfield') // Selection of field at step 2 setEventMessages($warnings, null, 'warnings'); } } -if ($action == 'unselectfield') -{ - if ($_GET["field"] == 'all') - { +if ($action == 'unselectfield') { + if ($_GET["field"] == 'all') { $array_selected = array(); $_SESSION["export_selected_fields"] = $array_selected; } else { @@ -226,8 +224,7 @@ if ($action == 'unselectfield') asort($array_selected); $i = 0; $array_selected_save = $array_selected; - foreach ($array_selected as $code=>$value) - { + foreach ($array_selected as $code => $value) { $i++; $array_selected[$code] = $i; //print "x $code x $i y
    "; @@ -236,52 +233,48 @@ if ($action == 'unselectfield') } } -if ($action == 'downfield' || $action == 'upfield') -{ +if ($action == 'downfield' || $action == 'upfield') { $pos = $array_selected[$_GET["field"]]; - if ($action == 'downfield') $newpos = $pos + 1; - if ($action == 'upfield') $newpos = $pos - 1; + if ($action == 'downfield') { + $newpos = $pos + 1; + } + if ($action == 'upfield') { + $newpos = $pos - 1; + } // Recherche code avec qui switcher $newcode = ""; - foreach ($array_selected as $code=>$value) - { - if ($value == $newpos) - { + foreach ($array_selected as $code => $value) { + if ($value == $newpos) { $newcode = $code; break; } } //print("Switch pos=$pos (code=".$_GET["field"].") and newpos=$newpos (code=$newcode)"); - if ($newcode) // Si newcode trouve (protection contre resoumission de page) - { + if ($newcode) { // Si newcode trouve (protection contre resoumission de page) $array_selected[$_GET["field"]] = $newpos; $array_selected[$newcode] = $pos; $_SESSION["export_selected_fields"] = $array_selected; } } -if ($step == 1 || $action == 'cleanselect') -{ +if ($step == 1 || $action == 'cleanselect') { $_SESSION["export_selected_fields"] = array(); $_SESSION["export_filtered_fields"] = array(); $array_selected = array(); $array_filtervalue = array(); } -if ($action == 'builddoc') -{ +if ($action == 'builddoc') { $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 } // Build export file $result = $objexport->build_file($user, GETPOST('model', 'alpha'), $datatoexport, $array_selected, $array_filtervalue); - if ($result < 0) - { + if ($result < 0) { setEventMessages($objexport->error, $objexport->errors, 'errors'); $sqlusedforexport = $objexport->sqlusedforexport; } else { @@ -291,47 +284,46 @@ if ($action == 'builddoc') } // Delete file -if ($step == 5 && $action == 'confirm_deletefile' && $confirm == 'yes') -{ +if ($step == 5 && $action == 'confirm_deletefile' && $confirm == 'yes') { $file = $upload_dir."/".GETPOST('file'); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP). $ret = dol_delete_file($file); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + if ($ret) { + setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + } header('Location: '.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport); exit; } -if ($action == 'deleteprof') -{ - if (GETPOST("id", 'int')) - { +if ($action == 'deleteprof') { + if (GETPOST("id", 'int')) { $objexport->fetch(GETPOST('id', 'int')); $result = $objexport->delete($user); } } // TODO The export for filter is not yet implemented (old code created conflicts with step 2). We must use same way of working and same combo list of predefined export than step 2. -if ($action == 'add_export_model') -{ - if ($export_name) - { +if ($action == 'add_export_model') { + if ($export_name) { asort($array_selected); // Set save string $hexa = ''; - foreach ($array_selected as $key=>$val) - { - if ($hexa) $hexa .= ','; + foreach ($array_selected as $key => $val) { + if ($hexa) { + $hexa .= ','; + } $hexa .= $key; } $hexafiltervalue = ''; - if (!empty($array_filtervalue) && is_array($array_filtervalue)) - { - foreach ($array_filtervalue as $key=>$val) - { - if ($hexafiltervalue) $hexafiltervalue .= ','; + if (!empty($array_filtervalue) && is_array($array_filtervalue)) { + foreach ($array_filtervalue as $key => $val) { + if ($hexafiltervalue) { + $hexafiltervalue .= ','; + } $hexafiltervalue .= $key.'='.$val; } } @@ -342,14 +334,15 @@ if ($action == 'add_export_model') $objexport->hexafiltervalue = $hexafiltervalue; $result = $objexport->create($user); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans("ExportModelSaved", $objexport->model_name), null, 'mesgs'); } else { $langs->load("errors"); - if ($objexport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') + if ($objexport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') { setEventMessages($langs->trans("ErrorExportDuplicateProfil"), null, 'errors'); - else setEventMessages($objexport->error, $objexport->errors, 'errors'); + } else { + setEventMessages($objexport->error, $objexport->errors, 'errors'); + } } } else { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ExportModelName")), null, 'errors'); @@ -357,8 +350,7 @@ if ($action == 'add_export_model') } // Reload a predefined export model -if ($step == 2 && $action == 'select_model') -{ +if ($step == 2 && $action == 'select_model') { $_SESSION["export_selected_fields"] = array(); $_SESSION["export_filtered_fields"] = array(); @@ -366,12 +358,10 @@ if ($step == 2 && $action == 'select_model') $array_filtervalue = array(); $result = $objexport->fetch($exportmodelid); - if ($result > 0) - { + if ($result > 0) { $fieldsarray = preg_split("/,(?! [^(]*\))/", $objexport->hexa); $i = 1; - foreach ($fieldsarray as $val) - { + foreach ($fieldsarray as $val) { $array_selected[$val] = $i; $i++; } @@ -379,8 +369,7 @@ if ($step == 2 && $action == 'select_model') $fieldsarrayvalue = explode(',', $objexport->hexafiltervalue); $i = 1; - foreach ($fieldsarrayvalue as $val) - { + foreach ($fieldsarrayvalue as $val) { $tmp = explode('=', $val); $array_filtervalue[$tmp[0]] = $tmp[1]; $i++; @@ -390,21 +379,20 @@ if ($step == 2 && $action == 'select_model') } // Get form with filters -if ($step == 4 && $action == 'submitFormField') -{ +if ($step == 4 && $action == 'submitFormField') { // on boucle sur les champs selectionne pour recuperer la valeur - if (is_array($objexport->array_export_TypeFields[0])) - { + if (is_array($objexport->array_export_TypeFields[0])) { $_SESSION["export_filtered_fields"] = array(); - foreach ($objexport->array_export_TypeFields[0] as $code => $type) // $code: s.fieldname $value: Text|Boolean|List:ccc - { + foreach ($objexport->array_export_TypeFields[0] as $code => $type) { // $code: s.fieldname $value: Text|Boolean|List:ccc $newcode = (string) preg_replace('/\./', '_', $code); //print 'xxx'.$code."=".$newcode."=".$type."=".$_POST[$newcode]."\n
    "; $filterqualified = 1; - if (!GETPOSTISSET($newcode) || GETPOST($newcode, 'restricthtml') == '') $filterqualified = 0; - elseif (preg_match('/^List/', $type) && (is_numeric(GETPOST($newcode, 'restricthtml')) && GETPOST($newcode, 'restricthtml') <= 0)) $filterqualified = 0; - if ($filterqualified) - { + if (!GETPOSTISSET($newcode) || GETPOST($newcode, 'restricthtml') == '') { + $filterqualified = 0; + } elseif (preg_match('/^List/', $type) && (is_numeric(GETPOST($newcode, 'restricthtml')) && GETPOST($newcode, 'restricthtml') <= 0)) { + $filterqualified = 0; + } + if ($filterqualified) { //print 'Filter on '.$newcode.' type='.$type.' value='.$_POST[$newcode]."\n"; $objexport->array_export_FilterValue[0][$code] = GETPOST($newcode, 'restricthtml'); } @@ -419,8 +407,7 @@ if ($step == 4 && $action == 'submitFormField') * View */ -if ($step == 1 || !$datatoexport) -{ +if ($step == 1 || !$datatoexport) { llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones'); $h = 0; @@ -443,13 +430,11 @@ if ($step == 1 || !$datatoexport) print ''; print ''; - if (count($objexport->array_export_module)) - { + if (count($objexport->array_export_module)) { asort($objexport->array_export_code_for_sort); //var_dump($objexport->array_export_code_for_sort); //$sortedarrayofmodules = dol_sort_array($objexport->array_export_module, 'module_position', 'asc', 0, 0, 1); - foreach ($objexport->array_export_code_for_sort as $key => $value) - { + foreach ($objexport->array_export_code_for_sort as $key => $value) { print ''; + print ''; } } else { print ''; @@ -477,8 +462,7 @@ if ($step == 1 || !$datatoexport) print ''; } -if ($step == 2 && $datatoexport) -{ +if ($step == 2 && $datatoexport) { llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones'); $h = 0; @@ -505,14 +489,14 @@ if ($step == 2 && $datatoexport) print $objexport->array_export_module[0]->getName(); print ''; - // Lot de donnees a exporter - print ''; - print ''; + // Lot de donnees a exporter + print ''; + print ''; print '
    '; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); print "
    \n"; print $px2->show(); diff --git a/htdocs/expensereport/tpl/expensereport_addfile.tpl.php b/htdocs/expensereport/tpl/expensereport_addfile.tpl.php index 9b2cd49faec..c27136ebd38 100644 --- a/htdocs/expensereport/tpl/expensereport_addfile.tpl.php +++ b/htdocs/expensereport/tpl/expensereport_addfile.tpl.php @@ -9,11 +9,9 @@ $permission = $user->rights->expensereport->creer; // We define var to enable the feature to add prefix of uploaded files $savingdocmask = ''; -if (empty($conf->global->MAIN_DISABLE_SUGGEST_REF_AS_PREFIX)) -{ +if (empty($conf->global->MAIN_DISABLE_SUGGEST_REF_AS_PREFIX)) { //var_dump($modulepart); - if (in_array($modulepart, array('facture_fournisseur', 'commande_fournisseur', 'facture', 'commande', 'propal', 'supplier_proposal', 'ficheinter', 'contract', 'expedition', 'project', 'project_task', 'expensereport', 'tax', 'produit', 'product_batch'))) - { + if (in_array($modulepart, array('facture_fournisseur', 'commande_fournisseur', 'facture', 'commande', 'propal', 'supplier_proposal', 'ficheinter', 'contract', 'expedition', 'project', 'project_task', 'expensereport', 'tax', 'produit', 'product_batch'))) { $savingdocmask = dol_sanitizeFileName($object->ref).'-__file__'; } } @@ -35,6 +33,6 @@ $formfile->form_attach_new_file( 'accept', '', 1 - ); +); print '
    '; //print ''.$langs->trans("AttachTheNewLineToTheDocument").'
    '; $modulepart = 'expensereport'; $maxheightmini = 48; $relativepath = (!empty($object->ref) ?dol_sanitizeFileName($object->ref) : '').'/'; $filei = 0; - foreach ($arrayoffiles as $file) - { + foreach ($arrayoffiles as $file) { $urlforhref = array(); $filei++; print '
    '; $fileinfo = pathinfo($file['fullname']); - if (image_format_supported($file['name']) > 0) - { + if (image_format_supported($file['name']) > 0) { $minifile = getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case however) than original //print $file['path'].'/'.$minifile.'
    '; $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity)); @@ -46,8 +42,7 @@ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) $error = 0; $thumbshown = ''; - if (preg_match('/\.pdf$/i', $file['name'])) - { + if (preg_match('/\.pdf$/i', $file['name'])) { $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity)); $filepdf = $conf->expensereport->dir_output.'/'.$relativepath.$file['name']; @@ -56,27 +51,26 @@ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) $pdfexists = file_exists($filepdf); - if ($pdfexists) - { + if ($pdfexists) { // Conversion du PDF en image png si fichier png non existant - if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) - { - if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here. - { + if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) { + if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } } } - if ($pdfexists && !$error) - { + if ($pdfexists && !$error) { $heightforphotref = 70; - if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60; + if (!empty($conf->dol_optimize_smallscreen)) { + $heightforphotref = 60; + } // If the preview file is found - if (file_exists($fileimage)) - { + if (file_exists($fileimage)) { $thumbshown = ''; } } @@ -98,10 +92,8 @@ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) //var_dump(GETPOST($file['relativename'])); var_dump($file['relativename']); var_dump($_FILES['userfile']['name']); // If a file was just uploaded, we check to preselect it if (is_array($_FILES['userfile']['name'])) { - foreach ($_FILES['userfile']['name'] as $tmpfile) - { - if ($file['relativename'] == (GETPOST('savingdocmask', 'alpha') ? dol_sanitizeFileName($object->ref.'-') : '').$tmpfile) - { + foreach ($_FILES['userfile']['name'] as $tmpfile) { + if ($file['relativename'] == (GETPOST('savingdocmask', 'alpha') ? dol_sanitizeFileName($object->ref.'-') : '').$tmpfile) { $checked = ' checked'; break; } elseif ($file['relativename'] && in_array($file['relativename'], GETPOST('attachfile', 'array'))) { @@ -111,8 +103,7 @@ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) } } // If we edit a line already linked, then $filenamelinked is defined to the filename (without path) of linked file - if (!empty($filenamelinked) && $filenamelinked == $file['relativename']) - { + if (!empty($filenamelinked) && $filenamelinked == $file['relativename']) { $checked = ' checked'; } print '
    '; diff --git a/htdocs/expensereport/tpl/linkedobjectblock.tpl.php b/htdocs/expensereport/tpl/linkedobjectblock.tpl.php index a0ef7c353c6..31c5526903b 100644 --- a/htdocs/expensereport/tpl/linkedobjectblock.tpl.php +++ b/htdocs/expensereport/tpl/linkedobjectblock.tpl.php @@ -18,8 +18,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -35,13 +34,12 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; $var = true; $total = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { ?>
    trans("ExpenseReport"); ?>getNomUrl(1); ?>getNomUrl(1); ?> date_debut, 'day'); ?> rights->expensereport->lire) { diff --git a/htdocs/exports/class/export.class.php b/htdocs/exports/class/export.class.php index e4725db3946..8c1bf9642b1 100644 --- a/htdocs/exports/class/export.class.php +++ b/htdocs/exports/class/export.class.php @@ -96,50 +96,49 @@ class Export $modulesdir = dolGetModulesDirs(); - foreach ($modulesdir as $dir) - { + foreach ($modulesdir as $dir) { // Search available exports $handle = @opendir(dol_osencode($dir)); - if (is_resource($handle)) - { + if (is_resource($handle)) { // Search module files - while (($file = readdir($handle)) !== false) - { + while (($file = readdir($handle)) !== false) { $reg = array(); - if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) - { + if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) { $modulename = $reg[1]; // Defined if module is enabled $enabled = true; $part = strtolower(preg_replace('/^mod/i', '', $modulename)); - if ($part == 'propale') $part = 'propal'; - if (empty($conf->$part->enabled)) $enabled = false; + if ($part == 'propale') { + $part = 'propal'; + } + if (empty($conf->$part->enabled)) { + $enabled = false; + } - if ($enabled) - { + if ($enabled) { // Loading Class $file = $dir.$modulename.".class.php"; $classname = $modulename; require_once $file; $module = new $classname($this->db); - if (isset($module->export_code) && is_array($module->export_code)) - { - foreach ($module->export_code as $r => $value) - { + if (isset($module->export_code) && is_array($module->export_code)) { + foreach ($module->export_code as $r => $value) { //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).'
    '; - if ($filter && ($filter != $module->export_code[$r])) continue; + if ($filter && ($filter != $module->export_code[$r])) { + continue; + } // Test if condition to show are ok - if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) continue; + if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) { + continue; + } // Test if permissions are ok $bool = true; - if (isset($module->export_permission)) - { - foreach ($module->export_permission[$r] as $val) - { + if (isset($module->export_permission)) { + foreach ($module->export_permission[$r] as $val) { $perm = $val; //print_r("$perm[0]-$perm[1]-$perm[2]
    "); if (!empty($perm[2])) { @@ -147,8 +146,12 @@ class Export } else { $bool = isset($user->rights->{$perm[0]}->{$perm[1]}) ? $user->rights->{$perm[0]}->{$perm[1]} : false; } - if ($perm[0] == 'user' && $user->admin) $bool = true; - if (!$bool) break; + if ($perm[0] == 'user' && $user->admin) { + $bool = true; + } + if (!$bool) { + break; + } } } //print $bool." $perm[0]"."
    "; @@ -158,10 +161,8 @@ class Export // { // Charge fichier lang en rapport $langtoload = $module->getLangFilesArray(); - if (is_array($langtoload)) - { - foreach ($langtoload as $key) - { + if (is_array($langtoload)) { + foreach ($langtoload as $key) { $langs->load($key); } } @@ -234,12 +235,18 @@ class Export $i = 0; //print_r($array_selected); - foreach ($this->array_export_fields[$indice] as $key => $value) - { - if (!array_key_exists($key, $array_selected)) continue; // Field not selected - if (preg_match('/^none\./', $key)) continue; // A field that must not appears into SQL - if ($i > 0) $sql .= ', '; - else $i++; + foreach ($this->array_export_fields[$indice] as $key => $value) { + if (!array_key_exists($key, $array_selected)) { + continue; // Field not selected + } + if (preg_match('/^none\./', $key)) { + continue; // A field that must not appears into SQL + } + if ($i > 0) { + $sql .= ', '; + } else { + $i++; + } if (strpos($key, ' as ') === false) { $newfield = $key.' as '.str_replace(array('.', '-', '(', ')'), '_', $key); @@ -252,14 +259,16 @@ class Export $sql .= $this->array_export_sql_end[$indice]; // Add the WHERE part. Filtering into sql if a filtering array is provided - if (is_array($array_filterValue) && !empty($array_filterValue)) - { + if (is_array($array_filterValue) && !empty($array_filterValue)) { $sqlWhere = ''; // Loop on each condition to add - foreach ($array_filterValue as $key => $value) - { - if (preg_match('/GROUP_CONCAT/i', $key)) continue; - if ($value != '') $sqlWhere .= " and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]); + foreach ($array_filterValue as $key => $value) { + if (preg_match('/GROUP_CONCAT/i', $key)) { + continue; + } + if ($value != '') { + $sqlWhere .= " and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]); + } } $sql .= $sqlWhere; } @@ -268,12 +277,12 @@ class Export $sql .= $this->array_export_sql_order[$indice]; // Add the HAVING part. - if (is_array($array_filterValue) && !empty($array_filterValue)) - { + if (is_array($array_filterValue) && !empty($array_filterValue)) { // Loop on each condition to add - foreach ($array_filterValue as $key => $value) - { - if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]); + foreach ($array_filterValue as $key => $value) { + if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') { + $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]); + } } } @@ -297,37 +306,41 @@ class Export // build the input field on depend of the type of file switch ($InfoFieldList[0]) { case 'Text': - if (!(strpos($ValueField, '%') === false)) + if (!(strpos($ValueField, '%') === false)) { $szFilterQuery .= " ".$NameField." LIKE '".$ValueField."'"; - else $szFilterQuery .= " ".$NameField." = '".$ValueField."'"; + } else { + $szFilterQuery .= " ".$NameField." = '".$ValueField."'"; + } break; case 'Date': - if (strpos($ValueField, "+") > 0) - { + if (strpos($ValueField, "+") > 0) { // mode plage $ValueArray = explode("+", $ValueField); $szFilterQuery = "(".$this->conditionDate($NameField, trim($ValueArray[0]), ">="); $szFilterQuery .= " AND ".$this->conditionDate($NameField, trim($ValueArray[1]), "<=").")"; } else { - if (is_numeric(substr($ValueField, 0, 1))) + if (is_numeric(substr($ValueField, 0, 1))) { $szFilterQuery = $this->conditionDate($NameField, trim($ValueField), "="); - else $szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1)); + } else { + $szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1)); + } } break; case 'Duree': break; case 'Numeric': // si le signe - - if (strpos($ValueField, "+") > 0) - { + if (strpos($ValueField, "+") > 0) { // mode plage $ValueArray = explode("+", $ValueField); $szFilterQuery = "(".$NameField.">=".$ValueArray[0]; $szFilterQuery .= " AND ".$NameField."<=".$ValueArray[1].")"; } else { - if (is_numeric(substr($ValueField, 0, 1))) + if (is_numeric(substr($ValueField, 0, 1))) { $szFilterQuery = " ".$NameField."=".$ValueField; - else $szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).substr($ValueField, 1); + } else { + $szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).substr($ValueField, 1); + } } break; case 'Boolean': @@ -335,12 +348,14 @@ class Export break; case 'Status': case 'List': - if (is_numeric($ValueField)) + if (is_numeric($ValueField)) { $szFilterQuery = " ".$NameField."=".$ValueField; - else { - if (!(strpos($ValueField, '%') === false)) + } else { + if (!(strpos($ValueField, '%') === false)) { $szFilterQuery = " ".$NameField." LIKE '".$ValueField."'"; - else $szFilterQuery = " ".$NameField." = '".$ValueField."'"; + } else { + $szFilterQuery = " ".$NameField." = '".$ValueField."'"; + } } break; default: @@ -361,9 +376,13 @@ class Export public function conditionDate($Field, $Value, $Sens) { // TODO date_format is forbidden, not performant and not portable. Use instead BETWEEN - if (strlen($Value) == 4) $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$Value."'"; - elseif (strlen($Value) == 6) $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'"; - else $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value; + if (strlen($Value) == 4) { + $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$Value."'"; + } elseif (strlen($Value) == 6) { + $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'"; + } else { + $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value; + } return $Condition; } @@ -385,8 +404,7 @@ class Export $InfoFieldList = explode(":", $TypeField); // build the input field on depend of the type of file - switch ($InfoFieldList[0]) - { + switch ($InfoFieldList[0]) { case 'Text': case 'Date': $szFilterField = ''; @@ -403,15 +421,21 @@ class Export case 'Boolean': $szFilterField = '"; break; @@ -422,51 +446,50 @@ class Export // 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list. // 4 : Name of element for getEntity(). - if (!empty($InfoFieldList[3])) + if (!empty($InfoFieldList[3])) { $keyList = $InfoFieldList[3]; - else $keyList = 'rowid'; + } else { + $keyList = 'rowid'; + } $sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3]) ? '' : ', '.$InfoFieldList[3].' as code'); - if ($InfoFieldList[1] == 'c_stcomm') $sql = 'SELECT id as id, '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3]) ? '' : ', '.$InfoFieldList[3].' as code'); - if ($InfoFieldList[1] == 'c_country') $sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label, code as code'; + if ($InfoFieldList[1] == 'c_stcomm') { + $sql = 'SELECT id as id, '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3]) ? '' : ', '.$InfoFieldList[3].' as code'); + } + if ($InfoFieldList[1] == 'c_country') { + $sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label, code as code'; + } $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[1]; if (!empty($InfoFieldList[4])) { $sql .= ' WHERE entity IN ('.getEntity($InfoFieldList[4]).')'; } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $szFilterField = '"; $this->db->free($resql); - } else dol_print_error($this->db); + } else { + dol_print_error($this->db); + } break; } @@ -542,8 +567,7 @@ class Export dol_syslog(__METHOD__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected)); // Check parameters or context properties - if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) - { + if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) { $this->error = "ErrorBadParameter"; dol_syslog($this->error, LOG_ERR); return -1; @@ -556,22 +580,20 @@ class Export require_once $dir.$file; $objmodel = new $classname($this->db); - if (!empty($sqlquery)) $sql = $sqlquery; - else { + if (!empty($sqlquery)) { + $sql = $sqlquery; + } else { // Define value for indice from $datatoexport $foundindice = 0; - foreach ($this->array_export_code as $key => $dataset) - { - if ($datatoexport == $dataset) - { + foreach ($this->array_export_code as $key => $dataset) { + if ($datatoexport == $dataset) { $indice = $key; $foundindice++; //print "Found indice = ".$indice." for dataset=".$datatoexport."\n"; break; } } - if (empty($foundindice)) - { + if (empty($foundindice)) { $this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code"; return -1; } @@ -582,13 +604,11 @@ class Export $this->sqlusedforexport = $sql; dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { //$this->array_export_label[$indice] if (!empty($conf->global->EXPORT_PREFIX_SPEC)) { $filename = $conf->global->EXPORT_PREFIX_SPEC."_".$datatoexport; - } - else { + } else { $filename = "export_".$datatoexport; } $filename .= '.'.$objmodel->getDriverExtension(); @@ -600,55 +620,48 @@ class Export dol_mkdir($dirname); $result = $objmodel->open_file($dirname."/".$filename, $outputlangs); - if ($result >= 0) - { + if ($result >= 0) { // Genere en-tete $objmodel->write_header($outputlangs); // Genere ligne de titre $objmodel->write_title($this->array_export_fields[$indice], $array_selected, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { // Process special operations - if (!empty($this->array_export_special[$indice])) - { - foreach ($this->array_export_special[$indice] as $key => $value) - { - if (!array_key_exists($key, $array_selected)) continue; // Field not selected + if (!empty($this->array_export_special[$indice])) { + foreach ($this->array_export_special[$indice] as $key => $value) { + if (!array_key_exists($key, $array_selected)) { + continue; // Field not selected + } // Operation NULLIFNEG - if ($this->array_export_special[$indice][$key] == 'NULLIFNEG') - { + if ($this->array_export_special[$indice][$key] == 'NULLIFNEG') { //$alias=$this->array_export_alias[$indice][$key]; $alias = str_replace(array('.', '-', '(', ')'), '_', $key); - if ($obj->$alias < 0) $obj->$alias = ''; - } - // Operation ZEROIFNEG - elseif ($this->array_export_special[$indice][$key] == 'ZEROIFNEG') - { + if ($obj->$alias < 0) { + $obj->$alias = ''; + } + } elseif ($this->array_export_special[$indice][$key] == 'ZEROIFNEG') { + // Operation ZEROIFNEG //$alias=$this->array_export_alias[$indice][$key]; $alias = str_replace(array('.', '-', '(', ')'), '_', $key); - if ($obj->$alias < 0) $obj->$alias = '0'; - } - // Operation GETNUMOPENDAYS (for Holiday module) - elseif ($this->array_export_special[$indice][$key] == 'getNumOpenDays') - { + if ($obj->$alias < 0) { + $obj->$alias = '0'; + } + } elseif ($this->array_export_special[$indice][$key] == 'getNumOpenDays') { + // Operation GETNUMOPENDAYS (for Holiday module) include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; //$alias=$this->array_export_alias[$indice][$key]; $alias = str_replace(array('.', '-', '(', ')'), '_', $key); $obj->$alias = num_open_day(dol_stringtotime($obj->d_date_debut, 1), dol_stringtotime($obj->d_date_fin, 1), 0, 1, $obj->d_halfday, $mysoc->country_code); - } - // Operation INVOICEREMAINTOPAY - elseif ($this->array_export_special[$indice][$key] == 'getRemainToPay') - { + } elseif ($this->array_export_special[$indice][$key] == 'getRemainToPay') { + // Operation INVOICEREMAINTOPAY //$alias=$this->array_export_alias[$indice][$key]; $alias = str_replace(array('.', '-', '(', ')'), '_', $key); $remaintopay = ''; - if ($obj->f_rowid > 0) - { + if ($obj->f_rowid > 0) { global $tmpobjforcomputecall; - if (!is_object($tmpobjforcomputecall)) - { + if (!is_object($tmpobjforcomputecall)) { include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $tmpobjforcomputecall = new Facture($this->db); } @@ -725,8 +738,7 @@ class Export dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { @@ -751,11 +763,9 @@ class Export dol_syslog("Export::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $obj = $this->db->fetch_object($result); - if ($obj) - { + if ($obj) { $this->id = $obj->rowid; $this->model_name = $obj->label; $this->datatoexport = $obj->type; @@ -788,19 +798,19 @@ class Export $error = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model"; - $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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -829,12 +839,10 @@ class Export $sql .= " ORDER BY rowid"; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $keyModel = array_search($obj->type, $this->array_export_code); print "
     
    '; //print img_object($objexport->array_export_module[$key]->getName(),$export->array_export_module[$key]->picto).' '; print $objexport->array_export_module[$key]->getName(); @@ -466,7 +451,7 @@ if ($step == 1 || !$datatoexport) } else { print $langs->trans("NotEnoughPermissions"); } - print '
    '.$langs->trans("NoExportableData").'
    '.$langs->trans("DatasetToExport").''; - $entity = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); - $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); - print img_object($objexport->array_export_module[0]->getName(), $entityicon).' '; - print $objexport->array_export_label[0]; - print '
    '.$langs->trans("DatasetToExport").''; + $entity = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); + $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); + print img_object($objexport->array_export_module[0]->getName(), $entityicon).' '; + print $objexport->array_export_label[0]; + print '
    '; print '
    '; @@ -568,8 +552,7 @@ if ($step == 2 && $datatoexport) $i = 0; - foreach ($fieldsarray as $code=>$label) - { + foreach ($fieldsarray as $code => $label) { print ''; $i++; @@ -583,8 +566,7 @@ if ($step == 2 && $datatoexport) //print $code.'-'.$label.'-'.$entity; $tmparray = explode(':', $entityicon); - if (count($tmparray) >= 2) - { + if (count($tmparray) >= 2) { $entityicon = $tmparray[0]; $entitylang = $tmparray[1]; } @@ -595,27 +577,22 @@ if ($step == 2 && $datatoexport) $tablename = getablenamefromfield($code, $sqlmaxforexport); $htmltext = ''.$langs->trans("Name").": ".$text.'
    '; - if (!empty($objexport->array_export_special[0][$code])) - { + if (!empty($objexport->array_export_special[0][$code])) { $htmltext .= ''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$objexport->array_export_special[0][$code]."
    "; } else { $htmltext .= ''.$langs->trans("Table")." -> ".$langs->trans("Field").": ".$tablename." -> ".preg_replace('/^.*\./', '', $code)."
    "; } - if (!empty($objexport->array_export_examplevalues[0][$code])) - { + if (!empty($objexport->array_export_examplevalues[0][$code])) { $htmltext .= ''.$langs->trans("SourceExample").': '.$objexport->array_export_examplevalues[0][$code].'
    '; } - if (!empty($objexport->array_export_TypeFields[0][$code])) - { + if (!empty($objexport->array_export_TypeFields[0][$code])) { $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].'
    '; } - if (!empty($objexport->array_export_help[0][$code])) - { + if (!empty($objexport->array_export_help[0][$code])) { $htmltext .= ''.$langs->trans("Help").': '.$langs->trans($objexport->array_export_help[0][$code]).'
    '; } - if (isset($array_selected[$code]) && $array_selected[$code]) - { + if (isset($array_selected[$code]) && $array_selected[$code]) { // Selected fields print ' '; print ''.img_left('default', 0, 'style="max-width: 20px"').''; @@ -642,15 +619,13 @@ if ($step == 2 && $datatoexport) print '
    '; /* - * Barre d'action - */ + * Action bar + */ print '
    '; - if (count($array_selected)) - { + if (count($array_selected)) { // If filters exist - if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) - { + if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) { print ''.$langs->trans("NextStep").''; } else { print ''.$langs->trans("NextStep").''; @@ -662,10 +637,8 @@ if ($step == 2 && $datatoexport) print '
    '; } -if ($step == 3 && $datatoexport) -{ - if (count($array_selected) < 1) // This occurs when going back to page after sessecion expired - { +if ($step == 3 && $datatoexport) { + if (count($array_selected) < 1) { // This occurs when going back to page after sessecion expired // Switch to step 2 header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport); exit; @@ -713,8 +686,7 @@ if ($step == 3 && $datatoexport) // Nbre champs exportes print ''.$langs->trans("ExportedFields").''; $list = ''; - foreach ($array_selected as $code=>$value) - { + foreach ($array_selected as $code => $value) { $list .= (!empty($list) ? ', ' : ''); $list .= (isset($objexport->array_export_fields[0][$code]) ? $langs->trans($objexport->array_export_fields[0][$code]) : ''); } @@ -755,8 +727,7 @@ if ($step == 3 && $datatoexport) $i = 0; // on boucle sur les champs - foreach ($fieldsarray as $code => $label) - { + foreach ($fieldsarray as $code => $label) { print ''; $i++; @@ -767,8 +738,7 @@ if ($step == 3 && $datatoexport) print ''; // If value of entityicon=entitylang='icon:Label' $tmparray = explode(':', $entityicon); - if (count($tmparray) >= 2) - { + if (count($tmparray) >= 2) { $entityicon = $tmparray[0]; $entitylang = $tmparray[1]; } @@ -782,22 +752,18 @@ if ($step == 3 && $datatoexport) $tablename = getablenamefromfield($code, $sqlmaxforexport); $htmltext = ''.$langs->trans("Name").': '.$text.'
    '; - if (!empty($objexport->array_export_special[0][$code])) - { + if (!empty($objexport->array_export_special[0][$code])) { $htmltext .= ''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$objexport->array_export_special[0][$code]."
    "; } else { $htmltext .= ''.$langs->trans("Table")." -> ".$langs->trans("Field").": ".$tablename." -> ".preg_replace('/^.*\./', '', $code)."
    "; } - if (!empty($objexport->array_export_examplevalues[0][$code])) - { + if (!empty($objexport->array_export_examplevalues[0][$code])) { $htmltext .= ''.$langs->trans("SourceExample").': '.$objexport->array_export_examplevalues[0][$code].'
    '; } - if (!empty($objexport->array_export_TypeFields[0][$code])) - { + if (!empty($objexport->array_export_TypeFields[0][$code])) { $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].'
    '; } - if (!empty($objexport->array_export_help[0][$code])) - { + if (!empty($objexport->array_export_help[0][$code])) { $htmltext .= ''.$langs->trans("Help").': '.$langs->trans($objexport->array_export_help[0][$code]).'
    '; } @@ -807,11 +773,9 @@ if ($step == 3 && $datatoexport) // Filter value print ''; - if (!empty($Typefieldsarray[$code])) // Example: Text, List:c_country:label:rowid, Number, Boolean - { + if (!empty($Typefieldsarray[$code])) { // Example: Text, List:c_country:label:rowid, Number, Boolean $szInfoFiltre = $objexport->genDocFilter($Typefieldsarray[$code]); - if ($szInfoFiltre) // Is there an info help for this filter ? - { + if ($szInfoFiltre) { // Is there an info help for this filter ? $tmp = $objexport->build_filterField($Typefieldsarray[$code], $code, $ValueFilter); print $form->textwithpicto($tmp, $szInfoFiltre); } else { @@ -829,7 +793,7 @@ if ($step == 3 && $datatoexport) print '
    '; /* - * Barre d'action + * Action bar */ print '
    '; // il n'est pas obligatoire de filtrer les champs @@ -837,10 +801,8 @@ if ($step == 3 && $datatoexport) print '
    '; } -if ($step == 4 && $datatoexport) -{ - if (count($array_selected) < 1) // This occurs when going back to page after sessecion expired - { +if ($step == 4 && $datatoexport) { + if (count($array_selected) < 1) { // This occurs when going back to page after sessecion expired // Switch to step 2 header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport); exit; @@ -862,8 +824,7 @@ if ($step == 4 && $datatoexport) $h++; // If filters exist - if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) - { + if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) { $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport; $head[$h][1] = $langs->trans("Step")." 3"; $h++; @@ -888,20 +849,19 @@ if ($step == 4 && $datatoexport) print $objexport->array_export_module[0]->getName(); print ''; - // Lot de donnees a exporter - print ''.$langs->trans("DatasetToExport").''; - print ''; + // Lot de donnees a exporter + print ''.$langs->trans("DatasetToExport").''; + print ''; $entity = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); - print img_object($objexport->array_export_module[0]->getName(), $entityicon).' '; - print $objexport->array_export_label[0]; - print ''; + print img_object($objexport->array_export_module[0]->getName(), $entityicon).' '; + print $objexport->array_export_label[0]; + print ''; // List of exported fields print ''.$langs->trans("ExportedFields").''; $list = ''; - foreach ($array_selected as $code=>$value) - { + foreach ($array_selected as $code => $value) { $list .= (!empty($list) ? ', ' : ''); $list .= $langs->trans($objexport->array_export_fields[0][$code]); } @@ -909,19 +869,18 @@ if ($step == 4 && $datatoexport) print ''; // List of filtered fiels - if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) - { + if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) { print ''.$langs->trans("FilteredFields").''; $list = ''; - if (!empty($array_filtervalue)) - { - foreach ($array_filtervalue as $code=>$value) - { - if (isset($objexport->array_export_fields[0][$code])) - { + if (!empty($array_filtervalue)) { + foreach ($array_filtervalue as $code => $value) { + if (isset($objexport->array_export_fields[0][$code])) { $list .= ($list ? ', ' : ''); - if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : ''); - else $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'"; + if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) { + $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : ''); + } else { + $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'"; + } } } } @@ -949,8 +908,7 @@ if ($step == 4 && $datatoexport) //print ''.$langs->trans("FieldsTitle").''; print ''; - foreach ($array_selected as $code=>$value) - { + foreach ($array_selected as $code => $value) { print ''; $entity = (!empty($objexport->array_export_entities[0][$code]) ? $objexport->array_export_entities[0][$code] : $objexport->array_export_icon[0]); @@ -960,8 +918,7 @@ if ($step == 4 && $datatoexport) print ''; // If value of entityicon=entitylang='icon:Label' $tmparray = explode(':', $entityicon); - if (count($tmparray) >= 2) - { + if (count($tmparray) >= 2) { $entityicon = $tmparray[0]; $entitylang = $tmparray[1]; } @@ -974,22 +931,18 @@ if ($step == 4 && $datatoexport) $tablename = getablenamefromfield($code, $sqlmaxforexport); $htmltext = ''.$langs->trans("Name").': '.$text.'
    '; - if (!empty($objexport->array_export_special[0][$code])) - { + if (!empty($objexport->array_export_special[0][$code])) { $htmltext .= ''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$objexport->array_export_special[0][$code]."
    "; } else { $htmltext .= ''.$langs->trans("Table")." -> ".$langs->trans("Field").": ".$tablename." -> ".preg_replace('/^.*\./', '', $code)."
    "; } - if (!empty($objexport->array_export_examplevalues[0][$code])) - { + if (!empty($objexport->array_export_examplevalues[0][$code])) { $htmltext .= ''.$langs->trans("SourceExample").': '.$objexport->array_export_examplevalues[0][$code].'
    '; } - if (!empty($objexport->array_export_TypeFields[0][$code])) - { + if (!empty($objexport->array_export_TypeFields[0][$code])) { $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].'
    '; } - if (!empty($objexport->array_export_help[0][$code])) - { + if (!empty($objexport->array_export_help[0][$code])) { $htmltext .= ''.$langs->trans("Help").': '.$langs->trans($objexport->array_export_help[0][$code]).'
    '; } @@ -1001,8 +954,12 @@ if ($step == 4 && $datatoexport) print ''; print $value.' '; print ''; - if ($value < count($array_selected)) print ''.img_down().''; - if ($value > 1) print ''.img_up().''; + if ($value < count($array_selected)) { + print ''.img_down().''; + } + if ($value > 1) { + print ''.img_up().''; + } print ''; //print ' '; @@ -1017,13 +974,11 @@ if ($step == 4 && $datatoexport) print ''; /* - * Barre d'action - * - */ + * Action bar + */ print '
    '; - if (count($array_selected)) - { + if (count($array_selected)) { print ''.$langs->trans("NextStep").''; } @@ -1031,8 +986,7 @@ if ($step == 4 && $datatoexport) // Area for profils export - if (count($array_selected)) - { + if (count($array_selected)) { print '
    '; print '
    '; @@ -1062,15 +1016,15 @@ if ($step == 4 && $datatoexport) $sql = "SELECT rowid, label"; $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; $sql .= " WHERE type = '".$db->escape($datatoexport)."'"; - if (empty($conf->global->EXPORTS_SHARE_MODELS))$sql .= " AND fk_user=".$user->id; + if (empty($conf->global->EXPORTS_SHARE_MODELS)) { + $sql .= " AND fk_user=".$user->id; + } $sql .= " ORDER BY rowid"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; print $obj->label; @@ -1092,10 +1046,8 @@ if ($step == 4 && $datatoexport) } } -if ($step == 5 && $datatoexport) -{ - if (count($array_selected) < 1) // This occurs when going back to page after sessecion expired - { +if ($step == 5 && $datatoexport) { + if (count($array_selected) < 1) { // This occurs when going back to page after sessecion expired // Switch to step 2 header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport); exit; @@ -1117,8 +1069,7 @@ if ($step == 5 && $datatoexport) $h++; // si le filtrage est parametre pour l'export ou pas - if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) - { + if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) { $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport; $head[$h][1] = $langs->trans("Step")." 3"; $h++; @@ -1137,10 +1088,9 @@ if ($step == 5 && $datatoexport) print dol_get_fiche_head($head, $hselected, '', -2); /* - * Confirmation suppression fichier - */ - if ($action == 'remove_file') - { + * Confirmation suppression fichier + */ + if ($action == 'remove_file') { print $form->formconfirm($_SERVER["PHP_SELF"].'?step=5&datatoexport='.$datatoexport.'&file='.urlencode(GETPOST("file")), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1); } @@ -1156,39 +1106,37 @@ if ($step == 5 && $datatoexport) print $objexport->array_export_module[0]->getName(); print ''; - // Dataset to export - print ''.$langs->trans("DatasetToExport").''; - print ''; - $entity = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); - $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); - print img_object($objexport->array_export_module[0]->getName(), $entityicon).' '; - print $objexport->array_export_label[0]; - print ''; + // Dataset to export + print ''.$langs->trans("DatasetToExport").''; + print ''; + $entity = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); + $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); + print img_object($objexport->array_export_module[0]->getName(), $entityicon).' '; + print $objexport->array_export_label[0]; + print ''; // List of exported fields print ''.$langs->trans("ExportedFields").''; $list = ''; - foreach ($array_selected as $code=>$label) - { + foreach ($array_selected as $code => $label) { $list .= (!empty($list) ? ', ' : ''); $list .= $langs->trans($objexport->array_export_fields[0][$code]); } print ''.$list.''; // List of filtered fields - if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) - { + if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) { print ''.$langs->trans("FilteredFields").''; $list = ''; - if (!empty($array_filtervalue)) - { - foreach ($array_filtervalue as $code=>$value) - { - if (isset($objexport->array_export_fields[0][$code])) - { + if (!empty($array_filtervalue)) { + foreach ($array_filtervalue as $code => $value) { + if (isset($objexport->array_export_fields[0][$code])) { $list .= ($list ? ', ' : ''); - if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : ''); - else $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'"; + if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) { + $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : ''); + } else { + $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'"; + } } } } @@ -1211,10 +1159,8 @@ if ($step == 5 && $datatoexport) $liste = $objmodelexport->liste_modeles($db); $listeall = $liste; - foreach ($listeall as $key => $val) - { - if (preg_match('/__\(Disabled\)__/', $listeall[$key])) - { + foreach ($listeall as $key => $val) { + if (preg_match('/__\(Disabled\)__/', $listeall[$key])) { $listeall[$key] = preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $listeall[$key]); unset($liste[$key]); } @@ -1237,13 +1183,14 @@ if ($step == 5 && $datatoexport) print '
    '; - if ($sqlusedforexport && $user->admin) - { + if ($sqlusedforexport && $user->admin) { print info_admin($langs->trans("SQLUsedForExport").':
    '.$sqlusedforexport, 0, 0, 1, '', 'TechnicalInformation'); } - if (!is_dir($conf->export->dir_temp)) dol_mkdir($conf->export->dir_temp); + if (!is_dir($conf->export->dir_temp)) { + dol_mkdir($conf->export->dir_temp); + } // Show existing generated documents // NB: La fonction show_documents rescanne les modules qd genallowed=1, sinon prend $liste @@ -1273,8 +1220,9 @@ function getablenamefromfield($code, $sqlmaxforexport) $newsql = preg_replace('/^(.*) FROM /i', '', $newsql); // Remove part before the FROM $newsql = preg_replace('/WHERE (.*)$/i', '', $newsql); // Remove part after the WHERE so we have now only list of table aliases in a string. We must keep the ' ' before WHERE - if (preg_match($regexstring, $newsql, $reg)) - { + if (preg_match($regexstring, $newsql, $reg)) { return $reg[1]; // The tablename - } else return ''; + } else { + return ''; + } } diff --git a/htdocs/exports/index.php b/htdocs/exports/index.php index 79655a19b2f..22b1729550d 100644 --- a/htdocs/exports/index.php +++ b/htdocs/exports/index.php @@ -39,7 +39,10 @@ $export->load_arrays($user); $form = new Form($db); -llxHeader('', $langs->trans("ExportsArea"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones'); + +$help_url = 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones'; + +llxHeader('', $langs->trans("ExportsArea"), $help_url); print load_fiche_titre($langs->trans("ExportsArea")); @@ -48,8 +51,7 @@ print '
    '; print '
    '; -if (count($export->array_export_code)) -{ +if (count($export->array_export_code)) { print dolGetButtonTitle($langs->trans('NewExport'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/exports/export.php?leftmenu=export', '', $user->rights->export->creer); } print '
    '; @@ -71,10 +73,8 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php'; $model = new ModeleExports($db); $liste = $model->liste_modeles($db); // This is not a static method for exports because method load non static properties -foreach ($liste as $key => $val) -{ - if (preg_match('/__\(Disabled\)__/', $liste[$key])) - { +foreach ($liste as $key => $val) { + if (preg_match('/__\(Disabled\)__/', $liste[$key])) { $liste[$key] = preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $liste[$key]); } diff --git a/htdocs/externalsite/admin/externalsite.php b/htdocs/externalsite/admin/externalsite.php index 66c6d265dec..47f0a3d57be 100644 --- a/htdocs/externalsite/admin/externalsite.php +++ b/htdocs/externalsite/admin/externalsite.php @@ -26,14 +26,17 @@ * \brief Page de configuration du module externalsite */ -if (!defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check anti CSRF attack test +if (!defined('NOSCANPOSTFORINJECTION')) { + define('NOSCANPOSTFORINJECTION', '1'); // Do not check anti CSRF attack test +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'externalsite')); @@ -43,8 +46,7 @@ $def = array(); $action = GETPOST('action', 'aZ09'); // Sauvegardes parametres -if ($action == 'update') -{ +if ($action == 'update') { $i = 0; $db->begin(); @@ -55,8 +57,7 @@ if ($action == 'update') $i += dolibarr_set_const($db, 'EXTERNALSITE_LABEL', trim($label), 'chaine', 0, '', $conf->entity); $i += dolibarr_set_const($db, 'EXTERNALSITE_URL', trim($exturl), 'chaine', 0, '', $conf->entity); - if ($i >= 2) - { + if ($i >= 2) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { diff --git a/htdocs/externalsite/frames.php b/htdocs/externalsite/frames.php index 4827d832af4..04b48ba3cad 100644 --- a/htdocs/externalsite/frames.php +++ b/htdocs/externalsite/frames.php @@ -44,35 +44,29 @@ $keyforcontent = GETPOST('keyforcontent', 'aZ09'); * View */ -if (empty($keyforcontent) && empty($conf->global->EXTERNALSITE_URL)) -{ +if (empty($keyforcontent) && empty($conf->global->EXTERNALSITE_URL)) { llxHeader(); print '
    '.$langs->trans('ExternalSiteModuleNotComplete').'
    '; llxFooter(); exit; } -if (!empty($keyforcontent)) -{ +if (!empty($keyforcontent)) { llxHeader(); print '
    '; if (!preg_match('/EXTERNAL_SITE_CONTENT_/', $keyforcontent) - && !preg_match('/EXTERNAL_SITE_URL_/', $keyforcontent)) - { + && !preg_match('/EXTERNAL_SITE_URL_/', $keyforcontent)) { $langs->load("errors"); print $langs->trans("ErrorBadSyntaxForParamKeyForContent", 'EXTERNAL_SITE_CONTENT_', 'EXTERNAL_SITE_URL_'); - } elseif (empty($conf->global->$keyforcontent)) - { + } elseif (empty($conf->global->$keyforcontent)) { $langs->load("errors"); print $langs->trans("ErrorVariableKeyForContentMustBeSet", 'EXTERNAL_SITE_CONTENT_'.$keyforcontent, 'EXTERNAL_SITE_URL_'.$keyforcontent); } else { - if (preg_match('/EXTERNAL_SITE_CONTENT_/', $keyforcontent)) - { + if (preg_match('/EXTERNAL_SITE_CONTENT_/', $keyforcontent)) { print $conf->global->$keyforcontent; - } elseif (preg_match('/EXTERNAL_SITE_URL_/', $keyforcontent)) - { + } elseif (preg_match('/EXTERNAL_SITE_URL_/', $keyforcontent)) { /*print " @@ -80,17 +74,17 @@ if (!empty($keyforcontent)) global->MAIN_MENU_INVERT)?"rows":"cols")."=\"".$heightforframes.",*\" border=0 framespacing=0 frameborder=0> - + "; print ''; print " - - <body> + <noframes> + <body> - </body> - + + @@ -111,8 +105,7 @@ if (!empty($keyforcontent)) print '<div>'; llxFooter(); } else { - if (preg_match('/^\//', $conf->global->EXTERNALSITE_URL) || preg_match('/^http/i', $conf->global->EXTERNALSITE_URL)) - { + if (preg_match('/^\//', $conf->global->EXTERNALSITE_URL) || preg_match('/^http/i', $conf->global->EXTERNALSITE_URL)) { print " <html> <head> diff --git a/htdocs/fichinter/admin/fichinter_extrafields.php b/htdocs/fichinter/admin/fichinter_extrafields.php index 0fa5a930f05..2fec51a0f5b 100644 --- a/htdocs/fichinter/admin/fichinter_extrafields.php +++ b/htdocs/fichinter/admin/fichinter_extrafields.php @@ -39,13 +39,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 = 'fichinter'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -77,8 +81,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -91,8 +94,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -104,8 +106,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/fichinter/admin/fichinterdet_extrafields.php b/htdocs/fichinter/admin/fichinterdet_extrafields.php index f648548c3b4..1cbdeb4cf0a 100644 --- a/htdocs/fichinter/admin/fichinterdet_extrafields.php +++ b/htdocs/fichinter/admin/fichinterdet_extrafields.php @@ -39,13 +39,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 = 'fichinterdet'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -78,8 +82,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -92,8 +95,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -105,8 +107,7 @@ if ($action == 'create') /* Edition d'un champ optionnel */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/fichinter/card-rec.php b/htdocs/fichinter/card-rec.php index f245084f8db..e687169fe50 100644 --- a/htdocs/fichinter/card-rec.php +++ b/htdocs/fichinter/card-rec.php @@ -8,7 +8,7 @@ * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr> * Copyright (C) 2015 Alexandre Spangaro <aspangaro@open-dsi.fr> * Copyright (C) 2016-2018 Charlie Benke <charlie@patas-monkey.com> - * Copyright (C) 2018-2019 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -52,22 +52,31 @@ $langs->loadLangs(array("interventions", "admin", "compta", "bills")); // Security check $id = (GETPOST('fichinterid', 'int') ?GETPOST('fichinterid', 'int') : GETPOST('id', 'int')); $action = GETPOST('action', 'aZ09'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $objecttype = 'fichinter_rec'; -if ($action == "create" || $action == "add") $objecttype = ''; +if ($action == "create" || $action == "add") { + $objecttype = ''; +} $result = restrictedArea($user, 'ficheinter', $id, $objecttype); -if ($page == -1) +if ($page == -1) { $page = 0; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; -if ($sortorder == "") +$sortorder = GETPOST('sortorder', 'alpha'); +$sortfield = GETPOST('sortfield', 'aZ09comma'); +if ($sortorder == "") { $sortorder = "DESC"; +} -if ($sortfield == "") +if ($sortfield == "") { $sortfield = "f.datec"; +} $object = new FichinterRec($db); $extrafields = new ExtraFields($db); @@ -212,7 +221,9 @@ if ($action == 'add') { // Set next date of execution $object->fetch($id); $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); + if (!empty($date)) { + $object->setNextDate($date); + } } elseif ($action == 'setnb_gen_max' && $user->rights->ficheinter->creer) { // Set max period $object->fetch($id); @@ -224,7 +235,9 @@ if ($action == 'add') { * View */ -llxHeader('', $langs->trans("RepeatableIntervention"), 'ch-fichinter.html#s-fac-fichinter-rec'); +$help_url = ''; + +llxHeader('', $langs->trans("RepeatableIntervention"), $help_url); $form = new Form($db); $companystatic = new Societe($db); @@ -259,8 +272,12 @@ if ($action == 'create') { print dol_get_fiche_head(); $rowspan = 4; - if (!empty($conf->projet->enabled) && $object->fk_project > 0) $rowspan++; - if (!empty($conf->contrat->enabled) && $object->fk_contrat > 0) $rowspan++; + if (!empty($conf->projet->enabled) && $object->fk_project > 0) { + $rowspan++; + } + if (!empty($conf->contrat->enabled) && $object->fk_contrat > 0) { + $rowspan++; + } print '<table class="border centpercent">'; @@ -593,9 +610,11 @@ if ($action == 'create') { print '<td class="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>'; print '</tr></table></form>'; } else { - if ($object->frequency > 0) + if ($object->frequency > 0) { print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency); - else print $langs->trans("NotARecurringInterventionalTemplate"); + } else { + print $langs->trans("NotARecurringInterventionalTemplate"); + } } print '</td></tr>'; @@ -617,12 +636,16 @@ if ($action == 'create') { print '<tr><td>'; if ($user->rights->ficheinter->creer && ($action == 'nb_gen_max' || $object->frequency > 0)) { print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->rights->facture->creer); - } else print $langs->trans("MaxPeriodNumber"); + } else { + print $langs->trans("MaxPeriodNumber"); + } print '</td><td>'; if ($action == 'nb_gen_max' || $object->frequency > 0) { print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max ? $object->nb_gen_max : '', $object, $user->rights->facture->creer); - } else print ''; + } else { + print ''; + } print '</td>'; print '</tr>'; @@ -686,13 +709,19 @@ if ($action == 'create') { $i = 0; while ($i < $num) { // Show product and description - if (isset($object->lines[$i]->product_type)) + if (isset($object->lines[$i]->product_type)) { $type = $object->lines[$i]->product_type; - else $object->lines[$i]->fk_product_type; + } else { + $object->lines[$i]->fk_product_type; + } // Try to enhance type detection using date_start and date_end for free lines when type // was not saved. - if (!empty($objp->date_start)) $type = 1; - if (!empty($objp->date_end)) $type = 1; + if (!empty($objp->date_start)) { + $type = 1; + } + if (!empty($objp->date_end)) { + $type = 1; + } // Show line print '<tr class="oddeven">'; @@ -707,8 +736,8 @@ if ($action == 'create') { } print '</table>'; - /** - * Barre d'actions + /* + * Action bar */ print '<div class="tabsAction">'; @@ -725,7 +754,9 @@ if ($action == 'create') { print $langs->trans('Delete').'</a></div>'; } print '</div>'; - } else print $langs->trans("ErrorRecordNotFound"); + } else { + print $langs->trans("ErrorRecordNotFound"); + } } else { /* * List mode @@ -741,14 +772,24 @@ if ($action == 'create') { } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity = ".$conf->entity; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } if (!$user->rights->societe->client->voir && !$socid) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } - if ($search_ref) $sql .= natural_search('f.titre', $search_ref); - if ($search_societe) $sql .= natural_search('s.nom', $search_societe); - if ($search_frequency == '1') $sql .= ' AND f.frequency > 0'; - if ($search_frequency == '0') $sql .= ' AND (f.frequency IS NULL or f.frequency = 0)'; + if ($search_ref) { + $sql .= natural_search('f.titre', $search_ref); + } + if ($search_societe) { + $sql .= natural_search('s.nom', $search_societe); + } + if ($search_frequency == '1') { + $sql .= ' AND f.frequency > 0'; + } + if ($search_frequency == '0') { + $sql .= ' AND (f.frequency IS NULL or f.frequency = 0)'; + } //$sql .= " ORDER BY $sortfield $sortorder, rowid DESC "; @@ -853,8 +894,12 @@ if ($action == 'create') { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=createfrommodel'; print '&socid='.$objp->socid.'&id='.$objp->fich_rec.'">'; print $langs->trans("CreateFichInter").'</a>'; - } else print $langs->trans("DateIsNotEnough"); - } else print "&nbsp;"; + } else { + print $langs->trans("DateIsNotEnough"); + } + } else { + print "&nbsp;"; + } print "</td>"; diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php index 6c1dd4ddeb2..ebc884eb033 100644 --- a/htdocs/fichinter/card.php +++ b/htdocs/fichinter/card.php @@ -36,18 +36,15 @@ require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/fichinter.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } -if ($conf->contrat->enabled) -{ +if ($conf->contrat->enabled) { require_once DOL_DOCUMENT_ROOT."/core/class/html.formcontract.class.php"; require_once DOL_DOCUMENT_ROOT."/contrat/class/contrat.class.php"; } -if (!empty($conf->global->FICHEINTER_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/fichinter/mod_".$conf->global->FICHEINTER_ADDON.".php")) -{ +if (!empty($conf->global->FICHEINTER_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/fichinter/mod_".$conf->global->FICHEINTER_ADDON.".php")) { require_once DOL_DOCUMENT_ROOT."/core/modules/fichinter/mod_".$conf->global->FICHEINTER_ADDON.'.php'; } require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -75,7 +72,9 @@ $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($ $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -87,11 +86,14 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Load object -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $ret = $object->fetch($id, $ref); - if ($ret > 0) $ret = $object->fetch_thirdparty(); - if ($ret < 0) dol_print_error('', $object->error); + if ($ret > 0) { + $ret = $object->fetch_thirdparty(); + } + if ($ret < 0) { + dol_print_error('', $object->error); + } } $permissionnote = $user->rights->ficheinter->creer; // Used by the include of actions_setnotes.inc.php @@ -106,14 +108,13 @@ $error = 0; $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)) -{ - if ($cancel) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -125,20 +126,16 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->ficheinter->creer) - { - if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) - { + if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->ficheinter->creer) { + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { - if ($object->id > 0) - { + if ($object->id > 0) { // Because createFromClone modifies the object, we must clone it so that we can restore it later $orig = clone $object; $result = $object->createFromClone($user, $socid); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit; } else { @@ -150,21 +147,21 @@ if (empty($reshook)) } } - if ($action == 'confirm_validate' && $confirm == 'yes' && $user->rights->ficheinter->creer) - { + if ($action == 'confirm_validate' && $confirm == 'yes' && $user->rights->ficheinter->creer) { $result = $object->setValid($user); - if ($result >= 0) - { - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if ($result >= 0) { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -178,15 +175,17 @@ if (empty($reshook)) } } elseif ($action == 'confirm_modify' && $confirm == 'yes' && $user->rights->ficheinter->creer) { $result = $object->setDraft($user); - if ($result >= 0) - { - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if ($result >= 0) { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -212,16 +211,13 @@ if (empty($reshook)) $object->note_private = GETPOST('note_private', 'restricthtml'); $object->note_public = GETPOST('note_public', 'restricthtml'); - if ($object->socid > 0) - { + if ($object->socid > 0) { // If creation from another object of another module (Example: origin=propal, originid=1) - if (!empty($origin) && !empty($originid)) - { + if (!empty($origin) && !empty($originid)) { // Parse element/subelement (ex: project_task) $regs = array(); $element = $subelement = GETPOST('origin', 'alphanohtml'); - if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin', 'alphanohtml'), $regs)) - { + if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin', 'alphanohtml'), $regs)) { $element = $regs[1]; $subelement = $regs[2]; } @@ -242,8 +238,7 @@ if (empty($reshook)) // Possibility to add external linked objects with hooks $object->linked_objects[$object->origin] = $object->origin_id; - if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) - { + if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) { $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); } @@ -261,8 +256,7 @@ if (empty($reshook)) $id = $object->create($user); - if ($id > 0) - { + if ($id > 0) { dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); @@ -270,12 +264,10 @@ if (empty($reshook)) dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); $result = $srcobject->fetch($object->origin_id); - if ($result > 0) - { + if ($result > 0) { $srcobject->fetch_thirdparty(); $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject, 'fetch_lines')) - { + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) { $srcobject->fetch_lines(); $lines = $srcobject->lines; } @@ -283,9 +275,10 @@ if (empty($reshook)) if (is_array($lines)) { $num = count($lines); - for ($i = 0; $i < $num; $i++) - { - if (!in_array($lines[$i]->id, $selectedLines)) continue; // Skip unselected lines + for ($i = 0; $i < $num; $i++) { + if (!in_array($lines[$i]->id, $selectedLines)) { + continue; // Skip unselected lines + } $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : Product::TYPE_PRODUCT); @@ -293,8 +286,7 @@ if (empty($reshook)) $duration = 3600; // Default to one hour // Predefined products & services - if ($lines[$i]->fk_product > 0) - { + if ($lines[$i]->fk_product > 0) { $prod = new Product($db); $prod->id = $lines[$i]->fk_product; @@ -305,8 +297,12 @@ if (empty($reshook)) $prod->fetch($lines[$i]->fk_product); $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) $newlang = $srcobject->thirdparty->default_lang; + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if (empty($newlang)) { + $newlang = $srcobject->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -367,12 +363,11 @@ if (empty($reshook)) $id, $desc, $date_intervention, - $duration, - $array_options + $duration, + $array_options ); - if ($result < 0) - { + if ($result < 0) { $error++; break; } @@ -395,16 +390,14 @@ if (empty($reshook)) $action = 'create'; } - if (!$error) - { + if (!$error) { // Extrafields $array_options = $extrafields->getOptionalsFromPost($object->table_element); $object->array_options = $array_options; $result = $object->create($user); - if ($result > 0) - { + if ($result > 0) { $id = $result; // Force raffraichissement sur fiche venant d'etre cree } else { $langs->load("errors"); @@ -429,22 +422,19 @@ if (empty($reshook)) if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Set into a project - elseif ($action == 'classin' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'classin' && $user->rights->ficheinter->creer) { + // Set into a project $result = $object->setProject(GETPOST('projectid', 'int')); - if ($result < 0) dol_print_error($db, $object->error); - } - - // Set into a contract - elseif ($action == 'setcontract' && $user->rights->contrat->creer) - { + if ($result < 0) { + dol_print_error($db, $object->error); + } + } elseif ($action == 'setcontract' && $user->rights->contrat->creer) { + // Set into a contract $result = $object->set_contrat($user, GETPOST('contratid', 'int')); - if ($result < 0) dol_print_error($db, $object->error); - } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->ficheinter->supprimer) - { + if ($result < 0) { + dol_print_error($db, $object->error); + } + } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->ficheinter->supprimer) { $result = $object->delete($user); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -452,32 +442,26 @@ if (empty($reshook)) header('Location: '.DOL_URL_ROOT.'/fichinter/list.php?leftmenu=ficheinter&restore_lastsearch_values=1'); exit; - } elseif ($action == 'setdescription' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'setdescription' && $user->rights->ficheinter->creer) { $result = $object->set_description($user, GETPOST('description')); - if ($result < 0) dol_print_error($db, $object->error); - } - - // Add line - elseif ($action == "addline" && $user->rights->ficheinter->creer) - { - if (!GETPOST('np_desc', 'restricthtml') && empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) - { + if ($result < 0) { + dol_print_error($db, $object->error); + } + } elseif ($action == "addline" && $user->rights->ficheinter->creer) { + // Add line + if (!GETPOST('np_desc', 'restricthtml') && empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")); $error++; } - if (empty($conf->global->FICHINTER_WITHOUT_DURATION) && !GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) - { + if (empty($conf->global->FICHINTER_WITHOUT_DURATION) && !GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Duration")); $error++; } - if (empty($conf->global->FICHINTER_WITHOUT_DURATION) && GETPOST('durationhour', 'int') >= 24 && GETPOST('durationmin', 'int') > 0) - { + if (empty($conf->global->FICHINTER_WITHOUT_DURATION) && GETPOST('durationhour', 'int') >= 24 && GETPOST('durationmin', 'int') > 0) { $mesg = $langs->trans("ErrorValueTooHigh"); $error++; } - if (!$error) - { + if (!$error) { $db->begin(); $desc = GETPOST('np_desc', 'restricthtml'); @@ -500,19 +484,23 @@ if (empty($reshook)) // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if ($result >= 0) - { + if ($result >= 0) { $db->commit(); - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + fichinter_create($db, $object, $object->model_pdf, $outputlangs); + } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } else { @@ -520,73 +508,51 @@ if (empty($reshook)) $db->rollback(); } } - } - - // Classify Billed - elseif ($action == 'classifybilled' && $user->rights->ficheinter->creer) - { - $result = $object->setStatut(2); + } elseif ($action == 'classifybilled' && $user->rights->ficheinter->creer) { + // Classify Billed + $result = $object->setStatut(Fichinter::STATUS_BILLED); if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Classify unbilled - elseif ($action == 'classifyunbilled' && $user->rights->ficheinter->creer) - { - $result = $object->setStatut(1); - if ($result > 0) - { + } elseif ($action == 'classifyunbilled' && $user->rights->ficheinter->creer) { + // Classify unbilled + $result = $object->setStatut(Fichinter::STATUS_VALIDATED); + if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } else { $mesg = $object->error; } - } - - // Classify Done - elseif ($action == 'classifydone' && $user->rights->ficheinter->creer) - { - $result = $object->setStatut(3); - if ($result > 0) - { + } elseif ($action == 'classifydone' && $user->rights->ficheinter->creer) { + // Classify Done + $result = $object->setStatut(Fichinter::STATUS_CLOSED); + if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Reopen - elseif ($action == 'confirm_reopen' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'confirm_reopen' && $user->rights->ficheinter->creer) { + // Reopen $result = $object->setStatut(Fichinter::STATUS_VALIDATED); - if ($result > 0) - { + if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; - } - else { + } else { $mesg = $object->error; } - } - - /* - * Mise a jour d'une ligne d'intervention - */ - elseif ($action == 'updateline' && $user->rights->ficheinter->creer && GETPOST('save', 'alpha') == $langs->trans("Save")) { + } elseif ($action == 'updateline' && $user->rights->ficheinter->creer && GETPOST('save', 'alpha') == $langs->trans("Save")) { + // Mise a jour d'une ligne d'intervention $objectline = new FichinterLigne($db); - if ($objectline->fetch($lineid) <= 0) - { + if ($objectline->fetch($lineid) <= 0) { dol_print_error($db); exit; } - if ($object->fetch($objectline->fk_fichinter) <= 0) - { + if ($object->fetch($objectline->fk_fichinter) <= 0) { dol_print_error($db); exit; } @@ -606,8 +572,7 @@ if (empty($reshook)) $objectline->array_options = $array_options; $result = $objectline->update($user); - if ($result < 0) - { + if ($result < 0) { dol_print_error($db); exit; } @@ -615,34 +580,32 @@ if (empty($reshook)) // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + fichinter_create($db, $object, $object->model_pdf, $outputlangs); + } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; - } - - /* - * Supprime une ligne d'intervention AVEC confirmation - */ - elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->ficheinter->creer) { + // Supprime une ligne d'intervention AVEC confirmation $objectline = new FichinterLigne($db); - if ($objectline->fetch($lineid) <= 0) - { + if ($objectline->fetch($lineid) <= 0) { dol_print_error($db); exit; } $result = $objectline->deleteline($user); - if ($object->fetch($objectline->fk_fichinter) <= 0) - { + if ($object->fetch($objectline->fk_fichinter) <= 0) { dol_print_error($db); exit; } @@ -650,52 +613,61 @@ if (empty($reshook)) // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs); - } - - /* - * Set position of lines - */ - elseif ($action == 'up' && $user->rights->ficheinter->creer) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + fichinter_create($db, $object, $object->model_pdf, $outputlangs); + } + } elseif ($action == 'up' && $user->rights->ficheinter->creer) { + // Set position of lines $object->line_up($lineid); // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + fichinter_create($db, $object, $object->model_pdf, $outputlangs); + } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.$lineid); exit; - } elseif ($action == 'down' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'down' && $user->rights->ficheinter->creer) { $object->line_down($lineid); // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + fichinter_create($db, $object, $object->model_pdf, $outputlangs); + } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.$lineid); exit; @@ -715,66 +687,55 @@ if (empty($reshook)) $permissiontoadd = $user->rights->ficheinter->creer; include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('INTERVENTION_MODIFY'); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if ($error) $action = 'edit_extras'; + if ($error) { + $action = 'edit_extras'; + } } - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->ficheinter->creer) - { - if ($action == 'addcontact') - { - if ($result > 0 && $id > 0) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->ficheinter->creer) { + if ($action == 'addcontact') { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); $mesg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); } else { $mesg = $object->error; } } - } - - // bascule du statut d'un contact - elseif ($action == 'swapstatut') - { + } elseif ($action == 'swapstatut') { + // bascule du statut d'un contact $result = $object->swapContactStatus(GETPOST('ligne', 'int')); - } - - // Efface un contact - elseif ($action == 'deletecontact') - { + } elseif ($action == 'deletecontact') { + // Efface un contact $result = $object->delete_contact(GETPOST('lineid', 'int')); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -791,13 +752,19 @@ if (empty($reshook)) $form = new Form($db); $formfile = new FormFile($db); -if ($conf->contrat->enabled) $formcontract = new FormContract($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if ($conf->contrat->enabled) { + $formcontract = new FormContract($db); +} +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} -llxHeader('', $langs->trans("Intervention")); -if ($action == 'create') -{ +$help_url = 'EN:Module_Interventions'; + +llxHeader('', $langs->trans("Intervention"), $help_url); + +if ($action == 'create') { // Create new intervention $soc = new Societe($db); @@ -810,21 +777,20 @@ if ($action == 'create') dol_htmloutput_mesg($mesg); } - if ($socid) $res = $soc->fetch($socid); + if ($socid) { + $res = $soc->fetch($socid); + } - if (GETPOST('origin', 'alphanohtml') && GETPOST('originid', 'int')) - { + if (GETPOST('origin', 'alphanohtml') && GETPOST('originid', 'int')) { // Parse element/subelement (ex: project_task) $regs = array(); $element = $subelement = GETPOST('origin', 'alphanohtml'); - if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin', 'alphanohtml'), $regs)) - { + if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin', 'alphanohtml'), $regs)) { $element = $regs[1]; $subelement = $regs[2]; } - if ($element == 'project') - { + if ($element == 'project') { $projectid = GETPOST('originid', 'int'); } else { // For compatibility @@ -843,8 +809,7 @@ if ($action == 'create') $classname = ucfirst($subelement); $objectsrc = new $classname($db); $objectsrc->fetch(GETPOST('originid')); - if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) - { + if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) { $objectsrc->fetch_lines(); $lines = $objectsrc->lines; } @@ -864,8 +829,7 @@ if ($action == 'create') $projectid = GETPOST('projectid', 'int'); } - if (!$conf->global->FICHEINTER_ADDON) - { + if (!$conf->global->FICHEINTER_ADDON) { dol_print_error($db, $langs->trans("Error")." ".$langs->trans("Error_FICHEINTER_ADDON_NotDefined")); exit; } @@ -878,8 +842,7 @@ if ($action == 'create') //$modFicheinter = new $obj; //$numpr = $modFicheinter->getNextValue($soc, $object); - if ($socid > 0) - { + if ($socid > 0) { $soc = new Societe($db); $soc->fetch($socid); @@ -904,35 +867,31 @@ if ($action == 'create') print '</td></tr>'; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); $langs->load("project"); print '<tr><td>'.$langs->trans("Project").'</td><td>'; /* Fix: If a project must be linked to any companies (suppliers or not), project must be not be set as limited to customer but must be not linked to any particular thirdparty - if ($societe->fournisseur==1) - $numprojet=select_projects(-1,$_POST["projectid"],'projectid'); - else - $numprojet=select_projects($societe->id,$_POST["projectid"],'projectid'); - */ + if ($societe->fournisseur==1) + $numprojet=select_projects(-1,$_POST["projectid"],'projectid'); + else + $numprojet=select_projects($societe->id,$_POST["projectid"],'projectid'); + */ $numprojet = $formproject->select_projects($soc->id, $projectid, 'projectid'); - if ($numprojet == 0) - { + if ($numprojet == 0) { print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$soc->id.'&action=create"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddProject").'"></span></a>'; } print '</td></tr>'; } // Contract - if ($conf->contrat->enabled) - { + if ($conf->contrat->enabled) { $langs->load("contracts"); print '<tr><td>'.$langs->trans("Contract").'</td><td>'; $numcontrat = $formcontract->select_contract($soc->id, GETPOST('contratid', 'int'), 'contratid', 0, 1, 1); - if ($numcontrat == 0) - { + if ($numcontrat == 0) { print ' &nbsp; <a href="'.DOL_URL_ROOT.'/contrat/card.php?socid='.$soc->id.'&action=create"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddContract").'"></span></a>'; } print '</td></tr>'; @@ -956,8 +915,7 @@ if ($action == 'create') print '</td></tr>'; // Private note - if (empty($user->socid)) - { + if (empty($user->socid)) { print '<tr>'; print '<td class="tdtop">'.$langs->trans('NotePrivate').'</td>'; print '<td>'; @@ -971,47 +929,46 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } // Show link to origin object - if (!empty($origin) && !empty($originid) && is_object($objectsrc)) - { + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) { $newclassname = $classname; - if ($newclassname == 'Propal') $newclassname = 'CommercialProposal'; + if ($newclassname == 'Propal') { + $newclassname = 'CommercialProposal'; + } print '<tr><td>'.$langs->trans($newclassname).'</td><td colspan="2">'.$objectsrc->getNomUrl(1).'</td></tr>'; // Amount /* Hide amount because we only copy services so amount may differ than source - print '<tr><td>' . $langs->trans('AmountHT') . '</td><td>' . price($objectsrc->total_ht) . '</td></tr>'; - print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td>' . price($objectsrc->total_tva) . "</td></tr>"; - if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE - { - print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td><td>' . price($objectsrc->total_localtax1) . "</td></tr>"; - } + print '<tr><td>' . $langs->trans('AmountHT') . '</td><td>' . price($objectsrc->total_ht) . '</td></tr>'; + print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td>' . price($objectsrc->total_tva) . "</td></tr>"; + if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE + { + print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td><td>' . price($objectsrc->total_localtax1) . "</td></tr>"; + } - if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF - { - print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td><td>' . price($objectsrc->total_localtax2) . "</td></tr>"; - } + if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF + { + print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td><td>' . price($objectsrc->total_localtax2) . "</td></tr>"; + } - print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td>' . price($objectsrc->total_ttc) . "</td></tr>"; + print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td>' . price($objectsrc->total_ttc) . "</td></tr>"; - if (!empty($conf->multicurrency->enabled)) - { - print '<tr><td>' . $langs->trans('MulticurrencyAmountHT') . '</td><td>' . price($objectsrc->multicurrency_total_ht) . '</td></tr>'; - print '<tr><td>' . $langs->trans('MulticurrencyAmountVAT') . '</td><td>' . price($objectsrc->multicurrency_total_tva) . "</td></tr>"; - print '<tr><td>' . $langs->trans('MulticurrencyAmountTTC') . '</td><td>' . price($objectsrc->multicurrency_total_ttc) . "</td></tr>"; - } - */ + if (!empty($conf->multicurrency->enabled)) + { + print '<tr><td>' . $langs->trans('MulticurrencyAmountHT') . '</td><td>' . price($objectsrc->multicurrency_total_ht) . '</td></tr>'; + print '<tr><td>' . $langs->trans('MulticurrencyAmountVAT') . '</td><td>' . price($objectsrc->multicurrency_total_tva) . "</td></tr>"; + print '<tr><td>' . $langs->trans('MulticurrencyAmountTTC') . '</td><td>' . price($objectsrc->multicurrency_total_ttc) . "</td></tr>"; + } + */ } print '</table>'; - if (is_object($objectsrc)) - { + if (is_object($objectsrc)) { print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">'; print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">'; } elseif ($origin == 'project' && !empty($projectid)) { @@ -1045,8 +1002,7 @@ if ($action == 'create') print dol_get_fiche_head(''); - if (is_object($objectsrc)) - { + if (is_object($objectsrc)) { print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">'; print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">'; } elseif ($origin == 'project' && !empty($projectid)) { @@ -1070,11 +1026,10 @@ if ($action == 'create') print '</form>'; } -} elseif ($id > 0 || !empty($ref)) -{ +} elseif ($id > 0 || !empty($ref)) { /* * Affichage en mode visu - */ + */ $object->fetch($id, $ref); $object->fetch_thirdparty(); @@ -1095,21 +1050,17 @@ if ($action == 'create') $formconfirm = ''; // Confirm deletion of intervention - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteIntervention'), $langs->trans('ConfirmDeleteIntervention'), 'confirm_delete', '', 0, 1); } // Confirm validation - if ($action == 'validate') - { + if ($action == 'validate') { // on verifie si l'objet est en numerotation provisoire $ref = substr($object->ref, 1, 4); - if ($ref == 'PROV') - { + if ($ref == 'PROV') { $numref = $object->getNextNumRef($soc); - if (empty($numref)) - { + if (empty($numref)) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } @@ -1122,20 +1073,17 @@ if ($action == 'create') } // Confirm back to draft - if ($action == 'modify') - { + if ($action == 'modify') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ModifyIntervention'), $langs->trans('ConfirmModifyIntervention'), 'confirm_modify', '', 0, 1); } // Confirm back to open - if ($action == 'reopen') - { + if ($action == 'reopen') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Reopen'), $langs->trans('ConfirmReopenIntervention', $object->ref), 'confirm_reopen', '', 0, 1); } // Confirm deletion of line - if ($action == 'ask_deleteline') - { + if ($action == 'ask_deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&line_id='.$lineid, $langs->trans('DeleteInterventionLine'), $langs->trans('ConfirmDeleteInterventionLine'), 'confirm_deleteline', '', 0, 1); } @@ -1153,12 +1101,14 @@ if ($action == 'create') $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneIntervention', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } - if (!$formconfirm) - { + if (!$formconfirm) { $parameters = array('formConfirm' => $formconfirm, 'lineid'=>$lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } } // Print form confirm @@ -1176,12 +1126,10 @@ if ($action == 'create') // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->ficheinter->creer) - { + if ($user->rights->ficheinter->creer) { if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; } @@ -1219,8 +1167,7 @@ if ($action == 'create') print '<table class="border tableforfield" width="100%">'; - if (!empty($conf->global->FICHINTER_USE_PLANNED_AND_DONE_DATES)) - { + if (!empty($conf->global->FICHINTER_USE_PLANNED_AND_DONE_DATES)) { // Date Start print '<tr><td class="titlefield">'.$langs->trans("Dateo").'</td>'; print '<td>'; @@ -1252,8 +1199,7 @@ if ($action == 'create') print '</tr>'; // Contract - if ($conf->contrat->enabled) - { + if ($conf->contrat->enabled) { $langs->load('contracts'); print '<tr>'; print '<td>'; @@ -1261,21 +1207,18 @@ if ($action == 'create') print '<table class="nobordernopadding centpercent"><tr><td>'; print $langs->trans('Contract'); print '</td>'; - if ($action != 'contrat') - { + if ($action != 'contrat') { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=contrat&amp;id='.$object->id.'">'; print img_edit($langs->trans('SetContract'), 1); print '</a></td>'; } print '</tr></table>'; print '</td><td>'; - if ($action == 'contrat') - { + if ($action == 'contrat') { $formcontract = new Formcontract($db); $formcontract->formSelectContract($_SERVER["PHP_SELF"].'?id='.$object->id, $object->socid, $object->fk_contrat, 'contratid', 0, 1, 1); } else { - if ($object->fk_contrat) - { + if ($object->fk_contrat) { $contratstatic = new Contrat($db); $contratstatic->fetch($object->fk_contrat); //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>'; @@ -1301,8 +1244,7 @@ if ($action == 'create') print '<table class="border tableforfield centpercent">'; - if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) - { + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) { // Duration print '<tr><td class="titlefield">'.$langs->trans("TotalDuration").'</td>'; print '<td>'.convertSecondToTime($object->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'</td>'; @@ -1318,23 +1260,20 @@ if ($action == 'create') print '<div class="clearboth"></div><br>'; - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $blocname = 'contacts'; $title = $langs->trans('ContactsAddresses'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } - if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $blocname = 'notes'; $title = $langs->trans('Notes'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } // Line of interventions - if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) - { + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) { print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" name="addinter" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; @@ -1356,13 +1295,11 @@ if ($action == 'create') $sql .= ' ORDER BY ft.rang ASC, ft.date ASC, ft.rowid'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num) - { + if ($num) { print '<br>'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; @@ -1404,8 +1341,7 @@ if ($action == 'create') print "</td>\n"; // Icon to edit and delete - if ($object->statut == 0 && $user->rights->ficheinter->creer) - { + if ($object->statut == 0 && $user->rights->ficheinter->creer) { print '<td class="center">'; print '<a class="editfielda marginrightonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=editline&amp;line_id='.$objp->rowid.'#'.$objp->rowid.'">'; print img_edit(); @@ -1414,16 +1350,13 @@ if ($action == 'create') print img_delete(); print '</a></td>'; print '<td class="center">'; - if ($num > 1) - { - if ($i > 0) - { + if ($num > 1) { + if ($i > 0) { print '<a class="marginleftonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=up&amp;line_id='.$objp->rowid.'">'; print img_up(); print '</a>'; } - if ($i < $num - 1) - { + if ($i < $num - 1) { print '<a class="marginleftonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=down&amp;line_id='.$objp->rowid.'">'; print img_down(); print '</a>'; @@ -1447,8 +1380,7 @@ if ($action == 'create') } // Line in update mode - if ($object->statut == 0 && $action == 'editline' && $user->rights->ficheinter->creer && GETPOST('line_id', 'int') == $objp->rowid) - { + if ($object->statut == 0 && $action == 'editline' && $user->rights->ficheinter->creer && GETPOST('line_id', 'int') == $objp->rowid) { print '<tr class="oddeven nohover">'; // No. @@ -1478,8 +1410,9 @@ if ($action == 'create') print '<td class="right">'; if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { $selectmode = 'select'; - if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) + if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) { $selectmode = 'text'; + } $form->select_duration('duration', $objp->duree, 0, $selectmode); } print '</td>'; @@ -1504,10 +1437,8 @@ if ($action == 'create') $db->free($resql); // Add new line - if ($object->statut == 0 && $user->rights->ficheinter->creer && $action <> 'editline' && empty($conf->global->FICHINTER_DISABLE_DETAILS)) - { - if (!$num) - { + if ($object->statut == 0 && $user->rights->ficheinter->creer && $action <> 'editline' && empty($conf->global->FICHINTER_DISABLE_DETAILS)) { + if (!$num) { print '<br>'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; @@ -1522,7 +1453,7 @@ if ($action == 'create') print $langs->trans('Description').'</td>'; print '<td class="center">'.$langs->trans('Date').'</td>'; print '<td class="right">'.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').'</td>'; - print '<td colspan="3">&nbsp;</td>'; + print '<td colspan="3">&nbsp;</td>'; print "</tr>\n"; } @@ -1580,16 +1511,20 @@ if ($action == 'create') print $lineadd->showOptionals($extrafields, 'edit', array('colspan'=>5)); - if (!$num) print '</table>'; + if (!$num) { + print '</table>'; + } } - if ($num) print '</table>'; + if ($num) { + print '</table>'; + } } else { dol_print_error($db); } print '</form>'."\n"; - } + } print dol_get_fiche_end(); @@ -1605,10 +1540,8 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { - if ($user->socid == 0) - { + if (empty($reshook)) { + if ($user->socid == 0) { if ($action != 'editdescription' && ($action != 'presend')) { // Validate if ($object->statut == Fichinter::STATUS_DRAFT && (count($object->lines) > 0 || !empty($conf->global->FICHINTER_DISABLE_DETAILS))) { @@ -1619,31 +1552,33 @@ if ($action == 'create') } // Modify - if ($object->statut == Fichinter::STATUS_VALIDATED && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->unvalidate))) - { + if ($object->statut == Fichinter::STATUS_VALIDATED && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->unvalidate))) { print '<div class="inline-block divButAction"><a class="butAction" href="card.php?id='.$object->id.'&action=modify">'; - if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) print $langs->trans("Modify"); - else print $langs->trans("SetToDraft"); + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) { + print $langs->trans("Modify"); + } else { + print $langs->trans("SetToDraft"); + } print '</a></div>'; } // Reopen - if ($object->statut >= Fichinter::STATUS_CLOSED) - { - if ($user->rights->ficheinter->creer) - { + if ($object->statut >= Fichinter::STATUS_CLOSED) { + if ($user->rights->ficheinter->creer) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=reopen">'.$langs->trans('Reopen').'</a></div>'; - } else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('Reopen').'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('Reopen').'</a></div>'; + } } // Send if (empty($user->socid)) { - if ($object->statut > Fichinter::STATUS_DRAFT) - { - if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->ficheinter->ficheinter_advance->send) - { + if ($object->statut > Fichinter::STATUS_DRAFT) { + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->ficheinter->ficheinter_advance->send) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>'; - } else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('SendMail').'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('SendMail').'</a></div>'; + } } } @@ -1655,30 +1590,30 @@ if ($action == 'create') } // Proposal - if ($conf->service->enabled && !empty($conf->propal->enabled) && $object->statut > Fichinter::STATUS_DRAFT) - { + if ($conf->service->enabled && !empty($conf->propal->enabled) && $object->statut > Fichinter::STATUS_DRAFT) { $langs->load("propal"); - if ($object->statut < Fichinter::STATUS_BILLED) - { - if ($user->rights->propal->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/comm/propal/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("AddProp").'</a></div>'; - else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("AddProp").'</a></div>'; + if ($object->statut < Fichinter::STATUS_BILLED) { + if ($user->rights->propal->creer) { + print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/comm/propal/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("AddProp").'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("AddProp").'</a></div>'; + } } } // Invoicing - if (!empty($conf->facture->enabled) && $object->statut > Fichinter::STATUS_DRAFT) - { + if (!empty($conf->facture->enabled) && $object->statut > Fichinter::STATUS_DRAFT) { $langs->load("bills"); - if ($object->statut < Fichinter::STATUS_BILLED) - { - if ($user->rights->facture->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("AddBill").'</a></div>'; - else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("AddBill").'</a></div>'; + if ($object->statut < Fichinter::STATUS_BILLED) { + if ($user->rights->facture->creer) { + print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("AddBill").'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("AddBill").'</a></div>'; + } } - if (!empty($conf->global->FICHINTER_CLASSIFY_BILLED)) // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 - { - if ($object->statut != Fichinter::STATUS_BILLED) - { + if (!empty($conf->global->FICHINTER_CLASSIFY_BILLED)) { // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 + if ($object->statut != Fichinter::STATUS_BILLED) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifybilled">'.$langs->trans("InterventionClassifyBilled").'</a></div>'; } else { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifyunbilled">'.$langs->trans("InterventionClassifyUnBilled").'</a></div>'; @@ -1687,8 +1622,7 @@ if ($action == 'create') } // Done - if (empty($conf->global->FICHINTER_CLASSIFY_BILLED) && $object->statut > Fichinter::STATUS_DRAFT && $object->statut < Fichinter::STATUS_CLOSED) - { + if (empty($conf->global->FICHINTER_CLASSIFY_BILLED) && $object->statut > Fichinter::STATUS_DRAFT && $object->statut < Fichinter::STATUS_CLOSED) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifydone">'.$langs->trans("InterventionClassifyDone").'</a></div>'; } @@ -1698,8 +1632,7 @@ if ($action == 'create') } // Delete - if (($object->statut == Fichinter::STATUS_DRAFT && $user->rights->ficheinter->creer) || $user->rights->ficheinter->supprimer) - { + if (($object->statut == Fichinter::STATUS_DRAFT && $user->rights->ficheinter->creer) || $user->rights->ficheinter->supprimer) { print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'"'; print '>'.$langs->trans('Delete').'</a></div>'; } @@ -1709,8 +1642,7 @@ if ($action == 'create') print '</div>'; - if ($action != 'presend') - { + if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; /* diff --git a/htdocs/fichinter/class/api_interventions.class.php b/htdocs/fichinter/class/api_interventions.class.php index 7046a61e2d5..a5ba127a54d 100644 --- a/htdocs/fichinter/class/api_interventions.class.php +++ b/htdocs/fichinter/class/api_interventions.class.php @@ -32,7 +32,7 @@ class Interventions extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'socid', 'fk_project', 'description', @@ -41,7 +41,7 @@ class Interventions extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDSLINE = array( + public static $FIELDSLINE = array( 'description', 'date', 'duree', @@ -117,27 +117,37 @@ class Interventions extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= ' WHERE t.entity IN ('.getEntity('intervention').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -146,8 +156,7 @@ class Interventions extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -158,13 +167,11 @@ class Interventions extends DolibarrApi dol_syslog("API Rest request"); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $fichinter_static = new Fichinter($this->db); if ($fichinter_static->fetch($obj->rowid)) { @@ -216,28 +223,28 @@ class Interventions extends DolibarrApi * @return int */ /* TODO - public function getLines($id) - { - if(! DolibarrApiAccess::$user->rights->ficheinter->lire) { - throw new RestException(401); - } + public function getLines($id) + { + if(! DolibarrApiAccess::$user->rights->ficheinter->lire) { + throw new RestException(401); + } - $result = $this->fichinter->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Intervention not found'); - } + $result = $this->fichinter->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Intervention not found'); + } - if( ! DolibarrApi::_checkAccessToResource('fichinter',$this->fichinter->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->fichinter->getLinesArray(); - $result = array(); - foreach ($this->fichinter->lines as $line) { - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } - */ + if( ! DolibarrApi::_checkAccessToResource('fichinter',$this->fichinter->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->fichinter->getLinesArray(); + $result = array(); + foreach ($this->fichinter->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + */ /** * Add a line to given intervention @@ -270,11 +277,11 @@ class Interventions extends DolibarrApi } $updateRes = $this->fichinter->addLine( - DolibarrApiAccess::$user, - $id, - $this->fichinter->description, - $this->fichinter->date, - $this->fichinter->duree + DolibarrApiAccess::$user, + $id, + $this->fichinter->description, + $this->fichinter->date, + $this->fichinter->duree ); if ($updateRes > 0) { @@ -369,8 +376,7 @@ class Interventions extends DolibarrApi */ public function closeFichinter($id) { - if (!DolibarrApiAccess::$user->rights->ficheinter->creer) - { + if (!DolibarrApiAccess::$user->rights->ficheinter->creer) { throw new RestException(401, "Insuffisant rights"); } $result = $this->fichinter->fetch($id); @@ -408,8 +414,9 @@ class Interventions extends DolibarrApi { $fichinter = array(); foreach (Interventions::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $fichinter[$field] = $data[$field]; } return $fichinter; @@ -447,8 +454,9 @@ class Interventions extends DolibarrApi { $fichinter = array(); foreach (Interventions::$FIELDSLINE as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $fichinter[$field] = $data[$field]; } return $fichinter; diff --git a/htdocs/fichinter/class/fichinter.class.php b/htdocs/fichinter/class/fichinter.class.php index 39ac094132a..f5602bc5abb 100644 --- a/htdocs/fichinter/class/fichinter.class.php +++ b/htdocs/fichinter/class/fichinter.class.php @@ -204,8 +204,7 @@ class Fichinter extends CommonObject $sql = "SELECT count(fi.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as fi"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON fi.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -213,10 +212,8 @@ class Fichinter extends CommonObject $sql .= " ".$clause." fi.entity IN (".getEntity('intervention').")"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["interventions"] = $obj->nb; } $this->db->free($resql); @@ -244,21 +241,20 @@ class Fichinter extends CommonObject dol_syslog(get_class($this)."::create ref=".$this->ref); // Check parameters - if (!empty($this->ref)) // We check that ref is not already used - { + if (!empty($this->ref)) { // We check that ref is not already used $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used - if ($result > 0) - { + if ($result > 0) { $this->error = 'ErrorRefAlreadyExists'; dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); $this->db->rollback(); return -1; } } - if (!is_numeric($this->duration)) $this->duration = 0; + if (!is_numeric($this->duration)) { + $this->duration = 0; + } - if ($this->socid <= 0) - { + if ($this->socid <= 0) { $this->error = 'ErrorBadParameterForFunc'; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -1; @@ -304,42 +300,42 @@ class Fichinter extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."fichinter"); - if ($this->id) - { + if ($this->id) { $this->ref = '(PROV'.$this->id.')'; - $sql = 'UPDATE '.MAIN_DB_PREFIX."fichinter SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX."fichinter SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } // Add linked object - if (!$error && $this->origin && $this->origin_id) - { + if (!$error && $this->origin && $this->origin_id) { $ret = $this->add_object_linked(); - if (!$ret) dol_print_error($this->db); + if (!$ret) { + dol_print_error($this->db); + } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('FICHINTER_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -370,14 +366,14 @@ class Fichinter extends CommonObject { global $conf; - if (!is_numeric($this->duration)) { - $this->duration = 0; - } - if (!dol_strlen($this->fk_project)) { - $this->fk_project = 0; - } + if (!is_numeric($this->duration)) { + $this->duration = 0; + } + if (!dol_strlen($this->fk_project)) { + $this->fk_project = 0; + } - $error = 0; + $error = 0; $this->db->begin(); @@ -391,22 +387,20 @@ class Fichinter extends CommonObject $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); - if ($this->db->query($sql)) - { - if (!$error) - { + if ($this->db->query($sql)) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('FICHINTER_MODIFY', $user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } + if ($result < 0) { + $error++; $this->db->rollback(); return -1; + } // End call triggers } @@ -437,14 +431,14 @@ class Fichinter extends CommonObject if ($ref) { $sql .= " WHERE f.entity IN (".getEntity('intervention').")"; $sql .= " AND f.ref='".$this->db->escape($ref)."'"; - } else $sql .= " WHERE f.rowid=".$rowid; + } else { + $sql .= " WHERE f.rowid=".$rowid; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -470,7 +464,9 @@ class Fichinter extends CommonObject $this->extraparams = (array) json_decode($obj->extraparams, true); - if ($this->statut == 0) $this->brouillon = 1; + if ($this->statut == 0) { + $this->brouillon = 1; + } // Retrieve extrafields $this->fetch_optionals(); @@ -479,8 +475,7 @@ class Fichinter extends CommonObject * Lines */ $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { return -3; } $this->db->free($resql); @@ -505,8 +500,7 @@ class Fichinter extends CommonObject $error = 0; // Protection - if ($this->statut <= self::STATUS_DRAFT) - { + if ($this->statut <= self::STATUS_DRAFT) { return 0; } @@ -519,8 +513,7 @@ class Fichinter extends CommonObject $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { if (!$error) { $this->oldcopy = clone $this; } @@ -528,7 +521,9 @@ class Fichinter extends CommonObject if (!$error) { // Call trigger $result = $this->call_trigger('FICHINTER_UNVALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } if (!$error) { @@ -560,15 +555,13 @@ class Fichinter extends CommonObject $error = 0; - if ($this->statut != 1) - { + if ($this->statut != 1) { $this->db->begin(); $now = dol_now(); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($this->thirdparty); } else { $num = $this->ref; @@ -586,51 +579,48 @@ class Fichinter extends CommonObject dol_syslog(get_class($this)."::setValid", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('FICHINTER_VALIDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'ficheinter/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'ficheinter/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->ficheinter->dir_output.'/'.$oldref; $dirdest = $conf->ficheinter->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::setValid rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->ficheinter->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -643,8 +633,7 @@ class Fichinter extends CommonObject } // Set new ref and define current statut - if (!$error) - { + if (!$error) { $this->ref = $num; $this->statut = 1; $this->brouillon = 0; @@ -740,8 +729,7 @@ class Fichinter extends CommonObject { // phpcs:enable // Init/load array of translation of status - if (empty($this->statuts) || empty($this->statuts_short) || empty($this->statuts_logo)) - { + if (empty($this->statuts) || empty($this->statuts_short) || empty($this->statuts_logo)) { global $langs; $langs->load("fichinter"); @@ -785,19 +773,20 @@ class Fichinter extends CommonObject $url = DOL_URL_ROOT.'/fichinter/card.php?id='.$this->id; - if ($option !== 'nolink') - { + 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'; + } + } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowIntervention"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -817,16 +806,23 @@ class Fichinter extends CommonObject $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; global $action; $hookmanager->initHooks(array('interventiondao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -844,8 +840,7 @@ class Fichinter extends CommonObject global $conf, $db, $langs; $langs->load("interventions"); - if (!empty($conf->global->FICHEINTER_ADDON)) - { + if (!empty($conf->global->FICHEINTER_ADDON)) { $mybool = false; $file = "mod_".$conf->global->FICHEINTER_ADDON.".php"; @@ -870,8 +865,7 @@ class Fichinter extends CommonObject $numref = ""; $numref = $obj->getNextValue($soc, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { dol_print_error($db, "Fichinter::getNextNumRef ".$obj->error); @@ -902,13 +896,11 @@ class Fichinter extends CommonObject $sql .= " f.fk_user_modif as fk_user_modification,"; $sql .= " f.fk_user_valid"; $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as f"; - $sql .= " WHERE f.rowid = ".$id; + $sql .= " WHERE f.rowid = ".((int) $id); $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; @@ -921,14 +913,12 @@ class Fichinter extends CommonObject $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_modification) - { + if ($obj->fk_user_modification) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modification); $this->user_modification = $muser; @@ -956,27 +946,27 @@ class Fichinter extends CommonObject $this->db->begin(); - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('FICHINTER_DELETE', $user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } + if ($result < 0) { + $error++; $this->db->rollback(); return -1; + } // End call triggers } // Delete linked object - if (!$error) - { + if (!$error) { $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } // Delete linked contacts - if (!$error) - { + if (!$error) { $res = $this->delete_linked_contact(); - if ($res < 0) - { + if ($res < 0) { $this->error = 'ErrorFailToDeleteLinkedContact'; $error++; } @@ -988,62 +978,61 @@ class Fichinter extends CommonObject $sql = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_fichinter = ".$this->id.")"; $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet"; $sql .= " WHERE fk_fichinter = ".$this->id; $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } } - if (!$error) - { + if (!$error) { // Remove extrafields $res = $this->deleteExtraFields(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { // Delete object $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinter"; $sql .= " WHERE rowid = ".$this->id; dol_syslog("Fichinter::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } } - if (!$error) - { + if (!$error) { // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive $this->deleteEcmFiles(); // Remove directory with files $fichinterref = dol_sanitizeFileName($this->ref); - if ($conf->ficheinter->dir_output) - { + if ($conf->ficheinter->dir_output) { $dir = $conf->ficheinter->dir_output."/".$fichinterref; $file = $conf->ficheinter->dir_output."/".$fichinterref."/".$fichinterref.".pdf"; - if (file_exists($file)) - { + if (file_exists($file)) { dol_delete_preview($this); - if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers - { + if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers $langs->load("errors"); $this->error = $langs->trans("ErrorFailToDeleteFile", $file); return 0; } } - if (file_exists($dir)) - { - if (!dol_delete_dir_recursive($dir)) - { + if (file_exists($dir)) { + if (!dol_delete_dir_recursive($dir)) { $langs->load("errors"); $this->error = $langs->trans("ErrorFailToDeleteDir", $dir); return 0; @@ -1052,8 +1041,7 @@ class Fichinter extends CommonObject } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1075,15 +1063,13 @@ class Fichinter extends CommonObject // phpcs:enable global $conf; - if ($user->rights->ficheinter->creer) - { + if ($user->rights->ficheinter->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter "; $sql .= " SET datei = '".$this->db->idate($date_delivery)."'"; $sql .= " WHERE rowid = ".$this->id; $sql .= " AND fk_statut = 0"; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->date_delivery = $date_delivery; return 1; } else { @@ -1107,15 +1093,13 @@ class Fichinter extends CommonObject // phpcs:enable global $conf; - if ($user->rights->ficheinter->creer) - { + if ($user->rights->ficheinter->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter "; $sql .= " SET description = '".$this->db->escape($description)."',"; $sql .= " fk_user_modif = ".$user->id; $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->description = $description; return 1; } else { @@ -1140,14 +1124,12 @@ class Fichinter extends CommonObject // phpcs:enable global $conf; - if ($user->rights->ficheinter->creer) - { + if ($user->rights->ficheinter->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter "; $sql .= " SET fk_contrat = ".((int) $contractid); $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->fk_contrat = $contractid; return 1; } else { @@ -1176,19 +1158,18 @@ class Fichinter extends CommonObject $this->db->begin(); // get extrafields so they will be clone - foreach ($this->lines as $line) + foreach ($this->lines as $line) { $line->fetch_optionals(); + } // Load source object $objFrom = clone $this; // Change socid if needed - if (!empty($socid) && $socid != $this->socid) - { + if (!empty($socid) && $socid != $this->socid) { $objsoc = new Societe($this->db); - if ($objsoc->fetch($socid) > 0) - { + if ($objsoc->fetch($socid) > 0) { $this->socid = $objsoc->id; //$this->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); //$this->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); @@ -1213,31 +1194,31 @@ class Fichinter extends CommonObject // Create clone $this->context['createfromclone'] = 'createfromclone'; $result = $this->create($user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Add lines because it is not included into create function - foreach ($this->lines as $line) - { + foreach ($this->lines as $line) { $this->addline($user, $this->id, $line->desc, $line->datei, $line->duration); } // Hook of thirdparty module - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('objFrom'=>$objFrom); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } } } unset($this->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -1262,8 +1243,7 @@ class Fichinter extends CommonObject { dol_syslog(get_class($this)."::addline $fichinterid, $desc, $date_intervention, $duration"); - if ($this->statut == 0) - { + if ($this->statut == 0) { $this->db->begin(); // Insertion ligne @@ -1280,8 +1260,7 @@ class Fichinter extends CommonObject $result = $line->insert($user); - if ($result >= 0) - { + if ($result >= 0) { $this->db->commit(); return 1; } else { @@ -1317,8 +1296,7 @@ class Fichinter extends CommonObject $this->duration = 0; $nbp = 25; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new FichinterLigne($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; $line->datei = ($now - 3600 * (1 + $xnbp)); @@ -1348,12 +1326,10 @@ class Fichinter extends CommonObject dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($resql); $line = new FichinterLigne($this->db); @@ -1466,8 +1442,7 @@ class FichinterLigne extends CommonObjectLine dol_syslog("FichinterLigne::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $objp = $this->db->fetch_object($result); $this->rowid = $objp->rowid; $this->id = $objp->rowid; @@ -1503,14 +1478,12 @@ class FichinterLigne extends CommonObjectLine $this->db->begin(); $rangToUse = $this->rang; - if ($rangToUse == -1) - { + if ($rangToUse == -1) { // Recupere rang max de la ligne d'intervention dans $rangmax $sql = 'SELECT max(rang) as max FROM '.MAIN_DB_PREFIX.'fichinterdet'; $sql .= ' WHERE fk_fichinter ='.$this->fk_fichinter; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $rangToUse = $obj->max + 1; } else { @@ -1532,16 +1505,13 @@ class FichinterLigne extends CommonObjectLine dol_syslog("FichinterLigne::insert", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'fichinterdet'); $this->rowid = $this->id; - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } @@ -1549,15 +1519,15 @@ class FichinterLigne extends CommonObjectLine $result = $this->update_total(); - if ($result > 0) - { + if ($result > 0) { $this->rang = $rangToUse; - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINEFICHINTER_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } @@ -1602,31 +1572,27 @@ class FichinterLigne extends CommonObjectLine dol_syslog("FichinterLigne::update", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$error) - { + if ($resql) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } $result = $this->update_total(); - if ($result > 0) - { - if (!$notrigger) - { + if ($result > 0) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINEFICHINTER_UPDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } - if (!$error) - { + if (!$error) { $this->db->commit(); return $result; } else { @@ -1660,11 +1626,12 @@ class FichinterLigne extends CommonObjectLine dol_syslog("FichinterLigne::update_total", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $total_duration = 0; - if (!empty($obj->total_duration)) $total_duration = $obj->total_duration; + if (!empty($obj->total_duration)) { + $total_duration = $obj->total_duration; + } $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter"; $sql .= " SET duree = ".$total_duration; @@ -1674,8 +1641,7 @@ class FichinterLigne extends CommonObjectLine dol_syslog("FichinterLigne::update_total", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { @@ -1703,8 +1669,7 @@ class FichinterLigne extends CommonObjectLine $error = 0; - if ($this->statut == 0) - { + if ($this->statut == 0) { dol_syslog(get_class($this)."::deleteline lineid=".$this->id); $this->db->begin(); @@ -1718,16 +1683,15 @@ class FichinterLigne extends CommonObjectLine $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $result = $this->update_total(); - if ($result > 0) - { - if (!$notrigger) - { + if ($result > 0) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINEFICHINTER_DELETE', $user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } + if ($result < 0) { + $error++; $this->db->rollback(); return -1; + } // End call triggers } diff --git a/htdocs/fichinter/class/fichinterrec.class.php b/htdocs/fichinter/class/fichinterrec.class.php index 418e1232bb8..8ed842a70c9 100644 --- a/htdocs/fichinter/class/fichinterrec.class.php +++ b/htdocs/fichinter/class/fichinterrec.class.php @@ -214,8 +214,8 @@ class FichinterRec extends Fichinter $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); /* - * Lines - */ + * Lines + */ $num = count($fichintsrc->lines); for ($i = 0; $i < $num; $i++) { //var_dump($fichintsrc->lines[$i]); @@ -239,13 +239,14 @@ class FichinterRec extends Fichinter $fichintsrc->lines[$i]->fk_unit ); - if ($result_insert < 0) + if ($result_insert < 0) { $error++; + } } - if ($error) + if ($error) { $this->db->rollback(); - else { + } else { $this->db->commit(); return $this->id; } @@ -277,8 +278,11 @@ class FichinterRec extends Fichinter $sql .= ', f.frequency, f.unit_frequency, f.date_when, f.date_last_gen, f.nb_gen_done, f.nb_gen_max, f.auto_validate'; $sql .= ', f.note_private, f.note_public, f.fk_user_author'; $sql .= ' FROM '.MAIN_DB_PREFIX.'fichinter_rec as f'; - if ($rowid > 0) $sql .= ' WHERE f.rowid='.$rowid; - elseif ($ref) $sql .= " WHERE f.titre='".$this->db->escape($ref)."'"; + if ($rowid > 0) { + $sql .= ' WHERE f.rowid='.$rowid; + } elseif ($ref) { + $sql .= " WHERE f.titre='".$this->db->escape($ref)."'"; + } dol_syslog(get_class($this)."::fetch rowid=".$rowid, LOG_DEBUG); @@ -421,7 +425,9 @@ class FichinterRec extends Fichinter */ public function delete($rowid = 0, $notrigger = 0, $idwarehouse = -1) { - if (empty($rowid)) $rowid = $this->id; + if (empty($rowid)) { + $rowid = $this->id; + } dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG); @@ -481,14 +487,20 @@ class FichinterRec extends Fichinter include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } if ($this->brouillon) { // Clean parameters $remise_percent = price2num($remise_percent); $qty = price2num($qty); - if (!$qty) $qty = 1; - if (!$info_bits) $info_bits = 0; + if (!$qty) { + $qty = 1; + } + if (!$info_bits) { + $info_bits = 0; + } $pu_ht = price2num($pu_ht); $pu_ttc = price2num($pu_ttc); if (!preg_match('/\((.*)\)/', $txtva)) { @@ -623,7 +635,9 @@ class FichinterRec extends Fichinter $url = DOL_URL_ROOT.'/fichinter/card-rec.php?id='.$this->id; - if ($short) return $url; + if ($short) { + return $url; + } $picto = 'intervention'; @@ -709,7 +723,9 @@ class FichinterRec extends Fichinter dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG); if ($this->db->query($sql)) { $this->frequency = $frequency; - if (!empty($unit)) $this->unit_frequency = $unit; + if (!empty($unit)) { + $this->unit_frequency = $unit; + } return 1; } else { dol_print_error($this->db); @@ -732,13 +748,17 @@ class FichinterRec extends Fichinter } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null"); - if ($increment_nb_gen_done > 0) $sql .= ', nb_gen_done = nb_gen_done + 1'; + if ($increment_nb_gen_done > 0) { + $sql .= ', nb_gen_done = nb_gen_done + 1'; + } $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG); if ($this->db->query($sql)) { $this->date_when = $date; - if ($increment_nb_gen_done > 0) $this->nb_gen_done++; + if ($increment_nb_gen_done > 0) { + $this->nb_gen_done++; + } return 1; } else { dol_print_error($this->db); @@ -759,7 +779,9 @@ class FichinterRec extends Fichinter return -1; } - if (empty($nb)) $nb = 0; + if (empty($nb)) { + $nb = 0; + } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET nb_gen_max = '.$nb; @@ -818,8 +840,9 @@ class FichinterRec extends Fichinter $sql .= ' SET nb_gen_done = nb_gen_done + 1'; $sql .= ' , date_last_gen = now()'; // si on et arrivé à la fin des génération - if ($this->nb_gen_max == $this->nb_gen_done + 1) + if ($this->nb_gen_max == $this->nb_gen_done + 1) { $sql .= ' , statut = 1'; + } $sql .= ' WHERE rowid = '.$this->id; diff --git a/htdocs/fichinter/class/fichinterstats.class.php b/htdocs/fichinter/class/fichinterstats.class.php index 5df841bf6f2..a0d22cf1e2a 100644 --- a/htdocs/fichinter/class/fichinterstats.class.php +++ b/htdocs/fichinter/class/fichinterstats.class.php @@ -64,8 +64,7 @@ class FichinterStats extends Stats $this->userid = $userid; $this->cachefilesuffix = $mode; - if ($mode == 'customer') - { + if ($mode == 'customer') { $object = new Fichinter($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as c"; $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl"; @@ -73,14 +72,17 @@ class FichinterStats extends Stats $this->field_line = '0'; //$this->where.= " AND c.fk_statut > 0"; // Not draft and not cancelled } - if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + if (!$user->rights->societe->client->voir && !$this->socid) { + $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } $this->where .= ($this->where ? ' AND ' : '')."c.entity IN (".getEntity('fichinter').')'; - if ($this->socid) - { + if ($this->socid) { $this->where .= " AND c.fk_soc = ".$this->socid; } - if ($this->userid > 0) $this->where .= ' AND c.fk_user_author = '.$this->userid; + if ($this->userid > 0) { + $this->where .= ' AND c.fk_user_author = '.$this->userid; + } } /** @@ -96,7 +98,9 @@ class FichinterStats extends Stats $sql = "SELECT date_format(c.date_valid,'%m') as dm, COUNT(*) as nb"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; $sql .= " GROUP BY dm"; @@ -118,7 +122,9 @@ class FichinterStats extends Stats $sql = "SELECT date_format(c.date_valid,'%Y') as dm, COUNT(*) as nb, 0"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE ".$this->where; $sql .= " GROUP BY dm"; $sql .= $this->db->order('dm', 'DESC'); @@ -139,7 +145,9 @@ class FichinterStats extends Stats $sql = "SELECT date_format(c.date_valid,'%m') as dm, 0"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; $sql .= " GROUP BY dm"; @@ -161,7 +169,9 @@ class FichinterStats extends Stats $sql = "SELECT date_format(c.date_valid,'%m') as dm, 0"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; $sql .= " GROUP BY dm"; @@ -181,7 +191,9 @@ class FichinterStats extends Stats $sql = "SELECT date_format(c.date_valid,'%Y') as year, COUNT(*) as nb, 0 as total, 0 as avg"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE ".$this->where; $sql .= " GROUP BY year"; $sql .= $this->db->order('year', 'DESC'); diff --git a/htdocs/fichinter/contact.php b/htdocs/fichinter/contact.php index bace3d10231..7957479e611 100644 --- a/htdocs/fichinter/contact.php +++ b/htdocs/fichinter/contact.php @@ -39,13 +39,14 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); $object = new Fichinter($db); $result = $object->fetch($id, $ref); -if (!$result) -{ +if (!$result) { print 'Record not found'; exit; } @@ -54,17 +55,14 @@ if (!$result) * Adding a new contact */ -if ($action == 'addcontact' && $user->rights->ficheinter->creer) -{ - if ($result > 0 && $id > 0) - { +if ($action == 'addcontact' && $user->rights->ficheinter->creer) { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -77,21 +75,14 @@ if ($action == 'addcontact' && $user->rights->ficheinter->creer) setEventMessages($mesg, null, 'errors'); } -} - -// Toggle the status of a contact -elseif ($action == 'swapstatut' && $user->rights->ficheinter->creer) -{ +} elseif ($action == 'swapstatut' && $user->rights->ficheinter->creer) { + // Toggle the status of a contact $result = $object->swapContactStatus(GETPOST('ligne', 'int')); -} - -// Deletes a contact -elseif ($action == 'deletecontact' && $user->rights->ficheinter->creer) -{ +} elseif ($action == 'deletecontact' && $user->rights->ficheinter->creer) { + // Deletes a contact $result = $object->delete_contact(GETPOST('lineid', 'int')); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -114,8 +105,7 @@ llxHeader('', $langs->trans("Intervention")); // Mode vue et edition -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = fichinter_prepare_head($object); @@ -133,12 +123,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->ficheinter->creer) - { + if ($user->rights->ficheinter->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; @@ -174,15 +162,20 @@ if ($id > 0 || !empty($ref)) print '<br>'; - if (!empty($conf->global->FICHINTER_HIDE_ADD_CONTACT_USER)) $hideaddcontactforuser = 1; - if (!empty($conf->global->FICHINTER_HIDE_ADD_CONTACT_THIPARTY)) $hideaddcontactforthirdparty = 1; + if (!empty($conf->global->FICHINTER_HIDE_ADD_CONTACT_USER)) { + $hideaddcontactforuser = 1; + } + if (!empty($conf->global->FICHINTER_HIDE_ADD_CONTACT_THIPARTY)) { + $hideaddcontactforthirdparty = 1; + } // Contacts lines (modules that overwrite templates must declare this into descriptor) $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); - foreach ($dirtpls as $reldir) - { + foreach ($dirtpls as $reldir) { $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); - if ($res) break; + if ($res) { + break; + } } } diff --git a/htdocs/fichinter/document.php b/htdocs/fichinter/document.php index 1b9326468f4..ba1f22c122b 100644 --- a/htdocs/fichinter/document.php +++ b/htdocs/fichinter/document.php @@ -47,7 +47,9 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); @@ -56,12 +58,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) { $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"; +} $object = new Fichinter($db); @@ -75,7 +83,7 @@ $modulepart = 'fichinter'; * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -86,8 +94,7 @@ $form = new Form($db); llxHeader('', $langs->trans("Intervention")); -if ($object->id) -{ +if ($object->id) { $object->fetch_thirdparty(); $head = fichinter_prepare_head($object); @@ -98,8 +105,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -115,12 +121,10 @@ if ($object->id) // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/fichinter/index.php b/htdocs/fichinter/index.php index 3ea69f8d185..863463e8d0e 100644 --- a/htdocs/fichinter/index.php +++ b/htdocs/fichinter/index.php @@ -30,7 +30,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; -if (!$user->rights->ficheinter->lire) accessforbidden(); +if (!$user->rights->ficheinter->lire) { + accessforbidden(); +} $hookmanager = new HookManager($db); @@ -42,8 +44,7 @@ $langs->load("interventions"); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -66,8 +67,7 @@ print load_fiche_titre($langs->trans("InterventionsArea"), '', 'intervention'); print '<div class="fichecenter"><div class="fichethirdleft">'; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo // Search ficheinter $var = false; print '<form method="post" action="'.DOL_URL_ROOT.'/fichinter/list.php">'; @@ -88,15 +88,20 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useles $sql = "SELECT count(f.rowid), f.fk_statut"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."fichinter as f"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE f.entity IN (".getEntity('intervention').")"; $sql .= " AND f.fk_soc = s.rowid"; -if ($user->socid) $sql .= ' AND f.fk_soc = '.$user->socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($user->socid) { + $sql .= ' AND f.fk_soc = '.$user->socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " GROUP BY f.fk_statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -106,15 +111,15 @@ if ($resql) $vals = array(); $bool = false; // -1=Canceled, 0=Draft, 1=Validated, 2=Accepted/On process, 3=Closed (Sent/Received, billed or not) - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); - if ($row) - { + if ($row) { //if ($row[1]!=-1 && ($row[1]!=3 || $row[2]!=1)) { $bool = (!empty($row[2]) ?true:false); - if (!isset($vals[$row[1].$bool])) $vals[$row[1].$bool] = 0; + if (!isset($vals[$row[1].$bool])) { + $vals[$row[1].$bool] = 0; + } $vals[$row[1].$bool] += $row[0]; $totalinprocess += $row[0]; } @@ -131,19 +136,28 @@ if ($resql) print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("Interventions").'</th></tr>'."\n"; $listofstatus = array(0, 1, 3); $bool = false; - foreach ($listofstatus as $status) - { + foreach ($listofstatus as $status) { $dataseries[] = array($fichinterstatic->LibStatut($status, $bool, 1), (isset($vals[$status.$bool]) ? (int) $vals[$status.$bool] : 0)); - if ($status == 3 && !$bool) $bool = true; - else $bool = false; + if ($status == 3 && !$bool) { + $bool = true; + } else { + $bool = false; + } - if ($status == Fichinter::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; - if ($status == Fichinter::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus1; - if ($status == Fichinter::STATUS_BILLED) $colorseries[$status] = $badgeStatus4; - if ($status == Fichinter::STATUS_CLOSED) $colorseries[$status] = $badgeStatus6; + if ($status == Fichinter::STATUS_DRAFT) { + $colorseries[$status] = '-'.$badgeStatus0; + } + if ($status == Fichinter::STATUS_VALIDATED) { + $colorseries[$status] = $badgeStatus1; + } + if ($status == Fichinter::STATUS_BILLED) { + $colorseries[$status] = $badgeStatus4; + } + if ($status == Fichinter::STATUS_CLOSED) { + $colorseries[$status] = $badgeStatus6; + } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<tr class="impair"><td class="center" colspan="2">'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -160,10 +174,8 @@ if ($resql) print '</td></tr>'; } $bool = false; - foreach ($listofstatus as $status) - { - if (!$conf->use_javascript_ajax) - { + foreach ($listofstatus as $status) { + if (!$conf->use_javascript_ajax) { print '<tr class="oddeven">'; print '<td>'.$fichinterstatic->LibStatut($status, $bool, 0).'</td>'; print '<td class="right"><a href="list.php?search_status='.$status.'">'.(isset($vals[$status.$bool]) ? $vals[$status.$bool] : 0).' '; @@ -171,8 +183,11 @@ if ($resql) print '</a>'; print '</td>'; print "</tr>\n"; - if ($status == 3 && !$bool) $bool = true; - else $bool = false; + if ($status == 3 && !$bool) { + $bool = true; + } else { + $bool = false; + } } } //if ($totalinprocess != $total) @@ -187,32 +202,34 @@ if ($resql) /* * Draft orders */ -if (!empty($conf->ficheinter->enabled)) -{ +if (!empty($conf->ficheinter->enabled)) { $sql = "SELECT f.rowid, f.ref, s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as f"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.entity IN (".getEntity('intervention').")"; $sql .= " AND f.fk_soc = s.rowid"; $sql .= " AND f.fk_statut = 0"; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="2">'.$langs->trans("DraftFichinter").'</th></tr>'; $langs->load("fichinter"); $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; print '<td class="nowrap">'; @@ -239,29 +256,32 @@ $sql = "SELECT f.rowid, f.ref, f.fk_statut, f.date_valid as datec, f.tms as date $sql .= " s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as f,"; $sql .= " ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE f.entity IN (".getEntity('intervention').")"; $sql .= " AND f.fk_soc = s.rowid"; //$sql.= " AND c.fk_statut > 2"; -if ($socid) $sql .= " AND f.fk_soc = ".$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " ORDER BY f.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="4">'.$langs->trans("LastModifiedInterventions", $max).'</th></tr>'; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -296,29 +316,35 @@ if ($resql) } } print "</table></div><br>"; -} else dol_print_error($db); +} else { + dol_print_error($db); +} /* * interventions to process */ -if (!empty($conf->ficheinter->enabled)) -{ +if (!empty($conf->ficheinter->enabled)) { $sql = "SELECT f.rowid, f.ref, f.fk_statut, s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as f"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.entity IN (".getEntity('intervention').")"; $sql .= " AND f.fk_soc = s.rowid"; $sql .= " AND f.fk_statut = 1"; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= " ORDER BY f.rowid DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '<div class="div-table-responsive-no-min">'; @@ -326,11 +352,9 @@ if (!empty($conf->ficheinter->enabled)) print '<tr class="liste_titre">'; print '<th colspan="3">'.$langs->trans("FichinterToProcess").' <a href="'.DOL_URL_ROOT.'/fichinter/list.php?search_status=1"><span class="badge">'.$num.'</span></a></th></tr>'; - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; print '<td class="nowrap" width="20%">'; @@ -366,7 +390,9 @@ if (!empty($conf->ficheinter->enabled)) } print "</table></div><br>"; - } else dol_print_error($db); + } else { + dol_print_error($db); + } } print '</div></div></div>'; diff --git a/htdocs/fichinter/info.php b/htdocs/fichinter/info.php index a53c69b77bd..39ac695f84e 100644 --- a/htdocs/fichinter/info.php +++ b/htdocs/fichinter/info.php @@ -40,13 +40,14 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); $object = new Fichinter($db); -if (!$object->fetch($id, $ref) > 0) -{ +if (!$object->fetch($id, $ref) > 0) { dol_print_error($db); exit; } @@ -77,15 +78,14 @@ $morehtmlref = '<div class="refidno">'; // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->commande->creer) - { - if ($action != 'classify') + if ($user->rights->commande->creer) { + if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php index d054f5e5bcc..8f0ae8e626f 100644 --- a/htdocs/fichinter/list.php +++ b/htdocs/fichinter/list.php @@ -32,13 +32,21 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -if (!empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; -if (!empty($conf->contrat->enabled)) require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; +if (!empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +} +if (!empty($conf->contrat->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('companies', 'bills', 'interventions')); -if (!empty($conf->projet->enabled)) $langs->load("projects"); -if (!empty($conf->contrat->enabled)) $langs->load("contracts"); +if (!empty($conf->projet->enabled)) { + $langs->load("projects"); +} +if (!empty($conf->contrat->enabled)) { + $langs->load("contracts"); +} $action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); @@ -59,7 +67,9 @@ $socid = GETPOST('socid', 'int'); // Security check $id = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); $diroutputmassaction = $conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id; @@ -68,14 +78,17 @@ $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 (!$sortorder) $sortorder = "DESC"; -if (!$sortfield) -{ - $sortfield = "f.ref"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "f.ref"; } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -97,8 +110,12 @@ $fieldstosearchall = array( 'f.note_public'=>'NotePublic', 'fd.description'=>'DescriptionOfLine', ); -if (empty($user->socid)) $fieldstosearchall["f.note_private"] = "NotePrivate"; -if (!empty($conf->global->FICHINTER_DISABLE_DETAILS)) unset($fieldstosearchall['fd.description']); +if (empty($user->socid)) { + $fieldstosearchall["f.note_private"] = "NotePrivate"; +} +if (!empty($conf->global->FICHINTER_DISABLE_DETAILS)) { + unset($fieldstosearchall['fd.description']); +} // Definition of fields for list $arrayfields = array( @@ -127,21 +144,25 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * 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)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_ref = ""; $search_company = ""; $search_projet_ref = ""; @@ -187,10 +208,8 @@ $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields $atleastonefieldinlines = 0; -foreach ($arrayfields as $tmpkey => $tmpval) -{ - if (preg_match('/^fd\./', $tmpkey) && !empty($arrayfields[$tmpkey]['checked'])) - { +foreach ($arrayfields as $tmpkey => $tmpval) { + if (preg_match('/^fd\./', $tmpkey) && !empty($arrayfields[$tmpkey]['checked'])) { $atleastonefieldinlines++; break; } @@ -198,7 +217,9 @@ foreach ($arrayfields as $tmpkey => $tmpval) $sql = "SELECT"; $sql .= " f.ref, f.rowid, f.fk_statut as status, f.description, f.datec as date_creation, f.tms as date_update, f.note_public, f.note_private,"; -if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) $sql .= " fd.rowid as lineid, fd.description as descriptiondetail, fd.date as dp, fd.duree,"; +if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) { + $sql .= " fd.rowid as lineid, fd.description as descriptiondetail, fd.date as dp, fd.duree,"; +} $sql .= " s.nom as name, s.rowid as socid, s.client, s.fournisseur, s.email, s.status as thirdpartystatus"; if (!empty($conf->projet->enabled)) { $sql .= ", pr.rowid as projet_id, pr.ref as projet_ref, pr.title as projet_title"; @@ -208,7 +229,9 @@ if (!empty($conf->contrat->enabled)) { } // 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 : ''); + 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(); @@ -221,9 +244,15 @@ if (!empty($conf->projet->enabled)) { if (!empty($conf->contrat->enabled)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contrat as c on f.fk_contrat = c.rowid"; } -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (f.rowid = ef.fk_object)"; -if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."fichinterdet as fd ON fd.fk_fichinter = f.rowid"; -if (!$user->rights->societe->client->voir && empty($socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (f.rowid = ef.fk_object)"; +} +if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."fichinterdet as fd ON fd.fk_fichinter = f.rowid"; +} +if (!$user->rights->societe->client->voir && empty($socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= ", ".MAIN_DB_PREFIX."societe as s"; $sql .= " WHERE f.entity IN (".getEntity('intervention').")"; $sql .= " AND f.fk_soc = s.rowid"; @@ -240,16 +269,21 @@ if ($search_contrat_ref) { $sql .= natural_search('c.ref', $search_contrat_ref); } if ($search_desc) { - if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) $sql .= natural_search(array('f.description', 'fd.description'), $search_desc); - else $sql .= natural_search(array('f.description'), $search_desc); + if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) { + $sql .= natural_search(array('f.description', 'fd.description'), $search_desc); + } else { + $sql .= natural_search(array('f.description'), $search_desc); + } } if ($search_status != '' && $search_status >= 0) { $sql .= ' AND f.fk_statut = '.urlencode($search_status); } -if (!$user->rights->societe->client->voir && empty($socid)) +if (!$user->rights->societe->client->voir && empty($socid)) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) +} +if ($socid) { $sql .= " AND s.rowid = ".$socid; +} if ($sall) { $sql .= natural_search(array_keys($fieldstosearchall), $sall); } @@ -263,12 +297,10 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -278,30 +310,50 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); - if ($socid > 0) - { + if ($socid > 0) { $soc = new Societe($db); $soc->fetch($socid); - if (empty($search_company)) $search_company = $soc->name; + if (empty($search_company)) { + $search_company = $soc->name; + } } $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 ($socid) $param .= "&socid=".urlencode($socid); - if ($search_ref) $param .= "&search_ref=".urlencode($search_ref); - if ($search_company) $param .= "&search_company=".urlencode($search_company); - if ($search_desc) $param .= "&search_desc=".urlencode($search_desc); - if ($search_status != '' && $search_status > -1) $param .= "&search_status=".urlencode($search_status); - if ($show_files) $param .= '&show_files='.urlencode($show_files); - 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 ($socid) { + $param .= "&socid=".urlencode($socid); + } + if ($search_ref) { + $param .= "&search_ref=".urlencode($search_ref); + } + if ($search_company) { + $param .= "&search_company=".urlencode($search_company); + } + if ($search_desc) { + $param .= "&search_desc=".urlencode($search_desc); + } + if ($search_status != '' && $search_status > -1) { + $param .= "&search_status=".urlencode($search_status); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -311,19 +363,27 @@ if ($resql) 'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->ficheinter->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + if ($user->rights->ficheinter->supprimer) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); + } + if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $newcardbutton = ''; $url = DOL_URL_ROOT.'/fichinter/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewIntervention'), '', 'fa fa-plus-circle', $url, '', $user->rights->ficheinter->creer); // Lines of title fields print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -339,9 +399,10 @@ if ($resql) $trackid = 'int'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } @@ -349,48 +410,47 @@ if ($resql) $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)) - { + if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; } - if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); + if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); + } print '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; print '<tr class="liste_titre_filter">'; - if (!empty($arrayfields['f.ref']['checked'])) - { + if (!empty($arrayfields['f.ref']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_ref" value="'.$search_ref.'" size="8">'; print '</td>'; } - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_company" value="'.$search_company.'" size="10">'; print '</td>'; } - if (!empty($arrayfields['pr.ref']['checked'])) - { + if (!empty($arrayfields['pr.ref']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_projet_ref" value="'.$search_projet_ref.'" size="8">'; print '</td>'; } - if (!empty($arrayfields['c.ref']['checked'])) - { + if (!empty($arrayfields['c.ref']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_contrat_ref" value="'.$search_contrat_ref.'" size="8">'; print '</td>'; } - if (!empty($arrayfields['f.description']['checked'])) - { + if (!empty($arrayfields['f.description']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_desc" value="'.$search_desc.'" size="12">'; print '</td>'; @@ -402,51 +462,45 @@ if ($resql) $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (!empty($arrayfields['f.datec']['checked'])) - { + if (!empty($arrayfields['f.datec']['checked'])) { // Date creation print '<td class="liste_titre">'; print '</td>'; } - if (!empty($arrayfields['f.tms']['checked'])) - { + if (!empty($arrayfields['f.tms']['checked'])) { // Date modification print '<td class="liste_titre">'; print '</td>'; } - if (!empty($arrayfields['f.note_public']['checked'])) - { + if (!empty($arrayfields['f.note_public']['checked'])) { // Note public print '<td class="liste_titre">'; print '</td>'; } - if (!empty($arrayfields['f.note_private']['checked'])) - { + if (!empty($arrayfields['f.note_private']['checked'])) { // Note private print '<td class="liste_titre">'; print '</td>'; } // Status - if (!empty($arrayfields['f.fk_statut']['checked'])) - { + if (!empty($arrayfields['f.fk_statut']['checked'])) { print '<td class="liste_titre right">'; $tmp = $objectstatic->LibStatut(0); // To load $this->statuts_short $liststatus = $objectstatic->statuts_short; - if (empty($conf->global->FICHINTER_CLASSIFY_BILLED)) unset($liststatus[2]); // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 + if (empty($conf->global->FICHINTER_CLASSIFY_BILLED)) { + unset($liststatus[2]); // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 + } print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 1); print '</td>'; } // Fields of detail line - if (!empty($arrayfields['fd.description']['checked'])) - { + if (!empty($arrayfields['fd.description']['checked'])) { print '<td class="liste_titre">&nbsp;</td>'; } - if (!empty($arrayfields['fd.date']['checked'])) - { + if (!empty($arrayfields['fd.date']['checked'])) { print '<td class="liste_titre">&nbsp;</td>'; } - if (!empty($arrayfields['fd.duree']['checked'])) - { + if (!empty($arrayfields['fd.duree']['checked'])) { print '<td class="liste_titre">&nbsp;</td>'; } print '<td class="liste_titre maxwidthsearch">'; @@ -457,33 +511,58 @@ if ($resql) print "</tr>\n"; print '<tr class="liste_titre">'; - if (!empty($arrayfields['f.ref']['checked'])) print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER["PHP_SELF"], "f.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['pr.ref']['checked'])) print_liste_field_titre($arrayfields['pr.ref']['label'], $_SERVER["PHP_SELF"], "pr.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.description']['checked'])) print_liste_field_titre($arrayfields['f.description']['label'], $_SERVER["PHP_SELF"], "f.description", "", $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['f.ref']['checked'])) { + print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER["PHP_SELF"], "f.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['pr.ref']['checked'])) { + print_liste_field_titre($arrayfields['pr.ref']['label'], $_SERVER["PHP_SELF"], "pr.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['c.ref']['checked'])) { + print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.description']['checked'])) { + print_liste_field_titre($arrayfields['f.description']['label'], $_SERVER["PHP_SELF"], "f.description", "", $param, '', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $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['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.note_public']['checked'])) print_liste_field_titre($arrayfields['f.note_public']['label'], $_SERVER["PHP_SELF"], "f.note_public", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.note_private']['checked'])) print_liste_field_titre($arrayfields['f.note_private']['label'], $_SERVER["PHP_SELF"], "f.note_private", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'], $_SERVER["PHP_SELF"], "f.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['fd.description']['checked'])) print_liste_field_titre($arrayfields['fd.description']['label'], $_SERVER["PHP_SELF"], ''); - if (!empty($arrayfields['fd.date']['checked'])) print_liste_field_titre($arrayfields['fd.date']['label'], $_SERVER["PHP_SELF"], "fd.date", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['fd.duree']['checked'])) print_liste_field_titre($arrayfields['fd.duree']['label'], $_SERVER["PHP_SELF"], "fd.duree", "", $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['f.datec']['checked'])) { + print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.tms']['checked'])) { + print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.note_public']['checked'])) { + print_liste_field_titre($arrayfields['f.note_public']['label'], $_SERVER["PHP_SELF"], "f.note_public", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.note_private']['checked'])) { + print_liste_field_titre($arrayfields['f.note_private']['label'], $_SERVER["PHP_SELF"], "f.note_private", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_statut']['label'], $_SERVER["PHP_SELF"], "f.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['fd.description']['checked'])) { + print_liste_field_titre($arrayfields['fd.description']['label'], $_SERVER["PHP_SELF"], ''); + } + if (!empty($arrayfields['fd.date']['checked'])) { + print_liste_field_titre($arrayfields['fd.date']['label'], $_SERVER["PHP_SELF"], "fd.date", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['fd.duree']['checked'])) { + print_liste_field_titre($arrayfields['fd.duree']['label'], $_SERVER["PHP_SELF"], "fd.duree", "", $param, '', $sortfield, $sortorder, 'right '); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; $total = 0; $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->rowid; @@ -500,8 +579,7 @@ if ($resql) print '<tr class="oddeven">'; - if (!empty($arrayfields['f.ref']['checked'])) - { + if (!empty($arrayfields['f.ref']['checked'])) { print "<td>"; print '<table class="nobordernopadding"><tr class="nocellnopadd">'; @@ -512,15 +590,13 @@ if ($resql) // Warning $warnornote = ''; //if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->fichinter->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); - if (!empty($obj->note_private)) - { + if (!empty($obj->note_private)) { $warnornote .= ($warnornote ? ' ' : ''); $warnornote .= '<span class="note">'; $warnornote .= '<a href="note.php?id='.$obj->rowid.'">'.img_picto($langs->trans("ViewPrivateNote"), 'object_generic').'</a>'; $warnornote .= '</span>'; } - if ($warnornote) - { + if ($warnornote) { print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; print $warnornote; print '</td>'; @@ -535,17 +611,19 @@ if ($resql) print '</td></tr></table>'; print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td>'; print $companystatic->getNomUrl(1, '', 44); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['pr.ref']['checked'])) - { + if (!empty($arrayfields['pr.ref']['checked'])) { print '<td>'; $projetstatic->id = $obj->projet_id; $projetstatic->ref = $obj->projet_ref; @@ -554,10 +632,11 @@ if ($resql) print $projetstatic->getNomUrl(1, ''); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['c.ref']['checked'])) - { + if (!empty($arrayfields['c.ref']['checked'])) { print '<td>'; $contratstatic->id = $obj->contrat_id; $contratstatic->ref = $obj->contrat_ref; @@ -567,12 +646,15 @@ if ($resql) print $contratstatic->getNomUrl(1, ''); print '</td>'; } - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['f.description']['checked'])) - { + if (!empty($arrayfields['f.description']['checked'])) { print '<td>'.dol_trunc(dolGetFirstLineOfText($obj->description), 48).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -582,71 +664,84 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['f.datec']['checked'])) - { + if (!empty($arrayfields['f.datec']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['f.tms']['checked'])) - { + if (!empty($arrayfields['f.tms']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Note public - if (!empty($arrayfields['f.note_public']['checked'])) - { + if (!empty($arrayfields['f.note_public']['checked'])) { print '<td class="center">'; print dol_escape_htmltag($obj->note_public); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Note private - if (!empty($arrayfields['f.note_private']['checked'])) - { + if (!empty($arrayfields['f.note_private']['checked'])) { print '<td class="center">'; print dol_escape_htmltag($obj->note_private); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['f.fk_statut']['checked'])) - { + if (!empty($arrayfields['f.fk_statut']['checked'])) { print '<td class="right">'.$objectstatic->getLibStatut(5).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Fields of detail of line - if (!empty($arrayfields['fd.description']['checked'])) - { + if (!empty($arrayfields['fd.description']['checked'])) { print '<td>'.dolGetFirstLineOfText($obj->descriptiondetail).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['fd.date']['checked'])) - { + if (!empty($arrayfields['fd.date']['checked'])) { print '<td class="center">'.dol_print_date($db->jdate($obj->dp), 'dayhour')."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['fd.duree']['checked'])) - { + if (!empty($arrayfields['fd.duree']['checked'])) { print '<td class="right">'.convertSecondToTime($obj->duree, 'allhourmin').'</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'fd.duree'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'fd.duree'; + } $totalarray['val']['fd.duree'] += $obj->duree; } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; @@ -669,7 +764,9 @@ if ($resql) print "</form>\n"; $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/fichinter/note.php b/htdocs/fichinter/note.php index dddbe79e33e..fcc790bf8c2 100644 --- a/htdocs/fichinter/note.php +++ b/htdocs/fichinter/note.php @@ -39,7 +39,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); $object = new Fichinter($db); @@ -62,8 +64,7 @@ llxHeader('', $langs->trans("Intervention")); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = fichinter_prepare_head($object); @@ -80,12 +81,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/fichinter/stats/index.php b/htdocs/fichinter/stats/index.php index 19e7f86d8a0..29a5f9976b0 100644 --- a/htdocs/fichinter/stats/index.php +++ b/htdocs/fichinter/stats/index.php @@ -30,13 +30,14 @@ $WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); $mode = 'customer'; -if (!$user->rights->ficheinter->lire) accessforbidden(); +if (!$user->rights->ficheinter->lire) { + accessforbidden(); +} $userid = GETPOST('userid', 'int'); $socid = GETPOST('socid', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -70,15 +71,16 @@ print load_fiche_titre($title, '', 'intervention'); dol_mkdir($dir); $stats = new FichinterStats($db, $socid, $mode, ($userid > 0 ? $userid : 0)); -if ($object_status != '' && $object_status > -1) $stats->where .= ' AND c.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +if ($object_status != '' && $object_status > -1) { + $stats->where .= ' AND c.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +} // Build graphic number of object $data = $stats->getNbByMonthWithPrevYear($endyear, $startyear); // $data = array(array('Lib',val1,val2,val3),...) -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filenamenb = $dir.'/interventionsnbinyear-'.$user->id.'-'.$year.'.png'; $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsnbinyear-'.$user->id.'-'.$year.'.png'; } else { @@ -88,12 +90,10 @@ if (!$user->rights->societe->client->voir || $user->socid) $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -115,8 +115,7 @@ if (!$mesg) $data = $stats->getAmountByMonthWithPrevYear($endyear, $startyear); // $data = array(array('Lib',val1,val2,val3),...) -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filenameamount = $dir.'/interventionsamountinyear-'.$user->id.'-'.$year.'.png'; $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsamountinyear-'.$user->id.'-'.$year.'.png'; } else { @@ -126,12 +125,10 @@ if (!$user->rights->societe->client->voir || $user->socid) $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px2->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -152,8 +149,7 @@ if (!$mesg) $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filename_avg = $dir.'/interventionsaverage-'.$user->id.'-'.$year.'.png'; $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsaverage-'.$user->id.'-'.$year.'.png'; } else { @@ -163,12 +159,10 @@ if (!$user->rights->societe->client->voir || $user->socid) $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px3->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -196,7 +190,9 @@ foreach ($data as $val) { $arrayyears[$val['year']] = $val['year']; } } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; $head = array(); @@ -236,13 +232,19 @@ print '<div class="fichecenter"><div class="fichethirdleft">'; print '<tr><td class="left">'.$langs->trans("Status").'</td><td class="left">'; $tmp = $objectstatic->LibStatut(0); // To load $this->statuts_short $liststatus = $objectstatic->statuts_short; - if (empty($conf->global->FICHINTER_CLASSIFY_BILLED)) unset($liststatus[2]); // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 +if (empty($conf->global->FICHINTER_CLASSIFY_BILLED)) { + unset($liststatus[2]); // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 +} print $form->selectarray('object_status', $liststatus, $object_status, 1, 0, 0, '', 1); print '</td></tr>'; // Year print '<tr><td class="left">'.$langs->trans("Year").'</td><td class="left">'; - if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; - if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} +if (!in_array($nowyear, $arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print '</td></tr>'; @@ -265,11 +267,9 @@ print '<td class="right">%</td>'; print '</tr>'; $oldyear = 0; -foreach ($data as $val) -{ +foreach ($data as $val) { $year = $val['year']; - while (!empty($year) && $oldyear > $year + 1) - { + while (!empty($year) && $oldyear > $year + 1) { // If we have empty year $oldyear--; @@ -307,12 +307,14 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; // Show graphs print '<table class="border centpercent"><tr class="pair nohover"><td class="center">'; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); /*print "<br>\n"; - print $px2->show(); - print "<br>\n"; - print $px3->show();*/ + print $px2->show(); + print "<br>\n"; + print $px3->show();*/ } print '</td></tr></table>'; diff --git a/htdocs/fichinter/tpl/linkedobjectblock.tpl.php b/htdocs/fichinter/tpl/linkedobjectblock.tpl.php index b483e877e5e..ba754ec3321 100644 --- a/htdocs/fichinter/tpl/linkedobjectblock.tpl.php +++ b/htdocs/fichinter/tpl/linkedobjectblock.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -36,17 +35,18 @@ $langs->load("interventions"); $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1); $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - <tr class="<?php echo $trclass; ?>"> + <tr class="<?php echo $trclass; ?>"> <td><?php echo $langs->trans("Intervention"); ?></td> - <td><?php echo $objectlink->getNomUrl(1); ?></td> - <td></td> + <td><?php echo $objectlink->getNomUrl(1); ?></td> + <td></td> <td class="center"><?php echo dol_print_date($objectlink->datev, 'day'); ?></td> <td></td> <td class="right"><?php echo $objectlink->getLibStatut(3); ?></td> diff --git a/htdocs/filefunc.inc.php b/htdocs/filefunc.inc.php index 8d9778b177e..aff0ebad349 100644 --- a/htdocs/filefunc.inc.php +++ b/htdocs/filefunc.inc.php @@ -30,14 +30,19 @@ * \brief File that include conf.php file and commons lib like functions.lib.php */ -if (!defined('DOL_APPLICATION_TITLE')) define('DOL_APPLICATION_TITLE', 'Dolibarr'); -if (!defined('DOL_VERSION')) define('DOL_VERSION', '14.0.0-alpha'); // a.b.c-alpha, a.b.c-beta, a.b.c-rcX or a.b.c +if (!defined('DOL_APPLICATION_TITLE')) { + define('DOL_APPLICATION_TITLE', 'Dolibarr'); +} +if (!defined('DOL_VERSION')) { + define('DOL_VERSION', '14.0.0-alpha'); // a.b.c-alpha, a.b.c-beta, a.b.c-rcX or a.b.c +} -if (!defined('EURO')) define('EURO', chr(128)); +if (!defined('EURO')) { + define('EURO', chr(128)); +} // Define syslog constants -if (!defined('LOG_DEBUG')) -{ +if (!defined('LOG_DEBUG')) { if (!function_exists("syslog")) { // For PHP versions without syslog (like running on Windows OS) define('LOG_EMERG', 0); @@ -52,7 +57,9 @@ if (!defined('LOG_DEBUG')) } // End of common declaration part -if (defined('DOL_INC_FOR_VERSION_ERROR')) return; +if (defined('DOL_INC_FOR_VERSION_ERROR')) { + return; +} // Define vars @@ -73,15 +80,13 @@ $conffiletoshow = "htdocs/conf/conf.php"; // Include configuration $result = @include_once $conffile; // Keep @ because with some error reporting this break the redirect done when file not found -if (!$result && !empty($_SERVER["GATEWAY_INTERFACE"])) // If install not done and we are in a web session -{ - if (!empty($_SERVER["CONTEXT_PREFIX"])) // CONTEXT_PREFIX and CONTEXT_DOCUMENT_ROOT are not defined on all apache versions - { +if (!$result && !empty($_SERVER["GATEWAY_INTERFACE"])) { // If install not done and we are in a web session + if (!empty($_SERVER["CONTEXT_PREFIX"])) { // CONTEXT_PREFIX and CONTEXT_DOCUMENT_ROOT are not defined on all apache versions $path = $_SERVER["CONTEXT_PREFIX"]; // example '/dolibarr/' when using an apache alias. - if (!preg_match('/\/$/', $path)) $path .= '/'; - } - elseif (preg_match('/index\.php/', $_SERVER['PHP_SELF'])) - { + if (!preg_match('/\/$/', $path)) { + $path .= '/'; + } + } elseif (preg_match('/index\.php/', $_SERVER['PHP_SELF'])) { // When we ask index.php, we MUST BE SURE that $path is '' at the end. This is required to make install process // when using apache alias like '/dolibarr/' that point to htdocs. // Note: If calling page was an index.php not into htdocs (ie comm/index.php, ...), then this redirect will fails, @@ -94,11 +99,16 @@ if (!$result && !empty($_SERVER["GATEWAY_INTERFACE"])) // If install not done $TDir = explode('/', $_SERVER['PHP_SELF']); $path = ''; $i = count($TDir); - while ($i--) - { - if (empty($TDir[$i]) || $TDir[$i] == 'htdocs') break; - if ($TDir[$i] == 'dolibarr') break; - if (substr($TDir[$i], -4, 4) == '.php') continue; + while ($i--) { + if (empty($TDir[$i]) || $TDir[$i] == 'htdocs') { + break; + } + if ($TDir[$i] == 'dolibarr') { + break; + } + if (substr($TDir[$i], -4, 4) == '.php') { + continue; + } $path .= '../'; } @@ -109,15 +119,16 @@ if (!$result && !empty($_SERVER["GATEWAY_INTERFACE"])) // If install not done } // Force PHP error_reporting setup (Dolibarr may report warning without this) -if (!empty($dolibarr_strict_mode)) -{ +if (!empty($dolibarr_strict_mode)) { error_reporting(E_ALL | E_STRICT); } else { error_reporting(E_ALL & ~(E_STRICT | E_NOTICE | E_DEPRECATED)); } // Disable php display errors -if (!empty($dolibarr_main_prod)) ini_set('display_errors', 'Off'); +if (!empty($dolibarr_main_prod)) { + ini_set('display_errors', 'Off'); +} // Clean parameters $dolibarr_main_data_root = trim($dolibarr_main_data_root); @@ -126,39 +137,63 @@ $dolibarr_main_url_root_alt = (empty($dolibarr_main_url_root_alt) ? '' : trim($d $dolibarr_main_document_root = trim($dolibarr_main_document_root); $dolibarr_main_document_root_alt = (empty($dolibarr_main_document_root_alt) ? '' : trim($dolibarr_main_document_root_alt)); -if (empty($dolibarr_main_db_port)) $dolibarr_main_db_port = 3306; // For compatibility with old configs, if not defined, we take 'mysql' type -if (empty($dolibarr_main_db_type)) $dolibarr_main_db_type = 'mysqli'; // For compatibility with old configs, if not defined, we take 'mysql' type +if (empty($dolibarr_main_db_port)) { + $dolibarr_main_db_port = 3306; // For compatibility with old configs, if not defined, we take 'mysql' type +} +if (empty($dolibarr_main_db_type)) { + $dolibarr_main_db_type = 'mysqli'; // For compatibility with old configs, if not defined, we take 'mysql' type +} // Mysql driver support has been removed in favor of mysqli -if ($dolibarr_main_db_type == 'mysql') $dolibarr_main_db_type = 'mysqli'; -if (empty($dolibarr_main_db_prefix)) $dolibarr_main_db_prefix = 'llx_'; -if (empty($dolibarr_main_db_character_set)) $dolibarr_main_db_character_set = ($dolibarr_main_db_type == 'mysqli' ? 'utf8' : ''); // Old installation -if (empty($dolibarr_main_db_collation)) $dolibarr_main_db_collation = ($dolibarr_main_db_type == 'mysqli' ? 'utf8_unicode_ci' : ''); // Old installation -if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption = 0; -if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey = ''; -if (empty($dolibarr_main_limit_users)) $dolibarr_main_limit_users = 0; -if (empty($dolibarr_mailing_limit_sendbyweb)) $dolibarr_mailing_limit_sendbyweb = 0; -if (empty($dolibarr_mailing_limit_sendbycli)) $dolibarr_mailing_limit_sendbycli = 0; -if (empty($dolibarr_strict_mode)) $dolibarr_strict_mode = 0; // For debug in php strict mode +if ($dolibarr_main_db_type == 'mysql') { + $dolibarr_main_db_type = 'mysqli'; +} +if (empty($dolibarr_main_db_prefix)) { + $dolibarr_main_db_prefix = 'llx_'; +} +if (empty($dolibarr_main_db_character_set)) { + $dolibarr_main_db_character_set = ($dolibarr_main_db_type == 'mysqli' ? 'utf8' : ''); // Old installation +} +if (empty($dolibarr_main_db_collation)) { + $dolibarr_main_db_collation = ($dolibarr_main_db_type == 'mysqli' ? 'utf8_unicode_ci' : ''); // Old installation +} +if (empty($dolibarr_main_db_encryption)) { + $dolibarr_main_db_encryption = 0; +} +if (empty($dolibarr_main_db_cryptkey)) { + $dolibarr_main_db_cryptkey = ''; +} +if (empty($dolibarr_main_limit_users)) { + $dolibarr_main_limit_users = 0; +} +if (empty($dolibarr_mailing_limit_sendbyweb)) { + $dolibarr_mailing_limit_sendbyweb = 0; +} +if (empty($dolibarr_mailing_limit_sendbycli)) { + $dolibarr_mailing_limit_sendbycli = 0; +} +if (empty($dolibarr_strict_mode)) { + $dolibarr_strict_mode = 0; // For debug in php strict mode +} // Security: CSRF protection // This test check if referrer ($_SERVER['HTTP_REFERER']) is same web site than Dolibarr ($_SERVER['HTTP_HOST']) -// when we post forms (we allow GET to allow direct link to access a particular page). +// when we post forms (we allow GET and HEAD to accept direct link from a particular page). // Note about $_SERVER[HTTP_HOST/SERVER_NAME]: http://shiflett.org/blog/2006/mar/server-name-versus-http-host -// See also option $conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN for a stronger CSRF protection. -if (!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck)) -{ - if (!empty($_SERVER['REQUEST_METHOD']) && !in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) && !empty($_SERVER['HTTP_HOST'])) - { +// See also CSRF protections done into main.inc.php +if (!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck)) { + if (!empty($_SERVER['REQUEST_METHOD']) && !in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) && !empty($_SERVER['HTTP_HOST'])) { $csrfattack = false; - if (empty($_SERVER['HTTP_REFERER'])) $csrfattack = true; // An evil browser was used - else { + if (empty($_SERVER['HTTP_REFERER'])) { + $csrfattack = true; // An evil browser was used + } else { $tmpa = parse_url($_SERVER['HTTP_HOST']); $tmpb = parse_url($_SERVER['HTTP_REFERER']); - if ((empty($tmpa['host']) ? $tmpa['path'] : $tmpa['host']) != (empty($tmpb['host']) ? $tmpb['path'] : $tmpb['host'])) $csrfattack = true; + if ((empty($tmpa['host']) ? $tmpa['path'] : $tmpa['host']) != (empty($tmpb['host']) ? $tmpb['path'] : $tmpb['host'])) { + $csrfattack = true; + } } - if ($csrfattack) - { + if ($csrfattack) { //print 'NOCSRFCHECK='.defined('NOCSRFCHECK').' REQUEST_METHOD='.$_SERVER['REQUEST_METHOD'].' HTTP_HOST='.$_SERVER['HTTP_HOST'].' HTTP_REFERER='.$_SERVER['HTTP_REFERER']; // Note: We can't use dol_escape_htmltag here to escape output because lib functions.lib.ph is not yet loaded. print "Access refused by CSRF protection in main.inc.php. Referer of form (".htmlentities($_SERVER['HTTP_REFERER'], ENT_COMPAT, 'UTF-8').") is outside the server that serve this page (with method = ".htmlentities($_SERVER['REQUEST_METHOD'], ENT_COMPAT, 'UTF-8').").\n"; @@ -168,21 +203,23 @@ if (!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck)) } // Another test is done later on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on. } -if (empty($dolibarr_main_db_host)) -{ +if (empty($dolibarr_main_db_host) && !defined('NOREQUIREDB')) { print '<div class="center">Dolibarr setup is not yet complete.<br><br>'."\n"; print '<a href="install/index.php">Click here to finish Dolibarr install process</a> ...</div>'."\n"; die; } -if (empty($dolibarr_main_url_root)) -{ +if (empty($dolibarr_main_url_root) && !defined('NOREQUIREVIRTUALURL')) { print 'Value for parameter \'dolibarr_main_url_root\' is not defined in your \'htdocs\conf\conf.php\' file.<br>'."\n"; print 'You must add this parameter with your full Dolibarr root Url (Example: http://myvirtualdomain/ or http://mydomain/mydolibarrurl/)'."\n"; die; } -if (empty($dolibarr_main_data_root)) -{ - // Si repertoire documents non defini, on utilise celui par defaut + +if (empty($dolibarr_main_document_root_alt)) { + $dolibarr_main_document_root_alt = $dolibarr_main_document_root.'/custom'; +} + +if (empty($dolibarr_main_data_root)) { + // If directory not defined, we use the default hardcoded value $dolibarr_main_data_root = str_replace("/htdocs", "", $dolibarr_main_document_root); $dolibarr_main_data_root .= "/documents"; } @@ -204,14 +241,14 @@ if (!empty($_SERVER["DOCUMENT_ROOT"])) { $paths = explode('/', str_replace('\\', '/', $_SERVER["SCRIPT_NAME"])); // C) Value reported by web server, to say full path on filesystem of a file. Ex: /dolibarr/htdocs/admin/system/phpinfo.php // Try to detect if $_SERVER["DOCUMENT_ROOT"]+start of $_SERVER["SCRIPT_NAME"] is $dolibarr_main_document_root. If yes, relative url to add before dol files is this start part. $concatpath = ''; -foreach ($paths as $tmppath) // We check to find (B+start of C)=A -{ - if (empty($tmppath)) continue; +foreach ($paths as $tmppath) { // We check to find (B+start of C)=A + if (empty($tmppath)) { + continue; + } $concatpath .= '/'.$tmppath; //if ($tmppath) $concatpath.='/'.$tmppath; //print $_SERVER["SCRIPT_NAME"].'-'.$pathroot.'-'.$concatpath.'-'.$real_dolibarr_main_document_root.'-'.realpath($pathroot.$concatpath).'<br>'; - if ($real_dolibarr_main_document_root == @realpath($pathroot.$concatpath)) // @ avoid warning when safe_mode is on. - { + if ($real_dolibarr_main_document_root == @realpath($pathroot.$concatpath)) { // @ avoid warning when safe_mode is on. //print "Found relative url = ".$concatpath; $tmp3 = $concatpath; $found = 1; @@ -220,14 +257,21 @@ foreach ($paths as $tmppath) // We check to find (B+start of C)=A //else print "Not found yet for concatpath=".$concatpath."<br>\n"; } //print "found=".$found." dolibarr_main_url_root=".$dolibarr_main_url_root."\n"; -if (!$found) $tmp = $dolibarr_main_url_root; // If autodetect fails (Ie: when using apache alias that point outside default DOCUMENT_ROOT). -else $tmp = 'http'.(((empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != 'on') && (empty($_SERVER["SERVER_PORT"]) || $_SERVER["SERVER_PORT"] != 443)) ? '' : 's').'://'.$_SERVER["SERVER_NAME"].((empty($_SERVER["SERVER_PORT"]) || $_SERVER["SERVER_PORT"] == 80 || $_SERVER["SERVER_PORT"] == 443) ? '' : ':'.$_SERVER["SERVER_PORT"]).($tmp3 ? (preg_match('/^\//', $tmp3) ? '' : '/').$tmp3 : ''); +if (!$found) { + $tmp = $dolibarr_main_url_root; // If autodetect fails (Ie: when using apache alias that point outside default DOCUMENT_ROOT). +} else { + $tmp = 'http'.(((empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != 'on') && (empty($_SERVER["SERVER_PORT"]) || $_SERVER["SERVER_PORT"] != 443)) ? '' : 's').'://'.$_SERVER["SERVER_NAME"].((empty($_SERVER["SERVER_PORT"]) || $_SERVER["SERVER_PORT"] == 80 || $_SERVER["SERVER_PORT"] == 443) ? '' : ':'.$_SERVER["SERVER_PORT"]).($tmp3 ? (preg_match('/^\//', $tmp3) ? '' : '/').$tmp3 : ''); +} //print "tmp1=".$tmp1." tmp2=".$tmp2." tmp3=".$tmp3." tmp=".$tmp."\n"; -if (!empty($dolibarr_main_force_https)) $tmp = preg_replace('/^http:/i', 'https:', $tmp); +if (!empty($dolibarr_main_force_https)) { + $tmp = preg_replace('/^http:/i', 'https:', $tmp); +} define('DOL_MAIN_URL_ROOT', $tmp); // URL absolute root (https://sss/dolibarr, ...) $uri = preg_replace('/^http(s?):\/\//i', '', constant('DOL_MAIN_URL_ROOT')); // $uri contains url without http* $suburi = strstr($uri, '/'); // $suburi contains url without domain:port -if ($suburi == '/') $suburi = ''; // If $suburi is /, it is now '' +if ($suburi == '/') { + $suburi = ''; // If $suburi is /, it is now '' +} define('DOL_URL_ROOT', $suburi); // URL relative root ('', '/dolibarr', ...) //print DOL_MAIN_URL_ROOT.'-'.DOL_URL_ROOT."\n"; @@ -241,29 +285,54 @@ define('MAIN_DB_PREFIX', $dolibarr_main_db_prefix); * To use other version than embeded libraries, define here constant to path. Use '' to use include class path autodetect. */ // Path to root libraries -if (!defined('ADODB_PATH')) { define('ADODB_PATH', (!isset($dolibarr_lib_ADODB_PATH)) ?DOL_DOCUMENT_ROOT.'/includes/adodbtime/' : (empty($dolibarr_lib_ADODB_PATH) ? '' : $dolibarr_lib_ADODB_PATH.'/')); } -if (!defined('TCPDF_PATH')) { define('TCPDF_PATH', (empty($dolibarr_lib_TCPDF_PATH)) ?DOL_DOCUMENT_ROOT.'/includes/tecnickcom/tcpdf/' : $dolibarr_lib_TCPDF_PATH.'/'); } -if (!defined('TCPDI_PATH')) { define('TCPDI_PATH', (empty($dolibarr_lib_TCPDI_PATH)) ?DOL_DOCUMENT_ROOT.'/includes/tcpdi/' : $dolibarr_lib_TCPDI_PATH.'/'); } -if (!defined('NUSOAP_PATH')) { define('NUSOAP_PATH', (!isset($dolibarr_lib_NUSOAP_PATH)) ?DOL_DOCUMENT_ROOT.'/includes/nusoap/lib/' : (empty($dolibarr_lib_NUSOAP_PATH) ? '' : $dolibarr_lib_NUSOAP_PATH.'/')); } -if (!defined('PHPEXCELNEW_PATH')) { define('PHPEXCELNEW_PATH', (!isset($dolibarr_lib_PHPEXCELNEW_PATH)) ?DOL_DOCUMENT_ROOT.'/includes/phpoffice/PhpSpreadsheet/' : (empty($dolibarr_lib_PHPEXCELNEW_PATH) ? '' : $dolibarr_lib_PHPEXCELNEW_PATH.'/')); } -if (!defined('ODTPHP_PATH')) { define('ODTPHP_PATH', (!isset($dolibarr_lib_ODTPHP_PATH)) ?DOL_DOCUMENT_ROOT.'/includes/odtphp/' : (empty($dolibarr_lib_ODTPHP_PATH) ? '' : $dolibarr_lib_ODTPHP_PATH.'/')); } -if (!defined('ODTPHP_PATHTOPCLZIP')) { define('ODTPHP_PATHTOPCLZIP', (!isset($dolibarr_lib_ODTPHP_PATHTOPCLZIP)) ?DOL_DOCUMENT_ROOT.'/includes/odtphp/zip/pclzip/' : (empty($dolibarr_lib_ODTPHP_PATHTOPCLZIP) ? '' : $dolibarr_lib_ODTPHP_PATHTOPCLZIP.'/')); } -if (!defined('JS_CKEDITOR')) { define('JS_CKEDITOR', (!isset($dolibarr_js_CKEDITOR)) ? '' : (empty($dolibarr_js_CKEDITOR) ? '' : $dolibarr_js_CKEDITOR.'/')); } -if (!defined('JS_JQUERY')) { define('JS_JQUERY', (!isset($dolibarr_js_JQUERY)) ? '' : (empty($dolibarr_js_JQUERY) ? '' : $dolibarr_js_JQUERY.'/')); } -if (!defined('JS_JQUERY_UI')) { define('JS_JQUERY_UI', (!isset($dolibarr_js_JQUERY_UI)) ? '' : (empty($dolibarr_js_JQUERY_UI) ? '' : $dolibarr_js_JQUERY_UI.'/')); } +if (!defined('ADODB_PATH')) { + define('ADODB_PATH', (!isset($dolibarr_lib_ADODB_PATH)) ?DOL_DOCUMENT_ROOT.'/includes/adodbtime/' : (empty($dolibarr_lib_ADODB_PATH) ? '' : $dolibarr_lib_ADODB_PATH.'/')); +} +if (!defined('TCPDF_PATH')) { + define('TCPDF_PATH', (empty($dolibarr_lib_TCPDF_PATH)) ?DOL_DOCUMENT_ROOT.'/includes/tecnickcom/tcpdf/' : $dolibarr_lib_TCPDF_PATH.'/'); +} +if (!defined('TCPDI_PATH')) { + define('TCPDI_PATH', (empty($dolibarr_lib_TCPDI_PATH)) ?DOL_DOCUMENT_ROOT.'/includes/tcpdi/' : $dolibarr_lib_TCPDI_PATH.'/'); +} +if (!defined('NUSOAP_PATH')) { + define('NUSOAP_PATH', (!isset($dolibarr_lib_NUSOAP_PATH)) ?DOL_DOCUMENT_ROOT.'/includes/nusoap/lib/' : (empty($dolibarr_lib_NUSOAP_PATH) ? '' : $dolibarr_lib_NUSOAP_PATH.'/')); +} +if (!defined('PHPEXCELNEW_PATH')) { + define('PHPEXCELNEW_PATH', (!isset($dolibarr_lib_PHPEXCELNEW_PATH)) ?DOL_DOCUMENT_ROOT.'/includes/phpoffice/PhpSpreadsheet/' : (empty($dolibarr_lib_PHPEXCELNEW_PATH) ? '' : $dolibarr_lib_PHPEXCELNEW_PATH.'/')); +} +if (!defined('ODTPHP_PATH')) { + define('ODTPHP_PATH', (!isset($dolibarr_lib_ODTPHP_PATH)) ?DOL_DOCUMENT_ROOT.'/includes/odtphp/' : (empty($dolibarr_lib_ODTPHP_PATH) ? '' : $dolibarr_lib_ODTPHP_PATH.'/')); +} +if (!defined('ODTPHP_PATHTOPCLZIP')) { + define('ODTPHP_PATHTOPCLZIP', (!isset($dolibarr_lib_ODTPHP_PATHTOPCLZIP)) ?DOL_DOCUMENT_ROOT.'/includes/odtphp/zip/pclzip/' : (empty($dolibarr_lib_ODTPHP_PATHTOPCLZIP) ? '' : $dolibarr_lib_ODTPHP_PATHTOPCLZIP.'/')); +} +if (!defined('JS_CKEDITOR')) { + define('JS_CKEDITOR', (!isset($dolibarr_js_CKEDITOR)) ? '' : (empty($dolibarr_js_CKEDITOR) ? '' : $dolibarr_js_CKEDITOR.'/')); +} +if (!defined('JS_JQUERY')) { + define('JS_JQUERY', (!isset($dolibarr_js_JQUERY)) ? '' : (empty($dolibarr_js_JQUERY) ? '' : $dolibarr_js_JQUERY.'/')); +} +if (!defined('JS_JQUERY_UI')) { + define('JS_JQUERY_UI', (!isset($dolibarr_js_JQUERY_UI)) ? '' : (empty($dolibarr_js_JQUERY_UI) ? '' : $dolibarr_js_JQUERY_UI.'/')); +} // Other required path -if (!defined('DOL_DEFAULT_TTF')) { define('DOL_DEFAULT_TTF', (!isset($dolibarr_font_DOL_DEFAULT_TTF)) ?DOL_DOCUMENT_ROOT.'/includes/fonts/Aerial.ttf' : (empty($dolibarr_font_DOL_DEFAULT_TTF) ? '' : $dolibarr_font_DOL_DEFAULT_TTF)); } -if (!defined('DOL_DEFAULT_TTF_BOLD')) { define('DOL_DEFAULT_TTF_BOLD', (!isset($dolibarr_font_DOL_DEFAULT_TTF_BOLD)) ?DOL_DOCUMENT_ROOT.'/includes/fonts/AerialBd.ttf' : (empty($dolibarr_font_DOL_DEFAULT_TTF_BOLD) ? '' : $dolibarr_font_DOL_DEFAULT_TTF_BOLD)); } +if (!defined('DOL_DEFAULT_TTF')) { + define('DOL_DEFAULT_TTF', (!isset($dolibarr_font_DOL_DEFAULT_TTF)) ?DOL_DOCUMENT_ROOT.'/includes/fonts/Aerial.ttf' : (empty($dolibarr_font_DOL_DEFAULT_TTF) ? '' : $dolibarr_font_DOL_DEFAULT_TTF)); +} +if (!defined('DOL_DEFAULT_TTF_BOLD')) { + define('DOL_DEFAULT_TTF_BOLD', (!isset($dolibarr_font_DOL_DEFAULT_TTF_BOLD)) ?DOL_DOCUMENT_ROOT.'/includes/fonts/AerialBd.ttf' : (empty($dolibarr_font_DOL_DEFAULT_TTF_BOLD) ? '' : $dolibarr_font_DOL_DEFAULT_TTF_BOLD)); +} /* * Include functions */ -if (!defined('ADODB_DATE_VERSION')) include_once ADODB_PATH.'adodb-time.inc.php'; +if (!defined('ADODB_DATE_VERSION')) { + include_once ADODB_PATH.'adodb-time.inc.php'; +} -if (!file_exists(DOL_DOCUMENT_ROOT."/core/lib/functions.lib.php")) -{ +if (!file_exists(DOL_DOCUMENT_ROOT."/core/lib/functions.lib.php")) { print "Error: Dolibarr config file content seems to be not correctly defined.<br>\n"; print "Please run dolibarr setup by calling page <b>/install</b>.<br>\n"; exit; diff --git a/htdocs/fourn/ajax/getSupplierPrices.php b/htdocs/fourn/ajax/getSupplierPrices.php index 0c0d8f42c9e..e0cd9beff0c 100644 --- a/htdocs/fourn/ajax/getSupplierPrices.php +++ b/htdocs/fourn/ajax/getSupplierPrices.php @@ -22,10 +22,18 @@ * \brief File to return an Ajax response to get list of possible prices for margin calculation */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; @@ -46,47 +54,45 @@ top_httphead(); //print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n"; -if ($idprod > 0) -{ +if ($idprod > 0) { $producttmp = new ProductFournisseur($db); $producttmp->fetch($idprod); $sorttouse = 's.nom, pfp.quantity, pfp.price'; - if (GETPOST('bestpricefirst')) $sorttouse = 'pfp.unitprice, s.nom, pfp.quantity, pfp.price'; + if (GETPOST('bestpricefirst')) { + $sorttouse = 'pfp.unitprice, s.nom, pfp.quantity, pfp.price'; + } $productSupplierArray = $producttmp->list_product_fournisseur_price($idprod, $sorttouse); // We list all price per supplier, and then firstly with the lower quantity. So we can choose first one with enough quantity into list. - if (is_array($productSupplierArray)) - { - foreach ($productSupplierArray as $productSupplier) - { + if (is_array($productSupplierArray)) { + foreach ($productSupplierArray as $productSupplier) { $price = $productSupplier->fourn_price * (1 - $productSupplier->fourn_remise_percent / 100); $unitprice = $productSupplier->fourn_unitprice * (1 - $productSupplier->fourn_remise_percent / 100); $title = $productSupplier->fourn_name.' - '.$productSupplier->fourn_ref.' - '; - if ($productSupplier->fourn_qty == 1) - { + if ($productSupplier->fourn_qty == 1) { $title .= price($price, 0, $langs, 0, 0, -1, $conf->currency)."/"; } $title .= $productSupplier->fourn_qty.' '.($productSupplier->fourn_qty == 1 ? $langs->trans("Unit") : $langs->trans("Units")); - if ($productSupplier->fourn_qty > 1) - { + if ($productSupplier->fourn_qty > 1) { $title .= " - "; $title .= price($unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit"); $price = $unitprice; } $label = price($price, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit"); - if ($productSupplier->fourn_ref) $label .= ' ('.$productSupplier->fourn_ref.')'; + if ($productSupplier->fourn_ref) { + $label .= ' ('.$productSupplier->fourn_ref.')'; + } $prices[] = array("id" => $productSupplier->product_fourn_price_id, "price" => price2num($price, 0, '', 0), "label" => $label, "title" => $title); // For price field, we must use price2num(), for label or title, price() } } // After best supplier prices and before costprice - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { // Add price for pmp $price = $producttmp->pmp; $prices[] = array("id" => 'pmpprice', "price" => price2num($price), "label" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency), "title" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency)); // For price field, we must use price2num(), for label or title, price() diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 9d18f3cfd1a..6db5ba5cad3 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -7,6 +7,7 @@ * Copyright (C) 2014 Jean Heimburger <jean@tiaris.info> * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com> * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr> + * Copyright (C) 2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -35,8 +36,12 @@ require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (!empty($conf->adherent->enabled)) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; -if (!empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +if (!empty($conf->adherent->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; +} +if (!empty($conf->categorie->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +} // Load translation files required by page $langs->loadLangs(array( @@ -53,7 +58,9 @@ $cancelbutton = GETPOST('cancel', 'alpha'); // Security check $id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); -if ($user->socid) $id = $user->socid; +if ($user->socid) { + $id = $user->socid; +} $result = restrictedArea($user, 'societe&fournisseur', $id, '&societe', '', 'rowid'); $object = new Fournisseur($db); @@ -81,44 +88,48 @@ if ($object->id > 0) { $parameters = array('id'=>$id); $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 ($cancelbutton) - { +if (empty($reshook)) { + if ($cancelbutton) { $action = ""; } - if ($action == 'setsupplieraccountancycode') - { + if ($action == 'setsupplieraccountancycode') { $result = $object->fetch($id); - $object->code_compta_fournisseur = $_POST["supplieraccountancycode"]; + $object->code_compta_fournisseur = GETPOST("supplieraccountancycode"); $result = $object->update($object->id, $user, 1, 0, 1); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // terms of the settlement - if ($action == 'setconditions' && $user->rights->societe->creer) - { + if ($action == 'setconditions' && $user->rights->societe->creer) { $object->fetch($id); $result = $object->setPaymentTerms(GETPOST('cond_reglement_supplier_id', 'int')); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + dol_print_error($db, $object->error); + } } // mode de reglement - if ($action == 'setmode' && $user->rights->societe->creer) - { + if ($action == 'setmode' && $user->rights->societe->creer) { $object->fetch($id); $result = $object->setPaymentMethods(GETPOST('mode_reglement_supplier_id', 'int')); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + dol_print_error($db, $object->error); + } } // update supplier order min amount - if ($action == 'setsupplier_order_min_amount') - { + if ($action == 'setsupplier_order_min_amount') { $object->fetch($id); $object->supplier_order_min_amount = price2num(GETPOST('supplier_order_min_amount', 'alpha')); $result = $object->update($object->id, $user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } if ($action == 'update_extras') { @@ -129,15 +140,20 @@ if (empty($reshook)) // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; - - if (!$error) - { - $result = $object->insertExtraFields('COMPANY_MODIFY'); - if ($result < 0) $error++; + if ($ret < 0) { + $error++; } - if ($error) $action = 'edit_extras'; + if (!$error) { + $result = $object->insertExtraFields('COMPANY_MODIFY'); + if ($result < 0) { + $error++; + } + } + + if ($error) { + $action = 'edit_extras'; + } } } @@ -149,17 +165,19 @@ if (empty($reshook)) $contactstatic = new Contact($db); $form = new Form($db); -if ($id > 0 && empty($object->id)) -{ +if ($id > 0 && empty($object->id)) { // Load data of third party $res = $object->fetch($id); - if ($object->id <= 0) dol_print_error($db, $object->error); + if ($object->id <= 0) { + dol_print_error($db, $object->error); + } } -if ($object->id > 0) -{ +if ($object->id > 0) { $title = $langs->trans("ThirdParty")." - ".$langs->trans('Supplier'); - if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name." - ".$langs->trans('Supplier'); + if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name." - ".$langs->trans('Supplier'); + } $help_url = ''; llxHeader('', $title, $help_url); @@ -177,29 +195,27 @@ if ($object->id > 0) print '<div class="fichecenter"><div class="fichehalfleft">'; print '<div class="underbanner clearboth"></div>'; - print '<table width="100%" class="border">'; + print '<table class="border centpercent tableforfield">'; // Type Prospect/Customer/Supplier print '<tr><td class="titlefield">'.$langs->trans('NatureOfThirdParty').'</td><td>'; print $object->getTypeUrl(1); print '</td></tr>'; - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td>'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>'; } - if ($object->fournisseur) - { + if ($object->fournisseur) { print '<tr>'; - print '<td class="titlefield">'.$langs->trans("SupplierCode").'</td><td>'; - print $object->code_fournisseur; - $tmpcheck = $object->check_codefournisseur(); - if ($tmpcheck != 0 && $tmpcheck != -5) { - print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; - } - print '</td>'; - print '</tr>'; + print '<td class="titlefield">'.$langs->trans("SupplierCode").'</td><td>'; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_fournisseur)); + $tmpcheck = $object->check_codefournisseur(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; + } + print '</td>'; + print '</tr>'; $langs->load('compta'); print '<tr>'; @@ -221,14 +237,12 @@ if ($object->id > 0) print '</tr>'; // Local Taxes - if ($mysoc->useLocalTax(1)) - { + if ($mysoc->useLocalTax(1)) { print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td>'; print yn($object->localtax1_assuj); print '</td></tr>'; } - if ($mysoc->useLocalTax(2)) - { + if ($mysoc->useLocalTax(2)) { print '<tr><td>'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td>'; print yn($object->localtax2_assuj); print '</td></tr>'; @@ -236,7 +250,7 @@ if ($object->id > 0) // TVA Intra print '<tr><td class="nowrap">'.$langs->trans('VATIntra').'</td><td>'; - print $object->tva_intra; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->tva_intra)); print '</td></tr>'; // Default terms of the settlement @@ -246,11 +260,12 @@ if ($object->id > 0) print '<table width="100%" class="nobordernopadding"><tr><td>'; print $langs->trans('PaymentConditions'); print '<td>'; - if (($action != 'editconditions') && $user->rights->societe->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;socid='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>'; + if (($action != 'editconditions') && $user->rights->societe->creer) { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;socid='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; - if ($action == 'editconditions') - { + if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->cond_reglement_supplier_id, 'cond_reglement_supplier_id', -1, 1); } else { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->cond_reglement_supplier_id, 'none'); @@ -263,11 +278,12 @@ if ($object->id > 0) print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">'; print $langs->trans('PaymentMode'); print '<td>'; - if (($action != 'editmode') && $user->rights->societe->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;socid='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>'; + if (($action != 'editmode') && $user->rights->societe->creer) { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;socid='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; - if ($action == 'editmode') - { + if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->mode_reglement_supplier_id, 'mode_reglement_supplier_id', 'DBIT', 1, 1); } else { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->mode_reglement_supplier_id, 'none'); @@ -280,8 +296,7 @@ if ($object->id > 0) print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">'; print $langs->trans("CustomerRelativeDiscountShort"); print '<td><td class="right">'; - if ($user->rights->societe->creer && !$user->socid > 0) - { + if ($user->rights->societe->creer && !$user->socid > 0) { print '<a class="editfielda" href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$object->id.'">'.img_edit($langs->trans("Modify")).'</a>'; } print '</td></tr></table>'; @@ -294,22 +309,24 @@ if ($object->id > 0) print '<tr><td class="nowrap">'; print $langs->trans("CustomerAbsoluteDiscountShort"); print '<td><td class="right">'; - if ($user->rights->societe->creer && !$user->socid > 0) - { + if ($user->rights->societe->creer && !$user->socid > 0) { print '<a class="editfielda" href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$object->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$object->id).'">'.img_edit($langs->trans("Modify")).'</a>'; } print '</td></tr></table>'; print '</td>'; print '<td>'; $amount_discount = $object->getAvailableDiscounts('', '', 0, 1); - if ($amount_discount < 0) dol_print_error($db, $object->error); - if ($amount_discount > 0) print '<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$object->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$object->id).'">'.price($amount_discount, 1, $langs, 1, -1, -1, $conf->currency).'</a>'; + if ($amount_discount < 0) { + dol_print_error($db, $object->error); + } + if ($amount_discount > 0) { + print '<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$object->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$object->id).'">'.price($amount_discount, 1, $langs, 1, -1, -1, $conf->currency).'</a>'; + } //else print $langs->trans("DiscountNone"); print '</td>'; print '</tr>'; - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)) { print '<tr class="nowrap">'; print '<td>'; print $form->editfieldkey("OrderMinAmount", 'supplier_order_min_amount', $object->supplier_order_min_amount, $object, $user->rights->societe->creer); @@ -321,8 +338,7 @@ if ($object->id > 0) } // Categories - if (!empty($conf->categorie->enabled)) - { + if (!empty($conf->categorie->enabled)) { $langs->load("categories"); print '<tr><td>'.$langs->trans("SuppliersCategoriesShort").'</td>'; print '<td>'; @@ -335,16 +351,14 @@ if ($object->id > 0) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; // Module Adherent - if (!empty($conf->adherent->enabled)) - { + if (!empty($conf->adherent->enabled)) { $langs->load("members"); $langs->load("users"); print '<tr><td>'.$langs->trans("LinkedToDolibarrMember").'</td>'; print '<td>'; $adh = new Adherent($db); $result = $adh->fetch('', '', $object->id); - if ($result > 0) - { + if ($result > 0) { $adh->ref = $adh->getFullName($langs); print $adh->getNomUrl(1); } else { @@ -371,8 +385,7 @@ if ($object->id > 0) $boxstat .= '<table summary="'.dol_escape_htmltag($langs->trans("DolibarrStateBoard")).'" class="border boxtable boxtablenobottom boxtablenotop" width="100%">'; $boxstat .= '<tr class="impair nohover"><td colspan="2" class="tdboxstats nohover">'; - if ($conf->supplier_proposal->enabled) - { + if ($conf->supplier_proposal->enabled) { // Box proposals $tmp = $object->getOutstandingProposals('supplier'); $outstandingOpened = $tmp['opened']; @@ -381,16 +394,19 @@ if ($object->id > 0) $text = $langs->trans("OverAllSupplierProposals"); $link = DOL_URL_ROOT.'/supplier_proposal/list.php?socid='.$object->id; $icon = 'bill'; - if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + if ($link) { + $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + } $boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">'; $boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' <span>'.$text.'</span></span><br>'; $boxstat .= '<span class="boxstatsindicator">'.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).'</span>'; $boxstat .= '</div>'; - if ($link) $boxstat .= '</a>'; + if ($link) { + $boxstat .= '</a>'; + } } - if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) - { + if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) { // Box proposals $tmp = $object->getOutstandingOrders('supplier'); $outstandingOpened = $tmp['opened']; @@ -399,16 +415,19 @@ if ($object->id > 0) $text = $langs->trans("OverAllOrders"); $link = DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->id; $icon = 'bill'; - if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + if ($link) { + $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + } $boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">'; $boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' <span>'.$text.'</span></span><br>'; $boxstat .= '<span class="boxstatsindicator">'.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).'</span>'; $boxstat .= '</div>'; - if ($link) $boxstat .= '</a>'; + if ($link) { + $boxstat .= '</a>'; + } } - if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) - { + if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) { $tmp = $object->getOutstandingBills('supplier'); $outstandingOpened = $tmp['opened']; $outstandingTotal = $tmp['total_ht']; @@ -417,23 +436,31 @@ if ($object->id > 0) $text = $langs->trans("OverAllInvoices"); $link = DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->id; $icon = 'bill'; - if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + if ($link) { + $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + } $boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">'; $boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' <span>'.$text.'</span></span><br>'; $boxstat .= '<span class="boxstatsindicator">'.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).'</span>'; $boxstat .= '</div>'; - if ($link) $boxstat .= '</a>'; + if ($link) { + $boxstat .= '</a>'; + } // Box outstanding bill $text = $langs->trans("CurrentOutstandingBill"); $link = DOL_URL_ROOT.'/fourn/recap-fourn.php?socid='.$object->id; $icon = 'bill'; - if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + if ($link) { + $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + } $boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">'; $boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' <span>'.$text.'</span></span><br>'; $boxstat .= '<span class="boxstatsindicator'.($outstandingOpened > 0 ? ' amountremaintopay' : '').'">'.price($outstandingOpened, 1, $langs, 1, -1, -1, $conf->currency).$warn.'</span>'; $boxstat .= '</div>'; - if ($link) $boxstat .= '</a>'; + if ($link) { + $boxstat .= '</a>'; + } $tmp = $object->getOutstandingBills('supplier', 1); $outstandingOpenedLate = $tmp['opened']; @@ -441,12 +468,16 @@ if ($object->id > 0) $text = $langs->trans("CurrentOutstandingBillLate"); $link = DOL_URL_ROOT.'/fourn/recap-fourn.php?socid='.$object->id; $icon = 'bill'; - if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + if ($link) { + $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + } $boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">'; $boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' <span>'.$text.'</span></span><br>'; $boxstat .= '<span class="boxstatsindicator'.($outstandingOpenedLate > 0 ? ' amountremaintopay' : '').'">'.price($outstandingOpenedLate, 1, $langs, 1, -1, -1, $conf->currency).$warn.'</span>'; $boxstat .= '</div>'; - if ($link) $boxstat .= '</a>'; + if ($link) { + $boxstat .= '</a>'; + } } } @@ -468,13 +499,12 @@ if ($object->id > 0) print '</tr>'; print '</table>'; print '<br>'; - */ + */ /* * List of products */ - if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) - { + if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) { $langs->load("products"); //Query from product/liste.php $sql = 'SELECT p.rowid, p.ref, p.label, p.fk_product_type, p.entity,'; @@ -487,7 +517,9 @@ if ($object->id > 0) $sql .= $db->plimit($MAXLIST); $query = $db->query($sql); - if (!$query) dol_print_error($db); + if (!$query) { + dol_print_error($db); + } $num = $db->num_rows($query); @@ -498,12 +530,10 @@ if ($object->id > 0) print '</a></td></tr>'; $return = array(); - if ($num > 0) - { + if ($num > 0) { $productstatic = new Product($db); - while ($objp = $db->fetch_object($query)) - { + while ($objp = $db->fetch_object($query)) { $productstatic->id = $objp->rowid; $productstatic->ref = $objp->ref; $productstatic->label = $objp->label; @@ -523,11 +553,9 @@ if ($object->id > 0) //print '<td class="right" class="nowrap">'.dol_print_date($objp->tms, 'day').'</td>'; print '<td class="right">'; //print (isset($objp->unitprice) ? price($objp->unitprice) : ''); - if (isset($objp->price)) - { + if (isset($objp->price)) { print price($objp->price); - if ($objp->quantity > 1) - { + if ($objp->quantity > 1) { print ' / '; print $objp->quantity; } @@ -546,11 +574,10 @@ if ($object->id > 0) */ $proposalstatic = new SupplierProposal($db); - if ($user->rights->supplier_proposal->lire) - { + if ($user->rights->supplier_proposal->lire) { $langs->loadLangs(array("supplier_proposal")); - $sql = "SELECT p.rowid, p.ref, p.date_valid as dc, p.fk_statut, p.total_ht, p.tva as total_tva, p.total as total_ttc"; + $sql = "SELECT p.rowid, p.ref, p.date_valid as dc, p.fk_statut, p.total_ht, p.total_tva, p.total_ttc"; $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p "; $sql .= " WHERE p.fk_soc =".$object->id; $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; @@ -558,13 +585,11 @@ if ($object->id > 0) $sql .= " ".$db->plimit($MAXLIST); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { print '<table class="noborder centpercent lastrecordtable">'; print '<tr class="liste_titre">'; @@ -576,8 +601,7 @@ if ($object->id > 0) print '</td></tr>'; } - while ($i < $num && $i <= $MAXLIST) - { + while ($i < $num && $i <= $MAXLIST) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -590,8 +614,7 @@ if ($object->id > 0) print $proposalstatic->getNomUrl(1); print '</td>'; print '<td class="center" width="80">'; - if ($obj->dc) - { + if ($obj->dc) { print dol_print_date($db->jdate($obj->dc), 'day'); } else { print "-"; @@ -603,7 +626,9 @@ if ($object->id > 0) } $db->free($resql); - if ($num > 0) print "</table>"; + if ($num > 0) { + print "</table>"; + } } else { dol_print_error($db); } @@ -614,8 +639,7 @@ if ($object->id > 0) */ $orderstatic = new CommandeFournisseur($db); - if ($user->rights->fournisseur->commande->lire) - { + if ($user->rights->fournisseur->commande->lire) { // TODO move to DAO class // Check if there are supplier orders billable $sql2 = 'SELECT s.nom, s.rowid as socid, s.client, c.rowid, c.ref, c.total_ht, c.ref_supplier,'; @@ -626,8 +650,7 @@ if ($object->id > 0) $sql2 .= " AND c.entity IN (".getEntity('commande_fournisseur').")"; $sql2 .= ' AND s.rowid = '.$object->id; // Show orders we can bill - if (empty($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS)) - { + if (empty($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS)) { $sql2 .= " AND c.fk_statut IN (".$db->sanitize(CommandeFournisseur::STATUS_RECEIVED_COMPLETELY).")"; // Must match filter in htdocs/fourn/commande/list.php } else { // CommandeFournisseur::STATUS_ORDERSENT.", ".CommandeFournisseur::STATUS_RECEIVED_PARTIALLY.", ".CommandeFournisseur::STATUS_RECEIVED_COMPLETELY @@ -651,25 +674,22 @@ if ($object->id > 0) $sql .= " WHERE p.fk_soc =".$object->id; $sql .= " AND p.entity IN (".getEntity('commande_fournisseur').")"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $object_count = $db->fetch_object($resql); $num = $object_count->total; } - $sql = "SELECT p.rowid,p.ref, p.date_commande as dc, p.fk_statut, p.total_ht, p.tva as total_tva, p.total_ttc"; + $sql = "SELECT p.rowid,p.ref, p.date_commande as dc, p.fk_statut, p.total_ht, p.total_tva, p.total_ttc"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as p"; $sql .= " WHERE p.fk_soc =".$object->id; $sql .= " AND p.entity IN (".getEntity('commande_fournisseur').")"; $sql .= " ORDER BY p.date_commande DESC"; $sql .= " ".$db->plimit($MAXLIST); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; - if ($num > 0) - { + if ($num > 0) { print '<table class="noborder centpercent lastrecordtable">'; print '<tr class="liste_titre">'; @@ -681,8 +701,7 @@ if ($object->id > 0) print '</td></tr>'; } - while ($i < $num && $i < $MAXLIST) - { + while ($i < $num && $i < $MAXLIST) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -695,8 +714,7 @@ if ($object->id > 0) print $orderstatic->getNomUrl(1); print '</td>'; print '<td class="center" width="80">'; - if ($obj->dc) - { + if ($obj->dc) { print dol_print_date($db->jdate($obj->dc), 'day'); } else { print "-"; @@ -708,7 +726,9 @@ if ($object->id > 0) } $db->free($resql); - if ($num > 0) print "</table>"; + if ($num > 0) { + print "</table>"; + } } else { dol_print_error($db); } @@ -721,8 +741,7 @@ if ($object->id > 0) $langs->load('bills'); $facturestatic = new FactureFournisseur($db); - if ($user->rights->fournisseur->facture->lire) - { + if ($user->rights->fournisseur->facture->lire) { // TODO move to DAO class $sql = 'SELECT f.rowid, f.libelle as label, f.ref, f.ref_supplier, f.fk_statut, f.datef as df, f.total_ht, f.total_tva, f.total_ttc as amount,f.paye,'; $sql .= ' SUM(pf.amount) as am'; @@ -733,12 +752,10 @@ if ($object->id > 0) $sql .= ' GROUP BY f.rowid,f.libelle,f.ref,f.ref_supplier,f.fk_statut,f.datef,f.total_ht,f.total_tva,f.total_ttc,f.paye'; $sql .= ' ORDER BY f.datef DESC'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { print '<table class="noborder centpercent lastrecordtable">'; print '<tr class="liste_titre">'; @@ -749,8 +766,7 @@ if ($object->id > 0) print '</td></tr>'; } - while ($i < min($num, $MAXLIST)) - { + while ($i < min($num, $MAXLIST)) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -777,7 +793,9 @@ if ($object->id > 0) $i++; } $db->free($resql); - if ($num > 0) print '</table>'; + if ($num > 0) { + print '</table>'; + } } else { dol_print_error($db); } @@ -790,22 +808,19 @@ if ($object->id > 0) /* - * Barre d'actions + * Action bar */ print '<div class="tabsAction">'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { - if ($object->status != 1) - { + if (empty($reshook)) { + if ($object->status != 1) { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("ThirdPartyIsClosed")).'" href="#">'.$langs->trans("ThirdPartyIsClosed").'</a></div>'; } - if ($conf->supplier_proposal->enabled && $user->rights->supplier_proposal->creer) - { + if ($conf->supplier_proposal->enabled && $user->rights->supplier_proposal->creer) { $langs->load("supplier_proposal"); if ($object->status == 1) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/supplier_proposal/card.php?action=create&socid='.$object->id.'">'.$langs->trans("AddSupplierProposal").'</a>'; @@ -814,8 +829,7 @@ if ($object->id > 0) } } - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { $langs->load("orders"); if ($object->status == 1) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/commande/card.php?action=create&socid='.$object->id.'">'.$langs->trans("AddOrder").'</a>'; @@ -824,21 +838,20 @@ if ($object->id > 0) } } - if ($user->rights->fournisseur->facture->creer) - { - if (!empty($orders2invoice) && $orders2invoice > 0) - { + if ($user->rights->fournisseur->facture->creer) { + if (!empty($orders2invoice) && $orders2invoice > 0) { if ($object->status == 1) { // Company is open print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->id.'&search_billed=0&autoselectall=1">'.$langs->trans("CreateInvoiceForThisSupplier").'</a></div>'; } else { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans("CreateInvoiceForThisCustomer").'</a></div>'; } - } else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("NoOrdersToInvoice").' ('.$langs->trans("WithReceptionFinished").')').'" href="#">'.$langs->trans("CreateInvoiceForThisCustomer").'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("NoOrdersToInvoice").' ('.$langs->trans("WithReceptionFinished").')').'" href="#">'.$langs->trans("CreateInvoiceForThisCustomer").'</a></div>'; + } } - if ($user->rights->fournisseur->facture->creer) - { + if ($user->rights->fournisseur->facture->creer) { $langs->load("bills"); if ($object->status == 1) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?action=create&socid='.$object->id.'">'.$langs->trans("AddBill").'</a>'; @@ -848,10 +861,8 @@ if ($object->id > 0) } // Add action - if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1) - { - if ($user->rights->agenda->myactions->create) - { + if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1) { + if ($user->rights->agenda->myactions->create) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&socid='.$object->id.'">'.$langs->trans("AddAction").'</a>'; } else { print '<a class="butAction" title="'.dol_escape_js($langs->trans("NotAllowed")).'" href="#">'.$langs->trans("AddAction").'</a>'; @@ -862,15 +873,13 @@ if ($object->id > 0) print '</div>'; - if (!empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD)) - { + if (!empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD)) { print '<br>'; // List of contacts show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id); } - if (!empty($conf->global->MAIN_REPEATTASKONEACHTAB)) - { + if (!empty($conf->global->MAIN_REPEATTASKONEACHTAB)) { print load_fiche_titre($langs->trans("ActionsOnCompany"), '', ''); // List of todo actions diff --git a/htdocs/fourn/class/api_supplier_invoices.class.php b/htdocs/fourn/class/api_supplier_invoices.class.php index 247434be7a8..953092120e4 100644 --- a/htdocs/fourn/class/api_supplier_invoices.class.php +++ b/htdocs/fourn/class/api_supplier_invoices.class.php @@ -34,7 +34,7 @@ class SupplierInvoices extends DolibarrApi * * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'socid', ); @@ -109,20 +109,32 @@ class SupplierInvoices extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) - if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; + if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; + } $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as t"; // We need this table joined to the select in order to filter by sale - if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= ' WHERE t.entity IN ('.getEntity('supplier_invoice').')'; - if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Filter by status if ($status == 'draft') { @@ -142,10 +154,8 @@ class SupplierInvoices extends DolibarrApi $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -154,8 +164,7 @@ class SupplierInvoices extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -168,8 +177,7 @@ class SupplierInvoices extends DolibarrApi $i = 0; $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $invoice_static = new FactureFournisseur($this->db); if ($invoice_static->fetch($obj->rowid)) { @@ -244,12 +252,15 @@ class SupplierInvoices extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->invoice->$field = $value; } - if ($this->invoice->update($id, DolibarrApiAccess::$user)) + if ($this->invoice->update($id, DolibarrApiAccess::$user)) { return $this->get($id); + } return false; } @@ -279,8 +290,7 @@ class SupplierInvoices extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if ($this->invoice->delete(DolibarrApiAccess::$user) < 0) - { + if ($this->invoice->delete(DolibarrApiAccess::$user) < 0) { throw new RestException(500); } @@ -459,16 +469,14 @@ class SupplierInvoices extends DolibarrApi $paiement->note_public = $comment; $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices - if ($paiement_id < 0) - { + if ($paiement_id < 0) { $this->db->rollback(); throw new RestException(400, 'Payment error : '.$paiement->error); } if (!empty($conf->banque->enabled)) { $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, $chqemetteur, $chqbank); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); throw new RestException(400, 'Add payment to bank error : '.$paiement->error); } @@ -706,8 +714,9 @@ class SupplierInvoices extends DolibarrApi { $invoice = array(); foreach (SupplierInvoices::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $invoice[$field] = $data[$field]; } return $invoice; diff --git a/htdocs/fourn/class/api_supplier_orders.class.php b/htdocs/fourn/class/api_supplier_orders.class.php index 254e577f2f2..d75abb17e90 100644 --- a/htdocs/fourn/class/api_supplier_orders.class.php +++ b/htdocs/fourn/class/api_supplier_orders.class.php @@ -32,7 +32,7 @@ class SupplierOrders extends DolibarrApi * * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'socid' ); @@ -108,41 +108,70 @@ class SupplierOrders extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } - if (!empty($product_ids)) $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product + if (!empty($product_ids)) { + $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product + } $sql .= ' WHERE t.entity IN ('.getEntity('supplier_order').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if (!empty($product_ids)) $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$product_ids.")"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if (!empty($product_ids)) { + $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$product_ids.")"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Filter by status - if ($status == 'draft') $sql .= " AND t.fk_statut IN (0)"; - if ($status == 'validated') $sql .= " AND t.fk_statut IN (1)"; - if ($status == 'approved') $sql .= " AND t.fk_statut IN (2)"; - if ($status == 'running') $sql .= " AND t.fk_statut IN (3)"; - if ($status == 'received_start') $sql .= " AND t.fk_statut IN (4)"; - if ($status == 'received_end') $sql .= " AND t.fk_statut IN (5)"; - if ($status == 'cancelled') $sql .= " AND t.fk_statut IN (6,7)"; - if ($status == 'refused') $sql .= " AND t.fk_statut IN (9)"; + if ($status == 'draft') { + $sql .= " AND t.fk_statut IN (0)"; + } + if ($status == 'validated') { + $sql .= " AND t.fk_statut IN (1)"; + } + if ($status == 'approved') { + $sql .= " AND t.fk_statut IN (2)"; + } + if ($status == 'running') { + $sql .= " AND t.fk_statut IN (3)"; + } + if ($status == 'received_start') { + $sql .= " AND t.fk_statut IN (4)"; + } + if ($status == 'received_end') { + $sql .= " AND t.fk_statut IN (5)"; + } + if ($status == 'cancelled') { + $sql .= " AND t.fk_statut IN (6,7)"; + } + if ($status == 'refused') { + $sql .= " AND t.fk_statut IN (9)"; + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -151,8 +180,7 @@ class SupplierOrders extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -161,13 +189,11 @@ class SupplierOrders extends DolibarrApi } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $i = 0; $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $order_static = new CommandeFournisseur($this->db); if ($order_static->fetch($obj->rowid)) { @@ -207,13 +233,13 @@ class SupplierOrders extends DolibarrApi $this->order->date = dol_now(); } /* We keep lines as an array - if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->order->lines = $lines; - }*/ + if (isset($request_data["lines"])) { + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->order->lines = $lines; + }*/ if ($this->order->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating order", array_merge(array($this->order->error), $this->order->errors)); @@ -244,12 +270,15 @@ class SupplierOrders extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->order->$field = $value; } - if ($this->order->update($id, DolibarrApiAccess::$user)) + if ($this->order->update(DolibarrApiAccess::$user)) { return $this->get($id); + } return false; } @@ -368,8 +397,9 @@ class SupplierOrders extends DolibarrApi { $order = array(); foreach (SupplierOrders::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $order[$field] = $data[$field]; } return $order; diff --git a/htdocs/fourn/class/fournisseur.class.php b/htdocs/fourn/class/fournisseur.class.php index 4ca073a38c7..1ab1095a191 100644 --- a/htdocs/fourn/class/fournisseur.class.php +++ b/htdocs/fourn/class/fournisseur.class.php @@ -62,12 +62,10 @@ class Fournisseur extends Societe $sql .= " WHERE cf.fk_soc = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num == 1) - { + if ($num == 1) { $row = $this->db->fetch_row($resql); $this->single_open_commande = $row[0]; @@ -91,8 +89,7 @@ class Fournisseur extends Societe $sql .= " AND pfp.fk_soc = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); return $obj->nb; } else { @@ -116,8 +113,7 @@ class Fournisseur extends Societe $sql = "SELECT count(s.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -126,10 +122,8 @@ class Fournisseur extends Societe $sql .= " AND s.entity IN (".getEntity('societe').")"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["suppliers"] = $obj->nb; } $this->db->free($resql); @@ -158,8 +152,7 @@ class Fournisseur extends Societe dol_syslog("Fournisseur::CreateCategory", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { dol_syslog("Fournisseur::CreateCategory : Success"); return 0; } else { @@ -185,17 +178,19 @@ class Fournisseur extends Societe $sql = "SELECT s.rowid, s.nom as name"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE s.fournisseur = 1"; $sql .= " AND s.entity IN (".getEntity('societe').")"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $arr[$obj->rowid] = $obj->name; } } else { @@ -204,4 +199,21 @@ class Fournisseur extends Societe } return $arr; } + + /** + * Function used to replace a thirdparty id with another one. + * + * @param DoliDB $db Database handler + * @param int $origin_id Old third-party id + * @param int $dest_id New third-party id + * @return bool + */ + public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id) + { + $tables = array( + 'facture_fourn' + ); + + return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); + } } diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index 58b39cba8d6..1c9ed333fae 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -34,7 +34,9 @@ include_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -if (!empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; +if (!empty($conf->productbatch->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; +} require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; /** @@ -139,6 +141,8 @@ class CommandeFournisseur extends CommonOrder public $cond_reglement_id; public $cond_reglement_code; + public $cond_reglement_label; // Label + public $cond_reglement_doc; // Label on documents /** * @var int ID @@ -202,7 +206,7 @@ class CommandeFournisseur extends CommonOrder 'amount_ht' =>array('type'=>'double(24,8)', 'label'=>'Amount ht', 'enabled'=>1, 'visible'=>-1, 'position'=>115), 'remise_percent' =>array('type'=>'double', 'label'=>'Remise percent', 'enabled'=>1, 'visible'=>-1, 'position'=>120), 'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>125), - 'tva' =>array('type'=>'double(24,8)', 'label'=>'Tva', 'enabled'=>1, 'visible'=>-1, 'position'=>130, 'isameasure'=>1), + 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'Tva', 'enabled'=>1, 'visible'=>-1, 'position'=>130, 'isameasure'=>1), 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'Localtax1', 'enabled'=>1, 'visible'=>-1, 'position'=>135, 'isameasure'=>1), 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'Localtax2', 'enabled'=>1, 'visible'=>-1, 'position'=>140, 'isameasure'=>1), 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>145, 'isameasure'=>1), @@ -301,9 +305,11 @@ class CommandeFournisseur extends CommonOrder global $conf; // Check parameters - if (empty($id) && empty($ref)) return -1; + if (empty($id) && empty($ref)) { + return -1; + } - $sql = "SELECT c.rowid, c.entity, c.ref, ref_supplier, c.fk_soc, c.fk_statut, c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_vat,"; + $sql = "SELECT c.rowid, c.entity, c.ref, ref_supplier, c.fk_soc, c.fk_statut, c.amount_ht, c.total_ht, c.total_ttc, c.total_tva,"; $sql .= " c.localtax1, c.localtax2, "; $sql .= " c.date_creation, c.date_valid, c.date_approve, c.date_approve2,"; $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_approve, c.fk_user_approve2,"; @@ -312,7 +318,7 @@ class CommandeFournisseur extends CommonOrder $sql .= " c.note_private, c.note_public, c.model_pdf, c.extraparams, c.billed,"; $sql .= " c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc,"; $sql .= " cm.libelle as methode_commande,"; - $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc,"; + $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_label, cr.libelle_facture as cond_reglement_doc,"; $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle"; $sql .= ', c.fk_incoterms, c.location_incoterms'; $sql .= ', i.libelle as label_incoterms'; @@ -322,18 +328,21 @@ class CommandeFournisseur extends CommonOrder $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_input_method as cm ON cm.rowid = c.fk_input_method"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid'; - if (empty($id)) $sql .= " WHERE c.entity IN (".getEntity('supplier_order').")"; - else $sql .= " WHERE c.rowid=".$id; + if (empty($id)) { + $sql .= " WHERE c.entity IN (".getEntity('supplier_order').")"; + } else { + $sql .= " WHERE c.rowid=".$id; + } - if ($ref) $sql .= " AND c.ref='".$this->db->escape($ref)."'"; + if ($ref) { + $sql .= " AND c.ref='".$this->db->escape($ref)."'"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if (!$obj) - { + if (!$obj) { $this->error = 'Bill with id '.$id.' not found'; dol_syslog(get_class($this).'::fetch '.$this->error); return 0; @@ -354,7 +363,7 @@ class CommandeFournisseur extends CommonOrder $this->user_approve_id = $obj->fk_user_approve; $this->user_approve_id2 = $obj->fk_user_approve2; $this->total_ht = $obj->total_ht; - $this->total_tva = $obj->total_vat; + $this->total_tva = $obj->total_tva; $this->total_localtax1 = $obj->localtax1; $this->total_localtax2 = $obj->localtax2; $this->total_ttc = $obj->total_ttc; @@ -373,8 +382,9 @@ class CommandeFournisseur extends CommonOrder $this->fk_project = $obj->fk_project; $this->cond_reglement_id = $obj->fk_cond_reglement; $this->cond_reglement_code = $obj->cond_reglement_code; - $this->cond_reglement = $obj->cond_reglement_libelle; - $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; + $this->cond_reglement = $obj->cond_reglement_label; // deprecated + $this->cond_reglement_label = $obj->cond_reglement_label; + $this->cond_reglement_doc = $obj->cond_reglement_doc; $this->fk_account = $obj->fk_account; $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; @@ -406,14 +416,15 @@ class CommandeFournisseur extends CommonOrder // fetch optionals attributes and labels $this->fetch_optionals(); - if ($this->statut == 0) $this->brouillon = 1; + if ($this->statut == 0) { + $this->brouillon = 1; + } /* - * Lines - */ + * Lines + */ $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { return -1; } else { return 1; @@ -446,26 +457,28 @@ class CommandeFournisseur extends CommonOrder $sql .= " l.fk_unit,"; $sql .= " l.date_start, l.date_end,"; $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc'; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $sql .= ", pfp.rowid as fk_pfp, pfp.packaging"; - $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as l"; + } + $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as l"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON l.fk_product = pfp.fk_product and l.ref = pfp.ref_fourn"; + } $sql .= " WHERE l.fk_commande = ".$this->id; - if ($only_product) $sql .= ' AND p.fk_product_type = 0'; + if ($only_product) { + $sql .= ' AND p.fk_product_type = 0'; + } $sql .= " ORDER BY l.rang, l.rowid"; //print $sql; dol_syslog(get_class($this)."::fetch get lines", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($result); $line = new CommandeFournisseurLigne($this->db); @@ -502,8 +515,7 @@ class CommandeFournisseur extends CommonOrder $line->ref_fourn = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since $line->ref_supplier = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) - { + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $line->fk_fournprice = $objp->fk_pfp; $line->packaging = $objp->packaging; } @@ -560,8 +572,7 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::valid"); $result = 0; if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->commande->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_order_advance->validate))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_order_advance->validate))) { $this->db->begin(); // Definition of supplier order numbering model name @@ -569,8 +580,7 @@ class CommandeFournisseur extends CommonOrder $soc->fetch($this->fourn_id); // Check if object has a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life - { + if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($soc); } else { $num = $this->ref; @@ -586,49 +596,46 @@ class CommandeFournisseur extends CommonOrder $sql .= " AND fk_statut = ".self::STATUS_DRAFT; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'fournisseur/commande/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/commande/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->fournisseur->commande->dir_output.'/'.$oldref; $dirdest = $conf->fournisseur->commande->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->fournisseur->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -640,15 +647,13 @@ class CommandeFournisseur extends CommonOrder } } - if (!$error) - { + if (!$error) { $result = 1; $this->statut = self::STATUS_VALIDATED; $this->ref = $num; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -693,8 +698,11 @@ class CommandeFournisseur extends CommonOrder $this->statuts[0] = 'StatusSupplierOrderDraft'; $this->statuts[1] = 'StatusSupplierOrderValidated'; $this->statuts[2] = 'StatusSupplierOrderApproved'; - if (empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $this->statuts[3] = 'StatusSupplierOrderOnProcess'; - else $this->statuts[3] = 'StatusSupplierOrderOnProcessWithValidation'; + if (empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) { + $this->statuts[3] = 'StatusSupplierOrderOnProcess'; + } else { + $this->statuts[3] = 'StatusSupplierOrderOnProcessWithValidation'; + } $this->statuts[4] = 'StatusSupplierOrderReceivedPartially'; $this->statuts[5] = 'StatusSupplierOrderReceivedAll'; $this->statuts[6] = 'StatusSupplierOrderCanceled'; // Approved->Canceled @@ -734,7 +742,9 @@ class CommandeFournisseur extends CommonOrder if ($billed) { $billedtext = ' - '.$langs->trans("Billed"); } - if ($status == 5 && $billed) $statusClass = 'status6'; + if ($status == 5 && $billed) { + $statusClass = 'status6'; + } $statusLong = $langs->transnoentitiesnoconv($this->statuts[$status]).$billedtext; $statusShort = $langs->transnoentitiesnoconv($this->statutshort[$status]); @@ -789,19 +799,20 @@ class CommandeFournisseur extends CommonOrder $picto = 'order'; $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id; - if ($option !== 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowOrder"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -814,15 +825,17 @@ class CommandeFournisseur extends CommonOrder $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; - if ($addlinktonotes) - { + if ($addlinktonotes) { $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { + if ($txttoshow) { $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1); $result .= ' <span class="note inline-block">'; $result .= '<a href="'.DOL_URL_ROOT.'/fourn/commande/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">'; @@ -850,8 +863,7 @@ class CommandeFournisseur extends CommonOrder global $db, $langs, $conf; $langs->load("orders"); - if (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER)) - { + if (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER)) { $mybool = false; $file = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER.'.php'; @@ -875,8 +887,7 @@ class CommandeFournisseur extends CommonOrder $obj = new $classname(); $numref = $obj->getNextValue($soc, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -897,8 +908,7 @@ class CommandeFournisseur extends CommonOrder { $error = 0; - if ($this->billed) - { + if ($this->billed) { return 0; } @@ -907,18 +917,17 @@ class CommandeFournisseur extends CommonOrder $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur SET billed = 1'; $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; - if ($this->db->query($sql)) - { - if (!$error) - { + if ($this->db->query($sql)) { + if (!$error) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->billed = 1; $this->db->commit(); @@ -952,8 +961,7 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::approve"); - if ($user->rights->fournisseur->commande->approuver) - { + if ($user->rights->fournisseur->commande->approuver) { $now = dol_now(); $this->db->begin(); @@ -963,8 +971,7 @@ class CommandeFournisseur extends CommonOrder $soc->fetch($this->fourn_id); // Check if object has a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life - { + if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($soc); } else { $num = $this->ref; @@ -977,14 +984,11 @@ class CommandeFournisseur extends CommonOrder $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; $sql .= " SET ref='".$this->db->escape($num)."',"; - if (empty($secondlevel)) // standard or first level approval - { + if (empty($secondlevel)) { // standard or first level approval $sql .= " date_approve='".$this->db->idate($now)."',"; $sql .= " fk_user_approve = ".$user->id; - if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) - { - if (empty($this->user_approve_id2)) - { + if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) { + if (empty($this->user_approve_id2)) { $movetoapprovestatus = false; // second level approval not done $comment = ' (first level)'; } @@ -993,67 +997,72 @@ class CommandeFournisseur extends CommonOrder { $sql .= " date_approve2='".$this->db->idate($now)."',"; $sql .= " fk_user_approve2 = ".$user->id; - if (empty($this->user_approve_id)) $movetoapprovestatus = false; // first level approval not done + if (empty($this->user_approve_id)) { + $movetoapprovestatus = false; // first level approval not done + } $comment = ' (second level)'; } // If double approval is required and first approval, we keep status to 1 = validated - if ($movetoapprovestatus) $sql .= ", fk_statut = ".self::STATUS_ACCEPTED; - else $sql .= ", fk_statut = ".self::STATUS_VALIDATED; + if ($movetoapprovestatus) { + $sql .= ", fk_statut = ".self::STATUS_ACCEPTED; + } else { + $sql .= ", fk_statut = ".self::STATUS_VALIDATED; + } $sql .= " WHERE rowid = ".$this->id; $sql .= " AND fk_statut = ".self::STATUS_VALIDATED; - if ($this->db->query($sql)) - { - if (!empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT)) - { + if ($this->db->query($sql)) { + if (!empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT)) { $result = $this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1); - if ($result < 0 && $result != -2) // -2 means already exists - { + if ($result < 0 && $result != -2) { // -2 means already exists $error++; } } // If stock is incremented on validate order, we must increment it - if (!$error && $movetoapprovestatus && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) - { + if (!$error && $movetoapprovestatus && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); $cpt = count($this->lines); - for ($i = 0; $i < $cpt; $i++) - { + for ($i = 0; $i < $cpt; $i++) { // Product with reference - if ($this->lines[$i]->fk_product > 0) - { + if ($this->lines[$i]->fk_product > 0) { $this->line = $this->lines[$i]; $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We decrement stock of product (and sub-products) $up_ht_disc = $this->lines[$i]->subprice; - if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU'); + if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) { + $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU'); + } $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr", $this->ref)); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } unset($this->line); } } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_APPROVE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->ref = $this->newref; - if ($movetoapprovestatus) $this->statut = self::STATUS_ACCEPTED; - else $this->statut = self::STATUS_VALIDATED; - if (empty($secondlevel)) // standard or first level approval - { + if ($movetoapprovestatus) { + $this->statut = self::STATUS_ACCEPTED; + } else { + $this->statut = self::STATUS_VALIDATED; + } + if (empty($secondlevel)) { // standard or first level approval $this->date_approve = $now; $this->user_approve_id = $user->id; } else // request a second level approval @@ -1093,26 +1102,24 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::refuse"); $result = 0; - if ($user->rights->fournisseur->commande->approuver) - { + if ($user->rights->fournisseur->commande->approuver) { $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".self::STATUS_REFUSED; $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $result = 0; - if ($error == 0) - { + if ($error == 0) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_REFUSE', $user); - if ($result < 0) - { + if ($result < 0) { $error++; $this->db->rollback(); - } else $this->db->commit(); + } else { + $this->db->commit(); + } // End call triggers } } else { @@ -1145,8 +1152,7 @@ class CommandeFournisseur extends CommonOrder //dol_syslog("CommandeFournisseur::Cancel"); $result = 0; - if ($user->rights->fournisseur->commande->commander) - { + if ($user->rights->fournisseur->commande->commander) { $statut = self::STATUS_CANCELED; $this->db->begin(); @@ -1154,17 +1160,17 @@ class CommandeFournisseur extends CommonOrder $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".$statut; $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::cancel", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $result = 0; // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_CANCEL', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if ($error == 0) - { + if ($error == 0) { $this->db->commit(); return 1; } else { @@ -1197,21 +1203,21 @@ class CommandeFournisseur extends CommonOrder global $langs; dol_syslog(get_class($this)."::commande"); $error = 0; - if ($user->rights->fournisseur->commande->commander) - { + if ($user->rights->fournisseur->commande->commander) { $this->db->begin(); $newnoteprivate = $this->note_private; - if ($comment) $newnoteprivate = dol_concatdesc($newnoteprivate, $langs->trans("Comment").': '.$comment); + if ($comment) { + $newnoteprivate = dol_concatdesc($newnoteprivate, $langs->trans("Comment").': '.$comment); + } $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; $sql .= " SET fk_statut=".self::STATUS_ORDERSENT.", fk_input_method=".$methode.", date_commande='".$this->db->idate($date)."', "; $sql .= " note_private='".$this->db->escape($newnoteprivate)."'"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::commande", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->statut = self::STATUS_ORDERSENT; $this->methode_commande_id = $methode; $this->date_commande = $date; @@ -1219,7 +1225,9 @@ class CommandeFournisseur extends CommonOrder // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } else { $error++; @@ -1227,8 +1235,7 @@ class CommandeFournisseur extends CommonOrder $this->errors[] = $this->db->lasterror(); } - if (!$error) - { + if (!$error) { $this->db->commit(); } else { $this->db->rollback(); @@ -1261,17 +1268,23 @@ class CommandeFournisseur extends CommonOrder // set tmp vars $date = ($this->date_commande ? $this->date_commande : $this->date); // in case of date is set - if (empty($date)) $date = $now; + if (empty($date)) { + $date = $now; + } $delivery_date = empty($this->delivery_date) ? $this->date_livraison : $this->delivery_date; // Clean parameters - if (empty($this->source)) $this->source = 0; + if (empty($this->source)) { + $this->source = 0; + } // 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)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date); - else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); - if (empty($this->fk_multicurrency)) - { + if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) { + list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date); + } else { + $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); + } + if (empty($this->fk_multicurrency)) { $this->multicurrency_code = $conf->currency; $this->fk_multicurrency = 0; $this->multicurrency_tx = 1; @@ -1303,7 +1316,7 @@ class CommandeFournisseur extends CommonOrder $sql .= ", multicurrency_tx"; $sql .= ") "; $sql .= " VALUES ("; - $sql .= "''"; + $sql .= "'(PROV)'"; $sql .= ", '".$this->db->escape($this->ref_supplier)."'"; $sql .= ", '".$this->db->escape($this->note_private)."'"; $sql .= ", '".$this->db->escape($this->note_public)."'"; @@ -1327,16 +1340,14 @@ class CommandeFournisseur extends CommonOrder $sql .= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."commande_fournisseur"); if ($this->id) { $num = count($this->lines); // insert products details into database - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $this->special_code = $this->lines[$i]->special_code; // TODO : remove this in 9.0 and add special_code param to addline() // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set @@ -1361,8 +1372,7 @@ class CommandeFournisseur extends CommonOrder $this->lines[$i]->array_options, $this->lines[$i]->fk_unit ); - if ($result < 0) - { + if ($result < 0) { dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); // do not use dol_print_error here as it may be a functionnal error $this->db->rollback(); return -1; @@ -1371,32 +1381,24 @@ class CommandeFournisseur extends CommonOrder $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; $sql .= " SET ref='(PROV".$this->id.")'"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::create", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { // Add link with price request and supplier order - if ($this->id) - { + if ($this->id) { $this->ref = "(PROV".$this->id.")"; - if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects - { + if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) - { - foreach ($this->linked_objects as $origin => $tmp_origin_id) - { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { + if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) { + foreach ($this->linked_objects as $origin => $tmp_origin_id) { + if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { dol_print_error($this->db); $error++; } @@ -1405,8 +1407,7 @@ class CommandeFournisseur extends CommonOrder { $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { dol_print_error($this->db); $error++; } @@ -1415,18 +1416,17 @@ class CommandeFournisseur extends CommonOrder } } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_CREATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -1448,6 +1448,109 @@ class CommandeFournisseur extends CommonOrder } } + /** + * Update Supplier Order + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = 0) + { + global $conf; + + $error = 0; + + // Clean parameters + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->ref_supplier)) { + $this->ref_supplier = trim($this->ref_supplier); + } + if (isset($this->note_private)) { + $this->note_private = trim($this->note_private); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->model_pdf)) { + $this->model_pdf = trim($this->model_pdf); + } + if (isset($this->import_key)) { + $this->import_key = trim($this->import_key); + } + + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + + $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").","; + $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").","; + $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").","; + $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").","; + $sql .= " date_commande=".(strval($this->date_commande) != '' ? "'".$this->db->idate($this->date_commande)."'" : 'null').","; + $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').","; + $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").","; + $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").","; + $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").","; + $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").","; + $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").","; + $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").","; + $sql .= " fk_user_author=".(isset($this->user_author_id) ? $this->user_author_id : "null").","; + $sql .= " fk_user_valid=".(isset($this->user_valid) ? $this->user_valid : "null").","; + $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").","; + $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").","; + $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").","; + $sql .= " date_livraison=".(strval($this->delivery_date) != '' ? "'".$this->db->idate($this->delivery_date)."'" : 'null').","; + //$sql .= " fk_shipping_method=".(isset($this->shipping_method_id) ? $this->shipping_method_id : "null").","; + $sql .= " fk_account=".($this->fk_account > 0 ? $this->fk_account : "null").","; + //$sql .= " fk_input_reason=".($this->demand_reason_id > 0 ? $this->demand_reason_id : "null").","; + $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").","; + $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=".((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(); + } + + if (!$error) { + $result = $this->insertExtraFields(); + if ($result < 0) { + $error++; + } + } + + if (!$error && !$notrigger) { + // Call trigger + $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; + } + } + /** * Load an object from its id and create a new one in database * @@ -1464,19 +1567,18 @@ class CommandeFournisseur extends CommonOrder $this->db->begin(); // get extrafields so they will be clone - foreach ($this->lines as $line) + foreach ($this->lines as $line) { $line->fetch_optionals(); + } // Load source object $objFrom = clone $this; // Change socid if needed - if (!empty($socid) && $socid != $this->socid) - { + if (!empty($socid) && $socid != $this->socid) { $objsoc = new Societe($this->db); - if ($objsoc->fetch($socid) > 0) - { + if ($objsoc->fetch($socid) > 0) { $this->socid = $objsoc->id; $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); @@ -1504,25 +1606,26 @@ class CommandeFournisseur extends CommonOrder // Create clone $this->context['createfromclone'] = 'createfromclone'; $result = $this->create($user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Hook of thirdparty module - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('objFrom'=>$objFrom); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } } } unset($this->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -1562,22 +1665,31 @@ class CommandeFournisseur extends CommonOrder { global $langs, $mysoc, $conf; - $error = 0; - dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $fk_prod_fourn_price, $ref_supplier, $remise_percent, $price_base_type, $pu_ttc, $type, $info_bits, $notrigger, $date_start, $date_end, $fk_unit, $pu_ht_devise, $origin, $origin_id"); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - if (empty($qty)) $qty = 0; - if (!$info_bits) $info_bits = 0; - if (empty($txtva)) $txtva = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; - if (empty($remise_percent)) $remise_percent = 0; + if (empty($qty)) { + $qty = 0; + } + if (!$info_bits) { + $info_bits = 0; + } + if (empty($txtva)) { + $txtva = 0; + } + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } + if (empty($remise_percent)) { + $remise_percent = 0; + } $remise_percent = price2num($remise_percent); $qty = price2num($qty); @@ -1589,8 +1701,7 @@ class CommandeFournisseur extends CommonOrder } $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); - if ($price_base_type == 'HT') - { + if ($price_base_type == 'HT') { $pu = $pu_ht; } else { $pu = $pu_ttc; @@ -1598,12 +1709,13 @@ class CommandeFournisseur extends CommonOrder $desc = trim($desc); // Check parameters - if ($qty < 0 && !$fk_product) - { + if ($qty < 0 && !$fk_product) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")); return -1; } - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); $this->error = $langs->trans('ErrorStartDateGreaterEnd'); @@ -1631,15 +1743,15 @@ class CommandeFournisseur extends CommonOrder // If supplier order created from customer order, we take best supplier price // If $pu (defined previously from pu_ht or pu_ttc) is not defined at all, we also take the best supplier price - if ($result > 0 && ($origin == 'commande' || $pu === '')) - { + if ($result > 0 && ($origin == 'commande' || $pu === '')) { $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice // is remise percent not keyed but present for the product we add it - if ($remise_percent == 0 && $prod->remise_percent != 0) $remise_percent = $prod->remise_percent; + if ($remise_percent == 0 && $prod->remise_percent != 0) { + $remise_percent = $prod->remise_percent; + } } - if ($result == 0) // If result == 0, we failed to found the supplier reference price - { + if ($result == 0) { // If result == 0, we failed to found the supplier reference price $langs->load("errors"); $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier"); $this->db->rollback(); @@ -1648,16 +1760,14 @@ class CommandeFournisseur extends CommonOrder //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price return -1; } - if ($result == -1) - { + if ($result == -1) { $langs->load("errors"); $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier"); $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG); return -1; } - if ($result < -1) - { + if ($result < -1) { $this->error = $prod->error; $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR); @@ -1694,8 +1804,7 @@ class CommandeFournisseur extends CommonOrder // Clean vat code $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -1782,15 +1891,15 @@ class CommandeFournisseur extends CommonOrder } $result = $this->line->insert($notrigger); - if ($result > 0) - { + if ($result > 0) { // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) { + $this->line_order(true, 'DESC'); + } // Mise a jour informations denormalisees au niveau de la commande meme $result = $this->update_price(1, 'auto', 0, $this->thirdparty); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return $this->line->id; } else { @@ -1832,24 +1941,23 @@ class CommandeFournisseur extends CommonOrder require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; // Check parameters (if test are wrong here, there is bug into caller) - if ($entrepot <= 0) - { + if ($entrepot <= 0) { $this->error = 'ErrorBadValueForParameterWarehouse'; return -1; } - if ($qty == 0) - { + if ($qty == 0) { $this->error = 'ErrorBadValueForParameterQty'; return -1; } $dispatchstatus = 1; - if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $dispatchstatus = 0; // Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on + if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) { + $dispatchstatus = 0; // Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on + } $now = dol_now(); - if (($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY || $this->statut == self::STATUS_RECEIVED_COMPLETELY)) - { + if (($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY || $this->statut == self::STATUS_RECEIVED_COMPLETELY)) { $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur_dispatch"; @@ -1860,15 +1968,12 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$notrigger) - { + if ($resql) { + if (!$notrigger) { global $conf, $langs, $user; // Call trigger $result = $this->call_trigger('LINEORDER_SUPPLIER_DISPATCH', $user); - if ($result < 0) - { + if ($result < 0) { $error++; } // End call triggers @@ -1879,16 +1984,13 @@ class CommandeFournisseur extends CommonOrder } // If module stock is enabled and the stock increase is done on purchase order dispatching - if (!$error && $entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) - { + if (!$error && $entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { $mouv = new MouvementStock($this->db); - if ($product > 0) - { + if ($product > 0) { // $price should take into account discount (except if option STOCK_EXCLUDE_DISCOUNT_FOR_PMP is on) $mouv->origin = &$this; $result = $mouv->reception($user, $product, $entrepot, $qty, $price, $comment, $eatby, $sellby, $batch); - if ($result < 0) - { + if ($result < 0) { $this->error = $mouv->error; $this->errors = $mouv->errors; dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".join(',', $this->errors), LOG_ERR); @@ -1897,8 +1999,7 @@ class CommandeFournisseur extends CommonOrder } } - if ($error == 0) - { + if ($error == 0) { $this->db->commit(); return 1; } else { @@ -1920,17 +2021,14 @@ class CommandeFournisseur extends CommonOrder */ public function deleteline($idline, $notrigger = 0) { - if ($this->statut == 0) - { + if ($this->statut == 0) { $line = new CommandeFournisseurLigne($this->db); - if ($line->fetch($idline) <= 0) - { + if ($line->fetch($idline) <= 0) { return 0; } - if ($line->delete($notrigger) > 0) - { + if ($line->delete($notrigger) > 0) { $this->update_price(); return 1; } else { @@ -1959,12 +2057,10 @@ class CommandeFournisseur extends CommonOrder $this->db->begin(); - if (empty($notrigger)) - { + if (empty($notrigger)) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_DELETE', $user); - if ($result < 0) - { + if ($result < 0) { $this->errors[] = 'ErrorWhenRunningTrigger'; dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); $this->db->rollback(); @@ -1977,8 +2073,7 @@ class CommandeFournisseur extends CommonOrder $ef = $main."_extrafields"; $sql = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_commande = ".$this->id.")"; dol_syslog(get_class($this)."::delete extrafields lines", LOG_DEBUG); - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $this->error = $this->db->lasterror(); $this->errors[] = $this->db->lasterror(); $error++; @@ -1986,8 +2081,7 @@ class CommandeFournisseur extends CommonOrder $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande =".$this->id; dol_syslog(get_class($this)."::delete", LOG_DEBUG); - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $this->error = $this->db->lasterror(); $this->errors[] = $this->db->lasterror(); $error++; @@ -1995,10 +2089,8 @@ class CommandeFournisseur extends CommonOrder $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE rowid =".$this->id; dol_syslog(get_class($this)."::delete", LOG_DEBUG); - if ($resql = $this->db->query($sql)) - { - if ($this->db->affected_rows($resql) < 1) - { + if ($resql = $this->db->query($sql)) { + if ($this->db->affected_rows($resql) < 1) { $this->error = $this->db->lasterror(); $this->errors[] = $this->db->lasterror(); $error++; @@ -2010,11 +2102,9 @@ class CommandeFournisseur extends CommonOrder } // Remove extrafields - if (!$error) - { + if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->error = 'FailToDeleteExtraFields'; $this->errors[] = 'FailToDeleteExtraFields'; $error++; @@ -2030,31 +2120,25 @@ class CommandeFournisseur extends CommonOrder $error++; } - if (!$error) - { + if (!$error) { // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive $this->deleteEcmFiles(); // We remove directory $ref = dol_sanitizeFileName($this->ref); - if ($conf->fournisseur->commande->dir_output) - { + if ($conf->fournisseur->commande->dir_output) { $dir = $conf->fournisseur->commande->dir_output."/".$ref; $file = $dir."/".$ref.".pdf"; - if (file_exists($file)) - { - if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers - { + if (file_exists($file)) { + if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers $this->error = 'ErrorFailToDeleteFile'; $this->errors[] = 'ErrorFailToDeleteFile'; $error++; } } - if (file_exists($dir)) - { + if (file_exists($dir)) { $res = @dol_delete_dir_recursive($dir); - if (!$res) - { + if (!$res) { $this->error = 'ErrorFailToDeleteDir'; $this->errors[] = 'ErrorFailToDeleteDir'; $error++; @@ -2063,8 +2147,7 @@ class CommandeFournisseur extends CommonOrder } } - if (!$error) - { + if (!$error) { dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG); $this->db->commit(); return 1; @@ -2089,13 +2172,11 @@ class CommandeFournisseur extends CommonOrder $sql .= " WHERE active = 1"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $this->db->num_rows($resql); $this->methodes_commande = array(); - while ($i < $num) - { + while ($i < $num) { $row = $this->db->fetch_row($resql); $this->methodes_commande[$row[0]] = $row[1]; @@ -2129,20 +2210,19 @@ class CommandeFournisseur extends CommonOrder $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e ON cfd.fk_entrepot = e.rowid"; $sql .= " WHERE cfd.fk_commande = ".$this->id; $sql .= " AND cfd.fk_product = p.rowid"; - if ($status >= 0) $sql .= " AND cfd.status = ".$status; + if ($status >= 0) { + $sql .= " AND cfd.status = ".$status; + } $sql .= " ORDER BY cfd.rowid ASC"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($resql); - if ($objp) - { + if ($objp) { $ret[] = array( 'id' => $objp->dispatchedlineid, 'productid' => $objp->fk_product, @@ -2153,7 +2233,9 @@ class CommandeFournisseur extends CommonOrder $i++; } - } else dol_print_error($this->db, 'Failed to execute request to get dispatched lines'); + } else { + dol_print_error($this->db, 'Failed to execute request to get dispatched lines'); + } return $ret; } @@ -2179,39 +2261,37 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::Livraison"); - if ($user->rights->fournisseur->commande->receptionner) - { + if ($user->rights->fournisseur->commande->receptionner) { // Define the new status - if ($type == 'par') $statut = self::STATUS_RECEIVED_PARTIALLY; - elseif ($type == 'tot') $statut = self::STATUS_RECEIVED_COMPLETELY; - elseif ($type == 'nev') $statut = self::STATUS_CANCELED_AFTER_ORDER; - elseif ($type == 'can') $statut = self::STATUS_CANCELED_AFTER_ORDER; - else { + if ($type == 'par') { + $statut = self::STATUS_RECEIVED_PARTIALLY; + } elseif ($type == 'tot') { + $statut = self::STATUS_RECEIVED_COMPLETELY; + } elseif ($type == 'nev') { + $statut = self::STATUS_CANCELED_AFTER_ORDER; + } elseif ($type == 'can') { + $statut = self::STATUS_CANCELED_AFTER_ORDER; + } else { $error++; dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR); return -2; } // Some checks to accept the record - if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) - { + if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) { // If option SUPPLIER_ORDER_USE_DISPATCH_STATUS is on, we check all reception are approved to allow status "total/done" - if (!$error && ($type == 'tot')) - { + if (!$error && ($type == 'tot')) { $dispatchedlinearray = $this->getDispachedLines(0); - if (count($dispatchedlinearray) > 0) - { + if (count($dispatchedlinearray) > 0) { $result = -1; $error++; $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionToApprove'; dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionToApprove', LOG_DEBUG); } } - if (!$error && !empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS_NEED_APPROVE) && ($type == 'tot')) // Accept to move to reception done, only if status of all line are ok (refuse denied) - { + if (!$error && !empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS_NEED_APPROVE) && ($type == 'tot')) { // Accept to move to reception done, only if status of all line are ok (refuse denied) $dispatcheddenied = $this->getDispachedLines(2); - if (count($dispatchedlinearray) > 0) - { + if (count($dispatchedlinearray) > 0) { $result = -1; $error++; $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionDenied'; @@ -2222,8 +2302,7 @@ class CommandeFournisseur extends CommonOrder // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty). - if (empty($error)) - { + if (empty($error)) { $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; @@ -2233,8 +2312,7 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::Livraison", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $result = 1; $old_statut = $this->statut; $this->statut = $statut; @@ -2242,11 +2320,12 @@ class CommandeFournisseur extends CommonOrder // Call trigger $result_trigger = $this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user); - if ($result_trigger < 0) $error++; + if ($result_trigger < 0) { + $error++; + } // End call triggers - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); } else { $this->statut = $old_statut; @@ -2295,8 +2374,7 @@ class CommandeFournisseur extends CommonOrder */ public function setDeliveryDate($user, $delivery_date, $notrigger = 0) { - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { $error = 0; $this->db->begin(); @@ -2307,34 +2385,31 @@ class CommandeFournisseur extends CommonOrder dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->date_livraison = $delivery_date; $this->delivery_date = $delivery_date; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2358,8 +2433,7 @@ class CommandeFournisseur extends CommonOrder public function set_id_projet($user, $id_projet, $notrigger = 0) { // phpcs:enable - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { $error = 0; $this->db->begin(); @@ -2370,34 +2444,31 @@ class CommandeFournisseur extends CommonOrder dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->fk_projet = $id_projet; $this->fk_project = $id_projet; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2427,13 +2498,11 @@ class CommandeFournisseur extends CommonOrder $this->lines = array(); $num = count($comclient->lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $prod = new Product($this->db); $label = ''; $ref = ''; - if ($prod->fetch($comclient->lines[$i]->fk_product) > 0) - { + if ($prod->fetch($comclient->lines[$i]->fk_product) > 0) { $label = $prod->label; $ref = $prod->ref; } @@ -2444,8 +2513,7 @@ class CommandeFournisseur extends CommonOrder $sql .= ",".$comclient->lines[$i]->fk_product.", ".price2num($comclient->lines[$i]->price); $sql .= ", ".$comclient->lines[$i]->qty.", ".$comclient->lines[$i]->tva_tx.", ".$comclient->lines[$i]->localtax1_tx.", ".$comclient->lines[$i]->localtax2_tx.", ".$comclient->lines[$i]->remise_percent; $sql .= ", '".price2num($comclient->lines[$i]->subprice)."','0', '".$this->db->escape($ref)."');"; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->update_price(); } } @@ -2473,8 +2541,7 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::setStatus", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Trigger names for each status $triggerName = array(); $triggerName[0] = 'DRAFT'; @@ -2489,7 +2556,9 @@ class CommandeFournisseur extends CommonOrder // Call trigger $result = $this->call_trigger("ORDER_SUPPLIER_STATUS_".$triggerName[$status], $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } else { $error++; @@ -2497,8 +2566,7 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::setStatus ".$this->error); } - if (!$error) - { + if (!$error) { $this->statut = $status; $this->db->commit(); return 1; @@ -2539,30 +2607,47 @@ class CommandeFournisseur extends CommonOrder $error = 0; - if ($this->brouillon) - { + if ($this->brouillon) { // Clean parameters - if (empty($qty)) $qty = 0; - if (empty($info_bits)) $info_bits = 0; - if (empty($txtva)) $txtva = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; - if (empty($remise)) $remise = 0; - if (empty($remise_percent)) $remise_percent = 0; + if (empty($qty)) { + $qty = 0; + } + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($txtva)) { + $txtva = 0; + } + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } + if (empty($remise)) { + $remise = 0; + } + if (empty($remise_percent)) { + $remise_percent = 0; + } $remise_percent = price2num($remise_percent); $qty = price2num($qty); - if (!$qty) $qty = 1; + if (!$qty) { + $qty = 1; + } $pu = price2num($pu); $pu_ht_devise = price2num($pu_ht_devise); - if (!preg_match('/\((.*)\)/', $txtva)) { - $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' - } + if (!preg_match('/\((.*)\)/', $txtva)) { + $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' + } $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); $this->error = $langs->trans('ErrorStartDateGreaterEnd'); @@ -2581,8 +2666,7 @@ class CommandeFournisseur extends CommonOrder // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -2620,14 +2704,11 @@ class CommandeFournisseur extends CommonOrder $this->line->desc = $desc; // redefine quantity according to packaging - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) - { - if ($qty < $this->line->packaging) - { + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + if ($qty < $this->line->packaging) { $qty = $this->line->packaging; } else { - if (($qty % $this->line->packaging) > 0) - { + if (($qty % $this->line->packaging) > 0) { $coeff = intval($qty / $this->line->packaging) + 1; $qty = $this->line->packaging * $coeff; setEventMessage($langs->trans('QtyRecalculatedWithPackaging'), 'mesgs'); @@ -2685,8 +2766,7 @@ class CommandeFournisseur extends CommonOrder // Mise a jour info denormalisees au niveau facture - if ($result >= 0) - { + if ($result >= 0) { $this->update_price('', 'auto'); $this->db->commit(); return $result; @@ -2729,8 +2809,7 @@ class CommandeFournisseur extends CommonOrder $sql .= $this->db->order("rowid", "ASC"); $sql .= $this->db->plimit(1); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $prodid = $obj->rowid; } @@ -2757,8 +2836,7 @@ class CommandeFournisseur extends CommonOrder // Lines $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new CommandeFournisseurLigne($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; $line->qty = 1; @@ -2767,8 +2845,7 @@ class CommandeFournisseur extends CommonOrder $line->tva_tx = 19.6; $line->localtax1_tx = 0; $line->localtax2_tx = 0; - if ($xnbp == 2) - { + if ($xnbp == 2) { $line->total_ht = 50; $line->total_ttc = 59.8; $line->total_tva = 9.8; @@ -2802,20 +2879,28 @@ class CommandeFournisseur extends CommonOrder $sql = 'SELECT c.rowid, date_creation as datec, tms as datem, date_valid as date_validation, date_approve as datea, date_approve2 as datea2,'; $sql .= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_approve, fk_user_approve2'; $sql .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) $this->user_creation_id = $obj->fk_user_author; - if ($obj->fk_user_valid) $this->user_validation_id = $obj->fk_user_valid; - if ($obj->fk_user_modif) $this->user_modification_id = $obj->fk_user_modif; - if ($obj->fk_user_approve) $this->user_approve_id = $obj->fk_user_approve; - if ($obj->fk_user_approve2) $this->user_approve_id2 = $obj->fk_user_approve2; + if ($obj->fk_user_author) { + $this->user_creation_id = $obj->fk_user_author; + } + if ($obj->fk_user_valid) { + $this->user_validation_id = $obj->fk_user_valid; + } + if ($obj->fk_user_modif) { + $this->user_modification_id = $obj->fk_user_modif; + } + if ($obj->fk_user_approve) { + $this->user_approve_id = $obj->fk_user_approve; + } + if ($obj->fk_user_approve2) { + $this->user_approve_id2 = $obj->fk_user_approve2; + } $this->date_creation = $this->db->idate($obj->datec); $this->date_modification = $this->db->idate($obj->datem); @@ -2846,8 +2931,7 @@ class CommandeFournisseur extends CommonOrder $sql = "SELECT count(co.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as co"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -2855,10 +2939,8 @@ class CommandeFournisseur extends CommonOrder $sql .= " ".$clause." co.entity = ".$conf->entity; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["supplier_orders"] = $obj->nb; } $this->db->free($resql); @@ -2887,8 +2969,7 @@ class CommandeFournisseur extends CommonOrder $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.fk_statut, c.date_livraison as delivery_date"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = " AND"; @@ -2899,11 +2980,12 @@ class CommandeFournisseur extends CommonOrder } else { $sql .= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")"; } - if ($user->socid) $sql .= " AND c.fk_soc = ".$user->socid; + if ($user->socid) { + $sql .= " AND c.fk_soc = ".$user->socid; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $commandestatic = new CommandeFournisseur($this->db); $response = new WorkboardResponse(); @@ -2919,8 +3001,7 @@ class CommandeFournisseur extends CommonOrder $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?statut=3,4&mainmenu=commercial&leftmenu=orders_suppliers'; } - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; $commandestatic->delivery_date = $this->db->jdate($obj->delivery_date); @@ -2949,27 +3030,25 @@ class CommandeFournisseur extends CommonOrder { global $db, $langs; - if ($this->methode_commande_id > 0) - { + if ($this->methode_commande_id > 0) { $sql = "SELECT rowid, code, libelle as label"; $sql .= " FROM ".MAIN_DB_PREFIX.'c_input_method'; $sql .= " WHERE active=1 AND rowid = ".$this->db->escape($this->methode_commande_id); $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); $string = $langs->trans($obj->code); - if ($string == $obj->code) - { + if ($string == $obj->code) { $string = $obj->label != '-' ? $obj->label : ''; } return $string; } - } else dol_print_error($this->db); + } else { + dol_print_error($this->db); + } } return ''; @@ -3016,26 +3095,30 @@ class CommandeFournisseur extends CommonOrder */ public function getMaxDeliveryTimeDay($langs) { - if (empty($this->lines)) return ''; + if (empty($this->lines)) { + return ''; + } $obj = new ProductFournisseur($this->db); $nb = 0; - foreach ($this->lines as $line) - { - if ($line->fk_product > 0) - { + foreach ($this->lines as $line) { + if ($line->fk_product > 0) { $idp = $obj->find_min_price_product_fournisseur($line->fk_product, $line->qty); - if ($idp) - { + if ($idp) { $obj->fetch($idp); - if ($obj->delivery_time_days > $nb) $nb = $obj->delivery_time_days; + if ($obj->delivery_time_days > $nb) { + $nb = $obj->delivery_time_days; + } } } } - if ($nb === 0) return ''; - else return $nb.' '.$langs->trans('Days'); + if ($nb === 0) { + return ''; + } else { + return $nb.' '.$langs->trans('Days'); + } } /** @@ -3078,7 +3161,9 @@ class CommandeFournisseur extends CommonOrder { global $conf; - if (empty($this->delivery_date) && !empty($this->date_livraison)) $this->delivery_date = $this->date_livraison; // For backward compatibility + if (empty($this->delivery_date) && !empty($this->date_livraison)) { + $this->delivery_date = $this->date_livraison; // For backward compatibility + } if ($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY) { $now = dol_now(); @@ -3109,7 +3194,9 @@ class CommandeFournisseur extends CommonOrder { global $conf, $langs; - if (empty($this->delivery_date) && !empty($this->date_livraison)) $this->delivery_date = $this->date_livraison; // For backward compatibility + if (empty($this->delivery_date) && !empty($this->date_livraison)) { + $this->delivery_date = $this->date_livraison; // For backward compatibility + } $text = ''; @@ -3142,8 +3229,7 @@ class CommandeFournisseur extends CommonOrder { global $conf, $langs; - if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) - { + if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php'; $qtydelivered = array(); @@ -3170,7 +3256,9 @@ class CommandeFournisseur extends CommonOrder } foreach ($this->lines as $line) { // Exclude lines not qualified for shipment, similar code is found into interface_20_modWrokflow for customers - if (empty($conf->global->STOCK_SUPPORTS_SERVICES) && $line->product_type > 0) continue; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES) && $line->product_type > 0) { + continue; + } $qtywished[$line->fk_product] += $line->qty; } @@ -3180,16 +3268,14 @@ class CommandeFournisseur extends CommonOrder $keysindeliverednotinwished = array_diff(array_keys($qtydelivered), array_keys($qtywished)); // To check we also have same number of keys /*var_dump(array_keys($qtydelivered)); - var_dump(array_keys($qtywished)); - var_dump($diff_array); - var_dump($keysinwishednotindelivered); - var_dump($keysindeliverednotinwished); - exit;*/ + var_dump(array_keys($qtywished)); + var_dump($diff_array); + var_dump($keysinwishednotindelivered); + var_dump($keysindeliverednotinwished); + exit;*/ - if (count($diff_array) == 0 && count($keysinwishednotindelivered) == 0 && count($keysindeliverednotinwished) == 0) //No diff => mean everythings is received - { - if ($closeopenorder) - { + if (count($diff_array) == 0 && count($keysinwishednotindelivered) == 0 && count($keysindeliverednotinwished) == 0) { //No diff => mean everythings is received + if ($closeopenorder) { //$ret=$this->setStatus($user,5); $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' if ($ret < 0) { @@ -3210,16 +3296,13 @@ class CommandeFournisseur extends CommonOrder $close = 0; - if (count($diff_array) > 0) - { + if (count($diff_array) > 0) { //there are some difference between the two arrays //scan the array of results - foreach ($diff_array as $key => $value) - { + foreach ($diff_array as $key => $value) { //if the quantity delivered is greater or equal to wish quantity - if ($qtydelivered[$key] >= $qtywished[$key]) - { + if ($qtydelivered[$key] >= $qtywished[$key]) { $close++; } } @@ -3279,25 +3362,31 @@ class CommandeFournisseur extends CommonOrder $sql = 'SELECT cd.rowid, cd.fk_product,'; $sql .= ' sum(cfd.qty) as qty'; $sql .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur_dispatch as cfd,'; - if ($filtre_statut >= 0) $sql .= ' '.MAIN_DB_PREFIX.'reception as e,'; + if ($filtre_statut >= 0) { + $sql .= ' '.MAIN_DB_PREFIX.'reception as e,'; + } $sql .= ' '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd'; $sql .= ' WHERE'; - if ($filtre_statut >= 0) $sql .= ' cfd.fk_reception = e.rowid AND'; + if ($filtre_statut >= 0) { + $sql .= ' cfd.fk_reception = e.rowid AND'; + } $sql .= ' cfd.fk_commandefourndet = cd.rowid'; $sql .= ' AND cd.fk_commande ='.$this->id; - if ($this->fk_product > 0) $sql .= ' AND cd.fk_product = '.$this->fk_product; - if ($filtre_statut >= 0) $sql .= ' AND e.fk_statut >= '.$filtre_statut; + if ($this->fk_product > 0) { + $sql .= ' AND cd.fk_product = '.$this->fk_product; + } + if ($filtre_statut >= 0) { + $sql .= ' AND e.fk_statut >= '.$filtre_statut; + } $sql .= ' GROUP BY cd.rowid, cd.fk_product'; dol_syslog(get_class($this)."::loadReceptions", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); empty($this->receptions[$obj->rowid]) ? $this->receptions[$obj->rowid] = $obj->qty : $this->receptions[$obj->rowid] += $obj->qty; $i++; @@ -3398,20 +3487,20 @@ class CommandeFournisseurLigne extends CommonOrderLine $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,'; $sql .= ' cd.date_start, cd.date_end, cd.fk_unit,'; $sql .= ' cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc'; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $sql .= ", pfp.rowid as fk_pfp, pfp.packaging"; + } $sql .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid'; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON cd.fk_product = pfp.fk_product and cd.ref = pfp.ref_fourn"; + } $sql .= ' WHERE cd.rowid = '.$rowid; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $objp = $this->db->fetch_object($result); - if (!empty($objp)) - { + if (!empty($objp)) { $this->rowid = $objp->rowid; $this->id = $objp->rowid; $this->fk_commande = $objp->fk_commande; @@ -3442,8 +3531,7 @@ class CommandeFournisseurLigne extends CommonOrderLine $this->product_ref = $objp->product_ref; $this->product_label = $objp->product_label; $this->product_desc = $objp->product_desc; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) - { + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $this->packaging = $objp->packaging; $this->fk_fournprice = $objp->fk_pfp; } @@ -3487,32 +3575,63 @@ class CommandeFournisseurLigne extends CommonOrderLine dol_syslog(get_class($this)."::insert rang=".$this->rang); // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->localtax1_type)) $this->localtax1_type = '0'; - if (empty($this->localtax2_type)) $this->localtax2_type = '0'; - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; - if (empty($this->rang)) $this->rang = 0; - if (empty($this->remise)) $this->remise = 0; - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->info_bits)) $this->info_bits = 0; - if (empty($this->special_code)) $this->special_code = 0; - if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; - if (empty($this->pa_ht)) $this->pa_ht = 0; + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->localtax1_type)) { + $this->localtax1_type = '0'; + } + if (empty($this->localtax2_type)) { + $this->localtax2_type = '0'; + } + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } + if (empty($this->rang)) { + $this->rang = 0; + } + if (empty($this->remise)) { + $this->remise = 0; + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->info_bits)) { + $this->info_bits = 0; + } + if (empty($this->special_code)) { + $this->special_code = 0; + } + if (empty($this->fk_parent_line)) { + $this->fk_parent_line = 0; + } + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } // Multicurrency - if (!empty($this->multicurrency_code)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code); - if (empty($this->fk_multicurrency)) - { + if (!empty($this->multicurrency_code)) { + list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code); + } + if (empty($this->fk_multicurrency)) { $this->multicurrency_code = $conf->currency; $this->fk_multicurrency = 0; $this->multicurrency_tx = 1; } // Check parameters - if ($this->product_type < 0) return -1; + if ($this->product_type < 0) { + return -1; + } $this->db->begin(); @@ -3527,7 +3646,11 @@ class CommandeFournisseurLigne extends CommonOrderLine $sql .= " VALUES (".$this->fk_commande.", '".$this->db->escape($this->label)."','".$this->db->escape($this->desc)."',"; $sql .= " ".($this->date_start ? "'".$this->db->idate($this->date_start)."'" : "null").","; $sql .= " ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null").","; - if ($this->fk_product) { $sql .= $this->fk_product.","; } else { $sql .= "null,"; } + if ($this->fk_product) { + $sql .= $this->fk_product.","; + } else { + $sql .= "null,"; + } $sql .= "'".$this->db->escape($this->product_type)."',"; $sql .= "'".$this->db->escape($this->special_code)."',"; $sql .= "'".$this->db->escape($this->rang)."',"; @@ -3555,25 +3678,23 @@ class CommandeFournisseurLigne extends CommonOrderLine dol_syslog(get_class($this)."::insert", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); $this->rowid = $this->id; - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINEORDER_SUPPLIER_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -3582,8 +3703,7 @@ class CommandeFournisseurLigne extends CommonOrderLine return 1; } - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->errors[] = ($this->errors ? ', '.$errmsg : $errmsg); } @@ -3646,32 +3766,26 @@ class CommandeFournisseurLigne extends CommonOrderLine dol_syslog(get_class($this)."::updateline", LOG_DEBUG); $result = $this->db->query($sql); - if ($result > 0) - { - if (!$error) - { + if ($result > 0) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { global $user; // Call trigger $result = $this->call_trigger('LINEORDER_SUPPLIER_UPDATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -3701,34 +3815,31 @@ class CommandeFournisseurLigne extends CommonOrderLine // extrafields $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } - $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande_fournisseurdet WHERE rowid=".$this->id; + $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande_fournisseurdet WHERE rowid=".((int) $this->id); dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$notrigger) - { + if ($resql) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINEORDER_SUPPLIER_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } diff --git a/htdocs/fourn/class/fournisseur.commande.dispatch.class.php b/htdocs/fourn/class/fournisseur.commande.dispatch.class.php index a7abed27369..21c36ced633 100644 --- a/htdocs/fourn/class/fournisseur.commande.dispatch.class.php +++ b/htdocs/fourn/class/fournisseur.commande.dispatch.class.php @@ -140,16 +140,36 @@ class CommandeFournisseurDispatch extends CommonObject // Clean parameters - if (isset($this->fk_commande)) $this->fk_commande = trim($this->fk_commande); - if (isset($this->fk_product)) $this->fk_product = trim($this->fk_product); - if (isset($this->fk_commandefourndet)) $this->fk_commandefourndet = trim($this->fk_commandefourndet); - if (isset($this->qty)) $this->qty = trim($this->qty); - if (isset($this->fk_entrepot)) $this->fk_entrepot = trim($this->fk_entrepot); - if (isset($this->fk_user)) $this->fk_user = trim($this->fk_user); - if (isset($this->comment)) $this->comment = trim($this->comment); - if (isset($this->status)) $this->status = trim($this->status); - if (isset($this->batch)) $this->batch = trim($this->batch); - if (empty($this->datec)) $this->datec = dol_now(); + if (isset($this->fk_commande)) { + $this->fk_commande = trim($this->fk_commande); + } + if (isset($this->fk_product)) { + $this->fk_product = trim($this->fk_product); + } + if (isset($this->fk_commandefourndet)) { + $this->fk_commandefourndet = trim($this->fk_commandefourndet); + } + if (isset($this->qty)) { + $this->qty = trim($this->qty); + } + if (isset($this->fk_entrepot)) { + $this->fk_entrepot = trim($this->fk_entrepot); + } + if (isset($this->fk_user)) { + $this->fk_user = trim($this->fk_user); + } + if (isset($this->comment)) { + $this->comment = trim($this->comment); + } + if (isset($this->status)) { + $this->status = trim($this->status); + } + if (isset($this->batch)) { + $this->batch = trim($this->batch); + } + if (empty($this->datec)) { + $this->datec = dol_now(); + } // Check parameters @@ -190,16 +210,16 @@ class CommandeFournisseurDispatch extends CommonObject $this->db->begin(); - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - if (!$notrigger) - { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -211,17 +231,16 @@ class CommandeFournisseurDispatch extends CommonObject } // Create extrafields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -264,15 +283,16 @@ class CommandeFournisseurDispatch extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; - if ($ref) $sql .= " WHERE t.ref = '".$ref."'"; - else $sql .= " WHERE t.rowid = ".$id; + if ($ref) { + $sql .= " WHERE t.ref = '".$ref."'"; + } else { + $sql .= " WHERE t.rowid = ".((int) $id); + } dol_syslog(get_class($this)."::fetch"); $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; @@ -318,15 +338,33 @@ class CommandeFournisseurDispatch extends CommonObject // Clean parameters - if (isset($this->fk_commande)) $this->fk_commande = trim($this->fk_commande); - if (isset($this->fk_product)) $this->fk_product = trim($this->fk_product); - if (isset($this->fk_commandefourndet)) $this->fk_commandefourndet = trim($this->fk_commandefourndet); - if (isset($this->qty)) $this->qty = trim($this->qty); - if (isset($this->fk_entrepot)) $this->fk_entrepot = trim($this->fk_entrepot); - if (isset($this->fk_user)) $this->fk_user = trim($this->fk_user); - if (isset($this->comment)) $this->comment = trim($this->comment); - if (isset($this->status)) $this->status = trim($this->status); - if (isset($this->batch)) $this->batch = trim($this->batch); + if (isset($this->fk_commande)) { + $this->fk_commande = trim($this->fk_commande); + } + if (isset($this->fk_product)) { + $this->fk_product = trim($this->fk_product); + } + if (isset($this->fk_commandefourndet)) { + $this->fk_commandefourndet = trim($this->fk_commandefourndet); + } + if (isset($this->qty)) { + $this->qty = trim($this->qty); + } + if (isset($this->fk_entrepot)) { + $this->fk_entrepot = trim($this->fk_entrepot); + } + if (isset($this->fk_user)) { + $this->fk_user = trim($this->fk_user); + } + if (isset($this->comment)) { + $this->comment = trim($this->comment); + } + if (isset($this->status)) { + $this->status = trim($this->status); + } + if (isset($this->batch)) { + $this->batch = trim($this->batch); + } @@ -351,40 +389,40 @@ class CommandeFournisseurDispatch extends CommonObject $sql .= " sellby=".(dol_strlen($this->sellby) != 0 ? "'".$this->db->idate($this->sellby)."'" : 'null').""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { - if (!$error) - { - if (empty($this->id) && !empty($this->rowid))$this->id = $this->rowid; + if (!$error) { + if (!$error) { + if (empty($this->id) && !empty($this->rowid)) { + $this->id = $this->rowid; + } $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$notrigger) - { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you $result = $this->call_trigger('LINERECEPTION_UPDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } //// End call triggers } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -397,13 +435,13 @@ class CommandeFournisseurDispatch extends CommonObject } - /** - * Delete object in database - * - * @param User $user User that deletes - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + /** + * Delete object in database + * + * @param User $user User that deletes + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function delete($user, $notrigger = 0) { global $conf, $langs; @@ -411,10 +449,8 @@ class CommandeFournisseurDispatch extends CommonObject $this->db->begin(); - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -428,28 +464,26 @@ class CommandeFournisseurDispatch extends CommonObject // Remove extrafields if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR); } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -491,21 +525,18 @@ class CommandeFournisseurDispatch extends CommonObject $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $error++; } - if (!$error) - { + if (!$error) { } unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { @@ -541,30 +572,36 @@ class CommandeFournisseurDispatch extends CommonObject global $langs; $langs->load('orders'); - if ($mode == 0) - { + if ($mode == 0) { return $langs->trans($this->statuts[$status]); - } elseif ($mode == 1) - { + } elseif ($mode == 1) { return $langs->trans($this->statutshort[$status]); - } elseif ($mode == 2) - { + } elseif ($mode == 2) { return $langs->trans($this->statuts[$status]); - } elseif ($mode == 3) - { - if ($status == 0) return img_picto($langs->trans($this->statuts[$status]), 'statut0'); - elseif ($status == 1) return img_picto($langs->trans($this->statuts[$status]), 'statut4'); - elseif ($status == 2) return img_picto($langs->trans($this->statuts[$status]), 'statut8'); - } elseif ($mode == 4) - { - if ($status == 0) return img_picto($langs->trans($this->statuts[$status]), 'statut0').' '.$langs->trans($this->statuts[$status]); - elseif ($status == 1) return img_picto($langs->trans($this->statuts[$status]), 'statut4').' '.$langs->trans($this->statuts[$status]); - elseif ($status == 2) return img_picto($langs->trans($this->statuts[$status]), 'statut8').' '.$langs->trans($this->statuts[$status]); - } elseif ($mode == 5) - { - if ($status == 0) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$status]).' </span>'.img_picto($langs->trans($this->statuts[$status]), 'statut0'); - elseif ($status == 1) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$status]).' </span>'.img_picto($langs->trans($this->statuts[$status]), 'statut4'); - elseif ($status == 2) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$status]).' </span>'.img_picto($langs->trans($this->statuts[$status]), 'statut8'); + } elseif ($mode == 3) { + if ($status == 0) { + return img_picto($langs->trans($this->statuts[$status]), 'statut0'); + } elseif ($status == 1) { + return img_picto($langs->trans($this->statuts[$status]), 'statut4'); + } elseif ($status == 2) { + return img_picto($langs->trans($this->statuts[$status]), 'statut8'); + } + } elseif ($mode == 4) { + if ($status == 0) { + return img_picto($langs->trans($this->statuts[$status]), 'statut0').' '.$langs->trans($this->statuts[$status]); + } elseif ($status == 1) { + return img_picto($langs->trans($this->statuts[$status]), 'statut4').' '.$langs->trans($this->statuts[$status]); + } elseif ($status == 2) { + return img_picto($langs->trans($this->statuts[$status]), 'statut8').' '.$langs->trans($this->statuts[$status]); + } + } elseif ($mode == 5) { + if ($status == 0) { + return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$status]).' </span>'.img_picto($langs->trans($this->statuts[$status]), 'statut0'); + } elseif ($status == 1) { + return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$status]).' </span>'.img_picto($langs->trans($this->statuts[$status]), 'statut4'); + } elseif ($status == 2) { + return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$status]).' </span>'.img_picto($langs->trans($this->statuts[$status]), 'statut8'); + } } } @@ -610,7 +647,7 @@ class CommandeFournisseurDispatch extends CommonObject { dol_syslog(__METHOD__, LOG_DEBUG); - $sql = "SELECT"; + $sql = "SELECT"; $sql .= " t.rowid,"; $sql .= " t.fk_commande,"; diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 67070b99c57..dccb3901069 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -38,8 +38,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php'; require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +} +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +} /** * Class to manage suppliers invoices @@ -176,8 +180,11 @@ class FactureFournisseur extends CommonInvoice public $note_private; public $note_public; public $propalid; + public $cond_reglement_id; public $cond_reglement_code; + public $cond_reglement_label; + public $cond_reglement_doc; /** * @var int ID @@ -347,9 +354,15 @@ class FactureFournisseur extends CommonInvoice $now = dol_now(); // Clean parameters - if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier); - if (empty($this->type)) $this->type = self::TYPE_STANDARD; - if (empty($this->date)) $this->date = $now; + if (isset($this->ref_supplier)) { + $this->ref_supplier = trim($this->ref_supplier); + } + if (empty($this->type)) { + $this->type = self::TYPE_STANDARD; + } + if (empty($this->date)) { + $this->date = $now; + } $socid = $this->socid; $ref_supplier = $this->ref_supplier; @@ -357,10 +370,12 @@ class FactureFournisseur extends CommonInvoice $remise = $this->remise; // 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)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date); - else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); - if (empty($this->fk_multicurrency)) - { + if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) { + list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date); + } else { + $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); + } + if (empty($this->fk_multicurrency)) { $this->multicurrency_code = $conf->currency; $this->fk_multicurrency = 0; $this->multicurrency_tx = 1; @@ -368,7 +383,9 @@ class FactureFournisseur extends CommonInvoice $this->db->begin(); - if (!$remise) $remise = 0; + if (!$remise) { + $remise = 0; + } $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn ("; $sql .= "ref"; @@ -420,35 +437,30 @@ class FactureFournisseur extends CommonInvoice dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn'); // Update ref with new one $this->ref = '(PROV'.$this->id.')'; - $sql = 'UPDATE '.MAIN_DB_PREFIX."facture_fourn SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX."facture_fourn SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } - if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects - { + if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) - { - foreach ($this->linked_objects as $origin => $tmp_origin_id) - { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { + if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) { + foreach ($this->linked_objects as $origin => $tmp_origin_id) { + if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { dol_print_error($this->db); $error++; } @@ -457,8 +469,7 @@ class FactureFournisseur extends CommonInvoice { $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { dol_print_error($this->db); $error++; } @@ -466,17 +477,14 @@ class FactureFournisseur extends CommonInvoice } } - if (count($this->lines) && is_object($this->lines[0])) // If this->lines is array of InvoiceLines (preferred mode) - { + if (count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode) dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects"); - foreach ($this->lines as $i => $val) - { + foreach ($this->lines as $i => $val) { $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code)'; $sql .= ' VALUES ('.$this->id.','.intval($this->lines[$i]->special_code).')'; $resql_insert = $this->db->query($sql); - if ($resql_insert) - { + if ($resql_insert) { $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det'); $this->updateline( @@ -508,20 +516,20 @@ class FactureFournisseur extends CommonInvoice } else // If this->lines is an array of invoice line arrays { dol_syslog("There is ".count($this->lines)." lines that are array lines"); - foreach ($this->lines as $i => $val) - { + foreach ($this->lines as $i => $val) { $line = $this->lines[$i]; // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. - if (!is_object($line)) $line = (object) $line; + if (!is_object($line)) { + $line = (object) $line; + } $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code)'; $sql .= ' VALUES ('.$this->id.','.intval($this->lines[$i]->special_code).')'; $resql_insert = $this->db->query($sql); - if ($resql_insert) - { + if ($resql_insert) { $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det'); $this->updateline( @@ -536,7 +544,7 @@ class FactureFournisseur extends CommonInvoice 'HT', (!empty($line->info_bits) ? $line->info_bits : ''), $line->product_type - ); + ); } else { $this->error = $this->db->lasterror(); $this->db->rollback(); @@ -547,28 +555,25 @@ class FactureFournisseur extends CommonInvoice // Update total price $result = $this->update_price(); - if ($result > 0) - { + if ($result > 0) { // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); // This also set $this->error or $this->errors if errors are found - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -581,8 +586,7 @@ class FactureFournisseur extends CommonInvoice return -3; } } else { - if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $this->error = $langs->trans('ErrorRefAlreadyExists'); $this->db->rollback(); return -1; @@ -641,8 +645,8 @@ class FactureFournisseur extends CommonInvoice $sql .= " t.model_pdf,"; $sql .= " t.import_key,"; $sql .= " t.extraparams,"; - $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,"; - $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle,"; + $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_label, cr.libelle_facture as cond_reglement_doc,"; + $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_label,"; $sql .= ' s.nom as socnom, s.rowid as socid,'; $sql .= ' t.fk_incoterms, t.location_incoterms,'; $sql .= " i.libelle as label_incoterms,"; @@ -652,15 +656,17 @@ class FactureFournisseur extends CommonInvoice $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON t.fk_cond_reglement = cr.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON t.fk_mode_reglement = p.id"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid'; - if ($id) $sql .= " WHERE t.rowid=".$id; - if ($ref) $sql .= " WHERE t.ref='".$this->db->escape($ref)."' AND t.entity IN (".getEntity('supplier_invoice').")"; + if ($id) { + $sql .= " WHERE t.rowid=".$id; + } + if ($ref) { + $sql .= " WHERE t.ref='".$this->db->escape($ref)."' AND t.entity IN (".getEntity('supplier_invoice').")"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -697,12 +703,13 @@ class FactureFournisseur extends CommonInvoice $this->fk_project = $obj->fk_project; $this->cond_reglement_id = $obj->fk_cond_reglement; $this->cond_reglement_code = $obj->cond_reglement_code; - $this->cond_reglement = $obj->cond_reglement_libelle; - $this->cond_reglement_doc = $obj->cond_reglement_libelle; + $this->cond_reglement = $obj->cond_reglement_label; // deprecated + $this->cond_reglement_label = $obj->cond_reglement_label; + $this->cond_reglement_doc = $obj->cond_reglement_doc; $this->fk_account = $obj->fk_account; $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; - $this->mode_reglement = $obj->mode_reglement_libelle; + $this->mode_reglement = $obj->mode_reglement_label; $this->date_echeance = $this->db->jdate($obj->date_lim_reglement); $this->note = $obj->note_private; // deprecated $this->note_private = $obj->note_private; @@ -733,11 +740,12 @@ class FactureFournisseur extends CommonInvoice // fetch optionals attributes and labels $this->fetch_optionals(); - if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; + if ($this->statut == self::STATUS_DRAFT) { + $this->brouillon = 1; + } $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->db->lasterror(); return -3; } @@ -779,14 +787,11 @@ class FactureFournisseur extends CommonInvoice dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $resql_rows = $this->db->query($sql); - if ($resql_rows) - { + if ($resql_rows) { $num_rows = $this->db->num_rows($resql_rows); - if ($num_rows) - { + if ($num_rows) { $i = 0; - while ($i < $num_rows) - { + while ($i < $num_rows) { $obj = $this->db->fetch_object($resql_rows); $line = new SupplierInvoiceLine($this->db); @@ -873,37 +878,95 @@ class FactureFournisseur extends CommonInvoice $error = 0; // Clean parameters - if (empty($this->type)) $this->type = self::TYPE_STANDARD; - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier); - if (isset($this->entity)) $this->entity = trim($this->entity); - if (isset($this->type)) $this->type = trim($this->type); - if (isset($this->fk_soc)) $this->fk_soc = trim($this->fk_soc); - if (isset($this->label)) $this->label = trim($this->label); - if (isset($this->libelle)) $this->libelle = trim($this->libelle); // deprecated - if (isset($this->paye)) $this->paye = trim($this->paye); - if (isset($this->amount)) $this->amount = trim($this->amount); - if (isset($this->remise)) $this->remise = trim($this->remise); - if (isset($this->close_code)) $this->close_code = trim($this->close_code); - if (isset($this->close_note)) $this->close_note = trim($this->close_note); - if (isset($this->tva)) $this->tva = trim($this->tva); - if (isset($this->localtax1)) $this->localtax1 = trim($this->localtax1); - if (isset($this->localtax2)) $this->localtax2 = trim($this->localtax2); - if (empty($this->total_ht)) $this->total_ht = 0; - if (empty($this->total_tva)) $this->total_tva = 0; + if (empty($this->type)) { + $this->type = self::TYPE_STANDARD; + } + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->ref_supplier)) { + $this->ref_supplier = trim($this->ref_supplier); + } + if (isset($this->entity)) { + $this->entity = trim($this->entity); + } + if (isset($this->type)) { + $this->type = trim($this->type); + } + if (isset($this->fk_soc)) { + $this->fk_soc = trim($this->fk_soc); + } + if (isset($this->label)) { + $this->label = trim($this->label); + } + if (isset($this->libelle)) { + $this->libelle = trim($this->libelle); // deprecated + } + if (isset($this->paye)) { + $this->paye = trim($this->paye); + } + if (isset($this->amount)) { + $this->amount = trim($this->amount); + } + if (isset($this->remise)) { + $this->remise = trim($this->remise); + } + if (isset($this->close_code)) { + $this->close_code = trim($this->close_code); + } + if (isset($this->close_note)) { + $this->close_note = trim($this->close_note); + } + if (isset($this->tva)) { + $this->tva = trim($this->tva); + } + if (isset($this->localtax1)) { + $this->localtax1 = trim($this->localtax1); + } + if (isset($this->localtax2)) { + $this->localtax2 = trim($this->localtax2); + } + if (empty($this->total_ht)) { + $this->total_ht = 0; + } + if (empty($this->total_tva)) { + $this->total_tva = 0; + } // if (isset($this->total_localtax1)) $this->total_localtax1=trim($this->total_localtax1); // if (isset($this->total_localtax2)) $this->total_localtax2=trim($this->total_localtax2); - if (isset($this->total_ttc)) $this->total_ttc = trim($this->total_ttc); - if (isset($this->statut)) $this->statut = (int) $this->statut; - if (isset($this->author)) $this->author = trim($this->author); - if (isset($this->fk_user_valid)) $this->fk_user_valid = trim($this->fk_user_valid); - if (isset($this->fk_facture_source)) $this->fk_facture_source = trim($this->fk_facture_source); - if (isset($this->fk_project)) $this->fk_project = trim($this->fk_project); - if (isset($this->cond_reglement_id)) $this->cond_reglement_id = trim($this->cond_reglement_id); - if (isset($this->note_private)) $this->note = trim($this->note_private); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf); - if (isset($this->import_key)) $this->import_key = trim($this->import_key); + if (isset($this->total_ttc)) { + $this->total_ttc = trim($this->total_ttc); + } + if (isset($this->statut)) { + $this->statut = (int) $this->statut; + } + if (isset($this->author)) { + $this->author = trim($this->author); + } + if (isset($this->fk_user_valid)) { + $this->fk_user_valid = trim($this->fk_user_valid); + } + if (isset($this->fk_facture_source)) { + $this->fk_facture_source = trim($this->fk_facture_source); + } + if (isset($this->fk_project)) { + $this->fk_project = trim($this->fk_project); + } + if (isset($this->cond_reglement_id)) { + $this->cond_reglement_id = trim($this->cond_reglement_id); + } + if (isset($this->note_private)) { + $this->note = trim($this->note_private); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->model_pdf)) { + $this->model_pdf = trim($this->model_pdf); + } + if (isset($this->import_key)) { + $this->import_key = trim($this->import_key); + } // Check parameters @@ -918,7 +981,9 @@ class FactureFournisseur extends CommonInvoice $sql .= " fk_soc=".(isset($this->fk_soc) ? $this->fk_soc : "null").","; $sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').","; $sql .= " datef=".(dol_strlen($this->date) != 0 ? "'".$this->db->idate($this->date)."'" : 'null').","; - if (dol_strlen($this->tms) != 0) $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; + if (dol_strlen($this->tms) != 0) { + $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; + } $sql .= " libelle=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; $sql .= " paye=".(isset($this->paye) ? $this->paye : "null").","; $sql .= " amount=".(isset($this->amount) ? $this->amount : "null").","; @@ -942,7 +1007,7 @@ class FactureFournisseur extends CommonInvoice $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(); @@ -959,31 +1024,27 @@ class FactureFournisseur extends CommonInvoice } } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_UPDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -1015,10 +1076,8 @@ class FactureFournisseur extends CommonInvoice $remise = new DiscountAbsolute($this->db); $result = $remise->fetch($idremise); - if ($result > 0) - { - if ($remise->fk_invoice_supplier) // Protection against multiple submission - { + if ($result > 0) { + if ($remise->fk_invoice_supplier) { // Protection against multiple submission $this->error = $langs->trans("ErrorDiscountAlreadyUsed"); $this->db->rollback(); return -5; @@ -1039,8 +1098,7 @@ class FactureFournisseur extends CommonInvoice $facligne->info_bits = 2; // Get buy/cost price of invoice that is source of discount - if ($remise->fk_invoice_supplier_source > 0) - { + if ($remise->fk_invoice_supplier_source > 0) { $srcinvoice = new FactureFournisseur($this->db); $srcinvoice->fetch($remise->fk_invoice_supplier_source); $totalcostpriceofinvoice = 0; @@ -1060,15 +1118,12 @@ class FactureFournisseur extends CommonInvoice $facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc; $lineid = $facligne->insert(); - if ($lineid > 0) - { + if ($lineid > 0) { $result = $this->update_price(1); - if ($result > 0) - { + if ($result > 0) { // Create link between discount and invoice line $result = $remise->link_to_invoice($lineid, 0, 'supplier'); - if ($result < 0) - { + if ($result < 0) { $this->error = $remise->error; $this->db->rollback(); return -4; @@ -1113,12 +1168,10 @@ class FactureFournisseur extends CommonInvoice $error = 0; $this->db->begin(); - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_DELETE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -1152,8 +1205,7 @@ class FactureFournisseur extends CommonInvoice } } - if (!$error) - { + if (!$error) { $main = MAIN_DB_PREFIX.'facture_fourn_det'; $ef = $main."_extrafields"; $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_facture_fourn = $rowid)"; @@ -1161,8 +1213,7 @@ class FactureFournisseur extends CommonInvoice $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.$rowid.';'; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resqlef && $resql) - { + if ($resqlef && $resql) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.$rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql2 = $this->db->query($sql); @@ -1174,47 +1225,43 @@ class FactureFournisseur extends CommonInvoice } } - if (!$error) - { + if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive $this->deleteEcmFiles(); // We remove directory - if ($conf->fournisseur->facture->dir_output) - { + if ($conf->fournisseur->facture->dir_output) { include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $ref = dol_sanitizeFileName($this->ref); - $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoive_supplier').$ref; + $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$ref; $file = $dir."/".$ref.".pdf"; - if (file_exists($file)) - { - if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers - { + if (file_exists($file)) { + if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers $this->error = 'ErrorFailToDeleteFile'; $error++; } } - if (file_exists($dir)) - { + if (file_exists($dir)) { $res = @dol_delete_dir_recursive($dir); - if (!$res) - { + if (!$res) { $this->error = 'ErrorFailToDeleteDir'; $error++; } @@ -1223,18 +1270,15 @@ class FactureFournisseur extends CommonInvoice } // Remove extrafields - if (!$error) - { + if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); } } - if (!$error) - { + if (!$error) { dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG); $this->db->commit(); return 1; @@ -1285,11 +1329,12 @@ class FactureFournisseur extends CommonInvoice dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_PAYED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } else { $error++; @@ -1297,8 +1342,7 @@ class FactureFournisseur extends CommonInvoice dol_print_error($this->db); } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1346,11 +1390,12 @@ class FactureFournisseur extends CommonInvoice dol_syslog("FactureFournisseur::set_unpaid", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_UNPAYED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } else { $error++; @@ -1358,8 +1403,7 @@ class FactureFournisseur extends CommonInvoice dol_syslog("FactureFournisseur::set_unpaid ".$this->error); } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1393,19 +1437,16 @@ class FactureFournisseur extends CommonInvoice $this->fetch_lines(); // Check parameters - if ($this->statut > self::STATUS_DRAFT) // This is to avoid to validate twice (avoid errors on logs and stock management) - { + if ($this->statut > self::STATUS_DRAFT) { // This is to avoid to validate twice (avoid errors on logs and stock management) dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING); return 0; } - if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier)) - { + if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier)) { $langs->load("errors"); $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf")); return -1; } - if (count($this->lines) <= 0) - { + if (count($this->lines) <= 0) { $langs->load("errors"); $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref); return -1; @@ -1414,11 +1455,9 @@ class FactureFournisseur extends CommonInvoice $this->db->begin(); // Define new ref - if ($force_number) - { + if ($force_number) { $num = $force_number; - } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life - { + } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($this->thirdparty); } else { $num = $this->ref; @@ -1431,71 +1470,72 @@ class FactureFournisseur extends CommonInvoice dol_syslog(get_class($this)."::validate", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Si on incrémente le produit principal et ses composants à la validation de facture fournisseur - if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) - { + if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); $cpt = count($this->lines); - for ($i = 0; $i < $cpt; $i++) - { - if ($this->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $cpt; $i++) { + if ($this->lines[$i]->fk_product > 0) { $this->line = $this->lines[$i]; $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We increase stock for product $up_ht_disc = $this->lines[$i]->pu_ht; - if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU'); - if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num)); - else $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num)); - if ($result < 0) { $error++; } + if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) { + $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU'); + } + if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num)); + } else { + $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num)); + } + if ($result < 0) { + $error++; + } unset($this->line); } } } // Triggers call - if (!$error && empty($notrigger)) - { + if (!$error && empty($notrigger)) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$oldref; $dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -1508,15 +1548,13 @@ class FactureFournisseur extends CommonInvoice } // Set new ref and define current statut - if (!$error) - { + if (!$error) { $this->ref = $num; $this->statut = self::STATUS_VALIDATED; //$this->date_validation=$now; this is stored into log table } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1544,8 +1582,7 @@ class FactureFournisseur extends CommonInvoice $error = 0; - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { dol_syslog(__METHOD__." already draft status", LOG_WARNING); return 0; } @@ -1559,42 +1596,40 @@ class FactureFournisseur extends CommonInvoice $sql .= " WHERE rowid = ".$this->id; $result = $this->db->query($sql); - if ($result) - { - if (!$error) - { + if ($result) { + if (!$error) { $this->oldcopy = clone $this; } // Si on incremente le produit principal et ses composants a la validation de facture fournisseur, on decremente - if ($result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) - { + if ($result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); $cpt = count($this->lines); - for ($i = 0; $i < $cpt; $i++) - { - if ($this->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $cpt; $i++) { + if ($this->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We increase stock for product - if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); - else $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); + if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); + } else { + $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); + } } } } // Triggers call - if (!$error && empty($notrigger)) - { + if (!$error && empty($notrigger)) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_UNVALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if ($error == 0) - { + if ($error == 0) { $this->db->commit(); return 1; } else { @@ -1648,17 +1683,32 @@ class FactureFournisseur extends CommonInvoice dol_syslog(get_class($this)."::addline $desc,$pu,$qty,$txtva,$fk_product,$remise_percent,$date_start,$date_end,$ventil,$info_bits,$price_base_type,$type,$fk_unit", LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { // Clean parameters - if (empty($remise_percent)) $remise_percent = 0; - if (empty($qty)) $qty = 0; - if (empty($info_bits)) $info_bits = 0; - if (empty($rang)) $rang = 0; - if (empty($ventil)) $ventil = 0; - if (empty($txtva)) $txtva = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; + if (empty($remise_percent)) { + $remise_percent = 0; + } + if (empty($qty)) { + $qty = 0; + } + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($rang)) { + $rang = 0; + } + if (empty($ventil)) { + $ventil = 0; + } + if (empty($txtva)) { + $txtva = 0; + } + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } $remise_percent = price2num($remise_percent); $qty = price2num($qty); @@ -1677,15 +1727,12 @@ class FactureFournisseur extends CommonInvoice $this->db->begin(); - if ($fk_product > 0) - { - if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) - { + if ($fk_product > 0) { + if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) { // Check quantity is enough dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." qty=".$qty." ref_supplier=".$ref_supplier); $prod = new Product($this->db, $fk_product); - if ($prod->fetch($fk_product) > 0) - { + if ($prod->fetch($fk_product) > 0) { $product_type = $prod->type; $label = $prod->label; $fk_prod_fourn_price = 0; @@ -1693,16 +1740,17 @@ class FactureFournisseur extends CommonInvoice // We use 'none' instead of $ref_supplier, because $ref_supplier may not exists anymore. So we will take the first supplier price ok. // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price. $result = $prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', ($this->fk_soc ? $this->fk_soc : $this->socid)); // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$ref_supplier/$this->fk_soc - if ($result > 0) - { - if (empty($pu)) $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice + if ($result > 0) { + if (empty($pu)) { + $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice + } $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice // is remise percent not keyed but present for the product we add it - if ($remise_percent == 0 && $prod->remise_percent != 0) + if ($remise_percent == 0 && $prod->remise_percent != 0) { $remise_percent = $prod->remise_percent; + } } - if ($result == 0) // If result == 0, we failed to found the supplier reference price - { + if ($result == 0) { // If result == 0, we failed to found the supplier reference price $langs->load("errors"); $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier"); $this->db->rollback(); @@ -1711,16 +1759,14 @@ class FactureFournisseur extends CommonInvoice //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price return -1; } - if ($result == -1) - { + if ($result == -1) { $langs->load("errors"); $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier"); $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG); return -1; } - if ($result < -1) - { + if ($result < -1) { $this->error = $prod->error; $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR); @@ -1745,8 +1791,7 @@ class FactureFournisseur extends CommonInvoice // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -1771,10 +1816,11 @@ class FactureFournisseur extends CommonInvoice $pu_ht_devise = $tabprice[19]; // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } - if ($rang < 0) - { + if ($rang < 0) { $rangmax = $this->line_max(); $rang = $rangmax + 1; } @@ -1833,15 +1879,15 @@ class FactureFournisseur extends CommonInvoice } $result = $this->line->insert($notrigger); - if ($result > 0) - { + if ($result > 0) { // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) { + $this->line_order(true, 'DESC'); + } // Mise a jour informations denormalisees au niveau de la facture meme $result = $this->update_price(1, 'auto', 0, $this->thirdparty); // The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode. - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return $this->line->id; } else { @@ -1898,7 +1944,9 @@ class FactureFournisseur extends CommonInvoice // Check parameters //if (! is_numeric($pu) || ! is_numeric($qty)) return -1; - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); @@ -1907,9 +1955,15 @@ class FactureFournisseur extends CommonInvoice } // Clean parameters - if (empty($vatrate)) $vatrate = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; + if (empty($vatrate)) { + $vatrate = 0; + } + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); @@ -1925,8 +1979,7 @@ class FactureFournisseur extends CommonInvoice // Clean vat code $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $vatrate, $reg)) - { + if (preg_match('/\((.*)\)/', $vatrate, $reg)) { $vat_src_code = $reg[1]; $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. } @@ -1947,10 +2000,11 @@ class FactureFournisseur extends CommonInvoice $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; - if (empty($info_bits)) $info_bits = 0; + if (empty($info_bits)) { + $info_bits = 0; + } - if ($idproduct) - { + if ($idproduct) { $product = new Product($this->db); $result = $product->fetch($idproduct); $product_type = $product->type; @@ -2042,8 +2096,7 @@ class FactureFournisseur extends CommonInvoice dol_syslog(get_class($this)."::deleteline", LOG_DEBUG); $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $this->error = $this->db->error(); $this->db->rollback(); return -2; @@ -2064,8 +2117,7 @@ class FactureFournisseur extends CommonInvoice } else { $res = $this->update_price(); - if ($res > 0) - { + if ($res > 0) { $this->db->commit(); return 1; } else { @@ -2088,29 +2140,24 @@ class FactureFournisseur extends CommonInvoice $sql = 'SELECT c.rowid, datec, tms as datem, '; $sql .= ' fk_user_author, fk_user_modif, fk_user_valid'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_modif) - { + if ($obj->fk_user_modif) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modif); $this->user_modification = $muser; @@ -2151,15 +2198,15 @@ class FactureFournisseur extends CommonInvoice $sql .= " AND f.paye = 0"; // Pas classee payee completement $sql .= " AND pf.fk_paiementfourn IS NULL"; // Aucun paiement deja fait $sql .= " AND ff.fk_statut IS NULL"; // Renvoi vrai si pas facture de remplacement - if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid; + if ($socid > 0) { + $sql .= " AND f.fk_soc = ".$socid; + } $sql .= " ORDER BY f.ref"; dol_syslog(get_class($this)."::list_replacable_supplier_invoices", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $return[$obj->rowid] = array( 'id' => $obj->rowid, 'ref' => $obj->ref, @@ -2199,20 +2246,23 @@ class FactureFournisseur extends CommonInvoice $sql .= " AND NOT EXISTS (SELECT rowid from ".MAIN_DB_PREFIX."facture_fourn as ff WHERE f.rowid = ff.fk_facture_source"; $sql .= " AND ff.type=".self::TYPE_REPLACEMENT.")"; $sql .= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir - if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid; + if ($socid > 0) { + $sql .= " AND f.fk_soc = ".$socid; + } $sql .= " ORDER BY f.ref"; dol_syslog(get_class($this)."::list_qualified_avoir_supplier_invoices", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $qualified = 0; - if ($obj->fk_statut == self::STATUS_VALIDATED) $qualified = 1; - if ($obj->fk_statut == self::STATUS_CLOSED) $qualified = 1; - if ($qualified) - { + if ($obj->fk_statut == self::STATUS_VALIDATED) { + $qualified = 1; + } + if ($obj->fk_statut == self::STATUS_CLOSED) { + $qualified = 1; + } + if ($qualified) { $paymentornot = ($obj->fk_paiementfourn ? 1 : 0); $return[$obj->rowid] = array('ref'=>$obj->ref, 'status'=>$obj->fk_statut, 'type'=>$obj->type, 'paye'=>$obj->paye, 'paymentornot'=>$paymentornot); } @@ -2239,16 +2289,21 @@ class FactureFournisseur extends CommonInvoice $sql = 'SELECT ff.rowid, ff.date_lim_reglement as datefin, ff.fk_statut'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as ff'; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= ' WHERE ff.paye=0'; $sql .= ' AND ff.fk_statut > 0'; $sql .= " AND ff.entity = ".$conf->entity; - if ($user->socid) $sql .= ' AND ff.fk_soc = '.$user->socid; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND ff.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) { + $sql .= ' AND ff.fk_soc = '.$user->socid; + } + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= " AND ff.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $langs->load("bills"); $now = dol_now(); @@ -2262,8 +2317,7 @@ class FactureFournisseur extends CommonInvoice $facturestatic = new FactureFournisseur($this->db); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; $facturestatic->date_echeance = $this->db->jdate($obj->datefin); @@ -2303,56 +2357,88 @@ class FactureFournisseur extends CommonInvoice $result = ''; - if ($option == 'withdraw') $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id.'&type=bank-transfer'; - elseif ($option == 'document') $url = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id; - else $url = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id; + if ($option == 'withdraw') { + $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id.'&type=bank-transfer'; + } elseif ($option == 'document') { + $url = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id; + } else { + $url = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id; + } - if ($short) return $url; + if ($short) { + return $url; + } - if ($option !== 'nolink') - { + 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'; + } } $picto = $this->picto; - if ($this->type == self::TYPE_REPLACEMENT) $picto .= 'r'; // Replacement invoice - if ($this->type == self::TYPE_CREDIT_NOTE) $picto .= 'a'; // Credit note - if ($this->type == self::TYPE_DEPOSIT) $picto .= 'd'; // Deposit invoice + if ($this->type == self::TYPE_REPLACEMENT) { + $picto .= 'r'; // Replacement invoice + } + if ($this->type == self::TYPE_CREDIT_NOTE) { + $picto .= 'a'; // Credit note + } + if ($this->type == self::TYPE_DEPOSIT) { + $picto .= 'd'; // Deposit invoice + } $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("SupplierInvoice").'</u>'; - if ($this->type == self::TYPE_REPLACEMENT) $label = '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("InvoiceReplace").'</u>'; - elseif ($this->type == self::TYPE_CREDIT_NOTE) $label = '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("CreditNote").'</u>'; - elseif ($this->type == self::TYPE_DEPOSIT) $label = '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("Deposit").'</u>'; - if (!empty($this->ref)) + if ($this->type == self::TYPE_REPLACEMENT) { + $label = '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("InvoiceReplace").'</u>'; + } elseif ($this->type == self::TYPE_CREDIT_NOTE) { + $label = '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("CreditNote").'</u>'; + } elseif ($this->type == self::TYPE_DEPOSIT) { + $label = '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("Deposit").'</u>'; + } + if (isset($this->status)) { + $alreadypaid = -1; + $label .= ' '.$this->getLibStatut(5, $alreadypaid); + } + if (!empty($this->ref)) { $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref; - if (!empty($this->ref_supplier)) + } + if (!empty($this->ref_supplier)) { $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier; - if (!empty($this->label)) + } + if (!empty($this->label)) { $label .= '<br><b>'.$langs->trans('Label').':</b> '.$this->label; - if (!empty($this->date)) + } + if (!empty($this->date)) { $label .= '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day'); - if (!empty($this->total_ht)) + } + if (!empty($this->total_ht)) { $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_tva)) + } + if (!empty($this->total_tva)) { $label .= '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_ttc)) + } + if (!empty($this->total_ttc)) { $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - if ($moretitle) $label .= ' - '.$moretitle; + } + if ($moretitle) { + $label .= ' - '.$moretitle; + } if (isset($this->statut) && isset($this->alreadypaid)) { $label .= '<br><b>'.$langs->trans("Status").":</b> ".$this->getLibStatut(5, $this->alreadypaid); } $ref = $this->ref; - if (empty($ref)) $ref = $this->id; + if (empty($ref)) { + $ref = $this->id; + } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowSupplierInvoice"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -2365,15 +2451,17 @@ class FactureFournisseur extends CommonInvoice $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= ($max ?dol_trunc($ref, $max) : $ref); + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= ($max ?dol_trunc($ref, $max) : $ref); + } $result .= $linkend; - if ($addlinktonotes) - { + if ($addlinktonotes) { $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { + if ($txttoshow) { $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1); $result .= ' <span class="note inline-block">'; $result .= '<a href="'.DOL_URL_ROOT.'/fourn/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">'; @@ -2402,7 +2490,9 @@ class FactureFournisseur extends CommonInvoice $langs->load("orders"); // Clean parameters (if not defined or using deprecated value) - if (empty($conf->global->INVOICE_SUPPLIER_ADDON_NUMBER)) $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER = 'mod_facture_fournisseur_cactus'; + if (empty($conf->global->INVOICE_SUPPLIER_ADDON_NUMBER)) { + $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER = 'mod_facture_fournisseur_cactus'; + } $mybool = false; @@ -2428,8 +2518,7 @@ class FactureFournisseur extends CommonInvoice $numref = ""; $numref = $obj->getNumRef($soc, $this, $mode); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -2463,12 +2552,10 @@ class FactureFournisseur extends CommonInvoice $sql .= $this->db->plimit(100); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -2492,13 +2579,11 @@ class FactureFournisseur extends CommonInvoice $this->multicurrency_tx = 1; $this->multicurrency_code = $conf->currency; - if (empty($option) || $option != 'nolines') - { + if (empty($option) || $option != 'nolines') { // Lines $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new SupplierInvoiceLine($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; $line->qty = 1; @@ -2508,8 +2593,7 @@ class FactureFournisseur extends CommonInvoice $line->tva_tx = 19.6; $line->localtax1_tx = 0; $line->localtax2_tx = 0; - if ($xnbp == 2) - { + if ($xnbp == 2) { $line->total_ht = 50; $line->total_ttc = 59.8; $line->total_tva = 9.8; @@ -2521,8 +2605,7 @@ class FactureFournisseur extends CommonInvoice $line->remise_percent = 0; } - if ($num_prods > 0) - { + if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; } @@ -2562,8 +2645,7 @@ class FactureFournisseur extends CommonInvoice $sql = "SELECT count(f.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -2571,10 +2653,8 @@ class FactureFournisseur extends CommonInvoice $sql .= " ".$clause." f.entity = ".$conf->entity; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["supplier_invoices"] = $obj->nb; } $this->db->free($resql); @@ -2625,10 +2705,8 @@ class FactureFournisseur extends CommonInvoice $object->close_note = ''; // Loop on each line of new invoice - foreach ($object->lines as $i => $line) - { - if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts - { + foreach ($object->lines as $i => $line) { + if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts unset($object->lines[$i]); } } @@ -2638,22 +2716,19 @@ class FactureFournisseur extends CommonInvoice $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $this->errors = $object->errors; $error++; } - if (!$error) - { + if (!$error) { } unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { @@ -2681,18 +2756,15 @@ class FactureFournisseur extends CommonInvoice $outputlangs->load("products"); // Set the model on the model name to use - if (empty($modele)) - { - if (!empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)) - { + if (empty($modele)) { + if (!empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)) { $modele = $conf->global->INVOICE_SUPPLIER_ADDON_PDF; } else { $modele = ''; // No default value. For supplier invoice, we allow to disable all PDF generation } } - if (empty($modele)) - { + if (empty($modele)) { return 0; } else { $modelpath = "core/modules/supplier_invoice/doc/"; @@ -2760,7 +2832,9 @@ class FactureFournisseur extends CommonInvoice $resql = $this->db->query($sql); if (!empty($resql)) { $obj = $this->db->fetch_object($resql); - if (!empty($obj->fk_invoice_supplier)) $isUsed = true; + if (!empty($obj->fk_invoice_supplier)) { + $isUsed = true; + } } return $isUsed; @@ -3092,7 +3166,7 @@ class SupplierInvoiceLine extends CommonObjectLine { global $user, $conf; - dol_syslog(get_class($this)."::deleteline rowid=".$this->id, LOG_DEBUG); + dol_syslog(get_class($this)."::deleteline rowid=".((int) $this->id), LOG_DEBUG); $error = 0; @@ -3107,11 +3181,9 @@ class SupplierInvoiceLine extends CommonObjectLine $this->deleteObjectLinked(); // Remove extrafields - if (!$error) - { + if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); } @@ -3129,8 +3201,7 @@ class SupplierInvoiceLine extends CommonObjectLine } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -3153,22 +3224,31 @@ class SupplierInvoiceLine extends CommonObjectLine $qty = price2num($this->qty); // Check parameters - if (empty($this->qty)) $this->qty = 0; + if (empty($this->qty)) { + $this->qty = 0; + } if ($this->product_type < 0) { return -1; } // Clean parameters - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } $this->db->begin(); - if (empty($this->fk_product)) - { + if (empty($this->fk_product)) { $fk_product = "null"; } else { $fk_product = $this->fk_product; @@ -3225,17 +3305,14 @@ class SupplierInvoiceLine extends CommonObjectLine $this->rowid = $this->id; $error = 0; - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { global $langs, $user; // Call trigger @@ -3271,41 +3348,78 @@ class SupplierInvoiceLine extends CommonObjectLine // Clean parameters $this->desc = trim($this->desc); - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->localtax1_type)) $this->localtax1_type = '0'; - if (empty($this->localtax2_type)) $this->localtax2_type = '0'; - if (empty($this->total_tva)) $this->total_tva = 0; - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; - if (empty($this->rang)) $this->rang = 0; - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->info_bits)) $this->info_bits = 0; - if (empty($this->subprice)) $this->subprice = 0; - if (empty($this->special_code)) $this->special_code = 0; - if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; - if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100; + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->localtax1_type)) { + $this->localtax1_type = '0'; + } + if (empty($this->localtax2_type)) { + $this->localtax2_type = '0'; + } + if (empty($this->total_tva)) { + $this->total_tva = 0; + } + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } + if (empty($this->rang)) { + $this->rang = 0; + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->info_bits)) { + $this->info_bits = 0; + } + if (empty($this->subprice)) { + $this->subprice = 0; + } + if (empty($this->special_code)) { + $this->special_code = 0; + } + if (empty($this->fk_parent_line)) { + $this->fk_parent_line = 0; + } + if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') { + $this->situation_percent = 100; + } - if (empty($this->pa_ht)) $this->pa_ht = 0; - if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0; - if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0; - if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0; - if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0; + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } + if (empty($this->multicurrency_subprice)) { + $this->multicurrency_subprice = 0; + } + if (empty($this->multicurrency_total_ht)) { + $this->multicurrency_total_ht = 0; + } + if (empty($this->multicurrency_total_tva)) { + $this->multicurrency_total_tva = 0; + } + if (empty($this->multicurrency_total_ttc)) { + $this->multicurrency_total_ttc = 0; + } // Check parameters - if ($this->product_type < 0) - { + if ($this->product_type < 0) { $this->error = 'ErrorProductTypeMustBe0orMore'; return -1; } - if (!empty($this->fk_product)) - { + if (!empty($this->fk_product)) { // Check product exists $result = Product::isExistingObject('product', $this->fk_product); - if ($result <= 0) - { + if ($result <= 0) { $this->error = 'ErrorProductIdDoesNotExists'; return -1; } @@ -3361,26 +3475,21 @@ class SupplierInvoiceLine extends CommonObjectLine $sql .= ')'; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); $this->rowid = $this->id; // backward compatibility - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINEBILL_SUPPLIER_CREATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -2; } @@ -3419,8 +3528,7 @@ class SupplierInvoiceLine extends CommonObjectLine dol_syslog("FactureFournisseurLigne.class.php::update_total", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php index 6ae9a3491ab..b124817bf9f 100644 --- a/htdocs/fourn/class/fournisseur.product.class.php +++ b/htdocs/fourn/class/fournisseur.product.class.php @@ -168,14 +168,12 @@ class ProductFournisseur extends Product dol_syslog(get_class($this)."::remove_fournisseur", LOG_DEBUG); $resql2 = $this->db->query($sql); - if (!$resql2) - { + if (!$resql2) { $this->error = $this->db->lasterror(); $ok = 0; } - if ($ok) - { + if ($ok) { $this->db->commit(); return 1; } else { @@ -203,18 +201,18 @@ class ProductFournisseur extends Product // Call trigger $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if (empty($error)) - { + if (empty($error)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; $sql .= " WHERE rowid = ".$rowid; dol_syslog(get_class($this)."::remove_product_fournisseur_price", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->lasterror(); $error++; } @@ -266,15 +264,28 @@ class ProductFournisseur extends Product //global $mysoc; // Clean parameter - if (empty($qty)) $qty = 0; - if (empty($buyprice)) $buyprice = 0; - if (empty($charges)) $charges = 0; - if (empty($availability)) $availability = 0; - if (empty($remise_percent)) $remise_percent = 0; - if (empty($supplier_reputation) || $supplier_reputation == -1) $supplier_reputation = ''; - if ($delivery_time_days != '' && !is_numeric($delivery_time_days)) $delivery_time_days = ''; - if ($price_base_type == 'TTC') - { + if (empty($qty)) { + $qty = 0; + } + if (empty($buyprice)) { + $buyprice = 0; + } + if (empty($charges)) { + $charges = 0; + } + if (empty($availability)) { + $availability = 0; + } + if (empty($remise_percent)) { + $remise_percent = 0; + } + if (empty($supplier_reputation) || $supplier_reputation == -1) { + $supplier_reputation = ''; + } + if ($delivery_time_days != '' && !is_numeric($delivery_time_days)) { + $delivery_time_days = ''; + } + if ($price_base_type == 'TTC') { $ttx = $tva_tx; $buyprice = $buyprice / (1 + ($ttx / 100)); } @@ -283,10 +294,13 @@ class ProductFournisseur extends Product $multicurrency_unitBuyPrice = null; $fk_multicurrency = null; if (!empty($conf->multicurrency->enabled)) { - if (empty($multicurrency_tx)) $multicurrency_tx = 1; - if (empty($multicurrency_buyprice)) $multicurrency_buyprice = 0; - if ($multicurrency_price_base_type == 'TTC') - { + if (empty($multicurrency_tx)) { + $multicurrency_tx = 1; + } + if (empty($multicurrency_buyprice)) { + $multicurrency_buyprice = 0; + } + if ($multicurrency_price_base_type == 'TTC') { $ttx = $tva_tx; $multicurrency_buyprice = $multicurrency_buyprice / (1 + ($ttx / 100)); } @@ -309,8 +323,7 @@ class ProductFournisseur extends Product $newvat = $tva_tx; - if (count($localtaxes_array) > 0) - { + if (count($localtaxes_array) > 0) { $localtaxtype1 = $localtaxes_array['0']; $localtax1 = $localtaxes_array['1']; $localtaxtype2 = $localtaxes_array['2']; @@ -321,26 +334,26 @@ class ProductFournisseur extends Product $localtaxtype2 = '0'; $localtax2 = get_localtax($newvat, 2); } - if (empty($localtax1)) $localtax1 = 0; // If = '' then = 0 - if (empty($localtax2)) $localtax2 = 0; // If = '' then = 0 + if (empty($localtax1)) { + $localtax1 = 0; // If = '' then = 0 + } + if (empty($localtax2)) { + $localtax2 = 0; // If = '' then = 0 + } // Check parameters - if ($buyprice != '' && !is_numeric($buyprice)) - { + if ($buyprice != '' && !is_numeric($buyprice)) { } $this->db->begin(); - if ($this->product_fourn_price_id > 0) - { + if ($this->product_fourn_price_id > 0) { // check if price already logged, if not first log current price $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id); - if (is_array($logPrices) && count($logPrices) == 0) - { + if (is_array($logPrices) && count($logPrices) == 0) { $currentPfp = new self($this->db); $result = $currentPfp->fetch_product_fournisseur_price($this->product_fourn_price_id); - if ($result > 0 && $currentPfp->fourn_price != 0) - { + if ($result > 0 && $currentPfp->fourn_price != 0) { $currentPfpUser = new User($this->db); $result = $currentPfpUser->fetch($currentPfp->user_id); if ($result > 0) { @@ -387,27 +400,28 @@ class ProductFournisseur extends Product $sql .= " supplier_reputation = ".(empty($supplier_reputation) ? 'NULL' : "'".$this->db->escape($supplier_reputation)."'").","; $sql .= " barcode = ".(empty($barcode) ? 'NULL' : "'".$this->db->escape($barcode)."'").","; $sql .= " fk_barcode_type = ".(empty($fk_barcode_type) ? 'NULL' : "'".$this->db->escape($fk_barcode_type)."'"); - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", packaging = ".(empty($packaging) ? 1 : $packaging); + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + $sql .= ", packaging = ".(empty($packaging) ? 1 : $packaging); + } $sql .= " WHERE rowid = ".$this->product_fourn_price_id; // TODO Add price_base_type and price_ttc dol_syslog(get_class($this).'::update_buyprice update knowing id of line = product_fourn_price_id = '.$this->product_fourn_price_id, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_UPDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if (!$error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG)) - { + if (!$error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG)) { $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, $multicurrency_unitBuyPrice, $multicurrency_tx, $fk_multicurrency, $multicurrency_code); if ($result < 0) { $error++; } } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return $this->product_fourn_price_id; } else { @@ -431,7 +445,9 @@ class ProductFournisseur extends Product $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price("; $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,"; $sql .= "datec, fk_product, fk_soc, ref_fourn, desc_fourn, fk_user, price, quantity, remise_percent, remise, unitprice, tva_tx, charges, fk_availability, default_vat_code, info_bits, entity, delivery_time_days, supplier_reputation, barcode, fk_barcode_type)"; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", packaging"; + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + $sql .= ", packaging"; + } $sql .= " values("; $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').","; $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').","; @@ -459,7 +475,9 @@ class ProductFournisseur extends Product $sql .= (empty($supplier_reputation) ? 'NULL' : "'".$this->db->escape($supplier_reputation)."'").","; $sql .= (empty($barcode) ? 'NULL' : "'".$this->db->escape($barcode)."'").","; $sql .= (empty($fk_barcode_type) ? 'NULL' : "'".$this->db->escape($fk_barcode_type)."'"); - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", ".(empty($this->packaging) ? 1 : $this->db->escape($this->packaging)); + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + $sql .= ", ".(empty($this->packaging) ? 1 : $this->db->escape($this->packaging)); + } $sql .= ")"; $this->product_fourn_price_id = 0; @@ -483,8 +501,9 @@ class ProductFournisseur extends Product if (!$error) { // Call trigger $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_CREATE', $user); - if ($result < 0) + if ($result < 0) { $error++; + } // End call triggers if (empty($error)) { @@ -532,11 +551,9 @@ class ProductFournisseur extends Product dol_syslog(get_class($this)."::fetch_product_fournisseur_price", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $this->product_fourn_price_id = $rowid; $this->id = $obj->fk_product; @@ -578,18 +595,18 @@ class ProductFournisseur extends Product if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $this->packaging = $obj->packaging; - if ($this->packaging < $this->fourn_qty) $this->packaging = $this->fourn_qty; + if ($this->packaging < $this->fourn_qty) { + $this->packaging = $this->fourn_qty; + } } - if (empty($ignore_expression) && !empty($this->fk_supplier_price_expression)) - { + if (empty($ignore_expression) && !empty($this->fk_supplier_price_expression)) { $priceparser = new PriceParser($this->db); $price_result = $priceparser->parseProductSupplier($this); if ($price_result >= 0) { $this->fourn_price = $price_result; //recalculation of unitprice, as probably the price changed... - if ($this->fourn_qty != 0) - { + if ($this->fourn_qty != 0) { $this->fourn_unitprice = price2num($this->fourn_price / $this->fourn_qty, 'MU'); } else { $this->fourn_unitprice = ""; @@ -629,24 +646,27 @@ class ProductFournisseur extends Product $sql .= " pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.fk_availability, pfp.charges, pfp.info_bits, pfp.delivery_time_days, pfp.supplier_reputation,"; $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code, pfp.datec, pfp.tms,"; $sql .= " pfp.barcode, pfp.fk_barcode_type"; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", pfp.packaging"; + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + $sql .= ", pfp.packaging"; + } $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp, ".MAIN_DB_PREFIX."product as p, ".MAIN_DB_PREFIX."societe as s"; $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")"; $sql .= " AND pfp.fk_soc = s.rowid AND pfp.fk_product = p.rowid"; $sql .= " AND s.status=1"; // only enabled company selected $sql .= " AND pfp.fk_product = ".$prodid; - if (empty($sortfield)) $sql .= " ORDER BY s.nom, pfp.quantity, pfp.price"; - else $sql .= $this->db->order($sortfield, $sortorder); + if (empty($sortfield)) { + $sql .= " ORDER BY s.nom, pfp.quantity, pfp.price"; + } else { + $sql .= $this->db->order($sortfield, $sortorder); + } $sql .= $this->db->plimit($limit, $offset); dol_syslog(get_class($this)."::list_product_fournisseur_price", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $retarray = array(); - while ($record = $this->db->fetch_array($resql)) - { + while ($record = $this->db->fetch_array($resql)) { //define base attribute $prodfourn = new ProductFournisseur($this->db); @@ -683,7 +703,9 @@ class ProductFournisseur extends Product if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $prodfourn->packaging = $record["packaging"]; - if ($prodfourn->packaging < $prodfourn->fourn_qty) $prodfourn->packaging = $prodfourn->fourn_qty; + if ($prodfourn->packaging < $prodfourn->fourn_qty) { + $prodfourn->packaging = $prodfourn->fourn_qty; + } } if (!empty($conf->barcode->enabled)) { @@ -700,10 +722,8 @@ class ProductFournisseur extends Product } } - if (!isset($prodfourn->fourn_unitprice)) - { - if ($prodfourn->fourn_qty != 0) - { + if (!isset($prodfourn->fourn_unitprice)) { + if ($prodfourn->fourn_qty != 0) { $prodfourn->fourn_unitprice = price2num($prodfourn->fourn_price / $prodfourn->fourn_qty, 'MU'); } else { $prodfourn->fourn_unitprice = ""; @@ -735,8 +755,7 @@ class ProductFournisseur extends Product // phpcs:enable global $conf; - if (empty($prodid)) - { + if (empty($prodid)) { dol_syslog("Warning function find_min_price_product_fournisseur were called with prodid empty. May be a bug.", LOG_WARNING); return 0; } @@ -771,30 +790,30 @@ class ProductFournisseur extends Product $sql .= " AND pfp.fk_product = ".$prodid; $sql .= " AND pfp.fk_soc = s.rowid"; $sql .= " AND s.status = 1"; // only enabled society - if ($qty > 0) $sql .= " AND pfp.quantity <= ".$qty; - if ($socid > 0) $sql .= ' AND pfp.fk_soc = '.$socid; + if ($qty > 0) { + $sql .= " AND pfp.quantity <= ".$qty; + } + if ($socid > 0) { + $sql .= ' AND pfp.fk_soc = '.$socid; + } dol_syslog(get_class($this)."::find_min_price_product_fournisseur", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $record_array = array(); //Store each record to array for later search of min - while ($record = $this->db->fetch_array($resql)) - { + while ($record = $this->db->fetch_array($resql)) { $record_array[] = $record; } - if (count($record_array) == 0) - { + if (count($record_array) == 0) { $this->db->free($resql); return 0; } else { $min = -1; - foreach ($record_array as $record) - { + foreach ($record_array as $record) { $fourn_price = $record["price"]; // discount calculated buy price $fourn_unitprice = $record["unitprice"] * (1 - $record["remise_percent"] / 100) - $record["remise"]; @@ -809,16 +828,14 @@ class ProductFournisseur extends Product $price_result = $priceparser->parseProductSupplier($prod_supplier); if ($price_result >= 0) { $fourn_price = price2num($price_result, 'MU'); - if ($record["quantity"] != 0) - { + if ($record["quantity"] != 0) { $fourn_unitprice = price2num($fourn_price / $record["quantity"], 'MU'); } else { $fourn_unitprice = $fourn_price; } } } - if ($fourn_unitprice < $min || $min == -1) - { + if ($fourn_unitprice < $min || $min == -1) { $this->product_fourn_price_id = $record["product_fourn_price_id"]; $this->ref_supplier = $record["ref_fourn"]; $this->ref_fourn = $record["ref_fourn"]; // deprecated @@ -874,8 +891,7 @@ class ProductFournisseur extends Product dol_syslog(get_class($this)."::setSupplierPriceExpression", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { @@ -936,7 +952,9 @@ class ProductFournisseur extends Product } $out .= '</table>'; } else { - $out = ($showunitprice ?price($this->fourn_unitprice * (1 - $this->fourn_remise_percent / 100) + $this->fourn_remise).' '.$langs->trans("HT").' &nbsp; (' : '').($showsuptitle ? $langs->trans("Supplier").': ' : '').$this->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).' / '.$langs->trans("SupplierRef").': '.$this->fourn_ref.($showunitprice ? ')' : ''); + $out = ($showunitprice ? price($this->fourn_unitprice * (1 - $this->fourn_remise_percent / 100) + $this->fourn_remise).' '.$langs->trans("HT").' &nbsp; <span class="opacitymedium">(</span>' : ''); + $out .= ($showsuptitle ? '<span class="opacitymedium">'.$langs->trans("Supplier").'</span>: ' : '').$this->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).' / <span class="opacitymedium">'.$langs->trans("SupplierRef").'</span>: '.$this->ref_supplier; + $out .= ($showunitprice ? '<span class="opacitymedium">)</span>' : ''); } return $out; } @@ -982,18 +1000,19 @@ class ProductFournisseur extends Product $sql .= " AND pfpl.fk_user = u.rowid"; $sql .= " AND pfp.rowid = pfpl.fk_product_fournisseur"; $sql .= " AND pfpl.fk_product_fournisseur = ".$product_fourn_price_id; - if (empty($sortfield)) $sql .= " ORDER BY pfpl.datec"; - else $sql .= $this->db->order($sortfield, $sortorder); + if (empty($sortfield)) { + $sql .= " ORDER BY pfpl.datec"; + } else { + $sql .= $this->db->order($sortfield, $sortorder); + } $sql .= $this->db->plimit($limit, $offset); dol_syslog(get_class($this)."::list_product_fournisseur_price_log", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $retarray = array(); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $tmparray = array(); $tmparray['rowid'] = $obj->rowid; $tmparray['supplier_ref'] = $obj->supplier_ref; @@ -1038,7 +1057,7 @@ class ProductFournisseur extends Product //$out .= '<td class="liste_titre right">'.$langs->trans("QtyMin").'</td>'; $out .= '<td class="liste_titre">'.$langs->trans("User").'</td></tr>'; foreach ($productFournLogList as $productFournLog) { - $out .= '<tr><td class="right">'.dol_print_date($productFournLog['datec'], 'dayhour', 'tzuser').'</td>'; + $out .= '<tr><td>'.dol_print_date($productFournLog['datec'], 'dayhour', 'tzuser').'</td>'; $out .= '<td class="right">'.price($productFournLog['price'], 0, $langs, 1, -1, -1, $conf->currency); if ($productFournLog['multicurrency_code'] != $conf->currency) { $out .= ' ('.price($productFournLog['multicurrency_price'], 0, $langs, 1, -1, -1, $productFournLog['multicurrency_code']).')'; @@ -1126,7 +1145,9 @@ class ProductFournisseur extends Product if ($this->height) { $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units); } - if ($labelsize) $label .= "<br>".$labelsize; + if ($labelsize) { + $label .= "<br>".$labelsize; + } $labelsurfacevolume = ""; if ($this->surface) { @@ -1135,7 +1156,9 @@ class ProductFournisseur extends Product if ($this->volume) { $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units); } - if ($labelsurfacevolume) $label .= "<br>".$labelsurfacevolume; + if ($labelsurfacevolume) { + $label .= "<br>".$labelsurfacevolume; + } } if (!empty($conf->accounting->enabled) && $this->status) { diff --git a/htdocs/fourn/class/paiementfourn.class.php b/htdocs/fourn/class/paiementfourn.class.php index cd172d08345..41c780f70c8 100644 --- a/htdocs/fourn/class/paiementfourn.class.php +++ b/htdocs/fourn/class/paiementfourn.class.php @@ -98,20 +98,19 @@ class PaiementFourn extends Paiement $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; $sql .= ' WHERE p.entity IN ('.getEntity('facture_fourn').')'; - if ($id > 0) - $sql .= ' AND p.rowid = '.$id; - elseif ($ref) + if ($id > 0) { + $sql .= ' AND p.rowid = '.((int) $id); + } elseif ($ref) { $sql .= ' AND p.rowid = '.$ref; - elseif ($fk_bank) + } elseif ($fk_bank) { $sql .= ' AND p.fk_bank = '.$fk_bank; + } //print $sql; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -166,8 +165,7 @@ class PaiementFourn extends Paiement dol_syslog(get_class($this)."::create", LOG_DEBUG); - if ($way == 'dolibarr') - { + if ($way == 'dolibarr') { $amounts = &$this->amounts; $amounts_to_update = &$this->multicurrency_amounts; } else { @@ -175,8 +173,7 @@ class PaiementFourn extends Paiement $amounts_to_update = &$this->amounts; } - foreach ($amounts as $key => $value) - { + foreach ($amounts as $key => $value) { $value_converted = Multicurrency::getAmountConversionFromInvoiceRate($key, $value ? $value : 0, $way, 'facture_fourn'); $totalamount_converted += $value_converted; $amounts_to_update[$key] = price2num($value_converted, 'MT'); @@ -190,13 +187,11 @@ class PaiementFourn extends Paiement $this->db->begin(); - if ($totalamount <> 0) // On accepte les montants negatifs - { + if ($totalamount <> 0) { // On accepte les montants negatifs $ref = $this->getNextNumRef(is_object($thirdparty) ? $thirdparty : ''); $now = dol_now(); - if ($way == 'dolibarr') - { + if ($way == 'dolibarr') { $total = $totalamount; $mtotal = $totalamount_converted; // Maybe use price2num with MT for the converted value } else { @@ -210,28 +205,23 @@ class PaiementFourn extends Paiement $sql .= " '".$this->db->idate($this->datepaye)."', '".$total."', '".$mtotal."', ".$this->paiementid.", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note_private)."', ".$user->id.", 0)"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'paiementfourn'); // Insere tableau des montants / factures - foreach ($this->amounts as $key => $amount) - { + foreach ($this->amounts as $key => $amount) { $facid = $key; - if (is_numeric($amount) && $amount <> 0) - { + if (is_numeric($amount) && $amount <> 0) { $amount = price2num($amount); $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiementfourn_facturefourn (fk_facturefourn, fk_paiementfourn, amount, multicurrency_amount)'; $sql .= ' VALUES ('.$facid.','.$this->id.',\''.$amount.'\', \''.$this->multicurrency_amounts[$key].'\')'; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $invoice = new FactureFournisseur($this->db); $invoice->fetch($facid); // If we want to closed paid invoices - if ($closepaidinvoices) - { + if ($closepaidinvoices) { $paiement = $invoice->getSommePaiement(); //$creditnotes=$invoice->getSumCreditNotesUsed(); $creditnotes = 0; @@ -239,18 +229,20 @@ class PaiementFourn extends Paiement $deposits = 0; $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT'); $remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT'); - if ($remaintopay == 0) - { + if ($remaintopay == 0) { $result = $invoice->setPaid($user, '', ''); - } else dol_syslog("Remain to pay for invoice ".$facid." not null. We do nothing."); + } else { + dol_syslog("Remain to pay for invoice ".$facid." not null. We do nothing."); + } } // Regenerate documents of invoices - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $newlang = ''; $outputlangs = $langs; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $invoice->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $invoice->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -271,11 +263,12 @@ class PaiementFourn extends Paiement } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('PAYMENT_SUPPLIER_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } } else { @@ -288,8 +281,7 @@ class PaiementFourn extends Paiement $error++; } - if ($totalamount <> 0 && $error == 0) // On accepte les montants negatifs - { + if ($totalamount <> 0 && $error == 0) { // On accepte les montants negatifs $this->amount = $total; $this->total = $total; $this->multicurrency_amount = $mtotal; @@ -322,10 +314,8 @@ class PaiementFourn extends Paiement // Verifier si paiement porte pas sur une facture a l'etat payee // Si c'est le cas, on refuse la suppression $billsarray = $this->getBillsArray('paye=1'); - if (is_array($billsarray)) - { - if (count($billsarray)) - { + if (is_array($billsarray)) { + if (count($billsarray)) { $this->error = "ErrorCantDeletePaymentSharedWithPayedInvoice"; $this->db->rollback(); return -1; @@ -337,12 +327,10 @@ class PaiementFourn extends Paiement // Verifier si paiement ne porte pas sur ecriture bancaire rapprochee // Si c'est le cas, on refuse le delete - if ($bank_line_id) - { + if ($bank_line_id) { $accline = new AccountLine($this->db); $accline->fetch($bank_line_id); - if ($accline->rappro) - { + if ($accline->rappro) { $this->error = "ErrorCantDeletePaymentReconciliated"; $this->db->rollback(); return -3; @@ -353,41 +341,34 @@ class PaiementFourn extends Paiement $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn'; $sql .= ' WHERE fk_paiementfourn = '.$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiementfourn'; $sql .= ' WHERE rowid = '.$this->id; $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $this->error = $this->db->error(); $this->db->rollback(); return -3; } // Supprimer l'ecriture bancaire si paiement lie a ecriture - if ($bank_line_id) - { + if ($bank_line_id) { $accline = new AccountLine($this->db); $result = $accline->fetch($bank_line_id); - if ($result > 0) // If result = 0, record not found, we don't try to delete - { + if ($result > 0) { // If result = 0, record not found, we don't try to delete $result = $accline->delete($user); } - if ($result < 0) - { + if ($result < 0) { $this->error = $accline->error; $this->db->rollback(); return -4; } } - if (!$notrigger) - { + if (!$notrigger) { // Appel des triggers $result = $this->call_trigger('PAYMENT_SUPPLIER_DELETE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -413,25 +394,21 @@ class PaiementFourn extends Paiement { $sql = 'SELECT c.rowid, datec, fk_user_author as fk_user_creat, tms'; $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as c'; - $sql .= ' WHERE c.rowid = '.$id; + $sql .= ' WHERE c.rowid = '.((int) $id); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num) - { + if ($num) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; - if ($obj->fk_user_creat) - { + if ($obj->fk_user_creat) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_creat); $this->user_creation = $cuser; } - if ($obj->fk_user_modif) - { + if ($obj->fk_user_modif) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modif); $this->user_modification = $muser; @@ -456,18 +433,18 @@ class PaiementFourn extends Paiement $sql = 'SELECT fk_facturefourn'; $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'facture_fourn as f'; $sql .= ' WHERE pf.fk_facturefourn = f.rowid AND fk_paiementfourn = '.$this->id; - if ($filter) $sql .= ' AND '.$filter; + if ($filter) { + $sql .= ' AND '.$filter; + } dol_syslog(get_class($this).'::getBillsArray', LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $this->db->num_rows($resql); $billsarray = array(); - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $billsarray[$i] = $obj->fk_facturefourn; $i++; @@ -564,20 +541,28 @@ class PaiementFourn extends Paiement $reg = array(); if (preg_match('/^\((.*)\)$/i', $text, $reg)) { // Label generique car entre parentheses. On l'affiche en le traduisant - if ($reg[1] == 'paiement') $reg[1] = 'Payment'; + if ($reg[1] == 'paiement') { + $reg[1] = 'Payment'; + } $text = $langs->trans($reg[1]); } $label = '<u>'.$langs->trans("Payment").'</u><br>'; $label .= '<strong>'.$langs->trans("Ref").':</strong> '.$text; - if ($this->datepaye ? $this->datepaye : $this->date) $label .= '<br><strong>'.$langs->trans("Date").':</strong> '.dol_print_date($this->datepaye ? $this->datepaye : $this->date, 'dayhour'); + if ($this->datepaye ? $this->datepaye : $this->date) { + $label .= '<br><strong>'.$langs->trans("Date").':</strong> '.dol_print_date($this->datepaye ? $this->datepaye : $this->date, 'dayhour'); + } $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/paiement/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; $linkend = '</a>'; $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; return $result; @@ -622,12 +607,15 @@ class PaiementFourn extends Paiement $langs->load("bills"); // Clean parameters (if not defined or using deprecated value) - if (empty($conf->global->SUPPLIER_PAYMENT_ADDON)) $conf->global->SUPPLIER_PAYMENT_ADDON = 'mod_supplier_payment_bronan'; - elseif ($conf->global->SUPPLIER_PAYMENT_ADDON == 'brodator') $conf->global->SUPPLIER_PAYMENT_ADDON = 'mod_supplier_payment_brodator'; - elseif ($conf->global->SUPPLIER_PAYMENT_ADDON == 'bronan') $conf->global->SUPPLIER_PAYMENT_ADDON = 'mod_supplier_payment_bronan'; + if (empty($conf->global->SUPPLIER_PAYMENT_ADDON)) { + $conf->global->SUPPLIER_PAYMENT_ADDON = 'mod_supplier_payment_bronan'; + } elseif ($conf->global->SUPPLIER_PAYMENT_ADDON == 'brodator') { + $conf->global->SUPPLIER_PAYMENT_ADDON = 'mod_supplier_payment_brodator'; + } elseif ($conf->global->SUPPLIER_PAYMENT_ADDON == 'bronan') { + $conf->global->SUPPLIER_PAYMENT_ADDON = 'mod_supplier_payment_bronan'; + } - if (!empty($conf->global->SUPPLIER_PAYMENT_ADDON)) - { + if (!empty($conf->global->SUPPLIER_PAYMENT_ADDON)) { $mybool = false; $file = $conf->global->SUPPLIER_PAYMENT_ADDON.".php"; @@ -640,8 +628,7 @@ class PaiementFourn extends Paiement $dir = dol_buildpath($reldir."core/modules/supplier_payment/"); // Load file with numbering class (if found) - if (is_file($dir.$file) && is_readable($dir.$file)) - { + if (is_file($dir.$file) && is_readable($dir.$file)) { $mybool |= include_once $dir.$file; } } @@ -706,18 +693,15 @@ class PaiementFourn extends Paiement $langs->load("suppliers"); // Set the model on the model name to use - if (empty($modele)) - { - if (!empty($conf->global->SUPPLIER_PAYMENT_ADDON_PDF)) - { + if (empty($modele)) { + if (!empty($conf->global->SUPPLIER_PAYMENT_ADDON_PDF)) { $modele = $conf->global->SUPPLIER_PAYMENT_ADDON_PDF; } else { $modele = ''; // No default value. For supplier invoice, we allow to disable all PDF generation } } - if (empty($modele)) - { + if (empty($modele)) { return 0; } else { $modelpath = "core/modules/supplier_payment/doc/"; @@ -738,12 +722,9 @@ class PaiementFourn extends Paiement global $conf; $way = 'dolibarr'; - if (!empty($conf->multicurrency->enabled)) - { - foreach ($this->multicurrency_amounts as $value) - { - if (!empty($value)) // one value found then payment is in invoice currency - { + if (!empty($conf->multicurrency->enabled)) { + foreach ($this->multicurrency_amounts as $value) { + if (!empty($value)) { // one value found then payment is in invoice currency $way = 'customer'; break; } @@ -766,14 +747,11 @@ class PaiementFourn extends Paiement // phpcs:enable require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; - if (empty($force_thirdparty_id)) - { + if (empty($force_thirdparty_id)) { $billsarray = $this->getBillsArray(); // From payment, the fk_soc isn't available, we should load the first supplier invoice to get him - if (!empty($billsarray)) - { + if (!empty($billsarray)) { $supplier_invoice = new FactureFournisseur($this->db); - if ($supplier_invoice->fetch($billsarray[0]) > 0) - { + if ($supplier_invoice->fetch($billsarray[0]) > 0) { $force_thirdparty_id = $supplier_invoice->fk_soc; } } diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 2ed7ccab8ef..fe854c72d48 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -41,10 +41,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; -if (!empty($conf->supplier_proposal->enabled)) +if (!empty($conf->supplier_proposal->enabled)) { require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; -if (!empty($conf->product->enabled)) +} +if (!empty($conf->product->enabled)) { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +} if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; @@ -56,7 +58,9 @@ if (!empty($conf->variants->enabled)) { } $langs->loadLangs(array('admin', 'orders', 'sendings', 'companies', 'bills', 'propal', 'receptions', 'supplier_proposal', 'deliveries', 'products', 'stocks', 'productbatch')); -if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); +if (!empty($conf->incoterm->enabled)) { + $langs->load('incoterm'); +} $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); @@ -80,7 +84,9 @@ $datelivraison = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int' // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -93,20 +99,26 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Load object -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $ret = $object->fetch($id, $ref); - if ($ret < 0) dol_print_error($db, $object->error); + if ($ret < 0) { + dol_print_error($db, $object->error); + } $ret = $object->fetch_thirdparty(); - if ($ret < 0) dol_print_error($db, $object->error); -} elseif (!empty($socid) && $socid > 0) -{ + if ($ret < 0) { + dol_print_error($db, $object->error); + } +} elseif (!empty($socid) && $socid > 0) { $fourn = new Fournisseur($db); $ret = $fourn->fetch($socid); - if ($ret < 0) dol_print_error($db, $object->error); + if ($ret < 0) { + dol_print_error($db, $object->error); + } $object->socid = $fourn->id; $ret = $object->fetch_thirdparty(); - if ($ret < 0) dol_print_error($db, $object->error); + if ($ret < 0) { + dol_print_error($db, $object->error); + } } // Common permissions @@ -136,14 +148,13 @@ $permissiontoadd = $usercancreate; // Used by the include of actions_addupdated $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)) -{ - if ($cancel) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -156,67 +167,69 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - if ($action == 'setref_supplier' && $usercancreate) - { + if ($action == 'setref_supplier' && $usercancreate) { $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier', 'alpha'), '', null, 'text', '', $user, 'ORDER_SUPPLIER_MODIFY'); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Set incoterm - if ($action == 'set_incoterms' && $usercancreate) - { + if ($action == 'set_incoterms' && $usercancreate) { $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // payment conditions - if ($action == 'setconditions' && $usercancreate) - { + if ($action == 'setconditions' && $usercancreate) { $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // payment mode - if ($action == 'setmode' && $usercancreate) - { + if ($action == 'setmode' && $usercancreate) { $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); - } - - // Multicurrency Code - elseif ($action == 'setmulticurrencycode' && $usercancreate) { + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } 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'))); + } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + // Multicurrency rate + $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int')); } // bank account - if ($action == 'setbankaccount' && $usercancreate) - { + if ($action == 'setbankaccount' && $usercancreate) { $result = $object->setBankAccount(GETPOST('fk_account', 'int')); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // date of delivery - if ($action == 'setdate_livraison' && $usercancreate) - { + if ($action == 'setdate_livraison' && $usercancreate) { $result = $object->setDeliveryDate($user, $datelivraison); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Set project - if ($action == 'classin' && $usercancreate) - { + if ($action == 'classin' && $usercancreate) { $result = $object->setProject($projectid); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Edit Thirdparty - if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $action == 'set_thirdparty' && $usercancreate && $object->statut == CommandeFournisseur::STATUS_DRAFT) - { + if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $action == 'set_thirdparty' && $usercancreate && $object->statut == CommandeFournisseur::STATUS_DRAFT) { $new_socid = GETPOST('new_socid', 'int'); if (!empty($new_socid) && $new_socid != $object->thirdparty->id) { $db->begin(); @@ -229,8 +242,9 @@ if (empty($reshook)) $res = $db->query($sql); - if (!$res) $db->rollback(); - else { + if (!$res) { + $db->rollback(); + } else { $db->commit(); // Replace prices for each lines by new supplier prices @@ -275,38 +289,44 @@ if (empty($reshook)) exit; } - if ($action == 'setremisepercent' && $usercancreate) - { + if ($action == 'setremisepercent' && $usercancreate) { $result = $object->set_remise($user, $_POST['remise_percent']); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } - if ($action == 'reopen') // no test on permission here, permission to use will depends on status - { - if (in_array($object->statut, array(1, 2, 3, 4, 5, 6, 7, 9))) - { - if ($object->statut == 1) $newstatus = 0; // Validated->Draft - elseif ($object->statut == 2) $newstatus = 0; // Approved->Draft - elseif ($object->statut == 3) $newstatus = 2; // Ordered->Approved - elseif ($object->statut == 4) $newstatus = 3; - elseif ($object->statut == 5) - { + if ($action == 'reopen') { // no test on permission here, permission to use will depends on status + if (in_array($object->statut, array(1, 2, 3, 4, 5, 6, 7, 9))) { + if ($object->statut == 1) { + $newstatus = 0; // Validated->Draft + } elseif ($object->statut == 2) { + $newstatus = 0; // Approved->Draft + } elseif ($object->statut == 3) { + $newstatus = 2; // Ordered->Approved + } elseif ($object->statut == 4) { + $newstatus = 3; + } elseif ($object->statut == 5) { //$newstatus=2; // Ordered // TODO Can we set it to submited ? //$newstatus=3; // Submited // TODO If there is at least one reception, we can set to Received->Received partially $newstatus = 4; // Received partially - } elseif ($object->statut == 6) $newstatus = 2; // Canceled->Approved - elseif ($object->statut == 7) $newstatus = 3; // Canceled->Process running - elseif ($object->statut == 9) $newstatus = 1; // Refused->Validated - else $newstatus = 2; + } elseif ($object->statut == 6) { + $newstatus = 2; // Canceled->Approved + } elseif ($object->statut == 7) { + $newstatus = 3; // Canceled->Process running + } elseif ($object->statut == 9) { + $newstatus = 1; // Refused->Validated + } else { + $newstatus = 2; + } //print "old status = ".$object->statut.' new status = '.$newstatus; $db->begin(); $result = $object->setStatus($user, $newstatus); - if ($result > 0) - { + if ($result > 0) { // Currently the "Re-open" also remove the billed flag because there is no button "Set unpaid" yet. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; $sql .= ' SET billed = 0'; @@ -314,8 +334,7 @@ if (empty($reshook)) $resql = $db->query($sql); - if ($newstatus == 0) - { + if ($newstatus == 0) { $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; $sql .= ' SET fk_user_approve = null, fk_user_approve2 = null, date_approve = null, date_approve2 = null'; $sql .= ' WHERE rowid = '.$object->id; @@ -338,8 +357,7 @@ if (empty($reshook)) /* * Classify supplier order as billed */ - if ($action == 'classifybilled' && $usercancreate) - { + if ($action == 'classifybilled' && $usercancreate) { $ret = $object->classifyBilled($user); if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -347,8 +365,7 @@ if (empty($reshook)) } // Add a product line - if ($action == 'addline' && $usercancreate) - { + if ($action == 'addline' && $usercancreate) { $db->begin(); $langs->load('errors'); @@ -360,20 +377,19 @@ if (empty($reshook)) $date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); $prod_entry_mode = GETPOST('prod_entry_mode'); - if ($prod_entry_mode == 'free') - { + if ($prod_entry_mode == 'free') { $idprod = 0; - $price_ht = price2num(GETPOST('price_ht'), 'MU'); + $price_ht = price2num(GETPOST('price_ht'), 'MU', 2); $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); } else { $idprod = GETPOST('idprod', 'int'); - $price_ht = price2num(GETPOST('price_ht'), 'MU'); + $price_ht = price2num(GETPOST('price_ht'), 'MU', 2); $tva_tx = ''; } $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS'); $remise_percent = price2num(GETPOST('remise_percent'.$predef), 2); - $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU'); + $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2); // Extrafields $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -386,28 +402,23 @@ if (empty($reshook)) } } - if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) - { + if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) { setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && !GETPOST('idprodfournprice') && GETPOST('type') < 0) - { + if ($prod_entry_mode == 'free' && !GETPOST('idprodfournprice') && GETPOST('type') < 0) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') // Unit price can be 0 but not '' - { + if ($prod_entry_mode == 'free' && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') { // Unit price can be 0 but not '' setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && !GETPOST('dp_desc')) - { + if ($prod_entry_mode == 'free' && !GETPOST('dp_desc')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); $error++; } - if (GETPOST('qty', 'int') == '') - { + if (GETPOST('qty', 'int') == '') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; } @@ -426,51 +437,49 @@ if (empty($reshook)) } } - if ($prod_entry_mode != 'free' && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' - { + if ($prod_entry_mode != 'free' && empty($error)) { // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' $productsupplier = new ProductFournisseur($db); $idprod = 0; - if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') { + $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + } $reg = array(); - if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) - { + if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) { $idprod = $reg[1]; $res = $productsupplier->fetch($idprod); // Load product from its id // Call to init some price properties of $productsupplier // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price - if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) - { + if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) { $fksoctosearch = 0; $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist - if ($productsupplier->fourn_socid != $socid) // The price we found is for another supplier, so we clear supplier price - { + if ($productsupplier->fourn_socid != $socid) { // The price we found is for another supplier, so we clear supplier price $productsupplier->ref_supplier = ''; } } else { $fksoctosearch = $object->thirdparty->id; $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist } - } elseif (GETPOST('idprodfournprice', 'alpha') > 0) - { + } elseif (GETPOST('idprodfournprice', 'alpha') > 0) { $qtytosearch = $qty; // Just to see if a price exists for the quantity. Not used to found vat. //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist $idprod = $productsupplier->get_buyprice(GETPOST('idprodfournprice', 'alpha'), $qtytosearch); $res = $productsupplier->fetch($idprod); } - if ($idprod > 0) - { + if ($idprod > 0) { $label = $productsupplier->label; // Define output language if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) + } + if (empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -489,8 +498,12 @@ if (empty($reshook)) $product_desc=''; } - if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $desc = $product_desc; - if (!empty($product_desc) && trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) { + $desc = $product_desc; + } + if (!empty($product_desc) && trim($product_desc) != trim($desc)) { + $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + } $type = $productsupplier->type; if ($price_ht != '' || $price_ht_devise != '') { @@ -514,11 +527,15 @@ if (empty($reshook)) $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha')); $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha')); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); - if (empty($pu)) $pu = 0; // If pu is '' or null, we force to have a numeric value + if (empty($pu)) { + $pu = 0; // If pu is '' or null, we force to have a numeric value + } $result = $object->addline( $desc, @@ -545,22 +562,19 @@ if (empty($reshook)) 0 ); } - if ($idprod == -99 || $idprod == 0) - { + if ($idprod == -99 || $idprod == 0) { // Product not selected $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors'); } - if ($idprod == -1) - { + if ($idprod == -1) { // Quantity too low $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); } - } elseif (empty($error)) // $price_ht is already set - { + } elseif (empty($error)) { // $price_ht is already set $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); $tva_tx = str_replace('*', '', $tva_tx); $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); @@ -570,14 +584,15 @@ if (empty($reshook)) $fk_unit = GETPOST('units', 'alpha'); - $tva_tx = price2num($tva_tx); // When vat is text input field + if (!preg_match('/\((.*)\)/', $tva_tx)) { + $tva_tx = price2num($tva_tx); // When vat is text input field + } // Local Taxes $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); - if ($price_ht !== '') - { + if ($price_ht !== '') { $pu_ht = price2num($price_ht, 'MU'); // $pu_ht must be rounded according to settings } else { $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); @@ -590,19 +605,21 @@ if (empty($reshook)) } //print "xx".$tva_tx; exit; - if (!$error && $result > 0) - { + if (!$error && $result > 0) { $db->commit(); $ret = $object->fetch($object->id); // Reload to get new records // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -611,7 +628,9 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } unset($_POST ['prod_entry_mode']); @@ -656,17 +675,17 @@ if (empty($reshook)) /* * Updating a line in the order */ - if ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) - { + if ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) { $db->begin(); $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); - if ($lineid) - { + if ($lineid) { $line = new CommandeFournisseurLigne($db); $res = $line->fetch($lineid); - if (!$res) dol_print_error($db); + if (!$res) { + dol_print_error($db); + } } $productsupplier = new ProductFournisseur($db); @@ -690,24 +709,22 @@ if (empty($reshook)) $localtax1_rate = get_localtax($vat_rate, 1, $mysoc, $object->thirdparty); $localtax2_rate = get_localtax($vat_rate, 2, $mysoc, $object->thirdparty); - if (GETPOST('price_ht') != '') - { + if (GETPOST('price_ht') != '') { $price_base_type = 'HT'; - $ht = price2num(GETPOST('price_ht')); + $ht = price2num(GETPOST('price_ht'), '', 2); } else { $vatratecleaned = $vat_rate; - if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) // If vat is "xx (yy)" - { + if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) { // If vat is "xx (yy)" $vatratecleaned = trim($reg[1]); $vatratecode = $reg[2]; } - $ttc = price2num(GETPOST('price_ttc')); + $ttc = price2num(GETPOST('price_ttc'), '', 2); $ht = $ttc / (1 + ($vatratecleaned / 100)); $price_base_type = 'HT'; } - $pu_ht_devise = GETPOST('multicurrency_subprice'); + $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2); // Extrafields Lines $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -767,15 +784,17 @@ if (empty($reshook)) unset($_POST['date_endmonth']); unset($_POST['date_endyear']); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -784,7 +803,9 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } $db->commit(); @@ -797,20 +818,20 @@ if (empty($reshook)) } // Remove a product line - if ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) - { + if ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) { $db->begin(); $result = $object->deleteline($lineid); - if ($result > 0) - { + if ($result > 0) { // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -837,21 +858,22 @@ if (empty($reshook)) } // Validate - if ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) - { + if ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) { $db->begin(); $object->date_commande = dol_now(); $result = $object->valid($user); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -871,8 +893,7 @@ if (empty($reshook)) } // If we have permission, and if we don't need to provide the idwarehouse, we go directly on approved step - if (!$error && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE) && $usercanapprove && !(!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1))) - { + if (!$error && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE) && $usercanapprove && !(!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1))) { $action = 'confirm_approve'; // can make standard or first level approval also if permission is set } @@ -883,41 +904,39 @@ if (empty($reshook)) } } - if (($action == 'confirm_approve' || $action == 'confirm_approve2') && $confirm == 'yes' && $usercanapprove) - { + if (($action == 'confirm_approve' || $action == 'confirm_approve2') && $confirm == 'yes' && $usercanapprove) { $db->begin(); $idwarehouse = GETPOST('idwarehouse', 'int'); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { - $qualified_for_stock_change = $object->hasProductsOrServices(1); + $qualified_for_stock_change = $object->hasProductsOrServices(1); } // Check parameters - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) // warning name of option should be STOCK_CALCULATE_ON_SUPPLIER_APPROVE_ORDER - { - if (!$idwarehouse || $idwarehouse == -1) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) { // warning name of option should be STOCK_CALCULATE_ON_SUPPLIER_APPROVE_ORDER + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; } } - if (!$error) - { + if (!$error) { $result = $object->approve($user, $idwarehouse, ($action == 'confirm_approve2' ? 1 : 0)); - if ($result > 0) - { + if ($result > 0) { if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -940,11 +959,9 @@ if (empty($reshook)) } } - if ($action == 'confirm_refuse' && $confirm == 'yes' && $usercanapprove) - { + if ($action == 'confirm_refuse' && $confirm == 'yes' && $usercanapprove) { $result = $object->refuse($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); exit; } else { @@ -962,19 +979,20 @@ if (empty($reshook)) } } - if ($action == 'confirm_commande' && $confirm == 'yes' && $usercanorder) - { + if ($action == 'confirm_commande' && $confirm == 'yes' && $usercanorder) { $db->begin(); $result = $object->commande($user, GETPOST("datecommande"), GETPOST("methode", 'int'), GETPOST('comment', 'alphanohtml')); - if ($result > 0) - { - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if ($result > 0) { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -998,11 +1016,9 @@ if (empty($reshook)) } - if ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) - { + if ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) { $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".DOL_URL_ROOT.'/fourn/commande/list.php?restore_lastsearch_values=1'); exit; } else { @@ -1011,19 +1027,15 @@ if (empty($reshook)) } // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) - { - if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) - { + if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) { + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { - if ($object->id > 0) - { + if ($object->id > 0) { $orig = clone $object; $result = $object->createFromClone($user, $socid); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit; } else { @@ -1036,22 +1048,18 @@ if (empty($reshook)) } // Set status of reception (complete, partial, ...) - if ($action == 'livraison' && $usercanreceived) - { + if ($action == 'livraison' && $usercanreceived) { $db->begin(); - if (GETPOST("type") != '') - { + if (GETPOST("type") != '') { $date_liv = dol_mktime(GETPOST('rehour'), GETPOST('remin'), GETPOST('resec'), GETPOST("remonth"), GETPOST("reday"), GETPOST("reyear")); $result = $object->Livraison($user, $date_liv, GETPOST("type"), GETPOST("comment")); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($result > 0) - { + if ($result > 0) { $langs->load("deliveries"); setEventMessages($langs->trans("DeliveryStateSaved"), null); $action = ''; - } elseif ($result == -3) - { + } elseif ($result == -3) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } else { @@ -1070,11 +1078,9 @@ if (empty($reshook)) } } - if ($action == 'confirm_cancel' && $confirm == 'yes' && $usercanorder) - { + if ($action == 'confirm_cancel' && $confirm == 'yes' && $usercanorder) { $result = $object->cancel($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); exit; } else { @@ -1097,55 +1103,51 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $object->insertExtraFields('ORDER_SUPPLIER_MODIFY'); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } /* * Create an order */ - if ($action == 'add' && $usercancreate) - { - $error = 0; + if ($action == 'add' && $usercancreate) { + $error = 0; $selectedLines = GETPOST('toselect', 'array'); - if ($socid < 1) - { + if ($socid < 1) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors'); $action = 'create'; $error++; } - if (!$error) - { + if (!$error) { $db->begin(); // Creation commande $object->ref_supplier = GETPOST('refsupplier'); $object->socid = $socid; - $object->cond_reglement_id = GETPOST('cond_reglement_id'); - $object->mode_reglement_id = GETPOST('mode_reglement_id'); + $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int'); + $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int'); $object->fk_account = GETPOST('fk_account', 'int'); $object->note_private = GETPOST('note_private', 'restricthtml'); $object->note_public = GETPOST('note_public', 'restricthtml'); @@ -1155,26 +1157,23 @@ if (empty($reshook)) $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); - $object->fk_project = GETPOST('projectid'); + $object->fk_project = GETPOST('projectid', 'int'); // Fill array 'array_options' with data from add form - if (!$error) - { + if (!$error) { $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; - } + if ($ret < 0) { + $error++; + } + } - if (!$error) - { - // If creation from another object of another module (Example: origin=propal, originid=1) - if (!empty($origin) && !empty($originid)) - { - if ($origin == 'propal' || $origin == 'proposal') - { + if (!$error) { + // If creation from another object of another module (Example: origin=propal, originid=1) + if (!empty($origin) && !empty($originid)) { + if ($origin == 'propal' || $origin == 'proposal') { $classname = 'Propal'; $element = 'comm/propal'; $subelement = 'propal'; - } elseif ($origin == 'order' || $origin == 'commande') - { + } elseif ($origin == 'order' || $origin == 'commande') { $classname = 'Commande'; $element = $subelement = 'commande'; } else { @@ -1194,23 +1193,20 @@ if (empty($reshook)) } $id = $object->create($user); - if ($id > 0) - { + if ($id > 0) { dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $srcobject = new $classname($db); dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); $result = $srcobject->fetch($object->origin_id); - if ($result > 0) - { + if ($result > 0) { $tmpdate = ($srcobject->delivery_date ? $srcobject->delivery_date : $srcobject->date_livraison); $object->setDeliveryDate($user, $tmpdate); $object->set_id_projet($user, $srcobject->fk_project); $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject, 'fetch_lines')) - { + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) { $srcobject->fetch_lines(); $lines = $srcobject->lines; } @@ -1218,10 +1214,10 @@ if (empty($reshook)) $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { - if (empty($lines[$i]->subprice) || $lines[$i]->qty <= 0 || !in_array($lines[$i]->id, $selectedLines)) + for ($i = 0; $i < $num; $i++) { + if (empty($lines[$i]->subprice) || $lines[$i]->qty <= 0 || !in_array($lines[$i]->id, $selectedLines)) { continue; + } $label = (!empty($lines[$i]->label) ? $lines[$i]->label : ''); $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->product_desc); @@ -1233,20 +1229,17 @@ if (empty($reshook)) } // Extrafields - if (method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if - { + if (method_exists($lines[$i], 'fetch_optionals')) { // For avoid conflicts if $lines[$i]->fetch_optionals(); $array_option = $lines[$i]->array_options; } $ref_supplier = ''; $product_fourn_price_id = 0; - if ($origin == "commande") - { + if ($origin == "commande") { $productsupplier = new ProductFournisseur($db); $result = $productsupplier->find_min_price_product_fournisseur($lines[$i]->fk_product, $lines[$i]->qty, $srcobject->socid); - if ($result > 0) - { + if ($result > 0) { $ref_supplier = $productsupplier->ref_supplier; $product_fourn_price_id = $productsupplier->product_fourn_price_id; } @@ -1257,8 +1250,7 @@ if (empty($reshook)) $tva_tx = $lines[$i]->tva_tx; - if ($origin == "commande") - { + if ($origin == "commande") { $soc = new societe($db); $soc->fetch($socid); $tva_tx = get_default_tva($soc, $mysoc, $lines[$i]->fk_product, $product_fourn_price_id); @@ -1307,8 +1299,9 @@ if (empty($reshook)) $parameters = array('objFrom' => $srcobject); $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been - if ($reshook < 0) + if ($reshook < 0) { $error++; + } } else { setEventMessages($srcobject->error, $srcobject->errors, 'errors'); $error++; @@ -1318,17 +1311,15 @@ if (empty($reshook)) $error++; } } else { - $id = $object->create($user); - if ($id < 0) - { + $id = $object->create($user); + if ($id < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } } } - if ($error) - { + if ($error) { $langs->load("errors"); $db->rollback(); $action = 'create'; @@ -1341,8 +1332,7 @@ if (empty($reshook)) } } - if ($action == 'webservice' && GETPOST('mode', 'alpha') == "send" && !GETPOST('cancel', 'alpha')) - { + if ($action == 'webservice' && GETPOST('mode', 'alpha') == "send" && !GETPOST('cancel', 'alpha')) { $ws_url = $object->thirdparty->webservices_url; $ws_key = $object->thirdparty->webservices_key; $ws_user = GETPOST('ws_user', 'alpha'); @@ -1380,13 +1370,11 @@ if (empty($reshook)) //Prepare the order lines from order $order_lines = array(); - foreach ($object->lines as $line) - { + foreach ($object->lines as $line) { $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $line->ref_supplier); $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, ''); - if ($result_product["result"]["result_code"] == "OK") - { + if ($result_product["result"]["result_code"] == "OK") { $order_lines[] = array( 'desc' => $line->product_desc, 'type' => $line->product_type, @@ -1417,11 +1405,9 @@ if (empty($reshook)) $ws_parameters = array('authentication'=>$ws_authentication, 'order' => $order); $result_order = $soapclient_order->call("createOrder", $ws_parameters, $ws_ns, ''); - if (empty($result_order["result"]["result_code"])) //No result, check error str - { + if (empty($result_order["result"]["result_code"])) { //No result, check error str setEventMessages($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", null, 'errors'); - } elseif ($result_order["result"]["result_code"] != "OK") //Something went wrong - { + } elseif ($result_order["result"]["result_code"] != "OK") { //Something went wrong setEventMessages($langs->trans("SOAPError")." '".$result_order["result"]["result_code"]."' - '".$result_order["result"]["result_label"]."'", null, 'errors'); } else { setEventMessages($langs->trans("RemoteOrderRef")." ".$result_order["ref"], null, 'mesgs'); @@ -1429,45 +1415,33 @@ if (empty($reshook)) } } - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) - { - if ($action == 'addcontact') - { - if ($object->id > 0) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) { + if ($action == 'addcontact') { + if ($object->id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // bascule du statut d'un contact - elseif ($action == 'swapstatut' && $object->id > 0) - { + } elseif ($action == 'swapstatut' && $object->id > 0) { + // bascule du statut d'un contact $result = $object->swapContactStatus(GETPOST('ligne')); - } - - // Efface un contact - elseif ($action == 'deletecontact' && $object->id > 0) - { + } elseif ($action == 'deletecontact' && $object->id > 0) { + // Efface un contact $result = $object->delete_contact($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -1486,15 +1460,16 @@ $form = new Form($db); $formfile = new FormFile($db); $formorder = new FormOrder($db); $productstatic = new Product($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $help_url = 'EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; llxHeader('', $langs->trans("Order"), $help_url); $now = dol_now(); -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans('NewOrderSupplier'), '', 'supplier_order'); dol_htmloutput_events(); @@ -1502,14 +1477,12 @@ if ($action == 'create') $currency_code = $conf->currency; $societe = ''; - if ($socid > 0) - { + if ($socid > 0) { $societe = new Societe($db); $societe->fetch($socid); } - if (!empty($origin) && !empty($originid)) - { + if (!empty($origin) && !empty($originid)) { // Parse element/subelement (ex: project_task) $element = $subelement = $origin; $regs = array(); @@ -1518,12 +1491,10 @@ if ($action == 'create') $subelement = $regs[2]; } - if ($origin == 'propal' || $origin == 'proposal') - { + if ($origin == 'propal' || $origin == 'proposal') { $classname = 'Propal'; $element = 'comm/propal'; $subelement = 'propal'; - } elseif ($origin == 'order' || $origin == 'commande') - { + } elseif ($origin == 'order' || $origin == 'commande') { $classname = 'Commande'; $element = $subelement = 'commande'; } else { @@ -1536,8 +1507,9 @@ if ($action == 'create') $objectsrc = new $classname($db); $objectsrc->fetch($originid); - if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) + if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) { $objectsrc->fetch_lines(); + } $objectsrc->fetch_thirdparty(); // Replicate extrafields @@ -1560,10 +1532,13 @@ if ($action == 'create') $datedelivery = (!empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : (!empty($objectsrc->delivery_date) ? $objectsrc->delivery_date : '')); - if (!empty($conf->multicurrency->enabled)) - { - if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code; - if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; + if (!empty($conf->multicurrency->enabled)) { + if (!empty($objectsrc->multicurrency_code)) { + $currency_code = $objectsrc->multicurrency_code; + } + if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) { + $currency_tx = $objectsrc->multicurrency_tx; + } } $note_private = $object->getDefaultCreateValueFor('note_private', (!empty($objectsrc->note_private) ? $objectsrc->note_private : null)); @@ -1575,15 +1550,21 @@ if ($action == 'create') $cond_reglement_id = $societe->cond_reglement_supplier_id; $mode_reglement_id = $societe->mode_reglement_supplier_id; - if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) $currency_code = $societe->multicurrency_code; + if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) { + $currency_code = $societe->multicurrency_code; + } $note_private = $object->getDefaultCreateValueFor('note_private'); $note_public = $object->getDefaultCreateValueFor('note_public'); } // If not defined, set default value from constant - if (empty($cond_reglement_id) && !empty($conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_TERM_ID)) $cond_reglement_id = $conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_TERM_ID; - if (empty($mode_reglement_id) && !empty($conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_MODE_ID)) $mode_reglement_id = $conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_MODE_ID; + if (empty($cond_reglement_id) && !empty($conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_TERM_ID)) { + $cond_reglement_id = $conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_TERM_ID; + } + if (empty($mode_reglement_id) && !empty($conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_MODE_ID)) { + $mode_reglement_id = $conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_MODE_ID; + } print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -1592,7 +1573,9 @@ if ($action == 'create') print '<input type="hidden" name="remise_percent" value="'.$soc->remise_supplier_percent.'">'; print '<input type="hidden" name="origin" value="'.$origin.'">'; print '<input type="hidden" name="originid" value="'.$originid.'">'; - if (!empty($currency_tx)) print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">'; + if (!empty($currency_tx)) { + print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">'; + } print dol_get_fiche_head(''); @@ -1605,15 +1588,13 @@ if ($action == 'create') print '<tr><td class="fieldrequired">'.$langs->trans('Supplier').'</td>'; print '<td>'; - if ($socid > 0) - { + if ($socid > 0) { print $societe->getNomUrl(1); print '<input type="hidden" name="socid" value="'.$socid.'">'; } else { print img_picto('', 'company').$form->select_company((empty($socid) ? '' : $socid), 'socid', 's.fournisseur=1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); // reload page to retrieve customer informations - if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) - { + if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) { print '<script> $(document).ready(function() { $("#socid").change(function() { @@ -1628,8 +1609,7 @@ if ($action == 'create') } print '</td>'; - if ($societe->id > 0) - { + if ($societe->id > 0) { // Discounts for third party print '<tr><td>'.$langs->trans('Discounts').'</td><td>'; @@ -1663,13 +1643,14 @@ if ($action == 'create') print '</td>'; print '<td>'; $usehourmin = 0; - if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin = 1; + if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) { + $usehourmin = 1; + } print $form->selectDate($datelivraison ? $datelivraison : -1, 'liv_', $usehourmin, $usehourmin, '', "set"); print '</td></tr>'; // Bank Account - if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && !empty($conf->banque->enabled)) - { + if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && !empty($conf->banque->enabled)) { $langs->load("bank"); print '<tr><td>'.$langs->trans('BankAccount').'</td><td>'; print img_picto('', 'bank_account', 'class="paddingrightonly"'); @@ -1678,8 +1659,7 @@ if ($action == 'create') } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); $langs->load('projects'); @@ -1690,8 +1670,7 @@ if ($action == 'create') } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { $fkincoterms = (!empty($object->fk_incoterms) ? $object->fk_incoterms : ($socid > 0 ? $societe->fk_incoterms : '')); $locincoterms = (!empty($object->location_incoterms) ? $object->location_incoterms : ($socid > 0 ? $societe->location_incoterms : '')); print '<tr>'; @@ -1702,8 +1681,7 @@ if ($action == 'create') } // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<tr>'; print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>'; print '<td class="maxwidthonsmartphone">'; @@ -1740,20 +1718,17 @@ if ($action == 'create') print '<tr><td>'.$langs->trans($newclassname).'</td><td>'.$objectsrc->getNomUrl(1).'</td></tr>'; print '<tr><td>'.$langs->trans('AmountHT').'</td><td>'.price($objectsrc->total_ht).'</td></tr>'; print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($objectsrc->total_tva)."</td></tr>"; - if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE - { + if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1 RE print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1)."</td></tr>"; } - if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF - { + if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2 IRPF print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2)."</td></tr>"; } print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($objectsrc->total_ttc)."</td></tr>"; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht).'</td></tr>'; print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva).'</td></tr>'; print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc).'</td></tr>'; @@ -1765,8 +1740,7 @@ if ($action == 'create') $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } @@ -1784,8 +1758,7 @@ if ($action == 'create') // Show origin lines - if (!empty($origin) && !empty($originid) && is_object($objectsrc)) - { + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) { $title = $langs->trans('ProductsAndServices'); print load_fiche_titre($title); @@ -1801,7 +1774,9 @@ if ($action == 'create') $societe = new Fournisseur($db); $result = $societe->fetch($object->socid); - if ($result < 0) dol_print_error($db); + if ($result < 0) { + dol_print_error($db); + } $author = new User($db); $author->fetch($object->user_author_id); @@ -1818,14 +1793,12 @@ if ($action == 'create') $formconfirm = ''; // Confirmation de la suppression de la commande - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteOrder'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 2); } // Clone confirmation - if ($action == 'clone') - { + if ($action == 'clone') { // Create an array for form $formquestion = array( array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.fournisseur=1)')) @@ -1835,24 +1808,22 @@ if ($action == 'create') } // Confirmation de la validation - if ($action == 'valid') - { + if ($action == 'valid') { $object->date_commande = dol_now(); // We check if number is temporary number - if (preg_match('/^[\(]?PROV/i', $object->ref) || empty($object->ref)) // empty should not happened, but when it occurs, the test save life - { + if (preg_match('/^[\(]?PROV/i', $object->ref) || empty($object->ref)) { // empty should not happened, but when it occurs, the test save life $newref = $object->getNextNumRef($object->thirdparty); - } else $newref = $object->ref; + } else { + $newref = $object->ref; + } - if ($newref < 0) - { + if ($newref < 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = ''; } else { $text = $langs->trans('ConfirmValidateOrder', $newref); - if (!empty($conf->notification->enabled)) - { + if (!empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; $notify = new Notify($db); $text .= '<br>'; @@ -1864,24 +1835,23 @@ if ($action == 'create') } // Confirm approval - if ($action == 'approve' || $action == 'approve2') - { + if ($action == 'approve' || $action == 'approve2') { $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { $qualified_for_stock_change = $object->hasProductsOrServices(1); } $formquestion = array(); - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) { $langs->load("stocks"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( //'text' => $langs->trans("ConfirmClone"), //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -1890,8 +1860,7 @@ if ($action == 'create') ); } $text = $langs->trans("ConfirmApproveThisOrder", $object->ref); - if (!empty($conf->notification->enabled)) - { + if (!empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; $notify = new Notify($db); $text .= '<br>'; @@ -1902,34 +1871,33 @@ if ($action == 'create') } // Confirmation de la desapprobation - if ($action == 'refuse') - { + if ($action == 'refuse') { $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id", $langs->trans("DenyingThisOrder"), $langs->trans("ConfirmDenyingThisOrder", $object->ref), "confirm_refuse", '', 0, 1); } // Confirmation de l'annulation - if ($action == 'cancel') - { + if ($action == 'cancel') { $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id", $langs->trans("Cancel"), $langs->trans("ConfirmCancelThisOrder", $object->ref), "confirm_cancel", '', 0, 1); } // Confirmation de l'envoi de la commande - if ($action == 'commande') - { + if ($action == 'commande') { $date_com = dol_mktime(GETPOST('rehour'), GETPOST('remin'), GETPOST('resec'), GETPOST("remonth"), GETPOST("reday"), GETPOST("reyear")); $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id."&datecommande=".$date_com."&methode=".$_POST["methodecommande"]."&comment=".urlencode($_POST["comment"]), $langs->trans("MakeOrder"), $langs->trans("ConfirmMakeOrder", dol_print_date($date_com, 'day')), "confirm_commande", '', 0, 2); } // Confirmation to delete line - if ($action == 'ask_deleteline') - { + if ($action == 'ask_deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1); } $parameters = array('formConfirm' => $formconfirm, 'lineid'=>$lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -1959,7 +1927,9 @@ if ($action == 'create') $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=edit_thirdparty&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetThirdParty')).'</a>'; } $morehtmlref .= ' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherOrders").'</a>)'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherOrders").'</a>)'; + } } // Project @@ -1967,8 +1937,9 @@ if ($action == 'create') $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; if ($usercancreate) { - if ($action != 'classify') + if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; @@ -2005,8 +1976,7 @@ if ($action == 'create') print '<table class="border tableforfield centpercent">'; // Date - if ($object->methode_commande_id > 0) - { + if ($object->methode_commande_id > 0) { print '<tr><td class="titlefield">'.$langs->trans("Date").'</td><td>'; print $object->date_commande ? dol_print_date($object->date_commande, $usehourmin) : ''; if ($object->hasDelay() && !empty($object->date_delivery) && !empty($object->date_commande)) { @@ -2014,8 +1984,7 @@ if ($action == 'create') } print "</td></tr>"; - if ($object->methode_commande) - { + if ($object->methode_commande) { print '<tr><td>'.$langs->trans("Method").'</td><td>'.$object->getInputMethod().'</td></tr>'; } } @@ -2054,11 +2023,12 @@ if ($action == 'create') print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">'; print $langs->trans('PaymentConditions'); print '<td>'; - if ($action != 'editconditions') print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;id='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>'; + if ($action != 'editconditions') { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;id='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; - if ($action == 'editconditions') - { + if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id'); } else { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none'); @@ -2072,11 +2042,12 @@ if ($action == 'create') print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">'; print $langs->trans('PaymentMode'); print '</td>'; - if ($action != 'editmode') print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>'; + if ($action != 'editmode') { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; - if ($action == 'editmode') - { + if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'DBIT', 1, 1); } else { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none'); @@ -2084,16 +2055,16 @@ if ($action == 'create') print '</td></tr>'; // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print '<tr>'; print '<td>'; print '<table class="nobordernopadding centpercent"><tr><td>'; print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0); print '</td>'; - if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) + if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencycode&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; if ($action == 'editmulticurrencycode') { @@ -2104,16 +2075,16 @@ if ($action == 'create') print '</td></tr>'; // Multicurrency rate - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { print '<tr>'; print '<td>'; print '<table class="nobordernopadding centpercent"><tr>'; print '<td>'; print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0); print '</td>'; - if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) + if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencyrate&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { @@ -2134,14 +2105,14 @@ if ($action == 'create') } // Bank Account - if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && !empty($conf->banque->enabled)) - { + if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && !empty($conf->banque->enabled)) { print '<tr><td class="nowrap">'; print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">'; print $langs->trans('BankAccount'); print '<td>'; - if ($action != 'editbankaccount' && $usercancreate) + if ($action != 'editbankaccount' && $usercancreate) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; if ($action == 'editbankaccount') { @@ -2164,22 +2135,27 @@ if ($action == 'create') print '<table class="nobordernopadding centpercent"><tr><td>'; print $langs->trans('DateDeliveryPlanned'); print '</td>'; - if ($action != 'editdate_livraison') print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_livraison&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).'</a></td>'; + if ($action != 'editdate_livraison') { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_livraison&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; - if ($action == 'editdate_livraison') - { + if ($action == 'editdate_livraison') { print '<form name="setdate_livraison" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="setdate_livraison">'; $usehourmin = 0; - if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin = 1; + if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) { + $usehourmin = 1; + } print $form->selectDate($object->delivery_date ? $object->delivery_date : -1, 'liv_', $usehourmin, $usehourmin, '', "setdate_livraison"); print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">'; print '</form>'; } else { $usehourmin = 'day'; - if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin = 'dayhour'; + if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) { + $usehourmin = 'dayhour'; + } print $object->delivery_date ? dol_print_date($object->delivery_date, $usehourmin) : '&nbsp;'; if ($object->hasDelay() && !empty($object->delivery_date)) { print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); @@ -2188,19 +2164,20 @@ if ($action == 'create') print '</td></tr>'; // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '<tr><td>'; print '<table class="nobordernopadding centpercent"><tr><td>'; print $langs->trans('IncotermLabel'); print '<td><td class="right">'; - if ($usercancreate) print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/commande/card.php?id='.$object->id.'&action=editincoterm">'.img_edit().'</a>'; - else print '&nbsp;'; + if ($usercancreate) { + print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/commande/card.php?id='.$object->id.'&action=editincoterm">'.img_edit().'</a>'; + } else { + print '&nbsp;'; + } print '</td></tr></table>'; print '</td>'; print '<td>'; - if ($action != 'editincoterm') - { + if ($action != 'editincoterm') { print $form->textwithpicto(dol_escape_htmltag($object->display_incoterms()), $object->label_incoterms, 1); } else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); @@ -2220,8 +2197,7 @@ if ($action == 'create') print '<table class="border tableforfield centpercent">'; - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { // Multicurrency Amount HT print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>'; print '<td class="nowrap">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>'; @@ -2252,14 +2228,12 @@ if ($action == 'create') print '</tr>'; // Amount Local Taxes - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) //Localtax1 - { + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { //Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>'; print '<td>'.price($object->total_localtax1, '', $langs, 1, -1, -1, $conf->currency).'</td>'; print '</tr>'; } - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) //Localtax2 - { + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { //Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>'; print '<td>'.price($object->total_localtax2, '', $langs, 1, -1, -1, $conf->currency).'</td>'; print '</tr>'; @@ -2273,7 +2247,7 @@ if ($action == 'create') // Margin Infos /*if (! empty($conf->margin->enabled)) { - $formmargin->displayMarginInfos($object); + $formmargin->displayMarginInfos($object); }*/ @@ -2283,15 +2257,13 @@ if ($action == 'create') print '<div class="clearboth"></div><br>'; - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $blocname = 'contacts'; $title = $langs->trans('ContactsAddresses'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } - if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $blocname = 'notes'; $title = $langs->trans('Notes'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; @@ -2322,19 +2294,20 @@ if ($action == 'create') global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax; $forceall = 1; $dateSelector = 0; $inputalsopricewithtax = 1; $senderissupplier = 2; // $senderissupplier=2 is same than 1 but disable test on minimum qty and disable autofill qty with minimum. - if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) $senderissupplier = 1; + if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) { + $senderissupplier = 1; + } // Show object lines - if (!empty($object->lines)) + if (!empty($object->lines)) { $ret = $object->printObjectLines($action, $societe, $mysoc, $lineid, 1); + } $num = count($object->lines); // Form to add new line - if ($object->statut == CommandeFournisseur::STATUS_DRAFT && $usercancreate) - { - if ($action != 'editline') - { + if ($object->statut == CommandeFournisseur::STATUS_DRAFT && $usercancreate) { + if ($action != 'editline') { // Add free products/services $object->formAddObjectLine(1, $societe, $mysoc); @@ -2352,24 +2325,22 @@ if ($action == 'create') * Boutons actions */ - if ($user->socid == 0 && $action != 'editline' && $action != 'delete') - { + if ($user->socid == 0 && $action != 'editline' && $action != 'delete') { print '<div class="tabsAction">'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { $object->fetchObjectLinked(); // Links are used to show or not button, so we load them now. // Validate - if ($object->statut == 0 && $num > 0) - { - if ($usercanvalidate) - { + if ($object->statut == 0 && $num > 0) { + if ($usercanvalidate) { $tmpbuttonlabel = $langs->trans('Validate'); - if ($usercanapprove && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE)) $tmpbuttonlabel = $langs->trans("ValidateAndApprove"); + if ($usercanapprove && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE)) { + $tmpbuttonlabel = $langs->trans("ValidateAndApprove"); + } print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid">'; print $tmpbuttonlabel; @@ -2383,21 +2354,16 @@ if ($action == 'create') }*/ // Modify - if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) - { - if ($usercanorder) - { + if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) { + if ($usercanorder) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Modify").'</a>'; } } // Approve - if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) - { - if ($usercanapprove) - { - if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED && !empty($object->user_approve_id)) - { + if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) { + if ($usercanapprove) { + if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED && !empty($object->user_approve_id)) { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("FirstApprovalAlreadyDone")).'">'.$langs->trans("ApproveOrder").'</a>'; } else { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=approve">'.$langs->trans("ApproveOrder").'</a>'; @@ -2408,14 +2374,10 @@ if ($action == 'create') } // Second approval (if option SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set) - if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) - { - if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) - { - if ($usercanapprovesecond) - { - if (!empty($object->user_approve_id2)) - { + if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) { + if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) { + if ($usercanapprovesecond) { + if (!empty($object->user_approve_id2)) { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("SecondApprovalAlreadyDone")).'">'.$langs->trans("Approve2Order").'</a>'; } else { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=approve2">'.$langs->trans("Approve2Order").'</a>'; @@ -2427,10 +2389,8 @@ if ($action == 'create') } // Refuse - if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) - { - if ($usercanapprove || $usercanapprovesecond) - { + if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) { + if ($usercanapprove || $usercanapprovesecond) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=refuse">'.$langs->trans("RefuseOrder").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("RefuseOrder").'</a>'; @@ -2439,51 +2399,43 @@ if ($action == 'create') // Send if (empty($user->socid)) { - if (in_array($object->statut, array(CommandeFournisseur::STATUS_ACCEPTED, 3, 4, 5)) || !empty($conf->global->SUPPLIER_ORDER_SENDBYEMAIL_FOR_ALL_STATUS)) - { - if ($usercanorder) - { + if (in_array($object->statut, array(CommandeFournisseur::STATUS_ACCEPTED, 3, 4, 5)) || !empty($conf->global->SUPPLIER_ORDER_SENDBYEMAIL_FOR_ALL_STATUS)) { + if ($usercanorder) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>'; } } } // Reopen - if (in_array($object->statut, array(CommandeFournisseur::STATUS_ACCEPTED))) - { + if (in_array($object->statut, array(CommandeFournisseur::STATUS_ACCEPTED))) { $buttonshown = 0; - if (!$buttonshown && $usercanapprove) - { + if (!$buttonshown && $usercanapprove) { if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) - || (!empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) && $user->id == $object->user_approve_id)) - { + || (!empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) && $user->id == $object->user_approve_id)) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Disapprove").'</a>'; $buttonshown++; } } - if (!$buttonshown && $usercanapprovesecond && !empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)) - { + if (!$buttonshown && $usercanapprovesecond && !empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)) { if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) - || (!empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) && $user->id == $object->user_approve_id2)) - { + || (!empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) && $user->id == $object->user_approve_id2)) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Disapprove").'</a>'; } } } - if (in_array($object->statut, array(3, 4, 5, 6, 7, 9))) - { - if ($usercanorder) - { + if (in_array($object->statut, array(3, 4, 5, 6, 7, 9))) { + if ($usercanorder) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("ReOpen").'</a>'; } } // Ship - if (!empty($conf->stock->enabled) && (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE))) - { + if (!empty($conf->stock->enabled) && (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE))) { $labelofbutton = $langs->trans('ReceiveProducts'); - if ($conf->reception->enabled) $labelofbutton = $langs->trans("CreateReception"); + if ($conf->reception->enabled) { + $labelofbutton = $langs->trans("CreateReception"); + } if (in_array($object->statut, array(3, 4, 5))) { if ($conf->fournisseur->enabled && $usercanreceived) { @@ -2494,10 +2446,8 @@ if ($action == 'create') } } - if ($object->statut == CommandeFournisseur::STATUS_ACCEPTED) - { - if ($usercanorder) - { + if ($object->statut == CommandeFournisseur::STATUS_ACCEPTED) { + if ($usercanorder) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=makeorder#makeorder">'.$langs->trans("MakeOrder").'</a></div>'; } else { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans("MakeOrder").'</a></div>'; @@ -2505,10 +2455,8 @@ if ($action == 'create') } // Classify received (this does not record reception) - if ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY) - { - if ($usercanreceived) - { + if ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY) { + if ($usercanreceived) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifyreception#classifyreception">'.$langs->trans("ClassifyReception").'</a></div>'; } } @@ -2516,26 +2464,20 @@ if ($action == 'create') // Create bill //if (! empty($conf->facture->enabled)) //{ - if (!empty($conf->fournisseur->enabled) && ($object->statut >= 2 && $object->statut != 7 && $object->billed != 1)) // statut 2 means approved, 7 means canceled - { - if ($user->rights->fournisseur->facture->creer) - { + if (!empty($conf->fournisseur->enabled) && ($object->statut >= 2 && $object->statut != 7 && $object->billed != 1)) { // statut 2 means approved, 7 means canceled + if ($user->rights->fournisseur->facture->creer) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("CreateBill").'</a>'; } } //} // Classify billed manually (need one invoice if module invoice is on, no condition on invoice if not) - if ($usercancreate && $object->statut >= 2 && $object->statut != 7 && $object->billed != 1) // statut 2 means approved - { - if (empty($conf->facture->enabled)) - { + if ($usercancreate && $object->statut >= 2 && $object->statut != 7 && $object->billed != 1) { // statut 2 means approved + if (empty($conf->facture->enabled)) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifybilled">'.$langs->trans("ClassifyBilled").'</a>'; } else { - if (!empty($object->linkedObjectsIds['invoice_supplier'])) - { - if ($user->rights->fournisseur->facture->creer) - { + if (!empty($object->linkedObjectsIds['invoice_supplier'])) { + if ($user->rights->fournisseur->facture->creer) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifybilled">'.$langs->trans("ClassifyBilled").'</a>'; } } else { @@ -2545,29 +2487,24 @@ if ($action == 'create') } // Create a remote order using WebService only if module is activated - if (!empty($conf->syncsupplierwebservices->enabled) && $object->statut >= 2) // 2 means accepted - { + if (!empty($conf->syncsupplierwebservices->enabled) && $object->statut >= 2) { // 2 means accepted print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=webservice&amp;mode=init">'.$langs->trans('CreateRemoteOrder').'</a>'; } // Clone - if ($usercancreate) - { + if ($usercancreate) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$object->socid.'&amp;action=clone&amp;object=order">'.$langs->trans("ToClone").'</a>'; } // Cancel - if ($object->statut == 2) - { - if ($usercanorder) - { + if ($object->statut == 2) { + if ($usercanorder) { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=cancel">'.$langs->trans("CancelOrder").'</a>'; } } // Delete - if (!empty($usercandelete) || ($object->statut == CommandeFournisseur::STATUS_DRAFT && !empty($usercancreate))) - { + if (!empty($usercandelete) || ($object->statut == CommandeFournisseur::STATUS_DRAFT && !empty($usercancreate))) { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans("Delete").'</a>'; } } @@ -2576,8 +2513,7 @@ if ($action == 'create') - if ($usercanorder && $object->statut == CommandeFournisseur::STATUS_ACCEPTED && $action == 'makeorder') - { + if ($usercanorder && $object->statut == CommandeFournisseur::STATUS_ACCEPTED && $action == 'makeorder') { // Set status to ordered (action=commande) print '<!-- form to record supplier order -->'."\n"; print '<form name="commande" id="makeorder" action="card.php?id='.$object->id.'&amp;action=commande" method="POST">'; @@ -2589,7 +2525,9 @@ if ($action == 'create') //print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("ToOrder").'</td></tr>'; print '<tr><td class="fieldrequired">'.$langs->trans("OrderDate").'</td><td>'; $date_com = dol_mktime(GETPOST('rehour', 'int'), GETPOST('remin', 'int'), GETPOST('resec', 'int'), GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - if (empty($date_com)) $date_com = dol_now(); + if (empty($date_com)) { + $date_com = dol_now(); + } print $form->selectDate($date_com, '', 1, 1, '', "commande", 1, 1); print '</td></tr>'; @@ -2610,8 +2548,7 @@ if ($action == 'create') print "<br>"; } - if ($action != 'makeorder') - { + if ($action != 'makeorder') { print '<div class="fichecenter"><div class="fichehalfleft">'; // Generated documents @@ -2632,10 +2569,8 @@ if ($action == 'create') print '</div><div class="fichehalfright"><div class="ficheaddleft">'; - if ($action == 'classifyreception') - { - if ($usercanreceived && ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY)) - { + if ($action == 'classifyreception') { + if ($usercanreceived && ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY)) { // Set status to received (action=livraison) print '<!-- form to record purchase order received -->'."\n"; print '<form id="classifyreception" action="card.php?id='.$object->id.'" method="post">'; @@ -2680,8 +2615,7 @@ if ($action == 'create') /* * Action webservice */ - if ($action == 'webservice' && GETPOST('mode', 'alpha') != "send" && !GETPOST('cancel', 'alpha')) - { + if ($action == 'webservice' && GETPOST('mode', 'alpha') != "send" && !GETPOST('cancel', 'alpha')) { $mode = GETPOST('mode', 'alpha'); $ws_url = $object->thirdparty->webservices_url; $ws_key = $object->thirdparty->webservices_key; @@ -2710,8 +2644,7 @@ if ($action == 'create') $mode = "init"; } - if ($mode == "init") - { + if ($mode == "init") { //Table/form header print '<table class="border centpercent">'; print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">'; @@ -2719,8 +2652,7 @@ if ($action == 'create') print '<input type="hidden" name="action" value="webservice">'; print '<input type="hidden" name="mode" value="check">'; - if ($error_occurred) - { + if ($error_occurred) { print "<br>".$langs->trans("ErrorOccurredReviseAndRetry")."<br>"; print '<input class="button button-cancel" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; } else { @@ -2743,8 +2675,7 @@ if ($action == 'create') //End table/form print '</form>'; print '</table>'; - } elseif ($mode == "check") - { + } elseif ($mode == "check") { $ws_entity = ''; $ws_thirdparty = ''; $error_occurred = false; @@ -2759,14 +2690,12 @@ if ($action == 'create') $result_user = $soapclient_user->call("getUser", $ws_parameters, $ws_ns, ''); $user_status_code = $result_user["result"]["result_code"]; - if ($user_status_code == "OK") - { + if ($user_status_code == "OK") { //Fill the variables $ws_entity = $result_user["user"]["entity"]; $ws_authentication['entity'] = $ws_entity; $ws_thirdparty = $result_user["user"]["fk_thirdparty"]; - if (empty($ws_thirdparty)) - { + if (empty($ws_thirdparty)) { setEventMessages($langs->trans("RemoteUserMissingAssociatedSoc"), null, 'errors'); $error_occurred = true; } else { @@ -2786,8 +2715,7 @@ if ($action == 'create') } $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $ref_supplier); $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, ''); - if (!$result_product) - { + if (!$result_product) { setEventMessages($line_id.$langs->trans("SOAPError")." ".$soapclient_product->error_str." - ".$soapclient_product->response, null, 'errors'); $error_occurred = true; break; @@ -2795,13 +2723,10 @@ if ($action == 'create') // Check the result code $status_code = $result_product["result"]["result_code"]; - if (empty($status_code)) //No result, check error str - { + if (empty($status_code)) { //No result, check error str setEventMessages($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", null, 'errors'); - } elseif ($status_code != "OK") //Something went wrong - { - if ($status_code == "NOT_FOUND") - { + } elseif ($status_code != "OK") { //Something went wrong + if ($status_code == "NOT_FOUND") { setEventMessages($line_id.$langs->trans("SupplierMissingRef")." '".$ref_supplier."'", null, 'warnings'); } else { setEventMessages($line_id.$langs->trans("ResponseNonOK")." '".$status_code."' - '".$result_product["result"]["result_label"]."'", null, 'errors'); @@ -2817,10 +2742,8 @@ if ($action == 'create') $product_fourn = new ProductFournisseur($db); $product_fourn_list = $product_fourn->list_product_fournisseur_price($line->fk_product); - if (count($product_fourn_list) > 0) - { - foreach ($product_fourn_list as $product_fourn_line) - { + if (count($product_fourn_list) > 0) { + foreach ($product_fourn_list as $product_fourn_line) { //Only accept the line where the supplier is the same at this order and has the same ref if ($product_fourn_line->fourn_id == $object->socid && $product_fourn_line->fourn_ref == $ref_supplier) { $local_price = price($product_fourn_line->fourn_price); @@ -2838,12 +2761,10 @@ if ($action == 'create') } } } - } elseif ($user_status_code == "PERMISSION_DENIED") - { + } elseif ($user_status_code == "PERMISSION_DENIED") { setEventMessages($langs->trans("RemoteUserNotPermission"), null, 'errors'); $error_occurred = true; - } elseif ($user_status_code == "BAD_CREDENTIALS") - { + } elseif ($user_status_code == "BAD_CREDENTIALS") { setEventMessages($langs->trans("RemoteUserBadCredentials"), null, 'errors'); $error_occurred = true; } else { @@ -2860,8 +2781,7 @@ if ($action == 'create') print '<input type="hidden" name="ws_password" value="'.$ws_password.'">'; print '<input type="hidden" name="ws_entity" value="'.$ws_entity.'">'; print '<input type="hidden" name="ws_thirdparty" value="'.$ws_thirdparty.'">'; - if ($error_occurred) - { + if ($error_occurred) { print "<br>".$langs->trans("ErrorOccurredReviseAndRetry")."<br>"; } else { print '<input class="button" type="submit" id="ws_submit" name="ws_submit" value="'.$langs->trans("Confirm").'">'; diff --git a/htdocs/fourn/commande/contact.php b/htdocs/fourn/commande/contact.php index 3e52f35d8bb..ae2e8bab481 100644 --- a/htdocs/fourn/commande/contact.php +++ b/htdocs/fourn/commande/contact.php @@ -41,7 +41,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); $object = new CommandeFournisseur($db); @@ -51,51 +53,39 @@ $object = new CommandeFournisseur($db); * Add a new contact */ -if ($action == 'addcontact' && $user->rights->fournisseur->commande->creer) -{ +if ($action == 'addcontact' && $user->rights->fournisseur->commande->creer) { $result = $object->fetch($id); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } -} - -// Toggle the status of a contact -elseif ($action == 'swapstatut' && $user->rights->fournisseur->commande->creer) -{ - if ($object->fetch($id)) - { +} elseif ($action == 'swapstatut' && $user->rights->fournisseur->commande->creer) { + // Toggle the status of a contact + if ($object->fetch($id)) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { dol_print_error($db); } -} - -// Deleting a contact -elseif ($action == 'deletecontact' && $user->rights->fournisseur->commande->creer) -{ +} elseif ($action == 'deletecontact' && $user->rights->fournisseur->commande->creer) { + // Deleting a contact $object->fetch($id); $result = $object->delete_contact($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -123,12 +113,10 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $langs->trans("OrderCard"); - if ($object->fetch($id, $ref) > 0) - { + if ($object->fetch($id, $ref) > 0) { $object->fetch_thirdparty(); $head = ordersupplier_prepare_head($object); @@ -145,12 +133,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/fourn/commande/dispatch.php b/htdocs/fourn/commande/dispatch.php index acfa5a54e16..0d48c7d30dd 100644 --- a/htdocs/fourn/commande/dispatch.php +++ b/htdocs/fourn/commande/dispatch.php @@ -40,14 +40,16 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; -if (!empty($conf->projet->enabled)) +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +} // Load translation files required by the page $langs->loadLangs(array("bills", "orders", "sendings", "companies", "deliveries", "products", "stocks", "receptions")); -if (!empty($conf->productbatch->enabled)) +if (!empty($conf->productbatch->enabled)) { $langs->load('productbatch'); +} // Security check $id = GETPOST("id", 'int'); @@ -58,8 +60,9 @@ $fk_default_warehouse = GETPOST('fk_default_warehouse', 'int'); $cancel = GETPOST('cancel', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); -if ($user->socid) +if ($user->socid) { $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); if (empty($conf->stock->enabled)) { @@ -70,8 +73,9 @@ $hookmanager->initHooks(array('ordersupplierdispatch')); // Recuperation de l'id de projet $projectid = 0; -if ($_GET["projectid"]) +if ($_GET["projectid"]) { $projectid = GETPOST("projectid", 'int'); +} $object = new CommandeFournisseur($db); @@ -93,25 +97,24 @@ if ($id > 0 || !empty($ref)) { $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 ($action == 'checkdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check)))) -{ +if ($action == 'checkdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check)))) { $error = 0; $supplierorderdispatch = new CommandeFournisseurDispatch($db); $db->begin(); $result = $supplierorderdispatch->fetch($lineid); - if (!$result) - { + if (!$result) { $error++; setEventMessages($supplierorderdispatch->error, $supplierorderdispatch->errors, 'errors'); $action = ''; } - if (!$error) - { + if (!$error) { $result = $supplierorderdispatch->setStatut(1); if ($result < 0) { setEventMessages($supplierorderdispatch->error, $supplierorderdispatch->errors, 'errors'); @@ -120,8 +123,7 @@ if ($action == 'checkdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_ } } - if (!$error) - { + if (!$error) { $result = $object->calcAndSetStatusDispatch($user); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -129,31 +131,27 @@ if ($action == 'checkdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_ $action = ''; } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); } } -if ($action == 'uncheckdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check)))) -{ +if ($action == 'uncheckdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check)))) { $error = 0; $supplierorderdispatch = new CommandeFournisseurDispatch($db); $db->begin(); $result = $supplierorderdispatch->fetch($lineid); - if (!$result) - { + if (!$result) { $error++; setEventMessages($supplierorderdispatch->error, $supplierorderdispatch->errors, 'errors'); $action = ''; } - if (!$error) - { + if (!$error) { $result = $supplierorderdispatch->setStatut(0); if ($result < 0) { setEventMessages($supplierorderdispatch->error, $supplierorderdispatch->errors, 'errors'); @@ -161,8 +159,7 @@ if ($action == 'uncheckdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCE $action = ''; } } - if (!$error) - { + if (!$error) { $result = $object->calcAndSetStatusDispatch($user); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -170,31 +167,27 @@ if ($action == 'uncheckdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCE $action = ''; } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); } } -if ($action == 'denydispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check)))) -{ +if ($action == 'denydispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check)))) { $error = 0; $supplierorderdispatch = new CommandeFournisseurDispatch($db); $db->begin(); $result = $supplierorderdispatch->fetch($lineid); - if (!$result) - { + if (!$result) { $error++; setEventMessages($supplierorderdispatch->error, $supplierorderdispatch->errors, 'errors'); $action = ''; } - if (!$error) - { + if (!$error) { $result = $supplierorderdispatch->setStatut(2); if ($result < 0) { setEventMessages($supplierorderdispatch->error, $supplierorderdispatch->errors, 'errors'); @@ -202,8 +195,7 @@ if ($action == 'denydispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_P $action = ''; } } - if (!$error) - { + if (!$error) { $result = $object->calcAndSetStatusDispatch($user); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -211,8 +203,7 @@ if ($action == 'denydispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_P $action = ''; } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -225,12 +216,10 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner) $db->begin(); $pos = 0; - foreach ($_POST as $key => $value) - { + foreach ($_POST as $key => $value) { // without batch module enabled $reg = array(); - if (preg_match('/^product_([0-9]+)_([0-9]+)$/i', $key, $reg)) - { + if (preg_match('/^product_([0-9]+)_([0-9]+)$/i', $key, $reg)) { $pos++; // $numline=$reg[2] + 1; // line of product @@ -238,7 +227,9 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner) $prod = "product_".$reg[1].'_'.$reg[2]; $qty = "qty_".$reg[1].'_'.$reg[2]; $ent = "entrepot_".$reg[1].'_'.$reg[2]; - if (empty(GETPOST($ent))) $ent = $fk_default_warehouse; + if (empty(GETPOST($ent))) { + $ent = $fk_default_warehouse; + } $pu = "pu_".$reg[1].'_'.$reg[2]; // This is unit price including discount $fk_commandefourndet = "fk_commandefourndet_".$reg[1].'_'.$reg[2]; @@ -293,8 +284,7 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner) } } // with batch module enabled - if (preg_match('/^product_batch_([0-9]+)_([0-9]+)$/i', $key, $reg)) - { + if (preg_match('/^product_batch_([0-9]+)_([0-9]+)$/i', $key, $reg)) { $pos++; // eat-by date dispatch @@ -398,104 +388,86 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner) } // Remove a dispatched line -if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->fournisseur->commande->receptionner) -{ +if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->fournisseur->commande->receptionner) { $db->begin(); $supplierorderdispatch = new CommandeFournisseurDispatch($db); $result = $supplierorderdispatch->fetch($lineid); - if ($result > 0) - { + if ($result > 0) { $qty = $supplierorderdispatch->qty; $entrepot = $supplierorderdispatch->fk_entrepot; $product = $supplierorderdispatch->fk_product; $price = GETPOST('price'); $comment = $supplierorderdispatch->comment; - $eatby = $supplierorderdispatch->fk_product; + $eatby = $supplierorderdispatch->eatby; $sellby = $supplierorderdispatch->sellby; $batch = $supplierorderdispatch->batch; $result = $supplierorderdispatch->delete($user); } - if ($result < 0) - { + if ($result < 0) { $errors = $object->errors; $error++; - } - else { + } else { // If module stock is enabled and the stock increase is done on purchase order dispatching - if ($entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) - { + if ($entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { $mouv = new MouvementStock($db); - if ($product > 0) - { + if ($product > 0) { $mouv->origin = &$object; $result = $mouv->livraison($user, $product, $entrepot, $qty, $price, $comment, '', $eatby, $sellby, $batch); - if ($result < 0) - { + if ($result < 0) { $errors = $mouv->errors; $error++; } } } } - if ($error > 0) - { + if ($error > 0) { $db->rollback(); setEventMessages($error, $errors, 'errors'); - } - else { + } else { $db->commit(); } } // Update a dispatched line -if ($action == 'updateline' && $user->rights->fournisseur->commande->receptionner) -{ +if ($action == 'updateline' && $user->rights->fournisseur->commande->receptionner) { $db->begin(); $error = 0; $supplierorderdispatch = new CommandeFournisseurDispatch($db); $result = $supplierorderdispatch->fetch($lineid); - if ($result > 0) - { + if ($result > 0) { $qty = $supplierorderdispatch->qty; $entrepot = $supplierorderdispatch->fk_entrepot; $product = $supplierorderdispatch->fk_product; - $price = GETPOST('price'); + $price = price2num(GETPOST('price'), '', 2); $comment = $supplierorderdispatch->comment; $eatby = $supplierorderdispatch->fk_product; $sellby = $supplierorderdispatch->sellby; $batch = $supplierorderdispatch->batch; - $supplierorderdispatch->qty = GETPOST('qty', 'int'); + $supplierorderdispatch->qty = price2num(GETPOST('qty', 'alpha'), 'MS', 2); $supplierorderdispatch->fk_entrepot = GETPOST('fk_entrepot'); $result = $supplierorderdispatch->update($user); } - if ($result < 0) - { + if ($result < 0) { $error++; $errors = $supplierorderdispatch->errors; - } - else { + } else { // If module stock is enabled and the stock increase is done on purchase order dispatching - if ($entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) - { + if ($entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { $mouv = new MouvementStock($db); - if ($product > 0) - { + if ($product > 0) { $mouv->origin = &$object; $result = $mouv->livraison($user, $product, $entrepot, $qty, $price, $comment, '', $eatby, $sellby, $batch); - if ($result < 0) - { + if ($result < 0) { $errors = $mouv->errors; $error++; - } - else { + } else { $mouv->origin = &$object; $result = $mouv->reception($user, $product, $supplierorderdispatch->fk_entrepot, $supplierorderdispatch->qty, $price, $comment, $eatby, $sellby, $batch); - if ($result < 0) - { + if ($result < 0) { $errors = $mouv->errors; $error++; } @@ -503,12 +475,10 @@ if ($action == 'updateline' && $user->rights->fournisseur->commande->receptionne } } } - if ($error > 0) - { + if ($error > 0) { $db->rollback(); setEventMessages($error, $errors, 'errors'); - } - else { + } else { $db->commit(); } } @@ -525,7 +495,9 @@ $warehouse_static = new Entrepot($db); $supplierorderdispatch = new CommandeFournisseurDispatch($db); $help_url = 'EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; -llxHeader('', $langs->trans("OrderDispatch"), $help_url, '', 0, 0, array('/fourn/js/lib_dispatch.js.php')); +$morejs = array('/fourn/js/lib_dispatch.js.php'); + +llxHeader('', $langs->trans("OrderDispatch"), $help_url, '', 0, 0, $morejs); if ($id > 0 || !empty($ref)) { $soc = new Societe($db); @@ -542,8 +514,7 @@ if ($id > 0 || !empty($ref)) { $formconfirm = ''; // Confirmation to delete line - if ($action == 'ask_deleteline') - { + if ($action == 'ask_deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); } @@ -551,8 +522,11 @@ if ($id > 0 || !empty($ref)) { $parameters = array('lineid' => $lineid); // Note that $action and $object may be modified by hook $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -568,12 +542,10 @@ if ($id > 0 || !empty($ref)) { // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; @@ -641,8 +613,9 @@ if ($id > 0 || !empty($ref)) { print '<br>'; $disabled = 1; - if (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) + if (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { $disabled = 0; + } // Line of orders if ($object->statut <= CommandeFournisseur::STATUS_ACCEPTED || $object->statut >= CommandeFournisseur::STATUS_CANCELED) { @@ -651,8 +624,7 @@ if ($id > 0 || !empty($ref)) { if ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY - || $object->statut == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) - { + || $object->statut == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) { require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $formproduct->loadWarehouses(); @@ -660,12 +632,18 @@ if ($id > 0 || !empty($ref)) { $listwarehouses = $entrepot->list_array(1); - if (empty($conf->reception->enabled))print '<form method="POST" action="dispatch.php?id='.$object->id.'">'; - else print '<form method="post" action="'.dol_buildpath('/reception/card.php', 1).'?originid='.$object->id.'&origin=supplierorder">'; + if (empty($conf->reception->enabled)) { + print '<form method="POST" action="dispatch.php?id='.$object->id.'">'; + } else { + print '<form method="post" action="'.dol_buildpath('/reception/card.php', 1).'?originid='.$object->id.'&origin=supplierorder">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; - if (empty($conf->reception->enabled))print '<input type="hidden" name="action" value="dispatch">'; - else print '<input type="hidden" name="action" value="create">'; + if (empty($conf->reception->enabled)) { + print '<input type="hidden" name="action" value="dispatch">'; + } else { + print '<input type="hidden" name="action" value="create">'; + } print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; @@ -704,14 +682,17 @@ if ($id > 0 || !empty($ref)) { $object, $action ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as l"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON l.fk_product=p.rowid"; $sql .= " WHERE l.fk_commande = ".$object->id; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $sql .= " AND l.product_type = 0"; + } // Enable hooks to alter the SQL query (WHERE) $parameters = array(); @@ -721,7 +702,9 @@ if ($id > 0 || !empty($ref)) { $object, $action ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $sql .= $hookmanager->resPrint; $sql .= " GROUP BY p.ref, p.label, p.tobatch, p.fk_default_warehouse, l.rowid, l.fk_product, l.subprice, l.remise_percent, l.ref"; // Calculation of amount dispatched is done per fk_product so we must group by fk_product @@ -783,7 +766,9 @@ if ($id > 0 || !empty($ref)) { $object, $action ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print "</tr>\n"; @@ -801,8 +786,9 @@ if ($id > 0 || !empty($ref)) { $nbfreeproduct++; } else { $remaintodispatch = price2num($objp->qty - ((float) $products_dispatched[$objp->rowid]), 5); // Calculation of dispatched - if ($remaintodispatch < 0) + if ($remaintodispatch < 0) { $remaintodispatch = 0; + } if ($remaintodispatch || empty($conf->global->SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED)) { $nbproduct++; @@ -856,8 +842,9 @@ if ($id > 0 || !empty($ref)) { // Define unit price for PMP calculation $up_ht_disc = $objp->subprice; - if (!empty($objp->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) + if (!empty($objp->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) { $up_ht_disc = price2num($up_ht_disc * (100 - $objp->remise_percent) / 100, 'MU'); + } // Supplier ref print '<td class="right">'.$objp->sref.'</td>'; @@ -868,7 +855,7 @@ if ($id > 0 || !empty($ref)) { // Already dispatched print '<td class="right">'.$products_dispatched[$objp->rowid].'</td>'; - if (!empty($conf->productbatch->enabled) && $objp->tobatch == 1) { + if (!empty($conf->productbatch->enabled) && $objp->tobatch > 0) { $type = 'batch'; print '<td class="right">'; print '</td>'; // Qty to dispatch @@ -890,7 +877,9 @@ if ($id > 0 || !empty($ref)) { $object, $action ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print '</tr>'; @@ -901,8 +890,7 @@ if ($id > 0 || !empty($ref)) { print '<input name="product_batch'.$suffix.'" type="hidden" value="'.$objp->fk_product.'">'; print '<!-- This is a up (may include discount or not depending on STOCK_EXCLUDE_DISCOUNT_FOR_PMP. will be used for PMP calculation) -->'; - if (!empty($conf->global->SUPPLIER_ORDER_EDIT_BUYINGPRICE_DURING_RECEIPT)) // Not tested ! - { + if (!empty($conf->global->SUPPLIER_ORDER_EDIT_BUYINGPRICE_DURING_RECEIPT)) { // Not tested ! print $langs->trans("BuyingPrice").': <input class="maxwidth75" name="pu'.$suffix.'" type="text" value="'.price2num($up_ht_disc, 'MU').'">'; } else { print '<input class="maxwidth75" name="pu'.$suffix.'" type="hidden" value="'.price2num($up_ht_disc, 'MU').'">'; @@ -951,7 +939,9 @@ if ($id > 0 || !empty($ref)) { $object, $action ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print '</tr>'; @@ -962,8 +952,7 @@ if ($id > 0 || !empty($ref)) { print '<input name="product'.$suffix.'" type="hidden" value="'.$objp->fk_product.'">'; print '<!-- This is a up (may include discount or not depending on STOCK_EXCLUDE_DISCOUNT_FOR_PMP. will be used for PMP calculation) -->'; - if (!empty($conf->global->SUPPLIER_ORDER_EDIT_BUYINGPRICE_DURING_RECEIPT)) // Not tested ! - { + if (!empty($conf->global->SUPPLIER_ORDER_EDIT_BUYINGPRICE_DURING_RECEIPT)) { // Not tested ! print $langs->trans("BuyingPrice").': <input class="maxwidth75" name="pu'.$suffix.'" type="text" value="'.price2num($up_ht_disc, 'MU').'">'; } else { print '<input class="maxwidth75" name="pu'.$suffix.'" type="hidden" value="'.price2num($up_ht_disc, 'MU').'">'; @@ -978,7 +967,7 @@ if ($id > 0 || !empty($ref)) { print '</td>'; print '<td>'; - if (!empty($conf->productbatch->enabled) && $objp->tobatch == 1) { + if (!empty($conf->productbatch->enabled) && $objp->tobatch > 0) { $type = 'batch'; print img_picto($langs->trans('AddStockLocationLine'), 'split.png', 'class="splitbutton" onClick="addDispatchLine('.$i.', \''.$type.'\')"'); } else { @@ -1028,7 +1017,9 @@ if ($id > 0 || !empty($ref)) { $object, $action ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print "</tr>\n"; @@ -1044,16 +1035,14 @@ if ($id > 0 || !empty($ref)) { print "</table>\n"; print '</div>'; - if ($nbproduct) - { + if ($nbproduct) { $checkboxlabel = $langs->trans("CloseReceivedSupplierOrdersAutomatically", $langs->transnoentitiesnoconv('StatusOrderReceivedAll')); print '<div class="center">'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { if (empty($conf->reception->enabled)) { print $langs->trans("Comment").' : '; print '<input type="text" class="minwidth400" maxlength="128" name="comment" value="'; @@ -1067,8 +1056,9 @@ if ($id > 0 || !empty($ref)) { $dispatchBt = empty($conf->reception->enabled) ? $langs->trans("Receive") : $langs->trans("CreateReception"); print '<br><input type="submit" class="button" name="dispatch" value="'.dol_escape_htmltag($dispatchBt).'"'; - if (count($listwarehouses) <= 0) + if (count($listwarehouses) <= 0) { print ' disabled'; + } print '>'; } print '</div>'; @@ -1077,9 +1067,11 @@ if ($id > 0 || !empty($ref)) { // Message if nothing to dispatch if (!$nbproduct) { print "<br>\n"; - if (empty($conf->global->SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED)) + if (empty($conf->global->SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED)) { print '<div class="opacitymedium">'.$langs->trans("NoPredefinedProductToDispatch").'</div>'; // No predefined line at all - else print '<div class="opacitymedium">'.$langs->trans("NoMorePredefinedProductToDispatch").'</div>'; // No predefined line that remain to be dispatched. + } else { + print '<div class="opacitymedium">'.$langs->trans("NoMorePredefinedProductToDispatch").'</div>'; // No predefined line that remain to be dispatched. + } } print '</form>'; @@ -1111,12 +1103,16 @@ if ($id > 0 || !empty($ref)) { $sql .= " e.rowid as warehouse_id, e.ref as entrepot,"; $sql .= " cfd.rowid as dispatchlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status, cfd.datec"; $sql .= " ,cd.rowid, cd.subprice"; - if ($conf->reception->enabled)$sql .= " ,cfd.fk_reception, r.date_delivery"; + if ($conf->reception->enabled) { + $sql .= " ,cfd.fk_reception, r.date_delivery"; + } $sql .= " FROM ".MAIN_DB_PREFIX."product as p,"; $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as cfd"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseurdet as cd ON cd.rowid = cfd.fk_commandefourndet"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e ON cfd.fk_entrepot = e.rowid"; - if ($conf->reception->enabled)$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."reception as r ON cfd.fk_reception = r.rowid"; + if ($conf->reception->enabled) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."reception as r ON cfd.fk_reception = r.rowid"; + } $sql .= " WHERE cfd.fk_commande = ".$object->id; $sql .= " AND cfd.fk_product = p.rowid"; $sql .= " ORDER BY cfd.rowid ASC"; @@ -1135,7 +1131,9 @@ if ($id > 0 || !empty($ref)) { print '<table id="dispatch_received_products" class="noborder centpercent">'; print '<tr class="liste_titre">'; - if ($conf->reception->enabled)print '<td>'.$langs->trans("Reception").'</td>'; + if ($conf->reception->enabled) { + print '<td>'.$langs->trans("Reception").'</td>'; + } print '<td>'.$langs->trans("Product").'</td>'; print '<td>'.$langs->trans("DateCreation").'</td>'; @@ -1167,8 +1165,7 @@ if ($id > 0 || !empty($ref)) { while ($i < $num) { $objp = $db->fetch_object($resql); - if ($action == 'editline' && $lineid == $objp->dispatchlineid) - { + if ($action == 'editline' && $lineid == $objp->dispatchlineid) { print '<form name="editdispatchedlines" id="editdispatchedlines" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'#line_'.GETPOST('lineid').'" method="POST"> <input type="hidden" name="token" value="'.newToken().'"> <input type="hidden" name="action" value="updateline"> @@ -1217,11 +1214,9 @@ if ($id > 0 || !empty($ref)) { // Qty print '<td class="right">'; - if ($action == 'editline' && $lineid == $objp->dispatchlineid) - { + if ($action == 'editline' && $lineid == $objp->dispatchlineid) { print '<input style="width: 50px;" type="number" min="1" name="qty" value="'.$objp->qty.'" />'; - } - else { + } else { print $objp->qty; } print '<input type="hidden" name="price" value="'.$objp->subprice.'" />'; @@ -1229,8 +1224,7 @@ if ($id > 0 || !empty($ref)) { // Warehouse print '<td>'; - if ($action == 'editline' && $lineid == $objp->dispatchlineid) - { + if ($action == 'editline' && $lineid == $objp->dispatchlineid) { if (count($listwarehouses) > 1) { print $formproduct->selectWarehouses(GETPOST("fk_entrepot") ?GETPOST("fk_entrepot") : ($objp->warehouse_id ? $objp->warehouse_id : ''), "fk_entrepot", '', 1, 0, $objp->fk_product, '', 1, 1, null, 'csswarehouse'); } elseif (count($listwarehouses) == 1) { @@ -1239,8 +1233,7 @@ if ($id > 0 || !empty($ref)) { $langs->load("errors"); print $langs->trans("ErrorNoWarehouseDefined"); } - } - else { + } else { $warehouse_static->id = $objp->warehouse_id; $warehouse_static->libelle = $objp->entrepot; print $warehouse_static->getNomUrl(1); @@ -1260,8 +1253,7 @@ if ($id > 0 || !empty($ref)) { // Add button to check/uncheck disaptching print '<td class="center">'; - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check))) - { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check))) { if (empty($objp->status)) { print '<a class="button buttonRefused" href="#">'.$langs->trans("Approve").'</a>'; print '<a class="button buttonRefused" href="#">'.$langs->trans("Deny").'</a>'; @@ -1271,8 +1263,9 @@ if ($id > 0 || !empty($ref)) { } } else { $disabled = ''; - if ($object->statut == 5) + if ($object->statut == 5) { $disabled = 1; + } if (empty($objp->status)) { print '<a class="button'.($disabled ? ' buttonRefused' : '').'" href="'.$_SERVER["PHP_SELF"]."?id=".$id."&action=checkdispatchline&lineid=".$objp->dispatchlineid.'">'.$langs->trans("Approve").'</a>'; print '<a class="button'.($disabled ? ' buttonRefused' : '').'" href="'.$_SERVER["PHP_SELF"]."?id=".$id."&action=denydispatchline&lineid=".$objp->dispatchlineid.'">'.$langs->trans("Deny").'</a>'; @@ -1295,8 +1288,7 @@ if ($id > 0 || !empty($ref)) { print '</td>'; } - if ($action != 'editline' || $lineid != $objp->dispatchlineid) - { + if ($action != 'editline' || $lineid != $objp->dispatchlineid) { print '<td class="linecoledit center">'; print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=editline&amp;lineid='.$objp->dispatchlineid.'#line_'.$objp->dispatchlineid.'">'; print img_edit(); @@ -1308,8 +1300,7 @@ if ($id > 0 || !empty($ref)) { print img_delete(); print '</a>'; print '</td>'; - } - else { + } else { print '<td class="center valignmiddle">'; print '<input type="submit" class="button button-save" id="savelinebutton" name="save" value="'.$langs->trans("Save").'" />'; print '</td>'; @@ -1320,7 +1311,9 @@ if ($id > 0 || !empty($ref)) { print "</tr>\n"; - if ($action == 'editline' && $lineid == $objp->dispatchlineid) print '</form>'; + if ($action == 'editline' && $lineid == $objp->dispatchlineid) { + print '</form>'; + } $i++; } diff --git a/htdocs/fourn/commande/document.php b/htdocs/fourn/commande/document.php index d5a4455db06..3bc2a799a5f 100644 --- a/htdocs/fourn/commande/document.php +++ b/htdocs/fourn/commande/document.php @@ -47,7 +47,9 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); // Get parameters @@ -55,17 +57,22 @@ $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"; +} $object = new CommandeFournisseur($db); -if ($object->fetch($id, $ref) < 0) -{ +if ($object->fetch($id, $ref) < 0) { dol_print_error($db); exit; } @@ -78,7 +85,7 @@ $object->fetch_thirdparty(); * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -87,8 +94,7 @@ include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; $form = new Form($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $help_url = 'EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; llxHeader('', $langs->trans("Order"), $help_url); @@ -105,8 +111,7 @@ if ($object->id > 0) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -121,12 +126,10 @@ if ($object->id > 0) // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/fourn/commande/index.php b/htdocs/fourn/commande/index.php index 1e9e69fb8cd..d46456b52dc 100644 --- a/htdocs/fourn/commande/index.php +++ b/htdocs/fourn/commande/index.php @@ -32,7 +32,9 @@ require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; // Security check $orderid = GETPOST('orderid'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $orderid, '', 'commande'); $hookmanager = new HookManager($db); @@ -59,8 +61,7 @@ print load_fiche_titre($langs->trans("SuppliersOrdersArea"), '', 'supplier_order print '<div class="fichecenter"><div class="fichethirdleft">'; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo print '<form method="post" action="list.php">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<div class="div-table-responsive-no-min">'; @@ -79,16 +80,21 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useles $sql = "SELECT count(cf.rowid) as nb, fk_statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as cf"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE cf.fk_soc = s.rowid"; $sql .= " AND cf.entity IN (".getEntity('supplier_order').")"; -if ($user->socid) $sql .= ' AND cf.fk_soc = '.$user->socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($user->socid) { + $sql .= ' AND cf.fk_soc = '.$user->socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " GROUP BY cf.fk_statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -98,11 +104,9 @@ if ($resql) // 0=Draft -> 1=Validated -> 2=Approved -> 3=Process runing -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially // -> 7=Canceled/Never received -> (reopen) 3=Process runing // -> 6=Canceled -> (reopen) 2=Approved - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $vals[($obj->status == CommandeFournisseur::STATUS_CANCELED_AFTER_ORDER ? CommandeFournisseur::STATUS_CANCELED : $obj->status)] = $obj->nb; $total += $obj->nb; @@ -118,28 +122,41 @@ if ($resql) print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("SuppliersOrders").'</th></tr>'; print "</tr>\n"; $listofstatus = array(0, 1, 2, 3, 4, 5, 6, 9); - foreach ($listofstatus as $status) - { + foreach ($listofstatus as $status) { $dataseries[] = array($commandestatic->LibStatut($status, 1), (isset($vals[$status]) ? (int) $vals[$status] : 0)); - if ($status == CommandeFournisseur::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; - if ($status == CommandeFournisseur::STATUS_VALIDATED) $colorseries[$status] = '-'.$badgeStatus1; - if ($status == CommandeFournisseur::STATUS_ACCEPTED) $colorseries[$status] = $badgeStatus1; - if ($status == CommandeFournisseur::STATUS_REFUSED) $colorseries[$status] = $badgeStatus9; - if ($status == CommandeFournisseur::STATUS_ORDERSENT) $colorseries[$status] = $badgeStatus4; - if ($status == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY) $colorseries[$status] = '-'.$badgeStatus4; - if ($status == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) $colorseries[$status] = $badgeStatus6; - if ($status == CommandeFournisseur::STATUS_CANCELED || $status == CommandeFournisseur::STATUS_CANCELED_AFTER_ORDER) $colorseries[$status] = $badgeStatus9; + if ($status == CommandeFournisseur::STATUS_DRAFT) { + $colorseries[$status] = '-'.$badgeStatus0; + } + if ($status == CommandeFournisseur::STATUS_VALIDATED) { + $colorseries[$status] = '-'.$badgeStatus1; + } + if ($status == CommandeFournisseur::STATUS_ACCEPTED) { + $colorseries[$status] = $badgeStatus1; + } + if ($status == CommandeFournisseur::STATUS_REFUSED) { + $colorseries[$status] = $badgeStatus9; + } + if ($status == CommandeFournisseur::STATUS_ORDERSENT) { + $colorseries[$status] = $badgeStatus4; + } + if ($status == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY) { + $colorseries[$status] = '-'.$badgeStatus4; + } + if ($status == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) { + $colorseries[$status] = $badgeStatus6; + } + if ($status == CommandeFournisseur::STATUS_CANCELED || $status == CommandeFournisseur::STATUS_CANCELED_AFTER_ORDER) { + $colorseries[$status] = $badgeStatus9; + } - if (!$conf->use_javascript_ajax) - { + if (!$conf->use_javascript_ajax) { print '<tr class="oddeven">'; print '<td>'.$commandestatic->LibStatut($status, 0).'</td>'; print '<td class="right"><a href="list.php?statut='.$status.'">'.(isset($vals[$status]) ? $vals[$status] : 0).'</a></td>'; print "</tr>\n"; } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<tr class="impair"><td class="center" colspan="2">'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -168,32 +185,34 @@ if ($resql) * Draft orders */ -if (!empty($conf->fournisseur->enabled)) -{ +if (!empty($conf->fournisseur->enabled)) { $sql = "SELECT c.rowid, c.ref, s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity("supplier_order").")"; // Thirdparty sharing is mandatory with supplier order sharing $sql .= " AND c.fk_statut = 0"; - if (!empty($socid)) $sql .= " AND c.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if (!empty($socid)) { + $sql .= " AND c.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="2">'.$langs->trans("DraftOrders").'</th></tr>'; $langs->load("orders"); $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -218,8 +237,7 @@ if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_T } $sql .= " u.rowid, u.lastname, u.firstname, u.email, u.statut"; $sql .= " FROM ".MAIN_DB_PREFIX."user as u"; -if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) -{ +if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug"; $sql .= " WHERE ((ug.fk_user = u.rowid"; $sql .= " AND ug.entity IN (".getEntity('usergroup')."))"; @@ -230,8 +248,7 @@ if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_T $sql .= " AND u.fk_soc IS NULL"; // An external user can not approved $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -240,16 +257,14 @@ if ($resql) print '<tr class="liste_titre"><th>'.$langs->trans("UserWithApproveOrderGrant").'</th>'; print "</tr>\n"; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $userstatic = new User($db); $userstatic->id = $obj->rowid; $userstatic->getrights('fournisseur'); - if (!empty($userstatic->rights->fournisseur->commande->approuver)) - { + if (!empty($userstatic->rights->fournisseur->commande->approuver)) { print '<tr class="oddeven">'; print '<td>'; $userstatic->lastname = $obj->lastname; @@ -281,29 +296,32 @@ $max = 5; $sql = "SELECT c.rowid, c.ref, c.fk_statut as status, c.tms, c.billed, s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity = ".$conf->entity; //$sql.= " AND c.fk_statut > 2"; -if (!empty($socid)) $sql .= " AND c.fk_soc = ".$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if (!empty($socid)) { + $sql .= " AND c.fk_soc = ".$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " ORDER BY c.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="4">'.$langs->trans("LastModifiedOrders", $max).'</th></tr>'; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -338,7 +356,9 @@ if ($resql) } } print "</table></div><br>"; -} else dol_print_error($db); +} else { + dol_print_error($db); +} /* diff --git a/htdocs/fourn/commande/info.php b/htdocs/fourn/commande/info.php index a50cbbdad39..60c67fdd0e8 100644 --- a/htdocs/fourn/commande/info.php +++ b/htdocs/fourn/commande/info.php @@ -44,17 +44,24 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = 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,DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC'; +} -if (GETPOST('actioncode', 'array')) -{ +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_OBJECTS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECTS)); } @@ -62,10 +69,14 @@ $search_agenda_label = GETPOST('search_agenda_label'); // Security check $socid = 0; -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); -if (!$user->rights->fournisseur->commande->lire) accessforbidden(); +if (!$user->rights->fournisseur->commande->lire) { + accessforbidden(); +} @@ -76,11 +87,12 @@ if (!$user->rights->fournisseur->commande->lire) accessforbidden(); $parameters = array('id'=>$id); $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'); +} // Purge search criteria -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers $actioncode = ''; $search_agenda_label = ''; } @@ -94,15 +106,16 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $form = new Form($db); $object = new CommandeFournisseur($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch($id, $ref); $object->fetch_thirdparty(); $object->info($object->id); } $title = $langs->trans("SupplierOrder").' - '.$object->ref.' '.$object->name; -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Info"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->ref.' '.$object->name.' - '.$langs->trans("Info"); +} $help_url = 'EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; llxHeader('', $title, $help_url); @@ -125,12 +138,10 @@ $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_ // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; @@ -181,18 +192,15 @@ print dol_get_fiche_end(); $out = ''; $permok = $user->rights->agenda->myactions->create; -if ($permok) -{ +if ($permok) { $out .= '&originid='.$object->id.'&origin=order_supplier'; } print '<div class="tabsAction">'; -if (!empty($conf->agenda->enabled)) -{ - if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) - { +if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id).'">'.$langs->trans("AddAction").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>'; @@ -202,18 +210,21 @@ if (!empty($conf->agenda->enabled)) print '</div>'; -if (!empty($object->id)) -{ +if (!empty($object->id)) { $param = '&id='.$object->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 load_fiche_titre($langs->trans("ActionsOnOrder"), '', ''); // List of actions on element /*include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); - $somethingshown = $formactions->showactions($object,'project',0);*/ + $formactions=new FormActions($db); + $somethingshown = $formactions->showactions($object,'project',0);*/ // List of todo actions //show_actions_todo($conf,$langs,$db,$object,null,0,$actioncode); diff --git a/htdocs/fourn/commande/list.php b/htdocs/fourn/commande/list.php index aa5f7c3ddc5..e35d9d84824 100644 --- a/htdocs/fourn/commande/list.php +++ b/htdocs/fourn/commande/list.php @@ -78,12 +78,12 @@ $optioncss = GETPOST('optioncss', 'alpha'); $socid = GETPOST('socid', 'int'); $search_sale = GETPOST('search_sale', 'int'); $search_total_ht = GETPOST('search_total_ht', 'alpha'); -$search_total_vat = GETPOST('search_total_vat', 'alpha'); +$search_total_tva = GETPOST('search_total_tva', 'alpha'); $search_total_ttc = GETPOST('search_total_ttc', 'alpha'); $search_multicurrency_code = GETPOST('search_multicurrency_code', 'alpha'); $search_multicurrency_tx = GETPOST('search_multicurrency_tx', 'alpha'); $search_multicurrency_montant_ht = GETPOST('search_multicurrency_montant_ht', 'alpha'); -$search_multicurrency_montant_vat = GETPOST('search_multicurrency_montant_vat', 'alpha'); +$search_multicurrency_montant_tva = GETPOST('search_multicurrency_montant_tva', 'alpha'); $search_multicurrency_montant_ttc = GETPOST('search_multicurrency_montant_ttc', 'alpha'); $optioncss = GETPOST('optioncss', 'alpha'); $search_billed = GETPOST('search_billed', 'int'); @@ -99,7 +99,9 @@ if (is_array(GETPOST('search_status', 'intcomma'))) { // Security check $orderid = GETPOST('orderid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $orderid, '', 'commande'); $diroutputmassaction = $conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id; @@ -108,14 +110,22 @@ $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 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 'cf.ref'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'cf.ref'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} -if ($search_status == '') $search_status = -1; +if ($search_status == '') { + $search_status = -1; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new CommandeFournisseur($db); @@ -138,7 +148,9 @@ $fieldstosearchall = array( 's.town'=>"Town", 'cf.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["cf.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["cf.note_private"] = "NotePrivate"; +} $checkedtypetiers = 0; $arrayfields = array( @@ -155,12 +167,12 @@ $arrayfields = array( 'cf.date_commande'=>array('label'=>"OrderDateShort", 'checked'=>1), 'cf.date_livraison'=>array('label'=>"DateDeliveryPlanned", 'checked'=>1, 'enabled'=>empty($conf->global->ORDER_DISABLE_DELIVERY_DATE)), 'cf.total_ht'=>array('label'=>"AmountHT", 'checked'=>1), - 'cf.total_vat'=>array('label'=>"AmountVAT", 'checked'=>0), + 'cf.total_tva'=>array('label'=>"AmountVAT", 'checked'=>0), 'cf.total_ttc'=>array('label'=>"AmountTTC", 'checked'=>0), 'cf.multicurrency_code'=>array('label'=>'Currency', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), 'cf.multicurrency_tx'=>array('label'=>'CurrencyRate', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), 'cf.multicurrency_total_ht'=>array('label'=>'MulticurrencyAmountHT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), - 'cf.multicurrency_total_vat'=>array('label'=>'MulticurrencyAmountVAT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), + 'cf.multicurrency_total_tva'=>array('label'=>'MulticurrencyAmountVAT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), 'cf.multicurrency_total_ttc'=>array('label'=>'MulticurrencyAmountTTC', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), 'cf.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500), 'cf.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), @@ -180,21 +192,25 @@ $error = 0; * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createsupplierbills') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createsupplierbills') { + $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)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_categ = ''; $search_user = ''; $search_sale = ''; @@ -210,12 +226,12 @@ if (empty($reshook)) $search_type_thirdparty = ''; $search_request_author = ''; $search_total_ht = ''; - $search_total_vat = ''; + $search_total_tva = ''; $search_total_ttc = ''; $search_multicurrency_code = ''; $search_multicurrency_tx = ''; $search_multicurrency_montant_ht = ''; - $search_multicurrency_montant_vat = ''; + $search_multicurrency_montant_tva = ''; $search_multicurrency_montant_ttc = ''; $search_project_ref = ''; $search_status = -1; @@ -231,8 +247,7 @@ if (empty($reshook)) $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -245,8 +260,7 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; // Mass action to generate vendor bills - if ($massaction == 'confirm_createsupplierbills') - { + if ($massaction == 'confirm_createsupplierbills') { $orders = GETPOST('toselect', 'array'); $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); $validate_invoices = GETPOST('validate_invoices', 'int'); @@ -262,7 +276,9 @@ if (empty($reshook)) foreach ($orders as $id_order) { $cmd = new CommandeFournisseur($db); - if ($cmd->fetch($id_order) <= 0) continue; + if ($cmd->fetch($id_order) <= 0) { + continue; + } $objecttmp = new FactureFournisseur($db); if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) { @@ -274,11 +290,12 @@ if (empty($reshook)) $objecttmp->mode_reglement_id = $cmd->mode_reglement_id; $objecttmp->fk_project = $cmd->fk_project; $objecttmp->multicurrency_code = $cmd->multicurrency_code; - if (empty($createbills_onebythird)) $objecttmp->ref_client = $cmd->ref_client; + if (empty($createbills_onebythird)) { + $objecttmp->ref_client = $cmd->ref_client; + } $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - if (empty($datefacture)) - { + if (empty($datefacture)) { $datefacture = dol_now(); } @@ -295,8 +312,7 @@ if (empty($reshook)) } } - if ($objecttmp->id > 0) - { + if ($objecttmp->id > 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; $sql .= "fk_source"; $sql .= ", sourcetype"; @@ -309,16 +325,13 @@ if (empty($reshook)) $sql .= ", '".$db->escape($objecttmp->element)."'"; $sql .= ")"; - if (!$db->query($sql)) - { + if (!$db->query($sql)) { $erorr++; } - if (!$error) - { + if (!$error) { $lines = $cmd->lines; - if (empty($lines) && method_exists($cmd, 'fetch_lines')) - { + if (empty($lines) && method_exists($cmd, 'fetch_lines')) { $cmd->fetch_lines(); $lines = $cmd->lines; } @@ -326,11 +339,9 @@ if (empty($reshook)) $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); - if ($lines[$i]->subprice < 0) - { + if ($lines[$i]->subprice < 0) { // Negative line, we create a discount line $discount = new DiscountAbsolute($db); $discount->fk_soc = $objecttmp->socid; @@ -341,8 +352,7 @@ if (empty($reshook)) $discount->fk_user = $user->id; $discount->description = $desc; $discountid = $discount->create($user); - if ($discountid > 0) - { + if ($discountid > 0) { $result = $objecttmp->insert_discount($discountid); //$result=$discount->link_to_invoice($lineid,$id); } else { @@ -355,17 +365,28 @@ if (empty($reshook)) $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); // Date start $date_start = false; - if ($lines[$i]->date_debut_prevue) $date_start = $lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) $date_start = $lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) $date_start = $lines[$i]->date_start; + if ($lines[$i]->date_debut_prevue) { + $date_start = $lines[$i]->date_debut_prevue; + } + if ($lines[$i]->date_debut_reel) { + $date_start = $lines[$i]->date_debut_reel; + } + if ($lines[$i]->date_start) { + $date_start = $lines[$i]->date_start; + } //Date end $date_end = false; - if ($lines[$i]->date_fin_prevue) $date_end = $lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) $date_end = $lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) $date_end = $lines[$i]->date_end; + if ($lines[$i]->date_fin_prevue) { + $date_end = $lines[$i]->date_fin_prevue; + } + if ($lines[$i]->date_fin_reel) { + $date_end = $lines[$i]->date_fin_reel; + } + if ($lines[$i]->date_end) { + $date_end = $lines[$i]->date_end; + } // Reset fk_parent_line for no child products and special product - if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) - { + if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) { $fk_parent_line = 0; } $result = $objecttmp->addline( @@ -393,8 +414,7 @@ if (empty($reshook)) $lines[$i]->special_code, $fk_parent_line ); - if ($result > 0) - { + if ($result > 0) { $lineid = $result; } else { $lineid = 0; @@ -402,8 +422,7 @@ if (empty($reshook)) break; } // Defined the new fk_parent_line - if ($result > 0 && $lines[$i]->product_type == 9) - { + if ($result > 0 && $lines[$i]->product_type == 9) { $fk_parent_line = $result; } } @@ -413,8 +432,11 @@ if (empty($reshook)) $cmd->classifyBilled($user); // TODO Move this in workflow like done for customer orders - if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp; - else $TFact[$objecttmp->id] = $objecttmp; + if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) { + $TFactThird[$cmd->socid] = $objecttmp; + } else { + $TFact[$objecttmp->id] = $objecttmp; + } } // Build doc with all invoices @@ -424,11 +446,9 @@ if (empty($reshook)) if (!$error && $validate_invoices) { $massaction = $action = 'builddoc'; - foreach ($TAllFact as &$objecttmp) - { + foreach ($TAllFact as &$objecttmp) { $objecttmp->validate($user); - if ($result <= 0) - { + if ($result <= 0) { $error++; setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); break; @@ -446,8 +466,7 @@ if (empty($reshook)) $massaction = $action = 'confirm_createsupplierbills'; } - if (!$error) - { + if (!$error) { $db->commit(); if ($nb_bills_created == 1) { @@ -460,29 +479,73 @@ if (empty($reshook)) // Make a redirect to avoid to bill twice if we make a refresh or back $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 ($socid > 0) $param .= '&socid='.urlencode($socid); - if ($search_status != '') $param .= '&search_status='.urlencode($search_status); - if ($search_orderday) $param .= '&search_orderday='.urlencode($search_orderday); - if ($search_ordermonth) $param .= '&search_ordermonth='.urlencode($search_ordermonth); - if ($search_orderyear) $param .= '&search_orderyear='.urlencode($search_orderyear); - if ($search_deliveryday) $param .= '&search_deliveryday='.urlencode($search_deliveryday); - if ($search_deliverymonth) $param .= '&search_deliverymonth='.urlencode($search_deliverymonth); - if ($search_deliveryyear) $param .= '&search_deliveryyear='.urlencode($search_deliveryyear); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_company) $param .= '&search_company='.urlencode($search_company); + 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 ($socid > 0) { + $param .= '&socid='.urlencode($socid); + } + if ($search_status != '') { + $param .= '&search_status='.urlencode($search_status); + } + if ($search_orderday) { + $param .= '&search_orderday='.urlencode($search_orderday); + } + if ($search_ordermonth) { + $param .= '&search_ordermonth='.urlencode($search_ordermonth); + } + if ($search_orderyear) { + $param .= '&search_orderyear='.urlencode($search_orderyear); + } + if ($search_deliveryday) { + $param .= '&search_deliveryday='.urlencode($search_deliveryday); + } + if ($search_deliverymonth) { + $param .= '&search_deliverymonth='.urlencode($search_deliverymonth); + } + if ($search_deliveryyear) { + $param .= '&search_deliveryyear='.urlencode($search_deliveryyear); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_company) { + $param .= '&search_company='.urlencode($search_company); + } //if ($search_ref_customer) $param .= '&search_ref_customer='.urlencode($search_ref_customer); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); - if ($search_total_ht != '') $param .= '&search_total_ht='.urlencode($search_total_ht); - if ($search_total_vat != '') $param .= '&search_total_vat='.urlencode($search_total_vat); - if ($search_total_ttc != '') $param .= '&search_total_ttc='.urlencode($search_total_ttc); - if ($search_project_ref >= 0) $param .= "&search_project_ref=".urlencode($search_project_ref); - if ($show_files) $param .= '&show_files='.urlencode($show_files); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($billed != '') $param .= '&billed='.urlencode($billed); + if ($search_user > 0) { + $param .= '&search_user='.urlencode($search_user); + } + if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); + } + if ($search_total_ht != '') { + $param .= '&search_total_ht='.urlencode($search_total_ht); + } + if ($search_total_tva != '') { + $param .= '&search_total_tva='.urlencode($search_total_tva); + } + if ($search_total_ttc != '') { + $param .= '&search_total_ttc='.urlencode($search_total_ttc); + } + if ($search_project_ref >= 0) { + $param .= "&search_project_ref=".urlencode($search_project_ref); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($billed != '') { + $param .= '&billed='.urlencode($billed); + } header("Location: ".$_SERVER['PHP_SELF'].'?'.$param); exit; @@ -513,8 +576,7 @@ $formother = new FormOther($db); $formcompany = new FormCompany($db); $title = $langs->trans("ListOfSupplierOrders"); -if ($socid > 0) -{ +if ($socid > 0) { $fourn = new Fournisseur($db); $fourn->fetch($socid); $title .= ' - '.$fourn->name; @@ -528,26 +590,32 @@ if ($socid > 0) elseif ($search_status == '6,7') $title .= ' - '.$langs->trans("StatusOrderCanceled"); elseif (is_numeric($search_status) && $search_status >= 0) $title .= ' - '.$commandestatic->LibStatut($search_status); }*/ -if ($search_billed > 0) $title .= ' - '.$langs->trans("Billed"); +if ($search_billed > 0) { + $title .= ' - '.$langs->trans("Billed"); +} //$help_url="EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes"; $help_url = ''; // llxHeader('',$title,$help_url); $sql = 'SELECT'; -if ($sall || $search_product_category > 0 || $search_user > 0) $sql = 'SELECT DISTINCT'; +if ($sall || $search_product_category > 0 || $search_user > 0) { + $sql = 'SELECT DISTINCT'; +} $sql .= ' s.rowid as socid, s.nom as name, s.town, s.zip, s.fk_pays, s.client, s.code_client, s.email,'; $sql .= " typent.code as typent_code,"; $sql .= " state.code_departement as state_code, state.nom as state_name,"; -$sql .= " cf.rowid, cf.ref, cf.ref_supplier, cf.fk_statut, cf.billed, cf.total_ht, cf.tva as total_tva, cf.total_ttc, cf.fk_user_author, cf.date_commande as date_commande, cf.date_livraison as date_livraison,"; -$sql .= ' cf.fk_multicurrency, cf.multicurrency_code, cf.multicurrency_tx, cf.multicurrency_total_ht, cf.multicurrency_total_tva as multicurrency_total_vat, cf.multicurrency_total_ttc,'; +$sql .= " cf.rowid, cf.ref, cf.ref_supplier, cf.fk_statut, cf.billed, cf.total_ht, cf.total_tva, cf.total_ttc, cf.fk_user_author, cf.date_commande as date_commande, cf.date_livraison as date_livraison,"; +$sql .= ' cf.fk_multicurrency, cf.multicurrency_code, cf.multicurrency_tx, cf.multicurrency_total_ht, cf.multicurrency_total_tva, cf.multicurrency_total_ttc,'; $sql .= ' cf.date_creation as date_creation, cf.tms as date_update,'; $sql .= ' cf.note_public, cf.note_private,'; $sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_title,"; $sql .= " u.firstname, u.lastname, u.photo, u.login, u.email as user_email"; // 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 : ''); + 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(); @@ -558,15 +626,22 @@ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as cf"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cf.rowid = ef.fk_object)"; -if ($sall || $search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commande_fournisseurdet as pd ON cf.rowid=pd.fk_commande'; -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cf.rowid = ef.fk_object)"; +} +if ($sall || $search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commande_fournisseurdet as pd ON cf.rowid=pd.fk_commande'; +} +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON cf.fk_user_author = u.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = cf.fk_projet"; // We'll need this table joined to the select in order to filter by sale -if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; -if ($search_user > 0) -{ +if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} +if ($search_user > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } @@ -575,39 +650,93 @@ $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object $sql .= $hookmanager->resPrint; $sql .= ' WHERE cf.fk_soc = s.rowid'; $sql .= ' AND cf.entity IN ('.getEntity('supplier_order').')'; -if ($socid > 0) $sql .= " AND s.rowid = ".$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($search_ref) $sql .= natural_search('cf.ref', $search_ref); -if ($search_refsupp) $sql .= natural_search("cf.ref_supplier", $search_refsupp); -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_request_author) $sql .= natural_search(array('u.lastname', 'u.firstname', 'u.login'), $search_request_author); -if ($search_billed != '' && $search_billed >= 0) $sql .= " AND cf.billed = ".$db->escape($search_billed); -if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; +if ($socid > 0) { + $sql .= " AND s.rowid = ".$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($search_ref) { + $sql .= natural_search('cf.ref', $search_ref); +} +if ($search_refsupp) { + $sql .= natural_search("cf.ref_supplier", $search_refsupp); +} +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} +if ($search_company) { + $sql .= natural_search('s.nom', $search_company); +} +if ($search_request_author) { + $sql .= natural_search(array('u.lastname', 'u.firstname', 'u.login'), $search_request_author); +} +if ($search_billed != '' && $search_billed >= 0) { + $sql .= " AND cf.billed = ".$db->escape($search_billed); +} +if ($search_product_category > 0) { + $sql .= " AND cp.fk_categorie = ".$search_product_category; +} //Required triple check because statut=0 means draft filter -if (GETPOST('statut', 'intcomma') !== '') +if (GETPOST('statut', 'intcomma') !== '') { $sql .= " AND cf.fk_statut IN (".$db->sanitize($db->escape($db->escape(GETPOST('statut', 'intcomma')))).")"; -if ($search_status != '' && $search_status != '-1') +} +if ($search_status != '' && $search_status != '-1') { $sql .= " AND cf.fk_statut IN (".$db->sanitize($db->escape($search_status)).")"; +} $sql .= dolSqlDateFilter("cf.date_commande", $search_orderday, $search_ordermonth, $search_orderyear); $sql .= dolSqlDateFilter("cf.date_livraison", $search_deliveryday, $search_deliverymonth, $search_deliveryyear); -if ($search_town) $sql .= natural_search('s.town', $search_town); -if ($search_zip) $sql .= natural_search("s.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_country) $sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')'; -if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; -if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$db->escape($search_sale); -if ($search_user > 0) $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='supplier_order' AND tc.source='internal' AND ec.element_id = cf.rowid AND ec.fk_socpeople = ".$db->escape($search_user); -if ($search_total_ht != '') $sql .= natural_search('cf.total_ht', $search_total_ht, 1); -if ($search_total_vat != '') $sql .= natural_search('cf.tva', $search_total_vat, 1); -if ($search_total_ttc != '') $sql .= natural_search('cf.total_ttc', $search_total_ttc, 1); -if ($search_multicurrency_code != '') $sql .= ' AND cf.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; -if ($search_multicurrency_tx != '') $sql .= natural_search('cf.multicurrency_tx', $search_multicurrency_tx, 1); -if ($search_multicurrency_montant_ht != '') $sql .= natural_search('cf.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); -if ($search_multicurrency_montant_vat != '') $sql .= natural_search('cf.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); -if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('cf.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); -if ($search_project_ref != '') $sql .= natural_search("p.ref", $search_project_ref); +if ($search_town) { + $sql .= natural_search('s.town', $search_town); +} +if ($search_zip) { + $sql .= natural_search("s.zip", $search_zip); +} +if ($search_state) { + $sql .= natural_search("state.nom", $search_state); +} +if ($search_country) { + $sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')'; +} +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; +} +if ($search_company) { + $sql .= natural_search('s.nom', $search_company); +} +if ($search_sale > 0) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$db->escape($search_sale); +} +if ($search_user > 0) { + $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='supplier_order' AND tc.source='internal' AND ec.element_id = cf.rowid AND ec.fk_socpeople = ".$db->escape($search_user); +} +if ($search_total_ht != '') { + $sql .= natural_search('cf.total_ht', $search_total_ht, 1); +} +if ($search_total_tva != '') { + $sql .= natural_search('cf.total_tva', $search_total_tva, 1); +} +if ($search_total_ttc != '') { + $sql .= natural_search('cf.total_ttc', $search_total_ttc, 1); +} +if ($search_multicurrency_code != '') { + $sql .= ' AND cf.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; +} +if ($search_multicurrency_tx != '') { + $sql .= natural_search('cf.multicurrency_tx', $search_multicurrency_tx, 1); +} +if ($search_multicurrency_montant_ht != '') { + $sql .= natural_search('cf.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); +} +if ($search_multicurrency_montant_tva != '') { + $sql .= natural_search('cf.multicurrency_total_tva', $search_multicurrency_montant_tva, 1); +} +if ($search_multicurrency_montant_ttc != '') { + $sql .= natural_search('cf.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); +} +if ($search_project_ref != '') { + $sql .= natural_search("p.ref", $search_project_ref); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -619,12 +748,10 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -634,14 +761,12 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); - if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) - { + if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/fourn/commande/card.php?id='.$id); @@ -651,36 +776,96 @@ if ($resql) llxHeader('', $title, $help_url); $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 ($socid > 0) $param .= '&socid='.urlencode($socid); - if ($sall) $param .= "&search_all=".urlencode($sall); - if ($search_orderday) $param .= '&search_orderday='.urlencode($search_orderday); - if ($search_ordermonth) $param .= '&search_ordermonth='.urlencode($search_ordermonth); - if ($search_orderyear) $param .= '&search_orderyear='.urlencode($search_orderyear); - if ($search_deliveryday) $param .= '&search_deliveryday='.urlencode($search_deliveryday); - if ($search_deliverymonth) $param .= '&search_deliverymonth='.urlencode($search_deliverymonth); - if ($search_deliveryyear) $param .= '&search_deliveryyear='.urlencode($search_deliveryyear); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_company) $param .= '&search_company='.urlencode($search_company); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_request_author) $param .= '&search_request_author='.urlencode($search_request_author); - if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); - if ($search_total_ht != '') $param .= '&search_total_ht='.urlencode($search_total_ht); - if ($search_total_ttc != '') $param .= "&search_total_ttc=".urlencode($search_total_ttc); - if ($search_multicurrency_code != '') $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); - if ($search_multicurrency_tx != '') $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); - if ($search_multicurrency_montant_ht != '') $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); - if ($search_multicurrency_montant_vat != '') $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); - if ($search_multicurrency_montant_ttc != '') $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); - if ($search_refsupp) $param .= "&search_refsupp=".urlencode($search_refsupp); - if ($search_status != '' && $search_status != '-1') $param .= "&search_status=".urlencode($search_status); - if ($search_project_ref >= 0) $param .= "&search_project_ref=".urlencode($search_project_ref); - if ($search_billed != '') $param .= "&search_billed=".urlencode($search_billed); - if ($show_files) $param .= '&show_files='.urlencode($show_files); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); + 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 ($socid > 0) { + $param .= '&socid='.urlencode($socid); + } + if ($sall) { + $param .= "&search_all=".urlencode($sall); + } + if ($search_orderday) { + $param .= '&search_orderday='.urlencode($search_orderday); + } + if ($search_ordermonth) { + $param .= '&search_ordermonth='.urlencode($search_ordermonth); + } + if ($search_orderyear) { + $param .= '&search_orderyear='.urlencode($search_orderyear); + } + if ($search_deliveryday) { + $param .= '&search_deliveryday='.urlencode($search_deliveryday); + } + if ($search_deliverymonth) { + $param .= '&search_deliverymonth='.urlencode($search_deliverymonth); + } + if ($search_deliveryyear) { + $param .= '&search_deliveryyear='.urlencode($search_deliveryyear); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_company) { + $param .= '&search_company='.urlencode($search_company); + } + if ($search_user > 0) { + $param .= '&search_user='.urlencode($search_user); + } + if ($search_request_author) { + $param .= '&search_request_author='.urlencode($search_request_author); + } + if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); + } + if ($search_total_ht != '') { + $param .= '&search_total_ht='.urlencode($search_total_ht); + } + if ($search_total_ttc != '') { + $param .= "&search_total_ttc=".urlencode($search_total_ttc); + } + if ($search_multicurrency_code != '') { + $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); + } + if ($search_multicurrency_tx != '') { + $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); + } + if ($search_multicurrency_montant_ht != '') { + $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); + } + if ($search_multicurrency_montant_tva != '') { + $param .= '&search_multicurrency_montant_tva='.urlencode($search_multicurrency_montant_tva); + } + if ($search_multicurrency_montant_ttc != '') { + $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); + } + if ($search_refsupp) { + $param .= "&search_refsupp=".urlencode($search_refsupp); + } + if ($search_status != '' && $search_status != '-1') { + $param .= "&search_status=".urlencode($search_status); + } + if ($search_project_ref >= 0) { + $param .= "&search_project_ref=".urlencode($search_project_ref); + } + if ($search_billed != '') { + $param .= "&search_billed=".urlencode($search_billed); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -695,18 +880,28 @@ if ($resql) 'builddoc'=>$langs->trans("PDFMerge"), 'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisSupplier"); - if ($user->rights->fournisseur->commande->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete', 'createbills'))) $arrayofmassactions = array(); + if ($user->rights->fournisseur->facture->creer) { + $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisSupplier"); + } + if ($user->rights->fournisseur->commande->supprimer) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); + } + if (in_array($massaction, array('presend', 'predelete', 'createbills'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $url = DOL_URL_ROOT.'/fourn/commande/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewOrder'), '', 'fa fa-plus-circle', $url, '', $user->rights->fournisseur->commande->creer); // Lines of title fields print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -723,8 +918,7 @@ if ($resql) $trackid = 'sord'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($massaction == 'createbills') - { + if ($massaction == 'createbills') { //var_dump($_REQUEST); print '<input type="hidden" name="massaction" value="confirm_createsupplierbills">'; @@ -763,17 +957,17 @@ if ($resql) print '<br>'; } - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } $moreforfilter = ''; // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; @@ -781,16 +975,14 @@ if ($resql) $moreforfilter .= '</div>'; } // If the user can view other users - if ($user->rights->user->user->lire) - { + if ($user->rights->user->user->lire) { $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter .= '</div>'; } // If the user can view prospects other than his' - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) - { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; @@ -800,11 +992,13 @@ if ($resql) } $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)) - { + if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -829,126 +1023,116 @@ if ($resql) print '<tr class="liste_titre_filter">'; // Ref - if (!empty($arrayfields['cf.ref']['checked'])) - { + if (!empty($arrayfields['cf.ref']['checked'])) { print '<td class="liste_titre"><input size="8" type="text" class="flat maxwidth75" name="search_ref" value="'.$search_ref.'"></td>'; } // Ref customer - if (!empty($arrayfields['cf.ref_supplier']['checked'])) - { + if (!empty($arrayfields['cf.ref_supplier']['checked'])) { print '<td class="liste_titre"><input type="text" class="flat maxwidth75" name="search_refsupp" value="'.$search_refsupp.'"></td>'; } // Project ref - if (!empty($arrayfields['p.project_ref']['checked'])) - { + if (!empty($arrayfields['p.project_ref']['checked'])) { print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="search_project_ref" value="'.$search_project_ref.'"></td>'; } // Request author - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" size="6" name="search_request_author" value="'.$search_request_author.'">'; print '</td>'; } // Thirpdarty - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="liste_titre"><input type="text" size="6" class="flat" name="search_company" value="'.$search_company.'"></td>'; } // Town - if (!empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_town" value="'.$search_town.'"></td>'; + if (!empty($arrayfields['s.town']['checked'])) { + print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_town" value="'.$search_town.'"></td>'; + } // Zip - if (!empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_zip" value="'.$search_zip.'"></td>'; + if (!empty($arrayfields['s.zip']['checked'])) { + print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_zip" value="'.$search_zip.'"></td>'; + } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat maxwidth50" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; print '</td>'; } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print '<td class="liste_titre center">'; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print '</td>'; } // Company type - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone center">'; print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); print '</td>'; } // Date order - if (!empty($arrayfields['cf.date_commande']['checked'])) - { + if (!empty($arrayfields['cf.date_commande']['checked'])) { print '<td class="liste_titre nowraponall center">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_orderday" value="'.$search_orderday.'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_orderday" value="'.$search_orderday.'">'; + } print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_ordermonth" value="'.$search_ordermonth.'">'; $formother->select_year($search_orderyear ? $search_orderyear : -1, 'search_orderyear', 1, 20, 5); print '</td>'; } // Date delivery - if (!empty($arrayfields['cf.date_livraison']['checked'])) - { + if (!empty($arrayfields['cf.date_livraison']['checked'])) { print '<td class="liste_titre nowraponall center">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_deliveryday" value="'.$search_deliveryday.'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_deliveryday" value="'.$search_deliveryday.'">'; + } print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_deliverymonth" value="'.$search_deliverymonth.'">'; $formother->select_year($search_deliveryyear ? $search_deliveryyear : -1, 'search_deliveryyear', 1, 20, 5); print '</td>'; } - if (!empty($arrayfields['cf.total_ht']['checked'])) - { + if (!empty($arrayfields['cf.total_ht']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_total_ht" value="'.$search_total_ht.'">'; print '</td>'; } - if (!empty($arrayfields['cf.total_vat']['checked'])) - { + if (!empty($arrayfields['cf.total_tva']['checked'])) { // Amount print '<td class="liste_titre right">'; - print '<input class="flat" type="text" size="5" name="search_total_vat" value="'.$search_total_vat.'">'; + print '<input class="flat" type="text" size="5" name="search_total_tva" value="'.$search_total_tva.'">'; print '</td>'; } - if (!empty($arrayfields['cf.total_ttc']['checked'])) - { + if (!empty($arrayfields['cf.total_ttc']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_total_ttc" value="'.$search_total_ttc.'">'; print '</td>'; } - if (!empty($arrayfields['cf.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_code']['checked'])) { // Currency print '<td class="liste_titre">'; print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1); print '</td>'; } - if (!empty($arrayfields['cf.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_tx']['checked'])) { // Currency rate print '<td class="liste_titre">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="'.dol_escape_htmltag($search_multicurrency_tx).'">'; print '</td>'; } - if (!empty($arrayfields['cf.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_total_ht']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="'.dol_escape_htmltag($search_multicurrency_montant_ht).'">'; print '</td>'; } - if (!empty($arrayfields['cf.multicurrency_total_vat']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_total_tva']['checked'])) { // Amount print '<td class="liste_titre right">'; - print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_vat" value="'.dol_escape_htmltag($search_multicurrency_montant_vat).'">'; + print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_tva" value="'.dol_escape_htmltag($search_multicurrency_montant_tva).'">'; print '</td>'; } - if (!empty($arrayfields['cf.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_total_ttc']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ttc" value="'.dol_escape_htmltag($search_multicurrency_montant_ttc).'">'; @@ -962,27 +1146,23 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['cf.datec']['checked'])) - { + if (!empty($arrayfields['cf.datec']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Date modification - if (!empty($arrayfields['cf.tms']['checked'])) - { + if (!empty($arrayfields['cf.tms']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Status - if (!empty($arrayfields['cf.fk_statut']['checked'])) - { + if (!empty($arrayfields['cf.fk_statut']['checked'])) { print '<td class="liste_titre right">'; $formorder->selectSupplierOrderStatus($search_status, 1, 'search_status'); print '</td>'; } // Status billed - if (!empty($arrayfields['cf.billed']['checked'])) - { + if (!empty($arrayfields['cf.billed']['checked'])) { print '<td class="liste_titre center">'; print $form->selectyesno('search_billed', $search_billed, 1, 0, 1, 1); print '</td>'; @@ -997,37 +1177,87 @@ if ($resql) // Fields title print '<tr class="liste_titre">'; - if (!empty($arrayfields['cf.ref']['checked'])) print_liste_field_titre($arrayfields['cf.ref']['label'], $_SERVER["PHP_SELF"], "cf.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['cf.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['cf.ref_supplier']['label'], $_SERVER["PHP_SELF"], "cf.ref_supplier", "", $param, '', $sortfield, $sortorder, 'tdoverflowmax100imp '); - if (!empty($arrayfields['p.project_ref']['checked'])) print_liste_field_titre($arrayfields['p.project_ref']['label'], $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['u.login']['checked'])) print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], "u.login", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['cf.fk_author']['checked'])) print_liste_field_titre($arrayfields['cf.fk_author']['label'], $_SERVER["PHP_SELF"], "cf.fk_author", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['cf.date_commande']['checked'])) print_liste_field_titre($arrayfields['cf.date_commande']['label'], $_SERVER["PHP_SELF"], "cf.date_commande", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['cf.date_livraison']['checked'])) print_liste_field_titre($arrayfields['cf.date_livraison']['label'], $_SERVER["PHP_SELF"], 'cf.date_livraison', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['cf.total_ht']['checked'])) print_liste_field_titre($arrayfields['cf.total_ht']['label'], $_SERVER["PHP_SELF"], "cf.total_ht", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['cf.total_vat']['checked'])) print_liste_field_titre($arrayfields['cf.total_vat']['label'], $_SERVER["PHP_SELF"], "cf.tva", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['cf.total_ttc']['checked'])) print_liste_field_titre($arrayfields['cf.total_ttc']['label'], $_SERVER["PHP_SELF"], "cf.total_ttc", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['cf.multicurrency_code']['checked'])) print_liste_field_titre($arrayfields['cf.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_code', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['cf.multicurrency_tx']['checked'])) print_liste_field_titre($arrayfields['cf.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_tx', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['cf.multicurrency_total_ht']['checked'])) print_liste_field_titre($arrayfields['cf.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['cf.multicurrency_total_vat']['checked'])) print_liste_field_titre($arrayfields['cf.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['cf.multicurrency_total_ttc']['checked'])) print_liste_field_titre($arrayfields['cf.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['cf.ref']['checked'])) { + print_liste_field_titre($arrayfields['cf.ref']['label'], $_SERVER["PHP_SELF"], "cf.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['cf.ref_supplier']['checked'])) { + print_liste_field_titre($arrayfields['cf.ref_supplier']['label'], $_SERVER["PHP_SELF"], "cf.ref_supplier", "", $param, '', $sortfield, $sortorder, 'tdoverflowmax100imp '); + } + if (!empty($arrayfields['p.project_ref']['checked'])) { + print_liste_field_titre($arrayfields['p.project_ref']['label'], $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['u.login']['checked'])) { + print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], "u.login", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['cf.fk_author']['checked'])) { + print_liste_field_titre($arrayfields['cf.fk_author']['label'], $_SERVER["PHP_SELF"], "cf.fk_author", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['cf.date_commande']['checked'])) { + print_liste_field_titre($arrayfields['cf.date_commande']['label'], $_SERVER["PHP_SELF"], "cf.date_commande", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['cf.date_livraison']['checked'])) { + print_liste_field_titre($arrayfields['cf.date_livraison']['label'], $_SERVER["PHP_SELF"], 'cf.date_livraison', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['cf.total_ht']['checked'])) { + print_liste_field_titre($arrayfields['cf.total_ht']['label'], $_SERVER["PHP_SELF"], "cf.total_ht", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['cf.total_tva']['checked'])) { + print_liste_field_titre($arrayfields['cf.total_tva']['label'], $_SERVER["PHP_SELF"], "cf.total_tva", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['cf.total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['cf.total_ttc']['label'], $_SERVER["PHP_SELF"], "cf.total_ttc", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['cf.multicurrency_code']['checked'])) { + print_liste_field_titre($arrayfields['cf.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_code', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['cf.multicurrency_tx']['checked'])) { + print_liste_field_titre($arrayfields['cf.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_tx', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['cf.multicurrency_total_ht']['checked'])) { + print_liste_field_titre($arrayfields['cf.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['cf.multicurrency_total_tva']['checked'])) { + print_liste_field_titre($arrayfields['cf.multicurrency_total_tva']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['cf.multicurrency_total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['cf.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $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['cf.datec']['checked'])) print_liste_field_titre($arrayfields['cf.datec']['label'], $_SERVER["PHP_SELF"], "cf.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['cf.tms']['checked'])) print_liste_field_titre($arrayfields['cf.tms']['label'], $_SERVER["PHP_SELF"], "cf.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['cf.fk_statut']['checked'])) print_liste_field_titre($arrayfields['cf.fk_statut']['label'], $_SERVER["PHP_SELF"], "cf.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['cf.billed']['checked'])) print_liste_field_titre($arrayfields['cf.billed']['label'], $_SERVER["PHP_SELF"], 'cf.billed', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['cf.datec']['checked'])) { + print_liste_field_titre($arrayfields['cf.datec']['label'], $_SERVER["PHP_SELF"], "cf.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['cf.tms']['checked'])) { + print_liste_field_titre($arrayfields['cf.tms']['label'], $_SERVER["PHP_SELF"], "cf.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['cf.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['cf.fk_statut']['label'], $_SERVER["PHP_SELF"], "cf.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['cf.billed']['checked'])) { + print_liste_field_titre($arrayfields['cf.billed']['label'], $_SERVER["PHP_SELF"], 'cf.billed', '', $param, '', $sortfield, $sortorder, 'center '); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; @@ -1042,8 +1272,7 @@ if ($resql) $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $notshippable = 0; @@ -1067,8 +1296,7 @@ if ($resql) print '<tr class="oddeven">'; // Ref - if (!empty($arrayfields['cf.ref']['checked'])) - { + if (!empty($arrayfields['cf.ref']['checked'])) { print '<td class="nowrap">'; // Picto + Ref @@ -1079,24 +1307,30 @@ if ($resql) print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); print '</td>'."\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Ref Supplier - if (!empty($arrayfields['cf.ref_supplier']['checked'])) - { + if (!empty($arrayfields['cf.ref_supplier']['checked'])) { print '<td>'.$obj->ref_supplier.'</td>'."\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Project - if (!empty($arrayfields['p.project_ref']['checked'])) - { + if (!empty($arrayfields['p.project_ref']['checked'])) { $projectstatic->id = $obj->project_id; $projectstatic->ref = $obj->project_ref; $projectstatic->title = $obj->project_title; print '<td>'; - if ($obj->project_id > 0) print $projectstatic->getNomUrl(1); + if ($obj->project_id > 0) { + print $projectstatic->getNomUrl(1); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Author $userstatic->id = $obj->fk_user_author; @@ -1105,68 +1339,78 @@ if ($resql) $userstatic->login = $obj->login; $userstatic->photo = $obj->photo; $userstatic->email = $obj->user_email; - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { print '<td class="tdoverflowmax150">'; - if ($userstatic->id) print $userstatic->getNomUrl(1); + if ($userstatic->id) { + print $userstatic->getNomUrl(1); + } print "</td>"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Thirdparty - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="tdoverflowmax150">'; $thirdpartytmp->id = $obj->socid; $thirdpartytmp->name = $obj->name; $thirdpartytmp->email = $obj->email; print $thirdpartytmp->getNomUrl(1, 'supplier'); print '</td>'."\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['s.town']['checked'])) - { + if (!empty($arrayfields['s.town']['checked'])) { print '<td>'; print $obj->town; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { + if (!empty($arrayfields['s.zip']['checked'])) { print '<td>'; print $obj->zip; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print "<td>".$obj->state_name."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print '<td class="center">'; $tmparray = getCountry($obj->fk_pays, 'all'); print $tmparray['label']; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print '<td class="center">'; - if (count($typenArray) == 0) $typenArray = $formcompany->typent_array(1); + if (count($typenArray) == 0) { + $typenArray = $formcompany->typent_array(1); + } print $typenArray[$obj->typent_code]; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Order date - if (!empty($arrayfields['cf.date_commande']['checked'])) - { + if (!empty($arrayfields['cf.date_commande']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_commande), 'day'); if ($objectstatic->statut != $objectstatic::STATUS_ORDERSENT && $objectstatic->statut != $objectstatic::STATUS_RECEIVED_PARTIALLY) { @@ -1175,11 +1419,12 @@ if ($resql) } } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Plannned date of delivery - if (!empty($arrayfields['cf.date_livraison']['checked'])) - { + if (!empty($arrayfields['cf.date_livraison']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_livraison), 'day'); if ($objectstatic->statut == $objectstatic::STATUS_ORDERSENT || $objectstatic->statut == $objectstatic::STATUS_RECEIVED_PARTIALLY) { @@ -1188,65 +1433,81 @@ if ($resql) } } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['cf.total_ht']['checked'])) - { + if (!empty($arrayfields['cf.total_ht']['checked'])) { print '<td class="right">'.price($obj->total_ht)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cf.total_ht'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'cf.total_ht'; + } $totalarray['val']['cf.total_ht'] += $obj->total_ht; } // Amount VAT - if (!empty($arrayfields['cf.total_vat']['checked'])) - { + if (!empty($arrayfields['cf.total_tva']['checked'])) { print '<td class="right">'.price($obj->total_tva)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cf.total_vat'; - $totalarray['val']['cf.total_vat'] += $obj->total_tva; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'cf.total_tva'; + } + $totalarray['val']['cf.total_tva'] += $obj->total_tva; } // Amount TTC - if (!empty($arrayfields['cf.total_ttc']['checked'])) - { + if (!empty($arrayfields['cf.total_ttc']['checked'])) { print '<td class="right">'.price($obj->total_ttc)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cf.total_ttc'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'cf.total_ttc'; + } $totalarray['val']['cf.total_ttc'] += $obj->total_ttc; } // Currency - if (!empty($arrayfields['cf.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_code']['checked'])) { print '<td class="nowrap">'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Currency rate - if (!empty($arrayfields['cf.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_tx']['checked'])) { print '<td class="nowrap">'; $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code); print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['cf.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_total_ht']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_ht)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount VAT - if (!empty($arrayfields['cf.multicurrency_total_vat']['checked'])) - { - print '<td class="right nowrap">'.price($obj->multicurrency_total_vat)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!empty($arrayfields['cf.multicurrency_total_tva']['checked'])) { + print '<td class="right nowrap">'.price($obj->multicurrency_total_tva)."</td>\n"; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount TTC - if (!empty($arrayfields['cf.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_total_ttc']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_ttc)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -1256,44 +1517,51 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['cf.datec']['checked'])) - { + if (!empty($arrayfields['cf.datec']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['cf.tms']['checked'])) - { + if (!empty($arrayfields['cf.tms']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['cf.fk_statut']['checked'])) - { + if (!empty($arrayfields['cf.fk_statut']['checked'])) { print '<td class="right nowrap">'.$objectstatic->LibStatut($obj->fk_statut, 5, $obj->billed).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Billed - if (!empty($arrayfields['cf.billed']['checked'])) - { + if (!empty($arrayfields['cf.billed']['checked'])) { print '<td class="center">'.yn($obj->billed).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; @@ -1317,7 +1585,9 @@ if ($resql) print '</form>'."\n"; $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/fourn/commande/note.php b/htdocs/fourn/commande/note.php index dea5ad69afa..9f8c192752c 100644 --- a/htdocs/fourn/commande/note.php +++ b/htdocs/fourn/commande/note.php @@ -40,7 +40,9 @@ $ref = GETPOST('ref'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); $object = new CommandeFournisseur($db); @@ -72,10 +74,8 @@ $form = new Form($db); $now = dol_now(); -if ($id > 0 || !empty($ref)) -{ - if ($result >= 0) - { +if ($id > 0 || !empty($ref)) { + if ($result >= 0) { $object->fetch_thirdparty(); $author = new User($db); @@ -97,12 +97,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/fourn/commande/tpl/linkedobjectblock.tpl.php b/htdocs/fourn/commande/tpl/linkedobjectblock.tpl.php index 57dfb90e3fd..a152ca26ff1 100644 --- a/htdocs/fourn/commande/tpl/linkedobjectblock.tpl.php +++ b/htdocs/fourn/commande/tpl/linkedobjectblock.tpl.php @@ -17,8 +17,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -37,41 +36,41 @@ $langs->load("orders"); $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - <tr class="<?php echo $trclass; ?>"> - <td><?php echo $langs->trans("SupplierOrder"); ?></td> - <td><a href="<?php echo DOL_URL_ROOT.'/fourn/commande/card.php?id='.$objectlink->id ?>"><?php echo img_object($langs->trans("ShowOrder"), "order").' '.$objectlink->ref; ?></a></td> - <td class="left"><?php echo $objectlink->ref_supplier; ?></td> - <td class="center"><?php echo dol_print_date($objectlink->date, 'day'); ?></td> - <td class="right"><?php + <tr class="<?php echo $trclass; ?>"> + <td><?php echo $langs->trans("SupplierOrder"); ?></td> + <td><a href="<?php echo DOL_URL_ROOT.'/fourn/commande/card.php?id='.$objectlink->id ?>"><?php echo img_object($langs->trans("ShowOrder"), "order").' '.$objectlink->ref; ?></a></td> + <td class="left"><?php echo $objectlink->ref_supplier; ?></td> + <td class="center"><?php echo dol_print_date($objectlink->date, 'day'); ?></td> + <td class="right"><?php if ($user->rights->fournisseur->commande->lire) { $total = $total + $objectlink->total_ht; echo price($objectlink->total_ht); } ?></td> - <td class="right"><?php echo $objectlink->getLibStatut(3); ?></td> - <td class="right"><a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a></td> - </tr> + <td class="right"><?php echo $objectlink->getLibStatut(3); ?></td> + <td class="right"><a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a></td> + </tr> <?php } -if (count($linkedObjectBlock) > 1) -{ +if (count($linkedObjectBlock) > 1) { ?> - <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> - <td><?php echo $langs->trans("Total"); ?></td> - <td></td> - <td class="center"></td> - <td class="center"></td> - <td class="right"><?php echo price($total); ?></td> - <td class="right"></td> - <td class="right"></td> - </tr> - <?php + <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> + <td><?php echo $langs->trans("Total"); ?></td> + <td></td> + <td class="center"></td> + <td class="center"></td> + <td class="right"><?php echo price($total); ?></td> + <td class="right"></td> + <td class="right"></td> + </tr> + <?php } print "<!-- END PHP TEMPLATE -->\n"; diff --git a/htdocs/fourn/contact.php b/htdocs/fourn/contact.php index 781fd4b6e9a..82c8df6ac66 100644 --- a/htdocs/fourn/contact.php +++ b/htdocs/fourn/contact.php @@ -35,8 +35,7 @@ $langs->load("companies"); llxHeader(); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -45,12 +44,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 = "p.name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "p.name"; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; @@ -59,14 +64,20 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; */ $sql = "SELECT s.rowid as socid, s.nom as name, st.libelle as stcomm, p.rowid as cidp, p.lastname, p.firstname, p.email, p.phone"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; +} $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."socpeople as p, ".MAIN_DB_PREFIX."c_stcomm as st"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE s.fk_stcomm = st.id"; $sql .= " AND s.fournisseur = 1"; $sql .= " AND s.rowid = p.fk_soc"; $sql .= " AND s.entity IN (".getEntity('societe').")"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} if (dol_strlen($stcomm)) { $sql .= " AND s.fk_stcomm=$stcomm"; @@ -90,8 +101,7 @@ $sql .= " ORDER BY $sortfield $sortorder "; $sql .= $db->plimit($limit, $offset); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); @@ -107,8 +117,7 @@ if ($result) print "</tr>\n"; $i = 0; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($result); print '<tr class="oddeven">'; diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index a8f7fa2cc42..d22006a52d0 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -9,7 +9,7 @@ * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro> * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com> * Copyright (C) 2016-2020 Alexandre Spangaro <aspangaro@open-dsi.fr> - * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr> * Copyright (C) 2019 Ferran Marcet <fmarcet@2byte.es> * * This program is free software; you can redistribute it and/or modify @@ -41,6 +41,7 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; if (!empty($conf->product->enabled)) { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; @@ -54,11 +55,15 @@ if (!empty($conf->projet->enabled)) { if (!empty($conf->variants->enabled)) { require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php'; } -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +} $langs->loadLangs(array('bills', 'compta', 'suppliers', 'companies', 'products', 'banks', 'admin')); -if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); +if (!empty($conf->incoterm->enabled)) { + $langs->load('incoterm'); +} $id = (GETPOST('facid', 'int') ? GETPOST('facid', 'int') : GETPOST('id', 'int')); $socid = GETPOST('socid', 'int'); @@ -86,17 +91,22 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Load object -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $ret = $object->fetch($id, $ref); - if ($ret < 0) dol_print_error($db, $object->error); + if ($ret < 0) { + dol_print_error($db, $object->error); + } $ret = $object->fetch_thirdparty(); - if ($ret < 0) dol_print_error($db, $object->error); + if ($ret < 0) { + dol_print_error($db, $object->error); + } } // Security check $socid = ''; -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $isdraft = (($object->statut == FactureFournisseur::STATUS_DRAFT) ? 1 : 0); $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture', 'fk_soc', 'rowid', $isdraft); @@ -124,14 +134,13 @@ $error = 0; $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)) -{ - if ($cancel) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -145,24 +154,23 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once // Link invoice to order - if (GETPOST('linkedOrder') && empty($cancel) && $id > 0) - { + if (GETPOST('linkedOrder') && empty($cancel) && $id > 0) { $object->fetch($id); $object->fetch_thirdparty(); $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder')); } // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) - { + if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) { $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid. - if (GETPOST('newsupplierref', 'alphanohtml')) $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml'); + if (GETPOST('newsupplierref', 'alphanohtml')) { + $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml'); + } $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int')); $result = $objectutil->createFromClone($user, $id); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit; } else { @@ -170,15 +178,14 @@ if (empty($reshook)) setEventMessages($objectutil->error, $objectutil->errors, 'errors'); $action = ''; } - } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) { + } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) { $idwarehouse = GETPOST('idwarehouse'); $object->fetch($id); $object->fetch_thirdparty(); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { $qualified_for_stock_change = $object->hasProductsOrServices(1); @@ -187,8 +194,7 @@ if (empty($reshook)) // Check parameters if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) { $langs->load("stocks"); - if (!$idwarehouse || $idwarehouse == -1) - { + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; @@ -201,12 +207,15 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } else { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -215,7 +224,9 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } } } @@ -225,25 +236,19 @@ if (empty($reshook)) $isErasable = $object->is_erasable(); - if (($usercandelete && $isErasable > 0) || ($usercancreate && $isErasable == 1)) - { + if (($usercandelete && $isErasable > 0) || ($usercancreate && $isErasable == 1)) { $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { header('Location: list.php?restore_lastsearch_values=1'); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // Remove a product line - elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) - { + } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) { + // Remove a product line $result = $object->deleteline($lineid); - if ($result > 0) - { + if ($result > 0) { // Define output language /*$outputlangs = $langs; $newlang = ''; @@ -267,11 +272,8 @@ if (empty($reshook)) /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */ $action = ''; } - } - - // Delete link of credit note to invoice - elseif ($action == 'unlinkdiscount' && $usercancreate) - { + } elseif ($action == 'unlinkdiscount' && $usercancreate) { + // Delete link of credit note to invoice $discount = new DiscountAbsolute($db); $result = $discount->fetch(GETPOST("discountid")); $discount->unlink_invoice(); @@ -331,8 +333,12 @@ if (empty($reshook)) if (!$error) { $old_date_echeance = $object->date_echeance; $new_date_echeance = $object->calculate_date_lim_reglement(); - if ($new_date_echeance > $old_date_echeance) $object->date_echeance = $new_date_echeance; - if ($object->date_echeance < $object->date) $object->date_echeance = $object->date; + if ($new_date_echeance > $old_date_echeance) { + $object->date_echeance = $new_date_echeance; + } + if ($object->date_echeance < $object->date) { + $object->date_echeance = $object->date; + } $result = $object->update($user); if ($result < 0) { $error++; @@ -345,83 +351,72 @@ if (empty($reshook)) } else { $db->commit(); } - } - - // Set incoterm - elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { + } elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) { + // Set incoterm $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); - } - - // payment mode - elseif ($action == 'setmode' && $usercancreate) - { + } elseif ($action == 'setmode' && $usercancreate) { + // payment mode $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', 'alpha'))); - } - - // bank account - elseif ($action == 'setbankaccount' && $usercancreate) { + } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + // Multicurrency rate + $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx', 'alpha')), GETPOST('calculation_mode', 'int')); + } elseif ($action == 'setbankaccount' && $usercancreate) { + // bank account $result = $object->setBankAccount(GETPOST('fk_account', 'int')); } - // transport mode - if ($action == 'settransportmode' && $user->rights->fournisseur->facture->creer) - { - $result = $object->setTransportMode(GETPOST('transport_mode_id', 'int')); - } - // Set label - elseif ($action == 'setlabel' && $usercancreate) - { + if ($action == 'settransportmode' && $user->rights->fournisseur->facture->creer) { + // transport mode + $result = $object->setTransportMode(GETPOST('transport_mode_id', 'int')); + } elseif ($action == 'setlabel' && $usercancreate) { + // Set label $object->fetch($id); $object->label = GETPOST('label'); $result = $object->update($user); - if ($result < 0) dol_print_error($db); + if ($result < 0) { + dol_print_error($db); + } } elseif ($action == 'setdatef' && $usercancreate) { $newdate = dol_mktime(0, 0, 0, $_POST['datefmonth'], $_POST['datefday'], $_POST['datefyear']); - if ($newdate > (dol_now() + (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE) ? 0 : $conf->global->INVOICE_MAX_OFFSET_IN_FUTURE))) - { - if (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)) setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings'); - else setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings'); + if ($newdate > (dol_now() + (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE) ? 0 : $conf->global->INVOICE_MAX_OFFSET_IN_FUTURE))) { + if (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)) { + setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings'); + } else { + setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings'); + } } $object->fetch($id); $object->date = $newdate; $date_echence_calc = $object->calculate_date_lim_reglement(); - if (!empty($object->date_echeance) && $object->date_echeance < $date_echence_calc) - { + if (!empty($object->date_echeance) && $object->date_echeance < $date_echence_calc) { $object->date_echeance = $date_echence_calc; } - if ($object->date_echeance && $object->date_echeance < $object->date) - { + if ($object->date_echeance && $object->date_echeance < $object->date) { $object->date_echeance = $object->date; } $result = $object->update($user); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + dol_print_error($db, $object->error); + } } elseif ($action == 'setdate_lim_reglement' && $usercancreate) { $object->fetch($id); $object->date_echeance = dol_mktime(12, 0, 0, $_POST['date_lim_reglementmonth'], $_POST['date_lim_reglementday'], $_POST['date_lim_reglementyear']); - if (!empty($object->date_echeance) && $object->date_echeance < $object->date) - { + if (!empty($object->date_echeance) && $object->date_echeance < $object->date) { $object->date_echeance = $object->date; setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings'); } $result = $object->update($user); - if ($result < 0) dol_print_error($db, $object->error); - } elseif ($action == "setabsolutediscount" && $usercancreate) - { + if ($result < 0) { + dol_print_error($db, $object->error); + } + } elseif ($action == "setabsolutediscount" && $usercancreate) { // POST[remise_id] or POST[remise_id_for_payment] // We use the credit to reduce amount of invoice @@ -437,23 +432,20 @@ if (empty($reshook)) } } // We use the credit to reduce remain to pay - if (!empty($_POST["remise_id_for_payment"])) - { + if (!empty($_POST["remise_id_for_payment"])) { require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discount = new DiscountAbsolute($db); $discount->fetch($_POST["remise_id_for_payment"]); //var_dump($object->getRemainToPay(0)); //var_dump($discount->amount_ttc);exit; - if (price2num($discount->amount_ttc) > price2num($object->getRemainToPay(0))) - { + if (price2num($discount->amount_ttc) > price2num($object->getRemainToPay(0))) { // TODO Split the discount in 2 automatically $error++; setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors'); } - if (!$error) - { + if (!$error) { $result = $discount->link_to_invoice(0, $id); if ($result < 0) { setEventMessages($discount->error, $discount->errors, 'errors'); @@ -461,12 +453,15 @@ if (empty($reshook)) } } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -474,12 +469,12 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } - } - // Convertir en reduc - elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) - { + } elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) { + // Convertir en reduc $object->fetch($id); $object->fetch_thirdparty(); //$object->fetch_lines(); // Already done into fetch @@ -489,10 +484,13 @@ if (empty($reshook)) $result = $discountcheck->fetch(0, 0, $object->id); $canconvert = 0; - if ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discountcheck->id)) $canconvert = 1; // we can convert deposit into discount if deposit is paid (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) - if (($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_STANDARD) && $object->paye == 0 && empty($discountcheck->id)) $canconvert = 1; // we can convert credit note into discount if credit note is not refunded completely and not already converted and amount of payment is 0 (see also the real condition used as the condition to show button converttoreduc) - if ($canconvert) - { + if ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discountcheck->id)) { + $canconvert = 1; // we can convert deposit into discount if deposit is paid (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) + } + if (($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_STANDARD) && $object->paye == 0 && empty($discountcheck->id)) { + $canconvert = 1; // we can convert credit note into discount if credit note is not refunded completely and not already converted and amount of payment is 0 (see also the real condition used as the condition to show button converttoreduc) + } + if ($canconvert) { $db->begin(); $amount_ht = $amount_tva = $amount_ttc = array(); @@ -500,10 +498,9 @@ if (empty($reshook)) // Loop on each vat rate $i = 0; - foreach ($object->lines as $line) - { - if ($line->product_type < 9 && $line->total_ht != 0) // Remove lines with product_type greater than or equal to 9 - { // no need to create discount if amount is null + foreach ($object->lines as $line) { + if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9 + // no need to create discount if amount is null $amount_ht[$line->tva_tx] += $line->total_ht; $amount_tva[$line->tva_tx] += $line->total_tva; $amount_ttc[$line->tva_tx] += $line->total_ttc; @@ -527,13 +524,13 @@ if (empty($reshook)) // Insert one discount by VAT rate category $discount = new DiscountAbsolute($db); - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { $discount->description = '(CREDIT_NOTE)'; - elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) + } elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) { $discount->description = '(DEPOSIT)'; - elseif ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) + } elseif ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) { $discount->description = '(EXCESS PAID)'; - else { + } else { setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors'); } $discount->discount_type = 1; // Supplier discount @@ -542,8 +539,7 @@ if (empty($reshook)) $error = 0; - if ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) - { + if ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) { // If we're on a standard invoice, we have to get excess paid to create a discount in TTC without VAT // Total payments @@ -555,7 +551,9 @@ if (empty($reshook)) $sql .= ' AND p.entity IN ('.getEntity('invoice').')'; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $res = $db->fetch_object($resql); $total_paiements = $res->total_paiements; @@ -571,43 +569,39 @@ if (empty($reshook)) while ($obj = $db->fetch_object($resql)) { $total_creditnote_and_deposit += $obj->amount_ttc; } - } else dol_print_error($db); + } else { + dol_print_error($db); + } $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $object->total_ttc; $discount->amount_tva = 0; $discount->tva_tx = 0; $result = $discount->create($user); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) - { - foreach ($amount_ht as $tva_tx => $xxx) - { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + foreach ($amount_ht as $tva_tx => $xxx) { $discount->amount_ht = abs($amount_ht[$tva_tx]); $discount->amount_tva = abs($amount_tva[$tva_tx]); $discount->amount_ttc = abs($amount_ttc[$tva_tx]); $discount->tva_tx = abs($tva_tx); $result = $discount->create($user); - if ($result < 0) - { + if ($result < 0) { $error++; break; } } } - if (empty($error)) - { + if (empty($error)) { if ($object->type != FactureFournisseur::TYPE_DEPOSIT) { // Classe facture $result = $object->setPaid($user); - if ($result >= 0) - { + if ($result >= 0) { $db->commit(); } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -621,15 +615,10 @@ if (empty($reshook)) $db->rollback(); } } - } - - - // Delete payment - elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercancreate) - { - $object->fetch($id); - if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) - { + } elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercancreate) { + // Delete payment + $object->fetch($id); + if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) { $paiementfourn = new PaiementFourn($db); $result = $paiementfourn->fetch(GETPOST('paiement_id')); if ($result > 0) { @@ -640,12 +629,11 @@ if (empty($reshook)) setEventMessages($paiementfourn->error, $paiementfourn->errors, 'errors'); } } - } - - // Create - elseif ($action == 'add' && $usercancreate) - { - if ($socid > 0) $object->socid = GETPOST('socid', 'int'); + } elseif ($action == 'add' && $usercancreate) { + // Create + if ($socid > 0) { + $object->socid = GETPOST('socid', 'int'); + } $db->begin(); @@ -653,14 +641,15 @@ 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++; + } $dateinvoice = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); $datedue = dol_mktime(12, 0, 0, GETPOST('echmonth', 'int'), GETPOST('echday', 'int'), GETPOST('echyear', 'int')); // Replacement invoice - if (GETPOST('type') == FactureFournisseur::TYPE_REPLACEMENT) - { + if (GETPOST('type') == FactureFournisseur::TYPE_REPLACEMENT) { if (empty($dateinvoice)) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors'); $action = 'create'; @@ -713,16 +702,13 @@ if (empty($reshook)) } // Credit note invoice - if (GETPOST('type') == FactureFournisseur::TYPE_CREDIT_NOTE) - { + if (GETPOST('type') == FactureFournisseur::TYPE_CREDIT_NOTE) { $sourceinvoice = GETPOST('fac_avoir', 'int'); - if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) - { + if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors'); } - if (GETPOST('socid', 'int') < 1) - { + if (GETPOST('socid', 'int') < 1) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors'); $action = 'create'; $error++; @@ -739,16 +725,14 @@ if (empty($reshook)) $action = 'create'; } - if (!GETPOST('ref_supplier')) - { + if (!GETPOST('ref_supplier')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplier')), null, 'errors'); $action = 'create'; $_GET['socid'] = $_POST['socid']; $error++; } - if (!$error) - { + if (!$error) { $tmpproject = GETPOST('projectid', 'int'); // Creation facture @@ -781,15 +765,12 @@ if (empty($reshook)) $error++; } - if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) - { + if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) { $facture_source = new FactureFournisseur($db); // fetch origin object - if ($facture_source->fetch($object->fk_facture_source) > 0) - { + if ($facture_source->fetch($object->fk_facture_source) > 0) { $fk_parent_line = 0; - foreach ($facture_source->lines as $line) - { + foreach ($facture_source->lines as $line) { // Reset fk_parent_line for no child products and special product if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { $fk_parent_line = 0; @@ -820,11 +801,9 @@ if (empty($reshook)) } } - if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) - { + if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) { $facture_source = new FactureFournisseur($db); // fetch origin object if not previously defined - if ($facture_source->fetch($object->fk_facture_source) > 0) - { + if ($facture_source->fetch($object->fk_facture_source) > 0) { $totalpaye = $facture_source->getSommePaiement(); $totalcreditnotes = $facture_source->getSumCreditNotesUsed(); $totaldeposits = $facture_source->getSumDepositsUsed(); @@ -837,10 +816,8 @@ if (empty($reshook)) } // Standard or deposit - if (GETPOST('type') == FactureFournisseur::TYPE_STANDARD || GETPOST('type') == FactureFournisseur::TYPE_DEPOSIT) - { - if (GETPOST('socid', 'int') < 1) - { + if (GETPOST('type') == FactureFournisseur::TYPE_STANDARD || GETPOST('type') == FactureFournisseur::TYPE_DEPOSIT) { + if (GETPOST('socid', 'int') < 1) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors'); $action = 'create'; $error++; @@ -857,16 +834,14 @@ if (empty($reshook)) $action = 'create'; } - if (!GETPOST('ref_supplier')) - { + if (!GETPOST('ref_supplier')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplier')), null, 'errors'); $action = 'create'; $_GET['socid'] = $_POST['socid']; $error++; } - if (!$error) - { + if (!$error) { $tmpproject = GETPOST('projectid', 'int'); // Creation invoice @@ -890,13 +865,14 @@ if (empty($reshook)) $object->transport_mode_id = GETPOST('transport_mode_id'); // Auto calculation of date due if not filled by user - if (empty($object->date_echeance)) $object->date_echeance = $object->calculate_date_lim_reglement(); + if (empty($object->date_echeance)) { + $object->date_echeance = $object->calculate_date_lim_reglement(); + } $object->fetch_thirdparty(); // If creation from another object of another module - if (!$error && GETPOST('origin', 'alpha') && GETPOST('originid')) - { + if (!$error && GETPOST('origin', 'alpha') && GETPOST('originid')) { // Parse element/subelement (ex: project_task) $element = $subelement = GETPOST('origin', 'alpha'); /*if (preg_match('/^([^_]+)_([^_]+)/i',$_POST['origin'],$regs)) @@ -918,8 +894,7 @@ if (empty($reshook)) if ($element == 'order_supplier') { $element = 'fourn'; $subelement = 'fournisseur.commande'; } - if ($element == 'project') - { + if ($element == 'project') { $element = 'projet'; } $object->origin = GETPOST('origin', 'alpha'); @@ -928,25 +903,23 @@ if (empty($reshook)) require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'; $classname = ucfirst($subelement); - if ($classname == 'Fournisseur.commande') $classname = 'CommandeFournisseur'; + if ($classname == 'Fournisseur.commande') { + $classname = 'CommandeFournisseur'; + } $objectsrc = new $classname($db); $objectsrc->fetch($originid); $objectsrc->fetch_thirdparty(); - if (!empty($object->origin) && !empty($object->origin_id)) - { + if (!empty($object->origin) && !empty($object->origin_id)) { $object->linkedObjectsIds[$object->origin] = $object->origin_id; } // Add also link with order if object is reception - if ($object->origin == 'reception') - { + if ($object->origin == 'reception') { $objectsrc->fetchObjectLinked(); - if (count($objectsrc->linkedObjectsIds['order_supplier']) > 0) - { - foreach ($objectsrc->linkedObjectsIds['order_supplier'] as $key => $value) - { + if (count($objectsrc->linkedObjectsIds['order_supplier']) > 0) { + foreach ($objectsrc->linkedObjectsIds['order_supplier'] as $key => $value) { $object->linkedObjectsIds['order_supplier'] = $value; } } @@ -955,26 +928,24 @@ if (empty($reshook)) $id = $object->create($user); // Add lines - if ($id > 0) - { + if ($id > 0) { require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'; $classname = ucfirst($subelement); - if ($classname == 'Fournisseur.commande') $classname = 'CommandeFournisseur'; + if ($classname == 'Fournisseur.commande') { + $classname = 'CommandeFournisseur'; + } $srcobject = new $classname($db); $result = $srcobject->fetch(GETPOST('originid', 'int')); - if ($result > 0) - { + if ($result > 0) { $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject, 'fetch_lines')) - { + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) { $srcobject->fetch_lines(); $lines = $srcobject->lines; } $num = count($lines); - for ($i = 0; $i < $num; $i++) // TODO handle subprice < 0 - { + for ($i = 0; $i < $num; $i++) { // TODO handle subprice < 0 $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); @@ -986,18 +957,25 @@ if (empty($reshook)) // Dates // TODO mutualiser $date_start = $lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) $date_start = $lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) $date_start = $lines[$i]->date_start; + if ($lines[$i]->date_debut_reel) { + $date_start = $lines[$i]->date_debut_reel; + } + if ($lines[$i]->date_start) { + $date_start = $lines[$i]->date_start; + } $date_end = $lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) $date_end = $lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) $date_end = $lines[$i]->date_end; + if ($lines[$i]->date_fin_reel) { + $date_end = $lines[$i]->date_fin_reel; + } + if ($lines[$i]->date_end) { + $date_end = $lines[$i]->date_end; + } // FIXME Missing special_code into addline and updateline methods $object->special_code = $lines[$i]->special_code; // FIXME If currency different from main currency, take multicurrency price - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { $pu = 0; $pu_currency = $lines[$i]->multicurrency_subprice; } else { @@ -1031,8 +1009,7 @@ if (empty($reshook)) $lines[$i]->special_code ); - if ($result < 0) - { + if ($result < 0) { $error++; break; } @@ -1046,19 +1023,16 @@ if (empty($reshook)) } else { $error++; } - } elseif (!$error) - { + } elseif (!$error) { $id = $object->create($user); - if ($id < 0) - { + if ($id < 0) { $error++; } } } } - if ($error) - { + if ($error) { $langs->load("errors"); $db->rollback(); @@ -1071,8 +1045,7 @@ if (empty($reshook)) if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) - { + if ($result < 0) { dol_print_error($db, $object->error, $object->errors); exit; } @@ -1081,11 +1054,8 @@ if (empty($reshook)) header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); exit; } - } - - // Edit line - elseif ($action == 'updateline' && $usercancreate) - { + } elseif ($action == 'updateline' && $usercancreate) { + // Edit line $db->begin(); $object->fetch($id); @@ -1093,22 +1063,18 @@ if (empty($reshook)) $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); - if (GETPOST('price_ht') != '' || GETPOST('multicurrency_subprice') != '') - { - $up = price2num(GETPOST('price_ht')); + if (GETPOST('price_ht') != '' || GETPOST('multicurrency_subprice') != '') { + $up = price2num(GETPOST('price_ht'), '', 2); $price_base_type = 'HT'; } else { - $up = price2num(GETPOST('price_ttc')); + $up = price2num(GETPOST('price_ttc'), '', 2); $price_base_type = 'TTC'; } - if (GETPOST('productid') > 0) - { + if (GETPOST('productid') > 0) { $productsupplier = new ProductFournisseur($db); - if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) - { - if (GETPOST('productid') > 0 && $productsupplier->get_buyprice(0, price2num(GETPOST('qty')), GETPOST('productid', 'int'), 'restricthtml', GETPOST('socid', 'int')) < 0) - { + if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) { + if (GETPOST('productid') > 0 && $productsupplier->get_buyprice(0, price2num(GETPOST('qty')), GETPOST('productid', 'int'), 'restricthtml', GETPOST('socid', 'int')) < 0) { setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings'); } } @@ -1116,7 +1082,9 @@ if (empty($reshook)) $prod = new Product($db); $prod->fetch(GETPOST('productid')); $label = $prod->description; - if (trim($_POST['product_desc']) != trim($label)) $label = $_POST['product_desc']; + if (trim($_POST['product_desc']) != trim($label)) { + $label = $_POST['product_desc']; + } $type = $prod->type; } else { @@ -1129,8 +1097,9 @@ if (empty($reshook)) // Define info_bits $info_bits = 0; - if (preg_match('/\*/', $tva_tx)) + if (preg_match('/\*/', $tva_tx)) { $info_bits |= 0x01; + } // Define vat_rate $tva_tx = str_replace('*', '', $tva_tx); @@ -1151,8 +1120,7 @@ if (empty($reshook)) } $result = $object->updateline(GETPOST('lineid', 'int'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, price2num(GETPOST('qty'), 'MS'), GETPOST('productid', 'int'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, GETPOST('units'), $pu_ht_devise, GETPOST('fourn_ref', 'alpha')); - if ($result >= 0) - { + if ($result >= 0) { unset($_POST['label']); unset($_POST['fourn_ref']); unset($_POST['date_starthour']); @@ -1177,8 +1145,7 @@ if (empty($reshook)) $db->begin(); $ret = $object->fetch($id); - if ($ret < 0) - { + if ($ret < 0) { dol_print_error($db, $object->error); exit; } @@ -1194,20 +1161,19 @@ if (empty($reshook)) $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); $prod_entry_mode = GETPOST('prod_entry_mode'); - if ($prod_entry_mode == 'free') - { + if ($prod_entry_mode == 'free') { $idprod = 0; - $price_ht = price2num(GETPOST('price_ht'), 'MU'); + $price_ht = price2num(GETPOST('price_ht'), 'MU', 2); $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); } else { $idprod = GETPOST('idprod', 'int'); - $price_ht = price2num(GETPOST('price_ht'), 'MU'); + $price_ht = price2num(GETPOST('price_ht'), 'MU', 2); $tva_tx = ''; } $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS'); $remise_percent = price2num(GETPOST('remise_percent'.$predef), 2); - $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU'); + $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2); // Extrafields $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -1220,28 +1186,23 @@ if (empty($reshook)) } } - if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) - { + if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) { setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && !GETPOST('idprodfournprice') && GETPOST('type') < 0) - { + if ($prod_entry_mode == 'free' && !GETPOST('idprodfournprice') && GETPOST('type') < 0) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') // Unit price can be 0 but not '' - { + if ($prod_entry_mode == 'free' && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') { // Unit price can be 0 but not '' setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && !GETPOST('dp_desc')) - { + if ($prod_entry_mode == 'free' && !GETPOST('dp_desc')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); $error++; } - if (!GETPOST('qty')) - { + if (!GETPOST('qty')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; } @@ -1260,55 +1221,57 @@ if (empty($reshook)) } } - if ($prod_entry_mode != 'free' && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' - { + if ($prod_entry_mode != 'free' && empty($error)) { // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' $productsupplier = new ProductFournisseur($db); $idprod = 0; - if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') { + $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + } $reg = array(); - if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) - { + if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) { $idprod = $reg[1]; $res = $productsupplier->fetch($idprod); // Load product from its id // Call to init some price properties of $productsupplier // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price - if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) - { + if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) { $fksoctosearch = 0; $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist - if ($productsupplier->fourn_socid != $socid) // The price we found is for another supplier, so we clear supplier price - { + if ($productsupplier->fourn_socid != $socid) { // The price we found is for another supplier, so we clear supplier price $productsupplier->ref_supplier = ''; } } else { $fksoctosearch = $object->thirdparty->id; $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist } - } elseif (GETPOST('idprodfournprice', 'alpha') > 0) - { + } elseif (GETPOST('idprodfournprice', 'alpha') > 0) { $qtytosearch = $qty; // Just to see if a price exists for the quantity. Not used to found vat. //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist $idprod = $productsupplier->get_buyprice(GETPOST('idprodfournprice', 'alpha'), $qtytosearch); $res = $productsupplier->fetch($idprod); } - if ($idprod > 0) - { + if ($idprod > 0) { $label = $productsupplier->label; // if we use supplier description of the products if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) { $desc = $productsupplier->desc_supplier; - } else $desc = $productsupplier->description; + } else { + $desc = $productsupplier->description; + } //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time if ($product_desc==$desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) { $product_desc=''; } - if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $desc = $product_desc; - if (!empty($product_desc) && trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) { + $desc = $product_desc; + } + if (!empty($product_desc) && trim($product_desc) != trim($desc)) { + $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + } $type = $productsupplier->type; if (GETPOST('price_ht') != '' || GETPOST('price_ht_devise') != '') { @@ -1330,11 +1293,15 @@ if (empty($reshook)) $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha')); $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha')); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); - if (empty($pu)) $pu = 0; // If pu is '' or null, we force to have a numeric value + if (empty($pu)) { + $pu = 0; // If pu is '' or null, we force to have a numeric value + } $result = $object->addline( $desc, @@ -1361,22 +1328,19 @@ if (empty($reshook)) '' ); } - if ($idprod == -99 || $idprod == 0) - { + if ($idprod == -99 || $idprod == 0) { // Product not selected $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors'); } - if ($idprod == -1) - { + if ($idprod == -1) { // Quantity too low $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); } - } elseif (empty($error)) // $price_ht is already set - { + } elseif (empty($error)) { // $price_ht is already set $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); $tva_tx = str_replace('*', '', $tva_tx); $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); @@ -1407,17 +1371,19 @@ if (empty($reshook)) } //print "xx".$tva_tx; exit; - if (!$error && $result > 0) - { + if (!$error && $result > 0) { $db->commit(); // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -1426,7 +1392,9 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } unset($_POST ['prod_entry_mode']); @@ -1470,12 +1438,8 @@ if (empty($reshook)) } elseif ($action == 'classin' && $usercancreate) { $object->fetch($id); $result = $object->setProject($projectid); - } - - - // Set invoice to draft status - elseif ($action == 'confirm_edit' && $confirm == 'yes' && $usercancreate) - { + } elseif ($action == 'confirm_edit' && $confirm == 'yes' && $usercancreate) { + // Set invoice to draft status $object->fetch($id); $totalpaye = $object->getSommePaiement(); @@ -1484,29 +1448,24 @@ if (empty($reshook)) // We check that lines of invoices are exported in accountancy $ventilExportCompta = $object->getVentilExportCompta(); - if (!$ventilExportCompta) - { + if (!$ventilExportCompta) { // On verifie si aucun paiement n'a ete effectue - if ($resteapayer == price2num($object->total_ttc, 'MT', 1) && $object->statut == FactureFournisseur::STATUS_VALIDATED) - { + if ($resteapayer == price2num($object->total_ttc, 'MT', 1) && $object->statut == FactureFournisseur::STATUS_VALIDATED) { $idwarehouse = GETPOST('idwarehouse'); $object->fetch_thirdparty(); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { $qualified_for_stock_change = $object->hasProductsOrServices(1); } // Check parameters - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) { $langs->load("stocks"); - if (!$idwarehouse || $idwarehouse == -1) - { + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; @@ -1516,12 +1475,15 @@ if (empty($reshook)) $object->setDraft($user, $idwarehouse); // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -1530,24 +1492,21 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } $action = ''; } } - } - - // Set invoice to validated/unpaid status - elseif ($action == 'reopen' && $usercancreate) - { + } elseif ($action == 'reopen' && $usercancreate) { + // Set invoice to validated/unpaid status $result = $object->fetch($id); if ($object->statut == FactureFournisseur::STATUS_CLOSED - || ($object->statut == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced')) - { + || ($object->statut == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced')) { $result = $object->setUnpaid($user); - if ($result > 0) - { + if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); exit; } else { @@ -1572,91 +1531,75 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; // Make calculation according to calculationrule - if ($action == 'calculate') - { + if ($action == 'calculate') { $calculationrule = GETPOST('calculationrule'); $object->fetch($id); $object->fetch_thirdparty(); $result = $object->update_price(0, (($calculationrule == 'totalofround') ? '0' : '1'), 0, $object->thirdparty); - if ($result <= 0) - { + if ($result <= 0) { dol_print_error($db, $result); exit; } } - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $object->insertExtraFields('BILL_SUPPLIER_MODIFY'); - if ($result < 0) - { + if ($result < 0) { $error++; } } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) - { - if ($action == 'addcontact') - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) { + if ($action == 'addcontact') { $result = $object->fetch($id); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // bascule du statut d'un contact - elseif ($action == 'swapstatut') - { - if ($object->fetch($id)) - { + } 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($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -1675,7 +1618,9 @@ $form = new Form($db); $formfile = new FormFile($db); $bankaccountstatic = new Account($db); $paymentstatic = new PaiementFourn($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $now = dol_now(); @@ -1684,8 +1629,7 @@ $helpurl = "EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Mód llxHeader('', $title, $helpurl); // Mode creation -if ($action == 'create') -{ +if ($action == 'create') { $facturestatic = new FactureFournisseur($db); print load_fiche_titre($langs->trans('NewBill'), '', 'supplier_invoice'); @@ -1698,7 +1642,9 @@ if ($action == 'create') if (GETPOST('socid') > 0) { $societe = new Societe($db); $societe->fetch(GETPOST('socid', 'int')); - if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) $currency_code = $societe->multicurrency_code; + if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) { + $currency_code = $societe->multicurrency_code; + } } if (!empty($origin) && !empty($originid)) { @@ -1726,7 +1672,9 @@ if ($action == 'create') require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'; $classname = ucfirst($subelement); - if ($classname == 'Fournisseur.commande') $classname = 'CommandeFournisseur'; + if ($classname == 'Fournisseur.commande') { + $classname = 'CommandeFournisseur'; + } $objectsrc = new $classname($db); $objectsrc->fetch($originid); $objectsrc->fetch_thirdparty(); @@ -1743,10 +1691,13 @@ if ($action == 'create') $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : ''; $transport_mode_id = (!empty($objectsrc->transport_mode_id) ? $objectsrc->transport_mode_id : (!empty($soc->transport_mode_id) ? $soc->transport_mode_id : 0)); - if (!empty($conf->multicurrency->enabled)) - { - if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code; - if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; + if (!empty($conf->multicurrency->enabled)) { + if (!empty($objectsrc->multicurrency_code)) { + $currency_code = $objectsrc->multicurrency_code; + } + if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) { + $currency_tx = $objectsrc->multicurrency_tx; + } } $datetmp = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); @@ -1767,7 +1718,9 @@ if ($action == 'create') $datetmp = dol_mktime(12, 0, 0, $_POST['echmonth'], $_POST['echday'], $_POST['echyear']); $datedue = ($datetmp == '' ?-1 : $datetmp); - if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; + if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) { + $currency_code = $soc->multicurrency_code; + } } // when payment condition is empty (means not override by payment condition form a other object, like third-party), try to use default value @@ -1786,10 +1739,14 @@ if ($action == 'create') print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; - if ($societe->id > 0) print '<input type="hidden" name="socid" value="'.$societe->id.'">'."\n"; + if ($societe->id > 0) { + print '<input type="hidden" name="socid" value="'.$societe->id.'">'."\n"; + } print '<input type="hidden" name="origin" value="'.$origin.'">'; print '<input type="hidden" name="originid" value="'.$originid.'">'; - if (!empty($currency_tx)) print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">'; + if (!empty($currency_tx)) { + print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">'; + } print dol_get_fiche_head(); @@ -1802,16 +1759,14 @@ if ($action == 'create') print '<tr><td class="fieldrequired">'.$langs->trans('Supplier').'</td>'; print '<td>'; - if ($societe->id > 0) - { + if ($societe->id > 0) { $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); print $societe->getNomUrl(1); print '<input type="hidden" name="socid" value="'.$societe->id.'">'; } else { print img_picto('', 'company').$form->select_company($societe->id, 'socid', 's.fournisseur=1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); // reload page to retrieve supplier informations - if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) - { + if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) { print '<script type="text/javascript"> $(document).ready(function() { $("#socid").change(function() { @@ -1828,7 +1783,9 @@ if ($action == 'create') // Ref supplier print '<tr><td class="fieldrequired">'.$langs->trans('RefSupplier').'</td><td><input name="ref_supplier" value="'.(isset($_POST['ref_supplier']) ? $_POST['ref_supplier'] : $objectsrc->ref_supplier).'" type="text"'; - if ($societe->id > 0) print ' autofocus'; + if ($societe->id > 0) { + print ' autofocus'; + } print '></td>'; print '</tr>'; @@ -1876,7 +1833,7 @@ if ($action == 'create') print '</div></div>'; } } - */ + */ /* Not yet supported for supplier if ($societe->id > 0) @@ -1942,24 +1899,19 @@ if ($action == 'create') } */ - if (empty($origin)) - { - if ($societe->id > 0) - { + if (empty($origin)) { + if ($societe->id > 0) { // Credit note - if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) - { + if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) { // Show link for credit note $facids = $facturestatic->list_qualified_avoir_supplier_invoices($societe->id); - if ($facids < 0) - { + if ($facids < 0) { dol_print_error($db, $facturestatic); exit; } $optionsav = ""; $newinvoice_static = new FactureFournisseur($db); - foreach ($facids as $key => $valarray) - { + foreach ($facids as $key => $valarray) { $newinvoice_static->id = $key; $newinvoice_static->ref = $valarray ['ref']; $newinvoice_static->statut = $valarray ['status']; @@ -1967,8 +1919,9 @@ if ($action == 'create') $newinvoice_static->paye = $valarray ['paye']; $optionsav .= '<option value="'.$key.'"'; - if ($key == GETPOST('fac_avoir', 'int')) + if ($key == GETPOST('fac_avoir', 'int')) { $optionsav .= ' selected'; + } $optionsav .= '>'; $optionsav .= $newinvoice_static->ref; $optionsav .= ' ('.$newinvoice_static->getLibStatut(1, $valarray ['paymentornot']).')'; @@ -1977,7 +1930,9 @@ if ($action == 'create') print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">'; $tmp = '<input type="radio" id="radio_creditnote" name="type" value="2"'.(GETPOST('type') == 2 ? ' checked' : ''); - if (!$optionsav) $tmp .= ' disabled'; + if (!$optionsav) { + $tmp .= ' disabled'; + } $tmp .= '> '; // Show credit note options only if we checked credit note print '<script type="text/javascript" language="javascript"> @@ -1997,8 +1952,9 @@ if ($action == 'create') $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk").' '; // $text.='<input type="text" value="">'; $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"'; - if (!$optionsav) + if (!$optionsav) { $text .= ' disabled'; + } $text .= '>'; if ($optionsav) { $text .= '<option value="-1"></option>'; @@ -2034,8 +1990,7 @@ if ($action == 'create') print '</td></tr>'; - if ($societe->id > 0) - { + if ($societe->id > 0) { // Discounts for third party print '<tr><td>'.$langs->trans('Discounts').'</td><td>'; @@ -2071,16 +2026,14 @@ if ($action == 'create') print '</td></tr>'; // Bank Account - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print '<tr><td>'.$langs->trans('BankAccount').'</td><td>'; print img_picto('', 'bank_account').$form->select_comptes((GETPOSTISSET('fk_account') ?GETPOST('fk_account', 'alpha') : $fk_account), 'fk_account', 0, '', 1, '', 0, '', 1); print '</td></tr>'; } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); $langs->load('projects'); @@ -2090,8 +2043,7 @@ if ($action == 'create') } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '<tr>'; print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), $objectsrc->label_incoterms, 1).'</label></td>'; print '<td colspan="3" class="maxwidthonsmartphone">'; @@ -2100,8 +2052,7 @@ if ($action == 'create') } // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<tr>'; print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>'; print '<td class="maxwidthonsmartphone">'; @@ -2110,8 +2061,7 @@ if ($action == 'create') } // Intracomm report - if (!empty($conf->intracommreport->enabled)) - { + if (!empty($conf->intracommreport->enabled)) { $langs->loadLangs(array("intracommreport")); print '<tr><td>'.$langs->trans('IntracommReportTransportMode').'</td><td>'; $form->selectTransportMode(isset($_POST['transport_mode_id']) ? $_POST['transport_mode_id'] : $transport_mode_id, 'transport_mode_id'); @@ -2136,13 +2086,11 @@ if ($action == 'create') // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>'; print '</tr>'; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } - if (is_object($objectsrc)) - { + if (is_object($objectsrc)) { print "\n<!-- ".$classname." info -->"; print "\n"; print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n"; @@ -2163,12 +2111,10 @@ if ($action == 'create') $invoice_supplier = $objectsrc->linkedObjects['invoice_supplier']; // count function need a array as argument (Note: the array must implement Countable too) - if (is_array($invoice_supplier)) - { + if (is_array($invoice_supplier)) { $cntinvoice = count($invoice_supplier); - if ($cntinvoice >= 1) - { + if ($cntinvoice >= 1) { setEventMessages('WarningBillExist', null, 'warnings'); echo ' ('.$langs->trans('LatestRelatedBill').end($invoice_supplier)->getNomUrl(1).')'; } @@ -2177,19 +2123,16 @@ if ($action == 'create') print '</td></tr>'; print '<tr><td>'.$langs->trans('AmountHT').'</td><td>'.price($objectsrc->total_ht).'</td></tr>'; print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($objectsrc->total_tva)."</td></tr>"; - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) //Localtax1 - { + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { //Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1)."</td></tr>"; } - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) //Localtax2 - { + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { //Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2)."</td></tr>"; } print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($objectsrc->total_ttc)."</td></tr>"; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht).'</td></tr>'; print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva)."</td></tr>"; print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc)."</td></tr>"; @@ -2240,11 +2183,15 @@ if ($action == 'create') $object->fetch($id, $ref); $result = $object->fetch_thirdparty(); - if ($result < 0) dol_print_error($db); + if ($result < 0) { + dol_print_error($db); + } $societe = new Fournisseur($db); $result = $societe->fetch($object->socid); - if ($result < 0) dol_print_error($db); + if ($result < 0) { + dol_print_error($db); + } $totalpaye = $object->getSommePaiement(); $totalcreditnotes = $object->getSumCreditNotesUsed(); @@ -2258,8 +2205,7 @@ if ($action == 'create') // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT); $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); - if ($object->paye) - { + if ($object->paye) { $resteapayer = 0; } $resteapayeraffiche = $resteapayer; @@ -2278,8 +2224,8 @@ if ($action == 'create') $absolute_creditnote = price2num($absolute_creditnote, 'MT'); /* - * View card - */ + * View card + */ $head = facturefourn_prepare_head($object); $titre = $langs->trans('SupplierInvoice'); @@ -2289,17 +2235,20 @@ if ($action == 'create') // Confirmation de la conversion de l'avoir en reduc if ($action == 'converttoreduc') { - if ($object->type == FactureFournisseur::TYPE_STANDARD) $type_fac = 'ExcessPaid'; - elseif ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $type_fac = 'CreditNote'; - elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) $type_fac = 'Deposit'; + if ($object->type == FactureFournisseur::TYPE_STANDARD) { + $type_fac = 'ExcessPaid'; + } elseif ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + $type_fac = 'CreditNote'; + } elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) { + $type_fac = 'Deposit'; + } $text = $langs->trans('ConfirmConvertToReducSupplier', strtolower($langs->transnoentities($type_fac))); $text .= '<br>'.$langs->trans('ConfirmConvertToReducSupplier2'); $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2); } // Clone confirmation - if ($action == 'clone') - { + if ($action == 'clone') { // Create an array for form $formquestion = array( array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier), @@ -2310,8 +2259,7 @@ if ($action == 'create') } // Confirmation of validation - if ($action == 'valid') - { + if ($action == 'valid') { // We check if number is temporary number if (preg_match('/^[\(]?PROV/i', $object->ref) || empty($object->ref)) { // empty should not happened, but when it occurs, the test save life @@ -2341,8 +2289,7 @@ if ($action == 'create') $qualified_for_stock_change = $object->hasProductsOrServices(1); } - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) { $langs->load("stocks"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); @@ -2365,19 +2312,16 @@ if ($action == 'create') } // Confirmation edit (back to draft) - if ($action == 'edit') - { + if ($action == 'edit') { $formquestion = array(); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { $qualified_for_stock_change = $object->hasProductsOrServices(1); } - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) { $langs->load("stocks"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); @@ -2398,34 +2342,32 @@ if ($action == 'create') } // Confirmation set paid - if ($action == 'paid') - { + if ($action == 'paid') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', 0, 1); } // Confirmation de la suppression de la facture fournisseur - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', '', 0, 1); } - if ($action == 'deletepayment') - { + if ($action == 'deletepayment') { $payment_id = GETPOST('paiement_id'); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 0, 1); } - // Confirmation to delete line - if ($action == 'ask_deleteline') - { + // Confirmation to delete line + if ($action == 'ask_deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1); } - if (!$formconfirm) - { + if (!$formconfirm) { $parameters = array('formConfirm' => $formconfirm, 'lineid'=>$lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } } // Print form confirm @@ -2441,14 +2383,14 @@ if ($action == 'create') $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($usercancreate) - { + if ($usercancreate) { if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; } @@ -2492,36 +2434,34 @@ if ($action == 'create') print '<span class="badgeneutral">'; print $object->getLibType(); print '</span>'; - if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) - { + if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) { $facreplaced = new FactureFournisseur($db); $facreplaced->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; } - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) - { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { $facusing = new FactureFournisseur($db); $facusing->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; } $facidavoir = $object->getListIdAvoirFromInvoice(); - if (count($facidavoir) > 0) - { + if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); $i = 0; - foreach ($facidavoir as $id) - { - if ($i == 0) print ' '; - else print ','; + foreach ($facidavoir as $id) { + if ($i == 0) { + print ' '; + } else { + print ','; + } $facavoir = new FactureFournisseur($db); $facavoir->fetch($id); print $facavoir->getNomUrl(1); } print ')'; } - if (isset($facidnext) && $facidnext > 0) - { + if (isset($facidnext) && $facidnext > 0) { $facthatreplace = new FactureFournisseur($db); $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; @@ -2530,7 +2470,12 @@ if ($action == 'create') $discount = new DiscountAbsolute($db); $result = $discount->fetch(0, 0, $object->id); if ($result > 0) { - print ' '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(1), $discount->getNomUrl(1, 'discount')).'<br>'; + print ' <span class="opacitymediumbycolor paddingleft">'; + $s = $langs->trans("CreditNoteConvertedIntoDiscount", '{s1}', '{s2}'); + $s = str_replace('{s1}', $object->getLibType(1), $s); + $s = str_replace('{s2}', $discount->getNomUrl(1, 'discount'), $s); + print $s; + print '</span><br>'; } } print '</td></tr>'; @@ -2571,8 +2516,7 @@ if ($action == 'create') } print '</tr></table>'; print '</td><td colspan="2">'; - if ($action == 'editconditions') - { + if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id'); } else { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none'); @@ -2599,8 +2543,7 @@ if ($action == 'create') } print '</tr></table>'; print '</td><td colspan="2">'; - if ($action == 'editmode') - { + if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'DBIT', 1, 1); } else { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none'); @@ -2608,16 +2551,16 @@ if ($action == 'create') print '</td></tr>'; // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print '<tr>'; print '<td>'; print '<table class="nobordernopadding" width="100%"><tr><td>'; print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0); print '</td>'; - if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) + if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencycode&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td colspan="3">'; if ($action == 'editmulticurrencycode') { @@ -2628,15 +2571,15 @@ if ($action == 'create') print '</td></tr>'; // Multicurrency rate - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { print '<tr>'; print '<td>'; print '<table class="nobordernopadding" width="100%"><tr><td>'; print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0); print '</td>'; - if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) + if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencyrate&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td colspan="3">'; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { @@ -2657,14 +2600,14 @@ if ($action == 'create') } // Bank Account - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print '<tr><td class="nowrap">'; print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">'; print $langs->trans('BankAccount'); print '<td>'; - if ($action != 'editbankaccount' && $usercancreate) + if ($action != 'editbankaccount' && $usercancreate) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td colspan="3">'; if ($action == 'editbankaccount') { @@ -2677,19 +2620,20 @@ if ($action == 'create') } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '<tr><td>'; print '<table width="100%" class="nobordernopadding"><tr><td>'; print $langs->trans('IncotermLabel'); print '<td><td class="right">'; - if ($usercancreate) print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id.'&action=editincoterm">'.img_edit().'</a>'; - else print '&nbsp;'; + if ($usercancreate) { + print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id.'&action=editincoterm">'.img_edit().'</a>'; + } else { + print '&nbsp;'; + } print '</td></tr></table>'; print '</td>'; print '<td colspan="3">'; - if ($action != 'editincoterm') - { + if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1); } else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); @@ -2711,11 +2655,9 @@ if ($action == 'create') print '</td>'; print '<td>'; - if ($action == 'editmode') - { + if ($action == 'editmode') { $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, $object->transport_mode_id, 'transport_mode_id', 1, 1); - } - else { + } else { $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, $object->transport_mode_id, 'none'); } print '</td></tr>'; @@ -2734,8 +2676,7 @@ if ($action == 'create') print '<table class="border tableforfield centpercent">'; - if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) - { + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { // Multicurrency Amount HT print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>'; print '<td class="nowrap">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>'; @@ -2755,10 +2696,16 @@ if ($action == 'create') // Amount print '<tr><td class="titlefield">'.$langs->trans('AmountHT').'</td><td>'.price($object->total_ht, 1, $langs, 0, -1, -1, $conf->currency).'</td></tr>'; print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($object->total_tva, 1, $langs, 0, -1, -1, $conf->currency).'<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; '; - if (GETPOST('calculationrule')) $calculationrule = GETPOST('calculationrule', 'alpha'); - else $calculationrule = (empty($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND) ? 'totalofround' : 'roundoftotal'); - if ($calculationrule == 'totalofround') $calculationrulenum = 1; - else $calculationrulenum = 2; + if (GETPOST('calculationrule')) { + $calculationrule = GETPOST('calculationrule', 'alpha'); + } else { + $calculationrule = (empty($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND) ? 'totalofround' : 'roundoftotal'); + } + if ($calculationrule == 'totalofround') { + $calculationrulenum = 1; + } else { + $calculationrulenum = 2; + } // Show link for "recalculate" if ($object->getVentilExportCompta() == 0) { $s = $langs->trans("ReCalculate").' '; @@ -2771,14 +2718,12 @@ if ($action == 'create') // Amount Local Taxes //TODO: Place into a function to control showing by country or study better option - if ($societe->localtax1_assuj == "1") //Localtax1 - { + if ($societe->localtax1_assuj == "1") { //Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $societe->country_code).'</td>'; print '<td>'.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; } - if ($societe->localtax2_assuj == "1") //Localtax2 - { + if ($societe->localtax2_assuj == "1") { //Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $societe->country_code).'</td>'; print '<td>'.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; @@ -2788,23 +2733,37 @@ if ($action == 'create') print '</table>'; /* - * List of payments - */ + * List of payments + */ $totalpaye = 0; $sign = 1; - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $sign = - 1; + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + $sign = - 1; + } $nbrows = 9; $nbcols = 3; - if (!empty($conf->projet->enabled)) $nbrows++; - if (!empty($conf->banque->enabled)) { $nbrows++; $nbcols++; } - if (!empty($conf->incoterm->enabled)) $nbrows++; - if (!empty($conf->multicurrency->enabled)) $nbrows += 5; + if (!empty($conf->projet->enabled)) { + $nbrows++; + } + if (!empty($conf->banque->enabled)) { + $nbrows++; $nbcols++; + } + if (!empty($conf->incoterm->enabled)) { + $nbrows++; + } + if (!empty($conf->multicurrency->enabled)) { + $nbrows += 5; + } // Local taxes - if ($societe->localtax1_assuj == "1") $nbrows++; - if ($societe->localtax2_assuj == "1") $nbrows++; + if ($societe->localtax1_assuj == "1") { + $nbrows++; + } + if ($societe->localtax2_assuj == "1") { + $nbrows++; + } $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,'; $sql .= ' c.id as paiement_type,'; @@ -2819,8 +2778,7 @@ if ($action == 'create') $sql .= ' ORDER BY p.datep, p.tms'; $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $i = 0; @@ -2830,15 +2788,15 @@ if ($action == 'create') print '<td class="liste_titre">'.($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>'; print '<td>'.$langs->trans('Date').'</td>'; print '<td>'.$langs->trans('Type').'</td>'; - if (!empty($conf->banque->enabled)) print '<td class="right">'.$langs->trans('BankAccount').'</td>'; + if (!empty($conf->banque->enabled)) { + print '<td class="right">'.$langs->trans('BankAccount').'</td>'; + } print '<td class="right">'.$langs->trans('Amount').'</td>'; print '<td width="18">&nbsp;</td>'; print '</tr>'; - if ($num > 0) - { - while ($i < $num) - { + if ($num > 0) { + while ($i < $num) { $objp = $db->fetch_object($result); $paymentstatic->id = $objp->rowid; @@ -2855,8 +2813,7 @@ if ($action == 'create') print '<td>'; print $form->form_modes_reglement(null, $objp->paiement_type, 'none').' '.$objp->num_payment; print '</td>'; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { $bankaccountstatic->id = $objp->baid; $bankaccountstatic->ref = $objp->baref; $bankaccountstatic->label = $objp->baref; @@ -2871,13 +2828,14 @@ if ($action == 'create') } print '<td class="right">'; - if ($objp->baid > 0) print $bankaccountstatic->getNomUrl(1, 'transactions'); + if ($objp->baid > 0) { + print $bankaccountstatic->getNomUrl(1, 'transactions'); + } print '</td>'; } print '<td class="right">'.price($sign * $objp->amount).'</td>'; print '<td class="center">'; - if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) - { + if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) { print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deletepayment&token='.newToken().'&paiement_id='.$objp->rowid.'">'; print img_delete(); print '</a>'; @@ -2892,16 +2850,16 @@ if ($action == 'create') } /* - if ($object->paye == 0) - { - print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('AlreadyPaid').' :</td><td class="right">'.price($totalpaye).'</td><td></td></tr>'; - print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("Billed").' :</td><td class="right">'.price($object->total_ttc).'</td><td></td></tr>'; + if ($object->paye == 0) + { + print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('AlreadyPaid').' :</td><td class="right">'.price($totalpaye).'</td><td></td></tr>'; + print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("Billed").' :</td><td class="right">'.price($object->total_ttc).'</td><td></td></tr>'; - $resteapayer = $object->total_ttc - $totalpaye; + $resteapayer = $object->total_ttc - $totalpaye; - print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('RemainderToPay').' :</td>'; - print '<td class="right'.($resteapayer?' amountremaintopay':'').'">'.price($resteapayer).'</td><td></td></tr>'; - } + print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('RemainderToPay').' :</td>'; + print '<td class="right'.($resteapayer?' amountremaintopay':'').'">'.price($resteapayer).'</td><td></td></tr>'; + } */ $db->free($result); @@ -2909,14 +2867,15 @@ if ($action == 'create') dol_print_error($db); } - if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) - { + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) { // Total already paid print '<tr><td colspan="'.$nbcols.'" class="right">'; print '<span class="opacitymedium">'; - if ($object->type != FactureFournisseur::TYPE_DEPOSIT) + if ($object->type != FactureFournisseur::TYPE_DEPOSIT) { print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits'); - else print $langs->trans('AlreadyPaid'); + } else { + print $langs->trans('AlreadyPaid'); + } print '</span>'; print '</td><td class="right"'.(($totalpaye > 0) ? ' class="amountalreadypaid"' : '').'>'.price($totalpaye).'</td><td>&nbsp;</td></tr>'; @@ -2943,10 +2902,12 @@ if ($action == 'create') $obj = $db->fetch_object($resql); $invoice->fetch($obj->fk_invoice_supplier_source); print '<tr><td colspan="'.$nbcols.'" class="right">'; - if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) { print $langs->trans("CreditNote").' '; - if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + } + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) { print $langs->trans("Deposit").' '; + } print $invoice->getNomUrl(0); print ' :</td>'; print '<td class="right">'.price($obj->amount_ttc).'</td>'; @@ -2954,10 +2915,12 @@ if ($action == 'create') print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&discountid='.$obj->rowid.'">'.img_delete().'</a>'; print '</td></tr>'; $i++; - if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) { $creditnoteamount += $obj->amount_ttc; - if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + } + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) { $depositamount += $obj->amount_ttc; + } } } else { dol_print_error($db); @@ -2997,8 +2960,9 @@ if ($action == 'create') if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'abandon') { print '<tr><td colspan="'.$nbcols.'" class="right nowrap">'; $text = $langs->trans("HelpAbandonOther"); - if ($object->close_note) + if ($object->close_note) { $text .= '<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note; + } print '<span class="opacitymedium">'; print $form->textwithpicto($langs->trans("Abandoned"), $text, - 1); print '</span>'; @@ -3017,9 +2981,11 @@ if ($action == 'create') // Remainder to pay print '<tr><td colspan="'.$nbcols.'" class="right">'; print '<span class="opacitymedium">'; - if ($resteapayeraffiche >= 0) + if ($resteapayeraffiche >= 0) { print $langs->trans('RemainderToPay'); - else print $langs->trans('ExcessPaid'); + } else { + print $langs->trans('ExcessPaid'); + } print '</span>'; print '</td>'; print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($resteapayeraffiche).'</td>'; @@ -3039,9 +3005,11 @@ if ($action == 'create') // Remainder to pay back print '<tr><td colspan="'.$nbcols.'" class="right">'; print '<span class="opacitymedium">'; - if ($resteapayeraffiche <= 0) + if ($resteapayeraffiche <= 0) { print $langs->trans('RemainderToPayBack'); - else print $langs->trans('ExcessPaid'); + } else { + print $langs->trans('ExcessPaid'); + } print '</td>'; print '</span>'; print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($sign * $resteapayeraffiche).'</td>'; @@ -3062,15 +3030,13 @@ if ($action == 'create') print '<div class="clearboth"></div><br>'; - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $blocname = 'contacts'; $title = $langs->trans('ContactsAddresses'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } - if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $colwidth = 20; $blocname = 'notes'; $title = $langs->trans('Notes'); @@ -3079,8 +3045,8 @@ if ($action == 'create') /* - * Lines - */ + * Lines + */ print '<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#addline' : '#line_'.GETPOST('lineid')).'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="'.(($action != 'editline') ? 'addline' : 'updateline').'">'; @@ -3099,7 +3065,9 @@ if ($action == 'create') $forceall = 1; $dateSelector = 0; $inputalsopricewithtax = 1; $senderissupplier = 2; // $senderissupplier=2 is same than 1 but disable test on minimum qty and disable autofill qty with minimum. //if (! empty($conf->global->SUPPLIER_INVOICE_WITH_NOPRICEDEFINED)) $senderissupplier=2; - if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) $senderissupplier = 1; + if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) { + $senderissupplier = 1; + } // Show object lines if (!empty($object->lines)) { @@ -3109,10 +3077,8 @@ if ($action == 'create') $num = count($object->lines); // Form to add new line - if ($object->statut == FactureFournisseur::STATUS_DRAFT && $usercancreate) - { - if ($action != 'editline') - { + if ($object->statut == FactureFournisseur::STATUS_DRAFT && $usercancreate) { + if ($action != 'editline') { // Add free products/services $object->formAddObjectLine(1, $societe, $mysoc); @@ -3128,27 +3094,23 @@ if ($action == 'create') print dol_get_fiche_end(); - if ($action != 'presend') - { + if ($action != 'presend') { /* - * Buttons actions - */ + * Buttons actions + */ print '<div class="tabsAction">'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { // Modify a validated invoice with no payments - if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $usercancreate) - { + if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $usercancreate) { // We check if lines of invoice are not already transfered into accountancy $ventilExportCompta = $object->getVentilExportCompta(); // Should be 0 since the sum of payments are zero. But we keep the protection. - if ($ventilExportCompta == 0) - { + if ($ventilExportCompta == 0) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=edit">'.$langs->trans('Modify').'</a></div>'; } else { print '<div class="inline-block divButAction"><span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Modify').'</span></div>'; @@ -3158,13 +3120,11 @@ if ($action == 'create') $discount = new DiscountAbsolute($db); $result = $discount->fetch(0, 0, $object->id); - // Reopen a standard paid invoice + // Reopen a standard paid invoice if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && empty($discount->id))) - && ($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED)) // A paid invoice (partially or completely) - { - if (!$facidnext && $object->close_code != 'replaced' && $usercancreate) // Not replaced by another invoice - { + && ($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED)) { // A paid invoice (partially or completely) + if (!$facidnext && $object->close_code != 'replaced' && $usercancreate) { // Not replaced by another invoice print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans('ReOpen').'</a></div>'; } else { if ($usercancreate) { @@ -3177,24 +3137,22 @@ if ($action == 'create') // Send by mail if (empty($user->socid)) { - if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED)) - { - if ($usercansend) - { + if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED)) { + if ($usercansend) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>'; - } else print '<div class="inline-block divButAction"><span class="butActionRefused classfortooltip">'.$langs->trans('SendMail').'</a></div>'; + } else { + print '<div class="inline-block divButAction"><span class="butActionRefused classfortooltip">'.$langs->trans('SendMail').'</a></div>'; + } } } // Make payments - if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) - { + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) { print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create'.($object->fk_account > 0 ? '&amp;accountid='.$object->fk_account : '').'">'.$langs->trans('DoPayment').'</a></div>'; // must use facid because id is for payment id not invoice } // Classify paid - if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) - { + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=paid"'; print '>'.$langs->trans('ClassifyPaid').'</a></div>'; @@ -3204,10 +3162,8 @@ if ($action == 'create') // Reverse back money or convert to reduction if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD) { // For credit note only - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) - { - if ($resteapayer == 0) - { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) { + if ($resteapayer == 0) { print '<div class="inline-block divButAction"><span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span></div>'; } else { print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create&amp;accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a></div>'; @@ -3215,8 +3171,7 @@ if ($action == 'create') } // For standard invoice with excess paid - if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $usercancreate && empty($discount->id)) - { + if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $usercancreate && empty($discount->id)) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertExcessPaidToReduc').'</a></div>'; } // For credit note @@ -3226,19 +3181,15 @@ if ($action == 'create') print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc" title="'.dol_escape_htmltag($langs->trans("ConfirmConvertToReducSupplier2")).'">'.$langs->trans('ConvertToReduc').'</a></div>'; } // For deposit invoice - if ($object->type == FactureFournisseur::TYPE_DEPOSIT && $object->paye == 1 && $resteapayer == 0 && $usercancreate && empty($discount->id)) - { + if ($object->type == FactureFournisseur::TYPE_DEPOSIT && $object->paye == 1 && $resteapayer == 0 && $usercancreate && empty($discount->id)) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a></div>'; } } // Validate - if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) - { - if (count($object->lines)) - { - if ($usercanvalidate) - { + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) { + if (count($object->lines)) { + if ($usercanvalidate) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid"'; print '>'.$langs->trans('Validate').'</a></div>'; } else { @@ -3255,24 +3206,20 @@ if ($action == 'create') }*/ // Clone - if ($action != 'edit' && $usercancreate) - { + if ($action != 'edit' && $usercancreate) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=clone&amp;socid='.$object->socid.'">'.$langs->trans('ToClone').'</a></div>'; } // Create a credit note - if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut > 0 && $usercancreate) - { - if (!$objectidnext) - { + if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut > 0 && $usercancreate) { + if (!$objectidnext) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->socid.'&amp;fac_avoir='.$object->id.'&amp;action=create&amp;type=2'.($object->fk_project > 0 ? '&amp;projectid='.$object->fk_project : '').'">'.$langs->trans("CreateCreditNote").'</a></div>'; } } // Delete $isErasable = $object->is_erasable(); - if ($action != 'confirm_edit' && ($user->rights->fournisseur->facture->supprimer || ($usercancreate && $isErasable == 1))) // isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions) - { + if ($action != 'confirm_edit' && ($user->rights->fournisseur->facture->supprimer || ($usercancreate && $isErasable == 1))) { // isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions) //var_dump($isErasable); if ($isErasable == -4) { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecausePayments").'">'.$langs->trans('Delete').'</a></div>'; @@ -3282,8 +3229,7 @@ if ($action == 'create') print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastInvoice").'">'.$langs->trans('Delete').'</a></div>'; } elseif ($isErasable == -1) { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Delete').'</a></div>'; - } elseif ($isErasable <= 0) // Any other cases - { + } elseif ($isErasable <= 0) { // Any other cases print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotErasable").'">'.$langs->trans('Delete').'</a></div>'; } else { print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>'; @@ -3291,13 +3237,12 @@ if ($action == 'create') } print '</div>'; - if ($action != 'confirm_edit') - { + if ($action != 'confirm_edit') { print '<div class="fichecenter"><div class="fichehalfleft">'; /* - * Documents generes - */ + * Generated documents + */ $ref = dol_sanitizeFileName($object->ref); $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref; $filedir = $conf->fournisseur->facture->dir_output.'/'.$subdir; diff --git a/htdocs/fourn/facture/contact.php b/htdocs/fourn/facture/contact.php index d655b97c74f..4f450bca3c4 100644 --- a/htdocs/fourn/facture/contact.php +++ b/htdocs/fourn/facture/contact.php @@ -41,7 +41,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); $object = new FactureFournisseur($db); @@ -51,51 +53,39 @@ $object = new FactureFournisseur($db); * Ajout d'un nouveau contact */ -if ($action == 'addcontact' && $user->rights->fournisseur->facture->creer) -{ +if ($action == 'addcontact' && $user->rights->fournisseur->facture->creer) { $result = $object->fetch($id, $ref); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } -} - -// bascule du statut d'un contact -elseif ($action == 'swapstatut' && $user->rights->fournisseur->facture->creer) -{ - if ($object->fetch($id)) - { +} elseif ($action == 'swapstatut' && $user->rights->fournisseur->facture->creer) { + // 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' && $user->rights->fournisseur->facture->creer) -{ +} elseif ($action == 'deletecontact' && $user->rights->fournisseur->facture->creer) { + // Efface un contact $object->fetch($id); $result = $object->delete_contact($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -124,10 +114,8 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref) > 0) - { +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { $object->fetch_thirdparty(); $alreadypaid = $object->getSommePaiement(); @@ -144,17 +132,18 @@ if ($id > 0 || !empty($ref)) $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') + if ($user->rights->facture->creer) { + if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; @@ -192,36 +181,34 @@ if ($id > 0 || !empty($ref)) // Type print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td colspan="4">'; print $object->getLibType(); - if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) - { + if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) { $facreplaced = new FactureFournisseur($db); $facreplaced->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; } - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) - { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { $facusing = new FactureFournisseur($db); $facusing->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; } $facidavoir = $object->getListIdAvoirFromInvoice(); - if (count($facidavoir) > 0) - { + if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); $i = 0; - foreach ($facidavoir as $fid) - { - if ($i == 0) print ' '; - else print ','; + foreach ($facidavoir as $fid) { + if ($i == 0) { + print ' '; + } else { + print ','; + } $facavoir = new FactureFournisseur($db); $facavoir->fetch($fid); print $facavoir->getNomUrl(1); } print ')'; } - if ($facidnext > 0) - { + if ($facidnext > 0) { $facthatreplace = new FactureFournisseur($db); $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; @@ -239,14 +226,12 @@ if ($id > 0 || !empty($ref)) // Amount Local Taxes //TODO: Place into a function to control showing by country or study better option - if ($societe->localtax1_assuj == "1") //Localtax1 - { + if ($societe->localtax1_assuj == "1") { //Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $societe->country_code).'</td>'; print '<td>'.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; } - if ($societe->localtax2_assuj == "1") //Localtax2 - { + if ($societe->localtax2_assuj == "1") { //Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $societe->country_code).'</td>'; print '<td>'.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; diff --git a/htdocs/fourn/facture/document.php b/htdocs/fourn/facture/document.php index 36f5a45b25e..24009d35dbc 100644 --- a/htdocs/fourn/facture/document.php +++ b/htdocs/fourn/facture/document.php @@ -46,7 +46,9 @@ $confirm = GETPOST('confirm', 'alpha'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); // Get parameters @@ -54,16 +56,21 @@ $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"; +} $object = new FactureFournisseur($db); -if ($object->fetch($id, $ref)) -{ +if ($object->fetch($id, $ref)) { $object->fetch_thirdparty(); $ref = dol_sanitizeFileName($object->ref); $upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref; @@ -74,7 +81,7 @@ if ($object->fetch($id, $ref)) * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -87,8 +94,7 @@ $title = $langs->trans('SupplierInvoice')." - ".$langs->trans('Documents'); $helpurl = "EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Módulo_Facturas_de_proveedores"; llxHeader('', $title, $helpurl); -if ($object->id > 0) -{ +if ($object->id > 0) { $head = facturefourn_prepare_head($object); print dol_get_fiche_head($head, 'documents', $langs->trans('SupplierInvoice'), -1, 'supplier_invoice'); @@ -102,17 +108,18 @@ if ($object->id > 0) $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') + if ($user->rights->facture->creer) { + if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; @@ -148,16 +155,14 @@ if ($object->id > 0) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } /* * Confirm delete file */ - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&urlfile='.urlencode($_GET["urlfile"]), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1); } @@ -166,28 +171,27 @@ if ($object->id > 0) // Type print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td>'; print $object->getLibType(); - if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) - { + if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) { $facreplaced = new FactureFournisseur($db); $facreplaced->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; } - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) - { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { $facusing = new FactureFournisseur($db); $facusing->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; } $facidavoir = $object->getListIdAvoirFromInvoice(); - if (count($facidavoir) > 0) - { + if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); $i = 0; - foreach ($facidavoir as $id) - { - if ($i == 0) print ' '; - else print ','; + foreach ($facidavoir as $id) { + if ($i == 0) { + print ' '; + } else { + print ','; + } $facavoir = new FactureFournisseur($db); $facavoir->fetch($id); print $facavoir->getNomUrl(1); @@ -215,14 +219,12 @@ if ($object->id > 0) // Amount Local Taxes //TODO: Place into a function to control showing by country or study better option - if ($mysoc->localtax1_assuj == "1") //Localtax1 - { + if ($mysoc->localtax1_assuj == "1") { //Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>'; print '<td>'.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; } - if ($mysoc->localtax2_assuj == "1") //Localtax2 - { + if ($mysoc->localtax2_assuj == "1") { //Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>'; print '<td>'.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; @@ -255,8 +257,7 @@ if ($object->id > 0) $defaulttpldir = '/core/tpl'; $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); - foreach ($dirtpls as $module => $reldir) - { + foreach ($dirtpls as $module => $reldir) { if (!empty($module)) { $tpl = dol_buildpath($reldir.'/document_actions_post_headers.tpl.php'); } else { @@ -268,7 +269,9 @@ if ($object->id > 0) } else { $res = include $tpl; // for debug } - if ($res) break; + if ($res) { + break; + } } } else { print $langs->trans('ErrorUnknown'); diff --git a/htdocs/fourn/facture/impayees.php b/htdocs/fourn/facture/impayees.php index 18c4bff9036..7019b90b868 100644 --- a/htdocs/fourn/facture/impayees.php +++ b/htdocs/fourn/facture/impayees.php @@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; -if (!$user->rights->fournisseur->facture->lire) accessforbidden(); +if (!$user->rights->fournisseur->facture->lire) { + accessforbidden(); +} $langs->loadLangs(array("companies", "bills")); @@ -39,8 +41,7 @@ $socid = GETPOST('socid', 'int'); $option = GETPOST('option'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -56,15 +57,20 @@ $search_amount_all_tax = GETPOST('search_amount_all_tax', 'alpha'); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $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 = "f.date_lim_reglement"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "f.date_lim_reglement"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $search_ref = ""; $search_ref_supplier = ""; $search_company = ""; @@ -85,101 +91,124 @@ $title = $langs->trans("BillsSuppliersUnpaid"); $facturestatic = new FactureFournisseur($db); $companystatic = new Societe($db); -if ($user->rights->fournisseur->facture->lire) -{ +if ($user->rights->fournisseur->facture->lire) { $sql = "SELECT s.rowid as socid, s.nom as name,"; $sql .= " f.rowid, f.ref, f.ref_supplier, f.total_ht, f.total_ttc,"; $sql .= " f.datef as df, f.date_lim_reglement as datelimite, "; $sql .= " f.paye as paye, f.rowid as facid, f.fk_statut"; $sql .= " ,sum(pf.amount) as am"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= ",".MAIN_DB_PREFIX."facture_fourn as f"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid=pf.fk_facturefourn "; $sql .= " WHERE f.entity = ".$conf->entity; $sql .= " AND f.fk_soc = s.rowid"; $sql .= " AND f.paye = 0 AND f.fk_statut = 1"; - if ($option == 'late') $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->fournisseur->warning_delay)."'"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if ($option == 'late') { + $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->fournisseur->warning_delay)."'"; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } - if (GETPOST('filtre')) - { + if (GETPOST('filtre')) { $filtrearr = explode(",", GETPOST('filtre')); - foreach ($filtrearr as $fil) - { + foreach ($filtrearr as $fil) { $filt = explode(":", $fil); $sql .= " AND ".$filt[0]." = ".$filt[1]; } } - if ($search_ref) - { + if ($search_ref) { $sql .= " AND f.ref LIKE '%".$db->escape($search_ref)."%'"; } - if ($search_ref_supplier) - { + if ($search_ref_supplier) { $sql .= " AND f.ref_supplier LIKE '%".$db->escape($search_ref_supplier)."%'"; } - if ($search_company) - { + if ($search_company) { $sql .= " AND s.nom LIKE '%".$db->escape($search_company)."%'"; } - if ($search_amount_no_tax) - { + if ($search_amount_no_tax) { $sql .= " AND f.total_ht = '".$db->escape($search_amount_no_tax)."'"; } - if ($search_amount_all_tax) - { + if ($search_amount_all_tax) { $sql .= " AND f.total_ttc = '".$db->escape($search_amount_all_tax)."'"; } - if (dol_strlen(GETPOST('sf_re')) > 0) - { + if (dol_strlen(GETPOST('sf_re')) > 0) { $sql .= " AND f.ref_supplier LIKE '%".$db->escape(GETPOST('sf_re'))."%'"; } $sql .= " GROUP BY s.rowid, s.nom, f.rowid, f.ref, f.ref_supplier, f.total_ht, f.total_ttc, f.datef, f.date_lim_reglement, f.paye, f.fk_statut"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= $db->order($sortfield, $sortorder); - if (!in_array("f.ref_supplier", explode(',', $sortfield))) $sql .= ", f.ref_supplier DESC"; + if (!in_array("f.ref_supplier", explode(',', $sortfield))) { + $sql .= ", f.ref_supplier DESC"; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($socid) - { + if ($socid) { $soc = new Societe($db); $soc->fetch($socid); } $param = ''; - if ($socid) $param .= "&socid=".$socid; + if ($socid) { + $param .= "&socid=".$socid; + } - if ($search_ref) $param .= '&amp;search_ref='.urlencode($search_ref); - if ($search_ref_supplier) $param .= '&amp;search_ref_supplier='.urlencode($search_ref_supplier); - if ($search_company) $param .= '&amp;search_company='.urlencode($search_company); - if ($search_amount_no_tax) $param .= '&amp;search_amount_no_tax='.urlencode($search_amount_no_tax); - if ($search_amount_all_tax) $param .= '&amp;search_amount_all_tax='.urlencode($search_amount_all_tax); + if ($search_ref) { + $param .= '&amp;search_ref='.urlencode($search_ref); + } + if ($search_ref_supplier) { + $param .= '&amp;search_ref_supplier='.urlencode($search_ref_supplier); + } + if ($search_company) { + $param .= '&amp;search_company='.urlencode($search_company); + } + if ($search_amount_no_tax) { + $param .= '&amp;search_amount_no_tax='.urlencode($search_amount_no_tax); + } + if ($search_amount_all_tax) { + $param .= '&amp;search_amount_all_tax='.urlencode($search_amount_all_tax); + } $param .= ($option ? "&option=".$option : ""); - if (!empty($late)) $param .= '&late='.urlencode($late); + if (!empty($late)) { + $param .= '&late='.urlencode($late); + } $urlsource = str_replace('&amp;', '&', $param); $titre = ($socid ? $langs->trans("BillsSuppliersUnpaidForCompany", $soc->name) : $langs->trans("BillsSuppliersUnpaid")); - if ($option == 'late') $titre .= ' ('.$langs->trans("Late").')'; - else $titre .= ' ('.$langs->trans("All").')'; + if ($option == 'late') { + $titre .= ' ('.$langs->trans("Late").')'; + } else { + $titre .= ' ('.$langs->trans("All").')'; + } $link = ''; - if (empty($option)) $link = '<a href="'.$_SERVER["PHP_SELF"].'?option=late'.($socid ? '&socid='.$socid : '').'">'.$langs->trans("ShowUnpaidLateOnly").'</a>'; - elseif ($option == 'late') $link = '<a href="'.$_SERVER["PHP_SELF"].'?'.($socid ? '&socid='.$socid : '').'">'.$langs->trans("ShowUnpaidAll").'</a>'; + if (empty($option)) { + $link = '<a href="'.$_SERVER["PHP_SELF"].'?option=late'.($socid ? '&socid='.$socid : '').'">'.$langs->trans("ShowUnpaidLateOnly").'</a>'; + } elseif ($option == 'late') { + $link = '<a href="'.$_SERVER["PHP_SELF"].'?'.($socid ? '&socid='.$socid : '').'">'.$langs->trans("ShowUnpaidAll").'</a>'; + } print load_fiche_titre($titre, $link); print_barre_liste('', '', $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', 0); // We don't want pagination on this page @@ -220,14 +249,12 @@ if ($user->rights->fournisseur->facture->lire) print '</td>'; print "</tr>\n"; - if ($num > 0) - { + if ($num > 0) { $total_ht = 0; $total_ttc = 0; $total_paid = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $facturestatic->statut = $objp->fk_statut; diff --git a/htdocs/fourn/facture/index.php b/htdocs/fourn/facture/index.php index 131b34bbe39..8904310bf3e 100644 --- a/htdocs/fourn/facture/index.php +++ b/htdocs/fourn/facture/index.php @@ -34,8 +34,7 @@ $langs->loadLangs(['bills', 'boxes']); // Filter to show only result of one supplier $socid = GETPOST('socid', 'int'); -if (isset($user->socid) && $user->socid > 0) -{ +if (isset($user->socid) && $user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -58,8 +57,7 @@ print '<div class="fichecenter">'; print '<div class="fichethirdleft">'; // This is useless due to the global search combo -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { print getAreaSearchFrom(); print '<br>'; } @@ -129,16 +127,21 @@ function getPieChart($socid = 0) $sql = "SELECT count(f.rowid), f.fk_statut"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."facture_fourn as f"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture_fourn').")"; - if ($user->socid) $sql .= ' AND f.fk_soc = '.$user->socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) { + $sql .= ' AND f.fk_soc = '.$user->socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= " GROUP BY f.fk_statut"; $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); return ''; } @@ -149,11 +152,9 @@ function getPieChart($socid = 0) $total = 0; $vals = []; - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); - if ($row) - { + if ($row) { $vals[$row[1]] = $row[0]; $total += $row[0]; } @@ -174,14 +175,12 @@ function getPieChart($socid = 0) $array = [FactureFournisseur::STATUS_DRAFT, FactureFournisseur::STATUS_VALIDATED, FactureFournisseur::STATUS_CLOSED, FactureFournisseur::STATUS_ABANDONED]; $dataseries = []; - foreach ($array as $status) - { + foreach ($array as $status) { $objectstatic->statut = $status; $objectstatic->paye = $status == FactureFournisseur::STATUS_CLOSED ? -1 : 0; $dataseries[] = [$objectstatic->getLibStatut(1), (isset($vals[$status]) ? (int) $vals[$status] : 0)]; - if (!$conf->use_javascript_ajax) - { + if (!$conf->use_javascript_ajax) { $result .= '<tr class="oddeven">'; $result .= '<td>'.$objectstatic->getLibStatut(0).'</td>'; $result .= '<td class="right"><a href="list.php?statut='.$status.'">'.(isset($vals[$status]) ? $vals[$status] : 0).'</a></td>'; @@ -189,8 +188,7 @@ function getPieChart($socid = 0) } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { $dolgraph = new DolGraph(); $dolgraph->SetData($dataseries); $dolgraph->setShowLegend(2); @@ -229,17 +227,22 @@ function getDraftTable($maxCount = 500, $socid = 0) $sql = "SELECT f.rowid, f.ref, s.nom as socname, s.rowid as socid, s.canvas, s.client, f.total_ttc"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture_fourn').")"; $sql .= " AND f.fk_statut = ".FactureFournisseur::STATUS_DRAFT; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= $db->plimit($maxCount, 0); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); return ''; } @@ -258,8 +261,7 @@ function getDraftTable($maxCount = 500, $socid = 0) $result .= '</td>'; $result .= '</tr>'; - if ($num < 1) - { + if ($num < 1) { $result .= '</table>'; $result .= '</div>'; return $result; @@ -271,8 +273,7 @@ function getDraftTable($maxCount = 500, $socid = 0) $total = 0; $i = 0; - while ($i < $nbofloop) - { + while ($i < $nbofloop) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->rowid; @@ -293,14 +294,11 @@ function getDraftTable($maxCount = 500, $socid = 0) $total += $obj->total_ttc; } - if ($num > $nbofloop) - { + if ($num > $nbofloop) { $result .= '<tr class="liste_total">'; $result .= '<td colspan="3" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>'; $result .= '</tr>'; - } - elseif ($total > 0) - { + } elseif ($total > 0) { $result .= '<tr class="liste_total">'; $result .= '<td colspan="2" class="right">'.$langs->trans("Total").'</td>'; $result .= '<td class="right">'.price($total).'</td>'; @@ -327,17 +325,22 @@ function getLatestEditTable($maxCount = 5, $socid = 0) $sql .= " f.datec"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture_fourn').")"; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= " ORDER BY f.tms DESC"; $sql .= $db->plimit($maxCount, 0); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); return ''; } @@ -350,8 +353,7 @@ function getLatestEditTable($maxCount = 5, $socid = 0) $result .= '<td colspan="4">'.$langs->trans("BoxTitleLastSupplierBills", $maxCount).'</td>'; $result .= '</tr>'; - if ($num < 1) - { + if ($num < 1) { $result .= '</table>'; $result .= '</div>'; return $result; @@ -362,8 +364,7 @@ function getLatestEditTable($maxCount = 5, $socid = 0) $formfile = new FormFile($db); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->rowid; @@ -423,18 +424,23 @@ function getOpenTable($maxCount = 500, $socid = 0) $sql .= ", f.datef as df, f.date_lim_reglement as datelimite"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."facture_fourn as f"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture_fourn').")"; $sql .= " AND f.fk_statut = ".FactureFournisseur::STATUS_VALIDATED; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } $sql .= " ORDER BY f.rowid DESC"; $sql .= $db->plimit($maxCount, 0); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); return ''; } @@ -452,8 +458,7 @@ function getOpenTable($maxCount = 500, $socid = 0) $result .= '</td>'; $result .= '</tr>'; - if ($num < 1) - { + if ($num < 1) { $result .= '</table>'; $result .= '</div>'; return $result; @@ -467,8 +472,7 @@ function getOpenTable($maxCount = 500, $socid = 0) $total = 0; $i = 0; - while ($i < $nbofloop) - { + while ($i < $nbofloop) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->id; @@ -491,8 +495,7 @@ function getOpenTable($maxCount = 500, $socid = 0) $result .= '<td class="nobordernopadding nowrap">'.$objectstatic->getNomUrl(1).'</td>'; $result .= '<td width="18" class="nobordernopadding nowrap">'; - if ($db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) - { + if ($db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) { $result .= img_warning($langs->trans("Late")); } @@ -514,14 +517,11 @@ function getOpenTable($maxCount = 500, $socid = 0) $total += $obj->total_ttc; } - if ($num > $nbofloop) - { + if ($num > $nbofloop) { $result .= '<tr class="liste_total">'; $result .= '<td colspan="4" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>'; $result .= '</tr>'; - } - elseif ($total > 0) - { + } elseif ($total > 0) { $result .= '<tr class="liste_total">'; $result .= '<td colspan="2" class="right">'.$langs->trans("Total").'</td>'; $result .= '<td align="right">'.price($total).'</td>'; diff --git a/htdocs/fourn/facture/info.php b/htdocs/fourn/facture/info.php index 69ea8839cfb..efe91880a56 100644 --- a/htdocs/fourn/facture/info.php +++ b/htdocs/fourn/facture/info.php @@ -40,7 +40,9 @@ $id = GETPOST("facid", 'int') ?GETPOST("facid", 'int') : GETPOST("id", 'int'); $ref = GETPOST("ref", 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); $object = new FactureFournisseur($db); @@ -75,39 +77,40 @@ $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_ $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); -if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; +if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; +} // Project -if (!empty($conf->projet->enabled)) -{ - $langs->load("projects"); - $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') - //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; - $morehtmlref .= ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; - $morehtmlref .= '<input type="hidden" name="action" value="classin">'; - $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; - $morehtmlref .= $formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; - $morehtmlref .= '</form>'; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (!empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">'; - $morehtmlref .= $proj->ref; - $morehtmlref .= '</a>'; - } else { - $morehtmlref .= ''; - } - } +if (!empty($conf->projet->enabled)) { + $langs->load("projects"); + $morehtmlref .= '<br>'.$langs->trans('Project').' '; + if ($user->rights->facture->creer) { + if ($action != 'classify') { + //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; + $morehtmlref .= ' : '; + } + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref .= '<input type="hidden" name="action" value="classin">'; + $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref .= $formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref .= '</form>'; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">'; + $morehtmlref .= $proj->ref; + $morehtmlref .= '</a>'; + } else { + $morehtmlref .= ''; + } + } } $morehtmlref .= '</div>'; diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index 99ab93ca973..7c6ed0c5e16 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -44,7 +44,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; -if (!$user->rights->fournisseur->facture->lire) accessforbidden(); +if (!$user->rights->fournisseur->facture->lire) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('products', 'bills', 'companies', 'projects')); @@ -120,12 +122,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 ($page == -1 || $page == null || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { $page = 0; } +if ($page == -1 || $page == null || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { + $page = 0; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) $sortorder = "DESC"; -if (!$sortfield) $sortfield = "f.datef,f.rowid"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "f.datef,f.rowid"; +} $diroutputmassaction = $conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id; @@ -149,7 +157,9 @@ $fieldstosearchall = array( 's.nom'=>"ThirdParty", 'f.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["f.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["f.note_private"] = "NotePrivate"; +} $checkedtypetiers = 0; $arrayfields = array( @@ -198,19 +208,23 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * 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)) -{ +if (empty($reshook)) { include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha')) // All tests must be present to be compatible with all browsers - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha')) { // All tests must be present to be compatible with all browsers $search_all = ""; $search_user = ''; $search_sale = ''; @@ -266,12 +280,10 @@ if (empty($reshook)) $uploaddir = $conf->fournisseur->facture->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - if ($massaction == 'banktransfertrequest') - { + if ($massaction == 'banktransfertrequest') { $langs->load("withdrawals"); - if (!$user->rights->paymentbybanktransfer->create) - { + if (!$user->rights->paymentbybanktransfer->create) { $error++; setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); } else { @@ -280,12 +292,10 @@ if (empty($reshook)) $arrayofselected = is_array($toselect) ? $toselect : array(); $listofbills = array(); - foreach ($arrayofselected as $toselectid) - { + foreach ($arrayofselected as $toselectid) { $objecttmp = new FactureFournisseur($db); $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $totalpaye = $objecttmp->getSommePaiement(); $totalcreditnotes = $objecttmp->getSumCreditNotesUsed(); $totaldeposits = $objecttmp->getSumDepositsUsed(); @@ -314,8 +324,7 @@ if (empty($reshook)) $rsql .= " ORDER BY pfd.date_demande DESC"; $result_sql = $db->query($rsql); - if ($result_sql) - { + if ($result_sql) { $numprlv = $db->num_rows($result_sql); } @@ -332,15 +341,12 @@ if (empty($reshook)) } //Massive withdraw request for request with no errors - if (!empty($listofbills)) - { + if (!empty($listofbills)) { $nbwithdrawrequestok = 0; - foreach ($listofbills as $aBill) - { + foreach ($listofbills as $aBill) { $db->begin(); $result = $aBill->demande_prelevement($user, $aBill->resteapayer, 'bank-transfer', 'supplier_invoice'); - if ($result > 0) - { + if ($result > 0) { $db->commit(); $nbwithdrawrequestok++; } else { @@ -348,8 +354,7 @@ if (empty($reshook)) setEventMessages($aBill->error, $aBill->errors, 'errors'); } } - if ($nbwithdrawrequestok > 0) - { + if ($nbwithdrawrequestok > 0) { setEventMessages($langs->trans("WithdrawRequestsDone", $nbwithdrawrequestok), null, 'mesgs'); } } @@ -358,8 +363,7 @@ if (empty($reshook)) } -if ($massaction == 'transfer_request') -{ +if ($massaction == 'transfer_request') { $langs->load("withdrawals"); if (!$user->rights->paymentbybanktransfer->create) { @@ -371,12 +375,10 @@ if ($massaction == 'transfer_request') $arrayofselected = is_array($toselect) ? $toselect : array(); $listofbills = array(); - foreach ($arrayofselected as $toselectid) - { + foreach ($arrayofselected as $toselectid) { $objecttmp = new FactureFournisseur($db); $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $totalpaye = $objecttmp->getSommePaiement(); $totalcreditnotes = $objecttmp->getSumCreditNotesUsed(); $totaldeposits = $objecttmp->getSumDepositsUsed(); @@ -405,16 +407,14 @@ if ($massaction == 'transfer_request') $rsql .= " ORDER BY pfd.date_demande DESC"; $result_sql = $db->query($rsql); - if ($result_sql) - { + if ($result_sql) { $numprlv = $db->num_rows($result_sql); } if ($numprlv > 0) { $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'warnings'); - } - elseif (!empty($objecttmp->mode_reglement_code) && $objecttmp->mode_reglement_code != 'VIR') { + } elseif (!empty($objecttmp->mode_reglement_code) && $objecttmp->mode_reglement_code != 'VIR') { $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("BadPaymentMethod"), $objecttmp->errors, 'errors'); } else { @@ -460,7 +460,9 @@ $thirdparty = new Societe($db); // llxHeader('',$langs->trans("SuppliersInvoices"),'EN:Suppliers_Invoices|FR:FactureFournisseur|ES:Facturas_de_proveedores'); $sql = "SELECT"; -if ($search_all || $search_product_category > 0) $sql = 'SELECT DISTINCT'; +if ($search_all || $search_product_category > 0) { + $sql = 'SELECT DISTINCT'; +} $sql .= " f.rowid as facid, f.ref, f.ref_supplier, f.type, f.datef, f.date_lim_reglement as datelimite, f.fk_mode_reglement, f.fk_cond_reglement,"; $sql .= " f.total_ht, f.total_ttc, f.total_tva as total_vat, f.paye as paye, f.fk_statut as fk_statut, f.libelle as label, f.datec as date_creation, f.tms as date_update,"; $sql .= " f.localtax1 as total_localtax1, f.localtax2 as total_localtax2,"; @@ -475,11 +477,17 @@ $sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_label, $sql .= " u.login"; // We need dynamount_payed to be able to sort on status (value is surely wrong because we can count several lines several times due to other left join or link with contacts. But what we need is just 0 or > 0) // TODO Better solution to be able to sort on already payed or remain to pay is to store amount_payed in a denormalized field. -if (!$search_all) $sql .= ', SUM(pf.amount) as dynamount_payed'; -if ($search_categ_sup) $sql .= ", cs.fk_categorie, cs.fk_soc"; +if (!$search_all) { + $sql .= ', SUM(pf.amount) as dynamount_payed'; +} +if ($search_categ_sup) { + $sql .= ", cs.fk_categorie, cs.fk_soc"; +} // 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 : ''); + 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(); @@ -489,86 +497,164 @@ $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; -if (!empty($search_categ_sup)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cs ON s.rowid = cs.fk_soc"; +if (!empty($search_categ_sup)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cs ON s.rowid = cs.fk_soc"; +} $sql .= ', '.MAIN_DB_PREFIX.'facture_fourn as f'; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (f.rowid = ef.fk_object)"; -if (!$search_all) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_facturefourn = f.rowid'; -if ($search_all || $search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_fourn_det as pd ON f.rowid=pd.fk_facture_fourn'; -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (f.rowid = ef.fk_object)"; +} +if (!$search_all) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_facturefourn = f.rowid'; +} +if ($search_all || $search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_fourn_det as pd ON f.rowid=pd.fk_facture_fourn'; +} +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +} $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user AS u ON f.fk_user_author = u.rowid'; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = f.fk_projet"; // We'll need this table joined to the select in order to filter by sale -if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; -if ($search_user > 0) -{ +if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} +if ($search_user > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql .= ' WHERE f.fk_soc = s.rowid'; $sql .= ' AND f.entity IN ('.getEntity('facture_fourn').')'; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; -if ($socid > 0) $sql .= ' AND s.rowid = '.$socid; -if ($search_ref) -{ - if (is_numeric($search_ref)) $sql .= natural_search(array('f.ref'), $search_ref); - else $sql .= natural_search('f.ref', $search_ref); +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } -if ($search_ref) $sql .= natural_search('f.ref', $search_ref); -if ($search_refsupplier) $sql .= natural_search('f.ref_supplier', $search_refsupplier); -if ($search_type != '' && $search_type >= 0) -{ - if ($search_type == '0') $sql .= " AND f.type = 0"; // standard - if ($search_type == '1') $sql .= " AND f.type = 1"; // replacement - if ($search_type == '2') $sql .= " AND f.type = 2"; // credit note - if ($search_type == '3') $sql .= " AND f.type = 3"; // deposit +if ($search_product_category > 0) { + $sql .= " AND cp.fk_categorie = ".$search_product_category; +} +if ($socid > 0) { + $sql .= ' AND s.rowid = '.$socid; +} +if ($search_ref) { + if (is_numeric($search_ref)) { + $sql .= natural_search(array('f.ref'), $search_ref); + } else { + $sql .= natural_search('f.ref', $search_ref); + } +} +if ($search_ref) { + $sql .= natural_search('f.ref', $search_ref); +} +if ($search_refsupplier) { + $sql .= natural_search('f.ref_supplier', $search_refsupplier); +} +if ($search_type != '' && $search_type >= 0) { + if ($search_type == '0') { + $sql .= " AND f.type = 0"; // standard + } + if ($search_type == '1') { + $sql .= " AND f.type = 1"; // replacement + } + if ($search_type == '2') { + $sql .= " AND f.type = 2"; // credit note + } + if ($search_type == '3') { + $sql .= " AND f.type = 3"; // deposit + } //if ($search_type == '4') $sql.=" AND f.type = 4"; // proforma //if ($search_type == '5') $sql.=" AND f.type = 5"; // situation } -if ($search_project) $sql .= natural_search('p.ref', $search_project); -if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_town) $sql .= natural_search('s.town', $search_town); -if ($search_zip) $sql .= natural_search("s.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_country) $sql .= " AND s.fk_pays IN (".$search_country.')'; -if ($search_type_thirdparty != '' && $search_type_thirdparty >= 0) $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; -if ($search_montant_ht != '') $sql .= natural_search('f.total_ht', $search_montant_ht, 1); -if ($search_montant_vat != '') $sql .= natural_search('f.total_tva', $search_montant_vat, 1); -if ($search_montant_localtax1 != '') $sql .= natural_search('f.localtax1', $search_montant_localtax1, 1); -if ($search_montant_localtax2 != '') $sql .= natural_search('f.localtax2', $search_montant_localtax2, 1); -if ($search_montant_ttc != '') $sql .= natural_search('f.total_ttc', $search_montant_ttc, 1); -if ($search_multicurrency_code != '') $sql .= ' AND f.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; -if ($search_multicurrency_tx != '') $sql .= natural_search('f.multicurrency_tx', $search_multicurrency_tx, 1); -if ($search_multicurrency_montant_ht != '') $sql .= natural_search('f.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); -if ($search_multicurrency_montant_vat != '') $sql .= natural_search('f.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); -if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('f.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); -if ($search_login) $sql .= natural_search('u.login', $search_login); -if ($search_status != '' && $search_status >= 0) $sql .= " AND f.fk_statut = ".$db->escape($search_status); -if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".((int) $search_paymentmode); -if ($search_paymentcond > 0) $sql .= " AND f.fk_cond_reglement = ".((int) $search_paymentcond); +if ($search_project) { + $sql .= natural_search('p.ref', $search_project); +} +if ($search_company) { + $sql .= natural_search('s.nom', $search_company); +} +if ($search_town) { + $sql .= natural_search('s.town', $search_town); +} +if ($search_zip) { + $sql .= natural_search("s.zip", $search_zip); +} +if ($search_state) { + $sql .= natural_search("state.nom", $search_state); +} +if ($search_country) { + $sql .= " AND s.fk_pays IN (".$search_country.')'; +} +if ($search_type_thirdparty != '' && $search_type_thirdparty >= 0) { + $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; +} +if ($search_montant_ht != '') { + $sql .= natural_search('f.total_ht', $search_montant_ht, 1); +} +if ($search_montant_vat != '') { + $sql .= natural_search('f.total_tva', $search_montant_vat, 1); +} +if ($search_montant_localtax1 != '') { + $sql .= natural_search('f.localtax1', $search_montant_localtax1, 1); +} +if ($search_montant_localtax2 != '') { + $sql .= natural_search('f.localtax2', $search_montant_localtax2, 1); +} +if ($search_montant_ttc != '') { + $sql .= natural_search('f.total_ttc', $search_montant_ttc, 1); +} +if ($search_multicurrency_code != '') { + $sql .= ' AND f.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; +} +if ($search_multicurrency_tx != '') { + $sql .= natural_search('f.multicurrency_tx', $search_multicurrency_tx, 1); +} +if ($search_multicurrency_montant_ht != '') { + $sql .= natural_search('f.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); +} +if ($search_multicurrency_montant_vat != '') { + $sql .= natural_search('f.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); +} +if ($search_multicurrency_montant_ttc != '') { + $sql .= natural_search('f.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); +} +if ($search_login) { + $sql .= natural_search('u.login', $search_login); +} +if ($search_status != '' && $search_status >= 0) { + $sql .= " AND f.fk_statut = ".$db->escape($search_status); +} +if ($search_paymentmode > 0) { + $sql .= " AND f.fk_mode_reglement = ".((int) $search_paymentmode); +} +if ($search_paymentcond > 0) { + $sql .= " AND f.fk_cond_reglement = ".((int) $search_paymentcond); +} $sql .= dolSqlDateFilter("f.datef", $day, $month, $year); $sql .= dolSqlDateFilter("f.date_lim_reglement", $day_lim, $month_lim, $year_lim); -if ($option == 'late') $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->fournisseur->warning_delay)."'"; -if ($search_label) $sql .= natural_search('f.libelle', $search_label); -if ($search_categ_sup > 0) $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ_sup); -if ($search_categ_sup == -2) $sql .= " AND cs.fk_categorie IS NULL"; -if ($search_status != '' && $search_status >= 0) -{ +if ($option == 'late') { + $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->fournisseur->warning_delay)."'"; +} +if ($search_label) { + $sql .= natural_search('f.libelle', $search_label); +} +if ($search_categ_sup > 0) { + $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ_sup); +} +if ($search_categ_sup == -2) { + $sql .= " AND cs.fk_categorie IS NULL"; +} +if ($search_status != '' && $search_status >= 0) { $sql .= " AND f.fk_statut = ".$search_status; } -if ($filter && $filter != -1) -{ +if ($filter && $filter != -1) { $aFilter = explode(',', $filter); - foreach ($aFilter as $fil) - { + foreach ($aFilter as $fil) { $filt = explode(':', $fil); $sql .= ' AND '.$db->escape(trim($filt[0])).' = '.$db->escape(trim($filt[1])); } } -if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $search_sale); -if ($search_user > 0) -{ +if ($search_sale > 0) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $search_sale); +} +if ($search_user > 0) { $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='invoice_supplier' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; } // Add where from extra fields @@ -578,8 +664,7 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; -if (!$search_all) -{ +if (!$search_all) { $sql .= " GROUP BY f.rowid, f.ref, f.ref_supplier, f.type, f.datef, f.date_lim_reglement, f.fk_mode_reglement, f.fk_cond_reglement,"; $sql .= " f.total_ht, f.total_ttc, f.total_tva, f.paye, f.fk_statut, f.libelle, f.datec, f.tms,"; $sql .= " f.localtax1, f.localtax2,"; @@ -605,12 +690,10 @@ if (!$search_all) $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -620,14 +703,12 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); - if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) - { + if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { $obj = $db->fetch_object($resql); $id = $obj->facid; @@ -637,47 +718,114 @@ if ($resql) llxHeader('', $langs->trans("SuppliersInvoices"), 'EN:Suppliers_Invoices|FR:FactureFournisseur|ES:Facturas_de_proveedores'); - if ($socid) - { + if ($socid) { $soc = new Societe($db); $soc->fetch($socid); - if (empty($search_company)) $search_company = $soc->name; + if (empty($search_company)) { + $search_company = $soc->name; + } } $param = '&socid='.$socid; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($search_all) $param .= '&search_all='.urlencode($search_all); - if ($day) $param .= '&day='.urlencode($day); - if ($month) $param .= '&month='.urlencode($month); - if ($year) $param .= '&year='.urlencode($year); - if ($day_lim) $param .= '&day_lim='.urlencode($day_lim); - if ($month_lim) $param .= '&month_lim='.urlencode($month_lim); - if ($year_lim) $param .= '&year_lim='.urlencode($year_lim); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_refsupplier) $param .= '&search_refsupplier='.urlencode($search_refsupplier); - if ($search_type != '') $param .= '&search_type='.urlencode($search_type); - if ($search_label) $param .= '&search_label='.urlencode($search_label); - if ($search_company) $param .= '&search_company='.urlencode($search_company); - if ($search_login) $param .= '&search_login='.urlencode($search_login); - if ($search_montant_ht != '') $param .= '&search_montant_ht='.urlencode($search_montant_ht); - if ($search_montant_vat != '') $param .= '&search_montant_vat='.urlencode($search_montant_vat); - if ($search_montant_localtax1 != '') $param .= '&search_montant_localtax1='.urlencode($search_montant_localtax1); - if ($search_montant_localtax2 != '') $param .= '&search_montant_localtax2='.urlencode($search_montant_localtax2); - if ($search_montant_ttc != '') $param .= '&search_montant_ttc='.urlencode($search_montant_ttc); - if ($search_multicurrency_code != '') $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); - if ($search_multicurrency_tx != '') $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); - if ($search_multicurrency_montant_ht != '') $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); - if ($search_multicurrency_montant_vat != '') $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); - if ($search_multicurrency_montant_ttc != '') $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); - if ($search_amount_no_tax) $param .= '&search_amount_no_tax='.urlencode($search_amount_no_tax); - if ($search_amount_all_tax) $param .= '&search_amount_all_tax='.urlencode($search_amount_all_tax); - if ($search_status >= 0) $param .= "&search_status=".urlencode($search_status); - if ($show_files) $param .= '&show_files='.urlencode($show_files); - if ($option) $param .= "&option=".urlencode($option); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($search_categ_sup > 0) $param .= '&search_categ_sup='.urlencode($search_categ_sup); - if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($search_all) { + $param .= '&search_all='.urlencode($search_all); + } + if ($day) { + $param .= '&day='.urlencode($day); + } + if ($month) { + $param .= '&month='.urlencode($month); + } + if ($year) { + $param .= '&year='.urlencode($year); + } + if ($day_lim) { + $param .= '&day_lim='.urlencode($day_lim); + } + if ($month_lim) { + $param .= '&month_lim='.urlencode($month_lim); + } + if ($year_lim) { + $param .= '&year_lim='.urlencode($year_lim); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_refsupplier) { + $param .= '&search_refsupplier='.urlencode($search_refsupplier); + } + if ($search_type != '') { + $param .= '&search_type='.urlencode($search_type); + } + if ($search_label) { + $param .= '&search_label='.urlencode($search_label); + } + if ($search_company) { + $param .= '&search_company='.urlencode($search_company); + } + if ($search_login) { + $param .= '&search_login='.urlencode($search_login); + } + if ($search_montant_ht != '') { + $param .= '&search_montant_ht='.urlencode($search_montant_ht); + } + if ($search_montant_vat != '') { + $param .= '&search_montant_vat='.urlencode($search_montant_vat); + } + if ($search_montant_localtax1 != '') { + $param .= '&search_montant_localtax1='.urlencode($search_montant_localtax1); + } + if ($search_montant_localtax2 != '') { + $param .= '&search_montant_localtax2='.urlencode($search_montant_localtax2); + } + if ($search_montant_ttc != '') { + $param .= '&search_montant_ttc='.urlencode($search_montant_ttc); + } + if ($search_multicurrency_code != '') { + $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); + } + if ($search_multicurrency_tx != '') { + $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); + } + if ($search_multicurrency_montant_ht != '') { + $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); + } + if ($search_multicurrency_montant_vat != '') { + $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); + } + if ($search_multicurrency_montant_ttc != '') { + $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); + } + if ($search_amount_no_tax) { + $param .= '&search_amount_no_tax='.urlencode($search_amount_no_tax); + } + if ($search_amount_all_tax) { + $param .= '&search_amount_all_tax='.urlencode($search_amount_all_tax); + } + if ($search_status >= 0) { + $param .= "&search_status=".urlencode($search_status); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); + } + if ($option) { + $param .= "&option=".urlencode($option); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($search_categ_sup > 0) { + $param .= '&search_categ_sup='.urlencode($search_categ_sup); + } + if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -690,25 +838,33 @@ if ($resql) //'presend'=>$langs->trans("SendByMail"), ); if ($conf->paymentbybanktransfer->enabled) { - $langs->load("withdrawals"); - $arrayofmassactions['transfer_request'] = $langs->trans("MakeBankTransferOrder"); + $langs->load("withdrawals"); + $arrayofmassactions['transfer_request'] = $langs->trans("MakeBankTransferOrder"); } //if($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); if (!empty($conf->paymentbybanktransfer->enabled) && !empty($user->rights->paymentbybanktransfer->create)) { $langs->load('withdrawals'); $arrayofmassactions['banktransfertrequest'] = $langs->trans("MakeBankTransferOrder"); } - if ($user->rights->fournisseur->facture->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete', 'createbills'))) $arrayofmassactions = array(); + if ($user->rights->fournisseur->facture->supprimer) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); + } + if (in_array($massaction, array('presend', 'predelete', 'createbills'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $url = DOL_URL_ROOT.'/fourn/facture/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewBill'), '', 'fa fa-plus-circle', $url, '', $user->rights->fournisseur->facture->creer); $i = 0; print '<form method="POST" name="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -724,8 +880,7 @@ if ($resql) $trackid = 'sinv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($massaction == 'createbills') - { + if ($massaction == 'createbills') { //var_dump($_REQUEST); print '<input type="hidden" name="massaction" value="confirm_createbills">'; @@ -764,33 +919,31 @@ if ($resql) print '<br>'; } - if ($search_all) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } - // If the user can view prospects other than his' - $moreforfilter = ''; - if ($user->rights->societe->client->voir || $socid) - { - $langs->load("commercial"); - $moreforfilter .= '<div class="divsearchfield">'; - $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; - $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); - $moreforfilter .= '</div>'; - } // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + $moreforfilter = ''; + if ($user->rights->societe->client->voir || $socid) { + $langs->load("commercial"); + $moreforfilter .= '<div class="divsearchfield">'; + $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; + $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); + $moreforfilter .= '</div>'; + } + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) { $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - $moreforfilter .= '</div>'; + $moreforfilter .= '</div>'; } // If the user can view prospects other than his' - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) - { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; @@ -799,8 +952,7 @@ if ($resql) $moreforfilter .= '</div>'; } - if (!empty($conf->categorie->enabled)) - { + if (!empty($conf->categorie->enabled)) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('SuppliersCategoriesShort').': '; @@ -809,19 +961,23 @@ if ($resql) } $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 ($moreforfilter) - { - print '<div class="liste_titre liste_titre_bydiv centpercent">'; + if ($moreforfilter) { + print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; } $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 '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; @@ -829,22 +985,19 @@ if ($resql) // Line for filters print '<tr class="liste_titre_filter">'; // Ref - if (!empty($arrayfields['f.ref']['checked'])) - { + if (!empty($arrayfields['f.ref']['checked'])) { print '<td class="liste_titre left">'; print '<input class="flat maxwidth50" type="text" name="search_ref" value="'.$search_ref.'">'; print '</td>'; } // Ref supplier - if (!empty($arrayfields['f.ref_supplier']['checked'])) - { + if (!empty($arrayfields['f.ref_supplier']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat maxwidth50" type="text" name="search_refsupplier" value="'.$search_refsupplier.'">'; print '</td>'; } // Type - if (!empty($arrayfields['f.type']['checked'])) - { + if (!empty($arrayfields['f.type']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone">'; $listtype = array( FactureFournisseur::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), @@ -857,180 +1010,163 @@ if ($resql) { $listtype[Facture::TYPE_SITUATION] = $langs->trans("InvoiceSituation"); } - */ + */ //$listtype[Facture::TYPE_PROFORMA]=$langs->trans("InvoiceProForma"); // A proformat invoice is not an invoice but must be an order. print $form->selectarray('search_type', $listtype, $search_type, 1, 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth100'); print '</td>'; } // Label - if (!empty($arrayfields['f.label']['checked'])) - { + if (!empty($arrayfields['f.label']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat maxwidth75" type="text" name="search_label" value="'.$search_label.'">'; print '</td>'; } // Date invoice - if (!empty($arrayfields['f.datef']['checked'])) - { + if (!empty($arrayfields['f.datef']['checked'])) { print '<td class="liste_titre nowraponall center">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="day" value="'.dol_escape_htmltag($day).'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="day" value="'.dol_escape_htmltag($day).'">'; + } print '<input class="flat width25 valignmiddle" type="text" size="1" maxlength="2" name="month" value="'.$month.'">'; $formother->select_year($year ? $year : -1, 'year', 1, 20, 5); print '</td>'; } // Date due - if (!empty($arrayfields['f.date_lim_reglement']['checked'])) - { + if (!empty($arrayfields['f.date_lim_reglement']['checked'])) { print '<td class="liste_titre nowraponall center">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="day_lim" value="'.dol_escape_htmltag($day_lim).'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="day_lim" value="'.dol_escape_htmltag($day_lim).'">'; + } print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="month_lim" value="'.$month_lim.'">'; $formother->select_year($year_lim ? $year_lim : -1, 'year_lim', 1, 20, 5); print '<br><input type="checkbox" name="option" value="late"'.($option == 'late' ? ' checked' : '').'> '.$langs->trans("Late"); print '</td>'; } // Project - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_project" value="'.$search_project.'"></td>'; } // Thirpdarty - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_company" value="'.$search_company.'"></td>'; } // Town - if (!empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_town" value="'.dol_escape_htmltag($search_town).'"></td>'; + if (!empty($arrayfields['s.town']['checked'])) { + print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_town" value="'.dol_escape_htmltag($search_town).'"></td>'; + } // Zip - if (!empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre center"><input class="flat maxwidth50" type="text" name="search_zip" value="'.dol_escape_htmltag($search_zip).'"></td>'; + if (!empty($arrayfields['s.zip']['checked'])) { + print '<td class="liste_titre center"><input class="flat maxwidth50" type="text" name="search_zip" value="'.dol_escape_htmltag($search_zip).'"></td>'; + } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; print '</td>'; } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print '<td class="liste_titre center">'; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print '</td>'; } // Company type - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone center">'; print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); print '</td>'; } // Condition of payment - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) { print '<td class="liste_titre left">'; $form->select_conditions_paiements($search_paymentcond, 'search_paymentcond', -1, 1, 1, 'maxwidth100'); print '</td>'; } // Payment mode - if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { print '<td class="liste_titre left">'; $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 1, 1, 20, 1, 'maxwidth100'); print '</td>'; } - if (!empty($arrayfields['f.total_ht']['checked'])) - { + if (!empty($arrayfields['f.total_ht']['checked'])) { // Amount without tax print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.dol_escape_htmltag($search_montant_ht).'">'; print '</td>'; } - if (!empty($arrayfields['f.total_vat']['checked'])) - { + if (!empty($arrayfields['f.total_vat']['checked'])) { // Amount vat print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.dol_escape_htmltag($search_montant_vat).'">'; print '</td>'; } - if (!empty($arrayfields['f.total_localtax1']['checked'])) - { + if (!empty($arrayfields['f.total_localtax1']['checked'])) { // Amount tax 1 print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_localtax1" value="'.$search_montant_localtax1.'">'; print '</td>'; } - if (!empty($arrayfields['f.total_localtax2']['checked'])) - { + if (!empty($arrayfields['f.total_localtax2']['checked'])) { // Amount tax 2 - print '<td class="liste_titre right">'; + print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_localtax2" value="'.$search_montant_localtax2.'">'; print '</td>'; } - if (!empty($arrayfields['f.total_ttc']['checked'])) - { + if (!empty($arrayfields['f.total_ttc']['checked'])) { // Amount inc tac print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.dol_escape_htmltag($search_montant_ttc).'">'; print '</td>'; } - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { // Author print '<td class="liste_titre" align="center">'; print '<input class="flat" size="4" type="text" name="search_login" value="'.dol_escape_htmltag($search_login).'">'; print '</td>'; } - if (!empty($arrayfields['dynamount_payed']['checked'])) - { + if (!empty($arrayfields['dynamount_payed']['checked'])) { print '<td class="liste_titre right">'; print '</td>'; } - if (!empty($arrayfields['rtp']['checked'])) - { + if (!empty($arrayfields['rtp']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } - if (!empty($arrayfields['f.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_code']['checked'])) { // Currency print '<td class="liste_titre">'; print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1); print '</td>'; } - if (!empty($arrayfields['f.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_tx']['checked'])) { // Currency rate print '<td class="liste_titre">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="'.dol_escape_htmltag($search_multicurrency_tx).'">'; print '</td>'; } - if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="'.dol_escape_htmltag($search_multicurrency_montant_ht).'">'; print '</td>'; } - if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_vat" value="'.dol_escape_htmltag($search_multicurrency_montant_vat).'">'; print '</td>'; } - if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ttc" value="'.dol_escape_htmltag($search_multicurrency_montant_ttc).'">'; print '</td>'; } - if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) - { + if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } - if (!empty($arrayfields['multicurrency_rtp']['checked'])) - { + if (!empty($arrayfields['multicurrency_rtp']['checked'])) { print '<td class="liste_titre right">'; print '</td>'; } @@ -1042,20 +1178,17 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['f.datec']['checked'])) - { + if (!empty($arrayfields['f.datec']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Date modification - if (!empty($arrayfields['f.tms']['checked'])) - { + if (!empty($arrayfields['f.tms']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Status - if (!empty($arrayfields['f.fk_statut']['checked'])) - { + if (!empty($arrayfields['f.fk_statut']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone right">'; $liststatus = array('0'=>$langs->trans("Draft"), '1'=>$langs->trans("Unpaid"), '2'=>$langs->trans("Paid")); print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 0, 0, 0, '', '', 1); @@ -1070,45 +1203,111 @@ if ($resql) print "</tr>\n"; print '<tr class="liste_titre">'; - if (!empty($arrayfields['f.ref']['checked'])) print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER['PHP_SELF'], 'f.ref,f.rowid', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['f.ref_supplier']['label'], $_SERVER["PHP_SELF"], 'f.ref_supplier', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'], $_SERVER["PHP_SELF"], 'f.type', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.label']['checked'])) print_liste_field_titre($arrayfields['f.label']['label'], $_SERVER['PHP_SELF'], "f.libelle,f.rowid", '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.datef']['checked'])) print_liste_field_titre($arrayfields['f.datef']['label'], $_SERVER['PHP_SELF'], 'f.datef,f.rowid', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'], $_SERVER['PHP_SELF'], "f.date_lim_reglement", '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER['PHP_SELF'], "p.ref", '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER['PHP_SELF'], 's.nom', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder, 'center '); - 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, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_cond_reglement", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_mode_reglement", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.total_ht']['checked'])) print_liste_field_titre($arrayfields['f.total_ht']['label'], $_SERVER['PHP_SELF'], 'f.total_ht', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['f.total_vat']['checked'])) print_liste_field_titre($arrayfields['f.total_vat']['label'], $_SERVER['PHP_SELF'], 'f.tva', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'], $_SERVER['PHP_SELF'], 'f.localtax1', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'], $_SERVER['PHP_SELF'], 'f.localtax2', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.total_ttc', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['u.login']['checked'])) print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['f.multicurrency_code']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_code', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_tx']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_tx', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['multicurrency_dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['multicurrency_rtp']['checked'])) print_liste_field_titre($arrayfields['multicurrency_rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['f.ref']['checked'])) { + print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER['PHP_SELF'], 'f.ref,f.rowid', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.ref_supplier']['checked'])) { + print_liste_field_titre($arrayfields['f.ref_supplier']['label'], $_SERVER["PHP_SELF"], 'f.ref_supplier', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.type']['checked'])) { + print_liste_field_titre($arrayfields['f.type']['label'], $_SERVER["PHP_SELF"], 'f.type', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.label']['checked'])) { + print_liste_field_titre($arrayfields['f.label']['label'], $_SERVER['PHP_SELF'], "f.libelle,f.rowid", '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.datef']['checked'])) { + print_liste_field_titre($arrayfields['f.datef']['label'], $_SERVER['PHP_SELF'], 'f.datef,f.rowid', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['f.date_lim_reglement']['checked'])) { + print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'], $_SERVER['PHP_SELF'], "f.date_lim_reglement", '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.ref']['checked'])) { + print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER['PHP_SELF'], "p.ref", '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER['PHP_SELF'], 's.nom', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder, 'center '); + } + 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, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_cond_reglement", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_mode_reglement", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['f.total_ht']['checked'])) { + print_liste_field_titre($arrayfields['f.total_ht']['label'], $_SERVER['PHP_SELF'], 'f.total_ht', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['f.total_vat']['checked'])) { + print_liste_field_titre($arrayfields['f.total_vat']['label'], $_SERVER['PHP_SELF'], 'f.tva', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['f.total_localtax1']['checked'])) { + print_liste_field_titre($arrayfields['f.total_localtax1']['label'], $_SERVER['PHP_SELF'], 'f.localtax1', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['f.total_localtax2']['checked'])) { + print_liste_field_titre($arrayfields['f.total_localtax2']['label'], $_SERVER['PHP_SELF'], 'f.localtax2', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['f.total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['f.total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.total_ttc', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['u.login']['checked'])) { + print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['dynamount_payed']['checked'])) { + print_liste_field_titre($arrayfields['dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['rtp']['checked'])) { + print_liste_field_titre($arrayfields['rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['f.multicurrency_code']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_code', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_tx']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_tx', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) { + print_liste_field_titre($arrayfields['multicurrency_dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['multicurrency_rtp']['checked'])) { + print_liste_field_titre($arrayfields['multicurrency_rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $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['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'], $_SERVER["PHP_SELF"], "fk_statut,paye,type", "", $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['f.datec']['checked'])) { + print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.tms']['checked'])) { + print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_statut']['label'], $_SERVER["PHP_SELF"], "fk_statut,paye,type", "", $param, '', $sortfield, $sortorder, 'right '); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; @@ -1117,12 +1316,10 @@ if ($resql) $projectstatic = new Project($db); $userstatic = new User($db); - if ($num > 0) - { + if ($num > 0) { $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $datelimit = $db->jdate($obj->datelimite); @@ -1176,8 +1373,7 @@ if ($resql) } print '<tr class="oddeven">'; - if (!empty($arrayfields['f.ref']['checked'])) - { + if (!empty($arrayfields['f.ref']['checked'])) { print '<td class="nowrap">'; print '<table class="nobordernopadding"><tr class="nocellnopadd">'; @@ -1192,253 +1388,301 @@ if ($resql) print '</td></tr></table>'; print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Supplier ref - if (!empty($arrayfields['f.ref_supplier']['checked'])) - { + if (!empty($arrayfields['f.ref_supplier']['checked'])) { print '<td class="nowrap tdoverflowmax200">'; print $obj->ref_supplier; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type - if (!empty($arrayfields['f.type']['checked'])) - { + if (!empty($arrayfields['f.type']['checked'])) { print '<td class="nowrap">'; print $facturestatic->getLibType(); print "</td>"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Label - if (!empty($arrayfields['f.label']['checked'])) - { + if (!empty($arrayfields['f.label']['checked'])) { print '<td class="nowrap">'; print $obj->label; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date - if (!empty($arrayfields['f.datef']['checked'])) - { + if (!empty($arrayfields['f.datef']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->datef), 'day'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date limit - if (!empty($arrayfields['f.date_lim_reglement']['checked'])) - { + if (!empty($arrayfields['f.date_lim_reglement']['checked'])) { print '<td class="center nowrap">'.dol_print_date($datelimit, 'day'); - if ($facturestatic->hasDelay()) - { + if ($facturestatic->hasDelay()) { print img_warning($langs->trans('Late')); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Project - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print '<td class="nowrap">'; - if ($obj->project_id > 0) - { + if ($obj->project_id > 0) { $projectstatic->id = $obj->project_id; $projectstatic->ref = $obj->project_ref; $projectstatic->title = $obj->project_label; print $projectstatic->getNomUrl(1); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Third party - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="tdoverflowmax200">'; print $thirdparty->getNomUrl(1, 'supplier'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['s.town']['checked'])) - { + if (!empty($arrayfields['s.town']['checked'])) { print '<td class="nocellnopadd">'; print $obj->town; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { + if (!empty($arrayfields['s.zip']['checked'])) { print '<td class="nocellnopadd center">'; print $obj->zip; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print "<td>".$obj->state_name."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print '<td class="center">'; $tmparray = getCountry($obj->fk_pays, 'all'); print $tmparray['label']; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print '<td class="center">'; - if (empty($typenArray)) $typenArray = $formcompany->typent_array(1); + if (empty($typenArray)) { + $typenArray = $formcompany->typent_array(1); + } print $typenArray[$obj->typent_code]; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Payment condition - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) { print '<td>'; $form->form_conditions_reglement($_SERVER['PHP_SELF'], $obj->fk_cond_reglement, 'none', '', -1); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Payment mode - if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { print '<td>'; $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['f.total_ht']['checked'])) - { + if (!empty($arrayfields['f.total_ht']['checked'])) { print '<td class="right nowrap">'.price($obj->total_ht)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ht'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ht'; + } $totalarray['val']['f.total_ht'] += $obj->total_ht; } // Amount VAT - if (!empty($arrayfields['f.total_vat']['checked'])) - { + if (!empty($arrayfields['f.total_vat']['checked'])) { print '<td class="right nowrap">'.price($obj->total_vat)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_vat'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_vat'; + } $totalarray['val']['f.total_vat'] += $obj->total_vat; } // Amount LocalTax1 - if (!empty($arrayfields['f.total_localtax1']['checked'])) - { + if (!empty($arrayfields['f.total_localtax1']['checked'])) { print '<td class="right nowrap">'.price($obj->total_localtax1)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax1'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax1'; + } $totalarray['val']['f.total_localtax1'] += $obj->total_localtax1; } // Amount LocalTax2 - if (!empty($arrayfields['f.total_localtax2']['checked'])) - { + if (!empty($arrayfields['f.total_localtax2']['checked'])) { print '<td class="right nowrap">'.price($obj->total_localtax2)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax2'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax2'; + } $totalarray['val']['f.total_localtax2'] += $obj->total_localtax2; } // Amount TTC - if (!empty($arrayfields['f.total_ttc']['checked'])) - { + if (!empty($arrayfields['f.total_ttc']['checked'])) { print '<td class="right nowrap">'.price($obj->total_ttc)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ttc'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ttc'; + } $totalarray['val']['f.total_ttc'] += $obj->total_ttc; } // Author - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { $userstatic->id = $obj->fk_user_author; $userstatic->login = $obj->login; print '<td align="center">'; - if ($userstatic->id) print $userstatic->getLoginUrl(1); - else print '&nbsp;'; + if ($userstatic->id) { + print $userstatic->getLoginUrl(1); + } else { + print '&nbsp;'; + } print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['dynamount_payed']['checked'])) - { + if (!empty($arrayfields['dynamount_payed']['checked'])) { print '<td class="right nowrap">'.(!empty($totalpay) ?price($totalpay, 0, $langs) : '&nbsp;').'</td>'; // TODO Use a denormalized field - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalam'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'totalam'; + } $totalarray['val']['totalam'] += $totalpay; } - if (!empty($arrayfields['rtp']['checked'])) - { + if (!empty($arrayfields['rtp']['checked'])) { print '<td class="right nowrap">'.(!empty($remaintopay) ?price($remaintopay, 0, $langs) : '&nbsp;').'</td>'; // TODO Use a denormalized field - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'rtp'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'rtp'; + } $totalarray['val']['rtp'] += $remaintopay; } // Currency - if (!empty($arrayfields['f.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_code']['checked'])) { print '<td class="nowrap">'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Currency rate - if (!empty($arrayfields['f.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_tx']['checked'])) { print '<td class="nowrap">'; $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code); print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_ht)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount VAT - if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_vat)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount TTC - if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_ttc)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) - { + if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) { print '<td class="right nowrap">'.(!empty($multicurrency_totalpay) ?price($multicurrency_totalpay, 0, $langs) : '&nbsp;').'</td>'; // TODO Use a denormalized field - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Pending amount - if (!empty($arrayfields['multicurrency_rtp']['checked'])) - { + if (!empty($arrayfields['multicurrency_rtp']['checked'])) { print '<td class="right nowrap">'; print (!empty($multicurrency_remaintopay) ? price($multicurrency_remaintopay, 0, $langs) : '&nbsp;'); print '</td>'; // TODO Use a denormalized field - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } @@ -1449,40 +1693,46 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['f.datec']['checked'])) - { + if (!empty($arrayfields['f.datec']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['f.tms']['checked'])) - { + if (!empty($arrayfields['f.tms']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['f.fk_statut']['checked'])) - { + if (!empty($arrayfields['f.fk_statut']['checked'])) { print '<td class="right nowrap">'; print $facturestatic->LibStatut($obj->paye, $obj->fk_statut, 5, $paiement, $obj->type); print "</td>"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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->facid, $arrayofselected)) $selected = 1; + if (in_array($obj->facid, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$obj->facid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->facid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; @@ -1505,7 +1755,9 @@ if ($resql) print "</form>\n"; $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/fourn/facture/note.php b/htdocs/fourn/facture/note.php index c98ad3ba1d8..541121031ee 100644 --- a/htdocs/fourn/facture/note.php +++ b/htdocs/fourn/facture/note.php @@ -40,7 +40,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); $object = new FactureFournisseur($db); @@ -56,11 +58,12 @@ $permissionnote = $user->rights->fournisseur->facture->creer; // Used by the inc include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once // Set label -if ($action == 'setlabel' && $user->rights->fournisseur->facture->creer) -{ +if ($action == 'setlabel' && $user->rights->fournisseur->facture->creer) { $object->label = $_POST['label']; $result = $object->update($user); - if ($result < 0) dol_print_error($db); + if ($result < 0) { + dol_print_error($db); + } } @@ -74,8 +77,7 @@ $title = $langs->trans('SupplierInvoice')." - ".$langs->trans('Notes'); $helpurl = "EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Módulo_Facturas_de_proveedores"; llxHeader('', $title, $helpurl); -if ($object->id > 0) -{ +if ($object->id > 0) { $object->fetch_thirdparty(); $alreadypaid = $object->getSommePaiement(); @@ -94,14 +96,14 @@ if ($object->id > 0) $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { // $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; @@ -143,36 +145,34 @@ if ($object->id > 0) // Type print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td>'; print $object->getLibType(); - if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) - { + if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) { $facreplaced = new FactureFournisseur($db); $facreplaced->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; } - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) - { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { $facusing = new FactureFournisseur($db); $facusing->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; } $facidavoir = $object->getListIdAvoirFromInvoice(); - if (count($facidavoir) > 0) - { + if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); $i = 0; - foreach ($facidavoir as $fid) - { - if ($i == 0) print ' '; - else print ','; + foreach ($facidavoir as $fid) { + if ($i == 0) { + print ' '; + } else { + print ','; + } $facavoir = new FactureFournisseur($db); $facavoir->fetch($fid); print $facavoir->getNomUrl(1); } print ')'; } - if ($facidnext > 0) - { + if ($facidnext > 0) { $facthatreplace = new FactureFournisseur($db); $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; @@ -190,14 +190,12 @@ if ($object->id > 0) // Amount Local Taxes //TODO: Place into a function to control showing by country or study better option - if ($societe->localtax1_assuj == "1") //Localtax1 - { + if ($societe->localtax1_assuj == "1") { //Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $societe->country_code).'</td>'; print '<td>'.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; } - if ($societe->localtax2_assuj == "1") //Localtax2 - { + if ($societe->localtax2_assuj == "1") { //Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $societe->country_code).'</td>'; print '<td>'.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; diff --git a/htdocs/fourn/facture/paiement.php b/htdocs/fourn/facture/paiement.php index 0592084f042..104e0e7efd2 100644 --- a/htdocs/fourn/facture/paiement.php +++ b/htdocs/fourn/facture/paiement.php @@ -64,12 +64,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 = "p.rowid"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "p.rowid"; +} $amounts = array(); $amountsresttopay = array(); @@ -79,8 +85,7 @@ $multicurrency_amounts = array(); $multicurrency_amountsresttopay = array(); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $socid = $user->socid; } @@ -103,8 +108,7 @@ $arrayfields = array(); * Actions */ -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_ref = ""; $search_account = ""; $search_amount = ""; @@ -119,12 +123,12 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $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)) -{ - if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes')) - { +if (empty($reshook)) { + if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes')) { $error = 0; $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); @@ -135,10 +139,8 @@ if (empty($reshook)) // Generate payment array and check if there is payment higher than invoice and payment date before invoice date $tmpinvoice = new FactureFournisseur($db); - foreach ($_POST as $key => $value) - { - if (substr($key, 0, 7) == 'amount_') - { + foreach ($_POST as $key => $value) { + if (substr($key, 0, 7) == 'amount_') { $cursorfacid = substr($key, 7); $amounts[$cursorfacid] = price2num(GETPOST($key)); if (!empty($amounts[$cursorfacid])) { @@ -150,19 +152,18 @@ if (empty($reshook)) } } $result = $tmpinvoice->fetch($cursorfacid); - if ($result <= 0) dol_print_error($db); + if ($result <= 0) { + dol_print_error($db); + } $amountsresttopay[$cursorfacid] = price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement()); - if ($amounts[$cursorfacid]) - { + if ($amounts[$cursorfacid]) { // Check amount - if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid]))) - { + if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid]))) { $addwarning = 1; $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPaySupplier")).' '.$langs->trans("HelpPaymentHigherThanReminderToPaySupplier"); } // Check date - if ($datepaye && ($datepaye < $tmpinvoice->date)) - { + if ($datepaye && ($datepaye < $tmpinvoice->date)) { $langs->load("errors"); //$error++; setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings'); @@ -170,26 +171,26 @@ if (empty($reshook)) } $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => $_POST[$key]); - } elseif (substr($key, 0, 21) == 'multicurrency_amount_') - { + } elseif (substr($key, 0, 21) == 'multicurrency_amount_') { $cursorfacid = substr($key, 21); $multicurrency_amounts[$cursorfacid] = (GETPOST($key) ? price2num(GETPOST($key)) : 0); $multicurrency_totalpayment += $multicurrency_amounts[$cursorfacid]; - if (!empty($multicurrency_amounts[$cursorfacid])) $atleastonepaymentnotnull++; + if (!empty($multicurrency_amounts[$cursorfacid])) { + $atleastonepaymentnotnull++; + } $result = $tmpinvoice->fetch($cursorfacid); - if ($result <= 0) dol_print_error($db); + if ($result <= 0) { + dol_print_error($db); + } $multicurrency_amountsresttopay[$cursorfacid] = price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement(1)); - if ($multicurrency_amounts[$cursorfacid]) - { + if ($multicurrency_amounts[$cursorfacid]) { // Check amount - if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid]))) - { + if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid]))) { $addwarning = 1; $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPaySupplier")).' '.$langs->trans("HelpPaymentHigherThanReminderToPaySupplier"); } // Check date - if ($datepaye && ($datepaye < $tmpinvoice->date)) - { + if ($datepaye && ($datepaye < $tmpinvoice->date)) { $langs->load("errors"); //$error++; setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings'); @@ -201,37 +202,31 @@ if (empty($reshook)) } // Check parameters - if ($_POST['paiementid'] <= 0) - { + if ($_POST['paiementid'] <= 0) { setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('PaymentMode')), null, 'errors'); $error++; } - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { // If bank module is on, account is required to enter a payment - if (GETPOST('accountid') <= 0) - { + if (GETPOST('accountid') <= 0) { setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('AccountToCredit')), null, 'errors'); $error++; } } - if (empty($totalpayment) && empty($multicurrency_totalpayment) && empty($atleastonepaymentnotnull)) - { + if (empty($totalpayment) && empty($multicurrency_totalpayment) && empty($atleastonepaymentnotnull)) { setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->trans('PaymentAmount')), null, 'errors'); $error++; } - if (empty($datepaye)) - { + if (empty($datepaye)) { setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('Date')), null, 'errors'); $error++; } // Check if payments in both currency - if ($totalpayment > 0 && $multicurrency_totalpayment > 0) - { + if ($totalpayment > 0 && $multicurrency_totalpayment > 0) { setEventMessages($langs->transnoentities('ErrorPaymentInBothCurrency'), null, 'errors'); $error++; } @@ -240,10 +235,8 @@ if (empty($reshook)) /* * Action add_paiement */ - if ($action == 'add_paiement') - { - if ($error) - { + if ($action == 'add_paiement') { + if ($error) { $action = 'create'; } // All the next of this action is displayed at the page's bottom. @@ -253,30 +246,25 @@ if (empty($reshook)) /* * Action confirm_paiement */ - if ($action == 'confirm_paiement' && $confirm == 'yes') - { + if ($action == 'confirm_paiement' && $confirm == 'yes') { $error = 0; $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); // Clean parameters amount if payment is for a credit note - foreach ($amounts as $key => $value) // How payment is dispatched - { + foreach ($amounts as $key => $value) { // How payment is dispatched $tmpinvoice = new FactureFournisseur($db); $tmpinvoice->fetch($key); - if ($tmpinvoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - { + if ($tmpinvoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) { $newvalue = price2num($value, 'MT'); $amounts[$key] = - abs($newvalue); } } - foreach ($multicurrency_amounts as $key => $value) // How payment is dispatched - { + foreach ($multicurrency_amounts as $key => $value) { // How payment is dispatched $tmpinvoice = new FactureFournisseur($db); $tmpinvoice->fetch($key); - if ($tmpinvoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - { + if ($tmpinvoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) { $newvalue = price2num($value, 'MT'); $multicurrency_amounts[$key] = - abs($newvalue); } @@ -286,12 +274,13 @@ if (empty($reshook)) //var_dump($multicurrency_amounts); //exit; - if (!$error) - { + if (!$error) { $db->begin(); $thirdparty = new Societe($db); - if ($socid > 0) $thirdparty->fetch($socid); + if ($socid > 0) { + $thirdparty->fetch($socid); + } // Creation of payment line $paiement = new PaiementFourn($db); @@ -305,43 +294,42 @@ if (empty($reshook)) $paiement->num_payment = $paiement->num_payment; $paiement->note_private = $paiement->note_private; - if (!$error) - { + if (!$error) { $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices') == 'on' ? 1 : 0), $thirdparty); - if ($paiement_id < 0) - { + if ($paiement_id < 0) { setEventMessages($paiement->error, $paiement->errors, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { $result = $paiement->addPaymentToBank($user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, '', ''); - if ($result < 0) - { + if ($result < 0) { setEventMessages($paiement->error, $paiement->errors, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { $db->commit(); // If payment dispatching on more than one invoice, we stay on summary page, otherwise go on invoice card $invoiceid = 0; - foreach ($paiement->amounts as $key => $amount) - { + foreach ($paiement->amounts as $key => $amount) { $facid = $key; - if (is_numeric($amount) && $amount <> 0) - { - if ($invoiceid != 0) $invoiceid = -1; // There is more than one invoice payed by this payment - else $invoiceid = $facid; + if (is_numeric($amount) && $amount <> 0) { + if ($invoiceid != 0) { + $invoiceid = -1; // There is more than one invoice payed by this payment + } else { + $invoiceid = $facid; + } } } - if ($invoiceid > 0) $loc = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$invoiceid; - else $loc = DOL_URL_ROOT.'/fourn/paiement/card.php?id='.$paiement_id; + if ($invoiceid > 0) { + $loc = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$invoiceid; + } else { + $loc = DOL_URL_ROOT.'/fourn/paiement/card.php?id='.$paiement_id; + } header('Location: '.$loc); exit; } else { @@ -364,8 +352,7 @@ $invoicesupplierstatic = new FactureFournisseur($db); llxHeader('', $langs->trans('ListPayment')); -if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paiement') -{ +if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paiement') { $object = new FactureFournisseur($db); $result = $object->fetch($facid); @@ -374,26 +361,29 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $sql = 'SELECT s.nom as name, s.rowid as socid,'; $sql .= ' f.rowid, f.ref, f.ref_supplier, f.total_ttc as total, f.fk_mode_reglement, f.fk_account'; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s, '.MAIN_DB_PREFIX.'facture_fourn as f'; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= ' WHERE f.fk_soc = s.rowid'; $sql .= ' AND f.rowid = '.$facid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $obj = $db->fetch_object($resql); $total = $obj->total; print load_fiche_titre($langs->trans('DoPayment')); // Add realtime total information - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print "\n".'<script type="text/javascript" language="javascript">'; print '$(document).ready(function () { @@ -491,8 +481,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print '<tr><td class="fieldrequired">'.$langs->trans('PaymentMode').'</td><td>'; $form->select_types_paiements(empty($_POST['paiementid']) ? $obj->fk_mode_reglement : $_POST['paiementid'], 'paiementid'); print '</td>'; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print '<tr><td class="fieldrequired">'.$langs->trans('Account').'</td><td>'; $form->select_comptes(empty($accountid) ? $obj->fk_account : $accountid, 'accountid', 0, '', 2); print '</td></tr>'; @@ -510,11 +499,10 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $parameters = array('facid'=>$facid, 'ref'=>$ref, 'objcanvas'=>$objcanvas); $reshook = $hookmanager->executeHooks('paymentsupplierinvoices', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $error = $hookmanager->error; $errors = $hookmanager->errors; - if (empty($reshook)) - { + if (empty($reshook)) { /* - * All unpaid supplier invoices - */ + * All unpaid supplier invoices + */ $sql = 'SELECT f.rowid as facid, f.ref, f.ref_supplier, f.type, f.total_ht, f.total_ttc,'; $sql .= ' f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc,'; $sql .= ' f.datef as df, f.date_lim_reglement as dlr,'; @@ -525,8 +513,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $sql .= ' AND f.fk_soc = '.$object->socid; $sql .= ' AND f.paye = 0'; $sql .= ' AND f.fk_statut = 1'; // Status=0 => unvalidated, Status=2 => canceled - if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) - { + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) { $sql .= ' AND f.type IN (0,1,3,5)'; // Standard invoice, replacement, deposit, situation } else { $sql .= ' AND f.type = 2'; // If paying back a credit note, we show all credit notes @@ -537,11 +524,9 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $sql .= ' ORDER BY f.datef ASC, f.ref ASC'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { $i = 0; print '<br>'; @@ -582,12 +567,13 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $total = 0; $total_ttc = 0; $totalrecu = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $sign = 1; - if ($objp->type == FactureFournisseur::TYPE_CREDIT_NOTE) $sign = -1; + if ($objp->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + $sign = -1; + } $invoice = new FactureFournisseur($db); $invoice->fetch($objp->facid); @@ -629,13 +615,11 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } // Date Max Payment - if ($objp->dlr > 0) - { + if ($objp->dlr > 0) { print '<td class="center nowraponall">'; print dol_print_date($db->jdate($objp->dlr), 'day'); - if ($invoice->hasDelay()) - { + if ($invoice->hasDelay()) { print img_warning($langs->trans('Late')); } @@ -645,28 +629,24 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { // Currency print '<td class="center">'.$objp->multicurrency_code."</td>\n"; print '<td class="right">'; - if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) - { + if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) { print price($objp->multicurrency_total_ttc); } print '</td>'; print '<td class="right">'; - if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) - { + if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) { print price($objp->multicurrency_am); } print '</td>'; print '<td class="right">'; - if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) - { + if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) { print price($objp->multicurrency_total_ttc - $objp->multicurrency_am); } print '</td>'; @@ -675,8 +655,12 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print '<td class="right">'.price($sign * $objp->total_ttc).'</td>'; print '<td class="right">'.price($sign * $objp->am); - if ($creditnotes) print '+'.price($creditnotes); - if ($deposits) print '+'.price($deposits); + if ($creditnotes) { + print '+'.price($creditnotes); + } + if ($deposits) { + print '+'.price($deposits); + } print '</td>'; print '<td class="right">'.price($sign * $remaintopay).'</td>'; @@ -687,10 +671,10 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $namef = 'amount_'.$objp->facid; $nameRemain = 'remain_'.$objp->facid; - if ($action != 'add_paiement') - { - if (!empty($conf->use_javascript_ajax)) + if ($action != 'add_paiement') { + if (!empty($conf->use_javascript_ajax)) { print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $remaintopay)."'"); + } print '<input type="hidden" class="remain" name="'.$nameRemain.'" value="'.$remaintopay.'">'; print '<input type="text" size="8" class="amount" name="'.$namef.'" value="'.dol_escape_htmltag(GETPOST($namef)).'">'; // class is requied to be used by javascript callForResult(); } else { @@ -700,20 +684,18 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print "</td>"; // Multicurrency Price - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<td class="right">'; // Add remind multicurrency amount $namef = 'multicurrency_amount_'.$objp->facid; $nameRemain = 'multicurrency_remain_'.$objp->facid; - if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) - { - if ($action != 'add_paiement') - { - if (!empty($conf->use_javascript_ajax)) + if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) { + if ($action != 'add_paiement') { + if (!empty($conf->use_javascript_ajax)) { print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $multicurrency_remaintopay)."'"); + } print '<input type=hidden class="multicurrency_remain" name="'.$nameRemain.'" value="'.$multicurrency_remaintopay.'">'; print '<input type="text" size="8" class="multicurrency_amount" name="'.$namef.'" value="'.$_POST[$namef].'">'; } else { @@ -744,8 +726,12 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } print '<td class="right"><b>'.price($sign * $total_ttc).'</b></td>'; print '<td class="right"><b>'.price($sign * $totalrecu); - if ($totalrecucreditnote) print '+'.price($totalrecucreditnote); - if ($totalrecudeposits) print '+'.price($totalrecudeposits); + if ($totalrecucreditnote) { + print '+'.price($totalrecucreditnote); + } + if ($totalrecudeposits) { + print '+'.price($totalrecudeposits); + } print '</b></td>'; print '<td class="right"><b>'.price($sign * price2num($total_ttc - $totalrecu - $totalrecucreditnote - $totalrecudeposits, 'MT')).'</b></td>'; print '<td class="center" id="result" style="font-weight: bold;"></td>'; // Autofilled @@ -765,25 +751,23 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } // Save Button - if ($action != 'add_paiement') - { + if ($action != 'add_paiement') { print '<br><div class="center"><input type="checkbox" checked name="closepaidinvoices"> '.$langs->trans("ClosePaidInvoicesAutomatically"); print '<br><input type="submit" class="button" value="'.$langs->trans('ToMakePayment').'"></div>'; } // Form to confirm payment - if ($action == 'add_paiement') - { + if ($action == 'add_paiement') { $preselectedchoice = $addwarning ? 'no' : 'yes'; print '<br>'; - if (!empty($totalpayment)) $text = $langs->trans('ConfirmSupplierPayment', price($totalpayment), $langs->trans("Currency".$conf->currency)); - if (!empty($multicurrency_totalpayment)) - { + if (!empty($totalpayment)) { + $text = $langs->trans('ConfirmSupplierPayment', price($totalpayment), $langs->trans("Currency".$conf->currency)); + } + if (!empty($multicurrency_totalpayment)) { $text .= '<br>'.$langs->trans('ConfirmSupplierPayment', price($multicurrency_totalpayment), $langs->trans("paymentInInvoiceCurrency")); } - if (GETPOST('closepaidinvoices')) - { + if (GETPOST('closepaidinvoices')) { $text .= '<br>'.$langs->trans("AllCompletelyPayedInvoiceWillBeClosed"); print '<input type="hidden" name="closepaidinvoices" value="'.GETPOST('closepaidinvoices').'">'; } diff --git a/htdocs/fourn/facture/rapport.php b/htdocs/fourn/facture/rapport.php index 9ae7970d7db..fe2bb78008d 100644 --- a/htdocs/fourn/facture/rapport.php +++ b/htdocs/fourn/facture/rapport.php @@ -32,36 +32,39 @@ $langs->loadLangs(array('bills')); // Security check $socid = ''; -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); $action = GETPOST('action', 'aZ09'); $socid = 0; -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } $dir = $conf->fournisseur->facture->dir_output.'/payments'; -if (!$user->rights->societe->client->voir || $socid) $dir .= '/private/'.$user->id; // If user has no permission to see all, output dir is specific to user +if (!$user->rights->societe->client->voir || $socid) { + $dir .= '/private/'.$user->id; // If user has no permission to see all, output dir is specific to user +} $year = GETPOST("year", 'int'); -if (!$year) { $year = date("Y"); } +if (!$year) { + $year = date("Y"); +} /* * Actions */ -if ($action == 'builddoc') -{ +if ($action == 'builddoc') { $rap = new pdf_paiement_fourn($db); $outputlangs = $langs; - if (GETPOST('lang_id', 'aZ09')) - { + if (GETPOST('lang_id', 'aZ09')) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang(GETPOST('lang_id', 'aZ09')); } @@ -69,8 +72,7 @@ if ($action == 'builddoc') // We save charset_output to restore it because write_file can change it if needed for // output format that does not support UTF8. $sav_charset_output = $outputlangs->charset_output; - if ($rap->write_file($dir, GETPOST("remonth", 'int'), GETPOST("reyear", 'int'), $outputlangs) > 0) - { + if ($rap->write_file($dir, GETPOST("remonth", 'int'), GETPOST("reyear", 'int'), $outputlangs) > 0) { $outputlangs->charset_output = $sav_charset_output; } else { $outputlangs->charset_output = $sav_charset_output; @@ -114,15 +116,11 @@ clearstatcache(); // Show link on other years $linkforyear = array(); $found = 0; -if (is_dir($dir)) -{ +if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (is_dir($dir.'/'.$file) && !preg_match('/^\./', $file) && is_numeric($file)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (is_dir($dir.'/'.$file) && !preg_match('/^\./', $file) && is_numeric($file)) { $found = 1; $linkforyear[] = $file; } @@ -130,18 +128,17 @@ if (is_dir($dir)) } } asort($linkforyear); -foreach ($linkforyear as $cursoryear) -{ +foreach ($linkforyear as $cursoryear) { print '<a href="'.$_SERVER["PHP_SELF"].'?year='.$cursoryear.'">'.$cursoryear.'</a> &nbsp;'; } -if ($year) -{ - if (is_dir($dir.'/'.$year)) - { +if ($year) { + if (is_dir($dir.'/'.$year)) { $handle = opendir($dir.'/'.$year); - if ($found) print '<br>'; + if ($found) { + print '<br>'; + } print '<br>'; print '<table width="100%" class="noborder">'; print '<tr class="liste_titre">'; @@ -150,12 +147,9 @@ if ($year) print '<td class="right">'.$langs->trans("Date").'</td>'; print '</tr>'; - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/^supplier_payment/i', $file)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/^supplier_payment/i', $file)) { $tfile = $dir.'/'.$year.'/'.$file; $relativepath = $year.'/'.$file; print '<tr class="oddeven"><td><a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart=facture_fournisseur&amp;file=payments/'.urlencode($relativepath).'">'.img_pdf().' '.$file.'</a>'.$formfile->showPreview($file, 'facture_fournisseur', 'payments/'.$relativepath, 0).'</td>'; diff --git a/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php b/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php index 4456d27c539..c3ca301ed45 100644 --- a/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php +++ b/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php @@ -19,8 +19,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -38,24 +37,26 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; $langs->load("bills"); $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - <tr class="<?php echo $trclass; ?>"> - <td><?php echo $langs->trans("SupplierInvoice"); ?></td> - <td><a href="<?php echo DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$objectlink->id ?>"><?php echo img_object($langs->trans("ShowBill"), "bill").' '.$objectlink->ref; ?></a></td> - <td class="left"><?php echo $objectlink->ref_supplier; ?></td> - <td class="center"><?php echo dol_print_date($objectlink->date, 'day'); ?></td> - <td class="right"><?php + <tr class="<?php echo $trclass; ?>"> + <td><?php echo $langs->trans("SupplierInvoice"); ?></td> + <td><a href="<?php echo DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$objectlink->id ?>"><?php echo img_object($langs->trans("ShowBill"), "bill").' '.$objectlink->ref; ?></a></td> + <td class="left"><?php echo $objectlink->ref_supplier; ?></td> + <td class="center"><?php echo dol_print_date($objectlink->date, 'day'); ?></td> + <td class="right"><?php if ($user->rights->fournisseur->facture->lire) { $sign = 1; - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $sign = -1; - if ($objectlink->statut != 3) - { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + $sign = -1; + } + if ($objectlink->statut != 3) { // If not abandonned $total = $total + $sign * $objectlink->total_ht; echo price($objectlink->total_ht); @@ -63,24 +64,23 @@ foreach ($linkedObjectBlock as $key => $objectlink) echo '<strike>'.price($objectlink->total_ht).'</strike>'; } } ?></td> - <td class="right"><?php echo $objectlink->getLibStatut(3); ?></td> - <td class="right"><a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a></td> - </tr> - <?php + <td class="right"><?php echo $objectlink->getLibStatut(3); ?></td> + <td class="right"><a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a></td> + </tr> + <?php } -if (count($linkedObjectBlock) > 1) -{ +if (count($linkedObjectBlock) > 1) { ?> - <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> - <td><?php echo $langs->trans("Total"); ?></td> - <td></td> - <td class="center"></td> - <td class="center"></td> - <td class="right"><?php echo price($total); ?></td> - <td class="right"></td> - <td class="right"></td> - </tr> - <?php + <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> + <td><?php echo $langs->trans("Total"); ?></td> + <td></td> + <td class="center"></td> + <td class="center"></td> + <td class="right"><?php echo price($total); ?></td> + <td class="right"></td> + <td class="right"></td> + </tr> + <?php } print "<!-- END PHP TEMPLATE -->\n"; diff --git a/htdocs/fourn/index.php b/htdocs/fourn/index.php index 5d82021bf3c..54ed40e37b0 100644 --- a/htdocs/fourn/index.php +++ b/htdocs/fourn/index.php @@ -32,7 +32,9 @@ $langs->loadLangs(array("suppliers", "orders", "companies")); // Security check $socid = GETPOST("socid", 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'societe', $socid, ''); @@ -58,15 +60,18 @@ print '<div class="fichecenter"><div class="fichethirdleft">'; $sql = "SELECT count(cf.rowid), cf.fk_statut"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf,"; $sql .= " ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; +} $sql .= " WHERE cf.fk_soc = s.rowid "; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND sc.fk_user = ".$user->id; +} $sql .= " AND cf.entity = ".$conf->entity; $sql .= " GROUP BY cf.fk_statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -74,8 +79,7 @@ if ($resql) print '<tr class="liste_titre"><td>'.$langs->trans("Orders").'</td><td class="center">'.$langs->trans("Nb").'</td><td>&nbsp;</td>'; print "</tr>\n"; - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); print '<tr class="oddeven">'; @@ -95,35 +99,37 @@ if ($resql) // Draft orders -if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) -{ +if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) { $langs->load("orders"); $sql = "SELECT cf.rowid, cf.ref, cf.total_ttc,"; $sql .= " s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + } $sql .= " WHERE cf.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND sc.fk_user = ".$user->id; + } $sql .= " AND cf.entity = ".$conf->entity; $sql .= " AND cf.fk_statut = 0"; - if ($socid) $sql .= " AND cf.fk_soc = ".$socid; + if ($socid) { + $sql .= " AND cf.fk_soc = ".$socid; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $total = 0; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<td colspan="3">'.$langs->trans("DraftOrders").'<span class="badge marginleftonlyshort">'.$num.'</span></td></tr>'; $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven"><td class="nowrap">'; @@ -141,8 +147,7 @@ if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUP $i++; $total += $obj->total_ttc; } - if ($total > 0) - { + if ($total > 0) { print '<tr class="liste_total"><td>'.$langs->trans("Total").'</td><td colspan="2" class="right">'.price($total)."</td></tr>"; } print "</table>"; @@ -152,34 +157,36 @@ if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUP } // Draft invoices -if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) -{ +if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) { $sql = "SELECT ff.ref_supplier, ff.rowid, ff.total_ttc, ff.type"; $sql .= ", s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as ff"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + } $sql .= " WHERE s.rowid = ff.fk_soc"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND sc.fk_user = ".$user->id; + } $sql .= " AND ff.entity = ".$conf->entity; $sql .= " AND ff.fk_statut = 0"; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<td colspan="3">'.$langs->trans("DraftBills").'<span class="badge marginleftonlyshort">'.$num.'</span></td></tr>'; $i = 0; $tot_ttc = 0; - while ($i < $num && $i < 20) - { + while ($i < $num && $i < 20) { $obj = $db->fetch_object($resql); print '<tr class="oddeven"><td class="nowrap">'; @@ -226,18 +233,23 @@ $sql = "SELECT s.rowid as socid, s.nom as name, s.town, s.datec, s.tms, s.prefix $sql .= ", st.libelle as stcomm"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."c_stcomm as st"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE s.fk_stcomm = st.id"; $sql .= " AND s.fournisseur = 1"; $sql .= " AND s.entity IN (".getEntity('societe').")"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND s.rowid = ".$socid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} $sql .= " ORDER BY s.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $langs->load("boxes"); $num = $db->num_rows($resql); $i = 0; @@ -248,8 +260,7 @@ if ($resql) print '<td class="right">'.$langs->trans("DateModification")."</td>\n"; print "</tr>\n"; - while ($obj = $db->fetch_object($resql)) - { + while ($obj = $db->fetch_object($resql)) { print '<tr class="oddeven">'; print '<td><a href="card.php?socid='.$obj->socid.'">'.img_object($langs->trans("ShowSupplier"), "company").'</a>'; print "&nbsp;<a href=\"card.php?socid=".$obj->socid."\">".$obj->name."</a></td>\n"; @@ -271,8 +282,7 @@ if ($resql) $companystatic->LoadSupplierCateg(); $categstatic = new Categorie($db); -if (count($companystatic->SupplierCategories)) -{ +if (count($companystatic->SupplierCategories)) { print '<br>'; print '<table class="liste centpercent">'; @@ -280,8 +290,7 @@ if (count($companystatic->SupplierCategories)) print $langs->trans("Category"); print "</td></tr>\n"; - foreach ($companystatic->SupplierCategories as $rowid => $label) - { + foreach ($companystatic->SupplierCategories as $rowid => $label) { print '<tr class="oddeven">'."\n"; print '<td>'; $categstatic->id = $rowid; diff --git a/htdocs/fourn/js/lib_dispatch.js.php b/htdocs/fourn/js/lib_dispatch.js.php index b4090e8a34d..fd15894b4ec 100644 --- a/htdocs/fourn/js/lib_dispatch.js.php +++ b/htdocs/fourn/js/lib_dispatch.js.php @@ -21,13 +21,27 @@ * \brief File that include javascript functions used for dispatching qty/stock/lot */ -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); -if (!defined('NOLOGIN')) define('NOLOGIN', 1); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', 1); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', 1); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', 1); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', 1); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', 1); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} session_cache_limiter('public'); @@ -36,8 +50,11 @@ require_once '../../main.inc.php'; // Define javascript type top_httphead('text/javascript; charset=UTF-8'); // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. -if (empty($dolibarr_nocache)) header('Cache-Control: max-age=10800, public, must-revalidate'); -else header('Cache-Control: no-cache'); +if (empty($dolibarr_nocache)) { + header('Cache-Control: max-age=10800, public, must-revalidate'); +} else { + header('Cache-Control: no-cache'); +} ?> /** @@ -76,9 +93,7 @@ function addDispatchLine(index, type, mode) if (qtyOrdered <= 1) { window.alert("Quantity can't be split"); - } - if (qtyDispatched < qtyOrdered) - { + } else if (qtyDispatched < qtyOrdered) { //replace tr suffix nbr $row.html($row.html().replace(/_0_/g,"_"+nbrTrs+"_")); //create new select2 to avoid duplicate id of cloned one diff --git a/htdocs/fourn/paiement/card.php b/htdocs/fourn/paiement/card.php index 355b84796f2..f061385c5bb 100644 --- a/htdocs/fourn/paiement/card.php +++ b/htdocs/fourn/paiement/card.php @@ -39,24 +39,35 @@ $action = GETPOST('action', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); $object = new PaiementFourn($db); +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('supplierpaymentcard', 'globalcard')); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. + +$result = restrictedArea($user, $object->element, $object->id, 'paiementfourn', ''); + +// Security check +if ($user->socid) { + $socid = $user->socid; +} +// Now check also permission on thirdparty of invoices of payments. Thirdparty were loaded by the fetch_object before based on first invoice. +// It should be enough because all payments are done on invoices of the same thirdparty. +if ($socid && $socid != $object->thirdparty->id) { + accessforbidden(); +} -// PDF -$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); -$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); -$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); /* * Actions */ -if ($action == 'setnote' && $user->rights->fournisseur->facture->creer) -{ +if ($action == 'setnote' && $user->rights->fournisseur->facture->creer) { $db->begin(); $object->fetch($id); $result = $object->update_note(GETPOST('note', 'restricthtml')); - if ($result > 0) - { + if ($result > 0) { $db->commit(); $action = ''; } else { @@ -65,14 +76,12 @@ if ($action == 'setnote' && $user->rights->fournisseur->facture->creer) } } -if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->facture->supprimer) -{ +if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->facture->supprimer) { $db->begin(); $object->fetch($id); $result = $object->delete(); - if ($result > 0) - { + if ($result > 0) { $db->commit(); header('Location: '.DOL_URL_ROOT.'/fourn/paiement/list.php'); exit; @@ -85,13 +94,11 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisse if ($action == 'confirm_validate' && $confirm == 'yes' && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->facture->creer)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate))) -) -{ +) { $db->begin(); $object->fetch($id); - if ($object->validate() >= 0) - { + if ($object->validate() >= 0) { $db->commit(); header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); exit; @@ -101,25 +108,21 @@ if ($action == 'confirm_validate' && $confirm == 'yes' && } } -if ($action == 'setnum_paiement' && !empty($_POST['num_paiement'])) -{ +if ($action == 'setnum_paiement' && !empty($_POST['num_paiement'])) { $object->fetch($id); $res = $object->update_num($_POST['num_paiement']); - if ($res === 0) - { + if ($res === 0) { setEventMessages($langs->trans('PaymentNumberUpdateSucceeded'), null, 'mesgs'); } else { setEventMessages($langs->trans('PaymentNumberUpdateFailed'), null, 'errors'); } } -if ($action == 'setdatep' && !empty($_POST['datepday'])) -{ +if ($action == 'setdatep' && !empty($_POST['datepday'])) { $object->fetch($id); $datepaye = dol_mktime(GETPOST('datephour', 'int'), GETPOST('datepmin', 'int'), GETPOST('datepsec', 'int'), GETPOST('datepmonth', 'int'), GETPOST('datepday', 'int'), GETPOST('datepyear', 'int')); $res = $object->update_date($datepaye); - if ($res === 0) - { + if ($res === 0) { setEventMessages($langs->trans('PaymentDateUpdateSucceeded'), null, 'mesgs'); } else { setEventMessages($langs->trans('PaymentDateUpdateFailed'), null, 'errors'); @@ -148,21 +151,18 @@ $head = payment_supplier_prepare_head($object); print dol_get_fiche_head($head, 'payment', $langs->trans('SupplierPayment'), -1, 'payment'); -if ($result > 0) -{ +if ($result > 0) { /* * Confirmation of payment's delete */ - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete'); } /* * Confirmation of payment's validation */ - if ($action == 'validate') - { + if ($action == 'validate') { print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_validate'); } @@ -177,53 +177,54 @@ if ($result > 0) print '<table class="border centpercent">'; /*print '<tr>'; - print '<td width="20%" colspan="2">'.$langs->trans('Ref').'</td><td colspan="3">'; - print $form->showrefnav($object,'id','',1,'rowid','ref'); + print '<td width="20%">'.$langs->trans('Ref').'</td><td>'; + print $form->showrefnav($object,'id','',1,'rowid','ref'); print '</td></tr>';*/ // Date of payment - print '<tr><td class="titlefield" colspan="2">'.$form->editfieldkey("Date", 'datep', $object->date, $object, $object->statut == 0 && $user->rights->fournisseur->facture->creer).'</td><td colspan="3">'; + print '<tr><td class="titlefield">'.$form->editfieldkey("Date", 'datep', $object->date, $object, $object->statut == 0 && $user->rights->fournisseur->facture->creer).'</td>'; + print '<td>'; print $form->editfieldval("Date", 'datep', $object->date, $object, $object->statut == 0 && $user->rights->fournisseur->facture->creer, 'datehourpicker', '', null, $langs->trans('PaymentDateUpdateSucceeded')); print '</td></tr>'; // Payment mode $labeltype = $langs->trans("PaymentType".$object->type_code) != ("PaymentType".$object->type_code) ? $langs->trans("PaymentType".$object->type_code) : $object->type_label; - print '<tr><td colspan="2">'.$langs->trans('PaymentMode').'</td><td colspan="3">'.$labeltype; + print '<tr><td>'.$langs->trans('PaymentMode').'</td>'; + print '<td>'.$labeltype; print $object->num_payment ? ' - '.$object->num_payment : ''; print '</td></tr>'; // Payment numero /* TODO Add field num_payment into payment table and save it - print '<tr><td colspan="2">'.$form->editfieldkey("Numero",'num_paiement',$object->num_paiement,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).'</td><td colspan="3">'; + print '<tr><td>'.$form->editfieldkey("Numero",'num_paiement',$object->num_paiement,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).'</td>'; + print '<td>'; print $form->editfieldval("Numero",'num_paiement',$object->num_paiement,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('PaymentNumberUpdateSucceeded')); print '</td></tr>'; - */ + */ // Amount - print '<tr><td colspan="2">'.$langs->trans('Amount').'</td><td colspan="3">'.price($object->amount, '', $langs, 0, 0, -1, $conf->currency).'</td></tr>'; + print '<tr><td>'.$langs->trans('Amount').'</td>'; + print '<td>'.price($object->amount, '', $langs, 0, 0, -1, $conf->currency).'</td></tr>'; - if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) - { - print '<tr><td colspan="2">'.$langs->trans('Status').'</td><td colspan="3">'.$object->getLibStatut(4).'</td></tr>'; + if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) { + print '<tr><td>'.$langs->trans('Status').'</td>'; + print '<td>'.$object->getLibStatut(4).'</td></tr>'; } $allow_delete = 1; // Bank account - if (!empty($conf->banque->enabled)) - { - if ($object->bank_account) - { + if (!empty($conf->banque->enabled)) { + if ($object->fk_account) { $bankline = new AccountLine($db); $bankline->fetch($object->bank_line); - if ($bankline->rappro) - { + if ($bankline->rappro) { $allow_delete = 0; $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemoveConciliatedPayment")); } print '<tr>'; - print '<td colspan="2">'.$langs->trans('BankAccount').'</td>'; - print '<td colspan="3">'; + print '<td>'.$langs->trans('BankAccount').'</td>'; + print '<td>'; $accountstatic = new Account($db); $accountstatic->fetch($bankline->fk_account); print $accountstatic->getNomUrl(1); @@ -231,8 +232,8 @@ if ($result > 0) print '</tr>'; print '<tr>'; - print '<td colspan="2">'.$langs->trans('BankTransactionLine').'</td>'; - print '<td colspan="3">'; + print '<td>'.$langs->trans('BankTransactionLine').'</td>'; + print '<td>'; print $bankline->getNomUrl(1, 0, 'showconciliated'); print '</td>'; print '</tr>'; @@ -240,7 +241,8 @@ if ($result > 0) } // Note - print '<tr><td colspan="2">'.$form->editfieldkey("Note", 'note', $object->note, $object, $user->rights->fournisseur->facture->creer).'</td><td colspan="3">'; + print '<tr><td>'.$form->editfieldkey("Comments", 'note', $object->note, $object, $user->rights->fournisseur->facture->creer).'</td>'; + print '<td>'; print $form->editfieldval("Note", 'note', $object->note, $object, $user->rights->fournisseur->facture->creer, 'textarea'); print '</td></tr>'; @@ -259,8 +261,7 @@ if ($result > 0) $sql .= ' WHERE pf.fk_facturefourn = f.rowid AND f.fk_soc = s.rowid'; $sql .= ' AND pf.fk_paiementfourn = '.$object->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -276,12 +277,10 @@ if ($result > 0) print '<td class="right">'.$langs->trans('Status').'</td>'; print "</tr>\n"; - if ($num > 0) - { + if ($num > 0) { $facturestatic = new FactureFournisseur($db); - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $facturestatic->id = $objp->facid; @@ -311,8 +310,7 @@ if ($result > 0) print '<td class="right">'.$facturestatic->LibStatut($objp->paye, $objp->status, 6, 1).'</td>'; print "</tr>\n"; - if ($objp->paye == 1) - { + if ($objp->paye == 1) { $allow_delete = 0; $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemovePaymentWithOneInvoicePaid")); } @@ -336,23 +334,17 @@ if ($result > 0) */ print '<div class="tabsAction">'; - if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) - { - if ($user->socid == 0 && $object->statut == 0 && $action == '') - { + if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) { + if ($user->socid == 0 && $object->statut == 0 && $action == '') { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->facture->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate))) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=validate">'.$langs->trans('Valid').'</a>'; } } } - if ($user->socid == 0 && $action == '') - { - if ($user->rights->fournisseur->facture->supprimer) - { - if ($allow_delete) - { + if ($user->socid == 0 && $action == '') { + if ($user->rights->fournisseur->facture->supprimer) { + if ($allow_delete) { print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.$title_button.'">'.$langs->trans('Delete').'</a>'; @@ -364,12 +356,10 @@ if ($result > 0) print '<div class="fichecenter"><div class="fichehalfleft">'; - // Documents generes - + // Generated documents include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php'; $modellist = ModelePDFSuppliersPayments::liste_modeles($db); - if (is_array($modellist)) - { + if (is_array($modellist)) { $ref = dol_sanitizeFileName($object->ref); $filedir = $conf->fournisseur->payment->dir_output.'/'.dol_sanitizeFileName($object->ref); $urlsource = $_SERVER['PHP_SELF'].'?id='.$object->id; diff --git a/htdocs/fourn/paiement/info.php b/htdocs/fourn/paiement/info.php index 97ac2343c23..8032b2b418f 100644 --- a/htdocs/fourn/paiement/info.php +++ b/htdocs/fourn/paiement/info.php @@ -33,8 +33,28 @@ $langs->loadLangs(array("bills", "suppliers", "companies")); $id = GETPOST('id', 'int'); $object = new PaiementFourn($db); -$object->fetch($id); -$object->info($id); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. + +$result = restrictedArea($user, $object->element, $object->id, 'paiementfourn', ''); + +// Security check +if ($user->socid) { + $socid = $user->socid; +} +// Now check also permission on thirdparty of invoices of payments. Thirdparty were loaded by the fetch_object before based on first invoice. +// It should be enough because all payments are done on invoices of the same thirdparty. +if ($socid && $socid != $object->thirdparty->id) { + accessforbidden(); +} + + +/* + * Actions + */ + +// None /* @@ -43,10 +63,14 @@ $object->info($id); llxHeader(); +$object->info($id); + $head = payment_supplier_prepare_head($object); print dol_get_fiche_head($head, 'info', $langs->trans("SupplierPayment"), 0, 'payment'); +$linkback = '<a href="'.DOL_URL_ROOT.'/fourn/paiement/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; + dol_banner_tab($object, 'id', $linkback, -1, 'rowid', 'ref'); print dol_get_fiche_end(); diff --git a/htdocs/fourn/paiement/list.php b/htdocs/fourn/paiement/list.php index 3fca286eff0..02adee36149 100644 --- a/htdocs/fourn/paiement/list.php +++ b/htdocs/fourn/paiement/list.php @@ -35,7 +35,9 @@ require '../../main.inc.php'; // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} // doesn't work :-( // restrictedArea($user, 'fournisseur'); @@ -78,13 +80,19 @@ $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 = "p.datep"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "p.datep"; +} $search_all = trim(GETPOSTISSET("search_all") ? GETPOST("search_all", 'alpha') : GETPOST('sall')); @@ -117,7 +125,9 @@ $object = new PaiementFourn($db); $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)) { include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; @@ -150,7 +160,9 @@ $sql = 'SELECT p.rowid, p.ref, p.datep, p.amount as pamount, p.num_paiement'; $sql .= ', s.rowid as socid, s.nom as name, s.email'; $sql .= ', c.code as paiement_type, c.libelle as paiement_libelle'; $sql .= ', ba.rowid as bid, ba.label'; -if (!$user->rights->societe->client->voir) $sql .= ', sc.fk_soc, sc.fk_user'; +if (!$user->rights->societe->client->voir) { + $sql .= ', sc.fk_soc, sc.fk_user'; +} $sql .= ', SUM(pf.amount)'; $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn AS p'; @@ -160,26 +172,48 @@ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement AS c ON p.fk_paiement = c.id'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON s.rowid = f.fk_soc'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; -if (!$user->rights->societe->client->voir) $sql .= ', '.MAIN_DB_PREFIX.'societe_commerciaux as sc'; +if (!$user->rights->societe->client->voir) { + $sql .= ', '.MAIN_DB_PREFIX.'societe_commerciaux as sc'; +} $sql .= ' WHERE f.entity = '.$conf->entity; -if (!$user->rights->societe->client->voir) $sql .= ' AND s.rowid = sc.fk_soc AND sc.fk_user = '.$user->id; -if ($socid > 0) $sql .= ' AND f.fk_soc = '.$socid; -if ($search_ref) $sql .= natural_search('p.ref', $search_ref); +if (!$user->rights->societe->client->voir) { + $sql .= ' AND s.rowid = sc.fk_soc AND sc.fk_user = '.$user->id; +} +if ($socid > 0) { + $sql .= ' AND f.fk_soc = '.$socid; +} +if ($search_ref) { + $sql .= natural_search('p.ref', $search_ref); +} $sql .= dolSqlDateFilter('p.datep', $search_day, $search_month, $search_year); -if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_payment_type != '') $sql .= " AND c.code='".$db->escape($search_payment_type)."'"; -if ($search_cheque_num != '') $sql .= natural_search('p.num_paiement', $search_cheque_num); -if ($search_amount) $sql .= natural_search('p.amount', $search_amount, 1); -if ($search_bank_account > 0) $sql .= ' AND b.fk_account='.$search_bank_account."'"; +if ($search_company) { + $sql .= natural_search('s.nom', $search_company); +} +if ($search_payment_type != '') { + $sql .= " AND c.code='".$db->escape($search_payment_type)."'"; +} +if ($search_cheque_num != '') { + $sql .= natural_search('p.num_paiement', $search_cheque_num); +} +if ($search_amount) { + $sql .= natural_search('p.amount', $search_amount, 1); +} +if ($search_bank_account > 0) { + $sql .= ' AND b.fk_account='.$search_bank_account."'"; +} -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; -$sql .= ' GROUP BY p.rowid, p.datep, p.amount, p.num_paiement, s.rowid, s.nom, c.code, c.libelle, ba.rowid, ba.label'; -if (!$user->rights->societe->client->voir) $sql .= ', sc.fk_soc, sc.fk_user'; +$sql .= ' GROUP BY p.rowid, p.ref, p.datep, p.amount, p.num_paiement, s.rowid, s.nom, s.email, c.code, c.libelle, ba.rowid, ba.label'; +if (!$user->rights->societe->client->voir) { + $sql .= ', sc.fk_soc, sc.fk_user'; +} $sql .= $db->order($sortfield, $sortorder); @@ -207,24 +241,48 @@ $num = $db->num_rows($resql); $i = 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 ($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); +} -if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); -if ($saerch_day) $param .= '&search_day='.urlencode($search_day); -if ($saerch_month) $param .= '&search_month='.urlencode($search_month); -if ($search_year) $param .= '&search_year='.urlencode($search_year); -if ($search_company) $param .= '&search_company='.urlencode($search_company); -if ($search_payment_type) $param .= '&search_company='.urlencode($search_payment_type); -if ($search_cheque_num) $param .= '&search_cheque_num='.urlencode($search_cheque_num); -if ($search_amount) $param .= '&search_amount='.urlencode($search_amount); +if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); +} +if ($saerch_day) { + $param .= '&search_day='.urlencode($search_day); +} +if ($saerch_month) { + $param .= '&search_month='.urlencode($search_month); +} +if ($search_year) { + $param .= '&search_year='.urlencode($search_year); +} +if ($search_company) { + $param .= '&search_company='.urlencode($search_company); +} +if ($search_payment_type) { + $param .= '&search_company='.urlencode($search_payment_type); +} +if ($search_cheque_num) { + $param .= '&search_cheque_num='.urlencode($search_cheque_num); +} +if ($search_amount) { + $param .= '&search_amount='.urlencode($search_amount); +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; @@ -234,9 +292,10 @@ print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; print_barre_liste($langs->trans('SupplierPayments'), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'supplier_invoice', 0, '', '', $limit, 0, 0, 1); -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } @@ -244,8 +303,11 @@ $moreforfilter = ''; $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 ($moreforfilter) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; @@ -255,7 +317,9 @@ if ($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 '<div class="div-table-responsive">'; print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : '').'">'; @@ -272,7 +336,9 @@ if (!empty($arrayfields['p.ref']['checked'])) { // Filter: Date if (!empty($arrayfields['p.datep']['checked'])) { print '<td class="liste_titre center">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_day" value="'.dol_escape_htmltag($search_day).'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_day" value="'.dol_escape_htmltag($search_day).'">'; + } print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_month" value="'.dol_escape_htmltag($search_month).'">'; $formother->select_year($search_year ? $search_year : -1, 'search_year', 1, 20, 5); print '</td>'; @@ -326,14 +392,30 @@ print '</td>'; print '</tr>'; print '<tr class="liste_titre">'; -if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], 'p.rowid', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.datep']['checked'])) print_liste_field_titre($arrayfields['p.datep']['label'], $_SERVER["PHP_SELF"], 'p.datep', '', $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['c.libelle']['checked'])) print_liste_field_titre($arrayfields['c.libelle']['label'], $_SERVER["PHP_SELF"], 'c.libelle', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.num_paiement']['checked'])) print_liste_field_titre($arrayfields['p.num_paiement']['label'], $_SERVER["PHP_SELF"], "p.num_paiement", '', $param, '', $sortfield, $sortorder, '', $arrayfields['p.num_paiement']['tooltip']); -if (!empty($arrayfields['ba.label']['checked'])) print_liste_field_titre($arrayfields['ba.label']['label'], $_SERVER["PHP_SELF"], 'ba.label', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.amount']['checked'])) print_liste_field_titre($arrayfields['p.amount']['label'], $_SERVER["PHP_SELF"], 'p.amount', '', $param, '', $sortfield, $sortorder, 'right '); +if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { + print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.ref']['checked'])) { + print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], 'p.rowid', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.datep']['checked'])) { + print_liste_field_titre($arrayfields['p.datep']['label'], $_SERVER["PHP_SELF"], 'p.datep', '', $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['c.libelle']['checked'])) { + print_liste_field_titre($arrayfields['c.libelle']['label'], $_SERVER["PHP_SELF"], 'c.libelle', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.num_paiement']['checked'])) { + print_liste_field_titre($arrayfields['p.num_paiement']['label'], $_SERVER["PHP_SELF"], "p.num_paiement", '', $param, '', $sortfield, $sortorder, '', $arrayfields['p.num_paiement']['tooltip']); +} +if (!empty($arrayfields['ba.label']['checked'])) { + print_liste_field_titre($arrayfields['ba.label']['label'], $_SERVER["PHP_SELF"], 'ba.label', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.amount']['checked'])) { + print_liste_field_titre($arrayfields['p.amount']['label'], $_SERVER["PHP_SELF"], 'p.amount', '', $param, '', $sortfield, $sortorder, 'right '); +} // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); @@ -368,21 +450,29 @@ while ($i < min($num, $limit)) { // No if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { print '<td>'.(($offset * $limit) + $i).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Ref if (!empty($arrayfields['p.ref']['checked'])) { print '<td class="nowrap">'.$paymentfournstatic->getNomUrl(1).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date if (!empty($arrayfields['p.datep']['checked'])) { $dateformatforpayment = 'day'; - if (!empty($conf->global->INVOICE_USE_HOURS_FOR_PAYMENT)) $dateformatforpayment = 'dayhour'; + if (!empty($conf->global->INVOICE_USE_HOURS_FOR_PAYMENT)) { + $dateformatforpayment = 'dayhour'; + } print '<td class="nowrap center">'.dol_print_date($db->jdate($objp->datep), $dateformatforpayment).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Thirdparty @@ -392,43 +482,57 @@ while ($i < min($num, $limit)) { print $companystatic->getNomUrl(1, '', 24); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Pyament type if (!empty($arrayfields['c.libelle']['checked'])) { $payment_type = $langs->trans("PaymentType".$objp->paiement_type) != ("PaymentType".$objp->paiement_type) ? $langs->trans("PaymentType".$objp->paiement_type) : $objp->paiement_libelle; print '<td>'.$payment_type.' '.dol_trunc($objp->num_paiement, 32).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Cheque number (fund transfer) if (!empty($arrayfields['p.num_paiement']['checked'])) { print '<td>'.$objp->num_paiement.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Account - if (!empty($arrayfields['ba.label']['checked'])) - { + if (!empty($arrayfields['ba.label']['checked'])) { print '<td>'; - if ($objp->bid) print '<a href="'.DOL_URL_ROOT.'/compta/bank/bankentries_list.php?account='.$objp->bid.'">'.img_object($langs->trans("ShowAccount"), 'account').' '.dol_trunc($objp->label, 24).'</a>'; - else print '&nbsp;'; + if ($objp->bid) { + print '<a href="'.DOL_URL_ROOT.'/compta/bank/bankentries_list.php?account='.$objp->bid.'">'.img_object($langs->trans("ShowAccount"), 'account').' '.dol_trunc($objp->label, 24).'</a>'; + } else { + print '&nbsp;'; + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount if (!empty($arrayfields['p.amount']['checked'])) { print '<td class="right">'.price($objp->pamount).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } $totalarray['pos'][$checkedCount] = 'amount'; $totalarray['val']['amount'] += $objp->pamount; } // Buttons print '<td></td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'; $i++; diff --git a/htdocs/fourn/product/list.php b/htdocs/fourn/product/list.php index 468352c72fe..32ddf769ce2 100644 --- a/htdocs/fourn/product/list.php +++ b/htdocs/fourn/product/list.php @@ -33,7 +33,9 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; $langs->loadLangs(array("products", "suppliers")); -if (!$user->rights->produit->lire && !$user->rights->service->lire) accessforbidden(); +if (!$user->rights->produit->lire && !$user->rights->service->lire) { + accessforbidden(); +} $sref = GETPOST('sref', 'alphanohtml'); $sRefSupplier = GETPOST('srefsupplier'); @@ -46,15 +48,23 @@ $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 (!$sortfield) $sortfield = "p.ref"; // Set here default search field -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "p.ref"; // Set here default search field +} +if (!$sortorder) { + $sortorder = "ASC"; +} $fourn_id = GETPOST('fourn_id', 'intcomma'); -if ($user->socid) $fourn_id = $user->socid; +if ($user->socid) { + $fourn_id = $user->socid; +} $catid = GETPOST('catid', 'intcomma'); @@ -71,22 +81,26 @@ $extrafields = new ExtraFields($db); * Put here all code to do according to value of "action" parameter */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 $sref = ''; $sRefSupplier = ''; $snom = ''; @@ -109,8 +123,7 @@ $companystatic = new Societe($db); $title = $langs->trans("ProductsAndServices"); -if ($fourn_id) -{ +if ($fourn_id) { $supplier = new Fournisseur($db); $supplier->fetch($fourn_id); } @@ -122,8 +135,12 @@ $arrayofmassactions = array( 'builddoc'=>$langs->trans("PDFMerge"), 'presend'=>$langs->trans("SendByMail"), ); -if ($user->rights->mymodule->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($user->rights->mymodule->supprimer) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); @@ -133,54 +150,52 @@ $sql .= " s.rowid as socid, s.nom as name"; // Add fields to SELECT from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object, $action); -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; -if ($catid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON cp.fk_product = p.rowid"; +if ($catid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON cp.fk_product = p.rowid"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as ppf ON p.rowid = ppf.fk_product"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON ppf.fk_soc = s.rowid"; $sql .= " WHERE p.entity IN (".getEntity('product').")"; -if ($sRefSupplier) -{ +if ($sRefSupplier) { $sql .= natural_search('ppf.ref_fourn', $sRefSupplier); } -if (GETPOST('type')) -{ +if (GETPOST('type')) { $sql .= " AND p.fk_product_type = ".GETPOST('type', 'int'); } -if ($sref) -{ +if ($sref) { $sql .= natural_search('p.ref', $sref); } -if ($snom) -{ +if ($snom) { $sql .= natural_search('p.label', $snom); } -if ($catid) -{ +if ($catid) { $sql .= " AND cp.fk_categorie = ".$catid; } -if ($fourn_id > 0) -{ +if ($fourn_id > 0) { $sql .= " AND ppf.fk_soc = ".$fourn_id; } // Add WHERE filters from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} $sql .= $hookmanager->resPrint; $sql .= $db->order($sortfield, $sortorder); // Count total nb of records without orderby and limit $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -190,30 +205,32 @@ $sql .= $db->plimit($limit + 1, $offset); dol_syslog("fourn/product/list.php:", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num == 1 && (GETPOST("mode") == 'search')) - { + if ($num == 1 && (GETPOST("mode") == 'search')) { $objp = $db->fetch_object($resql); header("Location: ".DOL_URL_ROOT."/product/card.php?id=".$objp->rowid); exit; } - if (!empty($supplier->id)) $texte = $langs->trans("ListOfSupplierProductForSupplier", $supplier->name); - else $texte = $langs->trans("List"); + if (!empty($supplier->id)) { + $texte = $langs->trans("ListOfSupplierProductForSupplier", $supplier->name); + } else { + $texte = $langs->trans("List"); + } llxHeader("", "", $texte); $param = "&sref=".$sref."&snom=".$snom."&fourn_id=".$fourn_id.(isset($type) ? "&amp;type=".$type : "").(empty($sRefSupplier) ? "" : "&amp;srefsupplier=".$sRefSupplier); - if ($optioncss != '') $param .= '&optioncss='.$optioncss; + if ($optioncss != '') { + $param .= '&optioncss='.$optioncss; + } print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords); - if (!empty($catid)) - { + if (!empty($catid)) { print "<div id='ways'>"; $c = new Categorie($db); $ways = $c->print_all_ways(' &gt; ', 'fourn/product/list.php'); @@ -222,9 +239,13 @@ if ($resql) } print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; - if ($fourn_id > 0) print '<input type="hidden" name="fourn_id" value="'.$fourn_id.'">'; + if ($fourn_id > 0) { + print '<input type="hidden" name="fourn_id" value="'.$fourn_id.'">'; + } print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="page" value="'.$page.'">'; @@ -256,7 +277,9 @@ if ($resql) // add filters from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print '<td class="liste_titre maxwidthsearch">'; $searchpicto = $form->showFilterButtons(); @@ -276,13 +299,14 @@ if ($resql) // add header cells from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print_liste_field_titre('', $_SERVER["PHP_SELF"]); print "</tr>\n"; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($resql); $productstatic->id = $objp->rowid; @@ -307,7 +331,9 @@ if ($resql) $companystatic->name = $objp->name; $companystatic->id = $objp->socid; print '<td>'; - if ($companystatic->id > 0) print $companystatic->getNomUrl(1, 'supplier'); + if ($companystatic->id > 0) { + print $companystatic->getNomUrl(1, 'supplier'); + } print '</td>'; print '<td class="right">'.(isset($objp->price) ? price($objp->price) : '').'</td>'; @@ -319,7 +345,9 @@ if ($resql) // add additional columns from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $objp, $action); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print '<td class="right"></td>'; diff --git a/htdocs/fourn/recap-fourn.php b/htdocs/fourn/recap-fourn.php index 736a7bf4f90..06ad90ec858 100644 --- a/htdocs/fourn/recap-fourn.php +++ b/htdocs/fourn/recap-fourn.php @@ -32,8 +32,7 @@ $langs->loadLangs(array('bills', 'companies')); // Security check $socid = GETPOST("socid", 'int'); -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -51,22 +50,20 @@ $userstatic = new User($db); llxHeader(); -if ($socid > 0) -{ +if ($socid > 0) { $societe = new Societe($db); $societe->fetch($socid); /* - * Affichage onglets - */ + * Affichage onglets + */ $head = societe_prepare_head($societe); print dol_get_fiche_head($head, 'supplier', $langs->trans("ThirdParty"), 0, 'company'); dol_banner_tab($societe, 'socid', '', ($user->socid ? 0 : 1), 'rowid', 'nom'); print dol_get_fiche_end(); - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->facture->lire) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->facture->lire) { // Invoice list print load_fiche_titre($langs->trans("SupplierPreview")); @@ -82,8 +79,7 @@ if ($socid > 0) $sql .= " ORDER BY f.datef DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '<tr class="liste_titre">'; @@ -96,22 +92,19 @@ if ($socid > 0) print '<td>&nbsp;</td>'; print '</tr>'; - if (!$num > 0) - { + if (!$num > 0) { print '<tr><td colspan="7">'.$langs->trans("NoInvoice").'</td></tr>'; } $solde = 0; // Boucle sur chaque facture - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $objf = $db->fetch_object($resql); $fac = new FactureFournisseur($db); $ret = $fac->fetch($objf->facid); - if ($ret < 0) - { + if ($ret < 0) { print $fac->error."<br>"; continue; } @@ -144,13 +137,11 @@ if ($socid > 0) $sql .= " AND pf.fk_facturefourn = ".$fac->id; $resqlp = $db->query($sql); - if ($resqlp) - { + if ($resqlp) { $nump = $db->num_rows($resqlp); $j = 0; - while ($j < $nump) - { + while ($j < $nump) { $objp = $db->fetch_object($resqlp); // print '<tr class="oddeven">'; diff --git a/htdocs/ftp/admin/ftpclient.php b/htdocs/ftp/admin/ftpclient.php index 6a51d6d0a88..ab673e45447 100644 --- a/htdocs/ftp/admin/ftpclient.php +++ b/htdocs/ftp/admin/ftpclient.php @@ -28,7 +28,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; $langs->loadLangs(array("admin", "ftp")); // Security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $def = array(); $lastftpentry = 0; @@ -45,36 +47,33 @@ $entry = GETPOST('numero_entry', 'alpha'); $sql = "select MAX(name) as name from ".MAIN_DB_PREFIX."const"; $sql .= " WHERE name like 'FTP_SERVER_%'"; $result = $db->query($sql); -if ($result) -{ +if ($result) { $obj = $db->fetch_object($result); preg_match('/([0-9]+)$/i', $obj->name, $reg); - if ($reg[1]) $lastftpentry = $reg[1]; + if ($reg[1]) { + $lastftpentry = $reg[1]; + } } else { dol_print_error($db); } -if ($action == 'add' || GETPOST('modify', 'alpha')) -{ +if ($action == 'add' || GETPOST('modify', 'alpha')) { $ftp_name = "FTP_NAME_".$entry; // $_POST["numero_entry"]; $ftp_server = "FTP_SERVER_".$entry; //$_POST["numero_entry"]; $error = 0; - if (!GETPOST("$ftp_name", 'alpha')) - { + if (!GETPOST("$ftp_name", 'alpha')) { $error = 1; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); } - if (!GETPOST("$ftp_server", 'alpha')) - { + if (!GETPOST("$ftp_server", 'alpha')) { $error = 1; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Server")), null, 'errors'); } - if (!$error) - { + if (!$error) { $ftp_port = "FTP_PORT_".$entry; $ftp_user = "FTP_USER_".$entry; $ftp_password = "FTP_PASSWORD_".$entry; @@ -83,14 +82,23 @@ if ($action == 'add' || GETPOST('modify', 'alpha')) $db->begin(); $result1 = dolibarr_set_const($db, "FTP_PORT_".$entry, GETPOST($ftp_port, 'alpha'), 'chaine', 0, '', $conf->entity); - if ($result1) $result2 = dolibarr_set_const($db, "FTP_SERVER_".$entry, GETPOST($ftp_server, 'alpha'), 'chaine', 0, '', $conf->entity); - if ($result2) $result3 = dolibarr_set_const($db, "FTP_USER_".$entry, GETPOST($ftp_user, 'alpha'), 'chaine', 0, '', $conf->entity); - if ($result3) $result4 = dolibarr_set_const($db, "FTP_PASSWORD_".$entry, GETPOST($ftp_password, 'alpha'), 'chaine', 0, '', $conf->entity); - if ($result4) $result5 = dolibarr_set_const($db, "FTP_NAME_".$entry, GETPOST($ftp_name, 'alpha'), 'chaine', 0, '', $conf->entity); - if ($result5) $result6 = dolibarr_set_const($db, "FTP_PASSIVE_".$entry, GETPOST($ftp_passive, 'alpha'), 'chaine', 0, '', $conf->entity); + if ($result1) { + $result2 = dolibarr_set_const($db, "FTP_SERVER_".$entry, GETPOST($ftp_server, 'alpha'), 'chaine', 0, '', $conf->entity); + } + if ($result2) { + $result3 = dolibarr_set_const($db, "FTP_USER_".$entry, GETPOST($ftp_user, 'alpha'), 'chaine', 0, '', $conf->entity); + } + if ($result3) { + $result4 = dolibarr_set_const($db, "FTP_PASSWORD_".$entry, GETPOST($ftp_password, 'alpha'), 'chaine', 0, '', $conf->entity); + } + if ($result4) { + $result5 = dolibarr_set_const($db, "FTP_NAME_".$entry, GETPOST($ftp_name, 'alpha'), 'chaine', 0, '', $conf->entity); + } + if ($result5) { + $result6 = dolibarr_set_const($db, "FTP_PASSIVE_".$entry, GETPOST($ftp_passive, 'alpha'), 'chaine', 0, '', $conf->entity); + } - if ($result1 && $result2 && $result3 && $result4 && $result5 && $result6) - { + if ($result1 && $result2 && $result3 && $result4 && $result5 && $result6) { $db->commit(); header("Location: ".$_SERVER["PHP_SELF"]); exit; @@ -101,21 +109,28 @@ if ($action == 'add' || GETPOST('modify', 'alpha')) } } -if (GETPOST('delete', 'alpha')) -{ - if ($entry) - { +if (GETPOST('delete', 'alpha')) { + if ($entry) { $db->begin(); $result1 = dolibarr_del_const($db, "FTP_PORT_".$entry, $conf->entity); - if ($result1) $result2 = dolibarr_del_const($db, "FTP_SERVER_".$entry, $conf->entity); - if ($result2) $result3 = dolibarr_del_const($db, "FTP_USER_".$entry, $conf->entity); - if ($result3) $result4 = dolibarr_del_const($db, "FTP_PASSWORD_".$entry, $conf->entity); - if ($result4) $result5 = dolibarr_del_const($db, "FTP_NAME_".$entry, $conf->entity); - if ($result4) $result6 = dolibarr_del_const($db, "FTP_PASSIVE_".$entry, $conf->entity); + if ($result1) { + $result2 = dolibarr_del_const($db, "FTP_SERVER_".$entry, $conf->entity); + } + if ($result2) { + $result3 = dolibarr_del_const($db, "FTP_USER_".$entry, $conf->entity); + } + if ($result3) { + $result4 = dolibarr_del_const($db, "FTP_PASSWORD_".$entry, $conf->entity); + } + if ($result4) { + $result5 = dolibarr_del_const($db, "FTP_NAME_".$entry, $conf->entity); + } + if ($result4) { + $result6 = dolibarr_del_const($db, "FTP_PASSIVE_".$entry, $conf->entity); + } - if ($result1 && $result2 && $result3 && $result4 && $result5 && $result6) - { + if ($result1 && $result2 && $result3 && $result4 && $result5 && $result6) { $db->commit(); header("Location: ".$_SERVER["PHP_SELF"]); exit; @@ -133,14 +148,16 @@ if (GETPOST('delete', 'alpha')) $form = new Form($db); -llxHeader(); + +$help_url = 'EN:Module_FTP_En|FR:Module_FTP|ES:Módulo_FTP'; + +llxHeader('', 'FTP', $help_url); $linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>'; print load_fiche_titre($langs->trans("FTPClientSetup"), $linkback, 'title_setup'); print '<br>'; -if (!function_exists('ftp_connect')) -{ +if (!function_exists('ftp_connect')) { print $langs->trans("FTPFeatureNotSupportedByYourPHP"); } else { // Formulaire ajout @@ -186,7 +203,9 @@ if (!function_exists('ftp_connect')) print '<tr class="impair">'; print '<td>'.$langs->trans("FTPPassiveMode").'</td>'; $defaultpassive = GETPOST("FTP_PASSIVE_".($lastftpentry + 1)); - if (!isset($_POST["FTP_PASSIVE_".($lastftpentry + 1)])) $defaultpassive = empty($conf->global->FTP_SUGGEST_PASSIVE_BYDEFAULT) ? 0 : 1; + if (!isset($_POST["FTP_PASSIVE_".($lastftpentry + 1)])) { + $defaultpassive = empty($conf->global->FTP_SUGGEST_PASSIVE_BYDEFAULT) ? 0 : 1; + } print '<td>'.$form->selectyesno('FTP_PASSIVE_'.($lastftpentry + 1), $defaultpassive, 2).'</td>'; print '<td>'.$langs->trans("No").'</td>'; print '</tr>'; @@ -211,13 +230,11 @@ if (!function_exists('ftp_connect')) dol_syslog("ftpclient select ftp setup", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); preg_match('/([0-9]+)$/i', $obj->name, $reg); diff --git a/htdocs/ftp/index.php b/htdocs/ftp/index.php index 51a8028e1f3..6a97265b050 100644 --- a/htdocs/ftp/index.php +++ b/htdocs/ftp/index.php @@ -32,13 +32,17 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/treeview.lib.php'; $langs->loadLangs(array('ftp', 'companies', 'other')); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ftp', ''); // Get parameters $action = GETPOST('action', 'aZ09'); $section = GETPOST('section'); -if (!$section) $section = '/'; +if (!$section) { + $section = '/'; +} $numero_ftp = GETPOST("numero_ftp"); /* if (! $numero_ftp) $numero_ftp=1; */ $file = GETPOST("file"); @@ -51,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 = "ASC"; -if (!$sortfield) $sortfield = "label"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "label"; +} $s_ftp_name = 'FTP_NAME_'.$numero_ftp; $s_ftp_server = 'FTP_SERVER_'.$numero_ftp; @@ -66,7 +76,9 @@ $s_ftp_password = 'FTP_PASSWORD_'.$numero_ftp; $s_ftp_passive = 'FTP_PASSIVE_'.$numero_ftp; $ftp_name = $conf->global->$s_ftp_name; $ftp_server = $conf->global->$s_ftp_server; -$ftp_port = $conf->global->$s_ftp_port; if (empty($ftp_port)) $ftp_port = 21; +$ftp_port = $conf->global->$s_ftp_port; if (empty($ftp_port)) { + $ftp_port = 21; +} $ftp_user = $conf->global->$s_ftp_user; $ftp_password = $conf->global->$s_ftp_password; $ftp_passive = $conf->global->$s_ftp_passive; @@ -83,29 +95,24 @@ $mesg = ''; */ // Submit file -if (GETPOST("sendit") && !empty($conf->global->MAIN_UPLOAD_DOC)) -{ +if (GETPOST("sendit") && !empty($conf->global->MAIN_UPLOAD_DOC)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $result = $ecmdir->fetch(GETPOST("section", 'int')); - if (!$result > 0) - { + if (!$result > 0) { dol_print_error($db, $ecmdir->error); exit; } $relativepath = $ecmdir->getRelativePath(); $upload_dir = $conf->ecm->dir_output.'/'.$relativepath; - if (dol_mkdir($upload_dir) >= 0) - { + if (dol_mkdir($upload_dir) >= 0) { $resupload = dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_dir."/".dol_unescapefile($_FILES['userfile']['name']), 0); - if (is_numeric($resupload) && $resupload > 0) - { + if (is_numeric($resupload) && $resupload > 0) { $result = $ecmdir->changeNbOfFiles('+'); } else { $langs->load("errors"); - if ($resupload < 0) // Unknown error - { + if ($resupload < 0) { // Unknown error setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors'); } elseif (preg_match('/ErrorFileIsInfectedWithAVirus/', $resupload)) { // Files infected by a virus @@ -116,22 +123,20 @@ if (GETPOST("sendit") && !empty($conf->global->MAIN_UPLOAD_DOC)) } } } else { - // Echec transfert (fichier depassant la limite ?) + // Transfer failure (file exceeding the limit ?) $langs->load("errors"); setEventMessages($langs->trans("ErrorFailToCreateDir", $upload_dir), null, 'errors'); } } // Action ajout d'un rep -if ($action == 'add' && $user->rights->ftp->setup) -{ +if ($action == 'add' && $user->rights->ftp->setup) { $ecmdir->ref = GETPOST("ref"); $ecmdir->label = GETPOST("label"); $ecmdir->description = GETPOST("desc"); $id = $ecmdir->create($user); - if ($id > 0) - { + if ($id > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -141,11 +146,9 @@ if ($action == 'add' && $user->rights->ftp->setup) } // Remove 1 file -if ($action == 'confirm_deletefile' && GETPOST('confirm') == 'yes') -{ +if ($action == 'confirm_deletefile' && GETPOST('confirm') == 'yes') { // set up a connection or die - if (!$conn_id) - { + if (!$conn_id) { $newsectioniso = utf8_decode($section); $resultarray = dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive); $conn_id = $resultarray['conn_id']; @@ -153,11 +156,9 @@ if ($action == 'confirm_deletefile' && GETPOST('confirm') == 'yes') $mesg = $resultarray['mesg']; } - if ($conn_id && $ok && !$mesg) - { + if ($conn_id && $ok && !$mesg) { $newsection = $section; - if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) - { + if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169 } @@ -175,8 +176,7 @@ if ($action == 'confirm_deletefile' && GETPOST('confirm') == 'yes') } else { $result = @ftp_delete($conn_id, $newremotefileiso); } - if ($result) - { + if ($result) { setEventMessages($langs->trans("FileWasRemoved", $file), null, 'mesgs'); } else { dol_syslog("ftp/index.php ftp_delete", LOG_ERR); @@ -192,11 +192,9 @@ if ($action == 'confirm_deletefile' && GETPOST('confirm') == 'yes') } // Delete several lines at once -if (GETPOST("const", 'array') && GETPOST("delete") && GETPOST("delete") == $langs->trans("Delete")) -{ +if (GETPOST("const", 'array') && GETPOST("delete") && GETPOST("delete") == $langs->trans("Delete")) { // set up a connection or die - if (!$conn_id) - { + if (!$conn_id) { $newsectioniso = utf8_decode($section); $resultarray = dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive); $conn_id = $resultarray['conn_id']; @@ -204,19 +202,15 @@ if (GETPOST("const", 'array') && GETPOST("delete") && GETPOST("delete") == $lang $mesg = $resultarray['mesg']; } - if ($conn_id && $ok && !$mesg) - { - foreach (GETPOST('const', 'array') as $const) - { - if ($const["check"]) // Is checkbox checked - { + if ($conn_id && $ok && !$mesg) { + foreach (GETPOST('const', 'array') as $const) { + if ($const["check"]) { // Is checkbox checked $langs->load("other"); // Remote file $file = $const["file"]; $newsection = $const["section"]; - if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) - { + if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169 } $remotefile = $newsection.(preg_match('@[\\\/]$@', $newsection) ? '' : '/').$file; @@ -229,8 +223,7 @@ if (GETPOST("const", 'array') && GETPOST("delete") && GETPOST("delete") == $lang } else { $result = @ftp_delete($conn_id, $newremotefileiso); } - if ($result) - { + if ($result) { setEventMessages($langs->trans("FileWasRemoved", $file), null, 'mesgs'); } else { dol_syslog("ftp/index.php ftp_delete n files", LOG_ERR); @@ -248,11 +241,9 @@ if (GETPOST("const", 'array') && GETPOST("delete") && GETPOST("delete") == $lang } // Remove directory -if ($action == 'confirm_deletesection' && $confirm == 'yes') -{ +if ($action == 'confirm_deletesection' && $confirm == 'yes') { // set up a connection or die - if (!$conn_id) - { + if (!$conn_id) { $newsectioniso = utf8_decode($section); $resultarray = dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive); $conn_id = $resultarray['conn_id']; @@ -260,11 +251,9 @@ if ($action == 'confirm_deletesection' && $confirm == 'yes') $mesg = $resultarray['mesg']; } - if ($conn_id && $ok && !$mesg) - { + if ($conn_id && $ok && !$mesg) { $newsection = $section; - if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) - { + if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169 } @@ -278,8 +267,7 @@ if ($action == 'confirm_deletesection' && $confirm == 'yes') } else { $result = @ftp_rmdir($conn_id, $newremotefileiso); } - if ($result) - { + if ($result) { setEventMessages($langs->trans("DirWasRemoved", $file), null, 'mesgs'); } else { setEventMessages($langs->trans("FTPFailedToRemoveDir", $file), null, 'errors'); @@ -294,11 +282,9 @@ if ($action == 'confirm_deletesection' && $confirm == 'yes') } // Download directory -if ($action == 'download') -{ +if ($action == 'download') { // set up a connection or die - if (!$conn_id) - { + if (!$conn_id) { $newsectioniso = utf8_decode($section); $resultarray = dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive); $conn_id = $resultarray['conn_id']; @@ -306,14 +292,12 @@ if ($action == 'download') $mesg = $resultarray['mesg']; } - if ($conn_id && $ok && !$mesg) - { + if ($conn_id && $ok && !$mesg) { // Local file $localfile = tempnam($download_dir, 'dol_'); $newsection = $section; - if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) - { + if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169 } @@ -327,23 +311,31 @@ if ($action == 'download') } else { $result = ftp_get($conn_id, $localfile, $newremotefileiso, FTP_BINARY); } - if ($result) - { - if (!empty($conf->global->MAIN_UMASK)) - @chmod($localfile, octdec($conf->global->MAIN_UMASK)); + if ($result) { + if (!empty($conf->global->MAIN_UMASK)) { + @chmod($localfile, octdec($conf->global->MAIN_UMASK)); + } // Define mime type $type = 'application/octet-stream'; - if (GETPOSTISSET("type")) $type = GETPOST("type"); - else $type = dol_mimetype($file); + if (GETPOSTISSET("type")) { + $type = GETPOST("type"); + } else { + $type = dol_mimetype($file); + } // Define attachment (attachment=true to force choice popup 'open'/'save as') $attachment = true; //if ($encoding) header('Content-Encoding: '.$encoding); - if ($type) header('Content-Type: '.$type); - if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"'); - else header('Content-Disposition: inline; filename="'.$filename.'"'); + if ($type) { + header('Content-Type: '.$type); + } + if ($attachment) { + header('Content-Disposition: attachment; filename="'.$filename.'"'); + } else { + header('Content-Disposition: inline; filename="'.$filename.'"'); + } // Ajout directives pour resoudre bug IE header('Cache-Control: Public, must-revalidate'); @@ -374,8 +366,7 @@ if ($action == 'download') llxHeader(); // Add logic to shoow/hide buttons -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { ?> <script type="text/javascript"> jQuery(document).ready(function() { @@ -411,21 +402,17 @@ print load_fiche_titre($langs->trans("FTPArea")); print $langs->trans("FTPAreaDesc")."<br>"; -if (!function_exists('ftp_connect')) -{ +if (!function_exists('ftp_connect')) { print $langs->trans("FTPFeatureNotSupportedByYourPHP"); } else { - if (!empty($ftp_server)) - { + if (!empty($ftp_server)) { // Confirm remove file - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'&section='.urlencode(GETPOST('section')).'&file='.urlencode(GETPOST('file')), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', '', 1); } // Confirmation de la suppression d'une ligne categorie - if ($action == 'delete_section') - { + if ($action == 'delete_section') { print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'&section='.urlencode(GETPOST('section')).'&file='.urlencode(GETPOST('file')), $langs->trans('DeleteSection'), $langs->trans('ConfirmDeleteSection', $ecmdir->label), 'confirm_deletesection', '', '', 1); } @@ -443,11 +430,11 @@ if (!function_exists('ftp_connect')) print '</a> '; // For other directories $i = 0; - foreach ($sectionarray as $val) - { - if (empty($val)) continue; // Discard first and last entry that should be empty as section start/end with / - if ($i > 0) - { + foreach ($sectionarray as $val) { + if (empty($val)) { + continue; // Discard first and last entry that should be empty as section start/end with / + } + if ($i > 0) { print ' / '; $newsection .= '/'; } @@ -476,14 +463,15 @@ if (!function_exists('ftp_connect')) print '<td class="liste_titre center">'.$langs->trans("Group").'</td>'."\n"; print '<td class="liste_titre center">'.$langs->trans("Permissions").'</td>'."\n"; print '<td class="liste_titre nowrap right">'; - if ($conf->use_javascript_ajax) print '<a href="#" id="checkall">'.$langs->trans("All").'</a> / <a href="#" id="checknone">'.$langs->trans("None").'</a> '; + if ($conf->use_javascript_ajax) { + print '<a href="#" id="checkall">'.$langs->trans("All").'</a> / <a href="#" id="checknone">'.$langs->trans("None").'</a> '; + } print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($section ? '&section='.urlencode($section) : '').'">'.img_picto($langs->trans("Refresh"), 'refresh').'</a>&nbsp;'; print '</td>'."\n"; print '</tr>'."\n"; // set up a connection or die - if (empty($conn_id)) - { + if (empty($conn_id)) { $resultarray = dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $section, $ftp_passive); $conn_id = $resultarray['conn_id']; @@ -491,8 +479,7 @@ if (!function_exists('ftp_connect')) $mesg = $resultarray['mesg']; } - if ($ok) - { + if ($ok) { //$type = ftp_systype($conn_id); $newsection = $section; @@ -500,8 +487,7 @@ if (!function_exists('ftp_connect')) //$newsection='/home'; // List content of directory ($newsection = '/', '/home', ...) - if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) - { + if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { if ($newsection == '/') { //$newsection = '/./'; $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169 @@ -511,8 +497,7 @@ if (!function_exists('ftp_connect')) //$dirHandle = opendir("ssh2.sftp://".intval($conn_id).ssh2_sftp_realpath($conn_id, ".").'/./'); $contents = scandir('ssh2.sftp://'.intval($conn_id).$newsection); $buff = array(); - foreach ($contents as $i => $key) - { + foreach ($contents as $i => $key) { $buff[$i] = "---------- - root root 1234 Aug 01 2000 ".$key; } } else { @@ -525,31 +510,32 @@ if (!function_exists('ftp_connect')) $nboflines = count($contents); $rawlisthasfailed = false; $i = 0; - while ($i < $nboflines && $i < 1000) - { + while ($i < $nboflines && $i < 1000) { $vals = preg_split('@ +@', utf8_encode($buff[$i]), 9); //$vals=preg_split('@ +@','drwxr-xr-x 2 root root 4096 Aug 30 2008 backup_apollon1',9); //var_dump($vals); $file = $vals[8]; - if (empty($file)) - { + if (empty($file)) { $rawlisthasfailed = true; $file = utf8_encode($contents[$i]); } - if ($file == '.' || ($file == '..' && $section == '/')) - { + if ($file == '.' || ($file == '..' && $section == '/')) { $i++; continue; } // Is it a directory ? $is_directory = 0; - if ($file == '..') $is_directory = 1; - elseif (!$rawlisthasfailed) - { - if (preg_match('/^d/', $vals[0])) $is_directory = 1; - if (preg_match('/^l/', $vals[0])) $is_link = 1; + if ($file == '..') { + $is_directory = 1; + } elseif (!$rawlisthasfailed) { + if (preg_match('/^d/', $vals[0])) { + $is_directory = 1; + } + if (preg_match('/^l/', $vals[0])) { + $is_link = 1; + } } else { // Remote file $filename = $file; @@ -569,14 +555,21 @@ if (!function_exists('ftp_connect')) print '<td>'; $newsection = $section.(preg_match('@[\\\/]$@', $section) ? '' : '/').$file; $newsection = preg_replace('@[\\\/][^\\\/]+[\\\/]\.\.$@', '/', $newsection); // Change aaa/xxx/.. to new aaa - if ($is_directory) print '<a href="'.$_SERVER["PHP_SELF"].'?section='.urlencode($newsection).'&numero_ftp='.$numero_ftp.'">'; + if ($is_directory) { + print '<a href="'.$_SERVER["PHP_SELF"].'?section='.urlencode($newsection).'&numero_ftp='.$numero_ftp.'">'; + } print dol_escape_htmltag($file); - if ($is_directory) print '</a>'; + if ($is_directory) { + print '</a>'; + } print '</td>'; // Size print '<td class="center nowrap">'; - if (!$is_directory && !$is_link) print $vals[4]; - else print '&nbsp;'; + if (!$is_directory && !$is_link) { + print $vals[4]; + } else { + print '&nbsp;'; + } print '</td>'; // Date print '<td class="center nowrap">'; @@ -596,12 +589,13 @@ if (!function_exists('ftp_connect')) print '</td>'; // Action print '<td class="right nowrap" width="64">'; - if ($is_directory) - { - if ($file != '..') print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete_section&token='.newToken().'&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_delete().'</a>'; - else print '&nbsp;'; - } elseif ($is_link) - { + if ($is_directory) { + if ($file != '..') { + print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete_section&token='.newToken().'&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_delete().'</a>'; + } else { + print '&nbsp;'; + } + } elseif ($is_link) { $newfile = $file; $newfile = preg_replace('/ ->.*/', '', $newfile); print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($newfile).'">'.img_delete().'</a>'; @@ -624,8 +618,7 @@ if (!function_exists('ftp_connect')) print "</table>"; - if (!$ok) - { + if (!$ok) { print $mesg.'<br>'."\n"; setEventMessages($mesg, null, 'errors'); } @@ -650,19 +643,16 @@ if (!function_exists('ftp_connect')) $foundsetup = false; $MAXFTP = 20; $i = 1; - while ($i <= $MAXFTP) - { + while ($i <= $MAXFTP) { $paramkey = 'FTP_NAME_'.$i; //print $paramkey; - if (!empty($conf->global->$paramkey)) - { + if (!empty($conf->global->$paramkey)) { $foundsetup = true; break; } $i++; } - if (!$foundsetup) - { + if (!$foundsetup) { print $langs->trans("SetupOfFTPClientModuleNotComplete"); } else { print $langs->trans("ChooseAFTPEntryIntoMenu"); @@ -673,12 +663,9 @@ if (!function_exists('ftp_connect')) print '<br>'; // Close FTP connection -if ($conn_id) -{ - if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) - { - } elseif (!empty($conf->global->FTP_CONNECT_WITH_SSL)) - { +if ($conn_id) { + if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { + } elseif (!empty($conf->global->FTP_CONNECT_WITH_SSL)) { ftp_close($conn_id); } else { ftp_close($conn_id); @@ -709,14 +696,12 @@ function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $sect $ok = 1; $conn_id = null; - if (!is_numeric($ftp_port)) - { + if (!is_numeric($ftp_port)) { $mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServer", $ftp_server, $ftp_port); $ok = 0; } - if ($ok) - { + if ($ok) { $connecttimeout = (empty($conf->global->FTP_CONNECT_TIMEOUT) ? 40 : $conf->global->FTP_CONNECT_TIMEOUT); if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { dol_syslog('Try to connect with ssh2_ftp'); @@ -728,15 +713,11 @@ function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $sect dol_syslog('Try to connect with ftp_connect'); $conn_id = ftp_connect($ftp_server, $ftp_port, $connecttimeout); } - if ($conn_id || $tmp_conn_id) - { - if ($ftp_user) - { - if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) - { + if ($conn_id || $tmp_conn_id) { + if ($ftp_user) { + if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { dol_syslog('Try to authenticate with ssh2_auth_password'); - if (ssh2_auth_password($tmp_conn_id, $ftp_user, $ftp_password)) - { + if (ssh2_auth_password($tmp_conn_id, $ftp_user, $ftp_password)) { // Turn on passive mode transfers (must be after a successful login //if ($ftp_passive) ftp_pasv($conn_id, true); @@ -744,31 +725,31 @@ function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $sect $newsectioniso = utf8_decode($section); //ftp_chdir($conn_id, $newsectioniso); $conn_id = ssh2_sftp($tmp_conn_id); - if (!$conn_id) - { + if (!$conn_id) { dol_syslog('Failed to connect to SFTP after sssh authentication', LOG_DEBUG); $mesg = $langs->transnoentitiesnoconv("FailedToConnectToSFTPAfterSSHAuthentication"); - $ok = 0; + $ok = 0; $error++; } } else { dol_syslog('Failed to connect to FTP with login '.$ftp_user, LOG_DEBUG); $mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials"); - $ok = 0; + $ok = 0; $error++; } } else { - if (ftp_login($conn_id, $ftp_user, $ftp_password)) - { + if (ftp_login($conn_id, $ftp_user, $ftp_password)) { // Turn on passive mode transfers (must be after a successful login - if ($ftp_passive) ftp_pasv($conn_id, true); + if ($ftp_passive) { + ftp_pasv($conn_id, true); + } // Change the dir $newsectioniso = utf8_decode($section); ftp_chdir($conn_id, $newsectioniso); } else { $mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials"); - $ok = 0; + $ok = 0; $error++; } } @@ -794,8 +775,7 @@ function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $sect */ function ftp_isdir($connect_id, $dir) { - if (@ftp_chdir($connect_id, $dir)) - { + if (@ftp_chdir($connect_id, $dir)) { ftp_cdup($connect_id); return 1; } else { diff --git a/htdocs/holiday/card.php b/htdocs/holiday/card.php index bbd5a1ac9d4..bab0655b4c2 100644 --- a/htdocs/holiday/card.php +++ b/htdocs/holiday/card.php @@ -6,6 +6,7 @@ * Copyright (C) 2017 Alexandre Spangaro <aspangaro@open-dsi.fr> * Copyright (C) 2014-2017 Ferran Marcet <fmarcet@2byte.es> * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2020-2021 Udo Tamm <dev@dolibit.de> * * 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 @@ -51,14 +52,16 @@ $fuserid = (GETPOST('fuserid', 'int') ?GETPOST('fuserid', 'int') : $user->id); // Load translation files required by the page $langs->loadLangs(array("other", "holiday", "mails")); +$error = 0; + $now = dol_now(); $childids = $user->getAllChildIds(1); $morefilter = ''; -if (!empty($conf->global->HOLIDAY_HIDE_FOR_NON_SALARIES)) $morefilter = 'AND employee = 1'; - -$error = 0; +if (!empty($conf->global->HOLIDAY_HIDE_FOR_NON_SALARIES)) { + $morefilter = 'AND employee = 1'; +} $object = new Holiday($db); @@ -67,31 +70,43 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -if (($id > 0) || $ref) -{ +if (($id > 0) || $ref) { $object->fetch($id, $ref); // Check current user can read this leave request $canread = 0; - if (!empty($user->rights->holiday->readall)) $canread = 1; - if (!empty($user->rights->holiday->read) && in_array($object->fk_user, $childids)) $canread = 1; - if (!$canread) - { + if (!empty($user->rights->holiday->readall)) { + $canread = 1; + } + if (!empty($user->rights->holiday->read) && in_array($object->fk_user, $childids)) { + $canread = 1; + } + if (!$canread) { accessforbidden(); } } $cancreate = 0; -if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->holiday->writeall_advance)) $cancreate = 1; -if (!empty($user->rights->holiday->write) && in_array($fuserid, $childids)) $cancreate = 1; +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->holiday->writeall_advance)) { + $cancreate = 1; +} +if (!empty($user->rights->holiday->write) && in_array($fuserid, $childids)) { + $cancreate = 1; +} $candelete = 0; -if (!empty($user->rights->holiday->delete)) $candelete = 1; -if ($object->statut == Holiday::STATUS_DRAFT && $user->rights->holiday->write && in_array($object->fk_user, $childids)) $candelete = 1; +if (!empty($user->rights->holiday->delete)) { + $candelete = 1; +} +if ($object->statut == Holiday::STATUS_DRAFT && $user->rights->holiday->write && in_array($object->fk_user, $childids)) { + $candelete = 1; +} // Protection if external user -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'holiday', $object->id, 'holiday'); @@ -101,14 +116,13 @@ $result = restrictedArea($user, 'holiday', $object->id, 'holiday'); $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)) -{ - if ($cancel) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -116,18 +130,15 @@ if (empty($reshook)) } // Add leave request - if ($action == 'add') - { + if ($action == 'add') { // If no right to create a request - if (!$cancreate) - { + if (!$cancreate) { $error++; setEventMessages($langs->trans('CantCreateCP'), null, 'errors'); $action = 'create'; } - if (!$error) - { + if (!$error) { $object = new Holiday($db); $db->begin(); @@ -140,17 +151,24 @@ if (empty($reshook)) $endhalfday = GETPOST('endhalfday'); $type = GETPOST('type'); $halfday = 0; - if ($starthalfday == 'afternoon' && $endhalfday == 'morning') $halfday = 2; - elseif ($starthalfday == 'afternoon') $halfday = -1; - elseif ($endhalfday == 'morning') $halfday = 1; + if ($starthalfday == 'afternoon' && $endhalfday == 'morning') { + $halfday = 2; + } elseif ($starthalfday == 'afternoon') { + $halfday = -1; + } elseif ($endhalfday == 'morning') { + $halfday = 1; + } $valideur = GETPOST('valideur', 'int'); $description = trim(GETPOST('description', 'restricthtml')); // Check that leave is for a user inside the hierarchy or advanced permission for all is set - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->holiday->write)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->holiday->writeall_advance))) { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->holiday->write)) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->id == $fuserid && empty($user->rights->holiday->write)) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->id != $fuserid && empty($user->rights->holiday->writeall_advance)) + ) { $error++; - setEventMessages($langs->trans("NotEnoughPermission"), null, 'errors'); + setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); } else { if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->holiday->writeall_advance)) { if (!in_array($fuserid, $childids)) { @@ -162,30 +180,26 @@ if (empty($reshook)) } // If no type - if ($type <= 0) - { + if ($type <= 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); $error++; $action = 'create'; } // If no start date - if (empty($date_debut)) - { + if (empty($date_debut)) { setEventMessages($langs->trans("NoDateDebut"), null, 'errors'); $error++; $action = 'create'; } // If no end date - if (empty($date_fin)) - { + if (empty($date_fin)) { setEventMessages($langs->trans("NoDateFin"), null, 'errors'); $error++; $action = 'create'; } // If start date after end date - if ($date_debut > $date_fin) - { + if ($date_debut > $date_fin) { setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors'); $error++; $action = 'create'; @@ -193,8 +207,7 @@ if (empty($reshook)) // Check if there is already holiday for this period $verifCP = $object->verifDateHolidayCP($fuserid, $date_debut, $date_fin, $halfday); - if (!$verifCP) - { + if (!$verifCP) { setEventMessages($langs->trans("alreadyCPexist"), null, 'errors'); $error++; $action = 'create'; @@ -202,24 +215,21 @@ if (empty($reshook)) // If there is no Business Days within request $nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday); - if ($nbopenedday < 0.5) - { + if ($nbopenedday < 0.5) { setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); // No working day $error++; $action = 'create'; } // If no validator designated - if ($valideur < 1) - { + if ($valideur < 1) { setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors'); $error++; } $result = 0; - if (!$error) - { + if (!$error) { $object->fk_user = $fuserid; $object->description = $description; $object->fk_validator = $valideur; @@ -229,16 +239,14 @@ if (empty($reshook)) $object->halfday = $halfday; $result = $object->create($user); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } // If no SQL error we redirect to the request card - if (!$error) - { + if (!$error) { $db->commit(); header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); @@ -249,20 +257,17 @@ if (empty($reshook)) } } - if ($action == 'update' && GETPOSTISSET('savevalidator') && !empty($user->rights->holiday->approve)) - { + if ($action == 'update' && GETPOSTISSET('savevalidator') && !empty($user->rights->holiday->approve)) { $object->fetch($id); $object->oldcopy = dol_clone($object); $object->fk_validator = GETPOST('valideur', 'int'); - if ($object->fk_validator != $object->oldcopy->fk_validator) - { + if ($object->fk_validator != $object->oldcopy->fk_validator) { $verif = $object->update($user); - if ($verif <= 0) - { + if ($verif <= 0) { setEventMessages($object->error, $object->errors, 'warnings'); $action = 'editvalidator'; } else { @@ -274,8 +279,7 @@ if (empty($reshook)) $action = ''; } - if ($action == 'update' && !GETPOSTISSET('savevalidator')) - { + if ($action == 'update' && !GETPOSTISSET('savevalidator')) { $date_debut = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year')); $date_fin = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year')); $date_debut_gmt = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'), 1); @@ -283,13 +287,16 @@ if (empty($reshook)) $starthalfday = GETPOST('starthalfday'); $endhalfday = GETPOST('endhalfday'); $halfday = 0; - if ($starthalfday == 'afternoon' && $endhalfday == 'morning') $halfday = 2; - elseif ($starthalfday == 'afternoon') $halfday = -1; - elseif ($endhalfday == 'morning') $halfday = 1; + if ($starthalfday == 'afternoon' && $endhalfday == 'morning') { + $halfday = 2; + } elseif ($starthalfday == 'afternoon') { + $halfday = -1; + } elseif ($endhalfday == 'morning') { + $halfday = 1; + } // If no right to modify a request - if (!$user->rights->holiday->write) - { + if (!$user->rights->holiday->write) { setEventMessages($langs->trans("CantUpdate"), null, 'errors'); header('Location: '.$_SERVER["PHP_SELF"].'?action=create'); exit; @@ -298,11 +305,9 @@ if (empty($reshook)) $object->fetch($id); // If under validation - if ($object->statut == Holiday::STATUS_DRAFT) - { + if ($object->statut == Holiday::STATUS_DRAFT) { // If this is the requestor or has read/write rights - if ($cancreate) - { + if ($cancreate) { $valideur = GETPOST('valideur', 'int'); $description = trim(GETPOST('description', 'restricthtml')); @@ -332,8 +337,7 @@ if (empty($reshook)) // If there is no Business Days within request $nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday); - if ($nbopenedday < 0.5) - { + if ($nbopenedday < 0.5) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=DureeHoliday'); exit; } @@ -347,8 +351,7 @@ if (empty($reshook)) // Update $verif = $object->update($user); - if ($verif <= 0) - { + if ($verif <= 0) { setEventMessages($object->error, $object->errors, 'warnings'); $action = 'edit'; } else { @@ -366,8 +369,7 @@ if (empty($reshook)) } // If delete of request - if ($action == 'confirm_delete' && GETPOST('confirm') == 'yes' && $user->rights->holiday->delete) - { + if ($action == 'confirm_delete' && GETPOST('confirm') == 'yes' && $user->rights->holiday->delete) { $error = 0; $db->begin(); @@ -375,11 +377,9 @@ if (empty($reshook)) $object->fetch($id); // If this is a rough draft, approved, canceled or refused - if ($object->statut == Holiday::STATUS_DRAFT || $object->statut == Holiday::STATUS_CANCELED || $object->statut == Holiday::STATUS_REFUSED) - { + if ($object->statut == Holiday::STATUS_DRAFT || $object->statut == Holiday::STATUS_CANCELED || $object->statut == Holiday::STATUS_REFUSED) { // Si l'utilisateur à le droit de lire cette demande, il peut la supprimer - if ($candelete) - { + if ($candelete) { $result = $object->delete($user); } else { $error++; @@ -388,8 +388,7 @@ if (empty($reshook)) } } - if (!$error) - { + if (!$error) { $db->commit(); header('Location: list.php?restore_lastsearch_values=1'); exit; @@ -399,29 +398,25 @@ if (empty($reshook)) } // Action validate (+ send email for approval) - if ($action == 'confirm_send') - { + if ($action == 'confirm_send') { $object->fetch($id); // If draft and owner of leave - if ($object->statut == Holiday::STATUS_DRAFT && $cancreate) - { + if ($object->statut == Holiday::STATUS_DRAFT && $cancreate) { $object->oldcopy = dol_clone($object); $object->statut = Holiday::STATUS_VALIDATED; $verif = $object->validate($user); - // Si pas d'erreur SQL on redirige vers la fiche de la demande - if ($verif > 0) - { + // If no SQL error, we redirect to the request form + if ($verif > 0) { // To $destinataire = new User($db); $destinataire->fetch($object->fk_validator); $emailTo = $destinataire->email; - if (!$emailTo) - { + if (!$emailTo) { dol_syslog("Expected validator has no email, so we redirect directly to finished page without sending email"); header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; @@ -435,7 +430,9 @@ if (empty($reshook)) // Subject $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $societeName = $conf->global->MAIN_APPLICATION_TITLE; + } $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysToValidate"); @@ -450,22 +447,18 @@ if (empty($reshook)) $nextMonth = dol_time_plus_duree($now, $delayForRequest, 'd'); - // Si l'option pour avertir le valideur en cas de délai trop court - if ($object->getConfCP('AlertValidatorDelay')) - { - if ($object->date_debut < $nextMonth) - { + // option to warn the validator in case of too short delay + if ($object->getConfCP('AlertValidatorDelay')) { + if ($object->date_debut < $nextMonth) { $message .= "\n"; $message .= $langs->transnoentities("HolidaysToValidateDelay", $object->getConfCP('delayForRequest'))."\n"; } } - // Si l'option pour avertir le valideur en cas de solde inférieur à la demande - if ($object->getConfCP('AlertValidatorSolde')) - { + // option to notify the validator if the balance is less than the request + if ($object->getConfCP('AlertValidatorSolde')) { $nbopenedday = num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday); - if ($nbopenedday > $object->getCPforUser($object->fk_user, $object->fk_type)) - { + if ($nbopenedday > $object->getCPforUser($object->fk_user, $object->fk_type)) { $message .= "\n"; $message .= $langs->transnoentities("HolidaysToValidateAlertSolde")."\n"; } @@ -481,11 +474,10 @@ if (empty($reshook)) $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); - // Envoi du mail + // Sending the email $result = $mail->sendfile(); - if (!$result) - { + if (!$result) { setEventMessages($mail->error, $mail->errors, 'warnings'); $action = ''; } else { @@ -499,37 +491,35 @@ if (empty($reshook)) } } - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('HOLIDAY_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } // Approve leave request - if ($action == 'confirm_valid') - { + if ($action == 'confirm_valid') { $object->fetch($id); // If status is waiting approval and approver is also user - if ($object->statut == Holiday::STATUS_VALIDATED && $user->id == $object->fk_validator) - { + if ($object->statut == Holiday::STATUS_VALIDATED && $user->id == $object->fk_validator) { $object->oldcopy = dol_clone($object); $object->date_valid = dol_now(); @@ -539,46 +529,40 @@ if (empty($reshook)) $db->begin(); $verif = $object->approve($user); - if ($verif <= 0) - { + if ($verif <= 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } - // Si pas d'erreur SQL on redirige vers la fiche de la demande - if (!$error) - { + // If no SQL error, we redirect to the request form + if (!$error) { // Calculcate number of days consummed $nbopenedday = num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday); $soldeActuel = $object->getCpforUser($object->fk_user, $object->fk_type); $newSolde = ($soldeActuel - $nbopenedday); - // On ajoute la modification dans le LOG + // The modification is added to the LOG $result = $object->addLogCP($user->id, $object->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $object->fk_type); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages(null, $object->errors, 'errors'); } - //Update balance + // Update balance $result = $object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages(null, $object->errors, 'errors'); } } - if (!$error) - { + if (!$error) { // To $destinataire = new User($db); $destinataire->fetch($object->fk_user); $emailTo = $destinataire->email; - if (!$emailTo) - { + if (!$emailTo) { dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email"); } else { // From @@ -589,7 +573,9 @@ if (empty($reshook)) // Subject $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $societeName = $conf->global->MAIN_APPLICATION_TITLE; + } $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated"); @@ -608,23 +594,21 @@ if (empty($reshook)) $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); - // Envoi du mail + // Sending email $result = $mail->sendfile(); - if (!$result) - { + if (!$result) { setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1 $action = ''; } } } - if (!$error) - { + if (!$error) { $db->commit(); - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; } else { $db->rollback(); $action = ''; @@ -632,15 +616,12 @@ if (empty($reshook)) } } - if ($action == 'confirm_refuse' && GETPOST('confirm', 'alpha') == 'yes') - { - if (!empty($_POST['detail_refuse'])) - { + if ($action == 'confirm_refuse' && GETPOST('confirm', 'alpha') == 'yes') { + if (!empty($_POST['detail_refuse'])) { $object->fetch($id); - // Si statut en attente de validation et valideur = utilisateur - if ($object->statut == Holiday::STATUS_VALIDATED && $user->id == $object->fk_validator) - { + // If status pending validation and validator = user + if ($object->statut == Holiday::STATUS_VALIDATED && $user->id == $object->fk_validator) { $object->date_refuse = dol_print_date('dayhour', dol_now()); $object->fk_user_refuse = $user->id; $object->statut = Holiday::STATUS_REFUSED; @@ -649,22 +630,19 @@ if (empty($reshook)) $db->begin(); $verif = $object->update($user); - if ($verif <= 0) - { + if ($verif <= 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } - // Si pas d'erreur SQL on redirige vers la fiche de la demande - if (!$error) - { + // If no SQL error, we redirect to the request form + if (!$error) { // To $destinataire = new User($db); $destinataire->fetch($object->fk_user); $emailTo = $destinataire->email; - if (!$emailTo) - { + if (!$emailTo) { dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email"); } else { // From @@ -675,7 +653,9 @@ if (empty($reshook)) // Subject $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $societeName = $conf->global->MAIN_APPLICATION_TITLE; + } $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysRefused"); @@ -695,11 +675,10 @@ if (empty($reshook)) $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); - // Envoi du mail + // sending email $result = $mail->sendfile(); - if (!$result) - { + if (!$result) { setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1 $action = ''; } @@ -708,8 +687,7 @@ if (empty($reshook)) $action = ''; } - if (!$error) - { + if (!$error) { $db->commit(); header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); @@ -726,9 +704,8 @@ if (empty($reshook)) } - // Si Validation de la demande - if ($action == 'confirm_draft' && GETPOST('confirm') == 'yes') - { + // If the request is validated + if ($action == 'confirm_draft' && GETPOST('confirm') == 'yes') { $error = 0; $object->fetch($id); @@ -737,14 +714,12 @@ if (empty($reshook)) $object->statut = Holiday::STATUS_DRAFT; $result = $object->update($user); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($langs->trans('ErrorBackToDraft').' '.$object->error, $object->errors, 'errors'); } - if (!$error) - { + if (!$error) { $db->commit(); header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); @@ -754,17 +729,15 @@ if (empty($reshook)) } } - // Si confirmation of cancellation - if ($action == 'confirm_cancel' && GETPOST('confirm') == 'yes') - { + // If confirmation of cancellation + if ($action == 'confirm_cancel' && GETPOST('confirm') == 'yes') { $error = 0; $object->fetch($id); - // Si statut en attente de validation et valideur = valideur ou utilisateur, ou droits de faire pour les autres + // If status pending validation and validator = validator or user, or rights to do for others if (($object->statut == Holiday::STATUS_VALIDATED || $object->statut == Holiday::STATUS_APPROVED) && ($user->id == $object->fk_validator || in_array($object->fk_user, $childids) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->holiday->writeall_advance)))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->holiday->writeall_advance)))) { $db->begin(); $oldstatus = $object->statut; @@ -774,44 +747,39 @@ if (empty($reshook)) $result = $object->update($user); - if ($result >= 0 && $oldstatus == Holiday::STATUS_APPROVED) // holiday was already validated, status 3, so we must increase back the balance - { + if ($result >= 0 && $oldstatus == Holiday::STATUS_APPROVED) { // holiday was already validated, status 3, so we must increase back the balance // Calculcate number of days consummed $nbopenedday = num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday); $soldeActuel = $object->getCpforUser($object->fk_user, $object->fk_type); $newSolde = ($soldeActuel + $nbopenedday); - // On ajoute la modification dans le LOG + // The modification is added to the LOG $result1 = $object->addLogCP($user->id, $object->fk_user, $langs->transnoentitiesnoconv("HolidaysCancelation"), $newSolde, $object->fk_type); - // Mise à jour du solde + // Update of the balance $result2 = $object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type); - if ($result1 < 0 || $result2 < 0) - { + if ($result1 < 0 || $result2 < 0) { $error++; setEventMessages($langs->trans('ErrorCantDeleteCP').' '.$object->error, $object->errors, 'errors'); } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); } - // Si pas d'erreur SQL on redirige vers la fiche de la demande - if (!$error && $result > 0) - { + // If no SQL error, we redirect to the request form + if (!$error && $result > 0) { // To $destinataire = new User($db); $destinataire->fetch($object->fk_user); $emailTo = $destinataire->email; - if (!$emailTo) - { + if (!$emailTo) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } @@ -824,12 +792,14 @@ if (empty($reshook)) // Subject $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $societeName = $conf->global->MAIN_APPLICATION_TITLE; + } $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysCanceled"); // Content - $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; + $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; $message .= "\n"; $message .= $langs->transnoentities("HolidaysCanceledBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."\n"; @@ -842,11 +812,10 @@ if (empty($reshook)) $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); - // Envoi du mail + // sending email $result = $mail->sendfile(); - if (!$result) - { + if (!$result) { setEventMessages($mail->error, $mail->errors, 'warnings'); $action = ''; } else { @@ -885,13 +854,13 @@ $object = new Holiday($db); $listhalfday = array('morning'=>$langs->trans("Morning"), "afternoon"=>$langs->trans("Afternoon")); -llxHeader('', $langs->trans('CPTitreMenu')); +$help_url = 'EN:Module_Holiday'; -if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') -{ +llxHeader('', $langs->trans('CPTitreMenu'), $help_url); + +if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') { // If user has no permission to create a leave - if ((in_array($fuserid, $childids) && empty($user->rights->holiday->write)) || (!in_array($fuserid, $childids) && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->holiday->writeall_advance)))) - { + if ((in_array($fuserid, $childids) && empty($user->rights->holiday->write)) || (!in_array($fuserid, $childids) && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->holiday->writeall_advance)))) { $errors[] = $langs->trans('CantCreateCP'); } else { // Form to add a leave request @@ -900,28 +869,28 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') // Error management if (GETPOST('error')) { switch (GETPOST('error')) { - case 'datefin' : + case 'datefin': $errors[] = $langs->trans('ErrorEndDateCP'); break; - case 'SQL_Create' : + case 'SQL_Create': $errors[] = $langs->trans('ErrorSQLCreateCP').' <b>'.htmlentities($_GET['msg']).'</b>'; break; - case 'CantCreate' : + case 'CantCreate': $errors[] = $langs->trans('CantCreateCP'); break; - case 'Valideur' : + case 'Valideur': $errors[] = $langs->trans('InvalidValidatorCP'); break; - case 'nodatedebut' : + case 'nodatedebut': $errors[] = $langs->trans('NoDateDebut'); break; - case 'nodatefin' : + case 'nodatefin': $errors[] = $langs->trans('NoDateFin'); break; - case 'DureeHoliday' : + case 'DureeHoliday': $errors[] = $langs->trans('ErrorDureeCP'); break; - case 'alreadyCP' : + case 'alreadyCP': $errors[] = $langs->trans('alreadyCPexist'); break; } @@ -974,8 +943,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') $out = ''; $typeleaves = $object->getTypes(1, 1); - foreach ($typeleaves as $key => $val) - { + foreach ($typeleaves as $key => $val) { $nb_type = $object->getCPforUser($user->id, $val['rowid']); $nb_holiday += $nb_type; @@ -1002,8 +970,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') print '<td class="titlefield fieldrequired">'.$langs->trans("User").'</td>'; print '<td>'; - if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->holiday->writeall_advance)) - { + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->holiday->writeall_advance)) { print img_picto('', 'user').$form->select_dolusers(($fuserid ? $fuserid : $user->id), 'fuserid', 0, '', 0, 'hierarchyme', '', '0,'.$conf->entity, 0, 0, $morefilter, 0, '', 'minwidth200 maxwidth500'); //print '<input type="hidden" name="fuserid" value="'.($fuserid?$fuserid:$user->id).'">'; } else { @@ -1018,14 +985,15 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') print '<td>'; $typeleaves = $object->getTypes(1, -1); $arraytypeleaves = array(); - foreach ($typeleaves as $key => $val) - { + foreach ($typeleaves as $key => $val) { $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']); $labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')' : ''); $arraytypeleaves[$val['rowid']] = $labeltoshow; } print $form->selectarray('type', $arraytypeleaves, (GETPOST('type', 'alpha') ?GETPOST('type', 'alpha') : ''), 1, 0, 0, '', 0, 0, 0, '', '', true); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '</td>'; print '</tr>'; @@ -1075,8 +1043,12 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateHolidays"); } else { $defaultselectuser = (empty($user->fk_user_holiday_validator) ? $user->fk_user : $user->fk_user_holiday_validator); // Will work only if supervisor has permission to approve so is inside include_users - if (!empty($conf->global->HOLIDAY_DEFAULT_VALIDATOR)) $defaultselectuser = $conf->global->HOLIDAY_DEFAULT_VALIDATOR; // Can force default approver - if (GETPOST('valideur', 'int') > 0) $defaultselectuser = GETPOST('valideur', 'int'); + if (!empty($conf->global->HOLIDAY_DEFAULT_VALIDATOR)) { + $defaultselectuser = $conf->global->HOLIDAY_DEFAULT_VALIDATOR; // Can force default approver + } + if (GETPOST('valideur', 'int') > 0) { + $defaultselectuser = GETPOST('valideur', 'int'); + } $s = $form->select_dolusers($defaultselectuser, "valideur", 1, '', 0, $include_users, '', '0,'.$conf->entity, 0, 0, '', 0, '', 'minwidth200 maxwidth500'); print img_picto('', 'user').$form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate")); } @@ -1117,8 +1089,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') print '</div>'; } else { // Affichage de la fiche d'une demande de congés payés - if (($id > 0) || $ref) - { + if (($id > 0) || $ref) { $result = $object->fetch($id, $ref); $valideur = new User($db); @@ -1130,35 +1101,33 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') //print load_fiche_titre($langs->trans('TitreRequestCP')); // Si il y a une erreur - if (GETPOST('error')) - { - switch (GETPOST('error')) - { - case 'datefin' : + if (GETPOST('error')) { + switch (GETPOST('error')) { + case 'datefin': $errors[] = $langs->transnoentitiesnoconv('ErrorEndDateCP'); break; - case 'SQL_Create' : + case 'SQL_Create': $errors[] = $langs->transnoentitiesnoconv('ErrorSQLCreateCP').' '.$_GET['msg']; break; - case 'CantCreate' : + case 'CantCreate': $errors[] = $langs->transnoentitiesnoconv('CantCreateCP'); break; - case 'Valideur' : + case 'Valideur': $errors[] = $langs->transnoentitiesnoconv('InvalidValidatorCP'); break; - case 'nodatedebut' : + case 'nodatedebut': $errors[] = $langs->transnoentitiesnoconv('NoDateDebut'); break; - case 'nodatefin' : + case 'nodatefin': $errors[] = $langs->transnoentitiesnoconv('NoDateFin'); break; - case 'DureeHoliday' : + case 'DureeHoliday': $errors[] = $langs->transnoentitiesnoconv('ErrorDureeCP'); break; - case 'NoMotifRefuse' : + case 'NoMotifRefuse': $errors[] = $langs->transnoentitiesnoconv('NoMotifRefuseCP'); break; - case 'mail' : + case 'mail': $errors[] = $langs->transnoentitiesnoconv('ErrorMailNotSend')."\n".$_GET['error_content']; break; } @@ -1167,13 +1136,13 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') } // On vérifie si l'utilisateur à le droit de lire cette demande - if ($cancreate) - { + if ($cancreate) { $head = holiday_prepare_head($object); - if (($action == 'edit' && $object->statut == Holiday::STATUS_DRAFT) || ($action == 'editvalidator')) - { - if ($action == 'edit' && $object->statut == Holiday::STATUS_DRAFT) $edit = true; + if (($action == 'edit' && $object->statut == Holiday::STATUS_DRAFT) || ($action == 'editvalidator')) { + if ($action == 'edit' && $object->statut == Holiday::STATUS_DRAFT) { + $edit = true; + } print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'."\n"; print '<input type="hidden" name="token" value="'.newToken().'" />'."\n"; @@ -1215,8 +1184,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') $starthalfday = ($object->halfday == -1 || $object->halfday == 2) ? 'afternoon' : 'morning'; $endhalfday = ($object->halfday == 1 || $object->halfday == 2) ? 'morning' : 'afternoon'; - if (!$edit) - { + if (!$edit) { print '<tr>'; print '<td class="nowrap">'; print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday")); @@ -1239,8 +1207,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') print '</tr>'; } - if (!$edit) - { + if (!$edit) { print '<tr>'; print '<td class="nowrap">'; print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday")); @@ -1269,8 +1236,12 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') $htmlhelp = $langs->trans('NbUseDaysCPHelp'); $includesaturday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY : 1); $includesunday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY : 1); - if ($includesaturday) $htmlhelp .= '<br>'.$langs->trans("DayIsANonWorkingDay", $langs->trans("Saturday")); - if ($includesunday) $htmlhelp .= '<br>'.$langs->trans("DayIsANonWorkingDay", $langs->trans("Sunday")); + if ($includesaturday) { + $htmlhelp .= '<br>'.$langs->trans("DayIsANonWorkingDay", $langs->trans("Saturday")); + } + if ($includesunday) { + $htmlhelp .= '<br>'.$langs->trans("DayIsANonWorkingDay", $langs->trans("Sunday")); + } print $form->textwithpicto($langs->trans('NbUseDaysCP'), $htmlhelp); print '</td>'; print '<td>'; @@ -1278,8 +1249,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') print '</td>'; print '</tr>'; - if ($object->statut == Holiday::STATUS_REFUSED) - { + if ($object->statut == Holiday::STATUS_REFUSED) { print '<tr>'; print '<td>'.$langs->trans('DetailRefusCP').'</td>'; print '<td>'.$object->detail_refuse.'</td>'; @@ -1287,8 +1257,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') } // Description - if (!$edit) - { + if (!$edit) { print '<tr>'; print '<td>'.$langs->trans('DescCP').'</td>'; print '<td>'.nl2br($object->description).'</td>'; @@ -1318,8 +1287,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') print '<table class="border tableforfield centpercent">'."\n"; print '<tbody>'; - if (!empty($object->fk_user_create)) - { + if (!empty($object->fk_user_create)) { $userCreate = new User($db); $userCreate->fetch($object->fk_user_create); print '<tr>'; @@ -1332,13 +1300,15 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') if (!$edit && $action != 'editvalidator') { print '<tr>'; print '<td class="titlefield">'; - if ($object->statut == Holiday::STATUS_APPROVED || $object->statut == Holiday::STATUS_CANCELED) print $langs->trans('ApprovedBy'); - else print $langs->trans('ReviewedByCP'); + if ($object->statut == Holiday::STATUS_APPROVED || $object->statut == Holiday::STATUS_CANCELED) { + print $langs->trans('ApprovedBy'); + } else { + print $langs->trans('ReviewedByCP'); + } print '</td>'; print '<td>'.$valideur->getNomUrl(-1); $include_users = $object->fetch_users_approver_holiday(); - if (is_array($include_users) && in_array($user->id, $include_users) && $object->statut == Holiday::STATUS_VALIDATED) - { + if (is_array($include_users) && in_array($user->id, $include_users) && $object->statut == Holiday::STATUS_VALIDATED) { print '<a class="editfielda paddingleft" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=editvalidator">'.img_edit($langs->trans("Edit")).'</a>'; } print '</td>'; @@ -1348,18 +1318,17 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') print '<td class="titlefield">'.$langs->trans('ReviewedByCP').'</td>'; print '<td>'; $include_users = $object->fetch_users_approver_holiday(); - if (!in_array($object->fk_validator, $include_users)) // Add the current validator to the list to not lose it when editing. - { + if (!in_array($object->fk_validator, $include_users)) { // Add the current validator to the list to not lose it when editing. $include_users[] = $object->fk_validator; } - if (empty($include_users)) print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateHolidays"); - else { + if (empty($include_users)) { + print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateHolidays"); + } else { $arrayofvalidatorstoexclude = (($user->admin || ($user->id != $userRequest->id)) ? '' : array($user->id)); // Nobody if we are admin or if we are not the user of the leave. $s = $form->select_dolusers($object->fk_validator, "valideur", (($action == 'editvalidator') ? 0 : 1), $arrayofvalidatorstoexclude, 0, $include_users); print $form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate")); } - if ($action == 'editvalidator') - { + if ($action == 'editvalidator') { print '<input type="submit" class="button button-save" name="savevalidator" value="'.$langs->trans("Save").'">'; print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; } @@ -1402,52 +1371,42 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') // Confirmation messages - if ($action == 'delete') - { - if ($user->rights->holiday->delete) - { + if ($action == 'delete') { + if ($user->rights->holiday->delete) { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleDeleteCP"), $langs->trans("ConfirmDeleteCP"), "confirm_delete", '', 0, 1); } } // Si envoi en validation - if ($action == 'sendToValidate' && $object->statut == Holiday::STATUS_DRAFT) - { + if ($action == 'sendToValidate' && $object->statut == Holiday::STATUS_DRAFT) { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleToValidCP"), $langs->trans("ConfirmToValidCP"), "confirm_send", '', 1, 1); } // Si validation de la demande - if ($action == 'valid') - { + if ($action == 'valid') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleValidCP"), $langs->trans("ConfirmValidCP"), "confirm_valid", '', 1, 1); } // Si refus de la demande - if ($action == 'refuse') - { + if ($action == 'refuse') { $array_input = array(array('type'=>"text", 'label'=> $langs->trans('DetailRefusCP'), 'name'=>"detail_refuse", 'size'=>"50", 'value'=>"")); print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&action=confirm_refuse", $langs->trans("TitleRefuseCP"), $langs->trans('ConfirmRefuseCP'), "confirm_refuse", $array_input, 1, 0); } // Si annulation de la demande - if ($action == 'cancel') - { + if ($action == 'cancel') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleCancelCP"), $langs->trans("ConfirmCancelCP"), "confirm_cancel", '', 1, 1); } // Si back to draft - if ($action == 'backtodraft') - { + if ($action == 'backtodraft') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleSetToDraft"), $langs->trans("ConfirmSetToDraft"), "confirm_draft", '', 1, 1); } - if (($action == 'edit' && $object->statut == Holiday::STATUS_DRAFT) || ($action == 'editvalidator')) - { - if ($action == 'edit' && $object->statut == Holiday::STATUS_DRAFT) - { + if (($action == 'edit' && $object->statut == Holiday::STATUS_DRAFT) || ($action == 'editvalidator')) { + if ($action == 'edit' && $object->statut == Holiday::STATUS_DRAFT) { print '<div class="center">'; - if ($cancreate && $object->statut == Holiday::STATUS_DRAFT) - { + if ($cancreate && $object->statut == Holiday::STATUS_DRAFT) { print '<input type="submit" value="'.$langs->trans("Save").'" class="button button-save">'; } print '</div>'; @@ -1456,24 +1415,19 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') print '</form>'; } - if (!$edit) - { + if (!$edit) { // Buttons for actions print '<div class="tabsAction">'; - if ($cancreate && $object->statut == Holiday::STATUS_DRAFT) - { + if ($cancreate && $object->statut == Holiday::STATUS_DRAFT) { print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit" class="butAction">'.$langs->trans("EditCP").'</a>'; } - if ($cancreate && $object->statut == Holiday::STATUS_DRAFT) // If draft - { + if ($cancreate && $object->statut == Holiday::STATUS_DRAFT) { // If draft print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=sendToValidate" class="butAction">'.$langs->trans("Validate").'</a>'; } - if ($object->statut == Holiday::STATUS_VALIDATED) // If validated - { - if ($user->id == $object->fk_validator) - { + if ($object->statut == Holiday::STATUS_VALIDATED) { // If validated + if ($user->id == $object->fk_validator) { print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=valid" class="butAction">'.$langs->trans("Approve").'</a>'; print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=refuse" class="butAction">'.$langs->trans("ActionRefuseCP").'</a>'; } else { @@ -1481,17 +1435,17 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') print '<a href="#" class="butActionRefused classfortooltip" title="'.$langs->trans("NotTheAssignedApprover").'">'.$langs->trans("ActionRefuseCP").'</a>'; } } - if (($user->id == $object->fk_validator || in_array($object->fk_user, $childids) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->holiday->writeall_advance))) && ($object->statut == 2 || $object->statut == 3)) // Status validated or approved - { - if (($object->date_debut > dol_now()) || $user->admin) print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=cancel" class="butAction">'.$langs->trans("ActionCancelCP").'</a>'; - else print '<a href="#" class="butActionRefused classfortooltip" title="'.$langs->trans("HolidayStarted").'">'.$langs->trans("ActionCancelCP").'</a>'; + if (($user->id == $object->fk_validator || in_array($object->fk_user, $childids) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->holiday->writeall_advance))) && ($object->statut == 2 || $object->statut == 3)) { // Status validated or approved + if (($object->date_debut > dol_now()) || $user->admin) { + print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=cancel" class="butAction">'.$langs->trans("ActionCancelCP").'</a>'; + } else { + print '<a href="#" class="butActionRefused classfortooltip" title="'.$langs->trans("HolidayStarted").'">'.$langs->trans("ActionCancelCP").'</a>'; + } } - if ($cancreate && $object->statut == Holiday::STATUS_CANCELED) - { + if ($cancreate && $object->statut == Holiday::STATUS_CANCELED) { print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=backtodraft" class="butAction">'.$langs->trans("SetToDraft").'</a>'; } - if ($candelete && ($object->statut == Holiday::STATUS_DRAFT || $object->statut == Holiday::STATUS_CANCELED || $object->statut == Holiday::STATUS_REFUSED)) // If draft or canceled or refused - { + if ($candelete && ($object->statut == Holiday::STATUS_DRAFT || $object->statut == Holiday::STATUS_CANCELED || $object->statut == Holiday::STATUS_REFUSED)) { // If draft or canceled or refused print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'" class="butActionDelete">'.$langs->trans("DeleteCP").'</a>'; } @@ -1516,8 +1470,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre @@ -1560,4 +1513,6 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') // End of page llxFooter(); -if (is_object($db)) $db->close(); +if (is_object($db)) { + $db->close(); +} diff --git a/htdocs/holiday/class/holiday.class.php b/htdocs/holiday/class/holiday.class.php index f61c0a66ca8..7943df254c1 100644 --- a/htdocs/holiday/class/holiday.class.php +++ b/htdocs/holiday/class/holiday.class.php @@ -4,7 +4,7 @@ * Copyright (C) 2012-2016 Regis Houssin <regis.houssin@inodbox.com> * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro> * Copyright (C) 2016 Juanjo Menent <jmenent@2byte.es> - * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -170,13 +170,11 @@ class Holiday extends CommonObject global $langs, $conf; $langs->load("order"); - if (empty($conf->global->HOLIDAY_ADDON)) - { + if (empty($conf->global->HOLIDAY_ADDON)) { $conf->global->HOLIDAY_ADDON = 'mod_holiday_madonna'; } - if (!empty($conf->global->HOLIDAY_ADDON)) - { + if (!empty($conf->global->HOLIDAY_ADDON)) { $mybool = false; $file = $conf->global->HOLIDAY_ADDON.".php"; @@ -184,16 +182,14 @@ class Holiday extends CommonObject // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/holiday/"); // Load file with numbering class (if found) $mybool |= @include_once $dir.$file; } - if ($mybool === false) - { + if ($mybool === false) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -201,8 +197,7 @@ class Holiday extends CommonObject $obj = new $classname(); $numref = $obj->getNextValue($objsoc, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -230,8 +225,7 @@ class Holiday extends CommonObject // Check nb of users into table llx_holiday_users and update with empty lines //if ($result > 0) $result = $this->verifNbUsers($this->countActiveUsersWithoutCP(), $this->getConfCP('nbUser')); - if ($result >= 0) - { + if ($result >= 0) { $this->db->commit(); return 1; } else { @@ -255,9 +249,15 @@ class Holiday extends CommonObject $now = dol_now(); // Check parameters - if (empty($this->fk_user) || !is_numeric($this->fk_user) || $this->fk_user < 0) { $this->error = "ErrorBadParameterFkUser"; return -1; } - if (empty($this->fk_validator) || !is_numeric($this->fk_validator) || $this->fk_validator < 0) { $this->error = "ErrorBadParameterFkValidator"; return -1; } - if (empty($this->fk_type) || !is_numeric($this->fk_type) || $this->fk_type < 0) { $this->error = "ErrorBadParameterFkType"; return -1; } + if (empty($this->fk_user) || !is_numeric($this->fk_user) || $this->fk_user < 0) { + $this->error = "ErrorBadParameterFkUser"; return -1; + } + if (empty($this->fk_validator) || !is_numeric($this->fk_validator) || $this->fk_validator < 0) { + $this->error = "ErrorBadParameterFkValidator"; return -1; + } + if (empty($this->fk_type) || !is_numeric($this->fk_type) || $this->fk_type < 0) { + $this->error = "ErrorBadParameterFkType"; return -1; + } // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday("; @@ -296,32 +296,33 @@ class Holiday extends CommonObject $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday"); - if ($this->id) - { + if ($this->id) { // update ref $initialref = '(PROV'.$this->id.')'; - if (!empty($this->ref)) $initialref = $this->ref; + if (!empty($this->ref)) { + $initialref = $this->ref; + } - $sql = 'UPDATE '.MAIN_DB_PREFIX."holiday SET ref='".$this->db->escape($initialref)."' WHERE rowid=".$this->id; - if ($this->db->query($sql)) - { + $sql = 'UPDATE '.MAIN_DB_PREFIX."holiday SET ref='".$this->db->escape($initialref)."' WHERE rowid=".((int) $this->id); + if ($this->db->query($sql)) { $this->ref = $initialref; - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('HOLIDAY_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } @@ -329,10 +330,8 @@ class Holiday extends CommonObject } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -380,15 +379,16 @@ class Holiday extends CommonObject $sql .= " cp.fk_type,"; $sql .= " cp.entity"; $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp"; - if ($id > 0) $sql .= " WHERE cp.rowid = ".$id; - else $sql .= " WHERE cp.ref = '".$this->db->escape($ref)."'"; + if ($id > 0) { + $sql .= " WHERE cp.rowid = ".((int) $id); + } else { + $sql .= " WHERE cp.ref = '".$this->db->escape($ref)."'"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -693,8 +693,7 @@ class Holiday extends CommonObject $error = 0; // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref) || $this->ref == $this->id)) - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref) || $this->ref == $this->id)) { $num = $this->getNextNumRef(null); } else { $num = $this->ref; @@ -719,22 +718,20 @@ class Holiday extends CommonObject $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('HOLIDAY_VALIDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::validate ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -831,22 +828,20 @@ class Holiday extends CommonObject $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('HOLIDAY_APPROVE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::approve ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -942,22 +937,20 @@ class Holiday extends CommonObject $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('HOLIDAY_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -983,7 +976,7 @@ class Holiday extends CommonObject $error = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); @@ -993,22 +986,20 @@ class Holiday extends CommonObject $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('HOLIDAY_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -1037,60 +1028,67 @@ class Holiday extends CommonObject { $this->fetchByUser($fk_user, '', ''); - foreach ($this->holiday as $infos_CP) - { - if ($infos_CP['statut'] == 4) continue; // ignore not validated holidays - if ($infos_CP['statut'] == 5) continue; // ignore not validated holidays + foreach ($this->holiday as $infos_CP) { + if ($infos_CP['statut'] == 4) { + continue; // ignore not validated holidays + } + if ($infos_CP['statut'] == 5) { + continue; // ignore not validated holidays + } /* var_dump("--"); var_dump("old: ".dol_print_date($infos_CP['date_debut'],'dayhour').' '.dol_print_date($infos_CP['date_fin'],'dayhour').' '.$infos_CP['halfday']); var_dump("new: ".dol_print_date($dateStart,'dayhour').' '.dol_print_date($dateEnd,'dayhour').' '.$halfday); */ - if ($halfday == 0) - { - if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) - { + if ($halfday == 0) { + if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) { return false; } - if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) - { + if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) { return false; } - } elseif ($halfday == -1) - { + } elseif ($halfday == -1) { // new start afternoon, new end afternoon - if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) - { - if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) return false; + if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) { + if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) { + return false; + } } - if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) - { - if ($dateStart < $dateEnd) return false; - if ($dateEnd < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) return false; + if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) { + if ($dateStart < $dateEnd) { + return false; + } + if ($dateEnd < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) { + return false; + } } - } elseif ($halfday == 1) - { + } elseif ($halfday == 1) { // new start morning, new end morning - if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) - { - if ($dateStart < $dateEnd) return false; - if ($dateStart > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) return false; + if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) { + if ($dateStart < $dateEnd) { + return false; + } + if ($dateStart > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) { + return false; + } } - if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) - { - if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) return false; + if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) { + if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) { + return false; + } } - } elseif ($halfday == 2) - { + } elseif ($halfday == 2) { // new start afternoon, new end morning - if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) - { - if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) return false; + if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) { + if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) { + return false; + } } - if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) - { - if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) return false; + if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) { + if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) { + return false; + } } } else { dol_print_error('', 'Bad value of parameter halfday when calling function verifDateHolidayCP'); @@ -1123,18 +1121,17 @@ class Holiday extends CommonObject $sql .= " WHERE cp.entity IN (".getEntity('holiday').")"; $sql .= " AND cp.fk_user = ".(int) $fk_user; $sql .= " AND cp.date_debut <= '".$this->db->idate($timestamp)."' AND cp.date_fin >= '".$this->db->idate($timestamp)."'"; - if ($status != '-1') $sql .= " AND cp.statut IN (".$this->db->sanitize($this->db->escape($status)).")"; + if ($status != '-1') { + $sql .= " AND cp.statut IN (".$this->db->sanitize($this->db->escape($status)).")"; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_rows = $this->db->num_rows($resql); // Note, we can have 2 records if on is morning and the other one is afternoon - if ($num_rows > 0) - { + if ($num_rows > 0) { $arrayofrecord = array(); $i = 0; - while ($i < $num_rows) - { + while ($i < $num_rows) { $obj = $this->db->fetch_object($resql); // Note: $obj->halfday is 0:Full days, 2:Sart afternoon end morning, -1:Start afternoon, 1:End morning @@ -1144,27 +1141,39 @@ class Holiday extends CommonObject // We found a record, user is on holiday by default, so is not available is true. $isavailablemorning = true; - foreach ($arrayofrecord as $record) - { - if ($timestamp == $record['date_start'] && $record['halfday'] == 2) continue; - if ($timestamp == $record['date_start'] && $record['halfday'] == -1) continue; + foreach ($arrayofrecord as $record) { + if ($timestamp == $record['date_start'] && $record['halfday'] == 2) { + continue; + } + if ($timestamp == $record['date_start'] && $record['halfday'] == -1) { + continue; + } $isavailablemorning = false; break; } $isavailableafternoon = true; - foreach ($arrayofrecord as $record) - { - if ($timestamp == $record['date_end'] && $record['halfday'] == 2) continue; - if ($timestamp == $record['date_end'] && $record['halfday'] == 1) continue; + foreach ($arrayofrecord as $record) { + if ($timestamp == $record['date_end'] && $record['halfday'] == 2) { + continue; + } + if ($timestamp == $record['date_end'] && $record['halfday'] == 1) { + continue; + } $isavailableafternoon = false; break; } } - } else dol_print_error($this->db); + } else { + dol_print_error($this->db); + } $result = array('morning'=>$isavailablemorning, 'afternoon'=>$isavailableafternoon); - if (!$isavailablemorning) $result['morning_reason'] = 'leave_request'; - if (!$isavailableafternoon) $result['afternoon_reason'] = 'leave_request'; + if (!$isavailablemorning) { + $result['morning_reason'] = 'leave_request'; + } + if (!$isavailableafternoon) { + $result['afternoon_reason'] = 'leave_request'; + } return $result; } @@ -1174,9 +1183,10 @@ class Holiday extends CommonObject * * @param int $withpicto 0=_No picto, 1=Includes the picto in the linkn, 2=Picto only * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @param int $notooltip 1=Disable tooltip * @return string String with URL */ - public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1) + public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1, $notooltip = 0) { global $langs; @@ -1194,16 +1204,24 @@ class Holiday extends CommonObject //{ // 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 = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; return $result; @@ -1233,8 +1251,7 @@ class Holiday extends CommonObject public function LibStatut($status, $mode = 0, $startdate = '') { // phpcs:enable - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('DraftCP'); @@ -1250,11 +1267,21 @@ class Holiday extends CommonObject } $statusType = 'status6'; - if (!empty($startdate) && $startdate > dol_now()) $statusType = 'status4'; - if ($status == self::STATUS_DRAFT) $statusType = 'status0'; - if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; - if ($status == self::STATUS_CANCELED) $statusType = 'status5'; - if ($status == self::STATUS_REFUSED) $statusType = 'status5'; + if (!empty($startdate) && $startdate > dol_now()) { + $statusType = 'status4'; + } + if ($status == self::STATUS_DRAFT) { + $statusType = 'status0'; + } + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status1'; + } + if ($status == self::STATUS_CANCELED) { + $statusType = 'status5'; + } + if ($status == self::STATUS_REFUSED) { + $statusType = 'status5'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -1338,15 +1365,12 @@ class Holiday extends CommonObject if ($result) { $obj = $this->db->fetch_object($result); // Return value - if (empty($obj)) - { - if ($createifnotfound) - { + if (empty($obj)) { + if ($createifnotfound) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_config(name, value)"; $sql .= " VALUES('".$this->db->escape($name)."', '".$this->db->escape($createifnotfound)."')"; $result = $this->db->query($sql); - if ($result) - { + if ($result) { return $createifnotfound; } else { $this->error = $this->db->lasterror(); @@ -1379,8 +1403,7 @@ class Holiday extends CommonObject $error = 0; - if (empty($userID) && empty($nbHoliday) && empty($fk_type)) - { + if (empty($userID) && empty($nbHoliday) && empty($fk_type)) { $langs->load("holiday"); // Si mise à jour pour tout le monde en début de mois @@ -1395,8 +1418,7 @@ class Holiday extends CommonObject //print 'month: '.$month.' lastUpdate:'.$lastUpdate.' monthLastUpdate:'.$monthLastUpdate;exit; // Si la date du mois n'est pas la même que celle sauvegardée, on met à jour le timestamp - if ($month != $monthLastUpdate) - { + if ($month != $monthLastUpdate) { $this->db->begin(); $users = $this->fetchUsers(false, false); @@ -1412,7 +1434,9 @@ class Holiday extends CommonObject // Update each user counter foreach ($users as $userCounter) { $nbDaysToAdd = (isset($typeleaves[$userCounter['type']]['newByMonth']) ? $typeleaves[$userCounter['type']]['newByMonth'] : 0); - if (empty($nbDaysToAdd)) continue; + if (empty($nbDaysToAdd)) { + continue; + } dol_syslog("We update leave type id ".$userCounter['type']." for user id ".$userCounter['rowid'], LOG_DEBUG); @@ -1424,15 +1448,13 @@ class Holiday extends CommonObject $result = $this->updateSoldeCP($userCounter['rowid'], $newSolde, $userCounter['type'], $langs->trans('HolidaysMonthlyUpdate')); - if ($result < 0) - { + if ($result < 0) { $error++; break; } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1449,19 +1471,16 @@ class Holiday extends CommonObject $sql = "SELECT nb_holiday FROM ".MAIN_DB_PREFIX."holiday_users"; $sql .= " WHERE fk_user = ".(int) $userID." AND fk_type = ".(int) $fk_type; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { // Update for user $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET"; $sql .= " nb_holiday = ".$nbHoliday; $sql .= " WHERE fk_user = ".(int) $userID." AND fk_type = ".(int) $fk_type; $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $error++; $this->errors[] = $this->db->lasterror(); } @@ -1471,8 +1490,7 @@ class Holiday extends CommonObject $sql .= $nbHoliday; $sql .= ", ".(int) $userID.", ".(int) $fk_type.")"; $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $error++; $this->errors[] = $this->db->lasterror(); } @@ -1482,8 +1500,7 @@ class Holiday extends CommonObject $error++; } - if (!$error) - { + if (!$error) { return 1; } else { return -1; @@ -1527,19 +1544,19 @@ class Holiday extends CommonObject public function createCPusers($single = false, $userid = '') { // do we have to add balance for all users ? - if (!$single) - { + if (!$single) { dol_syslog(get_class($this).'::createCPusers'); $arrayofusers = $this->fetchUsers(false, true); - foreach ($arrayofusers as $users) - { + foreach ($arrayofusers as $users) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users"; $sql .= " (fk_user, nb_holiday)"; $sql .= " VALUES (".((int) $users['rowid'])."', '0')"; $resql = $this->db->query($sql); - if (!$resql) dol_print_error($this->db); + if (!$resql) { + dol_print_error($this->db); + } } } else { $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users"; @@ -1547,7 +1564,9 @@ class Holiday extends CommonObject $sql .= " VALUES (".((int) $userid)."', '0')"; $resql = $this->db->query($sql); - if (!$resql) dol_print_error($this->db); + if (!$resql) { + dol_print_error($this->db); + } } } @@ -1579,16 +1598,20 @@ class Holiday extends CommonObject $sql = "SELECT nb_holiday"; $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users"; $sql .= " WHERE fk_user = ".(int) $user_id; - if ($fk_type > 0) $sql .= " AND fk_type = ".(int) $fk_type; + if ($fk_type > 0) { + $sql .= " AND fk_type = ".(int) $fk_type; + } dol_syslog(get_class($this).'::getCPforUser user_id='.$user_id.' type_id='.$fk_type, LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $obj = $this->db->fetch_object($result); //return number_format($obj->nb_holiday,2); - if ($obj) return $obj->nb_holiday; - else return null; + if ($obj) { + return $obj->nb_holiday; + } else { + return null; + } } else { return null; } @@ -1608,10 +1631,8 @@ class Holiday extends CommonObject dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG); - if ($stringlist) - { - if ($type) - { + if ($stringlist) { + if ($type) { // If user of Dolibarr $sql = "SELECT"; if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { @@ -1620,8 +1641,7 @@ class Holiday extends CommonObject $sql .= " u.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."user as u"; - if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { + if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug"; $sql .= " WHERE ((ug.fk_user = u.rowid"; $sql .= " AND ug.entity IN (".getEntity('usergroup')."))"; @@ -1630,7 +1650,9 @@ class Holiday extends CommonObject $sql .= " WHERE u.entity IN (".getEntity('user').")"; } $sql .= " AND u.statut > 0"; - if ($filters) $sql .= $filters; + if ($filters) { + $sql .= $filters; + } $resql = $this->db->query($sql); @@ -1641,8 +1663,7 @@ class Holiday extends CommonObject $stringlist = ''; // Boucles du listage des utilisateurs - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); if ($i == 0) { @@ -1665,7 +1686,9 @@ class Holiday extends CommonObject $sql = "SELECT DISTINCT cpu.fk_user"; $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u"; $sql .= " WHERE cpu.fk_user = u.rowid"; - if ($filters) $sql .= $filters; + if ($filters) { + $sql .= $filters; + } $resql = $this->db->query($sql); @@ -1676,8 +1699,7 @@ class Holiday extends CommonObject $stringlist = ''; // Boucles du listage des utilisateurs - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); if ($i == 0) { @@ -1699,8 +1721,7 @@ class Holiday extends CommonObject } else { // Si faux donc return array // List for Dolibarr users - if ($type) - { + if ($type) { // If user of Dolibarr $sql = "SELECT"; if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { @@ -1709,8 +1730,7 @@ class Holiday extends CommonObject $sql .= " u.rowid, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut, u.fk_user"; $sql .= " FROM ".MAIN_DB_PREFIX."user as u"; - if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { + if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug"; $sql .= " WHERE ((ug.fk_user = u.rowid"; $sql .= " AND ug.entity IN (".getEntity('usergroup')."))"; @@ -1720,13 +1740,14 @@ class Holiday extends CommonObject } $sql .= " AND u.statut > 0"; - if ($filters) $sql .= $filters; + if ($filters) { + $sql .= $filters; + } $resql = $this->db->query($sql); // Si pas d'erreur SQL - if ($resql) - { + if ($resql) { $i = 0; $tab_result = $this->holiday; $num = $this->db->num_rows($resql); @@ -1761,20 +1782,20 @@ class Holiday extends CommonObject $sql = "SELECT cpu.fk_type, cpu.nb_holiday, u.rowid, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut, u.fk_user"; $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u"; $sql .= " WHERE cpu.fk_user = u.rowid"; - if ($filters) $sql .= $filters; + if ($filters) { + $sql .= $filters; + } $resql = $this->db->query($sql); // Si pas d'erreur SQL - if ($resql) - { + if ($resql) { $i = 0; $tab_result = $this->holiday; $num = $this->db->num_rows($resql); // Boucles du listage des utilisateurs - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $tab_result[$i]['rowid'] = $obj->rowid; // rowid of user @@ -1827,11 +1848,9 @@ class Holiday extends CommonObject dol_syslog(get_class($this)."::fetch_users_approver_holiday sql=".$sql); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num_rows = $this->db->num_rows($result); $i = 0; - while ($i < $num_rows) - { + while ($i < $num_rows) { $objp = $this->db->fetch_object($result); array_push($users_validator, $objp->fk_user); $i++; @@ -1888,7 +1907,9 @@ class Holiday extends CommonObject */ public function verifNbUsers($userDolibarrWithoutCP, $userCP) { - if (empty($userCP)) $userCP = 0; + if (empty($userCP)) { + $userCP = 0; + } dol_syslog(get_class($this).'::verifNbUsers userDolibarr='.$userDolibarrWithoutCP.' userCP='.$userCP); return 1; } @@ -1914,7 +1935,9 @@ class Holiday extends CommonObject $new_solde = price2num($new_solde, 5); //print "$prev_solde == $new_solde"; - if ($prev_solde == $new_solde) return 0; + if ($prev_solde == $new_solde) { + return 0; + } $this->db->begin(); @@ -1938,21 +1961,17 @@ class Holiday extends CommonObject $sql .= ")"; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (!$error) - { + if (!$error) { $this->optRowid = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday_logs"); } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::addLogCP ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2051,23 +2070,26 @@ class Holiday extends CommonObject $sql = "SELECT rowid, code, label, affect, delay, newByMonth"; $sql .= " FROM ".MAIN_DB_PREFIX."c_holiday_types"; $sql .= " WHERE (fk_country IS NULL OR fk_country = ".$mysoc->country_id.')'; - if ($active >= 0) $sql .= " AND active = ".((int) $active); - if ($affect >= 0) $sql .= " AND affect = ".((int) $affect); + if ($active >= 0) { + $sql .= " AND active = ".((int) $active); + } + if ($affect >= 0) { + $sql .= " AND affect = ".((int) $affect); + } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); - if ($num) - { - while ($obj = $this->db->fetch_object($result)) - { + if ($num) { + while ($obj = $this->db->fetch_object($result)) { $types[$obj->rowid] = array('rowid'=> $obj->rowid, 'code'=> $obj->code, 'label'=>$obj->label, 'affect'=>$obj->affect, 'delay'=>$obj->delay, 'newByMonth'=>$obj->newByMonth); } return $types; } - } else dol_print_error($this->db); + } else { + dol_print_error($this->db); + } return array(); } @@ -2095,14 +2117,12 @@ class Holiday extends CommonObject $sql .= " f.fk_validator as fk_user_approve,"; $sql .= " f.fk_user_refuse as fk_user_refuse"; $sql .= " FROM ".MAIN_DB_PREFIX."holiday as f"; - $sql .= " WHERE f.rowid = ".$id; + $sql .= " WHERE f.rowid = ".((int) $id); $sql .= " AND f.entity = ".$conf->entity; $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; @@ -2116,26 +2136,22 @@ class Holiday extends CommonObject $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; - if ($obj->fk_user_creation) - { + if ($obj->fk_user_creation) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_creation); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_modification) - { + if ($obj->fk_user_modification) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modification); $this->user_modification = $muser; } - if ($obj->fk_user_approve) - { + if ($obj->fk_user_approve) { $auser = new User($this->db); $auser->fetch($obj->fk_user_approve); $this->user_approve = $auser; @@ -2191,8 +2207,7 @@ class Holiday extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h"; $sql .= " WHERE h.statut > 1"; $sql .= " AND h.entity IN (".getEntity('holiday').")"; - if (empty($user->rights->expensereport->readall)) - { + if (empty($user->rights->expensereport->readall)) { $userchildids = $user->getAllChildIds(1); $sql .= " AND (h.fk_user IN (".join(',', $userchildids).")"; $sql .= " OR h.fk_validator IN (".join(',', $userchildids)."))"; @@ -2224,7 +2239,9 @@ class Holiday 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(); @@ -2232,16 +2249,14 @@ class Holiday extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h"; $sql .= " WHERE h.statut = 2"; $sql .= " AND h.entity IN (".getEntity('holiday').")"; - if (empty($user->rights->expensereport->read_all)) - { + if (empty($user->rights->expensereport->read_all)) { $userchildids = $user->getAllChildIds(1); $sql .= " AND (h.fk_user IN (".join(',', $userchildids).")"; $sql .= " OR h.fk_validator IN (".join(',', $userchildids)."))"; } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $langs->load("members"); $response = new WorkboardResponse(); @@ -2251,8 +2266,7 @@ class Holiday extends CommonObject $response->url = DOL_URL_ROOT.'/holiday/list.php?search_statut=2&amp;mainmenu=hrm&amp;leftmenu=holiday'; $response->img = img_object('', "holiday"); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; if ($this->db->jdate($obj->date_debut) < ($now - $conf->holiday->approve->warning_delay)) { diff --git a/htdocs/holiday/define_holiday.php b/htdocs/holiday/define_holiday.php index d3a2f23019f..e57e12dcaee 100644 --- a/htdocs/holiday/define_holiday.php +++ b/htdocs/holiday/define_holiday.php @@ -44,19 +44,29 @@ $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 (!$sortfield) $sortfield = "t.rowid"; // Set here default search field -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "t.rowid"; // Set here default search field +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Protection if external user -if ($user->socid > 0) accessforbidden(); +if ($user->socid > 0) { + accessforbidden(); +} // If the user does not have perm to read the page -if (empty($user->rights->holiday->read)) accessforbidden(); +if (empty($user->rights->holiday->read)) { + accessforbidden(); +} // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array @@ -65,8 +75,7 @@ $extrafields = new ExtraFields($db); $holiday = new Holiday($db); -if (empty($conf->holiday->enabled)) -{ +if (empty($conf->holiday->enabled)) { llxHeader('', $langs->trans('CPTitreMenu')); print '<div class="tabBar">'; print '<span style="color: #FF0000;">'.$langs->trans('NotActiveModCP').'</span>'; @@ -81,21 +90,25 @@ if (empty($conf->holiday->enabled)) * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_name = ''; $search_supervisor = ''; $toselect = ''; @@ -104,17 +117,16 @@ if (empty($reshook)) // Mass actions /* - $objectclass='Skeleton'; - $objectlabel='Skeleton'; - $permissiontoread = $user->rights->skeleton->read; - $permissiontodelete = $user->rights->skeleton->delete; - $uploaddir = $conf->skeleton->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - */ + $objectclass='Skeleton'; + $objectlabel='Skeleton'; + $permissiontoread = $user->rights->skeleton->read; + $permissiontodelete = $user->rights->skeleton->delete; + $uploaddir = $conf->skeleton->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + */ // Si il y a une action de mise à jour - if ($action == 'update' && isset($_POST['update_cp'])) - { + if ($action == 'update' && isset($_POST['update_cp'])) { $error = 0; $typeleaves = $holiday->getTypes(1, 1); @@ -122,13 +134,11 @@ if (empty($reshook)) $userID = array_keys($_POST['update_cp']); $userID = $userID[0]; - foreach ($typeleaves as $key => $val) - { + foreach ($typeleaves as $key => $val) { $userValue = $_POST['nb_holiday_'.$val['rowid']]; $userValue = $userValue[$userID]; - if (!empty($userValue) || (string) $userValue == '0') - { + if (!empty($userValue) || (string) $userValue == '0') { $userValue = price2num($userValue, 5); } else { $userValue = ''; @@ -138,37 +148,36 @@ if (empty($reshook)) $comment = ((isset($_POST['note_holiday'][$userID]) && !empty($_POST['note_holiday'][$userID])) ? ' ('.$_POST['note_holiday'][$userID].')' : ''); //print 'holiday: '.$val['rowid'].'-'.$userValue; - if ($userValue != '') - { + if ($userValue != '') { // We add the modification to the log (must be before update of sold because we read current value of sold) $result = $holiday->addLogCP($user->id, $userID, $langs->transnoentitiesnoconv('ManualUpdate').$comment, $userValue, $val['rowid']); - if ($result < 0) - { + if ($result < 0) { setEventMessages($holiday->error, $holiday->errors, 'errors'); $error++; } // Update of the days of the employee $result = $holiday->updateSoldeCP($userID, $userValue, $val['rowid']); - if ($result < 0) - { + if ($result < 0) { setEventMessages($holiday->error, $holiday->errors, 'errors'); $error++; } // If it first update of balance, we set date to avoid to have sold incremented by new month /* - $now=dol_now(); - $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET"; - $sql.= " value = '".dol_print_date($now,'%Y%m%d%H%M%S')."'"; - $sql.= " WHERE name = 'lastUpdate' and value IS NULL"; // Add value IS NULL to be sure to update only at init. - dol_syslog('define_holiday update lastUpdate entry', LOG_DEBUG); - $result = $db->query($sql); - */ + $now=dol_now(); + $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET"; + $sql.= " value = '".dol_print_date($now,'%Y%m%d%H%M%S')."'"; + $sql.= " WHERE name = 'lastUpdate' and value IS NULL"; // Add value IS NULL to be sure to update only at init. + dol_syslog('define_holiday update lastUpdate entry', LOG_DEBUG); + $result = $db->query($sql); + */ } } - if (!$error) setEventMessages('UpdateConfCPOK', '', 'mesgs'); + if (!$error) { + setEventMessages('UpdateConfCPOK', '', 'mesgs'); + } } } @@ -191,7 +200,9 @@ if ($result < 0) { print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="update">'; @@ -217,35 +228,36 @@ $filters = ''; // Filter on array of ids of all childs $userchilds = array(); -if (empty($user->rights->holiday->readall)) -{ +if (empty($user->rights->holiday->readall)) { $userchilds = $user->getAllChildIds(1); $filters .= ' AND u.rowid IN ('.join(', ', $userchilds).')'; } if (!empty($search_name)) { $filters .= natural_search(array('u.firstname', 'u.lastname'), $search_name); } -if ($search_supervisor > 0) $filters .= natural_search(array('u.fk_user'), $search_supervisor, 2); +if ($search_supervisor > 0) { + $filters .= natural_search(array('u.fk_user'), $search_supervisor, 2); +} $filters .= ' AND employee = 1'; // Only employee users are visible $listUsers = $holiday->fetchUsers(false, true, $filters); -if (is_numeric($listUsers) && $listUsers < 0) -{ +if (is_numeric($listUsers) && $listUsers < 0) { setEventMessages($holiday->error, $holiday->errors, 'errors'); } $i = 0; -if (count($typeleaves) == 0) -{ +if (count($typeleaves) == 0) { //print '<div class="info">'; print $langs->trans("NoLeaveWithCounterDefined")."<br>\n"; print $langs->trans("GoIntoDictionaryHolidayTypes"); //print '</div>'; } else { $canedit = 0; - if (!empty($user->rights->holiday->define_holiday)) $canedit = 1; + if (!empty($user->rights->holiday->define_holiday)) { + $canedit = 1; + } $moreforfilter = ''; @@ -263,10 +275,8 @@ if (count($typeleaves) == 0) print '</td>'; // Type of leave request - if (count($typeleaves)) - { - foreach ($typeleaves as $key => $val) - { + if (count($typeleaves)) { + foreach ($typeleaves as $key => $val) { print '<td class="liste_titre" style="text-align:center"></td>'; } } else { @@ -285,10 +295,8 @@ if (count($typeleaves) == 0) print '<tr class="liste_titre">'; print_liste_field_titre('Employee', $_SERVER["PHP_SELF"]); print_liste_field_titre('Supervisor', $_SERVER["PHP_SELF"]); - if (count($typeleaves)) - { - foreach ($typeleaves as $key => $val) - { + if (count($typeleaves)) { + foreach ($typeleaves as $key => $val) { $labeltype = ($langs->trans($val['code']) != $val['code']) ? $langs->trans($val['code']) : $langs->trans($val['label']); print_liste_field_titre($labeltype, $_SERVER["PHP_SELF"], '', '', '', '', '', '', 'center '); } @@ -301,12 +309,12 @@ if (count($typeleaves) == 0) $usersupervisor = new User($db); - foreach ($listUsers as $users) - { + foreach ($listUsers as $users) { // If user has not permission to edit/read all, we must see only subordinates - if (empty($user->rights->holiday->readall)) - { - if (($users['rowid'] != $user->id) && (!in_array($users['rowid'], $userchilds))) continue; // This user is not into hierarchy of current user, we hide it. + if (empty($user->rights->holiday->readall)) { + if (($users['rowid'] != $user->id) && (!in_array($users['rowid'], $userchilds))) { + continue; // This user is not into hierarchy of current user, we hide it. + } } $userstatic->id = $users['rowid']; @@ -318,7 +326,9 @@ if (count($typeleaves) == 0) $userstatic->employee = $users['employee']; $userstatic->fk_user = $users['fk_user']; - if ($userstatic->fk_user > 0) $usersupervisor->fetch($userstatic->fk_user); + if ($userstatic->fk_user > 0) { + $usersupervisor->fetch($userstatic->fk_user); + } print '<tr class="oddeven">'; @@ -329,21 +339,26 @@ if (count($typeleaves) == 0) // Supervisor print '<td>'; - if ($userstatic->fk_user > 0) print $usersupervisor->getNomUrl(-1); + if ($userstatic->fk_user > 0) { + print $usersupervisor->getNomUrl(-1); + } print '</td>'; // Amount for each type - if (count($typeleaves)) - { - foreach ($typeleaves as $key => $val) - { + if (count($typeleaves)) { + foreach ($typeleaves as $key => $val) { $nbtoshow = ''; - if ($holiday->getCPforUser($users['rowid'], $val['rowid']) != '') $nbtoshow = price2num($holiday->getCPforUser($users['rowid'], $val['rowid']), 5); + if ($holiday->getCPforUser($users['rowid'], $val['rowid']) != '') { + $nbtoshow = price2num($holiday->getCPforUser($users['rowid'], $val['rowid']), 5); + } //var_dump($users['rowid'].' - '.$val['rowid']); print '<td style="text-align:center">'; - if ($canedit) print '<input type="text"'.($canedit ? '' : ' disabled="disabled"').' value="'.$nbtoshow.'" name="nb_holiday_'.$val['rowid'].'['.$users['rowid'].']" size="5" style="text-align: center;"/>'; - else print $nbtoshow; + if ($canedit) { + print '<input type="text"'.($canedit ? '' : ' disabled="disabled"').' value="'.$nbtoshow.'" name="nb_holiday_'.$val['rowid'].'['.$users['rowid'].']" size="5" style="text-align: center;"/>'; + } else { + print $nbtoshow; + } //print ' '.$langs->trans('days'); print '</td>'."\n"; } @@ -353,13 +368,14 @@ if (count($typeleaves) == 0) // Note print '<td>'; - if ($canedit) print '<input type="text"'.($canedit ? '' : ' disabled="disabled"').' class="maxwidthonsmartphone" value="" name="note_holiday['.$users['rowid'].']" size="30"/>'; + if ($canedit) { + print '<input type="text"'.($canedit ? '' : ' disabled="disabled"').' class="maxwidthonsmartphone" value="" name="note_holiday['.$users['rowid'].']" size="30"/>'; + } print '</td>'; // Button modify print '<td>'; - if (!empty($user->rights->holiday->define_holiday)) // Allowed to set the balance of any user - { + if (!empty($user->rights->holiday->define_holiday)) { // Allowed to set the balance of any user print '<input type="submit" name="update_cp['.$users['rowid'].']" value="'.dol_escape_htmltag($langs->trans("Save")).'" class="button smallpaddingimp"/>'; } print '</td>'."\n"; diff --git a/htdocs/holiday/document.php b/htdocs/holiday/document.php index f366bb50c85..02fe52a9a4d 100644 --- a/htdocs/holiday/document.php +++ b/htdocs/holiday/document.php @@ -44,35 +44,89 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); -// Security check -if ($user->socid) $socid = $user->socid; -$result = restrictedArea($user, 'holiday', $id, 'holiday'); - // Get parameters $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 (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "position_name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "position_name"; +} +$childids = $user->getAllChildIds(1); + +$morefilter = ''; +if (!empty($conf->global->HOLIDAY_HIDE_FOR_NON_SALARIES)) { + $morefilter = 'AND employee = 1'; +} + $object = new Holiday($db); -$object->fetch($id, $ref); + +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +if (($id > 0) || $ref) { + $object->fetch($id, $ref); + + // Check current user can read this leave request + $canread = 0; + if (!empty($user->rights->holiday->readall)) { + $canread = 1; + } + if (!empty($user->rights->holiday->read) && in_array($object->fk_user, $childids)) { + $canread = 1; + } + if (!$canread) { + accessforbidden(); + } +} + +/*$cancreate = 0; + +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->holiday->writeall_advance)) { + $cancreate = 1; +} +if (!empty($user->rights->holiday->write) && in_array($fuserid, $childids)) { + $cancreate = 1; +} + +$candelete = 0; +if (!empty($user->rights->holiday->delete)) { + $candelete = 1; +} +if ($object->statut == Holiday::STATUS_DRAFT && $user->rights->holiday->write && in_array($object->fk_user, $childids)) { + $candelete = 1; +} +*/ $upload_dir = $conf->holiday->dir_output.'/'.get_exdir(0, 0, 0, 1, $object, ''); $modulepart = 'holiday'; +// Protection if external user +if ($user->socid) { + $socid = $user->socid; +} +$result = restrictedArea($user, 'holiday', $object->id, 'holiday'); + + /* * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -86,8 +140,7 @@ $listhalfday = array('morning'=>$langs->trans("Morning"), "afternoon"=>$langs->t llxHeader("", "", $langs->trans("InterventionCard")); -if ($object->id) -{ +if ($object->id) { $valideur = new User($db); $valideur->fetch($object->fk_validator); @@ -102,8 +155,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -138,8 +190,7 @@ if ($object->id) $starthalfday = ($object->halfday == -1 || $object->halfday == 2) ? 'afternoon' : 'morning'; $endhalfday = ($object->halfday == 1 || $object->halfday == 2) ? 'morning' : 'afternoon'; - if (!$edit) - { + if (!$edit) { print '<tr>'; print '<td>'; print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday")); @@ -162,8 +213,7 @@ if ($object->id) print '</tr>'; } - if (!$edit) - { + if (!$edit) { print '<tr>'; print '<td>'; print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday")); @@ -192,15 +242,18 @@ if ($object->id) $htmlhelp = $langs->trans('NbUseDaysCPHelp'); $includesaturday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY : 1); $includesunday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY : 1); - if ($includesaturday) $htmlhelp .= '<br>'.$langs->trans("DayIsANonWorkingDay", $langs->trans("Saturday")); - if ($includesunday) $htmlhelp .= '<br>'.$langs->trans("DayIsANonWorkingDay", $langs->trans("Sunday")); + if ($includesaturday) { + $htmlhelp .= '<br>'.$langs->trans("DayIsANonWorkingDay", $langs->trans("Saturday")); + } + if ($includesunday) { + $htmlhelp .= '<br>'.$langs->trans("DayIsANonWorkingDay", $langs->trans("Sunday")); + } print $form->textwithpicto($langs->trans('NbUseDaysCP'), $htmlhelp); print '</td>'; print '<td>'.num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday).'</td>'; print '</tr>'; - if ($object->statut == 5) - { + if ($object->statut == 5) { print '<tr>'; print '<td>'.$langs->trans('DetailRefusCP').'</td>'; print '<td>'.$object->detail_refuse.'</td>'; @@ -208,8 +261,7 @@ if ($object->id) } // Description - if (!$edit) - { + if (!$edit) { print '<tr>'; print '<td>'.$langs->trans('DescCP').'</td>'; print '<td>'.nl2br($object->description).'</td>'; @@ -227,67 +279,67 @@ if ($object->id) print '</tbody>'; print '</table>'."\n"; /* - print '</div>'; - print '<div class="fichehalfright">'; - print '<div class="ficheaddleft">'; + print '</div>'; + print '<div class="fichehalfright">'; + print '<div class="ficheaddleft">'; - print '<div class="underbanner clearboth"></div>'; + print '<div class="underbanner clearboth"></div>'; // Info workflow - print '<table class="border tableforfield centpercent">'."\n"; - print '<tbody>'; + print '<table class="border tableforfield centpercent">'."\n"; + print '<tbody>'; - if (! empty($object->fk_user_create)) - { - $userCreate=new User($db); - $userCreate->fetch($object->fk_user_create); - print '<tr>'; - print '<td class="titlefield">'.$langs->trans('RequestByCP').'</td>'; - print '<td>'.$userCreate->getNomUrl(-1).'</td>'; - print '</tr>'; - } + if (! empty($object->fk_user_create)) + { + $userCreate=new User($db); + $userCreate->fetch($object->fk_user_create); + print '<tr>'; + print '<td class="titlefield">'.$langs->trans('RequestByCP').'</td>'; + print '<td>'.$userCreate->getNomUrl(-1).'</td>'; + print '</tr>'; + } - if (!$edit) { - print '<tr>'; - print '<td class="titlefield">'.$langs->trans('ReviewedByCP').'</td>'; - print '<td>'.$valideur->getNomUrl(-1).'</td>'; - print '</tr>'; - } else { - print '<tr>'; - print '<td class="titlefield">'.$langs->trans('ReviewedByCP').'</td>'; - print '<td>'; + if (!$edit) { + print '<tr>'; + print '<td class="titlefield">'.$langs->trans('ReviewedByCP').'</td>'; + print '<td>'.$valideur->getNomUrl(-1).'</td>'; + print '</tr>'; + } else { + print '<tr>'; + print '<td class="titlefield">'.$langs->trans('ReviewedByCP').'</td>'; + print '<td>'; print $form->select_dolusers($object->fk_user, "valideur", 1, ($user->admin ? '' : array($user->id))); // By default, hierarchical parent - print '</td>'; - print '</tr>'; - } + print '</td>'; + print '</tr>'; + } - print '<tr>'; - print '<td>'.$langs->trans('DateCreation').'</td>'; - print '<td>'.dol_print_date($object->date_create,'dayhour').'</td>'; - print '</tr>'; - if ($object->statut == 3) { - print '<tr>'; - print '<td>'.$langs->trans('DateValidCP').'</td>'; - print '<td>'.dol_print_date($object->date_valid,'dayhour').'</td>'; - print '</tr>'; - } - if ($object->statut == 4) { - print '<tr>'; - print '<td>'.$langs->trans('DateCancelCP').'</td>'; - print '<td>'.dol_print_date($object->date_cancel,'dayhour').'</td>'; - print '</tr>'; - } - if ($object->statut == 5) { - print '<tr>'; - print '<td>'.$langs->trans('DateRefusCP').'</td>'; - print '<td>'.dol_print_date($object->date_refuse,'dayhour').'</td>'; - print '</tr>'; - } - print '</tbody>'; - print '</table>'; + print '<tr>'; + print '<td>'.$langs->trans('DateCreation').'</td>'; + print '<td>'.dol_print_date($object->date_create,'dayhour').'</td>'; + print '</tr>'; + if ($object->statut == 3) { + print '<tr>'; + print '<td>'.$langs->trans('DateValidCP').'</td>'; + print '<td>'.dol_print_date($object->date_valid,'dayhour').'</td>'; + print '</tr>'; + } + if ($object->statut == 4) { + print '<tr>'; + print '<td>'.$langs->trans('DateCancelCP').'</td>'; + print '<td>'.dol_print_date($object->date_cancel,'dayhour').'</td>'; + print '</tr>'; + } + if ($object->statut == 5) { + print '<tr>'; + print '<td>'.$langs->trans('DateRefusCP').'</td>'; + print '<td>'.dol_print_date($object->date_refuse,'dayhour').'</td>'; + print '</tr>'; + } + print '</tbody>'; + print '</table>'; - print '</div>'; - print '</div>'; */ + print '</div>'; + print '</div>'; */ print '</div>'; print '<div class="clearboth"></div>'; diff --git a/htdocs/holiday/info.php b/htdocs/holiday/info.php index 2209143001c..3ec95e61a52 100644 --- a/htdocs/holiday/info.php +++ b/htdocs/holiday/info.php @@ -34,30 +34,43 @@ $langs->load("holiday"); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); + $childids = $user->getAllChildIds(1); -// Security check -if ($user->socid) $socid = $user->socid; -$result = restrictedArea($user, 'holiday', $id, 'holiday'); - -$object = new Holiday($db); -if (!$object->fetch($id, $ref) > 0) -{ - dol_print_error($db); +$morefilter = ''; +if (!empty($conf->global->HOLIDAY_HIDE_FOR_NON_SALARIES)) { + $morefilter = 'AND employee = 1'; } -if ($object->id > 0) -{ - // Check current user can read this expense report +$object = new Holiday($db); + +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +if (($id > 0) || $ref) { + $object->fetch($id, $ref); + + // Check current user can read this leave request $canread = 0; - if (!empty($user->rights->holiday->readall)) $canread = 1; - if (!empty($user->rights->holiday->lire) && in_array($object->fk_user_author, $childids)) $canread = 1; - if (!$canread) - { + if (!empty($user->rights->holiday->readall)) { + $canread = 1; + } + if (!empty($user->rights->holiday->read) && in_array($object->fk_user, $childids)) { + $canread = 1; + } + if (!$canread) { accessforbidden(); } } +// Security check +if ($user->socid) { + $socid = $user->socid; +} +$result = restrictedArea($user, 'holiday', $object->id, 'holiday'); + /* * View @@ -69,8 +82,7 @@ $title = $langs->trans("Holiday")." - ".$langs->trans("Info"); $helpurl = ""; llxHeader("", $title, $helpurl); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object = new Holiday($db); $object->fetch($id, $ref); $object->info($object->id); diff --git a/htdocs/holiday/list.php b/htdocs/holiday/list.php index cb8da24052b..4474aecf748 100644 --- a/htdocs/holiday/list.php +++ b/htdocs/holiday/list.php @@ -3,7 +3,7 @@ * Copyright (C) 2013-2020 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2012-2016 Regis Houssin <regis.houssin@inodbox.com> * Copyright (C) 2018 Charlene Benke <charlie@patas-monkey.com> - * Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -40,7 +40,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php'; $langs->loadLangs(array('users', 'other', 'holiday', 'hrm')); // Protection if external user -if ($user->socid > 0) accessforbidden(); +if ($user->socid > 0) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); // The action 'add', 'create', 'edit', 'update', 'view', ... $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) @@ -51,7 +53,7 @@ $toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'holidaylist'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page -$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') $id = GETPOST('id', 'int'); @@ -59,21 +61,24 @@ $childids = $user->getAllChildIds(1); // Security check $socid = 0; -if ($user->socid > 0) // Protection if external user -{ +if ($user->socid > 0) { // Protection if external user //$socid = $user->socid; accessforbidden(); } $result = restrictedArea($user, 'holiday', '', ''); // If we are on the view of a specific user -if ($id > 0) -{ +if ($id > 0) { $canread = 0; - if ($id == $user->id) $canread = 1; - if (!empty($user->rights->holiday->readall)) $canread = 1; - if (!empty($user->rights->holiday->read) && in_array($id, $childids)) $canread = 1; - if (!$canread) - { + if ($id == $user->id) { + $canread = 1; + } + if (!empty($user->rights->holiday->readall)) { + $canread = 1; + } + if (!empty($user->rights->holiday->read) && in_array($id, $childids)) { + $canread = 1; + } + if (!$canread) { accessforbidden(); } } @@ -86,12 +91,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) { $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 = "cp.rowid"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "cp.rowid"; +} $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $search_ref = GETPOST('search_ref', 'alphanohtml'); @@ -145,8 +156,7 @@ $arrayfields = array( // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; -if (empty($conf->holiday->enabled)) -{ +if (empty($conf->holiday->enabled)) { llxHeader('', $langs->trans('CPTitreMenu')); print '<div class="tabBar">'; print '<span style="color: #FF0000;">'.$langs->trans('NotActiveModCP').'</span>'; @@ -160,21 +170,25 @@ if (empty($conf->holiday->enabled)) * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $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)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_ref = ""; $search_month_create = ""; $search_year_create = ""; @@ -190,8 +204,7 @@ if (empty($reshook)) $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -230,8 +243,7 @@ $min_year = 10; // Get current user id $user_id = $user->id; -if ($id > 0) -{ +if ($id > 0) { // Charge utilisateur edite $fuser->fetch($id, '', '', 1); $fuser->getrights(); @@ -282,21 +294,29 @@ $sql .= " ua.statut as validator_status,"; $sql .= " ua.photo as validator_photo"; // 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 : ''); + 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 $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cp.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cp.rowid = ef.fk_object)"; +} $sql .= ", ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua"; $sql .= " WHERE cp.entity IN (".getEntity('holiday').")"; $sql .= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack pour la recherche sur le tableau // Search all -if (!empty($sall)) $sql .= natural_search(array_keys($fieldstosearchall), $sall); +if (!empty($sall)) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} // Ref -if (!empty($search_ref)) $sql .= natural_search("cp.ref", $search_ref); +if (!empty($search_ref)) { + $sql .= natural_search("cp.ref", $search_ref); +} // Start date $sql .= dolSqlDateFilter("cp.date_debut", $search_day_start, $search_month_start, $search_year_start); // End date @@ -320,8 +340,12 @@ if (!empty($search_status) && $search_status != -1) { $sql .= " AND cp.statut = '".$db->escape($search_status)."'\n"; } -if (empty($user->rights->holiday->readall)) $sql .= ' AND cp.fk_user IN ('.join(',', $childids).')'; -if ($id > 0) $sql .= " AND cp.fk_user IN (".$id.")"; +if (empty($user->rights->holiday->readall)) { + $sql .= ' AND cp.fk_user IN ('.join(',', $childids).')'; +} +if ($id > 0) { + $sql .= " AND cp.fk_user IN (".$id.")"; +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -334,12 +358,10 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -350,30 +372,63 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); $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 ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_day_create) $param .= '&search_day_create='.urlencode($search_day_create); - if ($search_month_create) $param .= '&search_month_create='.urlencode($search_month_create); - if ($search_year_create) $param .= '&search_year_create='.urlencode($search_year_create); - if ($search_day_start) $param .= '&search_day_start='.urlencode($search_day_start); - if ($search_month_start) $param .= '&search_month_start='.urlencode($search_month_start); - if ($search_year_start) $param .= '&search_year_start='.urlencode($search_year_start); - if ($search_day_end) $param .= '&search_day_end='.urlencode($search_day_end); - if ($search_month_end) $param .= '&search_month_end='.urlencode($search_month_end); - if ($search_year_end) $param .= '&search_year_end='.urlencode($search_year_end); - if ($search_employee > 0) $param .= '&search_employee='.urlencode($search_employee); - if ($search_valideur > 0) $param .= '&search_valideur='.urlencode($search_valideur); - if ($search_type > 0) $param .= '&search_type='.urlencode($search_type); - if ($search_status > 0) $param .= '&search_status='.urlencode($search_status); + 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 ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_day_create) { + $param .= '&search_day_create='.urlencode($search_day_create); + } + if ($search_month_create) { + $param .= '&search_month_create='.urlencode($search_month_create); + } + if ($search_year_create) { + $param .= '&search_year_create='.urlencode($search_year_create); + } + if ($search_day_start) { + $param .= '&search_day_start='.urlencode($search_day_start); + } + if ($search_month_start) { + $param .= '&search_month_start='.urlencode($search_month_start); + } + if ($search_year_start) { + $param .= '&search_year_start='.urlencode($search_year_start); + } + if ($search_day_end) { + $param .= '&search_day_end='.urlencode($search_day_end); + } + if ($search_month_end) { + $param .= '&search_month_end='.urlencode($search_month_end); + } + if ($search_year_end) { + $param .= '&search_year_end='.urlencode($search_year_end); + } + if ($search_employee > 0) { + $param .= '&search_employee='.urlencode($search_employee); + } + if ($search_valideur > 0) { + $param .= '&search_valideur='.urlencode($search_valideur); + } + if ($search_type > 0) { + $param .= '&search_type='.urlencode($search_type); + } + if ($search_status > 0) { + $param .= '&search_status='.urlencode($search_status); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -383,23 +438,30 @@ if ($resql) //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->holiday->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + if (!empty($user->rights->holiday->delete)) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); + } + if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); // Lines of title fields print '<form id="searchFormList" action="'.$_SERVER["PHP_SELF"].'" method="POST">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="'.($action == 'edit' ? 'update' : 'list').'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; - if ($id > 0) print '<input type="hidden" name="id" value="'.$id.'">'; + if ($id > 0) { + print '<input type="hidden" name="id" value="'.$id.'">'; + } - if ($id > 0) // For user tab - { + if ($id > 0) { // For user tab $title = $langs->trans("User"); $linkback = '<a href="'.DOL_URL_ROOT.'/user/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $head = user_prepare_head($fuser); @@ -408,8 +470,7 @@ if ($resql) dol_banner_tab($fuser, 'id', $linkback, $user->rights->user->user->lire || $user->admin); - if (empty($conf->global->HOLIDAY_HIDE_BALANCE)) - { + if (empty($conf->global->HOLIDAY_HIDE_BALANCE)) { print '<div class="underbanner clearboth"></div>'; print '<br>'; @@ -425,8 +486,7 @@ if ($resql) $canedit = (($user->id == $user_id && $user->rights->holiday->write) || ($user->id != $user_id && (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->holiday->writeall_advance)))); - if ($canedit) - { + if ($canedit) { print '<a href="'.DOL_URL_ROOT.'/holiday/card.php?action=create&fuserid='.$user_id.'" class="butAction">'.$langs->trans("AddCP").'</a>'; } @@ -445,9 +505,10 @@ if ($resql) $trackid = 'leav'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } @@ -455,11 +516,13 @@ if ($resql) $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)) - { + if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -471,7 +534,9 @@ if ($resql) $include = ''; - if (empty($user->rights->holiday->readall)) $include = 'hierarchyme'; // Can see only its hierarchyl + if (empty($user->rights->holiday->readall)) { + $include = 'hierarchyme'; // Can see only its hierarchyl + } print '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; @@ -480,23 +545,22 @@ if ($resql) // Filters print '<tr class="liste_titre_filter">'; - if (!empty($arrayfields['cp.ref']['checked'])) - { + if (!empty($arrayfields['cp.ref']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat maxwidth50" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; print '</td>'; } - if (!empty($arrayfields['cp.fk_user']['checked'])) - { + if (!empty($arrayfields['cp.fk_user']['checked'])) { $morefilter = ''; - if (!empty($conf->global->HOLIDAY_HIDE_FOR_NON_SALARIES)) $morefilter = 'AND employee = 1'; + if (!empty($conf->global->HOLIDAY_HIDE_FOR_NON_SALARIES)) { + $morefilter = 'AND employee = 1'; + } // User $disabled = 0; // If into the tab holiday of a user ($id is set in such a case) - if ($id && !GETPOSTISSET('search_employee')) - { + if ($id && !GETPOSTISSET('search_employee')) { $search_employee = $id; $disabled = 1; } @@ -507,16 +571,16 @@ if ($resql) } // Approver - if (!empty($arrayfields['cp.fk_validator']['checked'])) - { - if ($user->rights->holiday->readall) - { + if (!empty($arrayfields['cp.fk_validator']['checked'])) { + if ($user->rights->holiday->readall) { print '<td class="liste_titre maxwidthonsmartphone left">'; $validator = new UserGroup($db); $excludefilter = $user->admin ? '' : 'u.rowid <> '.$user->id; $valideurobjects = $validator->listUsersForGroup($excludefilter); $valideurarray = array(); - foreach ($valideurobjects as $val) $valideurarray[$val->id] = $val->id; + foreach ($valideurobjects as $val) { + $valideurarray[$val->id] = $val->id; + } print $form->select_dolusers($search_valideur, "search_valideur", 1, "", 0, $valideurarray, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth150'); print '</td>'; } else { @@ -525,16 +589,14 @@ if ($resql) } // Type - if (!empty($arrayfields['cp.fk_type']['checked'])) - { + if (!empty($arrayfields['cp.fk_type']['checked'])) { print '<td class="liste_titre">'; if (empty($mysoc->country_id)) { setEventMessages(null, array($langs->trans("ErrorSetACountryFirst"), $langs->trans("CompanyFoundation")), 'errors'); } else { $typeleaves = $holidaystatic->getTypes(1, -1); $arraytypeleaves = array(); - foreach ($typeleaves as $key => $val) - { + foreach ($typeleaves as $key => $val) { $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']); //$labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')':''); $arraytypeleaves[$val['rowid']] = $labeltoshow; @@ -545,14 +607,12 @@ if ($resql) } // Duration - if (!empty($arrayfields['duration']['checked'])) - { + if (!empty($arrayfields['duration']['checked'])) { print '<td class="liste_titre">&nbsp;</td>'; } // Start date - if (!empty($arrayfields['cp.date_debut']['checked'])) - { + if (!empty($arrayfields['cp.date_debut']['checked'])) { print '<td class="liste_titre center nowraponall">'; print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month_start" value="'.dol_escape_htmltag($search_month_start).'">'; $formother->select_year($search_year_start, 'search_year_start', 1, $min_year, $max_year); @@ -560,8 +620,7 @@ if ($resql) } // End date - if (!empty($arrayfields['cp.date_fin']['checked'])) - { + if (!empty($arrayfields['cp.date_fin']['checked'])) { print '<td class="liste_titre center nowraponall">'; print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month_end" value="'.dol_escape_htmltag($search_month_end).'">'; $formother->select_year($search_year_end, 'search_year_end', 1, $min_year, $max_year); @@ -576,8 +635,7 @@ if ($resql) print $hookmanager->resPrint; // Create date - if (!empty($arrayfields['cp.date_create']['checked'])) - { + if (!empty($arrayfields['cp.date_create']['checked'])) { print '<td class="liste_titre center nowraponall">'; print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month_create" value="'.dol_escape_htmltag($search_month_create).'">'; $formother->select_year($search_year_create, 'search_year_create', 1, $min_year, 0); @@ -585,8 +643,7 @@ if ($resql) } // Create date - if (!empty($arrayfields['cp.tms']['checked'])) - { + if (!empty($arrayfields['cp.tms']['checked'])) { print '<td class="liste_titre center nowraponall">'; print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month_update" value="'.dol_escape_htmltag($search_month_update).'">'; $formother->select_year($search_year_update, 'search_year_update', 1, $min_year, 0); @@ -594,8 +651,7 @@ if ($resql) } // Status - if (!empty($arrayfields['cp.statut']['checked'])) - { + if (!empty($arrayfields['cp.statut']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone maxwidth200 right">'; $object->selectStatutCP($search_status, 'search_status'); print '</td>'; @@ -610,22 +666,42 @@ if ($resql) print "</tr>\n"; print '<tr class="liste_titre">'; - if (!empty($arrayfields['cp.ref']['checked'])) print_liste_field_titre($arrayfields['cp.ref']['label'], $_SERVER["PHP_SELF"], "cp.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['cp.fk_user']['checked'])) print_liste_field_titre($arrayfields['cp.fk_user']['label'], $_SERVER["PHP_SELF"], "cp.fk_user", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['cp.fk_validator']['checked'])) print_liste_field_titre($arrayfields['cp.fk_validator']['label'], $_SERVER["PHP_SELF"], "cp.fk_validator", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['cp.fk_type']['checked'])) print_liste_field_titre($arrayfields['cp.fk_type']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['duration']['checked'])) print_liste_field_titre($arrayfields['duration']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right maxwidth100'); - if (!empty($arrayfields['cp.date_debut']['checked'])) print_liste_field_titre($arrayfields['cp.date_debut']['label'], $_SERVER["PHP_SELF"], "cp.date_debut", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['cp.date_fin']['checked'])) print_liste_field_titre($arrayfields['cp.date_fin']['label'], $_SERVER["PHP_SELF"], "cp.date_fin", "", $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['cp.ref']['checked'])) { + print_liste_field_titre($arrayfields['cp.ref']['label'], $_SERVER["PHP_SELF"], "cp.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['cp.fk_user']['checked'])) { + print_liste_field_titre($arrayfields['cp.fk_user']['label'], $_SERVER["PHP_SELF"], "cp.fk_user", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['cp.fk_validator']['checked'])) { + print_liste_field_titre($arrayfields['cp.fk_validator']['label'], $_SERVER["PHP_SELF"], "cp.fk_validator", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['cp.fk_type']['checked'])) { + print_liste_field_titre($arrayfields['cp.fk_type']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['duration']['checked'])) { + print_liste_field_titre($arrayfields['duration']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right maxwidth100'); + } + if (!empty($arrayfields['cp.date_debut']['checked'])) { + print_liste_field_titre($arrayfields['cp.date_debut']['label'], $_SERVER["PHP_SELF"], "cp.date_debut", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['cp.date_fin']['checked'])) { + print_liste_field_titre($arrayfields['cp.date_fin']['label'], $_SERVER["PHP_SELF"], "cp.date_fin", "", $param, '', $sortfield, $sortorder, 'center '); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $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['cp.date_create']['checked'])) print_liste_field_titre($arrayfields['cp.date_create']['label'], $_SERVER["PHP_SELF"], "cp.date_create", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['cp.tms']['checked'])) print_liste_field_titre($arrayfields['cp.tms']['label'], $_SERVER["PHP_SELF"], "cp.tms", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['cp.statut']['checked'])) print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "cp.statut", "", $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['cp.date_create']['checked'])) { + print_liste_field_titre($arrayfields['cp.date_create']['label'], $_SERVER["PHP_SELF"], "cp.date_create", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['cp.tms']['checked'])) { + print_liste_field_titre($arrayfields['cp.tms']['label'], $_SERVER["PHP_SELF"], "cp.tms", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['cp.statut']['checked'])) { + print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "cp.statut", "", $param, '', $sortfield, $sortorder, 'right '); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print "</tr>\n"; @@ -637,8 +713,7 @@ if ($resql) $langs->load("errors"); print '<tr class="oddeven opacitymediuem"><td colspan="10">'.$langs->trans("NotEnoughPermissions").'</td></tr>'; $result = 0; - } elseif ($num > 0 && !empty($mysoc->country_id)) - { + } elseif ($num > 0 && !empty($mysoc->country_id)) { // Lines $userstatic = new User($db); $approbatorstatic = new User($db); @@ -647,8 +722,7 @@ if ($resql) $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); // Leave request @@ -684,54 +758,61 @@ if ($resql) print '<tr class="oddeven">'; - if (!empty($arrayfields['cp.ref']['checked'])) - { + if (!empty($arrayfields['cp.ref']['checked'])) { print '<td class="nowraponall">'; print $holidaystatic->getNomUrl(1, 1); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cp.fk_user']['checked'])) - { + if (!empty($arrayfields['cp.fk_user']['checked'])) { print '<td class="tdoverflowmax150">'.$userstatic->getNomUrl(-1, 'leave').'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cp.fk_validator']['checked'])) - { + if (!empty($arrayfields['cp.fk_validator']['checked'])) { print '<td class="tdoverflowmax150">'.$approbatorstatic->getNomUrl(-1).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cp.fk_type']['checked'])) - { + if (!empty($arrayfields['cp.fk_type']['checked'])) { print '<td>'; $labeltypeleavetoshow = ($langs->trans($typeleaves[$obj->fk_type]['code']) != $typeleaves[$obj->fk_type]['code'] ? $langs->trans($typeleaves[$obj->fk_type]['code']) : $typeleaves[$obj->fk_type]['label']); print empty($typeleaves[$obj->fk_type]['label']) ? $langs->trans("TypeWasDisabledOrRemoved", $obj->fk_type) : $labeltypeleavetoshow; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['duration']['checked'])) - { + if (!empty($arrayfields['duration']['checked'])) { print '<td class="right">'; $nbopenedday = num_open_day($db->jdate($obj->date_debut, 1), $db->jdate($obj->date_fin, 1), 0, 1, $obj->halfday); print $nbopenedday.' '.$langs->trans('DurationDays'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cp.date_debut']['checked'])) - { + if (!empty($arrayfields['cp.date_debut']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_debut), 'day'); print ' <span class="opacitymedium nowraponall">('.$langs->trans($listhalfday[$starthalfday]).')</span>'; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cp.date_fin']['checked'])) - { + if (!empty($arrayfields['cp.date_fin']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_fin), 'day'); print ' <span class="opacitymedium nowraponall">('.$langs->trans($listhalfday[$endhalfday]).')</span>'; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -742,32 +823,38 @@ if ($resql) print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['cp.date_create']['checked'])) - { + if (!empty($arrayfields['cp.date_create']['checked'])) { print '<td style="text-align: center;">'.dol_print_date($date, 'dayhour').'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cp.tms']['checked'])) - { + if (!empty($arrayfields['cp.tms']['checked'])) { print '<td style="text-align: center;">'.dol_print_date($date_modif, 'dayhour').'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cp.statut']['checked'])) - { + if (!empty($arrayfields['cp.statut']['checked'])) { print '<td class="right nowrap">'.$holidaystatic->getLibStatut(5).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'."\n"; @@ -776,10 +863,13 @@ if ($resql) } // Si il n'y a pas d'enregistrement suite à une recherche - if ($num == 0) - { + 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 '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } @@ -815,8 +905,7 @@ function showMyBalance($holiday, $user_id) $out = ''; $nb_holiday = 0; $typeleaves = $holiday->getTypes(1, 1); - foreach ($typeleaves as $key => $val) - { + foreach ($typeleaves as $key => $val) { $nb_type = $holiday->getCPforUser($user_id, $val['rowid']); $nb_holiday += $nb_type; $out .= ' - '.$val['label'].': <strong>'.($nb_type ?price2num($nb_type) : 0).'</strong><br>'; diff --git a/htdocs/holiday/month_report.php b/htdocs/holiday/month_report.php index b83d957b27f..37497fd1810 100644 --- a/htdocs/holiday/month_report.php +++ b/htdocs/holiday/month_report.php @@ -36,8 +36,7 @@ $langs->loadLangs(array("holiday")); // Security check $socid = 0; -if ($user->socid > 0) // Protection if external user -{ +if ($user->socid > 0) { // Protection if external user //$socid = $user->socid; accessforbidden(); } @@ -57,8 +56,12 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_ $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'alpha'); -if (!$sortfield) $sortfield = "cp.rowid"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "cp.rowid"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} $hookmanager->initHooks(array('leavemovementlist')); @@ -69,21 +72,25 @@ $arrayofmassactions = array(); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_ref = ''; $search_employee = ''; $search_type = ''; @@ -97,8 +104,7 @@ if (empty($reshook)) || GETPOST('button_removefilter', 'alpha') || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') - || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search', 'alpha')) { $massaction = ''; } } @@ -141,16 +147,23 @@ $sql .= " WHERE cp.rowid > 0"; $sql .= " AND cp.statut = 3"; // 3 = Approved $sql .= " AND (date_format(cp.date_debut, '%Y-%m') = '".$db->escape($year_month)."' OR date_format(cp.date_fin, '%Y-%m') = '".$db->escape($year_month)."')"; -if (!empty($search_ref)) $sql .= natural_search('cp.ref', $search_ref); -if (!empty($search_employee)) $sql .= " AND cp.fk_user = '".$db->escape($search_employee)."'"; -if (!empty($search_type)) $sql .= ' AND cp.fk_type IN ('.$db->escape($search_type).')'; -if (!empty($search_description)) $sql .= natural_search('cp.description', $search_description); +if (!empty($search_ref)) { + $sql .= natural_search('cp.ref', $search_ref); +} +if (!empty($search_employee)) { + $sql .= " AND cp.fk_user = '".$db->escape($search_employee)."'"; +} +if (!empty($search_type)) { + $sql .= ' AND cp.fk_type IN ('.$db->escape($search_type).')'; +} +if (!empty($search_description)) { + $sql .= natural_search('cp.description', $search_description); +} $sql .= $db->order($sortfield, $sortorder); $resql = $db->query($sql); -if (empty($resql)) -{ +if (empty($resql)) { dol_print_error($db); exit; } @@ -158,15 +171,29 @@ if (empty($resql)) $num = $db->num_rows($resql); $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($search_ref)) $param .= '&search_ref='.urlencode($search_ref); -if (!empty($search_employee)) $param .= '&search_employee='.urlencode($search_employee); -if (!empty($search_type)) $param .= '&search_type='.urlencode($search_type); -if (!empty($search_description)) $param .= '&search_description='.urlencode($search_description); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +if (!empty($search_ref)) { + $param .= '&search_ref='.urlencode($search_ref); +} +if (!empty($search_employee)) { + $param .= '&search_employee='.urlencode($search_employee); +} +if (!empty($search_type)) { + $param .= '&search_type='.urlencode($search_type); +} +if (!empty($search_description)) { + $param .= '&search_description='.urlencode($search_description); +} print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -215,8 +242,7 @@ if (!empty($arrayfields['cp.fk_user']['checked'])) { if (!empty($arrayfields['ct.label']['checked'])) { $typeleaves = $holidaystatic->getTypes(1, -1); $arraytypeleaves = array(); - foreach ($typeleaves as $key => $val) - { + foreach ($typeleaves as $key => $val) { $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']); $arraytypeleaves[$val['rowid']] = $labeltoshow; } @@ -226,12 +252,24 @@ if (!empty($arrayfields['ct.label']['checked'])) { print '</td>'; } -if (!empty($arrayfields['cp.date_debut']['checked'])) print '<td class="liste_titre"></td>'; -if (!empty($arrayfields['cp.date_fin']['checked'])) print '<td class="liste_titre"></td>'; -if (!empty($arrayfields['used_days']['checked'])) print '<td class="liste_titre"></td>'; -if (!empty($arrayfields['date_start_month']['checked'])) print '<td class="liste_titre"></td>'; -if (!empty($arrayfields['date_end_month']['checked'])) print '<td class="liste_titre"></td>'; -if (!empty($arrayfields['used_days_month']['checked'])) print '<td class="liste_titre"></td>'; +if (!empty($arrayfields['cp.date_debut']['checked'])) { + print '<td class="liste_titre"></td>'; +} +if (!empty($arrayfields['cp.date_fin']['checked'])) { + print '<td class="liste_titre"></td>'; +} +if (!empty($arrayfields['used_days']['checked'])) { + print '<td class="liste_titre"></td>'; +} +if (!empty($arrayfields['date_start_month']['checked'])) { + print '<td class="liste_titre"></td>'; +} +if (!empty($arrayfields['date_end_month']['checked'])) { + print '<td class="liste_titre"></td>'; +} +if (!empty($arrayfields['used_days_month']['checked'])) { + print '<td class="liste_titre"></td>'; +} // Filter: Description if (!empty($arrayfields['cp.description']['checked'])) { @@ -248,26 +286,43 @@ print '</td>'; print '</tr>'; print '<tr class="liste_titre">'; -if (!empty($arrayfields['cp.ref']['checked'])) print_liste_field_titre($arrayfields['cp.ref']['label'], $_SERVER["PHP_SELF"], 'cp.ref', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['cp.fk_user']['checked'])) print_liste_field_titre($arrayfields['cp.fk_user']['label'], $_SERVER["PHP_SELF"], 'cp.fk_user', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['ct.label']['checked'])) print_liste_field_titre($arrayfields['ct.label']['label'], $_SERVER["PHP_SELF"], 'ct.label', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['cp.date_debut']['checked'])) print_liste_field_titre($arrayfields['cp.date_debut']['label'], $_SERVER["PHP_SELF"], 'cp.date_debut', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['cp.date_fin']['checked'])) print_liste_field_titre($arrayfields['cp.date_fin']['label'], $_SERVER["PHP_SELF"], 'cp.date_fin', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['used_days']['checked'])) print_liste_field_titre($arrayfields['used_days']['label'], $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['date_start_month']['checked'])) print_liste_field_titre($arrayfields['date_start_month']['label'], $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['date_end_month']['checked'])) print_liste_field_titre($arrayfields['date_end_month']['label'], $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['used_days_month']['checked'])) print_liste_field_titre($arrayfields['used_days_month']['label'], $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['cp.description']['checked'])) print_liste_field_titre($arrayfields['cp.description']['label'], $_SERVER["PHP_SELF"], 'cp.description', '', '', '', $sortfield, $sortorder); +if (!empty($arrayfields['cp.ref']['checked'])) { + print_liste_field_titre($arrayfields['cp.ref']['label'], $_SERVER["PHP_SELF"], 'cp.ref', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['cp.fk_user']['checked'])) { + print_liste_field_titre($arrayfields['cp.fk_user']['label'], $_SERVER["PHP_SELF"], 'cp.fk_user', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['ct.label']['checked'])) { + print_liste_field_titre($arrayfields['ct.label']['label'], $_SERVER["PHP_SELF"], 'ct.label', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['cp.date_debut']['checked'])) { + print_liste_field_titre($arrayfields['cp.date_debut']['label'], $_SERVER["PHP_SELF"], 'cp.date_debut', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['cp.date_fin']['checked'])) { + print_liste_field_titre($arrayfields['cp.date_fin']['label'], $_SERVER["PHP_SELF"], 'cp.date_fin', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['used_days']['checked'])) { + print_liste_field_titre($arrayfields['used_days']['label'], $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['date_start_month']['checked'])) { + print_liste_field_titre($arrayfields['date_start_month']['label'], $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['date_end_month']['checked'])) { + print_liste_field_titre($arrayfields['date_end_month']['label'], $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['used_days_month']['checked'])) { + print_liste_field_titre($arrayfields['used_days_month']['label'], $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['cp.description']['checked'])) { + print_liste_field_titre($arrayfields['cp.description']['label'], $_SERVER["PHP_SELF"], 'cp.description', '', '', '', $sortfield, $sortorder); +} print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; print '</tr>'; -if ($num == 0) -{ +if ($num == 0) { print '<tr><td colspan="10" class="opacitymedium">'.$langs->trans('None').'</td></tr>'; -} -else { - while ($obj = $db->fetch_object($resql)) - { +} else { + while ($obj = $db->fetch_object($resql)) { $user = new User($db); $user->fetch($obj->fk_user); @@ -289,19 +344,25 @@ else { // Set date_start_gmt and date_end_gmt that are date to show for the selected month $date_start_inmonth = $db->jdate($obj->date_debut, true); $date_end_inmonth = $db->jdate($obj->date_fin, true); - if ($tmpstart['year'] < $search_year || $tmpstart['mon'] < $search_month) - { + if ($tmpstart['year'] < $search_year || $tmpstart['mon'] < $search_month) { $date_start_inmonth = dol_get_first_day($search_year, $search_month, true); $starthalfdayinmonth = 'morning'; - if ($halfdayinmonth == 2) $halfdayinmonth = 1; - if ($halfdayinmonth == -1) $halfdayinmonth = 0; + if ($halfdayinmonth == 2) { + $halfdayinmonth = 1; + } + if ($halfdayinmonth == -1) { + $halfdayinmonth = 0; + } } - if ($tmpend['year'] > $search_year || $tmpend['mon'] > $search_month) - { + if ($tmpend['year'] > $search_year || $tmpend['mon'] > $search_month) { $date_end_inmonth = dol_get_last_day($search_year, $search_month, true) - ((24 * 3600) - 1); $endhalfdayinmonth = 'afternoon'; - if ($halfdayinmonth == 2) $halfdayinmonth = -1; - if ($halfdayinmonth == 1) $halfdayinmonth = 0; + if ($halfdayinmonth == 2) { + $halfdayinmonth = -1; + } + if ($halfdayinmonth == 1) { + $halfdayinmonth = 0; + } } // Leave request @@ -310,42 +371,50 @@ else { print '<tr class="oddeven">'; - if (!empty($arrayfields['cp.ref']['checked'])) print '<td>'.$holidaystatic->getNomUrl(1, 1).'</td>'; - if (!empty($arrayfields['cp.fk_user']['checked'])) print '<td>'.$user->getFullName($langs).'</td>'; - if (!empty($arrayfields['ct.label']['checked'])) print '<td>'.$obj->label.'</td>'; + if (!empty($arrayfields['cp.ref']['checked'])) { + print '<td>'.$holidaystatic->getNomUrl(1, 1).'</td>'; + } + if (!empty($arrayfields['cp.fk_user']['checked'])) { + print '<td>'.$user->getFullName($langs).'</td>'; + } + if (!empty($arrayfields['ct.label']['checked'])) { + print '<td>'.$obj->label.'</td>'; + } - if (!empty($arrayfields['cp.date_debut']['checked'])) - { + if (!empty($arrayfields['cp.date_debut']['checked'])) { print '<td class="center">'.dol_print_date($db->jdate($obj->date_debut), 'day'); print ' <span class="opacitymedium">('.$langs->trans($listhalfday[$starthalfday]).')</span>'; print '</td>'; } - if (!empty($arrayfields['cp.date_fin']['checked'])) - { + if (!empty($arrayfields['cp.date_fin']['checked'])) { print '<td class="center">'.dol_print_date($db->jdate($obj->date_fin), 'day'); print ' <span class="opacitymedium">('.$langs->trans($listhalfday[$endhalfday]).')</span>'; print '</td>'; } - if (!empty($arrayfields['used_days']['checked'])) print '<td class="right">'.num_open_day($date_start, $date_end, 0, 1, $obj->halfday).'</td>'; + if (!empty($arrayfields['used_days']['checked'])) { + print '<td class="right">'.num_open_day($date_start, $date_end, 0, 1, $obj->halfday).'</td>'; + } - if (!empty($arrayfields['date_start_month']['checked'])) - { + if (!empty($arrayfields['date_start_month']['checked'])) { print '<td class="center">'.dol_print_date($date_start_inmonth, 'day'); print ' <span class="opacitymedium">('.$langs->trans($listhalfday[$starthalfdayinmonth]).')</span>'; print '</td>'; } - if (!empty($arrayfields['date_end_month']['checked'])) - { + if (!empty($arrayfields['date_end_month']['checked'])) { print '<td class="center">'.dol_print_date($date_end_inmonth, 'day'); print ' <span class="opacitymedium">('.$langs->trans($listhalfday[$endhalfdayinmonth]).')</span>'; print '</td>'; } - if (!empty($arrayfields['used_days_month']['checked'])) print '<td class="right">'.num_open_day($date_start_inmonth, $date_end_inmonth, 0, 1, $halfdayinmonth).'</td>'; - if (!empty($arrayfields['cp.description']['checked'])) print '<td class="maxwidth300">'.dol_escape_htmltag(dolGetFirstLineOfText($obj->description)).'</td>'; + if (!empty($arrayfields['used_days_month']['checked'])) { + print '<td class="right">'.num_open_day($date_start_inmonth, $date_end_inmonth, 0, 1, $halfdayinmonth).'</td>'; + } + if (!empty($arrayfields['cp.description']['checked'])) { + print '<td class="maxwidth300">'.dol_escape_htmltag(dolGetFirstLineOfText($obj->description)).'</td>'; + } print '<td></td>'; print '</tr>'; diff --git a/htdocs/holiday/view_log.php b/htdocs/holiday/view_log.php index 2f2e223c87c..a2ecbe1e8b3 100644 --- a/htdocs/holiday/view_log.php +++ b/htdocs/holiday/view_log.php @@ -61,15 +61,23 @@ $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 = "cpl.rowid"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "cpl.rowid"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} // Si l'utilisateur n'a pas le droit de lire cette page -if (!$user->rights->holiday->readall) accessforbidden(); +if (!$user->rights->holiday->readall) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('users', 'other', 'holiday')); @@ -83,8 +91,7 @@ $hookmanager->initHooks(array('leavemovementlist')); // Note that conf->hooks_mo $arrayfields = array(); $arrayofmassactions = array(); -if (empty($conf->holiday->enabled)) -{ +if (empty($conf->holiday->enabled)) { llxHeader('', $langs->trans('CPTitreMenu')); print '<div class="tabBar">'; print '<span style="color: #FF0000;">'.$langs->trans('NotActiveModCP').'</span>'; @@ -98,12 +105,18 @@ if (empty($conf->holiday->enabled)) * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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)) { // Selection of new fields @@ -129,8 +142,7 @@ if (empty($reshook)) { || GETPOST('button_removefilter', 'alpha') || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') - || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -184,13 +196,27 @@ if (!empty($search_year) && $search_year > 0) { $sqlwhere .= "AND date_action BETWEEN '".$db->idate($from_date)."' AND '".$db->idate($to_date)."'"; } -if (!empty($search_id) && $search_id > 0) $sqlwhere .= natural_search('rowid', $search_id, 1); -if (!empty($search_validator) && $search_validator > 0) $sqlwhere .= natural_search('fk_user_action', $search_validator, 1); -if (!empty($search_employee) && $search_employee > 0) $sqlwhere .= natural_search('fk_user_update', $search_employee, 1); -if (!empty($search_description)) $sqlwhere .= natural_search('type_action', $search_description); -if (!empty($search_type) && $search_type > 0) $sqlwhere .= natural_search('fk_type', $search_type, 1); -if (!empty($search_prev_solde)) $sqlwhere .= natural_search('prev_solde', $search_prev_solde, 1); -if (!empty($search_new_solde)) $sqlwhere .= natural_search('new_solde', $search_new_solde, 1); +if (!empty($search_id) && $search_id > 0) { + $sqlwhere .= natural_search('rowid', $search_id, 1); +} +if (!empty($search_validator) && $search_validator > 0) { + $sqlwhere .= natural_search('fk_user_action', $search_validator, 1); +} +if (!empty($search_employee) && $search_employee > 0) { + $sqlwhere .= natural_search('fk_user_update', $search_employee, 1); +} +if (!empty($search_description)) { + $sqlwhere .= natural_search('type_action', $search_description); +} +if (!empty($search_type) && $search_type > 0) { + $sqlwhere .= natural_search('fk_type', $search_type, 1); +} +if (!empty($search_prev_solde)) { + $sqlwhere .= natural_search('prev_solde', $search_prev_solde, 1); +} +if (!empty($search_new_solde)) { + $sqlwhere .= natural_search('new_solde', $search_new_solde, 1); +} $sqlorder = $db->order($sortfield, $sortorder); @@ -214,20 +240,44 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $num = is_array($object->logs) ? count($object->logs) : 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 (!empty($search_id)) $param .= '&search_statut='.urlencode($search_statut); -if (!empty($search_month) && $search_month > 0) $param .= '&search_month='.urlencode($search_month); -if (!empty($search_year) && $search_year > 0) $param .= '&search_year='.urlencode($search_year); -if (!empty($search_validator) && $search_validator > 0) $param .= '&search_validator='.urlencode($search_validator); -if (!empty($search_employee) && $search_employee > 0) $param .= '&search_employee='.urlencode($search_employee); -if (!empty($search_description)) $param .= '&search_description='.urlencode($search_description); -if (!empty($search_type) && $search_type > 0) $param .= '&search_type='.urlencode($search_type); -if (!empty($search_prev_solde)) $param .= '&search_prev_solde='.urlencode($search_prev_solde); -if (!empty($search_new_solde)) $param .= '&search_new_solde='.urlencode($search_new_solde); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +if (!empty($search_id)) { + $param .= '&search_statut='.urlencode($search_statut); +} +if (!empty($search_month) && $search_month > 0) { + $param .= '&search_month='.urlencode($search_month); +} +if (!empty($search_year) && $search_year > 0) { + $param .= '&search_year='.urlencode($search_year); +} +if (!empty($search_validator) && $search_validator > 0) { + $param .= '&search_validator='.urlencode($search_validator); +} +if (!empty($search_employee) && $search_employee > 0) { + $param .= '&search_employee='.urlencode($search_employee); +} +if (!empty($search_description)) { + $param .= '&search_description='.urlencode($search_description); +} +if (!empty($search_type) && $search_type > 0) { + $param .= '&search_type='.urlencode($search_type); +} +if (!empty($search_prev_solde)) { + $param .= '&search_prev_solde='.urlencode($search_prev_solde); +} +if (!empty($search_new_solde)) { + $param .= '&search_new_solde='.urlencode($search_new_solde); +} print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -348,23 +398,40 @@ print '</td>'; print '</tr>'; print '<tr class="liste_titre">'; -if (!empty($arrayfields['cpl.rowid']['checked'])) print_liste_field_titre($arrayfields['cpl.rowid']['label'], $_SERVER["PHP_SELF"], 'rowid', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['cpl.date_action']['checked'])) print_liste_field_titre($arrayfields['cpl.date_action']['label'], $_SERVER["PHP_SELF"], 'date_action', '', '', '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['cpl.fk_user_action']['checked'])) print_liste_field_titre($arrayfields['cpl.fk_user_action']['label'], $_SERVER["PHP_SELF"], 'fk_user_action', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['cpl.fk_user_update']['checked'])) print_liste_field_titre($arrayfields['cpl.fk_user_update']['label'], $_SERVER["PHP_SELF"], 'fk_user_update', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['cpl.type_action']['checked'])) print_liste_field_titre($arrayfields['cpl.type_action']['label'], $_SERVER["PHP_SELF"], 'type_action', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['cpl.fk_type']['checked'])) print_liste_field_titre($arrayfields['cpl.fk_type']['label'], $_SERVER["PHP_SELF"], 'fk_type', '', '', '', $sortfield, $sortorder); -if (!empty($arrayfields['cpl.prev_solde']['checked'])) print_liste_field_titre($arrayfields['cpl.prev_solde']['label'], $_SERVER["PHP_SELF"], 'prev_solde', '', '', '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['variation']['checked'])) print_liste_field_titre($arrayfields['variation']['label'], $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['cpl.new_solde']['checked'])) print_liste_field_titre($arrayfields['cpl.new_solde']['label'], $_SERVER["PHP_SELF"], 'new_solde', '', '', '', $sortfield, $sortorder, 'right '); +if (!empty($arrayfields['cpl.rowid']['checked'])) { + print_liste_field_titre($arrayfields['cpl.rowid']['label'], $_SERVER["PHP_SELF"], 'rowid', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['cpl.date_action']['checked'])) { + print_liste_field_titre($arrayfields['cpl.date_action']['label'], $_SERVER["PHP_SELF"], 'date_action', '', '', '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['cpl.fk_user_action']['checked'])) { + print_liste_field_titre($arrayfields['cpl.fk_user_action']['label'], $_SERVER["PHP_SELF"], 'fk_user_action', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['cpl.fk_user_update']['checked'])) { + print_liste_field_titre($arrayfields['cpl.fk_user_update']['label'], $_SERVER["PHP_SELF"], 'fk_user_update', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['cpl.type_action']['checked'])) { + print_liste_field_titre($arrayfields['cpl.type_action']['label'], $_SERVER["PHP_SELF"], 'type_action', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['cpl.fk_type']['checked'])) { + print_liste_field_titre($arrayfields['cpl.fk_type']['label'], $_SERVER["PHP_SELF"], 'fk_type', '', '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['cpl.prev_solde']['checked'])) { + print_liste_field_titre($arrayfields['cpl.prev_solde']['label'], $_SERVER["PHP_SELF"], 'prev_solde', '', '', '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['variation']['checked'])) { + print_liste_field_titre($arrayfields['variation']['label'], $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['cpl.new_solde']['checked'])) { + print_liste_field_titre($arrayfields['cpl.new_solde']['label'], $_SERVER["PHP_SELF"], 'new_solde', '', '', '', $sortfield, $sortorder, 'right '); +} print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print '</tr>'; // TODO: $i = 0; $i = 1; -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { //TODO: $obj = $db->fetch_object($resql); $obj = next($object->logs); diff --git a/htdocs/hrm/admin/admin_establishment.php b/htdocs/hrm/admin/admin_establishment.php index a777ada50f9..eb61b7e7807 100644 --- a/htdocs/hrm/admin/admin_establishment.php +++ b/htdocs/hrm/admin/admin_establishment.php @@ -27,8 +27,9 @@ require_once DOL_DOCUMENT_ROOT.'/hrm/class/establishment.class.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'hrm')); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $error = 0; @@ -52,8 +53,12 @@ llxHeader('', $langs->trans("Establishments")); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortorder = GETPOST("sortorder", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha'); -if (!$sortorder) $sortorder = "DESC"; -if (!$sortfield) $sortfield = "e.rowid"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "e.rowid"; +} if (empty($page) || $page == -1) { $page = 0; @@ -79,8 +84,7 @@ $sql .= $db->order($sortfield, $sortorder); $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; @@ -95,12 +99,10 @@ if ($result) print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "e.status", "", "", '', $sortfield, $sortorder, 'right '); print "</tr>\n"; - if ($num > 0) - { + if ($num > 0) { $establishmentstatic = new Establishment($db); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($result); $establishmentstatic->id = $obj->rowid; diff --git a/htdocs/hrm/admin/admin_hrm.php b/htdocs/hrm/admin/admin_hrm.php index c4081e1d454..0131539071a 100644 --- a/htdocs/hrm/admin/admin_hrm.php +++ b/htdocs/hrm/admin/admin_hrm.php @@ -27,8 +27,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'hrm')); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); diff --git a/htdocs/hrm/class/establishment.class.php b/htdocs/hrm/class/establishment.class.php index dc97787ae6e..bca81f2e45d 100644 --- a/htdocs/hrm/class/establishment.class.php +++ b/htdocs/hrm/class/establishment.class.php @@ -180,7 +180,9 @@ class Establishment extends CommonObject $this->zip = trim($this->zip); $this->town = trim($this->town); - if (empty($this->ref)) $this->ref = '(PROV)'; + if (empty($this->ref)) { + $this->ref = '(PROV)'; + } $this->db->begin(); @@ -248,8 +250,7 @@ class Establishment extends CommonObject global $langs; // Check parameters - if (empty($this->label)) - { + if (empty($this->label)) { $this->error = 'ErrorBadParameter'; return -1; } @@ -292,12 +293,11 @@ class Establishment extends CommonObject $sql .= ' c.code as country_code, c.label as country'; $sql .= " FROM ".MAIN_DB_PREFIX."establishment as e"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON e.fk_country = c.rowid'; - $sql .= " WHERE e.rowid = ".$id; + $sql .= " WHERE e.rowid = ".((int) $id); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -330,12 +330,11 @@ class Establishment extends CommonObject { $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."establishment WHERE rowid = ".$id; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."establishment WHERE rowid = ".((int) $id); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->db->commit(); return 1; } else { @@ -367,8 +366,7 @@ class Establishment extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[self::STATUS_OPEN] = $langs->trans('Open'); @@ -378,8 +376,12 @@ class Establishment extends CommonObject } $statusType = 'status'.$status; - if ($status == self::STATUS_OPEN) $statusType = 'status4'; - if ($status == self::STATUS_CLOSED) $statusType = 'status6'; + if ($status == self::STATUS_OPEN) { + $statusType = 'status4'; + } + if ($status == self::STATUS_CLOSED) { + $statusType = 'status6'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -395,27 +397,23 @@ class Establishment extends CommonObject { $sql = 'SELECT e.rowid, e.ref, e.datec, e.fk_user_author, e.tms, e.fk_user_mod, e.entity'; $sql .= ' FROM '.MAIN_DB_PREFIX.'establishment as e'; - $sql .= ' WHERE e.rowid = '.$id; + $sql .= ' WHERE e.rowid = '.((int) $id); dol_syslog(get_class($this)."::fetch info", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; $this->date_creation = $this->db->jdate($obj->datec); - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_mod) - { + if ($obj->fk_user_mod) { $muser = new User($this->db); $muser->fetch($obj->fk_user_mod); $this->user_modification = $muser; @@ -449,9 +447,15 @@ class Establishment extends CommonObject $label = '<u>'.$langs->trans("Establishment").'</u>'; $label .= '<br>'.$langs->trans("Label").': '.$this->label; - if ($withpicto) $result .= ($link.img_object($label, $picto).$linkend); - if ($withpicto && $withpicto != 2) $result .= ' '; - if ($withpicto != 2) $result .= $link.$this->label.$linkend; + if ($withpicto) { + $result .= ($link.img_object($label, $picto).$linkend); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + if ($withpicto != 2) { + $result .= $link.$this->label.$linkend; + } return $result; } @@ -465,10 +469,14 @@ class Establishment extends CommonObject global $mysoc; // We return country code of bank account - if (!empty($this->country_code)) return $this->country_code; + if (!empty($this->country_code)) { + return $this->country_code; + } // We return country code of managed company - if (!empty($mysoc->country_code)) return $mysoc->country_code; + if (!empty($mysoc->country_code)) { + return $mysoc->country_code; + } return ''; } diff --git a/htdocs/hrm/establishment/card.php b/htdocs/hrm/establishment/card.php index 15fd44e2c3b..a46ebfa28f3 100644 --- a/htdocs/hrm/establishment/card.php +++ b/htdocs/hrm/establishment/card.php @@ -29,7 +29,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; $langs->loadLangs(array('admin', 'hrm')); // Security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $error = 0; @@ -44,7 +46,9 @@ static $tmpstatus2label = array( '1'=>'OpenEtablishment' ); $status2label = array(''); -foreach ($tmpstatus2label as $key => $val) $status2label[$key] = $langs->trans($val); +foreach ($tmpstatus2label as $key => $val) { + $status2label[$key] = $langs->trans($val); +} $object = new Establishment($db); @@ -56,31 +60,25 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ * Actions */ -if ($action == 'confirm_delete' && $confirm == "yes") -{ +if ($action == 'confirm_delete' && $confirm == "yes") { $result = $object->delete($id); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ../admin/admin_establishment.php"); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } -} elseif ($action == 'add') -{ - if (!$cancel) - { +} elseif ($action == 'add') { + if (!$cancel) { $error = 0; $object->label = GETPOST('label', 'alpha'); - if (empty($object->label)) - { + if (empty($object->label)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); $error++; } - if (empty($error)) - { + if (empty($error)) { $object->address = GETPOST('address', 'alpha'); $object->zip = GETPOST('zipcode', 'alpha'); $object->town = GETPOST('town', 'alpha'); @@ -92,8 +90,7 @@ if ($action == 'confirm_delete' && $confirm == "yes") $id = $object->create($user); - if ($id > 0) - { + if ($id > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { @@ -106,11 +103,8 @@ if ($action == 'confirm_delete' && $confirm == "yes") header("Location: ../admin/admin_establishment.php"); exit; } -} - -// Update record -elseif ($action == 'update') -{ +} elseif ($action == 'update') { + // Update record $error = 0; if (!$cancel) { @@ -120,8 +114,7 @@ elseif ($action == 'update') $error++; } - if (empty($error)) - { + if (empty($error)) { $object->label = GETPOST('label', 'alphanohtml'); $object->address = GETPOST('address', 'alpha'); $object->zip = GETPOST('zipcode', 'alpha'); @@ -133,8 +126,7 @@ elseif ($action == 'update') $result = $object->update($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_POST['id']); exit; } else { @@ -159,8 +151,7 @@ $formcompany = new FormCompany($db); /* * Action create */ -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewEstablishment")); print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">'; @@ -228,7 +219,9 @@ if ($action == 'create') print '<td>'.$form->editfieldkey('Country', 'selectcountry_id', '', $object, 0).'</td>'; print '<td class="maxwidthonsmartphone">'; print $form->select_country(GETPOSTISSET('country_id') ? GETPOST('country_id', 'int') : ($object->country_id ? $object->country_id : $mysoc->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 '</td>'; print '</tr>'; @@ -253,15 +246,12 @@ if ($action == 'create') } // Part to edit record -if (($id || $ref) && $action == 'edit') -{ +if (($id || $ref) && $action == 'edit') { $result = $object->fetch($id); - if ($result > 0) - { + if ($result > 0) { $head = establishment_prepare_head($object); - if ($action == 'edit') - { + if ($action == 'edit') { print dol_get_fiche_head($head, 'card', $langs->trans("Establishment"), 0, 'building'); print '<form name="update" action="'.$_SERVER["PHP_SELF"].'" method="POST">'."\n"; @@ -284,12 +274,12 @@ if (($id || $ref) && $action == 'edit') // Entity /* - if (! empty($conf->multicompany->enabled)) { - print '<tr><td>'.$form->editfieldkey('Parent', 'entity', '', $object, 0, 'string', '', 1).'</td>'; + if (! empty($conf->multicompany->enabled)) { + print '<tr><td>'.$form->editfieldkey('Parent', 'entity', '', $object, 0, 'string', '', 1).'</td>'; print '<td class="maxwidthonsmartphone">'; print $object->entity > 0 ? $object->entity : $conf->entity; - print '</td></tr>'; - }*/ + print '</td></tr>'; + }*/ // Address print '<tr><td>'.$form->editfieldkey('Address', 'address', '', $object, 0).'</td>'; @@ -313,7 +303,9 @@ if (($id || $ref) && $action == 'edit') print '<tr><td>'.$form->editfieldkey('Country', 'selectcountry_id', '', $object, 0).'</td>'; print '<td class="maxwidthonsmartphone">'; print $form->select_country($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 '</td>'; print '</tr>'; @@ -334,19 +326,19 @@ if (($id || $ref) && $action == 'edit') print '</form>'; } - } else dol_print_error($db); + } else { + dol_print_error($db); + } } -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_optionals(); $head = establishment_prepare_head($object); print dol_get_fiche_head($head, 'card', $langs->trans("Establishment"), -1, 'building'); // Confirmation to delete - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("DeleteEstablishment"), $langs->trans("ConfirmDeleteEstablishment"), "confirm_delete"); } @@ -404,8 +396,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<tr>'; print '<td>'.$langs->trans("Country").'</td>'; print '<td>'; - if ($object->country_id > 0) - { + if ($object->country_id > 0) { $img = picto_from_langcode($object->country_code); print $img ? $img.' ' : ''; print getCountry($object->getCountryCode(), 0, $db); @@ -421,9 +412,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print dol_get_fiche_end(); /* - * Barre d'actions - */ - + * Action bar + */ print '<div class="tabsAction">'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&id='.$id.'">'.$langs->trans('Modify').'</a>'; print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&id='.$id.'">'.$langs->trans('Delete').'</a>'; diff --git a/htdocs/hrm/establishment/info.php b/htdocs/hrm/establishment/info.php index 3185f897958..f72b381a2d8 100644 --- a/htdocs/hrm/establishment/info.php +++ b/htdocs/hrm/establishment/info.php @@ -37,7 +37,9 @@ $backtopage = GETPOST('backtopage', 'alpha'); 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)); } @@ -47,12 +49,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 (!$sortfield) $sortfield = 'a.datep,a.id'; -if (!$sortorder) $sortorder = 'DESC,DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC'; +} // Initialize technical objects $object = new Establishment($db); @@ -64,7 +72,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->hrm->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->hrm->multidir_output[$object->entity]."/".$object->id; +} // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); @@ -80,20 +90,19 @@ $permissiontoadd = $user->rights->hrm->write; // Used by the include of actions_ $parameters = array('id'=>$id); $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 (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // 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 $actioncode = ''; $search_agenda_label = ''; } @@ -107,14 +116,15 @@ if (empty($reshook)) $form = new Form($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $title = $langs->trans("Agenda"); //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; $help_url = ''; llxHeader('', $title, $help_url); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = establishment_prepare_head($object); diff --git a/htdocs/hrm/index.php b/htdocs/hrm/index.php index f0bbb442acc..e40ceb3f9ba 100644 --- a/htdocs/hrm/index.php +++ b/htdocs/hrm/index.php @@ -4,6 +4,7 @@ * Copyright (C) 2012-2014 Regis Houssin <regis.houssin@inodbox.com> * Copyright (C) 2015-2016 Alexandre Spangaro <aspangaro@open-dsi.fr> * Copyright (C) 2019 Nicolas ZABOURI <info@inovea-conseil.com> + * Copyright (C) 2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -33,8 +34,12 @@ require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php'; -if ($conf->deplacement->enabled) require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php'; -if ($conf->expensereport->enabled) require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +if ($conf->deplacement->enabled) { + require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php'; +} +if ($conf->expensereport->enabled) { + require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +} require_once DOL_DOCUMENT_ROOT.'/recruitment/class/recruitmentcandidature.class.php'; require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; @@ -47,9 +52,13 @@ $langs->loadLangs(array('users', 'holidays', 'trips', 'boxes')); $socid = GETPOST("socid", "int"); // Protection if external user -if ($user->socid > 0) accessforbidden(); +if ($user->socid > 0) { + accessforbidden(); +} -if (empty($conf->global->MAIN_INFO_SOCIETE_NOM) || empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) $setupcompanynotcomplete = 1; +if (empty($conf->global->MAIN_INFO_SOCIETE_NOM) || empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) { + $setupcompanynotcomplete = 1; +} $holiday = new Holiday($db); $holidaystatic = new Holiday($db); @@ -63,8 +72,7 @@ $max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; */ // Update sold -if (!empty($conf->holiday->enabled) && !empty($setupcompanynotcomplete)) -{ +if (!empty($conf->holiday->enabled) && !empty($setupcompanynotcomplete)) { $result = $holiday->updateBalance(); } @@ -81,8 +89,7 @@ llxHeader('', $langs->trans('HRMArea')); print load_fiche_titre($langs->trans("HRMArea"), '', 'hrm'); -if (!empty($setupcompanynotcomplete)) -{ +if (!empty($setupcompanynotcomplete)) { $langs->load("errors"); $warnpicto = img_warning($langs->trans("WarningMandatorySetupNotComplete")); print '<br><div class="warning"><a href="'.DOL_URL_ROOT.'/admin/company.php?mainmenu=home'.(empty($setupcompanynotcomplete) ? '' : '&action=edit').'">'.$warnpicto.' '.$langs->trans("WarningMandatorySetupNotComplete").'</a></div>'; @@ -94,36 +101,34 @@ if (!empty($setupcompanynotcomplete)) print '<div class="fichecenter"><div class="fichethirdleft">'; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ - if (!empty($conf->holiday->enabled) && $user->rights->holiday->read) - { +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo + if (!empty($conf->holiday->enabled) && $user->rights->holiday->read) { $langs->load("holiday"); $listofsearchfields['search_holiday'] = array('text'=>'TitreRequestCP'); } - if (!empty($conf->deplacement->enabled) && $user->rights->deplacement->lire) - { + if (!empty($conf->deplacement->enabled) && $user->rights->deplacement->lire) { $langs->load("trips"); $listofsearchfields['search_deplacement'] = array('text'=>'ExpenseReport'); } - if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) - { + if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) { $langs->load("trips"); $listofsearchfields['search_expensereport'] = array('text'=>'ExpenseReport'); } - if (count($listofsearchfields)) - { + if (count($listofsearchfields)) { print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<div class="div-table-responsive-no-min">'; print '<table class="noborder nohover centpercent">'; $i = 0; - foreach ($listofsearchfields as $key => $value) - { - if ($i == 0) print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>'; + foreach ($listofsearchfields as $key => $value) { + if ($i == 0) { + print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>'; + } print '<tr '.$bc[false].'>'; print '<td class="nowrap"><label for="'.$key.'">'.$langs->trans($value["text"]).'</label></td><td><input type="text" class="flat inputsearch" name="'.$key.'" id="'.$key.'" size="18"></td>'; - if ($i == 0) print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>'; + if ($i == 0) { + print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>'; + } print '</tr>'; $i++; } @@ -135,10 +140,8 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useles } -if (!empty($conf->holiday->enabled)) -{ - if (empty($conf->global->HOLIDAY_HIDE_BALANCE)) - { +if (!empty($conf->holiday->enabled)) { + if (empty($conf->global->HOLIDAY_HIDE_BALANCE)) { $user_id = $user->id; print '<div class="div-table-responsive-no-min">'; @@ -148,9 +151,9 @@ if (!empty($conf->holiday->enabled)) print '<td colspan="3">'; $out = ''; + $nb_holiday = 0; $typeleaves = $holiday->getTypes(1, 1); - foreach ($typeleaves as $key => $val) - { + foreach ($typeleaves as $key => $val) { $nb_type = $holiday->getCPforUser($user->id, $val['rowid']); $nb_holiday += $nb_type; $out .= ' - '.($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']).': <strong>'.($nb_type ? price2num($nb_type) : 0).'</strong><br>'; @@ -161,8 +164,7 @@ if (!empty($conf->holiday->enabled)) print '</td>'; print '</tr>'; print '</table></div><br>'; - } elseif (!is_numeric($conf->global->HOLIDAY_HIDE_BALANCE)) - { + } elseif (!is_numeric($conf->global->HOLIDAY_HIDE_BALANCE)) { print $langs->trans($conf->global->HOLIDAY_HIDE_BALANCE).'<br>'; } } @@ -173,22 +175,22 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; // Latest leave requests -if (!empty($conf->holiday->enabled) && $user->rights->holiday->read) -{ +if (!empty($conf->holiday->enabled) && $user->rights->holiday->read) { $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.photo, u.statut as user_status,"; $sql .= " x.rowid, x.rowid as ref, x.fk_type, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.tms as dm, x.statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u"; $sql .= " WHERE u.rowid = x.fk_user"; $sql .= " AND x.entity = ".$conf->entity; - if (empty($user->rights->holiday->readall)) $sql .= ' AND x.fk_user IN ('.join(',', $childids).')'; + if (empty($user->rights->holiday->readall)) { + $sql .= ' AND x.fk_user IN ('.join(',', $childids).')'; + } //if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND x.fk_soc = s. rowid AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; //if (!empty($socid)) $sql.= " AND x.fk_soc = ".$socid; $sql .= $db->order("x.tms", "DESC"); $sql .= $db->plimit($max, 0); $result = $db->query($sql); - if ($result) - { + if ($result) { $var = false; $num = $db->num_rows($result); @@ -208,10 +210,8 @@ if (!empty($conf->holiday->enabled) && $user->rights->holiday->read) print '<th>'.$langs->trans("to").'</th>'; print '<th class="right" colspan="2"><a href="'.DOL_URL_ROOT.'/holiday/list.php?sortfield=cp.tms&sortorder=DESC">'.$langs->trans("FullList").'</th>'; print '</tr>'; - if ($num) - { - while ($i < $num && $i < $max) - { + if ($num) { + while ($i < $num && $i < $max) { $obj = $db->fetch_object($result); $holidaystatic->id = $obj->rowid; @@ -248,28 +248,30 @@ if (!empty($conf->holiday->enabled) && $user->rights->holiday->read) print '</table>'; print '</div>'; print '<br>'; - } else dol_print_error($db); + } else { + dol_print_error($db); + } } // Latest expense report -if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) -{ +if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) { $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.statut as user_status, u.photo,"; $sql .= " x.rowid, x.ref, x.date_debut as date, x.tms as dm, x.total_ttc, x.fk_statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as x, ".MAIN_DB_PREFIX."user as u"; //if (!$user->rights->societe->client->voir && !$user->socid) $sql.= ", ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= " WHERE u.rowid = x.fk_user_author"; $sql .= " AND x.entity = ".$conf->entity; - if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) $sql .= ' AND x.fk_user_author IN ('.join(',', $childids).')'; + if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) { + $sql .= ' AND x.fk_user_author IN ('.join(',', $childids).')'; + } //if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND x.fk_soc = s. rowid AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; //if (!empty($socid)) $sql.= " AND x.fk_soc = ".$socid; $sql .= $db->order("x.tms", "DESC"); $sql .= $db->plimit($max, 0); $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $i = 0; @@ -281,14 +283,12 @@ if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) print '<th class="right">'.$langs->trans("TotalTTC").'</th>'; print '<th class="right" colspan="2"><a href="'.DOL_URL_ROOT.'/expensereport/list.php?sortfield=d.tms&sortorder=DESC">'.$langs->trans("FullList").'</th>'; print '</tr>'; - if ($num) - { + if ($num) { $total_ttc = $totalam = $total = 0; $expensereportstatic = new ExpenseReport($db); $userstatic = new User($db); - while ($i < $num && $i < $max) - { + while ($i < $num && $i < $max) { $obj = $db->fetch_object($result); $expensereportstatic->id = $obj->rowid; @@ -320,26 +320,32 @@ if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) print '</table>'; print '</div>'; print '<br>'; - } else dol_print_error($db); + } else { + dol_print_error($db); + } } // Last modified job position -if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read) -{ +if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read) { $sql = "SELECT rc.rowid, rc.ref, rc.email, rc.lastname, rc.firstname, rc.date_creation, rc.tms, rc.status"; $sql .= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature as rc"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as s ON rc.fk_recruitmentjobposition = s.rowid"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE rc.entity IN (".getEntity($staticrecruitmentjobposition->element).")"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.fk_soc = $socid"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.fk_soc = $socid"; + } $sql .= " ORDER BY rc.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -351,10 +357,8 @@ if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitme print '</th>'; print '<th class="right" colspan="2"><a href="'.DOL_URL_ROOT.'/recruitment/recruitmentcandidature_list.php?sortfield=t.tms&sortorder=DESC">'.$langs->trans("FullList").'</th>'; print '</tr>'; - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $objp = $db->fetch_object($resql); $staticrecruitmentcandidature->id = $objp->rowid; $staticrecruitmentcandidature->ref = $objp->ref; diff --git a/htdocs/imports/class/import.class.php b/htdocs/imports/class/import.class.php index 19b71cb8cd3..567aaf754a8 100644 --- a/htdocs/imports/class/import.class.php +++ b/htdocs/imports/class/import.class.php @@ -2,6 +2,7 @@ /* Copyright (C) 2011 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr> * Copyright (C) 2020 Ahmad Jamaly Rabib <rabib@metroworks.co.jp> + * Copyright (C) 2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -87,15 +88,17 @@ class Import $modulesdir = dolGetModulesDirs(); // Load list of modules - foreach ($modulesdir as $dir) - { + foreach ($modulesdir as $dir) { $handle = @opendir(dol_osencode($dir)); - if (!is_resource($handle)) continue; + if (!is_resource($handle)) { + continue; + } // Search module files - while (($file = readdir($handle)) !== false) - { - if (!preg_match("/^(mod.*)\.class\.php/i", $file, $reg)) continue; + while (($file = readdir($handle)) !== false) { + if (!preg_match("/^(mod.*)\.class\.php/i", $file, $reg)) { + continue; + } $modulename = $reg[1]; @@ -103,10 +106,16 @@ class Import $enabled = true; $part = strtolower(preg_replace('/^mod/i', '', $modulename)); // Adds condition for propal module - if ($part === 'propale') $part = 'propal'; - if (empty($conf->$part->enabled)) $enabled = false; + if ($part === 'propale') { + $part = 'propal'; + } + if (empty($conf->$part->enabled)) { + $enabled = false; + } - if (empty($enabled)) continue; + if (empty($enabled)) { + continue; + } // Init load class $file = $dir."/".$modulename.".class.php"; @@ -114,11 +123,11 @@ class Import require_once $file; $module = new $classname($this->db); - if (isset($module->import_code) && is_array($module->import_code)) - { - foreach ($module->import_code as $r => $value) - { - if ($filter && ($filter != $module->import_code[$r])) continue; + if (isset($module->import_code) && is_array($module->import_code)) { + foreach ($module->import_code as $r => $value) { + if ($filter && ($filter != $module->import_code[$r])) { + continue; + } // Test if permissions are ok /*$perm=$module->import_permission[$r][0]; @@ -137,10 +146,8 @@ class Import // Load lang file $langtoload = $module->getLangFilesArray(); - if (is_array($langtoload)) - { - foreach ($langtoload as $key) - { + if (is_array($langtoload)) { + foreach ($langtoload as $key) { $langs->load($key); } } @@ -160,15 +167,15 @@ class Import // Array of fields to import (key=field, value=label) $this->array_import_fields[$i] = $module->import_fields_array[$r]; // Array of hidden fields to import (key=field, value=label) - $this->array_import_fieldshidden[$i] = $module->import_fieldshidden_array[$r]; + $this->array_import_fieldshidden[$i] = (isset($module->import_fieldshidden_array[$r]) ? $module->import_fieldshidden_array[$r] : ''); // Tableau des entites a exporter (cle=champ, valeur=entite) $this->array_import_entities[$i] = $module->import_entities_array[$r]; // Tableau des alias a exporter (cle=champ, valeur=alias) - $this->array_import_regex[$i] = $module->import_regex_array[$r]; + $this->array_import_regex[$i] = (isset($module->import_regex_array[$r]) ? $module->import_regex_array[$r] : ''); // Array of columns allowed as UPDATE options - $this->array_import_updatekeys[$i] = $module->import_updatekeys_array[$r]; + $this->array_import_updatekeys[$i] = (isset($module->import_updatekeys_array[$r]) ? $module->import_updatekeys_array[$r] : ''); // Array of examples - $this->array_import_examplevalues[$i] = $module->import_examplevalues_array[$r]; + $this->array_import_examplevalues[$i] = (isset($module->import_examplevalues_array[$r]) ? $module->import_examplevalues_array[$r] : ''); // Tableau des regles de conversion d'une valeur depuis une autre source (cle=champ, valeur=tableau des regles) $this->array_import_convertvalue[$i] = (isset($module->import_convertvalue_array[$r]) ? $module->import_convertvalue_array[$r] : ''); // Sql request to run after import @@ -246,9 +253,15 @@ class Import dol_syslog("Import.class.php::create"); // Check parameters - if (empty($this->model_name)) { $this->error = 'ErrorWrongParameters'; return -1; } - if (empty($this->datatoimport)) { $this->error = 'ErrorWrongParameters'; return -1; } - if (empty($this->hexa)) { $this->error = 'ErrorWrongParameters'; return -1; } + if (empty($this->model_name)) { + $this->error = 'ErrorWrongParameters'; return -1; + } + if (empty($this->datatoimport)) { + $this->error = 'ErrorWrongParameters'; return -1; + } + if (empty($this->hexa)) { + $this->error = 'ErrorWrongParameters'; return -1; + } $this->db->begin(); @@ -259,8 +272,7 @@ class Import dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { @@ -285,11 +297,9 @@ class Import dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $obj = $this->db->fetch_object($result); - if ($obj) - { + if ($obj) { $this->id = $obj->rowid; $this->hexa = $obj->field; $this->model_name = $obj->label; @@ -319,32 +329,30 @@ class Import $error = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."import_model"; - $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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { /* Not used. This is not a business object. To convert it we must herit from CommonObject - // Call trigger - $result=$this->call_trigger('IMPORT_DELETE',$user); - if ($result < 0) $error++; - // End call triggers - */ + // Call trigger + $result=$this->call_trigger('IMPORT_DELETE',$user); + if ($result < 0) $error++; + // End call triggers + */ } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } diff --git a/htdocs/imports/emptyexample.php b/htdocs/imports/emptyexample.php index 7e7cec1707e..a50a2fc9996 100644 --- a/htdocs/imports/emptyexample.php +++ b/htdocs/imports/emptyexample.php @@ -21,7 +21,9 @@ * \brief Show example of import file */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +} /** @@ -58,8 +60,7 @@ $format = GETPOST('format'); $langs->load("exports"); // Check exportkey -if (empty($datatoimport)) -{ +if (empty($datatoimport)) { $user->getrights(); llxHeader(); @@ -81,23 +82,30 @@ $fieldstarget = $objimport->array_import_fields[0]; $valuestarget = $objimport->array_import_examplevalues[0]; $attachment = true; -if (isset($_GET["attachment"])) $attachment = $_GET["attachment"]; +if (isset($_GET["attachment"])) { + $attachment = $_GET["attachment"]; +} //$attachment = false; $contenttype = dol_mimetype($format); -if (isset($_GET["contenttype"])) $contenttype = $_GET["contenttype"]; +if (isset($_GET["contenttype"])) { + $contenttype = $_GET["contenttype"]; +} //$contenttype='text/plain'; $outputencoding = 'UTF-8'; -if ($contenttype) header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : '')); -if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"'); +if ($contenttype) { + header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : '')); +} +if ($attachment) { + header('Content-Disposition: attachment; filename="'.$filename.'"'); +} // List of targets fields $headerlinefields = array(); $contentlinevalues = array(); $i = 0; -foreach ($fieldstarget as $code=>$label) -{ +foreach ($fieldstarget as $code => $label) { $withoutstar = preg_replace('/\*/', '', $fieldstarget[$code]); $headerlinefields[] = $langs->transnoentities($withoutstar).($withoutstar != $fieldstarget[$code] ? '*' : '').' ('.$code.')'; $contentlinevalues[] = $valuestarget[$code]; diff --git a/htdocs/imports/import.php b/htdocs/imports/import.php index 1f8e6bb0bea..50ab14dfce5 100644 --- a/htdocs/imports/import.php +++ b/htdocs/imports/import.php @@ -41,61 +41,61 @@ $result = restrictedArea($user, 'import'); // Map icons, array duplicated in export.php, was not synchronized, TODO put it somewhere only once $entitytoicon = array( 'invoice' => 'bill', - 'invoice_line' => 'bill', + 'invoice_line' => 'bill', 'order' => 'order', - 'order_line' => 'order', + 'order_line' => 'order', 'propal' => 'propal', - 'propal_line' => 'propal', + 'propal_line' => 'propal', 'intervention' => 'intervention', - 'inter_line' => 'intervention', + 'inter_line' => 'intervention', 'member' => 'user', - 'member_type' => 'group', - 'subscription' => 'payment', - 'payment' => 'payment', + 'member_type' => 'group', + 'subscription' => 'payment', + 'payment' => 'payment', 'tax' => 'bill', - 'tax_type' => 'generic', - 'other' => 'generic', + 'tax_type' => 'generic', + 'other' => 'generic', 'account' => 'account', 'product' => 'product', - 'virtualproduct'=>'product', + 'virtualproduct'=>'product', 'subproduct' => 'product', 'product_supplier_ref' => 'product', - 'stock' => 'stock', + 'stock' => 'stock', 'warehouse' => 'stock', 'batch' => 'stock', 'stockbatch' => 'stock', 'category' => 'category', 'shipment' => 'sending', - 'shipment_line'=> 'sending', - 'reception'=> 'sending', - 'reception_line'=> 'sending', + 'shipment_line'=> 'sending', + 'reception'=> 'sending', + 'reception_line'=> 'sending', 'expensereport'=> 'trip', - 'expensereport_line'=> 'trip', + 'expensereport_line'=> 'trip', 'holiday' => 'holiday', - 'contract_line' => 'contract', - 'translation' => 'generic', - 'bomm' => 'bom', - 'bomline' => 'bom' + 'contract_line' => 'contract', + 'translation' => 'generic', + 'bomm' => 'bom', + 'bomline' => 'bom' ); // Translation code, array duplicated in export.php, was not synchronized, TODO put it somewhere only once $entitytolang = array( 'user' => 'User', 'company' => 'Company', - 'contact' => 'Contact', + 'contact' => 'Contact', 'invoice' => 'Bill', - 'invoice_line' => 'InvoiceLine', + 'invoice_line' => 'InvoiceLine', 'order' => 'Order', - 'order_line' => 'OrderLine', - 'propal' => 'Proposal', - 'propal_line' => 'ProposalLine', + 'order_line' => 'OrderLine', + 'propal' => 'Proposal', + 'propal_line' => 'ProposalLine', 'intervention' => 'Intervention', - 'inter_line' => 'InterLine', + 'inter_line' => 'InterLine', 'member' => 'Member', - 'member_type' => 'MemberType', - 'subscription' => 'Subscription', + 'member_type' => 'MemberType', + 'subscription' => 'Subscription', 'tax' => 'SocialContribution', - 'tax_type' => 'DictionarySocialContributions', + 'tax_type' => 'DictionarySocialContributions', 'account' => 'BankTransactions', 'payment' => 'Payment', 'product' => 'Product', @@ -103,28 +103,28 @@ $entitytolang = array( 'subproduct' => 'SubProduct', 'product_supplier_ref' => 'SupplierPrices', 'service' => 'Service', - 'stock' => 'Stock', + 'stock' => 'Stock', 'movement' => 'StockMovement', 'batch' => 'Batch', 'stockbatch' => 'StockDetailPerBatch', 'warehouse' => 'Warehouse', 'category' => 'Category', 'other' => 'Other', - 'trip' => 'TripsAndExpenses', - 'shipment' => 'Shipments', - 'shipment_line'=> 'ShipmentLine', - 'project' => 'Projects', - 'projecttask' => 'Tasks', - 'task_time' => 'TaskTimeSpent', + 'trip' => 'TripsAndExpenses', + 'shipment' => 'Shipments', + 'shipment_line'=> 'ShipmentLine', + 'project' => 'Projects', + 'projecttask' => 'Tasks', + 'task_time' => 'TaskTimeSpent', 'action' => 'Event', 'expensereport'=> 'ExpenseReport', 'expensereport_line'=> 'ExpenseReportLine', 'holiday' => 'TitreRequestCP', 'contract' => 'Contract', - 'contract_line'=> 'ContractLine', - 'translation' => 'Translation', - 'bom' => 'BOM', - 'bomline' => 'BOMLine' + 'contract_line'=> 'ContractLine', + 'translation' => 'Translation', + 'bom' => 'BOM', + 'bomline' => 'BOMLine' ); $datatoimport = GETPOST('datatoimport'); @@ -155,13 +155,11 @@ $formfile = new FormFile($db); $serialized_array_match_file_to_database = isset($_SESSION["dol_array_match_file_to_database"]) ? $_SESSION["dol_array_match_file_to_database"] : ''; $array_match_file_to_database = array(); $fieldsarray = explode(',', $serialized_array_match_file_to_database); -foreach ($fieldsarray as $elem) -{ +foreach ($fieldsarray as $elem) { $tabelem = explode('=', $elem, 2); $key = $tabelem[0]; $val = (isset($tabelem[1]) ? $tabelem[1] : ''); - if ($key && $val) - { + if ($key && $val) { $array_match_file_to_database[$key] = $val; } } @@ -196,37 +194,32 @@ if ($action=='downfield' || $action=='upfield') } } */ -if ($action == 'builddoc') -{ +if ($action == 'builddoc') { // Build import file $result = $objimport->build_file($user, GETPOST('model', 'alpha'), $datatoimport, $array_match_file_to_database); - if ($result < 0) - { + if ($result < 0) { setEventMessages($objimport->error, $objimport->errors, 'errors'); } else { setEventMessages($langs->trans("FileSuccessfullyBuilt"), null, 'mesgs'); } } -if ($action == 'deleteprof') -{ - if (GETPOST("id", 'int')) - { +if ($action == 'deleteprof') { + if (GETPOST("id", 'int')) { $objimport->fetch(GETPOST("id", 'int')); $result = $objimport->delete($user); } } // Save import config to database -if ($action == 'add_import_model') -{ - if ($import_name) - { +if ($action == 'add_import_model') { + if ($import_name) { // Set save string $hexa = ''; - foreach ($array_match_file_to_database as $key=>$val) - { - if ($hexa) $hexa .= ','; + foreach ($array_match_file_to_database as $key => $val) { + if ($hexa) { + $hexa .= ','; + } $hexa .= $key.'='.$val; } @@ -235,13 +228,11 @@ if ($action == 'add_import_model') $objimport->hexa = $hexa; $result = $objimport->create($user); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans("ImportModelSaved", $objimport->model_name), null, 'mesgs'); } else { $langs->load("errors"); - if ($objimport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($objimport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') { setEventMessages($langs->trans("ErrorImportDuplicateProfil"), null, 'errors'); } else { setEventMessages($objimport->error, null, 'errors'); @@ -252,16 +243,13 @@ if ($action == 'add_import_model') } } -if ($step == 3 && $datatoimport) -{ - if (GETPOST('sendit') && !empty($conf->global->MAIN_UPLOAD_DOC)) - { +if ($step == 3 && $datatoimport) { + if (GETPOST('sendit') && !empty($conf->global->MAIN_UPLOAD_DOC)) { dol_mkdir($conf->import->dir_temp); $nowyearmonth = dol_print_date(dol_now(), '%Y%m%d%H%M%S'); $fullpath = $conf->import->dir_temp."/".$nowyearmonth.'-'.$_FILES['userfile']['name']; - if (dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $fullpath, 1) > 0) - { + if (dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $fullpath, 1) > 0) { dol_syslog("File ".$fullpath." was added for import"); } else { $langs->load("errors"); @@ -270,25 +258,30 @@ if ($step == 3 && $datatoimport) } // Delete file - if ($action == 'confirm_deletefile' && $confirm == 'yes') - { + if ($action == 'confirm_deletefile' && $confirm == 'yes') { $langs->load("other"); $param = '&datatoimport='.urlencode($datatoimport).'&format='.urlencode($format); - if ($excludefirstline) $param .= '&excludefirstline='.urlencode($excludefirstline); - if ($endatlinenb) $param .= '&endatlinenb='.urlencode($endatlinenb); + if ($excludefirstline) { + $param .= '&excludefirstline='.urlencode($excludefirstline); + } + if ($endatlinenb) { + $param .= '&endatlinenb='.urlencode($endatlinenb); + } $file = $conf->import->dir_temp.'/'.GETPOST('urlfile'); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP). $ret = dol_delete_file($file); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors'); + if ($ret) { + setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors'); + } Header('Location: '.$_SERVER["PHP_SELF"].'?step='.$step.$param); exit; } } -if ($step == 4 && $action == 'select_model') -{ +if ($step == 4 && $action == 'select_model') { // Reinit match arrays $_SESSION["dol_array_match_file_to_database"] = ''; $serialized_array_match_file_to_database = ''; @@ -297,17 +290,14 @@ if ($step == 4 && $action == 'select_model') // Load model from $importmodelid and set $array_match_file_to_database // and $_SESSION["dol_array_match_file_to_database"] $result = $objimport->fetch($importmodelid); - if ($result > 0) - { + if ($result > 0) { $serialized_array_match_file_to_database = $objimport->hexa; $fieldsarray = explode(',', $serialized_array_match_file_to_database); - foreach ($fieldsarray as $elem) - { + foreach ($fieldsarray as $elem) { $tabelem = explode('=', $elem); $key = $tabelem[0]; $val = $tabelem[1]; - if ($key && $val) - { + if ($key && $val) { $array_match_file_to_database[$key] = $val; } } @@ -315,8 +305,7 @@ if ($step == 4 && $action == 'select_model') } } -if ($action == 'saveorder') -{ +if ($action == 'saveorder') { // Enregistrement de la position des champs dol_syslog("boxorder=".$_GET['boxorder']." datatoimport=".$_GET["datatoimport"], LOG_DEBUG); $part = explode(':', $_GET['boxorder']); @@ -332,15 +321,12 @@ if ($action == 'saveorder') $array_match_file_to_database = array(); $fieldsarray = explode(',', $list); $pos = 0; - foreach ($fieldsarray as $fieldnb) // For each elem in list. fieldnb start from 1 to ... - { + foreach ($fieldsarray as $fieldnb) { // For each elem in list. fieldnb start from 1 to ... // Get name of database fields at position $pos and put it into $namefield $posbis = 0; $namefield = ''; - foreach ($fieldstarget as $key => $val) // key: val: - { + foreach ($fieldstarget as $key => $val) { // key: val: //dol_syslog('AjaxImport key='.$key.' val='.$val); - if ($posbis < $pos) - { + if ($posbis < $pos) { $posbis++; continue; } @@ -351,10 +337,11 @@ if ($action == 'saveorder') break; } - if ($fieldnb && $namefield) - { + if ($fieldnb && $namefield) { $array_match_file_to_database[$fieldnb] = $namefield; - if ($serialized_array_match_file_to_database) $serialized_array_match_file_to_database .= ','; + if ($serialized_array_match_file_to_database) { + $serialized_array_match_file_to_database .= ','; + } $serialized_array_match_file_to_database .= ($fieldnb.'='.$namefield); } @@ -374,21 +361,31 @@ if ($action == 'saveorder') */ +$help_url = 'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones'; + + // STEP 1: Page to select dataset to import -if ($step == 1 || !$datatoimport) -{ +if ($step == 1 || !$datatoimport) { // Clean saved file-database matching $serialized_array_match_file_to_database = ''; $array_match_file_to_database = array(); $_SESSION["dol_array_match_file_to_database"] = ''; $param = ''; - if ($excludefirstline) $param .= '&excludefirstline='.urlencode($excludefirstline); - if ($endatlinenb) $param .= '&endatlinenb='.urlencode($endatlinenb); - if ($separator) $param .= '&separator='.urlencode($separator); - if ($enclosure) $param .= '&enclosure='.urlencode($enclosure); + if ($excludefirstline) { + $param .= '&excludefirstline='.urlencode($excludefirstline); + } + if ($endatlinenb) { + $param .= '&endatlinenb='.urlencode($endatlinenb); + } + if ($separator) { + $param .= '&separator='.urlencode($separator); + } + if ($enclosure) { + $param .= '&enclosure='.urlencode($enclosure); + } - llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones'); + llxHeader('', $langs->trans("NewImport"), $help_url); $head = import_prepare_head($param, 1); @@ -405,16 +402,16 @@ if ($step == 1 || !$datatoimport) print '<td>&nbsp;</td>'; print '</tr>'; - if (count($objimport->array_import_module)) - { + if (count($objimport->array_import_module)) { $sortedarrayofmodules = dol_sort_array($objimport->array_import_module, 'position_of_profile', 'asc', 0, 0, 1); - foreach ($sortedarrayofmodules as $key => $value) - { + foreach ($sortedarrayofmodules as $key => $value) { //var_dump($key.' '.$value['position_of_profile'].' '.$value['import_code'].' '.$objimport->array_import_module[$key]['module']->getName().' '.$objimport->array_import_code[$key]); print '<tr class="oddeven"><td>'; $titleofmodule = $objimport->array_import_module[$key]['module']->getName(); // Special cas for import common to module/services - if (in_array($objimport->array_import_code[$key], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) $titleofmodule = $langs->trans("ProductOrService"); + if (in_array($objimport->array_import_code[$key], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) { + $titleofmodule = $langs->trans("ProductOrService"); + } print $titleofmodule; print '</td><td>'; $entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[$key]); @@ -422,8 +419,7 @@ if ($step == 1 || !$datatoimport) print img_object($objimport->array_import_module[$key]['module']->getName(), $entityicon).' '; print $objimport->array_import_label[$key]; print '</td><td style="text-align: right">'; - if ($objimport->array_import_perms[$key]) - { + if ($objimport->array_import_perms[$key]) { print '<a href="'.DOL_URL_ROOT.'/imports/import.php?step=2&datatoimport='.$objimport->array_import_code[$key].$param.'">'.img_picto($langs->trans("NewImport"), 'next', 'class="fa-15x"').'</a>'; } else { print $langs->trans("NotEnoughPermissions"); @@ -441,15 +437,22 @@ if ($step == 1 || !$datatoimport) // STEP 2: Page to select input format file -if ($step == 2 && $datatoimport) -{ +if ($step == 2 && $datatoimport) { $param = '&datatoimport='.urlencode($datatoimport); - if ($excludefirstline) $param .= '&excludefirstline='.urlencode($excludefirstline); - if ($endatlinenb) $param .= '&endatlinenb='.urlencode($endatlinenb); - if ($separator) $param .= '&separator='.urlencode($separator); - if ($enclosure) $param .= '&enclosure='.urlencode($enclosure); + if ($excludefirstline) { + $param .= '&excludefirstline='.urlencode($excludefirstline); + } + if ($endatlinenb) { + $param .= '&endatlinenb='.urlencode($endatlinenb); + } + if ($separator) { + $param .= '&separator='.urlencode($separator); + } + if ($enclosure) { + $param .= '&enclosure='.urlencode($enclosure); + } - llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones'); + llxHeader('', $langs->trans("NewImport"), $help_url); $head = import_prepare_head($param, 2); @@ -465,7 +468,9 @@ if ($step == 2 && $datatoimport) print '<td>'; $titleofmodule = $objimport->array_import_module[0]['module']->getName(); // Special cas for import common to module/services - if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) $titleofmodule = $langs->trans("ProductOrService"); + if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) { + $titleofmodule = $langs->trans("ProductOrService"); + } print $titleofmodule; print '</td></tr>'; @@ -503,8 +508,7 @@ if ($step == 2 && $datatoimport) print $langs->trans("FileMustHaveOneOfFollowingFormat"); print '</td></tr>'; $list = $objmodelimport->liste_modeles($db); - foreach ($list as $key) - { + foreach ($list as $key) { print '<tr class="oddeven">'; print '<td width="16">'.img_picto_common($key, $objmodelimport->getPictoForKey($key)).'</td>'; $text = $objmodelimport->getDriverDescForKey($key); @@ -525,17 +529,24 @@ if ($step == 2 && $datatoimport) // STEP 3: Page to select file -if ($step == 3 && $datatoimport) -{ +if ($step == 3 && $datatoimport) { $param = '&datatoimport='.urlencode($datatoimport).'&format='.urlencode($format); - if ($excludefirstline) $param .= '&excludefirstline='.urlencode($excludefirstline); - if ($endatlinenb) $param .= '&endatlinenb='.urlencode($endatlinenb); - if ($separator) $param .= '&separator='.urlencode($separator); - if ($enclosure) $param .= '&enclosure='.urlencode($enclosure); + if ($excludefirstline) { + $param .= '&excludefirstline='.urlencode($excludefirstline); + } + if ($endatlinenb) { + $param .= '&endatlinenb='.urlencode($endatlinenb); + } + if ($separator) { + $param .= '&separator='.urlencode($separator); + } + if ($enclosure) { + $param .= '&enclosure='.urlencode($enclosure); + } $list = $objmodelimport->liste_modeles($db); - llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones'); + llxHeader('', $langs->trans("NewImport"), $help_url); $head = import_prepare_head($param, 3); @@ -544,8 +555,7 @@ if ($step == 3 && $datatoimport) /* * Confirm delete file */ - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"].'?urlfile='.urlencode(GETPOST('urlfile')).'&step=3'.$param, $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1); } @@ -559,7 +569,9 @@ if ($step == 3 && $datatoimport) print '<td>'; $titleofmodule = $objimport->array_import_module[0]['module']->getName(); // Special cas for import common to module/services - if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) $titleofmodule = $langs->trans("ProductOrService"); + if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) { + $titleofmodule = $langs->trans("ProductOrService"); + } print $titleofmodule; print '</td></tr>'; @@ -635,33 +647,45 @@ if ($step == 3 && $datatoimport) $out = (empty($conf->global->MAIN_UPLOAD_DOC) ? ' disabled' : ''); print '<input type="submit" class="button" value="'.$langs->trans("AddFile").'"'.$out.' name="sendit">'; $out = ''; - if (!empty($conf->global->MAIN_UPLOAD_DOC)) - { + if (!empty($conf->global->MAIN_UPLOAD_DOC)) { $max = $conf->global->MAIN_UPLOAD_DOC; // In Kb $maxphp = @ini_get('upload_max_filesize'); // In unknown - if (preg_match('/k$/i', $maxphp)) $maxphp = $maxphp * 1; - if (preg_match('/m$/i', $maxphp)) $maxphp = $maxphp * 1024; - if (preg_match('/g$/i', $maxphp)) $maxphp = $maxphp * 1024 * 1024; - if (preg_match('/t$/i', $maxphp)) $maxphp = $maxphp * 1024 * 1024 * 1024; + if (preg_match('/k$/i', $maxphp)) { + $maxphp = $maxphp * 1; + } + if (preg_match('/m$/i', $maxphp)) { + $maxphp = $maxphp * 1024; + } + if (preg_match('/g$/i', $maxphp)) { + $maxphp = $maxphp * 1024 * 1024; + } + if (preg_match('/t$/i', $maxphp)) { + $maxphp = $maxphp * 1024 * 1024 * 1024; + } $maxphp2 = @ini_get('post_max_size'); // In unknown - if (preg_match('/k$/i', $maxphp2)) $maxphp2 = $maxphp2 * 1; - if (preg_match('/m$/i', $maxphp2)) $maxphp2 = $maxphp2 * 1024; - if (preg_match('/g$/i', $maxphp2)) $maxphp2 = $maxphp2 * 1024 * 1024; - if (preg_match('/t$/i', $maxphp2)) $maxphp2 = $maxphp2 * 1024 * 1024 * 1024; + if (preg_match('/k$/i', $maxphp2)) { + $maxphp2 = $maxphp2 * 1; + } + if (preg_match('/m$/i', $maxphp2)) { + $maxphp2 = $maxphp2 * 1024; + } + if (preg_match('/g$/i', $maxphp2)) { + $maxphp2 = $maxphp2 * 1024 * 1024; + } + if (preg_match('/t$/i', $maxphp2)) { + $maxphp2 = $maxphp2 * 1024 * 1024 * 1024; + } // Now $max and $maxphp and $maxphp2 are in Kb $maxmin = $max; $maxphptoshow = $maxphptoshowparam = ''; - if ($maxphp > 0) - { + if ($maxphp > 0) { $maxmin = min($max, $maxphp); $maxphptoshow = $maxphp; $maxphptoshowparam = 'upload_max_filesize'; } - if ($maxphp2 > 0) - { + if ($maxphp2 > 0) { $maxmin = min($max, $maxphp2); - if ($maxphp2 < $maxphp) - { + if ($maxphp2 < $maxphp) { $maxphptoshow = $maxphp2; $maxphptoshowparam = 'post_max_size'; } @@ -679,20 +703,22 @@ if ($step == 3 && $datatoimport) // Search available imports $filearray = dol_dir_list($conf->import->dir_temp, 'files', 0, '', '', 'name', SORT_DESC); - if (count($filearray) > 0) - { + if (count($filearray) > 0) { $dir = $conf->import->dir_temp; // Search available files to import $i = 0; - foreach ($filearray as $key => $val) - { + foreach ($filearray as $key => $val) { $file = $val['name']; // readdir return value in ISO and we want UTF8 in memory - if (!utf8_check($file)) $file = utf8_encode($file); + if (!utf8_check($file)) { + $file = utf8_encode($file); + } - if (preg_match('/^\./', $file)) continue; + if (preg_match('/^\./', $file)) { + continue; + } $modulepart = 'import'; $urlsource = $_SERVER["PHP_SELF"].'?step='.$step.$param.'&filetoimport='.urlencode($filetoimport); @@ -728,8 +754,7 @@ if ($step == 3 && $datatoimport) // STEP 4: Page to make matching between source file and database fields -if ($step == 4 && $datatoimport) -{ +if ($step == 4 && $datatoimport) { $model = $format; $list = $objmodelimport->liste_modeles($db); @@ -739,14 +764,12 @@ if ($step == 4 && $datatoimport) $classname = "Import".ucfirst($model); require_once $dir.$file; $obj = new $classname($db, $datatoimport); - if ($model == 'csv') - { + if ($model == 'csv') { $obj->separator = $separator; $obj->enclosure = $enclosure; } if ($model == 'xlsx') { - if (!preg_match('/\.xlsx$/i', $filetoimport)) - { + if (!preg_match('/\.xlsx$/i', $filetoimport)) { $langs->load("errors"); $param = '&datatoimport='.$datatoimport.'&format='.$format; setEventMessages($langs->trans("ErrorFileMustHaveFormat", $model), null, 'errors'); @@ -762,14 +785,12 @@ if ($step == 4 && $datatoimport) // Load source fields in input file $fieldssource = array(); $result = $obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport, $langs); - if ($result >= 0) - { + if ($result >= 0) { // Read first line $arrayrecord = $obj->import_read_record(); // Put into array fieldssource starting with 1. $i = 1; - foreach ($arrayrecord as $key => $val) - { + foreach ($arrayrecord as $key => $val) { $fieldssource[$i]['example1'] = dol_trunc($val['val'], 24); $i++; } @@ -784,29 +805,26 @@ if ($step == 4 && $datatoimport) //var_dump($array_match_file_to_database); // Is it a first time in page (if yes, we must initialize array_match_file_to_database) - if (count($array_match_file_to_database) == 0) - { + if (count($array_match_file_to_database) == 0) { // This is first input in screen, we need to define // $array_match_file_to_database // $serialized_array_match_file_to_database // $_SESSION["dol_array_match_file_to_database"] $pos = 1; $num = count($fieldssource); - while ($pos <= $num) - { - if ($num >= 1 && $pos <= $num) - { + while ($pos <= $num) { + if ($num >= 1 && $pos <= $num) { $posbis = 1; - foreach ($fieldstarget as $key => $val) - { - if ($posbis < $pos) - { + foreach ($fieldstarget as $key => $val) { + if ($posbis < $pos) { $posbis++; continue; } // We found the key of targets that is at position pos $array_match_file_to_database[$pos] = $key; - if ($serialized_array_match_file_to_database) $serialized_array_match_file_to_database .= ','; + if ($serialized_array_match_file_to_database) { + $serialized_array_match_file_to_database .= ','; + } $serialized_array_match_file_to_database .= ($pos.'='.$key); break; } @@ -825,12 +843,20 @@ if ($step == 4 && $datatoimport) // Now $array_match_file_to_database contains fieldnb(1,2,3...)=>fielddatabase(key in $array_match_file_to_database) $param = '&format='.$format.'&datatoimport='.urlencode($datatoimport).'&filetoimport='.urlencode($filetoimport); - if ($excludefirstline) $param .= '&excludefirstline='.urlencode($excludefirstline); - if ($endatlinenb) $param .= '&endatlinenb='.urlencode($endatlinenb); - if ($separator) $param .= '&separator='.urlencode($separator); - if ($enclosure) $param .= '&enclosure='.urlencode($enclosure); + if ($excludefirstline) { + $param .= '&excludefirstline='.urlencode($excludefirstline); + } + if ($endatlinenb) { + $param .= '&endatlinenb='.urlencode($endatlinenb); + } + if ($separator) { + $param .= '&separator='.urlencode($separator); + } + if ($enclosure) { + $param .= '&enclosure='.urlencode($enclosure); + } - llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones'); + llxHeader('', $langs->trans("NewImport"), $help_url); $head = import_prepare_head($param, 4); @@ -846,7 +872,9 @@ if ($step == 4 && $datatoimport) print '<td>'; $titleofmodule = $objimport->array_import_module[0]['module']->getName(); // Special cas for import common to module/services - if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) $titleofmodule = $langs->trans("ProductOrService"); + if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) { + $titleofmodule = $langs->trans("ProductOrService"); + } print $titleofmodule; print '</td></tr>'; @@ -954,8 +982,7 @@ if ($step == 4 && $datatoimport) $fieldsplaced = array(); $valforsourcefieldnb = array(); $listofkeys = array(); - foreach ($array_match_file_to_database as $key => $val) - { + foreach ($array_match_file_to_database as $key => $val) { $listofkeys[$key] = 1; } @@ -965,8 +992,7 @@ if ($step == 4 && $datatoimport) // List of source fields $var = true; $lefti = 1; - foreach ($array_match_file_to_database as $key => $val) - { + foreach ($array_match_file_to_database as $key => $val) { $var = !$var; show_elem($fieldssource, $key, $val, $var); // key is field number in source file //print '> '.$lefti.'-'.$key.'-'.$val; @@ -975,15 +1001,16 @@ if ($step == 4 && $datatoimport) $valforsourcefieldnb[$lefti] = $key; $lefti++; - if ($lefti > count($fieldstarget)) break; // Other fields are in the not imported area + if ($lefti > count($fieldstarget)) { + break; // Other fields are in the not imported area + } } //var_dump($valforsourcefieldnb); // Complete source fields from count($fieldssource)+1 to count($fieldstarget) $more = 1; $num = count($fieldssource); - while ($lefti <= $num) - { + while ($lefti <= $num) { $var = !$var; $newkey = getnewkey($fieldssource, $listofkeys); show_elem($fieldssource, $newkey, '', $var); // key start after field number in source file @@ -1005,8 +1032,7 @@ if ($step == 4 && $datatoimport) $mandatoryfieldshavesource = true; print '<table width="100%" class="nobordernopadding">'; - foreach ($fieldstarget as $code=>$label) - { + foreach ($fieldstarget as $code => $label) { print '<tr class="oddeven" style="height:'.$height.'">'; $i++; @@ -1023,11 +1049,12 @@ if ($step == 4 && $datatoimport) $newlabel = preg_replace('/\*$/', '', $label); $text = $langs->trans($newlabel); $more = ''; - if (preg_match('/\*$/', $label)) - { + if (preg_match('/\*$/', $label)) { $text = '<span class="fieldrequired">'.$text.'</span>'; $more = ((!empty($valforsourcefieldnb[$i]) && $valforsourcefieldnb[$i] <= count($fieldssource)) ? '' : img_warning($langs->trans("FieldNeedSource"))); - if ($mandatoryfieldshavesource) $mandatoryfieldshavesource = (!empty($valforsourcefieldnb[$i]) && ($valforsourcefieldnb[$i] <= count($fieldssource))); + if ($mandatoryfieldshavesource) { + $mandatoryfieldshavesource = (!empty($valforsourcefieldnb[$i]) && ($valforsourcefieldnb[$i] <= count($fieldssource))); + } //print 'xx'.($i).'-'.$valforsourcefieldnb[$i].'-'.$mandatoryfieldshavesource; } print $text; @@ -1037,43 +1064,54 @@ if ($step == 4 && $datatoimport) $filecolumn = $array_match_database_to_file[$code]; // Source field info $htmltext = '<b><u>'.$langs->trans("FieldSource").'</u></b><br>'; - if ($filecolumn > count($fieldssource)) $htmltext .= $langs->trans("DataComeFromNoWhere").'<br>'; - else { - if (empty($objimport->array_import_convertvalue[0][$code])) // If source file does not need convertion - { + if ($filecolumn > count($fieldssource)) { + $htmltext .= $langs->trans("DataComeFromNoWhere").'<br>'; + } else { + if (empty($objimport->array_import_convertvalue[0][$code])) { // If source file does not need convertion $filecolumntoshow = $filecolumn; $htmltext .= $langs->trans("DataComeFromFileFieldNb", $filecolumntoshow).'<br>'; } else { - if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromref') $htmltext .= $langs->trans("DataComeFromIdFoundFromRef", $filecolumn, $langs->transnoentitiesnoconv($entitylang)).'<br>'; - if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromcodeid') $htmltext .= $langs->trans("DataComeFromIdFoundFromCodeId", $filecolumn, $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$code]['dict'])).'<br>'; + if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromref') { + $htmltext .= $langs->trans("DataComeFromIdFoundFromRef", $filecolumn, $langs->transnoentitiesnoconv($entitylang)).'<br>'; + } + if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromcodeid') { + $htmltext .= $langs->trans("DataComeFromIdFoundFromCodeId", $filecolumn, $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$code]['dict'])).'<br>'; + } } } // Source required $htmltext .= $langs->trans("SourceRequired").': <b>'.yn(preg_match('/\*$/', $label)).'</b><br>'; $example = $objimport->array_import_examplevalues[0][$code]; // Example - if (empty($objimport->array_import_convertvalue[0][$code])) // If source file does not need convertion - { - if ($example) $htmltext .= $langs->trans("SourceExample").': <b>'.$example.'</b><br>'; + if (empty($objimport->array_import_convertvalue[0][$code])) { // If source file does not need convertion + if ($example) { + $htmltext .= $langs->trans("SourceExample").': <b>'.$example.'</b><br>'; + } } else { - if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromref') $htmltext .= $langs->trans("SourceExample").': <b>'.$langs->transnoentitiesnoconv("ExampleAnyRefFoundIntoElement", $entitylang).($example ? ' ('.$langs->transnoentitiesnoconv("Example").': '.$example.')' : '').'</b><br>'; - elseif ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromcodeid') $htmltext .= $langs->trans("SourceExample").': <b>'.$langs->trans("ExampleAnyCodeOrIdFoundIntoDictionary", $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$code]['dict'])).($example ? ' ('.$langs->transnoentitiesnoconv("Example").': '.$example.')' : '').'</b><br>'; - elseif ($example) $htmltext .= $langs->trans("SourceExample").': <b>'.$example.'</b><br>'; + if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromref') { + $htmltext .= $langs->trans("SourceExample").': <b>'.$langs->transnoentitiesnoconv("ExampleAnyRefFoundIntoElement", $entitylang).($example ? ' ('.$langs->transnoentitiesnoconv("Example").': '.$example.')' : '').'</b><br>'; + } elseif ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromcodeid') { + $htmltext .= $langs->trans("SourceExample").': <b>'.$langs->trans("ExampleAnyCodeOrIdFoundIntoDictionary", $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$code]['dict'])).($example ? ' ('.$langs->transnoentitiesnoconv("Example").': '.$example.')' : '').'</b><br>'; + } elseif ($example) { + $htmltext .= $langs->trans("SourceExample").': <b>'.$example.'</b><br>'; + } } // Format control rule - if (!empty($objimport->array_import_regex[0][$code])) - { + if (!empty($objimport->array_import_regex[0][$code])) { $htmltext .= $langs->trans("FormatControlRule").': <b>'.$objimport->array_import_regex[0][$code].'</b><br>'; } $htmltext .= '<br>'; // Target field info $htmltext .= '<b><u>'.$langs->trans("FieldTarget").'</u></b><br>'; - if (empty($objimport->array_import_convertvalue[0][$code])) // If source file does not need convertion - { + if (empty($objimport->array_import_convertvalue[0][$code])) { // If source file does not need convertion $htmltext .= $langs->trans("DataIsInsertedInto").'<br>'; } else { - if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromref') $htmltext .= $langs->trans("DataIDSourceIsInsertedInto").'<br>'; - if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromcodeid') $htmltext .= $langs->trans("DataCodeIDSourceIsInsertedInto").'<br>'; + if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromref') { + $htmltext .= $langs->trans("DataIDSourceIsInsertedInto").'<br>'; + } + if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromcodeid') { + $htmltext .= $langs->trans("DataCodeIDSourceIsInsertedInto").'<br>'; + } } $htmltext .= $langs->trans("FieldTitle").": <b>".$langs->trans($newlabel)."</b><br>"; $htmltext .= $langs->trans("Table")." -> ".$langs->trans("Field").': <b>'.$tablename." -> ".preg_replace('/^.*\./', '', $code)."</b><br>"; @@ -1096,10 +1134,8 @@ if ($step == 4 && $datatoimport) print '<div id="right" class="connectedSortable">'."\n"; $nbofnotimportedfields = 0; - foreach ($fieldssource as $key => $val) - { - if (empty($fieldsplaced[$key])) - { + foreach ($fieldssource as $key => $val) { + if (empty($fieldsplaced[$key])) { // $nbofnotimportedfields++; show_elem($fieldssource, $key, '', $var, 'nostyle'); @@ -1122,8 +1158,7 @@ if ($step == 4 && $datatoimport) print '</td>'; print '<td width="50%">'; $i = 0; - while ($i < $nbofnotimportedfields) - { + while ($i < $nbofnotimportedfields) { // Print empty cells show_elem('', '', 'none', $var, 'nostyle'); $i++; @@ -1134,8 +1169,7 @@ if ($step == 4 && $datatoimport) print '</div>'; - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<script type="text/javascript" language="javascript">'; print 'jQuery(function() { jQuery("#left, #right").sortable({ @@ -1172,14 +1206,12 @@ if ($step == 4 && $datatoimport) } /* - * Barre d'action + * Action bar */ print '<div class="tabsAction">'; - if (count($array_match_file_to_database)) - { - if ($mandatoryfieldshavesource) - { + if (count($array_match_file_to_database)) { + if ($mandatoryfieldshavesource) { print '<a class="butAction" href="import.php?step=5'.$param.'&filetoimport='.urlencode($filetoimport).'">'.$langs->trans("NextStep").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("SomeMandatoryFieldHaveNoSource")).'">'.$langs->trans("NextStep").'</a>'; @@ -1190,8 +1222,7 @@ if ($step == 4 && $datatoimport) // Area for profils import - if (count($array_match_file_to_database)) - { + if (count($array_match_file_to_database)) { print '<br>'."\n"; print '<!-- Area to add new import profile -->'."\n"; print '<div class="marginbottomonly"><span class="opacitymedium">'.$langs->trans("SaveImportModel").'</span></div>'; @@ -1226,12 +1257,10 @@ if ($step == 4 && $datatoimport) $sql .= " WHERE type = '".$db->escape($datatoimport)."'"; $sql .= " ORDER BY rowid"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven"><td>'; print $obj->label; @@ -1253,12 +1282,10 @@ if ($step == 4 && $datatoimport) // STEP 5: Summary of choices and launch simulation -if ($step == 5 && $datatoimport) -{ +if ($step == 5 && $datatoimport) { $max_execution_time_for_importexport = (empty($conf->global->IMPORT_MAX_EXECUTION_TIME) ? 300 : $conf->global->IMPORT_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 } @@ -1281,14 +1308,12 @@ if ($step == 5 && $datatoimport) $fieldssource = array(); $result = $obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport, $langs); - if ($result >= 0) - { + if ($result >= 0) { // Read first line $arrayrecord = $obj->import_read_record(); // Put into array fieldssource starting with 1. $i = 1; - foreach ($arrayrecord as $key => $val) - { + foreach ($arrayrecord as $key => $val) { $fieldssource[$i]['example1'] = dol_trunc($val['val'], 24); $i++; } @@ -1299,9 +1324,15 @@ if ($step == 5 && $datatoimport) $param = '&leftmenu=import&format='.urlencode($format).'&datatoimport='.urlencode($datatoimport).'&filetoimport='.urlencode($filetoimport).'&nboflines='.urlencode($nboflines).'&separator='.urlencode($separator).'&enclosure='.urlencode($enclosure); $param2 = $param; // $param2 = $param without excludefirstline and endatlinenb - if ($excludefirstline) $param .= '&excludefirstline='.urlencode($excludefirstline); - if ($endatlinenb) $param .= '&endatlinenb='.urlencode($endatlinenb); - if (!empty($updatekeys)) $param .= '&updatekeys[]='.implode('&updatekeys[]=', $updatekeys); + if ($excludefirstline) { + $param .= '&excludefirstline='.urlencode($excludefirstline); + } + if ($endatlinenb) { + $param .= '&endatlinenb='.urlencode($endatlinenb); + } + if (!empty($updatekeys)) { + $param .= '&updatekeys[]='.implode('&updatekeys[]=', $updatekeys); + } llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones'); @@ -1325,7 +1356,9 @@ if ($step == 5 && $datatoimport) print '<td>'; $titleofmodule = $objimport->array_import_module[0]['module']->getName(); // Special cas for import common to module/services - if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) $titleofmodule = $langs->trans("ProductOrService"); + if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) { + $titleofmodule = $langs->trans("ProductOrService"); + } print $titleofmodule; print '</td></tr>'; @@ -1384,8 +1417,7 @@ if ($step == 5 && $datatoimport) print '<tr><td>'; print $langs->trans("ImportFromToLine"); print '</td><td>'; - if ($action == 'launchsimu') - { + if ($action == 'launchsimu') { print '<input type="number" class="maxwidth50" name="excludefirstlinebis" disabled="disabled" value="'.$excludefirstline.'">'; print '<input type="hidden" name="excludefirstline" value="'.$excludefirstline.'">'; } else { @@ -1393,15 +1425,16 @@ if ($step == 5 && $datatoimport) print $form->textwithpicto("", $langs->trans("SetThisValueTo2ToExcludeFirstLine")); } print ' - '; - if ($action == 'launchsimu') - { + if ($action == 'launchsimu') { print '<input type="text" class="maxwidth50" name="endatlinenbbis" disabled="disabled" value="'.$endatlinenb.'">'; print '<input type="hidden" name="endatlinenb" value="'.$endatlinenb.'">'; } else { print '<input type="text" class="maxwidth50" name="endatlinenb" value="'.$endatlinenb.'">'; print $form->textwithpicto("", $langs->trans("KeepEmptyToGoToEndOfFile")); } - if ($action == 'launchsimu') print ' &nbsp; <a href="'.$_SERVER["PHP_SELF"].'?step=5'.$param.'">'.$langs->trans("Modify").'</a>'; + if ($action == 'launchsimu') { + print ' &nbsp; <a href="'.$_SERVER["PHP_SELF"].'?step=5'.$param.'">'.$langs->trans("Modify").'</a>'; + } print '</td></tr>'; // Keys for data UPDATE (not INSERT of new data) @@ -1409,8 +1442,7 @@ if ($step == 5 && $datatoimport) print $langs->trans("KeysToUseForUpdates"); print '</td><td>'; if ($action == 'launchsimu') { - if (count($updatekeys)) - { + if (count($updatekeys)) { print $form->multiselectarray('updatekeysbis', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0, '', 1, '80%', 'disabled'); } else { print '<span class="opacitymedium">'.$langs->trans("NoUpdateAttempt").'</span> &nbsp; -'; @@ -1420,8 +1452,7 @@ if ($step == 5 && $datatoimport) } print ' &nbsp; <a href="'.$_SERVER["PHP_SELF"].'?step=5'.$param.'">'.$langs->trans("Modify").'</a>'; } else { - if (is_array($objimport->array_import_updatekeys[0]) && count($objimport->array_import_updatekeys[0])) - { //TODO dropdown UL is created inside nested SPANS + if (is_array($objimport->array_import_updatekeys[0]) && count($objimport->array_import_updatekeys[0])) { //TODO dropdown UL is created inside nested SPANS print $form->multiselectarray('updatekeys', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0, '', 1, '80%'); print $form->textwithpicto("", $langs->trans("SelectPrimaryColumnsForUpdateAttempt")); } else { @@ -1450,21 +1481,22 @@ if ($step == 5 && $datatoimport) print '</td><td>'; $listtables = array(); $sort_array_match_file_to_database = $array_match_file_to_database; - foreach ($array_match_file_to_database as $code=>$label) - { + foreach ($array_match_file_to_database as $code => $label) { //var_dump($fieldssource); - if ($code > count($fieldssource)) continue; + if ($code > count($fieldssource)) { + continue; + } //print $code.'-'.$label; $alias = preg_replace('/(\..*)$/i', '', $label); $listtables[$alias] = $objimport->array_import_tables[0][$alias]; } - if (count($listtables)) - { + if (count($listtables)) { $newval = ''; //ksort($listtables); - foreach ($listtables as $val) - { - if ($newval) print ', '; + foreach ($listtables as $val) { + if ($newval) { + print ', '; + } $newval = $val; // Link to Dolibarr wiki pages /*$helppagename='EN:Table_'.$newval; @@ -1479,7 +1511,9 @@ if ($step == 5 && $datatoimport) }*/ print $newval; } - } else print $langs->trans("Error"); + } else { + print $langs->trans("Error"); + } print '</td></tr>'; // Fields imported @@ -1491,11 +1525,12 @@ if ($step == 5 && $datatoimport) $sort_array_match_file_to_database = $array_match_file_to_database; ksort($sort_array_match_file_to_database); //var_dump($sort_array_match_file_to_database); - foreach ($sort_array_match_file_to_database as $code=>$label) - { + foreach ($sort_array_match_file_to_database as $code => $label) { $i++; //var_dump($fieldssource); - if ($code > count($fieldssource)) continue; + if ($code > count($fieldssource)) { + continue; + } //print $code.'-'.$label; $alias = preg_replace('/(\..*)$/i', '', $label); $listfields[$i] = $langs->trans("Field").' '.$code.'->'.$label; @@ -1509,8 +1544,7 @@ if ($step == 5 && $datatoimport) print dol_get_fiche_end(); - if ($action != 'launchsimu') - { + if ($action != 'launchsimu') { // Show import id print '<br><span class="opacitymedium">'; print $langs->trans("NowClickToTestTheImport", $langs->transnoentitiesnoconv("RunSimulateImportFile")).'</span><br>'; @@ -1518,8 +1552,7 @@ if ($step == 5 && $datatoimport) // Actions print '<div class="center">'; - if ($user->rights->import->run) - { + if ($user->rights->import->run) { print '<input type="submit" class="butAction" value="'.$langs->trans("RunSimulateImportFile").'">'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("RunSimulateImportFile").'</a>'; @@ -1544,34 +1577,41 @@ if ($step == 5 && $datatoimport) $nbok = 0; $pathfile = $conf->import->dir_temp.'/'.$filetoimport; $result = $obj->import_open_file($pathfile, $langs); - if ($result > 0) - { + if ($result > 0) { global $tablewithentity_cache; $tablewithentity_cache = array(); $sourcelinenb = 0; $endoffile = 0; // Loop on each input file record - while (($sourcelinenb < $nboflines) && !$endoffile) - { + while (($sourcelinenb < $nboflines) && !$endoffile) { $sourcelinenb++; // Read line and store it into $arrayrecord //dol_syslog("line ".$sourcelinenb.' - '.$nboflines.' - '.$excludefirstline.' - '.$endatlinenb); $arrayrecord = $obj->import_read_record(); - if ($arrayrecord === false) - { + if ($arrayrecord === false) { $arrayofwarnings[$sourcelinenb][0] = array('lib'=>'File has '.$nboflines.' lines. However we reach end of file after record '.$sourcelinenb.'. This may occurs when some records are split onto several lines. Ensure the complete string is delimited correctly when there is a separator character in the text string.', 'type'=>'EOF_RECORD_ON_SEVERAL_LINES'); $endoffile++; continue; } - if ($excludefirstline && ($sourcelinenb < $excludefirstline)) continue; - if ($endatlinenb && ($sourcelinenb > $endatlinenb)) break; + if ($excludefirstline && ($sourcelinenb < $excludefirstline)) { + continue; + } + if ($endatlinenb && ($sourcelinenb > $endatlinenb)) { + break; + } // Run import $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys); - if (count($obj->errors)) $arrayoferrors[$sourcelinenb] = $obj->errors; - if (count($obj->warnings)) $arrayofwarnings[$sourcelinenb] = $obj->warnings; - if (!count($obj->errors) && !count($obj->warnings)) $nbok++; + if (count($obj->errors)) { + $arrayoferrors[$sourcelinenb] = $obj->errors; + } + if (count($obj->warnings)) { + $arrayofwarnings[$sourcelinenb] = $obj->warnings; + } + if (!count($obj->errors) && !count($obj->warnings)) { + $nbok++; + } } // Close file $obj->import_close_file(); @@ -1583,15 +1623,12 @@ if ($step == 5 && $datatoimport) // Run the sql after import if defined //var_dump($objimport->array_import_run_sql_after[0]); - if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) - { + if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) { $i = 0; - foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) - { + foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) { $i++; $resqlafterimport = $db->query($sqlafterimport); - if (!$resqlafterimport) - { + if (!$resqlafterimport) { $arrayoferrors['none'][] = array('lib'=>$langs->trans("Error running final request: ".$sqlafterimport)); $error++; } @@ -1607,25 +1644,23 @@ if ($step == 5 && $datatoimport) print $langs->trans("NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).'<br>'; print $langs->trans("NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).'<br><br>'; print '</div>'; - } else print $langs->trans("NbOfLinesOK", $nbok).'<br><br>'; + } else { + print $langs->trans("NbOfLinesOK", $nbok).'<br><br>'; + } // Show Errors //var_dump($arrayoferrors); - if (count($arrayoferrors)) - { + if (count($arrayoferrors)) { print img_error().' <b>'.$langs->trans("ErrorsOnXLines", count($arrayoferrors)).'</b><br>'; print '<table width="100%" class="border"><tr><td>'; - foreach ($arrayoferrors as $key => $val) - { + foreach ($arrayoferrors as $key => $val) { $nboferrors++; - if ($nboferrors > $maxnboferrors) - { + if ($nboferrors > $maxnboferrors) { print $langs->trans("TooMuchErrors", (count($arrayoferrors) - $nboferrors))."<br>"; break; } print '* '.$langs->trans("Line").' '.$key.'<br>'; - foreach ($val as $i => $err) - { + foreach ($val as $i => $err) { print ' &nbsp; &nbsp; > '.$err['lib'].'<br>'; } } @@ -1635,21 +1670,17 @@ if ($step == 5 && $datatoimport) // Show Warnings //var_dump($arrayoferrors); - if (count($arrayofwarnings)) - { + if (count($arrayofwarnings)) { print img_warning().' <b>'.$langs->trans("WarningsOnXLines", count($arrayofwarnings)).'</b><br>'; print '<table width="100%" class="border"><tr><td>'; - foreach ($arrayofwarnings as $key => $val) - { + foreach ($arrayofwarnings as $key => $val) { $nbofwarnings++; - if ($nbofwarnings > $maxnbofwarnings) - { + if ($nbofwarnings > $maxnbofwarnings) { print $langs->trans("TooMuchWarnings", (count($arrayofwarnings) - $nbofwarnings))."<br>"; break; } print ' * '.$langs->trans("Line").' '.$key.'<br>'; - foreach ($val as $i => $err) - { + foreach ($val as $i => $err) { print ' &nbsp; &nbsp; > '.$err['lib'].'<br>'; } } @@ -1662,17 +1693,17 @@ if ($step == 5 && $datatoimport) print '<div class="center">'; print '<span class="opacitymedium">'.$langs->trans("NowClickToRunTheImport", $langs->transnoentitiesnoconv("RunImportFile")).'</span><br>'; - if (empty($nboferrors)) print $langs->trans("DataLoadedWithId", $importid).'<br>'; + if (empty($nboferrors)) { + print $langs->trans("DataLoadedWithId", $importid).'<br>'; + } print '</div>'; print '<br>'; // Actions print '<div class="center">'; - if ($user->rights->import->run) - { - if (empty($nboferrors)) - { + if ($user->rights->import->run) { + if (empty($nboferrors)) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/imports/import.php?leftmenu=import&step=6&importid='.$importid.$param.'">'.$langs->trans("RunImportFile").'</a>'; } else { //print '<input type="submit" class="butAction" value="'.dol_escape_htmltag($langs->trans("RunSimulateImportFile")).'">'; @@ -1692,12 +1723,10 @@ if ($step == 5 && $datatoimport) // STEP 6: Real import -if ($step == 6 && $datatoimport) -{ +if ($step == 6 && $datatoimport) { $max_execution_time_for_importexport = (empty($conf->global->IMPORT_MAX_EXECUTION_TIME) ? 300 : $conf->global->IMPORT_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 } @@ -1721,14 +1750,12 @@ if ($step == 6 && $datatoimport) // Load source fields in input file $fieldssource = array(); $result = $obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport, $langs); - if ($result >= 0) - { + if ($result >= 0) { // Read first line $arrayrecord = $obj->import_read_record(); // Put into array fieldssource starting with 1. $i = 1; - foreach ($arrayrecord as $key => $val) - { + foreach ($arrayrecord as $key => $val) { $fieldssource[$i]['example1'] = dol_trunc($val['val'], 24); $i++; } @@ -1738,10 +1765,18 @@ if ($step == 6 && $datatoimport) $nboflines = (!empty($_GET["nboflines"]) ? $_GET["nboflines"] : dol_count_nb_of_line($conf->import->dir_temp.'/'.$filetoimport)); $param = '&format='.$format.'&datatoimport='.urlencode($datatoimport).'&filetoimport='.urlencode($filetoimport).'&nboflines='.urlencode($nboflines); - if ($excludefirstline) $param .= '&excludefirstline='.urlencode($excludefirstline); - if ($endatlinenb) $param .= '&endatlinenb='.urlencode($endatlinenb); - if ($separator) $param .= '&separator='.urlencode($separator); - if ($enclosure) $param .= '&enclosure='.urlencode($enclosure); + if ($excludefirstline) { + $param .= '&excludefirstline='.urlencode($excludefirstline); + } + if ($endatlinenb) { + $param .= '&endatlinenb='.urlencode($endatlinenb); + } + if ($separator) { + $param .= '&separator='.urlencode($separator); + } + if ($enclosure) { + $param .= '&enclosure='.urlencode($enclosure); + } llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones'); @@ -1759,7 +1794,9 @@ if ($step == 6 && $datatoimport) print '<td>'; $titleofmodule = $objimport->array_import_module[0]['module']->getName(); // Special cas for import common to module/services - if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) $titleofmodule = $langs->trans("ProductOrService"); + if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) { + $titleofmodule = $langs->trans("ProductOrService"); + } print $titleofmodule; print '</td></tr>'; @@ -1846,20 +1883,21 @@ if ($step == 6 && $datatoimport) print $langs->trans("TablesTarget"); print '</td><td>'; $listtables = array(); - foreach ($array_match_file_to_database as $code=>$label) - { + foreach ($array_match_file_to_database as $code => $label) { //var_dump($fieldssource); - if ($code > count($fieldssource)) continue; + if ($code > count($fieldssource)) { + continue; + } //print $code.'-'.$label; $alias = preg_replace('/(\..*)$/i', '', $label); $listtables[$alias] = $objimport->array_import_tables[0][$alias]; } - if (count($listtables)) - { + if (count($listtables)) { $newval = ''; - foreach ($listtables as $val) - { - if ($newval) print ', '; + foreach ($listtables as $val) { + if ($newval) { + print ', '; + } $newval = $val; // Link to Dolibarr wiki pages /*$helppagename='EN:Table_'.$newval; @@ -1874,7 +1912,9 @@ if ($step == 6 && $datatoimport) }*/ print $newval; } - } else print $langs->trans("Error"); + } else { + print $langs->trans("Error"); + } print '</td></tr>'; // Fields imported @@ -1885,11 +1925,12 @@ if ($step == 6 && $datatoimport) $sort_array_match_file_to_database = $array_match_file_to_database; ksort($sort_array_match_file_to_database); //var_dump($sort_array_match_file_to_database); - foreach ($sort_array_match_file_to_database as $code=>$label) - { + foreach ($sort_array_match_file_to_database as $code => $label) { $i++; //var_dump($fieldssource); - if ($code > count($fieldssource)) continue; + if ($code > count($fieldssource)) { + continue; + } //print $code.'-'.$label; $alias = preg_replace('/(\..*)$/i', '', $label); $listfields[$i] = $langs->trans("Field").' '.$code.'->'.$label; @@ -1918,31 +1959,38 @@ if ($step == 6 && $datatoimport) $nbok = 0; $pathfile = $conf->import->dir_temp.'/'.$filetoimport; $result = $obj->import_open_file($pathfile, $langs); - if ($result > 0) - { + if ($result > 0) { global $tablewithentity_cache; $tablewithentity_cache = array(); $sourcelinenb = 0; $endoffile = 0; - while ($sourcelinenb < $nboflines && !$endoffile) - { + while ($sourcelinenb < $nboflines && !$endoffile) { $sourcelinenb++; $arrayrecord = $obj->import_read_record(); - if ($arrayrecord === false) - { + if ($arrayrecord === false) { $arrayofwarnings[$sourcelinenb][0] = array('lib'=>'File has '.$nboflines.' lines. However we reach end of file after record '.$sourcelinenb.'. This may occurs when some records are split onto several lines.', 'type'=>'EOF_RECORD_ON_SEVERAL_LINES'); $endoffile++; continue; } - if ($excludefirstline && ($sourcelinenb < $excludefirstline)) continue; - if ($endatlinenb && ($sourcelinenb > $endatlinenb)) break; + if ($excludefirstline && ($sourcelinenb < $excludefirstline)) { + continue; + } + if ($endatlinenb && ($sourcelinenb > $endatlinenb)) { + break; + } // Run import $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys); - if (count($obj->errors)) $arrayoferrors[$sourcelinenb] = $obj->errors; - if (count($obj->warnings)) $arrayofwarnings[$sourcelinenb] = $obj->warnings; - if (!count($obj->errors) && !count($obj->warnings)) $nbok++; + if (count($obj->errors)) { + $arrayoferrors[$sourcelinenb] = $obj->errors; + } + if (count($obj->warnings)) { + $arrayofwarnings[$sourcelinenb] = $obj->warnings; + } + if (!count($obj->errors) && !count($obj->warnings)) { + $nbok++; + } } // Close file $obj->import_close_file(); @@ -1950,29 +1998,30 @@ if ($step == 6 && $datatoimport) print $langs->trans("ErrorFailedToOpenFile", $pathfile); } - if (count($arrayoferrors) > 0) $db->rollback(); // We force rollback because this was errors. - else { + if (count($arrayoferrors) > 0) { + $db->rollback(); // We force rollback because this was errors. + } else { $error = 0; // Run the sql after import if defined //var_dump($objimport->array_import_run_sql_after[0]); - if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) - { + if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) { $i = 0; - foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) - { + foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) { $i++; $resqlafterimport = $db->query($sqlafterimport); - if (!$resqlafterimport) - { + if (!$resqlafterimport) { $arrayoferrors['none'][] = array('lib'=>$langs->trans("Error running final request: ".$sqlafterimport)); $error++; } } } - if (!$error) $db->commit(); // We can commit if no errors. - else $db->rollback(); + if (!$error) { + $db->commit(); // We can commit if no errors. + } else { + $db->rollback(); + } } print dol_get_fiche_end(); @@ -2028,8 +2077,7 @@ function show_elem($fieldssource, $pos, $key, $var, $nostyle = '') print '<table summary="boxtable'.$pos.'" width="100%" class="nobordernopadding">'."\n"; } - if ($pos && $pos > count($fieldssource)) // No fields - { + if ($pos && $pos > count($fieldssource)) { // No fields print '<tr'.($nostyle ? '' : ' '.$bc[$var]).' style="height:'.$height.'">'; print '<td class="nocellnopadding" width="16" style="font-weight: normal">'; print img_picto(($pos > 0 ? $langs->trans("MoveField", $pos) : ''), 'grip_title', 'class="boxhandle" style="cursor:move;"'); @@ -2038,8 +2086,7 @@ function show_elem($fieldssource, $pos, $key, $var, $nostyle = '') print $langs->trans("NoFields"); print '</td>'; print '</tr>'; - } elseif ($key == 'none') // Empty line - { + } elseif ($key == 'none') { // Empty line print '<tr'.($nostyle ? '' : ' '.$bc[$var]).' style="height:'.$height.'">'; print '<td class="nocellnopadding" width="16" style="font-weight: normal">'; print '&nbsp;'; @@ -2058,9 +2105,10 @@ function show_elem($fieldssource, $pos, $key, $var, $nostyle = '') print '<td style="font-weight: normal">'; print $langs->trans("Field").' '.$pos; $example = $fieldssource[$pos]['example1']; - if ($example) - { - if (!utf8_check($example)) $example = utf8_encode($example); + if ($example) { + if (!utf8_check($example)) { + $example = utf8_encode($example); + } print ' (<i>'.$example.'</i>)'; } print '</td>'; @@ -2086,15 +2134,16 @@ function getnewkey(&$fieldssource, &$listofkey) $i = count($fieldssource) + 1; // Max number of key $maxkey = 0; - foreach ($listofkey as $key=>$val) - { + foreach ($listofkey as $key => $val) { $maxkey = max($maxkey, $key); } // Found next empty key - while ($i <= $maxkey) - { - if (empty($listofkey[$i])) break; - else $i++; + while ($i <= $maxkey) { + if (empty($listofkey[$i])) { + break; + } else { + $i++; + } } $listofkey[$i] = 1; diff --git a/htdocs/imports/index.php b/htdocs/imports/index.php index e27712a5e56..ac3d2b23f69 100644 --- a/htdocs/imports/index.php +++ b/htdocs/imports/index.php @@ -27,8 +27,9 @@ require_once DOL_DOCUMENT_ROOT.'/imports/class/import.class.php'; // Load translation files required by the page $langs->load("exports"); -if (!$user->socid == 0) - accessforbidden(); +if (!$user->socid == 0) { + accessforbidden(); +} $import = new Import($db); $import->load_arrays($user); @@ -49,8 +50,7 @@ print '<br>'; print '<div class="center">'; -if (count($import->array_import_code)) -{ +if (count($import->array_import_code)) { print dolGetButtonTitle($langs->trans('NewImport'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/imports/import.php?leftmenu=import'); } print '</div>'; @@ -70,8 +70,7 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/import/modules_import.php'; $model = new ModeleImports(); $list = $model->liste_modeles($db); -foreach ($list as $key) -{ +foreach ($list as $key) { print '<tr class="oddeven">'; print '<td width="16">'.img_picto_common($model->getDriverLabelForKey($key), $model->getPictoForKey($key)).'</td>'; $text = $model->getDriverDescForKey($key); diff --git a/htdocs/includes/odtphp/odf.php b/htdocs/includes/odtphp/odf.php index 800b29a918d..91fec8d998e 100644 --- a/htdocs/includes/odtphp/odf.php +++ b/htdocs/includes/odtphp/odf.php @@ -913,16 +913,20 @@ IMG; { dol_syslog(get_class($this).'::exportAsAttachedPDF $ret_val='.$retval, LOG_DEBUG); $filename=''; $linenum=0; - if (headers_sent($filename, $linenum)) { - throw new OdfException("headers already sent ($filename at $linenum)"); + + if (php_sapi_name() != 'cli') { // If we are in a web context (not into CLI context) + if (headers_sent($filename, $linenum)) { + throw new OdfException("headers already sent ($filename at $linenum)"); + } + + if (!empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $name=preg_replace('/\.od(x|t)/i', '', $name); + header('Content-type: application/pdf'); + header('Content-Disposition: attachment; filename="'.$name.'.pdf"'); + readfile($name.".pdf"); + } } - if (!empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $name=preg_replace('/\.od(x|t)/i', '', $name); - header('Content-type: application/pdf'); - header('Content-Disposition: attachment; filename="'.$name.'.pdf"'); - readfile($name.".pdf"); - } if (!empty($conf->global->MAIN_ODT_AS_PDF_DEL_SOURCE)) { unlink($name); @@ -931,7 +935,7 @@ IMG; dol_syslog(get_class($this).'::exportAsAttachedPDF $ret_val='.$retval, LOG_DEBUG); dol_syslog(get_class($this).'::exportAsAttachedPDF $output_arr='.var_export($output_arr, true), LOG_DEBUG); - if ($retval==126) { + if ($retval == 126) { throw new OdfException('Permission execute convert script : ' . $command); } else { diff --git a/htdocs/index.php b/htdocs/index.php index 92914b96e83..5485f9bc7be 100644 --- a/htdocs/index.php +++ b/htdocs/index.php @@ -24,13 +24,14 @@ * \brief Dolibarr home page */ -define('NOCSRFCHECK', 1); // This is main home and login page. We must be able to go on it from another web site. + +define('CSRFCHECK_WITH_TOKEN', 1); // We force need to use a token to login when making a POST require 'main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; // If not defined, we select menu "home" -$_GET['mainmenu'] = GETPOST('mainmenu', 'aZ09') ?GETPOST('mainmenu', 'aZ09') : 'home'; +$_GET['mainmenu'] = GETPOST('mainmenu', 'aZ09') ? GETPOST('mainmenu', 'aZ09') : 'home'; $action = GETPOST('action', 'aZ09'); $hookmanager->initHooks(array('index')); @@ -41,18 +42,15 @@ $hookmanager->initHooks(array('index')); */ // Check if company name is defined (first install) -if (!isset($conf->global->MAIN_INFO_SOCIETE_NOM) || empty($conf->global->MAIN_INFO_SOCIETE_NOM)) -{ +if (!isset($conf->global->MAIN_INFO_SOCIETE_NOM) || empty($conf->global->MAIN_INFO_SOCIETE_NOM)) { header("Location: ".DOL_URL_ROOT."/admin/index.php?mainmenu=home&leftmenu=setup&mesg=setupnotcomplete"); exit; } -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 -{ +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 header("Location: ".DOL_URL_ROOT."/admin/index.php?mainmenu=home&leftmenu=setup&mesg=setupnotcomplete"); exit; } -if (GETPOST('addbox')) // Add box (when submit is done from a form when ajax disabled) -{ +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'); @@ -60,7 +58,9 @@ if (GETPOST('addbox')) // Add box (when submit is done from a form when ajax dis $boxorder .= GETPOST('boxcombo', 'aZ09'); $result = InfoBox::saveboxorder($db, $zone, $boxorder, $userid); - if ($result > 0) setEventMessages($langs->trans("BoxAdded"), null); + if ($result > 0) { + setEventMessages($langs->trans("BoxAdded"), null); + } } @@ -68,11 +68,15 @@ if (GETPOST('addbox')) // Add box (when submit is done from a form when ajax dis * View */ -if (!isset($form) || !is_object($form)) $form = new Form($db); +if (!isset($form) || !is_object($form)) { + $form = new Form($db); +} // Title $title = $langs->trans("HomeArea").' - Dolibarr '.DOL_VERSION; -if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = $langs->trans("HomeArea").' - '.$conf->global->MAIN_APPLICATION_TITLE; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $title = $langs->trans("HomeArea").' - '.$conf->global->MAIN_APPLICATION_TITLE; +} llxHeader('', $title); @@ -82,11 +86,9 @@ $resultboxes = FormOther::getBoxesArea($user, "0"); // Load $resultboxes (select print load_fiche_titre('&nbsp;', $resultboxes['selectboxlist'], '', 0, '', 'titleforhome'); -if (!empty($conf->global->MAIN_MOTD)) -{ +if (!empty($conf->global->MAIN_MOTD)) { $conf->global->MAIN_MOTD = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', '<br>', $conf->global->MAIN_MOTD); - if (!empty($conf->global->MAIN_MOTD)) - { + if (!empty($conf->global->MAIN_MOTD)) { $substitutionarray = getCommonSubstitutionArray($langs); complete_substitutions_array($substitutionarray, $langs); $texttoshow = make_substitutions($conf->global->MAIN_MOTD, $substitutionarray, $langs); @@ -258,8 +260,12 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) { $object = new stdClass(); $parameters = array(); $action = ''; - $reshook = $hookmanager->executeHooks('addOpenElementsDashboardLine', $parameters, $object, - $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks( + 'addOpenElementsDashboardLine', + $parameters, + $object, + $action + ); // Note that $action and $object may have been modified by some hooks if ($reshook == 0) { $dashboardlines = array_merge($dashboardlines, $hookmanager->resArray); } @@ -414,8 +420,10 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) { $boxwork .= '<th class="liste_titre"><div class="inline-block valignmiddle">'.$langs->trans("DolibarrWorkBoard").'</div>'; if ($showweather) { if ($totallate > 0) { - $text = $langs->transnoentitiesnoconv("WarningYouHaveAtLeastOneTaskLate").' ('.$langs->transnoentitiesnoconv("NActionsLate", - $totallate.(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '%' : '')).')'; + $text = $langs->transnoentitiesnoconv("WarningYouHaveAtLeastOneTaskLate").' ('.$langs->transnoentitiesnoconv( + "NActionsLate", + $totallate.(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '%' : '') + ).')'; } else { $text = $langs->transnoentitiesnoconv("NoItemLate"); } @@ -457,17 +465,17 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) { $globalStatsKey = $groupElement['globalStatsKey']; $groupElement['globalStats'] = array(); - if (is_array($keys) && in_array($globalStatsKey, $keys)) - { + if (isset($keys) && is_array($keys) && in_array($globalStatsKey, $keys)) { // get key index of stats used in $includes, $classes, $keys, $icons, $titres, $links $keyIndex = array_search($globalStatsKey, $keys); $classe = (!empty($classes[$keyIndex]) ? $classes[$keyIndex] : ''); - if (isset($boardloaded[$classe]) && is_object($boardloaded[$classe])) - { + if (isset($boardloaded[$classe]) && is_object($boardloaded[$classe])) { $groupElement['globalStats']['total'] = $boardloaded[$classe]->nb[$globalStatsKey] ? $boardloaded[$classe]->nb[$globalStatsKey] : 0; $nbTotal = doubleval($groupElement['globalStats']['total']); - if ($nbTotal >= 10000) { $nbTotal = round($nbTotal / 1000, 2).'k'; } + if ($nbTotal >= 10000) { + $nbTotal = round($nbTotal / 1000, 2).'k'; + } $groupElement['globalStats']['text'] = $langs->trans('Total').' : '.$langs->trans($titres[$keyIndex]).' ('.$groupElement['globalStats']['total'].')'; $groupElement['globalStats']['total'] = $nbTotal; $groupElement['globalStats']['link'] = $links[$keyIndex]; @@ -549,13 +557,15 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) { } if ($showweather && !empty($isIntopOpenedDashBoard)) { - $appendClass = (!empty($conf->global->MAIN_DISABLE_METEO) && $conf->global->MAIN_DISABLE_METEO == 2 ? ' hideonsmartphone' : ''); + $appendClass = (!empty($conf->global->MAIN_DISABLE_METEO) && $conf->global->MAIN_DISABLE_METEO == 2 ? ' hideonsmartphone' : ''); $weather = getWeatherStatus($totallate); $text = ''; if ($totallate > 0) { - $text = $langs->transnoentitiesnoconv("WarningYouHaveAtLeastOneTaskLate").' ('.$langs->transnoentitiesnoconv("NActionsLate", - $totallate.(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '%' : '')).')'; + $text = $langs->transnoentitiesnoconv("WarningYouHaveAtLeastOneTaskLate").' ('.$langs->transnoentitiesnoconv( + "NActionsLate", + $totallate.(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '%' : '') + ).')'; } else { $text = $langs->transnoentitiesnoconv("NoItemLate"); } @@ -570,16 +580,24 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) { $weatherDashBoard .= ' <div class="info-box-title">'.$langs->trans('GlobalOpenedElemView').'</div>'."\n"; if ($totallatePercentage > 0 && !empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) { - $weatherDashBoard .= ' <span class="info-box-number">'.$langs->transnoentitiesnoconv("NActionsLate", - price($totallatePercentage).'%').'</span>'."\n"; - $weatherDashBoard .= ' <span class="progress-description">'.$langs->trans('NActionsLate', - $totalLateNumber).'</span>'."\n"; + $weatherDashBoard .= ' <span class="info-box-number">'.$langs->transnoentitiesnoconv( + "NActionsLate", + price($totallatePercentage).'%' + ).'</span>'."\n"; + $weatherDashBoard .= ' <span class="progress-description">'.$langs->trans( + 'NActionsLate', + $totalLateNumber + ).'</span>'."\n"; } else { - $weatherDashBoard .= ' <span class="info-box-number">'.$langs->transnoentitiesnoconv("NActionsLate", - $totalLateNumber).'</span>'."\n"; + $weatherDashBoard .= ' <span class="info-box-number">'.$langs->transnoentitiesnoconv( + "NActionsLate", + $totalLateNumber + ).'</span>'."\n"; if ($totallatePercentage > 0) { - $weatherDashBoard .= ' <span class="progress-description">'.$langs->trans('NActionsLate', - price($totallatePercentage).'%').'</span>'."\n"; + $weatherDashBoard .= ' <span class="progress-description">'.$langs->trans( + 'NActionsLate', + price($totallatePercentage).'%' + ).'</span>'."\n"; } } @@ -627,8 +645,11 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) { $boxwork .= '<div class="dashboardlinelatecoin nowrap">'; $boxwork .= '<a title="'.dol_escape_htmltag($textlate).'" class="valignmiddle dashboardlineindicatorlate'.($board->nbtodolate > 0 ? ' dashboardlineko' : ' dashboardlineok').'" href="'.((!$board->url_late) ? $board->url : $board->url_late).'">'; //$boxwork .= img_picto($textlate, "warning_white", 'class="valigntextbottom"').''; - $boxwork .= img_picto($textlate, "warning_white", - 'class="inline-block hideonsmartphone valigntextbottom"').''; + $boxwork .= img_picto( + $textlate, + "warning_white", + 'class="inline-block hideonsmartphone valigntextbottom"' + ).''; $boxwork .= '<span class="dashboardlineindicatorlate'.($board->nbtodolate > 0 ? ' dashboardlineko' : ' dashboardlineok').'">'; $boxwork .= $board->nbtodolate; $boxwork .= '</span>'; @@ -679,8 +700,7 @@ print '<div class="fichecenter fichecenterbis">'; $boxlist = '<div class="twocolumns">'; $boxlist .= '<div class="firstcolumn fichehalfleft boxhalfleft" id="boxhalfleft">'; -if (!empty($nbworkboardcount)) -{ +if (!empty($nbworkboardcount)) { $boxlist .= $boxwork; } @@ -708,30 +728,26 @@ print '</div>'; */ // Security warning repertoire install existe (si utilisateur admin) -if ($user->admin && empty($conf->global->MAIN_REMOVE_INSTALL_WARNING)) -{ +if ($user->admin && empty($conf->global->MAIN_REMOVE_INSTALL_WARNING)) { $message = ''; // Check if install lock file is present $lockfile = DOL_DATA_ROOT.'/install.lock'; - if (!empty($lockfile) && !file_exists($lockfile) && is_dir(DOL_DOCUMENT_ROOT."/install")) - { + if (!empty($lockfile) && !file_exists($lockfile) && is_dir(DOL_DOCUMENT_ROOT."/install")) { $langs->load("errors"); //if (! empty($message)) $message.='<br>'; $message .= info_admin($langs->trans("WarningLockFileDoesNotExists", DOL_DATA_ROOT).' '.$langs->trans("WarningUntilDirRemoved", DOL_DOCUMENT_ROOT."/install"), 0, 0, '1', 'clearboth'); } // Conf files must be in read only mode - if (is_writable($conffile)) - { + if (is_writable($conffile)) { $langs->load("errors"); //$langs->load("other"); //if (! empty($message)) $message.='<br>'; $message .= info_admin($langs->transnoentities("WarningConfFileMustBeReadOnly").' '.$langs->trans("WarningUntilDirRemoved", DOL_DOCUMENT_ROOT."/install"), 0, 0, '1', 'clearboth'); } - if ($message) - { + if ($message) { print $message; //$message.='<br>'; //print info_admin($langs->trans("WarningUntilDirRemoved",DOL_DOCUMENT_ROOT."/install")); diff --git a/htdocs/install/check.php b/htdocs/install/check.php index 0a3e49c9600..79c8e590ab9 100644 --- a/htdocs/install/check.php +++ b/htdocs/install/check.php @@ -43,7 +43,9 @@ $langs->load("install"); // Now we load forced/pre-set values from install.forced.php file. $useforcedwizard = false; $forcedfile = "./install.forced.php"; -if ($conffile == "/etc/dolibarr/conf.php") $forcedfile = "/etc/dolibarr/install.forced.php"; +if ($conffile == "/etc/dolibarr/conf.php") { + $forcedfile = "/etc/dolibarr/install.forced.php"; +} if (@file_exists($forcedfile)) { $useforcedwizard = true; include_once $forcedfile; @@ -62,40 +64,41 @@ pHeader('', ''); // No next step for navigation buttons. Next step is defined by //print "<br>\n"; //print $langs->trans("InstallEasy")."<br><br>\n"; -print '<h3><img class="valigntextbottom" src="../theme/common/octicons/build/svg/gear.svg" width="20" alt="Database"> '.$langs->trans("MiscellaneousChecks").":</h3>\n"; +print '<h3><img class="valigntextbottom inline-block" src="../theme/common/octicons/build/svg/gear.svg" width="20" alt="Database"> '; +print '<span class="inline-block">'.$langs->trans("MiscellaneousChecks")."</span></h3>\n"; // Check browser $useragent = $_SERVER['HTTP_USER_AGENT']; -if (!empty($useragent)) -{ +if (!empty($useragent)) { $tmp = getBrowserInfo($_SERVER["HTTP_USER_AGENT"]); $browserversion = $tmp['browserversion']; $browsername = $tmp['browsername']; - if ($browsername == 'ie' && $browserversion < 7) print '<img src="../theme/eldy/img/warning.png" alt="Error"> '.$langs->trans("WarningBrowserTooOld")."<br>\n"; + if ($browsername == 'ie' && $browserversion < 7) { + print '<img src="../theme/eldy/img/warning.png" alt="Error"> '.$langs->trans("WarningBrowserTooOld")."<br>\n"; + } } // Check PHP version $arrayphpminversionerror = array(5, 5, 0); $arrayphpminversionwarning = array(5, 6, 0); -if (versioncompare(versionphparray(), $arrayphpminversionerror) < 0) // Minimum to use (error if lower) -{ +if (versioncompare(versionphparray(), $arrayphpminversionerror) < 0) { // Minimum to use (error if lower) print '<img src="../theme/eldy/img/error.png" alt="Error"> '.$langs->trans("ErrorPHPVersionTooLow", versiontostring($arrayphpminversionerror)); $checksok = 0; // 0=error, 1=warning -} elseif (versioncompare(versionphparray(), $arrayphpminversionwarning) < 0) // Minimum supported (warning if lower) -{ +} elseif (versioncompare(versionphparray(), $arrayphpminversionwarning) < 0) { // Minimum supported (warning if lower) print '<img src="../theme/eldy/img/warning.png" alt="Error"> '.$langs->trans("ErrorPHPVersionTooLow", versiontostring($arrayphpminversionwarning)); $checksok = 0; // 0=error, 1=warning } else { print '<img src="../theme/eldy/img/tick.png" alt="Ok"> '.$langs->trans("PHPVersion")." ".versiontostring(versionphparray()); } -if (empty($force_install_nophpinfo)) print ' (<a href="phpinfo.php" target="_blank">'.$langs->trans("MoreInformation").'</a>)'; +if (empty($force_install_nophpinfo)) { + print ' (<a href="phpinfo.php" target="_blank">'.$langs->trans("MoreInformation").'</a>)'; +} print "<br>\n"; // Check PHP support for $_GET and $_POST -if (!isset($_GET["testget"]) && !isset($_POST["testpost"])) // We must keep $_GET and $_POST here -{ +if (!isset($_GET["testget"]) && !isset($_POST["testpost"])) { // We must keep $_GET and $_POST here print '<img src="../theme/eldy/img/warning.png" alt="Warning"> '.$langs->trans("PHPSupportPOSTGETKo"); print ' (<a href="'.$_SERVER["PHP_SELF"].'?testget=ok">'.$langs->trans("Recheck").'</a>)'; print "<br>\n"; @@ -106,8 +109,7 @@ if (!isset($_GET["testget"]) && !isset($_POST["testpost"])) // We must keep $_GE // Check if session_id is enabled -if (!function_exists("session_id")) -{ +if (!function_exists("session_id")) { print '<img src="../theme/eldy/img/error.png" alt="Error"> '.$langs->trans("ErrorPHPDoesNotSupportSessions")."<br>\n"; $checksok = 0; } else { @@ -116,8 +118,7 @@ if (!function_exists("session_id")) // Check if GD is supported (we need GD for image conversion) -if (!function_exists("imagecreate")) -{ +if (!function_exists("imagecreate")) { $langs->load("errors"); print '<img src="../theme/eldy/img/warning.png" alt="Error"> '.$langs->trans("ErrorPHPDoesNotSupportGD")."<br>\n"; // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install) @@ -127,8 +128,7 @@ if (!function_exists("imagecreate")) // Check if Curl is supported -if (!function_exists("curl_init")) -{ +if (!function_exists("curl_init")) { $langs->load("errors"); print '<img src="../theme/eldy/img/warning.png" alt="Error"> '.$langs->trans("ErrorPHPDoesNotSupportCurl")."<br>\n"; // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install) @@ -137,8 +137,7 @@ if (!function_exists("curl_init")) } // Check if PHP calendar extension is available -if (!function_exists("easter_date")) -{ +if (!function_exists("easter_date")) { print '<img src="../theme/eldy/img/warning.png" alt="Error"> '.$langs->trans("ErrorPHPDoesNotSupportCalendar")."<br>\n"; } else { print '<img src="../theme/eldy/img/tick.png" alt="Ok"> '.$langs->trans("PHPSupport", "Calendar")."<br>\n"; @@ -146,8 +145,7 @@ if (!function_exists("easter_date")) // Check if UTF8 is supported -if (!function_exists("utf8_encode")) -{ +if (!function_exists("utf8_encode")) { $langs->load("errors"); print '<img src="../theme/eldy/img/warning.png" alt="Error"> '.$langs->trans("ErrorPHPDoesNotSupportUTF8")."<br>\n"; // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install) @@ -157,10 +155,8 @@ if (!function_exists("utf8_encode")) // Check if intl methods are supported -if (empty($_SERVER["SERVER_ADMIN"]) || $_SERVER["SERVER_ADMIN"] != 'doliwamp@localhost') -{ - if (!function_exists("locale_get_primary_language") || !function_exists("locale_get_region")) - { +if (empty($_SERVER["SERVER_ADMIN"]) || $_SERVER["SERVER_ADMIN"] != 'doliwamp@localhost') { + if (!function_exists("locale_get_primary_language") || !function_exists("locale_get_region")) { $langs->load("errors"); print '<img src="../theme/eldy/img/warning.png" alt="Error"> '.$langs->trans("ErrorPHPDoesNotSupportIntl")."<br>\n"; // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install) @@ -169,8 +165,7 @@ if (empty($_SERVER["SERVER_ADMIN"]) || $_SERVER["SERVER_ADMIN"] != 'doliwamp@loc } } -if (!class_exists('ZipArchive')) -{ +if (!class_exists('ZipArchive')) { $langs->load("errors"); print '<img src="../theme/eldy/img/warning.png" alt="Error"> '.$langs->trans("ErrorPHPDoesNotSupport", "ZIP")."<br>\n"; // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install) @@ -183,17 +178,20 @@ $memrequiredorig = '64M'; $memrequired = 64 * 1024 * 1024; $memmaxorig = @ini_get("memory_limit"); $memmax = @ini_get("memory_limit"); -if ($memmaxorig != '') -{ +if ($memmaxorig != '') { preg_match('/([0-9]+)([a-zA-Z]*)/i', $memmax, $reg); - if ($reg[2]) - { - if (strtoupper($reg[2]) == 'G') $memmax = $reg[1] * 1024 * 1024 * 1024; - if (strtoupper($reg[2]) == 'M') $memmax = $reg[1] * 1024 * 1024; - if (strtoupper($reg[2]) == 'K') $memmax = $reg[1] * 1024; + if ($reg[2]) { + if (strtoupper($reg[2]) == 'G') { + $memmax = $reg[1] * 1024 * 1024 * 1024; + } + if (strtoupper($reg[2]) == 'M') { + $memmax = $reg[1] * 1024 * 1024; + } + if (strtoupper($reg[2]) == 'K') { + $memmax = $reg[1] * 1024; + } } - if ($memmax >= $memrequired || $memmax == -1) - { + if ($memmax >= $memrequired || $memmax == -1) { print '<img src="../theme/eldy/img/tick.png" alt="Ok"> '.$langs->trans("PHPMemoryOK", $memmaxorig, $memrequiredorig)."<br>\n"; } else { print '<img src="../theme/eldy/img/warning.png" alt="Warning"> '.$langs->trans("PHPMemoryTooLow", $memmaxorig, $memrequiredorig)."<br>\n"; @@ -203,15 +201,13 @@ if ($memmaxorig != '') // If that config file is present and filled clearstatcache(); -if (is_readable($conffile) && filesize($conffile) > 8) -{ +if (is_readable($conffile) && filesize($conffile) > 8) { dolibarr_install_syslog("check: conf file '".$conffile."' already defined"); $confexists = 1; include_once $conffile; $databaseok = 1; - if ($databaseok) - { + if ($databaseok) { // Already installed for all parts (config and database). We can propose upgrade. $allowupgrade = true; } else { @@ -223,8 +219,7 @@ if (is_readable($conffile) && filesize($conffile) > 8) $confexists = 0; // First we try by copying example - if (@copy($conffile.".example", $conffile)) - { + if (@copy($conffile.".example", $conffile)) { // Success dolibarr_install_syslog("check: successfully copied file ".$conffile.".example into ".$conffile); } else { @@ -232,12 +227,13 @@ if (is_readable($conffile) && filesize($conffile) > 8) dolibarr_install_syslog("check: failed to copy file ".$conffile.".example into ".$conffile.". We try to create it.", LOG_WARNING); $fp = @fopen($conffile, "w"); - if ($fp) - { + if ($fp) { @fwrite($fp, '<?php'); @fputs($fp, "\n"); fclose($fp); - } else dolibarr_install_syslog("check: failed to create a new file ".$conffile." into current dir ".getcwd().". Please check permissions.", LOG_ERR); + } else { + dolibarr_install_syslog("check: failed to create a new file ".$conffile." into current dir ".getcwd().". Please check permissions.", LOG_ERR); + } } // First install: no upgrade necessary/required @@ -247,8 +243,7 @@ if (is_readable($conffile) && filesize($conffile) > 8) // File is missing and cannot be created -if (!file_exists($conffile)) -{ +if (!file_exists($conffile)) { print '<img src="../theme/eldy/img/error.png" alt="Error"> '.$langs->trans("ConfFileDoesNotExistsAndCouldNotBeCreated", $conffiletoshow); print "<br><br>"; print $langs->trans("YouMustCreateWithPermission", $conffiletoshow); @@ -257,17 +252,13 @@ if (!file_exists($conffile)) print $langs->trans("CorrectProblemAndReloadPage", $_SERVER['PHP_SELF'].'?testget=ok'); $err++; } else { - if (dol_is_dir($conffile)) - { + if (dol_is_dir($conffile)) { print '<img src="../theme/eldy/img/error.png" alt="Warning"> '.$langs->trans("ConfFileMustBeAFileNotADir", $conffiletoshow); $allowinstall = 0; - } - // File exists but cannot be modified - elseif (!is_writable($conffile)) - { - if ($confexists) - { + } elseif (!is_writable($conffile)) { + // File exists but cannot be modified + if ($confexists) { print '<img src="../theme/eldy/img/tick.png" alt="Ok"> '.$langs->trans("ConfFileExists", $conffiletoshow); } else { print '<img src="../theme/eldy/img/tick.png" alt="Ok"> '.$langs->trans("ConfFileCouldBeCreated", $conffiletoshow); @@ -277,11 +268,9 @@ if (!file_exists($conffile)) print "<br>\n"; $allowinstall = 0; - } - // File exists and can be modified - else { - if ($confexists) - { + } else { + // File exists and can be modified + if ($confexists) { print '<img src="../theme/eldy/img/tick.png" alt="Ok"> '.$langs->trans("ConfFileExists", $conffiletoshow); } else { print '<img src="../theme/eldy/img/tick.png" alt="Ok"> '.$langs->trans("ConfFileCouldBeCreated", $conffiletoshow); @@ -295,32 +284,28 @@ if (!file_exists($conffile)) print "<br>\n"; // Requirements met/all ok: display the next step button - if ($checksok) - { + if ($checksok) { $ok = 0; // Try to create db connection - if (file_exists($conffile)) - { + if (file_exists($conffile)) { include_once $conffile; - if (!empty($dolibarr_main_db_type) && !empty($dolibarr_main_document_root)) - { - if (!file_exists($dolibarr_main_document_root."/core/lib/admin.lib.php")) - { + if (!empty($dolibarr_main_db_type) && !empty($dolibarr_main_document_root)) { + if (!file_exists($dolibarr_main_document_root."/core/lib/admin.lib.php")) { print '<span class="error">A '.$conffiletoshow.' file exists with a dolibarr_main_document_root to '.$dolibarr_main_document_root.' that seems wrong. Try to fix or remove the '.$conffiletoshow.' file.</span><br>'."\n"; dol_syslog("A '".$conffiletoshow."' file exists with a dolibarr_main_document_root to ".$dolibarr_main_document_root." that seems wrong. Try to fix or remove the '".$conffiletoshow."' file.", LOG_WARNING); } else { require_once $dolibarr_main_document_root.'/core/lib/admin.lib.php'; // If password is encoded, we decode it - if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) - { + if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) { require_once $dolibarr_main_document_root.'/core/lib/security.lib.php'; - if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) - { + if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) { $dolibarr_main_db_encrypted_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass); // We need to set this as it is used to know the password was initially crypted $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); - } else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } else { + $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } } // $conf already created in inc.php @@ -331,8 +316,7 @@ if (!file_exists($conffile)) $conf->db->user = $dolibarr_main_db_user; $conf->db->pass = $dolibarr_main_db_pass; $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); - if ($db->connected && $db->database_selected) - { + if ($db->connected && $db->database_selected) { $ok = true; } } @@ -340,16 +324,21 @@ if (!file_exists($conffile)) } // If database access is available, we set more variables - if ($ok) - { - if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption = 0; + if ($ok) { + if (empty($dolibarr_main_db_encryption)) { + $dolibarr_main_db_encryption = 0; + } $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption; - if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey = ''; + if (empty($dolibarr_main_db_cryptkey)) { + $dolibarr_main_db_cryptkey = ''; + } $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey; $conf->setValues($db); // Reset forced setup after the setValues - if (defined('SYSLOG_FILE')) $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); + if (defined('SYSLOG_FILE')) { + $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); + } $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1; // Current version is $conf->global->MAIN_VERSION_LAST_UPGRADE @@ -359,14 +348,15 @@ if (!file_exists($conffile)) } // Show title - if (!empty($conf->global->MAIN_VERSION_LAST_UPGRADE) || !empty($conf->global->MAIN_VERSION_LAST_INSTALL)) - { + if (!empty($conf->global->MAIN_VERSION_LAST_UPGRADE) || !empty($conf->global->MAIN_VERSION_LAST_INSTALL)) { print $langs->trans("VersionLastUpgrade").': <b><span class="ok">'.(empty($conf->global->MAIN_VERSION_LAST_UPGRADE) ? $conf->global->MAIN_VERSION_LAST_INSTALL : $conf->global->MAIN_VERSION_LAST_UPGRADE).'</span></b> - '; print $langs->trans("VersionProgram").': <b><span class="ok">'.DOL_VERSION.'</span></b>'; //print ' '.img_warning($langs->trans("RunningUpdateProcessMayBeRequired")); print '<br>'; print '<br>'; - } else print "<br>\n"; + } else { + print "<br>\n"; + } //print $langs->trans("InstallEasy")." "; print '<h3><span class="soustitre">'.$langs->trans("ChooseYourSetupMode").'</span></h3>'; @@ -376,8 +366,7 @@ if (!file_exists($conffile)) $available_choices = array(); $notavailable_choices = array(); - if (empty($dolibarr_main_db_host)) // This means install process was not run - { + if (empty($dolibarr_main_db_host)) { // This means install process was not run $foundrecommandedchoice = 1; // To show only once } @@ -387,8 +376,7 @@ if (!file_exists($conffile)) $choice .= '</td>'; $choice .= '<td class="listofchoicesdesc">'; $choice .= $langs->trans("FreshInstallDesc"); - if (empty($dolibarr_main_db_host)) // This means install process was not run - { + if (empty($dolibarr_main_db_host)) { // This means install process was not run $choice .= '<br>'; //print $langs->trans("InstallChoiceRecommanded",DOL_VERSION,$conf->global->MAIN_VERSION_LAST_UPGRADE); $choice .= '<div class="center"><div class="ok suggestedchoice">'.$langs->trans("InstallChoiceSuggested").'</div></div>'; @@ -397,8 +385,7 @@ if (!file_exists($conffile)) $choice .= '</td>'; $choice .= '<td class="center">'; - if ($allowinstall) - { + if ($allowinstall) { $choice .= '<a class="button" href="fileconf.php?selectlang='.$setuplang.'">'.$langs->trans("Start").'</a>'; } else { $choice .= ($foundrecommandedchoice ? '<span class="warning">' : '').$langs->trans("InstallNotAllowed").($foundrecommandedchoice ? '</span>' : ''); @@ -415,12 +402,15 @@ if (!file_exists($conffile)) // Show upgrade lines $allowupgrade = true; - if (empty($dolibarr_main_db_host)) // This means install process was not run - { + if (empty($dolibarr_main_db_host)) { // This means install process was not run $allowupgrade = false; } - if (defined("MAIN_NOT_INSTALLED")) $allowupgrade = false; - if (GETPOST('allowupgrade')) $allowupgrade = true; + if (defined("MAIN_NOT_INSTALLED")) { + $allowupgrade = false; + } + if (GETPOST('allowupgrade')) { + $allowupgrade = true; + } $migrationscript = array(array('from'=>'3.0.0', 'to'=>'3.1.0'), array('from'=>'3.1.0', 'to'=>'3.2.0'), array('from'=>'3.2.0', 'to'=>'3.3.0'), @@ -444,8 +434,7 @@ if (!file_exists($conffile)) ); $count = 0; - foreach ($migrationscript as $migarray) - { + foreach ($migrationscript as $migarray) { $choice = ''; $count++; @@ -460,20 +449,16 @@ if (!file_exists($conffile)) $newversionfrom = preg_replace('/(\.[0-9]+)$/i', '.*', $versionfrom); $newversionto = preg_replace('/(\.[0-9]+)$/i', '.*', $versionto); $newversionfrombis = ''; - if (versioncompare($dolibarrversiontoarray, $versionarray) < -2) // From x.y.z -> x.y.z+1 - { + if (versioncompare($dolibarrversiontoarray, $versionarray) < -2) { // From x.y.z -> x.y.z+1 $newversionfrombis = ' '.$langs->trans("or").' '.$versionto; } - if ($ok) - { - if (count($dolibarrlastupgradeversionarray) >= 2) // If database access is available and last upgrade version is known - { + if ($ok) { + if (count($dolibarrlastupgradeversionarray) >= 2) { // If database access is available and last upgrade version is known // Now we check if this is the first qualified choice if ($allowupgrade && empty($foundrecommandedchoice) && (versioncompare($dolibarrversiontoarray, $dolibarrlastupgradeversionarray) > 0 || versioncompare($dolibarrversiontoarray, $versionarray) < -2) - ) - { + ) { $foundrecommandedchoice = 1; // To show only once $recommended_choice = true; } @@ -489,14 +474,12 @@ if (!file_exists($conffile)) $choice .= '<td class="listofchoicesdesc">'; $choice .= $langs->trans("UpgradeDesc"); - if ($recommended_choice) - { + if ($recommended_choice) { $choice .= '<br>'; //print $langs->trans("InstallChoiceRecommanded",DOL_VERSION,$conf->global->MAIN_VERSION_LAST_UPGRADE); $choice .= '<div class="center">'; $choice .= '<div class="ok suggestedchoice">'.$langs->trans("InstallChoiceSuggested").'</div>'; - if ($count < count($migarray)) // There are other choices after - { + if ($count < count($migarray)) { // There are other choices after print $langs->trans("MigrateIsDoneStepByStep", DOL_VERSION); } $choice .= '</div>'; @@ -504,19 +487,15 @@ if (!file_exists($conffile)) $choice .= '</td>'; $choice .= '<td class="center">'; - if ($allowupgrade) - { + if ($allowupgrade) { $disabled = false; - if ($foundrecommandedchoice == 2) - { + if ($foundrecommandedchoice == 2) { $disabled = true; } - if ($foundrecommandedchoice == 1) - { + if ($foundrecommandedchoice == 1) { $foundrecommandedchoice = 2; } - if ($disabled) - { + if ($disabled) { $choice .= '<span class="opacitymedium">'.$langs->trans("NotYetAvailable").'</span>'; } else { $choice .= '<a class="button runupgrade" href="upgrade.php?action=upgrade'.($count < count($migrationscript) ? '_'.$versionto : '').'&amp;selectlang='.$setuplang.'&amp;versionfrom='.$versionfrom.'&amp;versionto='.$versionto.'">'.$langs->trans("Start").'</a>'; @@ -535,8 +514,7 @@ if (!file_exists($conffile)) } // If there is no choice at all, we show all of them. - if (empty($available_choices)) - { + if (empty($available_choices)) { $available_choices = $notavailable_choices; $notavailable_choices = array(); } diff --git a/htdocs/install/default.css b/htdocs/install/default.css index ca397d1ca40..eaefd6d5b2b 100644 --- a/htdocs/install/default.css +++ b/htdocs/install/default.css @@ -20,6 +20,10 @@ opacity: 0.5; } +.inline-block { + display: inline-block; +} + body { font-size:14px; font-family: roboto,arial,tahoma,verdana,helvetica; @@ -353,15 +357,16 @@ tr.choiceselected td.listofchoicesdesc { } tr.choiceselected td .button { - background: rgb(0,113,121); + background: rgba(150, 110, 162, 0.95); color: #fff; } a.button:link,a.button:visited,a.button:active { color: #888; + } .button { - background: #ddd; + background: rgb(234,228,225); color: #fff; /* border: 1px solid #e0e0e0; */ padding: 0.5em 0.7em; diff --git a/htdocs/install/inc.php b/htdocs/install/inc.php index 12bab777edb..91ceae9eaaa 100644 --- a/htdocs/install/inc.php +++ b/htdocs/install/inc.php @@ -5,7 +5,8 @@ * Copyright (C) 2007-2012 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2012 Marcos García <marcosgdf@gmail.com> * Copyright (C) 2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr> - * + * Copyright (C) 2021 Charlene Benke <charlene@patas-monkey.com> +* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or @@ -27,40 +28,40 @@ */ // Just to define version DOL_VERSION -if (!defined('DOL_INC_FOR_VERSION_ERROR')) define('DOL_INC_FOR_VERSION_ERROR', '1'); +if (!defined('DOL_INC_FOR_VERSION_ERROR')) { + define('DOL_INC_FOR_VERSION_ERROR', '1'); +} require_once '../filefunc.inc.php'; // Define DOL_DOCUMENT_ROOT and ADODB_PATH used for install/upgrade process -if (!defined('DOL_DOCUMENT_ROOT')) define('DOL_DOCUMENT_ROOT', '..'); -if (!defined('ADODB_PATH')) -{ +if (!defined('DOL_DOCUMENT_ROOT')) { + define('DOL_DOCUMENT_ROOT', '..'); +} +if (!defined('ADODB_PATH')) { $foundpath = DOL_DOCUMENT_ROOT.'/includes/adodbtime/'; - if (!is_dir($foundpath)) $foundpath = '/usr/share/php/adodb/'; + if (!is_dir($foundpath)) { + $foundpath = '/usr/share/php/adodb/'; + } define('ADODB_PATH', $foundpath); } require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/conf.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once ADODB_PATH.'adodb-time.inc.php'; -// Avoid warnings with strict mode E_STRICT -$conf = new stdClass(); // instantiate $conf explicitely -$conf->global = new stdClass(); -$conf->file = new stdClass(); -$conf->db = new stdClass(); -$conf->syslog = new stdClass(); +$conf = new Conf(); // Force $_REQUEST["logtohtml"] $_REQUEST["logtohtml"] = 1; // Correction PHP_SELF (ex pour apache via caudium) car PHP_SELF doit valoir URL relative // et non path absolu. -if (isset($_SERVER["DOCUMENT_URI"]) && $_SERVER["DOCUMENT_URI"]) -{ +if (isset($_SERVER["DOCUMENT_URI"]) && $_SERVER["DOCUMENT_URI"]) { $_SERVER["PHP_SELF"] = $_SERVER["DOCUMENT_URI"]; } @@ -79,19 +80,21 @@ $conffiletoshow = "htdocs/conf/conf.php"; // Load conf file if it is already defined -if (!defined('DONOTLOADCONF') && file_exists($conffile) && filesize($conffile) > 8) // Test on filesize is to ensure that conf file is more that an empty template with just <?php in first line -{ +if (!defined('DONOTLOADCONF') && file_exists($conffile) && filesize($conffile) > 8) { // Test on filesize is to ensure that conf file is more that an empty template with just <?php in first line $result = include_once $conffile; // Load conf file - if ($result) - { - if (empty($dolibarr_main_db_type)) $dolibarr_main_db_type = 'mysqli'; // For backward compatibility + if ($result) { + if (empty($dolibarr_main_db_type)) { + $dolibarr_main_db_type = 'mysqli'; // For backward compatibility + } //Mysql driver support has been removed in favor of mysqli if ($dolibarr_main_db_type == 'mysql') { $dolibarr_main_db_type = 'mysqli'; } - if (empty($dolibarr_main_db_port) && ($dolibarr_main_db_type == 'mysqli')) $dolibarr_main_db_port = '3306'; // For backward compatibility + if (empty($dolibarr_main_db_port) && ($dolibarr_main_db_type == 'mysqli')) { + $dolibarr_main_db_port = '3306'; // For backward compatibility + } // Clean parameters $dolibarr_main_data_root = isset($dolibarr_main_data_root) ?trim($dolibarr_main_data_root) : DOL_DOCUMENT_ROOT.'/../documents'; @@ -101,25 +104,31 @@ if (!defined('DONOTLOADCONF') && file_exists($conffile) && filesize($conffile) > $dolibarr_main_document_root_alt = isset($dolibarr_main_document_root_alt) ?trim($dolibarr_main_document_root_alt) : ''; // Remove last / or \ on directories or url value - if (!empty($dolibarr_main_document_root) && !preg_match('/^[\\/]+$/', $dolibarr_main_document_root)) $dolibarr_main_document_root = preg_replace('/[\\/]+$/', '', $dolibarr_main_document_root); - if (!empty($dolibarr_main_url_root) && !preg_match('/^[\\/]+$/', $dolibarr_main_url_root)) $dolibarr_main_url_root = preg_replace('/[\\/]+$/', '', $dolibarr_main_url_root); - if (!empty($dolibarr_main_data_root) && !preg_match('/^[\\/]+$/', $dolibarr_main_data_root)) $dolibarr_main_data_root = preg_replace('/[\\/]+$/', '', $dolibarr_main_data_root); - if (!empty($dolibarr_main_document_root_alt) && !preg_match('/^[\\/]+$/', $dolibarr_main_document_root_alt)) $dolibarr_main_document_root_alt = preg_replace('/[\\/]+$/', '', $dolibarr_main_document_root_alt); - if (!empty($dolibarr_main_url_root_alt) && !preg_match('/^[\\/]+$/', $dolibarr_main_url_root_alt)) $dolibarr_main_url_root_alt = preg_replace('/[\\/]+$/', '', $dolibarr_main_url_root_alt); + if (!empty($dolibarr_main_document_root) && !preg_match('/^[\\/]+$/', $dolibarr_main_document_root)) { + $dolibarr_main_document_root = preg_replace('/[\\/]+$/', '', $dolibarr_main_document_root); + } + if (!empty($dolibarr_main_url_root) && !preg_match('/^[\\/]+$/', $dolibarr_main_url_root)) { + $dolibarr_main_url_root = preg_replace('/[\\/]+$/', '', $dolibarr_main_url_root); + } + if (!empty($dolibarr_main_data_root) && !preg_match('/^[\\/]+$/', $dolibarr_main_data_root)) { + $dolibarr_main_data_root = preg_replace('/[\\/]+$/', '', $dolibarr_main_data_root); + } + if (!empty($dolibarr_main_document_root_alt) && !preg_match('/^[\\/]+$/', $dolibarr_main_document_root_alt)) { + $dolibarr_main_document_root_alt = preg_replace('/[\\/]+$/', '', $dolibarr_main_document_root_alt); + } + if (!empty($dolibarr_main_url_root_alt) && !preg_match('/^[\\/]+$/', $dolibarr_main_url_root_alt)) { + $dolibarr_main_url_root_alt = preg_replace('/[\\/]+$/', '', $dolibarr_main_url_root_alt); + } // Create conf object - if (!empty($dolibarr_main_document_root)) - { + if (!empty($dolibarr_main_document_root)) { $result = conf($dolibarr_main_document_root); } // Load database driver - if ($result) - { - if (!empty($dolibarr_main_document_root) && !empty($dolibarr_main_db_type)) - { + if ($result) { + if (!empty($dolibarr_main_document_root) && !empty($dolibarr_main_db_type)) { $result = include_once $dolibarr_main_document_root."/core/db/".$dolibarr_main_db_type.'.class.php'; - if (!$result) - { + if (!$result) { $includeconferror = 'ErrorBadValueForDolibarrMainDBType'; } } @@ -133,7 +142,9 @@ if (!defined('DONOTLOADCONF') && file_exists($conffile) && filesize($conffile) > $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1; // Define prefix -if (!isset($dolibarr_main_db_prefix) || !$dolibarr_main_db_prefix) $dolibarr_main_db_prefix = 'llx_'; +if (!isset($dolibarr_main_db_prefix) || !$dolibarr_main_db_prefix) { + $dolibarr_main_db_prefix = 'llx_'; +} define('MAIN_DB_PREFIX', (isset($dolibarr_main_db_prefix) ? $dolibarr_main_db_prefix : '')); define('DOL_CLASS_PATH', 'class/'); // Filsystem path to class dir @@ -141,42 +152,51 @@ define('DOL_DATA_ROOT', (isset($dolibarr_main_data_root) ? $dolibarr_main_data_r define('DOL_MAIN_URL_ROOT', (isset($dolibarr_main_url_root) ? $dolibarr_main_url_root : '')); // URL relative root $uri = preg_replace('/^http(s?):\/\//i', '', constant('DOL_MAIN_URL_ROOT')); // $uri contains url without http* $suburi = strstr($uri, '/'); // $suburi contains url without domain -if ($suburi == '/') $suburi = ''; // If $suburi is /, it is now '' +if ($suburi == '/') { + $suburi = ''; // If $suburi is /, it is now '' +} define('DOL_URL_ROOT', $suburi); // URL relative root ('', '/dolibarr', ...) -if (empty($conf->file->character_set_client)) $conf->file->character_set_client = "utf-8"; -if (empty($conf->db->character_set)) $conf->db->character_set = 'utf8'; -if (empty($conf->db->dolibarr_main_db_collation)) $conf->db->dolibarr_main_db_collation = 'utf8_unicode_ci'; -if (empty($conf->db->dolibarr_main_db_encryption)) $conf->db->dolibarr_main_db_encryption = 0; -if (empty($conf->db->dolibarr_main_db_cryptkey)) $conf->db->dolibarr_main_db_cryptkey = ''; -if (empty($conf->db->user)) $conf->db->user = ''; +if (empty($conf->file->character_set_client)) { + $conf->file->character_set_client = "utf-8"; +} +if (empty($conf->db->character_set)) { + $conf->db->character_set = 'utf8'; +} +if (empty($conf->db->dolibarr_main_db_collation)) { + $conf->db->dolibarr_main_db_collation = 'utf8_unicode_ci'; +} +if (empty($conf->db->dolibarr_main_db_encryption)) { + $conf->db->dolibarr_main_db_encryption = 0; +} +if (empty($conf->db->dolibarr_main_db_cryptkey)) { + $conf->db->dolibarr_main_db_cryptkey = ''; +} +if (empty($conf->db->user)) { + $conf->db->user = ''; +} // Define array of document root directories $conf->file->dol_document_root = array(DOL_DOCUMENT_ROOT); -if (!empty($dolibarr_main_document_root_alt)) -{ +if (!empty($dolibarr_main_document_root_alt)) { // dolibarr_main_document_root_alt contains several directories $values = preg_split('/[;,]/', $dolibarr_main_document_root_alt); - foreach ($values as $value) - { + foreach ($values as $value) { $conf->file->dol_document_root[] = $value; } } // Security check (old method, when directory is renamed /install.lock) -if (preg_match('/install\.lock/i', $_SERVER["SCRIPT_FILENAME"])) -{ - if (!is_object($langs)) - { +if (preg_match('/install\.lock/i', $_SERVER["SCRIPT_FILENAME"])) { + if (!is_object($langs)) { $langs = new Translate('..', $conf); $langs->setDefaultLang('auto'); } $langs->load("install"); print $langs->trans("YouTryInstallDisabledByDirLock"); - if (!empty($dolibarr_main_url_root)) - { + if (!empty($dolibarr_main_url_root)) { print 'Click on following link, <a href="'.$dolibarr_main_url_root.'/admin/index.php?mainmenu=home&leftmenu=setup'.(GETPOSTISSET("login") ? '&username='.urlencode(GETPOST("login")) : '').'">'; print $langs->trans("ClickHereToGoToApp"); print '</a>'; @@ -190,17 +210,14 @@ if (constant('DOL_DATA_ROOT') === null) { // Try to detect any lockfile in the default documents path $lockfile = '../../documents/install.lock'; } -if (@file_exists($lockfile)) -{ - if (!isset($langs) || !is_object($langs)) - { +if (@file_exists($lockfile)) { + if (!isset($langs) || !is_object($langs)) { $langs = new Translate('..', $conf); $langs->setDefaultLang('auto'); } $langs->load("install"); print $langs->trans("YouTryInstallDisabledByFileLock"); - if (!empty($dolibarr_main_url_root)) - { + if (!empty($dolibarr_main_url_root)) { print $langs->trans("ClickOnLinkOrRemoveManualy").'<br>'; print '<a href="'.$dolibarr_main_url_root.'/admin/index.php?mainmenu=home&leftmenu=setup'.(GETPOSTISSET("login") ? '&username='.urlencode(GETPOST("login")) : '').'">'; print $langs->trans("ClickHereToGoToApp"); @@ -215,42 +232,55 @@ if (@file_exists($lockfile)) // Force usage of log file for install and upgrades $conf->syslog->enabled = 1; $conf->global->SYSLOG_LEVEL = constant('LOG_DEBUG'); -if (!defined('SYSLOG_HANDLERS')) define('SYSLOG_HANDLERS', '["mod_syslog_file"]'); -if (!defined('SYSLOG_FILE')) // To avoid warning on systems with constant already defined -{ - if (@is_writable('/tmp')) define('SYSLOG_FILE', '/tmp/dolibarr_install.log'); - elseif (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"])) define('SYSLOG_FILE', $_ENV["TMP"].'/dolibarr_install.log'); - elseif (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"])) define('SYSLOG_FILE', $_ENV["TEMP"].'/dolibarr_install.log'); - elseif (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat')) define('SYSLOG_FILE', '../../../../dolibarr_install.log'); // For DoliWamp - elseif (@is_writable('../../')) define('SYSLOG_FILE', '../../dolibarr_install.log'); // For others +if (!defined('SYSLOG_HANDLERS')) { + define('SYSLOG_HANDLERS', '["mod_syslog_file"]'); +} +if (!defined('SYSLOG_FILE')) { // To avoid warning on systems with constant already defined + if (@is_writable('/tmp')) { + define('SYSLOG_FILE', '/tmp/dolibarr_install.log'); + } elseif (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"])) { + define('SYSLOG_FILE', $_ENV["TMP"].'/dolibarr_install.log'); + } elseif (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"])) { + define('SYSLOG_FILE', $_ENV["TEMP"].'/dolibarr_install.log'); + } elseif (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat')) { + define('SYSLOG_FILE', '../../../../dolibarr_install.log'); // For DoliWamp + } elseif (@is_writable('../../')) { + define('SYSLOG_FILE', '../../dolibarr_install.log'); // For others + } //print 'SYSLOG_FILE='.SYSLOG_FILE;exit; } -if (defined('SYSLOG_FILE')) $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); -if (!defined('SYSLOG_FILE_NO_ERROR')) define('SYSLOG_FILE_NO_ERROR', 1); +if (defined('SYSLOG_FILE')) { + $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); +} +if (!defined('SYSLOG_FILE_NO_ERROR')) { + define('SYSLOG_FILE_NO_ERROR', 1); +} // We init log handler for install $handlers = array('mod_syslog_file'); -foreach ($handlers as $handler) -{ +foreach ($handlers as $handler) { $file = DOL_DOCUMENT_ROOT.'/core/modules/syslog/'.$handler.'.php'; - if (!file_exists($file)) - { + if (!file_exists($file)) { throw new Exception('Missing log handler file '.$handler.'.php'); } require_once $file; $loghandlerinstance = new $handler(); - if (!$loghandlerinstance instanceof LogHandlerInterface) - { + if (!$loghandlerinstance instanceof LogHandlerInterface) { throw new Exception('Log handler does not extend LogHandlerInterface'); } - if (empty($conf->loghandlers[$handler])) $conf->loghandlers[$handler] = $loghandlerinstance; + if (empty($conf->loghandlers[$handler])) { + $conf->loghandlers[$handler] = $loghandlerinstance; + } } // Define object $langs $langs = new Translate('..', $conf); -if (GETPOST('lang', 'aZ09')) $langs->setDefaultLang(GETPOST('lang', 'aZ09')); -else $langs->setDefaultLang('auto'); +if (GETPOST('lang', 'aZ09')) { + $langs->setDefaultLang(GETPOST('lang', 'aZ09')); +} else { + $langs->setDefaultLang('auto'); +} /** @@ -271,7 +301,9 @@ function conf($dolibarr_main_document_root) global $character_set_client; $return = include_once $dolibarr_main_document_root.'/core/class/conf.class.php'; - if (!$return) return -1; + if (!$return) { + return -1; + } $conf = new Conf(); $conf->db->type = trim($dolibarr_main_db_type); @@ -282,51 +314,73 @@ function conf($dolibarr_main_document_root) $conf->db->pass = trim($dolibarr_main_db_pass); // Mysql driver support has been removed in favor of mysqli - if ($conf->db->type == 'mysql') $conf->db->type = 'mysqli'; - if (empty($character_set_client)) $character_set_client = "UTF-8"; + if ($conf->db->type == 'mysql') { + $conf->db->type = 'mysqli'; + } + if (empty($character_set_client)) { + $character_set_client = "UTF-8"; + } $conf->file->character_set_client = strtoupper($character_set_client); - if (empty($dolibarr_main_db_character_set)) $dolibarr_main_db_character_set = ($conf->db->type == 'mysqli' ? 'utf8' : ''); + if (empty($dolibarr_main_db_character_set)) { + $dolibarr_main_db_character_set = ($conf->db->type == 'mysqli' ? 'utf8' : ''); + } $conf->db->character_set = $dolibarr_main_db_character_set; - if (empty($dolibarr_main_db_collation)) $dolibarr_main_db_collation = ($conf->db->type == 'mysqli' ? 'utf8_unicode_ci' : ''); + if (empty($dolibarr_main_db_collation)) { + $dolibarr_main_db_collation = ($conf->db->type == 'mysqli' ? 'utf8_unicode_ci' : ''); + } $conf->db->dolibarr_main_db_collation = $dolibarr_main_db_collation; - if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption = 0; + if (empty($dolibarr_main_db_encryption)) { + $dolibarr_main_db_encryption = 0; + } $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption; - if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey = ''; + if (empty($dolibarr_main_db_cryptkey)) { + $dolibarr_main_db_cryptkey = ''; + } $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey; // Force usage of log file for install and upgrades $conf->syslog->enabled = 1; $conf->global->SYSLOG_LEVEL = constant('LOG_DEBUG'); - if (!defined('SYSLOG_HANDLERS')) define('SYSLOG_HANDLERS', '["mod_syslog_file"]'); - if (!defined('SYSLOG_FILE')) // To avoid warning on systems with constant already defined - { - if (@is_writable('/tmp')) define('SYSLOG_FILE', '/tmp/dolibarr_install.log'); - elseif (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"])) define('SYSLOG_FILE', $_ENV["TMP"].'/dolibarr_install.log'); - elseif (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"])) define('SYSLOG_FILE', $_ENV["TEMP"].'/dolibarr_install.log'); - elseif (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat')) define('SYSLOG_FILE', '../../../../dolibarr_install.log'); // For DoliWamp - elseif (@is_writable('../../')) define('SYSLOG_FILE', '../../dolibarr_install.log'); // For others + if (!defined('SYSLOG_HANDLERS')) { + define('SYSLOG_HANDLERS', '["mod_syslog_file"]'); + } + if (!defined('SYSLOG_FILE')) { // To avoid warning on systems with constant already defined + if (@is_writable('/tmp')) { + define('SYSLOG_FILE', '/tmp/dolibarr_install.log'); + } elseif (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"])) { + define('SYSLOG_FILE', $_ENV["TMP"].'/dolibarr_install.log'); + } elseif (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"])) { + define('SYSLOG_FILE', $_ENV["TEMP"].'/dolibarr_install.log'); + } elseif (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat')) { + define('SYSLOG_FILE', '../../../../dolibarr_install.log'); // For DoliWamp + } elseif (@is_writable('../../')) { + define('SYSLOG_FILE', '../../dolibarr_install.log'); // For others + } //print 'SYSLOG_FILE='.SYSLOG_FILE;exit; } - if (defined('SYSLOG_FILE')) $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); - if (!defined('SYSLOG_FILE_NO_ERROR')) define('SYSLOG_FILE_NO_ERROR', 1); + if (defined('SYSLOG_FILE')) { + $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); + } + if (!defined('SYSLOG_FILE_NO_ERROR')) { + define('SYSLOG_FILE_NO_ERROR', 1); + } // We init log handler for install $handlers = array('mod_syslog_file'); - foreach ($handlers as $handler) - { + foreach ($handlers as $handler) { $file = DOL_DOCUMENT_ROOT.'/core/modules/syslog/'.$handler.'.php'; - if (!file_exists($file)) - { + if (!file_exists($file)) { throw new Exception('Missing log handler file '.$handler.'.php'); } require_once $file; $loghandlerinstance = new $handler(); - if (!$loghandlerinstance instanceof LogHandlerInterface) - { + if (!$loghandlerinstance instanceof LogHandlerInterface) { throw new Exception('Log handler does not extend LogHandlerInterface'); } - if (empty($conf->loghandlers[$handler])) $conf->loghandlers[$handler] = $loghandlerinstance; + if (empty($conf->loghandlers[$handler])) { + $conf->loghandlers[$handler] = $loghandlerinstance; + } } return 1; @@ -354,8 +408,7 @@ function pHeader($subtitle, $next, $action = 'set', $param = '', $forcejqueryurl $jquerytheme = 'base'; - if ($forcejqueryurl) - { + if ($forcejqueryurl) { $jQueryCustomPath = $forcejqueryurl; $jQueryUiCustomPath = $forcejqueryurl; } else { @@ -376,14 +429,23 @@ function pHeader($subtitle, $next, $action = 'set', $param = '', $forcejqueryurl print '<link rel="stylesheet" type="text/css" href="default.css">'."\n"; print '<!-- Includes CSS for JQuery -->'."\n"; - if ($jQueryUiCustomPath) print '<link rel="stylesheet" type="text/css" href="'.$jQueryUiCustomPath.'css/'.$jquerytheme.'/jquery-ui.min.css" />'."\n"; // JQuery - else print '<link rel="stylesheet" type="text/css" href="../includes/jquery/css/'.$jquerytheme.'/jquery-ui.min.css" />'."\n"; // JQuery + if ($jQueryUiCustomPath) { + print '<link rel="stylesheet" type="text/css" href="'.$jQueryUiCustomPath.'css/'.$jquerytheme.'/jquery-ui.min.css" />'."\n"; // JQuery + } else { + print '<link rel="stylesheet" type="text/css" href="../includes/jquery/css/'.$jquerytheme.'/jquery-ui.min.css" />'."\n"; // JQuery + } print '<!-- Includes JS for JQuery -->'."\n"; - if ($jQueryCustomPath) print '<script type="text/javascript" src="'.$jQueryCustomPath.'jquery.min.js"></script>'."\n"; - else print '<script type="text/javascript" src="../includes/jquery/js/jquery.min.js"></script>'."\n"; - if ($jQueryUiCustomPath) print '<script type="text/javascript" src="'.$jQueryUiCustomPath.'jquery-ui.min.js"></script>'."\n"; - else print '<script type="text/javascript" src="../includes/jquery/js/jquery-ui.min.js"></script>'."\n"; + if ($jQueryCustomPath) { + print '<script type="text/javascript" src="'.$jQueryCustomPath.'jquery.min.js"></script>'."\n"; + } else { + print '<script type="text/javascript" src="../includes/jquery/js/jquery.min.js"></script>'."\n"; + } + if ($jQueryUiCustomPath) { + print '<script type="text/javascript" src="'.$jQueryUiCustomPath.'jquery-ui.min.js"></script>'."\n"; + } else { + print '<script type="text/javascript" src="../includes/jquery/js/jquery-ui.min.js"></script>'."\n"; + } print '<title>'.$langs->trans("DolibarrSetup").'</title>'."\n"; print '</head>'."\n"; @@ -402,7 +464,9 @@ function pHeader($subtitle, $next, $action = 'set', $param = '', $forcejqueryurl print '</span>'."\n"; print '<form name="forminstall" style="width: 100%" action="'.$next.'.php'.($param ? '?'.$param : '').'" method="POST"'; - if ($next == 'step5') print ' autocomplete="off"'; + if ($next == 'step5') { + print ' autocomplete="off"'; + } print '>'."\n"; print '<input type="hidden" name="testpost" value="ok">'."\n"; print '<input type="hidden" name="action" value="'.$action.'">'."\n"; @@ -419,9 +483,10 @@ function pHeader($subtitle, $next, $action = 'set', $param = '', $forcejqueryurl * @param string $setuplang Language code * @param string $jscheckfunction Add a javascript check function * @param integer $withpleasewait Add also please wait tags + * @param string $morehtml Add more HTML content * @return void */ -function pFooter($nonext = 0, $setuplang = '', $jscheckfunction = '', $withpleasewait = 0) +function pFooter($nonext = 0, $setuplang = '', $jscheckfunction = '', $withpleasewait = 0, $morehtml = '') { global $conf, $langs; @@ -430,11 +495,13 @@ function pFooter($nonext = 0, $setuplang = '', $jscheckfunction = '', $withpleas print '</td></tr></table>'."\n"; print '</td></tr></table>'."\n"; - if (!$nonext || ($nonext == '2')) - { + print '<!-- pFooter -->'."\n"; + + print $morehtml; + + if (!$nonext || ($nonext == '2')) { print '<div class="nextbutton" id="nextbutton">'; - if ($nonext == '2') - { + if ($nonext == '2') { print '<span class="warning">'; print $langs->trans("ErrorFoundDuringMigration", isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"].'&ignoreerrors=1' : ''); print '</span>'; @@ -442,25 +509,26 @@ function pFooter($nonext = 0, $setuplang = '', $jscheckfunction = '', $withpleas } print '<input type="submit" '.($nonext == '2' ? 'disabled="disabled" ' : '').'value="'.$langs->trans("NextStep").' ->"'; - if ($jscheckfunction) print ' onClick="return '.$jscheckfunction.'();"'; + if ($jscheckfunction) { + print ' onClick="return '.$jscheckfunction.'();"'; + } print '></div>'; - if ($withpleasewait) print '<div style="visibility: hidden;" class="pleasewait" id="pleasewait"><br>'.$langs->trans("NextStepMightLastALongTime").'<br><br><div class="blinkwait">'.$langs->trans("PleaseBePatient").'</div></div>'; + if ($withpleasewait) { + print '<div style="visibility: hidden;" class="pleasewait" id="pleasewait"><br>'.$langs->trans("NextStepMightLastALongTime").'<br><br><div class="blinkwait">'.$langs->trans("PleaseBePatient").'</div></div>'; + } } - if ($setuplang) - { + if ($setuplang) { print '<input type="hidden" name="selectlang" value="'.$setuplang.'">'; } print '</form>'."\n"; // If there is some logs in buffer to show - if (isset($conf->logbuffer) && count($conf->logbuffer)) - { + if (isset($conf->logbuffer) && count($conf->logbuffer)) { print "\n"; print "<!-- Start of log output\n"; //print '<div class="hidden">'."\n"; - foreach ($conf->logbuffer as $logline) - { + foreach ($conf->logbuffer as $logline) { print $logline."<br>\n"; } //print '</div>'."\n"; @@ -481,7 +549,9 @@ function pFooter($nonext = 0, $setuplang = '', $jscheckfunction = '', $withpleas */ function dolibarr_install_syslog($message, $level = LOG_DEBUG) { - if (!defined('LOG_DEBUG')) define('LOG_DEBUG', 6); + if (!defined('LOG_DEBUG')) { + define('LOG_DEBUG', 6); + } dol_syslog($message, $level); } @@ -494,8 +564,7 @@ function detect_dolibarr_main_document_root() { // If PHP is in CGI mode, SCRIPT_FILENAME is PHP's path. // Since that's not what we want, we suggest $_SERVER["DOCUMENT_ROOT"] - if ($_SERVER["SCRIPT_FILENAME"] == 'php' || preg_match('/[\\/]php$/i', $_SERVER["SCRIPT_FILENAME"]) || preg_match('/php\.exe$/i', $_SERVER["SCRIPT_FILENAME"])) - { + if ($_SERVER["SCRIPT_FILENAME"] == 'php' || preg_match('/[\\/]php$/i', $_SERVER["SCRIPT_FILENAME"]) || preg_match('/php\.exe$/i', $_SERVER["SCRIPT_FILENAME"])) { $dolibarr_main_document_root = $_SERVER["DOCUMENT_ROOT"]; if (!preg_match('/[\\/]dolibarr[\\/]htdocs$/i', $dolibarr_main_document_root)) { @@ -532,11 +601,11 @@ function detect_dolibarr_main_url_root() // If defined (Ie: Apache with Linux) if (isset($_SERVER["SCRIPT_URI"])) { $dolibarr_main_url_root = $_SERVER["SCRIPT_URI"]; - } // If defined (Ie: Apache with Caudium) - elseif (isset($_SERVER["SERVER_URL"]) && isset($_SERVER["DOCUMENT_URI"])) { + } elseif (isset($_SERVER["SERVER_URL"]) && isset($_SERVER["DOCUMENT_URI"])) { + // If defined (Ie: Apache with Caudium) $dolibarr_main_url_root = $_SERVER["SERVER_URL"].$_SERVER["DOCUMENT_URI"]; - } // If SCRIPT_URI, SERVER_URL, DOCUMENT_URI not defined (Ie: Apache 2.0.44 for Windows) - else { + } else { + // If SCRIPT_URI, SERVER_URL, DOCUMENT_URI not defined (Ie: Apache 2.0.44 for Windows) $proto = ((!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') || (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443)) ? 'https' : 'http'; if (!empty($_SERVER["HTTP_HOST"])) { $serverport = $_SERVER["HTTP_HOST"]; diff --git a/htdocs/install/index.php b/htdocs/install/index.php index f2da647e68c..09300a75721 100644 --- a/htdocs/install/index.php +++ b/htdocs/install/index.php @@ -32,8 +32,7 @@ global $langs; $err = 0; // If the config file exists and is filled, we're not on first install so we skip the language selection page -if (file_exists($conffile) && isset($dolibarr_main_url_root)) -{ +if (file_exists($conffile) && isset($dolibarr_main_url_root)) { header("Location: check.php?testget=ok"); exit; } @@ -65,4 +64,6 @@ print '</table></div>'; print '<br><br><span class="opacitymedium">'.$langs->trans("SomeTranslationAreUncomplete").'</span>'; // If there's no error, we display the next step button -if ($err == 0) pFooter(0); +if ($err == 0) { + pFooter(0); +} diff --git a/htdocs/install/lib/repair.lib.php b/htdocs/install/lib/repair.lib.php index 1a05dad1b77..6133f3eccc8 100644 --- a/htdocs/install/lib/repair.lib.php +++ b/htdocs/install/lib/repair.lib.php @@ -33,14 +33,18 @@ function checkElementExist($id, $table) global $db; $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$table; - $sql .= ' WHERE rowid = '.$id; + $sql .= ' WHERE rowid = '.((int) $id); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num > 0) return true; - else return false; - } else return true; // for security + if ($num > 0) { + return true; + } else { + return false; + } + } else { + return true; // for security + } } /** @@ -60,28 +64,37 @@ function checkLinkedElements($sourcetype, $targettype) $sourcetable = $sourcetype; $targettable = $targettype; - if ($sourcetype == 'shipping') $sourcetable = 'expedition'; - elseif ($targettype == 'shipping') $targettable = 'expedition'; - if ($sourcetype == 'delivery') $sourcetable = 'livraison'; - elseif ($targettype == 'delivery') $targettable = 'livraison'; - if ($sourcetype == 'order_supplier') $sourcetable = 'commande_fournisseur'; - elseif ($targettype == 'order_supplier') $targettable = 'commande_fournisseur'; - if ($sourcetype == 'invoice_supplier') $sourcetable = 'facture_fourn'; - elseif ($targettype == 'invoice_supplier') $targettable = 'facture_fourn'; + if ($sourcetype == 'shipping') { + $sourcetable = 'expedition'; + } elseif ($targettype == 'shipping') { + $targettable = 'expedition'; + } + if ($sourcetype == 'delivery') { + $sourcetable = 'livraison'; + } elseif ($targettype == 'delivery') { + $targettable = 'livraison'; + } + if ($sourcetype == 'order_supplier') { + $sourcetable = 'commande_fournisseur'; + } elseif ($targettype == 'order_supplier') { + $targettable = 'commande_fournisseur'; + } + if ($sourcetype == 'invoice_supplier') { + $sourcetable = 'facture_fourn'; + } elseif ($targettype == 'invoice_supplier') { + $targettable = 'facture_fourn'; + } $out = $langs->trans('SourceType').': '.$sourcetype.' => '.$langs->trans('TargetType').': '.$targettype.' '; $sql = 'SELECT rowid, fk_source, fk_target FROM '.MAIN_DB_PREFIX.'element_element'; $sql .= ' WHERE sourcetype="'.$sourcetype.'" AND targettype="'.$targettype.'"'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $elements[$obj->rowid] = array($sourcetype => $obj->fk_source, $targettype => $obj->fk_target); $i++; @@ -89,12 +102,9 @@ function checkLinkedElements($sourcetype, $targettype) } } - if (!empty($elements)) - { - foreach ($elements as $key => $element) - { - if (!checkElementExist($element[$sourcetype], $sourcetable) || !checkElementExist($element[$targettype], $targettable)) - { + if (!empty($elements)) { + foreach ($elements as $key => $element) { + if (!checkElementExist($element[$sourcetype], $sourcetable) || !checkElementExist($element[$targettype], $targettable)) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'element_element'; $sql .= ' WHERE rowid = '.$key; $resql = $db->query($sql); @@ -103,8 +113,11 @@ function checkLinkedElements($sourcetype, $targettype) } } - if ($deleted) $out .= '('.$langs->trans('LinkedElementsInvalidDeleted', $deleted).')<br>'; - else $out .= '('.$langs->trans('NothingToDelete').')<br>'; + if ($deleted) { + $out .= '('.$langs->trans('LinkedElementsInvalidDeleted', $deleted).')<br>'; + } else { + $out .= '('.$langs->trans('NothingToDelete').')<br>'; + } return $out; } @@ -121,22 +134,23 @@ function clean_data_ecm_directories() // Clean data from ecm_directories $sql = "SELECT rowid, label FROM ".MAIN_DB_PREFIX."ecm_directories"; $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $db->fetch_object($resql)) { $id = $obj->rowid; $label = $obj->label; $newlabel = dol_sanitizeFileName($label); - if ($label != $newlabel) - { + if ($label != $newlabel) { $sqlupdate = "UPDATE ".MAIN_DB_PREFIX."ecm_directories set label='".$db->escape($newlabel)."' WHERE rowid=".$id; print '<tr><td>'.$sqlupdate."</td></tr>\n"; $resqlupdate = $db->query($sqlupdate); - if (!$resqlupdate) dol_print_error($db, 'Failed to update'); + if (!$resqlupdate) { + dol_print_error($db, 'Failed to update'); + } } } - } else dol_print_error($db, 'Failed to run request'); + } else { + dol_print_error($db, 'Failed to run request'); + } return; } diff --git a/htdocs/install/mysql/data/llx_00_c_country.sql b/htdocs/install/mysql/data/llx_00_c_country.sql index acb2c956fda..b0d578829b9 100644 --- a/htdocs/install/mysql/data/llx_00_c_country.sql +++ b/htdocs/install/mysql/data/llx_00_c_country.sql @@ -278,4 +278,5 @@ INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (24 -- Set field eec -UPDATE llx_c_country SET eec = 1 WHERE code IN ('AT','BE','BG','CY','CZ','DE','DK','EE','ES','FI','FR','GB','GR','HR','NL','HU','IE','IM','IT','LT','LU','LV','MC','MT','PL','PT','RO','SE','SK','SI','UK'); +UPDATE llx_c_country SET eec = 1 WHERE code IN ('AT','BE','BG','CY','CZ','DE','DK','EE','ES','FI','FR','GR','HR','NL','HU','IE','IM','IT','LT','LU','LV','MC','MT','PL','PT','RO','SE','SK','SI'); + diff --git a/htdocs/install/mysql/data/llx_10_c_regions.sql b/htdocs/install/mysql/data/llx_10_c_regions.sql index 43d2652298f..f10b86fca7a 100644 --- a/htdocs/install/mysql/data/llx_10_c_regions.sql +++ b/htdocs/install/mysql/data/llx_10_c_regions.sql @@ -32,7 +32,15 @@ -- -- --- Regions +-- Regions +-- ID Country +-- 1 France +-- 2 Belgium +-- 3 Italy +-- 4 Spain +-- 5 Germany -> use departments +-- 6 Switzerland +-- 7 United Kingdom (NOT England) -- insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 0, 0, '0',0,'-'); @@ -131,7 +139,7 @@ INSERT INTO llx_c_regions ( code_region, fk_pays, cheflieu, tncc, nom, active) v -- Regions Switzerland (id country=6) INSERT INTO llx_c_regions (fk_pays, code_region, cheflieu, tncc, nom, active) values ( 6, 601, '', 1, 'Cantons', 1); --- Regions England (id_country=7) +-- Regions UK United Kingdom (id_country=7) INSERT INTO llx_c_regions (fk_pays, code_region, cheflieu, tncc, nom, active) values ( 7, 701, '', 0, 'England', 1); INSERT INTO llx_c_regions (fk_pays, code_region, cheflieu, tncc, nom, active) values ( 7, 702, '', 0, 'Wales', 1); INSERT INTO llx_c_regions (fk_pays, code_region, cheflieu, tncc, nom, active) values ( 7, 703, '', 0, 'Scotland', 1); @@ -163,7 +171,7 @@ insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (10,102 insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (10,1023, '',0,'Tunis'); insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (10,1024, '',0,'Zaghouan'); --- Region US (id country=11) +-- Region USA (id country=11) INSERT INTO llx_c_regions (fk_pays, code_region, cheflieu, tncc, nom, active) values ( 11, 1101, '', 0, 'United-States', 1); -- Regions Algeria (id country=13) @@ -346,41 +354,44 @@ INSERT INTO llx_c_regions (fk_pays, code_region, cheflieu, tncc, nom) VALUES ('2 INSERT INTO llx_c_regions (fk_pays, code_region, cheflieu, tncc, nom) VALUES ('202', '20204', 'SI04', NULL, 'West Slovenia'); -- Regions China (rowid country=9) -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,901, '京',0,'北京市'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,902, '津',0,'天津市'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,903, '沪',0,'上海市'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,904, '渝',0,'重庆市'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,905, '冀',0,'河北省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,906, '晋',0,'山西省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,907, '辽',0,'辽宁省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,908, '吉',0,'吉林省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,909, '黑',0,'黑龙江省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,910, '苏',0,'江苏省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,911, '浙',0,'浙江省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,912, '皖',0,'安徽省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,913, '闽',0,'福建省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,914, '赣',0,'江西省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,915, '鲁',0,'山东省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,916, '豫',0,'河南省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,917, '鄂',0,'湖北省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,918, '湘',0,'湖南省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,919, '粤',0,'广东省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,920, '琼',0,'海南省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,921, '川',0,'四川省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,922, '贵',0,'贵州省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,923, '云',0,'云南省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,924, '陕',0,'陕西省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,925, '甘',0,'甘肃省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,926, '青',0,'青海省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,927, '台',0,'台湾省'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,928, '蒙',0,'内蒙古自治区'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,929, '桂',0,'广西壮族自治区'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,930, '藏',0,'西藏自治区'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,931, '宁',0,'宁夏回族自治区'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,932, '新',0,'新疆维吾尔自治区'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,933, '港',0,'香港特别行政区'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9,934, '澳',0,'澳门特别行政区'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 901, '京',0,'北京市'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 902, '津',0,'天津市'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 903, '沪',0,'上海市'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 904, '渝',0,'重庆市'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 905, '冀',0,'河北省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 906, '晋',0,'山西省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 907, '辽',0,'辽宁省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 908, '吉',0,'吉林省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 909, '黑',0,'黑龙江省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 910, '苏',0,'江苏省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 911, '浙',0,'浙江省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 912, '皖',0,'安徽省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 913, '闽',0,'福建省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 914, '赣',0,'江西省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 915, '鲁',0,'山东省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 916, '豫',0,'河南省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 917, '鄂',0,'湖北省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 918, '湘',0,'湖南省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 919, '粤',0,'广东省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 920, '琼',0,'海南省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 921, '川',0,'四川省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 922, '贵',0,'贵州省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 923, '云',0,'云南省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 924, '陕',0,'陕西省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 925, '甘',0,'甘肃省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 926, '青',0,'青海省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 927, '台',0,'台湾省'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 928, '蒙',0,'内蒙古自治区'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 929, '桂',0,'广西壮族自治区'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 930, '藏',0,'西藏自治区'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 931, '宁',0,'宁夏回族自治区'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 932, '新',0,'新疆维吾尔自治区'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 933, '港',0,'香港特别行政区'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (9, 934, '澳',0,'澳门特别行政区'); -- Regions Angola (rowid country=35) INSERT INTO llx_c_regions (fk_pays, code_region, cheflieu, tncc, nom) VALUES (35, 35001, 'AO', NULL, 'Angola'); +-- Regions Taiwan (rowid country=213) +INSERT INTO llx_c_regions (fk_pays, code_region, cheflieu, tncc, nom) VALUES (213, 21301, 'TW', NULL, 'Taiwan'); + diff --git a/htdocs/install/mysql/data/llx_20_c_departements.sql b/htdocs/install/mysql/data/llx_20_c_departements.sql index 00f30fab0be..acd9f0532b5 100644 --- a/htdocs/install/mysql/data/llx_20_c_departements.sql +++ b/htdocs/install/mysql/data/llx_20_c_departements.sql @@ -30,10 +30,33 @@ -- Do not concatenate the values in a single query, for the same reason. -- --- Departements/Cantons/Provinces +-- Departements/Cantons/Provinces/States -- -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values ( 0, '0', '0',0,'-','-'); +insert into llx_c_departements (fk_region, code_departement, cheflieu, tncc, ncc, nom) values ( 0, '0', '0',0,'-','-'); + + +-- Andorra Parròquies (id country=34) +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, ncc, nom) VALUES (34000, 'AD-002', 'AD100', NULL, NULL, 'Canillo'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, ncc, nom) VALUES (34000, 'AD-003', 'AD200', NULL, NULL, 'Encamp'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, ncc, nom) VALUES (34000, 'AD-004', 'AD400', NULL, NULL, 'La Massana'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, ncc, nom) VALUES (34000, 'AD-005', 'AD300', NULL, NULL, 'Ordino'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, ncc, nom) VALUES (34000, 'AD-006', 'AD600', NULL, NULL, 'Sant Julià de Lòria'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, ncc, nom) VALUES (34000, 'AD-007', 'AD500', NULL, NULL, 'Andorra la Vella'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, ncc, nom) VALUES (34000, 'AD-008', 'AD700', NULL, NULL, 'Escaldes-Engordany'); + + +-- Austria States (Bundesländer) (id country=41) +INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'B','BURGENLAND','Burgenland',1); +INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'K','KAERNTEN','Kärnten',1); +INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'N','NIEDEROESTERREICH','Niederösterreich',1); +INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'O','OBEROESTERREICH','Oberösterreich',1); +INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'S','SALZBURG','Salzburg',1); +INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'ST','STEIERMARK','Steiermark',1); +INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'T','TIROL','Tirol',1); +INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'V','VORARLBERG','Vorarlberg',1); +INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'W','WIEN','Wien',1); + -- Departements France (id country=1) insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values ( 1,'971','97105',3,'GUADELOUPE','Guadeloupe'); @@ -139,16 +162,6 @@ insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,no insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (11,'94','94028',2,'VAL-DE-MARNE','Val-de-Marne'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (11,'95','95500',2,'VAL-D OISE','Val-d Oise'); --- Provinces Austria (id country=41) -INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'B','BURGENLAND','Burgenland',1); -INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'K','KAERNTEN','Kärnten',1); -INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'N','NIEDEROESTERREICH','Niederösterreich',1); -INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'O','OBEROESTERREICH','Oberösterreich',1); -INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'S','SALZBURG','Salzburg',1); -INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'ST','STEIERMARK','Steiermark',1); -INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'T','TIROL','Tirol',1); -INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'V','VORARLBERG','Vorarlberg',1); -INSERT INTO llx_c_departements (fk_region, code_departement, ncc, nom, active) VALUES (4101,'W','WIEN','Wien',1); -- Provinces Belgium (id country=2) insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (201,'01','',1,'ANVERS','Anvers'); @@ -1539,15 +1552,6 @@ INSERT INTO llx_c_departements (code_departement, fk_region, cheflieu, tncc, ncc INSERT INTO llx_c_departements (code_departement, fk_region, cheflieu, tncc, ncc, nom, active) VALUES ('AE-6', 22701, '', 0, '', 'Sharjah', 1); INSERT INTO llx_c_departements (code_departement, fk_region, cheflieu, tncc, ncc, nom, active) VALUES ('AE-7', 22701, '', 0, '', 'Umm al-Quwain', 1); --- Provinces Andorra (rowid country=34) -INSERT INTO llx_c_departements (code_departement, fk_region, cheflieu, tncc, ncc, nom) VALUES ('AD-002', 34000, 'AD100', NULL, NULL, 'Canillo'); -INSERT INTO llx_c_departements (code_departement, fk_region, cheflieu, tncc, ncc, nom) VALUES ('AD-003', 34000, 'AD200', NULL, NULL, 'Encamp'); -INSERT INTO llx_c_departements (code_departement, fk_region, cheflieu, tncc, ncc, nom) VALUES ('AD-004', 34000, 'AD400', NULL, NULL, 'La Massana'); -INSERT INTO llx_c_departements (code_departement, fk_region, cheflieu, tncc, ncc, nom) VALUES ('AD-005', 34000, 'AD300', NULL, NULL, 'Ordino'); -INSERT INTO llx_c_departements (code_departement, fk_region, cheflieu, tncc, ncc, nom) VALUES ('AD-006', 34000, 'AD600', NULL, NULL, 'Sant Julià de Lòria'); -INSERT INTO llx_c_departements (code_departement, fk_region, cheflieu, tncc, ncc, nom) VALUES ('AD-007', 34000, 'AD500', NULL, NULL, 'Andorra la Vella'); -INSERT INTO llx_c_departements (code_departement, fk_region, cheflieu, tncc, ncc, nom) VALUES ('AD-008', 34000, 'AD700', NULL, NULL, 'Escaldes-Engordany'); - -- Provinces Hungary (rowid country=18) INSERT INTO llx_c_departements (code_departement, fk_region, cheflieu, tncc, ncc, nom) VALUES ('HU-BK', 183300, 'HU331', NULL, NULL, 'Bács-Kiskun'); INSERT INTO llx_c_departements (code_departement, fk_region, cheflieu, tncc, ncc, nom) VALUES ('HU-BA', 182300, 'HU231', NULL, NULL, 'Baranya'); @@ -1626,3 +1630,37 @@ INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, ncc INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, ncc, nom) VALUES ('35001', 'AO-NAM', NULL, NULL, 'NAMÍBE', 'Namíbe'); INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, ncc, nom) VALUES ('35001', 'AO-UIG', NULL, NULL, 'UÍGE', 'Uíge'); INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, ncc, nom) VALUES ('35001', 'AO-ZAI', NULL, NULL, 'ZAÍRE', 'Zaíre'); + +-- Provinces Taiwan (rowid country=886) +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-KLU', 'KLU', NULL, '基隆市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-TPE', 'TPE', NULL, '臺北市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-TPH', 'TPH', NULL, '新北市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-TYC', 'TYC', NULL, '桃園市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-HSH', 'HSH', NULL, '新竹縣'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-HSC', 'HSC', NULL, '新竹市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-MAL', 'MAL', NULL, '苗栗縣'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-MAC', 'MAC', NULL, '苗栗市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-TXG', 'TXG', NULL, '臺中市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-CWH', 'CWH', NULL, '彰化縣'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-CWS', 'CWS', NULL, '彰化市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-NTC', 'NTC', NULL, '南投市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-NTO', 'NTO', NULL, '南投縣'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-YLH', 'YLH', NULL, '雲林縣'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-CHY', 'CHY', NULL, '嘉義縣'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-CYI', 'CYI', NULL, '嘉義市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-TNN', 'TNN', NULL, '臺南市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-KHH', 'KHH', NULL, '高雄市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-IUH', 'IUH', NULL, '屏東縣'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-PTS', 'PTS', NULL, '屏東市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-ILN', 'ILN', NULL, '宜蘭縣'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-ILC', 'ILC', NULL, '宜蘭市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-HWA', 'HWA', NULL, '花蓮縣'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-HWC', 'HWC', NULL, '花蓮市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-TTC', 'TTC', NULL, '臺東市'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-TTT', 'TTT', NULL, '臺東縣'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-PEH', 'PEH', NULL, '澎湖縣'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-GNI', 'GNI', NULL, '綠島'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-KYD', 'KYD', NULL, '蘭嶼'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-KMN', 'KMN', NULL, '金門縣'); +INSERT INTO llx_c_departements (fk_region, code_departement, cheflieu, tncc, nom) VALUES (21301, 'TW-LNN', 'LNN', NULL, '連江縣'); + diff --git a/htdocs/install/mysql/data/llx_accounting_abc.sql b/htdocs/install/mysql/data/llx_accounting_abc.sql index b5e94449988..3c178f7c70d 100644 --- a/htdocs/install/mysql/data/llx_accounting_abc.sql +++ b/htdocs/install/mysql/data/llx_accounting_abc.sql @@ -178,3 +178,6 @@ INSERT INTO llx_accounting_system (fk_country, pcg_version, label, active) VALUE -- Description of chart of account Canada CA-ENG-BASE INSERT INTO llx_accounting_system (fk_country, pcg_version, label, active) VALUES ( 14, 'CA-ENG-BASE', 'Canadian basic chart of accounts - English', 1); + +-- Description of chart of account Mexico SAT/24-2019 +INSERT INTO llx_accounting_system (fk_country, pcg_version, label, active) VALUES ( 154, 'SAT/24-2019', 'Catalogo y codigo agrupador fiscal del 2019', 1); diff --git a/htdocs/install/mysql/data/llx_accounting_account_mx.sql b/htdocs/install/mysql/data/llx_accounting_account_mx.sql new file mode 100644 index 00000000000..000a81022c7 --- /dev/null +++ b/htdocs/install/mysql/data/llx_accounting_account_mx.sql @@ -0,0 +1,1085 @@ +-- + +-- Description of chart of account Mexico SAT/24-2019 +-- + +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526100000, 'SAT/24-2019', 'ACTIVO', '100', 0, 'Activo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526100010, 'SAT/24-2019', 'ACTIVO', '100.01', 526100000, 'Activo a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526100990, 'SAT/24-2019', 'ACTIVO', '100.99', 526100010, 'Efectivo y Equivalentes de Efectivo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526101000, 'SAT/24-2019', 'ACTIVO', '101', 526100990, 'Caja', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526101010, 'SAT/24-2019', 'ACTIVO', '101.01', 526101000, 'Caja y efectivo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526102000, 'SAT/24-2019', 'ACTIVO', '102', 526100990, 'Bancos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526102010, 'SAT/24-2019', 'ACTIVO', '102.01', 526102000, 'Bancos nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526102020, 'SAT/24-2019', 'ACTIVO', '102.02', 526102000, 'Bancos extranjeros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526103000, 'SAT/24-2019', 'ACTIVO', '103', 526100990, 'Inversiones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526103010, 'SAT/24-2019', 'ACTIVO', '103.01', 526103000, 'Inversiones temporales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526103020, 'SAT/24-2019', 'ACTIVO', '103.02', 526103000, 'Inversiones en fideicomisos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526103030, 'SAT/24-2019', 'ACTIVO', '103.03', 526103000, 'Otras inversiones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526104000, 'SAT/24-2019', 'ACTIVO', '104', 526100990, 'Otros instrumentos financieros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526104010, 'SAT/24-2019', 'ACTIVO', '104.01', 526104000, 'Otros instrumentos financieros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526105000, 'SAT/24-2019', 'ACTIVO', '105', 526100010, 'Clientes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526105010, 'SAT/24-2019', 'ACTIVO', '105.01', 526105000, 'Clientes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526105020, 'SAT/24-2019', 'ACTIVO', '105.02', 526105000, 'Clientes extranjeros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526105030, 'SAT/24-2019', 'ACTIVO', '105.03', 526105000, 'Clientes nacionales parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526105040, 'SAT/24-2019', 'ACTIVO', '105.04', 526105000, 'Clientes extranjeros parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526106000, 'SAT/24-2019', 'ACTIVO', '106', 526100010, 'Cuentas y documentos por cobrar a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526106010, 'SAT/24-2019', 'ACTIVO', '106.01', 526106000, 'Cuentas y documentos por cobrar a corto plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526106020, 'SAT/24-2019', 'ACTIVO', '106.02', 526106000, 'Cuentas y documentos por cobrar a corto plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526106030, 'SAT/24-2019', 'ACTIVO', '106.03', 526106000, 'Cuentas y documentos por cobrar a corto plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526106040, 'SAT/24-2019', 'ACTIVO', '106.04', 526106000, 'Cuentas y documentos por cobrar a corto plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526106050, 'SAT/24-2019', 'ACTIVO', '106.05', 526106000, 'Intereses por cobrar a corto plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526106060, 'SAT/24-2019', 'ACTIVO', '106.06', 526106000, 'Intereses por cobrar a corto plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526106070, 'SAT/24-2019', 'ACTIVO', '106.07', 526106000, 'Intereses por cobrar a corto plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526106080, 'SAT/24-2019', 'ACTIVO', '106.08', 526106000, 'Intereses por cobrar a corto plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526106090, 'SAT/24-2019', 'ACTIVO', '106.09', 526106000, 'Otras cuentas y documentos por cobrar a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526106100, 'SAT/24-2019', 'ACTIVO', '106.1', 526106000, 'Otras cuentas y documentos por cobrar a corto plazo parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526107000, 'SAT/24-2019', 'ACTIVO', '107', 526100010, 'Deudores diversos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526107010, 'SAT/24-2019', 'ACTIVO', '107.01', 526107000, 'Funcionarios y empleados', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526107020, 'SAT/24-2019', 'ACTIVO', '107.02', 526107000, 'Socios y accionistas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526107030, 'SAT/24-2019', 'ACTIVO', '107.03', 526107000, 'Partes relacionadas nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526107040, 'SAT/24-2019', 'ACTIVO', '107.04', 526107000, 'Partes relacionadas extranjeros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526107050, 'SAT/24-2019', 'ACTIVO', '107.05', 526107000, 'Otros deudores diversos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526108000, 'SAT/24-2019', 'ACTIVO', '108', 526100010, 'Estimación de cuentas incobrables', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526108010, 'SAT/24-2019', 'ACTIVO', '108.01', 526108000, 'Estimación de cuentas incobrables nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526108020, 'SAT/24-2019', 'ACTIVO', '108.02', 526108000, 'Estimación de cuentas incobrables extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526108030, 'SAT/24-2019', 'ACTIVO', '108.03', 526108000, 'Estimación de cuentas incobrables nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526108040, 'SAT/24-2019', 'ACTIVO', '108.04', 526108000, 'Estimación de cuentas incobrables extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109000, 'SAT/24-2019', 'ACTIVO', '109', 526100990, 'Pagos anticipados', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109010, 'SAT/24-2019', 'ACTIVO', '109.01', 526109000, 'Seguros y fianzas pagados por anticipado nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109020, 'SAT/24-2019', 'ACTIVO', '109.02', 526109000, 'Seguros y fianzas pagados por anticipado extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109030, 'SAT/24-2019', 'ACTIVO', '109.03', 526109000, 'Seguros y fianzas pagados por anticipado nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109040, 'SAT/24-2019', 'ACTIVO', '109.04', 526109000, 'Seguros y fianzas pagados por anticipado extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109050, 'SAT/24-2019', 'ACTIVO', '109.05', 526109000, 'Rentas pagados por anticipado nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109060, 'SAT/24-2019', 'ACTIVO', '109.06', 526109000, 'Rentas pagados por anticipado extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109070, 'SAT/24-2019', 'ACTIVO', '109.07', 526109000, 'Rentas pagados por anticipado nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109080, 'SAT/24-2019', 'ACTIVO', '109.08', 526109000, 'Rentas pagados por anticipado extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109090, 'SAT/24-2019', 'ACTIVO', '109.09', 526109000, 'Intereses pagados por anticipado nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109100, 'SAT/24-2019', 'ACTIVO', '109.1', 526109000, 'Intereses pagados por anticipado extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109110, 'SAT/24-2019', 'ACTIVO', '109.11', 526109000, 'Intereses pagados por anticipado nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109120, 'SAT/24-2019', 'ACTIVO', '109.12', 526109000, 'Intereses pagados por anticipado extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109130, 'SAT/24-2019', 'ACTIVO', '109.13', 526109000, 'Factoraje financiero pagados por anticipado nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109140, 'SAT/24-2019', 'ACTIVO', '109.14', 526109000, 'Factoraje financiero pagados por anticipado extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109150, 'SAT/24-2019', 'ACTIVO', '109.15', 526109000, 'Factoraje financiero pagados por anticipado nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109160, 'SAT/24-2019', 'ACTIVO', '109.16', 526109000, 'Factoraje financiero pagados por anticipado extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109170, 'SAT/24-2019', 'ACTIVO', '109.17', 526109000, 'Arrendamiento financiero pagados por anticipado nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109180, 'SAT/24-2019', 'ACTIVO', '109.18', 526109000, 'Arrendamiento financiero pagados por anticipado extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109190, 'SAT/24-2019', 'ACTIVO', '109.19', 526109000, 'Arrendamiento financiero pagados por anticipado nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109200, 'SAT/24-2019', 'ACTIVO', '109.2', 526109000, 'Arrendamiento financiero pagados por anticipado extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109210, 'SAT/24-2019', 'ACTIVO', '109.21', 526109000, 'Pérdida por deterioro de pagos anticipados', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109220, 'SAT/24-2019', 'ACTIVO', '109.22', 526109000, 'Derechos fiduciarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526109230, 'SAT/24-2019', 'ACTIVO', '109.23', 526109000, 'Otros pagos anticipados', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526110000, 'SAT/24-2019', 'ACTIVO', '110', 526100010, 'Subsidio al empleo por aplicar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526110010, 'SAT/24-2019', 'ACTIVO', '110.01', 526110000, 'Subsidio al empleo por aplicar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526111000, 'SAT/24-2019', 'ACTIVO', '111', 526100010, 'Crédito al diésel por acreditar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526111010, 'SAT/24-2019', 'ACTIVO', '111.01', 526111000, 'Crédito al diésel por acreditar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526112000, 'SAT/24-2019', 'ACTIVO', '112', 526100010, 'Otros estímulos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526112010, 'SAT/24-2019', 'ACTIVO', '112.01', 526112000, 'Otros estímulos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526113000, 'SAT/24-2019', 'ACTIVO', '113', 526100010, 'Impuestos a favor', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526113010, 'SAT/24-2019', 'ACTIVO', '113.01', 526113000, 'IVA a favor', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526113020, 'SAT/24-2019', 'ACTIVO', '113.02', 526113000, 'ISR a favor', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526113030, 'SAT/24-2019', 'ACTIVO', '113.03', 526113000, 'IETU a favor', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526113040, 'SAT/24-2019', 'ACTIVO', '113.04', 526113000, 'IDE a favor', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526113050, 'SAT/24-2019', 'ACTIVO', '113.05', 526113000, 'IA a favor', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526113060, 'SAT/24-2019', 'ACTIVO', '113.06', 526113000, 'Subsidio al empleo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526113070, 'SAT/24-2019', 'ACTIVO', '113.07', 526113000, 'Pago de lo indebido', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526113080, 'SAT/24-2019', 'ACTIVO', '113.08', 526113000, 'Otros impuestos a favor', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526114000, 'SAT/24-2019', 'ACTIVO', '114', 526100010, 'Pagos provisionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526114010, 'SAT/24-2019', 'ACTIVO', '114.01', 526114000, 'Pagos provisionales de ISR', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526115000, 'SAT/24-2019', 'ACTIVO', '115', 526100010, 'Inventario', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526115010, 'SAT/24-2019', 'ACTIVO', '115.01', 526115000, 'Inventario', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526115020, 'SAT/24-2019', 'ACTIVO', '115.02', 526115000, 'Materia prima y materiales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526115030, 'SAT/24-2019', 'ACTIVO', '115.03', 526115000, 'Producción en proceso', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526115040, 'SAT/24-2019', 'ACTIVO', '115.04', 526115000, 'Productos terminados', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526115050, 'SAT/24-2019', 'ACTIVO', '115.05', 526115000, 'Mercancías en tránsito', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526115060, 'SAT/24-2019', 'ACTIVO', '115.06', 526115000, 'Mercancías en poder de terceros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526115070, 'SAT/24-2019', 'ACTIVO', '115.07', 526115000, 'Otros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526116000, 'SAT/24-2019', 'ACTIVO', '116', 526100010, 'Estimación de inventarios obsoletos y de lento movimiento', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526116010, 'SAT/24-2019', 'ACTIVO', '116.01', 526116000, 'Estimación de inventarios obsoletos y de lento movimiento', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526117000, 'SAT/24-2019', 'ACTIVO', '117', 526100010, 'Obras en proceso de inmuebles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526117010, 'SAT/24-2019', 'ACTIVO', '117.01', 526117000, 'Obras en proceso de inmuebles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526118000, 'SAT/24-2019', 'ACTIVO', '118', 526100010, 'Impuestos acreditables pagados', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526118010, 'SAT/24-2019', 'ACTIVO', '118.01', 526118000, 'IVA acreditable pagado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526118020, 'SAT/24-2019', 'ACTIVO', '118.02', 526118000, 'IVA acreditable de importación pagado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526118030, 'SAT/24-2019', 'ACTIVO', '118.03', 526118000, 'IEPS acreditable pagado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526118040, 'SAT/24-2019', 'ACTIVO', '118.04', 526118000, 'IEPS pagado en importación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526119000, 'SAT/24-2019', 'ACTIVO', '119', 526100010, 'Impuestos acreditables por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526119010, 'SAT/24-2019', 'ACTIVO', '119.01', 526119000, 'IVA pendiente de pago', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526119020, 'SAT/24-2019', 'ACTIVO', '119.02', 526119000, 'IVA de importación pendiente de pago', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526119030, 'SAT/24-2019', 'ACTIVO', '119.03', 526119000, 'IEPS pendiente de pago', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526119040, 'SAT/24-2019', 'ACTIVO', '119.04', 526119000, 'IEPS pendiente de pago en importación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526120000, 'SAT/24-2019', 'ACTIVO', '120', 526100010, 'Anticipo a proveedores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526120010, 'SAT/24-2019', 'ACTIVO', '120.01', 526120000, 'Anticipo a proveedores nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526120020, 'SAT/24-2019', 'ACTIVO', '120.02', 526120000, 'Anticipo a proveedores extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526120030, 'SAT/24-2019', 'ACTIVO', '120.03', 526120000, 'Anticipo a proveedores nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526120040, 'SAT/24-2019', 'ACTIVO', '120.04', 526120000, 'Anticipo a proveedores extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526121000, 'SAT/24-2019', 'ACTIVO', '121', 526100010, 'Otros activos a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526121010, 'SAT/24-2019', 'ACTIVO', '121.01', 526121000, 'Otros activos a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526100020, 'SAT/24-2019', 'ACTIVO', '100.02', 526100000, 'Activo a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526151000, 'SAT/24-2019', 'ACTIVO', '151', 526100020, 'Terrenos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526151010, 'SAT/24-2019', 'ACTIVO', '151.01', 526151000, 'Terrenos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526152600, 'SAT/24-2019', 'ACTIVO', '152', 526100020, 'Edificios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526152610, 'SAT/24-2019', 'ACTIVO', '152.01', 526152600, 'Edificios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526153000, 'SAT/24-2019', 'ACTIVO', '153', 526100020, 'Maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526153010, 'SAT/24-2019', 'ACTIVO', '153.01', 526153000, 'Maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526154000, 'SAT/24-2019', 'ACTIVO', '154', 526100020, 'Automóviles, autobuses, camiones de carga, tractocamiones, montacargas y remolques', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526154010, 'SAT/24-2019', 'ACTIVO', '154.01', 526154000, 'Automóviles, autobuses, camiones de carga, tractocamiones, montacargas y remolques', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526155000, 'SAT/24-2019', 'ACTIVO', '155', 526100020, 'Mobiliario y equipo de oficina', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526155010, 'SAT/24-2019', 'ACTIVO', '155.01', 526155000, 'Mobiliario y equipo de oficina', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526156000, 'SAT/24-2019', 'ACTIVO', '156', 526100020, 'Equipo de cómputo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526156010, 'SAT/24-2019', 'ACTIVO', '156.01', 526156000, 'Equipo de cómputo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526157000, 'SAT/24-2019', 'ACTIVO', '157', 526100020, 'Equipo de comunicación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526157010, 'SAT/24-2019', 'ACTIVO', '157.01', 526157000, 'Equipo de comunicación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526158000, 'SAT/24-2019', 'ACTIVO', '158', 526100020, 'Activos biológicos, vegetales y semovientes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526158010, 'SAT/24-2019', 'ACTIVO', '158.01', 526158000, 'Activos biológicos, vegetales y semovientes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526159000, 'SAT/24-2019', 'ACTIVO', '159', 526100020, 'Obras en proceso de activos fijos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526159010, 'SAT/24-2019', 'ACTIVO', '159.01', 526159000, 'Obras en proceso de activos fijos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526160000, 'SAT/24-2019', 'ACTIVO', '160', 526100020, 'Otros activos fijos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526160010, 'SAT/24-2019', 'ACTIVO', '160.01', 526160000, 'Otros activos fijos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526161000, 'SAT/24-2019', 'ACTIVO', '161', 526100020, 'Ferrocarriles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526161010, 'SAT/24-2019', 'ACTIVO', '161.01', 526161000, 'Ferrocarriles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526162000, 'SAT/24-2019', 'ACTIVO', '162', 526100020, 'Embarcaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526162010, 'SAT/24-2019', 'ACTIVO', '162.01', 526162000, 'Embarcaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526163000, 'SAT/24-2019', 'ACTIVO', '163', 526100020, 'Aviones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526163010, 'SAT/24-2019', 'ACTIVO', '163.01', 526163000, 'Aviones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526164000, 'SAT/24-2019', 'ACTIVO', '164', 526100020, 'Troqueles, moldes, matrices y herramental', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526164010, 'SAT/24-2019', 'ACTIVO', '164.01', 526164000, 'Troqueles, moldes, matrices y herramental', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526165000, 'SAT/24-2019', 'ACTIVO', '165', 526100020, 'Equipo de comunicaciones telefónicas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526165010, 'SAT/24-2019', 'ACTIVO', '165.01', 526165000, 'Equipo de comunicaciones telefónicas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526166000, 'SAT/24-2019', 'ACTIVO', '166', 526100020, 'Equipo de comunicación satelital', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526166010, 'SAT/24-2019', 'ACTIVO', '166.01', 526166000, 'Equipo de comunicación satelital', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526167000, 'SAT/24-2019', 'ACTIVO', '167', 526100020, 'Equipo de adaptaciones para personas con capacidades diferentes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526167010, 'SAT/24-2019', 'ACTIVO', '167.01', 526167000, 'Equipo de adaptaciones para personas con capacidades diferentes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526168000, 'SAT/24-2019', 'ACTIVO', '168', 526100020, 'Maquinaria y equipo de generación de energía de fuentes renovables o de sistemas de cogeneración de electricidad eficiente', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526168010, 'SAT/24-2019', 'ACTIVO', '168.01', 526168000, 'Maquinaria y equipo de generación de energía de fuentes renovables o de sistemas de cogeneración de electricidad eficiente', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526169000, 'SAT/24-2019', 'ACTIVO', '169', 526100020, 'Otra maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526169010, 'SAT/24-2019', 'ACTIVO', '169.01', 526169000, 'Otra maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526170000, 'SAT/24-2019', 'ACTIVO', '170', 526100020, 'Adaptaciones y mejoras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526170010, 'SAT/24-2019', 'ACTIVO', '170.01', 526170000, 'Adaptaciones y mejoras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171000, 'SAT/24-2019', 'ACTIVO', '171', 526100020, 'Depreciación acumulada de activos fijos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171010, 'SAT/24-2019', 'ACTIVO', '171.01', 526171000, 'Depreciación acumulada de edificios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171020, 'SAT/24-2019', 'ACTIVO', '171.02', 526171000, 'Depreciación acumulada de maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171030, 'SAT/24-2019', 'ACTIVO', '171.03', 526171000, 'Depreciación acumulada de automóviles, autobuses, camiones de carga, tractocamiones, montacargas y remolques', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171040, 'SAT/24-2019', 'ACTIVO', '171.04', 526171000, 'Depreciación acumulada de mobiliario y equipo de oficina', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171050, 'SAT/24-2019', 'ACTIVO', '171.05', 526171000, 'Depreciación acumulada de equipo de cómputo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171060, 'SAT/24-2019', 'ACTIVO', '171.06', 526171000, 'Depreciación acumulada de equipo de comunicación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171070, 'SAT/24-2019', 'ACTIVO', '171.07', 526171000, 'Depreciación acumulada de activos biológicos, vegetales y semovientes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171080, 'SAT/24-2019', 'ACTIVO', '171.08', 526171000, 'Depreciación acumulada de otros activos fijos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171090, 'SAT/24-2019', 'ACTIVO', '171.09', 526171000, 'Depreciación acumulada de ferrocarriles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171100, 'SAT/24-2019', 'ACTIVO', '171.1', 526171000, 'Depreciación acumulada de embarcaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171110, 'SAT/24-2019', 'ACTIVO', '171.11', 526171000, 'Depreciación acumulada de aviones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171120, 'SAT/24-2019', 'ACTIVO', '171.12', 526171000, 'Depreciación acumulada de troqueles, moldes, matrices y herramental', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171130, 'SAT/24-2019', 'ACTIVO', '171.13', 526171000, 'Depreciación acumulada de equipo de comunicaciones telefónicas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171140, 'SAT/24-2019', 'ACTIVO', '171.14', 526171000, 'Depreciación acumulada de equipo de comunicación satelital', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171150, 'SAT/24-2019', 'ACTIVO', '171.15', 526171000, 'Depreciación acumulada de equipo de adaptaciones para personas con capacidades diferentes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171160, 'SAT/24-2019', 'ACTIVO', '171.16', 526171000, 'Depreciación acumulada de maquinaria y equipo de generación de energía de fuentes renovables o de sistemas de cogeneración de electricidad eficiente', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171170, 'SAT/24-2019', 'ACTIVO', '171.17', 526171000, 'Depreciación acumulada de adaptaciones y mejoras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526171180, 'SAT/24-2019', 'ACTIVO', '171.18', 526171000, 'Depreciación acumulada de otra maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172000, 'SAT/24-2019', 'ACTIVO', '172', 526100020, 'Pérdida por deterioro acumulado de activos fijos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172010, 'SAT/24-2019', 'ACTIVO', '172.01', 526172000, 'Pérdida por deterioro acumulado de edificios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172020, 'SAT/24-2019', 'ACTIVO', '172.02', 526172000, 'Pérdida por deterioro acumulado de maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172030, 'SAT/24-2019', 'ACTIVO', '172.03', 526172000, 'Pérdida por deterioro acumulado de automóviles, autobuses, camiones de carga, tractocamiones, montacargas y remolques', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172040, 'SAT/24-2019', 'ACTIVO', '172.04', 526172000, 'Pérdida por deterioro acumulado de mobiliario y equipo de oficina', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172050, 'SAT/24-2019', 'ACTIVO', '172.05', 526172000, 'Pérdida por deterioro acumulado de equipo de cómputo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172060, 'SAT/24-2019', 'ACTIVO', '172.06', 526172000, 'Pérdida por deterioro acumulado de equipo de comunicación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172070, 'SAT/24-2019', 'ACTIVO', '172.07', 526172000, 'Pérdida por deterioro acumulado de activos biológicos, vegetales y semovientes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172080, 'SAT/24-2019', 'ACTIVO', '172.08', 526172000, 'Pérdida por deterioro acumulado de otros activos fijos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172090, 'SAT/24-2019', 'ACTIVO', '172.09', 526172000, 'Pérdida por deterioro acumulado de ferrocarriles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172100, 'SAT/24-2019', 'ACTIVO', '172.1', 526172000, 'Pérdida por deterioro acumulado de embarcaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172110, 'SAT/24-2019', 'ACTIVO', '172.11', 526172000, 'Pérdida por deterioro acumulado de aviones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172120, 'SAT/24-2019', 'ACTIVO', '172.12', 526172000, 'Pérdida por deterioro acumulado de troqueles, moldes, matrices y herramental', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172130, 'SAT/24-2019', 'ACTIVO', '172.13', 526172000, 'Pérdida por deterioro acumulado de equipo de comunicaciones telefónicas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172140, 'SAT/24-2019', 'ACTIVO', '172.14', 526172000, 'Pérdida por deterioro acumulado de equipo de comunicación satelital', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172150, 'SAT/24-2019', 'ACTIVO', '172.15', 526172000, 'Pérdida por deterioro acumulado de equipo de adaptaciones para personas con capacidades diferentes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172160, 'SAT/24-2019', 'ACTIVO', '172.16', 526172000, 'Pérdida por deterioro acumulado de maquinaria y equipo de generación de energía de fuentes renovables o de sistemas de cogeneración de electricidad eficiente', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172170, 'SAT/24-2019', 'ACTIVO', '172.17', 526172000, 'Pérdida por deterioro acumulado de adaptaciones y mejoras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526172180, 'SAT/24-2019', 'ACTIVO', '172.18', 526172000, 'Pérdida por deterioro acumulado de otra maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526173000, 'SAT/24-2019', 'ACTIVO', '173', 526100020, 'Gastos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526173010, 'SAT/24-2019', 'ACTIVO', '173.01', 526173000, 'Gastos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526174000, 'SAT/24-2019', 'ACTIVO', '174', 526100020, 'Gastos pre operativos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526174010, 'SAT/24-2019', 'ACTIVO', '174.01', 526174000, 'Gastos pre operativos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526175000, 'SAT/24-2019', 'ACTIVO', '175', 526100020, 'Regalías, asistencia técnica y otros gastos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526175010, 'SAT/24-2019', 'ACTIVO', '175.01', 526175000, 'Regalías, asistencia técnica y otros gastos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526176000, 'SAT/24-2019', 'ACTIVO', '176', 526100020, 'Activos intangibles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526176010, 'SAT/24-2019', 'ACTIVO', '176.01', 526176000, 'Activos intangibles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526177000, 'SAT/24-2019', 'ACTIVO', '177', 526100020, 'Gastos de organización', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526177010, 'SAT/24-2019', 'ACTIVO', '177.01', 526177000, 'Gastos de organización', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526178000, 'SAT/24-2019', 'ACTIVO', '178', 526100020, 'Investigación y desarrollo de mercado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526178010, 'SAT/24-2019', 'ACTIVO', '178.01', 526178000, 'Investigación y desarrollo de mercado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526179000, 'SAT/24-2019', 'ACTIVO', '179', 526100020, 'Marcas y patentes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526179010, 'SAT/24-2019', 'ACTIVO', '179.01', 526179000, 'Marcas y patentes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526180000, 'SAT/24-2019', 'ACTIVO', '180', 526100020, 'Crédito mercantil', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526180010, 'SAT/24-2019', 'ACTIVO', '180.01', 526180000, 'Crédito mercantil', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526181000, 'SAT/24-2019', 'ACTIVO', '181', 526100020, 'Gastos de instalación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526181010, 'SAT/24-2019', 'ACTIVO', '181.01', 526181000, 'Gastos de instalación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526182000, 'SAT/24-2019', 'ACTIVO', '182', 526100020, 'Otros activos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526182010, 'SAT/24-2019', 'ACTIVO', '182.01', 526182000, 'Otros activos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526183000, 'SAT/24-2019', 'ACTIVO', '183', 526100020, 'Amortización acumulada de activos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526183010, 'SAT/24-2019', 'ACTIVO', '183.01', 526183000, 'Amortización acumulada de gastos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526183020, 'SAT/24-2019', 'ACTIVO', '183.02', 526183000, 'Amortización acumulada de gastos pre operativos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526183030, 'SAT/24-2019', 'ACTIVO', '183.03', 526183000, 'Amortización acumulada de regalías, asistencia técnica y otros gastos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526183040, 'SAT/24-2019', 'ACTIVO', '183.04', 526183000, 'Amortización acumulada de activos intangibles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526183050, 'SAT/24-2019', 'ACTIVO', '183.05', 526183000, 'Amortización acumulada de gastos de organización', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526183060, 'SAT/24-2019', 'ACTIVO', '183.06', 526183000, 'Amortización acumulada de investigación y desarrollo de mercado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526183070, 'SAT/24-2019', 'ACTIVO', '183.07', 526183000, 'Amortización acumulada de marcas y patentes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526183080, 'SAT/24-2019', 'ACTIVO', '183.08', 526183000, 'Amortización acumulada de crédito mercantil', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526183090, 'SAT/24-2019', 'ACTIVO', '183.09', 526183000, 'Amortización acumulada de gastos de instalación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526183100, 'SAT/24-2019', 'ACTIVO', '183.1', 526183000, 'Amortización acumulada de otros activos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526184000, 'SAT/24-2019', 'ACTIVO', '184', 526100020, 'Depósitos en garantía', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526184010, 'SAT/24-2019', 'ACTIVO', '184.01', 526184000, 'Depósitos de fianzas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526184020, 'SAT/24-2019', 'ACTIVO', '184.02', 526184000, 'Depósitos de arrendamiento de bienes inmuebles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526184030, 'SAT/24-2019', 'ACTIVO', '184.03', 526184000, 'Otros depósitos en garantía', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526185000, 'SAT/24-2019', 'ACTIVO', '185', 526100020, 'Impuestos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526185010, 'SAT/24-2019', 'ACTIVO', '185.01', 526185000, 'Impuestos diferidos ISR', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526186000, 'SAT/24-2019', 'ACTIVO', '186', 526100020, 'Cuentas y documentos por cobrar a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526186010, 'SAT/24-2019', 'ACTIVO', '186.01', 526186000, 'Cuentas y documentos por cobrar a largo plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526186020, 'SAT/24-2019', 'ACTIVO', '186.02', 526186000, 'Cuentas y documentos por cobrar a largo plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526186030, 'SAT/24-2019', 'ACTIVO', '186.03', 526186000, 'Cuentas y documentos por cobrar a largo plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526186040, 'SAT/24-2019', 'ACTIVO', '186.04', 526186000, 'Cuentas y documentos por cobrar a largo plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526186050, 'SAT/24-2019', 'ACTIVO', '186.05', 526186000, 'Intereses por cobrar a largo plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526186060, 'SAT/24-2019', 'ACTIVO', '186.06', 526186000, 'Intereses por cobrar a largo plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526186070, 'SAT/24-2019', 'ACTIVO', '186.07', 526186000, 'Intereses por cobrar a largo plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526186080, 'SAT/24-2019', 'ACTIVO', '186.08', 526186000, 'Intereses por cobrar a largo plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526186090, 'SAT/24-2019', 'ACTIVO', '186.09', 526186000, 'Otras cuentas y documentos por cobrar a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526186100, 'SAT/24-2019', 'ACTIVO', '186.1', 526186000, 'Otras cuentas y documentos por cobrar a largo plazo parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526187000, 'SAT/24-2019', 'ACTIVO', '187', 526100020, 'Participación de los trabajadores en las utilidades diferidas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526187010, 'SAT/24-2019', 'ACTIVO', '187.01', 526187000, 'Participación de los trabajadores en las utilidades diferidas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526188000, 'SAT/24-2019', 'ACTIVO', '188', 526100020, 'Inversiones permanentes en acciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526188010, 'SAT/24-2019', 'ACTIVO', '188.01', 526188000, 'Inversiones a largo plazo en subsidiarias', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526188020, 'SAT/24-2019', 'ACTIVO', '188.02', 526188000, 'Inversiones a largo plazo en asociadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526188030, 'SAT/24-2019', 'ACTIVO', '188.03', 526188000, 'Otras inversiones permanentes en acciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526189000, 'SAT/24-2019', 'ACTIVO', '189', 526100020, 'Estimación por deterioro de inversiones permanentes en acciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526189010, 'SAT/24-2019', 'ACTIVO', '189.01', 526189000, 'Estimación por deterioro de inversiones permanentes en acciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526190000, 'SAT/24-2019', 'ACTIVO', '190', 526100020, 'Otros instrumentos financieros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526190010, 'SAT/24-2019', 'ACTIVO', '190.01', 526190000, 'Otros instrumentos financieros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526191000, 'SAT/24-2019', 'ACTIVO', '191', 526100020, 'Otros activos a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526191010, 'SAT/24-2019', 'ACTIVO', '191.01', 526191000, 'Otros activos a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526200000, 'SAT/24-2019', 'PASIVO', '200', 0, 'Pasivo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526200010, 'SAT/24-2019', 'PASIVO', '200.01', 526200000, 'Pasivo a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526201000, 'SAT/24-2019', 'PASIVO', '201', 526200010, 'Proveedores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526201010, 'SAT/24-2019', 'PASIVO', '201.01', 526201000, 'Proveedores nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526201020, 'SAT/24-2019', 'PASIVO', '201.02', 526201000, 'Proveedores extranjeros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526201030, 'SAT/24-2019', 'PASIVO', '201.03', 526201000, 'Proveedores nacionales parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526201040, 'SAT/24-2019', 'PASIVO', '201.04', 526201000, 'Proveedores extranjeros parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202000, 'SAT/24-2019', 'PASIVO', '202', 526200010, 'Cuentas por pagar a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202010, 'SAT/24-2019', 'PASIVO', '202.01', 526202000, 'Documentos por pagar bancario y financiero nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202020, 'SAT/24-2019', 'PASIVO', '202.02', 526202000, 'Documentos por pagar bancario y financiero extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202030, 'SAT/24-2019', 'PASIVO', '202.03', 526202000, 'Documentos y cuentas por pagar a corto plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202040, 'SAT/24-2019', 'PASIVO', '202.04', 526202000, 'Documentos y cuentas por pagar a corto plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202050, 'SAT/24-2019', 'PASIVO', '202.05', 526202000, 'Documentos y cuentas por pagar a corto plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202060, 'SAT/24-2019', 'PASIVO', '202.06', 526202000, 'Documentos y cuentas por pagar a corto plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202070, 'SAT/24-2019', 'PASIVO', '202.07', 526202000, 'Intereses por pagar a corto plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202080, 'SAT/24-2019', 'PASIVO', '202.08', 526202000, 'Intereses por pagar a corto plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202090, 'SAT/24-2019', 'PASIVO', '202.09', 526202000, 'Intereses por pagar a corto plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202100, 'SAT/24-2019', 'PASIVO', '202.1', 526202000, 'Intereses por pagar a corto plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202110, 'SAT/24-2019', 'PASIVO', '202.11', 526202000, 'Dividendo por pagar nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526202120, 'SAT/24-2019', 'PASIVO', '202.12', 526202000, 'Dividendo por pagar extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203000, 'SAT/24-2019', 'PASIVO', '203', 526200010, 'Cobros anticipados a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203010, 'SAT/24-2019', 'PASIVO', '203.01', 526203000, 'Rentas cobradas por anticipado a corto plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203020, 'SAT/24-2019', 'PASIVO', '203.02', 526203000, 'Rentas cobradas por anticipado a corto plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203030, 'SAT/24-2019', 'PASIVO', '203.03', 526203000, 'Rentas cobradas por anticipado a corto plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203040, 'SAT/24-2019', 'PASIVO', '203.04', 526203000, 'Rentas cobradas por anticipado a corto plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203050, 'SAT/24-2019', 'PASIVO', '203.05', 526203000, 'Intereses cobrados por anticipado a corto plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203060, 'SAT/24-2019', 'PASIVO', '203.06', 526203000, 'Intereses cobrados por anticipado a corto plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203070, 'SAT/24-2019', 'PASIVO', '203.07', 526203000, 'Intereses cobrados por anticipado a corto plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203080, 'SAT/24-2019', 'PASIVO', '203.08', 526203000, 'Intereses cobrados por anticipado a corto plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203090, 'SAT/24-2019', 'PASIVO', '203.09', 526203000, 'Factoraje financiero cobrados por anticipado a corto plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203100, 'SAT/24-2019', 'PASIVO', '203.1', 526203000, 'Factoraje financiero cobrados por anticipado a corto plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203110, 'SAT/24-2019', 'PASIVO', '203.11', 526203000, 'Factoraje financiero cobrados por anticipado a corto plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203120, 'SAT/24-2019', 'PASIVO', '203.12', 526203000, 'Factoraje financiero cobrados por anticipado a corto plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203130, 'SAT/24-2019', 'PASIVO', '203.13', 526203000, 'Arrendamiento financiero cobrados por anticipado a corto plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203140, 'SAT/24-2019', 'PASIVO', '203.14', 526203000, 'Arrendamiento financiero cobrados por anticipado a corto plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203150, 'SAT/24-2019', 'PASIVO', '203.15', 526203000, 'Arrendamiento financiero cobrados por anticipado a corto plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203160, 'SAT/24-2019', 'PASIVO', '203.16', 526203000, 'Arrendamiento financiero cobrados por anticipado a corto plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203170, 'SAT/24-2019', 'PASIVO', '203.17', 526203000, 'Derechos fiduciarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526203180, 'SAT/24-2019', 'PASIVO', '203.18', 526203000, 'Otros cobros anticipados', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526204000, 'SAT/24-2019', 'PASIVO', '204', 526200010, 'Instrumentos financieros a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526204010, 'SAT/24-2019', 'PASIVO', '204.01', 526204000, 'Instrumentos financieros a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526205000, 'SAT/24-2019', 'PASIVO', '205', 526200010, 'Acreedores diversos a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526205010, 'SAT/24-2019', 'PASIVO', '205.01', 526205000, 'Socios, accionistas o representante legal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526205020, 'SAT/24-2019', 'PASIVO', '205.02', 526205000, 'Acreedores diversos a corto plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526205030, 'SAT/24-2019', 'PASIVO', '205.03', 526205000, 'Acreedores diversos a corto plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526205040, 'SAT/24-2019', 'PASIVO', '205.04', 526205000, 'Acreedores diversos a corto plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526205050, 'SAT/24-2019', 'PASIVO', '205.05', 526205000, 'Acreedores diversos a corto plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526205060, 'SAT/24-2019', 'PASIVO', '205.06', 526205000, 'Otros acreedores diversos a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526206000, 'SAT/24-2019', 'PASIVO', '206', 526200010, 'Anticipo de cliente', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526206010, 'SAT/24-2019', 'PASIVO', '206.01', 526206000, 'Anticipo de cliente nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526206020, 'SAT/24-2019', 'PASIVO', '206.02', 526206000, 'Anticipo de cliente extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526206030, 'SAT/24-2019', 'PASIVO', '206.03', 526206000, 'Anticipo de cliente nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526206040, 'SAT/24-2019', 'PASIVO', '206.04', 526206000, 'Anticipo de cliente extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526206050, 'SAT/24-2019', 'PASIVO', '206.05', 526206000, 'Otros anticipos de clientes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526207000, 'SAT/24-2019', 'PASIVO', '207', 526200010, 'Impuestos trasladados', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526207010, 'SAT/24-2019', 'PASIVO', '207.01', 526207000, 'IVA trasladado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526207020, 'SAT/24-2019', 'PASIVO', '207.02', 526207000, 'IEPS trasladado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526208000, 'SAT/24-2019', 'PASIVO', '208', 526200010, 'Impuestos trasladados cobrados', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526208010, 'SAT/24-2019', 'PASIVO', '208.01', 526208000, 'IVA trasladado cobrado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526208020, 'SAT/24-2019', 'PASIVO', '208.02', 526208000, 'IEPS trasladado cobrado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526209000, 'SAT/24-2019', 'PASIVO', '209', 526200010, 'Impuestos trasladados no cobrados', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526209010, 'SAT/24-2019', 'PASIVO', '209.01', 526209000, 'IVA trasladado no cobrado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526209020, 'SAT/24-2019', 'PASIVO', '209.02', 526209000, 'IEPS trasladado no cobrado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526210000, 'SAT/24-2019', 'PASIVO', '210', 526200010, 'Provisión de sueldos y salarios por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526210010, 'SAT/24-2019', 'PASIVO', '210.01', 526210000, 'Provisión de sueldos y salarios por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526210020, 'SAT/24-2019', 'PASIVO', '210.02', 526210000, 'Provisión de vacaciones por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526210030, 'SAT/24-2019', 'PASIVO', '210.03', 526210000, 'Provisión de aguinaldo por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526210040, 'SAT/24-2019', 'PASIVO', '210.04', 526210000, 'Provisión de fondo de ahorro por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526210050, 'SAT/24-2019', 'PASIVO', '210.05', 526210000, 'Provisión de asimilados a salarios por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526210060, 'SAT/24-2019', 'PASIVO', '210.06', 526210000, 'Provisión de anticipos o remanentes por distribuir', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526210070, 'SAT/24-2019', 'PASIVO', '210.07', 526210000, 'Provisión de otros sueldos y salarios por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526211000, 'SAT/24-2019', 'PASIVO', '211', 526200010, 'Provisión de contribuciones de seguridad social por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526211010, 'SAT/24-2019', 'PASIVO', '211.01', 526211000, 'Provisión de IMSS patronal por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526211020, 'SAT/24-2019', 'PASIVO', '211.02', 526211000, 'Provisión de SAR por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526211030, 'SAT/24-2019', 'PASIVO', '211.03', 526211000, 'Provisión de infonavit por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526212000, 'SAT/24-2019', 'PASIVO', '212', 526200010, 'Provisión de impuesto estatal sobre nómina por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526212010, 'SAT/24-2019', 'PASIVO', '212.01', 526212000, 'Provisión de impuesto estatal sobre nómina por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526213000, 'SAT/24-2019', 'PASIVO', '213', 526200010, 'Impuestos y derechos por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526213010, 'SAT/24-2019', 'PASIVO', '213.01', 526213000, 'IVA por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526213020, 'SAT/24-2019', 'PASIVO', '213.02', 526213000, 'IEPS por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526213030, 'SAT/24-2019', 'PASIVO', '213.03', 526213000, 'ISR por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526213040, 'SAT/24-2019', 'PASIVO', '213.04', 526213000, 'Impuesto estatal sobre nómina por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526213050, 'SAT/24-2019', 'PASIVO', '213.05', 526213000, 'Impuesto estatal y municipal por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526213060, 'SAT/24-2019', 'PASIVO', '213.06', 526213000, 'Derechos por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526213070, 'SAT/24-2019', 'PASIVO', '213.07', 526213000, 'Otros impuestos por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526214000, 'SAT/24-2019', 'PASIVO', '214', 526200010, 'Dividendos por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526214010, 'SAT/24-2019', 'PASIVO', '214.01', 526214000, 'Dividendos por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526215000, 'SAT/24-2019', 'PASIVO', '215', 526200010, 'PTU por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526215010, 'SAT/24-2019', 'PASIVO', '215.01', 526215000, 'PTU por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526215020, 'SAT/24-2019', 'PASIVO', '215.02', 526215000, 'PTU por pagar de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526215030, 'SAT/24-2019', 'PASIVO', '215.03', 526215000, 'Provisión de PTU por pagar', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216000, 'SAT/24-2019', 'PASIVO', '216', 526200010, 'Impuestos retenidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216010, 'SAT/24-2019', 'PASIVO', '216.01', 526216000, 'Impuestos retenidos de ISR por sueldos y salarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216020, 'SAT/24-2019', 'PASIVO', '216.02', 526216000, 'Impuestos retenidos de ISR por asimilados a salarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216030, 'SAT/24-2019', 'PASIVO', '216.03', 526216000, 'Impuestos retenidos de ISR por arrendamiento', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216040, 'SAT/24-2019', 'PASIVO', '216.04', 526216000, 'Impuestos retenidos de ISR por servicios profesionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216050, 'SAT/24-2019', 'PASIVO', '216.05', 526216000, 'Impuestos retenidos de ISR por dividendos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216060, 'SAT/24-2019', 'PASIVO', '216.06', 526216000, 'Impuestos retenidos de ISR por intereses', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216070, 'SAT/24-2019', 'PASIVO', '216.07', 526216000, 'Impuestos retenidos de ISR por pagos al extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216080, 'SAT/24-2019', 'PASIVO', '216.08', 526216000, 'Impuestos retenidos de ISR por venta de acciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216090, 'SAT/24-2019', 'PASIVO', '216.09', 526216000, 'Impuestos retenidos de ISR por venta de partes sociales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216100, 'SAT/24-2019', 'PASIVO', '216.1', 526216000, 'Impuestos retenidos de IVA', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216110, 'SAT/24-2019', 'PASIVO', '216.11', 526216000, 'Retenciones de IMSS a los trabajadores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526216120, 'SAT/24-2019', 'PASIVO', '216.12', 526216000, 'Otras impuestos retenidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526217000, 'SAT/24-2019', 'PASIVO', '217', 526200010, 'Pagos realizados por cuenta de terceros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526217010, 'SAT/24-2019', 'PASIVO', '217.01', 526217000, 'Pagos realizados por cuenta de terceros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526218000, 'SAT/24-2019', 'PASIVO', '218', 526200010, 'Otros pasivos a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526218010, 'SAT/24-2019', 'PASIVO', '218.01', 526218000, 'Otros pasivos a corto plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526200020, 'SAT/24-2019', 'PASIVO', '200.02', 526200000, 'Pasivo a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526251000, 'SAT/24-2019', 'PASIVO', '251', 526200020, 'Acreedores diversos a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526251010, 'SAT/24-2019', 'PASIVO', '251.01', 526251000, 'Socios, accionistas o representante legal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526251020, 'SAT/24-2019', 'PASIVO', '251.02', 526251000, 'Acreedores diversos a largo plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526251030, 'SAT/24-2019', 'PASIVO', '251.03', 526251000, 'Acreedores diversos a largo plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526251040, 'SAT/24-2019', 'PASIVO', '251.04', 526251000, 'Acreedores diversos a largo plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526251050, 'SAT/24-2019', 'PASIVO', '251.05', 526251000, 'Acreedores diversos a largo plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526251060, 'SAT/24-2019', 'PASIVO', '251.06', 526251000, 'Otros acreedores diversos a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252600, 'SAT/24-2019', 'PASIVO', '252', 526200020, 'Cuentas por pagar a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252610, 'SAT/24-2019', 'PASIVO', '252.01', 526252600, 'Documentos bancarios y financieros por pagar a largo plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252620, 'SAT/24-2019', 'PASIVO', '252.02', 526252600, 'Documentos bancarios y financieros por pagar a largo plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252630, 'SAT/24-2019', 'PASIVO', '252.03', 526252600, 'Documentos y cuentas por pagar a largo plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252640, 'SAT/24-2019', 'PASIVO', '252.04', 526252600, 'Documentos y cuentas por pagar a largo plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252650, 'SAT/24-2019', 'PASIVO', '252.05', 526252600, 'Documentos y cuentas por pagar a largo plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252660, 'SAT/24-2019', 'PASIVO', '252.06', 526252600, 'Documentos y cuentas por pagar a largo plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252670, 'SAT/24-2019', 'PASIVO', '252.07', 526252600, 'Hipotecas por pagar a largo plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252680, 'SAT/24-2019', 'PASIVO', '252.08', 526252600, 'Hipotecas por pagar a largo plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252690, 'SAT/24-2019', 'PASIVO', '252.09', 526252600, 'Hipotecas por pagar a largo plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252100, 'SAT/24-2019', 'PASIVO', '252.1', 526252600, 'Hipotecas por pagar a largo plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252110, 'SAT/24-2019', 'PASIVO', '252.11', 526252600, 'Intereses por pagar a largo plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252120, 'SAT/24-2019', 'PASIVO', '252.12', 526252600, 'Intereses por pagar a largo plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252130, 'SAT/24-2019', 'PASIVO', '252.13', 526252600, 'Intereses por pagar a largo plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252140, 'SAT/24-2019', 'PASIVO', '252.14', 526252600, 'Intereses por pagar a largo plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252150, 'SAT/24-2019', 'PASIVO', '252.15', 526252600, 'Dividendos por pagar nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252160, 'SAT/24-2019', 'PASIVO', '252.16', 526252600, 'Dividendos por pagar extranjeros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526252170, 'SAT/24-2019', 'PASIVO', '252.17', 526252600, 'Otras cuentas y documentos por pagar a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253000, 'SAT/24-2019', 'PASIVO', '253', 526200020, 'Cobros anticipados a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253010, 'SAT/24-2019', 'PASIVO', '253.01', 526253000, 'Rentas cobradas por anticipado a largo plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253020, 'SAT/24-2019', 'PASIVO', '253.02', 526253000, 'Rentas cobradas por anticipado a largo plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253030, 'SAT/24-2019', 'PASIVO', '253.03', 526253000, 'Rentas cobradas por anticipado a largo plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253040, 'SAT/24-2019', 'PASIVO', '253.04', 526253000, 'Rentas cobradas por anticipado a largo plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253050, 'SAT/24-2019', 'PASIVO', '253.05', 526253000, 'Intereses cobrados por anticipado a largo plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253060, 'SAT/24-2019', 'PASIVO', '253.06', 526253000, 'Intereses cobrados por anticipado a largo plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253070, 'SAT/24-2019', 'PASIVO', '253.07', 526253000, 'Intereses cobrados por anticipado a largo plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253080, 'SAT/24-2019', 'PASIVO', '253.08', 526253000, 'Intereses cobrados por anticipado a largo plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253090, 'SAT/24-2019', 'PASIVO', '253.09', 526253000, 'Factoraje financiero cobrados por anticipado a largo plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253100, 'SAT/24-2019', 'PASIVO', '253.1', 526253000, 'Factoraje financiero cobrados por anticipado a largo plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253110, 'SAT/24-2019', 'PASIVO', '253.11', 526253000, 'Factoraje financiero cobrados por anticipado a largo plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253120, 'SAT/24-2019', 'PASIVO', '253.12', 526253000, 'Factoraje financiero cobrados por anticipado a largo plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253130, 'SAT/24-2019', 'PASIVO', '253.13', 526253000, 'Arrendamiento financiero cobrados por anticipado a largo plazo nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253140, 'SAT/24-2019', 'PASIVO', '253.14', 526253000, 'Arrendamiento financiero cobrados por anticipado a largo plazo extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253150, 'SAT/24-2019', 'PASIVO', '253.15', 526253000, 'Arrendamiento financiero cobrados por anticipado a largo plazo nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253160, 'SAT/24-2019', 'PASIVO', '253.16', 526253000, 'Arrendamiento financiero cobrados por anticipado a largo plazo extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253170, 'SAT/24-2019', 'PASIVO', '253.17', 526253000, 'Derechos fiduciarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526253180, 'SAT/24-2019', 'PASIVO', '253.18', 526253000, 'Otros cobros anticipados', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526254000, 'SAT/24-2019', 'PASIVO', '254', 526200020, 'Instrumentos financieros a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526254010, 'SAT/24-2019', 'PASIVO', '254.01', 526254000, 'Instrumentos financieros a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526255000, 'SAT/24-2019', 'PASIVO', '255', 526200020, 'Pasivos por beneficios a los empleados a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526255010, 'SAT/24-2019', 'PASIVO', '255.01', 526255000, 'Pasivos por beneficios a los empleados a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526256000, 'SAT/24-2019', 'PASIVO', '256', 526200020, 'Otros pasivos a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526256010, 'SAT/24-2019', 'PASIVO', '256.01', 526256000, 'Otros pasivos a largo plazo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526257000, 'SAT/24-2019', 'PASIVO', '257', 526200020, 'Participación de los trabajadores en las utilidades diferida', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526257010, 'SAT/24-2019', 'PASIVO', '257.01', 526257000, 'Participación de los trabajadores en las utilidades diferida', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526258000, 'SAT/24-2019', 'PASIVO', '258', 526200020, 'Obligaciones contraídas de fideicomisos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526258010, 'SAT/24-2019', 'PASIVO', '258.01', 526258000, 'Obligaciones contraídas de fideicomisos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526259000, 'SAT/24-2019', 'PASIVO', '259', 526200020, 'Impuestos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526259010, 'SAT/24-2019', 'PASIVO', '259.01', 526259000, 'ISR diferido', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526259020, 'SAT/24-2019', 'PASIVO', '259.02', 526259000, 'ISR por dividendo diferido', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526259030, 'SAT/24-2019', 'PASIVO', '259.03', 526259000, 'Otros impuestos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526260000, 'SAT/24-2019', 'PASIVO', '260', 526200020, 'Pasivos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526260010, 'SAT/24-2019', 'PASIVO', '260.01', 526260000, 'Pasivos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526300000, 'SAT/24-2019', 'CAPITAL', '300', 0, 'Capital contable', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526301000, 'SAT/24-2019', 'CAPITAL', '301', 526300000, 'Capital social', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526301010, 'SAT/24-2019', 'CAPITAL', '301.01', 526301000, 'Capital fijo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526301020, 'SAT/24-2019', 'CAPITAL', '301.02', 526301000, 'Capital variable', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526301030, 'SAT/24-2019', 'CAPITAL', '301.03', 526301000, 'Aportaciones para futuros aumentos de capital', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526301040, 'SAT/24-2019', 'CAPITAL', '301.04', 526301000, 'Prima en suscripción de acciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526301050, 'SAT/24-2019', 'CAPITAL', '301.05', 526301000, 'Prima en suscripción de partes sociales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526302000, 'SAT/24-2019', 'CAPITAL', '302', 526300000, 'Patrimonio', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526302010, 'SAT/24-2019', 'CAPITAL', '302.01', 526302000, 'Patrimonio', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526302020, 'SAT/24-2019', 'CAPITAL', '302.02', 526302000, 'Aportación patrimonial', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526302030, 'SAT/24-2019', 'CAPITAL', '302.03', 526302000, 'Déficit o remanente del ejercicio', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526303000, 'SAT/24-2019', 'CAPITAL', '303', 526300000, 'Reserva legal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526303010, 'SAT/24-2019', 'CAPITAL', '303.01', 526303000, 'Reserva legal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526304000, 'SAT/24-2019', 'CAPITAL', '304', 526300000, 'Resultado de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526304010, 'SAT/24-2019', 'CAPITAL', '304.01', 526304000, 'Utilidad de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526304020, 'SAT/24-2019', 'CAPITAL', '304.02', 526304000, 'Pérdida de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526304030, 'SAT/24-2019', 'CAPITAL', '304.03', 526304000, 'Resultado integral de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526304040, 'SAT/24-2019', 'CAPITAL', '304.04', 526304000, 'Déficit o remanente de ejercicio anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526305000, 'SAT/24-2019', 'CAPITAL', '305', 526300000, 'Resultado del ejercicio', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526305010, 'SAT/24-2019', 'CAPITAL', '305.01', 526305000, 'Utilidad del ejercicio', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526305020, 'SAT/24-2019', 'CAPITAL', '305.02', 526305000, 'Pérdida del ejercicio', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526305030, 'SAT/24-2019', 'CAPITAL', '305.03', 526305000, 'Resultado integral', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526306000, 'SAT/24-2019', 'CAPITAL', '306', 526300000, 'Otras cuentas de capital', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526306010, 'SAT/24-2019', 'CAPITAL', '306.01', 526306000, 'Otras cuentas de capital', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526400000, 'SAT/24-2019', 'INGRESOS', '400', 0, 'Ingresos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401000, 'SAT/24-2019', 'INGRESOS', '401', 526400000, 'Ingresos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401010, 'SAT/24-2019', 'INGRESOS', '401.01', 526401000, 'Ventas y/o servicios gravados a la tasa general', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401020, 'SAT/24-2019', 'INGRESOS', '401.02', 526401000, 'Ventas y/o servicios gravados a la tasa general de contado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401030, 'SAT/24-2019', 'INGRESOS', '401.03', 526401000, 'Ventas y/o servicios gravados a la tasa general a crédito', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401040, 'SAT/24-2019', 'INGRESOS', '401.04', 526401000, 'Ventas y/o servicios gravados realizados en zona fronteriza norte', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401050, 'SAT/24-2019', 'INGRESOS', '401.05', 526401000, 'Ventas y/o servicios gravados realizados en zona fronteriza norte de contado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401060, 'SAT/24-2019', 'INGRESOS', '401.06', 526401000, 'Ventas y/o servicios gravados realizados en zona fronteriza norte a crédito', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401070, 'SAT/24-2019', 'INGRESOS', '401.07', 526401000, 'Ventas y/o servicios gravados al 0%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401080, 'SAT/24-2019', 'INGRESOS', '401.08', 526401000, 'Ventas y/o servicios gravados al 0% de contado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401090, 'SAT/24-2019', 'INGRESOS', '401.09', 526401000, 'Ventas y/o servicios gravados al 0% a crédito', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401100, 'SAT/24-2019', 'INGRESOS', '401.1', 526401000, 'Ventas y/o servicios exentos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401110, 'SAT/24-2019', 'INGRESOS', '401.11', 526401000, 'Ventas y/o servicios exentos de contado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401120, 'SAT/24-2019', 'INGRESOS', '401.12', 526401000, 'Ventas y/o servicios exentos a crédito', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401130, 'SAT/24-2019', 'INGRESOS', '401.13', 526401000, 'Ventas y/o servicios gravados a la tasa general nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401140, 'SAT/24-2019', 'INGRESOS', '401.14', 526401000, 'Ventas y/o servicios gravados a la tasa general extranjeros partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401150, 'SAT/24-2019', 'INGRESOS', '401.15', 526401000, 'Ventas y/o servicios gravados al 0% nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401160, 'SAT/24-2019', 'INGRESOS', '401.16', 526401000, 'Ventas y/o servicios gravados al 0% extranjeros partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401170, 'SAT/24-2019', 'INGRESOS', '401.17', 526401000, 'Ventas y/o servicios exentos nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401180, 'SAT/24-2019', 'INGRESOS', '401.18', 526401000, 'Ventas y/o servicios exentos extranjeros partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401190, 'SAT/24-2019', 'INGRESOS', '401.19', 526401000, 'Ingresos por servicios administrativos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401200, 'SAT/24-2019', 'INGRESOS', '401.2', 526401000, 'Ingresos por servicios administrativos nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401210, 'SAT/24-2019', 'INGRESOS', '401.21', 526401000, 'Ingresos por servicios administrativos extranjeros partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401220, 'SAT/24-2019', 'INGRESOS', '401.22', 526401000, 'Ingresos por servicios profesionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401230, 'SAT/24-2019', 'INGRESOS', '401.23', 526401000, 'Ingresos por servicios profesionales nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401240, 'SAT/24-2019', 'INGRESOS', '401.24', 526401000, 'Ingresos por servicios profesionales extranjeros partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401250, 'SAT/24-2019', 'INGRESOS', '401.25', 526401000, 'Ingresos por arrendamiento', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401260, 'SAT/24-2019', 'INGRESOS', '401.26', 526401000, 'Ingresos por arrendamiento nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401270, 'SAT/24-2019', 'INGRESOS', '401.27', 526401000, 'Ingresos por arrendamiento extranjeros partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401280, 'SAT/24-2019', 'INGRESOS', '401.28', 526401000, 'Ingresos por exportación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401290, 'SAT/24-2019', 'INGRESOS', '401.29', 526401000, 'Ingresos por comisiones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401300, 'SAT/24-2019', 'INGRESOS', '401.3', 526401000, 'Ingresos por maquila', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401310, 'SAT/24-2019', 'INGRESOS', '401.31', 526401000, 'Ingresos por coordinados', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401320, 'SAT/24-2019', 'INGRESOS', '401.32', 526401000, 'Ingresos por regalías', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401330, 'SAT/24-2019', 'INGRESOS', '401.33', 526401000, 'Ingresos por asistencia técnica', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401340, 'SAT/24-2019', 'INGRESOS', '401.34', 526401000, 'Ingresos por donativos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401350, 'SAT/24-2019', 'INGRESOS', '401.35', 526401000, 'Ingresos por intereses (actividad propia)', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401360, 'SAT/24-2019', 'INGRESOS', '401.36', 526401000, 'Ingresos de copropiedad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401370, 'SAT/24-2019', 'INGRESOS', '401.37', 526401000, 'Ingresos por fideicomisos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401380, 'SAT/24-2019', 'INGRESOS', '401.38', 526401000, 'Ingresos por factoraje financiero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401390, 'SAT/24-2019', 'INGRESOS', '401.39', 526401000, 'Ingresos por arrendamiento financiero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401400, 'SAT/24-2019', 'INGRESOS', '401.4', 526401000, 'Ingresos de extranjeros con establecimiento en el país', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526401410, 'SAT/24-2019', 'INGRESOS', '401.41', 526401000, 'Otros ingresos propios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526402000, 'SAT/24-2019', 'INGRESOS', '402', 526400000, 'Devoluciones, descuentos o bonificaciones sobre ingresos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526402010, 'SAT/24-2019', 'INGRESOS', '402.01', 526402000, 'Devoluciones, descuentos o bonificaciones sobre ventas y/o servicios a la tasa general', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526402020, 'SAT/24-2019', 'INGRESOS', '402.02', 526402000, 'Devoluciones, descuentos o bonificaciones sobre ventas y/o servicios en zona fronteriza norte', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526402030, 'SAT/24-2019', 'INGRESOS', '402.03', 526402000, 'Devoluciones, descuentos o bonificaciones sobre ventas y/o servicios al 0%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526402040, 'SAT/24-2019', 'INGRESOS', '402.04', 526402000, 'Devoluciones, descuentos o bonificaciones sobre ventas y/o servicios exentos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526402050, 'SAT/24-2019', 'INGRESOS', '402.05', 526402000, 'Devoluciones, descuentos o bonificaciones de otros ingresos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526403000, 'SAT/24-2019', 'INGRESOS', '403', 526400000, 'Otros ingresos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526403010, 'SAT/24-2019', 'INGRESOS', '403.01', 526403000, 'Otros Ingresos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526403020, 'SAT/24-2019', 'INGRESOS', '403.02', 526403000, 'Otros ingresos nacionales parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526403030, 'SAT/24-2019', 'INGRESOS', '403.03', 526403000, 'Otros ingresos extranjeros parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526403040, 'SAT/24-2019', 'INGRESOS', '403.04', 526403000, 'Ingresos por operaciones discontinuas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526403050, 'SAT/24-2019', 'INGRESOS', '403.05', 526403000, 'Ingresos por condonación de adeudo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526500000, 'SAT/24-2019', 'COSTOS', '500', 0, 'Costos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526501000, 'SAT/24-2019', 'COSTOS', '501', 526500000, 'Costo de venta y/o servicio', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526501010, 'SAT/24-2019', 'COSTOS', '501.01', 526501000, 'Costo de venta', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526501020, 'SAT/24-2019', 'COSTOS', '501.02', 526501000, 'Costo de servicios (Mano de obra)', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526501030, 'SAT/24-2019', 'COSTOS', '501.03', 526501000, 'Materia prima directa utilizada para la producción', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526501040, 'SAT/24-2019', 'COSTOS', '501.04', 526501000, 'Materia prima consumida en el proceso productivo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526501050, 'SAT/24-2019', 'COSTOS', '501.05', 526501000, 'Mano de obra directa consumida', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526501060, 'SAT/24-2019', 'COSTOS', '501.06', 526501000, 'Mano de obra directa', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526501070, 'SAT/24-2019', 'COSTOS', '501.07', 526501000, 'Cargos indirectos de producción', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526501080, 'SAT/24-2019', 'COSTOS', '501.08', 526501000, 'Otros conceptos de costo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526502000, 'SAT/24-2019', 'COSTOS', '502', 526500000, 'Compras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526502010, 'SAT/24-2019', 'COSTOS', '502.01', 526502000, 'Compras nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526502020, 'SAT/24-2019', 'COSTOS', '502.02', 526502000, 'Compras nacionales parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526502030, 'SAT/24-2019', 'COSTOS', '502.03', 526502000, 'Compras de Importación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526502040, 'SAT/24-2019', 'COSTOS', '502.04', 526502000, 'Compras de Importación partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526503000, 'SAT/24-2019', 'COSTOS', '503', 526500000, 'Devoluciones, descuentos o bonificaciones sobre compras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526503010, 'SAT/24-2019', 'COSTOS', '503.01', 526503000, 'Devoluciones, descuentos o bonificaciones sobre compras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504000, 'SAT/24-2019', 'COSTOS', '504', 526500000, 'Otras cuentas de costos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504010, 'SAT/24-2019', 'COSTOS', '504.01', 526504000, 'Gastos indirectos de fabricación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504020, 'SAT/24-2019', 'COSTOS', '504.02', 526504000, 'Gastos indirectos de fabricación de partes relacionadas nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504030, 'SAT/24-2019', 'COSTOS', '504.03', 526504000, 'Gastos indirectos de fabricación de partes relacionadas extranjeras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504040, 'SAT/24-2019', 'COSTOS', '504.04', 526504000, 'Otras cuentas de costos incurridos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504050, 'SAT/24-2019', 'COSTOS', '504.05', 526504000, 'Otras cuentas de costos incurridos con partes relacionadas nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504060, 'SAT/24-2019', 'COSTOS', '504.06', 526504000, 'Otras cuentas de costos incurridos con partes relacionadas extranjeras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504070, 'SAT/24-2019', 'COSTOS', '504.07', 526504000, 'Depreciación de edificios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504080, 'SAT/24-2019', 'COSTOS', '504.08', 526504000, 'Depreciación de maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504090, 'SAT/24-2019', 'COSTOS', '504.09', 526504000, 'Depreciación de automóviles, autobuses, camiones de carga, tractocamiones, montacargas y remolques', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504100, 'SAT/24-2019', 'COSTOS', '504.1', 526504000, 'Depreciación de mobiliario y equipo de oficina', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504110, 'SAT/24-2019', 'COSTOS', '504.11', 526504000, 'Depreciación de equipo de cómputo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504120, 'SAT/24-2019', 'COSTOS', '504.12', 526504000, 'Depreciación de equipo de comunicación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504130, 'SAT/24-2019', 'COSTOS', '504.13', 526504000, 'Depreciación de activos biológicos, vegetales y semovientes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504140, 'SAT/24-2019', 'COSTOS', '504.14', 526504000, 'Depreciación de otros activos fijos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504150, 'SAT/24-2019', 'COSTOS', '504.15', 526504000, 'Depreciación de ferrocarriles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504160, 'SAT/24-2019', 'COSTOS', '504.16', 526504000, 'Depreciación de embarcaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504170, 'SAT/24-2019', 'COSTOS', '504.17', 526504000, 'Depreciación de aviones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504180, 'SAT/24-2019', 'COSTOS', '504.18', 526504000, 'Depreciación de troqueles, moldes, matrices y herramental', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504190, 'SAT/24-2019', 'COSTOS', '504.19', 526504000, 'Depreciación de equipo de comunicaciones telefónicas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504200, 'SAT/24-2019', 'COSTOS', '504.2', 526504000, 'Depreciación de equipo de comunicación satelital', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504210, 'SAT/24-2019', 'COSTOS', '504.21', 526504000, 'Depreciación de equipo de adaptaciones para personas con capacidades diferentes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504220, 'SAT/24-2019', 'COSTOS', '504.22', 526504000, 'Depreciación de maquinaria y equipo de generación de energía de fuentes renovables o de sistemas de cogeneración de electricidad eficiente', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504230, 'SAT/24-2019', 'COSTOS', '504.23', 526504000, 'Depreciación de adaptaciones y mejoras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504240, 'SAT/24-2019', 'COSTOS', '504.24', 526504000, 'Depreciación de otra maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526504250, 'SAT/24-2019', 'COSTOS', '504.25', 526504000, 'Otras cuentas de costos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526505000, 'SAT/24-2019', 'COSTOS', '505', 526500000, 'Costo de activo fijo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526505010, 'SAT/24-2019', 'COSTOS', '505.01', 526505000, 'Costo por venta de activo fijo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526505020, 'SAT/24-2019', 'COSTOS', '505.02', 526505000, 'Costo por baja de activo fijo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526600000, 'SAT/24-2019', 'GASTOS', '600', 0, 'Gastos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601000, 'SAT/24-2019', 'GASTOS', '601', 526600000, 'Gastos generales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601010, 'SAT/24-2019', 'GASTOS', '601.01', 526601000, 'Sueldos y salarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601020, 'SAT/24-2019', 'GASTOS', '601.02', 526601000, 'Compensaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601030, 'SAT/24-2019', 'GASTOS', '601.03', 526601000, 'Tiempos extras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601040, 'SAT/24-2019', 'GASTOS', '601.04', 526601000, 'Premios de asistencia', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601050, 'SAT/24-2019', 'GASTOS', '601.05', 526601000, 'Premios de puntualidad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601060, 'SAT/24-2019', 'GASTOS', '601.06', 526601000, 'Vacaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601070, 'SAT/24-2019', 'GASTOS', '601.07', 526601000, 'Prima vacacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601080, 'SAT/24-2019', 'GASTOS', '601.08', 526601000, 'Prima dominical', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601090, 'SAT/24-2019', 'GASTOS', '601.09', 526601000, 'Días festivos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601100, 'SAT/24-2019', 'GASTOS', '601.1', 526601000, 'Gratificaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601110, 'SAT/24-2019', 'GASTOS', '601.11', 526601000, 'Primas de antigüedad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601120, 'SAT/24-2019', 'GASTOS', '601.12', 526601000, 'Aguinaldo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601130, 'SAT/24-2019', 'GASTOS', '601.13', 526601000, 'Indemnizaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601140, 'SAT/24-2019', 'GASTOS', '601.14', 526601000, 'Destajo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601150, 'SAT/24-2019', 'GASTOS', '601.15', 526601000, 'Despensa', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601160, 'SAT/24-2019', 'GASTOS', '601.16', 526601000, 'Transporte', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601170, 'SAT/24-2019', 'GASTOS', '601.17', 526601000, 'Servicio médico', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601180, 'SAT/24-2019', 'GASTOS', '601.18', 526601000, 'Ayuda en gastos funerarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601190, 'SAT/24-2019', 'GASTOS', '601.19', 526601000, 'Fondo de ahorro', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601200, 'SAT/24-2019', 'GASTOS', '601.2', 526601000, 'Cuotas sindicales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601210, 'SAT/24-2019', 'GASTOS', '601.21', 526601000, 'PTU', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601220, 'SAT/24-2019', 'GASTOS', '601.22', 526601000, 'Estímulo al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601230, 'SAT/24-2019', 'GASTOS', '601.23', 526601000, 'Previsión social', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601240, 'SAT/24-2019', 'GASTOS', '601.24', 526601000, 'Aportaciones para el plan de jubilación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601250, 'SAT/24-2019', 'GASTOS', '601.25', 526601000, 'Otras prestaciones al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601260, 'SAT/24-2019', 'GASTOS', '601.26', 526601000, 'Cuotas al IMSS', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601270, 'SAT/24-2019', 'GASTOS', '601.27', 526601000, 'Aportaciones al infonavit', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601280, 'SAT/24-2019', 'GASTOS', '601.28', 526601000, 'Aportaciones al SAR', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601290, 'SAT/24-2019', 'GASTOS', '601.29', 526601000, 'Impuesto estatal sobre nóminas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601300, 'SAT/24-2019', 'GASTOS', '601.3', 526601000, 'Otras aportaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601310, 'SAT/24-2019', 'GASTOS', '601.31', 526601000, 'Asimilados a salarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601320, 'SAT/24-2019', 'GASTOS', '601.32', 526601000, 'Servicios administrativos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601330, 'SAT/24-2019', 'GASTOS', '601.33', 526601000, 'Servicios administrativos partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601340, 'SAT/24-2019', 'GASTOS', '601.34', 526601000, 'Honorarios a personas físicas residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601350, 'SAT/24-2019', 'GASTOS', '601.35', 526601000, 'Honorarios a personas físicas residentes nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601360, 'SAT/24-2019', 'GASTOS', '601.36', 526601000, 'Honorarios a personas físicas residentes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601370, 'SAT/24-2019', 'GASTOS', '601.37', 526601000, 'Honorarios a personas físicas residentes del extranjero partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601380, 'SAT/24-2019', 'GASTOS', '601.38', 526601000, 'Honorarios a personas morales residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601390, 'SAT/24-2019', 'GASTOS', '601.39', 526601000, 'Honorarios a personas morales residentes nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601400, 'SAT/24-2019', 'GASTOS', '601.4', 526601000, 'Honorarios a personas morales residentes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601410, 'SAT/24-2019', 'GASTOS', '601.41', 526601000, 'Honorarios a personas morales residentes del extranjero partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601420, 'SAT/24-2019', 'GASTOS', '601.42', 526601000, 'Honorarios aduanales personas físicas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601430, 'SAT/24-2019', 'GASTOS', '601.43', 526601000, 'Honorarios aduanales personas morales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601440, 'SAT/24-2019', 'GASTOS', '601.44', 526601000, 'Honorarios al consejo de administración', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601450, 'SAT/24-2019', 'GASTOS', '601.45', 526601000, 'Arrendamiento a personas físicas residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601460, 'SAT/24-2019', 'GASTOS', '601.46', 526601000, 'Arrendamiento a personas morales residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601470, 'SAT/24-2019', 'GASTOS', '601.47', 526601000, 'Arrendamiento a residentes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601480, 'SAT/24-2019', 'GASTOS', '601.48', 526601000, 'Combustibles y lubricantes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601490, 'SAT/24-2019', 'GASTOS', '601.49', 526601000, 'Viáticos y gastos de viaje', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601500, 'SAT/24-2019', 'GASTOS', '601.5', 526601000, 'Teléfono, internet', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601510, 'SAT/24-2019', 'GASTOS', '601.51', 526601000, 'Agua', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601526, 'SAT/24-2019', 'GASTOS', '601.52', 526601000, 'Energía eléctrica', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601530, 'SAT/24-2019', 'GASTOS', '601.53', 526601000, 'Vigilancia y seguridad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601540, 'SAT/24-2019', 'GASTOS', '601.54', 526601000, 'Limpieza', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601550, 'SAT/24-2019', 'GASTOS', '601.55', 526601000, 'Papelería y artículos de oficina', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601560, 'SAT/24-2019', 'GASTOS', '601.56', 526601000, 'Mantenimiento y conservación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601570, 'SAT/24-2019', 'GASTOS', '601.57', 526601000, 'Seguros y fianzas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601580, 'SAT/24-2019', 'GASTOS', '601.58', 526601000, 'Otros impuestos y derechos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601590, 'SAT/24-2019', 'GASTOS', '601.59', 526601000, 'Recargos fiscales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601600, 'SAT/24-2019', 'GASTOS', '601.6', 526601000, 'Cuotas y suscripciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601610, 'SAT/24-2019', 'GASTOS', '601.61', 526601000, 'Propaganda y publicidad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601620, 'SAT/24-2019', 'GASTOS', '601.62', 526601000, 'Capacitación al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601630, 'SAT/24-2019', 'GASTOS', '601.63', 526601000, 'Donativos y ayudas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601640, 'SAT/24-2019', 'GASTOS', '601.64', 526601000, 'Asistencia técnica', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601650, 'SAT/24-2019', 'GASTOS', '601.65', 526601000, 'Regalías sujetas a otros porcentajes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601660, 'SAT/24-2019', 'GASTOS', '601.66', 526601000, 'Regalías sujetas al 5%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601670, 'SAT/24-2019', 'GASTOS', '601.67', 526601000, 'Regalías sujetas al 10%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601680, 'SAT/24-2019', 'GASTOS', '601.68', 526601000, 'Regalías sujetas al 15%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601690, 'SAT/24-2019', 'GASTOS', '601.69', 526601000, 'Regalías sujetas al 25%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601700, 'SAT/24-2019', 'GASTOS', '601.7', 526601000, 'Regalías sujetas al 30%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601710, 'SAT/24-2019', 'GASTOS', '601.71', 526601000, 'Regalías sin retención', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601720, 'SAT/24-2019', 'GASTOS', '601.72', 526601000, 'Fletes y acarreos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601730, 'SAT/24-2019', 'GASTOS', '601.73', 526601000, 'Gastos de importación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601740, 'SAT/24-2019', 'GASTOS', '601.74', 526601000, 'Comisiones sobre ventas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601750, 'SAT/24-2019', 'GASTOS', '601.75', 526601000, 'Comisiones por tarjetas de crédito', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601760, 'SAT/24-2019', 'GASTOS', '601.76', 526601000, 'Patentes y marcas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601770, 'SAT/24-2019', 'GASTOS', '601.77', 526601000, 'Uniformes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601780, 'SAT/24-2019', 'GASTOS', '601.78', 526601000, 'Prediales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601790, 'SAT/24-2019', 'GASTOS', '601.79', 526601000, 'Gastos generales de urbanización', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601800, 'SAT/24-2019', 'GASTOS', '601.8', 526601000, 'Gastos generales de construcción', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601810, 'SAT/24-2019', 'GASTOS', '601.81', 526601000, 'Fletes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601820, 'SAT/24-2019', 'GASTOS', '601.82', 526601000, 'Recolección de bienes del sector agropecuario y/o ganadero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601830, 'SAT/24-2019', 'GASTOS', '601.83', 526601000, 'Gastos no deducibles (sin requisitos fiscales)', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526601840, 'SAT/24-2019', 'GASTOS', '601.84', 526601000, 'Otros gastos generales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602000, 'SAT/24-2019', 'GASTOS', '602', 526600000, 'Gastos de venta', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602010, 'SAT/24-2019', 'GASTOS', '602.01', 526602000, 'Sueldos y salarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602020, 'SAT/24-2019', 'GASTOS', '602.02', 526602000, 'Compensaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602030, 'SAT/24-2019', 'GASTOS', '602.03', 526602000, 'Tiempos extras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602040, 'SAT/24-2019', 'GASTOS', '602.04', 526602000, 'Premios de asistencia', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602050, 'SAT/24-2019', 'GASTOS', '602.05', 526602000, 'Premios de puntualidad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602060, 'SAT/24-2019', 'GASTOS', '602.06', 526602000, 'Vacaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602070, 'SAT/24-2019', 'GASTOS', '602.07', 526602000, 'Prima vacacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602080, 'SAT/24-2019', 'GASTOS', '602.08', 526602000, 'Prima dominical', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602090, 'SAT/24-2019', 'GASTOS', '602.09', 526602000, 'Días festivos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602100, 'SAT/24-2019', 'GASTOS', '602.1', 526602000, 'Gratificaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602110, 'SAT/24-2019', 'GASTOS', '602.11', 526602000, 'Primas de antigüedad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602120, 'SAT/24-2019', 'GASTOS', '602.12', 526602000, 'Aguinaldo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602130, 'SAT/24-2019', 'GASTOS', '602.13', 526602000, 'Indemnizaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602140, 'SAT/24-2019', 'GASTOS', '602.14', 526602000, 'Destajo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602150, 'SAT/24-2019', 'GASTOS', '602.15', 526602000, 'Despensa', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602160, 'SAT/24-2019', 'GASTOS', '602.16', 526602000, 'Transporte', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602170, 'SAT/24-2019', 'GASTOS', '602.17', 526602000, 'Servicio médico', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602180, 'SAT/24-2019', 'GASTOS', '602.18', 526602000, 'Ayuda en gastos funerarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602190, 'SAT/24-2019', 'GASTOS', '602.19', 526602000, 'Fondo de ahorro', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602200, 'SAT/24-2019', 'GASTOS', '602.2', 526602000, 'Cuotas sindicales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602210, 'SAT/24-2019', 'GASTOS', '602.21', 526602000, 'PTU', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602220, 'SAT/24-2019', 'GASTOS', '602.22', 526602000, 'Estímulo al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602230, 'SAT/24-2019', 'GASTOS', '602.23', 526602000, 'Previsión social', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602240, 'SAT/24-2019', 'GASTOS', '602.24', 526602000, 'Aportaciones para el plan de jubilación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602250, 'SAT/24-2019', 'GASTOS', '602.25', 526602000, 'Otras prestaciones al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602260, 'SAT/24-2019', 'GASTOS', '602.26', 526602000, 'Cuotas al IMSS', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602270, 'SAT/24-2019', 'GASTOS', '602.27', 526602000, 'Aportaciones al infonavit', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602280, 'SAT/24-2019', 'GASTOS', '602.28', 526602000, 'Aportaciones al SAR', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602290, 'SAT/24-2019', 'GASTOS', '602.29', 526602000, 'Impuesto estatal sobre nóminas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602300, 'SAT/24-2019', 'GASTOS', '602.3', 526602000, 'Otras aportaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602310, 'SAT/24-2019', 'GASTOS', '602.31', 526602000, 'Asimilados a salarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602320, 'SAT/24-2019', 'GASTOS', '602.32', 526602000, 'Servicios administrativos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602330, 'SAT/24-2019', 'GASTOS', '602.33', 526602000, 'Servicios administrativos partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602340, 'SAT/24-2019', 'GASTOS', '602.34', 526602000, 'Honorarios a personas físicas residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602350, 'SAT/24-2019', 'GASTOS', '602.35', 526602000, 'Honorarios a personas físicas residentes nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602360, 'SAT/24-2019', 'GASTOS', '602.36', 526602000, 'Honorarios a personas físicas residentes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602370, 'SAT/24-2019', 'GASTOS', '602.37', 526602000, 'Honorarios a personas físicas residentes del extranjero partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602380, 'SAT/24-2019', 'GASTOS', '602.38', 526602000, 'Honorarios a personas morales residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602390, 'SAT/24-2019', 'GASTOS', '602.39', 526602000, 'Honorarios a personas morales residentes nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602400, 'SAT/24-2019', 'GASTOS', '602.4', 526602000, 'Honorarios a personas morales residentes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602410, 'SAT/24-2019', 'GASTOS', '602.41', 526602000, 'Honorarios a personas morales residentes del extranjero partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602420, 'SAT/24-2019', 'GASTOS', '602.42', 526602000, 'Honorarios aduanales personas físicas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602430, 'SAT/24-2019', 'GASTOS', '602.43', 526602000, 'Honorarios aduanales personas morales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602440, 'SAT/24-2019', 'GASTOS', '602.44', 526602000, 'Honorarios al consejo de administración', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602450, 'SAT/24-2019', 'GASTOS', '602.45', 526602000, 'Arrendamiento a personas físicas residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602460, 'SAT/24-2019', 'GASTOS', '602.46', 526602000, 'Arrendamiento a personas morales residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602470, 'SAT/24-2019', 'GASTOS', '602.47', 526602000, 'Arrendamiento a residentes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602480, 'SAT/24-2019', 'GASTOS', '602.48', 526602000, 'Combustibles y lubricantes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602490, 'SAT/24-2019', 'GASTOS', '602.49', 526602000, 'Viáticos y gastos de viaje', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602500, 'SAT/24-2019', 'GASTOS', '602.5', 526602000, 'Teléfono, internet', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602510, 'SAT/24-2019', 'GASTOS', '602.51', 526602000, 'Agua', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602526, 'SAT/24-2019', 'GASTOS', '602.52', 526602000, 'Energía eléctrica', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602530, 'SAT/24-2019', 'GASTOS', '602.53', 526602000, 'Vigilancia y seguridad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602540, 'SAT/24-2019', 'GASTOS', '602.54', 526602000, 'Limpieza', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602550, 'SAT/24-2019', 'GASTOS', '602.55', 526602000, 'Papelería y artículos de oficina', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602560, 'SAT/24-2019', 'GASTOS', '602.56', 526602000, 'Mantenimiento y conservación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602570, 'SAT/24-2019', 'GASTOS', '602.57', 526602000, 'Seguros y fianzas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602580, 'SAT/24-2019', 'GASTOS', '602.58', 526602000, 'Otros impuestos y derechos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602590, 'SAT/24-2019', 'GASTOS', '602.59', 526602000, 'Recargos fiscales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602600, 'SAT/24-2019', 'GASTOS', '602.6', 526602000, 'Cuotas y suscripciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602610, 'SAT/24-2019', 'GASTOS', '602.61', 526602000, 'Propaganda y publicidad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602620, 'SAT/24-2019', 'GASTOS', '602.62', 526602000, 'Capacitación al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602630, 'SAT/24-2019', 'GASTOS', '602.63', 526602000, 'Donativos y ayudas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602640, 'SAT/24-2019', 'GASTOS', '602.64', 526602000, 'Asistencia técnica', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602650, 'SAT/24-2019', 'GASTOS', '602.65', 526602000, 'Regalías sujetas a otros porcentajes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602660, 'SAT/24-2019', 'GASTOS', '602.66', 526602000, 'Regalías sujetas al 5%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602670, 'SAT/24-2019', 'GASTOS', '602.67', 526602000, 'Regalías sujetas al 10%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602680, 'SAT/24-2019', 'GASTOS', '602.68', 526602000, 'Regalías sujetas al 15%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602690, 'SAT/24-2019', 'GASTOS', '602.69', 526602000, 'Regalías sujetas al 25%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602700, 'SAT/24-2019', 'GASTOS', '602.7', 526602000, 'Regalías sujetas al 30%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602710, 'SAT/24-2019', 'GASTOS', '602.71', 526602000, 'Regalías sin retención', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602720, 'SAT/24-2019', 'GASTOS', '602.72', 526602000, 'Fletes y acarreos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602730, 'SAT/24-2019', 'GASTOS', '602.73', 526602000, 'Gastos de importación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602740, 'SAT/24-2019', 'GASTOS', '602.74', 526602000, 'Comisiones sobre ventas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602750, 'SAT/24-2019', 'GASTOS', '602.75', 526602000, 'Comisiones por tarjetas de crédito', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602760, 'SAT/24-2019', 'GASTOS', '602.76', 526602000, 'Patentes y marcas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602770, 'SAT/24-2019', 'GASTOS', '602.77', 526602000, 'Uniformes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602780, 'SAT/24-2019', 'GASTOS', '602.78', 526602000, 'Prediales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602790, 'SAT/24-2019', 'GASTOS', '602.79', 526602000, 'Gastos de venta de urbanización', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602800, 'SAT/24-2019', 'GASTOS', '602.8', 526602000, 'Gastos de venta de construcción', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602810, 'SAT/24-2019', 'GASTOS', '602.81', 526602000, 'Fletes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602820, 'SAT/24-2019', 'GASTOS', '602.82', 526602000, 'Recolección de bienes del sector agropecuario y/o ganadero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602830, 'SAT/24-2019', 'GASTOS', '602.83', 526602000, 'Gastos no deducibles (sin requisitos fiscales)', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526602840, 'SAT/24-2019', 'GASTOS', '602.84', 526602000, 'Otros gastos de venta', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603000, 'SAT/24-2019', 'GASTOS', '603', 526600000, 'Gastos de administración', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603010, 'SAT/24-2019', 'GASTOS', '603.01', 526603000, 'Sueldos y salarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603020, 'SAT/24-2019', 'GASTOS', '603.02', 526603000, 'Compensaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603030, 'SAT/24-2019', 'GASTOS', '603.03', 526603000, 'Tiempos extras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603040, 'SAT/24-2019', 'GASTOS', '603.04', 526603000, 'Premios de asistencia', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603050, 'SAT/24-2019', 'GASTOS', '603.05', 526603000, 'Premios de puntualidad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603060, 'SAT/24-2019', 'GASTOS', '603.06', 526603000, 'Vacaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603070, 'SAT/24-2019', 'GASTOS', '603.07', 526603000, 'Prima vacacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603080, 'SAT/24-2019', 'GASTOS', '603.08', 526603000, 'Prima dominical', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603090, 'SAT/24-2019', 'GASTOS', '603.09', 526603000, 'Días festivos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603100, 'SAT/24-2019', 'GASTOS', '603.1', 526603000, 'Gratificaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603110, 'SAT/24-2019', 'GASTOS', '603.11', 526603000, 'Primas de antigüedad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603120, 'SAT/24-2019', 'GASTOS', '603.12', 526603000, 'Aguinaldo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603130, 'SAT/24-2019', 'GASTOS', '603.13', 526603000, 'Indemnizaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603140, 'SAT/24-2019', 'GASTOS', '603.14', 526603000, 'Destajo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603150, 'SAT/24-2019', 'GASTOS', '603.15', 526603000, 'Despensa', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603160, 'SAT/24-2019', 'GASTOS', '603.16', 526603000, 'Transporte', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603170, 'SAT/24-2019', 'GASTOS', '603.17', 526603000, 'Servicio médico', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603180, 'SAT/24-2019', 'GASTOS', '603.18', 526603000, 'Ayuda en gastos funerarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603190, 'SAT/24-2019', 'GASTOS', '603.19', 526603000, 'Fondo de ahorro', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603200, 'SAT/24-2019', 'GASTOS', '603.2', 526603000, 'Cuotas sindicales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603210, 'SAT/24-2019', 'GASTOS', '603.21', 526603000, 'PTU', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603220, 'SAT/24-2019', 'GASTOS', '603.22', 526603000, 'Estímulo al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603230, 'SAT/24-2019', 'GASTOS', '603.23', 526603000, 'Previsión social', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603240, 'SAT/24-2019', 'GASTOS', '603.24', 526603000, 'Aportaciones para el plan de jubilación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603250, 'SAT/24-2019', 'GASTOS', '603.25', 526603000, 'Otras prestaciones al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603260, 'SAT/24-2019', 'GASTOS', '603.26', 526603000, 'Cuotas al IMSS', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603270, 'SAT/24-2019', 'GASTOS', '603.27', 526603000, 'Aportaciones al infonavit', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603280, 'SAT/24-2019', 'GASTOS', '603.28', 526603000, 'Aportaciones al SAR', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603290, 'SAT/24-2019', 'GASTOS', '603.29', 526603000, 'Impuesto estatal sobre nóminas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603300, 'SAT/24-2019', 'GASTOS', '603.3', 526603000, 'Otras aportaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603310, 'SAT/24-2019', 'GASTOS', '603.31', 526603000, 'Asimilados a salarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603320, 'SAT/24-2019', 'GASTOS', '603.32', 526603000, 'Servicios administrativos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603330, 'SAT/24-2019', 'GASTOS', '603.33', 526603000, 'Servicios administrativos partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603340, 'SAT/24-2019', 'GASTOS', '603.34', 526603000, 'Honorarios a personas físicas residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603350, 'SAT/24-2019', 'GASTOS', '603.35', 526603000, 'Honorarios a personas físicas residentes nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603360, 'SAT/24-2019', 'GASTOS', '603.36', 526603000, 'Honorarios a personas físicas residentes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603370, 'SAT/24-2019', 'GASTOS', '603.37', 526603000, 'Honorarios a personas físicas residentes del extranjero partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603380, 'SAT/24-2019', 'GASTOS', '603.38', 526603000, 'Honorarios a personas morales residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603390, 'SAT/24-2019', 'GASTOS', '603.39', 526603000, 'Honorarios a personas morales residentes nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603400, 'SAT/24-2019', 'GASTOS', '603.4', 526603000, 'Honorarios a personas morales residentes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603410, 'SAT/24-2019', 'GASTOS', '603.41', 526603000, 'Honorarios a personas morales residentes del extranjero partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603420, 'SAT/24-2019', 'GASTOS', '603.42', 526603000, 'Honorarios aduanales personas físicas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603430, 'SAT/24-2019', 'GASTOS', '603.43', 526603000, 'Honorarios aduanales personas morales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603440, 'SAT/24-2019', 'GASTOS', '603.44', 526603000, 'Honorarios al consejo de administración', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603450, 'SAT/24-2019', 'GASTOS', '603.45', 526603000, 'Arrendamiento a personas físicas residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603460, 'SAT/24-2019', 'GASTOS', '603.46', 526603000, 'Arrendamiento a personas morales residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603470, 'SAT/24-2019', 'GASTOS', '603.47', 526603000, 'Arrendamiento a residentes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603480, 'SAT/24-2019', 'GASTOS', '603.48', 526603000, 'Combustibles y lubricantes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603490, 'SAT/24-2019', 'GASTOS', '603.49', 526603000, 'Viáticos y gastos de viaje', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603500, 'SAT/24-2019', 'GASTOS', '603.5', 526603000, 'Teléfono, internet', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603510, 'SAT/24-2019', 'GASTOS', '603.51', 526603000, 'Agua', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603526, 'SAT/24-2019', 'GASTOS', '603.52', 526603000, 'Energía eléctrica', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603530, 'SAT/24-2019', 'GASTOS', '603.53', 526603000, 'Vigilancia y seguridad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603540, 'SAT/24-2019', 'GASTOS', '603.54', 526603000, 'Limpieza', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603550, 'SAT/24-2019', 'GASTOS', '603.55', 526603000, 'Papelería y artículos de oficina', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603560, 'SAT/24-2019', 'GASTOS', '603.56', 526603000, 'Mantenimiento y conservación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603570, 'SAT/24-2019', 'GASTOS', '603.57', 526603000, 'Seguros y fianzas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603580, 'SAT/24-2019', 'GASTOS', '603.58', 526603000, 'Otros impuestos y derechos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603590, 'SAT/24-2019', 'GASTOS', '603.59', 526603000, 'Recargos fiscales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603600, 'SAT/24-2019', 'GASTOS', '603.6', 526603000, 'Cuotas y suscripciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603610, 'SAT/24-2019', 'GASTOS', '603.61', 526603000, 'Propaganda y publicidad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603620, 'SAT/24-2019', 'GASTOS', '603.62', 526603000, 'Capacitación al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603630, 'SAT/24-2019', 'GASTOS', '603.63', 526603000, 'Donativos y ayudas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603640, 'SAT/24-2019', 'GASTOS', '603.64', 526603000, 'Asistencia técnica', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603650, 'SAT/24-2019', 'GASTOS', '603.65', 526603000, 'Regalías sujetas a otros porcentajes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603660, 'SAT/24-2019', 'GASTOS', '603.66', 526603000, 'Regalías sujetas al 5%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603670, 'SAT/24-2019', 'GASTOS', '603.67', 526603000, 'Regalías sujetas al 10%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603680, 'SAT/24-2019', 'GASTOS', '603.68', 526603000, 'Regalías sujetas al 15%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603690, 'SAT/24-2019', 'GASTOS', '603.69', 526603000, 'Regalías sujetas al 25%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603700, 'SAT/24-2019', 'GASTOS', '603.7', 526603000, 'Regalías sujetas al 30%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603710, 'SAT/24-2019', 'GASTOS', '603.71', 526603000, 'Regalías sin retención', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603720, 'SAT/24-2019', 'GASTOS', '603.72', 526603000, 'Fletes y acarreos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603730, 'SAT/24-2019', 'GASTOS', '603.73', 526603000, 'Gastos de importación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603740, 'SAT/24-2019', 'GASTOS', '603.74', 526603000, 'Patentes y marcas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603750, 'SAT/24-2019', 'GASTOS', '603.75', 526603000, 'Uniformes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603760, 'SAT/24-2019', 'GASTOS', '603.76', 526603000, 'Prediales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603770, 'SAT/24-2019', 'GASTOS', '603.77', 526603000, 'Gastos de administración de urbanización', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603780, 'SAT/24-2019', 'GASTOS', '603.78', 526603000, 'Gastos de administración de construcción', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603790, 'SAT/24-2019', 'GASTOS', '603.79', 526603000, 'Fletes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603800, 'SAT/24-2019', 'GASTOS', '603.8', 526603000, 'Recolección de bienes del sector agropecuario y/o ganadero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603810, 'SAT/24-2019', 'GASTOS', '603.81', 526603000, 'Gastos no deducibles (sin requisitos fiscales)', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526603820, 'SAT/24-2019', 'GASTOS', '603.82', 526603000, 'Otros gastos de administración', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604000, 'SAT/24-2019', 'GASTOS', '604', 526600000, 'Gastos de fabricación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604010, 'SAT/24-2019', 'GASTOS', '604.01', 526604000, 'Sueldos y salarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604020, 'SAT/24-2019', 'GASTOS', '604.02', 526604000, 'Compensaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604030, 'SAT/24-2019', 'GASTOS', '604.03', 526604000, 'Tiempos extras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604040, 'SAT/24-2019', 'GASTOS', '604.04', 526604000, 'Premios de asistencia', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604050, 'SAT/24-2019', 'GASTOS', '604.05', 526604000, 'Premios de puntualidad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604060, 'SAT/24-2019', 'GASTOS', '604.06', 526604000, 'Vacaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604070, 'SAT/24-2019', 'GASTOS', '604.07', 526604000, 'Prima vacacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604080, 'SAT/24-2019', 'GASTOS', '604.08', 526604000, 'Prima dominical', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604090, 'SAT/24-2019', 'GASTOS', '604.09', 526604000, 'Días festivos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604100, 'SAT/24-2019', 'GASTOS', '604.1', 526604000, 'Gratificaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604110, 'SAT/24-2019', 'GASTOS', '604.11', 526604000, 'Primas de antigüedad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604120, 'SAT/24-2019', 'GASTOS', '604.12', 526604000, 'Aguinaldo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604130, 'SAT/24-2019', 'GASTOS', '604.13', 526604000, 'Indemnizaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604140, 'SAT/24-2019', 'GASTOS', '604.14', 526604000, 'Destajo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604150, 'SAT/24-2019', 'GASTOS', '604.15', 526604000, 'Despensa', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604160, 'SAT/24-2019', 'GASTOS', '604.16', 526604000, 'Transporte', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604170, 'SAT/24-2019', 'GASTOS', '604.17', 526604000, 'Servicio médico', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604180, 'SAT/24-2019', 'GASTOS', '604.18', 526604000, 'Ayuda en gastos funerarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604190, 'SAT/24-2019', 'GASTOS', '604.19', 526604000, 'Fondo de ahorro', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604200, 'SAT/24-2019', 'GASTOS', '604.2', 526604000, 'Cuotas sindicales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604210, 'SAT/24-2019', 'GASTOS', '604.21', 526604000, 'PTU', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604220, 'SAT/24-2019', 'GASTOS', '604.22', 526604000, 'Estímulo al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604230, 'SAT/24-2019', 'GASTOS', '604.23', 526604000, 'Previsión social', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604240, 'SAT/24-2019', 'GASTOS', '604.24', 526604000, 'Aportaciones para el plan de jubilación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604250, 'SAT/24-2019', 'GASTOS', '604.25', 526604000, 'Otras prestaciones al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604260, 'SAT/24-2019', 'GASTOS', '604.26', 526604000, 'Cuotas al IMSS', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604270, 'SAT/24-2019', 'GASTOS', '604.27', 526604000, 'Aportaciones al infonavit', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604280, 'SAT/24-2019', 'GASTOS', '604.28', 526604000, 'Aportaciones al SAR', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604290, 'SAT/24-2019', 'GASTOS', '604.29', 526604000, 'Impuesto estatal sobre nóminas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604300, 'SAT/24-2019', 'GASTOS', '604.3', 526604000, 'Otras aportaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604310, 'SAT/24-2019', 'GASTOS', '604.31', 526604000, 'Asimilados a salarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604320, 'SAT/24-2019', 'GASTOS', '604.32', 526604000, 'Servicios administrativos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604330, 'SAT/24-2019', 'GASTOS', '604.33', 526604000, 'Servicios administrativos partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604340, 'SAT/24-2019', 'GASTOS', '604.34', 526604000, 'Honorarios a personas físicas residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604350, 'SAT/24-2019', 'GASTOS', '604.35', 526604000, 'Honorarios a personas físicas residentes nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604360, 'SAT/24-2019', 'GASTOS', '604.36', 526604000, 'Honorarios a personas físicas residentes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604370, 'SAT/24-2019', 'GASTOS', '604.37', 526604000, 'Honorarios a personas físicas residentes del extranjero partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604380, 'SAT/24-2019', 'GASTOS', '604.38', 526604000, 'Honorarios a personas morales residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604390, 'SAT/24-2019', 'GASTOS', '604.39', 526604000, 'Honorarios a personas morales residentes nacionales partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604400, 'SAT/24-2019', 'GASTOS', '604.4', 526604000, 'Honorarios a personas morales residentes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604410, 'SAT/24-2019', 'GASTOS', '604.41', 526604000, 'Honorarios a personas morales residentes del extranjero partes relacionadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604420, 'SAT/24-2019', 'GASTOS', '604.42', 526604000, 'Honorarios aduanales personas físicas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604430, 'SAT/24-2019', 'GASTOS', '604.43', 526604000, 'Honorarios aduanales personas morales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604440, 'SAT/24-2019', 'GASTOS', '604.44', 526604000, 'Honorarios al consejo de administración', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604450, 'SAT/24-2019', 'GASTOS', '604.45', 526604000, 'Arrendamiento a personas físicas residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604460, 'SAT/24-2019', 'GASTOS', '604.46', 526604000, 'Arrendamiento a personas morales residentes nacionales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604470, 'SAT/24-2019', 'GASTOS', '604.47', 526604000, 'Arrendamiento a residentes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604480, 'SAT/24-2019', 'GASTOS', '604.48', 526604000, 'Combustibles y lubricantes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604490, 'SAT/24-2019', 'GASTOS', '604.49', 526604000, 'Viáticos y gastos de viaje', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604500, 'SAT/24-2019', 'GASTOS', '604.5', 526604000, 'Teléfono, internet', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604510, 'SAT/24-2019', 'GASTOS', '604.51', 526604000, 'Agua', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604526, 'SAT/24-2019', 'GASTOS', '604.52', 526604000, 'Energía eléctrica', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604530, 'SAT/24-2019', 'GASTOS', '604.53', 526604000, 'Vigilancia y seguridad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604540, 'SAT/24-2019', 'GASTOS', '604.54', 526604000, 'Limpieza', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604550, 'SAT/24-2019', 'GASTOS', '604.55', 526604000, 'Papelería y artículos de oficina', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604560, 'SAT/24-2019', 'GASTOS', '604.56', 526604000, 'Mantenimiento y conservación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604570, 'SAT/24-2019', 'GASTOS', '604.57', 526604000, 'Seguros y fianzas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604580, 'SAT/24-2019', 'GASTOS', '604.58', 526604000, 'Otros impuestos y derechos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604590, 'SAT/24-2019', 'GASTOS', '604.59', 526604000, 'Recargos fiscales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604600, 'SAT/24-2019', 'GASTOS', '604.6', 526604000, 'Cuotas y suscripciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604610, 'SAT/24-2019', 'GASTOS', '604.61', 526604000, 'Propaganda y publicidad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604620, 'SAT/24-2019', 'GASTOS', '604.62', 526604000, 'Capacitación al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604630, 'SAT/24-2019', 'GASTOS', '604.63', 526604000, 'Donativos y ayudas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604640, 'SAT/24-2019', 'GASTOS', '604.64', 526604000, 'Asistencia técnica', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604650, 'SAT/24-2019', 'GASTOS', '604.65', 526604000, 'Regalías sujetas a otros porcentajes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604660, 'SAT/24-2019', 'GASTOS', '604.66', 526604000, 'Regalías sujetas al 5%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604670, 'SAT/24-2019', 'GASTOS', '604.67', 526604000, 'Regalías sujetas al 10%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604680, 'SAT/24-2019', 'GASTOS', '604.68', 526604000, 'Regalías sujetas al 15%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604690, 'SAT/24-2019', 'GASTOS', '604.69', 526604000, 'Regalías sujetas al 25%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604700, 'SAT/24-2019', 'GASTOS', '604.7', 526604000, 'Regalías sujetas al 30%', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604710, 'SAT/24-2019', 'GASTOS', '604.71', 526604000, 'Regalías sin retención', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604720, 'SAT/24-2019', 'GASTOS', '604.72', 526604000, 'Fletes y acarreos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604730, 'SAT/24-2019', 'GASTOS', '604.73', 526604000, 'Gastos de importación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604740, 'SAT/24-2019', 'GASTOS', '604.74', 526604000, 'Patentes y marcas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604750, 'SAT/24-2019', 'GASTOS', '604.75', 526604000, 'Uniformes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604760, 'SAT/24-2019', 'GASTOS', '604.76', 526604000, 'Prediales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604770, 'SAT/24-2019', 'GASTOS', '604.77', 526604000, 'Gastos de fabricación de urbanización', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604780, 'SAT/24-2019', 'GASTOS', '604.78', 526604000, 'Gastos de fabricación de construcción', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604790, 'SAT/24-2019', 'GASTOS', '604.79', 526604000, 'Fletes del extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604800, 'SAT/24-2019', 'GASTOS', '604.8', 526604000, 'Recolección de bienes del sector agropecuario y/o ganadero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604810, 'SAT/24-2019', 'GASTOS', '604.81', 526604000, 'Gastos no deducibles (sin requisitos fiscales)', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526604820, 'SAT/24-2019', 'GASTOS', '604.82', 526604000, 'Otros gastos de fabricación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605000, 'SAT/24-2019', 'GASTOS', '605', 526600000, 'Mano de obra directa', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605010, 'SAT/24-2019', 'GASTOS', '605.01', 526605000, 'Mano de obra', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605020, 'SAT/24-2019', 'GASTOS', '605.02', 526605000, 'Sueldos y Salarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605030, 'SAT/24-2019', 'GASTOS', '605.03', 526605000, 'Compensaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605040, 'SAT/24-2019', 'GASTOS', '605.04', 526605000, 'Tiempos extras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605050, 'SAT/24-2019', 'GASTOS', '605.05', 526605000, 'Premios de asistencia', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605060, 'SAT/24-2019', 'GASTOS', '605.06', 526605000, 'Premios de puntualidad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605070, 'SAT/24-2019', 'GASTOS', '605.07', 526605000, 'Vacaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605080, 'SAT/24-2019', 'GASTOS', '605.08', 526605000, 'Prima vacacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605090, 'SAT/24-2019', 'GASTOS', '605.09', 526605000, 'Prima dominical', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605100, 'SAT/24-2019', 'GASTOS', '605.1', 526605000, 'Días festivos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605110, 'SAT/24-2019', 'GASTOS', '605.11', 526605000, 'Gratificaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605120, 'SAT/24-2019', 'GASTOS', '605.12', 526605000, 'Primas de antigüedad', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605130, 'SAT/24-2019', 'GASTOS', '605.13', 526605000, 'Aguinaldo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605140, 'SAT/24-2019', 'GASTOS', '605.14', 526605000, 'Indemnizaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605150, 'SAT/24-2019', 'GASTOS', '605.15', 526605000, 'Destajo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605160, 'SAT/24-2019', 'GASTOS', '605.16', 526605000, 'Despensa', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605170, 'SAT/24-2019', 'GASTOS', '605.17', 526605000, 'Transporte', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605180, 'SAT/24-2019', 'GASTOS', '605.18', 526605000, 'Servicio médico', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605190, 'SAT/24-2019', 'GASTOS', '605.19', 526605000, 'Ayuda en gastos funerarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605260, 'SAT/24-2019', 'GASTOS', '605.2', 526605000, 'Fondo de ahorro', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605210, 'SAT/24-2019', 'GASTOS', '605.21', 526605000, 'Cuotas sindicales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605220, 'SAT/24-2019', 'GASTOS', '605.22', 526605000, 'PTU', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605230, 'SAT/24-2019', 'GASTOS', '605.23', 526605000, 'Estímulo al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605240, 'SAT/24-2019', 'GASTOS', '605.24', 526605000, 'Previsión social', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605250, 'SAT/24-2019', 'GASTOS', '605.25', 526605000, 'Aportaciones para el plan de jubilación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605265, 'SAT/24-2019', 'GASTOS', '605.26', 526605000, 'Otras prestaciones al personal', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605270, 'SAT/24-2019', 'GASTOS', '605.27', 526605000, 'Asimilados a salarios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605280, 'SAT/24-2019', 'GASTOS', '605.28', 526605000, 'Cuotas al IMSS', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605290, 'SAT/24-2019', 'GASTOS', '605.29', 526605000, 'Aportaciones al infonavit', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605300, 'SAT/24-2019', 'GASTOS', '605.3', 526605000, 'Aportaciones al SAR', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526605310, 'SAT/24-2019', 'GASTOS', '605.31', 526605000, 'Otros costos de mano de obra directa', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526606000, 'SAT/24-2019', 'GASTOS', '606', 526600000, 'Facilidades administrativas fiscales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526606010, 'SAT/24-2019', 'GASTOS', '606.01', 526606000, 'Facilidades administrativas fiscales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526607000, 'SAT/24-2019', 'GASTOS', '607', 526600000, 'Participación de los trabajadores en las utilidades', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526607010, 'SAT/24-2019', 'GASTOS', '607.01', 526607000, 'Participación de los trabajadores en las utilidades', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526608000, 'SAT/24-2019', 'GASTOS', '608', 526600000, 'Participación en resultados de subsidiarias', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526608010, 'SAT/24-2019', 'GASTOS', '608.01', 526608000, 'Participación en resultados de subsidiarias', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526609000, 'SAT/24-2019', 'GASTOS', '609', 526600000, 'Participación en resultados de asociadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526609010, 'SAT/24-2019', 'GASTOS', '609.01', 526609000, 'Participación en resultados de asociadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526610000, 'SAT/24-2019', 'GASTOS', '610', 526600000, 'Participación de los trabajadores en las utilidades diferida', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526610010, 'SAT/24-2019', 'GASTOS', '610.01', 526610000, 'Participación de los trabajadores en las utilidades diferida', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526611000, 'SAT/24-2019', 'GASTOS', '611', 526600000, 'Impuesto Sobre la renta', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526611010, 'SAT/24-2019', 'GASTOS', '611.01', 526611000, 'Impuesto Sobre la renta', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526611020, 'SAT/24-2019', 'GASTOS', '611.02', 526611000, 'Impuesto Sobre la renta por remanente distribuible', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526612000, 'SAT/24-2019', 'GASTOS', '612', 526600000, 'Gastos no deducibles para CUFIN', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526612010, 'SAT/24-2019', 'GASTOS', '612.01', 526612000, 'Gastos no deducibles para CUFIN', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613000, 'SAT/24-2019', 'GASTOS', '613', 526600000, 'Depreciación contable', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613010, 'SAT/24-2019', 'GASTOS', '613.01', 526613000, 'Depreciación de edificios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613020, 'SAT/24-2019', 'GASTOS', '613.02', 526613000, 'Depreciación de maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613030, 'SAT/24-2019', 'GASTOS', '613.03', 526613000, 'Depreciación de automóviles, autobuses, camiones de carga, tractocamiones, montacargas y remolques', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613040, 'SAT/24-2019', 'GASTOS', '613.04', 526613000, 'Depreciación de mobiliario y equipo de oficina', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613050, 'SAT/24-2019', 'GASTOS', '613.05', 526613000, 'Depreciación de equipo de cómputo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613060, 'SAT/24-2019', 'GASTOS', '613.06', 526613000, 'Depreciación de equipo de comunicación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613070, 'SAT/24-2019', 'GASTOS', '613.07', 526613000, 'Depreciación de activos biológicos, vegetales y semovientes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613080, 'SAT/24-2019', 'GASTOS', '613.08', 526613000, 'Depreciación de otros activos fijos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613090, 'SAT/24-2019', 'GASTOS', '613.09', 526613000, 'Depreciación de ferrocarriles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613100, 'SAT/24-2019', 'GASTOS', '613.1', 526613000, 'Depreciación de embarcaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613110, 'SAT/24-2019', 'GASTOS', '613.11', 526613000, 'Depreciación de aviones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613120, 'SAT/24-2019', 'GASTOS', '613.12', 526613000, 'Depreciación de troqueles, moldes, matrices y herramental', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613130, 'SAT/24-2019', 'GASTOS', '613.13', 526613000, 'Depreciación de equipo de comunicaciones telefónicas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613140, 'SAT/24-2019', 'GASTOS', '613.14', 526613000, 'Depreciación de equipo de comunicación satelital', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613150, 'SAT/24-2019', 'GASTOS', '613.15', 526613000, 'Depreciación de equipo de adaptaciones para personas con capacidades diferentes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613160, 'SAT/24-2019', 'GASTOS', '613.16', 526613000, 'Depreciación de maquinaria y equipo de generación de energía de fuentes renovables o de sistemas de cogeneración de electricidad eficiente', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613170, 'SAT/24-2019', 'GASTOS', '613.17', 526613000, 'Depreciación de adaptaciones y mejoras', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526613180, 'SAT/24-2019', 'GASTOS', '613.18', 526613000, 'Depreciación de otra maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526614000, 'SAT/24-2019', 'GASTOS', '614', 526600000, 'Amortización contable', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526614010, 'SAT/24-2019', 'GASTOS', '614.01', 526614000, 'Amortización de gastos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526614020, 'SAT/24-2019', 'GASTOS', '614.02', 526614000, 'Amortización de gastos pre operativos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526614030, 'SAT/24-2019', 'GASTOS', '614.03', 526614000, 'Amortización de regalías, asistencia técnica y otros gastos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526614040, 'SAT/24-2019', 'GASTOS', '614.04', 526614000, 'Amortización de activos intangibles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526614050, 'SAT/24-2019', 'GASTOS', '614.05', 526614000, 'Amortización de gastos de organización', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526614060, 'SAT/24-2019', 'GASTOS', '614.06', 526614000, 'Amortización de investigación y desarrollo de mercado', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526614070, 'SAT/24-2019', 'GASTOS', '614.07', 526614000, 'Amortización de marcas y patentes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526614080, 'SAT/24-2019', 'GASTOS', '614.08', 526614000, 'Amortización de crédito mercantil', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526614090, 'SAT/24-2019', 'GASTOS', '614.09', 526614000, 'Amortización de gastos de instalación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526614100, 'SAT/24-2019', 'GASTOS', '614.1', 526614000, 'Amortización de otros activos diferidos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526700000, 'SAT/24-2019', 'RESULTADOS', '700', 0, 'Resultado integral de financiamiento', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526701000, 'SAT/24-2019', 'RESULTADOS', '701', 526700000, 'Gastos financieros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526701010, 'SAT/24-2019', 'RESULTADOS', '701.01', 526701000, 'Pérdida cambiaria', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526701020, 'SAT/24-2019', 'RESULTADOS', '701.02', 526701000, 'Pérdida cambiaria nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526701030, 'SAT/24-2019', 'RESULTADOS', '701.03', 526701000, 'Pérdida cambiaria extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526701040, 'SAT/24-2019', 'RESULTADOS', '701.04', 526701000, 'Intereses a cargo bancario nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526701050, 'SAT/24-2019', 'RESULTADOS', '701.05', 526701000, 'Intereses a cargo bancario extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526701060, 'SAT/24-2019', 'RESULTADOS', '701.06', 526701000, 'Intereses a cargo de personas físicas nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526701070, 'SAT/24-2019', 'RESULTADOS', '701.07', 526701000, 'Intereses a cargo de personas físicas extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526701080, 'SAT/24-2019', 'RESULTADOS', '701.08', 526701000, 'Intereses a cargo de personas morales nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526701090, 'SAT/24-2019', 'RESULTADOS', '701.09', 526701000, 'Intereses a cargo de personas morales extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526701100, 'SAT/24-2019', 'RESULTADOS', '701.1', 526701000, 'Comisiones bancarias', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526701110, 'SAT/24-2019', 'RESULTADOS', '701.11', 526701000, 'Otros gastos financieros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526702000, 'SAT/24-2019', 'RESULTADOS', '702', 526700000, 'Productos financieros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526702010, 'SAT/24-2019', 'RESULTADOS', '702.01', 526702000, 'Utilidad cambiaria', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526702020, 'SAT/24-2019', 'RESULTADOS', '702.02', 526702000, 'Utilidad cambiaria nacional parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526702030, 'SAT/24-2019', 'RESULTADOS', '702.03', 526702000, 'Utilidad cambiaria extranjero parte relacionada', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526702040, 'SAT/24-2019', 'RESULTADOS', '702.04', 526702000, 'Intereses a favor bancarios nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526702050, 'SAT/24-2019', 'RESULTADOS', '702.05', 526702000, 'Intereses a favor bancarios extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526702060, 'SAT/24-2019', 'RESULTADOS', '702.06', 526702000, 'Intereses a favor de personas físicas nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526702070, 'SAT/24-2019', 'RESULTADOS', '702.07', 526702000, 'Intereses a favor de personas físicas extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526702080, 'SAT/24-2019', 'RESULTADOS', '702.08', 526702000, 'Intereses a favor de personas morales nacional', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526702090, 'SAT/24-2019', 'RESULTADOS', '702.09', 526702000, 'Intereses a favor de personas morales extranjero', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526702100, 'SAT/24-2019', 'RESULTADOS', '702.1', 526702000, 'Otros productos financieros', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703000, 'SAT/24-2019', 'RESULTADOS', '703', 526700000, 'Otros gastos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703010, 'SAT/24-2019', 'RESULTADOS', '703.01', 526703000, 'Pérdida en venta y/o baja de terrenos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703020, 'SAT/24-2019', 'RESULTADOS', '703.02', 526703000, 'Pérdida en venta y/o baja de edificios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703030, 'SAT/24-2019', 'RESULTADOS', '703.03', 526703000, 'Pérdida en venta y/o baja de maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703040, 'SAT/24-2019', 'RESULTADOS', '703.04', 526703000, 'Pérdida en venta y/o baja de automóviles, autobuses, camiones de carga, tractocamiones, montacargas y remolques', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703050, 'SAT/24-2019', 'RESULTADOS', '703.05', 526703000, 'Pérdida en venta y/o baja de mobiliario y equipo de oficina', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703060, 'SAT/24-2019', 'RESULTADOS', '703.06', 526703000, 'Pérdida en venta y/o baja de equipo de cómputo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703070, 'SAT/24-2019', 'RESULTADOS', '703.07', 526703000, 'Pérdida en venta y/o baja de equipo de comunicación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703080, 'SAT/24-2019', 'RESULTADOS', '703.08', 526703000, 'Pérdida en venta y/o baja de activos biológicos, vegetales y semovientes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703090, 'SAT/24-2019', 'RESULTADOS', '703.09', 526703000, 'Pérdida en venta y/o baja de otros activos fijos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703100, 'SAT/24-2019', 'RESULTADOS', '703.1', 526703000, 'Pérdida en venta y/o baja de ferrocarriles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703110, 'SAT/24-2019', 'RESULTADOS', '703.11', 526703000, 'Pérdida en venta y/o baja de embarcaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703120, 'SAT/24-2019', 'RESULTADOS', '703.12', 526703000, 'Pérdida en venta y/o baja de aviones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703130, 'SAT/24-2019', 'RESULTADOS', '703.13', 526703000, 'Pérdida en venta y/o baja de troqueles, moldes, matrices y herramental', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703140, 'SAT/24-2019', 'RESULTADOS', '703.14', 526703000, 'Pérdida en venta y/o baja de equipo de comunicaciones telefónicas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703150, 'SAT/24-2019', 'RESULTADOS', '703.15', 526703000, 'Pérdida en venta y/o baja de equipo de comunicación satelital', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703160, 'SAT/24-2019', 'RESULTADOS', '703.16', 526703000, 'Pérdida en venta y/o baja de equipo de adaptaciones para personas con capacidades diferentes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703170, 'SAT/24-2019', 'RESULTADOS', '703.17', 526703000, 'Pérdida en venta y/o baja de maquinaria y equipo de generación de energía de fuentes renovables o de sistemas de cogeneración de electricidad eficiente', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703180, 'SAT/24-2019', 'RESULTADOS', '703.18', 526703000, 'Pérdida en venta y/o baja de otra maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703190, 'SAT/24-2019', 'RESULTADOS', '703.19', 526703000, 'Pérdida por enajenación de acciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703200, 'SAT/24-2019', 'RESULTADOS', '703.2', 526703000, 'Pérdida por enajenación de partes sociales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526703210, 'SAT/24-2019', 'RESULTADOS', '703.21', 526703000, 'Otros gastos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704000, 'SAT/24-2019', 'RESULTADOS', '704', 526700000, 'Otros productos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704010, 'SAT/24-2019', 'RESULTADOS', '704.01', 526704000, 'Ganancia en venta y/o baja de terrenos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704020, 'SAT/24-2019', 'RESULTADOS', '704.02', 526704000, 'Ganancia en venta y/o baja de edificios', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704030, 'SAT/24-2019', 'RESULTADOS', '704.03', 526704000, 'Ganancia en venta y/o baja de maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704040, 'SAT/24-2019', 'RESULTADOS', '704.04', 526704000, 'Ganancia en venta y/o baja de automóviles, autobuses, camiones de carga, tractocamiones, montacargas y remolques', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704050, 'SAT/24-2019', 'RESULTADOS', '704.05', 526704000, 'Ganancia en venta y/o baja de mobiliario y equipo de oficina', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704060, 'SAT/24-2019', 'RESULTADOS', '704.06', 526704000, 'Ganancia en venta y/o baja de equipo de cómputo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704070, 'SAT/24-2019', 'RESULTADOS', '704.07', 526704000, 'Ganancia en venta y/o baja de equipo de comunicación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704080, 'SAT/24-2019', 'RESULTADOS', '704.08', 526704000, 'Ganancia en venta y/o baja de activos biológicos, vegetales y semovientes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704090, 'SAT/24-2019', 'RESULTADOS', '704.09', 526704000, 'Ganancia en venta y/o baja de otros activos fijos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704100, 'SAT/24-2019', 'RESULTADOS', '704.1', 526704000, 'Ganancia en venta y/o baja de ferrocarriles', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704110, 'SAT/24-2019', 'RESULTADOS', '704.11', 526704000, 'Ganancia en venta y/o baja de embarcaciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704120, 'SAT/24-2019', 'RESULTADOS', '704.12', 526704000, 'Ganancia en venta y/o baja de aviones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704130, 'SAT/24-2019', 'RESULTADOS', '704.13', 526704000, 'Ganancia en venta y/o baja de troqueles, moldes, matrices y herramental', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704140, 'SAT/24-2019', 'RESULTADOS', '704.14', 526704000, 'Ganancia en venta y/o baja de equipo de comunicaciones telefónicas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704150, 'SAT/24-2019', 'RESULTADOS', '704.15', 526704000, 'Ganancia en venta y/o baja de equipo de comunicación satelital', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704160, 'SAT/24-2019', 'RESULTADOS', '704.16', 526704000, 'Ganancia en venta y/o baja de equipo de adaptaciones para personas con capacidades diferentes', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704170, 'SAT/24-2019', 'RESULTADOS', '704.17', 526704000, 'Ganancia en venta de maquinaria y equipo de generación de energía de fuentes renovables o de sistemas de cogeneración de electricidad eficiente', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704180, 'SAT/24-2019', 'RESULTADOS', '704.18', 526704000, 'Ganancia en venta y/o baja de otra maquinaria y equipo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704190, 'SAT/24-2019', 'RESULTADOS', '704.19', 526704000, 'Ganancia por enajenación de acciones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704200, 'SAT/24-2019', 'RESULTADOS', '704.2', 526704000, 'Ganancia por enajenación de partes sociales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704210, 'SAT/24-2019', 'RESULTADOS', '704.21', 526704000, 'Ingresos por estímulos fiscales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704220, 'SAT/24-2019', 'RESULTADOS', '704.22', 526704000, 'Ingresos por condonación de adeudo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526704230, 'SAT/24-2019', 'RESULTADOS', '704.23', 526704000, 'Otros productos', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526800000, 'SAT/24-2019', 'CTAS DE ORDEN', '800', 0, 'Cuentas de orden', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526801000, 'SAT/24-2019', 'CTAS DE ORDEN', '801', 526800000, 'UFIN del ejercicio', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526801010, 'SAT/24-2019', 'CTAS DE ORDEN', '801.01', 526801000, 'UFIN', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526801020, 'SAT/24-2019', 'CTAS DE ORDEN', '801.02', 526801000, 'Contra cuenta UFIN', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526802000, 'SAT/24-2019', 'CTAS DE ORDEN', '802', 526800000, 'CUFIN del ejercicio', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526802010, 'SAT/24-2019', 'CTAS DE ORDEN', '802.01', 526802000, 'CUFIN', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526802020, 'SAT/24-2019', 'CTAS DE ORDEN', '802.02', 526802000, 'Contra cuenta CUFIN', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526803000, 'SAT/24-2019', 'CTAS DE ORDEN', '803', 526800000, 'CUFIN de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526803010, 'SAT/24-2019', 'CTAS DE ORDEN', '803.01', 526803000, 'CUFIN de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526803020, 'SAT/24-2019', 'CTAS DE ORDEN', '803.02', 526803000, 'Contra cuenta CUFIN de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526804000, 'SAT/24-2019', 'CTAS DE ORDEN', '804', 526800000, 'CUFINRE del ejercicio', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526804010, 'SAT/24-2019', 'CTAS DE ORDEN', '804.01', 526804000, 'CUFINRE', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526804020, 'SAT/24-2019', 'CTAS DE ORDEN', '804.02', 526804000, 'Contra cuenta CUFINRE', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526805000, 'SAT/24-2019', 'CTAS DE ORDEN', '805', 526800000, 'CUFINRE de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526805010, 'SAT/24-2019', 'CTAS DE ORDEN', '805.01', 526805000, 'CUFINRE de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526805020, 'SAT/24-2019', 'CTAS DE ORDEN', '805.02', 526805000, 'Contra cuenta CUFINRE de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526806000, 'SAT/24-2019', 'CTAS DE ORDEN', '806', 526800000, 'CUCA del ejercicio', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526806010, 'SAT/24-2019', 'CTAS DE ORDEN', '806.01', 526806000, 'CUCA', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526806020, 'SAT/24-2019', 'CTAS DE ORDEN', '806.02', 526806000, 'Contra cuenta CUCA', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526807000, 'SAT/24-2019', 'CTAS DE ORDEN', '807', 526800000, 'CUCA de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526807010, 'SAT/24-2019', 'CTAS DE ORDEN', '807.01', 526807000, 'CUCA de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526807020, 'SAT/24-2019', 'CTAS DE ORDEN', '807.02', 526807000, 'Contra cuenta CUCA de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526808000, 'SAT/24-2019', 'CTAS DE ORDEN', '808', 526800000, 'Ajuste anual por inflación acumulable', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526808010, 'SAT/24-2019', 'CTAS DE ORDEN', '808.01', 526808000, 'Ajuste anual por inflación acumulable', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526808020, 'SAT/24-2019', 'CTAS DE ORDEN', '808.02', 526808000, 'Acumulación del ajuste anual inflacionario', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526809000, 'SAT/24-2019', 'CTAS DE ORDEN', '809', 526800000, 'Ajuste anual por inflación deducible', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526809010, 'SAT/24-2019', 'CTAS DE ORDEN', '809.01', 526809000, 'Ajuste anual por inflación deducible', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526809020, 'SAT/24-2019', 'CTAS DE ORDEN', '809.02', 526809000, 'Deducción del ajuste anual inflacionario', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526810000, 'SAT/24-2019', 'CTAS DE ORDEN', '810', 526800000, 'Deducción de inversión', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526810010, 'SAT/24-2019', 'CTAS DE ORDEN', '810.01', 526810000, 'Deducción de inversión', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526810020, 'SAT/24-2019', 'CTAS DE ORDEN', '810.02', 526810000, 'Contra cuenta deducción de inversiones', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526811000, 'SAT/24-2019', 'CTAS DE ORDEN', '811', 526800000, 'Utilidad o pérdida fiscal en venta y/o baja de activo fijo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526811010, 'SAT/24-2019', 'CTAS DE ORDEN', '811.01', 526811000, 'Utilidad o pérdida fiscal en venta y/o baja de activo fijo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526811020, 'SAT/24-2019', 'CTAS DE ORDEN', '811.02', 526811000, 'Contra cuenta utilidad o pérdida fiscal en venta y/o baja de activo fijo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526812000, 'SAT/24-2019', 'CTAS DE ORDEN', '812', 526800000, 'Utilidad o pérdida fiscal en venta acciones o partes sociales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526812010, 'SAT/24-2019', 'CTAS DE ORDEN', '812.01', 526812000, 'Utilidad o pérdida fiscal en venta acciones o partes sociales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526812020, 'SAT/24-2019', 'CTAS DE ORDEN', '812.02', 526812000, 'Contra cuenta utilidad o pérdida fiscal en venta acciones o partes sociales', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526813000, 'SAT/24-2019', 'CTAS DE ORDEN', '813', 526800000, 'Pérdidas fiscales pendientes de amortizar actualizadas de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526813010, 'SAT/24-2019', 'CTAS DE ORDEN', '813.01', 526813000, 'Pérdidas fiscales pendientes de amortizar actualizadas de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526813020, 'SAT/24-2019', 'CTAS DE ORDEN', '813.02', 526813000, 'Actualización de pérdidas fiscales pendientes de amortizar de ejercicios anteriores', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526814000, 'SAT/24-2019', 'CTAS DE ORDEN', '814', 526800000, 'Mercancías recibidas en consignación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526814010, 'SAT/24-2019', 'CTAS DE ORDEN', '814.01', 526814000, 'Mercancías recibidas en consignación', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526814020, 'SAT/24-2019', 'CTAS DE ORDEN', '814.02', 526814000, 'Consignación de mercancías recibidas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526815000, 'SAT/24-2019', 'CTAS DE ORDEN', '815', 526800000, 'Crédito fiscal de IVA e IEPS por la importación de mercancías para empresas certificadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526815010, 'SAT/24-2019', 'CTAS DE ORDEN', '815.01', 526815000, 'Crédito fiscal de IVA e IEPS por la importación de mercancías', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526815020, 'SAT/24-2019', 'CTAS DE ORDEN', '815.02', 526815000, 'Importación de mercancías con aplicación de crédito fiscal de IVA e IEPS', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526816000, 'SAT/24-2019', 'CTAS DE ORDEN', '816', 526800000, 'Crédito fiscal de IVA e IEPS por la importación de activos fijos para empresas certificadas', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526816010, 'SAT/24-2019', 'CTAS DE ORDEN', '816.01', 526816000, 'Crédito fiscal de IVA e IEPS por la importación de activo fijo', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526816020, 'SAT/24-2019', 'CTAS DE ORDEN', '816.02', 526816000, 'Importación de activo fijo con aplicación de crédito fiscal de IVA e IEPS', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526899000, 'SAT/24-2019', 'CTAS DE ORDEN', '899', 526800000, 'Otras cuentas de orden', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526899010, 'SAT/24-2019', 'CTAS DE ORDEN', '899.01', 526899000, 'Otras cuentas de orden', 1 ); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 526899020, 'SAT/24-2019', 'CTAS DE ORDEN', '899.02', 526899000, 'Contra cuenta otras cuentas de orden', 1 ); diff --git a/htdocs/install/mysql/data/llx_c_actioncomm.sql b/htdocs/install/mysql/data/llx_c_actioncomm.sql index 9a0d8c223b6..47197af644d 100644 --- a/htdocs/install/mysql/data/llx_c_actioncomm.sql +++ b/htdocs/install/mysql/data/llx_c_actioncomm.sql @@ -30,7 +30,7 @@ -- Types action comm -- -delete from llx_c_actioncomm where id in (1,2,3,4,5,8,9,10,30,31,40,50); +delete from llx_c_actioncomm where id in (1,2,3,4,5,6,8,9,10,11,30,31,40,50); -- Code used from 3.3+ when type of event is used insert into llx_c_actioncomm (id, code, type, libelle, module, active, position) values ( 1,'AC_TEL','system','Phone call',NULL, 1, 2); insert into llx_c_actioncomm (id, code, type, libelle, module, active, position) values ( 2,'AC_FAX','system','Send Fax',NULL, 1, 3); @@ -48,3 +48,8 @@ insert into llx_c_actioncomm (id, code, type, libelle, module, active, position) -- Code used from 3.3+ when type of event is not used insert into llx_c_actioncomm (id, code, type, libelle, module, active, position) values ( 40,'AC_OTH_AUTO','systemauto','Other (automatically inserted events)',NULL, 1, 20); insert into llx_c_actioncomm (id, code, type, libelle, module, active, position) values ( 50,'AC_OTH','system','Other (manually inserted events)',NULL, 1, 5); + +INSERT INTO llx_c_actioncomm (id, code, type, libelle, module, active, position) VALUES ( 60,'AC_EO_ONLINECONF','module','Online/Virtual conference','conference@eventorganization', 1, 60); +INSERT INTO llx_c_actioncomm (id, code, type, libelle, module, active, position) VALUES ( 61,'AC_EO_INDOORCONF','module','Indoor conference','conference@eventorganization', 1, 61); +INSERT INTO llx_c_actioncomm (id, code, type, libelle, module, active, position) VALUES ( 62,'AC_EO_ONLINEBOOTH','module','Online/Virtual booth','booth@eventorganization', 1, 62); +INSERT INTO llx_c_actioncomm (id, code, type, libelle, module, active, position) VALUES ( 63,'AC_EO_INDOORBOOTH','module','Indoor booth','booth@eventorganization', 1, 63); diff --git a/htdocs/install/mysql/data/llx_c_chargesociales.sql b/htdocs/install/mysql/data/llx_c_chargesociales.sql index 324223b274d..b728d9c6414 100644 --- a/htdocs/install/mysql/data/llx_c_chargesociales.sql +++ b/htdocs/install/mysql/data/llx_c_chargesociales.sql @@ -33,19 +33,19 @@ -- -- France -- -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 1, 'Allocations familiales', 1,1,'TAXFAM' ,'1'); -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 2, 'CSG Deductible', 1,1,'TAXCSGD' ,'1'); -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 3, 'CSG/CRDS NON Deductible',0,1,'TAXCSGND' ,'1'); -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 10, 'Taxe apprentissage', 0,1,'TAXAPP' ,'1'); -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 11, 'Taxe professionnelle', 0,1,'TAXPRO' ,'1'); -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 12, 'Cotisation fonciere des entreprises', 0,1,'TAXCFE' ,'1'); -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 13, 'Cotisation sur la valeur ajoutee des entreprises', 0,1,'TAXCVAE' ,'1'); -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 20, 'Impots locaux/fonciers', 0,1,'TAXFON' ,'1'); -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 25, 'Impots revenus', 0,1,'TAXREV' ,'1'); -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 30, 'Assurance Sante', 0,1,'TAXSECU' ,'1'); -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 40, 'Mutuelle', 0,1,'TAXMUT' ,'1'); -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 50, 'Assurance vieillesse', 0,1,'TAXRET' ,'1'); -insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 60, 'Assurance Chomage', 0,1,'TAXCHOM' ,'1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 1, 'Securite sociale (URSSAF / MSA)', 1, 1, 'TAXSECU', '1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 2, 'Securite sociale des indépendants (URSSAF)', 1, 1, 'TAXSSI', '1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 10, 'Taxe apprentissage', 1, 1, 'TAXAPP', '1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 11, 'Formation professionnelle continue', 1, 1, 'TAXFPC', '1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 12, 'Cotisation fonciere des entreprises (CFE)', 1, 1, 'TAXCFE', '1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 13, 'Cotisation sur la valeur ajoutee des entreprises (CVAE)', 1, 1, 'TAXCVAE', '1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 20, 'Taxe fonciere', 1, 1, 'TAXFON', '1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 25, 'Prelevement à la source (PAS)', 0, 1, 'TAXPAS', '1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 30, 'Prevoyance', 1, 1,'TAXPREV', '1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 40, 'Mutuelle', 1, 1,'TAXMUT', '1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 50, 'Retraite', 1, 1,'TAXRET', '1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 60, 'Taxe sur vehicule societe (TVS)', 0, 1, 'TAXTVS', '1'); +insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays) values ( 70, 'impôts sur les sociétés (IS)', 0, 1, 'TAXIS', '1'); -- -- Belgique diff --git a/htdocs/install/mysql/data/llx_c_currencies.sql b/htdocs/install/mysql/data/llx_c_currencies.sql index d05015721c8..478c263af4c 100644 --- a/htdocs/install/mysql/data/llx_c_currencies.sql +++ b/htdocs/install/mysql/data/llx_c_currencies.sql @@ -73,6 +73,7 @@ INSERT INTO llx_c_currencies ( code_iso, unicode, active, label ) VALUES ( 'XCD' INSERT INTO llx_c_currencies ( code_iso, unicode, active, label ) VALUES ( 'EGP', '[163]', 1, 'Egypt Pound'); INSERT INTO llx_c_currencies ( code_iso, unicode, active, label ) VALUES ( 'SVC', '[36]', 1, 'El Salvador Colon'); INSERT INTO llx_c_currencies ( code_iso, unicode, active, label ) VALUES ( 'EEK', '[107,114]', 1, 'Estonia Kroon'); +INSERT INTO llx_c_currencies ( code_iso, unicode, active, label ) VALUES ( 'ETB', NULL, 1, 'Ethiopian Birr'); INSERT INTO llx_c_currencies ( code_iso, unicode, active, label ) VALUES ( 'EUR', '[8364]', 1, 'Euro Member Countries'); INSERT INTO llx_c_currencies ( code_iso, unicode, active, label ) VALUES ( 'FKP', '[163]', 1, 'Falkland Islands (Malvinas) Pound'); INSERT INTO llx_c_currencies ( code_iso, unicode, active, label ) VALUES ( 'FJD', '[36]', 1, 'Fiji Dollar'); diff --git a/htdocs/install/mysql/data/llx_c_email_templates.sql b/htdocs/install/mysql/data/llx_c_email_templates.sql index 253ace246e7..713a7f31a4f 100644 --- a/htdocs/install/mysql/data/llx_c_email_templates.sql +++ b/htdocs/install/mysql/data/llx_c_email_templates.sql @@ -32,3 +32,9 @@ INSERT INTO llx_c_email_templates (entity,module,type_template,lang,private,fk_u INSERT INTO llx_c_email_templates (entity,module,type_template,lang,private,fk_user,datec,label,position,enabled,active,topic,content,content_lines,joinfiles) VALUES (0,'recruitment','recruitmentcandidature_send','',0,null,null,'(AnswerCandidature)' ,100,'$conf->recruitment->enabled',1,'[__[MAIN_INFO_SOCIETE_NOM]__] __(YourCandidature)__', '__(Hello)__ __CANDIDATE_FULLNAME__,<br><br>\n\n__(YourCandidatureAnswerMessage)__<br>__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__\n<br><br>\n__(Sincerely)__<br>__USER_SIGNATURE__',null, 0); +INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailAskConf', 10, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailAskConf)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventConfRequestWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null); +INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailAskBooth', 20, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailAskBooth)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBoothRequestWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null); +INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailSubsBooth', 30, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailSubsBooth)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBoothSubscriptionWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null); +INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailSubsEvent', 40, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailSubsEvent)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventEventSubscriptionWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null); +INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationMassEmailAttendees', 50, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationMassEmailAttendes)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBulkMailToAttendees)__<br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null); +INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationMassEmailSpeakers', 60, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationMassEmailSpeakers)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBulkMailToSpeakers)__<br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null); diff --git a/htdocs/install/mysql/data/llx_c_format_cards.sql b/htdocs/install/mysql/data/llx_c_format_cards.sql index 77cdcd6e904..fc249e9d629 100644 --- a/htdocs/install/mysql/data/llx_c_format_cards.sql +++ b/htdocs/install/mysql/data/llx_c_format_cards.sql @@ -25,7 +25,7 @@ INSERT INTO llx_c_format_cards (rowid, code, name, paper_size, orientation, metr INSERT INTO llx_c_format_cards (rowid, code, name, paper_size, orientation, metric, leftmargin, topmargin, nx, ny, spacex, spacey, width, height, font_size, custom_x, custom_y, active) VALUES (2, '5161', 'Avery-5161, WL-75WX', 'letter', 'P', 'mm', 4.44500000, 12.70000000, 2, 10, 3.96800000, 0.00000000, 101.60000000, 25.40000000, 7, 0.00000000, 0.00000000, 1); INSERT INTO llx_c_format_cards (rowid, code, name, paper_size, orientation, metric, leftmargin, topmargin, nx, ny, spacex, spacey, width, height, font_size, custom_x, custom_y, active) VALUES (3, '5162', 'Avery-5162, WL-100WX', 'letter', 'P', 'mm', 3.87350000, 22.35200000, 2, 7, 4.95400000, 0.00000000, 101.60000000, 33.78100000, 8, 0.00000000, 0.00000000, 1); INSERT INTO llx_c_format_cards (rowid, code, name, paper_size, orientation, metric, leftmargin, topmargin, nx, ny, spacex, spacey, width, height, font_size, custom_x, custom_y, active) VALUES (4, '5163', 'Avery-5163, WL-125WX', 'letter', 'P', 'mm', 4.57200000, 12.70000000, 2, 5, 3.55600000, 0.00000000, 101.60000000, 50.80000000, 10, 0.00000000, 0.00000000, 1); -INSERT INTO llx_c_format_cards (rowid, code, name, paper_size, orientation, metric, leftmargin, topmargin, nx, ny, spacex, spacey, width, height, font_size, custom_x, custom_y, active) VALUES (5, '5164', '5164 (Letter)', 'letter', 'P', 'in', 0.14800000, 0.50000000, 2, 3, 0.20310000, 0.00000000, 4.00000000, 3.33000000, 12, 0.00000000, 0.00000000, 0); +INSERT INTO llx_c_format_cards (rowid, code, name, paper_size, orientation, metric, leftmargin, topmargin, nx, ny, spacex, spacey, width, height, font_size, custom_x, custom_y, active) VALUES (5, '5164', 'Avery-5164 (inch)', 'letter', 'P', 'in', 0.14800000, 0.50000000, 2, 3, 0.20310000, 0.00000000, 4.00000000, 3.33000000, 12, 0.00000000, 0.00000000, 0); INSERT INTO llx_c_format_cards (rowid, code, name, paper_size, orientation, metric, leftmargin, topmargin, nx, ny, spacex, spacey, width, height, font_size, custom_x, custom_y, active) VALUES (6, '8600', 'Avery-8600', 'letter', 'P', 'mm', 7.10000000, 19.00000000, 3, 10, 9.50000000, 3.10000000, 66.60000000, 25.40000000, 7, 0.00000000, 0.00000000, 1); INSERT INTO llx_c_format_cards (rowid, code, name, paper_size, orientation, metric, leftmargin, topmargin, nx, ny, spacex, spacey, width, height, font_size, custom_x, custom_y, active) VALUES (7, '99012', 'DYMO 99012 89*36mm', 'custom', 'L', 'mm', 1.00000000, 1.00000000, 1, 1, 0.00000000, 0.00000000, 36.00000000, 89.00000000, 10, 36.00000000, 89.00000000, 1); INSERT INTO llx_c_format_cards (rowid, code, name, paper_size, orientation, metric, leftmargin, topmargin, nx, ny, spacex, spacey, width, height, font_size, custom_x, custom_y, active) VALUES (8, '99014', 'DYMO 99014 101*54mm', 'custom', 'L', 'mm', 1.00000000, 1.00000000, 1, 1, 0.00000000, 0.00000000, 54.00000000, 101.00000000, 10, 54.00000000, 101.00000000, 1); diff --git a/htdocs/install/mysql/data/llx_c_tva.sql b/htdocs/install/mysql/data/llx_c_tva.sql index 7156812fb01..72746ac99ea 100644 --- a/htdocs/install/mysql/data/llx_c_tva.sql +++ b/htdocs/install/mysql/data/llx_c_tva.sql @@ -23,15 +23,21 @@ -- along with this program. If not, see <https://www.gnu.org/licenses/>. -- --- +-- -- Ne pas placer de commentaire en fin de ligne, ce fichier est parsé lors -- de l'install et tous les sigles '--' sont supprimés. -- -- --- Taux TVA --- Source des taux: http://fr.wikipedia.org/wiki/Taxe_sur_la_valeur_ajout%C3%A9e +-- FR: +-- Taux TVA +-- Source des taux: https://fr.wikipedia.org/wiki/Taxe_sur_la_valeur_ajout%C3%A9e -- +-- EN: +-- VAT - value-added tax +-- Source: https://en.wikipedia.org/wiki/Value-added_tax +-- + delete from llx_c_tva; diff --git a/htdocs/install/mysql/data/llx_const.sql b/htdocs/install/mysql/data/llx_const.sql index 7cd039a2c19..ed5449c0bd3 100644 --- a/htdocs/install/mysql/data/llx_const.sql +++ b/htdocs/install/mysql/data/llx_const.sql @@ -56,7 +56,7 @@ insert into llx_const (name, value, type, note, visible, entity) values ('MAIN_M -- -- IHM -- -insert into llx_const (name, value, type, note, visible, entity) values ('MAIN_SIZE_LISTE_LIMIT','25','chaine','Maximum length of lists',0,0); +insert into llx_const (name, value, type, note, visible, entity) values ('MAIN_SIZE_LISTE_LIMIT','20','chaine','Maximum length of lists',0,0); insert into llx_const (name, value, type, note, visible, entity) values ('MAIN_SIZE_SHORTLIST_LIMIT','3','chaine','Maximum length of short lists',0,0); insert into llx_const (name, value, type, note, visible, entity) values ('MAIN_MENU_STANDARD','eldy_menu.php','chaine','Menu manager for internal users',0,0); diff --git a/htdocs/install/mysql/migration/12.0.0-13.0.0.sql b/htdocs/install/mysql/migration/12.0.0-13.0.0.sql index 9658d6c3051..abbeadf7166 100644 --- a/htdocs/install/mysql/migration/12.0.0-13.0.0.sql +++ b/htdocs/install/mysql/migration/12.0.0-13.0.0.sql @@ -328,7 +328,7 @@ ALTER TABLE llx_product MODIFY COLUMN desiredstock float; ALTER TABLE llx_product_warehouse_properties MODIFY COLUMN seuil_stock_alerte float; ALTER TABLE llx_product_warehouse_properties MODIFY COLUMN desiredstock float; -ALTER TABLE llx_product ADD COLUMN fk_state integer DEFAULT NULL; +ALTER TABLE llx_product ADD COLUMN fk_state integer DEFAULT NULL AFTER fk_country; ALTER TABLE llx_projet ADD COLUMN email_msgid varchar(255); ALTER TABLE llx_ticket ADD COLUMN email_msgid varchar(255); @@ -580,3 +580,11 @@ insert into llx_c_action_trigger (code,label,description,elementtype,rang) value -- Removed no more used function -- VPGSQL8.2 DROP FUNCTION IF EXISTS update_modified_column_date_m CASCADE; + +insert into llx_c_actioncomm (id, code, type, libelle, module, active, position) values ( 6,'AC_EMAIL_IN','system','reception Email',NULL, 1, 4); + + +-- VMYSQL4.3 ALTER TABLE llx_accounting_bookkeeping MODIFY COLUMN montant double(24,8) NULL; +-- VPGSQL8.2 ALTER TABLE llx_accounting_bookkeeping ALTER COLUMN montant DROP NOT NULL; + + diff --git a/htdocs/install/mysql/migration/13.0.0-14.0.0.sql b/htdocs/install/mysql/migration/13.0.0-14.0.0.sql index 0aa6804daf6..2e60f214c77 100644 --- a/htdocs/install/mysql/migration/13.0.0-14.0.0.sql +++ b/htdocs/install/mysql/migration/13.0.0-14.0.0.sql @@ -30,13 +30,35 @@ -- Missing in v13 or lower +ALTER TABLE llx_asset CHANGE COLUMN amount amount_ht double(24,8) DEFAULT NULL; +ALTER TABLE llx_asset ADD COLUMN amount_vat double(24,8) DEFAULT NULL; + ALTER TABLE llx_supplier_proposal_extrafields ADD INDEX idx_supplier_proposal_extrafields (fk_object); ALTER TABLE llx_supplier_proposaldet_extrafields ADD INDEX idx_supplier_proposaldet_extrafields (fk_object); ALTER TABLE llx_asset_extrafields ADD INDEX idx_asset_extrafields (fk_object); +insert into llx_c_actioncomm (id, code, type, libelle, module, active, position) values ( 6,'AC_EMAIL_IN','system','reception Email',NULL, 1, 4); + +-- VMYSQL4.3 ALTER TABLE llx_accounting_bookkeeping MODIFY COLUMN montant double(24,8) NULL; +-- VPGSQL8.2 ALTER TABLE llx_accounting_bookkeeping ALTER COLUMN montant DROP NOT NULL; + +UPDATE llx_c_country SET eec = 1 WHERE code IN ('AT','BE','BG','CY','CZ','DE','DK','EE','ES','FI','FR','GR','HR','NL','HU','IE','IM','IT','LT','LU','LV','MC','MT','PL','PT','RO','SE','SK','SI'); + + -- For v14 +ALTER TABLE llx_oauth_token ADD COLUMN restricted_ips varchar(200); +ALTER TABLE llx_oauth_token ADD COLUMN datec datetime DEFAULT NULL; +ALTER TABLE llx_oauth_token ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; + +ALTER TABLE llx_events ADD COLUMN authentication_method varchar(64) NULL; +ALTER TABLE llx_events ADD COLUMN fk_oauth_token integer NULL; + +ALTER TABLE llx_mailing_cibles MODIFY COLUMN tag varchar(64) NULL; +ALTER TABLE llx_mailing_cibles ADD INDEX idx_mailing_cibles_tag (tag); + + ALTER TABLE llx_c_availability ADD COLUMN position integer NOT NULL DEFAULT 0; ALTER TABLE llx_adherent ADD COLUMN ref varchar(30) AFTER rowid; @@ -121,7 +143,8 @@ ALTER TABLE llx_societe ADD INDEX idx_societe_warehouse(fk_warehouse); -- VMYSQL4.3 ALTER TABLE llx_societe MODIFY COLUMN fk_typent integer NULL; -- VPGSQL8.2 ALTER TABLE llx_societe ALTER COLUMN fk_typent DROP NOT NULL; -UPDATE llx_societe SET fk_typent=NULL WHERE fk_typent=0; +UPDATE llx_societe SET fk_typent=NULL, tms=tms WHERE fk_typent=0; + DELETE FROM llx_c_typent WHERE code='TE_UNKNOWN'; ALTER TABLE llx_socpeople MODIFY poste varchar(255); @@ -130,6 +153,9 @@ ALTER TABLE llx_menu ADD COLUMN prefix varchar(255) NULL AFTER titre; ALTER TABLE llx_chargesociales ADD COLUMN fk_user integer DEFAULT NULL; +ALTER TABLE llx_mrp_production ADD COLUMN origin_id integer AFTER fk_mo; +ALTER TABLE llx_mrp_production ADD COLUMN origin_type varchar(10) AFTER origin_id; + ALTER TABLE llx_fichinter ADD COLUMN last_main_doc varchar(255) AFTER model_pdf; ALTER TABLE llx_projet ADD COLUMN last_main_doc varchar(255) AFTER model_pdf; @@ -153,10 +179,97 @@ create table llx_payment_vat ALTER TABLE llx_tva ADD COLUMN paye smallint default 1 NOT NULL; ALTER TABLE llx_tva ADD COLUMN fk_account integer; ---INSERT INTO llx_payment_vat (fk_tva, datec, datep, amount, fk_typepaiement, num_paiement, note, fk_bank, fk_user_creat, fk_user_modif) SELECT rowid, NOW(), datep, amount, COALESCE(fk_typepayment, 0), num_payment, '', fk_bank, fk_user_creat, fk_user_modif FROM llx_tva; +INSERT INTO llx_payment_vat (rowid, fk_tva, datec, datep, amount, fk_typepaiement, num_paiement, note, fk_bank, fk_user_creat, fk_user_modif) SELECT rowid, rowid, NOW(), datep, amount, COALESCE(fk_typepayment, 0), num_payment, 'Created automatically by migration v13 to v14', fk_bank, fk_user_creat, fk_user_modif FROM llx_tva WHERE fk_bank IS NOT NULL; --UPDATE llx_bank_url as url INNER JOIN llx_tva tva ON tva.rowid = url.url_id SET url.type = 'vat', url.label = CONCAT('(', tva.label, ')') WHERE type = 'payment_vat'; --INSERT INTO llx_bank_url (fk_bank, url_id, url, label, type) SELECT b.fk_bank, ptva.rowid, REPLACE(b.url, 'tva/card.php', 'payment_vat/card.php'), '(paiement)', 'payment_vat' FROM llx_bank_url b INNER JOIN llx_tva tva ON (tva.fk_bank = b.fk_bank) INNER JOIN llx_payment_vat ptva on (ptva.fk_bank = b.fk_bank) WHERE type = 'vat'; --ALTER TABLE llx_tva DROP COLUMN fk_bank; ALTER TABLE llx_tva ALTER COLUMN paye SET DEFAULT 0; + + +INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailAskConf', 10, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailAskConf)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventConfRequestWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null); +INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailAskBooth', 20, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailAskBooth)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBoothRequestWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null); +INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailSubsBooth', 30, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailSubsBooth)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBoothSubscriptionWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null); +INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailSubsEvent', 40, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailSubsEvent)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventEventSubscriptionWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null); +INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationMassEmailAttendes', 50, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationMassEmailAttendes)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBulkMailToAttendees)__<br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null); +INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationMassEmailSpeakers', 60, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationMassEmailSpeakers)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBulkMailToSpeakers)__<br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null); + +ALTER TABLE llx_projet ADD COLUMN accept_conference_suggestions integer DEFAULT 0; +ALTER TABLE llx_projet ADD COLUMN accept_booth_suggestions integer DEFAULT 0; +ALTER TABLE llx_projet ADD COLUMN price_registration double(24,8); +ALTER TABLE llx_projet ADD COLUMN price_booth double(24,8); + +ALTER TABLE llx_actioncomm ADD COLUMN num_vote integer DEFAULT NULL AFTER reply_to; +ALTER TABLE llx_actioncomm ADD COLUMN event_paid smallint NOT NULL DEFAULT 0 AFTER num_vote; +ALTER TABLE llx_actioncomm ADD COLUMN status smallint NOT NULL DEFAULT 0 AFTER event_paid; +ALTER TABLE llx_actioncomm ADD COLUMN ref varchar(30) AFTER id; +UPDATE llx_actioncomm SET ref = id WHERE ref = '' OR ref IS NULL; +ALTER TABLE llx_actioncomm MODIFY COLUMN ref varchar(30) NOT NULL; +ALTER TABLE llx_actioncomm ADD UNIQUE INDEX uk_actioncomm_ref (ref, entity); + +ALTER TABLE llx_c_actioncomm MODIFY code varchar(50) NOT NULL; +ALTER TABLE llx_c_actioncomm MODIFY module varchar(50) DEFAULT NULL; + +INSERT INTO llx_c_actioncomm (id, code, type, libelle, module, active, position) VALUES ( 60,'AC_EO_ONLINECONF','module','Online/Virtual conference','conference@eventorganization', 1, 60); +INSERT INTO llx_c_actioncomm (id, code, type, libelle, module, active, position) VALUES ( 61,'AC_EO_INDOORCONF','module','Indoor conference','conference@eventorganization', 1, 61); +INSERT INTO llx_c_actioncomm (id, code, type, libelle, module, active, position) VALUES ( 62,'AC_EO_ONLINEBOOTH','module','Online/Virtual booth','booth@eventorganization', 1, 62); +INSERT INTO llx_c_actioncomm (id, code, type, libelle, module, active, position) VALUES ( 63,'AC_EO_INDOORBOOTH','module','Indoor booth','booth@eventorganization', 1, 63); +-- Code enhanced - Standardize field name +ALTER TABLE llx_commande CHANGE COLUMN tva total_tva double(24,8) default 0; +ALTER TABLE llx_supplier_proposal CHANGE COLUMN tva total_tva double(24,8) default 0; +ALTER TABLE llx_supplier_proposal CHANGE COLUMN total total_ttc double(24,8) default 0; +ALTER TABLE llx_propal CHANGE COLUMN tva total_tva double(24,8) default 0; +ALTER TABLE llx_propal CHANGE COLUMN total total_ttc double(24,8) default 0; +ALTER TABLE llx_commande_fournisseur CHANGE COLUMN tva total_tva double(24,8) default 0; + + +--VMYSQL4.3 ALTER TABLE llx_c_civility CHANGE COLUMN rowid rowid INTEGER NOT NULL AUTO_INCREMENT; +--VPGSQL8.2 CREATE SEQUENCE llx_c_civility_rowid_seq OWNED BY llx_c_civility.rowid; +--VPGSQL8.2 ALTER TABLE llx_c_civility ALTER COLUMN rowid SET DEFAULT nextval('llx_c_civility_rowid_seq'); +--VPGSQL8.2 SELECT setval('llx_c_civility_rowid_seq', MAX(rowid)) FROM llx_c_civility; + + +-- Change for salary intent table +create table llx_salary +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + ref varchar(30) NULL, -- payment reference number (currently NULL because there is no numbering manager yet) + label varchar(255), + tms timestamp, + datec datetime, -- Create date + fk_user integer NOT NULL, + datep date, -- payment date + datev date, -- value date (this field should not be here, only into bank tables) + salary double(24,8), -- salary of user when payment was done + amount double(24,8) NOT NULL DEFAULT 0, + fk_projet integer DEFAULT NULL, + datesp date, -- date start period + dateep date, -- date end period + entity integer DEFAULT 1 NOT NULL, -- multi company id + note text, + fk_bank integer, + paye smallint default 1 NOT NULL, + fk_typepayment integer NOT NULL, -- default payment mode for payment + fk_account integer, -- default bank account for payment + fk_user_author integer, -- user creating + fk_user_modif integer -- user making last change +) ENGINE=innodb; + +ALTER TABLE llx_payment_salary CHANGE COLUMN fk_user fk_user integer NULL; +ALTER TABLE llx_payment_salary ADD COLUMN fk_salary integer; + +INSERT INTO llx_salary (rowid, ref, fk_user, amount, fk_projet, fk_typepayment, label, datesp, dateep, entity, note, fk_bank, paye) SELECT ps.rowid, ps.rowid, ps.fk_user, ps.amount, ps.fk_projet, ps.fk_typepayment, ps.label, ps.datesp, ps.dateep, ps.entity, ps.note, ps.fk_bank, 1 FROM llx_payment_salary ps WHERE ps.fk_salary IS NULL; +UPDATE llx_payment_salary as ps SET ps.fk_salary = ps.rowid WHERE ps.fk_salary IS NULL; +UPDATE llx_payment_salary as ps SET ps.ref = ps.rowid WHERE ps.ref IS NULL; + +ALTER TABLE llx_salary CHANGE paye paye smallint default 0 NOT NULL; + + +DELETE FROM llx_boxes WHERE box_id IN (SELECT rowid FROM llx_boxes_def WHERE file IN ('box_ticket_by_severity.php', 'box_nb_ticket_last_x_days.php', 'box_nb_tickets_type.php', 'box_new_vs_close_ticket.php')); +DELETE FROM llx_boxes_def WHERE file IN ('box_ticket_by_severity.php', 'box_nb_ticket_last_x_days.php', 'box_nb_tickets_type.php', 'box_new_vs_close_ticket.php'); + +-- VMYSQL4.1 INSERT INTO llx_boxes_def (file, entity) SELECT 'box_graph_ticket_by_severity.php', 1 FROM DUAL WHERE NOT EXISTS (SELECT * FROM llx_boxes_def WHERE file = 'box_graph_ticket_by_severity.php' AND entity = 1); +-- VMYSQL4.1 INSERT INTO llx_boxes_def (file, entity) SELECT 'box_graph_nb_ticket_last_x_days.php', 1 FROM DUAL WHERE NOT EXISTS (SELECT * FROM llx_boxes_def WHERE file = 'box_graph_nb_ticket_last_x_days.php' AND entity = 1); +-- VMYSQL4.1 INSERT INTO llx_boxes_def (file, entity) SELECT 'box_graph_nb_tickets_type.php', 1 FROM DUAL WHERE NOT EXISTS (SELECT * FROM llx_boxes_def WHERE file = 'box_graph_nb_tickets_type.php' AND entity = 1); +-- VMYSQL4.1 INSERT INTO llx_boxes_def (file, entity) SELECT 'box_graph_new_vs_close_ticket.php', 1 FROM DUAL WHERE NOT EXISTS (SELECT * FROM llx_boxes_def WHERE file = 'box_graph_new_vs_close_ticket.php' AND entity = 1); diff --git a/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql b/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql index dae9eb79c42..cd147979790 100644 --- a/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql +++ b/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql @@ -35,7 +35,7 @@ CREATE TABLE llx_accounting_bookkeeping label_operation varchar(255), -- FEC:EcritureLib | label of the operation debit double(24,8) NOT NULL, -- FEC:Debit credit double(24,8) NOT NULL, -- FEC:Credit - montant double(24,8) NOT NULL, -- FEC:Montant (Not necessary) + montant double(24,8) NULL, -- FEC:Montant (Not necessary) sens varchar(1) DEFAULT NULL, -- FEC:Sens (Not necessary) multicurrency_amount double(24,8), -- FEC:Montantdevise multicurrency_code varchar(255), -- FEC:Idevise diff --git a/htdocs/install/mysql/tables/llx_actioncomm.key.sql b/htdocs/install/mysql/tables/llx_actioncomm.key.sql index 64fbe874fc2..ee16386c7c4 100644 --- a/htdocs/install/mysql/tables/llx_actioncomm.key.sql +++ b/htdocs/install/mysql/tables/llx_actioncomm.key.sql @@ -17,7 +17,6 @@ -- -- =========================================================================== - ALTER TABLE llx_actioncomm ADD INDEX idx_actioncomm_fk_soc (fk_soc); ALTER TABLE llx_actioncomm ADD INDEX idx_actioncomm_fk_contact (fk_contact); ALTER TABLE llx_actioncomm ADD INDEX idx_actioncomm_code (code); @@ -27,5 +26,6 @@ ALTER TABLE llx_actioncomm ADD INDEX idx_actioncomm_fk_project (fk_project); ALTER TABLE llx_actioncomm ADD INDEX idx_actioncomm_datep (datep); ALTER TABLE llx_actioncomm ADD INDEX idx_actioncomm_datep2 (datep2); ALTER TABLE llx_actioncomm ADD INDEX idx_actioncomm_recurid (recurid); - ALTER TABLE llx_actioncomm ADD INDEX idx_actioncomm_ref_ext (ref_ext); + +ALTER TABLE llx_actioncomm ADD UNIQUE INDEX uk_actioncomm_ref (ref, entity); diff --git a/htdocs/install/mysql/tables/llx_actioncomm.sql b/htdocs/install/mysql/tables/llx_actioncomm.sql index 82d97d3ec98..9012f6b3a66 100644 --- a/htdocs/install/mysql/tables/llx_actioncomm.sql +++ b/htdocs/install/mysql/tables/llx_actioncomm.sql @@ -24,6 +24,7 @@ create table llx_actioncomm ( id integer AUTO_INCREMENT PRIMARY KEY, + ref varchar(30) NOT NULL, ref_ext varchar(255), -- reference into an external system (not used by dolibarr). Example: An id coming from google calendar has length between 5 and 1024 chars. An event id must follow rule: chars used in base32hex encoding (i.e. lowercase letters a-v and digits 0-9, see section 3.1.2 in RFC2938) entity integer DEFAULT 1 NOT NULL, -- multi company id datep datetime, -- date start @@ -31,7 +32,7 @@ create table llx_actioncomm fk_action integer, -- type of action (optional link with id in llx_c_actioncomm or null) code varchar(50) NULL, -- code of action for automatic action ('AC_OTH_AUTO' for automatic actions, 'AC_EMAILIN_AUTO' for email input, 'AC_xxx' for manual action...) - + datec datetime, -- date creation tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date fk_user_author integer, -- user id of user that has created record @@ -71,7 +72,11 @@ create table llx_actioncomm recurid varchar(128), -- used to store event id to link each other all the repeating event record. It can be the 'iCalUID' as in RFC5545 (an id similar for all the same serie) recurrule varchar(128), -- contains string with ical format recurring rule like 'FREQ=MONTHLY;INTERVAL=2;BYMONTHDAY=19' or 'FREQ=WEEKLY;BYDAY=MO' recurdateend datetime, -- no more recurring event after this date - + + num_vote integer DEFAULT NULL, -- use for Event Organization module + event_paid smallint NOT NULL DEFAULT 0, -- use for Event Organization module + status smallint NOT NULL DEFAULT 0, -- use for Event Organization module for now, but could be use after for event global status + fk_element integer DEFAULT NULL, -- For link to an element (proposal, invoice, order, ...) elementtype varchar(255) DEFAULT NULL, -- For link to an element (proposal, invoice, order, ...) diff --git a/htdocs/install/mysql/tables/llx_c_actioncomm.sql b/htdocs/install/mysql/tables/llx_c_actioncomm.sql index 695aabbe6e4..a2b2dffe8a7 100644 --- a/htdocs/install/mysql/tables/llx_c_actioncomm.sql +++ b/htdocs/install/mysql/tables/llx_c_actioncomm.sql @@ -21,10 +21,10 @@ create table llx_c_actioncomm ( id integer PRIMARY KEY, - code varchar(12) NOT NULL, + code varchar(50) NOT NULL, type varchar(50) DEFAULT 'system' NOT NULL, libelle varchar(48) NOT NULL, - module varchar(16) DEFAULT NULL, + module varchar(50) DEFAULT NULL, active tinyint DEFAULT 1 NOT NULL, todo tinyint, -- deprecated color varchar(9), diff --git a/htdocs/install/mysql/tables/llx_c_civility.sql b/htdocs/install/mysql/tables/llx_c_civility.sql index 1198691ed60..63fc8fca81f 100644 --- a/htdocs/install/mysql/tables/llx_c_civility.sql +++ b/htdocs/install/mysql/tables/llx_c_civility.sql @@ -19,7 +19,7 @@ create table llx_c_civility ( - rowid integer PRIMARY KEY, + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, code varchar(6) NOT NULL, label varchar(50), active tinyint DEFAULT 1 NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_commande.sql b/htdocs/install/mysql/tables/llx_commande.sql index add836ce5d5..e3a075933c2 100644 --- a/htdocs/install/mysql/tables/llx_commande.sql +++ b/htdocs/install/mysql/tables/llx_commande.sql @@ -47,7 +47,7 @@ create table llx_commande remise_percent real default 0, remise_absolue real default 0, remise real default 0, - tva double(24,8) default 0, + total_tva double(24,8) default 0, localtax1 double(24,8) default 0, -- total localtax1 localtax2 double(24,8) default 0, -- total localtax2 total_ht double(24,8) default 0, diff --git a/htdocs/install/mysql/tables/llx_commande_fournisseur.sql b/htdocs/install/mysql/tables/llx_commande_fournisseur.sql index a9f155a2abb..56486b551c8 100644 --- a/htdocs/install/mysql/tables/llx_commande_fournisseur.sql +++ b/htdocs/install/mysql/tables/llx_commande_fournisseur.sql @@ -49,7 +49,7 @@ create table llx_commande_fournisseur amount_ht double(24,8) default 0, remise_percent real default 0, remise real default 0, - tva double(24,8) default 0, + total_tva double(24,8) default 0, localtax1 double(24,8) default 0, localtax2 double(24,8) default 0, total_ht double(24,8) default 0, diff --git a/htdocs/install/mysql/tables/llx_events.sql b/htdocs/install/mysql/tables/llx_events.sql index ffa4f1029e7..16d65c442ab 100644 --- a/htdocs/install/mysql/tables/llx_events.sql +++ b/htdocs/install/mysql/tables/llx_events.sql @@ -26,20 +26,15 @@ create table llx_events rowid integer AUTO_INCREMENT PRIMARY KEY, tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date type varchar(32) NOT NULL, -- action type - entity integer DEFAULT 1 NOT NULL, -- multi company id - prefix_session varchar(255) NULL, -- prefix of session, obtained with dol_getprefix + entity integer DEFAULT 1 NOT NULL, -- multi company id + prefix_session varchar(255) NULL, -- prefix of session, obtained with dol_getprefix dateevent datetime, -- date event fk_user integer, -- id user description varchar(250) NOT NULL, -- full description of action ip varchar(250) NOT NULL, -- ip (must contains ip v4 and v6 or dns names) user_agent varchar(255) NULL, -- user agent - fk_object integer -- id of related object + fk_object integer NULL -- id of related object + authentication_method varchar(64) NULL, -- type of authentication mode used if internal login event + fk_oauth_token integer NULL -- id in oauth_token if internal login event done using an oauth_token ) ENGINE=innodb; --- --- List of codes for the field entity --- --- 1 : first company events --- 2 : second company events --- 3 : etc... --- diff --git a/htdocs/install/mysql/tables/llx_mailing_cibles.key.sql b/htdocs/install/mysql/tables/llx_mailing_cibles.key.sql index 709b12de31b..12ae5b5cc17 100644 --- a/htdocs/install/mysql/tables/llx_mailing_cibles.key.sql +++ b/htdocs/install/mysql/tables/llx_mailing_cibles.key.sql @@ -21,3 +21,5 @@ ALTER TABLE llx_mailing_cibles ADD UNIQUE uk_mailing_cibles (fk_mailing, email); ALTER TABLE llx_mailing_cibles ADD INDEX idx_mailing_cibles_email (email); +ALTER TABLE llx_mailing_cibles ADD INDEX idx_mailing_cibles_tag (tag); + diff --git a/htdocs/install/mysql/tables/llx_mailing_cibles.sql b/htdocs/install/mysql/tables/llx_mailing_cibles.sql index 096142b10ad..da0b6c1683a 100644 --- a/htdocs/install/mysql/tables/llx_mailing_cibles.sql +++ b/htdocs/install/mysql/tables/llx_mailing_cibles.sql @@ -28,7 +28,7 @@ create table llx_mailing_cibles firstname varchar(160), email varchar(160) NOT NULL, other varchar(255) NULL, - tag varchar(128) NULL, + tag varchar(64) NULL, -- a unique key as a hash of: dolibarr_main_instance_unique_id;email;lastname;mailing_id;MAILING_EMAIL_UNSUBSCRIBE_KEY statut smallint NOT NULL DEFAULT 0, -- -1 = error, 0 = not sent, ... source_url varchar(255), source_id integer, diff --git a/htdocs/install/mysql/tables/llx_mrp_production.sql b/htdocs/install/mysql/tables/llx_mrp_production.sql index 36129a54aea..a76e1f655ae 100644 --- a/htdocs/install/mysql/tables/llx_mrp_production.sql +++ b/htdocs/install/mysql/tables/llx_mrp_production.sql @@ -17,6 +17,8 @@ CREATE TABLE llx_mrp_production( rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, fk_mo integer NOT NULL, + origin_id integer, + origin_type varchar(10), -- 'bom' bom production line or 'free' free production line added after Mo creation from bom position integer NOT NULL DEFAULT 0, fk_product integer NOT NULL, fk_warehouse integer, @@ -24,7 +26,7 @@ CREATE TABLE llx_mrp_production( qty_frozen smallint DEFAULT 0, disable_stock_change smallint DEFAULT 0, batch varchar(128), - role varchar(10), -- 'toconsume' or 'toproduce' (initialized at MO creation), 'consumed' or 'produced' (added after MO validation) + role varchar(10), -- 'toconsume' or 'toproduce' (initialized at MO creation), 'consumed' or 'produced' (added after MO validation) fk_mrp_production integer, -- if role = 'consumed', id of line with role 'toconsume', if role = 'produced' id of line with role 'toproduce' fk_stock_movement integer, -- id of stock movement when movements are validated date_creation datetime NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_oauth_token.sql b/htdocs/install/mysql/tables/llx_oauth_token.sql index 145e646230d..06f2625c76e 100644 --- a/htdocs/install/mysql/tables/llx_oauth_token.sql +++ b/htdocs/install/mysql/tables/llx_oauth_token.sql @@ -17,11 +17,14 @@ CREATE TABLE llx_oauth_token ( rowid integer AUTO_INCREMENT PRIMARY KEY, - service varchar(36), - token text, -- token in serialize() format, of an object StdOAuth2Token of library phpoauth2 - tokenstring text, -- token in json format '{"access_token": "sk_test_cccc", "refresh_token": "rt_aaa", "token_type": "bearer", ..., "scope": "read_write"} + service varchar(36), -- 'Google', 'Stripe', 'auth-public-key', ... + token text, -- token in serialize() format, of an object StdOAuth2Token of library phpoauth2 + tokenstring text, -- token in text or json format. Value depends on 'service. For example for an OAUTH service: '{"access_token": "sk_test_cccc", "refresh_token": "rt_aaa", "token_type": "bearer", ..., "scope": "read_write"} fk_soc integer, - fk_user integer, + fk_user integer, -- Id of user in llx_user fk_adherent integer, + restricted_ips varchar(200), -- Restrict the authentication mode/token to some IPs + datec datetime DEFAULT NULL, -- date creation project + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, entity integer DEFAULT 1 )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_payment_salary.key.sql b/htdocs/install/mysql/tables/llx_payment_salary.key.sql index 946cd1a08ff..2eb07157d09 100644 --- a/htdocs/install/mysql/tables/llx_payment_salary.key.sql +++ b/htdocs/install/mysql/tables/llx_payment_salary.key.sql @@ -24,4 +24,3 @@ ALTER TABLE llx_payment_salary ADD INDEX idx_payment_salary_datesp (datesp); ALTER TABLE llx_payment_salary ADD INDEX idx_payment_salary_dateep (dateep); ALTER TABLE llx_payment_salary ADD CONSTRAINT fk_payment_salary_user FOREIGN KEY (fk_user) REFERENCES llx_user (rowid); - diff --git a/htdocs/install/mysql/tables/llx_payment_salary.sql b/htdocs/install/mysql/tables/llx_payment_salary.sql index d6ad2ffcfed..308e70effc2 100644 --- a/htdocs/install/mysql/tables/llx_payment_salary.sql +++ b/htdocs/install/mysql/tables/llx_payment_salary.sql @@ -22,7 +22,7 @@ create table llx_payment_salary ref varchar(30) NULL, -- payment reference number (currently NULL because there is no numbering manager yet) tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, -- Create date - fk_user integer NOT NULL, + fk_user integer DEFAULT NULL, datep date, -- payment date datev date, -- value date (this field should not be here, only into bank tables) salary double(24,8), -- salary of user when payment was done @@ -37,5 +37,6 @@ create table llx_payment_salary note text, fk_bank integer, fk_user_author integer, -- user creating - fk_user_modif integer -- user making last change + fk_user_modif integer, -- user making last change + fk_salary integer )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_projet.sql b/htdocs/install/mysql/tables/llx_projet.sql index 76d254aafd3..cd5eedd2c9a 100644 --- a/htdocs/install/mysql/tables/llx_projet.sql +++ b/htdocs/install/mysql/tables/llx_projet.sql @@ -48,6 +48,10 @@ create table llx_projet usage_task integer DEFAULT 1, -- Set to 1 if project is used to manage tasks and/or record timesheet usage_bill_time integer DEFAULT 0, -- Set to 1 if time spent must be converted into invoices usage_organize_event integer DEFAULT 0, -- Set to 1 if you want to use project to organize an event, receive attendees subscription + accept_conference_suggestions integer DEFAULT 0, -- Set to 1 if you want to allow unknown people to suggest conferences + accept_booth_suggestions integer DEFAULT 0, -- Set to 1 if you want to Allow unknown people to suggest booth + price_registration double(24,8), + price_booth double(24,8), model_pdf varchar(255), last_main_doc varchar(255), -- relative filepath+filename of last main generated document import_key varchar(14) -- Import key diff --git a/htdocs/install/mysql/tables/llx_propal.sql b/htdocs/install/mysql/tables/llx_propal.sql index 6e3e38dffd6..004bb027d35 100644 --- a/htdocs/install/mysql/tables/llx_propal.sql +++ b/htdocs/install/mysql/tables/llx_propal.sql @@ -48,10 +48,10 @@ create table llx_propal remise_absolue real DEFAULT 0, -- remise globale absolue (obsolete) remise real DEFAULT 0, -- remise calculee (obsolete) total_ht double(24,8) DEFAULT 0, -- montant total ht apres remise globale - tva double(24,8) DEFAULT 0, -- montant total tva apres remise globale + total_tva double(24,8) DEFAULT 0, -- montant total tva apres remise globale localtax1 double(24,8) DEFAULT 0, -- amount total localtax1 localtax2 double(24,8) DEFAULT 0, -- amount total localtax2 - total double(24,8) DEFAULT 0, -- montant total ttc apres remise globale + total_ttc double(24,8) DEFAULT 0, -- montant total ttc apres remise globale fk_account integer, -- bank account fk_currency varchar(3), -- currency code @@ -76,9 +76,9 @@ create table llx_propal fk_delivery_address integer, -- delivery address (deprecated) fk_multicurrency integer, - multicurrency_code varchar(255), + multicurrency_code varchar(255), multicurrency_tx double(24,8) DEFAULT 1, - multicurrency_total_ht double(24,8) DEFAULT 0, + multicurrency_total_ht double(24,8) DEFAULT 0, multicurrency_total_tva double(24,8) DEFAULT 0, multicurrency_total_ttc double(24,8) DEFAULT 0 )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature.sql b/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature.sql index ded61d49e8b..5749acd93d8 100644 --- a/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature.sql +++ b/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature.sql @@ -37,7 +37,7 @@ CREATE TABLE llx_recruitment_recruitmentcandidature( date_birth date, remuneration_requested integer, remuneration_proposed integer, - email_msgid varchar(255), + email_msgid varchar(175), -- Do not use a too large value, it generates trouble with unique index fk_recruitment_origin INTEGER NULL -- END MODULEBUILDER FIELDS ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_salary.sql b/htdocs/install/mysql/tables/llx_salary.sql new file mode 100644 index 00000000000..af4b869d9bf --- /dev/null +++ b/htdocs/install/mysql/tables/llx_salary.sql @@ -0,0 +1,44 @@ +-- =================================================================== +-- Copyright (C) 2011-2018 Alexandre Spangaro <aspangaro@open-dsi.fr> +-- Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- 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 <https://www.gnu.org/licenses/>. +-- +-- =================================================================== + +create table llx_salary +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + ref varchar(30) NULL, -- payment reference number (currently NULL because there is no numbering manager yet) + tms timestamp, + datec datetime, -- Create date + fk_user integer NOT NULL, + datep date, -- payment date + datev date, -- value date (this field should not be here, only into bank tables) + salary double(24,8), -- salary of user when payment was done + amount double(24,8) NOT NULL DEFAULT 0, + fk_projet integer DEFAULT NULL, + fk_typepayment integer NOT NULL, + num_payment varchar(50), -- num cheque or other + label varchar(255), + datesp date, -- date start period + dateep date, -- date end period + entity integer DEFAULT 1 NOT NULL, -- multi company id + note text, + fk_bank integer, + paye smallint default 0 NOT NULL, + fk_account integer, + fk_user_author integer, -- user creating + fk_user_modif integer -- user making last change +)ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_supplier_proposal.sql b/htdocs/install/mysql/tables/llx_supplier_proposal.sql index e63c4ff64c7..cf64d76d7d1 100644 --- a/htdocs/install/mysql/tables/llx_supplier_proposal.sql +++ b/htdocs/install/mysql/tables/llx_supplier_proposal.sql @@ -37,10 +37,10 @@ CREATE TABLE llx_supplier_proposal ( remise_absolue double DEFAULT 0, remise double DEFAULT 0, total_ht double(24,8) DEFAULT 0, - tva double(24,8) DEFAULT 0, + total_tva double(24,8) DEFAULT 0, localtax1 double(24,8) DEFAULT 0, localtax2 double(24,8) DEFAULT 0, - total double(24,8) DEFAULT 0, + total_ttc double(24,8) DEFAULT 0, fk_account integer DEFAULT NULL, fk_currency varchar(3) DEFAULT NULL, fk_cond_reglement integer DEFAULT NULL, diff --git a/htdocs/install/mysql/tables/llx_user_alert.sql b/htdocs/install/mysql/tables/llx_user_alert.sql index cded256de70..fd443e5e93f 100644 --- a/htdocs/install/mysql/tables/llx_user_alert.sql +++ b/htdocs/install/mysql/tables/llx_user_alert.sql @@ -21,6 +21,6 @@ create table llx_user_alert ( rowid integer AUTO_INCREMENT PRIMARY KEY, type integer, - fk_contact integer, -- pointe sur llx_socpeople - fk_user integer + fk_contact integer, -- id of llx_socpeople + fk_user integer -- id of llx_user )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_user_clicktodial.sql b/htdocs/install/mysql/tables/llx_user_clicktodial.sql index e6b02be0cbc..d9941a09ab0 100644 --- a/htdocs/install/mysql/tables/llx_user_clicktodial.sql +++ b/htdocs/install/mysql/tables/llx_user_clicktodial.sql @@ -17,14 +17,12 @@ -- =========================================================================== -- --- Stockage des informations relatives au click to dial +-- Table to store each different IP / devices / puclib key used for login -- -create table llx_user_clicktodial +create table llx_user_ipdevices ( - fk_user integer PRIMARY KEY, - url varchar(255), - login varchar(32), - pass varchar(64), - poste varchar(20) - + rowid integer PRIMARY KEY, + fk_user integer NOT NULL, -- ID llx_user + ip varchar(64), + user_agent varchar(255) NULL, -- user agent )ENGINE=innodb; diff --git a/htdocs/install/repair.php b/htdocs/install/repair.php index 14138dc5664..80678abe24f 100644 --- a/htdocs/install/repair.php +++ b/htdocs/install/repair.php @@ -24,7 +24,9 @@ */ include_once 'inc.php'; -if (file_exists($conffile)) include_once $conffile; +if (file_exists($conffile)) { + include_once $conffile; +} require_once $dolibarr_main_document_root.'/core/lib/admin.lib.php'; include_once $dolibarr_main_document_root.'/core/lib/images.lib.php'; require_once $dolibarr_main_document_root.'/core/class/extrafields.class.php'; @@ -46,13 +48,21 @@ $langs->setDefaultLang($setuplang); $langs->loadLangs(array("admin", "install", "other")); -if ($dolibarr_main_db_type == "mysqli") $choix = 1; -if ($dolibarr_main_db_type == "pgsql") $choix = 2; -if ($dolibarr_main_db_type == "mssql") $choix = 3; +if ($dolibarr_main_db_type == "mysqli") { + $choix = 1; +} +if ($dolibarr_main_db_type == "pgsql") { + $choix = 2; +} +if ($dolibarr_main_db_type == "mssql") { + $choix = 3; +} dolibarr_install_syslog("--- repair: entering upgrade.php page"); -if (!is_object($conf)) dolibarr_install_syslog("repair: conf file not initialized", LOG_ERR); +if (!is_object($conf)) { + dolibarr_install_syslog("repair: conf file not initialized", LOG_ERR); +} /* @@ -90,15 +100,15 @@ print '<table cellspacing="0" cellpadding="1" border="0" width="100%">'; $error = 0; // If password is encoded, we decode it -if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) -{ +if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) { require_once $dolibarr_main_document_root.'/core/lib/security.lib.php'; - if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) - { + if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) { $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass); $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass); $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially crypted - } else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } else { + $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } } // $conf is already instancied inside inc.php @@ -115,8 +125,7 @@ $conf->db->dolibarr_main_db_cryptkey = isset($dolibarr_main_db_cryptkey) ? $doli $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); -if ($db->connected) -{ +if ($db->connected) { print '<tr><td class="nowrap">'; print $langs->trans("ServerConnection")." : $dolibarr_main_db_host</td><td class=\"right\">".$langs->trans("OK")."</td></tr>"; dolibarr_install_syslog("repair: ".$langs->transnoentities("ServerConnection").": ".$dolibarr_main_db_host.$langs->transnoentities("OK")); @@ -127,10 +136,8 @@ if ($db->connected) $ok = 0; } -if ($ok) -{ - if ($db->database_selected) - { +if ($ok) { + if ($db->database_selected) { print '<tr><td class="nowrap">'; print $langs->trans("DatabaseConnection")." : ".$dolibarr_main_db_name."</td><td class=\"right\">".$langs->trans("OK")."</td></tr>"; dolibarr_install_syslog("repair: database connection successful: ".$dolibarr_main_db_name); @@ -143,8 +150,7 @@ if ($ok) } // Show database version -if ($ok) -{ +if ($ok) { $version = $db->getVersion(); $versionarray = $db->getVersionArray(); print '<tr><td>'.$langs->trans("ServerVersion").'</td>'; @@ -155,7 +161,9 @@ if ($ok) $conf->setValues($db); // Reset forced setup after the setValues -if (defined('SYSLOG_FILE')) $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); +if (defined('SYSLOG_FILE')) { + $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); +} $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1; @@ -166,8 +174,7 @@ $oneoptionset = (GETPOST('standard', 'alpha') || GETPOST('restore_thirdparties_l || GETPOST('clean_perm_table', 'alpha') || GETPOST('force_disable_of_modules_not_found', 'alpha') || GETPOST('force_utf8_on_tables', 'alpha')); -if ($ok && $oneoptionset) -{ +if ($ok && $oneoptionset) { // Show wait message print '<tr><td colspan="2">'.$langs->trans("PleaseBePatient").'<br><br></td></tr>'; flush(); @@ -175,8 +182,7 @@ if ($ok && $oneoptionset) // run_sql: Run repair SQL file -if ($ok && GETPOST('standard', 'alpha')) -{ +if ($ok && GETPOST('standard', 'alpha')) { $dir = "mysql/migration/"; $filelist = array(); @@ -186,26 +192,23 @@ if ($ok && GETPOST('standard', 'alpha')) // Recupere list fichier $filesindir = array(); $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/\.sql$/i', $file)) $filesindir[] = $file; + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/\.sql$/i', $file)) { + $filesindir[] = $file; + } } } sort($filesindir); - foreach ($filesindir as $file) - { - if (preg_match('/repair/i', $file)) - { + foreach ($filesindir as $file) { + if (preg_match('/repair/i', $file)) { $filelist[] = $file; } } // Loop on each file - foreach ($filelist as $file) - { + foreach ($filelist as $file) { print '<tr><td class="nowrap">*** '; print $langs->trans("Script").'</td><td class="right">'.$file.'</td></tr>'; @@ -219,17 +222,15 @@ if ($ok && GETPOST('standard', 'alpha')) // sync_extrafields: Search list of fields declared and list of fields created into databases, then create fields missing -if ($ok && GETPOST('standard', 'alpha')) -{ +if ($ok && GETPOST('standard', 'alpha')) { $extrafields = new ExtraFields($db); $listofmodulesextra = array('societe'=>'societe', 'adherent'=>'adherent', 'product'=>'product', - 'socpeople'=>'socpeople', 'commande'=>'commande', 'facture'=>'facture', + 'socpeople'=>'socpeople', 'propal'=>'propal', 'commande'=>'commande', 'facture'=>'facture', 'supplier_proposal'=>'supplier_proposal', 'commande_fournisseur'=>'commande_fournisseur', 'facture_fourn'=>'facture_fourn', 'actioncomm'=>'actioncomm', 'bom_bom'=>'bom_bom', 'mrp_mo'=>'mrp_mo', 'adherent_type'=>'adherent_type', 'user'=>'user', 'projet'=>'projet', 'projet_task'=>'projet_task'); print '<tr><td colspan="2"><br>*** Check fields into extra table structure match table of definition. If not add column into table</td></tr>'; - foreach ($listofmodulesextra as $tablename => $elementtype) - { + foreach ($listofmodulesextra as $tablename => $elementtype) { // Get list of fields $tableextra = MAIN_DB_PREFIX.$tablename.'_extrafields'; @@ -239,15 +240,12 @@ if ($ok && GETPOST('standard', 'alpha')) // Define $arrayoffieldsfound $arrayoffieldsfound = array(); $resql = $db->DDLDescTable($tableextra); - if ($resql) - { + if ($resql) { print '<tr><td>Check availability of extra field for '.$tableextra."<br>\n"; $i = 0; - while ($obj = $db->fetch_object($resql)) - { + while ($obj = $db->fetch_object($resql)) { $fieldname = $fieldtype = ''; - if (preg_match('/mysql/', $db->type)) - { + if (preg_match('/mysql/', $db->type)) { $fieldname = $obj->Field; $fieldtype = $obj->Type; } else { @@ -255,20 +253,22 @@ if ($ok && GETPOST('standard', 'alpha')) $fieldtype = isset($obj->Type) ? $obj->Type : 'varchar'; } - if (empty($fieldname)) continue; - if (in_array($fieldname, array('rowid', 'tms', 'fk_object', 'import_key'))) continue; + if (empty($fieldname)) { + continue; + } + if (in_array($fieldname, array('rowid', 'tms', 'fk_object', 'import_key'))) { + continue; + } $arrayoffieldsfound[$fieldname] = array('type'=>$fieldtype); } // If it does not match, we create fields - foreach ($arrayoffieldsdesc as $code => $label) - { - if (!in_array($code, array_keys($arrayoffieldsfound))) - { + foreach ($arrayoffieldsdesc as $code => $label) { + if (!in_array($code, array_keys($arrayoffieldsfound))) { print 'Found field '.$code.' declared into '.MAIN_DB_PREFIX.'extrafields table but not found into desc of table '.$tableextra." -> "; $type = $extrafields->attributes[$elementtype]['type'][$code]; $length = $extrafields->attributes[$elementtype]['size'][$code]; $attribute = ''; $default = ''; $extra = ''; $null = 'null'; - if ($type == 'boolean') { + if ($type == 'boolean') { $typedb = 'int'; $lengthdb = '1'; } elseif ($type == 'price') { @@ -302,12 +302,10 @@ if ($ok && GETPOST('standard', 'alpha')) //var_dump($field_desc);exit; $result = 0; - if (GETPOST('standard', 'alpha') == 'confirmed') - { + if (GETPOST('standard', 'alpha') == 'confirmed') { $result = $db->DDLAddField($tableextra, $code, $field_desc, ""); - if ($result < 0) - { + if ($result < 0) { print "KO ".$db->lasterror."<br>\n"; } else { print "OK<br>\n"; @@ -327,15 +325,13 @@ if ($ok && GETPOST('standard', 'alpha')) // clean_data_ecm_dir: Clean data into ecm_directories table -if ($ok && GETPOST('standard', 'alpha')) -{ +if ($ok && GETPOST('standard', 'alpha')) { clean_data_ecm_directories(); } // clean declaration constants -if ($ok && GETPOST('standard', 'alpha')) -{ +if ($ok && GETPOST('standard', 'alpha')) { print '<tr><td colspan="2"><br>*** Clean constant record of modules not enabled</td></tr>'; $sql = "SELECT name, entity, value"; @@ -347,22 +343,18 @@ if ($ok && GETPOST('standard', 'alpha')) $sql .= " ORDER BY name, entity"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $db->begin(); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $reg = array(); - if (preg_match('/MAIN_MODULE_([^_]+)_(.+)/i', $obj->name, $reg)) - { + if (preg_match('/MAIN_MODULE_([^_]+)_(.+)/i', $obj->name, $reg)) { $name = $reg[1]; $type = $reg[2]; @@ -371,16 +363,13 @@ if ($ok && GETPOST('standard', 'alpha')) $sql2 .= " WHERE name = 'MAIN_MODULE_".$name."'"; $sql2 .= " AND entity = ".$obj->entity; $resql2 = $db->query($sql2); - if ($resql2) - { + if ($resql2) { $obj2 = $db->fetch_object($resql2); - if ($obj2 && $obj2->nb == 0) - { + if ($obj2 && $obj2->nb == 0) { // Module not found, so we can remove entry $sqldelete = "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = '".$db->escape($obj->name)."' AND entity = ".$obj->entity; - if (GETPOST('standard', 'alpha') == 'confirmed') - { + if (GETPOST('standard', 'alpha') == 'confirmed') { $db->query($sqldelete); print '<tr><td>Widget '.$obj->name.' set in entity '.$obj->entity.' with value '.$obj->value.' -> Module '.$name.' not enabled in entity '.$obj->entity.', we delete record</td></tr>'; @@ -405,30 +394,25 @@ if ($ok && GETPOST('standard', 'alpha')) // clean box of not enabled modules -if ($ok && GETPOST('standard', 'alpha')) -{ +if ($ok && GETPOST('standard', 'alpha')) { print '<tr><td colspan="2"><br>*** Clean definition of boxes of modules not enabled</td></tr>'; $sql = "SELECT file, entity FROM ".MAIN_DB_PREFIX."boxes_def"; $sql .= " WHERE file like '%@%'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $db->begin(); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $reg = array(); - if (preg_match('/^(.+)@(.+)$/i', $obj->file, $reg)) - { + if (preg_match('/^(.+)@(.+)$/i', $obj->file, $reg)) { $name = $reg[1]; $module = $reg[2]; @@ -438,17 +422,14 @@ if ($ok && GETPOST('standard', 'alpha')) $sql2 .= " AND entity = ".$obj->entity; $sql2 .= " AND value <> 0"; $resql2 = $db->query($sql2); - if ($resql2) - { + if ($resql2) { $obj2 = $db->fetch_object($resql2); - if ($obj2 && $obj2->nb == 0) - { + if ($obj2 && $obj2->nb == 0) { // Module not found, so we canremove entry $sqldeletea = "DELETE FROM ".MAIN_DB_PREFIX."boxes WHERE entity = ".$obj->entity." AND box_id IN (SELECT rowid FROM ".MAIN_DB_PREFIX."boxes_def WHERE file = '".$db->escape($obj->file)."' AND entity = ".$obj->entity.")"; $sqldeleteb = "DELETE FROM ".MAIN_DB_PREFIX."boxes_def WHERE file = '".$db->escape($obj->file)."' AND entity = ".$obj->entity; - if (GETPOST('standard', 'alpha') == 'confirmed') - { + if (GETPOST('standard', 'alpha') == 'confirmed') { $db->query($sqldeletea); $db->query($sqldeleteb); @@ -472,8 +453,7 @@ if ($ok && GETPOST('standard', 'alpha')) // restore_thirdparties_logos: Move logos to correct new directory. -if ($ok && GETPOST('restore_thirdparties_logos')) -{ +if ($ok && GETPOST('restore_thirdparties_logos')) { //$exts=array('gif','png','jpg'); $ext = ''; @@ -482,13 +462,11 @@ if ($ok && GETPOST('restore_thirdparties_logos')) $sql = "SELECT s.rowid, s.nom as name, s.logo FROM ".MAIN_DB_PREFIX."societe as s ORDER BY s.nom"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); /* @@ -499,43 +477,37 @@ if ($ok && GETPOST('restore_thirdparties_logos')) $tmp = explode('.', $obj->logo); $name = $tmp[0]; - if (isset($tmp[1])) $ext = '.'.$tmp[1]; + if (isset($tmp[1])) { + $ext = '.'.$tmp[1]; + } - if (!empty($name)) - { + if (!empty($name)) { $filetotest = $dolibarr_main_data_root.'/societe/logos/'.$name.$ext; $filetotestsmall = $dolibarr_main_data_root.'/societe/logos/thumbs/'.$name.'_small'.$ext; $exists = dol_is_file($filetotest); print 'Check thirdparty '.$obj->rowid.' name='.$obj->name.' logo='.$obj->logo.' file '.$filetotest." exists=".$exists."<br>\n"; - if ($exists) - { + if ($exists) { $filetarget = $dolibarr_main_data_root.'/societe/'.$obj->rowid.'/logos/'.$name.$ext; $filetargetsmall = $dolibarr_main_data_root.'/societe/'.$obj->rowid.'/logos/thumbs/'.$name.'_small'.$ext; $existt = dol_is_file($filetarget); - if (!$existt) - { - if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') - { + if (!$existt) { + if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') { dol_mkdir($dolibarr_main_data_root.'/societe/'.$obj->rowid.'/logos'); } print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotest." -> ".$filetarget."<br>\n"; - if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') - { + if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') { dol_copy($filetotest, $filetarget, '', 0); } } $existtt = dol_is_file($filetargetsmall); - if (!$existtt) - { - if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') - { + if (!$existtt) { + if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') { dol_mkdir($dolibarr_main_data_root.'/societe/'.$obj->rowid.'/logos/thumbs'); } print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotestsmall." -> ".$filetargetsmall."<br>\n"; - if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') - { + if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') { dol_copy($filetotestsmall, $filetargetsmall, '', 0); } } @@ -555,8 +527,7 @@ if ($ok && GETPOST('restore_thirdparties_logos')) // restore_user_pictures: Move pictures to correct new directory. -if ($ok && GETPOST('restore_user_pictures', 'alpha')) -{ +if ($ok && GETPOST('restore_user_pictures', 'alpha')) { //$exts=array('gif','png','jpg'); $ext = ''; @@ -565,13 +536,11 @@ if ($ok && GETPOST('restore_user_pictures', 'alpha')) $sql = "SELECT s.rowid, s.firstname, s.lastname, s.login, s.photo FROM ".MAIN_DB_PREFIX."user as s ORDER BY s.rowid"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); /* @@ -582,62 +551,53 @@ if ($ok && GETPOST('restore_user_pictures', 'alpha')) $tmp = explode('.', $obj->photo); $name = $tmp[0]; - if (isset($tmp[1])) $ext = '.'.$tmp[1]; + if (isset($tmp[1])) { + $ext = '.'.$tmp[1]; + } - if (!empty($name)) - { + if (!empty($name)) { $filetotest = $dolibarr_main_data_root.'/users/'.substr(sprintf('%08d', $obj->rowid), -1, 1).'/'.substr(sprintf('%08d', $obj->rowid), -2, 1).'/'.$name.$ext; $filetotestsmall = $dolibarr_main_data_root.'/users/'.substr(sprintf('%08d', $obj->rowid), -1, 1).'/'.substr(sprintf('%08d', $obj->rowid), -2, 1).'/thumbs/'.$name.'_small'.$ext; $filetotestmini = $dolibarr_main_data_root.'/users/'.substr(sprintf('%08d', $obj->rowid), -1, 1).'/'.substr(sprintf('%08d', $obj->rowid), -2, 1).'/thumbs/'.$name.'_mini'.$ext; $exists = dol_is_file($filetotest); print 'Check user '.$obj->rowid.' lastname='.$obj->lastname.' fistname='.$obj->firstname.' photo='.$obj->photo.' file '.$filetotest." exists=".$exists."<br>\n"; - if ($exists) - { + if ($exists) { $filetarget = $dolibarr_main_data_root.'/users/'.$obj->rowid.'/'.$name.$ext; $filetargetsmall = $dolibarr_main_data_root.'/users/'.$obj->rowid.'/thumbs/'.$name.'_small'.$ext; $filetargetmini = $dolibarr_main_data_root.'/users/'.$obj->rowid.'/thumbs/'.$name.'_mini'.$ext; $existt = dol_is_file($filetarget); - if (!$existt) - { - if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') - { + if (!$existt) { + if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') { dol_mkdir($dolibarr_main_data_root.'/users/'.$obj->rowid); } print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotest." -> ".$filetarget."<br>\n"; - if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') - { + if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') { dol_copy($filetotest, $filetarget, '', 0); } } $existtt = dol_is_file($filetargetsmall); - if (!$existtt) - { - if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') - { + if (!$existtt) { + if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') { dol_mkdir($dolibarr_main_data_root.'/users/'.$obj->rowid.'/thumbs'); } print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotestsmall." -> ".$filetargetsmall."<br>\n"; - if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') - { + if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') { dol_copy($filetotestsmall, $filetargetsmall, '', 0); } } $existtt = dol_is_file($filetargetmini); - if (!$existtt) - { - if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') - { + if (!$existtt) { + if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') { dol_mkdir($dolibarr_main_data_root.'/users/'.$obj->rowid.'/thumbs'); } print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotestmini." -> ".$filetargetmini."<br>\n"; - if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') - { + if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') { dol_copy($filetotestmini, $filetargetmini, '', 0); } } @@ -656,8 +616,7 @@ if ($ok && GETPOST('restore_user_pictures', 'alpha')) // rebuild_product_thumbs: Rebuild thumbs for product files -if ($ok && GETPOST('rebuild_product_thumbs', 'alpha')) -{ +if ($ok && GETPOST('rebuild_product_thumbs', 'alpha')) { $ext = ''; global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini; @@ -665,33 +624,26 @@ if ($ok && GETPOST('rebuild_product_thumbs', 'alpha')) $sql = "SELECT s.rowid, s.ref FROM ".MAIN_DB_PREFIX."product as s ORDER BY s.ref"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if (!empty($obj->ref)) - { + if (!empty($obj->ref)) { $files = dol_dir_list($dolibarr_main_data_root.'/produit/'.$obj->ref, 'files', 0); - foreach ($files as $file) - { + foreach ($files as $file) { // Generate thumbs. - if (image_format_supported($file['fullname']) == 1) - { + if (image_format_supported($file['fullname']) == 1) { $imgThumbSmall = 'notbuild'; - if (GETPOST('rebuild_product_thumbs', 'alpha') == 'confirmed') - { + if (GETPOST('rebuild_product_thumbs', 'alpha') == 'confirmed') { // Used on logon for example $imgThumbSmall = vignette($file['fullname'], $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs"); } print 'Check product '.$obj->rowid.", file ".$file['fullname']." -> ".$imgThumbSmall." maxwidthsmall=".$maxwidthsmall." maxheightsmall=".$maxheightsmall."<br>\n"; $imgThumbMini = 'notbuild'; - if (GETPOST('rebuild_product_thumbs', 'alpha') == 'confirmed') - { + if (GETPOST('rebuild_product_thumbs', 'alpha') == 'confirmed') { // Create mini thumbs for image (Ratio is near 16/9) // Used on menu or for setup page for example $imgThumbMini = vignette($file['fullname'], $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs"); @@ -712,8 +664,7 @@ if ($ok && GETPOST('rebuild_product_thumbs', 'alpha')) } // clean_linked_elements: Check and clean linked elements -if ($ok && GETPOST('clean_linked_elements', 'alpha')) -{ +if ($ok && GETPOST('clean_linked_elements', 'alpha')) { print '<tr><td colspan="2"><br>*** Check table of linked elements and delete orphelins links</td></tr>'; // propal => order print '<tr><td colspan="2">'.checkLinkedElements('propal', 'commande')."</td></tr>\n"; @@ -736,8 +687,7 @@ if ($ok && GETPOST('clean_linked_elements', 'alpha')) // clean_menus: Check orphelins menus -if ($ok && GETPOST('clean_menus', 'alpha')) -{ +if ($ok && GETPOST('clean_menus', 'alpha')) { print '<tr><td colspan="2"><br>*** Clean menu entries coming from disabled modules</td></tr>'; $sql = "SELECT rowid, module"; @@ -746,14 +696,11 @@ if ($ok && GETPOST('clean_menus', 'alpha')) $sql .= " ORDER BY module"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $modulecond = $obj->module; @@ -764,30 +711,33 @@ if ($ok && GETPOST('clean_menus', 'alpha')) $db->begin(); - if ($modulecond) // And menu entry for module $modulecond was found in database. - { + if ($modulecond) { // And menu entry for module $modulecond was found in database. $moduleok = 0; - foreach ($modulecondarray as $tmpname) - { - if ($tmpname == 'margins') $tmpname = 'margin'; // TODO Remove this when normalized + foreach ($modulecondarray as $tmpname) { + if ($tmpname == 'margins') { + $tmpname = 'margin'; // TODO Remove this when normalized + } $result = 0; - if (!empty($conf->$tmpname)) $result = $conf->$tmpname->enabled; - if ($result) $moduleok++; + if (!empty($conf->$tmpname)) { + $result = $conf->$tmpname->enabled; + } + if ($result) { + $moduleok++; + } } - if (!$moduleok && $modulecond) - { + if (!$moduleok && $modulecond) { print ' - Module condition '.$modulecond.' seems ko, we delete menu entry.'; - if (GETPOST('clean_menus') == 'confirmed') - { + if (GETPOST('clean_menus') == 'confirmed') { $sql2 = "DELETE FROM ".MAIN_DB_PREFIX."menu WHERE module = '".$db->escape($modulecond)."'"; $resql2 = $db->query($sql2); - if (!$resql2) - { + if (!$resql2) { $error++; dol_print_error($db); - } else print ' - <span class="warning">Cleaned</span>'; + } else { + print ' - <span class="warning">Cleaned</span>'; + } } else { print ' - <span class="warning">Canceled (test mode)</span>'; } @@ -796,12 +746,17 @@ if ($ok && GETPOST('clean_menus', 'alpha')) } } - if (!$error) $db->commit(); - else $db->rollback(); + if (!$error) { + $db->commit(); + } else { + $db->rollback(); + } print'</td></tr>'; - if ($error) break; + if ($error) { + break; + } $i++; } @@ -816,70 +771,72 @@ if ($ok && GETPOST('clean_menus', 'alpha')) // clean_orphelin_dir: Run purge of directory -if ($ok && GETPOST('clean_orphelin_dir', 'alpha')) -{ +if ($ok && GETPOST('clean_orphelin_dir', 'alpha')) { $listmodulepart = array('company', 'invoice', 'invoice_supplier', 'propal', 'order', 'order_supplier', 'contract', 'tax'); - foreach ($listmodulepart as $modulepart) - { + foreach ($listmodulepart as $modulepart) { $filearray = array(); $upload_dir = isset($conf->$modulepart->dir_output) ? $conf->$modulepart->dir_output : ''; - if ($modulepart == 'company') $upload_dir = $conf->societe->dir_output; // TODO change for multicompany sharing - if ($modulepart == 'invoice') $upload_dir = $conf->facture->dir_output; - if ($modulepart == 'invoice_supplier') $upload_dir = $conf->fournisseur->facture->dir_output; - if ($modulepart == 'order') $upload_dir = $conf->commande->dir_output; - if ($modulepart == 'order_supplier') $upload_dir = $conf->fournisseur->commande->dir_output; - if ($modulepart == 'contract') $upload_dir = $conf->contrat->dir_output; + if ($modulepart == 'company') { + $upload_dir = $conf->societe->dir_output; // TODO change for multicompany sharing + } + if ($modulepart == 'invoice') { + $upload_dir = $conf->facture->dir_output; + } + if ($modulepart == 'invoice_supplier') { + $upload_dir = $conf->fournisseur->facture->dir_output; + } + if ($modulepart == 'order') { + $upload_dir = $conf->commande->dir_output; + } + if ($modulepart == 'order_supplier') { + $upload_dir = $conf->fournisseur->commande->dir_output; + } + if ($modulepart == 'contract') { + $upload_dir = $conf->contrat->dir_output; + } - if (empty($upload_dir)) continue; + if (empty($upload_dir)) { + continue; + } print '<tr><td colspan="2"><br>*** Clean orphelins files into files '.$upload_dir.'</td></tr>'; $filearray = dol_dir_list($upload_dir, "files", 1, '', array('^SPECIMEN\.pdf$', '^\.', '(\.meta|_preview.*\.png)$', '^temp$', '^payments$', '^CVS$', '^thumbs$'), '', SORT_DESC, 1, true); // To show ref or specific information according to view to show (defined by $module) - if ($modulepart == 'company') - { + if ($modulepart == 'company') { include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $object_instance = new Societe($db); } - if ($modulepart == 'invoice') - { + if ($modulepart == 'invoice') { include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $object_instance = new Facture($db); - } elseif ($modulepart == 'invoice_supplier') - { + } elseif ($modulepart == 'invoice_supplier') { include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; $object_instance = new FactureFournisseur($db); - } elseif ($modulepart == 'propal') - { + } elseif ($modulepart == 'propal') { include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $object_instance = new Propal($db); - } elseif ($modulepart == 'order') - { + } elseif ($modulepart == 'order') { include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $object_instance = new Commande($db); - } elseif ($modulepart == 'order_supplier') - { + } elseif ($modulepart == 'order_supplier') { include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; $object_instance = new CommandeFournisseur($db); - } elseif ($modulepart == 'contract') - { + } elseif ($modulepart == 'contract') { include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; $object_instance = new Contrat($db); - } elseif ($modulepart == 'tax') - { + } elseif ($modulepart == 'tax') { include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; $object_instance = new ChargeSociales($db); } - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { if (!is_dir($file['name']) && $file['name'] != '.' && $file['name'] != '..' && $file['name'] != 'CVS' - ) - { + ) { // Define relative path used to store the file $relativefile = preg_replace('/'.preg_quote($upload_dir.'/', '/').'/', '', $file['fullname']); @@ -909,23 +866,22 @@ if ($ok && GETPOST('clean_orphelin_dir', 'alpha')) preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg); $id = $reg[1]; } - if ($id || $ref) - { + if ($id || $ref) { //print 'Fetch '.$id.' or '.$ref.'<br>'; $result = $object_instance->fetch($id, $ref); //print $result.'<br>'; - if ($result == 0) // Not found but no error - { + if ($result == 0) { // Not found but no error // Clean of orphelins directories are done into repair.php print '<tr><td colspan="2">'; print 'Delete orphelins file '.$file['fullname'].'<br>'; - if (GETPOST('clean_orphelin_dir', 'alpha') == 'confirmed') - { + if (GETPOST('clean_orphelin_dir', 'alpha') == 'confirmed') { dol_delete_file($file['fullname'], 1, 1, 1); dol_delete_dir(dirname($file['fullname']), 1); } print "</td></tr>"; - } elseif ($result < 0) print 'Error in '.get_class($object_instance).'.fetch of id'.$id.' ref='.$ref.', result='.$result.'<br>'; + } elseif ($result < 0) { + print 'Error in '.get_class($object_instance).'.fetch of id'.$id.' ref='.$ref.', result='.$result.'<br>'; + } } } } @@ -933,8 +889,7 @@ if ($ok && GETPOST('clean_orphelin_dir', 'alpha')) } // clean_linked_elements: Check and clean linked elements -if ($ok && GETPOST('clean_product_stock_batch', 'alpha')) -{ +if ($ok && GETPOST('clean_product_stock_batch', 'alpha')) { $methodtofix = GETPOST('methodtofix', 'alpha') ?GETPOST('methodtofix', 'alpha') : 'updatestock'; print '<tr><td colspan="2"><br>*** Clean table product_batch, methodtofix='.$methodtofix.' (possible values: updatestock or updatebatch)</td></tr>'; @@ -942,37 +897,30 @@ if ($ok && GETPOST('clean_product_stock_batch', 'alpha')) $sql = "SELECT p.rowid, p.ref, p.tobatch, ps.rowid as psrowid, ps.fk_entrepot, ps.reel, SUM(pb.qty) as reelbatch"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p, ".MAIN_DB_PREFIX."product_stock as ps LEFT JOIN ".MAIN_DB_PREFIX."product_batch as pb ON ps.rowid = pb.fk_product_stock"; $sql .= " WHERE p.rowid = ps.fk_product"; - $sql .= " AND p.tobatch = 1"; + $sql .= " AND p.tobatch > 0"; $sql .= " GROUP BY p.rowid, p.ref, p.tobatch, ps.rowid, ps.fk_entrepot, ps.reel"; $sql .= " HAVING reel != SUM(pb.qty) or SUM(pb.qty) IS NULL"; print $sql; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr><td>Product '.$obj->rowid.'-'.$obj->ref.' in warehose '.$obj->fk_entrepot.' -> '.$obj->psrowid.': '.$obj->reel.' (product_stock.reel) != '.($obj->reelbatch ? $obj->reelbatch : '0').' (sum product_batch)'; // Fix - if ($obj->reel != $obj->reelbatch) - { - if ($methodtofix == 'updatebatch') - { + if ($obj->reel != $obj->reelbatch) { + if ($methodtofix == 'updatebatch') { // Method 1 print ' -> Insert qty '.($obj->reel - $obj->reelbatch).' with lot 000000 linked to fk_product_stock='.$obj->psrowid; - if (GETPOST('clean_product_stock_batch') == 'confirmed') - { + if (GETPOST('clean_product_stock_batch') == 'confirmed') { $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_batch(fk_product_stock, batch, qty)"; $sql2 .= "VALUES(".$obj->psrowid.", '000000', ".($obj->reel - $obj->reelbatch).")"; $resql2 = $db->query($sql2); - if (!$resql2) - { + if (!$resql2) { // TODO If it fails, we must make update //$sql2 ="UPDATE ".MAIN_DB_PREFIX."product_batch"; //$sql2.=" SET ".$obj->psrowid.", '000000', ".($obj->reel - $obj->reelbatch).")"; @@ -980,12 +928,10 @@ if ($ok && GETPOST('clean_product_stock_batch', 'alpha')) } } } - if ($methodtofix == 'updatestock') - { + if ($methodtofix == 'updatestock') { // Method 2 print ' -> Update qty of product_stock with qty = '.($obj->reelbatch ? $obj->reelbatch : '0').' for ps.rowid = '.$obj->psrowid; - if (GETPOST('clean_product_stock_batch') == 'confirmed') - { + if (GETPOST('clean_product_stock_batch') == 'confirmed') { $error = 0; $db->begin(); @@ -993,13 +939,11 @@ if ($ok && GETPOST('clean_product_stock_batch', 'alpha')) $sql2 = "UPDATE ".MAIN_DB_PREFIX."product_stock"; $sql2 .= " SET reel = ".($obj->reelbatch ? $obj->reelbatch : '0')." WHERE rowid = ".$obj->psrowid; $resql2 = $db->query($sql2); - if ($resql2) - { + if ($resql2) { // We update product_stock, so we must fill p.stock into product too. $sql3 = 'UPDATE '.MAIN_DB_PREFIX.'product p SET p.stock= (SELECT SUM(ps.reel) FROM '.MAIN_DB_PREFIX.'product_stock ps WHERE ps.fk_product = p.rowid)'; $resql3 = $db->query($sql3); - if (!$resql3) - { + if (!$resql3) { $error++; dol_print_error($db); } @@ -1008,8 +952,11 @@ if ($ok && GETPOST('clean_product_stock_batch', 'alpha')) dol_print_error($db); } - if (!$error) $db->commit(); - else $db->rollback(); + if (!$error) { + $db->commit(); + } else { + $db->rollback(); + } } } } @@ -1028,26 +975,22 @@ if ($ok && GETPOST('clean_product_stock_batch', 'alpha')) // clean_product_stock_negative_if_batch -if ($ok && GETPOST('clean_product_stock_negative_if_batch', 'alpha')) -{ +if ($ok && GETPOST('clean_product_stock_negative_if_batch', 'alpha')) { print '<tr><td colspan="2"><br>Clean table product_batch, methodtofix='.$methodtofix.' (possible values: updatestock or updatebatch)</td></tr>'; $sql = "SELECT p.rowid, p.ref, p.tobatch, ps.rowid as psrowid, ps.fk_entrepot, ps.reel, SUM(pb.qty) as reelbatch"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p, ".MAIN_DB_PREFIX."product_stock as ps, ".MAIN_DB_PREFIX."product_batch as pb"; $sql .= " WHERE p.rowid = ps.fk_product AND ps.rowid = pb.fk_product_stock"; - $sql .= " AND p.tobatch = 1"; + $sql .= " AND p.tobatch > 0"; $sql .= " GROUP BY p.rowid, p.ref, p.tobatch, ps.rowid, ps.fk_entrepot, ps.reel"; $sql .= " HAVING reel != SUM(pb.qty)"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr><td>'.$obj->rowid.'-'.$obj->ref.'-'.$obj->fk_entrepot.' -> '.$obj->psrowid.': '.$obj->reel.' != '.$obj->reelbatch; @@ -1058,8 +1001,7 @@ if ($ok && GETPOST('clean_product_stock_negative_if_batch', 'alpha')) } // set_empty_time_spent_amount -if ($ok && GETPOST('set_empty_time_spent_amount', 'alpha')) -{ +if ($ok && GETPOST('set_empty_time_spent_amount', 'alpha')) { print '<tr><td colspan="2"><br>*** Set value of time spent without amount</td></tr>'; $sql = "SELECT COUNT(ptt.rowid) as nb, u.rowid as user_id, u.login, u.thm as user_thm"; @@ -1069,38 +1011,38 @@ if ($ok && GETPOST('set_empty_time_spent_amount', 'alpha')) $sql .= " GROUP BY u.rowid, u.login, u.thm"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr><td>'.$obj->login.'-'.$obj->user_id.' ('.$obj->nb.' lines to fix) -> '.$obj->user_thm; $db->begin(); - if (GETPOST('set_empty_time_spent_amount') == 'confirmed') - { + if (GETPOST('set_empty_time_spent_amount') == 'confirmed') { $sql2 = "UPDATE ".MAIN_DB_PREFIX."projet_task_time"; $sql2 .= " SET thm = ".$obj->user_thm." WHERE thm IS NULL AND fk_user = ".$obj->user_id; $resql2 = $db->query($sql2); - if (!$resql2) - { + if (!$resql2) { $error++; dol_print_error($db); } } - if (!$error) $db->commit(); - else $db->rollback(); + if (!$error) { + $db->commit(); + } else { + $db->rollback(); + } print'</td></tr>'; - if ($error) break; + if ($error) { + break; + } $i++; } @@ -1114,28 +1056,23 @@ if ($ok && GETPOST('set_empty_time_spent_amount', 'alpha')) // force_disable_of_modules_not_found -if ($ok && GETPOST('force_disable_of_modules_not_found', 'alpha')) -{ +if ($ok && GETPOST('force_disable_of_modules_not_found', 'alpha')) { print '<tr><td colspan="2"><br>*** Force modules not found physicaly to be disabled (only modules adding js, css or hooks can be detected as removed physicaly)</td></tr>'; $arraylistofkey = array('hooks', 'js', 'css'); - foreach ($arraylistofkey as $key) - { + foreach ($arraylistofkey as $key) { $sql = "SELECT DISTINCT name, value"; $sql .= " FROM ".MAIN_DB_PREFIX."const as c"; $sql .= " WHERE name LIKE 'MAIN_MODULE_%_".strtoupper($key)."'"; $sql .= " ORDER BY name"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $constantname = $obj->name; // Name of constant for hook or js or css declaration @@ -1145,62 +1082,58 @@ if ($ok && GETPOST('force_disable_of_modules_not_found', 'alpha')) $db->begin(); $reg = array(); - if (preg_match('/MAIN_MODULE_(.*)_'.strtoupper($key).'/i', $constantname, $reg)) - { + if (preg_match('/MAIN_MODULE_(.*)_'.strtoupper($key).'/i', $constantname, $reg)) { $name = strtolower($reg[1]); - if ($name) // An entry for key $key and module $name was found in database. - { + if ($name) { // An entry for key $key and module $name was found in database. $reloffile = ''; $result = 'found'; - if ($key == 'hooks') $reloffile = $name.'/class/actions_'.$name.'.class.php'; - if ($key == 'js') - { + if ($key == 'hooks') { + $reloffile = $name.'/class/actions_'.$name.'.class.php'; + } + if ($key == 'js') { $value = $obj->value; $valuearray = json_decode($value); $reloffile = $valuearray[0]; $reloffile = preg_replace('/^\//', '', $valuearray[0]); } - if ($key == 'css') - { + if ($key == 'css') { $value = $obj->value; $valuearray = json_decode($value); - if ($value && count($valuearray) == 0) $valuearray[0] = $value; // If value was not a json array but a string + if ($value && count($valuearray) == 0) { + $valuearray[0] = $value; // If value was not a json array but a string + } $reloffile = preg_replace('/^\//', '', $valuearray[0]); } - if ($reloffile) - { + if ($reloffile) { //var_dump($key.' - '.$value.' - '.$reloffile); try { $result = dol_buildpath($reloffile, 0, 2); - } catch (Exception $e) - { + } catch (Exception $e) { // No catch yet $result = 'found'; // If error, we force lke if we found to avoid any deletion } } - if (!$result) - { + if (!$result) { print ' - File of '.$key.' ('.$reloffile.') NOT found, we disable the module.'; - if (GETPOST('force_disable_of_modules_not_found') == 'confirmed') - { + if (GETPOST('force_disable_of_modules_not_found') == 'confirmed') { $sql2 = "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = 'MAIN_MODULE_".strtoupper($name)."_".strtoupper($key)."'"; $resql2 = $db->query($sql2); - if (!$resql2) - { + if (!$resql2) { $error++; dol_print_error($db); } $sql3 = "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = 'MAIN_MODULE_".strtoupper($name)."'"; $resql3 = $db->query($sql3); - if (!$resql3) - { + if (!$resql3) { $error++; dol_print_error($db); - } else print ' - <span class="warning">Cleaned</span>'; + } else { + print ' - <span class="warning">Cleaned</span>'; + } } else { print ' - <span class="warning">Canceled (test mode)</span>'; } @@ -1209,13 +1142,18 @@ if ($ok && GETPOST('force_disable_of_modules_not_found', 'alpha')) } } - if (!$error) $db->commit(); - else $db->rollback(); + if (!$error) { + $db->commit(); + } else { + $db->rollback(); + } } print'</td></tr>'; - if ($error) break; + if ($error) { + break; + } $i++; } @@ -1230,35 +1168,27 @@ if ($ok && GETPOST('force_disable_of_modules_not_found', 'alpha')) // clean_old_module_entries: Clean data into const when files of module were removed without being -if ($ok && GETPOST('clean_perm_table', 'alpha')) -{ +if ($ok && GETPOST('clean_perm_table', 'alpha')) { print '<tr><td colspan="2"><br>*** Clean table user_rights from lines of external modules no more enabled</td></tr>'; $listofmods = ''; - foreach ($conf->modules as $key => $val) - { + foreach ($conf->modules as $key => $val) { $listofmods .= ($listofmods ? ',' : '')."'".$val."'"; } $sql = 'SELECT id, libelle as label, module from '.MAIN_DB_PREFIX.'rights_def WHERE module not in ('.$listofmods.') AND id > 100000'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj->id > 0) - { + if ($obj->id > 0) { print '<tr><td>Found line with id '.$obj->id.', label "'.$obj->label.'" of module "'.$obj->module.'" to delete'; - if (GETPOST('clean_perm_table', 'alpha') == 'confirmed') - { + if (GETPOST('clean_perm_table', 'alpha') == 'confirmed') { $sqldelete = 'DELETE FROM '.MAIN_DB_PREFIX.'rights_def WHERE id = '.$obj->id; $resqldelete = $db->query($sqldelete); - if (!$resqldelete) - { + if (!$resqldelete) { dol_print_error($db); } print ' - deleted'; @@ -1278,44 +1208,42 @@ if ($ok && GETPOST('clean_perm_table', 'alpha')) // force utf8 on tables -if ($ok && GETPOST('force_utf8_on_tables', 'alpha')) -{ +if ($ok && GETPOST('force_utf8_on_tables', 'alpha')) { print '<tr><td colspan="2"><br>*** Force page code and collation of tables into utf8/utf8_unicode_ci (for mysql/mariadb only)</td></tr>'; - if ($db->type == "mysql" || $db->type == "mysqli") - { + if ($db->type == "mysql" || $db->type == "mysqli") { $force_utf8_on_tables = GETPOST('force_utf8_on_tables', 'alpha'); $listoftables = $db->DDLListTables($db->database_name); // Disable foreign key checking for avoid errors - if ($force_utf8_on_tables == 'confirmed') - { + if ($force_utf8_on_tables == 'confirmed') { $sql = 'SET FOREIGN_KEY_CHECKS=0'; print '<!-- '.$sql.' -->'; $resql = $db->query($sql); } - foreach ($listoftables as $table) - { + foreach ($listoftables as $table) { // do not convert llx_const if mysql encrypt/decrypt is used - if ($conf->db->dolibarr_main_db_encryption != 0 && preg_match('/\_const$/', $table)) continue; + if ($conf->db->dolibarr_main_db_encryption != 0 && preg_match('/\_const$/', $table)) { + continue; + } print '<tr><td colspan="2">'; print $table; $sql = 'ALTER TABLE '.$table.' CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci'; print '<!-- '.$sql.' -->'; - if ($force_utf8_on_tables == 'confirmed') - { + if ($force_utf8_on_tables == 'confirmed') { $resql = $db->query($sql); print ' - Done ('.($resql ? 'OK' : 'KO').')'; - } else print ' - Disabled'; + } else { + print ' - Disabled'; + } print '</td></tr>'; } // Enable foreign key checking - if ($force_utf8_on_tables == 'confirmed') - { + if ($force_utf8_on_tables == 'confirmed') { $sql = 'SET FOREIGN_KEY_CHECKS=1'; print '<!-- '.$sql.' -->'; $resql = $db->query($sql); @@ -1328,27 +1256,27 @@ if ($ok && GETPOST('force_utf8_on_tables', 'alpha')) // if ($ok && GETPOST('repair_link_dispatch_lines_supplier_order_lines')) { /* - * This script is meant to be run when upgrading from a dolibarr version < 3.8 - * to a newer version. - * - * Version 3.8 introduces a new column in llx_commande_fournisseur_dispatch, which - * matches the dispatch to a specific supplier order line (so that if there are - * several with the same product, the user can specifically tell which products of - * which line were dispatched where). - * - * However when migrating, the new column has a default value of 0, which means that - * old supplier orders whose lines were dispatched using the old dolibarr version - * have unspecific dispatch lines, which are not taken into account by the new version, - * thus making the order look like it was never dispatched at all. - * - * This scripts sets this foreign key to the first matching supplier order line whose - * product (and supplier order of course) are the same as the dispatch’s. - * - * If the dispatched quantity is more than indicated on the order line (this happens if - * there are several order lines for the same product), it creates new dispatch lines - * pointing to the other order lines accordingly, until all the dispatched quantity is - * accounted for. - */ + * This script is meant to be run when upgrading from a dolibarr version < 3.8 + * to a newer version. + * + * Version 3.8 introduces a new column in llx_commande_fournisseur_dispatch, which + * matches the dispatch to a specific supplier order line (so that if there are + * several with the same product, the user can specifically tell which products of + * which line were dispatched where). + * + * However when migrating, the new column has a default value of 0, which means that + * old supplier orders whose lines were dispatched using the old dolibarr version + * have unspecific dispatch lines, which are not taken into account by the new version, + * thus making the order look like it was never dispatched at all. + * + * This scripts sets this foreign key to the first matching supplier order line whose + * product (and supplier order of course) are the same as the dispatch’s. + * + * If the dispatched quantity is more than indicated on the order line (this happens if + * there are several order lines for the same product), it creates new dispatch lines + * pointing to the other order lines accordingly, until all the dispatched quantity is + * accounted for. + */ $repair_link_dispatch_lines_supplier_order_lines = GETPOST('repair_link_dispatch_lines_supplier_order_lines', 'alpha'); @@ -1384,9 +1312,13 @@ if ($ok && GETPOST('repair_link_dispatch_lines_supplier_order_lines')) { $n_processed_rows++; continue; } - if ($db->num_rows($resql_line) == 0) continue; + if ($db->num_rows($resql_line) == 0) { + continue; + } while ($obj_line = $db->fetch_object($resql_line)) { - if (!$remaining_qty) break; + if (!$remaining_qty) { + break; + } if (!$obj_line->rowid) { continue; } @@ -1419,8 +1351,7 @@ if ($ok && GETPOST('repair_link_dispatch_lines_supplier_order_lines')) { $sql_attach .= ' VALUES ('.$sql_attach_values.')'; } - if ($repair_link_dispatch_lines_supplier_order_lines == 'confirmed') - { + if ($repair_link_dispatch_lines_supplier_order_lines == 'confirmed') { $resql_attach = $db->query($sql_attach); } else { $resql_attach = true; // Force success in test mode @@ -1466,13 +1397,11 @@ print '</table>'; -if (empty($actiondone)) -{ +if (empty($actiondone)) { print '<div class="error">'.$langs->trans("ErrorWrongParameters").'</div>'; } -if ($oneoptionset) -{ +if ($oneoptionset) { print '<div class="center" style="padding-top: 10px"><a href="../index.php?mainmenu=home&leftmenu=home'.(GETPOSTISSET("login") ? '&username='.urlencode(GETPOST("login")) : '').'">'; print $langs->trans("GoToDolibarr"); print '</a></div>'; @@ -1485,7 +1414,11 @@ if ($oneoptionset) dolibarr_install_syslog("--- repair: end"); pFooter(1, $setuplang); -if ($db->connected) $db->close(); +if ($db->connected) { + $db->close(); +} // Return code if ran from command line -if (!$ok && isset($argv[1])) exit(1); +if (!$ok && isset($argv[1])) { + exit(1); +} diff --git a/htdocs/install/step1.php b/htdocs/install/step1.php index 5b99649cf1a..e841a352b40 100644 --- a/htdocs/install/step1.php +++ b/htdocs/install/step1.php @@ -75,14 +75,18 @@ $_SESSION['dol_save_pass'] = $db_pass; // Now we load forced values from install.forced.php file. $useforcedwizard = false; $forcedfile = "./install.forced.php"; -if ($conffile == "/etc/dolibarr/conf.php") $forcedfile = "/etc/dolibarr/install.forced.php"; +if ($conffile == "/etc/dolibarr/conf.php") { + $forcedfile = "/etc/dolibarr/install.forced.php"; +} if (@file_exists($forcedfile)) { $useforcedwizard = true; include_once $forcedfile; // If forced install is enabled, replace the post values. These are empty because form fields are disabled. if ($force_install_noedit) { $main_dir = detect_dolibarr_main_document_root(); - if (!empty($argv[1])) $main_dir = $argv[1]; // override when executing the script in command line + if (!empty($argv[1])) { + $main_dir = $argv[1]; // override when executing the script in command line + } if (!empty($force_install_main_data_root)) { $main_data_dir = $force_install_main_data_root; } else { @@ -148,8 +152,7 @@ dolibarr_install_syslog("--- step1: entering step1.php page"); pHeader($langs->trans("ConfigurationFile"), "step2"); // Test if we can run a first install process -if (!is_writable($conffile)) -{ +if (!is_writable($conffile)) { print $langs->trans("ConfFileIsNotWritable", $conffiletoshow); pFooter(1, $setuplang, 'jscheckparam'); exit; @@ -158,57 +161,48 @@ if (!is_writable($conffile)) // Check parameters $is_sqlite = false; -if (empty($db_type)) -{ +if (empty($db_type)) { print '<div class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentities("DatabaseType")).'</div>'; $error++; } else { $is_sqlite = ($db_type === 'sqlite' || $db_type === 'sqlite3'); } -if (empty($db_host) && !$is_sqlite) -{ +if (empty($db_host) && !$is_sqlite) { print '<div class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentities("Server")).'</div>'; $error++; } -if (empty($db_name)) -{ +if (empty($db_name)) { print '<div class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentities("DatabaseName")).'</div>'; $error++; } -if (empty($db_user) && !$is_sqlite) -{ +if (empty($db_user) && !$is_sqlite) { print '<div class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentities("Login")).'</div>'; $error++; } -if (!empty($db_port) && !is_numeric($db_port)) -{ +if (!empty($db_port) && !is_numeric($db_port)) { print '<div class="error">'.$langs->trans("ErrorBadValueForParameter", $db_port, $langs->transnoentities("Port")).'</div>'; $error++; } -if (!empty($db_prefix) && !preg_match('/^[a-z0-9]+_$/i', $db_prefix)) -{ +if (!empty($db_prefix) && !preg_match('/^[a-z0-9]+_$/i', $db_prefix)) { print '<div class="error">'.$langs->trans("ErrorBadValueForParameter", $db_prefix, $langs->transnoentities("DatabasePrefix")).'</div>'; $error++; } // Remove last / into dans main_dir -if (substr($main_dir, dol_strlen($main_dir) - 1) == "/") -{ +if (substr($main_dir, dol_strlen($main_dir) - 1) == "/") { $main_dir = substr($main_dir, 0, dol_strlen($main_dir) - 1); } // Remove last / into dans main_url -if (!empty($main_url) && substr($main_url, dol_strlen($main_url) - 1) == "/") -{ +if (!empty($main_url) && substr($main_url, dol_strlen($main_url) - 1) == "/") { $main_url = substr($main_url, 0, dol_strlen($main_url) - 1); } // Test database connection if (!$error) { $result = @include_once $main_dir."/core/db/".$db_type.'.class.php'; - if ($result) - { + if ($result) { // If we require database or user creation we need to connect as root, so we need root login credentials if (!empty($db_create_database) && !$userroot) { print '<div class="error">'.$langs->trans("YouAskDatabaseCreationSoDolibarrNeedToConnect", $db_name).'</div>'; @@ -229,11 +223,9 @@ if (!$error) { if (!$error && (!empty($db_create_database) || !empty($db_create_user))) { $databasefortest = $db_name; if (!empty($db_create_database)) { - if ($db_type == 'mysql' || $db_type == 'mysqli') - { + if ($db_type == 'mysql' || $db_type == 'mysqli') { $databasefortest = 'mysql'; - } elseif ($db_type == 'pgsql') - { + } elseif ($db_type == 'pgsql') { $databasefortest = 'postgres'; } else { $databasefortest = 'master'; @@ -249,14 +241,21 @@ if (!$error) { if (empty($db_create_database) && $db->connected && !$db->database_selected) { print '<div class="error">'.$langs->trans("ErrorConnectedButDatabaseNotFound", $db_name).'</div>'; print '<br>'; - if (!$db->connected) print $langs->trans("IfDatabaseNotExistsGoBackAndUncheckCreate").'<br><br>'; + if (!$db->connected) { + print $langs->trans("IfDatabaseNotExistsGoBackAndUncheckCreate").'<br><br>'; + } print $langs->trans("ErrorGoBackAndCorrectParameters"); $error++; } elseif ($db->error && !(!empty($db_create_database) && $db->connected)) { // Note: you may experience error here with message "No such file or directory" when mysql was installed for the first time but not yet launched. - if ($db->error == "No such file or directory") print '<div class="error">'.$langs->trans("ErrorToConnectToMysqlCheckInstance").'</div>'; - else print '<div class="error">'.$db->error.'</div>'; - if (!$db->connected) print $langs->trans("BecauseConnectionFailedParametersMayBeWrong").'<br><br>'; + if ($db->error == "No such file or directory") { + print '<div class="error">'.$langs->trans("ErrorToConnectToMysqlCheckInstance").'</div>'; + } else { + print '<div class="error">'.$db->error.'</div>'; + } + if (!$db->connected) { + print $langs->trans("BecauseConnectionFailedParametersMayBeWrong").'<br><br>'; + } //print '<a href="#" onClick="javascript: history.back();">'; print $langs->trans("ErrorGoBackAndCorrectParameters"); //print '</a>'; @@ -267,10 +266,11 @@ if (!$error) { if (!$error && (empty($db_create_database) && empty($db_create_user))) { $db = getDoliDBInstance($db_type, $db_host, $db_user, $db_pass, $db_name, $db_port); - if ($db->error) - { + if ($db->error) { print '<div class="error">'.$db->error.'</div>'; - if (!$db->connected) print $langs->trans("BecauseConnectionFailedParametersMayBeWrong").'<br><br>'; + if (!$db->connected) { + print $langs->trans("BecauseConnectionFailedParametersMayBeWrong").'<br><br>'; + } //print '<a href="#" onClick="javascript: history.back();">'; print $langs->trans("ErrorGoBackAndCorrectParameters"); //print '</a>'; @@ -286,18 +286,20 @@ if (!$error) { $error++; } } else { - if (isset($db)) print $db->lasterror(); - if (isset($db) && !$db->connected) print '<br>'.$langs->trans("BecauseConnectionFailedParametersMayBeWrong").'<br><br>'; + if (isset($db)) { + print $db->lasterror(); + } + if (isset($db) && !$db->connected) { + print '<br>'.$langs->trans("BecauseConnectionFailedParametersMayBeWrong").'<br><br>'; + } print $langs->trans("ErrorGoBackAndCorrectParameters"); $error++; } -if (!$error && $db->connected) -{ +if (!$error && $db->connected) { if (!empty($db_create_database)) { $result = $db->select_db($db_name); - if ($result) - { + if ($result) { print '<div class="error">'.$langs->trans("ErrorDatabaseAlreadyExists", $db_name).'</div>'; print $langs->trans("IfDatabaseExistsGoBackAndCheckCreate").'<br><br>'; print $langs->trans("ErrorGoBackAndCorrectParameters"); @@ -307,10 +309,8 @@ if (!$error && $db->connected) } // Define $defaultCharacterSet and $defaultDBSortingCollation -if (!$error && $db->connected) -{ - if (!empty($db_create_database)) // If we create database, we force default value - { +if (!$error && $db->connected) { + if (!empty($db_create_database)) { // If we create database, we force default value // Default values come from the database handler $defaultCharacterSet = $db->forcecharset; @@ -323,8 +323,7 @@ if (!$error && $db->connected) // Force to avoid utf8mb4 because index on field char 255 reach limit of 767 char for indexes (example with mysql 5.6.34 = mariadb 10.0.29) // TODO Remove this when utf8mb4 is supported - if ($defaultCharacterSet == 'utf8mb4' || $defaultDBSortingCollation == 'utf8mb4_unicode_ci') - { + if ($defaultCharacterSet == 'utf8mb4' || $defaultDBSortingCollation == 'utf8mb4_unicode_ci') { $defaultCharacterSet = 'utf8'; $defaultDBSortingCollation = 'utf8_unicode_ci'; } @@ -338,13 +337,10 @@ if (!$error && $db->connected) // Create config file -if (!$error && $db->connected && $action == "set") -{ +if (!$error && $db->connected && $action == "set") { umask(0); - if (is_array($_POST)) - { - foreach ($_POST as $key => $value) - { + if (is_array($_POST)) { + foreach ($_POST as $key => $value) { if (!preg_match('/^db_pass/i', $key)) { dolibarr_install_syslog("step1: choice for ".$key." = ".$value); } @@ -356,10 +352,8 @@ if (!$error && $db->connected && $action == "set") print '<table cellspacing="0" width="100%" cellpadding="1" border="0">'; // Check parameter main_dir - if (!$error) - { - if (!is_dir($main_dir)) - { + if (!$error) { + if (!is_dir($main_dir)) { dolibarr_install_syslog("step1: directory '".$main_dir."' is unavailable or can't be accessed"); print "<tr><td>"; @@ -373,23 +367,19 @@ if (!$error && $db->connected && $action == "set") } } - if (!$error) - { + if (!$error) { dolibarr_install_syslog("step1: directory '".$main_dir."' exists"); } // Create subdirectory main_data_dir - if (!$error) - { + if (!$error) { // Create directory for documents - if (!is_dir($main_data_dir)) - { + if (!is_dir($main_data_dir)) { dol_mkdir($main_data_dir); } - if (!is_dir($main_data_dir)) - { + if (!is_dir($main_data_dir)) { print "<tr><td>".$langs->trans("ErrorDirDoesNotExists", $main_data_dir); print ' '.$langs->trans("YouMustCreateItAndAllowServerToWrite"); print '</td><td>'; @@ -400,12 +390,10 @@ if (!$error && $db->connected && $action == "set") } else { // Create .htaccess file in document directory $pathhtaccess = $main_data_dir.'/.htaccess'; - if (!file_exists($pathhtaccess)) - { + if (!file_exists($pathhtaccess)) { dolibarr_install_syslog("step1: .htaccess file did not exist, we created it in '".$main_data_dir."'"); $handlehtaccess = @fopen($pathhtaccess, 'w'); - if ($handlehtaccess) - { + if ($handlehtaccess) { fwrite($handlehtaccess, 'Order allow,deny'."\n"); fwrite($handlehtaccess, 'Deny from all'."\n"); @@ -427,14 +415,11 @@ if (!$error && $db->connected && $action == "set") // Loop on each directory of dir [] to create them if they do not exist $num = count($dir); - for ($i = 0; $i < $num; $i++) - { - if (is_dir($dir[$i])) - { + for ($i = 0; $i < $num; $i++) { + if (is_dir($dir[$i])) { dolibarr_install_syslog("step1: directory '".$dir[$i]."' exists"); } else { - if (dol_mkdir($dir[$i]) < 0) - { + if (dol_mkdir($dir[$i]) < 0) { print "<tr><td>"; print "Failed to create directory: ".$dir[$i]; print '</td><td>'; @@ -454,8 +439,7 @@ if (!$error && $db->connected && $action == "set") $destroot = $main_data_dir.'/medias'; dolCopyDir($srcroot, $destroot, 0, 0); - if ($error) - { + if ($error) { print "<tr><td>".$langs->trans("ErrorDirDoesNotExists", $main_data_dir); print ' '.$langs->trans("YouMustCreateItAndAllowServerToWrite"); print '</td><td>'; @@ -480,16 +464,14 @@ if (!$error && $db->connected && $action == "set") 'usergroups' => 'usergroups', 'users' => 'user', ); - foreach ($docs as $cursordir => $cursorfile) - { + foreach ($docs as $cursordir => $cursorfile) { $src = $srcroot.'/'.$cursordir.'/template_'.$cursorfile.'.odt'; $dirodt = $destroot.'/'.$cursordir; $dest = $dirodt.'/template_'.$cursorfile.'.odt'; dol_mkdir($dirodt); $result = dol_copy($src, $dest, 0, 0); - if ($result < 0) - { + if ($result < 0) { print '<tr><td colspan="2"><br>'.$langs->trans('ErrorFailToCopyFile', $src, $dest).'</td></tr>'; } } @@ -501,11 +483,9 @@ if (!$error && $db->connected && $action == "set") $main_db_prefix = (!empty($db_prefix) ? $db_prefix : 'llx_'); // Write conf file on disk - if (!$error) - { + if (!$error) { // Save old conf file on disk - if (file_exists("$conffile")) - { + if (file_exists("$conffile")) { // We must ignore errors as an existing old file may already exist and not be replaceable or // the installer (like for ubuntu) may not have permission to create another file than conf.php. // Also no other process must be able to read file or we expose the new file, so content with password. @@ -516,8 +496,7 @@ if (!$error && $db->connected && $action == "set") } // Create database and admin user database - if (!$error) - { + if (!$error) { // We reload configuration file conf($dolibarr_main_document_root); @@ -532,14 +511,11 @@ if (!$error && $db->connected && $action == "set") //print $conf->db->host." , ".$conf->db->name." , ".$conf->db->user." , ".$conf->db->port; $databasefortest = $conf->db->name; - if ($conf->db->type == 'mysql' || $conf->db->type == 'mysqli') - { + if ($conf->db->type == 'mysql' || $conf->db->type == 'mysqli') { $databasefortest = 'mysql'; - } elseif ($conf->db->type == 'pgsql') - { + } elseif ($conf->db->type == 'pgsql') { $databasefortest = 'postgres'; - } elseif ($conf->db->type == 'mssql') - { + } elseif ($conf->db->type == 'mssql') { $databasefortest = 'master'; } @@ -547,32 +523,26 @@ if (!$error && $db->connected && $action == "set") $db = getDoliDBInstance($conf->db->type, $conf->db->host, $userroot, $passroot, $databasefortest, $conf->db->port); - if ($db->error) - { + if ($db->error) { print '<div class="error">'.$db->error.'</div>'; $error++; } - if (!$error) - { - if ($db->connected) - { + if (!$error) { + if ($db->connected) { $resultbis = 1; // Create user $result = $db->DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name); // Create user bis - if ($databasefortest == 'mysql') - { - if (!in_array($dolibarr_main_db_host, array('127.0.0.1', '::1', 'localhost', 'localhost.local'))) - { + if ($databasefortest == 'mysql') { + if (!in_array($dolibarr_main_db_host, array('127.0.0.1', '::1', 'localhost', 'localhost.local'))) { $resultbis = $db->DDLCreateUser('%', $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name); } } - if ($result > 0 && $resultbis > 0) - { + if ($result > 0 && $resultbis > 0) { print '<tr><td>'; print $langs->trans("UserCreation").' : '; print $dolibarr_main_db_user; @@ -581,8 +551,7 @@ if (!$error && $db->connected && $action == "set") } else { if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS' || $db->errno() == 'DB_ERROR_KEY_NAME_ALREADY_EXISTS' - || $db->errno() == 'DB_ERROR_USER_ALREADY_EXISTS') - { + || $db->errno() == 'DB_ERROR_USER_ALREADY_EXISTS') { dolibarr_install_syslog("step1: user already exists"); print '<tr><td>'; print $langs->trans("UserCreation").' : '; @@ -628,12 +597,10 @@ if (!$error && $db->connected && $action == "set") $newdb = getDoliDBInstance($conf->db->type, $conf->db->host, $userroot, $passroot, '', $conf->db->port); //print 'eee'.$conf->db->type." ".$conf->db->host." ".$userroot." ".$passroot." ".$conf->db->port." ".$newdb->connected." ".$newdb->forcecharset;exit; - if ($newdb->connected) - { + if ($newdb->connected) { $result = $newdb->DDLCreateDb($dolibarr_main_db_name, $dolibarr_main_db_character_set, $dolibarr_main_db_collation, $dolibarr_main_db_user); - if ($result) - { + if ($result) { print '<tr><td>'; print $langs->trans("DatabaseCreation")." (".$langs->trans("User")." ".$userroot.") : "; print $dolibarr_main_db_name; @@ -683,15 +650,13 @@ if (!$error && $db->connected && $action == "set") // We test access with dolibarr database user (not admin) - if (!$error) - { + if (!$error) { dolibarr_install_syslog("step1: connection type=".$conf->db->type." on host=".$conf->db->host." port=".$conf->db->port." user=".$conf->db->user." name=".$conf->db->name); //print "connexion de type=".$conf->db->type." sur host=".$conf->db->host." port=".$conf->db->port." user=".$conf->db->user." name=".$conf->db->name; $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); - if ($db->connected) - { + if ($db->connected) { dolibarr_install_syslog("step1: connection to server by user ".$conf->db->user." ok"); print "<tr><td>"; print $langs->trans("ServerConnection")." (".$langs->trans("User")." ".$conf->db->user.") : "; @@ -701,8 +666,7 @@ if (!$error && $db->connected && $action == "set") print "</td></tr>"; // server access ok, basic access ok - if ($db->database_selected) - { + if ($db->database_selected) { dolibarr_install_syslog("step1: connection to database ".$conf->db->name." by user ".$conf->db->user." ok"); print "<tr><td>"; print $langs->trans("DatabaseConnection")." (".$langs->trans("User")." ".$conf->db->user.") : "; @@ -773,7 +737,9 @@ function jsinfo() <?php $ret = 0; -if ($error && isset($argv[1])) $ret = 1; +if ($error && isset($argv[1])) { + $ret = 1; +} dolibarr_install_syslog("Exit ".$ret); dolibarr_install_syslog("--- step1: end"); @@ -781,7 +747,9 @@ dolibarr_install_syslog("--- step1: end"); pFooter($error ? 1 : 0, $setuplang, 'jsinfo', 1); // Return code if ran from command line -if ($ret) exit($ret); +if ($ret) { + exit($ret); +} /** @@ -794,8 +762,7 @@ if ($ret) exit($ret); function write_main_file($mainfile, $main_dir) { $fp = @fopen("$mainfile", "w"); - if ($fp) - { + if ($fp) { clearstatcache(); fputs($fp, '<?php'."\n"); fputs($fp, "// Wrapper to include main into htdocs\n"); @@ -815,8 +782,7 @@ function write_main_file($mainfile, $main_dir) function write_master_file($masterfile, $main_dir) { $fp = @fopen("$masterfile", "w"); - if ($fp) - { + if ($fp) { clearstatcache(); fputs($fp, '<?php'."\n"); fputs($fp, "// Wrapper to include master into htdocs\n"); @@ -854,8 +820,7 @@ function write_conf_file($conffile) $key = md5(uniqid(mt_rand(), true)); // Generate random hash $fp = fopen("$conffile", "w"); - if ($fp) - { + if ($fp) { clearstatcache(); fputs($fp, '<?php'."\n"); @@ -940,49 +905,77 @@ function write_conf_file($conffile) // Write params to overwrites default lib path fputs($fp, "\n"); - if (empty($force_dolibarr_lib_FPDF_PATH)) { fputs($fp, '//'); $force_dolibarr_lib_FPDF_PATH = ''; } + if (empty($force_dolibarr_lib_FPDF_PATH)) { + fputs($fp, '//'); $force_dolibarr_lib_FPDF_PATH = ''; + } fputs($fp, '$dolibarr_lib_FPDF_PATH=\''.$force_dolibarr_lib_FPDF_PATH.'\';'); fputs($fp, "\n"); - if (empty($force_dolibarr_lib_TCPDF_PATH)) { fputs($fp, '//'); $force_dolibarr_lib_TCPDF_PATH = ''; } + if (empty($force_dolibarr_lib_TCPDF_PATH)) { + fputs($fp, '//'); $force_dolibarr_lib_TCPDF_PATH = ''; + } fputs($fp, '$dolibarr_lib_TCPDF_PATH=\''.$force_dolibarr_lib_TCPDF_PATH.'\';'); fputs($fp, "\n"); - if (empty($force_dolibarr_lib_FPDI_PATH)) { fputs($fp, '//'); $force_dolibarr_lib_FPDI_PATH = ''; } + if (empty($force_dolibarr_lib_FPDI_PATH)) { + fputs($fp, '//'); $force_dolibarr_lib_FPDI_PATH = ''; + } fputs($fp, '$dolibarr_lib_FPDI_PATH=\''.$force_dolibarr_lib_FPDI_PATH.'\';'); fputs($fp, "\n"); - if (empty($force_dolibarr_lib_TCPDI_PATH)) { fputs($fp, '//'); $force_dolibarr_lib_TCPDI_PATH = ''; } + if (empty($force_dolibarr_lib_TCPDI_PATH)) { + fputs($fp, '//'); $force_dolibarr_lib_TCPDI_PATH = ''; + } fputs($fp, '$dolibarr_lib_TCPDI_PATH=\''.$force_dolibarr_lib_TCPDI_PATH.'\';'); fputs($fp, "\n"); - if (empty($force_dolibarr_lib_ADODB_PATH)) { fputs($fp, '//'); $force_dolibarr_lib_ADODB_PATH = ''; } + if (empty($force_dolibarr_lib_ADODB_PATH)) { + fputs($fp, '//'); $force_dolibarr_lib_ADODB_PATH = ''; + } fputs($fp, '$dolibarr_lib_ADODB_PATH=\''.$force_dolibarr_lib_ADODB_PATH.'\';'); fputs($fp, "\n"); - if (empty($force_dolibarr_lib_GEOIP_PATH)) { fputs($fp, '//'); $force_dolibarr_lib_GEOIP_PATH = ''; } + if (empty($force_dolibarr_lib_GEOIP_PATH)) { + fputs($fp, '//'); $force_dolibarr_lib_GEOIP_PATH = ''; + } fputs($fp, '$dolibarr_lib_GEOIP_PATH=\''.$force_dolibarr_lib_GEOIP_PATH.'\';'); fputs($fp, "\n"); - if (empty($force_dolibarr_lib_NUSOAP_PATH)) { fputs($fp, '//'); $force_dolibarr_lib_NUSOAP_PATH = ''; } + if (empty($force_dolibarr_lib_NUSOAP_PATH)) { + fputs($fp, '//'); $force_dolibarr_lib_NUSOAP_PATH = ''; + } fputs($fp, '$dolibarr_lib_NUSOAP_PATH=\''.$force_dolibarr_lib_NUSOAP_PATH.'\';'); fputs($fp, "\n"); - if (empty($force_dolibarr_lib_ODTPHP_PATH)) { fputs($fp, '//'); $force_dolibarr_lib_ODTPHP_PATH = ''; } + if (empty($force_dolibarr_lib_ODTPHP_PATH)) { + fputs($fp, '//'); $force_dolibarr_lib_ODTPHP_PATH = ''; + } fputs($fp, '$dolibarr_lib_ODTPHP_PATH=\''.$force_dolibarr_lib_ODTPHP_PATH.'\';'); fputs($fp, "\n"); - if (empty($force_dolibarr_lib_ODTPHP_PATHTOPCLZIP)) { fputs($fp, '//'); $force_dolibarr_lib_ODTPHP_PATHTOPCLZIP = ''; } + if (empty($force_dolibarr_lib_ODTPHP_PATHTOPCLZIP)) { + fputs($fp, '//'); $force_dolibarr_lib_ODTPHP_PATHTOPCLZIP = ''; + } fputs($fp, '$dolibarr_lib_ODTPHP_PATHTOPCLZIP=\''.$force_dolibarr_lib_ODTPHP_PATHTOPCLZIP.'\';'); fputs($fp, "\n"); - if (empty($force_dolibarr_js_CKEDITOR)) { fputs($fp, '//'); $force_dolibarr_js_CKEDITOR = ''; } + if (empty($force_dolibarr_js_CKEDITOR)) { + fputs($fp, '//'); $force_dolibarr_js_CKEDITOR = ''; + } fputs($fp, '$dolibarr_js_CKEDITOR=\''.$force_dolibarr_js_CKEDITOR.'\';'); fputs($fp, "\n"); - if (empty($force_dolibarr_js_JQUERY)) { fputs($fp, '//'); $force_dolibarr_js_JQUERY = ''; } + if (empty($force_dolibarr_js_JQUERY)) { + fputs($fp, '//'); $force_dolibarr_js_JQUERY = ''; + } fputs($fp, '$dolibarr_js_JQUERY=\''.$force_dolibarr_js_JQUERY.'\';'); fputs($fp, "\n"); - if (empty($force_dolibarr_js_JQUERY_UI)) { fputs($fp, '//'); $force_dolibarr_js_JQUERY_UI = ''; } + if (empty($force_dolibarr_js_JQUERY_UI)) { + fputs($fp, '//'); $force_dolibarr_js_JQUERY_UI = ''; + } fputs($fp, '$dolibarr_js_JQUERY_UI=\''.$force_dolibarr_js_JQUERY_UI.'\';'); fputs($fp, "\n"); // Write params to overwrites default font path fputs($fp, "\n"); - if (empty($force_dolibarr_font_DOL_DEFAULT_TTF)) { fputs($fp, '//'); $force_dolibarr_font_DOL_DEFAULT_TTF = ''; } - fputs($fp, '$dolibarr_font_DOL_DEFAULT_TTF=\''.$force_dolibarr_font_DOL_DEFAULT_TTF.'\';'); + if (empty($force_dolibarr_font_DOL_DEFAULT_TTF)) { + fputs($fp, '//'); $force_dolibarr_font_DOL_DEFAULT_TTF = ''; + } + fputs($fp, '$dolibarr_font_DOL_DEFAULT_TTF=\''.$force_dolibarr_font_DOL_DEFAULT_TTF.'\';'); fputs($fp, "\n"); - if (empty($force_dolibarr_font_DOL_DEFAULT_TTF_BOLD)) { fputs($fp, '//'); $force_dolibarr_font_DOL_DEFAULT_TTF_BOLD = ''; } + if (empty($force_dolibarr_font_DOL_DEFAULT_TTF_BOLD)) { + fputs($fp, '//'); $force_dolibarr_font_DOL_DEFAULT_TTF_BOLD = ''; + } fputs($fp, '$dolibarr_font_DOL_DEFAULT_TTF_BOLD=\''.$force_dolibarr_font_DOL_DEFAULT_TTF_BOLD.'\';'); fputs($fp, "\n"); @@ -992,8 +985,7 @@ function write_conf_file($conffile) fclose($fp); - if (file_exists("$conffile")) - { + if (file_exists("$conffile")) { include $conffile; // force config reload, do not put include_once conf($dolibarr_main_document_root); diff --git a/htdocs/install/step2.php b/htdocs/install/step2.php index 20c57cb0ccf..d9321656355 100644 --- a/htdocs/install/step2.php +++ b/htdocs/install/step2.php @@ -49,23 +49,37 @@ $langs->setDefaultLang($setuplang); $langs->loadLangs(array("admin", "install")); $choix = 0; -if ($dolibarr_main_db_type == "mysqli") $choix = 1; -if ($dolibarr_main_db_type == "pgsql") $choix = 2; -if ($dolibarr_main_db_type == "mssql") $choix = 3; -if ($dolibarr_main_db_type == "sqlite") $choix = 4; -if ($dolibarr_main_db_type == "sqlite3") $choix = 5; +if ($dolibarr_main_db_type == "mysqli") { + $choix = 1; +} +if ($dolibarr_main_db_type == "pgsql") { + $choix = 2; +} +if ($dolibarr_main_db_type == "mssql") { + $choix = 3; +} +if ($dolibarr_main_db_type == "sqlite") { + $choix = 4; +} +if ($dolibarr_main_db_type == "sqlite3") { + $choix = 5; +} //if (empty($choix)) dol_print_error('','Database type '.$dolibarr_main_db_type.' not supported into step2.php page'); // Now we load forced values from install.forced.php file. $useforcedwizard = false; $forcedfile = "./install.forced.php"; -if ($conffile == "/etc/dolibarr/conf.php") $forcedfile = "/etc/dolibarr/install.forced.php"; +if ($conffile == "/etc/dolibarr/conf.php") { + $forcedfile = "/etc/dolibarr/install.forced.php"; +} if (@file_exists($forcedfile)) { $useforcedwizard = true; include_once $forcedfile; // test for travis - if (!empty($argv[1]) && $argv[1] == "set") $action = "set"; + if (!empty($argv[1]) && $argv[1] == "set") { + $action = "set"; + } } dolibarr_install_syslog("- step2: entering step2.php page"); @@ -78,15 +92,13 @@ dolibarr_install_syslog("- step2: entering step2.php page"); pHeader($langs->trans("CreateDatabaseObjects"), "step4"); // Test if we can run a first install process -if (!is_writable($conffile)) -{ +if (!is_writable($conffile)) { print $langs->trans("ConfFileIsNotWritable", $conffiletoshow); pFooter(1, $setuplang, 'jscheckparam'); exit; } -if ($action == "set") -{ +if ($action == "set") { print '<h3><img class="valigntextbottom" src="../theme/common/octicons/build/svg/database.svg" width="20" alt="Database"> '.$langs->trans("Database").'</h3>'; print '<table cellspacing="0" style="padding: 4px 4px 4px 0" border="0" width="100%">'; @@ -94,8 +106,7 @@ if ($action == "set") $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); - if ($db->connected) - { + if ($db->connected) { print "<tr><td>"; print $langs->trans("ServerConnection")." : ".$conf->db->host.'</td><td><img src="../theme/eldy/img/tick.png" alt="Ok"></td></tr>'; $ok = 1; @@ -103,10 +114,8 @@ if ($action == "set") print "<tr><td>Failed to connect to server : ".$conf->db->host.'</td><td><img src="../theme/eldy/img/error.png" alt="Error"></td></tr>'; } - if ($ok) - { - if ($db->database_selected) - { + if ($ok) { + if ($db->database_selected) { dolibarr_install_syslog("step2: successful connection to database: ".$conf->db->name); } else { dolibarr_install_syslog("step2: failed connection to database :".$conf->db->name, LOG_ERR); @@ -117,8 +126,7 @@ if ($action == "set") // Affiche version - if ($ok) - { + if ($ok) { $version = $db->getVersion(); $versionarray = $db->getVersionArray(); print '<tr><td>'.$langs->trans("DatabaseVersion").'</td>'; @@ -145,13 +153,12 @@ if ($action == "set") /************************************************************************************** - * - * Chargement fichiers tables/*.sql (non *.key.sql) - * A faire avant les fichiers *.key.sql - * - ***************************************************************************************/ - if ($ok && $createtables) - { + * + * Chargement fichiers tables/*.sql (non *.key.sql) + * A faire avant les fichiers *.key.sql + * + ***************************************************************************************/ + if ($ok && $createtables) { // We always choose in mysql directory (Conversion is done by driver to translate SQL syntax) $dir = "mysql/tables/"; @@ -160,12 +167,9 @@ if ($action == "set") dolibarr_install_syslog("step2: open tables directory ".$dir." handle=".$handle); $tablefound = 0; $tabledata = array(); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/\.sql$/i', $file) && preg_match('/^llx_/i', $file) && !preg_match('/\.key\.sql$/i', $file)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/\.sql$/i', $file) && preg_match('/^llx_/i', $file) && !preg_match('/\.key\.sql$/i', $file)) { $tablefound++; $tabledata[] = $file; } @@ -175,18 +179,14 @@ if ($action == "set") // Sort list of sql files on alphabetical order (load order is important) sort($tabledata); - foreach ($tabledata as $file) - { + foreach ($tabledata as $file) { $name = substr($file, 0, dol_strlen($file) - 4); $buffer = ''; $fp = fopen($dir.$file, "r"); - if ($fp) - { - while (!feof($fp)) - { + if ($fp) { + while (!feof($fp)) { $buf = fgets($fp, 4096); - if (substr($buf, 0, 2) <> '--') - { + if (substr($buf, 0, 2) <> '--') { $buf = preg_replace('/--(.+)*/', '', $buf); $buffer .= $buf; } @@ -194,8 +194,7 @@ if ($action == "set") fclose($fp); $buffer = trim($buffer); - if ($conf->db->type == 'mysql' || $conf->db->type == 'mysqli') // For Mysql 5.5+, we must replace type=innodb with ENGINE=innodb - { + if ($conf->db->type == 'mysql' || $conf->db->type == 'mysqli') { // For Mysql 5.5+, we must replace type=innodb with ENGINE=innodb $buffer = preg_replace('/type=innodb/i', 'ENGINE=innodb', $buffer); } else { // Keyword ENGINE is MySQL-specific, so scrub it for @@ -205,8 +204,7 @@ if ($action == "set") } // Replace the prefix tables - if ($dolibarr_main_db_prefix != 'llx_') - { + if ($dolibarr_main_db_prefix != 'llx_') { $buffer = preg_replace('/llx_/i', $dolibarr_main_db_prefix, $buffer); } @@ -215,14 +213,12 @@ if ($action == "set") dolibarr_install_syslog("step2: request: ".$buffer); $resql = $db->query($buffer, 0, 'dml'); - if ($resql) - { + if ($resql) { // print "<td>OK requete ==== $buffer</td></tr>"; $db->free($resql); } else { if ($db->errno() == 'DB_ERROR_TABLE_ALREADY_EXISTS' || - $db->errno() == 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS') - { + $db->errno() == 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS') { //print "<td>Deja existante</td></tr>"; } else { print "<tr><td>".$langs->trans("CreateTableAndPrimaryKey", $name); @@ -241,10 +237,8 @@ if ($action == "set") } } - if ($tablefound) - { - if ($error == 0) - { + if ($tablefound) { + if ($error == 0) { print '<tr><td>'; print $langs->trans("TablesAndPrimaryKeysCreation").'</td><td><img src="../theme/eldy/img/tick.png" alt="Ok"></td></tr>'; $ok = 1; @@ -257,13 +251,12 @@ if ($action == "set") /*************************************************************************************** - * - * Chargement fichiers tables/*.key.sql - * A faire apres les fichiers *.sql - * - ***************************************************************************************/ - if ($ok && $createkeys) - { + * + * Chargement fichiers tables/*.key.sql + * A faire apres les fichiers *.sql + * + ***************************************************************************************/ + if ($ok && $createkeys) { // We always choose in mysql directory (Conversion is done by driver to translate SQL syntax) $dir = "mysql/tables/"; @@ -272,12 +265,9 @@ if ($action == "set") dolibarr_install_syslog("step2: open keys directory ".$dir." handle=".$handle); $tablefound = 0; $tabledata = array(); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/\.sql$/i', $file) && preg_match('/^llx_/i', $file) && preg_match('/\.key\.sql$/i', $file)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/\.sql$/i', $file) && preg_match('/^llx_/i', $file) && preg_match('/\.key\.sql$/i', $file)) { $tablefound++; $tabledata[] = $file; } @@ -287,40 +277,33 @@ if ($action == "set") // Sort list of sql files on alphabetical order (load order is important) sort($tabledata); - foreach ($tabledata as $file) - { + foreach ($tabledata as $file) { $name = substr($file, 0, dol_strlen($file) - 4); //print "<tr><td>Creation de la table $name</td>"; $buffer = ''; $fp = fopen($dir.$file, "r"); - if ($fp) - { - while (!feof($fp)) - { + if ($fp) { + while (!feof($fp)) { $buf = fgets($fp, 4096); // Special case of lines allowed for some version only - if ($choix == 1 && preg_match('/^--\sV([0-9\.]+)/i', $buf, $reg)) - { + if ($choix == 1 && preg_match('/^--\sV([0-9\.]+)/i', $buf, $reg)) { $versioncommande = explode('.', $reg[1]); //print var_dump($versioncommande); //print var_dump($versionarray); if (count($versioncommande) && count($versionarray) - && versioncompare($versioncommande, $versionarray) <= 0) - { + && versioncompare($versioncommande, $versionarray) <= 0) { // Version qualified, delete SQL comments $buf = preg_replace('/^--\sV([0-9\.]+)/i', '', $buf); //print "Ligne $i qualifiee par version: ".$buf.'<br>'; } } - if ($choix == 2 && preg_match('/^--\sPOSTGRESQL\sV([0-9\.]+)/i', $buf, $reg)) - { + if ($choix == 2 && preg_match('/^--\sPOSTGRESQL\sV([0-9\.]+)/i', $buf, $reg)) { $versioncommande = explode('.', $reg[1]); //print var_dump($versioncommande); //print var_dump($versionarray); if (count($versioncommande) && count($versionarray) - && versioncompare($versioncommande, $versionarray) <= 0) - { + && versioncompare($versioncommande, $versionarray) <= 0) { // Version qualified, delete SQL comments $buf = preg_replace('/^--\sPOSTGRESQL\sV([0-9\.]+)/i', '', $buf); //print "Ligne $i qualifiee par version: ".$buf.'<br>'; @@ -328,20 +311,19 @@ if ($action == "set") } // Ajout ligne si non commentaire - if (!preg_match('/^--/i', $buf)) $buffer .= $buf; + if (!preg_match('/^--/i', $buf)) { + $buffer .= $buf; + } } fclose($fp); // Si plusieurs requetes, on boucle sur chaque $listesql = explode(';', $buffer); - foreach ($listesql as $req) - { + foreach ($listesql as $req) { $buffer = trim($req); - if ($buffer) - { + if ($buffer) { // Replace the prefix tables - if ($dolibarr_main_db_prefix != 'llx_') - { + if ($dolibarr_main_db_prefix != 'llx_') { $buffer = preg_replace('/llx_/i', $dolibarr_main_db_prefix, $buffer); } @@ -350,8 +332,7 @@ if ($action == "set") dolibarr_install_syslog("step2: request: ".$buffer); $resql = $db->query($buffer, 0, 'dml'); - if ($resql) - { + if ($resql) { //print "<td>OK requete ==== $buffer</td></tr>"; $db->free($resql); } else { @@ -359,8 +340,7 @@ if ($action == "set") $db->errno() == 'DB_ERROR_CANNOT_CREATE' || $db->errno() == 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS' || $db->errno() == 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS' || - preg_match('/duplicate key name/i', $db->error())) - { + preg_match('/duplicate key name/i', $db->error())) { //print "<td>Deja existante</td></tr>"; $key_exists = 1; } else { @@ -382,8 +362,7 @@ if ($action == "set") } } - if ($tablefound && $error == 0) - { + if ($tablefound && $error == 0) { print '<tr><td>'; print $langs->trans("OtherKeysCreation").'</td><td><img src="../theme/eldy/img/tick.png" alt="Ok"></td></tr>'; $okkeys = 1; @@ -392,32 +371,32 @@ if ($action == "set") /*************************************************************************************** - * - * Chargement fichier functions.sql - * - ***************************************************************************************/ - if ($ok && $createfunctions) - { + * + * Chargement fichier functions.sql + * + ***************************************************************************************/ + if ($ok && $createfunctions) { // For this file, we use a directory according to database type - if ($choix == 1) $dir = "mysql/functions/"; - elseif ($choix == 2) $dir = "pgsql/functions/"; - elseif ($choix == 3) $dir = "mssql/functions/"; - elseif ($choix == 4) { $dir = "sqlite3/functions/"; } + if ($choix == 1) { + $dir = "mysql/functions/"; + } elseif ($choix == 2) { + $dir = "pgsql/functions/"; + } elseif ($choix == 3) { + $dir = "mssql/functions/"; + } elseif ($choix == 4) { + $dir = "sqlite3/functions/"; + } // Creation donnees $file = "functions.sql"; - if (file_exists($dir.$file)) - { + if (file_exists($dir.$file)) { $fp = fopen($dir.$file, "r"); dolibarr_install_syslog("step2: open function file ".$dir.$file." handle=".$fp); - if ($fp) - { + if ($fp) { $buffer = ''; - while (!feof($fp)) - { + while (!feof($fp)) { $buf = fgets($fp, 4096); - if (substr($buf, 0, 2) <> '--') - { + if (substr($buf, 0, 2) <> '--') { $buffer .= $buf."§"; } } @@ -427,27 +406,22 @@ if ($action == "set") // If several requests, we loop on each of them $listesql = explode('§', $buffer); - foreach ($listesql as $buffer) - { + foreach ($listesql as $buffer) { $buffer = trim($buffer); - if ($buffer) - { + if ($buffer) { // Replace the prefix in table names - if ($dolibarr_main_db_prefix != 'llx_') - { + if ($dolibarr_main_db_prefix != 'llx_') { $buffer = preg_replace('/llx_/i', $dolibarr_main_db_prefix, $buffer); } dolibarr_install_syslog("step2: request: ".$buffer); print "<!-- Insert line : ".$buffer."<br>-->\n"; $resql = $db->query($buffer, 0, 'dml'); - if ($resql) - { + if ($resql) { $ok = 1; $db->free($resql); } else { if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS' - || $db->errno() == 'DB_ERROR_KEY_NAME_ALREADY_EXISTS') - { + || $db->errno() == 'DB_ERROR_KEY_NAME_ALREADY_EXISTS') { //print "Insert line : ".$buffer."<br>\n"; } else { $ok = 0; @@ -463,8 +437,7 @@ if ($action == "set") } print "<tr><td>".$langs->trans("FunctionsCreation")."</td>"; - if ($ok) - { + if ($ok) { print '<td><img src="../theme/eldy/img/tick.png" alt="Ok"></td></tr>'; } else { print '<td><img src="../theme/eldy/img/error.png" alt="Error"></td></tr>'; @@ -475,12 +448,11 @@ if ($action == "set") /*************************************************************************************** - * - * Load files data/*.sql - * - ***************************************************************************************/ - if ($ok && $createdata) - { + * + * Load files data/*.sql + * + ***************************************************************************************/ + if ($ok && $createdata) { // We always choose in mysql directory (Conversion is done by driver to translate SQL syntax) $dir = "mysql/data/"; @@ -489,17 +461,15 @@ if ($action == "set") dolibarr_install_syslog("step2: open directory data ".$dir." handle=".$handle); $tablefound = 0; $tabledata = array(); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/\.sql$/i', $file) && preg_match('/^llx_/i', $file)) - { - if (preg_match('/^llx_accounting_account_/', $file)) continue; // We discard data file of chart of account. Will be loaded when a chart is selected. + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/\.sql$/i', $file) && preg_match('/^llx_/i', $file)) { + if (preg_match('/^llx_accounting_account_/', $file)) { + continue; // We discard data file of chart of account. Will be loaded when a chart is selected. + } //print 'x'.$file.'-'.$createdata.'<br>'; - if (is_numeric($createdata) || preg_match('/'.preg_quote($createdata).'/i', $file)) - { + if (is_numeric($createdata) || preg_match('/'.preg_quote($createdata).'/i', $file)) { $tablefound++; $tabledata[] = $file; } @@ -510,33 +480,33 @@ if ($action == "set") // Sort list of data files on alphabetical order (load order is important) sort($tabledata); - foreach ($tabledata as $file) - { + foreach ($tabledata as $file) { $name = substr($file, 0, dol_strlen($file) - 4); $fp = fopen($dir.$file, "r"); dolibarr_install_syslog("step2: open data file ".$dir.$file." handle=".$fp); - if ($fp) - { + if ($fp) { $arrayofrequests = array(); $linefound = 0; $linegroup = 0; $sizeofgroup = 1; // Grouping request to have 1 query for several requests does not works with mysql, so we use 1. // Load all requests - while (!feof($fp)) - { + while (!feof($fp)) { $buffer = fgets($fp, 4096); $buffer = trim($buffer); - if ($buffer) - { - if (substr($buffer, 0, 2) == '--') continue; + if ($buffer) { + if (substr($buffer, 0, 2) == '--') { + continue; + } - if ($linefound && ($linefound % $sizeofgroup) == 0) - { + if ($linefound && ($linefound % $sizeofgroup) == 0) { $linegroup++; } - if (empty($arrayofrequests[$linegroup])) $arrayofrequests[$linegroup] = $buffer; - else $arrayofrequests[$linegroup] .= " ".$buffer; + if (empty($arrayofrequests[$linegroup])) { + $arrayofrequests[$linegroup] = $buffer; + } else { + $arrayofrequests[$linegroup] .= " ".$buffer; + } $linefound++; } @@ -549,22 +519,18 @@ if ($action == "set") $db->begin(); // We loop on each requests of file - foreach ($arrayofrequests as $buffer) - { + foreach ($arrayofrequests as $buffer) { // Replace the prefix tables - if ($dolibarr_main_db_prefix != 'llx_') - { + if ($dolibarr_main_db_prefix != 'llx_') { $buffer = preg_replace('/llx_/i', $dolibarr_main_db_prefix, $buffer); } //dolibarr_install_syslog("step2: request: " . $buffer); $resql = $db->query($buffer, 1); - if ($resql) - { + if ($resql) { //$db->free($resql); // Not required as request we launch here does not return memory needs. } else { - if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { //print "<tr><td>Insertion ligne : $buffer</td><td>"; } else { $ok = 0; @@ -574,14 +540,16 @@ if ($action == "set") } } - if ($okallfile) $db->commit(); - else $db->rollback(); + if ($okallfile) { + $db->commit(); + } else { + $db->rollback(); + } } } print "<tr><td>".$langs->trans("ReferenceDataLoading")."</td>"; - if ($ok) - { + if ($ok) { print '<td><img src="../theme/eldy/img/tick.png" alt="Ok"></td></tr>'; } else { print '<td><img src="../theme/eldy/img/error.png" alt="Error"></td></tr>'; @@ -595,7 +563,9 @@ if ($action == "set") $ret = 0; -if (!$ok && isset($argv[1])) $ret = 1; +if (!$ok && isset($argv[1])) { + $ret = 1; +} dolibarr_install_syslog("Exit ".$ret); dolibarr_install_syslog("- step2: end"); @@ -621,7 +591,11 @@ print $out; pFooter($ok ? 0 : 1, $setuplang); -if (isset($db) && is_object($db)) $db->close(); +if (isset($db) && is_object($db)) { + $db->close(); +} // Return code if ran from command line -if ($ret) exit($ret); +if ($ret) { + exit($ret); +} diff --git a/htdocs/install/step4.php b/htdocs/install/step4.php index ca188ae4d5b..7d03c7b6fd0 100644 --- a/htdocs/install/step4.php +++ b/htdocs/install/step4.php @@ -40,7 +40,9 @@ $langs->loadLangs(array("admin", "install")); // Now we load forced value from install.forced.php file. $useforcedwizard = false; $forcedfile = "./install.forced.php"; -if ($conffile == "/etc/dolibarr/conf.php") $forcedfile = "/etc/dolibarr/install.forced.php"; +if ($conffile == "/etc/dolibarr/conf.php") { + $forcedfile = "/etc/dolibarr/install.forced.php"; +} if (@file_exists($forcedfile)) { $useforcedwizard = true; include_once $forcedfile; @@ -60,8 +62,7 @@ $ok = 0; pHeader($langs->trans("AdminAccountCreation"), "step5"); // Test if we can run a first install process -if (!is_writable($conffile)) -{ +if (!is_writable($conffile)) { print $langs->trans("ConfFileIsNotWritable", $conffiletoshow); pFooter(1, $setuplang, 'jscheckparam'); exit; @@ -77,8 +78,7 @@ print '<table cellspacing="0" cellpadding="2">'; $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); -if ($db->ok) -{ +if ($db->ok) { print '<tr><td><label for="login">'.$langs->trans("Login").' :</label></td><td>'; print '<input id="login" name="login" type="text" value="'.(!empty($_GET["login"]) ? GETPOST("login", 'alpha') : (isset($force_install_dolibarrlogin) ? $force_install_dolibarrlogin : '')).'"'.(@$force_install_noedit == 2 && $force_install_dolibarrlogin !== null ? ' disabled' : '').'></td></tr>'; print '<tr><td><label for="pass">'.$langs->trans("Password").' :</label></td><td>'; @@ -87,15 +87,13 @@ if ($db->ok) print '<input type="password" id="pass_verif" name="pass_verif" autocomplete="new-password"></td></tr>'; print '</table>'; - if (isset($_GET["error"]) && $_GET["error"] == 1) - { + if (isset($_GET["error"]) && $_GET["error"] == 1) { print '<br>'; print '<div class="error">'.$langs->trans("PasswordsMismatch").'</div>'; $error = 0; // We show button } - if (isset($_GET["error"]) && $_GET["error"] == 2) - { + if (isset($_GET["error"]) && $_GET["error"] == 2) { print '<br>'; print '<div class="error">'; print $langs->trans("PleaseTypePassword"); @@ -103,8 +101,7 @@ if ($db->ok) $error = 0; // We show button } - if (isset($_GET["error"]) && $_GET["error"] == 3) - { + if (isset($_GET["error"]) && $_GET["error"] == 3) { print '<br>'; print '<div class="error">'.$langs->trans("PleaseTypeALogin").'</div>'; $error = 0; // We show button @@ -112,7 +109,9 @@ if ($db->ok) } $ret = 0; -if ($error && isset($argv[1])) $ret = 1; +if ($error && isset($argv[1])) { + $ret = 1; +} dolibarr_install_syslog("Exit ".$ret); dolibarr_install_syslog("- step4: end"); @@ -122,4 +121,6 @@ pFooter($error, $setuplang); $db->close(); // Return code if ran from command line -if ($ret) exit($ret); +if ($ret) { + exit($ret); +} diff --git a/htdocs/install/step5.php b/htdocs/install/step5.php index ed64de7cbb1..8c6f1147e94 100644 --- a/htdocs/install/step5.php +++ b/htdocs/install/step5.php @@ -27,7 +27,9 @@ */ include_once 'inc.php'; -if (file_exists($conffile)) include_once $conffile; +if (file_exists($conffile)) { + include_once $conffile; +} require_once $dolibarr_main_document_root.'/core/lib/admin.lib.php'; require_once $dolibarr_main_document_root.'/core/lib/security.lib.php'; // for dol_hash @@ -42,13 +44,15 @@ $action = GETPOST('action', 'alpha') ?GETPOST('action', 'alpha') : (empty($argv[ // Define targetversion used to update MAIN_VERSION_LAST_INSTALL for first install // or MAIN_VERSION_LAST_UPGRADE for upgrade. $targetversion = DOL_VERSION; // If it's latest upgrade -if (!empty($action) && preg_match('/upgrade/i', $action)) // If it's an old upgrade -{ +if (!empty($action) && preg_match('/upgrade/i', $action)) { + // If it's an old upgrade $tmp = explode('_', $action, 2); - if ($tmp[0] == 'upgrade') - { - if (!empty($tmp[1])) $targetversion = $tmp[1]; // if $action = 'upgrade_6.0.0-beta', we use '6.0.0-beta' - else $targetversion = DOL_VERSION; // if $action = 'upgrade', we use DOL_VERSION + if ($tmp[0] == 'upgrade') { + if (!empty($tmp[1])) { + $targetversion = $tmp[1]; // if $action = 'upgrade_6.0.0-beta', we use '6.0.0-beta' + } else { + $targetversion = DOL_VERSION; // if $action = 'upgrade', we use DOL_VERSION + } } } @@ -63,7 +67,9 @@ $success = 0; $useforcedwizard = false; $forcedfile = "./install.forced.php"; -if ($conffile == "/etc/dolibarr/conf.php") $forcedfile = "/etc/dolibarr/install.forced.php"; +if ($conffile == "/etc/dolibarr/conf.php") { + $forcedfile = "/etc/dolibarr/install.forced.php"; +} if (@file_exists($forcedfile)) { $useforcedwizard = true; include_once $forcedfile; @@ -106,31 +112,31 @@ if ($action == "set") { * View */ +$morehtml = ''; + pHeader($langs->trans("SetupEnd"), "step5"); print '<br>'; // Test if we can run a first install process -if (empty($versionfrom) && empty($versionto) && !is_writable($conffile)) -{ +if (empty($versionfrom) && empty($versionto) && !is_writable($conffile)) { print $langs->trans("ConfFileIsNotWritable", $conffiletoshow); pFooter(1, $setuplang, 'jscheckparam'); exit; } -if ($action == "set" || empty($action) || preg_match('/upgrade/i', $action)) -{ +if ($action == "set" || empty($action) || preg_match('/upgrade/i', $action)) { $error = 0; // If password is encoded, we decode it - if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) - { + if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) { require_once $dolibarr_main_document_root.'/core/lib/security.lib.php'; - if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) - { + if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) { $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass); $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass); $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially crypted - } else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } else { + $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } } $conf->db->type = $dolibarr_main_db_type; @@ -151,8 +157,7 @@ if ($action == "set" || empty($action) || preg_match('/upgrade/i', $action)) $ok = 0; // If first install - if ($action == "set") - { + if ($action == "set") { // Active module user $modName = 'modUser'; $file = $modName.".class.php"; @@ -160,13 +165,16 @@ if ($action == "set" || empty($action) || preg_match('/upgrade/i', $action)) include_once DOL_DOCUMENT_ROOT."/core/modules/".$file; $objMod = new $modName($db); $result = $objMod->init(); - if (!$result) print 'ERROR in activating module file='.$file; + if (!$result) { + print 'ERROR in activating module file='.$file; + } - if ($db->connected) - { + if ($db->connected) { $conf->setValues($db); // Reset forced setup after the setValues - if (defined('SYSLOG_FILE')) $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); + if (defined('SYSLOG_FILE')) { + $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); + } $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1; // Create admin user @@ -176,17 +184,17 @@ if ($action == "set" || empty($action) || preg_match('/upgrade/i', $action)) $sql = "SELECT u.rowid, u.pass, u.pass_crypted"; $sql .= " FROM ".MAIN_DB_PREFIX."user as u"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $numrows = $db->num_rows($resql); - if ($numrows == 0) - { + if ($numrows == 0) { // Define default setup for password encryption dolibarr_set_const($db, "DATABASE_PWD_ENCRYPTED", "1", 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_SECURITY_SALT", dol_print_date(dol_now(), 'dayhourlog'), 'chaine', 0, '', 0); // All entities - if (function_exists('password_hash')) + if (function_exists('password_hash')) { dolibarr_set_const($db, "MAIN_SECURITY_HASH_ALGO", 'password_hash', 'chaine', 0, '', 0); // All entities - else dolibarr_set_const($db, "MAIN_SECURITY_HASH_ALGO", 'sha1md5', 'chaine', 0, '', 0); // All entities + } else { + dolibarr_set_const($db, "MAIN_SECURITY_HASH_ALGO", 'sha1md5', 'chaine', 0, '', 0); // All entities + } } dolibarr_install_syslog('step5: DATABASE_PWD_ENCRYPTED = '.$conf->global->DATABASE_PWD_ENCRYPTED.' MAIN_SECURITY_HASH_ALGO = '.$conf->global->MAIN_SECURITY_HASH_ALGO, LOG_INFO); @@ -208,13 +216,11 @@ if ($action == "set" || empty($action) || preg_match('/upgrade/i', $action)) $conf->global->USER_MAIL_REQUIRED = 0; // Force global option to be sure to create a new user with no email $result = $newuser->create($createuser, 1); - if ($result > 0) - { + if ($result > 0) { print $langs->trans("AdminLoginCreatedSuccessfuly", $login)."<br>"; $success = 1; } else { - if ($newuser->error == 'ErrorLoginAlreadyExists') - { + if ($newuser->error == 'ErrorLoginAlreadyExists') { dolibarr_install_syslog('step5: AdminLoginAlreadyExists', LOG_WARNING); print '<br><div class="warning">'.$langs->trans("AdminLoginAlreadyExists", $login)."</div><br>"; $success = 1; @@ -224,14 +230,12 @@ if ($action == "set" || empty($action) || preg_match('/upgrade/i', $action)) } } - if ($success) - { + if ($success) { // Insert MAIN_VERSION_FIRST_INSTALL in a dedicated transaction. So if it fails (when first install was already done), we can do other following requests. $db->begin(); dolibarr_install_syslog('step5: set MAIN_VERSION_FIRST_INSTALL const to '.$targetversion, LOG_DEBUG); $resql = $db->query("INSERT INTO ".MAIN_DB_PREFIX."const(name,value,type,visible,note,entity) values(".$db->encrypt('MAIN_VERSION_FIRST_INSTALL', 1).",".$db->encrypt($targetversion, 1).",'chaine',0,'Dolibarr version when first install',0)"); - if ($resql) - { + if ($resql) { $conf->global->MAIN_VERSION_FIRST_INSTALL = $targetversion; $db->commit(); } else { @@ -243,29 +247,36 @@ if ($action == "set" || empty($action) || preg_match('/upgrade/i', $action)) dolibarr_install_syslog('step5: set MAIN_VERSION_LAST_INSTALL const to '.$targetversion, LOG_DEBUG); $resql = $db->query("DELETE FROM ".MAIN_DB_PREFIX."const WHERE ".$db->decrypt('name')."='MAIN_VERSION_LAST_INSTALL'"); - if (!$resql) dol_print_error($db, 'Error in setup program'); + if (!$resql) { + dol_print_error($db, 'Error in setup program'); + } $resql = $db->query("INSERT INTO ".MAIN_DB_PREFIX."const(name,value,type,visible,note,entity) values(".$db->encrypt('MAIN_VERSION_LAST_INSTALL', 1).",".$db->encrypt($targetversion, 1).",'chaine',0,'Dolibarr version when last install',0)"); - if (!$resql) dol_print_error($db, 'Error in setup program'); + if (!$resql) { + dol_print_error($db, 'Error in setup program'); + } $conf->global->MAIN_VERSION_LAST_INSTALL = $targetversion; - if ($useforcedwizard) - { + if ($useforcedwizard) { dolibarr_install_syslog('step5: set MAIN_REMOVE_INSTALL_WARNING const to 1', LOG_DEBUG); $resql = $db->query("DELETE FROM ".MAIN_DB_PREFIX."const WHERE ".$db->decrypt('name')."='MAIN_REMOVE_INSTALL_WARNING'"); - if (!$resql) dol_print_error($db, 'Error in setup program'); + if (!$resql) { + dol_print_error($db, 'Error in setup program'); + } $resql = $db->query("INSERT INTO ".MAIN_DB_PREFIX."const(name,value,type,visible,note,entity) values(".$db->encrypt('MAIN_REMOVE_INSTALL_WARNING', 1).",".$db->encrypt(1, 1).",'chaine',1,'Disable install warnings',0)"); - if (!$resql) dol_print_error($db, 'Error in setup program'); + if (!$resql) { + dol_print_error($db, 'Error in setup program'); + } $conf->global->MAIN_REMOVE_INSTALL_WARNING = 1; } // If we ask to force some modules to be enabled - if (!empty($force_install_module)) - { - if (!defined('DOL_DOCUMENT_ROOT') && !empty($dolibarr_main_document_root)) define('DOL_DOCUMENT_ROOT', $dolibarr_main_document_root); + if (!empty($force_install_module)) { + if (!defined('DOL_DOCUMENT_ROOT') && !empty($dolibarr_main_document_root)) { + define('DOL_DOCUMENT_ROOT', $dolibarr_main_document_root); + } $tmparray = explode(',', $force_install_module); - foreach ($tmparray as $modtoactivate) - { + foreach ($tmparray as $modtoactivate) { $modtoactivatenew = preg_replace('/\.class\.php$/i', '', $modtoactivate); print $langs->trans("ActivateModule", $modtoactivatenew).'<br>'; @@ -274,46 +285,55 @@ if ($action == "set" || empty($action) || preg_match('/upgrade/i', $action)) $res = dol_include_once("/core/modules/".$file); $res = activateModule($modtoactivatenew, 1); - if (!empty($res['errors'])) print 'ERROR in activating module file='.$file; + if (!empty($res['errors'])) { + print 'ERROR in activating module file='.$file; + } } } dolibarr_install_syslog('step5: remove MAIN_NOT_INSTALLED const'); $resql = $db->query("DELETE FROM ".MAIN_DB_PREFIX."const WHERE ".$db->decrypt('name')."='MAIN_NOT_INSTALLED'"); - if (!$resql) dol_print_error($db, 'Error in setup program'); + if (!$resql) { + dol_print_error($db, 'Error in setup program'); + } $db->commit(); } } else { print $langs->trans("ErrorFailedToConnect")."<br>"; } - } - // If upgrade - elseif (empty($action) || preg_match('/upgrade/i', $action)) - { - if ($db->connected) - { + } elseif (empty($action) || preg_match('/upgrade/i', $action)) { + // If upgrade + if ($db->connected) { $conf->setValues($db); // Reset forced setup after the setValues - if (defined('SYSLOG_FILE')) $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); + if (defined('SYSLOG_FILE')) { + $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); + } $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1; // Define if we need to update the MAIN_VERSION_LAST_UPGRADE value in database $tagdatabase = false; - if (empty($conf->global->MAIN_VERSION_LAST_UPGRADE)) $tagdatabase = true; // We don't know what it was before, so now we consider we are version choosed. - else { + if (empty($conf->global->MAIN_VERSION_LAST_UPGRADE)) { + $tagdatabase = true; // We don't know what it was before, so now we consider we are version choosed. + } else { $mainversionlastupgradearray = preg_split('/[.-]/', $conf->global->MAIN_VERSION_LAST_UPGRADE); $targetversionarray = preg_split('/[.-]/', $targetversion); - if (versioncompare($targetversionarray, $mainversionlastupgradearray) > 0) $tagdatabase = true; + if (versioncompare($targetversionarray, $mainversionlastupgradearray) > 0) { + $tagdatabase = true; + } } - if ($tagdatabase) - { + if ($tagdatabase) { dolibarr_install_syslog('step5: set MAIN_VERSION_LAST_UPGRADE const to value '.$targetversion); $resql = $db->query("DELETE FROM ".MAIN_DB_PREFIX."const WHERE ".$db->decrypt('name')."='MAIN_VERSION_LAST_UPGRADE'"); - if (!$resql) dol_print_error($db, 'Error in setup program'); + if (!$resql) { + dol_print_error($db, 'Error in setup program'); + } $resql = $db->query("INSERT INTO ".MAIN_DB_PREFIX."const(name,value,type,visible,note,entity) VALUES (".$db->encrypt('MAIN_VERSION_LAST_UPGRADE', 1).",".$db->encrypt($targetversion, 1).",'chaine',0,'Dolibarr version for last upgrade',0)"); - if (!$resql) dol_print_error($db, 'Error in setup program'); + if (!$resql) { + dol_print_error($db, 'Error in setup program'); + } $conf->global->MAIN_VERSION_LAST_UPGRADE = $targetversion; } else { dolibarr_install_syslog('step5: we run an upgrade to version '.$targetversion.' but database was already upgraded to '.$conf->global->MAIN_VERSION_LAST_UPGRADE.'. We keep MAIN_VERSION_LAST_UPGRADE as it is.'); @@ -337,31 +357,28 @@ if ($action == "set" || empty($action) || preg_match('/upgrade/i', $action)) // Create lock file // If first install -if ($action == "set" && $success) -{ - if (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) || ($conf->global->MAIN_VERSION_LAST_UPGRADE == DOL_VERSION)) - { +if ($action == "set" && $success) { + if (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) || ($conf->global->MAIN_VERSION_LAST_UPGRADE == DOL_VERSION)) { // Install is finished print $langs->trans("SystemIsInstalled")."<br>"; $createlock = 0; - if (!empty($force_install_lockinstall) || !empty($conf->global->MAIN_ALWAYS_CREATE_LOCK_AFTER_LAST_UPGRADE)) - { + if (!empty($force_install_lockinstall) || !empty($conf->global->MAIN_ALWAYS_CREATE_LOCK_AFTER_LAST_UPGRADE)) { // Install is finished, we create the lock file $lockfile = DOL_DATA_ROOT.'/install.lock'; $fp = @fopen($lockfile, "w"); - if ($fp) - { - if (empty($force_install_lockinstall) || $force_install_lockinstall == 1) $force_install_lockinstall = 444; // For backward compatibility + if ($fp) { + if (empty($force_install_lockinstall) || $force_install_lockinstall == 1) { + $force_install_lockinstall = 444; // For backward compatibility + } fwrite($fp, "This is a lock file to prevent use of install pages (set with permission ".$force_install_lockinstall.")"); fclose($fp); @chmod($lockfile, octdec($force_install_lockinstall)); $createlock = 1; } } - if (empty($createlock)) - { + if (empty($createlock)) { print '<div class="warning">'.$langs->trans("WarningRemoveInstallDir")."</div>"; } @@ -383,41 +400,37 @@ if ($action == "set" && $success) print '<span class="fas fa-link-alt"></span> '.$langs->trans("GoToUpgradePage"); print '</a></div>'; } -} -// If upgrade -elseif (empty($action) || preg_match('/upgrade/i', $action)) -{ - if (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) || ($conf->global->MAIN_VERSION_LAST_UPGRADE == DOL_VERSION)) - { +} elseif (empty($action) || preg_match('/upgrade/i', $action)) { + // If upgrade + if (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) || ($conf->global->MAIN_VERSION_LAST_UPGRADE == DOL_VERSION)) { // Upgrade is finished print $langs->trans("SystemIsUpgraded")."<br>"; $createlock = 0; - if (!empty($force_install_lockinstall) || !empty($conf->global->MAIN_ALWAYS_CREATE_LOCK_AFTER_LAST_UPGRADE)) - { + if (!empty($force_install_lockinstall) || !empty($conf->global->MAIN_ALWAYS_CREATE_LOCK_AFTER_LAST_UPGRADE)) { // Upgrade is finished, we create the lock file $lockfile = DOL_DATA_ROOT.'/install.lock'; $fp = @fopen($lockfile, "w"); - if ($fp) - { - if (empty($force_install_lockinstall) || $force_install_lockinstall == 1) $force_install_lockinstall = 444; // For backward compatibility + if ($fp) { + if (empty($force_install_lockinstall) || $force_install_lockinstall == 1) { + $force_install_lockinstall = 444; // For backward compatibility + } fwrite($fp, "This is a lock file to prevent use of install pages (set with permission ".$force_install_lockinstall.")"); fclose($fp); @chmod($lockfile, octdec($force_install_lockinstall)); $createlock = 1; } } - if (empty($createlock)) - { + if (empty($createlock)) { print '<br><div class="warning">'.$langs->trans("WarningRemoveInstallDir")."</div>"; } - print "<br><br>"; + print "<br>"; - print '<div class="center"><a href="../index.php?mainmenu=home'.(isset($login) ? '&username='.urlencode($login) : '').'">'; - print '<span class="fas fa-link-alt"></span> '.$langs->trans("GoToDolibarr").'...'; - print '</a></div><br>'; + $morehtml = '<br><div class="center"><a href="../index.php?mainmenu=home'.(isset($login) ? '&username='.urlencode($login) : '').'">'; + $morehtml .= '<span class="fas fa-link-alt"></span> '.$langs->trans("GoToDolibarr").'...'; + $morehtml .= '</a></div><br>'; } else { // If here MAIN_VERSION_LAST_UPGRADE is not empty print $langs->trans("VersionLastUpgrade").': <b><span class="ok">'.$conf->global->MAIN_VERSION_LAST_UPGRADE.'</span></b><br>'; @@ -425,9 +438,9 @@ elseif (empty($action) || preg_match('/upgrade/i', $action)) print "<br>"; - print '<div class="center"><a href="../install/index.php">'; - print '<span class="fas fa-link-alt"></span> '.$langs->trans("GoToUpgradePage"); - print '</a></div>'; + $morehtml = '<br><div class="center"><a href="../install/index.php">'; + $morehtml .= '<span class="fas fa-link-alt"></span> '.$langs->trans("GoToUpgradePage"); + $morehtml .= '</a></div>'; } } else { dol_print_error('', 'step5.php: unknown choice of action'); @@ -437,12 +450,16 @@ elseif (empty($action) || preg_match('/upgrade/i', $action)) clearstatcache(); $ret = 0; -if ($error && isset($argv[1])) $ret = 1; +if ($error && isset($argv[1])) { + $ret = 1; +} dolibarr_install_syslog("Exit ".$ret); dolibarr_install_syslog("- step5: Dolibarr setup finished"); -pFooter(1, $setuplang); +pFooter(1, $setuplang, '', 0, $morehtml); // Return code if ran from command line -if ($ret) exit($ret); +if ($ret) { + exit($ret); +} diff --git a/htdocs/install/upgrade.php b/htdocs/install/upgrade.php index 29b51746a14..c985a50806d 100644 --- a/htdocs/install/upgrade.php +++ b/htdocs/install/upgrade.php @@ -37,8 +37,7 @@ */ include_once 'inc.php'; -if (!file_exists($conffile)) -{ +if (!file_exists($conffile)) { print 'Error: Dolibarr config file was not found. This may means that Dolibarr is not installed yet. Please call the page "/install/index.php" instead of "/install/upgrade.php").'; } require_once $conffile; @@ -68,29 +67,35 @@ $ignoredbversion = (GETPOST('ignoredbversion', 'alpha', 3) == 'ignoredbversion') $langs->loadLangs(array("admin", "install", "other", "errors")); -if ($dolibarr_main_db_type == "mysqli") $choix = 1; -if ($dolibarr_main_db_type == "pgsql") $choix = 2; -if ($dolibarr_main_db_type == "mssql") $choix = 3; +if ($dolibarr_main_db_type == "mysqli") { + $choix = 1; +} +if ($dolibarr_main_db_type == "pgsql") { + $choix = 2; +} +if ($dolibarr_main_db_type == "mssql") { + $choix = 3; +} dolibarr_install_syslog("--- upgrade: Entering upgrade.php page"); -if (!is_object($conf)) dolibarr_install_syslog("upgrade2: conf file not initialized", LOG_ERR); +if (!is_object($conf)) { + dolibarr_install_syslog("upgrade2: conf file not initialized", LOG_ERR); +} /* * View */ -if (!$versionfrom && !$versionto) -{ +if (!$versionfrom && !$versionto) { print 'Error: Parameter versionfrom or versionto missing.'."\n"; print 'Upgrade must be ran from command line with parameters or called from page install/index.php (like a first install)'."\n"; // Test if batch mode $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); $path = __DIR__.'/'; - if (substr($sapi_type, 0, 3) == 'cli') - { + if (substr($sapi_type, 0, 3) == 'cli') { print 'Syntax from command line: '.$script_file." x.y.z a.b.c\n"; } exit; @@ -102,25 +107,25 @@ pHeader('', "upgrade2", GETPOST('action', 'aZ09'), 'versionfrom='.$versionfrom.' $actiondone = 0; // Action to launch the migrate script -if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ09'))) -{ +if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ09'))) { $actiondone = 1; - print '<h3><img class="valigntextbottom" src="../theme/common/octicons/build/svg/database.svg" width="20" alt="Database"> '.$langs->trans("DatabaseMigration").'</h3>'; + print '<h3><img class="valigntextbottom inline-block" src="../theme/common/octicons/build/svg/database.svg" width="20" alt="Database"> '; + print '<span class="inline-block">'.$langs->trans("DatabaseMigration").'</span></h3>'; print '<table cellspacing="0" cellpadding="1" border="0" width="100%">'; $error = 0; // If password is encoded, we decode it - if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) - { + if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) { require_once $dolibarr_main_document_root.'/core/lib/security.lib.php'; - if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) - { + if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) { $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass); $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass); $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially crypted - } else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } else { + $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } } // $conf is already instancied inside inc.php @@ -132,9 +137,13 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ $conf->db->pass = $dolibarr_main_db_pass; // Load type and crypt key - if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption = 0; + if (empty($dolibarr_main_db_encryption)) { + $dolibarr_main_db_encryption = 0; + } $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption; - if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey = ''; + if (empty($dolibarr_main_db_cryptkey)) { + $dolibarr_main_db_cryptkey = ''; + } $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey; $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); @@ -143,8 +152,7 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; $hookmanager = new HookManager($db); - if ($db->connected) - { + if ($db->connected) { print '<tr><td class="nowrap">'; print $langs->trans("ServerConnection")." : ".$dolibarr_main_db_host.'</td><td class="right"><span class="neutral">'.$langs->trans("OK").'</span></td></tr>'."\n"; dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ServerConnection").": $dolibarr_main_db_host ".$langs->transnoentities("OK")); @@ -155,10 +163,8 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ $ok = 0; } - if ($ok) - { - if ($db->database_selected) - { + if ($ok) { + if ($db->database_selected) { print '<tr><td class="nowrap">'; print $langs->trans("DatabaseConnection")." : ".$dolibarr_main_db_name.'</td><td class="right"><span class="neutral">'.$langs->trans("OK")."</span></td></tr>\n"; dolibarr_install_syslog("upgrade: Database connection successful: ".$dolibarr_main_db_name); @@ -171,15 +177,13 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ } // Affiche version - if ($ok) - { + if ($ok) { $version = $db->getVersion(); $versionarray = $db->getVersionArray(); print '<tr><td>'.$langs->trans("ServerVersion").'</td>'; print '<td class="right">'.$version.'</td></tr>'; dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ServerVersion").": ".$version); - if ($db->type == 'mysqli' && function_exists('mysqli_get_charset')) - { + if ($db->type == 'mysqli' && function_exists('mysqli_get_charset')) { $tmparray = $db->db->get_charset(); print '<tr><td>'.$langs->trans("ClientCharset").'</td>'; print '<td class="right">'.$tmparray->charset.'</td></tr>'; @@ -193,8 +197,7 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ $versionmindb = explode('.', $db::VERSIONMIN); //print join('.',$versionarray).' - '.join('.',$versionmindb); if (count($versionmindb) && count($versionarray) - && versioncompare($versionarray, $versionmindb) < 0) - { + && versioncompare($versionarray, $versionmindb) < 0) { // Warning: database version too low. print "<tr><td>".$langs->trans("ErrorDatabaseVersionTooLow", join('.', $versionarray), join('.', $versionmindb)).'</td><td class="right"><span class="error">'.$langs->trans("Error")."</span></td></tr>\n"; dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorDatabaseVersionTooLow", join('.', $versionarray), join('.', $versionmindb))); @@ -202,8 +205,7 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ } // Test database version is not forbidden for migration - if (empty($ignoredbversion)) - { + if (empty($ignoredbversion)) { $dbversion_disallowed = array( array('type'=>'mysql', 'version'=>array(5, 5, 40)), array('type'=>'mysqli', 'version'=>array(5, 5, 40)) //, @@ -211,17 +213,16 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ //array('type'=>'mysqli','version'=>array(5,5,41)) ); $listofforbiddenversion = ''; - foreach ($dbversion_disallowed as $dbversion_totest) - { - if ($dbversion_totest['type'] == $db->type) $listofforbiddenversion .= ($listofforbiddenversion ? ', ' : '').join('.', $dbversion_totest['version']); + foreach ($dbversion_disallowed as $dbversion_totest) { + if ($dbversion_totest['type'] == $db->type) { + $listofforbiddenversion .= ($listofforbiddenversion ? ', ' : '').join('.', $dbversion_totest['version']); + } } - foreach ($dbversion_disallowed as $dbversion_totest) - { + foreach ($dbversion_disallowed as $dbversion_totest) { //print $db->type.' - '.join('.',$versionarray).' - '.versioncompare($dbversion_totest['version'],$versionarray)."<br>\n"; if ($dbversion_totest['type'] == $db->type && (versioncompare($dbversion_totest['version'], $versionarray) == 0 || versioncompare($dbversion_totest['version'], $versionarray) <= -4 || versioncompare($dbversion_totest['version'], $versionarray) >= 4) - ) - { + ) { // Warning: database version too low. print '<tr><td><div class="warning">'.$langs->trans("ErrorDatabaseVersionForbiddenForMigration", join('.', $versionarray), $listofforbiddenversion)."</div></td><td class=\"right\">".$langs->trans("Error")."</td></tr>\n"; dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorDatabaseVersionForbiddenForMigration", join('.', $versionarray), $listofforbiddenversion)); @@ -233,8 +234,7 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ } // Force l'affichage de la progression - if ($ok) - { + if ($ok) { print '<tr><td colspan="2">'.$langs->trans("PleaseBePatient").'</td></tr>'; flush(); } @@ -243,12 +243,10 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ /* * Remove deprecated indexes and constraints for Mysql */ - if ($ok && preg_match('/mysql/', $db->type)) - { + if ($ok && preg_match('/mysql/', $db->type)) { $versioncommande = array(4, 0, 0); if (count($versioncommande) && count($versionarray) - && versioncompare($versioncommande, $versionarray) <= 0) // Si mysql >= 4.0 - { + && versioncompare($versioncommande, $versionarray) <= 0) { // Si mysql >= 4.0 dolibarr_install_syslog("Clean database from bad named constraints"); // Suppression vieilles contraintes sans noms et en doubles @@ -262,25 +260,20 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ ); $listtables = $db->DDLListTables($conf->db->name, ''); - foreach ($listtables as $val) - { + foreach ($listtables as $val) { // Database prefix filter - if (preg_match('/^'.MAIN_DB_PREFIX.'/', $val)) - { + if (preg_match('/^'.MAIN_DB_PREFIX.'/', $val)) { //print "x".$val."<br>"; $sql = "SHOW CREATE TABLE ".$val; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $values = $db->fetch_array($resql); $i = 0; $createsql = $values[1]; - while (preg_match('/CONSTRAINT `(0_[0-9a-zA-Z]+|[_0-9a-zA-Z]+_ibfk_[0-9]+)`/i', $createsql, $reg) && $i < 100) - { + while (preg_match('/CONSTRAINT `(0_[0-9a-zA-Z]+|[_0-9a-zA-Z]+_ibfk_[0-9]+)`/i', $createsql, $reg) && $i < 100) { $sqldrop = "ALTER TABLE ".$val." DROP FOREIGN KEY ".$reg[1]; $resqldrop = $db->query($sqldrop); - if ($resqldrop) - { + if ($resqldrop) { print '<tr><td colspan="2">'.$sqldrop.";</td></tr>\n"; } $createsql = preg_replace('/CONSTRAINT `'.$reg[1].'`/i', 'XXX', $createsql); @@ -288,8 +281,7 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ } $db->free($resql); } else { - if ($db->lasterrno() != 'DB_ERROR_NOSUCHTABLE') - { + if ($db->lasterrno() != 'DB_ERROR_NOSUCHTABLE') { print '<tr><td colspan="2"><span class="error">'.$sql.' : '.$db->lasterror()."</font></td></tr>\n"; } } @@ -299,12 +291,13 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ } /* - * Load sql files - */ - if ($ok) - { + * Load sql files + */ + if ($ok) { $dir = "mysql/migration/"; // We use mysql migration scripts whatever is database driver - if (!empty($dirmodule)) $dir = dol_buildpath('/'.$dirmodule.'/sql/', 0); + if (!empty($dirmodule)) { + $dir = dol_buildpath('/'.$dirmodule.'/sql/', 0); + } dolibarr_install_syslog("Scan sql files for migration files in ".$dir); // Clean last part to exclude minor version x.y.z -> x.y @@ -320,11 +313,11 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Get files list $filesindir = array(); $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/\.sql$/i', $file)) $filesindir[] = $file; + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/\.sql$/i', $file)) { + $filesindir[] = $file; + } } sort($filesindir); } else { @@ -332,27 +325,24 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ } // Define which file to run - foreach ($filesindir as $file) - { - if (preg_match('/'.$from.'/i', $file)) - { + foreach ($filesindir as $file) { + if (preg_match('/'.$from.'/i', $file)) { $filelist[] = $file; - } elseif (preg_match('/'.$to.'/i', $file)) // First test may be false if we migrate from x.y.* to x.y.* - { + } elseif (preg_match('/'.$to.'/i', $file)) { // First test may be false if we migrate from x.y.* to x.y.* $filelist[] = $file; } } - if (count($filelist) == 0) - { + if (count($filelist) == 0) { print '<div class="error">'.$langs->trans("ErrorNoMigrationFilesFoundForParameters").'</div>'; } else { $listoffileprocessed = array(); // Protection to avoid to process twice the same file // Loop on each migrate files - foreach ($filelist as $file) - { - if (in_array($dir.$file, $listoffileprocessed)) continue; + foreach ($filelist as $file) { + if (in_array($dir.$file, $listoffileprocessed)) { + continue; + } print '<tr><td colspan="2"><hr style="border-color: #ccc; border-top-style: none;"></td></tr>'; print '<tr><td class="nowrap">'.$langs->trans("ChoosedMigrateScript").'</td><td class="right">'.$file.'</td></tr>'."\n"; @@ -364,18 +354,13 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Scan if there is migration scripts that depends of Dolibarr version // for modules htdocs/module/sql or htdocs/custom/module/sql (files called "dolibarr_x.y.z-a.b.c.sql") $modulesfile = array(); - foreach ($conf->file->dol_document_root as $type => $dirroot) - { + foreach ($conf->file->dol_document_root as $type => $dirroot) { $handlemodule = @opendir($dirroot); // $dirroot may be '..' - if (is_resource($handlemodule)) - { - while (($filemodule = readdir($handlemodule)) !== false) - { - if (!preg_match('/\./', $filemodule) && is_dir($dirroot.'/'.$filemodule.'/sql')) // We exclude filemodule that contains . (are not directories) and are not directories. - { + if (is_resource($handlemodule)) { + while (($filemodule = readdir($handlemodule)) !== false) { + if (!preg_match('/\./', $filemodule) && is_dir($dirroot.'/'.$filemodule.'/sql')) { // We exclude filemodule that contains . (are not directories) and are not directories. //print "Scan for ".$dirroot . '/' . $filemodule . '/sql/'.$file; - if (is_file($dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file)) - { + if (is_file($dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file)) { $modulesfile[$dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file] = '/'.$filemodule.'/sql/dolibarr_'.$file; } } @@ -384,9 +369,10 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ } } - foreach ($modulesfile as $modulefilelong => $modulefileshort) - { - if (in_array($modulefilelong, $listoffileprocessed)) continue; + foreach ($modulesfile as $modulefilelong => $modulefileshort) { + if (in_array($modulefilelong, $listoffileprocessed)) { + continue; + } print '<tr><td colspan="2"><hr></td></tr>'; print '<tr><td class="nowrap">'.$langs->trans("ChoosedMigrateScript").' (external modules)</td><td class="right">'.$modulefileshort.'</td></tr>'."\n"; @@ -401,24 +387,33 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ print '</table>'; - if ($db->connected) $db->close(); + if ($db->connected) { + $db->close(); + } } -if (empty($actiondone)) -{ +if (empty($actiondone)) { print '<div class="error">'.$langs->trans("ErrorWrongParameters").'</div>'; } $ret = 0; -if (!$ok && isset($argv[1])) $ret = 1; +if (!$ok && isset($argv[1])) { + $ret = 1; +} dolibarr_install_syslog("Exit ".$ret); dolibarr_install_syslog("--- upgrade: end ".((!$ok && empty($_GET["ignoreerrors"])) || $dirmodule)); $nonext = (!$ok && empty($_GET["ignoreerrors"])) ? 2 : 0; -if ($dirmodule) $nonext = 1; +if ($dirmodule) { + $nonext = 1; +} pFooter($nonext, $setuplang); -if ($db->connected) $db->close(); +if ($db->connected) { + $db->close(); +} // Return code if ran from command line -if ($ret) exit($ret); +if ($ret) { + exit($ret); +} diff --git a/htdocs/install/upgrade2.php b/htdocs/install/upgrade2.php index 07c68a498b2..d613e4a18b0 100644 --- a/htdocs/install/upgrade2.php +++ b/htdocs/install/upgrade2.php @@ -39,8 +39,7 @@ */ include_once 'inc.php'; -if (!file_exists($conffile)) -{ +if (!file_exists($conffile)) { print 'Error: Dolibarr config file was not found. This may means that Dolibarr is not installed yet. Please call the page "/install/index.php" instead of "/install/upgrade.php").'; } require_once $conffile; @@ -64,9 +63,11 @@ $error = 0; // Ne fonctionne que si on est pas en safe_mode. $err = error_reporting(); error_reporting(0); -if (!empty($conf->global->MAIN_OVERRIDE_TIME_LIMIT)) +if (!empty($conf->global->MAIN_OVERRIDE_TIME_LIMIT)) { @set_time_limit((int) $conf->global->MAIN_OVERRIDE_TIME_LIMIT); -else @set_time_limit(600); +} else { + @set_time_limit(600); +} error_reporting($err); $setuplang = GETPOST("selectlang", 'aZ09', 3) ?GETPOST("selectlang", 'aZ09', 3) : 'auto'; @@ -77,13 +78,21 @@ $enablemodules = GETPOST("enablemodules", 'alpha', 3) ?GETPOST("enablemodules", $langs->loadLangs(array("admin", "install", "bills", "suppliers")); -if ($dolibarr_main_db_type == 'mysqli') $choix = 1; -if ($dolibarr_main_db_type == 'pgsql') $choix = 2; -if ($dolibarr_main_db_type == 'mssql') $choix = 3; +if ($dolibarr_main_db_type == 'mysqli') { + $choix = 1; +} +if ($dolibarr_main_db_type == 'pgsql') { + $choix = 2; +} +if ($dolibarr_main_db_type == 'mssql') { + $choix = 3; +} dolibarr_install_syslog("--- upgrade2: entering upgrade2.php page ".$versionfrom." ".$versionto." ".$enablemodules); -if (!is_object($conf)) dolibarr_install_syslog("upgrade2: conf file not initialized", LOG_ERR); +if (!is_object($conf)) { + dolibarr_install_syslog("upgrade2: conf file not initialized", LOG_ERR); +} @@ -91,16 +100,14 @@ if (!is_object($conf)) dolibarr_install_syslog("upgrade2: conf file not initiali * View */ -if ((!$versionfrom || preg_match('/version/', $versionfrom)) && (!$versionto || preg_match('/version/', $versionto))) -{ +if ((!$versionfrom || preg_match('/version/', $versionfrom)) && (!$versionto || preg_match('/version/', $versionto))) { print 'Error: Parameter versionfrom or versionto missing or having a bad format.'."\n"; print 'Upgrade must be ran from command line with parameters or called from page install/index.php (like a first install)'."\n"; // Test if batch mode $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); $path = __DIR__.'/'; - if (substr($sapi_type, 0, 3) == 'cli') - { + if (substr($sapi_type, 0, 3) == 'cli') { print 'Syntax from command line: '.$script_file." x.y.z a.b.c [MAIN_MODULE_NAME1_TO_ENABLE,MAIN_MODULE_NAME2_TO_ENABLE...]\n"; } exit; @@ -109,22 +116,22 @@ if ((!$versionfrom || preg_match('/version/', $versionfrom)) && (!$versionto || pHeader('', 'step5', GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'upgrade', 'versionfrom='.$versionfrom.'&versionto='.$versionto); -if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ09'))) -{ - print '<h3><img class="valigntextbottom" src="../theme/common/octicons/build/svg/database.svg" width="20" alt="Database"> '.$langs->trans('DataMigration').'</h3>'; +if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ09'))) { + print '<h3><img class="valigntextbottom inline-block" src="../theme/common/octicons/build/svg/database.svg" width="20" alt="Database"> '; + print '<span class="inline-block">'.$langs->trans('DataMigration').'</span></h3>'; print '<table cellspacing="0" cellpadding="1" border="0" width="100%">'; // If password is encoded, we decode it - if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) - { + if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) { require_once $dolibarr_main_document_root.'/core/lib/security.lib.php'; - if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) - { + if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) { $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass); $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass); $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially crypted - } else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } else { + $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } } // $conf is already instancied inside inc.php @@ -142,47 +149,48 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ $hookmanager = new HookManager($db); $hookmanager->initHooks(array('upgrade')); - if (!$db->connected) - { + if (!$db->connected) { print '<tr><td colspan="4">'.$langs->trans("ErrorFailedToConnectToDatabase", $conf->db->name).'</td><td class="right">'.$langs->trans('Error').'</td></tr>'; dolibarr_install_syslog('upgrade2: failed to connect to database :'.$conf->db->name.' on '.$conf->db->host.' for user '.$conf->db->user, LOG_ERR); $error++; } - if (!$error) - { - if ($db->database_selected) - { + if (!$error) { + if ($db->database_selected) { dolibarr_install_syslog('upgrade2: database connection successful :'.$dolibarr_main_db_name); } else { $error++; } } - if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption = 0; + if (empty($dolibarr_main_db_encryption)) { + $dolibarr_main_db_encryption = 0; + } $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption; - if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey = ''; + if (empty($dolibarr_main_db_cryptkey)) { + $dolibarr_main_db_cryptkey = ''; + } $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey; // Chargement config - if (!$error) - { + if (!$error) { $conf->setValues($db); // Reset forced setup after the setValues - if (defined('SYSLOG_FILE')) $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); + if (defined('SYSLOG_FILE')) { + $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); + } $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1; } /*************************************************************************************** - * - * Migration of data - * - ***************************************************************************************/ + * + * Migration of data + * + ***************************************************************************************/ $db->begin(); - if (!$error) - { + if (!$error) { // Current version is $conf->global->MAIN_VERSION_LAST_UPGRADE // Version to install is DOL_VERSION $dolibarrlastupgradeversionarray = preg_split('/[\.-]/', isset($conf->global->MAIN_VERSION_LAST_UPGRADE) ? $conf->global->MAIN_VERSION_LAST_UPGRADE : (isset($conf->global->MAIN_VERSION_LAST_INSTALL) ? $conf->global->MAIN_VERSION_LAST_INSTALL : '')); @@ -222,8 +230,7 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ $afterversionarray = explode('.', '2.0.0'); $beforeversionarray = explode('.', '2.7.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { // Script pour V2 -> V2.1 migrate_paiements($db, $langs, $conf); @@ -286,8 +293,7 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ $afterversionarray = explode('.', '2.7.9'); $beforeversionarray = explode('.', '2.8.9'); //print $versionto.' '.versioncompare($versiontoarray,$afterversionarray).' '.versioncompare($versiontoarray,$beforeversionarray); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_price_facture($db, $langs, $conf); // Code of this function works for 2.8+ because need a field tva_tx migrate_relationship_tables($db, $langs, $conf, 'co_exp', 'fk_commande', 'commande', 'fk_expedition', 'shipping'); @@ -312,8 +318,7 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Script for 2.9 $afterversionarray = explode('.', '2.8.9'); $beforeversionarray = explode('.', '2.9.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_project_task_time($db, $langs, $conf); migrate_customerorder_shipping($db, $langs, $conf); @@ -326,16 +331,14 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Script for 3.0 $afterversionarray = explode('.', '2.9.9'); $beforeversionarray = explode('.', '3.0.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { // No particular code } // Script for 3.1 $afterversionarray = explode('.', '3.0.9'); $beforeversionarray = explode('.', '3.1.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_rename_directories($db, $langs, $conf, '/rss', '/externalrss'); migrate_actioncomm_element($db, $langs, $conf); @@ -344,8 +347,7 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Script for 3.2 $afterversionarray = explode('.', '3.1.9'); $beforeversionarray = explode('.', '3.2.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_price_contrat($db, $langs, $conf); migrate_mode_reglement($db, $langs, $conf); @@ -356,8 +358,7 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Script for 3.3 $afterversionarray = explode('.', '3.2.9'); $beforeversionarray = explode('.', '3.3.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_categorie_association($db, $langs, $conf); } @@ -367,32 +368,28 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Tasks to do always and only into last targeted version $afterversionarray = explode('.', '3.6.9'); // target is after this $beforeversionarray = explode('.', '3.7.9'); // target is before this - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { - migrate_event_assignement($db, $langs, $conf); + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { + migrate_event_assignement($db, $langs, $conf); } // Scripts for 3.9 $afterversionarray = explode('.', '3.7.9'); $beforeversionarray = explode('.', '3.8.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { // No particular code } // Scripts for 4.0 $afterversionarray = explode('.', '3.9.9'); $beforeversionarray = explode('.', '4.0.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_rename_directories($db, $langs, $conf, '/fckeditor', '/medias'); } // Scripts for 5.0 $afterversionarray = explode('.', '4.0.9'); $beforeversionarray = explode('.', '5.0.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { // Migrate to add entity value into llx_societe_remise migrate_remise_entity($db, $langs, $conf); @@ -403,15 +400,12 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Scripts for 6.0 $afterversionarray = explode('.', '5.0.9'); $beforeversionarray = explode('.', '6.0.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { - if (!empty($conf->multicompany->enabled)) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { + if (!empty($conf->multicompany->enabled)) { global $multicompany_transverse_mode; // Only if the transverse mode is not used - if (empty($multicompany_transverse_mode)) - { + if (empty($multicompany_transverse_mode)) { // Migrate to add entity value into llx_user_rights migrate_user_rights_entity($db, $langs, $conf); @@ -424,8 +418,7 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Scripts for 7.0 $afterversionarray = explode('.', '6.0.9'); $beforeversionarray = explode('.', '7.0.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { // Migrate contact association migrate_event_assignement_contact($db, $langs, $conf); @@ -435,16 +428,14 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Scripts for 8.0 $afterversionarray = explode('.', '7.0.9'); $beforeversionarray = explode('.', '8.0.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_rename_directories($db, $langs, $conf, '/contracts', '/contract'); } // Scripts for 9.0 $afterversionarray = explode('.', '8.0.9'); $beforeversionarray = explode('.', '9.0.9'); - if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) - { + if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_user_photospath(); } @@ -460,15 +451,16 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ } // Code executed only if migration is LAST ONE. Must always be done. - if (versioncompare($versiontoarray, $versionranarray) >= 0 || versioncompare($versiontoarray, $versionranarray) <= -3) - { + if (versioncompare($versiontoarray, $versionranarray) >= 0 || versioncompare($versiontoarray, $versionranarray) <= -3) { // Reload modules (this must be always done and only into last targeted version, because code to reload module may need table structure of last version) $listofmodule = array( 'MAIN_MODULE_ACCOUNTING'=>'newboxdefonly', 'MAIN_MODULE_AGENDA'=>'newboxdefonly', + 'MAIN_MODULE_BANQUE'=>'menuonly', 'MAIN_MODULE_BARCODE'=>'newboxdefonly', 'MAIN_MODULE_CRON'=>'newboxdefonly', 'MAIN_MODULE_COMMANDE'=>'newboxdefonly', + 'MAIN_MODULE_BLOCKEDLOG'=>'noboxes', 'MAIN_MODULE_DEPLACEMENT'=>'newboxdefonly', 'MAIN_MODULE_DON'=>'newboxdefonly', 'MAIN_MODULE_ECM'=>'newboxdefonly', @@ -482,11 +474,13 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ 'MAIN_MODULE_PAYBOX'=>'newboxdefonly', 'MAIN_MODULE_PRINTING'=>'newboxdefonly', 'MAIN_MODULE_PRODUIT'=>'newboxdefonly', - 'MAIN_MODULE_RESOURCE'=>'newboxdefonly', + 'MAIN_MODULE_RECRUITMENT'=>'menuonly', + 'MAIN_MODULE_RESOURCE'=>'noboxes', 'MAIN_MODULE_SALARIES'=>'newboxdefonly', + 'MAIN_MODULE_SERVICE'=>'newboxdefonly', 'MAIN_MODULE_SYSLOG'=>'newboxdefonly', 'MAIN_MODULE_SOCIETE'=>'newboxdefonly', - 'MAIN_MODULE_SERVICE'=>'newboxdefonly', + 'MAIN_MODULE_STRIPE'=>'menuonly', 'MAIN_MODULE_TICKET'=>'newboxdefonly', 'MAIN_MODULE_TAKEPOS'=>'newboxdefonly', 'MAIN_MODULE_USER'=>'newboxdefonly', //This one must be always done and only into last targeted version) @@ -501,14 +495,12 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Can force activation of some module during migration with parameter 'enablemodules=MAIN_MODULE_XXX,MAIN_MODULE_YYY,...' // In most cases (online install or upgrade) $enablemodules is empty. Can be forced when ran from command line. - if (!$error && $enablemodules) - { + if (!$error && $enablemodules) { // Reload modules (this must be always done and only into last targeted version) $listofmodules = array(); $enablemodules = preg_replace('/enablemodules=/', '', $enablemodules); $tmplistofmodules = explode(',', $enablemodules); - foreach ($tmplistofmodules as $value) - { + foreach ($tmplistofmodules as $value) { $listofmodules[$value] = 'forceactivate'; } @@ -520,32 +512,28 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Can call a dedicated external upgrade process - if (!$error) - { + if (!$error) { $parameters = array('versionfrom'=>$versionfrom, 'versionto='.$versionto); $object = new stdClass(); $action = "upgrade"; $reshook = $hookmanager->executeHooks('doUpgrade2', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if ($hookmanager->resNbOfHooks > 0) - { - if ($reshook < 0) - { + if ($hookmanager->resNbOfHooks > 0) { + if ($reshook < 0) { print '<tr><td colspan="4">'; print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: '; print $hookmanager->error; print "<!-- (".$reshook.") -->"; print '</td></tr>'; } else { - print '<tr><td colspan="4">'; + print '<tr class="trforrunsql"><td colspan="4">'; print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: <span class="ok">OK</span>'; print "<!-- (".$reshook.") -->"; print '</td></tr>'; } } else { //if (! empty($conf->modules)) - if (!empty($conf->modules_parts['hooks'])) // If there is at least one module with one hook, we show message to say nothing was done - { - print '<tr><td colspan="4">'; + if (!empty($conf->modules_parts['hooks'])) { // If there is at least one module with one hook, we show message to say nothing was done + print '<tr class="trforrunsql"><td colspan="4">'; print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: '.$langs->trans("None"); print '</td></tr>'; } @@ -555,6 +543,7 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ print '</table>'; + // Set constant to ask to remake a new ping to inform about upgrade (if first ping was done and OK) $sql = 'UPDATE '.MAIN_DB_PREFIX."const SET VALUE = 'torefresh' WHERE name = 'MAIN_FIRST_PING_OK_ID'"; $db->query($sql, 1); @@ -579,23 +568,61 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ // Actions for all versions (no database change but rename some directories) migrate_rename_directories($db, $langs, $conf, '/banque/bordereau', '/bank/checkdeposits'); - print '<div><br>'.$langs->trans("MigrationFinished").'</div>'; + $silent = 0; + if (!$silent) { + print '<table width="100%">'; + print '<tr><td style="width: 30%">'.$langs->trans("MigrationFinished").'</td>'; + print '<td class="right">'; + if ($error == 0) { + //print '<span class="ok">'.$langs->trans("OK").'</span> - '; // $error = 0 does not mean there is no error (error are not always trapped) + } else { + print '<span class="error">'.$langs->trans("Error").'</span> - '; + } + + //if (!empty($conf->use_javascript_ajax)) { // use_javascript_ajax is not defined + print '<script type="text/javascript" language="javascript"> + jQuery(document).ready(function() { + function init_trrunsql() + { + console.log("toggle .trforrunsql"); + jQuery(".trforrunsql").toggle(); + } + init_trrunsql(); + jQuery(".trforrunsqlshowhide").click(function() { + init_trrunsql(); + }); + }); + </script>'; + print '<a class="trforrunsqlshowhide" href="#">'.$langs->trans("ShowHideDetails").'</a>'; + //} + + print '</td></tr>'."\n"; + print '</table>'; + } + + //print '<div><br>'.$langs->trans("MigrationFinished").'</div>'; } else { print '<div class="error">'.$langs->trans('ErrorWrongParameters').'</div>'; $error++; } $ret = 0; -if ($error && isset($argv[1])) $ret = 1; +if ($error && isset($argv[1])) { + $ret = 1; +} dolibarr_install_syslog("Exit ".$ret); dolibarr_install_syslog("--- upgrade2: end"); pFooter($error ? 2 : 0, $setuplang); -if ($db->connected) $db->close(); +if ($db->connected) { + $db->close(); +} // Return code if ran from command line -if ($ret) exit($ret); +if ($ret) { + exit($ret); +} @@ -616,8 +643,7 @@ function migrate_paiements($db, $langs, $conf) $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement", "fk_facture"); $obj = $db->fetch_object($result); - if ($obj) - { + if ($obj) { $sql = "SELECT p.rowid, p.fk_facture, p.amount"; $sql .= " FROM ".MAIN_DB_PREFIX."paiement as p"; $sql .= " WHERE p.fk_facture > 0"; @@ -625,14 +651,12 @@ function migrate_paiements($db, $langs, $conf) $resql = $db->query($sql); dolibarr_install_syslog("upgrade2::migrate_paiements"); - if ($resql) - { + if ($resql) { $i = 0; $row = array(); $num = $db->num_rows($resql); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $row[$i][0] = $obj->rowid; $row[$i][1] = $obj->fk_facture; @@ -643,15 +667,12 @@ function migrate_paiements($db, $langs, $conf) dol_print_error($db); } - if ($num) - { + if ($num) { print $langs->trans('MigrationPaymentsNumberToUpdate', $num)."<br>\n"; - if ($db->begin()) - { + if ($db->begin()) { $res = 0; $num = count($row); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)"; $sql .= " VALUES (".$row[$i][1].",".$row[$i][0].",".$row[$i][2].")"; @@ -665,8 +686,7 @@ function migrate_paiements($db, $langs, $conf) } } - if ($res == (2 * count($row))) - { + if ($res == (2 * count($row))) { $db->commit(); print $langs->trans('MigrationSuccessfullUpdate')."<br>"; } else { @@ -702,8 +722,7 @@ function migrate_paiements_orphelins_1($db, $langs, $conf) $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement", "fk_facture"); $obj = $db->fetch_object($result); - if ($obj) - { + if ($obj) { // Tous les enregistrements qui sortent de cette requete devrait avoir un pere dans llx_paiement_facture $sql = "SELECT distinct p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,"; $sql .= " bu2.url_id as socid"; @@ -718,16 +737,13 @@ function migrate_paiements_orphelins_1($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_paiements_orphelins_1"); $row = array(); - if ($resql) - { + if ($resql) { $i = $j = 0; $num = $db->num_rows($resql); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj->pamount == $obj->bamount && $obj->socid) // Pour etre sur d'avoir bon cas - { + if ($obj->pamount == $obj->bamount && $obj->socid) { // Pour etre sur d'avoir bon cas $row[$j]['paymentid'] = $obj->rowid; // paymentid $row[$j]['pamount'] = $obj->pamount; $row[$j]['fk_bank'] = $obj->fk_bank; @@ -742,16 +758,16 @@ function migrate_paiements_orphelins_1($db, $langs, $conf) dol_print_error($db); } - if (count($row)) - { + if (count($row)) { print $langs->trans('OrphelinsPaymentsDetectedByMethod', 1).': '.count($row)."<br>\n"; $db->begin(); $res = 0; $num = count($row); - for ($i = 0; $i < $num; $i++) - { - if ($conf->global->MAIN_FEATURES_LEVEL == 2) print '* '.$row[$i]['datec'].' paymentid='.$row[$i]['paymentid'].' pamount='.$row[$i]['pamount'].' fk_bank='.$row[$i]['fk_bank'].' bamount='.$row[$i]['bamount'].' socid='.$row[$i]['socid'].'<br>'; + for ($i = 0; $i < $num; $i++) { + if ($conf->global->MAIN_FEATURES_LEVEL == 2) { + print '* '.$row[$i]['datec'].' paymentid='.$row[$i]['paymentid'].' pamount='.$row[$i]['pamount'].' fk_bank='.$row[$i]['fk_bank'].' bamount='.$row[$i]['bamount'].' socid='.$row[$i]['socid'].'<br>'; + } // On cherche facture sans lien paiement et du meme montant et pour meme societe. $sql = " SELECT distinct f.rowid from ".MAIN_DB_PREFIX."facture as f"; @@ -761,12 +777,10 @@ function migrate_paiements_orphelins_1($db, $langs, $conf) $sql .= " ORDER BY f.fk_statut"; //print $sql.'<br>'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); //print 'Nb of invoice found for this amount and company :'.$num.'<br>'; - if ($num >= 1) - { + if ($num >= 1) { $obj = $db->fetch_object($resql); $facid = $obj->rowid; @@ -782,8 +796,7 @@ function migrate_paiements_orphelins_1($db, $langs, $conf) } } - if ($res > 0) - { + if ($res > 0) { print $langs->trans('MigrationSuccessfullUpdate')."<br>"; } else { print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n"; @@ -819,8 +832,7 @@ function migrate_paiements_orphelins_2($db, $langs, $conf) $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement", "fk_facture"); $obj = $db->fetch_object($result); - if ($obj) - { + if ($obj) { // Tous les enregistrements qui sortent de cette requete devrait avoir un pere dans llx_paiement_facture $sql = "SELECT distinct p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,"; $sql .= " bu2.url_id as socid"; @@ -834,16 +846,13 @@ function migrate_paiements_orphelins_2($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_paiements_orphelins_2"); $row = array(); - if ($resql) - { + if ($resql) { $i = $j = 0; $num = $db->num_rows($resql); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj->pamount == $obj->bamount && $obj->socid) // Pour etre sur d'avoir bon cas - { + if ($obj->pamount == $obj->bamount && $obj->socid) { // Pour etre sur d'avoir bon cas $row[$j]['paymentid'] = $obj->rowid; // paymentid $row[$j]['pamount'] = $obj->pamount; $row[$j]['fk_bank'] = $obj->fk_bank; @@ -861,15 +870,15 @@ function migrate_paiements_orphelins_2($db, $langs, $conf) $nberr = 0; $num = count($row); - if ($num) - { + if ($num) { print $langs->trans('OrphelinsPaymentsDetectedByMethod', 2).': '.count($row)."<br>\n"; $db->begin(); $res = 0; - for ($i = 0; $i < $num; $i++) - { - if ($conf->global->MAIN_FEATURES_LEVEL == 2) print '* '.$row[$i]['datec'].' paymentid='.$row[$i]['paymentid'].' '.$row[$i]['pamount'].' fk_bank='.$row[$i]['fk_bank'].' '.$row[$i]['bamount'].' socid='.$row[$i]['socid'].'<br>'; + for ($i = 0; $i < $num; $i++) { + if ($conf->global->MAIN_FEATURES_LEVEL == 2) { + print '* '.$row[$i]['datec'].' paymentid='.$row[$i]['paymentid'].' '.$row[$i]['pamount'].' fk_bank='.$row[$i]['fk_bank'].' '.$row[$i]['bamount'].' socid='.$row[$i]['socid'].'<br>'; + } // On cherche facture sans lien paiement et du meme montant et pour meme societe. $sql = " SELECT distinct f.rowid from ".MAIN_DB_PREFIX."facture as f"; @@ -879,12 +888,10 @@ function migrate_paiements_orphelins_2($db, $langs, $conf) $sql .= " ORDER BY f.fk_statut"; //print $sql.'<br>'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); //print 'Nb of invoice found for this amount and company :'.$num.'<br>'; - if ($num >= 1) - { + if ($num >= 1) { $obj = $db->fetch_object($resql); $facid = $obj->rowid; @@ -900,8 +907,7 @@ function migrate_paiements_orphelins_2($db, $langs, $conf) } } - if ($res > 0) - { + if ($res > 0) { print $langs->trans('MigrationSuccessfullUpdate')."<br>"; } else { print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n"; @@ -918,8 +924,7 @@ function migrate_paiements_orphelins_2($db, $langs, $conf) $sql = "ALTER TABLE ".MAIN_DB_PREFIX."paiement DROP COLUMN fk_facture"; $db->query($sql); - if (!$nberr) - { + if (!$nberr) { $db->commit(); } else { print 'ERROR'; @@ -961,19 +966,16 @@ function migrate_contracts_det($db, $langs, $conf) $resql = $db->query($sql); dolibarr_install_syslog("upgrade2::migrate_contracts_det"); - if ($resql) - { + if ($resql) { $i = 0; $row = array(); $num = $db->num_rows($resql); - if ($num) - { + if ($num) { print $langs->trans('MigrationContractsNumberToUpdate', $num)."<br>\n"; $db->begin(); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet ("; @@ -992,8 +994,7 @@ function migrate_contracts_det($db, $langs, $conf) $sql .= "null"; $sql .= ")"; - if ($db->query($sql)) - { + if ($db->query($sql)) { print $langs->trans('MigrationContractsLineCreation', $obj->cref)."<br>\n"; } else { dol_print_error($db); @@ -1003,8 +1004,7 @@ function migrate_contracts_det($db, $langs, $conf) $i++; } - if (!$nberr) - { + if (!$nberr) { // $db->rollback(); $db->commit(); print $langs->trans('MigrationSuccessfullUpdate')."<br>"; @@ -1049,19 +1049,16 @@ function migrate_links_transfert($db, $langs, $conf) $resql = $db->query($sql); dolibarr_install_syslog("upgrade2::migrate_links_transfert"); - if ($resql) - { + if ($resql) { $i = 0; $row = array(); $num = $db->num_rows($resql); - if ($num) - { + if ($num) { print $langs->trans('MigrationBankTransfertsToUpdate', $num)."<br>\n"; $db->begin(); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url ("; @@ -1074,8 +1071,7 @@ function migrate_links_transfert($db, $langs, $conf) print $sql.'<br>'; dolibarr_install_syslog("migrate_links_transfert"); - if (!$db->query($sql)) - { + if (!$db->query($sql)) { dol_print_error($db); $nberr++; } @@ -1083,8 +1079,7 @@ function migrate_links_transfert($db, $langs, $conf) $i++; } - if (!$nberr) - { + if (!$nberr) { // $db->rollback(); $db->commit(); print $langs->trans('MigrationSuccessfullUpdate')."<br>"; @@ -1120,18 +1115,26 @@ function migrate_contracts_date1($db, $langs, $conf) $sql = "update ".MAIN_DB_PREFIX."contrat set date_contrat=tms where date_contrat is null"; dolibarr_install_syslog("upgrade2::migrate_contracts_date1"); $resql = $db->query($sql); - if (!$resql) dol_print_error($db); - if ($db->affected_rows($resql) > 0) - print $langs->trans('MigrationContractsEmptyDatesUpdateSuccess')."<br>\n"; - else print $langs->trans('MigrationContractsEmptyDatesNothingToUpdate')."<br>\n"; + if (!$resql) { + dol_print_error($db); + } + if ($db->affected_rows($resql) > 0) { + print $langs->trans('MigrationContractsEmptyDatesUpdateSuccess')."<br>\n"; + } else { + print $langs->trans('MigrationContractsEmptyDatesNothingToUpdate')."<br>\n"; + } $sql = "update ".MAIN_DB_PREFIX."contrat set datec=tms where datec is null"; dolibarr_install_syslog("upgrade2::migrate_contracts_date1"); $resql = $db->query($sql); - if (!$resql) dol_print_error($db); - if ($db->affected_rows($resql) > 0) - print $langs->trans('MigrationContractsEmptyCreationDatesUpdateSuccess')."<br>\n"; - else print $langs->trans('MigrationContractsEmptyCreationDatesNothingToUpdate')."<br>\n"; + if (!$resql) { + dol_print_error($db); + } + if ($db->affected_rows($resql) > 0) { + print $langs->trans('MigrationContractsEmptyCreationDatesUpdateSuccess')."<br>\n"; + } else { + print $langs->trans('MigrationContractsEmptyCreationDatesNothingToUpdate')."<br>\n"; + } print '</td></tr>'; } @@ -1161,22 +1164,18 @@ function migrate_contracts_date2($db, $langs, $conf) $resql = $db->query($sql); dolibarr_install_syslog("upgrade2::migrate_contracts_date2"); - if ($resql) - { + if ($resql) { $i = 0; $row = array(); $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $nbcontratsmodifie = 0; $db->begin(); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj->date_contrat > $obj->datemin) - { + if ($obj->date_contrat > $obj->datemin) { $datemin = $db->jdate($obj->datemin); print $langs->trans('MigrationContractsInvalidDateFix', $obj->cref, $obj->date_contrat, $obj->datemin)."<br>\n"; @@ -1184,7 +1183,9 @@ function migrate_contracts_date2($db, $langs, $conf) $sql .= " SET date_contrat='".$db->idate($datemin)."'"; $sql .= " WHERE rowid=".$obj->cref; $resql2 = $db->query($sql); - if (!$resql2) dol_print_error($db); + if (!$resql2) { + dol_print_error($db); + } $nbcontratsmodifie++; } @@ -1193,9 +1194,11 @@ function migrate_contracts_date2($db, $langs, $conf) $db->commit(); - if ($nbcontratsmodifie) - print $langs->trans('MigrationContractsInvalidDatesNumber', $nbcontratsmodifie)."<br>\n"; - else print $langs->trans('MigrationContractsInvalidDatesNothingToUpdate')."<br>\n"; + if ($nbcontratsmodifie) { + print $langs->trans('MigrationContractsInvalidDatesNumber', $nbcontratsmodifie)."<br>\n"; + } else { + print $langs->trans('MigrationContractsInvalidDatesNothingToUpdate')."<br>\n"; + } } } else { dol_print_error($db); @@ -1222,10 +1225,14 @@ function migrate_contracts_date3($db, $langs, $conf) $sql = "update ".MAIN_DB_PREFIX."contrat set datec=date_contrat where datec is null or datec > date_contrat"; dolibarr_install_syslog("upgrade2::migrate_contracts_date3"); $resql = $db->query($sql); - if (!$resql) dol_print_error($db); - if ($db->affected_rows($resql) > 0) - print $langs->trans('MigrationContractsIncoherentCreationDateUpdateSuccess')."<br>\n"; - else print $langs->trans('MigrationContractsIncoherentCreationDateNothingToUpdate')."<br>\n"; + if (!$resql) { + dol_print_error($db); + } + if ($db->affected_rows($resql) > 0) { + print $langs->trans('MigrationContractsIncoherentCreationDateUpdateSuccess')."<br>\n"; + } else { + print $langs->trans('MigrationContractsIncoherentCreationDateNothingToUpdate')."<br>\n"; + } print '</td></tr>'; } @@ -1249,19 +1256,19 @@ function migrate_contracts_open($db, $langs, $conf) $sql .= " WHERE cd.statut = 4 AND c.statut=2 AND c.rowid=cd.fk_contrat"; dolibarr_install_syslog("upgrade2::migrate_contracts_open"); $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } if ($db->affected_rows($resql) > 0) { $i = 0; $row = array(); $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $nbcontratsmodifie = 0; $db->begin(); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print $langs->trans('MigrationReopenThisContract', $obj->cref)."<br>\n"; @@ -1269,7 +1276,9 @@ function migrate_contracts_open($db, $langs, $conf) $sql .= " SET statut=1"; $sql .= " WHERE rowid=".$obj->cref; $resql2 = $db->query($sql); - if (!$resql2) dol_print_error($db); + if (!$resql2) { + dol_print_error($db); + } $nbcontratsmodifie++; @@ -1278,11 +1287,15 @@ function migrate_contracts_open($db, $langs, $conf) $db->commit(); - if ($nbcontratsmodifie) - print $langs->trans('MigrationReopenedContractsNumber', $nbcontratsmodifie)."<br>\n"; - else print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n"; + if ($nbcontratsmodifie) { + print $langs->trans('MigrationReopenedContractsNumber', $nbcontratsmodifie)."<br>\n"; + } else { + print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n"; + } } - } else print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n"; + } else { + print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n"; + } print '</td></tr>'; } @@ -1306,8 +1319,7 @@ function migrate_paiementfourn_facturefourn($db, $langs, $conf) $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiementfourn", "fk_facture_fourn"); $obj = $db->fetch_object($result); - if ($obj) - { + if ($obj) { $error = 0; $nb = 0; @@ -1317,15 +1329,13 @@ function migrate_paiementfourn_facturefourn($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_paiementfourn_facturefourn"); $select_resql = $db->query($select_sql); - if ($select_resql) - { + if ($select_resql) { $select_num = $db->num_rows($select_resql); $i = 0; $var = true; // Pour chaque paiement fournisseur, on insere une ligne dans paiementfourn_facturefourn - while (($i < $select_num) && (!$error)) - { + while (($i < $select_num) && (!$error)) { $var = !$var; $select_obj = $db->fetch_object($select_resql); @@ -1334,15 +1344,12 @@ function migrate_paiementfourn_facturefourn($db, $langs, $conf) $check_sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn'; $check_sql .= ' WHERE fk_paiementfourn = '.$select_obj->rowid.' AND fk_facturefourn = '.$select_obj->fk_facture_fourn; $check_resql = $db->query($check_sql); - if ($check_resql) - { + if ($check_resql) { $check_num = $db->num_rows($check_resql); - if ($check_num == 0) - { + if ($check_num == 0) { $db->begin(); - if ($nb == 0) - { + if ($nb == 0) { print '<tr><td colspan="4" class="nowrap"><b>'.$langs->trans('SuppliersInvoices').'</b></td></tr>'; print '<tr><td>fk_paiementfourn</td><td>fk_facturefourn</td><td>'.$langs->trans('Amount').'</td><td>&nbsp;</td></tr>'; } @@ -1356,8 +1363,7 @@ function migrate_paiementfourn_facturefourn($db, $langs, $conf) $insert_sql .= ' amount = \''.$select_obj->amount.'\''; $insert_resql = $db->query($insert_sql); - if ($insert_resql) - { + if ($insert_resql) { $nb++; print '<td><span class="ok">'.$langs->trans("OK").'</span></td>'; } else { @@ -1375,10 +1381,8 @@ function migrate_paiementfourn_facturefourn($db, $langs, $conf) $error++; } - if (!$error) - { - if (!$nb) - { + if (!$error) { + if (!$nb) { print '<tr><td>'.$langs->trans("AlreadyDone").'</td></tr>'; } $db->commit(); @@ -1426,14 +1430,11 @@ function migrate_price_facture($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_price_facture"); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $rowid = $obj->rowid; @@ -1464,15 +1465,12 @@ function migrate_price_facture($db, $langs, $conf) /* On touche a facture mere uniquement si total_ttc = 0 */ - if (!$total_ttc_f) - { + if (!$total_ttc_f) { $facture = new Facture($db); $facture->id = $obj->facid; - if ($facture->fetch($facture->id) >= 0) - { - if ($facture->update_price() > 0) - { + if ($facture->fetch($facture->id) >= 0) { + if ($facture->update_price() > 0) { //print $facture->id; } else { print "Error id=".$facture->id; @@ -1515,7 +1513,7 @@ function migrate_price_facture($db, $langs, $conf) */ function migrate_price_propal($db, $langs, $conf) { - $tmpmysoc = new Societe($db); + $tmpmysoc = new Societe($db); $tmpmysoc->setMysoc($conf); $db->begin(); @@ -1534,14 +1532,11 @@ function migrate_price_propal($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_price_propal"); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $rowid = $obj->rowid; @@ -1571,24 +1566,24 @@ function migrate_price_propal($db, $langs, $conf) /* On touche pas a propal mere - $propal = new Propal($db); - $propal->id=$obj->rowid; - if ( $propal->fetch($propal->id) >= 0 ) - { - if ( $propal->update_price() > 0 ) - { - print ". "; - } - else - { - print "Error id=".$propal->id; - } - } - else - { - print "Error #3"; - } - */ + $propal = new Propal($db); + $propal->id=$obj->rowid; + if ( $propal->fetch($propal->id) >= 0 ) + { + if ( $propal->update_price() > 0 ) + { + print ". "; + } + else + { + print "Error id=".$propal->id; + } + } + else + { + print "Error #3"; + } + */ $i++; } } else { @@ -1621,9 +1616,11 @@ function migrate_price_contrat($db, $langs, $conf) { $db->begin(); - $tmpmysoc = new Societe($db); + $tmpmysoc = new Societe($db); $tmpmysoc->setMysoc($conf); - if (empty($tmpmysoc->country_id)) $tmpmysoc->country_id = 0; // Ti not have this set to '' or will make sql syntax error. + if (empty($tmpmysoc->country_id)) { + $tmpmysoc->country_id = 0; // Ti not have this set to '' or will make sql syntax error. + } print '<tr><td colspan="4">'; @@ -1639,14 +1636,11 @@ function migrate_price_contrat($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_price_contrat"); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $rowid = $obj->rowid; @@ -1723,14 +1717,11 @@ function migrate_price_commande($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_price_commande"); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $rowid = $obj->rowid; @@ -1759,24 +1750,24 @@ function migrate_price_commande($db, $langs, $conf) $commandeligne->update_total(); /* On touche pas a facture mere - $commande = new Commande($db); - $commande->id = $obj->rowid; - if ( $commande->fetch($commande->id) >= 0 ) - { - if ( $commande->update_price() > 0 ) - { - print ". "; - } - else - { - print "Error id=".$commande->id; - } - } - else - { - print "Error #3"; - } - */ + $commande = new Commande($db); + $commande->id = $obj->rowid; + if ( $commande->fetch($commande->id) >= 0 ) + { + if ( $commande->update_price() > 0 ) + { + print ". "; + } + else + { + print "Error id=".$commande->id; + } + } + else + { + print "Error #3"; + } + */ $i++; } } else { @@ -1786,14 +1777,14 @@ function migrate_price_commande($db, $langs, $conf) $db->free($resql); /* - $sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet"; - $sql.= " WHERE price = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0 AND remise_percent = 0"; - $resql=$db->query($sql); - if (! $resql) - { - dol_print_error($db); - } - */ + $sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet"; + $sql.= " WHERE price = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0 AND remise_percent = 0"; + $resql=$db->query($sql); + if (! $resql) + { + dol_print_error($db); + } + */ $db->commit(); } else { @@ -1836,14 +1827,11 @@ function migrate_price_commande_fournisseur($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_price_commande_fournisseur"); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $rowid = $obj->rowid; @@ -1872,24 +1860,24 @@ function migrate_price_commande_fournisseur($db, $langs, $conf) $commandeligne->update_total(); /* On touche pas a facture mere - $commande = new Commande($db); - $commande->id = $obj->rowid; - if ( $commande->fetch($commande->id) >= 0 ) - { - if ( $commande->update_price() > 0 ) - { - print ". "; - } - else - { - print "Error id=".$commande->id; - } - } - else - { - print "Error #3"; - } - */ + $commande = new Commande($db); + $commande->id = $obj->rowid; + if ( $commande->fetch($commande->id) >= 0 ) + { + if ( $commande->update_price() > 0 ) + { + print ". "; + } + else + { + print "Error id=".$commande->id; + } + } + else + { + print "Error #3"; + } + */ $i++; } } else { @@ -1899,14 +1887,14 @@ function migrate_price_commande_fournisseur($db, $langs, $conf) $db->free($resql); /* - $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet"; - $sql.= " WHERE subprice = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0"; - $resql=$db->query($sql); - if (! $resql) - { - dol_print_error($db); - } - */ + $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet"; + $sql.= " WHERE subprice = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0"; + $resql=$db->query($sql); + if (! $resql) + { + dol_print_error($db); + } + */ $db->commit(); } else { @@ -1935,42 +1923,42 @@ function migrate_modeles($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_modeles"); - if (!empty($conf->facture->enabled)) - { + if (!empty($conf->facture->enabled)) { include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; $modellist = ModelePDFFactures::liste_modeles($db); - if (count($modellist) == 0) - { + if (count($modellist) == 0) { // Aucun model par defaut. $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('crabe','invoice')"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } } } - if (!empty($conf->commande->enabled)) - { + if (!empty($conf->commande->enabled)) { include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php'; $modellist = ModelePDFCommandes::liste_modeles($db); - if (count($modellist) == 0) - { + if (count($modellist) == 0) { // Aucun model par defaut. $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('einstein','order')"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } } } - if (!empty($conf->expedition->enabled)) - { + if (!empty($conf->expedition->enabled)) { include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php'; $modellist = ModelePDFExpedition::liste_modeles($db); - if (count($modellist) == 0) - { + if (count($modellist) == 0) { // Aucun model par defaut. $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('rouget','shipping')"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } } } @@ -1997,31 +1985,26 @@ function migrate_commande_expedition($db, $langs, $conf) $result = $db->DDLDescTable(MAIN_DB_PREFIX."expedition", "fk_commande"); $obj = $db->fetch_object($result); - if ($obj) - { + if ($obj) { $error = 0; $db->begin(); $sql = "SELECT e.rowid, e.fk_commande FROM ".MAIN_DB_PREFIX."expedition as e"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_exp (fk_expedition,fk_commande)"; $sql .= " VALUES (".$obj->rowid.",".$obj->fk_commande.")"; $resql2 = $db->query($sql); - if (!$resql2) - { + if (!$resql2) { $error++; dol_print_error($db); } @@ -2030,8 +2013,7 @@ function migrate_commande_expedition($db, $langs, $conf) } } - if ($error == 0) - { + if ($error == 0) { $db->commit(); $sql = "ALTER TABLE ".MAIN_DB_PREFIX."expedition DROP COLUMN fk_commande"; print $langs->trans('FieldRenamed')."<br>\n"; @@ -2068,8 +2050,7 @@ function migrate_commande_livraison($db, $langs, $conf) $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraison", "fk_commande"); $obj = $db->fetch_object($result); - if ($obj) - { + if ($obj) { $error = 0; $db->begin(); @@ -2079,23 +2060,19 @@ function migrate_commande_livraison($db, $langs, $conf) $sql .= " FROM ".MAIN_DB_PREFIX."livraison as l, ".MAIN_DB_PREFIX."commande as c"; $sql .= " WHERE c.rowid = l.fk_commande"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_liv (fk_livraison,fk_commande)"; $sql .= " VALUES (".$obj->rowid.",".$obj->fk_commande.")"; $resql2 = $db->query($sql); - if ($resql2) - { + if ($resql2) { $delivery_date = $db->jdate($obj->delivery_date); $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET"; @@ -2103,8 +2080,7 @@ function migrate_commande_livraison($db, $langs, $conf) $sqlu .= ", date_livraison='".$db->idate($delivery_date)."'"; $sqlu .= " WHERE rowid = ".$obj->rowid; $resql3 = $db->query($sqlu); - if (!$resql3) - { + if (!$resql3) { $error++; dol_print_error($db); } @@ -2117,8 +2093,7 @@ function migrate_commande_livraison($db, $langs, $conf) } } - if ($error == 0) - { + if ($error == 0) { $db->commit(); $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraison DROP COLUMN fk_commande"; print $langs->trans('FieldRenamed')."<br>\n"; @@ -2157,8 +2132,7 @@ function migrate_detail_livraison($db, $langs, $conf) // If not this means migration was already done. $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraisondet", "fk_commande_ligne"); $obj = $db->fetch_object($result); - if ($obj) - { + if ($obj) { $error = 0; $db->begin(); @@ -2168,15 +2142,12 @@ function migrate_detail_livraison($db, $langs, $conf) $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."livraisondet as ld"; $sql .= " WHERE ld.fk_commande_ligne = cd.rowid"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sql = "UPDATE ".MAIN_DB_PREFIX."livraisondet SET"; @@ -2187,15 +2158,13 @@ function migrate_detail_livraison($db, $langs, $conf) $sql .= " WHERE fk_commande_ligne = ".$obj->rowid; $resql2 = $db->query($sql); - if ($resql2) - { + if ($resql2) { $sql = "SELECT total_ht"; $sql .= " FROM ".MAIN_DB_PREFIX."livraison"; $sql .= " WHERE rowid = ".$obj->fk_livraison; $resql3 = $db->query($sql); - if ($resql3) - { + if ($resql3) { $obju = $db->fetch_object($resql3); $total_ht = $obju->total_ht + $obj->total_ht; @@ -2203,8 +2172,7 @@ function migrate_detail_livraison($db, $langs, $conf) $sqlu .= " total_ht='".$db->escape($total_ht)."'"; $sqlu .= " WHERE rowid=".$obj->fk_livraison; $resql4 = $db->query($sqlu); - if (!$resql4) - { + if (!$resql4) { $error++; dol_print_error($db); } @@ -2221,8 +2189,7 @@ function migrate_detail_livraison($db, $langs, $conf) } } - if ($error == 0) - { + if ($error == 0) { $db->commit(); $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraisondet CHANGE fk_commande_ligne fk_origin_line integer"; print $langs->trans('FieldRenamed')."<br>\n"; @@ -2237,8 +2204,7 @@ function migrate_detail_livraison($db, $langs, $conf) } else { $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraisondet", "fk_origin_line"); $obj = $db->fetch_object($result); - if (!$obj) - { + if (!$obj) { $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraisondet ADD COLUMN fk_origin_line integer after fk_livraison"; $db->query($sql); } @@ -2272,15 +2238,12 @@ function migrate_stocks($db, $langs, $conf) $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; $sql .= " GROUP BY fk_product"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sql = "UPDATE ".MAIN_DB_PREFIX."product SET"; @@ -2288,8 +2251,7 @@ function migrate_stocks($db, $langs, $conf) $sql .= " WHERE rowid=".$obj->fk_product; $resql2 = $db->query($sql); - if ($resql2) - { + if ($resql2) { } else { $error++; dol_print_error($db); @@ -2299,8 +2261,7 @@ function migrate_stocks($db, $langs, $conf) } } - if ($error == 0) - { + if ($error == 0) { $db->commit(); } else { $db->rollback(); @@ -2333,8 +2294,7 @@ function migrate_menus($db, $langs, $conf) $error = 0; - if ($db->DDLInfoTable(MAIN_DB_PREFIX."menu_constraint")) - { + if ($db->DDLInfoTable(MAIN_DB_PREFIX."menu_constraint")) { $db->begin(); $sql = "SELECT m.rowid, mc.action"; @@ -2342,14 +2302,11 @@ function migrate_menus($db, $langs, $conf) $sql .= " WHERE md.fk_menu = m.rowid AND md.fk_constraint = mc.rowid"; $sql .= " AND m.enabled = '1'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sql = "UPDATE ".MAIN_DB_PREFIX."menu SET"; @@ -2358,8 +2315,7 @@ function migrate_menus($db, $langs, $conf) $sql .= " AND enabled = '1'"; $resql2 = $db->query($sql); - if ($resql2) - { + if ($resql2) { } else { $error++; dol_print_error($db); @@ -2369,8 +2325,7 @@ function migrate_menus($db, $langs, $conf) } } - if ($error == 0) - { + if ($error == 0) { $db->commit(); } else { $db->rollback(); @@ -2406,8 +2361,7 @@ function migrate_commande_deliveryaddress($db, $langs, $conf) $error = 0; - if ($db->DDLInfoTable(MAIN_DB_PREFIX."co_exp")) - { + if ($db->DDLInfoTable(MAIN_DB_PREFIX."co_exp")) { $db->begin(); $sql = "SELECT c.fk_adresse_livraison, ce.fk_expedition"; @@ -2417,15 +2371,12 @@ function migrate_commande_deliveryaddress($db, $langs, $conf) $sql .= " AND c.fk_adresse_livraison IS NOT NULL AND c.fk_adresse_livraison != 0"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET"; @@ -2433,8 +2384,7 @@ function migrate_commande_deliveryaddress($db, $langs, $conf) $sql .= " WHERE rowid=".$obj->fk_expedition; $resql2 = $db->query($sql); - if (!$resql2) - { + if (!$resql2) { $error++; dol_print_error($db); } @@ -2445,8 +2395,7 @@ function migrate_commande_deliveryaddress($db, $langs, $conf) print $langs->trans('AlreadyDone')."<br>\n"; } - if ($error == 0) - { + if ($error == 0) { $db->commit(); } else { $db->rollback(); @@ -2475,10 +2424,8 @@ function migrate_restore_missing_links($db, $langs, $conf) { dolibarr_install_syslog("upgrade2::migrate_restore_missing_links"); - if (($db->type == 'mysql' || $db->type == 'mysqli')) - { - if (versioncompare($db->getVersionArray(), array(4, 0)) < 0) - { + if (($db->type == 'mysql' || $db->type == 'mysqli')) { + if (versioncompare($db->getVersionArray(), array(4, 0)) < 0) { dolibarr_install_syslog("upgrade2::migrate_restore_missing_links Version of database too old to make this migrate action"); return 0; } @@ -2505,15 +2452,12 @@ function migrate_restore_missing_links($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 1"); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.<br>'; @@ -2522,18 +2466,18 @@ function migrate_restore_missing_links($db, $langs, $conf) $sql .= " WHERE rowid=".$obj->field; $resql2 = $db->query($sql); - if (!$resql2) - { + if (!$resql2) { $error++; dol_print_error($db); } //print ". "; $i++; } - } else print $langs->trans('AlreadyDone')."<br>\n"; + } else { + print $langs->trans('AlreadyDone')."<br>\n"; + } - if ($error == 0) - { + if ($error == 0) { $db->commit(); } else { $db->rollback(); @@ -2565,15 +2509,12 @@ function migrate_restore_missing_links($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 2"); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.<br>'; @@ -2582,8 +2523,7 @@ function migrate_restore_missing_links($db, $langs, $conf) $sql .= " WHERE rowid=".$obj->field; $resql2 = $db->query($sql); - if (!$resql2) - { + if (!$resql2) { $error++; dol_print_error($db); } @@ -2594,8 +2534,7 @@ function migrate_restore_missing_links($db, $langs, $conf) print $langs->trans('AlreadyDone')."<br>\n"; } - if ($error == 0) - { + if ($error == 0) { $db->commit(); } else { $db->rollback(); @@ -2627,23 +2566,19 @@ function migrate_project_user_resp($db, $langs, $conf) $result = $db->DDLDescTable(MAIN_DB_PREFIX."projet", "fk_user_resp"); $obj = $db->fetch_object($result); - if ($obj) - { + if ($obj) { $error = 0; $db->begin(); $sql = "SELECT rowid, fk_user_resp FROM ".MAIN_DB_PREFIX."projet"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact ("; @@ -2660,11 +2595,9 @@ function migrate_project_user_resp($db, $langs, $conf) $sql2 .= ", ".$obj->fk_user_resp; $sql2 .= ")"; - if ($obj->fk_user_resp > 0) - { + if ($obj->fk_user_resp > 0) { $resql2 = $db->query($sql2); - if (!$resql2) - { + if (!$resql2) { $error++; dol_print_error($db); } @@ -2675,11 +2608,9 @@ function migrate_project_user_resp($db, $langs, $conf) } } - if ($error == 0) - { + if ($error == 0) { $sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."projet DROP COLUMN fk_user_resp"; - if ($db->query($sqlDrop)) - { + if ($db->query($sqlDrop)) { $db->commit(); } else { $db->rollback(); @@ -2714,23 +2645,19 @@ function migrate_project_task_actors($db, $langs, $conf) print '<br>'; print '<b>'.$langs->trans('MigrationProjectTaskActors')."</b><br>\n"; - if ($db->DDLInfoTable(MAIN_DB_PREFIX."projet_task_actors")) - { + if ($db->DDLInfoTable(MAIN_DB_PREFIX."projet_task_actors")) { $error = 0; $db->begin(); $sql = "SELECT fk_projet_task as fk_project_task, fk_user FROM ".MAIN_DB_PREFIX."projet_task_actors"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact ("; @@ -2749,8 +2676,7 @@ function migrate_project_task_actors($db, $langs, $conf) $resql2 = $db->query($sql2); - if (!$resql2) - { + if (!$resql2) { $error++; dol_print_error($db); } @@ -2759,11 +2685,9 @@ function migrate_project_task_actors($db, $langs, $conf) } } - if ($error == 0) - { + if ($error == 0) { $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX."projet_task_actors"; - if ($db->query($sqlDrop)) - { + if ($db->query($sqlDrop)) { $db->commit(); } else { $db->rollback(); @@ -2803,8 +2727,7 @@ function migrate_relationship_tables($db, $langs, $conf, $table, $fk_source, $so $error = 0; - if ($db->DDLInfoTable(MAIN_DB_PREFIX.$table)) - { + if ($db->DDLInfoTable(MAIN_DB_PREFIX.$table)) { dolibarr_install_syslog("upgrade2::migrate_relationship_tables table = ".MAIN_DB_PREFIX.$table); $db->begin(); @@ -2813,15 +2736,12 @@ function migrate_relationship_tables($db, $langs, $conf, $table, $fk_source, $so $sqlSelect .= " FROM ".MAIN_DB_PREFIX.$table; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; @@ -2837,8 +2757,7 @@ function migrate_relationship_tables($db, $langs, $conf, $table, $fk_source, $so $sqlInsert .= ")"; $result = $db->query($sqlInsert); - if (!$result) - { + if (!$result) { $error++; dol_print_error($db); } @@ -2849,11 +2768,9 @@ function migrate_relationship_tables($db, $langs, $conf, $table, $fk_source, $so print $langs->trans('AlreadyDone')."<br>\n"; } - if ($error == 0) - { + if ($error == 0) { $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX.$table; - if ($db->query($sqlDrop)) - { + if ($db->query($sqlDrop)) { $db->commit(); } else { $db->rollback(); @@ -2896,22 +2813,18 @@ function migrate_project_task_time($db, $langs, $conf) $sql = "SELECT rowid, fk_task, task_duration"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $totaltime = array(); $oldtime = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj->task_duration > 0) - { + if ($obj->task_duration > 0) { // convert to second // only for int time and float time ex: 1,75 for 1h45 list($hour, $min) = explode('.', $obj->task_duration); @@ -2924,36 +2837,37 @@ function migrate_project_task_time($db, $langs, $conf) $sql2 .= " WHERE rowid = ".$obj->rowid; $resql2 = $db->query($sql2); - if (!$resql2) - { + if (!$resql2) { $error++; dol_print_error($db); } print ". "; $oldtime++; - if (!empty($totaltime[$obj->fk_task])) $totaltime[$obj->fk_task] += $newtime; - else $totaltime[$obj->fk_task] = $newtime; + if (!empty($totaltime[$obj->fk_task])) { + $totaltime[$obj->fk_task] += $newtime; + } else { + $totaltime[$obj->fk_task] = $newtime; + } } else { - if (!empty($totaltime[$obj->fk_task])) $totaltime[$obj->fk_task] += $obj->task_duration; - else $totaltime[$obj->fk_task] = $obj->task_duration; + if (!empty($totaltime[$obj->fk_task])) { + $totaltime[$obj->fk_task] += $obj->task_duration; + } else { + $totaltime[$obj->fk_task] = $obj->task_duration; + } } $i++; } - if ($error == 0) - { - if ($oldtime > 0) - { - foreach ($totaltime as $taskid => $total_duration) - { + if ($error == 0) { + if ($oldtime > 0) { + foreach ($totaltime as $taskid => $total_duration) { $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET"; $sql .= " duration_effective = ".$total_duration; $sql .= " WHERE rowid = ".$taskid; $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; dol_print_error($db); } @@ -2971,8 +2885,7 @@ function migrate_project_task_time($db, $langs, $conf) dol_print_error($db); } - if ($error == 0) - { + if ($error == 0) { $db->commit(); } else { $db->rollback(); @@ -3002,8 +2915,7 @@ function migrate_customerorder_shipping($db, $langs, $conf) $result2 = $db->DDLDescTable(MAIN_DB_PREFIX."expedition", "date_delivery"); $obj1 = $db->fetch_object($result1); $obj2 = $db->fetch_object($result2); - if (!$obj1 && !$obj2) - { + if (!$obj1 && !$obj2) { dolibarr_install_syslog("upgrade2::migrate_customerorder_shipping"); $db->begin(); @@ -3011,8 +2923,7 @@ function migrate_customerorder_shipping($db, $langs, $conf) $sqlAdd1 = "ALTER TABLE ".MAIN_DB_PREFIX."expedition ADD COLUMN ref_customer varchar(30) AFTER entity"; $sqlAdd2 = "ALTER TABLE ".MAIN_DB_PREFIX."expedition ADD COLUMN date_delivery date DEFAULT NULL AFTER date_expedition"; - if ($db->query($sqlAdd1) && $db->query($sqlAdd2)) - { + if ($db->query($sqlAdd1) && $db->query($sqlAdd2)) { $sqlSelect = "SELECT e.rowid as shipping_id, c.ref_client, c.date_livraison as delivery_date"; $sqlSelect .= " FROM ".MAIN_DB_PREFIX."expedition as e"; $sqlSelect .= ", ".MAIN_DB_PREFIX."element_element as el"; @@ -3021,15 +2932,12 @@ function migrate_customerorder_shipping($db, $langs, $conf) $sqlSelect .= " AND el.targettype = 'shipping'"; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."expedition SET"; @@ -3038,8 +2946,7 @@ function migrate_customerorder_shipping($db, $langs, $conf) $sqlUpdate .= " WHERE rowid = ".$obj->shipping_id; $result = $db->query($sqlUpdate); - if (!$result) - { + if (!$result) { $error++; dol_print_error($db); } @@ -3050,8 +2957,7 @@ function migrate_customerorder_shipping($db, $langs, $conf) print $langs->trans('AlreadyDone')."<br>\n"; } - if ($error == 0) - { + if ($error == 0) { $db->commit(); } else { dol_print_error($db); @@ -3091,8 +2997,7 @@ function migrate_shipping_delivery($db, $langs, $conf) $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraison", "fk_expedition"); $obj = $db->fetch_object($result); - if ($obj) - { + if ($obj) { dolibarr_install_syslog("upgrade2::migrate_shipping_delivery"); $db->begin(); @@ -3102,15 +3007,12 @@ function migrate_shipping_delivery($db, $langs, $conf) $sqlSelect .= " WHERE fk_expedition is not null"; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; @@ -3126,14 +3028,12 @@ function migrate_shipping_delivery($db, $langs, $conf) $sqlInsert .= ")"; $result = $db->query($sqlInsert); - if ($result) - { + if ($result) { $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET fk_expedition = NULL"; $sqlUpdate .= " WHERE rowid = ".$obj->rowid; $result = $db->query($sqlUpdate); - if (!$result) - { + if (!$result) { $error++; dol_print_error($db); } @@ -3148,8 +3048,7 @@ function migrate_shipping_delivery($db, $langs, $conf) print $langs->trans('AlreadyDone')."<br>\n"; } - if ($error == 0) - { + if ($error == 0) { $sqlDelete = "DELETE FROM ".MAIN_DB_PREFIX."element_element WHERE sourcetype = 'commande' AND targettype = 'delivery'"; $db->query($sqlDelete); @@ -3208,15 +3107,12 @@ function migrate_shipping_delivery2($db, $langs, $conf) $sqlSelect .= " AND (l.date_delivery IS NULL".($db->type != 'pgsql' ? " or l.date_delivery = ''" : "").")"; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET"; @@ -3225,8 +3121,7 @@ function migrate_shipping_delivery2($db, $langs, $conf) $sqlUpdate .= " WHERE rowid = ".$obj->delivery_id; $result = $db->query($sqlUpdate); - if (!$result) - { + if (!$result) { $error++; dol_print_error($db); } @@ -3237,8 +3132,7 @@ function migrate_shipping_delivery2($db, $langs, $conf) print $langs->trans('AlreadyDone')."<br>\n"; } - if ($error == 0) - { + if ($error == 0) { $db->commit(); } else { dol_print_error($db); @@ -3276,12 +3170,10 @@ function migrate_actioncomm_element($db, $langs, $conf) 'invoice_supplier' => 'fk_supplier_invoice' ); - foreach ($elements as $type => $field) - { + foreach ($elements as $type => $field) { $result = $db->DDLDescTable(MAIN_DB_PREFIX."actioncomm", $field); $obj = $db->fetch_object($result); - if ($obj) - { + if ($obj) { dolibarr_install_syslog("upgrade2::migrate_actioncomm_element field=".$field); $db->begin(); @@ -3293,8 +3185,7 @@ function migrate_actioncomm_element($db, $langs, $conf) $sql .= " AND elementtype IS NULL"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $db->commit(); // DDL commands must not be inside a transaction @@ -3337,8 +3228,7 @@ function migrate_mode_reglement($db, $langs, $conf) ); $count = 0; - foreach ($elements['old_id'] as $key => $old_id) - { + foreach ($elements['old_id'] as $key => $old_id) { $error = 0; dolibarr_install_syslog("upgrade2::migrate_mode_reglement code=".$elements['code'][$key]); @@ -3349,11 +3239,9 @@ function migrate_mode_reglement($db, $langs, $conf) $sqlSelect .= " AND code = '".$db->escape($elements['code'][$key])."'"; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $count++; $db->begin(); @@ -3370,25 +3258,21 @@ function migrate_mode_reglement($db, $langs, $conf) $sql .= " AND code = '".$db->escape($elements['code'][$key])."'"; $resql = $db->query($sql); - if ($resqla && $resql) - { - foreach ($elements['tables'] as $table) - { + if ($resqla && $resql) { + foreach ($elements['tables'] as $table) { $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET "; $sql .= "fk_mode_reglement = ".$elements['new_id'][$key]; $sql .= " WHERE fk_mode_reglement = ".$old_id; $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); $error++; } print ". "; } - if (!$error) - { + if (!$error) { $db->commit(); } else { dol_print_error($db); @@ -3402,7 +3286,9 @@ function migrate_mode_reglement($db, $langs, $conf) } } - if ($count == 0) print $langs->trans('AlreadyDone')."<br>\n"; + if ($count == 0) { + print $langs->trans('AlreadyDone')."<br>\n"; + } print '</td></tr>'; @@ -3420,26 +3306,20 @@ function migrate_mode_reglement($db, $langs, $conf) function migrate_clean_association($db, $langs, $conf) { $result = $db->DDLDescTable(MAIN_DB_PREFIX."categorie_association"); - if ($result) // result defined for version 3.2 or - - { + if ($result) { // result defined for version 3.2 or - $obj = $db->fetch_object($result); - if ($obj) // It table categorie_association exists - { + if ($obj) { // It table categorie_association exists $couples = array(); $filles = array(); $sql = "SELECT fk_categorie_mere, fk_categorie_fille"; $sql .= " FROM ".MAIN_DB_PREFIX."categorie_association"; dolibarr_install_syslog("upgrade: search duplicate"); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - while ($obj = $db->fetch_object($resql)) - { - if (!isset($filles[$obj->fk_categorie_fille])) // Only one record as child (a child has only on parent). - { - if ($obj->fk_categorie_mere != $obj->fk_categorie_fille) - { + while ($obj = $db->fetch_object($resql)) { + if (!isset($filles[$obj->fk_categorie_fille])) { // Only one record as child (a child has only on parent). + if ($obj->fk_categorie_mere != $obj->fk_categorie_fille) { $filles[$obj->fk_categorie_fille] = 1; // Set record for this child $couples[$obj->fk_categorie_mere.'_'.$obj->fk_categorie_fille] = array('mere'=>$obj->fk_categorie_mere, 'fille'=>$obj->fk_categorie_fille); } @@ -3449,8 +3329,7 @@ function migrate_clean_association($db, $langs, $conf) dolibarr_install_syslog("upgrade: result is num=".$num." count(couples)=".count($couples)); // If there is duplicates couples or child with two parents - if (count($couples) > 0 && $num > count($couples)) - { + if (count($couples) > 0 && $num > count($couples)) { $error = 0; $db->begin(); @@ -3459,21 +3338,20 @@ function migrate_clean_association($db, $langs, $conf) $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_association"; dolibarr_install_syslog("upgrade: delete association"); $resqld = $db->query($sql); - if ($resqld) - { + if ($resqld) { // And we insert only each record once - foreach ($couples as $key => $val) - { + foreach ($couples as $key => $val) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_association(fk_categorie_mere,fk_categorie_fille)"; $sql .= " VALUES(".$val['mere'].", ".$val['fille'].")"; dolibarr_install_syslog("upgrade: insert association"); $resqli = $db->query($sql); - if (!$resqli) $error++; + if (!$resqli) { + $error++; + } } } - if (!$error) - { + if (!$error) { print '<tr><td>'.$langs->trans("MigrationCategorieAssociation").'</td>'; print '<td class="right">'.$langs->trans("RemoveDuplicates").' '.$langs->trans("Success").' ('.$num.'=>'.count($couples).')</td></tr>'; $db->commit(); @@ -3509,8 +3387,7 @@ function migrate_categorie_association($db, $langs, $conf) $error = 0; - if ($db->DDLInfoTable(MAIN_DB_PREFIX."categorie_association")) - { + if ($db->DDLInfoTable(MAIN_DB_PREFIX."categorie_association")) { dolibarr_install_syslog("upgrade2::migrate_categorie_association"); $db->begin(); @@ -3519,15 +3396,12 @@ function migrate_categorie_association($db, $langs, $conf) $sqlSelect .= " FROM ".MAIN_DB_PREFIX."categorie_association"; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."categorie SET "; @@ -3535,8 +3409,7 @@ function migrate_categorie_association($db, $langs, $conf) $sqlUpdate .= " WHERE rowid = ".$obj->fk_categorie_fille; $result = $db->query($sqlUpdate); - if (!$result) - { + if (!$result) { $error++; dol_print_error($db); } @@ -3547,8 +3420,7 @@ function migrate_categorie_association($db, $langs, $conf) print $langs->trans('AlreadyDone')."<br>\n"; } - if (!$error) - { + if (!$error) { // TODO DROP table in the next release /* $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX."categorie_association"; @@ -3606,23 +3478,19 @@ function migrate_event_assignement($db, $langs, $conf) //print $sqlSelect; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) "; $sqlUpdate .= "VALUES(".$obj->id.", 'user', ".$obj->fk_user_action.")"; $result = $db->query($sqlUpdate); - if (!$result) - { + if (!$result) { $error++; dol_print_error($db); } @@ -3633,8 +3501,7 @@ function migrate_event_assignement($db, $langs, $conf) print $langs->trans('AlreadyDone')."<br>\n"; } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -3677,23 +3544,19 @@ function migrate_event_assignement_contact($db, $langs, $conf) //print $sqlSelect; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) "; $sqlUpdate .= "VALUES(".$obj->id.", 'socpeople', ".$obj->fk_contact.")"; $result = $db->query($sqlUpdate); - if (!$result) - { + if (!$result) { $error++; dol_print_error($db); } @@ -3704,8 +3567,7 @@ function migrate_event_assignement_contact($db, $langs, $conf) print $langs->trans('AlreadyDone')."<br>\n"; } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -3751,34 +3613,28 @@ function migrate_reset_blocked_log($db, $langs, $conf) //print $sqlSelect; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); print 'Process entity '.$obj->entity; $sqlSearch = "SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."blockedlog WHERE action = 'MODULE_SET' and entity = ".$obj->entity; $resqlSearch = $db->query($sqlSearch); - if ($resqlSearch) - { + if ($resqlSearch) { $objSearch = $db->fetch_object($resqlSearch); //var_dump($objSearch); - if ($objSearch && $objSearch->nb == 0) - { + if ($objSearch && $objSearch->nb == 0) { print ' - Record for entity must be reset...'; $sqlUpdate = "DELETE FROM ".MAIN_DB_PREFIX."blockedlog"; $sqlUpdate .= " WHERE entity = ".$obj->entity; $resqlUpdate = $db->query($sqlUpdate); - if (!$resqlUpdate) - { + if (!$resqlUpdate) { $error++; dol_print_error($db); } else { @@ -3811,8 +3667,7 @@ function migrate_reset_blocked_log($db, $langs, $conf) print $langs->trans('NothingToDo')."<br>\n"; } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -3854,15 +3709,12 @@ function migrate_remise_entity($db, $langs, $conf) //print $sqlSelect; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise SET"; @@ -3870,8 +3722,7 @@ function migrate_remise_entity($db, $langs, $conf) $sqlUpdate .= " WHERE rowid = ".$obj->rowid; $result = $db->query($sqlUpdate); - if (!$result) - { + if (!$result) { $error++; dol_print_error($db); } @@ -3883,8 +3734,7 @@ function migrate_remise_entity($db, $langs, $conf) print $langs->trans('AlreadyDone')."<br>\n"; } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -3923,26 +3773,21 @@ function migrate_remise_except_entity($db, $langs, $conf) //print $sqlSelect; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); - if (!empty($obj->fk_facture_source) || !empty($obj->fk_facture)) - { + if (!empty($obj->fk_facture_source) || !empty($obj->fk_facture)) { $fk_facture = (!empty($obj->fk_facture_source) ? $obj->fk_facture_source : $obj->fk_facture); $sqlSelect2 = "SELECT f.entity"; $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."facture as f"; $sqlSelect2 .= " WHERE f.rowid = ".$fk_facture; - } elseif (!empty($obj->fk_facture_line)) - { + } elseif (!empty($obj->fk_facture_line)) { $sqlSelect2 = "SELECT f.entity"; $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as fd"; $sqlSelect2 .= " WHERE fd.rowid = ".$obj->fk_facture_line; @@ -3954,10 +3799,8 @@ function migrate_remise_except_entity($db, $langs, $conf) } $resql2 = $db->query($sqlSelect2); - if ($resql2) - { - if ($db->num_rows($resql2) > 0) - { + if ($resql2) { + if ($db->num_rows($resql2) > 0) { $obj2 = $db->fetch_object($resql2); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except SET"; @@ -3965,8 +3808,7 @@ function migrate_remise_except_entity($db, $langs, $conf) $sqlUpdate .= " WHERE rowid = ".$obj->rowid; $result = $db->query($sqlUpdate); - if (!$result) - { + if (!$result) { $error++; dol_print_error($db); } @@ -3983,8 +3825,7 @@ function migrate_remise_except_entity($db, $langs, $conf) print $langs->trans('AlreadyDone')."<br>\n"; } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -4024,15 +3865,12 @@ function migrate_user_rights_entity($db, $langs, $conf) //print $sqlSelect; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."user_rights SET"; @@ -4040,8 +3878,7 @@ function migrate_user_rights_entity($db, $langs, $conf) $sqlUpdate .= " WHERE fk_user = ".$obj->rowid; $result = $db->query($sqlUpdate); - if (!$result) - { + if (!$result) { $error++; dol_print_error($db); } @@ -4053,8 +3890,7 @@ function migrate_user_rights_entity($db, $langs, $conf) print $langs->trans('AlreadyDone')."<br>\n"; } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -4094,15 +3930,12 @@ function migrate_usergroup_rights_entity($db, $langs, $conf) //print $sqlSelect; $resql = $db->query($sqlSelect); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $db->fetch_object($resql); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."usergroup_rights SET"; @@ -4110,8 +3943,7 @@ function migrate_usergroup_rights_entity($db, $langs, $conf) $sqlUpdate .= " WHERE fk_usergroup = ".$obj->rowid; $result = $db->query($sqlUpdate); - if (!$result) - { + if (!$result) { $error++; dol_print_error($db); } @@ -4123,8 +3955,7 @@ function migrate_usergroup_rights_entity($db, $langs, $conf) print $langs->trans('AlreadyDone')."<br>\n"; } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -4152,8 +3983,7 @@ function migrate_rename_directories($db, $langs, $conf, $oldname, $newname) { dolibarr_install_syslog("upgrade2::migrate_rename_directories"); - if (is_dir(DOL_DATA_ROOT.$oldname) && !file_exists(DOL_DATA_ROOT.$newname)) - { + if (is_dir(DOL_DATA_ROOT.$oldname) && !file_exists(DOL_DATA_ROOT.$newname)) { dolibarr_install_syslog("upgrade2::migrate_rename_directories move ".DOL_DATA_ROOT.$oldname.' into '.DOL_DATA_ROOT.$newname); @rename(DOL_DATA_ROOT.$oldname, DOL_DATA_ROOT.$newname); } @@ -4289,18 +4119,22 @@ function migrate_delete_old_dir($db, $langs, $conf) * @param DoliDB $db Database handler * @param Translate $langs Object langs * @param Conf $conf Object conf - * @param array $listofmodule List of modules + * @param array $listofmodule List of modules, like array('MODULE_KEY_NAME'=>', $reloadmode) * @param int $force 1=Reload module even if not already loaded * @return int <0 if KO, >0 if OK */ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $force = 0) { - if (count($listofmodule) == 0) return; + if (count($listofmodule) == 0) { + return; + } dolibarr_install_syslog("upgrade2::migrate_reload_modules force=".$force.", listofmodule=".join(',', array_keys($listofmodule))); foreach ($listofmodule as $moduletoreload => $reloadmode) { // reloadmodule can be 'noboxes', 'newboxdefonly', 'forceactivate' - if (empty($moduletoreload) || (empty($conf->global->$moduletoreload) && !$force)) continue; // Discard reload if module not enabled + if (empty($moduletoreload) || (empty($conf->global->$moduletoreload) && !$force)) { + continue; // Discard reload if module not enabled + } $mod = null; @@ -4328,6 +4162,15 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo $mod->remove('noboxes'); $mod->init($reloadmode); } + } elseif ($moduletoreload == 'MAIN_MODULE_BLOCKEDLOG') { + dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate BlockedLog module"); + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modBlockedLog.class.php'; + if ($res) { + $mod = new modBlockedLog($db); + // For this module we only reload menus. + $mod->delete_menus(); + $mod->insert_menus(); + } } elseif ($moduletoreload == 'MAIN_MODULE_CRON') { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Cron module"); $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modCron.class.php'; @@ -4472,24 +4315,25 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo $mod->remove('noboxes'); // We need to remove because menu entries has changed $mod->init($reloadmode); } - } else { + } else { // Other generic cases/modules $reg = array(); $tmp = preg_match('/MAIN_MODULE_([a-zA-Z0-9]+)/', $moduletoreload, $reg); - if (!empty($reg[1])) - { - if (strtoupper($moduletoreload) == $moduletoreload) // If key is un uppercase - { + if (!empty($reg[1])) { + if (strtoupper($moduletoreload) == $moduletoreload) { // If key is un uppercase $moduletoreloadshort = ucfirst(strtolower($reg[1])); } else // If key is a mix of up and low case { $moduletoreloadshort = $reg[1]; } + dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate module ".$moduletoreloadshort." with mode ".$reloadmode); $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php'; if ($res) { $classname = 'mod'.$moduletoreloadshort; $mod = new $classname($db); + //$mod->remove('noboxes'); + $mod->delete_menus(); // We must delete to be sure it is inserted with new values $mod->init($reloadmode); } else { dolibarr_install_syslog('Failed to include '.DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php'); @@ -4498,7 +4342,6 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo if ($res) { $classname = 'mod'.$moduletoreloadshort; $mod = new $classname($db); - //$mod->remove('noboxes'); $mod->init($reloadmode); } else { dolibarr_install_syslog('Failed to include '.strtolower($moduletoreloadshort).'/core/modules/mod'.$moduletoreloadshort.'.class.php', LOG_ERR); @@ -4513,9 +4356,8 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo } } - if (!empty($mod) && is_object($mod)) - { - print '<tr><td colspan="4">'; + if (!empty($mod) && is_object($mod)) { + print '<tr class="trforrunsql"><td colspan="4">'; print '<b>'.$langs->trans('Upgrade').'</b>: '; print $langs->trans('MigrationReloadModule').' '.$mod->getName(); // We keep getName outside of trans because getName is already encoded/translated print "<!-- (".$reloadmode.") -->"; @@ -4530,7 +4372,7 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo /** - * Reload menu if dynamic menus, if modified by version + * Reload SQL menu file (if dynamic menus, if modified by version) * * @param DoliDB $db Database handler * @param Translate $langs Object langs @@ -4545,14 +4387,12 @@ function migrate_reload_menu($db, $langs, $conf) // Define list of menu handlers to initialize $listofmenuhandler = array(); if ($conf->global->MAIN_MENU_STANDARD == 'auguria_menu' || $conf->global->MAIN_MENU_SMARTPHONE == 'auguria_menu' - || $conf->global->MAIN_MENUFRONT_STANDARD == 'auguria_menu' || $conf->global->MAIN_MENUFRONT_SMARTPHONE == 'auguria_menu') - { + || $conf->global->MAIN_MENUFRONT_STANDARD == 'auguria_menu' || $conf->global->MAIN_MENUFRONT_SMARTPHONE == 'auguria_menu') { $listofmenuhandler['auguria'] = 1; // We set here only dynamic menu handlers } - foreach ($listofmenuhandler as $key => $val) - { - print '<tr><td colspan="4">'; + foreach ($listofmenuhandler as $key => $val) { + print '<tr class="trforrunsql"><td colspan="4">'; //print "x".$key; print '<br>'; @@ -4561,8 +4401,7 @@ function migrate_reload_menu($db, $langs, $conf) // Load sql ini_menu_handler.sql file $dir = DOL_DOCUMENT_ROOT."/core/menus/"; $file = 'init_menu_'.$key.'.sql'; - if (file_exists($dir.$file)) - { + if (file_exists($dir.$file)) { $result = run_sql($dir.$file, 1, '', 1, $key); } @@ -4586,14 +4425,14 @@ function migrate_user_photospath() include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; $fuser = new User($db); - if (!is_object($user)) $user = $fuser; // To avoid error during migration + if (!is_object($user)) { + $user = $fuser; // To avoid error during migration + } $sql = "SELECT rowid as uid from ".MAIN_DB_PREFIX."user"; // Get list of all users $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $db->fetch_object($resql)) { $fuser->fetch($obj->uid); //echo '<hr>'.$fuser->id.' -> '.$fuser->entity; $entity = (empty($fuser->entity) ? 1 : $fuser->entity); @@ -4603,8 +4442,7 @@ function migrate_user_photospath() $dir = $conf->user->multidir_output[$entity]; // $conf->user->multidir_output[] for each entity is construct by the multicompany module } - if ($dir) - { + if ($dir) { //print "Process user id ".$fuser->id."<br>\n"; $origin = $dir.'/'.get_exdir($fuser->id, 2, 0, 1, $fuser, 'user'); // Use old behaviour to get x/y path $destin = $dir.'/'.$fuser->id; @@ -4614,26 +4452,23 @@ function migrate_user_photospath() dol_mkdir($destin); //echo '<hr>'.$origin.' -> '.$destin; - if (dol_is_dir($origin)) - { + if (dol_is_dir($origin)) { $handle = opendir($origin_osencoded); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if ($file == '.' || $file == '..') continue; + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if ($file == '.' || $file == '..') { + continue; + } - if (dol_is_dir($origin.'/'.$file)) // it is a dir (like 'thumbs') - { + if (dol_is_dir($origin.'/'.$file)) { // it is a dir (like 'thumbs') $thumbs = opendir($origin_osencoded.'/'.$file); - if (is_resource($thumbs)) - { - dol_mkdir($destin.'/'.$file); - while (($thumb = readdir($thumbs)) !== false) - { - if (!dol_is_file($destin.'/'.$file.'/'.$thumb)) - { - if ($thumb == '.' || $thumb == '..') continue; + if (is_resource($thumbs)) { + dol_mkdir($destin.'/'.$file); + while (($thumb = readdir($thumbs)) !== false) { + if (!dol_is_file($destin.'/'.$file.'/'.$thumb)) { + if ($thumb == '.' || $thumb == '..') { + continue; + } //print $origin.'/'.$file.'/'.$thumb.' -> '.$destin.'/'.$file.'/'.$thumb.'<br>'."\n"; print '.'; @@ -4645,8 +4480,7 @@ function migrate_user_photospath() } } else // it is a file { - if (!dol_is_file($destin.'/'.$file)) - { + if (!dol_is_file($destin.'/'.$file)) { //print $origin.'/'.$file.' -> '.$destin.'/'.$file.'<br>'."\n"; print '.'; dol_copy($origin.'/'.$file, $destin.'/'.$file, 0, 0); diff --git a/htdocs/intracommreport/admin/intracommreport.php b/htdocs/intracommreport/admin/intracommreport.php index 16e24503959..c696dddcabd 100644 --- a/htdocs/intracommreport/admin/intracommreport.php +++ b/htdocs/intracommreport/admin/intracommreport.php @@ -30,7 +30,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "intracommreport")); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); @@ -46,10 +48,8 @@ $list_DES = array( if ($action == 'update') { $error = 0; - if (!$error) - { - foreach ($list_DEB as $constname) - { + if (!$error) { + foreach ($list_DEB as $constname) { $constvalue = GETPOST($constname, 'alpha'); if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { @@ -57,8 +57,7 @@ if ($action == 'update') { } } - foreach ($list_DES as $constname) - { + foreach ($list_DES as $constname) { $constvalue = GETPOST($constname, 'alpha'); if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { @@ -110,8 +109,7 @@ print '<td>'.$langs->trans("Description").'</td>'; print '<td>'.$langs->trans("Value").'</td>'; print '</tr>'; -foreach ($list_DEB as $key) -{ +foreach ($list_DEB as $key) { print '<tr class="oddeven value">'; // Param @@ -175,8 +173,7 @@ print '<td>'.$langs->trans("Description").'</td>'; print '<td>'.$langs->trans("Value").'</td>'; print '</tr>'; -foreach ($list_DES as $key) -{ +foreach ($list_DES as $key) { print '<tr class="oddeven value">'; // Param diff --git a/htdocs/langs/bs_BA/admin.lang b/htdocs/langs/bs_BA/admin.lang index 8edb636b439..268bcdc7337 100644 --- a/htdocs/langs/bs_BA/admin.lang +++ b/htdocs/langs/bs_BA/admin.lang @@ -1367,7 +1367,7 @@ BillsNumberingModule=Invoices and credit notes numbering model BillsPDFModules=Invoice documents models BillsPDFModulesAccordindToInvoiceType=Invoice documents models according to invoice type PaymentsPDFModules=Payment documents models -ForceInvoiceDate=Force invoice date to validation date +ForceInvoiceDate=Force invoice date to validation date (forcing is possible only the first time an invoice is validated) SuggestedPaymentModesIfNotDefinedInInvoice=Suggested payments mode on invoice by default if not defined on the invoice SuggestPaymentByRIBOnAccount=Suggest payment by withdrawal on account SuggestPaymentByChequeToAddress=Suggest payment by check to diff --git a/htdocs/langs/en_US/accountancy.lang b/htdocs/langs/en_US/accountancy.lang index 9e084932477..c635809404e 100644 --- a/htdocs/langs/en_US/accountancy.lang +++ b/htdocs/langs/en_US/accountancy.lang @@ -131,7 +131,7 @@ InvoiceLinesDone=Bound lines of invoices ExpenseReportLines=Lines of expense reports to bind ExpenseReportLinesDone=Bound lines of expense reports IntoAccount=Bind line with the accounting account -TotalForAccount=Total for accounting account +TotalForAccount=Total accounting account Ventilate=Bind diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index de7b0e704b4..6f7515a01ac 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -37,6 +37,7 @@ UnlockNewSessions=Remove connection lock YourSession=Your session Sessions=Users Sessions WebUserGroup=Web server user/group +PermissionsOnFiles=Permissions on files PermissionsOnFilesInWebRoot=Permissions on files in web root directory PermissionsOnFile=Permissions on file %s NoSessionFound=Your PHP configuration seems to not allow listing of active sessions. The directory used to save sessions (<b>%s</b>) may be protected (for example by OS permissions or by PHP directive open_basedir). @@ -62,6 +63,7 @@ IfModuleEnabled=Note: yes is effective only if module <b>%s</b> is enabled RemoveLock=Remove/rename file <b>%s</b> if it exists, to allow usage of the Update/Install tool. RestoreLock=Restore file <b>%s</b>, with read permission only, to disable any further use of the Update/Install tool. SecuritySetup=Security setup +PHPSetup=PHP setup SecurityFilesDesc=Define here options related to security about uploading files. ErrorModuleRequirePHPVersion=Error, this module requires PHP version %s or higher ErrorModuleRequireDolibarrVersion=Error, this module requires Dolibarr version %s or higher @@ -232,6 +234,7 @@ BoxesAvailable=Widgets available BoxesActivated=Widgets activated ActivateOn=Activate on ActiveOn=Activated on +ActivatableOn=Activatable on SourceFile=Source file AvailableOnlyIfJavascriptAndAjaxNotDisabled=Available only if JavaScript is not disabled Required=Required @@ -347,9 +350,10 @@ LastActivationAuthor=Latest activation author LastActivationIP=Latest activation IP UpdateServerOffline=Update server offline WithCounter=Manage a counter -GenericMaskCodes=You may enter any numbering mask. In this mask, the following tags could be used:<br><b>{000000}</b> corresponds to a number which will be incremented on each %s. Enter as many zeros as the desired length of the counter. The counter will be completed by zeros from the left in order to have as many zeros as the mask. <br><b>{000000+000}</b> same as previous but an offset corresponding to the number to the right of the + sign is applied starting on first %s. <br><b>{000000@x}</b> same as previous but the counter is reset to zero when month x is reached (x between 1 and 12, or 0 to use the early months of fiscal year defined in your configuration, or 99 to reset to zero every month). If this option is used and x is 2 or higher, then sequence {yy}{mm} or {yyyy}{mm} is also required. <br><b>{dd}</b> day (01 to 31).<br><b>{mm}</b> month (01 to 12).<br><b>{yy}</b>, <b>{yyyy}</b> or <b>{y}</b> year over 2, 4 or 1 numbers. <br> -GenericMaskCodes2=<b>{cccc}</b> the client code on n characters<br><b>{cccc000}</b> the client code on n characters is followed by a counter dedicated for customer. This counter dedicated to customer is reset at same time than global counter.<br><b>{tttt}</b> The code of third party type on n characters (see menu Home - Setup - Dictionary - Types of third parties). If you add this tag, the counter will be different for each type of third party.<br> -GenericMaskCodes3=All other characters in the mask will remain intact (except * or ? in 13th position in EAN13).<br>Spaces are not allowed.<br>In EAN13, the last character after the last } in 13th position should be * or ? . It will be replaced by the calculated key.<br> +GenericMaskCodes=You may enter any numbering mask. In this mask, the following tags can be used:<br><b>{000000}</b> corresponds to a number which will be incremented on each %s. Enter as many zeros as the desired length of the counter. The counter will be completed by zeros from the left in order to have as many zeros as the mask. <br><b>{000000+000}</b> same as the previous one but an offset corresponding to the number to the right of the + sign is applied starting on the first %s. <br><b>{000000@x}</b> same as the previous one but the counter is reset to zero when month x is reached (x between 1 and 12, or 0 to use the early months of fiscal year defined in your configuration, or 99 to reset to zero every month). If this option is used and x is 2 or higher, then the sequence {yy}{mm} or {yyyy}{mm} is also required. <br><b>{dd}</b> day (01 to 31).<br><b>{mm}</b> month (01 to 12).<br><b>{yy}</b>, <b>{yyyy}</b> or <b>{y}</b> year over 2, 4 or 1 numbers. <br> +GenericMaskCodes2=<b>{cccc}</b> the client code on n characters<br><b>{cccc000}</b> the client code on n characters is followed by a counter dedicated to the customer. This counter dedicated to customer is reset at same time as the global counter.<br><b>{tttt}</b> The code of third party type on n characters (see menu Home - Setup - Dictionary - Types of third parties). If you add this tag, the counter will be different for each type of third party.<br> +GenericMaskCodes3=All other characters in the mask will remain intact.<br>Spaces are not allowed.<br> +GenericMaskCodes3EAN=All other characters in the mask will remain intact (except * or ? in 13th position in EAN13).<br>Spaces are not allowed.<br>In EAN13, the last character after the last } in 13th position should be * or ? . It will be replaced by the calculated key.<br> GenericMaskCodes4a=<u>Example on the 99th %s of the third party TheCompany, with date 2007-01-31:</u><br> GenericMaskCodes4b=<u>Example on third party created on 2007-03-01:</u><br> GenericMaskCodes4c=<u>Example on product created on 2007-03-01:</u><br> @@ -647,8 +651,8 @@ Module4000Name=HRM Module4000Desc=Human resources management (management of department, employee contracts and feelings) Module5000Name=Multi-company Module5000Desc=Allows you to manage multiple companies -Module6000Name=Workflow -Module6000Desc=Workflow management (automatic creation of object and/or automatic status change) +Module6000Name=Inter-modules Workflow +Module6000Desc=Workflow management between different modules (automatic creation of object and/or automatic status change) Module10000Name=Websites Module10000Desc=Create websites (public) with a WYSIWYG editor. This is a webmaster or developer oriented CMS (it is better to know HTML and CSS language). Just setup your web server (Apache, Nginx, ...) to point to the dedicated Dolibarr directory to have it online on the internet with your own domain name. Module20000Name=Leave Request Management @@ -1248,7 +1252,7 @@ RunningUpdateProcessMayBeRequired=Running the upgrade process seems to be requir YouMustRunCommandFromCommandLineAfterLoginToUser=You must run this command from command line after login to a shell with user <b>%s</b> or you must add -W option at end of command line to provide <b>%s</b> password. YourPHPDoesNotHaveSSLSupport=SSL functions not available in your PHP DownloadMoreSkins=More skins to download -SimpleNumRefModelDesc=Returns the reference number with format %syymm-nnnn where yy is year, mm is month and nnnn is sequential with no reset +SimpleNumRefModelDesc=Returns the reference number in the format %syymm-nnnn where yy is the year, mm is the month and nnnn is a sequential auto-incrementing number with no reset ShowProfIdInAddress=Show professional id with addresses ShowVATIntaInAddress=Hide intra-Community VAT number with addresses TranslationUncomplete=Partial translation @@ -1266,7 +1270,7 @@ MAIN_PROXY_HOST=Proxy server: Name/Address MAIN_PROXY_PORT=Proxy server: Port MAIN_PROXY_USER=Proxy server: Login/User MAIN_PROXY_PASS=Proxy server: Password -DefineHereComplementaryAttributes=Define here any additional/custom attributes that you want to be included for: %s +DefineHereComplementaryAttributes=Define any additional / custom attributes that must be added to: %s ExtraFields=Complementary attributes ExtraFieldsLines=Complementary attributes (lines) ExtraFieldsLinesRec=Complementary attributes (templates invoices lines) @@ -1510,6 +1514,7 @@ LDAPFieldLoginUnix=Login (unix) LDAPFieldLoginExample=Example: uid LDAPFilterConnection=Search filter LDAPFilterConnectionExample=Example: &(objectClass=inetOrgPerson) +LDAPGroupFilterExample=Example: &(objectClass=groupOfUsers) LDAPFieldLoginSamba=Login (samba, activedirectory) LDAPFieldLoginSambaExample=Example: samaccountname LDAPFieldFullname=Full name @@ -1741,6 +1746,7 @@ YourCompanyDoesNotUseVAT=Your company has been defined to not use VAT (Home - Se AccountancyCode=Accounting Code AccountancyCodeSell=Sale account. code AccountancyCodeBuy=Purchase account. code +CREATE_NEW_VAT_WITHOUT_AUTO_PAYMENT=Keep the checkbox “Automatically create the payment” empty by default when creating a new tax ##### Agenda ##### AgendaSetup=Events and agenda module setup PasswordTogetVCalExport=Key to authorize export link @@ -1987,7 +1993,7 @@ SocialNetworkSetup=Setup of module Social Networks EnableFeatureFor=Enable features for <strong>%s</strong> VATIsUsedIsOff=Note: The option to use Sales Tax or VAT has been set to <strong>Off</strong> in the menu %s - %s, so Sales tax or Vat used will always be 0 for sales. SwapSenderAndRecipientOnPDF=Swap sender and recipient address position on PDF documents -FeatureSupportedOnTextFieldsOnly=Warning, feature supported on text fields only. Also an URL parameter action=create or action=edit must be set OR page name must end with 'new.php' to trigger this feature. +FeatureSupportedOnTextFieldsOnly=Warning, feature supported on text fields and combo lists only. Also an URL parameter action=create or action=edit must be set OR page name must end with 'new.php' to trigger this feature. EmailCollector=Email collector EmailCollectorDescription=Add a scheduled job and a setup page to scan regularly email boxes (using IMAP protocol) and record emails received into your application, at the right place and/or create some records automatically (like leads). NewEmailCollector=New Email Collector @@ -2094,11 +2100,15 @@ SwitchThisForABetterSecurity=Switching this value to %s is recommended for more DictionaryProductNature= Nature of product CountryIfSpecificToOneCountry=Country (if specific to a given country) YouMayFindSecurityAdviceHere=You may find security advisory here -ModuleActivatedMayExposeInformation=This module may expose sensitive data. If you don't need it, disable it. +ModuleActivatedMayExposeInformation=This PHP extension may expose sensitive data. If you don't need it, disable it. ModuleActivatedDoNotUseInProduction=A module designed for the development has been enabled. Do not enable it on a production environment. CombinationsSeparator=Separator character for product combinations SeeLinkToOnlineDocumentation=See link to online documention on top menu for examples SHOW_SUBPRODUCT_REF_IN_PDF=If the feature "%s" of module <b>%s</b> is used, show details of subproducts of a kit on PDF. AskThisIDToYourBank=Contact your bank to get this ID AdvancedModeOnly=Permision available in Advanced permission mode only -ConfFileIsReadableOrWritableByAnyUsers=The conf file is reabable or writable by any users. Give permission to web server user and group only. +ConfFileIsReadableOrWritableByAnyUsers=The conf file is readable or writable by any users. Give permission to web server user and group only. +MailToSendEventOrganization=Event Organization +AGENDA_EVENT_DEFAULT_STATUS=Default event status when creating a event from the form +YouShouldDisablePHPFunctions=You should disable PHP functions +IfCLINotRequiredYouShouldDisablePHPFunctions=Except if you need to run system commands (for the module Scheduled job for example), you shoud disable PHP functions diff --git a/htdocs/langs/en_US/agenda.lang b/htdocs/langs/en_US/agenda.lang index 33e0c01aad6..d16188d40d4 100644 --- a/htdocs/langs/en_US/agenda.lang +++ b/htdocs/langs/en_US/agenda.lang @@ -4,7 +4,7 @@ Actions=Events Agenda=Agenda TMenuAgenda=Agenda Agendas=Agendas -LocalAgenda=Internal calendar +LocalAgenda=Default calendar ActionsOwnedBy=Event owned by ActionsOwnedByShort=Owner AffectedTo=Assigned to @@ -20,7 +20,7 @@ MenuToDoActions=All incomplete events MenuDoneActions=All terminated events MenuToDoMyActions=My incomplete events MenuDoneMyActions=My terminated events -ListOfEvents=List of events (internal calendar) +ListOfEvents=List of events (default calendar) ActionsAskedBy=Events reported by ActionsToDoBy=Events assigned to ActionsDoneBy=Events done by @@ -131,7 +131,7 @@ AgendaUrlOptions4=<b>logint=%s</b> to restrict output to actions assigned to use AgendaUrlOptionsProject=<b>project=__PROJECT_ID__</b> to restrict output to actions linked to project <b>__PROJECT_ID__</b>. AgendaUrlOptionsNotAutoEvent=<b>notactiontype=systemauto</b> to exclude automatic events. AgendaUrlOptionsIncludeHolidays=<b>includeholidays=1</b> to include events of holidays. -AgendaShowBirthdayEvents=Show birthdays of contacts +AgendaShowBirthdayEvents=Birthdays of contacts AgendaHideBirthdayEvents=Hide birthdays of contacts Busy=Busy ExportDataset_event1=List of agenda events diff --git a/htdocs/langs/en_US/assets.lang b/htdocs/langs/en_US/assets.lang index ef04723c6c2..afafc98503f 100644 --- a/htdocs/langs/en_US/assets.lang +++ b/htdocs/langs/en_US/assets.lang @@ -61,5 +61,7 @@ MenuListTypeAssets = List # # Module # +Asset=Asset NewAssetType=New asset type NewAsset=New asset +ConfirmDeleteAsset=Are you sure you want to delete this asset ? diff --git a/htdocs/langs/en_US/bills.lang b/htdocs/langs/en_US/bills.lang index 45246dcc412..a1e04809a36 100644 --- a/htdocs/langs/en_US/bills.lang +++ b/htdocs/langs/en_US/bills.lang @@ -413,7 +413,7 @@ PaymentCondition14DENDMONTH=Within 14 days following the end of the month FixAmount=Fixed amount - 1 line with label '%s' VarAmount=Variable amount (%% tot.) VarAmountOneLine=Variable amount (%% tot.) - 1 line with label '%s' -VarAmountAllLines=Variable amount (%% tot.) - all same lines +VarAmountAllLines=Variable amount (%% tot.) - all lines from origin # PaymentType PaymentTypeVIR=Bank transfer PaymentTypeShortVIR=Bank transfer @@ -495,6 +495,7 @@ Reported=Delayed DisabledBecausePayments=Not possible since there are some payments CantRemovePaymentWithOneInvoicePaid=Can't remove payment since there is at least one invoice classified paid CantRemovePaymentVATPaid=Can't remove payment since VAT declaration is classified paid +CantRemovePaymentSalaryPaid=Can't remove payment since salary is classified paid ExpectedToPay=Expected payment CantRemoveConciliatedPayment=Can't remove reconciled payment PayedByThisPayment=Paid by this payment @@ -502,6 +503,7 @@ ClosePaidInvoicesAutomatically=Classify automatically all standard, down payment ClosePaidCreditNotesAutomatically=Classify automatically all credit notes as "Paid" when refund is done entirely. ClosePaidContributionsAutomatically=Classify automatically all social or fiscal contributions as "Paid" when payment is done entirely. ClosePaidVATAutomatically=Classify automatically VAT declaration as "Paid" when payment is done entirely. +ClosePaidSalaryAutomatically=Classify automatically salary as "Paid" when payment is done entirely. AllCompletelyPayedInvoiceWillBeClosed=All invoices with no remainder to pay will be automatically closed with status "Paid". ToMakePayment=Pay ToMakePaymentBack=Pay back diff --git a/htdocs/langs/en_US/boxes.lang b/htdocs/langs/en_US/boxes.lang index 7c656426e5f..981b63500ac 100644 --- a/htdocs/langs/en_US/boxes.lang +++ b/htdocs/langs/en_US/boxes.lang @@ -18,9 +18,12 @@ BoxLastActions=Latest actions BoxLastContracts=Latest contracts BoxLastContacts=Latest contacts/addresses BoxLastMembers=Latest members +BoxLastModifiedMembers=Latest modified members BoxFicheInter=Latest interventions BoxCurrentAccounts=Open accounts balance BoxTitleMemberNextBirthdays=Birthdays of this month (members) +BoxTitleMembersByType=Members by type +BoxTitleMembersSubscriptionsByYear=Members Subscriptions by year BoxTitleLastRssInfos=Latest %s news from %s BoxTitleLastProducts=Products/Services: last %s modified BoxTitleProductsAlertStock=Products: stock alert @@ -87,8 +90,8 @@ BoxTitleLatestModifiedSupplierOrders=Vendor Orders: last %s modified BoxTitleLastModifiedCustomerBills=Customer Invoices: last %s modified BoxTitleLastModifiedCustomerOrders=Sales Orders: last %s modified BoxTitleLastModifiedPropals=Latest %s modified proposals -BoxTitleLatestModifiedJobPositions=Latest %s modified jobs -BoxTitleLatestModifiedCandidatures=Latest %s modified candidatures +BoxTitleLatestModifiedJobPositions=Latest %s modified jobs +BoxTitleLatestModifiedCandidatures=Latest %s modified candidatures ForCustomersInvoices=Customers invoices ForCustomersOrders=Customers orders ForProposals=Proposals @@ -108,5 +111,9 @@ BoxTitleLastCustomerShipments=Latest %s customer shipments NoRecordedShipments=No recorded customer shipment BoxCustomersOutstandingBillReached=Customers with oustanding limit reached # Pages -AccountancyHome=Accountancy +UsersHome=Home users and groups +MembersHome=Home Membership +ThirdpartiesHome=Home Thirdparties +TicketsHome=Home Tickets +AccountancyHome=Home Accountancy ValidatedProjects=Validated projects diff --git a/htdocs/langs/en_US/cashdesk.lang b/htdocs/langs/en_US/cashdesk.lang index 88ff8fecdb6..a24109fa3d0 100644 --- a/htdocs/langs/en_US/cashdesk.lang +++ b/htdocs/langs/en_US/cashdesk.lang @@ -56,7 +56,8 @@ Paymentnumpad=Type of Pad to enter payment Numberspad=Numbers Pad BillsCoinsPad=Coins and banknotes Pad DolistorePosCategory=TakePOS modules and other POS solutions for Dolibarr -TakeposNeedsCategories=TakePOS needs product categories to work +TakeposNeedsCategories=TakePOS needs at least one product categorie to work +TakeposNeedsAtLeastOnSubCategoryIntoParentCategory=TakePOS needs at least 1 product category under the category <b>%s</b> to work OrderNotes=Order Notes CashDeskBankAccountFor=Default account to use for payments in NoPaimementModesDefined=No paiment mode defined in TakePOS configuration @@ -123,4 +124,6 @@ GiftReceipt=Gift receipt ModuleReceiptPrinterMustBeEnabled=Module Receipt printer must have been enabled first AllowDelayedPayment=Allow delayed payment PrintPaymentMethodOnReceipts=Print payment method on tickets|receipts -WeighingScale=Weighing scale \ No newline at end of file +WeighingScale=Weighing scale +ShowPriceHT = Display the price excluding tax column +ShowPriceHTOnReceipt = Display the price excluding tax column on receipt diff --git a/htdocs/langs/en_US/categories.lang b/htdocs/langs/en_US/categories.lang index 4ddf0d6093f..5ec33145da1 100644 --- a/htdocs/langs/en_US/categories.lang +++ b/htdocs/langs/en_US/categories.lang @@ -14,7 +14,7 @@ SuppliersCategoriesArea=Vendors tags/categories area CustomersCategoriesArea=Customers tags/categories area MembersCategoriesArea=Members tags/categories area ContactsCategoriesArea=Contacts tags/categories area -AccountsCategoriesArea=Accounts tags/categories area +AccountsCategoriesArea=Bank accounts tags/categories area ProjectsCategoriesArea=Projects tags/categories area UsersCategoriesArea=Users tags/categories area SubCats=Sub-categories diff --git a/htdocs/langs/en_US/commercial.lang b/htdocs/langs/en_US/commercial.lang index 10c536e0d48..21d282cd794 100644 --- a/htdocs/langs/en_US/commercial.lang +++ b/htdocs/langs/en_US/commercial.lang @@ -64,10 +64,11 @@ ActionAC_SHIP=Send shipping by mail ActionAC_SUP_ORD=Send purchase order by mail ActionAC_SUP_INV=Send vendor invoice by mail ActionAC_OTH=Other -ActionAC_OTH_AUTO=Automatically inserted events +ActionAC_OTH_AUTO=Other auto ActionAC_MANUAL=Manually inserted events ActionAC_AUTO=Automatically inserted events -ActionAC_OTH_AUTOShort=Auto +ActionAC_OTH_AUTOShort=Other +ActionAC_EVENTORGANIZATION=Event organization events Stats=Sales statistics StatusProsp=Prospect status DraftPropals=Draft commercial proposals diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index 99bed13179f..42180dde04f 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -172,13 +172,13 @@ ProfId1ES=Prof Id 1 (CIF/NIF) ProfId2ES=Prof Id 2 (Social security number) ProfId3ES=Prof Id 3 (CNAE) ProfId4ES=Prof Id 4 (Collegiate number) -ProfId5ES=EORI number +ProfId5ES=Prof Id 5 (EORI number) ProfId6ES=- ProfId1FR=Prof Id 1 (SIREN) ProfId2FR=Prof Id 2 (SIRET) ProfId3FR=Prof Id 3 (NAF, old APE) ProfId4FR=Prof Id 4 (RCS/RM) -ProfId5FR=EORI number +ProfId5FR=Prof Id 5 (numéro EORI) ProfId6FR=- ProfId1GB=Registration Number ProfId2GB=- @@ -203,6 +203,7 @@ ProfId2IT=- ProfId3IT=- ProfId4IT=- ProfId5IT=EORI number +ProfId6IT=- ProfId1LU=Id. prof. 1 (R.C.S. Luxembourg) ProfId2LU=Id. prof. 2 (Business permit) ProfId3LU=- @@ -231,7 +232,7 @@ ProfId1PT=Prof Id 1 (NIPC) ProfId2PT=Prof Id 2 (Social security number) ProfId3PT=Prof Id 3 (Commercial Record number) ProfId4PT=Prof Id 4 (Conservatory) -ProfId5PT=EORI number +ProfId5PT=Prof Id 5 (EORI number) ProfId6PT=- ProfId1SN=RC ProfId2SN=NINEA @@ -255,7 +256,7 @@ ProfId1RO=Prof Id 1 (CUI) ProfId2RO=Prof Id 2 (Nr. Înmatriculare) ProfId3RO=Prof Id 3 (CAEN) ProfId4RO=Prof Id 5 (EUID) -ProfId5RO=EORI number +ProfId5RO=Prof Id 5 (EORI number) ProfId6RO=- ProfId1RU=Prof Id 1 (OGRN) ProfId2RU=Prof Id 2 (INN) diff --git a/htdocs/langs/en_US/compta.lang b/htdocs/langs/en_US/compta.lang index 23e6cf0d724..3f892e3b29c 100644 --- a/htdocs/langs/en_US/compta.lang +++ b/htdocs/langs/en_US/compta.lang @@ -86,7 +86,7 @@ PaymentCustomerInvoice=Customer invoice payment PaymentSupplierInvoice=vendor invoice payment PaymentSocialContribution=Social/fiscal tax payment PaymentVat=VAT payment -AutomaticCreationPayment=Automatically create a total payment +AutomaticCreationPayment=Automatically record the payment of the salary ListPayment=List of payments ListOfCustomerPayments=List of customer payments ListOfSupplierPayments=List of vendor payments @@ -139,12 +139,16 @@ DateChequeReceived=Check reception date NbOfCheques=No. of checks PaySocialContribution=Pay a social/fiscal tax PayVAT=Pay a VAT declaration +PaySalary=Pay a salary card ConfirmPaySocialContribution=Are you sure you want to classify this social or fiscal tax as paid ? ConfirmPayVAT=Are you sure you want to classify this VAT declaration as paid ? +ConfirmPaySalary=Are you sure you want to classify this salary card as paid? DeleteSocialContribution=Delete a social or fiscal tax payment DeleteVAT=Delete a VAT declaration +DeleteSalary=Delete a salary card ConfirmDeleteSocialContribution=Are you sure you want to delete this social/fiscal tax payment ? ConfirmDeleteVAT=Are you sure you want to delete this VAT declaration ? +ConfirmDeleteSalary=Are you sure you want to delete this salary? ExportDataset_tax_1=Social and fiscal taxes and payments CalcModeVATDebt=Mode <b>%sVAT on commitment accounting%s</b>. CalcModeVATEngagement=Mode <b>%sVAT on incomes-expenses%s</b>. @@ -191,6 +195,7 @@ VATReportByThirdParties=Sale tax report by third parties VATReportByCustomers=Sale tax report by customer VATReportByCustomersInInputOutputMode=Report by the customer VAT collected and paid VATReportByQuartersInInputOutputMode=Report by Sale tax rate of the tax collected and paid +VATReportShowByRateDetails=Show details of this rate LT1ReportByQuarters=Report tax 2 by rate LT2ReportByQuarters=Report tax 3 by rate LT1ReportByQuartersES=Report by RE rate @@ -244,6 +249,7 @@ ACCOUNTING_ACCOUNT_SUPPLIER=Accounting account used for vendor third parties ACCOUNTING_ACCOUNT_SUPPLIER_Desc=The dedicated accounting account defined on third party card will be used for Subledger accounting only. This one will be used for General Ledger and as default value of Subledger accounting if dedicated vendor accounting account on third party is not defined. ConfirmCloneTax=Confirm the clone of a social/fiscal tax ConfirmCloneVAT=Confirm the clone of a VAT declaration +ConfirmCloneSalary=Confirm the clone of a salary CloneTaxForNextMonth=Clone it for next month SimpleReport=Simple report AddExtraReport=Extra reports (add foreign and national customer report) diff --git a/htdocs/langs/en_US/dict.lang b/htdocs/langs/en_US/dict.lang index ec315d97142..0524cf1ca18 100644 --- a/htdocs/langs/en_US/dict.lang +++ b/htdocs/langs/en_US/dict.lang @@ -21,7 +21,7 @@ CountryNL=Netherlands CountryHU=Hungary CountryRU=Russia CountrySE=Sweden -CountryCI=Ivoiry Coast +CountryCI=Ivory Coast CountrySN=Senegal CountryAR=Argentina CountryCM=Cameroon diff --git a/htdocs/langs/en_US/donations.lang b/htdocs/langs/en_US/donations.lang index de4bdf68f03..d512abb2eea 100644 --- a/htdocs/langs/en_US/donations.lang +++ b/htdocs/langs/en_US/donations.lang @@ -32,3 +32,4 @@ DONATION_ART238=Show article 238 from CGI if you are concerned DONATION_ART885=Show article 885 from CGI if you are concerned DonationPayment=Donation payment DonationValidated=Donation %s validated +DonationUseThirdparties=Use an existing thirdparty as coordinates of donators diff --git a/htdocs/langs/en_US/errors.lang b/htdocs/langs/en_US/errors.lang index 545fcdb62fb..bb5e7c5e287 100644 --- a/htdocs/langs/en_US/errors.lang +++ b/htdocs/langs/en_US/errors.lang @@ -258,6 +258,9 @@ ErrorLanguageRequiredIfPageIsTranslationOfAnother=The language of new page must ErrorLanguageMustNotBeSourceLanguageIfPageIsTranslationOfAnother=The language of new page must not be the source language if it is set as a translation of another page ErrorAParameterIsRequiredForThisOperation=A parameter is mandatory for this operation ErrorDateIsInFuture=Error, the date can't be in the future +ErrorAnAmountWithoutTaxIsRequired=Error, amount is mandatory +ErrorAPercentIsRequired=Error, please fill in the percentage correctly +ErrorYouMustFirstSetupYourChartOfAccount=You must first setup your chart of account # Warnings WarningParamUploadMaxFileSizeHigherThanPostMaxSize=Your PHP parameter upload_max_filesize (%s) is higher than PHP parameter post_max_size (%s). This is not a consistent setup. @@ -289,4 +292,5 @@ WarningSomeBankTransactionByChequeWereRemovedAfter=Some bank transaction were re WarningFailedToAddFileIntoDatabaseIndex=Warning, failed to add file entry into ECM database index table WarningTheHiddenOptionIsOn=Warning, the hidden option <b>%s</b> is on. WarningCreateSubAccounts=Warning, you can't create directly a sub account, you must create a third party or an user and assign them an accounting code to find them in this list -WarningAvailableOnlyForHTTPSServers=Available only if using HTTPS secured connection. \ No newline at end of file +WarningAvailableOnlyForHTTPSServers=Available only if using HTTPS secured connection. +WarningModuleXDisabledSoYouMayMissEventHere=Module %s has not been enabled. So you may miss a lot of event here. \ No newline at end of file diff --git a/htdocs/langs/en_US/eventorganization.lang b/htdocs/langs/en_US/eventorganization.lang new file mode 100644 index 00000000000..5444ed59e3d --- /dev/null +++ b/htdocs/langs/en_US/eventorganization.lang @@ -0,0 +1,87 @@ +# Copyright (C) 2021 Florian Henry <florian.henry@scopen.fr> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# 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 <https://www.gnu.org/licenses/>. + +# +# Generic +# +ModuleEventOrganizationName = Event Organization +EventOrganizationDescription = Event Organization through Module Project +EventOrganizationDescriptionLong= Manage Event organization for conference, attendees, speaker, and attendees, with public subcription page + +# +# Menu +# +EventOrganizationMenuLeft = Organized events +EventOrganizationConferenceOrBoothMenuLeft = Conference Or Booth + +# +# Admin page +# +EventOrganizationSetup = Event Organization setup +Settings = Settings +EventOrganizationSetupPage = Event Organization setup page +EVENTORGANIZATION_TASK_LABEL = Task label created when validate +EVENTORGANIZATION_TASK_LABELTooltip = When validate a Conference or a booth, some tasks will be created in the project<br><br> for example: <br>Send Call for Conference<br>Send Call for Booth<br>Receive call for conferences<br>Receive call for Booth<br>Open subscriptions to events for attendees<br>Send remind of event to speakers<br>Send remind of event to Booth hoster<br>Send remind of event to attendees +EVENTORGANIZATION_CATEG_THIRDPARTY_CONF = Category to add to third-parties automatically created when someone suggests a conference +EVENTORGANIZATION_CATEG_THIRDPARTY_BOOTH = Category to add to third-parties automatically created when they suggests a booth +EVENTORGANIZATION_TEMPLATE_EMAIL_ASK_CONF = Template of email to send after receiving a suggestion of a conference. +EVENTORGANIZATION_TEMPLATE_EMAIL_ASK_BOOTH = Template of email to send after receiving a suggestion of a booth. +EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_BOOTH = Template of email to send after a subscription to a booth has been paid. +EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_EVENT = Template of email to send after a subscription to an event has been paid. +EVENTORGANIZATION_TEMPLATE_EMAIL_BULK_SPEAKER = Template of email of massaction to attendes +EVENTORGANIZATION_TEMPLATE_EMAIL_BULK_ATTENDES = Template of email of massaction to speakers + +# +# Object +# +EventOrganizationConfOrBooth= Conference Or Booth +ManageOrganizeEvent = Manage event organisation +ConferenceOrBooth = Conference Or Booth +ConferenceOrBoothTab = Conference Or Booth + +# +# Template Mail +# +YourOrganizationEventConfRequestWasReceived = Your request for conference was received +YourOrganizationEventBoothRequestWasReceived = Your request for booth was received +EventOrganizationEmailAskConf = Request for conference +EventOrganizationEmailAskBooth = Request for booth +EventOrganizationEmailSubsBooth = Subscription for booth +EventOrganizationEmailSubsEvent = Subscription for an event +EventOrganizationMassEmailAttendees = Communication to attendes +EventOrganizationMassEmailSpeakers = Communication to speakers + +# +# Event +# +AllowUnknownPeopleSuggestConf=Allow unknown people to suggest conferences +AllowUnknownPeopleSuggestConfHelp=Allow unknown people to suggest conferences +AllowUnknownPeopleSuggestBooth=Allow unknown people to suggest booth +AllowUnknownPeopleSuggestBoothHelp=Allow unknown people to suggest booth +PriceOfRegistration=Price of registration +PriceOfRegistrationHelp=Price of registration +PriceOfBooth=Price of subscription +PriceOfBoothHelp=Price of subscription +EventOrganizationICSLink=Link ICS for events + +# +# Status +# +EvntOrgDraft = Draft +EvntOrgSuggested = Suggested +EvntOrgConfirmed = Confirmed +EvntOrgNotQualified = Not Qualified +EvntOrgDone = Done +EvntOrgCancelled = Cancelled diff --git a/htdocs/langs/en_US/holiday.lang b/htdocs/langs/en_US/holiday.lang index eb2cd89adf1..2393a02ee50 100644 --- a/htdocs/langs/en_US/holiday.lang +++ b/htdocs/langs/en_US/holiday.lang @@ -13,7 +13,7 @@ ToReviewCP=Awaiting approval ApprovedCP=Approved CancelCP=Canceled RefuseCP=Refused -ValidatorCP=Approbator +ValidatorCP=Approver ListeCP=List of leave Leave=Leave request LeaveId=Leave ID @@ -39,11 +39,11 @@ TitreRequestCP=Leave request TypeOfLeaveId=Type of leave ID TypeOfLeaveCode=Type of leave code TypeOfLeaveLabel=Type of leave label -NbUseDaysCP=Number of days of vacation consumed -NbUseDaysCPHelp=The calculation takes into account the non working days and the holidays defined in the dictionary. -NbUseDaysCPShort=Days consumed -NbUseDaysCPShortInMonth=Days consumed in month -DayIsANonWorkingDay=%s is a non working day +NbUseDaysCP=Number of days of leave used +NbUseDaysCPHelp=The calculation takes into account the non-working days and the holidays defined in the dictionary. +NbUseDaysCPShort=Days of leave +NbUseDaysCPShortInMonth=Days of leave in month +DayIsANonWorkingDay=%s is a non-working day DateStartInMonth=Start date in month DateEndInMonth=End date in month EditCP=Edit @@ -55,7 +55,7 @@ TitleDeleteCP=Delete the leave request ConfirmDeleteCP=Confirm the deletion of this leave request? ErrorCantDeleteCP=Error you don't have the right to delete this leave request. CantCreateCP=You don't have the right to make leave requests. -InvalidValidatorCP=You must choose an approbator to your leave request. +InvalidValidatorCP=You must choose the approver for your leave request. NoDateDebut=You must select a start date. NoDateFin=You must select an end date. ErrorDureeCP=Your leave request does not contain working day. @@ -80,14 +80,14 @@ UserCP=User ErrorAddEventToUserCP=An error occurred while adding the exceptional leave. AddEventToUserOkCP=The addition of the exceptional leave has been completed. MenuLogCP=View change logs -LogCP=Log of updates of available vacation days -ActionByCP=Performed by -UserUpdateCP=For the user +LogCP=Log of all updates made to "Balance of Leave" +ActionByCP=Updated by +UserUpdateCP=Updated for PrevSoldeCP=Previous Balance NewSoldeCP=New Balance alreadyCPexist=A leave request has already been done on this period. -FirstDayOfHoliday=First day of vacation -LastDayOfHoliday=Last day of vacation +FirstDayOfHoliday=Beginning day of leave request +LastDayOfHoliday=Ending day of leave request BoxTitleLastLeaveRequests=Latest %s modified leave requests HolidaysMonthlyUpdate=Monthly update ManualUpdate=Manual update @@ -104,8 +104,8 @@ LEAVE_SICK=Sick leave LEAVE_OTHER=Other leave LEAVE_PAID_FR=Paid vacation ## Configuration du Module ## -LastUpdateCP=Latest automatic update of leave allocation -MonthOfLastMonthlyUpdate=Month of latest automatic update of leave allocation +LastUpdateCP=Last automatic update of leave allocation +MonthOfLastMonthlyUpdate=Month of last automatic update of leave allocation UpdateConfCPOK=Updated successfully. Module27130Name= Management of leave requests Module27130Desc= Management of leave requests @@ -125,8 +125,8 @@ HolidaysCanceledBody=Your leave request for %s to %s has been canceled. FollowedByACounter=1: This type of leave need to be followed by a counter. Counter is incremented manually or automatically and when a leave request is validated, counter is decremented.<br>0: Not followed by a counter. NoLeaveWithCounterDefined=There is no leave types defined that need to be followed by a counter GoIntoDictionaryHolidayTypes=Go into <strong>Home - Setup - Dictionaries - Type of leave</strong> to setup the different types of leaves. -HolidaySetup=Setup of module Holiday -HolidaysNumberingModules=Leave requests numbering models +HolidaySetup=Setup of module Leave +HolidaysNumberingModules=Numbering models for leave requests TemplatePDFHolidays=Template for leave requests PDF FreeLegalTextOnHolidays=Free text on PDF WatermarkOnDraftHolidayCards=Watermarks on draft leave requests diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang index a5cd750e3d6..e27ec6d9c43 100644 --- a/htdocs/langs/en_US/main.lang +++ b/htdocs/langs/en_US/main.lang @@ -361,7 +361,7 @@ UnitPriceHTCurrency=Unit price (excl.) (currency) UnitPriceTTC=Unit price PriceU=U.P. PriceUHT=U.P. (net) -PriceUHTCurrency=U.P (currency) +PriceUHTCurrency=U.P (net) (currency) PriceUTTC=U.P. (inc. tax) Amount=Amount AmountInvoice=Invoice amount @@ -389,6 +389,8 @@ AmountTotal=Total amount AmountAverage=Average amount PriceQtyMinHT=Price quantity min. (excl. tax) PriceQtyMinHTCurrency=Price quantity min. (excl. tax) (currency) +PercentOfOriginalObject=Percent of original object +AmountOrPercent=Amount or percent Percentage=Percentage Total=Total SubTotal=Subtotal @@ -724,7 +726,7 @@ MenuMembers=Members MenuAgendaGoogle=Google agenda MenuTaxesAndSpecialExpenses=Taxes | Special expenses ThisLimitIsDefinedInSetup=Dolibarr limit (Menu home-setup-security): %s Kb, PHP limit: %s Kb -NoFileFound=No documents saved in this directory +NoFileFound=No documents uploaded CurrentUserLanguage=Current language CurrentTheme=Current theme CurrentMenuManager=Current menu manager @@ -899,8 +901,10 @@ ViewAccountList=View ledger ViewSubAccountList=View subaccount ledger RemoveString=Remove string '%s' SomeTranslationAreUncomplete=Some of the languages offered may be only partially translated or may contain errors. Please help to correct your language by registering at <a href="https://transifex.com/projects/p/dolibarr/" target="_blank">https://transifex.com/projects/p/dolibarr/</a> to add your improvements. -DirectDownloadLink=Direct download link (public/external) -DirectDownloadInternalLink=Direct download link (need to be logged and need permissions) +DirectDownloadLink=Public download link +PublicDownloadLinkDesc=Only the link is required to download the file +DirectDownloadInternalLink=Private download link +PrivateDownloadLinkDesc=You need to be logged and you need permissions to view or download the file Download=Download DownloadDocument=Download document ActualizeCurrency=Update currency rate @@ -1013,6 +1017,7 @@ SearchIntoContacts=Contacts SearchIntoMembers=Members SearchIntoUsers=Users SearchIntoProductsOrServices=Products or services +SearchIntoBatch=Lots / Serials SearchIntoProjects=Projects SearchIntoMO=Manufacturing Orders SearchIntoTasks=Tasks @@ -1049,7 +1054,7 @@ KeyboardShortcut=Keyboard shortcut AssignedTo=Assigned to Deletedraft=Delete draft ConfirmMassDraftDeletion=Draft mass delete confirmation -FileSharedViaALink=File shared via a link +FileSharedViaALink=File shared with a public link SelectAThirdPartyFirst=Select a third party first... YouAreCurrentlyInSandboxMode=You are currently in the %s "sandbox" mode Inventory=Inventory @@ -1121,3 +1126,4 @@ ConfirmAffectTag=Bulk Tag Affect ConfirmAffectTagQuestion=Are you sure you want to affect tags to the %s selected record(s)? CategTypeNotFound=No tag type found for type of records CopiedToClipboard=Copied to clipboard +InformationOnLinkToContract=This amount is only the total of all the lines of the contract. No notion of time is taken into consideration. diff --git a/htdocs/langs/en_US/mrp.lang b/htdocs/langs/en_US/mrp.lang index 5ca0dbc6981..fceeb1a15f1 100644 --- a/htdocs/langs/en_US/mrp.lang +++ b/htdocs/langs/en_US/mrp.lang @@ -89,7 +89,7 @@ ConfirmEnableWorkstation=Are you sure you want to enable workstation <b>%s</b> ? EnableAWorkstation=Enable a workstation ConfirmDisableWorkstation=Are you sure you want to disable workstation <b>%s</b> ? DisableAWorkstation=Disable a workstation -DeleteWorkstation=Supprimer +DeleteWorkstation=Delete NbOperatorsRequired=Number of operators required THMOperatorEstimated=Estimated operator THM THMMachineEstimated=Estimated machine THM diff --git a/htdocs/langs/en_US/productbatch.lang b/htdocs/langs/en_US/productbatch.lang index 54270c4a23b..36adfd571fb 100644 --- a/htdocs/langs/en_US/productbatch.lang +++ b/htdocs/langs/en_US/productbatch.lang @@ -1,8 +1,10 @@ # ProductBATCH language file - en_US - ProductBATCH ManageLotSerial=Use lot/serial number -ProductStatusOnBatch=Yes (lot/serial required) +ProductStatusOnBatch=Yes (lot required) +ProductStatusOnSerial=Yes (unique serial number required) ProductStatusNotOnBatch=No (lot/serial not used) -ProductStatusOnBatchShort=Yes +ProductStatusOnBatchShort=Lot +ProductStatusOnSerialShort=Serial ProductStatusNotOnBatchShort=No Batch=Lot/Serial atleast1batchfield=Eat-by date or Sell-by date or Lot/Serial number @@ -22,3 +24,5 @@ ProductLotSetup=Setup of module lot/serial ShowCurrentStockOfLot=Show current stock for couple product/lot ShowLogOfMovementIfLot=Show log of movements for couple product/lot StockDetailPerBatch=Stock detail per lot +SerialNumberAlreadyInUse=Serial number %s is already used for product %s +TooManyQtyForSerialNumber=You can only have one product %s for serial number %S diff --git a/htdocs/langs/en_US/products.lang b/htdocs/langs/en_US/products.lang index 9ecc11ed93d..9ec22ad00cc 100644 --- a/htdocs/langs/en_US/products.lang +++ b/htdocs/langs/en_US/products.lang @@ -141,6 +141,7 @@ VATRateForSupplierProduct=VAT Rate (for this vendor/product) DiscountQtyMin=Discount for this qty. NoPriceDefinedForThisSupplier=No price/qty defined for this vendor/product NoSupplierPriceDefinedForThisProduct=No vendor price/qty defined for this product +PredefinedItem=Predefined item PredefinedProductsToSell=Predefined Product PredefinedServicesToSell=Predefined Service PredefinedProductsAndServicesToSell=Predefined products/services to sell diff --git a/htdocs/langs/en_US/projects.lang b/htdocs/langs/en_US/projects.lang index 279bf99d162..33a0fafb5dc 100644 --- a/htdocs/langs/en_US/projects.lang +++ b/htdocs/langs/en_US/projects.lang @@ -269,3 +269,6 @@ OneLinePerPeriod=One line per period RefTaskParent=Ref. Parent Task ProfitIsCalculatedWith=Profit is calculated using AddPersonToTask=Add also to tasks +UsageOrganizeEvent=Usage: Event Organization +PROJECT_CLASSIFY_CLOSED_WHEN_ALL_TASKS_DONE=Classify project as closed when all its tasks are completed (100%% progress) +PROJECT_CLASSIFY_CLOSED_WHEN_ALL_TASKS_DONE_help=Note: existing projects with all tasks at 100 %% progress won't be affected: you will have to close them manually. This option only affects open projects. diff --git a/htdocs/langs/en_US/salaries.lang b/htdocs/langs/en_US/salaries.lang index 7c3c08a65bd..6b4fdc94163 100644 --- a/htdocs/langs/en_US/salaries.lang +++ b/htdocs/langs/en_US/salaries.lang @@ -2,12 +2,15 @@ SALARIES_ACCOUNTING_ACCOUNT_PAYMENT=Accounting account used for user third parties SALARIES_ACCOUNTING_ACCOUNT_PAYMENT_Desc=The dedicated accounting account defined on user card will be used for Subledger accounting only. This one will be used for General Ledger and as default value of Subledger accounting if dedicated user accounting account on user is not defined. SALARIES_ACCOUNTING_ACCOUNT_CHARGE=Accounting account by default for wage payments +CREATE_NEW_SALARY_WITHOUT_AUTO_PAYMENT=By default, leave empty the option "Automatically create a total payment" when creating a Salary Salary=Salary Salaries=Salaries -NewSalaryPayment=New salary payment +NewSalary=New salary +NewSalaryPayment=New salary card AddSalaryPayment=Add salary payment SalaryPayment=Salary payment SalariesPayments=Salaries payments +SalariesPaymentsOf=Salaries payments of %s ShowSalaryPayment=Show salary payment THM=Average hourly rate TJM=Average daily rate diff --git a/htdocs/langs/en_US/stocks.lang b/htdocs/langs/en_US/stocks.lang index ad4946ee9f9..aabbe1791b3 100644 --- a/htdocs/langs/en_US/stocks.lang +++ b/htdocs/langs/en_US/stocks.lang @@ -99,6 +99,7 @@ VirtualStock=Virtual stock VirtualStockAtDate=Virtual stock at date VirtualStockAtDateDesc=Virtual stock once all pending orders that are planned to be done before the date will be finished VirtualStockDesc=Virtual stock is the calculated stock available once all open/pending actions (that affect stocks) are closed (purchase orders received, sales orders shipped, manufacturing orders produced, etc) +AtDate=At date IdWarehouse=Id warehouse DescWareHouse=Description warehouse LieuWareHouse=Localisation warehouse diff --git a/htdocs/langs/en_US/supplier_proposal.lang b/htdocs/langs/en_US/supplier_proposal.lang index ca75eddb7df..a68319fb2df 100644 --- a/htdocs/langs/en_US/supplier_proposal.lang +++ b/htdocs/langs/en_US/supplier_proposal.lang @@ -53,3 +53,6 @@ SupplierProposalsToClose=Vendor proposals to close SupplierProposalsToProcess=Vendor proposals to process LastSupplierProposals=Latest %s price requests AllPriceRequests=All requests +TypeContact_supplier_proposal_external_SHIPPING=Vendor contact for delivery +TypeContact_supplier_proposal_external_BILLING=Vendor contact for billing +TypeContact_supplier_proposal_external_SERVICE=Representative following-up proposal diff --git a/htdocs/langs/en_US/ticket.lang b/htdocs/langs/en_US/ticket.lang index 3ca908e86d8..93f55289351 100644 --- a/htdocs/langs/en_US/ticket.lang +++ b/htdocs/langs/en_US/ticket.lang @@ -302,3 +302,13 @@ BoxLastModifiedTicket=Latest modified tickets BoxLastModifiedTicketDescription=Latest %s modified tickets BoxLastModifiedTicketContent= BoxLastModifiedTicketNoRecordedTickets=No recent modified tickets +BoxTicketType=Number of open tickets by type +BoxTicketSeverity=Number of open tickets by severity +BoxNoTicketSeverity=No tickets opened +BoxTicketLastXDays=Number of new tickets by days the last %s days +BoxTicketLastXDayswidget = Number of new tickets by days the last X days +BoxNoTicketLastXDays=No new tickets the last %s days +BoxNumberOfTicketByDay=Number of new tickets by day +BoxNewTicketVSClose=Number of today's new tickets versus today's closed tickets +TicketCreatedToday=Ticket created today +TicketClosedToday=Ticket closed today \ No newline at end of file diff --git a/htdocs/langs/en_US/trips.lang b/htdocs/langs/en_US/trips.lang index de31172e9d7..1f53a5737ff 100644 --- a/htdocs/langs/en_US/trips.lang +++ b/htdocs/langs/en_US/trips.lang @@ -33,7 +33,7 @@ ExpenseReportCanceledMessage=The expense report %s was canceled.<br> - User: %s< ExpenseReportPaid=An expense report was paid ExpenseReportPaidMessage=The expense report %s was paid.<br> - User: %s<br> - Paid by: %s<br>Click here to show the expense report: %s TripId=Id expense report -AnyOtherInThisListCanValidate=Person to inform for validation. +AnyOtherInThisListCanValidate=Person to be informed for validating the request. TripSociete=Information company TripNDF=Informations expense report PDFStandardExpenseReports=Standard template to generate a PDF document for expense report diff --git a/htdocs/langs/en_US/users.lang b/htdocs/langs/en_US/users.lang index 996ba20ab7d..d4326fc08c9 100644 --- a/htdocs/langs/en_US/users.lang +++ b/htdocs/langs/en_US/users.lang @@ -72,7 +72,7 @@ ExportDataset_user_1=Users and their properties DomainUser=Domain user %s Reactivate=Reactivate CreateInternalUserDesc=This form allows you to create an internal user in your company/organization. To create an external user (customer, vendor etc. ..), use the button 'Create Dolibarr User' from that third-party's contact card. -InternalExternalDesc=An <b>internal</b> user is a user that is part of your company/organization.<br>An <b>external</b> user is a customer, vendor or other (Creating an external user for a third-party can be done from the contact record of the third-party).<br><br>In both cases, permissions defines rights on Dolibarr, also external user can have a different menu manager than internal user (See Home - Setup - Display) +InternalExternalDesc=An <b>internal</b> user is a user that is part of your company/organization.<br>An <b>external</b> user is a customer, vendor or other that must view only data related to himself (Creating an external user for a third-party can be done from the contact record of the third-party).<br><br>In both cases, permissions defines rights on Dolibarr, also external user can have a different menu manager than internal user (See Home - Setup - Display) PermissionInheritedFromAGroup=Permission granted because inherited from one of a user's group. Inherited=Inherited UserWillBe=Created user will be diff --git a/htdocs/langs/en_US/website.lang b/htdocs/langs/en_US/website.lang index 7793fa5dead..c23f4425dca 100644 --- a/htdocs/langs/en_US/website.lang +++ b/htdocs/langs/en_US/website.lang @@ -46,12 +46,12 @@ SetHereVirtualHost=<u>Use with Apache/NGinx/...</u><br>Create on your web server ExampleToUseInApacheVirtualHostConfig=Example to use in Apache virtual host setup: YouCanAlsoTestWithPHPS=<u>Use with PHP embedded server</u><br>On develop environment, you may prefer to test the site with the PHP embedded web server (PHP 5.5 required) by running<br><strong>php -S 0.0.0.0:8080 -t %s</strong> YouCanAlsoDeployToAnotherWHP=<u>Run your web site with another Dolibarr Hosting provider</u><br>If you don't have a web server like Apache or NGinx available on internet, you can export and import your web site onto another Dolibarr instance provided by another Dolibarr hosting provider that provide full integration with the Website module. You can find a list of some Dolibarr hosting providers on <a href="https://saas.dolibarr.org" target="_blank">https://saas.dolibarr.org</a> -CheckVirtualHostPerms=Check also that virtual host has permission <strong>%s</strong> on files into<br><strong>%s</strong> +CheckVirtualHostPerms=Check also that the virtual host user (for example www-data) has <strong>%s</strong> permissions on files into<br><strong>%s</strong> ReadPerm=Read WritePerm=Write TestDeployOnWeb=Test/deploy on web PreviewSiteServedByWebServer=<u>Preview %s in a new tab.</u><br><br>The %s will be served by an external web server (like Apache, Nginx, IIS). You must install and setup this server before to point to directory:<br><strong>%s</strong><br>URL served by external server:<br><strong>%s</strong> -PreviewSiteServedByDolibarr=<u>Preview %s in a new tab.</u><br><br>The %s will be served by Dolibarr server so it does not need any extra web server (like Apache, Nginx, IIS) to be installed.<br>The inconvenient is that URL of pages are not user friendly and start with path of your Dolibarr.<br>URL served by Dolibarr:<br><strong>%s</strong><br><br>To use your own external web server to serve this web site, create a virtual host on your web server that point on directory<br><strong>%s</strong><br>then enter the name of this virtual server and click on the other preview button. +PreviewSiteServedByDolibarr=<u>Preview %s in a new tab.</u><br><br>The %s will be served by Dolibarr server so it does not need any extra web server (like Apache, Nginx, IIS) to be installed.<br>The inconvenient is that the URLs of pages are not user friendly and start with the path of your Dolibarr.<br>URL served by Dolibarr:<br><strong>%s</strong><br><br>To use your own external web server to serve this web site, create a virtual host on your web server that points on directory<br><strong>%s</strong><br>then enter the name of this virtual server in the properties of this website and click on the link "Test/Deploy on the web". VirtualHostUrlNotDefined=URL of the virtual host served by external web server not defined NoPageYet=No pages yet YouCanCreatePageOrImportTemplate=You can create a new page or import a full website template @@ -136,4 +136,8 @@ RSSFeedDesc=You can get a RSS feed of latest articles with type 'blogpost' using PagesRegenerated=%s page(s)/container(s) regenerated RegenerateWebsiteContent=Regenerate web site cache files AllowedInFrames=Allowed in Frames -DefineListOfAltLanguagesInWebsiteProperties=Define list of all available languages into web site properties. \ No newline at end of file +DefineListOfAltLanguagesInWebsiteProperties=Define list of all available languages into web site properties. +GenerateSitemaps=Generate website sitemap file +ConfirmGenerateSitemaps=If you confirm, you will erase the existing sitemap file... +ConfirmSitemapsCreation=Confirm sitemap generation +SitemapGenerated=Sitemap Generated diff --git a/htdocs/langs/fr_FR/accountancy.lang b/htdocs/langs/fr_FR/accountancy.lang index 4441dd4e1f9..3b2fc290352 100644 --- a/htdocs/langs/fr_FR/accountancy.lang +++ b/htdocs/langs/fr_FR/accountancy.lang @@ -131,7 +131,7 @@ InvoiceLinesDone=Lignes de factures liées ExpenseReportLines=Lignes de notes de frais à lier ExpenseReportLinesDone=Lignes de notes de frais liées IntoAccount=Lier ligne avec le compte comptable -TotalForAccount=Total pour le compte comptable +TotalForAccount=Total compte comptable Ventilate=Lier diff --git a/htdocs/langs/fr_FR/agenda.lang b/htdocs/langs/fr_FR/agenda.lang index 072fd057dbf..7ecd5800861 100644 --- a/htdocs/langs/fr_FR/agenda.lang +++ b/htdocs/langs/fr_FR/agenda.lang @@ -130,7 +130,7 @@ AgendaUrlOptions4=<b>logint=%s</b>pour limiter l'export aux actions assignées AgendaUrlOptionsProject=<b>project=__PROJECT_ID__</b> pour restreindre aux événements associés au projet <b>__PROJECT_ID__</b>. AgendaUrlOptionsNotAutoEvent=<b>notactiontype=systemauto</b> pour exclure les événements automatiques. AgendaUrlOptionsIncludeHolidays=<b>includeholidays=1</b> pour inclure les événements de type congé. -AgendaShowBirthdayEvents=Afficher les anniversaires de contacts +AgendaShowBirthdayEvents=Anniversaires de contacts AgendaHideBirthdayEvents=Masquer les anniversaires de contacts Busy=Occupé ExportDataset_event1=Liste des événements de l'agenda diff --git a/htdocs/langs/fr_FR/commercial.lang b/htdocs/langs/fr_FR/commercial.lang index 9b5721326d1..badec05e8c2 100644 --- a/htdocs/langs/fr_FR/commercial.lang +++ b/htdocs/langs/fr_FR/commercial.lang @@ -64,10 +64,10 @@ ActionAC_SHIP=Envoi bon d'expédition par email ActionAC_SUP_ORD=Envoi commande fournisseur par email ActionAC_SUP_INV=Envoi facture fournisseur par email ActionAC_OTH=Autre -ActionAC_OTH_AUTO=Évènements insérés automatiquement +ActionAC_OTH_AUTO=Autre auto ActionAC_MANUAL=Événements insérés manuellement ActionAC_AUTO=Événements insérés automatiquement -ActionAC_OTH_AUTOShort=Auto +ActionAC_OTH_AUTOShort=Autre Stats=Statistiques de vente StatusProsp=Status prospection DraftPropals=Propositions brouillons diff --git a/htdocs/langs/fr_FR/main.lang b/htdocs/langs/fr_FR/main.lang index a862a1ecb9d..86ba2247682 100644 --- a/htdocs/langs/fr_FR/main.lang +++ b/htdocs/langs/fr_FR/main.lang @@ -361,7 +361,7 @@ UnitPriceHTCurrency=Prix ​​unitaire (HT) (devise) UnitPriceTTC=Prix unitaire TTC PriceU=P.U. PriceUHT=P.U. HT -PriceUHTCurrency=P.U. (devise) +PriceUHTCurrency=P.U. HT (devise) PriceUTTC=P.U TTC Amount=Montant AmountInvoice=Montant facture @@ -548,7 +548,7 @@ None=Aucun NoneF=Aucune NoneOrSeveral=Aucun ou plusieurs Late=Retard -LateDesc=Le délai qui définit si un enregistrement est en retard ou non dépend de votre configuration. Demandez à votre administrateur pour changer ce délai depuis Accueil - Configuration - Alertes +LateDesc=Le délai qui définit si un enregistrement est en retard ou non dépend de votre configuration. Demandez à votre administrateur pour changer ce délai depuis Accueil - Configuration - Alertes NoItemLate=Aucun élément en retard Photo=Photo Photos=Photos @@ -1013,6 +1013,7 @@ SearchIntoContacts=Contacts SearchIntoMembers=Adhérents SearchIntoUsers=Utilisateurs SearchIntoProductsOrServices=Produits ou services +SearchIntoBatch=Lots / N° de série SearchIntoProjects=Projets SearchIntoMO=Ordres de fabrication SearchIntoTasks=Tâches diff --git a/htdocs/langs/fr_FR/productbatch.lang b/htdocs/langs/fr_FR/productbatch.lang index 162af66827c..94ceb434bfd 100644 --- a/htdocs/langs/fr_FR/productbatch.lang +++ b/htdocs/langs/fr_FR/productbatch.lang @@ -1,8 +1,10 @@ # ProductBATCH language file - en_US - ProductBATCH ManageLotSerial=Utiliser les numéros de lots/série -ProductStatusOnBatch=Oui (Lot/Série requis) +ProductStatusOnBatch=Lot (requis) +ProductStatusOnSerial=Numéro de série (doit être unique pour chaque équipement) ProductStatusNotOnBatch=Non (Lot/Série non utilisé) -ProductStatusOnBatchShort=Oui +ProductStatusOnBatchShort=Lot +ProductStatusOnSerialShort=N°série ProductStatusNotOnBatchShort=Non Batch=Lot/Série atleast1batchfield=Date limite utilisation optimale, de consommation ou numéro de lot/série @@ -22,3 +24,5 @@ ProductLotSetup=Configuration du module lot/série ShowCurrentStockOfLot=Afficher le stock actuel pour le couple produit / lot ShowLogOfMovementIfLot=Afficher l'historique des mouvements de couple produit / lot StockDetailPerBatch=Stock détaillé par lot +SerialNumberAlreadyInUse=Le numéro de série %s est déjà utilisé pour le produit %s +TooManyQtyForSerialNumber=Vous ne pouvez avoir qu'un produit %s avec le numéro de série %s diff --git a/htdocs/langs/fr_FR/projects.lang b/htdocs/langs/fr_FR/projects.lang index 1affdad0889..a963bffe13d 100644 --- a/htdocs/langs/fr_FR/projects.lang +++ b/htdocs/langs/fr_FR/projects.lang @@ -268,3 +268,5 @@ OneLinePerTask=Une ligne par tâche OneLinePerPeriod=Une ligne par période RefTaskParent=Réf. Tâche parent ProfitIsCalculatedWith=Le bénéfice est calculé sur la base de +PROJECT_CLASSIFY_CLOSED_WHEN_ALL_TASKS_DONE=Classer le projet à clôturé lorsque toutes les tâches de ce projet sont à 100 %% de progression +PROJECT_CLASSIFY_CLOSED_WHEN_ALL_TASKS_DONE_help=Non rétroactif : l’activation de cette option ne clôturera pas les projets dont les tâches sont déjà à 100 %%. Cette option ne classe que les projets ouverts. diff --git a/htdocs/langs/fr_FR/salaries.lang b/htdocs/langs/fr_FR/salaries.lang index f4138177a16..73ab172a424 100644 --- a/htdocs/langs/fr_FR/salaries.lang +++ b/htdocs/langs/fr_FR/salaries.lang @@ -2,6 +2,7 @@ SALARIES_ACCOUNTING_ACCOUNT_PAYMENT=Compte comptable utilisé pour les utilisateurs SALARIES_ACCOUNTING_ACCOUNT_PAYMENT_Desc=Le compte comptable défini sur la fiche utilisateur sera utilisé uniquement pour la comptabilité auxiliaire. Celui-ci sera utilisé pour le grand livre et comme valeur par défaut de la comptabilité auxiliaire si le compte dédié de l'utilisateur n'est pas défini. SALARIES_ACCOUNTING_ACCOUNT_CHARGE=Compte comptable par défaut pour les paiements de salaires +CREATE_NEW_SALARY_WITHOUT_AUTO_PAYMENT=Par défaut, laisser vide l’option « Créer automatiquement un règlement total » lors de la création d'un Salaire Salary=Salaire Salaries=Salaires NewSalaryPayment=Nouveau règlement de salaire diff --git a/htdocs/loan/calcmens.php b/htdocs/loan/calcmens.php index d5f9704addc..5c6260dec84 100644 --- a/htdocs/loan/calcmens.php +++ b/htdocs/loan/calcmens.php @@ -24,9 +24,15 @@ * \brief File to calculate loan monthly payments */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} require '../main.inc.php'; require DOL_DOCUMENT_ROOT.'/core/lib/loan.lib.php'; diff --git a/htdocs/loan/card.php b/htdocs/loan/card.php index 1143fbcd474..9e9e1a0a992 100644 --- a/htdocs/loan/card.php +++ b/htdocs/loan/card.php @@ -28,8 +28,12 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/loan.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +} +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +} require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; @@ -45,7 +49,9 @@ $projectid = GETPOST('projectid', 'int'); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'loan', $id, '', ''); $object = new Loan($db); @@ -60,16 +66,15 @@ $error = 0; */ $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 (empty($reshook)) -{ +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} +if (empty($reshook)) { // Classify paid - if ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->loan->write) - { + if ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->loan->write) { $object->fetch($id); $result = $object->setPaid($user); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans('LoanPaid'), null, 'mesgs'); } else { setEventMessages($loan->error, null, 'errors'); @@ -77,12 +82,10 @@ if (empty($reshook)) } // Delete loan - if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->loan->write) - { + if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->loan->write) { $object->fetch($id); $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans('LoanDeleted'), null, 'mesgs'); header("Location: list.php"); exit; @@ -92,44 +95,37 @@ if (empty($reshook)) } // Add loan - if ($action == 'add' && $user->rights->loan->write) - { - if (!$cancel) - { + if ($action == 'add' && $user->rights->loan->write) { + if (!$cancel) { $datestart = dol_mktime(12, 0, 0, GETPOST('startmonth', 'int'), GETPOST('startday', 'int'), GETPOST('startyear', 'int')); $dateend = dol_mktime(12, 0, 0, GETPOST('endmonth', 'int'), GETPOST('endday', 'int'), GETPOST('endyear', 'int')); $capital = price2num(GETPOST('capital')); $rate = GETPOST('rate'); - if (!$capital) - { + if (!$capital) { $error++; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("LoanCapital")), null, 'errors'); } - if (!$datestart) - { + if (!$datestart) { $error++; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("DateStart")), null, 'errors'); } - if (!$dateend) - { + if (!$dateend) { $error++; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("DateEnd")), null, 'errors'); } - if ($rate == '') - { + if ($rate == '') { $error++; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Rate")), null, 'errors'); } - if (!$error) - { + if (!$error) { $object->label = GETPOST('label'); - $object->fk_bank = GETPOST('accountid'); - $object->capital = $capital; + $object->fk_bank = GETPOST('accountid'); + $object->capital = $capital; $object->datestart = $datestart; - $object->dateend = $dateend; - $object->nbterm = GETPOST('nbterm'); + $object->dateend = $dateend; + $object->nbterm = GETPOST('nbterm'); $object->rate = $rate; $object->note_private = GETPOST('note_private', 'restricthtml'); $object->note_public = GETPOST('note_public', 'restricthtml'); @@ -140,13 +136,24 @@ if (empty($reshook)) $accountancy_account_insurance = GETPOST('accountancy_account_insurance'); $accountancy_account_interest = GETPOST('accountancy_account_interest'); - if ($accountancy_account_capital <= 0) { $object->account_capital = ''; } else { $object->account_capital = $accountancy_account_capital; } - if ($accountancy_account_insurance <= 0) { $object->account_insurance = ''; } else { $object->account_insurance = $accountancy_account_insurance; } - if ($accountancy_account_interest <= 0) { $object->account_interest = ''; } else { $object->account_interest = $accountancy_account_interest; } + if ($accountancy_account_capital <= 0) { + $object->account_capital = ''; + } else { + $object->account_capital = $accountancy_account_capital; + } + if ($accountancy_account_insurance <= 0) { + $object->account_insurance = ''; + } else { + $object->account_insurance = $accountancy_account_insurance; + } + if ($accountancy_account_interest <= 0) { + $object->account_interest = ''; + } else { + $object->account_interest = $accountancy_account_interest; + } $id = $object->create($user); - if ($id <= 0) - { + if ($id <= 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); $action = 'create'; @@ -156,21 +163,16 @@ if (empty($reshook)) header("Location: list.php"); exit(); } - } - - // Update record - elseif ($action == 'update' && $user->rights->loan->write) - { - if (!$cancel) - { + } elseif ($action == 'update' && $user->rights->loan->write) { + // Update record + if (!$cancel) { $result = $object->fetch($id); $datestart = dol_mktime(12, 0, 0, GETPOST('startmonth', 'int'), GETPOST('startday', 'int'), GETPOST('startyear', 'int')); $dateend = dol_mktime(12, 0, 0, GETPOST('endmonth', 'int'), GETPOST('endday', 'int'), GETPOST('endyear', 'int')); $capital = price2num(GETPOST('capital')); - if (!$capital) - { + if (!$capital) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("LoanCapital")), null, 'errors'); $action = 'edit'; } else { @@ -185,15 +187,26 @@ if (empty($reshook)) $accountancy_account_insurance = GETPOST('accountancy_account_insurance'); $accountancy_account_interest = GETPOST('accountancy_account_interest'); - if ($accountancy_account_capital <= 0) { $object->account_capital = ''; } else { $object->account_capital = $accountancy_account_capital; } - if ($accountancy_account_insurance <= 0) { $object->account_insurance = ''; } else { $object->account_insurance = $accountancy_account_insurance; } - if ($accountancy_account_interest <= 0) { $object->account_interest = ''; } else { $object->account_interest = $accountancy_account_interest; } + if ($accountancy_account_capital <= 0) { + $object->account_capital = ''; + } else { + $object->account_capital = $accountancy_account_capital; + } + if ($accountancy_account_insurance <= 0) { + $object->account_insurance = ''; + } else { + $object->account_insurance = $accountancy_account_insurance; + } + if ($accountancy_account_interest <= 0) { + $object->account_interest = ''; + } else { + $object->account_interest = $accountancy_account_interest; + } } $result = $object->update($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { @@ -207,20 +220,20 @@ if (empty($reshook)) } // Link to a project - if ($action == 'classin' && $user->rights->loan->write) - { + if ($action == 'classin' && $user->rights->loan->write) { $object->fetch($id); $result = $object->setProject($projectid); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } - if ($action == 'setlabel' && $user->rights->loan->write) - { + if ($action == 'setlabel' && $user->rights->loan->write) { $object->fetch($id); $result = $object->setValueFrom('label', GETPOST('label'), '', '', 'text', '', $user, 'LOAN_MODIFY'); - if ($result < 0) - setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } } @@ -231,7 +244,9 @@ if (empty($reshook)) $form = new Form($db); $formproject = new FormProjets($db); -if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); +if (!empty($conf->accounting->enabled)) { + $formaccounting = new FormAccounting($db); +} $title = $langs->trans("Loan").' - '.$langs->trans("Card"); $help_url = 'EN:Module_Loan|FR:Module_Emprunt'; @@ -239,8 +254,7 @@ llxHeader("", $title, $help_url); // Create mode -if ($action == 'create') -{ +if ($action == 'create') { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -260,8 +274,7 @@ if ($action == 'create') print '<tr><td class="fieldrequired titlefieldcreate">'.$langs->trans("Label").'</td><td><input name="label" class="minwidth300" maxlength="255" value="'.dol_escape_htmltag(GETPOST('label')).'" autofocus="autofocus"></td></tr>'; // Bank account - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print '<tr><td class="fieldrequired">'.$langs->trans("Account").'</td><td>'; $form->select_comptes(GETPOST("accountid"), "accountid", 0, "courant=1", 1); // Show list of bank account with courant print '</td></tr>'; @@ -296,8 +309,7 @@ if ($action == 'create') print '<tr><td>'.$langs->trans("Insurance").'</td><td><input name="insurance_amount" size="10" value="'.dol_escape_htmltag(GETPOST("insurance_amount")).'" placeholder="'.$langs->trans('Amount').'"></td></tr>'; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); // Projet associe @@ -329,8 +341,7 @@ if ($action == 'create') print '</td></tr>'; // Accountancy - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { // Accountancy_account_capital print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("LoanAccountancyCapitalCode").'</td>'; print '<td>'; @@ -379,32 +390,27 @@ if ($action == 'create') } // View -if ($id > 0) -{ +if ($id > 0) { $object = new Loan($db); $result = $object->fetch($id); - if ($result > 0) - { + if ($result > 0) { $head = loan_prepare_head($object); $totalpaid = $object->getSumPayment(); // Confirm for loan - if ($action == 'paid') - { + if ($action == 'paid') { $text = $langs->trans('ConfirmPayLoan'); print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans('PayLoan'), $text, "confirm_paid", '', '', 2); } - if ($action == 'delete') - { + if ($action == 'delete') { $text = $langs->trans('ConfirmDeleteLoan'); print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('DeleteLoan'), $text, 'confirm_delete', '', '', 2); } - if ($action == 'edit') - { + if ($action == 'edit') { print '<form name="update" action="'.$_SERVER["PHP_SELF"].'" method="POST">'."\n"; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; @@ -422,14 +428,13 @@ if ($id > 0) $morehtmlref .= $form->editfieldkey("Label", 'label', $object->label, $object, $user->rights->loan->write, 'string', '', 0, 1); $morehtmlref .= $form->editfieldval("Label", 'label', $object->label, $object, $user->rights->loan->write, 'string', '', null, null, '', 1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->loadLangs(array("projects")); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->loan->write) - { - if ($action != 'classify') + if ($user->rights->loan->write) { + if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; @@ -466,8 +471,7 @@ if ($id > 0) print '<table class="border centpercent tableforfield">'; // Capital - if ($action == 'edit') - { + if ($action == 'edit') { print '<tr><td class="fieldrequired titlefield">'.$langs->trans("LoanCapital").'</td><td>'; print '<input name="capital" size="10" value="'.$object->capital.'"></td></tr>'; print '</td></tr>'; @@ -476,8 +480,7 @@ if ($id > 0) } // Insurance - if ($action == 'edit') - { + if ($action == 'edit') { print '<tr><td class="titlefield">'.$langs->trans("Insurance").'</td><td>'; print '<input name="insurance_amount" size="10" value="'.$object->insurance_amount.'"></td></tr>'; print '</td></tr>'; @@ -488,8 +491,7 @@ if ($id > 0) // Date start print '<tr><td>'.$langs->trans("DateStart")."</td>"; print "<td>"; - if ($action == 'edit') - { + if ($action == 'edit') { print $form->selectDate($object->datestart, 'start', 0, 0, 0, 'update', 1, 0); } else { print dol_print_date($object->datestart, "day"); @@ -499,8 +501,7 @@ if ($id > 0) // Date end print '<tr><td>'.$langs->trans("DateEnd")."</td>"; print "<td>"; - if ($action == 'edit') - { + if ($action == 'edit') { print $form->selectDate($object->dateend, 'end', 0, 0, 0, 'update', 1, 0); } else { print dol_print_date($object->dateend, "day"); @@ -510,8 +511,7 @@ if ($id > 0) // Nbterms print '<tr><td>'.$langs->trans("Nbterms").'</td>'; print '<td>'; - if ($action == 'edit') - { + if ($action == 'edit') { print '<input name="nbterm" size="4" value="'.$object->nbterm.'">'; } else { print $object->nbterm; @@ -521,8 +521,7 @@ if ($id > 0) // Rate print '<tr><td>'.$langs->trans("Rate").'</td>'; print '<td>'; - if ($action == 'edit') - { + if ($action == 'edit') { print '<input name="rate" size="4" value="'.$object->rate.'">%'; } else { print price($object->rate).'%'; @@ -531,14 +530,12 @@ if ($id > 0) // Accountancy account capital print '<tr>'; - if ($action == 'edit') - { + if ($action == 'edit') { print '<td class="nowrap fieldrequired">'; print $langs->trans("LoanAccountancyCapitalCode"); print '</td><td>'; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { print $formaccounting->select_account($object->account_capital, 'accountancy_account_capital', 1, '', 1, 1); } else { print '<input name="accountancy_account_capital" size="16" value="'.$object->account_capital.'">'; @@ -549,8 +546,7 @@ if ($id > 0) print $langs->trans("LoanAccountancyCapitalCode"); print '</td><td>'; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->account_capital, 1); @@ -565,14 +561,12 @@ if ($id > 0) // Accountancy account insurance print '<tr>'; - if ($action == 'edit') - { + if ($action == 'edit') { print '<td class="nowrap fieldrequired">'; print $langs->trans("LoanAccountancyInsuranceCode"); print '</td><td>'; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { print $formaccounting->select_account($object->account_insurance, 'accountancy_account_insurance', 1, '', 1, 1); } else { print '<input name="accountancy_account_insurance" size="16" value="'.$object->account_insurance.'">'; @@ -583,8 +577,7 @@ if ($id > 0) print $langs->trans("LoanAccountancyInsuranceCode"); print '</td><td>'; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->account_insurance, 1); @@ -599,14 +592,12 @@ if ($id > 0) // Accountancy account interest print '<tr>'; - if ($action == 'edit') - { + if ($action == 'edit') { print '<td class="nowrap fieldrequired">'; print $langs->trans("LoanAccountancyInterestCode"); print '</td><td>'; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { print $formaccounting->select_account($object->account_interest, 'accountancy_account_interest', 1, '', 1, 1); } else { print '<input name="accountancy_account_interest" size="16" value="'.$object->account_interest.'">'; @@ -617,8 +608,7 @@ if ($id > 0) print $langs->trans("LoanAccountancyInterestCode"); print '</td><td>'; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->account_interest, 1); @@ -653,8 +643,7 @@ if ($id > 0) //print $sql; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; $total_insurance = 0; @@ -672,8 +661,7 @@ if ($id > 0) print '<td class="right">'.$langs->trans("LoanCapital").'</td>'; print '</tr>'; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -690,8 +678,7 @@ if ($id > 0) $totalpaid = $total_capital; - if ($object->paid == 0 || $object->paid == 2) - { + if ($object->paid == 0 || $object->paid == 2) { print '<tr><td colspan="5" class="right">'.$langs->trans("AlreadyPaid").' :</td><td class="nowrap right">'.price($totalpaid, 0, $langs, 0, -1, -1, $conf->currency).'</td></tr>'; print '<tr><td colspan="5" class="right">'.$langs->trans("AmountExpected").' :</td><td class="nowrap right">'.price($object->capital, 0, $outputlangs, 1, -1, -1, $conf->currency).'</td></tr>'; @@ -718,8 +705,7 @@ if ($id > 0) print dol_get_fiche_end(); - if ($action == 'edit') - { + if ($action == 'edit') { print '<div class="center">'; print '<input type="submit" class="button button-save" name="save" value="'.$langs->trans("Save").'">'; print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; @@ -732,34 +718,28 @@ if ($id > 0) /* * Buttons actions */ - if ($action != 'edit') - { + if ($action != 'edit') { $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { print '<div class="tabsAction">'; // Edit - if (($object->paid == 0 || $object->paid == 2) && $user->rights->loan->write) - { + if (($object->paid == 0 || $object->paid == 2) && $user->rights->loan->write) { print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/loan/card.php?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'; } // Emit payment - if (($object->paid == 0 || $object->paid == 2) && ((price2num($object->capital) > 0 && round($staytopay) < 0) || (price2num($object->capital) > 0 && round($staytopay) > 0)) && $user->rights->loan->write) - { + if (($object->paid == 0 || $object->paid == 2) && ((price2num($object->capital) > 0 && round($staytopay) < 0) || (price2num($object->capital) > 0 && round($staytopay) > 0)) && $user->rights->loan->write) { print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/loan/payment/payment.php?id='.$object->id.'&amp;action=create">'.$langs->trans("DoPayment").'</a></div>'; } // Classify 'paid' - if (($object->paid == 0 || $object->paid == 2) && round($staytopay) <= 0 && $user->rights->loan->write) - { + if (($object->paid == 0 || $object->paid == 2) && round($staytopay) <= 0 && $user->rights->loan->write) { print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/loan/card.php?id='.$object->id.'&amp;action=paid&amp;token='.newToken().'">'.$langs->trans("ClassifyPaid").'</a></div>'; } // Delete - if (($object->paid == 0 || $object->paid == 2) && $user->rights->loan->delete) - { + if (($object->paid == 0 || $object->paid == 2) && $user->rights->loan->delete) { print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.DOL_URL_ROOT.'/loan/card.php?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans("Delete").'</a></div>'; } diff --git a/htdocs/loan/class/loan.class.php b/htdocs/loan/class/loan.class.php index 9f2d8297edc..b628de1b68b 100644 --- a/htdocs/loan/class/loan.class.php +++ b/htdocs/loan/class/loan.class.php @@ -131,14 +131,12 @@ class Loan extends CommonObject $sql = "SELECT l.rowid, l.label, l.capital, l.datestart, l.dateend, l.nbterm, l.rate, l.note_private, l.note_public, l.insurance_amount,"; $sql .= " l.paid, l.accountancy_account_capital, l.accountancy_account_insurance, l.accountancy_account_interest, l.fk_projet as fk_project"; $sql .= " FROM ".MAIN_DB_PREFIX."loan as l"; - $sql .= " WHERE l.rowid = ".$id; + $sql .= " WHERE l.rowid = ".((int) $id); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -188,36 +186,52 @@ class Loan extends CommonObject // clean parameters $newcapital = price2num($this->capital, 'MT'); - if (empty($this->insurance_amount)) $this->insurance_amount = 0; + if (empty($this->insurance_amount)) { + $this->insurance_amount = 0; + } $newinsuranceamount = price2num($this->insurance_amount, 'MT'); - if (isset($this->note_private)) $this->note_private = trim($this->note_private); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->account_capital)) $this->account_capital = trim($this->account_capital); - if (isset($this->account_insurance)) $this->account_insurance = trim($this->account_insurance); - if (isset($this->account_interest)) $this->account_interest = trim($this->account_interest); - if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; - if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; - if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; - if (isset($this->fk_project)) $this->fk_project = (int) $this->fk_project; + if (isset($this->note_private)) { + $this->note_private = trim($this->note_private); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->account_capital)) { + $this->account_capital = trim($this->account_capital); + } + if (isset($this->account_insurance)) { + $this->account_insurance = trim($this->account_insurance); + } + if (isset($this->account_interest)) { + $this->account_interest = trim($this->account_interest); + } + if (isset($this->fk_bank)) { + $this->fk_bank = (int) $this->fk_bank; + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = (int) $this->fk_user_creat; + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = (int) $this->fk_user_modif; + } + if (isset($this->fk_project)) { + $this->fk_project = (int) $this->fk_project; + } // Check parameters - if (!$newcapital > 0 || empty($this->datestart) || empty($this->dateend)) - { + if (!$newcapital > 0 || empty($this->datestart) || empty($this->dateend)) { $this->error = "ErrorBadParameter"; return -2; } - if (($conf->accounting->enabled) && empty($this->account_capital)) - { + if (($conf->accounting->enabled) && empty($this->account_capital)) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("LoanAccountancyCapitalCode")); return -2; } - if (($conf->accounting->enabled) && empty($this->account_insurance)) - { + if (($conf->accounting->enabled) && empty($this->account_insurance)) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("LoanAccountancyInsuranceCode")); return -2; } - if (($conf->accounting->enabled) && empty($this->account_interest)) - { + if (($conf->accounting->enabled) && empty($this->account_interest)) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("LoanAccountancyInterestCode")); return -2; } @@ -248,8 +262,7 @@ class Loan extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."loan"); //dol_syslog("Loans::create this->id=".$this->id); @@ -281,47 +294,39 @@ class Loan extends CommonObject $lines_url = $account->get_url('', $this->id, 'loan'); // Delete bank urls - foreach ($lines_url as $line_url) - { - if (!$error) - { + foreach ($lines_url as $line_url) { + if (!$error) { $accountline = new AccountLine($this->db); $accountline->fetch($line_url['fk_bank']); $result = $accountline->delete_urls($user); - if ($result < 0) - { + if ($result < 0) { $error++; } } } // Delete payments - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_loan where fk_loan=".$this->id; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = $this->db->lasterror(); } } - if (!$error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."loan where rowid=".$this->id; + if (!$error) { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."loan where rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = $this->db->lasterror(); } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -341,8 +346,7 @@ class Loan extends CommonObject { $this->db->begin(); - if (!is_numeric($this->nbterm)) - { + if (!is_numeric($this->nbterm)) { $this->error = 'BadValueForParameterForNbTerm'; return -1; } @@ -360,12 +364,11 @@ class Loan extends CommonObject $sql .= " fk_projet=".(empty($this->fk_project) ? 'NULL' : $this->fk_project).","; $sql .= " fk_user_modif = ".$user->id.","; $sql .= " insurance_amount = '".price2num($this->db->escape($this->insurance_amount))."'"; - $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) - { + if ($resql) { $this->db->commit(); return 1; } else { @@ -512,22 +515,29 @@ class Loan extends CommonObject $langs->loadLangs(array("customers", "bills")); unset($this->labelStatus); // Force to reset the array of status label, because label can change depending on parameters - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; $this->labelStatus[self::STATUS_UNPAID] = $langs->trans('Unpaid'); $this->labelStatus[self::STATUS_PAID] = $langs->trans('Paid'); $this->labelStatus[self::STATUS_STARTED] = $langs->trans("BillStatusStarted"); - if ($status == 0 && $alreadypaid > 0) $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + if ($status == 0 && $alreadypaid > 0) { + $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + } $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans('Unpaid'); $this->labelStatusShort[self::STATUS_PAID] = $langs->trans('Enabled'); $this->labelStatusShort[self::STATUS_STARTED] = $langs->trans("BillStatusStarted"); - if ($status == 0 && $alreadypaid > 0) $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + if ($status == 0 && $alreadypaid > 0) { + $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + } } $statusType = 'status1'; - if (($status == 0 && $alreadypaid > 0) || $status == self::STATUS_STARTED) $statusType = 'status3'; - if ($status == 1) $statusType = 'status6'; + if (($status == 0 && $alreadypaid > 0) || $status == self::STATUS_STARTED) { + $statusType = 'status3'; + } + if ($status == 1) { + $statusType = 'status6'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -560,33 +570,40 @@ class Loan extends CommonObject $url = DOL_URL_ROOT.'/loan/card.php?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowMyObject"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = '<a href="'.$url.'"'; $linkstart .= $linkclose.'>'; $linkend = '</a>'; $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->ref, $maxlen) : $this->ref); + 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->ref, $maxlen) : $this->ref); + } $result .= $linkend; return $result; @@ -638,12 +655,13 @@ class Loan extends CommonObject dol_syslog(get_class($this)."::getSumPayment", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $amount = 0; $obj = $this->db->fetch_object($resql); - if ($obj) $amount = $obj->amount ? $obj->amount : 0; + if ($obj) { + $amount = $obj->amount ? $obj->amount : 0; + } $this->db->free($resql); return $amount; @@ -663,31 +681,29 @@ class Loan extends CommonObject { $sql = 'SELECT l.rowid, l.datec, l.fk_user_author, l.fk_user_modif,'; $sql .= ' l.tms'; - $sql .= ' WHERE l.rowid = '.$id; + $sql .= ' WHERE l.rowid = '.((int) $id); dol_syslog(get_class($this).'::info', LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_modif) - { + if ($obj->fk_user_modif) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modif); $this->user_modification = $muser; } $this->date_creation = $this->db->jdate($obj->datec); - if (empty($obj->fk_user_modif)) $obj->tms = ""; + if (empty($obj->fk_user_modif)) { + $obj->tms = ""; + } $this->date_modification = $this->db->jdate($obj->tms); $this->db->free($result); diff --git a/htdocs/loan/class/loanschedule.class.php b/htdocs/loan/class/loanschedule.class.php index 50339359a9d..bc819f747ca 100644 --- a/htdocs/loan/class/loanschedule.class.php +++ b/htdocs/loan/class/loanschedule.class.php @@ -129,21 +129,36 @@ class LoanSchedule extends CommonObject $now = dol_now(); // Validate parameters - if (!$this->datep) - { + if (!$this->datep) { $this->error = 'ErrorBadValueForParameter'; return -1; } // Clean parameters - if (isset($this->fk_loan)) $this->fk_loan = (int) $this->fk_loan; - if (isset($this->amount_capital)) $this->amount_capital = trim($this->amount_capital ? $this->amount_capital : 0); - if (isset($this->amount_insurance)) $this->amount_insurance = trim($this->amount_insurance ? $this->amount_insurance : 0); - if (isset($this->amount_interest)) $this->amount_interest = trim($this->amount_interest ? $this->amount_interest : 0); - if (isset($this->fk_typepayment)) $this->fk_typepayment = (int) $this->fk_typepayment; - if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; - if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; - if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + if (isset($this->fk_loan)) { + $this->fk_loan = (int) $this->fk_loan; + } + if (isset($this->amount_capital)) { + $this->amount_capital = trim($this->amount_capital ? $this->amount_capital : 0); + } + if (isset($this->amount_insurance)) { + $this->amount_insurance = trim($this->amount_insurance ? $this->amount_insurance : 0); + } + if (isset($this->amount_interest)) { + $this->amount_interest = trim($this->amount_interest ? $this->amount_interest : 0); + } + if (isset($this->fk_typepayment)) { + $this->fk_typepayment = (int) $this->fk_typepayment; + } + if (isset($this->fk_bank)) { + $this->fk_bank = (int) $this->fk_bank; + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = (int) $this->fk_user_creat; + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = (int) $this->fk_user_modif; + } $totalamount = $this->amount_capital + $this->amount_insurance + $this->amount_interest; $totalamount = price2num($totalamount); @@ -157,8 +172,7 @@ class LoanSchedule extends CommonObject $this->db->begin(); - if ($totalamount != 0) - { + if ($totalamount != 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (fk_loan, datec, datep, amount_capital, amount_insurance, amount_interest,"; $sql .= " fk_typepayment, fk_user_creat, fk_bank)"; $sql .= " VALUES (".$this->fk_loan.", '".$this->db->idate($now)."',"; @@ -172,8 +186,7 @@ class LoanSchedule extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_loan"); } else { $this->error = $this->db->lasterror(); @@ -181,8 +194,7 @@ class LoanSchedule extends CommonObject } } - if ($totalamount != 0 && !$error) - { + if ($totalamount != 0 && !$error) { $this->amount_capital = $totalamount; $this->db->commit(); return $this->id; @@ -224,7 +236,7 @@ class LoanSchedule extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = 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); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -280,14 +292,30 @@ class LoanSchedule extends CommonObject $error = 0; // Clean parameters - if (isset($this->amount_capital)) $this->amount_capital = trim($this->amount_capital); - if (isset($this->amount_insurance)) $this->amount_insurance = trim($this->amount_insurance); - if (isset($this->amount_interest)) $this->amount_interest = trim($this->amount_interest); - if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); - if (isset($this->note_private)) $this->note_private = trim($this->note_private); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->fk_bank)) $this->fk_bank = trim($this->fk_bank); - if (isset($this->fk_payment_loan)) $this->fk_payment_loan = (int) $this->fk_payment_loan; + if (isset($this->amount_capital)) { + $this->amount_capital = trim($this->amount_capital); + } + if (isset($this->amount_insurance)) { + $this->amount_insurance = trim($this->amount_insurance); + } + if (isset($this->amount_interest)) { + $this->amount_interest = trim($this->amount_interest); + } + if (isset($this->num_payment)) { + $this->num_payment = trim($this->num_payment); + } + if (isset($this->note_private)) { + $this->note_private = trim($this->note_private); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->fk_bank)) { + $this->fk_bank = trim($this->fk_bank); + } + if (isset($this->fk_payment_loan)) { + $this->fk_payment_loan = (int) $this->fk_payment_loan; + } // Check parameters // Put here code to add control on parameters values @@ -311,17 +339,18 @@ class LoanSchedule extends CommonObject $sql .= " fk_user_creat=".(isset($this->fk_user_creat) ? $this->fk_user_creat : "null").","; $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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { + if ($error) { $this->db->rollback(); return -1 * $error; } else { @@ -347,18 +376,18 @@ class LoanSchedule extends CommonObject if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; - $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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -423,10 +452,8 @@ class LoanSchedule extends CommonObject dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $line = new LoanSchedule($this->db); $line->id = $obj->rowid; $line->ref = $obj->rowid; @@ -537,14 +564,15 @@ class LoanSchedule extends CommonObject $sql = "SELECT p.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p "; $sql .= " WHERE p.fk_loan = ".$loanid; - if (!empty($datemax)) { $sql .= " AND p.datep > '".$this->db->idate($datemax)."'"; } + if (!empty($datemax)) { + $sql .= " AND p.datep > '".$this->db->idate($datemax)."'"; + } $sql .= " AND p.datep <= '".$this->db->idate(dol_now())."'"; $resql = $this->db->query($sql); if ($resql) { - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $result[] = $obj->rowid; } } diff --git a/htdocs/loan/class/paymentloan.class.php b/htdocs/loan/class/paymentloan.class.php index aa3f895f314..c7f1940943b 100644 --- a/htdocs/loan/class/paymentloan.class.php +++ b/htdocs/loan/class/paymentloan.class.php @@ -126,36 +126,58 @@ class PaymentLoan extends CommonObject $now = dol_now(); // Validate parameters - if (!$this->datep) - { + if (!$this->datep) { $this->error = 'ErrorBadValueForParameter'; return -1; } // Clean parameters - if (isset($this->fk_loan)) $this->fk_loan = (int) $this->fk_loan; - if (isset($this->amount_capital)) $this->amount_capital = price2num($this->amount_capital ? $this->amount_capital : 0); - if (isset($this->amount_insurance)) $this->amount_insurance = price2num($this->amount_insurance ? $this->amount_insurance : 0); - if (isset($this->amount_interest)) $this->amount_interest = price2num($this->amount_interest ? $this->amount_interest : 0); - if (isset($this->fk_typepayment)) $this->fk_typepayment = (int) $this->fk_typepayment; - if (isset($this->num_payment)) $this->num_payment = (int) $this->num_payment; - if (isset($this->note_private)) $this->note_private = trim($this->note_private); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; - if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; - if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + if (isset($this->fk_loan)) { + $this->fk_loan = (int) $this->fk_loan; + } + if (isset($this->amount_capital)) { + $this->amount_capital = price2num($this->amount_capital ? $this->amount_capital : 0); + } + if (isset($this->amount_insurance)) { + $this->amount_insurance = price2num($this->amount_insurance ? $this->amount_insurance : 0); + } + if (isset($this->amount_interest)) { + $this->amount_interest = price2num($this->amount_interest ? $this->amount_interest : 0); + } + if (isset($this->fk_typepayment)) { + $this->fk_typepayment = (int) $this->fk_typepayment; + } + if (isset($this->num_payment)) { + $this->num_payment = (int) $this->num_payment; + } + if (isset($this->note_private)) { + $this->note_private = trim($this->note_private); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->fk_bank)) { + $this->fk_bank = (int) $this->fk_bank; + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = (int) $this->fk_user_creat; + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = (int) $this->fk_user_modif; + } $totalamount = $this->amount_capital + $this->amount_insurance + $this->amount_interest; $totalamount = price2num($totalamount); // Check parameters - if ($totalamount == 0) return -1; // Negative amounts are accepted for reject prelevement but not null + if ($totalamount == 0) { + return -1; // Negative amounts are accepted for reject prelevement but not null + } $this->db->begin(); - if ($totalamount != 0) - { + if ($totalamount != 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_loan (fk_loan, datec, datep, amount_capital, amount_insurance, amount_interest,"; $sql .= " fk_typepayment, num_payment, note_private, note_public, fk_user_creat, fk_bank)"; $sql .= " VALUES (".$this->chid.", '".$this->db->idate($now)."',"; @@ -168,8 +190,7 @@ class PaymentLoan extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_loan"); } else { $this->error = $this->db->lasterror(); @@ -177,8 +198,7 @@ class PaymentLoan extends CommonObject } } - if ($totalamount != 0 && !$error) - { + if ($totalamount != 0 && !$error) { $this->amount_capital = $totalamount; $this->db->commit(); return $this->id; @@ -219,14 +239,12 @@ class PaymentLoan extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."payment_loan as t"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = 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); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -276,17 +294,39 @@ class PaymentLoan extends CommonObject $error = 0; // Clean parameters - if (isset($this->fk_loan)) $this->fk_loan = (int) $this->fk_loan; - if (isset($this->amount_capital)) $this->amount_capital = trim($this->amount_capital); - if (isset($this->amount_insurance)) $this->amount_insurance = trim($this->amount_insurance); - if (isset($this->amount_interest)) $this->amount_interest = trim($this->amount_interest); - if (isset($this->fk_typepayment)) $this->fk_typepayment = (int) $this->fk_typepayment; - if (isset($this->num_payment)) $this->num_payment = (int) $this->num_payment; - if (isset($this->note_private)) $this->note = trim($this->note_private); - if (isset($this->note_public)) $this->note = trim($this->note_public); - if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; - if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; - if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + if (isset($this->fk_loan)) { + $this->fk_loan = (int) $this->fk_loan; + } + if (isset($this->amount_capital)) { + $this->amount_capital = trim($this->amount_capital); + } + if (isset($this->amount_insurance)) { + $this->amount_insurance = trim($this->amount_insurance); + } + if (isset($this->amount_interest)) { + $this->amount_interest = trim($this->amount_interest); + } + if (isset($this->fk_typepayment)) { + $this->fk_typepayment = (int) $this->fk_typepayment; + } + if (isset($this->num_payment)) { + $this->num_payment = (int) $this->num_payment; + } + if (isset($this->note_private)) { + $this->note = trim($this->note_private); + } + if (isset($this->note_public)) { + $this->note = trim($this->note_public); + } + if (isset($this->fk_bank)) { + $this->fk_bank = (int) $this->fk_bank; + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = (int) $this->fk_user_creat; + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = (int) $this->fk_user_modif; + } // Check parameters @@ -308,19 +348,19 @@ class PaymentLoan extends CommonObject $sql .= " fk_user_creat=".(isset($this->fk_user_creat) ? $this->fk_user_creat : "null").","; $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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -347,35 +387,35 @@ class PaymentLoan extends CommonObject $this->db->begin(); - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url"; $sql .= " WHERE type='payment_loan' AND url_id=".$this->id; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_loan"; - $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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Set loan unpaid if loan has no other payment - if (!$error) - { + if (!$error) { require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; $loan = new Loan($this->db); $loan->fetch($this->fk_loan); $sum_payment = $loan->getSumPayment(); - if ($sum_payment == 0) - { + if ($sum_payment == 0) { dol_syslog(get_class($this)."::delete : set loan to unpaid", LOG_DEBUG); if ($loan->setUnpaid($user) < 1) { $error++; @@ -401,10 +441,8 @@ class PaymentLoan extends CommonObject //} // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -461,15 +499,16 @@ class PaymentLoan extends CommonObject $error = 0; $this->db->begin(); - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $acc = new Account($this->db); $acc->fetch($accountid); $total = $this->amount_capital; - if ($mode == 'payment_loan') $total = -$total; + if ($mode == 'payment_loan') { + $total = -$total; + } // Insert payment into llx_bank $bank_line_id = $acc->addline( @@ -486,23 +525,21 @@ class PaymentLoan extends CommonObject // Update fk_bank into llx_paiement. // We know the payment who generated the account write - if ($bank_line_id > 0) - { + if ($bank_line_id > 0) { $result = $this->update_fk_bank($bank_line_id); - if ($result <= 0) - { + if ($result <= 0) { $error++; dol_print_error($this->db); } // Add link 'payment_loan' in bank_url between payment and bank transaction $url = ''; - if ($mode == 'payment_loan') $url = DOL_URL_ROOT.'/loan/payment/card.php?id='; - if ($url) - { + if ($mode == 'payment_loan') { + $url = DOL_URL_ROOT.'/loan/payment/card.php?id='; + } + if ($url) { $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(payment)', $mode); - if ($result <= 0) - { + if ($result <= 0) { $error++; dol_print_error($this->db); } @@ -510,10 +547,11 @@ class PaymentLoan extends CommonObject // Add link 'loan' in bank_url between invoice and bank transaction (for each invoice concerned by payment) - if ($mode == 'payment_loan') - { + if ($mode == 'payment_loan') { $result = $acc->add_url_line($bank_line_id, $fk_loan, DOL_URL_ROOT.'/loan/card.php?id=', ($this->label ? $this->label : ''), 'loan'); - if ($result <= 0) dol_print_error($this->db); + if ($result <= 0) { + dol_print_error($this->db); + } } } else { $this->error = $acc->error; @@ -523,28 +561,23 @@ class PaymentLoan extends CommonObject // Set loan payment started if no set - if (!$error) - { + if (!$error) { require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; $loan = new Loan($this->db); $loan->fetch($fk_loan); - if ($loan->paid == $loan::STATUS_UNPAID) - { + if ($loan->paid == $loan::STATUS_UNPAID) { dol_syslog(get_class($this)."::addPaymentToBank : set loan payment to started", LOG_DEBUG); - if ($loan->setStarted($user) < 1) - { + if ($loan->setStarted($user) < 1) { $error++; dol_print_error($this->db); } } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; - } - else { + } else { $this->db->rollback(); return -1; } @@ -565,8 +598,7 @@ class PaymentLoan extends CommonObject dol_syslog(get_class($this)."::update_fk_bank", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->fk_bank = $id_bank; return 1; } else { @@ -589,27 +621,39 @@ class PaymentLoan extends CommonObject { global $langs, $conf; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; $label = '<u>'.$langs->trans("Loan").'</u>'; if (!empty($this->id)) { $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->id; } - if ($moretitle) $label .= ' - '.$moretitle; + if ($moretitle) { + $label .= ' - '.$moretitle; + } $url = DOL_URL_ROOT.'/loan/payment/card.php?id='.$this->id; $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 = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; return $result; diff --git a/htdocs/loan/document.php b/htdocs/loan/document.php index 91bfaf1f921..545d2ddfabf 100644 --- a/htdocs/loan/document.php +++ b/htdocs/loan/document.php @@ -40,7 +40,9 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'loan', $id, '', ''); // Get parameters @@ -54,11 +56,17 @@ if (empty($page) || $page == -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"; +} $object = new Loan($db); -if ($id > 0) $object->fetch($id); +if ($id > 0) { + $object->fetch($id); +} $upload_dir = $conf->loan->dir_output.'/'.dol_sanitizeFileName($object->ref); $modulepart = 'loan'; @@ -68,7 +76,7 @@ $modulepart = 'loan'; * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -81,8 +89,7 @@ $title = $langs->trans("Loan").' - '.$langs->trans("Documents"); $help_url = 'EN:Module_Loan|FR:Module_Emprunt'; llxHeader("", $title, $help_url); -if ($object->id) -{ +if ($object->id) { $totalpaid = $object->getSumPayment(); $head = loan_prepare_head($object); @@ -138,8 +145,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/loan/info.php b/htdocs/loan/info.php index 0d9306aa71f..7ecc41fe4d6 100644 --- a/htdocs/loan/info.php +++ b/htdocs/loan/info.php @@ -38,7 +38,9 @@ $action = GETPOST('action', 'aZ09'); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'loan', $id, '', ''); diff --git a/htdocs/loan/list.php b/htdocs/loan/list.php index 744a6929fc8..9040d140149 100644 --- a/htdocs/loan/list.php +++ b/htdocs/loan/list.php @@ -32,14 +32,18 @@ $langs->loadLangs(array("loan", "compta", "banks", "bills")); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'loan', '', '', ''); $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; @@ -48,8 +52,12 @@ $pagenext = $page + 1; $loan_static = new Loan($db); $extrafields = new ExtraFields($db); -if (!$sortfield) $sortfield = "l.rowid"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "l.rowid"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} $search_ref = GETPOST('search_ref', 'int'); $search_label = GETPOST('search_label', 'alpha'); @@ -63,18 +71,22 @@ $optioncss = GETPOST('optioncss', 'alpha'); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // 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_ref = ""; $search_label = ""; $search_amount = ""; @@ -97,35 +109,39 @@ $sql .= " SUM(pl.amount_capital) as alreadypaid"; $sql .= " FROM ".MAIN_DB_PREFIX."loan as l LEFT JOIN ".MAIN_DB_PREFIX."payment_loan AS pl"; $sql .= " ON l.rowid = pl.fk_loan"; $sql .= " WHERE l.entity = ".$conf->entity; -if ($search_amount) $sql .= natural_search("l.capital", $search_amount, 1); -if ($search_ref) $sql .= " AND l.rowid = ".$db->escape($search_ref); -if ($search_label) $sql .= natural_search("l.label", $search_label); +if ($search_amount) { + $sql .= natural_search("l.capital", $search_amount, 1); +} +if ($search_ref) { + $sql .= " AND l.rowid = ".$db->escape($search_ref); +} +if ($search_label) { + $sql .= natural_search("l.label", $search_label); +} $sql .= " GROUP BY l.rowid, l.label, l.capital, l.paid, l.datestart, l.dateend"; $sql .= $db->order($sortfield, $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 || empty($limit))) -{ +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -138,24 +154,39 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit llxHeader('', $title, $help_url); -if ($resql) -{ +if ($resql) { $i = 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 ($search_ref) $param .= "&search_ref=".urlencode($search_ref); - if ($search_label) $param .= "&search_label=".urlencode($search_label); - 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 ($search_ref) { + $param .= "&search_ref=".urlencode($search_ref); + } + if ($search_label) { + $param .= "&search_label=".urlencode($search_label); + } + if ($search_amount) { + $param .= "&search_amount=".urlencode($search_amount); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } $url = DOL_URL_ROOT.'/loan/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewLoan'), '', 'fa fa-plus-circle', $url, '', $user->rights->loan->write); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -201,10 +232,11 @@ if ($resql) // -------------------------------------------------------------------- $i = 0; $totalarray = array(); - while ($i < ($limit ? min($num, $limit) : $num)) - { + while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } $loan_static->id = $obj->rowid; $loan_static->ref = $obj->rowid; @@ -240,8 +272,7 @@ if ($resql) } // If no record found - if ($num == 0) - { + if ($num == 0) { $colspan = 7; //foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; diff --git a/htdocs/loan/note.php b/htdocs/loan/note.php index 91f32679699..f7930b64c9a 100644 --- a/htdocs/loan/note.php +++ b/htdocs/loan/note.php @@ -44,7 +44,9 @@ $id = GETPOST('id', 'int'); $result = restrictedArea($user, 'loan', $id, '&loan'); $object = new Loan($db); -if ($id > 0) $object->fetch($id); +if ($id > 0) { + $object->fetch($id); +} $permissionnote = $user->rights->loan->write; // Used by the include of actions_setnotes.inc.php @@ -66,11 +68,10 @@ $title = $langs->trans("Loan").' - '.$langs->trans("Notes"); $help_url = 'EN:Module_Loan|FR:Module_Emprunt'; llxHeader("", $title, $help_url); -if ($id > 0) -{ +if ($id > 0) { /* - * Affichage onglets - */ + * Affichage onglets + */ $totalpaid = $object->getSumPayment(); $head = loan_prepare_head($object); diff --git a/htdocs/loan/payment/card.php b/htdocs/loan/payment/card.php index ac76dbf9053..cf4466bb0da 100644 --- a/htdocs/loan/payment/card.php +++ b/htdocs/loan/payment/card.php @@ -24,7 +24,9 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; require_once DOL_DOCUMENT_ROOT.'/loan/class/paymentloan.class.php'; -if (!empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +if (!empty($conf->banque->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +} // Load translation files required by the page $langs->loadLangs(array("bills", "banks", "companies", "loan")); @@ -33,15 +35,18 @@ $langs->loadLangs(array("bills", "banks", "companies", "loan")); $id = GETPOST("id", 'int'); $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} // TODO ajouter regle pour restreindre acces paiement //$result = restrictedArea($user, 'facture', $id,''); $payment = new PaymentLoan($db); -if ($id > 0) -{ +if ($id > 0) { $result = $payment->fetch($id); - if (!$result) dol_print_error($db, 'Failed to get payment id '.$id); + if (!$result) { + dol_print_error($db, 'Failed to get payment id '.$id); + } } @@ -50,8 +55,7 @@ if ($id > 0) */ // Delete payment -if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->loan->delete) -{ +if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->loan->delete) { $db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."loan_schedule SET fk_bank = 0 WHERE fk_bank = ".$payment->fk_bank; @@ -60,8 +64,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->loan->del $fk_loan = $payment->fk_loan; $result = $payment->delete($user); - if ($result > 0) - { + if ($result > 0) { $db->commit(); header("Location: ".DOL_URL_ROOT."/loan/card.php?id=".$fk_loan); exit; @@ -93,8 +96,7 @@ print dol_get_fiche_head($head, $hselected, $langs->trans("PaymentLoan"), -1, 'p /* * Confirm deletion of the payment */ -if ($action == 'delete') -{ +if ($action == 'delete') { print $form->formconfirm('card.php?id='.$payment->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete', '', 0, 2); } @@ -127,10 +129,8 @@ print '<tr><td>'.$langs->trans('NotePrivate').'</td><td>'.nl2br($payment->note_p print '<tr><td>'.$langs->trans('NotePublic').'</td><td>'.nl2br($payment->note_public).'</td></tr>'; // Bank account -if (!empty($conf->banque->enabled)) -{ - if ($payment->bank_account) - { +if (!empty($conf->banque->enabled)) { + if ($payment->bank_account) { $bankline = new AccountLine($db); $bankline->fetch($payment->bank_line); @@ -161,8 +161,7 @@ $sql .= ' AND pl.rowid = '.$payment->id; dol_syslog("loan/payment/card.php", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -176,10 +175,8 @@ if ($resql) print '<td class="right">'.$langs->trans('PayedByThisPayment').'</td>'; print "</tr>\n"; - if ($num > 0) - { - while ($i < $num) - { + if ($num > 0) { + while ($i < $num) { $objp = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -199,8 +196,7 @@ if ($resql) print '<td class="right">'.price($amount_payed).'</td>'; print "</tr>\n"; - if ($objp->paid == 1) // If at least one invoice is paid, disable delete - { + if ($objp->paid == 1) { // If at least one invoice is paid, disable delete $disable_delete = 1; } $total = $total + $objp->amount_capital; @@ -224,10 +220,8 @@ print '</div>'; print '<div class="tabsAction">'; -if (empty($action) && !empty($user->rights->loan->delete)) -{ - if (!$disable_delete) - { +if (empty($action) && !empty($user->rights->loan->delete)) { + if (!$disable_delete) { print '<a class="butActionDelete" href="card.php?id='.$id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("CantRemovePaymentWithOneInvoicePaid")).'">'.$langs->trans('Delete').'</a>'; diff --git a/htdocs/loan/payment/payment.php b/htdocs/loan/payment/payment.php index 0c0574c15b4..eec24d9b3e2 100644 --- a/htdocs/loan/payment/payment.php +++ b/htdocs/loan/payment/payment.php @@ -39,10 +39,14 @@ $datepaid = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'in // Security check $socid = 0; -if ($user->socid > 0) +if ($user->socid > 0) { $socid = $user->socid; -elseif (GETPOSTISSET('socid')) $socid = GETPOST('socid', 'int'); -if (empty($user->rights->loan->write)) accessforbidden(); +} elseif (GETPOSTISSET('socid')) { + $socid = GETPOST('socid', 'int'); +} +if (empty($user->rights->loan->write)) { + accessforbidden(); +} $loan = new Loan($db); $loan->fetch($chid); @@ -51,35 +55,31 @@ $echance = 0; $ls = new LoanSchedule($db); // grab all loanschedule $res = $ls->fetchAll($chid); -if ($res > 0) -{ - foreach ($ls->lines as $l) - { +if ($res > 0) { + foreach ($ls->lines as $l) { $echance++; // Count term pos // last unpaid term - if (empty($l->fk_bank)) - { + if (empty($l->fk_bank)) { $line_id = $l->id; break; - } - // If line_id provided, only count temp pos - elseif ($line_id == $l->id) - { + } elseif ($line_id == $l->id) { + // If line_id provided, only count temp pos break; } } } // Set current line with last unpaid line (only if shedule is used) -if (!empty($line_id)) -{ +if (!empty($line_id)) { $line = new LoanSchedule($db); $res = $line->fetch($line_id); if ($res > 0) { $amount_capital = price($line->amount_capital); $amount_insurance = price($line->amount_insurance); $amount_interest = price($line->amount_interest); - if (empty($datepaid)) $ts_temppaid = $line->datep; + if (empty($datepaid)) { + $ts_temppaid = $line->datep; + } } } @@ -88,66 +88,59 @@ if (!empty($line_id)) * Actions */ -if ($action == 'add_payment') -{ +if ($action == 'add_payment') { $error = 0; - if ($cancel) - { + if ($cancel) { $loc = DOL_URL_ROOT.'/loan/card.php?id='.$chid; header("Location: ".$loc); exit; } - if (!GETPOST('paymenttype', 'int') > 0) - { + if (!GETPOST('paymenttype', 'int') > 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")), null, 'errors'); $error++; } - if ($datepaid == '') - { + if ($datepaid == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors'); $error++; } - if (!empty($conf->banque->enabled) && !GETPOST('accountid', 'int') > 0) - { + if (!empty($conf->banque->enabled) && !GETPOST('accountid', 'int') > 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountToCredit")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $paymentid = 0; $pay_amount_capital = price2num(GETPOST('amount_capital')); $pay_amount_insurance = price2num(GETPOST('amount_insurance')); // User can't set interest him self if schedule is set (else value in schedule can be incoherent) - if (!empty($line)) $pay_amount_interest = $line->amount_interest; - else $pay_amount_interest = price2num(GETPOST('amount_interest')); + if (!empty($line)) { + $pay_amount_interest = $line->amount_interest; + } else { + $pay_amount_interest = price2num(GETPOST('amount_interest')); + } $remaindertopay = price2num(GETPOST('remaindertopay')); $amount = $pay_amount_capital + $pay_amount_insurance + $pay_amount_interest; // This term is allready paid - if (!empty($line) && !empty($line->fk_bank)) - { + if (!empty($line) && !empty($line->fk_bank)) { setEventMessages($langs->trans('TermPaidAllreadyPaid'), null, 'errors'); $error++; } - if (empty($remaindertopay)) - { + if (empty($remaindertopay)) { setEventMessages('Empty sumpaid', null, 'errors'); $error++; } - if ($amount == 0) - { + if ($amount == 0) { setEventMessages($langs->trans('ErrorNoPaymentDefined'), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $db->begin(); // Create a line of payments @@ -164,38 +157,30 @@ if ($action == 'add_payment') $payment->note_private = GETPOST('note_private', 'restricthtml'); $payment->note_public = GETPOST('note_public', 'restricthtml'); - if (!$error) - { + if (!$error) { $paymentid = $payment->create($user); - if ($paymentid < 0) - { + if ($paymentid < 0) { setEventMessages($payment->error, $payment->errors, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { $result = $payment->addPaymentToBank($user, $chid, 'payment_loan', '(LoanPayment)', $payment->fk_bank, '', ''); - if (!$result > 0) - { + if (!$result > 0) { setEventMessages($payment->error, $payment->errors, 'errors'); $error++; } } // Update loan schedule with payment value - if (!$error && !empty($line)) - { + if (!$error && !empty($line)) { // If payment values are modified, recalculate schedule - if (($line->amount_capital <> $pay_amount_capital) || ($line->amount_insurance <> $pay_amount_insurance) || ($line->amount_interest <> $pay_amount_interest)) - { + if (($line->amount_capital <> $pay_amount_capital) || ($line->amount_insurance <> $pay_amount_insurance) || ($line->amount_interest <> $pay_amount_interest)) { $arr_term = loanCalcMonthlyPayment(($pay_amount_capital + $pay_amount_interest), $remaindertopay, ($loan->rate / 100), $echance, $loan->nbterm); - foreach ($arr_term as $k=>$v) - { + foreach ($arr_term as $k => $v) { // Update fk_bank for current line - if ($k == $echance) - { + if ($k == $echance) { $ls->lines[$k - 1]->fk_bank = $payment->fk_bank; $ls->lines[$k - 1]->fk_payment_loan = $payment->id; } @@ -204,29 +189,25 @@ if ($action == 'add_payment') $ls->lines[$k - 1]->tms = dol_now(); $ls->lines[$k - 1]->fk_user_modif = $user->id; $result = $ls->lines[$k - 1]->update($user, 0); - if ($result < 1) - { + if ($result < 1) { setEventMessages(null, $ls->errors, 'errors'); $error++; break; } } - } - else // Only add fk_bank bank to schedule line (mark as paid) + } else // Only add fk_bank bank to schedule line (mark as paid) { $line->fk_bank = $payment->fk_bank; $line->fk_payment_loan = $payment->id; $result = $line->update($user, 0); - if ($result < 1) - { + if ($result < 1) { setEventMessages(null, $line->errors, 'errors'); $error++; } } } - if (!$error) - { + if (!$error) { $db->commit(); $loc = DOL_URL_ROOT.'/loan/card.php?id='.$chid; header('Location: '.$loc); @@ -251,8 +232,7 @@ $form = new Form($db); // Form to create loan's payment -if ($action == 'create') -{ +if ($action == 'create') { $total = $loan->capital; print load_fiche_titre($langs->trans("DoPayment")); @@ -261,8 +241,7 @@ if ($action == 'create') $sql .= " FROM ".MAIN_DB_PREFIX."payment_loan"; $sql .= " WHERE fk_loan = ".$chid; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $sumpaid = $obj->total; $db->free(); @@ -282,10 +261,10 @@ if ($action == 'create') print '<table class="border centpercent">'; print '<tr><td class="titlefield">'.$langs->trans("Ref").'</td><td colspan="2"><a href="'.DOL_URL_ROOT.'/loan/card.php?id='.$chid.'">'.$chid.'</a></td></tr>'; - if ($echance > 0) - { - print '<tr><td>'.$langs->trans("Term").'</td><td colspan="2"><a href="'.DOL_URL_ROOT.'/loan/schedule.php?loanid='.$chid.'#n'.$echance.'">'.$echance.'</a></td></tr>'."\n"; - } + if ($echance > 0) + { + print '<tr><td>'.$langs->trans("Term").'</td><td colspan="2"><a href="'.DOL_URL_ROOT.'/loan/schedule.php?loanid='.$chid.'#n'.$echance.'">'.$echance.'</a></td></tr>'."\n"; + } print '<tr><td>'.$langs->trans("DateStart").'</td><td colspan="2">'.dol_print_date($loan->datestart, 'day')."</td></tr>\n"; print '<tr><td>'.$langs->trans("Label").'</td><td colspan="2">'.$loan->label."</td></tr>\n"; print '<tr><td>'.$langs->trans("Amount").'</td><td colspan="2">'.price($loan->capital, 0, $outputlangs, 1, -1, -1, $conf->currency).'</td></tr>'; @@ -300,108 +279,106 @@ if ($action == 'create') print '<table class="border centpercent">'; print '<tr><td class="titlefield fieldrequired">'.$langs->trans("Date").'</td><td colspan="2">'; - if (empty($datepaid)) - if (empty($ts_temppaid)) $datepayment = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : dol_now(); - else $datepayment = $ts_temppaid; - else $datepayment = $datepaid; - print $form->selectDate($datepayment, '', '', '', '', "add_payment", 1, 1); - print "</td>"; - print '</tr>'; + if (empty($datepaid)) { + if (empty($ts_temppaid)) { + $datepayment = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : dol_now(); + } else { + $datepayment = $ts_temppaid; + } + } else { + $datepayment = $datepaid; + } + print $form->selectDate($datepayment, '', '', '', '', "add_payment", 1, 1); + print "</td>"; + print '</tr>'; - print '<tr><td class="fieldrequired">'.$langs->trans("PaymentMode").'</td><td colspan="2">'; - $form->select_types_paiements(GETPOSTISSET("paymenttype") ? GETPOST("paymenttype", 'alphanohtml') : $loan->fk_typepayment, "paymenttype"); - print "</td>\n"; - print '</tr>'; + print '<tr><td class="fieldrequired">'.$langs->trans("PaymentMode").'</td><td colspan="2">'; + $form->select_types_paiements(GETPOSTISSET("paymenttype") ? GETPOST("paymenttype", 'alphanohtml') : $loan->fk_typepayment, "paymenttype"); + print "</td>\n"; + print '</tr>'; - print '<tr>'; - print '<td class="fieldrequired">'.$langs->trans('AccountToDebit').'</td>'; - print '<td colspan="2">'; - $form->select_comptes(GETPOSTISSET("accountid") ? GETPOST("accountid", 'int') : $loan->accountid, "accountid", 0, 'courant = '.Account::TYPE_CURRENT, 1); // Show opend bank account list - print '</td></tr>'; + print '<tr>'; + print '<td class="fieldrequired">'.$langs->trans('AccountToDebit').'</td>'; + print '<td colspan="2">'; + $form->select_comptes(GETPOSTISSET("accountid") ? GETPOST("accountid", 'int') : $loan->accountid, "accountid", 0, 'courant = '.Account::TYPE_CURRENT, 1); // Show opend bank account list + print '</td></tr>'; // Number - print '<tr><td>'.$langs->trans('Numero'); - print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>'; - print '</td>'; - print '<td colspan="2"><input name="num_payment" type="text" value="'.GETPOST('num_payment', 'alphanohtml').'"></td>'."\n"; - print "</tr>"; + print '<tr><td>'.$langs->trans('Numero'); + print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>'; + print '</td>'; + print '<td colspan="2"><input name="num_payment" type="text" value="'.GETPOST('num_payment', 'alphanohtml').'"></td>'."\n"; + print "</tr>"; - print '<tr>'; - print '<td class="tdtop">'.$langs->trans("NotePrivate").'</td>'; - print '<td valign="top" colspan="2"><textarea name="note_private" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>'; - print '</tr>'; + print '<tr>'; + print '<td class="tdtop">'.$langs->trans("NotePrivate").'</td>'; + print '<td valign="top" colspan="2"><textarea name="note_private" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>'; + print '</tr>'; - print '<tr>'; - print '<td class="tdtop">'.$langs->trans("NotePublic").'</td>'; - print '<td valign="top" colspan="2"><textarea name="note_public" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>'; - print '</tr>'; + print '<tr>'; + print '<td class="tdtop">'.$langs->trans("NotePublic").'</td>'; + print '<td valign="top" colspan="2"><textarea name="note_public" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>'; + print '</tr>'; - print '</table>'; + print '</table>'; - print dol_get_fiche_end(); + print dol_get_fiche_end(); - print '<table class="noborder centpercent">'; - print '<tr class="liste_titre">'; - print '<td class="left">'.$langs->trans("DateDue").'</td>'; - print '<td class="right">'.$langs->trans("LoanCapital").'</td>'; - print '<td class="right">'.$langs->trans("AlreadyPaid").'</td>'; - print '<td class="right">'.$langs->trans("RemainderToPay").'</td>'; - print '<td class="right">'.$langs->trans("Amount").'</td>'; - print "</tr>\n"; + print '<table class="noborder centpercent">'; + print '<tr class="liste_titre">'; + print '<td class="left">'.$langs->trans("DateDue").'</td>'; + print '<td class="right">'.$langs->trans("LoanCapital").'</td>'; + print '<td class="right">'.$langs->trans("AlreadyPaid").'</td>'; + print '<td class="right">'.$langs->trans("RemainderToPay").'</td>'; + print '<td class="right">'.$langs->trans("Amount").'</td>'; + print "</tr>\n"; - print '<tr class="oddeven">'; + print '<tr class="oddeven">'; - if ($loan->datestart > 0) - { + if ($loan->datestart > 0) { print '<td class="left" valign="center">'.dol_print_date($loan->datestart, 'day').'</td>'; } else { print '<td class="center" valign="center"><b>!!!</b></td>'; } - print '<td class="right" valign="center">'.price($loan->capital)."</td>"; + print '<td class="right" valign="center">'.price($loan->capital)."</td>"; - print '<td class="right" valign="center">'.price($sumpaid)."</td>"; + print '<td class="right" valign="center">'.price($sumpaid)."</td>"; - print '<td class="right" valign="center">'.price($loan->capital - $sumpaid)."</td>"; + print '<td class="right" valign="center">'.price($loan->capital - $sumpaid)."</td>"; - print '<td class="right">'; - if ($sumpaid < $loan->capital) - { + print '<td class="right">'; + if ($sumpaid < $loan->capital) { print $langs->trans("LoanCapital").': <input type="text" size="8" name="amount_capital" value="'.(GETPOSTISSET('amount_capital') ?GETPOST('amount_capital') : $amount_capital).'">'; - } - else { + } else { print '-'; } - print '<br>'; - if ($sumpaid < $loan->capital) - { + print '<br>'; + if ($sumpaid < $loan->capital) { print $langs->trans("Insurance").': <input type="text" size="8" name="amount_insurance" value="'.(GETPOSTISSET('amount_insurance') ?GETPOST('amount_insurance') : $amount_insurance).'">'; - } - else { + } else { print '-'; } - print '<br>'; - if ($sumpaid < $loan->capital) - { + print '<br>'; + if ($sumpaid < $loan->capital) { print $langs->trans("Interest").': <input type="text" size="8" name="amount_interest" value="'.(GETPOSTISSET('amount_interest') ?GETPOST('amount_interest') : $amount_interest).'" '.(!empty($line) ? 'disabled title="'.$langs->trans('CantModifyInterestIfScheduleIsUsed').'"' : '').'>'; - } - else { + } else { print '-'; } - print "</td>"; + print "</td>"; - print "</tr>\n"; + print "</tr>\n"; - print '</table>'; + print '</table>'; - print '<br><div class="center">'; - print '<input type="submit" class="button button-save" name="save" value="'.$langs->trans("Save").'">'; - print '&nbsp; &nbsp;'; - print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; - print '</div>'; + print '<br><div class="center">'; + print '<input type="submit" class="button button-save" name="save" value="'.$langs->trans("Save").'">'; + print '&nbsp; &nbsp;'; + print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; + print '</div>'; - print "</form>\n"; + print "</form>\n"; } llxFooter(); diff --git a/htdocs/loan/schedule.php b/htdocs/loan/schedule.php index b9e6783ceca..2969d6958b5 100644 --- a/htdocs/loan/schedule.php +++ b/htdocs/loan/schedule.php @@ -35,9 +35,15 @@ $action = GETPOST('action', 'aZ09'); // Security check $socid = 0; -if (GETPOSTISSET('socid')) $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; -if (empty($user->rights->loan->calc)) accessforbidden(); +if (GETPOSTISSET('socid')) { + $socid = GETPOST('socid', 'int'); +} +if ($user->socid) { + $socid = $user->socid; +} +if (empty($user->rights->loan->calc)) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array("compta", "bills", "loan")); @@ -120,7 +126,9 @@ if ($action == 'updateecheancier' && empty($pay_without_schedule)) { $echeances->lines[$i - 1] = $new_echeance; $i++; } - if ($result > 0) $db->commit(); + if ($result > 0) { + $db->commit(); + } } /* @@ -141,24 +149,23 @@ $morehtmlref = '<div class="refidno">'; $morehtmlref .= $form->editfieldkey("Label", 'label', $object->label, $object, 0, 'string', '', 0, 1); $morehtmlref .= $form->editfieldval("Label", 'label', $object->label, $object, 0, 'string', '', null, null, '', 1); // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->loadLangs(array("projects")); $morehtmlref .= '<br>'.$langs->trans('Project').' : '; - if ($user->rights->loan->write) - { - if ($action != 'classify') + if ($user->rights->loan->write) { + if ($action != 'classify') { //$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; - $morehtmlref .= '<input type="hidden" name="action" value="classin">'; - $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; - $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; - $morehtmlref .= '</form>'; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref .= '<input type="hidden" name="action" value="classin">'; + $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref .= '</form>'; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } } } else { if (!empty($object->fk_project)) { @@ -212,14 +219,14 @@ $(document).ready(function() { </script> <?php -if ($pay_without_schedule == 1) +if ($pay_without_schedule == 1) { print '<div class="warning">'.$langs->trans('CantUseScheduleWithLoanStartedToPaid').'</div>'."\n"; +} print '<form name="createecheancier" action="'.$_SERVER["PHP_SELF"].'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="loanid" value="'.$loanid.'">'; -if (count($echeances->lines) > 0) -{ +if (count($echeances->lines) > 0) { print '<input type="hidden" name="action" value="updateecheancier">'; } else { print '<input type="hidden" name="action" value="createecheancier">'; @@ -229,7 +236,9 @@ print '<div class="div-table-responsive-no-min">'; print '<table class="border centpercent">'; print '<tr class="liste_titre">'; $colspan = 6; -if (count($echeances->lines) > 0) $colspan++; +if (count($echeances->lines) > 0) { + $colspan++; +} print '<th class="center" colspan="'.$colspan.'">'; print $langs->trans("FinancialCommitment"); print '</th>'; @@ -245,18 +254,18 @@ print '<th class="center">'.$langs->trans("CapitalRemain"); print '<br>('.price($object->capital, 0, '', 1, -1, -1, $conf->currency).')'; print '<input type="hidden" name="hi_capital0" id ="hi_capital0" value="'.$object->capital.'">'; print '</th>'; -if (count($echeances->lines) > 0) print '<th class="center">'.$langs->trans('DoPayment').'</th>'; +if (count($echeances->lines) > 0) { + print '<th class="center">'.$langs->trans('DoPayment').'</th>'; +} print '</tr>'."\n"; -if ($object->nbterm > 0 && count($echeances->lines) == 0) -{ +if ($object->nbterm > 0 && count($echeances->lines) == 0) { $i = 1; $capital = $object->capital; $insurance = $object->insurance_amount / $object->nbterm; $insurance = price2num($insurance, 'MT'); $regulInsurance = price2num($object->insurance_amount - ($insurance * $object->nbterm)); - while ($i < $object->nbterm + 1) - { + while ($i < $object->nbterm + 1) { $mens = price2num($echeances->calcMonthlyPayments($capital, $object->rate / 100, $object->nbterm - $i + 1), 'MT'); $int = ($capital * ($object->rate / 12)) / 100; $int = price2num($int, 'MT'); @@ -273,8 +282,7 @@ if ($object->nbterm > 0 && count($echeances->lines) == 0) $i++; $capital = $cap_rest; } -} elseif (count($echeances->lines) > 0) -{ +} elseif (count($echeances->lines) > 0) { $i = 1; $capital = $object->capital; $insurance = $object->insurance_amount / $object->nbterm; @@ -300,14 +308,12 @@ if ($object->nbterm > 0 && count($echeances->lines) == 0) print '<td class="center" id="capital'.$i.'">'.price($cap_rest, 0, '', 1, -1, -1, $conf->currency).'</td><input type="hidden" name="hi_capital'.$i.'" id ="hi_capital'.$i.'" value="'.$cap_rest.'">'; print '<td class="center">'; - if (!empty($line->fk_bank)) - { + if (!empty($line->fk_bank)) { print $langs->trans('Paid'); - if (!empty($line->fk_payment_loan)) + if (!empty($line->fk_payment_loan)) { print '&nbsp;<a href="'.DOL_URL_ROOT.'/loan/payment/card.php?id='.$line->fk_payment_loan.'">('.img_object($langs->trans("Payment"), "payment").' '.$line->fk_payment_loan.')</a>'; - } - elseif (!$printed) - { + } + } elseif (!$printed) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/loan/payment/payment.php?id='.$object->id.'&amp;action=create">'.$langs->trans('DoPayment').'</a>'; $printed = true; } @@ -323,8 +329,11 @@ print '</div>'; print '</br>'; -if (count($echeances->lines) == 0) $label = $langs->trans("Create"); -else $label = $langs->trans("Save"); +if (count($echeances->lines) == 0) { + $label = $langs->trans("Create"); +} else { + $label = $langs->trans("Save"); +} print '<div class="center"><input class="button" type="submit" value="'.$label.'" '.(($pay_without_schedule == 1) ? 'disabled title="'.$langs->trans('CantUseScheduleWithLoanStartedToPaid').'"' : '').'title=""></div>'; print '</form>'; diff --git a/htdocs/mailmanspip/class/mailmanspip.class.php b/htdocs/mailmanspip/class/mailmanspip.class.php index a0a636dd136..d08f6f65094 100644 --- a/htdocs/mailmanspip/class/mailmanspip.class.php +++ b/htdocs/mailmanspip/class/mailmanspip.class.php @@ -77,8 +77,7 @@ class MailmanSpip */ public function isSpipEnabled() { - if (defined("ADHERENT_USE_SPIP") && (ADHERENT_USE_SPIP == 1)) - { + if (defined("ADHERENT_USE_SPIP") && (ADHERENT_USE_SPIP == 1)) { return true; } @@ -92,10 +91,8 @@ class MailmanSpip */ public function checkSpipConfig() { - if (defined('ADHERENT_SPIP_SERVEUR') && defined('ADHERENT_SPIP_USER') && defined('ADHERENT_SPIP_PASS') && defined('ADHERENT_SPIP_DB')) - { - if (ADHERENT_SPIP_SERVEUR != '' && ADHERENT_SPIP_USER != '' && ADHERENT_SPIP_PASS != '' && ADHERENT_SPIP_DB != '') - { + if (defined('ADHERENT_SPIP_SERVEUR') && defined('ADHERENT_SPIP_USER') && defined('ADHERENT_SPIP_PASS') && defined('ADHERENT_SPIP_DB')) { + if (ADHERENT_SPIP_SERVEUR != '' && ADHERENT_SPIP_USER != '' && ADHERENT_SPIP_PASS != '' && ADHERENT_SPIP_DB != '') { return true; } } @@ -112,8 +109,7 @@ class MailmanSpip { $resource = getDoliDBInstance('mysql', ADHERENT_SPIP_SERVEUR, ADHERENT_SPIP_USER, ADHERENT_SPIP_PASS, ADHERENT_SPIP_DB, ADHERENT_SPIP_PORT); - if ($resource->ok) - { + if ($resource->ok) { return $resource; } @@ -165,8 +161,7 @@ class MailmanSpip dol_syslog('result curl_exec='.$result); //An error was found, we store it in $this->error for later - if ($result === false || curl_errno($ch) > 0) - { + if ($result === false || curl_errno($ch) > 0) { $this->error = curl_errno($ch).' '.curl_error($ch); dol_syslog('Error using curl '.$this->error, LOG_ERR); } @@ -188,14 +183,11 @@ class MailmanSpip // phpcs:enable dol_syslog(get_class($this)."::add_to_spip"); - if ($this->isSpipEnabled()) - { - if ($this->checkSpipConfig()) - { + if ($this->isSpipEnabled()) { + if ($this->checkSpipConfig()) { $mydb = $this->connectSpip(); - if ($mydb) - { + if ($mydb) { require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; $mdpass = dol_hash($object->pass); $htpass = crypt($object->pass, makesalt()); @@ -205,13 +197,20 @@ class MailmanSpip $mydb->close(); - if ($result) - { + if ($result) { return 1; - } else $this->error = $mydb->lasterror(); - } else $this->error = 'Failed to connect to SPIP'; - } else $this->error = 'BadSPIPConfiguration'; - } else $this->error = 'SPIPNotEnabled'; + } else { + $this->error = $mydb->lasterror(); + } + } else { + $this->error = 'Failed to connect to SPIP'; + } + } else { + $this->error = 'BadSPIPConfiguration'; + } + } else { + $this->error = 'SPIPNotEnabled'; + } return 0; } @@ -228,27 +227,31 @@ class MailmanSpip // phpcs:enable dol_syslog(get_class($this)."::del_to_spip"); - if ($this->isSpipEnabled()) - { - if ($this->checkSpipConfig()) - { + if ($this->isSpipEnabled()) { + if ($this->checkSpipConfig()) { $mydb = $this->connectSpip(); - if ($mydb) - { + if ($mydb) { $query = "DELETE FROM spip_auteurs WHERE login='".$object->login."'"; $result = $mydb->query($query); $mydb->close(); - if ($result) - { + if ($result) { return 1; - } else $this->error = $mydb->lasterror(); - } else $this->error = 'Failed to connect to SPIP'; - } else $this->error = 'BadSPIPConfiguration'; - } else $this->error = 'SPIPNotEnabled'; + } else { + $this->error = $mydb->lasterror(); + } + } else { + $this->error = 'Failed to connect to SPIP'; + } + } else { + $this->error = 'BadSPIPConfiguration'; + } + } else { + $this->error = 'SPIPNotEnabled'; + } return 0; } @@ -263,22 +266,17 @@ class MailmanSpip public function is_in_spip($object) { // phpcs:enable - if ($this->isSpipEnabled()) - { - if ($this->checkSpipConfig()) - { + if ($this->isSpipEnabled()) { + if ($this->checkSpipConfig()) { $mydb = $this->connectSpip(); - if ($mydb) - { + if ($mydb) { $query = "SELECT login FROM spip_auteurs WHERE login='".$object->login."'"; $result = $mydb->query($query); - if ($result) - { - if ($mydb->num_rows($result)) - { + if ($result) { + if ($mydb->num_rows($result)) { // nous avons au moins une reponse $mydb->close($result); return 1; @@ -291,9 +289,15 @@ class MailmanSpip $this->error = $mydb->lasterror(); $mydb->close(); } - } else $this->error = 'Failed to connect to SPIP'; - } else $this->error = 'BadSPIPConfiguration'; - } else $this->error = 'SPIPNotEnabled'; + } else { + $this->error = 'Failed to connect to SPIP'; + } + } else { + $this->error = 'BadSPIPConfiguration'; + } + } else { + $this->error = 'SPIPNotEnabled'; + } return -1; } @@ -316,36 +320,32 @@ class MailmanSpip $this->mladded_ok = array(); $this->mladded_ko = array(); - if (!function_exists("curl_init")) - { + if (!function_exists("curl_init")) { $langs->load("errors"); $this->error = $langs->trans("ErrorFunctionNotAvailableInPHP", "curl_init"); return -1; } - if ($conf->adherent->enabled) // Synchro for members - { - if (!empty($conf->global->ADHERENT_MAILMAN_URL)) - { - if ($listes == '' && !empty($conf->global->ADHERENT_MAILMAN_LISTS)) $lists = explode(',', $conf->global->ADHERENT_MAILMAN_LISTS); - else $lists = explode(',', $listes); + if ($conf->adherent->enabled) { // Synchro for members + if (!empty($conf->global->ADHERENT_MAILMAN_URL)) { + if ($listes == '' && !empty($conf->global->ADHERENT_MAILMAN_LISTS)) { + $lists = explode(',', $conf->global->ADHERENT_MAILMAN_LISTS); + } else { + $lists = explode(',', $listes); + } $categstatic = new Categorie($this->db); - foreach ($lists as $list) - { + foreach ($lists as $list) { // Filter on type something (ADHERENT_MAILMAN_LISTS = "mailinglist0,TYPE:typevalue:mailinglist1,CATEG:categvalue:mailinglist2") $tmp = explode(':', $list); - if (!empty($tmp[2])) - { + if (!empty($tmp[2])) { $list = $tmp[2]; - if ($object->element == 'member' && $tmp[0] == 'TYPE' && $object->type != $tmp[1]) // Filter on member type label - { + if ($object->element == 'member' && $tmp[0] == 'TYPE' && $object->type != $tmp[1]) { // Filter on member type label dol_syslog("We ignore list ".$list." because object member type ".$object->type." does not match ".$tmp[1], LOG_DEBUG); continue; } - if ($object->element == 'member' && $tmp[0] == 'CATEG' && !in_array($tmp[1], $categstatic->containing($object->id, 'member', 'label'))) // Filter on member category - { + if ($object->element == 'member' && $tmp[0] == 'CATEG' && !in_array($tmp[1], $categstatic->containing($object->id, 'member', 'label'))) { // Filter on member category dol_syslog("We ignore list ".$list." because object member is not into category ".$tmp[1], LOG_DEBUG); continue; } @@ -354,11 +354,12 @@ class MailmanSpip //We call Mailman to subscribe the user $result = $this->callMailman($object, $conf->global->ADHERENT_MAILMAN_URL, $list); - if ($result === false) - { + if ($result === false) { $this->mladded_ko[$list] = $object->email; return -2; - } else $this->mladded_ok[$list] = $object->email; + } else { + $this->mladded_ok[$list] = $object->email; + } } return count($lists); } else { @@ -387,36 +388,32 @@ class MailmanSpip $this->mlremoved_ok = array(); $this->mlremoved_ko = array(); - if (!function_exists("curl_init")) - { + if (!function_exists("curl_init")) { $langs->load("errors"); $this->error = $langs->trans("ErrorFunctionNotAvailableInPHP", "curl_init"); return -1; } - if ($conf->adherent->enabled) // Synchro for members - { - if (!empty($conf->global->ADHERENT_MAILMAN_UNSUB_URL)) - { - if ($listes == '' && !empty($conf->global->ADHERENT_MAILMAN_LISTS)) $lists = explode(',', $conf->global->ADHERENT_MAILMAN_LISTS); - else $lists = explode(',', $listes); + if ($conf->adherent->enabled) { // Synchro for members + if (!empty($conf->global->ADHERENT_MAILMAN_UNSUB_URL)) { + if ($listes == '' && !empty($conf->global->ADHERENT_MAILMAN_LISTS)) { + $lists = explode(',', $conf->global->ADHERENT_MAILMAN_LISTS); + } else { + $lists = explode(',', $listes); + } $categstatic = new Categorie($this->db); - foreach ($lists as $list) - { + foreach ($lists as $list) { // Filter on type something (ADHERENT_MAILMAN_LISTS = "mailinglist0,TYPE:typevalue:mailinglist1,CATEG:categvalue:mailinglist2") $tmp = explode(':', $list); - if (!empty($tmp[2])) - { + if (!empty($tmp[2])) { $list = $tmp[2]; - if ($object->element == 'member' && $tmp[0] == 'TYPE' && $object->type != $tmp[1]) // Filter on member type label - { + if ($object->element == 'member' && $tmp[0] == 'TYPE' && $object->type != $tmp[1]) { // Filter on member type label dol_syslog("We ignore list ".$list." because object member type ".$object->type." does not match ".$tmp[1], LOG_DEBUG); continue; } - if ($object->element == 'member' && $tmp[0] == 'CATEG' && !in_array($tmp[1], $categstatic->containing($object->id, 'member', 'label'))) // Filter on member category - { + if ($object->element == 'member' && $tmp[0] == 'CATEG' && !in_array($tmp[1], $categstatic->containing($object->id, 'member', 'label'))) { // Filter on member category dol_syslog("We ignore list ".$list." because object member is not into category ".$tmp[1], LOG_DEBUG); continue; } @@ -425,11 +422,12 @@ class MailmanSpip //We call Mailman to unsubscribe the user $result = $this->callMailman($object, $conf->global->ADHERENT_MAILMAN_UNSUB_URL, $list); - if ($result === false) - { + if ($result === false) { $this->mlremoved_ko[$list] = $object->email; return -2; - } else $this->mlremoved_ok[$list] = $object->email; + } else { + $this->mlremoved_ok[$list] = $object->email; + } } return count($lists); } else { diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index c91f4802974..f6376a650b7 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -13,6 +13,7 @@ * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr> * Copyright (C) 2020 Demarest Maxime <maxime@indelog.fr> * Copyright (C) 2020 Charlene Benke <charlie@patas-monkey.com> + * Copyright (C) 2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -38,8 +39,7 @@ // For optional tuning. Enabled if environment variable MAIN_SHOW_TUNING_INFO is defined. $micro_start_time = 0; -if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO'])) -{ +if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO'])) { list($usec, $sec) = explode(" ", microtime()); $micro_start_time = ((float) $usec + (float) $sec); // Add Xdebug code coverage @@ -60,12 +60,16 @@ if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO'])) */ function testSqlAndScriptInject($val, $type) { - // Decode string first + // Decode string first bcause a lot of things are obfuscated by encoding or multiple encoding. // So <svg o&#110;load='console.log(&quot;123&quot;)' become <svg onload='console.log(&quot;123&quot;)' // So "&colon;&apos;" become ":'" (due to ENT_HTML5) - $val = html_entity_decode($val, ENT_QUOTES | ENT_HTML5); - - // TODO loop to decode until no more thing to decode ? + // Loop to decode until no more thing to decode. + //print "before decoding $val\n"; + do { + $oldval = $val; + $val = html_entity_decode($val, ENT_QUOTES | ENT_HTML5); + } while ($oldval != $val); + //print "after decoding $val\n"; // We clean string because some hacks try to obfuscate evil strings by inserting non printable chars. Example: 'java(ascci09)scr(ascii00)ipt' is processed like 'javascript' (whatever is place of evil ascii char) // We should use dol_string_nounprintableascii but function is not yet loaded/available @@ -75,8 +79,7 @@ function testSqlAndScriptInject($val, $type) $inj = 0; // For SQL Injection (only GET are used to be included into bad escaped SQL requests) - if ($type == 1 || $type == 3) - { + if ($type == 1 || $type == 3) { $inj += preg_match('/delete\s+from/i', $val); $inj += preg_match('/create\s+table/i', $val); $inj += preg_match('/insert\s+into/i', $val); @@ -86,12 +89,10 @@ function testSqlAndScriptInject($val, $type) $inj += preg_match('/information_schema/i', $val); // avoid to use request that read information_schema database $inj += preg_match('/<svg/i', $val); // <svg can be allowed in POST } - if ($type == 3) - { + if ($type == 3) { $inj += preg_match('/select|update|delete|truncate|replace|group\s+by|concat|count|from|union/i', $val); } - if ($type != 2) // Not common key strings, so we can check them both on GET and POST - { + if ($type != 2) { // Not common key strings, so we can check them both on GET and POST $inj += preg_match('/updatexml\(/i', $val); $inj += preg_match('/update.+set.+=/i', $val); $inj += preg_match('/union.+select/i', $val); @@ -110,7 +111,9 @@ function testSqlAndScriptInject($val, $type) $inj += preg_match('/<object/i', $val); $inj += preg_match('/<script/i', $val); $inj += preg_match('/Set\.constructor/i', $val); // ECMA script 6 - if (!defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val); + if (!defined('NOSTYLECHECK')) { + $inj += preg_match('/<style/i', $val); + } $inj += preg_match('/base\s+href/si', $val); $inj += preg_match('/=data:/si', $val); // List of dom events is on https://www.w3schools.com/jsref/dom_obj_event.asp @@ -119,7 +122,7 @@ function testSqlAndScriptInject($val, $type) $inj += preg_match('/ontouch([a-z]*)\s*=/i', $val); // $inj += preg_match('/on(abort|afterprint|beforeprint|beforeunload|blur|canplay|canplaythrough|change|click|contextmenu|copy|cut)\s*=/i', $val); $inj += preg_match('/on(dblclick|drop|durationchange|ended|error|focus|focusin|focusout|hashchange|input|invalid)\s*=/i', $val); - $inj += preg_match('/on(keydown|keypress|keyup|load|loadeddata|loadedmetadata|loadstart|offline|online|pagehide|pageshow)\s*=/i', $val); + $inj += preg_match('/on(keydown|keypress|keyup|load|loadeddata|loadedmetadata|loadstart|loadend|offline|online|pagehide|pageshow)\s*=/i', $val); $inj += preg_match('/on(paste|pause|play|playing|progress|ratechange|resize|reset|scroll|search|seeking|select|show|stalled|start|submit|suspend)\s*=/i', $val); $inj += preg_match('/on(timeupdate|toggle|unload|volumechange|waiting)\s*=/i', $val); @@ -131,20 +134,24 @@ function testSqlAndScriptInject($val, $type) $inj += preg_match('/ontouch([a-z]*)\s*=/i', $tmpval); // $inj += preg_match('/on(abort|afterprint|beforeprint|beforeunload|blur|canplay|canplaythrough|change|click|contextmenu|copy|cut)\s*=/i', $tmpval); $inj += preg_match('/on(dblclick|drop|durationchange|ended|error|focus|focusin|focusout|hashchange|input|invalid)\s*=/i', $tmpval); - $inj += preg_match('/on(keydown|keypress|keyup|load|loadeddata|loadedmetadata|loadstart|offline|online|pagehide|pageshow)\s*=/i', $tmpval); + $inj += preg_match('/on(keydown|keypress|keyup|load|loadeddata|loadedmetadata|loadstart|loadend|offline|online|pagehide|pageshow)\s*=/i', $tmpval); $inj += preg_match('/on(paste|pause|play|playing|progress|ratechange|resize|reset|scroll|search|seeking|select|show|stalled|start|submit|suspend)\s*=/i', $tmpval); $inj += preg_match('/on(timeupdate|toggle|unload|volumechange|waiting)\s*=/i', $tmpval); //$inj += preg_match('/on[A-Z][a-z]+\*=/', $val); // To lock event handlers onAbort(), ... $inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val); // refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...' + $inj += preg_match('/javascript\s*:/i', $val); $inj += preg_match('/vbscript\s*:/i', $val); // For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param) if ($type == 1) { - $val = str_replace('enclosure="', 'enclosure=X', $val); // We accept enclosure=" + $val = str_replace('enclosure="', 'enclosure=X', $val); // We accept enclosure=" for the export/import module $inj += preg_match('/"/i', $val); // We refused " in GET parameters value. } - if ($type == 2) $inj += preg_match('/[;"]/', $val); // PHP_SELF is a file system path. It can contains spaces. + if ($type == 2) { + $inj += preg_match('/[;"]/', $val); // PHP_SELF is a file system path. It can contains spaces. + } + return $inj; } @@ -157,17 +164,14 @@ function testSqlAndScriptInject($val, $type) */ function analyseVarsForSqlAndScriptsInjection(&$var, $type) { - if (is_array($var)) - { - foreach ($var as $key => $value) // Warning, $key may also be used for attacks - { - if (analyseVarsForSqlAndScriptsInjection($key, $type) && analyseVarsForSqlAndScriptsInjection($value, $type)) - { + if (is_array($var)) { + foreach ($var as $key => $value) { // Warning, $key may also be used for attacks + if (analyseVarsForSqlAndScriptsInjection($key, $type) && analyseVarsForSqlAndScriptsInjection($value, $type)) { //$var[$key] = $value; // This is useless } else { // Get remote IP: PS: We do not use getRemoteIP(), function is not yet loaded and we need a value that can't be spoofed $ip = (empty($_SERVER['REMOTE_ADDR']) ? 'unknown' : $_SERVER['REMOTE_ADDR']); - $errormessage = 'Access refused to '.$ip.' by SQL or Script injection protection in main.inc.php (type='.htmlentities($type).' key='.htmlentities($key).' value='.htmlentities($value).' page='.htmlentities($_SERVER["REQUEST_URI"]).')'; + $errormessage = 'Access refused to '.$ip.' by SQL or Script injection protection in main.inc.php - GETPOST type='.htmlentities($type).' paramkey='.htmlentities($key).' paramvalue='.htmlentities($value).' page='.htmlentities($_SERVER["REQUEST_URI"]); print $errormessage; // Add entry into error log if (function_exists('error_log')) { @@ -185,21 +189,22 @@ function analyseVarsForSqlAndScriptsInjection(&$var, $type) // Check consistency of NOREQUIREXXX DEFINES -if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && !defined('NOREQUIREMENU')) -{ - print 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not set them'; +if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && !defined('NOREQUIREMENU')) { + print 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not set them.'; + exit; +} +if (defined('NOREQUIREUSER') && !defined('NOREQUIREMENU')) { + print 'If define NOREQUIREUSER is set, you must also set NOREQUIREMENU or not set it.'; exit; } // Sanity check on URL -if (!empty($_SERVER["PHP_SELF"])) -{ +if (!empty($_SERVER["PHP_SELF"])) { $morevaltochecklikepost = array($_SERVER["PHP_SELF"]); analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost, 2); } // Sanity check on GET parameters -if (!defined('NOSCANGETFORINJECTION') && !empty($_SERVER["QUERY_STRING"])) -{ +if (!defined('NOSCANGETFORINJECTION') && !empty($_SERVER["QUERY_STRING"])) { // Note: QUERY_STRING is url encoded, but $_GET and $_POST are already decoded // Because the analyseVarsForSqlAndScriptsInjection is designed for already url decoded value, we must decode QUERY_STRING // Another solution is to provide $_GET as parameter @@ -207,14 +212,12 @@ if (!defined('NOSCANGETFORINJECTION') && !empty($_SERVER["QUERY_STRING"])) analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget, 1); } // Sanity check on POST -if (!defined('NOSCANPOSTFORINJECTION')) -{ +if (!defined('NOSCANPOSTFORINJECTION')) { analyseVarsForSqlAndScriptsInjection($_POST, 0); } // This is to make Dolibarr working with Plesk -if (!empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs') -{ +if (!empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs') { set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); } @@ -224,22 +227,24 @@ require_once 'filefunc.inc.php'; // If there is a POST parameter to tell to save automatically some POST parameters into cookies, we do it. // This is used for example by form of boxes to save personalization of some options. // DOL_AUTOSET_COOKIE=cookiename:val1,val2 and cookiename_val1=aaa cookiename_val2=bbb will set cookie_name with value json_encode(array('val1'=> , )) -if (!empty($_POST["DOL_AUTOSET_COOKIE"])) -{ +if (!empty($_POST["DOL_AUTOSET_COOKIE"])) { $tmpautoset = explode(':', $_POST["DOL_AUTOSET_COOKIE"], 2); $tmplist = explode(',', $tmpautoset[1]); $cookiearrayvalue = array(); - foreach ($tmplist as $tmpkey) - { + foreach ($tmplist as $tmpkey) { $postkey = $tmpautoset[0].'_'.$tmpkey; //var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]); - if (!empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey] = $_POST[$postkey]; + if (!empty($_POST[$postkey])) { + $cookiearrayvalue[$tmpkey] = $_POST[$postkey]; + } } $cookiename = $tmpautoset[0]; $cookievalue = json_encode($cookiearrayvalue); //var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue); setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, empty($cookievalue) ? 0 : (time() + (86400 * 354)), '/', null, false, true); // keep cookie 1 year and add tag httponly - if (empty($cookievalue)) unset($_COOKIE[$cookiename]); + if (empty($cookievalue)) { + unset($_COOKIE[$cookiename]); + } } @@ -254,11 +259,12 @@ if (ini_get('session.save_handler') == 'user') { $prefix = dol_getprefix(''); $sessionname = 'DOLSESSID_'.$prefix; $sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix; -if (!empty($_COOKIE[$sessiontimeout])) ini_set('session.gc_maxlifetime', $_COOKIE[$sessiontimeout]); +if (!empty($_COOKIE[$sessiontimeout])) { + ini_set('session.gc_maxlifetime', $_COOKIE[$sessiontimeout]); +} // This create lock, released by session_write_close() or end of page. // We need this lock as long as we read/write $_SESSION ['vars']. We can remove lock when finished. -if (!defined('NOSESSION')) -{ +if (!defined('NOSESSION')) { session_set_cookie_params(0, '/', null, (empty($dolibarr_main_force_https) ? false : true), true); // Add tag secure and httponly on session cookie (same as setting session.cookie_httponly into php.ini). Must be called before the session_start. session_name($sessionname); session_start(); @@ -270,18 +276,21 @@ require_once 'master.inc.php'; // If software has been locked. Only login $conf->global->MAIN_ONLY_LOGIN_ALLOWED is allowed. -if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) -{ +if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) { $ok = 0; - if ((!session_id() || !isset($_SESSION["dol_login"])) && !isset($_POST["username"]) && !empty($_SERVER["GATEWAY_INTERFACE"])) $ok = 1; // We let working pages if not logged and inside a web browser (login form, to allow login by admin) - elseif (isset($_POST["username"]) && $_POST["username"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok = 1; // We let working pages that is a login submission (login submit, to allow login by admin) - elseif (defined('NOREQUIREDB')) $ok = 1; // We let working pages that don't need database access (xxx.css.php) - elseif (defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) $ok = 1; // We let working pages that ask to work even if only login enabled (logout.php) - elseif (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok = 1; // We let working if user is allowed admin - if (!$ok) - { - if (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] != $conf->global->MAIN_ONLY_LOGIN_ALLOWED) - { + if ((!session_id() || !isset($_SESSION["dol_login"])) && !isset($_POST["username"]) && !empty($_SERVER["GATEWAY_INTERFACE"])) { + $ok = 1; // We let working pages if not logged and inside a web browser (login form, to allow login by admin) + } elseif (isset($_POST["username"]) && $_POST["username"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) { + $ok = 1; // We let working pages that is a login submission (login submit, to allow login by admin) + } elseif (defined('NOREQUIREDB')) { + $ok = 1; // We let working pages that don't need database access (xxx.css.php) + } elseif (defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) { + $ok = 1; // We let working pages that ask to work even if only login enabled (logout.php) + } elseif (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) { + $ok = 1; // We let working if user is allowed admin + } + if (!$ok) { + if (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] != $conf->global->MAIN_ONLY_LOGIN_ALLOWED) { print 'Sorry, your application is offline.'."\n"; print 'You are logged with user "'.$_SESSION["dol_login"].'" and only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n"; $nexturl = DOL_URL_ROOT.'/user/logout.php'; @@ -300,21 +309,21 @@ if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) register_shutdown_function('dol_shutdown'); // Load debugbar -if (!empty($conf->debugbar->enabled) && !GETPOST('dol_use_jmobile') && empty($_SESSION['dol_use_jmobile'])) -{ +if (!empty($conf->debugbar->enabled) && !GETPOST('dol_use_jmobile') && empty($_SESSION['dol_use_jmobile'])) { global $debugbar; include_once DOL_DOCUMENT_ROOT.'/debugbar/class/DebugBar.php'; $debugbar = new DolibarrDebugBar(); $renderer = $debugbar->getRenderer(); - if (empty($conf->global->MAIN_HTML_HEADER)) $conf->global->MAIN_HTML_HEADER = ''; + if (empty($conf->global->MAIN_HTML_HEADER)) { + $conf->global->MAIN_HTML_HEADER = ''; + } $conf->global->MAIN_HTML_HEADER .= $renderer->renderHead(); $debugbar['time']->startMeasure('pageaftermaster', 'Page generation (after environment init)'); } // Detection browser -if (isset($_SERVER["HTTP_USER_AGENT"])) -{ +if (isset($_SERVER["HTTP_USER_AGENT"])) { $tmp = getBrowserInfo($_SERVER["HTTP_USER_AGENT"]); $conf->browser->name = $tmp['browsername']; $conf->browser->os = $tmp['browseros']; @@ -322,26 +331,23 @@ if (isset($_SERVER["HTTP_USER_AGENT"])) $conf->browser->layout = $tmp['layout']; // 'classic', 'phone', 'tablet' //var_dump($conf->browser); - if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover = 1; + if ($conf->browser->layout == 'phone') { + $conf->dol_no_mouse_hover = 1; + } } // Set global MAIN_OPTIMIZEFORTEXTBROWSER (must be before login part) -if (GETPOST('textbrowser', 'int') || (!empty($conf->browser->name) && $conf->browser->name == 'lynxlinks')) // If we must enable text browser -{ +if (GETPOST('textbrowser', 'int') || (!empty($conf->browser->name) && $conf->browser->name == 'lynxlinks')) { // If we must enable text browser $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER = 1; } // Force HTTPS if required ($conf->file->main_force_https is 0/1 or 'https dolibarr root url') // $_SERVER["HTTPS"] is 'on' when link is https, otherwise $_SERVER["HTTPS"] is empty or 'off' -if (!empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != 'on')) -{ +if (!empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != 'on')) { $newurl = ''; - if (is_numeric($conf->file->main_force_https)) - { - if ($conf->file->main_force_https == '1' && !empty($_SERVER["SCRIPT_URI"])) // If SCRIPT_URI supported by server - { - if (preg_match('/^http:/i', $_SERVER["SCRIPT_URI"]) && !preg_match('/^https:/i', $_SERVER["SCRIPT_URI"])) // If link is http - { + if (is_numeric($conf->file->main_force_https)) { + if ($conf->file->main_force_https == '1' && !empty($_SERVER["SCRIPT_URI"])) { // If SCRIPT_URI supported by server + if (preg_match('/^http:/i', $_SERVER["SCRIPT_URI"]) && !preg_match('/^https:/i', $_SERVER["SCRIPT_URI"])) { // If link is http $newurl = preg_replace('/^http:/i', 'https:', $_SERVER["SCRIPT_URI"]); } } else { @@ -353,8 +359,7 @@ if (!empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SERV $newurl = $conf->file->main_force_https.$_SERVER["REQUEST_URI"]; } // Start redirect - if ($newurl) - { + if ($newurl) { header_remove(); // Clean header already set to be sure to remove any header like "Set-Cookie: DOLSESSID_..." from non HTTPS answers dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl); header("Location: ".$newurl); @@ -364,48 +369,45 @@ if (!empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SERV } } -if (!defined('NOLOGIN') && !defined('NOIPCHECK') && !empty($dolibarr_main_restrict_ip)) -{ +if (!defined('NOLOGIN') && !defined('NOIPCHECK') && !empty($dolibarr_main_restrict_ip)) { $listofip = explode(',', $dolibarr_main_restrict_ip); $found = false; - foreach ($listofip as $ip) - { + foreach ($listofip as $ip) { $ip = trim($ip); - if ($ip == $_SERVER['REMOTE_ADDR']) - { + if ($ip == $_SERVER['REMOTE_ADDR']) { $found = true; break; } } - if (!$found) - { + if (!$found) { print 'Access refused by IP protection. Your detected IP is '.$_SERVER['REMOTE_ADDR']; exit; } } // Loading of additional presentation includes -if (!defined('NOREQUIREHTML')) require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // Need 660ko memory (800ko in 2.2) -if (!defined('NOREQUIREAJAX')) require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; // Need 22ko memory +if (!defined('NOREQUIREHTML')) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // Need 660ko memory (800ko in 2.2) +} +if (!defined('NOREQUIREAJAX')) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; // Need 22ko memory +} // If install or upgrade process not done or not completely finished, we call the install page. -if (!empty($conf->global->MAIN_NOT_INSTALLED) || !empty($conf->global->MAIN_NOT_UPGRADED)) -{ +if (!empty($conf->global->MAIN_NOT_INSTALLED) || !empty($conf->global->MAIN_NOT_UPGRADED)) { dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING); header("Location: ".DOL_URL_ROOT."/install/index.php"); exit; } // If an upgrade process is required, we call the install page. if ((!empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION)) -|| (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && !empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION))) -{ +|| (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && !empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION))) { $versiontocompare = empty($conf->global->MAIN_VERSION_LAST_UPGRADE) ? $conf->global->MAIN_VERSION_LAST_INSTALL : $conf->global->MAIN_VERSION_LAST_UPGRADE; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; $dolibarrversionlastupgrade = preg_split('/[.-]/', $versiontocompare); $dolibarrversionprogram = preg_split('/[.-]/', DOL_VERSION); $rescomp = versioncompare($dolibarrversionprogram, $dolibarrversionlastupgrade); - if ($rescomp > 0) // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades - { + if ($rescomp > 0) { // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING); header("Location: ".DOL_URL_ROOT."/install/index.php"); exit; @@ -413,28 +415,29 @@ if ((!empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VE } // Creation of a token against CSRF vulnerabilities -if (!defined('NOTOKENRENEWAL')) -{ +if (!defined('NOTOKENRENEWAL')) { // Rolling token at each call ($_SESSION['token'] contains token of previous page) - if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken']; + if (isset($_SESSION['newtoken'])) { + $_SESSION['token'] = $_SESSION['newtoken']; + } - // Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken'] + // Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = newToken(); $token = dol_hash(uniqid(mt_rand(), true)); // Generates a hash of a random number $_SESSION['newtoken'] = $token; + dol_syslog("NEW TOKEN reclaimed by : " . $_SERVER['PHP_SELF'], LOG_DEBUG); } //dol_syslog("aaaa - ".defined('NOCSRFCHECK')." - ".$dolibarr_nocsrfcheck." - ".$conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN." - ".$_SERVER['REQUEST_METHOD']." - ".GETPOST('token', 'alpha').' '.$_SESSION['token']); -//$dolibarr_nocsrfcheck=1; -// Check token -if ((!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && !empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN)) - || defined('CSRFCHECK_WITH_TOKEN')) // Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set into page -{ - // Check all cases that need a token (all POST actions, all actions and mass actions on pages with CSRFCHECK_WITH_TOKEN set, all sensitive GET actions) - if ($_SERVER['REQUEST_METHOD'] == 'POST' || - ((GETPOSTISSET('action') || GETPOSTISSET('massaction')) && defined('CSRFCHECK_WITH_TOKEN')) || - in_array(GETPOST('action', 'aZ09'), array('add', 'addtimespent', 'update', 'install', 'delete', 'deletefilter', 'deleteoperation', 'deleteprof', 'deletepayment', 'confirm_create_user', 'confirm_create_thirdparty', 'confirm_reject_check'))) - { - if (!GETPOSTISSET('token')) { + +// Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set into page +if ((!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && !empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN)) || defined('CSRFCHECK_WITH_TOKEN')) { + // Check all cases that need a token (all POST actions + all login, actions and mass actions on pages with CSRFCHECK_WITH_TOKEN set + all sensitive GET actions) + if ( + $_SERVER['REQUEST_METHOD'] == 'POST' || + ((GETPOSTISSET('actionlogin') || GETPOSTISSET('action') || GETPOSTISSET('massaction')) && defined('CSRFCHECK_WITH_TOKEN')) || + in_array(GETPOST('action', 'aZ09'), array('add', 'addtimespent', 'update', 'install', 'delete', 'deletefilter', 'deleteoperation', 'deleteprof', 'deletepayment', 'confirm_create_user', 'confirm_create_thirdparty', 'confirm_reject_check')) + ) { + if (!GETPOST('token', 'alpha')) { // If token is not provided or empty if (GETPOST('uploadform', 'int')) { dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." refused. File size too large."); $langs->loadLangs(array("errors", "install")); @@ -454,8 +457,7 @@ if ((!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && !empty($conf->gl } } - if (GETPOSTISSET('token') && GETPOST('token', 'alpha') != $_SESSION['token']) - { + if (GETPOSTISSET('token') && GETPOST('token', 'alpha') != $_SESSION['token']) { dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." refused due to invalid token, so we disable POST and some GET parameters - referer=".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action', 'aZ09').", _GET|POST['token']=".GETPOST('token', 'alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING); //print 'Unset POST by CSRF protection in main.inc.php.'; // Do not output anything because this create problems when using the BACK button on browsers. setEventMessages('SecurityTokenHasExpiredSoActionHasBeenCanceledPleaseRetry', null, 'warnings'); @@ -470,27 +472,28 @@ if ((!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && !empty($conf->gl unset($_GET['massaction']); $_POST['id'] = ((int) $savid); } + + // Note: There is another CSRF protection into the filefunc.inc.php } // Disable modules (this must be after session_start and after conf has been loaded) -if (GETPOSTISSET('disablemodules')) $_SESSION["disablemodules"] = GETPOST('disablemodules', 'alpha'); -if (!empty($_SESSION["disablemodules"])) -{ +if (GETPOSTISSET('disablemodules')) { + $_SESSION["disablemodules"] = GETPOST('disablemodules', 'alpha'); +} +if (!empty($_SESSION["disablemodules"])) { $modulepartkeys = array('css', 'js', 'tabs', 'triggers', 'login', 'substitutions', 'menus', 'theme', 'sms', 'tpl', 'barcode', 'models', 'societe', 'hooks', 'dir', 'syslog', 'tpllinkable', 'contactelement', 'moduleforexternal'); $disabled_modules = explode(',', $_SESSION["disablemodules"]); - foreach ($disabled_modules as $module) - { - if ($module) - { - if (empty($conf->$module)) $conf->$module = new stdClass(); // To avoid warnings + foreach ($disabled_modules as $module) { + if ($module) { + if (empty($conf->$module)) { + $conf->$module = new stdClass(); // To avoid warnings + } $conf->$module->enabled = false; - foreach ($modulepartkeys as $modulepartkey) - { + foreach ($modulepartkeys as $modulepartkey) { unset($conf->modules_parts[$modulepartkey][$module]); } - if ($module == 'fournisseur') // Special case - { + if ($module == 'fournisseur') { // Special case $conf->supplier_order->enabled = 0; $conf->supplier_invoice->enabled = 0; } @@ -500,12 +503,9 @@ if (!empty($_SESSION["disablemodules"])) // Set current modulepart $modulepart = explode("/", $_SERVER["PHP_SELF"]); -if (is_array($modulepart) && count($modulepart) > 0) -{ - foreach ($conf->modules as $module) - { - if (in_array($module, $modulepart)) - { +if (is_array($modulepart) && count($modulepart) > 0) { + foreach ($conf->modules as $module) { + if (in_array($module, $modulepart)) { $conf->modulepart = $module; break; } @@ -516,26 +516,27 @@ if (is_array($modulepart) && count($modulepart) > 0) * Phase authentication / login */ $login = ''; -if (!defined('NOLOGIN')) -{ +if (!defined('NOLOGIN')) { // $authmode lists the different method of identification to be tested in order of preference. // Example: 'http', 'dolibarr', 'ldap', 'http,forceuser', '...' - if (defined('MAIN_AUTHENTICATION_MODE')) - { + if (defined('MAIN_AUTHENTICATION_MODE')) { $dolibarr_main_authentication = constant('MAIN_AUTHENTICATION_MODE'); } else { // Authentication mode - if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'http,dolibarr'; + if (empty($dolibarr_main_authentication)) { + $dolibarr_main_authentication = 'http,dolibarr'; + } // Authentication mode: forceuser - if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto'; + if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) { + $dolibarr_auto_user = 'auto'; + } } // Set authmode $authmode = explode(',', $dolibarr_main_authentication); // No authentication mode - if (!count($authmode)) - { + if (!count($authmode)) { $langs->load('main'); dol_print_error('', $langs->trans("ErrorConfigParameterNotDefined", 'dolibarr_main_authentication')); exit; @@ -546,8 +547,7 @@ if (!defined('NOLOGIN')) // At the end of this phase, the variable $login is defined. $resultFetchUser = ''; $test = true; - if (!isset($_SESSION["dol_login"])) - { + if (!isset($_SESSION["dol_login"])) { // It is not already authenticated and it requests the login / password include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; @@ -564,10 +564,8 @@ if (!defined('NOLOGIN')) //dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,',')); // If in demo mode, we check we go to home page through the public/demo/index.php page - if (!empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php') // We ask index page - { - if (empty($_SERVER['HTTP_REFERER']) || !preg_match('/public/', $_SERVER['HTTP_REFERER'])) - { + if (!empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php') { // We ask index page + if (empty($_SERVER['HTTP_REFERER']) || !preg_match('/public/', $_SERVER['HTTP_REFERER'])) { dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")"); $url = ''; $url .= ($url ? '&' : '').($dol_hide_topmenu ? 'dol_hide_topmenu='.$dol_hide_topmenu : ''); @@ -587,19 +585,17 @@ if (!defined('NOLOGIN')) $parameters = array(); $reshook = $hookmanager->executeHooks('beforeLoginAuthentication', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { - $test = false; - $error++; + $test = false; + $error++; } // Verification security graphic code - if ($test && GETPOST("username", "alpha", 2) && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA) && !isset($_SESSION['dol_bypass_antispam'])) - { + if ($test && GETPOST("username", "alpha", 2) && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA) && !isset($_SESSION['dol_bypass_antispam'])) { $sessionkey = 'dol_antispam_value'; - $ok = (array_key_exists($sessionkey, $_SESSION) === true && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code']))); + $ok = (array_key_exists($sessionkey, $_SESSION) === true && (strtolower($_SESSION[$sessionkey]) === strtolower(GETPOST('code', 'none')))); // Check code - if (!$ok) - { + if (!$ok) { dol_syslog('Bad value for code, connexion refused'); // Load translation files required by page $langs->loadLangs(array('main', 'errors')); @@ -612,7 +608,9 @@ if (!defined('NOLOGIN')) // Call trigger $result = $user->call_trigger('USER_LOGIN_FAILED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers // Hooks on failed login @@ -620,45 +618,54 @@ if (!defined('NOLOGIN')) $hookmanager->initHooks(array('login')); $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]); $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } // Note: exit is done later } } $allowedmethodtopostusername = 2; - if (defined('MAIN_AUTHENTICATION_POST_METHOD')) $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD'); + if (defined('MAIN_AUTHENTICATION_POST_METHOD')) { + $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD'); + } $usertotest = (!empty($_COOKIE['login_dolibarr']) ? preg_replace('/[^a-zA-Z0-9_\-]/', '', $_COOKIE['login_dolibarr']) : GETPOST("username", "alpha", $allowedmethodtopostusername)); $passwordtotest = GETPOST('password', 'none', $allowedmethodtopostusername); $entitytotest = (GETPOST('entity', 'int') ? GETPOST('entity', 'int') : (!empty($conf->entity) ? $conf->entity : 1)); // Define if we received data to test the login. $goontestloop = false; - if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) $goontestloop = true; - if ($dolibarr_main_authentication == 'forceuser' && !empty($dolibarr_auto_user)) $goontestloop = true; - if (GETPOST("username", "alpha", $allowedmethodtopostusername) || !empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode', 'alpha', 1)) $goontestloop = true; + if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) { + $goontestloop = true; + } + if ($dolibarr_main_authentication == 'forceuser' && !empty($dolibarr_auto_user)) { + $goontestloop = true; + } + if (GETPOST("username", "alpha", $allowedmethodtopostusername) || !empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode', 'alpha', 1)) { + $goontestloop = true; + } - if (!is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages. - { + if (!is_object($langs)) { // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; $langs = new Translate("", $conf); $langcode = (GETPOST('lang', 'aZ09', 1) ?GETPOST('lang', 'aZ09', 1) : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT)); - if (defined('MAIN_LANG_DEFAULT')) $langcode = constant('MAIN_LANG_DEFAULT'); + if (defined('MAIN_LANG_DEFAULT')) { + $langcode = constant('MAIN_LANG_DEFAULT'); + } $langs->setDefaultLang($langcode); } // Validation of login/pass/entity // If ok, the variable login will be returned // If error, we will put error message in session under the name dol_loginmesg - if ($test && $goontestloop && (GETPOST('actionlogin', 'aZ09') == 'login' || $dolibarr_main_authentication != 'dolibarr')) - { + if ($test && $goontestloop && (GETPOST('actionlogin', 'aZ09') == 'login' || $dolibarr_main_authentication != 'dolibarr')) { $login = checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode); if ($login === '--bad-login-validity--') { $login = ''; } - if ($login) - { + if ($login) { $dol_authmode = $conf->authmode; // This properties is defined only when logged, to say what mode was successfully used $dol_tz = $_POST["tz"]; $dol_tz_string = $_POST["tz_string"]; @@ -667,33 +674,37 @@ if (!defined('NOLOGIN')) $dol_tz_string = preg_replace('/\s/', '_', $dol_tz_string); $dol_dst = 0; // Keep $_POST here. Do not use GETPOSTISSET - if (isset($_POST["dst_first"]) && isset($_POST["dst_second"])) - { + if (isset($_POST["dst_first"]) && isset($_POST["dst_second"])) { include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $datenow = dol_now(); $datefirst = dol_stringtotime($_POST["dst_first"]); $datesecond = dol_stringtotime($_POST["dst_second"]); - if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst = 1; + if ($datenow >= $datefirst && $datenow < $datesecond) { + $dol_dst = 1; + } } //print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit; } - if (!$login) - { + if (!$login) { dol_syslog('Bad password, connexion refused', LOG_DEBUG); // Load translation files required by page $langs->loadLangs(array('main', 'errors')); // Bad password. No authmode has found a good password. // We set a generic message if not defined inside function checkLoginPassEntity or subfunctions - if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"] = $langs->trans("ErrorBadLoginPassword"); + if (empty($_SESSION["dol_loginmesg"])) { + $_SESSION["dol_loginmesg"] = $langs->trans("ErrorBadLoginPassword"); + } // Call trigger for the "security events" log $user->trigger_mesg = $langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username", "alpha", 2); // Call trigger $result = $user->call_trigger('USER_LOGIN_FAILED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers // Hooks on failed login @@ -701,19 +712,21 @@ if (!defined('NOLOGIN')) $hookmanager->initHooks(array('login')); $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]); $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } // Note: exit is done in next chapter } } // End test login / passwords - if (!$login || (in_array('ldap', $authmode) && empty($passwordtotest))) // With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success. - { + if (!$login || (in_array('ldap', $authmode) && empty($passwordtotest))) { // With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success. // No data to test login, so we show the login page. dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." - action=".GETPOST('action', 'aZ09')." - actionlogin=".GETPOST('actionlogin', 'aZ09')." - showing the login form and exit"); - if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED'; - else { + if (defined('NOREDIRECTBYMAINTOLOGIN')) { + return 'ERROR_NOT_LOGGED'; + } else { if ($_SERVER["HTTP_USER_AGENT"] == 'securitytest') { http_response_code(401); // It makes easier to understand if session was broken during security tests } @@ -723,16 +736,14 @@ if (!defined('NOLOGIN')) } $resultFetchUser = $user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1)); // login was retrieved previously when checking password. - if ($resultFetchUser <= 0) - { + if ($resultFetchUser <= 0) { dol_syslog('User not found, connexion refused'); session_destroy(); session_set_cookie_params(0, '/', null, (empty($dolibarr_main_force_https) ? false : true), true); // Add tag secure and httponly on session cookie session_name($sessionname); session_start(); - if ($resultFetchUser == 0) - { + if ($resultFetchUser == 0) { // Load translation files required by page $langs->loadLangs(array('main', 'errors')); @@ -740,8 +751,7 @@ if (!defined('NOLOGIN')) $user->trigger_mesg = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login; } - if ($resultFetchUser < 0) - { + if ($resultFetchUser < 0) { $_SESSION["dol_loginmesg"] = $user->error; $user->trigger_mesg = $user->error; @@ -749,7 +759,9 @@ if (!defined('NOLOGIN')) // Call trigger $result = $user->call_trigger('USER_LOGIN_FAILED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers @@ -758,12 +770,20 @@ if (!defined('NOLOGIN')) $hookmanager->initHooks(array('login')); $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]); $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } $paramsurl = array(); - if (GETPOST('textbrowser', 'int')) $paramsurl[] = 'textbrowser='.GETPOST('textbrowser', 'int'); - if (GETPOST('nojs', 'int')) $paramsurl[] = 'nojs='.GETPOST('nojs', 'int'); - if (GETPOST('lang', 'aZ09')) $paramsurl[] = 'lang='.GETPOST('lang', 'aZ09'); + if (GETPOST('textbrowser', 'int')) { + $paramsurl[] = 'textbrowser='.GETPOST('textbrowser', 'int'); + } + if (GETPOST('nojs', 'int')) { + $paramsurl[] = 'nojs='.GETPOST('nojs', 'int'); + } + if (GETPOST('lang', 'aZ09')) { + $paramsurl[] = 'lang='.GETPOST('lang', 'aZ09'); + } header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : '')); exit; } else { @@ -775,12 +795,11 @@ if (!defined('NOLOGIN')) } else { // We are already into an authenticated session $login = $_SESSION["dol_login"]; - $entity = $_SESSION["dol_entity"]; + $entity = isset($_SESSION["dol_entity"]) ? $_SESSION["dol_entity"] : 0; dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG); $resultFetchUser = $user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1)); - if ($resultFetchUser <= 0) - { + if ($resultFetchUser <= 0) { // Account has been removed after login dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING); session_destroy(); @@ -788,8 +807,7 @@ if (!defined('NOLOGIN')) session_name($sessionname); session_start(); - if ($resultFetchUser == 0) - { + if ($resultFetchUser == 0) { // Load translation files required by page $langs->loadLangs(array('main', 'errors')); @@ -797,8 +815,7 @@ if (!defined('NOLOGIN')) $user->trigger_mesg = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login; } - if ($resultFetchUser < 0) - { + if ($resultFetchUser < 0) { $_SESSION["dol_loginmesg"] = $user->error; $user->trigger_mesg = $user->error; @@ -806,7 +823,9 @@ if (!defined('NOLOGIN')) // Call trigger $result = $user->call_trigger('USER_LOGIN_FAILED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers // Hooks on failed login @@ -814,12 +833,20 @@ if (!defined('NOLOGIN')) $hookmanager->initHooks(array('login')); $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]); $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } $paramsurl = array(); - if (GETPOST('textbrowser', 'int')) $paramsurl[] = 'textbrowser='.GETPOST('textbrowser', 'int'); - if (GETPOST('nojs', 'int')) $paramsurl[] = 'nojs='.GETPOST('nojs', 'int'); - if (GETPOST('lang', 'aZ09')) $paramsurl[] = 'lang='.GETPOST('lang', 'aZ09'); + if (GETPOST('textbrowser', 'int')) { + $paramsurl[] = 'textbrowser='.GETPOST('textbrowser', 'int'); + } + if (GETPOST('nojs', 'int')) { + $paramsurl[] = 'nojs='.GETPOST('nojs', 'int'); + } + if (GETPOST('lang', 'aZ09')) { + $paramsurl[] = 'lang='.GETPOST('lang', 'aZ09'); + } header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : '')); exit; } else { @@ -827,34 +854,31 @@ if (!defined('NOLOGIN')) $hookmanager->initHooks(array('main')); // Code for search criteria persistence. - if (!empty($_GET['save_lastsearch_values'])) // We must use $_GET here - { + if (!empty($_GET['save_lastsearch_values'])) { // We must use $_GET here $relativepathstring = preg_replace('/\?.*$/', '', $_SERVER["HTTP_REFERER"]); $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/', '', $relativepathstring); // Get full path except host server // Clean $relativepathstring - if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring); + if (constant('DOL_URL_ROOT')) { + $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring); + } $relativepathstring = preg_replace('/^\//', '', $relativepathstring); $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring); //var_dump($relativepathstring); // We click on a link that leave a page we have to save search criteria, contextpage, limit and page. We save them from tmp to no tmp - if (!empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring])) - { + if (!empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring])) { $_SESSION['lastsearch_values_'.$relativepathstring] = $_SESSION['lastsearch_values_tmp_'.$relativepathstring]; unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]); } - if (!empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring])) - { + if (!empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring])) { $_SESSION['lastsearch_contextpage_'.$relativepathstring] = $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]; unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]); } - if (!empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 0) - { + if (!empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 0) { $_SESSION['lastsearch_page_'.$relativepathstring] = $_SESSION['lastsearch_page_tmp_'.$relativepathstring]; unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]); } - if (!empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit) - { + if (!empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit) { $_SESSION['lastsearch_limit_'.$relativepathstring] = $_SESSION['lastsearch_limit_tmp_'.$relativepathstring]; unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]); } @@ -870,8 +894,7 @@ if (!defined('NOLOGIN')) // Is it a new session that has started ? // If we are here, this means authentication was successfull. - if (!isset($_SESSION["dol_login"])) - { + if (!isset($_SESSION["dol_login"])) { // New session for this login has started. $error = 0; @@ -889,11 +912,21 @@ if (!defined('NOLOGIN')) $_SESSION["dol_company"] = $conf->global->MAIN_INFO_SOCIETE_NOM; $_SESSION["dol_entity"] = $conf->entity; // Store value into session (values stored only if defined) - if (!empty($dol_hide_topmenu)) $_SESSION['dol_hide_topmenu'] = $dol_hide_topmenu; - if (!empty($dol_hide_leftmenu)) $_SESSION['dol_hide_leftmenu'] = $dol_hide_leftmenu; - if (!empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen'] = $dol_optimize_smallscreen; - if (!empty($dol_no_mouse_hover)) $_SESSION['dol_no_mouse_hover'] = $dol_no_mouse_hover; - if (!empty($dol_use_jmobile)) $_SESSION['dol_use_jmobile'] = $dol_use_jmobile; + if (!empty($dol_hide_topmenu)) { + $_SESSION['dol_hide_topmenu'] = $dol_hide_topmenu; + } + if (!empty($dol_hide_leftmenu)) { + $_SESSION['dol_hide_leftmenu'] = $dol_hide_leftmenu; + } + if (!empty($dol_optimize_smallscreen)) { + $_SESSION['dol_optimize_smallscreen'] = $dol_optimize_smallscreen; + } + if (!empty($dol_no_mouse_hover)) { + $_SESSION['dol_no_mouse_hover'] = $dol_no_mouse_hover; + } + if (!empty($dol_use_jmobile)) { + $_SESSION['dol_use_jmobile'] = $dol_use_jmobile; + } dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id()); @@ -908,7 +941,9 @@ if (!defined('NOLOGIN')) // Call trigger $result = $user->call_trigger('USER_LOGIN', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers // Hooks on successfull login @@ -916,10 +951,11 @@ if (!defined('NOLOGIN')) $hookmanager->initHooks(array('login')); $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo); $reshook = $hookmanager->executeHooks('afterLogin', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } - if ($error) - { + if ($error) { $db->rollback(); session_destroy(); dol_print_error($db, 'Error in some triggers USER_LOGIN or in some hooks afterLogin'); @@ -930,11 +966,9 @@ if (!defined('NOLOGIN')) // Change landing page if defined. $landingpage = (empty($user->conf->MAIN_LANDING_PAGE) ? (empty($conf->global->MAIN_LANDING_PAGE) ? '' : $conf->global->MAIN_LANDING_PAGE) : $user->conf->MAIN_LANDING_PAGE); - if (!empty($landingpage)) // Example: /index.php - { + if (!empty($landingpage)) { // Example: /index.php $newpath = dol_buildpath($landingpage, 1); - if ($_SERVER["PHP_SELF"] != $newpath) // not already on landing page (avoid infinite loop) - { + if ($_SERVER["PHP_SELF"] != $newpath) { // not already on landing page (avoid infinite loop) header('Location: '.$newpath); exit; } @@ -943,8 +977,7 @@ if (!defined('NOLOGIN')) // If user admin, we force the rights-based modules - if ($user->admin) - { + if ($user->admin) { $user->rights->user->user->lire = 1; $user->rights->user->user->creer = 1; $user->rights->user->user->password = 1; @@ -954,24 +987,26 @@ if (!defined('NOLOGIN')) } /* - * Overwrite some configs globals (try to avoid this and have code to use instead $user->conf->xxx) - */ + * Overwrite some configs globals (try to avoid this and have code to use instead $user->conf->xxx) + */ // Set liste_limit - if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT)) $conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT; // Can be 0 - if (isset($user->conf->PRODUIT_LIMIT_SIZE)) $conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE; // Can be 0 + if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT)) { + $conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT; // Can be 0 + } + if (isset($user->conf->PRODUIT_LIMIT_SIZE)) { + $conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE; // Can be 0 + } // Replace conf->css by personalized value if theme not forced - if (empty($conf->global->MAIN_FORCETHEME) && !empty($user->conf->MAIN_THEME)) - { + if (empty($conf->global->MAIN_FORCETHEME) && !empty($user->conf->MAIN_THEME)) { $conf->theme = $user->conf->MAIN_THEME; $conf->css = "/theme/".$conf->theme."/style.css.php"; } } // Case forcing style from url -if (GETPOST('theme', 'alpha')) -{ +if (GETPOST('theme', 'alpha')) { $conf->theme = GETPOST('theme', 'alpha', 1); $conf->css = "/theme/".$conf->theme."/style.css.php"; } @@ -994,54 +1029,58 @@ if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && !empty($user->conf->MAI $conf->global->MAIN_OPTIMIZEFORCOLORBLIND = empty($user->conf->MAIN_OPTIMIZEFORCOLORBLIND) ? '' : $user->conf->MAIN_OPTIMIZEFORCOLORBLIND; // Set terminal output option according to conf->browser. -if (GETPOST('dol_hide_leftmenu', 'int') || !empty($_SESSION['dol_hide_leftmenu'])) $conf->dol_hide_leftmenu = 1; -if (GETPOST('dol_hide_topmenu', 'int') || !empty($_SESSION['dol_hide_topmenu'])) $conf->dol_hide_topmenu = 1; -if (GETPOST('dol_optimize_smallscreen', 'int') || !empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen = 1; -if (GETPOST('dol_no_mouse_hover', 'int') || !empty($_SESSION['dol_no_mouse_hover'])) $conf->dol_no_mouse_hover = 1; -if (GETPOST('dol_use_jmobile', 'int') || !empty($_SESSION['dol_use_jmobile'])) $conf->dol_use_jmobile = 1; -if (!empty($conf->browser->layout) && $conf->browser->layout != 'classic') $conf->dol_no_mouse_hover = 1; +if (GETPOST('dol_hide_leftmenu', 'int') || !empty($_SESSION['dol_hide_leftmenu'])) { + $conf->dol_hide_leftmenu = 1; +} +if (GETPOST('dol_hide_topmenu', 'int') || !empty($_SESSION['dol_hide_topmenu'])) { + $conf->dol_hide_topmenu = 1; +} +if (GETPOST('dol_optimize_smallscreen', 'int') || !empty($_SESSION['dol_optimize_smallscreen'])) { + $conf->dol_optimize_smallscreen = 1; +} +if (GETPOST('dol_no_mouse_hover', 'int') || !empty($_SESSION['dol_no_mouse_hover'])) { + $conf->dol_no_mouse_hover = 1; +} +if (GETPOST('dol_use_jmobile', 'int') || !empty($_SESSION['dol_use_jmobile'])) { + $conf->dol_use_jmobile = 1; +} +if (!empty($conf->browser->layout) && $conf->browser->layout != 'classic') { + $conf->dol_no_mouse_hover = 1; +} if ((!empty($conf->browser->layout) && $conf->browser->layout == 'phone') || (!empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400) || (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400) -) -{ +) { $conf->dol_optimize_smallscreen = 1; } -// If we force to use jmobile, then we reenable javascript -if (!empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax = 1; // Replace themes bugged with jmobile with eldy -if (!empty($conf->dol_use_jmobile) && in_array($conf->theme, array('bureau2crea', 'cameleo', 'amarok'))) -{ +if (!empty($conf->dol_use_jmobile) && in_array($conf->theme, array('bureau2crea', 'cameleo', 'amarok'))) { $conf->theme = 'eldy'; $conf->css = "/theme/".$conf->theme."/style.css.php"; } -if (!defined('NOREQUIRETRAN')) -{ - if (!GETPOST('lang', 'aZ09')) // If language was not forced on URL - { +if (!defined('NOREQUIRETRAN')) { + if (!GETPOST('lang', 'aZ09')) { // If language was not forced on URL // If user has chosen its own language - if (!empty($user->conf->MAIN_LANG_DEFAULT)) - { + if (!empty($user->conf->MAIN_LANG_DEFAULT)) { // If different than current language //print ">>>".$langs->getDefaultLang()."-".$user->conf->MAIN_LANG_DEFAULT; - if ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT) - { + if ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT) { $langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT); } } } } -if (!defined('NOLOGIN')) -{ +if (!defined('NOLOGIN')) { // If the login is not recovered, it is identified with an account that does not exist. // Hacking attempt? - if (!$user->login) accessforbidden(); + if (!$user->login) { + accessforbidden(); + } // Check if user is active - if ($user->statut < 1) - { + if ($user->statut < 1) { // If not active, we refuse the user $langs->load("other"); dol_syslog("Authentication KO as login is disabled", LOG_NOTICE); @@ -1058,8 +1097,7 @@ dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"])?'':$_SERVER["REQU //dol_syslog("Access to ".$_SERVER["PHP_SELF"].' GET='.join(',',array_keys($_GET)).'->'.join(',',$_GET).' POST:'.join(',',array_keys($_POST)).'->'.join(',',$_POST)); // Load main languages files -if (!defined('NOREQUIRETRAN')) -{ +if (!defined('NOREQUIRETRAN')) { // Load translation files required by page $langs->loadLangs(array('main', 'dict')); } @@ -1076,8 +1114,7 @@ $mesg = ''; $warning = ''; $error = 0; $mesgs = array(); $warnings = array(); $errors = array(); // Constants used to defined number of lines in textarea -if (empty($conf->browser->firefox)) -{ +if (empty($conf->browser->firefox)) { define('ROWS_1', 1); define('ROWS_2', 2); define('ROWS_3', 3); @@ -1102,10 +1139,8 @@ if (empty($conf->browser->firefox)) $heightforframes = 50; // Init menu manager -if (!defined('NOREQUIREMENU')) -{ - if (empty($user->socid)) // If internal user or not defined - { +if (!defined('NOREQUIREMENU')) { + if (empty($user->socid)) { // If internal user or not defined $conf->standard_menu = (empty($conf->global->MAIN_MENU_STANDARD_FORCED) ? (empty($conf->global->MAIN_MENU_STANDARD) ? 'eldy_menu.php' : $conf->global->MAIN_MENU_STANDARD) : $conf->global->MAIN_MENU_STANDARD_FORCED); } else { // If external user @@ -1114,18 +1149,19 @@ if (!defined('NOREQUIREMENU')) // Load the menu manager (only if not already done) $file_menu = $conf->standard_menu; - if (GETPOST('menu', 'alpha')) $file_menu = GETPOST('menu', 'alpha'); // example: menu=eldy_menu.php - if (!class_exists('MenuManager')) - { + if (GETPOST('menu', 'alpha')) { + $file_menu = GETPOST('menu', 'alpha'); // example: menu=eldy_menu.php + } + if (!class_exists('MenuManager')) { $menufound = 0; $dirmenus = array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']); - foreach ($dirmenus as $dirmenu) - { + foreach ($dirmenus as $dirmenu) { $menufound = dol_include_once($dirmenu."standard/".$file_menu); - if (class_exists('MenuManager')) break; + if (class_exists('MenuManager')) { + break; + } } - if (!class_exists('MenuManager')) // If failed to include, we try with standard eldy_menu.php - { + if (!class_exists('MenuManager')) { // If failed to include, we try with standard eldy_menu.php dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING); $file_menu = 'eldy_menu.php'; include_once DOL_DOCUMENT_ROOT."/core/menus/standard/".$file_menu; @@ -1139,8 +1175,7 @@ if (!defined('NOREQUIREMENU')) // Functions -if (!function_exists("llxHeader")) -{ +if (!function_exists("llxHeader")) { /** * Show HTML header HTML + BODY + Top menu + left menu + DIV * @@ -1169,10 +1204,11 @@ if (!function_exists("llxHeader")) $tmpcsstouse = 'sidebar-collapse'.($morecssonbody ? ' '.$morecssonbody : ''); // If theme MD and classic layer, we open the menulayer by default. - if ($conf->theme == 'md' && !in_array($conf->browser->layout, array('phone', 'tablet')) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if ($conf->theme == 'md' && !in_array($conf->browser->layout, array('phone', 'tablet')) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { global $mainmenu; - if ($mainmenu != 'website') $tmpcsstouse = $morecssonbody; // We do not use sidebar-collpase by default to have menuhider open by default. + if ($mainmenu != 'website') { + $tmpcsstouse = $morecssonbody; // We do not use sidebar-collpase by default to have menuhider open by default. + } } if (!empty($conf->global->MAIN_OPTIMIZEFORCOLORBLIND)) { @@ -1182,19 +1218,16 @@ if (!function_exists("llxHeader")) print '<body id="mainbody" class="'.$tmpcsstouse.'">'."\n"; // top menu and left menu area - if (empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) - { + if (empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) { top_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url); } - if (empty($conf->dol_hide_leftmenu)) - { + if (empty($conf->dol_hide_leftmenu)) { left_menu('', $help_url, '', '', 1, $title, 1); // $menumanager is retrieved with a global $menumanager inside this function } // main area - if ($replacemainareaby) - { + if ($replacemainareaby) { print $replacemainareaby; return; } @@ -1214,16 +1247,21 @@ function top_httphead($contenttype = 'text/html', $forcenocache = 0) { global $db, $conf, $hookmanager; - if ($contenttype == 'text/html') header("Content-Type: text/html; charset=".$conf->file->character_set_client); - else header("Content-Type: ".$contenttype); + if ($contenttype == 'text/html') { + header("Content-Type: text/html; charset=".$conf->file->character_set_client); + } else { + header("Content-Type: ".$contenttype); + } // Security options header("X-Content-Type-Options: nosniff"); // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on) - if (!defined('XFRAMEOPTIONS_ALLOWALL')) header("X-Frame-Options: SAMEORIGIN"); // Frames allowed only if on same domain (stop some XSS attacks) - else header("X-Frame-Options: ALLOWALL"); + if (!defined('XFRAMEOPTIONS_ALLOWALL')) { + header("X-Frame-Options: SAMEORIGIN"); // Frames allowed only if on same domain (stop some XSS attacks) + } else { + header("X-Frame-Options: ALLOWALL"); + } //header("X-XSS-Protection: 1"); // XSS filtering protection of some browsers (note: use of Content-Security-Policy is more efficient). Disabled as deprecated. - if (!defined('FORCECSP')) - { + if (!defined('FORCECSP')) { //if (! isset($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY)) //{ // // A default security policy that keep usage of js external component like ckeditor, stripe, google, working @@ -1232,16 +1270,20 @@ function top_httphead($contenttype = 'text/html', $forcenocache = 0) //else $contentsecuritypolicy = empty($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY) ? '' : $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY; - if (!is_object($hookmanager)) $hookmanager = new HookManager($db); + if (!is_object($hookmanager)) { + $hookmanager = new HookManager($db); + } $hookmanager->initHooks(array("main")); $parameters = array('contentsecuritypolicy'=>$contentsecuritypolicy); $result = $hookmanager->executeHooks('setContentSecurityPolicy', $parameters); // Note that $action and $object may have been modified by some hooks - if ($result > 0) $contentsecuritypolicy = $hookmanager->resPrint; // Replace CSP - else $contentsecuritypolicy .= $hookmanager->resPrint; // Concat CSP + if ($result > 0) { + $contentsecuritypolicy = $hookmanager->resPrint; // Replace CSP + } else { + $contentsecuritypolicy .= $hookmanager->resPrint; // Concat CSP + } - if (!empty($contentsecuritypolicy)) - { + if (!empty($contentsecuritypolicy)) { // For example, to restrict 'script', 'object', 'frames' or 'img' to some domains: // script-src https://api.google.com https://anotherhost.com; object-src https://youtube.com; frame-src https://youtube.com; img-src: https://static.example.com // For example, to restrict everything to one domain, except 'object', ...: @@ -1252,12 +1294,10 @@ function top_httphead($contenttype = 'text/html', $forcenocache = 0) // default-src http: https: 'unsafe-eval' 'unsafe-inline'; object-src 'none' header("Content-Security-Policy: ".$contentsecuritypolicy); } - } elseif (constant('FORCECSP')) - { + } elseif (constant('FORCECSP')) { header("Content-Security-Policy: ".constant('FORCECSP')); } - if ($forcenocache) - { + if ($forcenocache) { header("Cache-Control: no-cache, no-store, must-revalidate, max-age=0"); } } @@ -1282,23 +1322,31 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr top_httphead(); - if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php'; // If not defined, eldy by default + if (empty($conf->css)) { + $conf->css = '/theme/eldy/style.css.php'; // If not defined, eldy by default + } print '<!doctype html>'."\n"; - if (!empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang, 0, 2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n"; - else print '<html lang="'.substr($langs->defaultlang, 0, 2).'">'."\n"; + if (!empty($conf->global->MAIN_USE_CACHE_MANIFEST)) { + print '<html lang="'.substr($langs->defaultlang, 0, 2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n"; + } else { + print '<html lang="'.substr($langs->defaultlang, 0, 2).'">'."\n"; + } //print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n"; - if (empty($disablehead)) - { - if (!is_object($hookmanager)) $hookmanager = new HookManager($db); + if (empty($disablehead)) { + if (!is_object($hookmanager)) { + $hookmanager = new HookManager($db); + } $hookmanager->initHooks(array("main")); $ext = 'layout='.$conf->browser->layout.'&amp;version='.urlencode(DOL_VERSION); print "<head>\n"; - if (GETPOST('dol_basehref', 'alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref', 'alpha')).'">'."\n"; + if (GETPOST('dol_basehref', 'alpha')) { + print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref', 'alpha')).'">'."\n"; + } // Displays meta print '<meta charset="utf-8">'."\n"; @@ -1308,9 +1356,15 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr // Favicon $favicon = DOL_URL_ROOT.'/theme/dolibarr_256x256_color.png'; - if (!empty($mysoc->logo_squarred_mini)) $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini); - if (!empty($conf->global->MAIN_FAVICON_URL)) $favicon = $conf->global->MAIN_FAVICON_URL; - if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n"; // Not required into an Android webview + if (!empty($mysoc->logo_squarred_mini)) { + $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini); + } + if (!empty($conf->global->MAIN_FAVICON_URL)) { + $favicon = $conf->global->MAIN_FAVICON_URL; + } + if (empty($conf->dol_use_jmobile)) { + print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n"; // Not required into an Android webview + } //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n"; //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="copyright" title="GNU General Public License" href="https://www.gnu.org/copyleft/gpl.html#SEC1">'."\n"; @@ -1328,63 +1382,96 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr } // Auto refresh page - if (GETPOST('autorefresh', 'int') > 0) print '<meta http-equiv="refresh" content="'.GETPOST('autorefresh', 'int').'">'; + if (GETPOST('autorefresh', 'int') > 0) { + print '<meta http-equiv="refresh" content="'.GETPOST('autorefresh', 'int').'">'; + } // Displays title $appli = constant('DOL_APPLICATION_TITLE'); - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $appli = $conf->global->MAIN_APPLICATION_TITLE; + } print '<title>'; $titletoshow = ''; - if ($title && !empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/', $conf->global->MAIN_HTML_TITLE)) $titletoshow = dol_htmlentities($title); - elseif ($title) $titletoshow = dol_htmlentities($appli.' - '.$title); - else $titletoshow = dol_htmlentities($appli); + if ($title && !empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/', $conf->global->MAIN_HTML_TITLE)) { + $titletoshow = dol_htmlentities($title); + } elseif ($title) { + $titletoshow = dol_htmlentities($appli.' - '.$title); + } else { + $titletoshow = dol_htmlentities($appli); + } $parameters = array('title'=>$titletoshow); $result = $hookmanager->executeHooks('setHtmlTitle', $parameters); // Note that $action and $object may have been modified by some hooks - if ($result > 0) $titletoshow = $hookmanager->resPrint; // Replace Title to show - else $titletoshow .= $hookmanager->resPrint; // Concat to Title to show + if ($result > 0) { + $titletoshow = $hookmanager->resPrint; // Replace Title to show + } else { + $titletoshow .= $hookmanager->resPrint; // Concat to Title to show + } print $titletoshow; print '</title>'; print "\n"; - if (GETPOST('version', 'int')) $ext = 'version='.GETPOST('version', 'int'); // usefull to force no cache on css/js + if (GETPOST('version', 'int')) { + $ext = 'version='.GETPOST('version', 'int'); // usefull to force no cache on css/js + } $themeparam = '?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss', 'aZ09') ? '&amp;optioncss='.GETPOST('optioncss', 'aZ09', 1) : '').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity; $themeparam .= ($ext ? '&amp;'.$ext : '').'&amp;revision='.$conf->global->MAIN_IHM_PARAMS_REV; - if (!empty($_SESSION['dol_resetcache'])) $themeparam .= '&amp;dol_resetcache='.$_SESSION['dol_resetcache']; - if (GETPOSTISSET('dol_hide_topmenu')) { $themeparam .= '&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu', 'int'); } - if (GETPOSTISSET('dol_hide_leftmenu')) { $themeparam .= '&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu', 'int'); } - if (GETPOSTISSET('dol_optimize_smallscreen')) { $themeparam .= '&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen', 'int'); } - if (GETPOSTISSET('dol_no_mouse_hover')) { $themeparam .= '&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover', 'int'); } - if (GETPOSTISSET('dol_use_jmobile')) { $themeparam .= '&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile', 'int'); $conf->dol_use_jmobile = GETPOST('dol_use_jmobile', 'int'); } - if (GETPOSTISSET('THEME_DARKMODEENABLED')) { $themeparam .= '&amp;THEME_DARKMODEENABLED='.GETPOST('THEME_DARKMODEENABLED', 'int'); } - if (GETPOSTISSET('THEME_SATURATE_RATIO')) { $themeparam .= '&amp;THEME_SATURATE_RATIO='.GETPOST('THEME_SATURATE_RATIO', 'int'); } + if (!empty($_SESSION['dol_resetcache'])) { + $themeparam .= '&amp;dol_resetcache='.$_SESSION['dol_resetcache']; + } + if (GETPOSTISSET('dol_hide_topmenu')) { + $themeparam .= '&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu', 'int'); + } + if (GETPOSTISSET('dol_hide_leftmenu')) { + $themeparam .= '&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu', 'int'); + } + if (GETPOSTISSET('dol_optimize_smallscreen')) { + $themeparam .= '&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen', 'int'); + } + if (GETPOSTISSET('dol_no_mouse_hover')) { + $themeparam .= '&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover', 'int'); + } + if (GETPOSTISSET('dol_use_jmobile')) { + $themeparam .= '&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile', 'int'); $conf->dol_use_jmobile = GETPOST('dol_use_jmobile', 'int'); + } + if (GETPOSTISSET('THEME_DARKMODEENABLED')) { + $themeparam .= '&amp;THEME_DARKMODEENABLED='.GETPOST('THEME_DARKMODEENABLED', 'int'); + } + if (GETPOSTISSET('THEME_SATURATE_RATIO')) { + $themeparam .= '&amp;THEME_SATURATE_RATIO='.GETPOST('THEME_SATURATE_RATIO', 'int'); + } if (!empty($conf->global->MAIN_ENABLE_FONT_ROBOTO)) { print '<link rel="preconnect" href="https://fonts.gstatic.com">'."\n"; print '<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@200;300;400;500;600&display=swap" rel="stylesheet">'."\n"; } - if (!defined('DISABLE_JQUERY') && !$disablejs && $conf->use_javascript_ajax) - { + if (!defined('DISABLE_JQUERY') && !$disablejs && $conf->use_javascript_ajax) { print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n"; $jquerytheme = 'base'; - if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME; - if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext ? '?'.$ext : '').'">'."\n"; // Forced JQuery - else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext ? '?'.$ext : '').'">'."\n"; // JQuery - if (!defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext ? '?'.$ext : '').'">'."\n"; // JNotify - if (!defined('DISABLE_SELECT2') && (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) // jQuery plugin "mutiselect", "multiple-select", "select2"... - { + if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) { + $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME; + } + if (constant('JS_JQUERY_UI')) { + print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext ? '?'.$ext : '').'">'."\n"; // Forced JQuery + } else { + print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext ? '?'.$ext : '').'">'."\n"; // JQuery + } + if (!defined('DISABLE_JQUERY_JNOTIFY')) { + print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext ? '?'.$ext : '').'">'."\n"; // JNotify + } + if (!defined('DISABLE_SELECT2') && (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) { // jQuery plugin "mutiselect", "multiple-select", "select2"... $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT; print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css'.($ext ? '?'.$ext : '').'">'."\n"; } } - if (!defined('DISABLE_FONT_AWSOME')) - { + if (!defined('DISABLE_FONT_AWSOME')) { print '<!-- Includes CSS for font awesome -->'."\n"; print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome-5/css/all.min.css'.($ext ? '?'.$ext : '').'">'."\n"; print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome-5/css/v4-shims.min.css'.($ext ? '?'.$ext : '').'">'."\n"; @@ -1394,12 +1481,9 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr // Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php' $themepath = dol_buildpath($conf->css, 1); $themesubdir = ''; - if (!empty($conf->modules_parts['theme'])) // This slow down - { - foreach ($conf->modules_parts['theme'] as $reldir) - { - if (file_exists(dol_buildpath($reldir.$conf->css, 0))) - { + if (!empty($conf->modules_parts['theme'])) { // This slow down + foreach ($conf->modules_parts['theme'] as $reldir) { + if (file_exists(dol_buildpath($reldir.$conf->css, 0))) { $themepath = dol_buildpath($reldir.$conf->css, 1); $themesubdir = $reldir; break; @@ -1409,59 +1493,68 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr //print 'themepath='.$themepath.' themeparam='.$themeparam;exit; print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n"; - if (!empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n"; + if (!empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) { + print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n"; + } // CSS forced by modules (relative url starting with /) - if (!empty($conf->modules_parts['css'])) - { + if (!empty($conf->modules_parts['css'])) { $arraycss = (array) $conf->modules_parts['css']; - foreach ($arraycss as $modcss => $filescss) - { + foreach ($arraycss as $modcss => $filescss) { $filescss = (array) $filescss; // To be sure filecss is an array - foreach ($filescss as $cssfile) - { - if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING); + foreach ($filescss as $cssfile) { + if (empty($cssfile)) { + dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING); + } // cssfile is a relative path print '<!-- Includes CSS added by module '.$modcss.' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile, 1); // We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used. - if (!preg_match('/\.css$/i', $cssfile)) print $themeparam; + if (!preg_match('/\.css$/i', $cssfile)) { + print $themeparam; + } print '">'."\n"; } } } // CSS forced by page in top_htmlhead call (relative url starting with /) - if (is_array($arrayofcss)) - { - foreach ($arrayofcss as $cssfile) - { - if (preg_match('/^(http|\/\/)/i', $cssfile)) - { + if (is_array($arrayofcss)) { + foreach ($arrayofcss as $cssfile) { + if (preg_match('/^(http|\/\/)/i', $cssfile)) { $urltofile = $cssfile; } else { $urltofile = dol_buildpath($cssfile, 1); } print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.$urltofile; // We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used. - if (!preg_match('/\.css$/i', $cssfile)) print $themeparam; + if (!preg_match('/\.css$/i', $cssfile)) { + print $themeparam; + } print '">'."\n"; } } // Output standard javascript links - if (!defined('DISABLE_JQUERY') && !$disablejs && !empty($conf->use_javascript_ajax)) - { + if (!defined('DISABLE_JQUERY') && !$disablejs && !empty($conf->use_javascript_ajax)) { // JQuery. Must be before other includes print '<!-- Includes JS for JQuery -->'."\n"; - if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script src="'.JS_JQUERY.'jquery.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; - else print '<script src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; + if (defined('JS_JQUERY') && constant('JS_JQUERY')) { + print '<script src="'.JS_JQUERY.'jquery.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; + } else { + print '<script src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; + } /*if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED')) { if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n"; else print '<script src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n"; }*/ - if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; - else print '<script src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; - if (!defined('DISABLE_JQUERY_TABLEDND')) print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; + if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) { + print '<script src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; + } else { + print '<script src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; + } + if (!defined('DISABLE_JQUERY_TABLEDND')) { + print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; + } // jQuery jnotify if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && !defined('DISABLE_JQUERY_JNOTIFY')) { print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; @@ -1500,16 +1593,14 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT; print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; // We include full because we need the support of containerCssClass } - if (!defined('DISABLE_MULTISELECT')) // jQuery plugin "mutiselect" to select with checkboxes. Can be removed once we have an enhanced search tool - { + if (!defined('DISABLE_MULTISELECT')) { // jQuery plugin "mutiselect" to select with checkboxes. Can be removed once we have an enhanced search tool print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/multiselect/jquery.multi-select.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; } } if (!$disablejs && !empty($conf->use_javascript_ajax)) { // CKEditor - if ((!empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && !defined('DISABLE_CKEDITOR')) || defined('FORCE_CKEDITOR')) - { + if ((!empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && !defined('DISABLE_CKEDITOR')) || defined('FORCE_CKEDITOR')) { print '<!-- Includes JS for CKEditor -->'."\n"; $pathckeditor = DOL_URL_ROOT.'/includes/ckeditor/ckeditor/'; $jsckeditor = 'ckeditor.js'; @@ -1518,7 +1609,7 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr $pathckeditor = constant('JS_CKEDITOR'); } print '<script>'; - print '/* enable ckeditor by main.inc.php */'; + print '/* enable ckeditor by main.inc.php */'; print 'var CKEDITOR_BASEPATH = \''.$pathckeditor.'\';'."\n"; print 'var ckeditorConfig = \''.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext ? '?'.$ext : ''), 1).'\';'."\n"; // $themesubdir='' in standard usage print 'var ckeditorFilebrowserBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n"; @@ -1535,13 +1626,15 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr } // Browser notifications (if NOREQUIREMENU is on, it is mostly a page for popup, so we do not enable notif too. We hide also for public pages). - if (!defined('NOBROWSERNOTIF') && !defined('NOREQUIREMENU') && !defined('NOLOGIN')) - { + if (!defined('NOBROWSERNOTIF') && !defined('NOREQUIREMENU') && !defined('NOLOGIN')) { $enablebrowsernotif = false; - if (!empty($conf->agenda->enabled) && !empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif = true; - if ($conf->browser->layout == 'phone') $enablebrowsernotif = false; - if ($enablebrowsernotif) - { + if (!empty($conf->agenda->enabled) && !empty($conf->global->AGENDA_REMINDER_BROWSER)) { + $enablebrowsernotif = true; + } + if ($conf->browser->layout == 'phone') { + $enablebrowsernotif = false; + } + if ($enablebrowsernotif) { print '<!-- Includes JS of Dolibarr (browser layout = '.$conf->browser->layout.')-->'."\n"; print '<script src="'.DOL_URL_ROOT.'/core/js/lib_notification.js.php'.($ext ? '?'.$ext : '').'"></script>'."\n"; } @@ -1552,27 +1645,21 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr print '<script src="'.DOL_URL_ROOT.'/core/js/lib_head.js.php?lang='.$langs->defaultlang.($ext ? '&'.$ext : '').'"></script>'."\n"; // JS forced by modules (relative url starting with /) - if (!empty($conf->modules_parts['js'])) // $conf->modules_parts['js'] is array('module'=>array('file1','file2')) - { + if (!empty($conf->modules_parts['js'])) { // $conf->modules_parts['js'] is array('module'=>array('file1','file2')) $arrayjs = (array) $conf->modules_parts['js']; - foreach ($arrayjs as $modjs => $filesjs) - { + foreach ($arrayjs as $modjs => $filesjs) { $filesjs = (array) $filesjs; // To be sure filejs is an array - foreach ($filesjs as $jsfile) - { + foreach ($filesjs as $jsfile) { // jsfile is a relative path print '<!-- Include JS added by module '.$modjs.'-->'."\n".'<script src="'.dol_buildpath($jsfile, 1).'"></script>'."\n"; } } } // JS forced by page in top_htmlhead (relative url starting with /) - if (is_array($arrayofjs)) - { + if (is_array($arrayofjs)) { print '<!-- Includes JS added by page -->'."\n"; - foreach ($arrayofjs as $jsfile) - { - if (preg_match('/^(http|\/\/)/i', $jsfile)) - { + foreach ($arrayofjs as $jsfile) { + if (preg_match('/^(http|\/\/)/i', $jsfile)) { print '<script src="'.$jsfile.'"></script>'."\n"; } else { print '<script src="'.dol_buildpath($jsfile, 1).'"></script>'."\n"; @@ -1581,8 +1668,12 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr } } - if (!empty($head)) print $head."\n"; - if (!empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n"; + if (!empty($head)) { + print $head."\n"; + } + if (!empty($conf->global->MAIN_HTML_HEADER)) { + print $conf->global->MAIN_HTML_HEADER."\n"; + } $parameters = array(); $result = $hookmanager->executeHooks('addHtmlHeader', $parameters); // Note that $action and $object may have been modified by some hooks @@ -1626,18 +1717,16 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead $toprightmenu = ''; // For backward compatibility with old modules - if (empty($conf->headerdone)) - { + if (empty($conf->headerdone)) { $disablenofollow = 0; top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss, 0, $disablenofollow); print '<body id="mainbody">'; } /* - * Top menu - */ - if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) - { + * Top menu + */ + if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) { if (!isset($form) || !is_object($form)) { include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; $form = new Form($db); @@ -1655,24 +1744,28 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead // Define link to login card $appli = constant('DOL_APPLICATION_TITLE'); - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) - { + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { $appli = $conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core - } else $appli .= " ".DOL_VERSION; - } else $appli .= " ".DOL_VERSION; + if (preg_match('/\d\.\d/', $appli)) { + if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) { + $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core + } + } else { + $appli .= " ".DOL_VERSION; + } + } else { + $appli .= " ".DOL_VERSION; + } - if (!empty($conf->global->MAIN_FEATURES_LEVEL)) $appli .= "<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL; + if (!empty($conf->global->MAIN_FEATURES_LEVEL)) { + $appli .= "<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL; + } $logouttext = ''; $logouthtmltext = ''; - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { //$logouthtmltext=$appli.'<br>'; - if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http') - { + if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http') { $logouthtmltext .= $langs->trans("Logout").'<br>'; $logouttext .= '<a accesskey="l" href="'.DOL_URL_ROOT.'/user/logout.php">'; @@ -1691,11 +1784,10 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead // Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>') $parameters = array(); $result = $hookmanager->executeHooks('printTopRightMenu', $parameters); // Note that $action and $object may have been modified by some hooks - if (is_numeric($result)) - { - if ($result == 0) + if (is_numeric($result)) { + if ($result == 0) { $toprightmenu .= $hookmanager->resPrint; // add - else { + } else { $toprightmenu = $hookmanager->resPrint; // replace } } else { @@ -1703,8 +1795,7 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead } // Link to module builder - if (!empty($conf->modulebuilder->enabled)) - { + if (!empty($conf->modulebuilder->enabled)) { $text = '<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="modulebuilder">'; //$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"'); $text .= '<span class="fa fa-bug atoplogin valignmiddle"></span>'; @@ -1713,14 +1804,14 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead } // Link to print main content area - if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $conf->browser->layout != 'phone') - { + if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $conf->browser->layout != 'phone') { $qs = dol_escape_htmltag($_SERVER["QUERY_STRING"]); - if (is_array($_POST)) - { - foreach ($_POST as $key=>$value) { - if ($key !== 'action' && $key !== 'password' && !is_array($value)) $qs .= '&'.$key.'='.urlencode($value); + if (is_array($_POST)) { + foreach ($_POST as $key => $value) { + if ($key !== 'action' && $key !== 'password' && !is_array($value)) { + $qs .= '&'.$key.'='.urlencode($value); + } } } $qs .= (($qs && $morequerystring) ? '&' : '').$morequerystring; @@ -1732,8 +1823,7 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead } // Link to Dolibarr wiki pages - if (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $langs->load("help"); $helpbaseurl = ''; @@ -1754,21 +1844,28 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead $mode = $arrayres['mode']; // Link to help pages - if ($helpbaseurl && $helppage) - { + if ($helpbaseurl && $helppage) { $text = ''; $title = $langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage' : 'GoToHelpPage').'...'; if ($mode == 'wiki') { $title .= '<br>'.$langs->trans("PageWiki").' '.dol_escape_htmltag('"'.strtr($helppage, '_', ' ').'"'); - if ($helppresent) $title .= ' <span class="opacitymedium">('.$langs->trans("DedicatedPageAvailable").')</span>'; - else $title .= ' <span class="opacitymedium">('.$langs->trans("HomePage").')</span>'; + if ($helppresent) { + $title .= ' <span class="opacitymedium">('.$langs->trans("DedicatedPageAvailable").')</span>'; + } else { + $title .= ' <span class="opacitymedium">('.$langs->trans("HomePage").')</span>'; + } } $text .= '<a class="help" target="_blank" rel="noopener" href="'; - if ($mode == 'wiki') $text .= sprintf($helpbaseurl, urlencode(html_entity_decode($helppage))); - else $text .= sprintf($helpbaseurl, $helppage); + if ($mode == 'wiki') { + $text .= sprintf($helpbaseurl, urlencode(html_entity_decode($helppage))); + } else { + $text .= sprintf($helpbaseurl, $helppage); + } $text .= '">'; $text .= '<span class="fa fa-question-circle atoplogin valignmiddle'.($helppresent ? ' '.$helppresent : '').'"></span>'; - if ($helppresent) $text .= '<span class="fa fa-circle helppresentcircle"></span>'; + if ($helppresent) { + $text .= '<span class="fa fa-circle helppresentcircle"></span>'; + } $text .= '</a>'; $toprightmenu .= $form->textwithtooltip('', $title, 2, 1, $text, 'login_block_elem', 2); } @@ -1829,7 +1926,9 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead print "<!-- End top horizontal menu -->\n\n"; } - if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container">'; + if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) { + print '<!-- Begin div id-container --><div id="id-container" class="id-container">'; + } } @@ -1847,14 +1946,17 @@ function top_menu_user($hideloginname = 0, $urllogout = '') global $menumanager; $userImage = $userDropDownImage = ''; - if (!empty($user->photo)) - { + if (!empty($user->photo)) { $userImage = Form::showphoto('userphoto', $user, 0, 0, 0, 'photouserphoto userphoto', 'small', 0, 1); $userDropDownImage = Form::showphoto('userphoto', $user, 0, 0, 0, 'dropdown-user-image', 'small', 0, 1); } else { $nophoto = '/public/theme/common/user_anonymous.png'; - if ($user->gender == 'man') $nophoto = '/public/theme/common/user_man.png'; - if ($user->gender == 'woman') $nophoto = '/public/theme/common/user_woman.png'; + if ($user->gender == 'man') { + $nophoto = '/public/theme/common/user_man.png'; + } + if ($user->gender == 'woman') { + $nophoto = '/public/theme/common/user_woman.png'; + } $userImage = '<img class="photo photouserphoto userphoto" alt="No photo" src="'.DOL_URL_ROOT.$nophoto.'">'; $userDropDownImage = '<img class="photo dropdown-user-image" alt="No photo" src="'.DOL_URL_ROOT.$nophoto.'">'; @@ -1868,8 +1970,7 @@ function top_menu_user($hideloginname = 0, $urllogout = '') if (!empty($user->admin)) { $dropdownBody .= '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($user->admin); } - if (!empty($user->socid)) // Add thirdparty for external users - { + if (!empty($user->socid)) { // Add thirdparty for external users $thirdpartystatic = new Societe($db); $thirdpartystatic->fetch($user->socid); $companylink = ' '.$thirdpartystatic->getNomUrl(2); // picto only of company @@ -1882,7 +1983,9 @@ function top_menu_user($hideloginname = 0, $urllogout = '') $dropdownBody .= '<br><u>'.$langs->trans("Session").'</u>'; $dropdownBody .= '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_escape_htmltag($_SERVER["REMOTE_ADDR"]); - if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) $dropdownBody .= '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (user entity '.$user->entity.')'; + if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) { + $dropdownBody .= '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (user entity '.$user->entity.')'; + } $dropdownBody .= '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.$_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'); $dropdownBody .= '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($user->datelastlogin, "dayhour", 'tzuser'); $dropdownBody .= '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser'); @@ -1901,15 +2004,18 @@ function top_menu_user($hideloginname = 0, $urllogout = '') $dropdownBody .= '<br><b>'.$langs->trans("Browser").':</b> '.$conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.dol_escape_htmltag($_SERVER['HTTP_USER_AGENT']).')'; $dropdownBody .= '<br><b>'.$langs->trans("Layout").':</b> '.$conf->browser->layout; $dropdownBody .= '<br><b>'.$langs->trans("Screen").':</b> '.$_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']; - if ($conf->browser->layout == 'phone') $dropdownBody .= '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes"); - if (!empty($_SESSION["disablemodules"])) $dropdownBody .= '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.join(', ', explode(',', $_SESSION["disablemodules"])); + if ($conf->browser->layout == 'phone') { + $dropdownBody .= '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes"); + } + if (!empty($_SESSION["disablemodules"])) { + $dropdownBody .= '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.join(', ', explode(',', $_SESSION["disablemodules"])); + } $dropdownBody .= '</div>'; // Execute hook $parameters = array('user'=>$user, 'langs' => $langs); $result = $hookmanager->executeHooks('printTopRightMenuLoginDropdownBody', $parameters); // Note that $action and $object may have been modified by some hooks - if (is_numeric($result)) - { + if (is_numeric($result)) { if ($result == 0) { $dropdownBody .= $hookmanager->resPrint; // add } else { @@ -1932,14 +2038,18 @@ function top_menu_user($hideloginname = 0, $urllogout = '') // Define version to show $appli = constant('DOL_APPLICATION_TITLE'); - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) - { + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { $appli = $conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core - } else $appli .= " ".DOL_VERSION; - } else $appli .= " ".DOL_VERSION; + if (preg_match('/\d\.\d/', $appli)) { + if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) { + $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core + } + } else { + $appli .= " ".DOL_VERSION; + } + } else { + $appli .= " ".DOL_VERSION; + } if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $btnUser = '<!-- div for user link --> @@ -1988,8 +2098,7 @@ function top_menu_user($hideloginname = 0, $urllogout = '') </div>'; } - if (!defined('JS_JQUERY_DISABLE_DROPDOWN') && !empty($conf->use_javascript_ajax)) // This may be set by some pages that use different jquery version to avoid errors - { + if (!defined('JS_JQUERY_DISABLE_DROPDOWN') && !empty($conf->use_javascript_ajax)) { // This may be set by some pages that use different jquery version to avoid errors $btnUser .= ' <!-- Code to show/hide the user drop-down --> <script> @@ -2256,10 +2365,11 @@ function top_menu_bookmark() $html = ''; // Define $bookmarks - if (empty($conf->bookmark->enabled) || empty($user->rights->bookmark->lire)) return $html; + if (empty($conf->bookmark->enabled) || empty($user->rights->bookmark->lire)) { + return $html; + } - if (!defined('JS_JQUERY_DISABLE_DROPDOWN') && !empty($conf->use_javascript_ajax)) // This may be set by some pages that use different jquery version to avoid errors - { + if (!defined('JS_JQUERY_DISABLE_DROPDOWN') && !empty($conf->use_javascript_ajax)) { // This may be set by some pages that use different jquery version to avoid errors include_once DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php'; $langs->load("bookmarks"); @@ -2336,8 +2446,7 @@ function top_menu_search() $defaultAction = ''; $buttonList = '<div class="dropdown-global-search-button-list" >'; // Menu with all searchable items - foreach ($arrayresult as $keyItem => $item) - { + foreach ($arrayresult as $keyItem => $item) { if (empty($defaultAction)) { $defaultAction = $item['url']; } @@ -2462,20 +2571,25 @@ function left_menu($menu_array_before, $helppagename = '', $notused = '', $menu_ $searchform = ''; $bookmarks = ''; - if (!empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING); + if (!empty($menu_array_before)) { + dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING); + } - if (empty($conf->dol_hide_leftmenu) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) - { + if (empty($conf->dol_hide_leftmenu) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) { // Instantiate hooks for external modules $hookmanager->initHooks(array('searchform', 'leftblock')); print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n"; - if ($conf->browser->layout == 'phone') $conf->global->MAIN_USE_OLD_SEARCH_FORM = 1; // Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ? + if ($conf->browser->layout == 'phone') { + $conf->global->MAIN_USE_OLD_SEARCH_FORM = 1; // Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ? + } print "\n"; - if (!is_object($form)) $form = new Form($db); + if (!is_object($form)) { + $form = new Form($db); + } $selected = -1; if (empty($conf->global->MAIN_USE_TOP_MENU_SEARCH_DROPDOWN)) { $usedbyinclude = 1; @@ -2497,7 +2611,9 @@ function left_menu($menu_array_before, $helppagename = '', $notused = '', $menu_ $reshook = $hookmanager->executeHooks('printSearchForm', $parameters); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) { $searchform .= $hookmanager->resPrint; - } else $searchform = $hookmanager->resPrint; + } else { + $searchform = $hookmanager->resPrint; + } // Force special value for $searchform if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty($conf->use_javascript_ajax)) { @@ -2532,37 +2648,55 @@ function left_menu($menu_array_before, $helppagename = '', $notused = '', $menu_ print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n"; // Version - if (!empty($conf->global->MAIN_SHOW_VERSION)) // Version is already on help picto and on login page. - { + if (!empty($conf->global->MAIN_SHOW_VERSION)) { // Version is already on help picto and on login page. $doliurl = 'https://www.dolibarr.org'; //local communities - if (preg_match('/fr/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.fr'; - if (preg_match('/es/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.es'; - if (preg_match('/de/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.de'; - if (preg_match('/it/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.it'; - if (preg_match('/gr/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.gr'; + if (preg_match('/fr/i', $langs->defaultlang)) { + $doliurl = 'https://www.dolibarr.fr'; + } + if (preg_match('/es/i', $langs->defaultlang)) { + $doliurl = 'https://www.dolibarr.es'; + } + if (preg_match('/de/i', $langs->defaultlang)) { + $doliurl = 'https://www.dolibarr.de'; + } + if (preg_match('/it/i', $langs->defaultlang)) { + $doliurl = 'https://www.dolibarr.it'; + } + if (preg_match('/gr/i', $langs->defaultlang)) { + $doliurl = 'https://www.dolibarr.gr'; + } $appli = constant('DOL_APPLICATION_TITLE'); - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) - { + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { $appli = $conf->global->MAIN_APPLICATION_TITLE; $doliurl = ''; - if (preg_match('/\d\.\d/', $appli)) - { - if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core - } else $appli .= " ".DOL_VERSION; - } else $appli .= " ".DOL_VERSION; + if (preg_match('/\d\.\d/', $appli)) { + if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) { + $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core + } + } else { + $appli .= " ".DOL_VERSION; + } + } else { + $appli .= " ".DOL_VERSION; + } print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">'; - if ($doliurl) print '<a class="help" target="_blank" rel="noopener" href="'.$doliurl.'">'; - else print '<span class="help">'; + if ($doliurl) { + print '<a class="help" target="_blank" rel="noopener" href="'.$doliurl.'">'; + } else { + print '<span class="help">'; + } print $appli; - if ($doliurl) print '</a>'; - else print '</span>'; + if ($doliurl) { + print '</a>'; + } else { + print '</span>'; + } print '</div>'."\n"; } // Link to bugtrack - if (!empty($conf->global->MAIN_BUGTRACK_ENABLELINK)) - { + if (!empty($conf->global->MAIN_BUGTRACK_ENABLELINK)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new?labels=Bug'; @@ -2601,10 +2735,11 @@ function left_menu($menu_array_before, $helppagename = '', $notused = '', $menu_ // Execute hook printBugtrackInfo $parameters = array('bugbaseurl'=>$bugbaseurl); $reshook = $hookmanager->executeHooks('printBugtrackInfo', $parameters); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { + if (empty($reshook)) { $bugbaseurl .= $hookmanager->resPrint; - } else $bugbaseurl = $hookmanager->resPrint; + } else { + $bugbaseurl = $hookmanager->resPrint; + } $bugbaseurl .= urlencode("\n"); $bugbaseurl .= urlencode("## Report\n"); @@ -2632,7 +2767,9 @@ function left_menu($menu_array_before, $helppagename = '', $notused = '', $menu_ print "\n"; print '<!-- Begin right area -->'."\n"; - if (empty($leftmenuwithoutmainarea)) main_area($title); + if (empty($leftmenuwithoutmainarea)) { + main_area($title); + } } @@ -2646,23 +2783,25 @@ function main_area($title = '') { global $conf, $langs; - if (empty($conf->dol_hide_leftmenu)) print '<div id="id-right">'; + if (empty($conf->dol_hide_leftmenu)) { + print '<div id="id-right">'; + } print "\n"; print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n"; - if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode", $conf->global->MAIN_ONLY_LOGIN_ALLOWED), 0, 0, 1, 'warning maintenancemode'); + if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) { + print info_admin($langs->trans("WarningYouAreInMaintenanceMode", $conf->global->MAIN_ONLY_LOGIN_ALLOWED), 0, 0, 1, 'warning maintenancemode'); + } // Permit to add user company information on each printed document by setting SHOW_SOCINFO_ON_PRINT - if (!empty($conf->global->SHOW_SOCINFO_ON_PRINT) && GETPOST('optioncss', 'aZ09') == 'print' && empty(GETPOST('disable_show_socinfo_on_print', 'az09'))) - { + if (!empty($conf->global->SHOW_SOCINFO_ON_PRINT) && GETPOST('optioncss', 'aZ09') == 'print' && empty(GETPOST('disable_show_socinfo_on_print', 'az09'))) { global $hookmanager; $hookmanager->initHooks(array('main')); $parameters = array(); $reshook = $hookmanager->executeHooks('showSocinfoOnPrint', $parameters); - if (empty($reshook)) - { + if (empty($reshook)) { print '<!-- Begin show mysoc info header -->'."\n"; print '<div id="mysoc-info-header">'."\n"; print '<table class="centpercent div-table-responsive">'."\n"; @@ -2674,9 +2813,15 @@ function main_area($title = '') print '</td><td rowspan="0" class="width50p"></td></tr>'."\n"; print '<tr><td class="titre bold">'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_NOM).'</td></tr>'."\n"; print '<tr><td>'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_ADDRESS).'<br>'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_ZIP).' '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_TOWN).'</td></tr>'."\n"; - if (!empty($conf->global->MAIN_INFO_SOCIETE_TEL)) print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Phone").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_TEL).'</td></tr>'; - if (!empty($conf->global->MAIN_INFO_SOCIETE_MAIL)) print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Email").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_MAIL).'</td></tr>'; - if (!empty($conf->global->MAIN_INFO_SOCIETE_WEB)) print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Web").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_WEB).'</td></tr>'; + if (!empty($conf->global->MAIN_INFO_SOCIETE_TEL)) { + print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Phone").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_TEL).'</td></tr>'; + } + if (!empty($conf->global->MAIN_INFO_SOCIETE_MAIL)) { + print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Email").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_MAIL).'</td></tr>'; + } + if (!empty($conf->global->MAIN_INFO_SOCIETE_WEB)) { + print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Web").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_WEB).'</td></tr>'; + } print '</tbody>'; print '</table>'."\n"; print '</div>'."\n"; @@ -2699,8 +2844,7 @@ function getHelpParamFor($helppagename, $langs) $helppage = ''; $mode = ''; - if (preg_match('/^http/i', $helppagename)) - { + if (preg_match('/^http/i', $helppagename)) { // If complete URL $helpbaseurl = '%s'; $helppage = $helppagename; @@ -2708,20 +2852,23 @@ function getHelpParamFor($helppagename, $langs) } else { // If WIKI URL $reg = array(); - if (preg_match('/^es/i', $langs->defaultlang)) - { + if (preg_match('/^es/i', $langs->defaultlang)) { $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s'; - if (preg_match('/ES:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1]; + if (preg_match('/ES:([^|]+)/i', $helppagename, $reg)) { + $helppage = $reg[1]; + } } - if (preg_match('/^fr/i', $langs->defaultlang)) - { + if (preg_match('/^fr/i', $langs->defaultlang)) { $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s'; - if (preg_match('/FR:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1]; + if (preg_match('/FR:([^|]+)/i', $helppagename, $reg)) { + $helppage = $reg[1]; + } } - if (empty($helppage)) // If help page not already found - { + if (empty($helppage)) { // If help page not already found $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s'; - if (preg_match('/EN:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1]; + if (preg_match('/EN:([^|]+)/i', $helppagename, $reg)) { + $helppage = $reg[1]; + } } $mode = 'wiki'; } @@ -2754,7 +2901,9 @@ function printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinpu $ret .= '<input type="hidden" name="token" value="'.newToken().'">'; $ret .= '<input type="hidden" name="mode" value="search">'; $ret .= '<input type="hidden" name="savelogin" value="'.dol_escape_htmltag($user->login).'">'; - if ($showtitlebefore) $ret .= '<div class="tagtd left">'.$title.'</div> '; + if ($showtitlebefore) { + $ret .= '<div class="tagtd left">'.$title.'</div> '; + } $ret .= '<div class="tagtd">'; $ret .= img_picto('', $img, '', false, 0, 0, '', 'paddingright width20'); $ret .= '<input type="text" class="flat '.$htmlmorecss.'"'; @@ -2772,8 +2921,7 @@ function printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinpu } -if (!function_exists("llxFooter")) -{ +if (!function_exists("llxFooter")) { /** * Show HTML footer * Close div /DIV class=fiche + /DIV id-right + /DIV id-container + /BODY + /HTML. @@ -2798,16 +2946,17 @@ if (!function_exists("llxFooter")) // Code for search criteria persistence. // $user->lastsearch_values was set by the GETPOST when form field search_xxx exists - if (is_object($user) && !empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp)) - { + if (is_object($user) && !empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp)) { // Clean and save data - foreach ($user->lastsearch_values_tmp as $key => $val) - { + foreach ($user->lastsearch_values_tmp as $key => $val) { unset($_SESSION['lastsearch_values_tmp_'.$key]); // Clean array to rebuild it just after - if (count($val) && empty($_POST['button_removefilter'])) // If there is search criteria to save and we did not click on 'Clear filter' button - { - if (empty($val['sortfield'])) unset($val['sortfield']); - if (empty($val['sortorder'])) unset($val['sortorder']); + if (count($val) && empty($_POST['button_removefilter'])) { // If there is search criteria to save and we did not click on 'Clear filter' button + if (empty($val['sortfield'])) { + unset($val['sortfield']); + } + if (empty($val['sortorder'])) { + unset($val['sortorder']); + } dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criterias)"); $_SESSION['lastsearch_values_tmp_'.$key] = json_encode($val); unset($_SESSION['lastsearch_values_'.$key]); @@ -2818,18 +2967,25 @@ if (!function_exists("llxFooter")) $relativepathstring = $_SERVER["PHP_SELF"]; // Clean $relativepathstring - if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring); + if (constant('DOL_URL_ROOT')) { + $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring); + } $relativepathstring = preg_replace('/^\//', '', $relativepathstring); $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring); - if (preg_match('/list\.php$/', $relativepathstring)) - { + if (preg_match('/list\.php$/', $relativepathstring)) { unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]); unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]); unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]); - if (!empty($contextpage)) $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring] = $contextpage; - if (!empty($page) && $page > 0) $_SESSION['lastsearch_page_tmp_'.$relativepathstring] = $page; - if (!empty($limit) && $limit != $conf->liste_limit) $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] = $limit; + if (!empty($contextpage)) { + $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring] = $contextpage; + } + if (!empty($page) && $page > 0) { + $_SESSION['lastsearch_page_tmp_'.$relativepathstring] = $page; + } + if (!empty($limit) && $limit != $conf->liste_limit) { + $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] = $limit; + } unset($_SESSION['lastsearch_contextpage_'.$relativepathstring]); unset($_SESSION['lastsearch_page_'.$relativepathstring]); @@ -2837,11 +2993,9 @@ if (!function_exists("llxFooter")) } // Core error message - if (!empty($conf->global->MAIN_CORE_ERROR)) - { + if (!empty($conf->global->MAIN_CORE_ERROR)) { // Ajax version - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { $title = img_warning().' '.$langs->trans('CoreErrorTitle'); print ajax_dialog($title, $langs->trans('CoreErrorMessage')); } else { @@ -2857,55 +3011,60 @@ if (!function_exists("llxFooter")) print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche - if (empty($conf->dol_hide_leftmenu)) print '</div> <!-- End div id-right -->'."\n"; // End div id-right + if (empty($conf->dol_hide_leftmenu)) { + print '</div> <!-- End div id-right -->'."\n"; // End div id-right + } - if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n"; // End div container + if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) { + print '</div> <!-- End div id-container -->'."\n"; // End div container + } print "\n"; - if ($comment) print '<!-- '.$comment.' -->'."\n"; + if ($comment) { + print '<!-- '.$comment.' -->'."\n"; + } printCommonFooter($zone); - if (!empty($delayedhtmlcontent)) print $delayedhtmlcontent; + if (!empty($delayedhtmlcontent)) { + print $delayedhtmlcontent; + } - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n"; print '<script src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.($ext ? '&'.$ext : '').'"></script>'."\n"; } // Wrapper to add log when clicking on download or preview - if (!empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0) - { - if (in_array($object->element, array('facture'))) // Restrict for the moment to element 'facture' - { + if (!empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0) { + if (in_array($object->element, array('facture'))) { // Restrict for the moment to element 'facture' print "\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\n"; ?> - <script> - jQuery(document).ready(function () { - $('a.documentpreview').click(function() { - $.post('<?php echo DOL_URL_ROOT."/blockedlog/ajax/block-add.php" ?>' - , { - id:<?php echo $object->id; ?> - , element:'<?php echo $object->element ?>' - , action:'DOC_PREVIEW' - } - ); - }); - $('a.documentdownload').click(function() { - $.post('<?php echo DOL_URL_ROOT."/blockedlog/ajax/block-add.php" ?>' - , { - id:<?php echo $object->id; ?> - , element:'<?php echo $object->element ?>' - , action:'DOC_DOWNLOAD' - } - ); - }); - }); - </script> + <script> + jQuery(document).ready(function () { + $('a.documentpreview').click(function() { + $.post('<?php echo DOL_URL_ROOT."/blockedlog/ajax/block-add.php" ?>' + , { + id:<?php echo $object->id; ?> + , element:'<?php echo $object->element ?>' + , action:'DOC_PREVIEW' + } + ); + }); + $('a.documentdownload').click(function() { + $.post('<?php echo DOL_URL_ROOT."/blockedlog/ajax/block-add.php" ?>' + , { + id:<?php echo $object->id; ?> + , element:'<?php echo $object->element ?>' + , action:'DOC_DOWNLOAD' + } + ); + }); + }); + </script> <?php } - } + } // A div for the address popup print "\n<!-- A div to allow dialog popup -->\n"; @@ -2914,19 +3073,16 @@ if (!function_exists("llxFooter")) // Add code for the asynchronous anonymous first ping (for telemetry) // You can use &forceping=1 in parameters to force the ping if the ping was already sent. $forceping = GETPOST('forceping', 'alpha'); - if (($_SERVER["PHP_SELF"] == DOL_URL_ROOT.'/index.php') || $forceping) - { + if (($_SERVER["PHP_SELF"] == DOL_URL_ROOT.'/index.php') || $forceping) { //print '<!-- instance_unique_id='.$conf->file->instance_unique_id.' MAIN_FIRST_PING_OK_ID='.$conf->global->MAIN_FIRST_PING_OK_ID.' -->'; $hash_unique_id = md5('dolibarr'.$conf->file->instance_unique_id); if (empty($conf->global->MAIN_FIRST_PING_OK_DATE) || (!empty($conf->file->instance_unique_id) && ($hash_unique_id != $conf->global->MAIN_FIRST_PING_OK_ID) && ($conf->global->MAIN_FIRST_PING_OK_ID != 'disabled')) - || $forceping) - { + || $forceping) { // No ping done if we are into an alpha version if (strpos('alpha', DOL_VERSION) > 0 && !$forceping) { print "\n<!-- NO JS CODE TO ENABLE the anonymous Ping. It is an alpha version -->\n"; - } elseif (empty($_COOKIE['DOLINSTALLNOPING_'.$hash_unique_id]) || $forceping) // Cookie is set when we uncheck the checkbox in the installation wizard. - { + } elseif (empty($_COOKIE['DOLINSTALLNOPING_'.$hash_unique_id]) || $forceping) { // Cookie is set when we uncheck the checkbox in the installation wizard. // MAIN_LAST_PING_KO_DATE // Disable ping if MAIN_LAST_PING_KO_DATE is set and is recent if (!empty($conf->global->MAIN_LAST_PING_KO_DATE) && substr($conf->global->MAIN_LAST_PING_KO_DATE, 0, 6) == dol_print_date(dol_now(), '%Y%m') && !$forceping) { @@ -2939,51 +3095,55 @@ if (!function_exists("llxFooter")) $url_for_ping = (empty($conf->global->MAIN_URL_FOR_PING) ? "https://ping.dolibarr.org/" : $conf->global->MAIN_URL_FOR_PING); // Try to guess the distrib used $distrib = 'standard'; - if ($_SERVER["SERVER_ADMIN"] == 'doliwamp@localhost') $distrib = 'doliwamp'; - if (!empty($dolibarr_distrib)) $distrib = $dolibarr_distrib; + if ($_SERVER["SERVER_ADMIN"] == 'doliwamp@localhost') { + $distrib = 'doliwamp'; + } + if (!empty($dolibarr_distrib)) { + $distrib = $dolibarr_distrib; + } ?> - <script> - jQuery(document).ready(function (tmp) { - $.ajax({ - method: "POST", - url: "<?php echo $url_for_ping ?>", - timeout: 500, // timeout milliseconds - cache: false, - data: { - hash_algo: 'md5', - hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>', - action: 'dolibarrping', - version: '<?php echo (float) DOL_VERSION; ?>', - entity: '<?php echo (int) $conf->entity; ?>', - dbtype: '<?php echo dol_escape_js($db->type); ?>', - country_code: '<?php echo $mysoc->country_code ? dol_escape_js($mysoc->country_code) : 'unknown'; ?>', - php_version: '<?php echo dol_escape_js(phpversion()); ?>', - os_version: '<?php echo dol_escape_js(version_os('smr')); ?>', - distrib: '<?php echo $distrib ? dol_escape_js($distrib) : 'unknown'; ?>' - }, - success: function (data, status, xhr) { // success callback function (data contains body of response) - console.log("Ping ok"); - $.ajax({ - method: 'GET', - url: '<?php echo DOL_URL_ROOT.'/core/ajax/pingresult.php'; ?>', - timeout: 500, // timeout milliseconds - cache: false, - data: { hash_algo: 'md5', hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>', action: 'firstpingok' }, // for update - }); - }, - error: function (data,status,xhr) { // error callback function - console.log("Ping ko: " + data); - $.ajax({ - method: 'GET', - url: '<?php echo DOL_URL_ROOT.'/core/ajax/pingresult.php'; ?>', - timeout: 500, // timeout milliseconds - cache: false, - data: { hash_algo: 'md5', hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>', action: 'firstpingko' }, - }); - } - }); - }); - </script> + <script> + jQuery(document).ready(function (tmp) { + $.ajax({ + method: "POST", + url: "<?php echo $url_for_ping ?>", + timeout: 500, // timeout milliseconds + cache: false, + data: { + hash_algo: 'md5', + hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>', + action: 'dolibarrping', + version: '<?php echo (float) DOL_VERSION; ?>', + entity: '<?php echo (int) $conf->entity; ?>', + dbtype: '<?php echo dol_escape_js($db->type); ?>', + country_code: '<?php echo $mysoc->country_code ? dol_escape_js($mysoc->country_code) : 'unknown'; ?>', + php_version: '<?php echo dol_escape_js(phpversion()); ?>', + os_version: '<?php echo dol_escape_js(version_os('smr')); ?>', + distrib: '<?php echo $distrib ? dol_escape_js($distrib) : 'unknown'; ?>' + }, + success: function (data, status, xhr) { // success callback function (data contains body of response) + console.log("Ping ok"); + $.ajax({ + method: 'GET', + url: '<?php echo DOL_URL_ROOT.'/core/ajax/pingresult.php'; ?>', + timeout: 500, // timeout milliseconds + cache: false, + data: { hash_algo: 'md5', hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>', action: 'firstpingok' }, // for update + }); + }, + error: function (data,status,xhr) { // error callback function + console.log("Ping ko: " + data); + $.ajax({ + method: 'GET', + url: '<?php echo DOL_URL_ROOT.'/core/ajax/pingresult.php'; ?>', + timeout: 500, // timeout milliseconds + cache: false, + data: { hash_algo: 'md5', hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>', action: 'firstpingko' }, + }); + } + }); + }); + </script> <?php } } else { diff --git a/htdocs/margin/admin/margin.php b/htdocs/margin/admin/margin.php index d9c470b7acd..c041700fa18 100644 --- a/htdocs/margin/admin/margin.php +++ b/htdocs/margin/admin/margin.php @@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php"; $langs->loadLangs(array("admin", "bills", "margins", "stocks")); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); @@ -40,11 +42,9 @@ $action = GETPOST('action', 'aZ09'); * Action */ -if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) -{ +if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; - if (dolibarr_set_const($db, $code, 1, 'yesno', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, $code, 1, 'yesno', 0, '', $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -52,11 +52,9 @@ if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) } } -if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) -{ +if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; - if (dolibarr_del_const($db, $code, $conf->entity) > 0) - { + if (dolibarr_del_const($db, $code, $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -64,30 +62,24 @@ if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) } } -if ($action == 'remises') -{ - if (dolibarr_set_const($db, 'MARGIN_METHODE_FOR_DISCOUNT', $_POST['MARGIN_METHODE_FOR_DISCOUNT'], 'chaine', 0, '', $conf->entity) > 0) - { +if ($action == 'remises') { + if (dolibarr_set_const($db, 'MARGIN_METHODE_FOR_DISCOUNT', $_POST['MARGIN_METHODE_FOR_DISCOUNT'], 'chaine', 0, '', $conf->entity) > 0) { setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); } else { dol_print_error($db); } } -if ($action == 'typemarges') -{ - if (dolibarr_set_const($db, 'MARGIN_TYPE', $_POST['MARGIN_TYPE'], 'chaine', 0, '', $conf->entity) > 0) - { +if ($action == 'typemarges') { + if (dolibarr_set_const($db, 'MARGIN_TYPE', $_POST['MARGIN_TYPE'], 'chaine', 0, '', $conf->entity) > 0) { setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); } else { dol_print_error($db); } } -if ($action == 'contact') -{ - if (dolibarr_set_const($db, 'AGENT_CONTACT_TYPE', $_POST['AGENT_CONTACT_TYPE'], 'chaine', 0, '', $conf->entity) > 0) - { +if ($action == 'contact') { + if (dolibarr_set_const($db, 'AGENT_CONTACT_TYPE', $_POST['AGENT_CONTACT_TYPE'], 'chaine', 0, '', $conf->entity) > 0) { setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); } else { dol_print_error($db); @@ -126,18 +118,23 @@ print '<tr class="oddeven">'; print '<td>'.$langs->trans("MARGIN_TYPE").'</td>'; print '<td>'; print ' <input type="radio" name="MARGIN_TYPE" value="1" '; -if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == '1') +if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == '1') { print 'checked '; +} print '/> '; print $langs->trans('MargeType1'); print '<br>'; print ' <input type="radio" name="MARGIN_TYPE" value="pmp" '; -if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') print 'checked '; +if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') { + print 'checked '; +} print '/> '; print $langs->trans('MargeType2'); print '<br>'; print ' <input type="radio" name="MARGIN_TYPE" value="costprice" '; -if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') print 'checked '; +if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') { + print 'checked '; +} print '/> '; print $langs->trans('MargeType3'); print '</td>'; @@ -153,12 +150,10 @@ print '</form>'; print '<tr class="oddeven">'; print '<td>'.$langs->trans("DisplayMarginRates").'</td>'; print '<td colspan="2">'; -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print ajax_constantonoff('DISPLAY_MARGIN_RATES'); } else { - if (empty($conf->global->DISPLAY_MARGIN_RATES)) - { + if (empty($conf->global->DISPLAY_MARGIN_RATES)) { print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_DISPLAY_MARGIN_RATES&amp;token='.newToken().'">'.img_picto($langs->trans("Disabled"), 'off').'</a>'; } else { print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_DISPLAY_MARGIN_RATES&amp;token='.newToken().'">'.img_picto($langs->trans("Enabled"), 'on').'</a>'; @@ -172,12 +167,10 @@ print '</tr>'; print '<tr class="oddeven">'; print '<td>'.$langs->trans("DisplayMarkRates").'</td>'; print '<td colspan="2">'; -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print ajax_constantonoff('DISPLAY_MARK_RATES'); } else { - if (empty($conf->global->DISPLAY_MARK_RATES)) - { + if (empty($conf->global->DISPLAY_MARK_RATES)) { print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_DISPLAY_MARK_RATES">'.img_picto($langs->trans("Disabled"), 'off').'</a>'; } else { print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_DISPLAY_MARK_RATES">'.img_picto($langs->trans("Enabled"), 'on').'</a>'; @@ -191,12 +184,10 @@ print '</tr>'; print '<tr class="oddeven">'; print '<td>'.$langs->trans("ForceBuyingPriceIfNull").'</td>'; print '<td colspan="2">'; -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print ajax_constantonoff('ForceBuyingPriceIfNull'); } else { - if (empty($conf->global->ForceBuyingPriceIfNull)) - { + if (empty($conf->global->ForceBuyingPriceIfNull)) { print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_ForceBuyingPriceIfNull&amp;token='.newToken().'">'.img_picto($langs->trans("Disabled"), 'off').'</a>'; } else { print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_ForceBuyingPriceIfNull&amp;token='.newToken().'">'.img_picto($langs->trans("Enabled"), 'on').'</a>'; diff --git a/htdocs/margin/agentMargins.php b/htdocs/margin/agentMargins.php index d97d992b99d..717e2d02c1b 100644 --- a/htdocs/margin/agentMargins.php +++ b/htdocs/margin/agentMargins.php @@ -39,16 +39,21 @@ $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 (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) -{ - if ($agentid > 0) +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + if ($agentid > 0) { $sortfield = "s.nom"; - else $sortfield = "u.lastname"; + } else { + $sortfield = "u.lastname"; + } } $startdate = $enddate = ''; @@ -60,10 +65,12 @@ $enddateday = GETPOST('enddateday', 'int'); $enddatemonth = GETPOST('enddatemonth', 'int'); $enddateyear = GETPOST('enddateyear', 'int'); -if (!empty($startdatemonth)) +if (!empty($startdatemonth)) { $startdate = dol_mktime(0, 0, 0, $startdatemonth, $startdateday, $startdateyear); -if (!empty($enddatemonth)) +} +if (!empty($enddatemonth)) { $enddate = dol_mktime(23, 59, 59, $enddatemonth, $enddateday, $enddateyear); +} // Security check if ($user->rights->margins->read->all) { @@ -154,23 +161,31 @@ $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= ' AND f.entity IN ('.getEntity('invoice').')'; $sql .= " AND sc.fk_soc = f.fk_soc"; $sql .= " AND (d.product_type = 0 OR d.product_type = 1)"; -if (!empty($conf->global->AGENT_CONTACT_TYPE)) +if (!empty($conf->global->AGENT_CONTACT_TYPE)) { $sql .= " AND ((e.fk_socpeople IS NULL AND sc.fk_user = u.rowid) OR (e.fk_socpeople IS NOT NULL AND e.fk_socpeople = u.rowid))"; -else $sql .= " AND sc.fk_user = u.rowid"; +} else { + $sql .= " AND sc.fk_user = u.rowid"; +} $sql .= " AND f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")"; $sql .= ' AND s.entity IN ('.getEntity('societe').')'; $sql .= " AND d.fk_facture = f.rowid"; if ($agentid > 0) { - if (!empty($conf->global->AGENT_CONTACT_TYPE)) - $sql .= " AND ((e.fk_socpeople IS NULL AND sc.fk_user = ".$agentid.") OR (e.fk_socpeople IS NOT NULL AND e.fk_socpeople = ".$agentid."))"; - else $sql .= " AND sc.fk_user = ".$agentid; + if (!empty($conf->global->AGENT_CONTACT_TYPE)) { + $sql .= " AND ((e.fk_socpeople IS NULL AND sc.fk_user = ".$agentid.") OR (e.fk_socpeople IS NOT NULL AND e.fk_socpeople = ".$agentid."))"; + } else { + $sql .= " AND sc.fk_user = ".$agentid; + } +} +if (!empty($startdate)) { + $sql .= " AND f.datef >= '".$db->idate($startdate)."'"; +} +if (!empty($enddate)) { + $sql .= " AND f.datef <= '".$db->idate($enddate)."'"; } -if (!empty($startdate)) - $sql .= " AND f.datef >= '".$db->idate($startdate)."'"; -if (!empty($enddate)) - $sql .= " AND f.datef <= '".$db->idate($enddate)."'"; $sql .= " AND d.buy_price_ht IS NOT NULL"; -if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) $sql .= " AND d.buy_price_ht <> 0"; +if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) { + $sql .= " AND d.buy_price_ht <> 0"; +} //if ($agentid > 0) $sql.= " GROUP BY s.rowid, s.nom, s.code_client, s.client, u.rowid, u.login, u.lastname, u.firstname"; //else $sql.= " GROUP BY u.rowid, u.login, u.lastname, u.firstname"; $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client, u.rowid, u.login, u.lastname, u.firstname"; @@ -183,28 +198,42 @@ print '<br>'; print img_info('').' '.$langs->trans("MarginPerSaleRepresentativeWarning").'<br>'; $param = ''; -if (!empty($agentid)) $param .= "&amp;agentid=".urlencode($agentid); -if (!empty($startdateday)) $param .= "&amp;startdateday=".urlencode($startdateday); -if (!empty($startdatemonth)) $param .= "&amp;startdatemonth=".urlencode($startdatemonth); -if (!empty($startdateyear)) $param .= "&amp;startdateyear=".urlencode($startdateyear); -if (!empty($enddateday)) $param .= "&amp;enddateday=".urlencode($enddateday); -if (!empty($enddatemonth)) $param .= "&amp;enddatemonth=".urlencode($enddatemonth); -if (!empty($enddateyear)) $param .= "&amp;enddateyear=".urlencode($enddateyear); +if (!empty($agentid)) { + $param .= "&amp;agentid=".urlencode($agentid); +} +if (!empty($startdateday)) { + $param .= "&amp;startdateday=".urlencode($startdateday); +} +if (!empty($startdatemonth)) { + $param .= "&amp;startdatemonth=".urlencode($startdatemonth); +} +if (!empty($startdateyear)) { + $param .= "&amp;startdateyear=".urlencode($startdateyear); +} +if (!empty($enddateday)) { + $param .= "&amp;enddateday=".urlencode($enddateday); +} +if (!empty($enddatemonth)) { + $param .= "&amp;enddatemonth=".urlencode($enddatemonth); +} +if (!empty($enddateyear)) { + $param .= "&amp;enddateyear=".urlencode($enddateyear); +} dol_syslog('margin::agentMargins.php', LOG_DEBUG); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); print '<br>'; print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1); - if ($conf->global->MARGIN_TYPE == "1") + if ($conf->global->MARGIN_TYPE == "1") { $labelcostprice = 'BuyingPrice'; - else // value is 'costprice' or 'pmp' + } else { // value is 'costprice' or 'pmp' $labelcostprice = 'CostPrice'; + } $moreforfilter = ''; @@ -213,21 +242,24 @@ if ($result) print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; print '<tr class="liste_titre">'; - if ($agentid > 0) + if ($agentid > 0) { print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); - else print_liste_field_titre("SalesRepresentative", $_SERVER["PHP_SELF"], "u.lastname", "", $param, '', $sortfield, $sortorder); + } else { + print_liste_field_titre("SalesRepresentative", $_SERVER["PHP_SELF"], "u.lastname", "", $param, '', $sortfield, $sortorder); + } print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); + } print "</tr>\n"; - if ($num > 0) - { + if ($num > 0) { $group_list = array(); while ($objp = $db->fetch_object($result)) { if ($agentid > 0) { @@ -295,10 +327,12 @@ if ($result) print '<td class="nowrap right">'.price(price2num($pv, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($pa, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($marge, 'MT')).'</td>'; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>'; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>'; + } print "</tr>\n"; $i++; @@ -319,10 +353,12 @@ if ($result) print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>'; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>'; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>'; + } print '</tr>'; print '</table>'; diff --git a/htdocs/margin/checkMargins.php b/htdocs/margin/checkMargins.php index 5d019b2693a..f61d8d02e55 100644 --- a/htdocs/margin/checkMargins.php +++ b/htdocs/margin/checkMargins.php @@ -44,12 +44,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) { $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 = 'f.ref'; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = 'f.ref'; +} $startdate = $enddate = ''; @@ -73,15 +79,20 @@ if (GETPOST("button_search_x") || GETPOST("button_search")) { * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; @@ -108,23 +119,22 @@ if (empty($reshook)) } // 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_ref = ''; $search_array_options = array(); } // Mass actions /* - $objectclass='Product'; - if ((string) $type == '1') { $objectlabel='Services'; } - if ((string) $type == '0') { $objectlabel='Products'; } + $objectclass='Product'; + if ((string) $type == '1') { $objectlabel='Services'; } + if ((string) $type == '0') { $objectlabel='Products'; } - $permissiontoread = $user->rights->produit->lire; - $permissiontodelete = $user->rights->produit->supprimer; - $uploaddir = $conf->product->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - */ + $permissiontoread = $user->rights->produit->lire; + $permissiontodelete = $user->rights->produit->supprimer; + $uploaddir = $conf->product->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + */ } @@ -146,12 +156,24 @@ llxHeader('', $title); // print load_fiche_titre($text); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; -if ($search_ref != '') $param .= '&search_ref='.urlencode($search_ref); -if (!empty($startdate)) $param .= '&startdatemonth='.GETPOST('startdatemonth', 'int').'&startdateday='.GETPOST('startdateday', 'int').'&startdateyear='.GETPOST('startdateyear', 'int'); -if (!empty($enddate)) $param .= '&enddatemonth='.GETPOST('enddatemonth', 'int').'&enddateday='.GETPOST('enddateday', 'int').'&enddateyear='.GETPOST('enddateyear', 'int'); -if ($optioncss != '') $param .= '&optioncss='.$optioncss; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.$contextpage; +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; +} +if ($search_ref != '') { + $param .= '&search_ref='.urlencode($search_ref); +} +if (!empty($startdate)) { + $param .= '&startdatemonth='.GETPOST('startdatemonth', 'int').'&startdateday='.GETPOST('startdateday', 'int').'&startdateyear='.GETPOST('startdateyear', 'int'); +} +if (!empty($enddate)) { + $param .= '&enddatemonth='.GETPOST('enddatemonth', 'int').'&enddateday='.GETPOST('enddateday', 'int').'&enddateyear='.GETPOST('enddateyear', 'int'); +} +if ($optioncss != '') { + $param .= '&optioncss='.$optioncss; +} // Show tabs $head = marges_prepare_head($user); @@ -194,9 +216,15 @@ $sql .= " INNER JOIN ".MAIN_DB_PREFIX."facturedet as d ON d.fk_facture = f.rowi $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid"; $sql .= " WHERE f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")"; $sql .= " AND f.entity IN (".getEntity('invoice').") "; -if (!empty($startdate)) $sql .= " AND f.datef >= '".$db->idate($startdate)."'"; -if (!empty($enddate)) $sql .= " AND f.datef <= '".$db->idate($enddate)."'"; -if ($search_ref) $sql .= natural_search('f.ref', $search_ref); +if (!empty($startdate)) { + $sql .= " AND f.datef >= '".$db->idate($startdate)."'"; +} +if (!empty($enddate)) { + $sql .= " AND f.datef <= '".$db->idate($enddate)."'"; +} +if ($search_ref) { + $sql .= natural_search('f.ref', $search_ref); +} $sql .= " AND d.buy_price_ht IS NOT NULL"; $sql .= $db->order($sortfield, $sortorder); @@ -205,8 +233,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { dol_syslog(__FILE__, LOG_DEBUG); $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -221,10 +248,11 @@ if ($result) { print '<br>'; print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit); - if ($conf->global->MARGIN_TYPE == "1") + if ($conf->global->MARGIN_TYPE == "1") { $labelcostprice = 'BuyingPrice'; - else // value is 'costprice' or 'pmp' + } else { // value is 'costprice' or 'pmp' $labelcostprice = 'CostPrice'; + } $moreforfilter = ''; @@ -260,8 +288,7 @@ if ($result) { print "</tr>\n"; $i = 0; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($result); print '<tr class="oddeven">'; diff --git a/htdocs/margin/customerMargins.php b/htdocs/margin/customerMargins.php index 1693462b749..05d5aa1ca5c 100644 --- a/htdocs/margin/customerMargins.php +++ b/htdocs/margin/customerMargins.php @@ -36,7 +36,9 @@ $socid = GETPOST('socid', 'int'); $TSelectedProducts = GETPOST('products', 'array'); $TSelectedCats = GETPOST('categories', 'array'); -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'societe', '', ''); $result = restrictedArea($user, 'margins'); @@ -48,19 +50,27 @@ $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 (!$sortfield) $sortfield = "s.nom"; // Set here default search field -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "s.nom"; // Set here default search field +} +if (!$sortorder) { + $sortorder = "ASC"; +} $startdate = $enddate = ''; -if (!empty($_POST['startdatemonth'])) - $startdate = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']); -if (!empty($_POST['enddatemonth'])) - $enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']); +if (!empty($_POST['startdatemonth'])) { + $startdate = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']); +} +if (!empty($_POST['enddatemonth'])) { + $enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']); +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new Societe($db); @@ -98,16 +108,19 @@ if ($socid > 0) { $soc = new Societe($db); $soc->fetch($socid); - if ($soc->client) - { + if ($soc->client) { print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>'; print '<td class="maxwidthonsmartphone" colspan="4">'; print img_picto('', 'company').$form->select_company($socid, 'socid', '(client=1 OR client=3)', 1, 0, 0); print '</td></tr>'; $client = true; - if (!$sortorder) $sortorder = "DESC"; - if (!$sortfield) $sortfield = "f.datef"; + if (!$sortorder) { + $sortorder = "DESC"; + } + if (!$sortfield) { + $sortfield = "f.datef"; + } } } else { print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>'; @@ -118,11 +131,11 @@ if ($socid > 0) { $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) -{ - if ($client) - { +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + if ($client) { $sortfield = "f.datef"; $sortorder = "DESC"; } else { @@ -202,7 +215,9 @@ $invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABAND $sql = "SELECT"; $sql .= " s.rowid as socid, s.nom as name, s.code_client, s.client,"; -if ($client) $sql .= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,"; +if ($client) { + $sql .= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,"; +} $sql .= " sum(d.total_ht) as selling_price,"; // Note: qty and buy_price_ht is always positive (if not, your database may be corrupted, you can update this) $sql .= " sum(".$db->ifsql('d.total_ht < 0', 'd.qty * d.buy_price_ht * -1 * (d.situation_percent / 100)', 'd.qty * d.buy_price_ht * (d.situation_percent / 100)').") as buying_price,"; @@ -214,10 +229,16 @@ if (!empty($TSelectedCats)) { $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=d.fk_product'; } -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE f.fk_soc = s.rowid"; -if ($socid > 0) $sql .= ' AND s.rowid = '.$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($socid > 0) { + $sql .= ' AND s.rowid = '.$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " AND f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")"; $sql .= ' AND s.entity IN ('.getEntity('societe').')'; $sql .= ' AND f.entity IN ('.getEntity('invoice').')'; @@ -229,32 +250,38 @@ if (!empty($TSelectedProducts)) { if (!empty($TSelectedCats)) { $sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats).')'; } -if (!empty($startdate)) -$sql .= " AND f.datef >= '".$db->idate($startdate)."'"; -if (!empty($enddate)) -$sql .= " AND f.datef <= '".$db->idate($enddate)."'"; +if (!empty($startdate)) { + $sql .= " AND f.datef >= '".$db->idate($startdate)."'"; +} +if (!empty($enddate)) { + $sql .= " AND f.datef <= '".$db->idate($enddate)."'"; +} $sql .= " AND d.buy_price_ht IS NOT NULL"; -if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) -$sql .= " AND d.buy_price_ht <> 0"; -if ($client) $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut"; -else $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client"; +if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) { + $sql .= " AND d.buy_price_ht <> 0"; +} +if ($client) { + $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut"; +} else { + $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client"; +} $sql .= $db->order($sortfield, $sortorder); // TODO: calculate total to display then restore pagination //$sql.= $db->plimit($conf->liste_limit +1, $offset); dol_syslog('margin::customerMargins.php', LOG_DEBUG); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); - print '<br>'; + print '<br>'; print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1); - if ($conf->global->MARGIN_TYPE == "1") + if ($conf->global->MARGIN_TYPE == "1") { $labelcostprice = 'BuyingPrice'; - else // value is 'costprice' or 'pmp' + } else { // value is 'costprice' or 'pmp' $labelcostprice = 'CostPrice'; + } $moreforfilter = ''; @@ -264,33 +291,34 @@ if ($result) print '<tr class="liste_titre">'; if (!empty($client)) { - print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;socid=".$socid, '', $sortfield, $sortorder); - print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;socid=".$socid, 'align="center"', $sortfield, $sortorder); - } else print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "s.nom", "", "&amp;socid=".$socid, '', $sortfield, $sortorder); + print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;socid=".$socid, '', $sortfield, $sortorder); + print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;socid=".$socid, 'align="center"', $sortfield, $sortorder); + } else { + print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "s.nom", "", "&amp;socid=".$socid, '', $sortfield, $sortorder); + } print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder); print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder); - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder); - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder); + } print "</tr>\n"; $cumul_achat = 0; $cumul_vente = 0; - if ($num > 0) - { - while ($i < $num /*&& $i < $conf->liste_limit*/) - { + if ($num > 0) { + while ($i < $num /*&& $i < $conf->liste_limit*/) { $objp = $db->fetch_object($result); $pa = $objp->buying_price; $pv = $objp->selling_price; $marge = $objp->marge; - if ($marge < 0) - { + if ($marge < 0) { $marginRate = ($pa != 0) ?-1 * (100 * $marge / $pa) : ''; $markRate = ($pv != 0) ?-1 * (100 * $marge / $pv) : ''; } else { @@ -307,20 +335,22 @@ if ($result) print '</td>'; print '<td class="center">'; print dol_print_date($db->jdate($objp->datef), 'day').'</td>'; - } else { + } else { $companystatic->id = $objp->socid; $companystatic->name = $objp->name; $companystatic->client = $objp->client; - print '<td>'.$companystatic->getNomUrl(1, 'margin').'</td>'; - } + print '<td>'.$companystatic->getNomUrl(1, 'margin').'</td>'; + } print '<td class="nowrap right">'.price(price2num($pv, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($pa, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($marge, 'MT')).'</td>'; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>'; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>'; + } print "</tr>\n"; $i++; @@ -344,17 +374,21 @@ if ($result) //} print '<tr class="liste_total">'; - if ($client) + if ($client) { print '<td colspan=2>'; - else print '<td>'; - print $langs->trans('TotalMargin')."</td>"; + } else { + print '<td>'; + } + print $langs->trans('TotalMargin')."</td>"; print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>'; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>'; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>'; + } print '</tr>'; print '</table>'; diff --git a/htdocs/margin/lib/margins.lib.php b/htdocs/margin/lib/margins.lib.php index 6161ba2b6e4..802541b98ca 100644 --- a/htdocs/margin/lib/margins.lib.php +++ b/htdocs/margin/lib/margins.lib.php @@ -124,8 +124,7 @@ function getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localta if ($fk_pa > 0 && empty($paht)) { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $product = new ProductFournisseur($db); - if ($product->fetch_product_fournisseur_price($fk_pa)) - { + if ($product->fetch_product_fournisseur_price($fk_pa)) { $paht_ret = $product->fourn_unitprice * (1 - $product->fourn_remise_percent / 100); } else { $paht_ret = $paht; @@ -141,16 +140,20 @@ function getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localta $pu_ht_remise = price2num($pu_ht_remise, 'MU'); // calcul marge - if ($pu_ht_remise < 0) + if ($pu_ht_remise < 0) { $marge = -1 * (abs($pu_ht_remise) - $paht_ret); - else $marge = $pu_ht_remise - $paht_ret; + } else { + $marge = $pu_ht_remise - $paht_ret; + } // calcul taux marge - if ($paht_ret != 0) + if ($paht_ret != 0) { $marge_tx_ret = (100 * $marge) / $paht_ret; + } // calcul taux marque - if ($pu_ht_remise != 0) + if ($pu_ht_remise != 0) { $marque_tx_ret = (100 * $marge) / $pu_ht_remise; + } return array($paht_ret, $marge_tx_ret, $marque_tx_ret); } diff --git a/htdocs/margin/productMargins.php b/htdocs/margin/productMargins.php index 3bb7eff8e23..0ac47243723 100644 --- a/htdocs/margin/productMargins.php +++ b/htdocs/margin/productMargins.php @@ -41,9 +41,13 @@ $TSelectedCats = GETPOST('categories', 'array'); // Security check $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldtype = (!empty($ref) ? 'ref' : 'rowid'); -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); -if (empty($user->rights->margins->liretous)) accessforbidden(); +if (empty($user->rights->margins->liretous)) { + accessforbidden(); +} $mesg = ''; @@ -52,14 +56,14 @@ $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 (!$sortfield) -{ - if ($id > 0) - { +if (!$sortfield) { + if ($id > 0) { $sortfield = "f.datef"; $sortorder = "DESC"; } else { @@ -70,10 +74,12 @@ if (!$sortfield) $startdate = $enddate = ''; -if (!empty($_POST['startdatemonth'])) - $startdate = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']); -if (!empty($_POST['enddatemonth'])) - $enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']); +if (!empty($_POST['startdatemonth'])) { + $startdate = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']); +} +if (!empty($_POST['enddatemonth'])) { + $enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']); +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new Product($db); @@ -169,8 +175,12 @@ print '</form>'; $invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABANDONED); $sql = "SELECT p.label, p.rowid, p.fk_product_type, p.ref, p.entity as pentity,"; -if ($id > 0) $sql .= " d.fk_product,"; -if ($id > 0) $sql .= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,"; +if ($id > 0) { + $sql .= " d.fk_product,"; +} +if ($id > 0) { + $sql .= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,"; +} $sql .= " SUM(d.total_ht) as selling_price,"; // Note: qty and buy_price_ht is always positive (if not your database may be corrupted, you can update this) $sql .= " SUM(d.qty) as product_qty,"; @@ -187,38 +197,45 @@ $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= ' AND f.entity IN ('.getEntity('invoice').')'; $sql .= " AND f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")"; $sql .= " AND d.fk_facture = f.rowid"; -if ($id > 0) +if ($id > 0) { $sql .= " AND d.fk_product =".$id; +} if (!empty($TSelectedCats)) { $sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats).')'; } -if (!empty($startdate)) - $sql .= " AND f.datef >= '".$db->idate($startdate)."'"; -if (!empty($enddate)) - $sql .= " AND f.datef <= '".$db->idate($enddate)."'"; +if (!empty($startdate)) { + $sql .= " AND f.datef >= '".$db->idate($startdate)."'"; +} +if (!empty($enddate)) { + $sql .= " AND f.datef <= '".$db->idate($enddate)."'"; +} $sql .= " AND d.buy_price_ht IS NOT NULL"; -if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) +if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) { $sql .= " AND d.buy_price_ht <> 0"; -if ($id > 0) $sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity, d.fk_product, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut"; -else $sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity"; +} +if ($id > 0) { + $sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity, d.fk_product, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut"; +} else { + $sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity"; +} $sql .= $db->order($sortfield, $sortorder); // TODO: calculate total to display then restore pagination //$sql.= $db->plimit($conf->liste_limit +1, $offset); dol_syslog('margin::productMargins.php', LOG_DEBUG); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); print '<br>'; print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;id=".$id, $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1); //var_dump($conf->global->MARGIN_TYPE); - if ($conf->global->MARGIN_TYPE == "1") + if ($conf->global->MARGIN_TYPE == "1") { $labelcostprice = 'BuyingPrice'; - else // value is 'costprice' or 'pmp' + } else { // value is 'costprice' or 'pmp' $labelcostprice = 'CostPrice'; + } $moreforfilter = ''; @@ -228,37 +245,36 @@ if ($result) print '<tr class="liste_titre">'; if ($id > 0) { - print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;id=".$id, '', $sortfield, $sortorder); - print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'center '); - } else { - print_liste_field_titre("ProductService", $_SERVER["PHP_SELF"], "p.ref", "", "&amp;id=".$id, '', $sortfield, $sortorder); - } + print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;id=".$id, '', $sortfield, $sortorder); + print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'center '); + } else { + print_liste_field_titre("ProductService", $_SERVER["PHP_SELF"], "p.ref", "", "&amp;id=".$id, '', $sortfield, $sortorder); + } print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "product_qty", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'center '); print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right '); - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right '); - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right '); + } print "</tr>\n"; $cumul_achat = 0; $cumul_vente = 0; $cumul_qty = 0; - if ($num > 0) - { - while ($i < $num /*&& $i < $conf->liste_limit*/) - { + if ($num > 0) { + while ($i < $num /*&& $i < $conf->liste_limit*/) { $objp = $db->fetch_object($result); $qty = $objp->product_qty; $pa = $objp->buying_price; $pv = $objp->selling_price; $marge = $objp->marge; - if ($marge < 0) - { + if ($marge < 0) { $marginRate = ($pa != 0) ?-1 * (100 * $marge / $pa) : ''; $markRate = ($pv != 0) ?-1 * (100 * $marge / $pv) : ''; } else { @@ -277,8 +293,7 @@ if ($result) print dol_print_date($db->jdate($objp->datef), 'day')."</td>"; } else { print '<td>'; - if ($objp->rowid > 0) - { + if ($objp->rowid > 0) { $product_static->type = $objp->fk_product_type; $product_static->id = $objp->rowid; $product_static->ref = $objp->ref; @@ -296,10 +311,12 @@ if ($result) print '<td class="nowrap right">'.price(price2num($pv, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($pa, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($marge, 'MT')).'</td>'; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>'; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>'; + } print "</tr>\n"; $i++; @@ -317,18 +334,22 @@ if ($result) $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : ''; print '<tr class="liste_total">'; - if ($id > 0) + if ($id > 0) { print '<td colspan=2>'; - else print '<td>'; + } else { + print '<td>'; + } print $langs->trans('TotalMargin').'</td>'; print '<td class="center">'.$cumul_qty.'</td>'; print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>'; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>'; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>'; + } print "</tr>\n"; print "</table>"; diff --git a/htdocs/margin/tabs/productMargins.php b/htdocs/margin/tabs/productMargins.php index 5fcec11c93b..031c49e4cd0 100644 --- a/htdocs/margin/tabs/productMargins.php +++ b/htdocs/margin/tabs/productMargins.php @@ -36,9 +36,13 @@ $confirm = GETPOST('confirm', 'alpha'); // Security check $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldtype = (!empty($ref) ? 'ref' : 'rowid'); -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); -if (empty($user->rights->margins->liretous)) accessforbidden(); +if (empty($user->rights->margins->liretous)) { + accessforbidden(); +} $object = new Product($db); @@ -46,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 = "DESC"; -if (!$sortfield) $sortfield = "f.datef"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "f.datef"; +} /* @@ -62,20 +72,17 @@ $invoicestatic = new Facture($db); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref); $title = $langs->trans('ProductServiceCard'); $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); - if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) - { + if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Card'); $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; } - if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) - { + if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Card'); $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; } @@ -85,8 +92,7 @@ if ($id > 0 || !empty($ref)) /* * En mode visu */ - if ($result > 0) - { + if ($result > 0) { $head = product_prepare_head($object); $titre = $langs->trans("CardProduct".$object->type); $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -133,7 +139,9 @@ if ($id > 0 || !empty($ref)) $sql = "SELECT s.nom as name, s.rowid as socid, s.code_client,"; $sql .= " f.rowid as facid, f.ref, f.total as total_ht,"; $sql .= " f.datef, f.paye, f.fk_statut as statut, f.type,"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk_user,"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " sc.fk_soc, sc.fk_user,"; + } $sql .= " sum(d.total_ht) as selling_price,"; // may be negative or positive $sql .= " ".$db->ifsql('f.type = 2', -1, 1)." * sum(d.qty) as qty,"; // not always positive in case of Credit note $sql .= " ".$db->ifsql('f.type = 2', -1, 1)." * sum(d.qty * d.buy_price_ht * (d.situation_percent / 100)) as buying_price,"; // not always positive in case of Credit note @@ -141,18 +149,28 @@ if ($id > 0 || !empty($ref)) $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."facture as f"; $sql .= ", ".MAIN_DB_PREFIX."facturedet as d"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.fk_statut > 0"; $sql .= " AND f.entity IN (".getEntity('invoice').")"; $sql .= " AND d.fk_facture = f.rowid"; $sql .= " AND d.fk_product =".$object->id; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if (!empty($socid)) $sql .= " AND f.fk_soc = $socid"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if (!empty($socid)) { + $sql .= " AND f.fk_soc = $socid"; + } $sql .= " AND d.buy_price_ht IS NOT NULL"; - if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) $sql .= " AND d.buy_price_ht <> 0"; + if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) { + $sql .= " AND d.buy_price_ht <> 0"; + } $sql .= " GROUP BY s.nom, s.rowid, s.code_client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut, f.type"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user"; + } $sql .= $db->order($sortfield, $sortorder); // TODO: calculate total to display then restore pagination //$sql.= $db->plimit($conf->liste_limit +1, $offset); @@ -177,10 +195,12 @@ if ($id > 0 || !empty($ref)) print_liste_field_titre("BuyingPrice", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "d.qty", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right '); - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right '); - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right '); + } print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right '); print "</tr>\n"; @@ -209,10 +229,12 @@ if ($id > 0 || !empty($ref)) print "<td class=\"right\">".price(price2num($objp->buying_price, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num($objp->qty, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num($objp->marge, 'MT'))."</td>\n"; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n"; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n"; + } print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>'; print "</tr>\n"; $i++; @@ -225,8 +247,7 @@ if ($id > 0 || !empty($ref)) // affichage totaux marges $totalMargin = $cumul_vente - $cumul_achat; - if ($totalMargin < 0) - { + if ($totalMargin < 0) { $marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : ''; $markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : ''; } else { @@ -239,10 +260,12 @@ if ($id > 0 || !empty($ref)) print '<td class="right">'.price(price2num($cumul_achat, 'MT'))."</td>\n"; print '<td class="right">'.price(price2num($cumul_qty, 'MT'))."</td>\n"; print '<td class="right">'.price(price2num($totalMargin, 'MT'))."</td>\n"; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print '<td class="right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n"; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n"; + } print '<td class="right">&nbsp;</td>'; print "</tr>\n"; print "</table>"; diff --git a/htdocs/margin/tabs/thirdpartyMargins.php b/htdocs/margin/tabs/thirdpartyMargins.php index bfa5ac15811..0103bd03aca 100644 --- a/htdocs/margin/tabs/thirdpartyMargins.php +++ b/htdocs/margin/tabs/thirdpartyMargins.php @@ -30,7 +30,9 @@ $langs->loadLangs(array("companies", "bills", "products", "margins")); // Security check $socid = GETPOST('socid', 'int'); -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'societe', '', ''); @@ -38,15 +40,23 @@ $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 = "f.datef"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "f.datef"; +} $object = new Societe($db); -if ($socid > 0) $object->fetch($socid); +if ($socid > 0) { + $object->fetch($socid); +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('thirdpartymargins', 'globalcard')); @@ -58,7 +68,9 @@ $hookmanager->initHooks(array('thirdpartymargins', 'globalcard')); $parameters = array('id'=>$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'); +} @@ -70,18 +82,19 @@ $invoicestatic = new Facture($db); $form = new Form($db); $title = $langs->trans("ThirdParty").' - '.$langs->trans("Margins"); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name.' - '.$langs->trans("Files"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name.' - '.$langs->trans("Files"); +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($socid > 0) -{ +if ($socid > 0) { $object = new Societe($db); $object->fetch($socid); /* - * Affichage onglets - */ + * Affichage onglets + */ $head = societe_prepare_head($object); @@ -96,27 +109,25 @@ if ($socid > 0) print '<div class="underbanner clearboth"></div>'; print '<table class="border tableforfield" width="100%">'; - if ($object->client) - { - print '<tr><td class="titlefield">'; - print $langs->trans('CustomerCode').'</td><td colspan="3">'; - print $object->code_client; - $tmpcheck = $object->check_codeclient(); - if ($tmpcheck != 0 && $tmpcheck != -5) { - print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; - } - print '</td></tr>'; - } + if ($object->client) { + print '<tr><td class="titlefield">'; + print $langs->trans('CustomerCode').'</td><td colspan="3">'; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_client)); + $tmpcheck = $object->check_codeclient(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; + } + print '</td></tr>'; + } - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) { print '<tr><td class="titlefield">'; print $langs->trans('SupplierCode').'</td><td colspan="3">'; - print $object->code_fournisseur; - $tmpcheck = $object->check_codefournisseur(); - if ($tmpcheck != 0 && $tmpcheck != -5) { - print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; - } + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_fournisseur)); + $tmpcheck = $object->check_codefournisseur(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; + } print '</td></tr>'; } @@ -163,7 +174,9 @@ if ($socid > 0) $sql .= " AND d.fk_facture = f.rowid"; $sql .= " AND f.fk_soc = $socid"; $sql .= " AND d.buy_price_ht IS NOT NULL"; - if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) $sql .= " AND d.buy_price_ht <> 0"; + if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) { + $sql .= " AND d.buy_price_ht <> 0"; + } $sql .= " GROUP BY s.nom, s.rowid, s.code_client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut, f.type"; $sql .= $db->order($sortfield, $sortorder); // TODO: calculate total to display then restore pagination @@ -171,8 +184,7 @@ if ($socid > 0) dol_syslog('margin:tabs:thirdpartyMargins.php', LOG_DEBUG); $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;socid=".$object->id, $sortfield, $sortorder, '', $num, $num, ''); @@ -187,20 +199,20 @@ if ($socid > 0) print_liste_field_titre("SoldAmount", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); print_liste_field_titre("PurchasedAmount", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); + } print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); print "</tr>\n"; $cumul_achat = 0; $cumul_vente = 0; - if ($num > 0) - { - while ($i < $num /*&& $i < $conf->liste_limit*/) - { + if ($num > 0) { + while ($i < $num /*&& $i < $conf->liste_limit*/) { $objp = $db->fetch_object($result); $marginRate = ($objp->buying_price != 0) ? (100 * $objp->marge / $objp->buying_price) : ''; @@ -222,10 +234,12 @@ if ($socid > 0) print "<td class=\"right\">".price(price2num($objp->selling_price, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num(($objp->type == 2 ? -1 : 1) * $objp->buying_price, 'MT'))."</td>\n"; print "<td class=\"right\">".$sign.price(price2num($objp->marge, 'MT'))."</td>\n"; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : $sign.price(price2num($marginRate, 'MT'))."%")."</td>\n"; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n"; + } print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>'; print "</tr>\n"; $i++; @@ -237,8 +251,7 @@ if ($socid > 0) // affichage totaux marges $totalMargin = $cumul_vente - $cumul_achat; - if ($totalMargin < 0) - { + if ($totalMargin < 0) { $marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : ''; $markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : ''; } else { @@ -252,10 +265,12 @@ if ($socid > 0) print "<td class=\"right\">".price(price2num($cumul_vente, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num($cumul_achat, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num($totalMargin, 'MT'))."</td>\n"; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n"; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n"; + } print '<td class="right">&nbsp;</td>'; print "</tr>\n"; } else { diff --git a/htdocs/master.inc.php b/htdocs/master.inc.php index 9efff08306f..e38ddf9b93c 100644 --- a/htdocs/master.inc.php +++ b/htdocs/master.inc.php @@ -32,9 +32,21 @@ * This script reads the conf file, init $lang, $db and and empty $user */ -require_once 'filefunc.inc.php'; // May have been already require by main.inc.php. But may not by scripts. +// Declaration of variables. May have been already require by main.inc.php. But may not by scripts. So, here the require_once must be kept. +require_once 'filefunc.inc.php'; +if (!function_exists('is_countable')) { + /** + * function is_countable (to remove when php version supported will be >= 7.3) + * @param mixed $c data to check if countable + * @return bool + */ + function is_countable($c) + { + return is_array($c) || $c instanceof Countable; + } +} /* * Create $conf object @@ -45,18 +57,20 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/conf.class.php'; $conf = new Conf(); // Set properties specific to database -$conf->db->host = $dolibarr_main_db_host; -$conf->db->port = $dolibarr_main_db_port; -$conf->db->name = $dolibarr_main_db_name; -$conf->db->user = $dolibarr_main_db_user; -$conf->db->pass = empty($dolibarr_main_db_pass) ? '' : $dolibarr_main_db_pass; -$conf->db->type = $dolibarr_main_db_type; +$conf->db->host = $dolibarr_main_db_host; +$conf->db->port = $dolibarr_main_db_port; +$conf->db->name = $dolibarr_main_db_name; +$conf->db->user = $dolibarr_main_db_user; +$conf->db->pass = empty($dolibarr_main_db_pass) ? '' : $dolibarr_main_db_pass; +$conf->db->type = $dolibarr_main_db_type; $conf->db->prefix = $dolibarr_main_db_prefix; $conf->db->character_set = $dolibarr_main_db_character_set; $conf->db->dolibarr_main_db_collation = $dolibarr_main_db_collation; $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption; $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey; -if (defined('TEST_DB_FORCE_TYPE')) $conf->db->type = constant('TEST_DB_FORCE_TYPE'); // Force db type (for test purpose, by PHP unit for example) +if (defined('TEST_DB_FORCE_TYPE')) { + $conf->db->type = constant('TEST_DB_FORCE_TYPE'); // Force db type (for test purpose, by PHP unit for example) +} // Set properties specific to conf file $conf->file->main_limit_users = $dolibarr_main_limit_users; @@ -68,18 +82,17 @@ $conf->file->strict_mode = empty($dolibarr_strict_mode) ? '' : $dolibarr_strict_ $conf->file->instance_unique_id = empty($dolibarr_main_instance_unique_id) ? (empty($dolibarr_main_cookie_cryptkey) ? '' : $dolibarr_main_cookie_cryptkey) : $dolibarr_main_instance_unique_id; // Unique id of instance $conf->file->dol_document_root = array('main' => (string) DOL_DOCUMENT_ROOT); // Define array of document root directories ('/home/htdocs') $conf->file->dol_url_root = array('main' => (string) DOL_URL_ROOT); // Define array of url root path ('' or '/dolibarr') -if (!empty($dolibarr_main_document_root_alt)) -{ +if (!empty($dolibarr_main_document_root_alt)) { // dolibarr_main_document_root_alt can contains several directories $values = preg_split('/[;,]/', $dolibarr_main_document_root_alt); $i = 0; - foreach ($values as $value) $conf->file->dol_document_root['alt'.($i++)] = (string) $value; + foreach ($values as $value) { + $conf->file->dol_document_root['alt'.($i++)] = (string) $value; + } $values = preg_split('/[;,]/', $dolibarr_main_url_root_alt); $i = 0; - foreach ($values as $value) - { - if (preg_match('/^http(s)?:/', $value)) - { + foreach ($values as $value) { + if (preg_match('/^http(s)?:/', $value)) { // Show error message $correct_value = str_replace($dolibarr_main_url_root, '', $value); print '<b>Error:</b><br>'."\n"; @@ -99,36 +112,39 @@ if (!empty($dolibarr_main_document_root_alt)) } // Chargement des includes principaux de librairies communes -if (!defined('NOREQUIREUSER')) require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; // Need 500ko memory -if (!defined('NOREQUIRETRAN')) require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; -if (!defined('NOREQUIRESOC')) require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +if (!defined('NOREQUIREUSER')) { + require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; // Need 500ko memory +} +if (!defined('NOREQUIRETRAN')) { + require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; +} +if (!defined('NOREQUIRESOC')) { + require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +} /* * Creation objet $langs (must be before all other code) */ -if (!defined('NOREQUIRETRAN')) -{ +if (!defined('NOREQUIRETRAN')) { $langs = new Translate('', $conf); // Must be after reading conf } /* * Object $db */ -if (!defined('NOREQUIREDB')) -{ +if (!defined('NOREQUIREDB')) { $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); - if ($db->error) - { + if ($db->error) { // If we were into a website context - if (!defined('USEDOLIBARREDITOR') && !defined('USEDOLIBARRSERVER') && !empty($_SERVER['SCRIPT_FILENAME']) && (strpos($_SERVER['SCRIPT_FILENAME'], DOL_DATA_ROOT.'/website') === 0)) - { + if (!defined('USEDOLIBARREDITOR') && !defined('USEDOLIBARRSERVER') && !empty($_SERVER['SCRIPT_FILENAME']) && (strpos($_SERVER['SCRIPT_FILENAME'], DOL_DATA_ROOT.'/website') === 0)) { $sapi_type = php_sapi_name(); - if (substr($sapi_type, 0, 3) != 'cgi') http_response_code(503); // To tel search engine this is a temporary error + if (substr($sapi_type, 0, 3) != 'cgi') { + http_response_code(503); // To tel search engine this is a temporary error + } print '<div class="center" style="text-align: center; margin: 100px;">'; - if (is_object($langs)) - { + if (is_object($langs)) { $langs->setDefaultLang('auto'); $langs->load("website"); print $langs->trans("SorryWebsiteIsCurrentlyOffLine"); @@ -175,10 +191,11 @@ if (session_id() && !empty($_SESSION["dol_entity"])) { } // Sanitize entity -if (!is_numeric($conf->entity)) $conf->entity = 1; +if (!is_numeric($conf->entity)) { + $conf->entity = 1; +} -if (!defined('NOREQUIREDB')) -{ +if (!defined('NOREQUIREDB')) { //print "Will work with data into entity instance number '".$conf->entity."'"; // Here we read database (llx_const table) and define $conf->global->XXX var. @@ -197,23 +214,25 @@ if (!empty($conf->file->mailing_limit_sendbycli)) { } // Create object $mysoc (A thirdparty object that contains properties of companies managed by Dolibarr. -if (!defined('NOREQUIREDB') && !defined('NOREQUIRESOC')) -{ +if (!defined('NOREQUIREDB') && !defined('NOREQUIRESOC')) { require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $mysoc = new Societe($db); $mysoc->setMysoc($conf); // For some countries, we need to invert our address with customer address - if ($mysoc->country_code == 'DE' && !isset($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $conf->global->MAIN_INVERT_SENDER_RECIPIENT = 1; + if ($mysoc->country_code == 'DE' && !isset($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) { + $conf->global->MAIN_INVERT_SENDER_RECIPIENT = 1; + } } // Set default language (must be after the setValues setting global $conf->global->MAIN_LANG_DEFAULT. Page main.inc.php will overwrite langs->defaultlang with user value later) -if (!defined('NOREQUIRETRAN')) -{ +if (!defined('NOREQUIRETRAN')) { $langcode = (GETPOST('lang', 'aZ09') ? GETPOST('lang', 'aZ09', 1) : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT)); - if (defined('MAIN_LANG_DEFAULT')) $langcode = constant('MAIN_LANG_DEFAULT'); + if (defined('MAIN_LANG_DEFAULT')) { + $langcode = constant('MAIN_LANG_DEFAULT'); + } $langs->setDefaultLang($langcode); } @@ -223,5 +242,7 @@ include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; $hookmanager = new HookManager($db); -if (!defined('MAIN_LABEL_MENTION_NPR')) define('MAIN_LABEL_MENTION_NPR', 'NPR'); +if (!defined('MAIN_LABEL_MENTION_NPR')) { + define('MAIN_LABEL_MENTION_NPR', 'NPR'); +} //if (! defined('PCLZIP_TEMPORARY_DIR')) define('PCLZIP_TEMPORARY_DIR', $conf->user->dir_temp); diff --git a/htdocs/modulebuilder/admin/setup.php b/htdocs/modulebuilder/admin/setup.php index c5b41ac9390..e9e3ea752f5 100644 --- a/htdocs/modulebuilder/admin/setup.php +++ b/htdocs/modulebuilder/admin/setup.php @@ -26,8 +26,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; global $conf, $langs, $user, $db; $langs->loadLangs(array("admin", "other", "modulebuilder")); -if (!$user->admin || empty($conf->modulebuilder->enabled)) +if (!$user->admin || empty($conf->modulebuilder->enabled)) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); @@ -35,8 +36,7 @@ $backtopage = GETPOST('backtopage', 'alpha'); /* * Actions */ -if ($action == "update") -{ +if ($action == "update") { $res1 = dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_README', GETPOST('MODULEBUILDER_SPECIFIC_README', 'restricthtml'), 'chaine', 0, '', $conf->entity); $res2 = dolibarr_set_const($db, 'MODULEBUILDER_ASCIIDOCTOR', GETPOST('MODULEBUILDER_ASCIIDOCTOR', 'nohtml'), 'chaine', 0, '', $conf->entity); $res3 = dolibarr_set_const($db, 'MODULEBUILDER_ASCIIDOCTORPDF', GETPOST('MODULEBUILDER_ASCIIDOCTORPDF', 'nohtml'), 'chaine', 0, '', $conf->entity); @@ -58,8 +58,9 @@ $reg = array(); if (preg_match('/set_(.*)/', $action, $reg)) { $code = $reg[1]; $values = GETPOST($code); - if (is_array($values)) + if (is_array($values)) { $values = implode(',', $values); + } if (dolibarr_set_const($db, $code, $values, 'chaine', 0, '', $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); @@ -112,8 +113,7 @@ print '<td>'.$langs->trans("Value").'</td>'; print "</tr>\n"; -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) -{ +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { // What is use case of this 2 options ? print '<tr class="oddeven">'; diff --git a/htdocs/modulebuilder/index.php b/htdocs/modulebuilder/index.php index 9cbb6ae4167..101aa6db09c 100644 --- a/htdocs/modulebuilder/index.php +++ b/htdocs/modulebuilder/index.php @@ -27,7 +27,9 @@ * into the dirins directory. */ -if (!defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check anti SQL+XSS injection attack test +if (!defined('NOSCANPOSTFORINJECTION')) { + define('NOSCANPOSTFORINJECTION', '1'); // Do not check anti SQL+XSS injection attack test +} require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -48,17 +50,27 @@ $module = GETPOST('module', 'alpha'); $tab = GETPOST('tab', 'aZ09'); $tabobj = GETPOST('tabobj', 'alpha'); $propertykey = GETPOST('propertykey', 'alpha'); -if (empty($module)) $module = 'initmodule'; -if (empty($tab)) $tab = 'description'; -if (empty($tabobj)) $tabobj = 'newobjectifnoobj'; +if (empty($module)) { + $module = 'initmodule'; +} +if (empty($tab)) { + $tab = 'description'; +} +if (empty($tabobj)) { + $tabobj = 'newobjectifnoobj'; +} $file = GETPOST('file', 'alpha'); $modulename = dol_sanitizeFileName(GETPOST('modulename', 'alpha')); $objectname = dol_sanitizeFileName(GETPOST('objectname', 'alpha')); // Security check -if (empty($conf->modulebuilder->enabled)) accessforbidden(); -if (!$user->admin && empty($conf->global->MODULEBUILDER_FOREVERYONE)) accessforbidden($langs->trans('ModuleBuilderNotAllowed')); +if (empty($conf->modulebuilder->enabled)) { + accessforbidden(); +} +if (!$user->admin && empty($conf->global->MODULEBUILDER_FOREVERYONE)) { + accessforbidden($langs->trans('ModuleBuilderNotAllowed')); +} // Dir for custom dirs @@ -68,14 +80,12 @@ $dirread = $dirins; $forceddirread = 0; $tmpdir = explode('@', $module); -if (!empty($tmpdir[1])) -{ +if (!empty($tmpdir[1])) { $module = $tmpdir[0]; $dirread = $tmpdir[1]; $forceddirread = 1; } -if (GETPOST('dirins', 'alpha')) -{ +if (GETPOST('dirins', 'alpha')) { $dirread = $dirins = GETPOST('dirins', 'alpha'); $forceddirread = 1; } @@ -84,9 +94,10 @@ $FILEFLAG = 'modulebuilder.txt'; $now = dol_now(); $newmask = 0; -if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK; -if (empty($newmask)) // This should no happen -{ +if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) { + $newmask = $conf->global->MAIN_UMASK; +} +if (empty($newmask)) { // This should no happen $newmask = '0664'; } @@ -99,14 +110,15 @@ $form = new Form($db); // Define $listofmodules $dirsrootforscan = array($dirread); // Add also the core modules into the list of modules to show/edit -if ($dirread != DOL_DOCUMENT_ROOT && ($conf->global->MAIN_FEATURES_LEVEL >= 2 || !empty($conf->global->MODULEBUILDER_ADD_DOCUMENT_ROOT))) { $dirsrootforscan[] = DOL_DOCUMENT_ROOT; } +if ($dirread != DOL_DOCUMENT_ROOT && ($conf->global->MAIN_FEATURES_LEVEL >= 2 || !empty($conf->global->MODULEBUILDER_ADD_DOCUMENT_ROOT))) { + $dirsrootforscan[] = DOL_DOCUMENT_ROOT; +} // Search modules to edit $textforlistofdirs = '<!-- Directory scanned -->'."\n"; $listofmodules = array(); $i = 0; -foreach ($dirsrootforscan as $dirread) -{ +foreach ($dirsrootforscan as $dirread) { $moduletype = 'external'; if ($dirread == DOL_DOCUMENT_ROOT) { $moduletype = 'internal'; @@ -116,14 +128,12 @@ foreach ($dirsrootforscan as $dirread) if (is_array($dirsincustom) && count($dirsincustom) > 0) { foreach ($dirsincustom as $dircustomcursor) { $fullname = $dircustomcursor['fullname']; - if (dol_is_file($fullname.'/'.$FILEFLAG)) - { + if (dol_is_file($fullname.'/'.$FILEFLAG)) { // Get real name of module (MyModule instead of mymodule) $dirtoscanrel = basename($fullname).'/core/modules/'; $descriptorfiles = dol_dir_list(dirname($fullname).'/'.$dirtoscanrel, 'files', 0, 'mod.*\.class\.php$'); - if (empty($descriptorfiles)) // If descriptor not found into module dir, we look into main module dir. - { + if (empty($descriptorfiles)) { // If descriptor not found into module dir, we look into main module dir. $dirtoscanrel = 'core/modules/'; $descriptorfiles = dol_dir_list($fullname.'/../'.$dirtoscanrel, 'files', 0, 'mod'.strtoupper(basename($fullname)).'\.class\.php$'); } @@ -138,8 +148,7 @@ foreach ($dirsrootforscan as $dirread) $moduledescriptorfullpath = $descriptorcursor['fullname']; //var_dump($descriptorcursor); } - if ($modulenamewithcase) - { + if ($modulenamewithcase) { $listofmodules[$dircustomcursor['name']] = array( 'modulenamewithcase'=>$modulenamewithcase, 'moduledescriptorrelpath'=> $moduledescriptorrelpath, @@ -153,8 +162,7 @@ foreach ($dirsrootforscan as $dirread) } } - if ($forceddirread && empty($listofmodules)) // $forceddirread is 1 if we forced dir to read with dirins=... or with module=...@mydir - { + if ($forceddirread && empty($listofmodules)) { // $forceddirread is 1 if we forced dir to read with dirins=... or with module=...@mydir $listofmodules[strtolower($module)] = array( 'modulenamewithcase'=>$module, 'moduledescriptorrelpath'=> 'notyetimplemented', @@ -165,15 +173,24 @@ foreach ($dirsrootforscan as $dirread) // Show description of content $newdircustom = $dirins; - if (empty($newdircustom)) $newdircustom = img_warning(); + if (empty($newdircustom)) { + $newdircustom = img_warning(); + } // If dirread was forced to somewhere else, by using URL // htdocs/modulebuilder/index.php?module=Inventory@/home/ldestailleur/git/dolibarr/htdocs/product - if (empty($i)) $textforlistofdirs .= $langs->trans("DirScanned").' : '; - else $textforlistofdirs .= ', '; + if (empty($i)) { + $textforlistofdirs .= $langs->trans("DirScanned").' : '; + } else { + $textforlistofdirs .= ', '; + } $textforlistofdirs .= '<strong class="wordbreakimp">'.$dirread.'</strong>'; if ($dirread == DOL_DOCUMENT_ROOT) { - if ($conf->global->MAIN_FEATURES_LEVEL >= 2) $textforlistofdirs .= $form->textwithpicto('', $langs->trans("ConstantIsOn", "MAIN_FEATURES_LEVEL")); - if (!empty($conf->global->MODULEBUILDER_ADD_DOCUMENT_ROOT)) $textforlistofdirs .= $form->textwithpicto('', $langs->trans("ConstantIsOn", "MODULEBUILDER_ADD_DOCUMENT_ROOT")); + if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { + $textforlistofdirs .= $form->textwithpicto('', $langs->trans("ConstantIsOn", "MAIN_FEATURES_LEVEL")); + } + if (!empty($conf->global->MODULEBUILDER_ADD_DOCUMENT_ROOT)) { + $textforlistofdirs .= $form->textwithpicto('', $langs->trans("ConstantIsOn", "MODULEBUILDER_ADD_DOCUMENT_ROOT")); + } } $i++; } @@ -183,18 +200,15 @@ foreach ($dirsrootforscan as $dirread) * Actions */ -if ($dirins && $action == 'initmodule' && $modulename) -{ +if ($dirins && $action == 'initmodule' && $modulename) { $modulename = ucfirst($modulename); // Force first letter in uppercase - if (preg_match('/[^a-z0-9_]/i', $modulename)) - { + if (preg_match('/[^a-z0-9_]/i', $modulename)) { $error++; setEventMessages($langs->trans("SpaceOrSpecialCharAreNotAllowed"), null, 'errors'); } - if (!$error) - { + if (!$error) { $srcdir = DOL_DOCUMENT_ROOT.'/modulebuilder/template'; $destdir = $dirins.'/'.strtolower($modulename); @@ -205,10 +219,8 @@ if ($dirins && $action == 'initmodule' && $modulename) $result = dolCopyDir($srcdir, $destdir, 0, 0, $arrayreplacement); //dol_mkdir($destfile); - if ($result <= 0) - { - if ($result < 0) - { + if ($result <= 0) { + if ($result < 0) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFailToCopyDir", $srcdir, $destdir), null, 'errors'); @@ -218,8 +230,7 @@ if ($dirins && $action == 'initmodule' && $modulename) } } - if (!empty($conf->global->MODULEBUILDER_USE_ABOUT)) - { + if (!empty($conf->global->MODULEBUILDER_USE_ABOUT)) { dol_delete_file($destdir.'/admin/about.php'); } @@ -274,11 +285,9 @@ if ($dirins && $action == 'initmodule' && $modulename) } // Edit PHP files - if (!$error) - { + if (!$error) { $listofphpfilestoedit = dol_dir_list($destdir, 'files', 1, '\.(php|MD|js|sql|txt|xml|lang)$', '', 'fullname', SORT_ASC, 0, 1); - foreach ($listofphpfilestoedit as $phpfileval) - { + foreach ($listofphpfilestoedit as $phpfileval) { //var_dump($phpfileval['fullname']); $arrayreplacement = array( 'mymodule'=>strtolower($modulename), @@ -293,39 +302,45 @@ if ($dirins && $action == 'initmodule' && $modulename) ); if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { - if (!empty($conf->global->MODULEBUILDER_SPECIFIC_EDITOR_NAME)) $arrayreplacement['Editor name'] = $conf->global->MODULEBUILDER_SPECIFIC_EDITOR_NAME; - if (!empty($conf->global->MODULEBUILDER_SPECIFIC_EDITOR_URL)) $arrayreplacement['https://www.example.com'] = $conf->global->MODULEBUILDER_SPECIFIC_EDITOR_URL; - if (!empty($conf->global->MODULEBUILDER_SPECIFIC_AUTHOR)) $arrayreplacement['---Put here your own copyright and developer email---'] = dol_print_date($now, '%Y').' '.$conf->global->MODULEBUILDER_SPECIFIC_AUTHOR; - if (!empty($conf->global->MODULEBUILDER_SPECIFIC_VERSION)) $arrayreplacement['1.0'] = $conf->global->MODULEBUILDER_SPECIFIC_VERSION; - if (!empty($conf->global->MODULEBUILDER_SPECIFIC_FAMILY)) $arrayreplacement['other'] = $conf->global->MODULEBUILDER_SPECIFIC_FAMILY; + if (!empty($conf->global->MODULEBUILDER_SPECIFIC_EDITOR_NAME)) { + $arrayreplacement['Editor name'] = $conf->global->MODULEBUILDER_SPECIFIC_EDITOR_NAME; + } + if (!empty($conf->global->MODULEBUILDER_SPECIFIC_EDITOR_URL)) { + $arrayreplacement['https://www.example.com'] = $conf->global->MODULEBUILDER_SPECIFIC_EDITOR_URL; + } + if (!empty($conf->global->MODULEBUILDER_SPECIFIC_AUTHOR)) { + $arrayreplacement['---Put here your own copyright and developer email---'] = dol_print_date($now, '%Y').' '.$conf->global->MODULEBUILDER_SPECIFIC_AUTHOR; + } + if (!empty($conf->global->MODULEBUILDER_SPECIFIC_VERSION)) { + $arrayreplacement['1.0'] = $conf->global->MODULEBUILDER_SPECIFIC_VERSION; + } + if (!empty($conf->global->MODULEBUILDER_SPECIFIC_FAMILY)) { + $arrayreplacement['other'] = $conf->global->MODULEBUILDER_SPECIFIC_FAMILY; + } } $result = dolReplaceInFile($phpfileval['fullname'], $arrayreplacement); //var_dump($result); - if ($result < 0) - { + if ($result < 0) { setEventMessages($langs->trans("ErrorFailToMakeReplacementInto", $phpfileval['fullname']), null, 'errors'); } } - if (!empty($conf->global->MODULEBUILDER_SPECIFIC_README)) - { + if (!empty($conf->global->MODULEBUILDER_SPECIFIC_README)) { setEventMessages($langs->trans("ContentOfREADMECustomized"), null, 'warnings'); dol_delete_file($destdir.'/README.md'); file_put_contents($destdir.'/README.md', $conf->global->MODULEBUILDER_SPECIFIC_README); } } - if (!$error) - { + if (!$error) { setEventMessages('ModuleInitialized', null); $module = $modulename; $modulename = ''; } } -if ($dirins && $action == 'initapi' && !empty($module)) -{ +if ($dirins && $action == 'initapi' && !empty($module)) { $modulename = ucfirst($module); // Force first letter in uppercase $objectname = $tabobj; @@ -336,8 +351,7 @@ if ($dirins && $action == 'initapi' && !empty($module)) //var_dump($srcfile);var_dump($destfile); $result = dol_copy($srcfile, $destfile, 0, 0); - if ($result > 0) - { + if ($result > 0) { //var_dump($phpfileval['fullname']); $arrayreplacement = array( 'mymodule'=>strtolower($modulename), @@ -360,8 +374,7 @@ if ($dirins && $action == 'initapi' && !empty($module)) setEventMessages($langs->trans('ErrorFailToCreateFile', $destfile), null, 'errors'); } } -if ($dirins && $action == 'initphpunit' && !empty($module)) -{ +if ($dirins && $action == 'initphpunit' && !empty($module)) { $modulename = ucfirst($module); // Force first letter in uppercase $objectname = $tabobj; @@ -371,8 +384,7 @@ if ($dirins && $action == 'initphpunit' && !empty($module)) $destfile = $dirins.'/'.strtolower($module).'/test/phpunit/'.strtolower($objectname).'Test.php'; $result = dol_copy($srcfile, $destfile, 0, 0); - if ($result > 0) - { + if ($result > 0) { //var_dump($phpfileval['fullname']); $arrayreplacement = array( 'mymodule'=>strtolower($modulename), @@ -410,8 +422,7 @@ if ($dirins && $action == 'initsqlextrafields' && !empty($module)) { //var_dump($srcfile);var_dump($destfile); $result2 = dol_copy($srcfile2, $destfile2, 0, 0); - if ($result1 > 0 && $result2 > 0) - { + if ($result1 > 0 && $result2 > 0) { $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); @@ -439,8 +450,7 @@ if ($dirins && $action == 'initsqlextrafields' && !empty($module)) { } // TODO Enable in class the property $isextrafieldmanaged = 1 } -if ($dirins && $action == 'inithook' && !empty($module)) -{ +if ($dirins && $action == 'inithook' && !empty($module)) { dol_mkdir($dirins.'/'.strtolower($module).'/class'); $srcdir = DOL_DOCUMENT_ROOT.'/modulebuilder/template'; $srcfile = $srcdir.'/class/actions_mymodule.class.php'; @@ -448,8 +458,7 @@ if ($dirins && $action == 'inithook' && !empty($module)) //var_dump($srcfile);var_dump($destfile); $result = dol_copy($srcfile, $destfile, 0, 0); - if ($result > 0) - { + if ($result > 0) { $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); @@ -471,8 +480,7 @@ if ($dirins && $action == 'inithook' && !empty($module)) setEventMessages($langs->trans('ErrorFailToCreateFile', $destfile), null, 'errors'); } } -if ($dirins && $action == 'inittrigger' && !empty($module)) -{ +if ($dirins && $action == 'inittrigger' && !empty($module)) { dol_mkdir($dirins.'/'.strtolower($module).'/core/triggers'); $srcdir = DOL_DOCUMENT_ROOT.'/modulebuilder/template'; $srcfile = $srcdir.'/core/triggers/interface_99_modMyModule_MyModuleTriggers.class.php'; @@ -480,8 +488,7 @@ if ($dirins && $action == 'inittrigger' && !empty($module)) //var_dump($srcfile);var_dump($destfile); $result = dol_copy($srcfile, $destfile, 0, 0); - if ($result > 0) - { + if ($result > 0) { $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); @@ -503,8 +510,7 @@ if ($dirins && $action == 'inittrigger' && !empty($module)) setEventMessages($langs->trans('ErrorFailToCreateFile', $destfile), null, 'errors'); } } -if ($dirins && $action == 'initwidget' && !empty($module)) -{ +if ($dirins && $action == 'initwidget' && !empty($module)) { dol_mkdir($dirins.'/'.strtolower($module).'/core/boxes'); $srcdir = DOL_DOCUMENT_ROOT.'/modulebuilder/template'; $srcfile = $srcdir.'/core/boxes/mymodulewidget1.php'; @@ -534,8 +540,7 @@ if ($dirins && $action == 'initwidget' && !empty($module)) setEventMessages($langs->trans('ErrorFailToCreateFile', $destfile), null, 'errors'); } } -if ($dirins && $action == 'initcss' && !empty($module)) -{ +if ($dirins && $action == 'initcss' && !empty($module)) { dol_mkdir($dirins.'/'.strtolower($module).'/css'); $srcdir = DOL_DOCUMENT_ROOT.'/modulebuilder/template'; $srcfile = $srcdir.'/css/mymodule.css.php'; @@ -543,8 +548,7 @@ if ($dirins && $action == 'initcss' && !empty($module)) //var_dump($srcfile);var_dump($destfile); $result = dol_copy($srcfile, $destfile, 0, 0); - if ($result > 0) - { + if ($result > 0) { $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); @@ -572,8 +576,7 @@ if ($dirins && $action == 'initcss' && !empty($module)) } } -if ($dirins && $action == 'initjs' && !empty($module)) -{ +if ($dirins && $action == 'initjs' && !empty($module)) { dol_mkdir($dirins.'/'.strtolower($module).'/js'); $srcdir = DOL_DOCUMENT_ROOT.'/modulebuilder/template'; $srcfile = $srcdir.'/js/mymodule.js.php'; @@ -581,8 +584,7 @@ if ($dirins && $action == 'initjs' && !empty($module)) //var_dump($srcfile);var_dump($destfile); $result = dol_copy($srcfile, $destfile, 0, 0); - if ($result > 0) - { + if ($result > 0) { $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); @@ -609,8 +611,7 @@ if ($dirins && $action == 'initjs' && !empty($module)) setEventMessages($langs->trans('ErrorFailToCreateFile', $destfile), null, 'errors'); } } -if ($dirins && $action == 'initcli' && !empty($module)) -{ +if ($dirins && $action == 'initcli' && !empty($module)) { dol_mkdir($dirins.'/'.strtolower($module).'/scripts'); $srcdir = DOL_DOCUMENT_ROOT.'/modulebuilder/template'; $srcfile = $srcdir.'/scripts/mymodule.php'; @@ -618,8 +619,7 @@ if ($dirins && $action == 'initcli' && !empty($module)) //var_dump($srcfile);var_dump($destfile); $result = dol_copy($srcfile, $destfile, 0, 0); - if ($result > 0) - { + if ($result > 0) { $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); @@ -694,19 +694,16 @@ if ($dirins && $action == 'initdoc' && !empty($module)) { } } -if ($dirins && $action == 'addlanguage' && !empty($module)) -{ +if ($dirins && $action == 'addlanguage' && !empty($module)) { $newlangcode = GETPOST('newlangcode', 'aZ09'); $srcfile = $dirins.'/'.strtolower($module).'/langs/en_US'; $destfile = $dirins.'/'.strtolower($module).'/langs/'.$newlangcode; $result = dolCopyDir($srcfile, $destfile, 0, 0); } -if ($dirins && $action == 'confirm_removefile' && !empty($module)) -{ +if ($dirins && $action == 'confirm_removefile' && !empty($module)) { $relativefilename = dol_sanitizePathName(GETPOST('file', 'none')); - if ($relativefilename) - { + if ($relativefilename) { $dirnametodelete = dirname($relativefilename); $filetodelete = $dirins.'/'.$relativefilename; $dirtodelete = $dirins.'/'.$dirnametodelete; @@ -715,11 +712,12 @@ if ($dirins && $action == 'confirm_removefile' && !empty($module)) if (!$result) { setEventMessages($langs->trans("ErrorFailToDeleteFile", basename($filetodelete)), null, 'errors'); } else { - if (dol_is_dir_empty($dirtodelete)) dol_delete_dir($dirtodelete); + if (dol_is_dir_empty($dirtodelete)) { + dol_delete_dir($dirtodelete); + } // Update descriptor file to comment file - if (in_array($tab, array('css', 'js'))) - { + if (in_array($tab, array('css', 'js'))) { $srcfile = $dirins.'/'.strtolower($module).'/core/modules/mod'.$module.'.class.php'; $arrayreplacement = array('/^\s*\''.preg_quote('/'.$relativefilename, '/').'\',*/m'=>' // \'/'.$relativefilename.'\','); dolReplaceInFile($srcfile, $arrayreplacement, '', 0, 0, 1); @@ -729,12 +727,10 @@ if ($dirins && $action == 'confirm_removefile' && !empty($module)) } // Build the $fields array from SQL table (initfromtablename) -if ($dirins && $action == 'initobject' && $module && GETPOST('createtablearray', 'alpha')) -{ +if ($dirins && $action == 'initobject' && $module && GETPOST('createtablearray', 'alpha')) { $tablename = GETPOST('initfromtablename', 'alpha'); $_results = $db->DDLDescTable($tablename); - if (empty($_results)) - { + if (empty($_results)) { setEventMessages($langs->trans("ErrorTableNotFound", $tablename), null, 'errors'); } else { /** @@ -780,66 +776,133 @@ if ($dirins && $action == 'initobject' && $module && GETPOST('createtablearray', $string = 'public $fields=array('."\n"; $string .= "<br>"; $i = 10; - while ($obj = $db->fetch_object($_results)) - { + while ($obj = $db->fetch_object($_results)) { // fieldname $fieldname = $obj->Field; // type $type = $obj->Type; - if ($type == 'int(11)') $type = 'integer'; - if ($type == 'float') $type = 'real'; - if (strstr($type, 'tinyint')) $type = 'integer'; - if ($obj->Field == 'fk_soc') $type = 'integer:Societe:societe/class/societe.class.php'; - if (preg_match('/^fk_proj/', $obj->Field)) $type = 'integer:Project:projet/class/project.class.php:1:fk_statut=1'; - if (preg_match('/^fk_prod/', $obj->Field)) $type = 'integer:Product:product/class/product.class.php:1'; - if ($obj->Field == 'fk_warehouse') $type = 'integer:Entrepot:product/stock/class/entrepot.class.php'; - if (preg_match('/^(fk_user|fk_commercial)/', $obj->Field)) $type = 'integer:User:user/class/user.class.php'; + if ($type == 'int(11)') { + $type = 'integer'; + } + if ($type == 'float') { + $type = 'real'; + } + if (strstr($type, 'tinyint')) { + $type = 'integer'; + } + if ($obj->Field == 'fk_soc') { + $type = 'integer:Societe:societe/class/societe.class.php'; + } + if (preg_match('/^fk_proj/', $obj->Field)) { + $type = 'integer:Project:projet/class/project.class.php:1:fk_statut=1'; + } + if (preg_match('/^fk_prod/', $obj->Field)) { + $type = 'integer:Product:product/class/product.class.php:1'; + } + if ($obj->Field == 'fk_warehouse') { + $type = 'integer:Entrepot:product/stock/class/entrepot.class.php'; + } + if (preg_match('/^(fk_user|fk_commercial)/', $obj->Field)) { + $type = 'integer:User:user/class/user.class.php'; + } // notnull $notnull = ($obj->Null == 'YES' ? 0 : 1); - if ($fieldname == 'fk_user_modif') $notnull = -1; + if ($fieldname == 'fk_user_modif') { + $notnull = -1; + } // label $label = preg_replace('/_/', '', ucfirst($fieldname)); - if ($fieldname == 'rowid') $label = 'TechnicalID'; - if ($fieldname == 'import_key') $label = 'ImportId'; - if ($fieldname == 'fk_soc') $label = 'ThirdParty'; - if ($fieldname == 'tms') $label = 'DateModification'; - if ($fieldname == 'datec') $label = 'DateCreation'; - if ($fieldname == 'date_valid') $label = 'DateValidation'; - if ($fieldname == 'datev') $label = 'DateValidation'; - if ($fieldname == 'note_private') $label = 'NotePublic'; - if ($fieldname == 'note_public') $label = 'NotePrivate'; - if ($fieldname == 'fk_user_creat') $label = 'UserAuthor'; - if ($fieldname == 'fk_user_modif') $label = 'UserModif'; - if ($fieldname == 'fk_user_valid') $label = 'UserValidation'; + if ($fieldname == 'rowid') { + $label = 'TechnicalID'; + } + if ($fieldname == 'import_key') { + $label = 'ImportId'; + } + if ($fieldname == 'fk_soc') { + $label = 'ThirdParty'; + } + if ($fieldname == 'tms') { + $label = 'DateModification'; + } + if ($fieldname == 'datec') { + $label = 'DateCreation'; + } + if ($fieldname == 'date_valid') { + $label = 'DateValidation'; + } + if ($fieldname == 'datev') { + $label = 'DateValidation'; + } + if ($fieldname == 'note_private') { + $label = 'NotePublic'; + } + if ($fieldname == 'note_public') { + $label = 'NotePrivate'; + } + if ($fieldname == 'fk_user_creat') { + $label = 'UserAuthor'; + } + if ($fieldname == 'fk_user_modif') { + $label = 'UserModif'; + } + if ($fieldname == 'fk_user_valid') { + $label = 'UserValidation'; + } // visible $visible = -1; - if ($fieldname == 'entity') $visible = -2; - if ($fieldname == 'import_key') $visible = -2; - if ($fieldname == 'fk_user_creat') $visible = -2; - if ($fieldname == 'fk_user_modif') $visible = -2; - if (in_array($fieldname, array('ref_ext', 'model_pdf', 'note_public', 'note_private'))) $visible = 0; + if ($fieldname == 'entity') { + $visible = -2; + } + if ($fieldname == 'import_key') { + $visible = -2; + } + if ($fieldname == 'fk_user_creat') { + $visible = -2; + } + if ($fieldname == 'fk_user_modif') { + $visible = -2; + } + if (in_array($fieldname, array('ref_ext', 'model_pdf', 'note_public', 'note_private'))) { + $visible = 0; + } // enabled $enabled = 1; // default $default = ''; - if ($fieldname == 'entity') $default = 1; + if ($fieldname == 'entity') { + $default = 1; + } // position $position = $i; - if (in_array($fieldname, array('status', 'statut', 'fk_status', 'fk_statut'))) $position = 500; - if ($fieldname == 'import_key') $position = 900; + if (in_array($fieldname, array('status', 'statut', 'fk_status', 'fk_statut'))) { + $position = 500; + } + if ($fieldname == 'import_key') { + $position = 900; + } // index $index = 0; - if ($fieldname == 'entity') $index = 1; + if ($fieldname == 'entity') { + $index = 1; + } $string .= "'".$obj->Field."' =>array('type'=>'".$type."', 'label'=>'".$label."',"; - if ($default != '') $string .= " 'default'=>".$default.","; + if ($default != '') { + $string .= " 'default'=>".$default.","; + } $string .= " 'enabled'=>".$enabled.","; $string .= " 'visible'=>".$visible; - if ($notnull) $string .= ", 'notnull'=>".$notnull; - if ($fieldname == 'ref') $string .= ", 'showoncombobox'=>1"; + if ($notnull) { + $string .= ", 'notnull'=>".$notnull; + } + if ($fieldname == 'ref') { + $string .= ", 'showoncombobox'=>1"; + } $string .= ", 'position'=>".$position; - if ($index) $string .= ", 'index'=>".$index; + if ($index) { + $string .= ", 'index'=>".$index; + } $string .= "),\n"; $string .= "<br>"; $i += 5; @@ -851,15 +914,13 @@ if ($dirins && $action == 'initobject' && $module && GETPOST('createtablearray', } } -if ($dirins && $action == 'initobject' && $module && $objectname) -{ +if ($dirins && $action == 'initobject' && $module && $objectname) { $objectname = ucfirst($objectname); $dirins = $dirread = $listofmodules[strtolower($module)]['moduledescriptorrootpath']; $moduletype = $listofmodules[strtolower($module)]['moduletype']; - if (preg_match('/[^a-z0-9_]/i', $objectname)) - { + if (preg_match('/[^a-z0-9_]/i', $objectname)) { $error++; setEventMessages($langs->trans("SpaceOrSpecialCharAreNotAllowed"), null, 'errors'); $tabobj = 'newobject'; @@ -882,15 +943,12 @@ if ($dirins && $action == 'initobject' && $module && $objectname) dol_mkdir($destdir.'/sql'); // Scan dir class to find if an object with same name already exists. - if (!$error) - { + if (!$error) { $dirlist = dol_dir_list($destdir.'/class', 'files', 0, '\.txt$'); $alreadyfound = false; - foreach ($dirlist as $key => $val) - { + foreach ($dirlist as $key => $val) { $filefound = preg_replace('/\.txt$/', '', $val['name']); - if (strtolower($objectname) == strtolower($filefound) && $objectname != $filefound) - { + if (strtolower($objectname) == strtolower($filefound) && $objectname != $filefound) { $alreadyfound = true; $error++; setEventMessages($langs->trans("AnObjectAlreadyExistWithThisNameAndDiffCase"), null, 'errors'); @@ -899,8 +957,7 @@ if ($dirins && $action == 'initobject' && $module && $objectname) } } - if (!$error) - { + if (!$error) { // Copy some files $filetogenerate = array( 'myobject_card.php'=>strtolower($objectname).'_card.php', @@ -922,8 +979,7 @@ if ($dirins && $action == 'initobject' && $module && $objectname) //'class/api_mymodule.class.php'=>'class/api_'.strtolower($module).'.class.php', ); - if (GETPOST('includerefgeneration', 'aZ09')) - { + if (GETPOST('includerefgeneration', 'aZ09')) { dol_mkdir($destdir.'/core/modules/'.strtolower($module)); $filetogenerate += array( @@ -932,8 +988,7 @@ if ($dirins && $action == 'initobject' && $module && $objectname) 'core/modules/mymodule/modules_myobject.php'=>'core/modules/'.strtolower($module).'/modules_'.strtolower($objectname).'.php', ); } - if (GETPOST('includedocgeneration', 'aZ09')) - { + if (GETPOST('includedocgeneration', 'aZ09')) { dol_mkdir($destdir.'/core/modules/'.strtolower($module)); dol_mkdir($destdir.'/core/modules/'.strtolower($module).'/doc'); @@ -943,13 +998,10 @@ if ($dirins && $action == 'initobject' && $module && $objectname) ); } - foreach ($filetogenerate as $srcfile => $destfile) - { + foreach ($filetogenerate as $srcfile => $destfile) { $result = dol_copy($srcdir.'/'.$srcfile, $destdir.'/'.$destfile, $newmask, 0); - if ($result <= 0) - { - if ($result < 0) - { + if ($result <= 0) { + if ($result < 0) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFailToCopyFile", $srcdir.'/'.$srcfile, $destdir.'/'.$destfile), null, 'errors'); @@ -999,17 +1051,21 @@ if ($dirins && $action == 'initobject' && $module && $objectname) $listofobject = dol_dir_list($destdir.'/class', 'files', 0, '\.class\.php$'); $firstobjectname = ''; - foreach ($listofobject as $fileobj) - { - if (preg_match('/^api_/', $fileobj['name'])) continue; - if (preg_match('/^actions_/', $fileobj['name'])) continue; + foreach ($listofobject as $fileobj) { + if (preg_match('/^api_/', $fileobj['name'])) { + continue; + } + if (preg_match('/^actions_/', $fileobj['name'])) { + continue; + } $tmpcontent = file_get_contents($fileobj['fullname']); $reg = array(); - if (preg_match('/class\s+([^\s]*)\s+extends\s+CommonObject/ims', $tmpcontent, $reg)) - { + if (preg_match('/class\s+([^\s]*)\s+extends\s+CommonObject/ims', $tmpcontent, $reg)) { $objectnameloop = $reg[1]; - if (empty($firstobjectname)) $firstobjectname = $objectnameloop; + if (empty($firstobjectname)) { + $firstobjectname = $objectnameloop; + } } // Regenerate left menu entry in descriptor for $objectname @@ -1070,11 +1126,9 @@ if ($dirins && $action == 'initobject' && $module && $objectname) } } - if (!$error) - { + if (!$error) { // Edit PHP files to make replacement - foreach ($filetogenerate as $destfile) - { + foreach ($filetogenerate as $destfile) { $phpfileval['fullname'] = $destdir.'/'.$destfile; //var_dump($phpfileval['fullname']); @@ -1094,75 +1148,71 @@ if ($dirins && $action == 'initobject' && $module && $objectname) $result = dolReplaceInFile($phpfileval['fullname'], $arrayreplacement); //var_dump($result); - if ($result < 0) - { + if ($result < 0) { setEventMessages($langs->trans("ErrorFailToMakeReplacementInto", $phpfileval['fullname']), null, 'errors'); } } } - if (!$error) - { + if (!$error) { // Edit the class file to write properties $object = rebuildObjectClass($destdir, $module, $objectname, $newmask); - if (is_numeric($object) && $object < 0) $error++; + if (is_numeric($object) && $object < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { // Edit sql with new properties $result = rebuildObjectSql($destdir, $module, $objectname, $newmask, '', $object); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans('FilesForObjectInitialized', $objectname), null); $tabobj = $objectname; } } -if ($dirins && ($action == 'droptable' || $action == 'droptableextrafields') && !empty($module) && !empty($tabobj)) -{ +if ($dirins && ($action == 'droptable' || $action == 'droptableextrafields') && !empty($module) && !empty($tabobj)) { $objectname = $tabobj; $arrayoftables = array(); - if ($action == 'droptable') $arrayoftables[] = MAIN_DB_PREFIX.strtolower($module).'_'.strtolower($tabobj); - if ($action == 'droptableextrafields') $arrayoftables[] = MAIN_DB_PREFIX.strtolower($module).'_'.strtolower($tabobj).'_extrafields'; + if ($action == 'droptable') { + $arrayoftables[] = MAIN_DB_PREFIX.strtolower($module).'_'.strtolower($tabobj); + } + if ($action == 'droptableextrafields') { + $arrayoftables[] = MAIN_DB_PREFIX.strtolower($module).'_'.strtolower($tabobj).'_extrafields'; + } - foreach ($arrayoftables as $tabletodrop) - { + foreach ($arrayoftables as $tabletodrop) { $nb = -1; $sql = "SELECT COUNT(*) as nb FROM ".$tabletodrop; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $nb = $obj->nb; } } else { - if ($db->lasterrno() == 'DB_ERROR_NOSUCHTABLE') - { + if ($db->lasterrno() == 'DB_ERROR_NOSUCHTABLE') { setEventMessages($langs->trans("TableDoesNotExists", $tabletodrop), null, 'warnings'); } else { dol_print_error($db); } } - if ($nb == 0) - { + if ($nb == 0) { $resql = $db->DDLDropTable($tabletodrop); //var_dump($resql); setEventMessages($langs->trans("TableDropped", $tabletodrop), null, 'mesgs'); - } elseif ($nb > 0) - { + } elseif ($nb > 0) { setEventMessages($langs->trans("TableNotEmptyDropCanceled", $tabletodrop), null, 'warnings'); } } } -if ($dirins && $action == 'addproperty' && !empty($module) && !empty($tabobj)) -{ +if ($dirins && $action == 'addproperty' && !empty($module) && !empty($tabobj)) { $error = 0; $objectname = $tabobj; @@ -1175,26 +1225,21 @@ if ($dirins && $action == 'addproperty' && !empty($module) && !empty($tabobj)) dol_mkdir($destdir); // We click on add property - if (!GETPOST('regenerateclasssql') && !GETPOST('regeneratemissing')) - { - if (!GETPOST('propname', 'aZ09')) - { + if (!GETPOST('regenerateclasssql') && !GETPOST('regeneratemissing')) { + if (!GETPOST('propname', 'aZ09')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Name")), null, 'errors'); } - if (!GETPOST('proplabel', 'alpha')) - { + if (!GETPOST('proplabel', 'alpha')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); } - if (!GETPOST('proptype', 'alpha')) - { + if (!GETPOST('proptype', 'alpha')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Type")), null, 'errors'); } - if (!$error) - { + if (!$error) { $addfieldentry = array( 'name'=>GETPOST('propname', 'aZ09'), 'label'=>GETPOST('proplabel', 'alpha'), 'type'=>GETPOST('proptype', 'alpha'), 'arrayofkeyval'=>GETPOST('proparrayofkeyval', 'restricthtml'), // Example json string '{"0":"Draft","1":"Active","-1":"Cancel"}' @@ -1203,8 +1248,7 @@ if ($dirins && $action == 'addproperty' && !empty($module) && !empty($tabobj)) 'isameasure'=>GETPOST('propisameasure', 'int'), 'comment'=>GETPOST('propcomment', 'alpha'), 'help'=>GETPOST('prophelp', 'alpha') ); - if (!empty($addfieldentry['arrayofkeyval']) && !is_array($addfieldentry['arrayofkeyval'])) - { + if (!empty($addfieldentry['arrayofkeyval']) && !is_array($addfieldentry['arrayofkeyval'])) { $addfieldentry['arrayofkeyval'] = json_decode($addfieldentry['arrayofkeyval'], true); } } @@ -1217,31 +1261,26 @@ if ($dirins && $action == 'addproperty' && !empty($module) && !empty($tabobj)) }*/ // Edit the class file to write properties - if (!$error) - { + if (!$error) { $moduletype = 'external'; $object = rebuildObjectClass($destdir, $module, $objectname, $newmask, $srcdir, $addfieldentry, $moduletype); - if (is_numeric($object) && $object <= 0) - { + if (is_numeric($object) && $object <= 0) { $error++; } } // Edit sql with new properties - if (!$error) - { + if (!$error) { $moduletype = 'external'; $result = rebuildObjectSql($destdir, $module, $objectname, $newmask, $srcdir, $object, $moduletype); - if ($result <= 0) - { + if ($result <= 0) { $error++; } } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans('FilesForObjectUpdated', $objectname), null); clearstatcache(true); @@ -1253,8 +1292,7 @@ if ($dirins && $action == 'addproperty' && !empty($module) && !empty($tabobj)) } } -if ($dirins && $action == 'confirm_deleteproperty' && $propertykey) -{ +if ($dirins && $action == 'confirm_deleteproperty' && $propertykey) { $objectname = $tabobj; $srcdir = $dirread.'/'.strtolower($module); @@ -1262,21 +1300,22 @@ if ($dirins && $action == 'confirm_deleteproperty' && $propertykey) dol_mkdir($destdir); // Edit the class file to write properties - if (!$error) - { + if (!$error) { $object = rebuildObjectClass($destdir, $module, $objectname, $newmask, $srcdir, array(), $propertykey); - if (is_numeric($object) && $object <= 0) $error++; + if (is_numeric($object) && $object <= 0) { + $error++; + } } // Edit sql with new properties - if (!$error) - { + if (!$error) { $result = rebuildObjectSql($destdir, $module, $objectname, $newmask, $srcdir, $object); - if ($result <= 0) $error++; + if ($result <= 0) { + $error++; + } } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans('FilesForObjectUpdated', $objectname), null); clearstatcache(true); @@ -1288,16 +1327,13 @@ if ($dirins && $action == 'confirm_deleteproperty' && $propertykey) } } -if ($dirins && $action == 'confirm_deletemodule') -{ - if (preg_match('/[^a-z0-9_]/i', $module)) - { +if ($dirins && $action == 'confirm_deletemodule') { + if (preg_match('/[^a-z0-9_]/i', $module)) { $error++; setEventMessages($langs->trans("SpaceOrSpecialCharAreNotAllowed"), null, 'errors'); } - if (!$error) - { + if (!$error) { $modulelowercase = strtolower($module); // Dir for module @@ -1305,8 +1341,7 @@ if ($dirins && $action == 'confirm_deletemodule') $result = dol_delete_dir_recursive($dir); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans("DirWasRemoved", $modulelowercase), null); } else { setEventMessages($langs->trans("PurgeNothingToDelete"), null, 'warnings'); @@ -1317,16 +1352,13 @@ if ($dirins && $action == 'confirm_deletemodule') $module = 'deletemodule'; } -if ($dirins && $action == 'confirm_deleteobject' && $objectname) -{ - if (preg_match('/[^a-z0-9_]/i', $objectname)) - { +if ($dirins && $action == 'confirm_deleteobject' && $objectname) { + if (preg_match('/[^a-z0-9_]/i', $objectname)) { $error++; setEventMessages($langs->trans("SpaceOrSpecialCharAreNotAllowed"), null, 'errors'); } - if (!$error) - { + if (!$error) { $modulelowercase = strtolower($module); $objectlowercase = strtolower($objectname); @@ -1360,15 +1392,15 @@ if ($dirins && $action == 'confirm_deleteobject' && $objectname) ); $resultko = 0; - foreach ($filetodelete as $filetodelete) - { + foreach ($filetodelete as $filetodelete) { $resulttmp = dol_delete_file($dir.'/'.$filetodelete, 0, 0, 1); $resulttmp = dol_delete_file($dir.'/'.$filetodelete.'.back', 0, 0, 1); - if (!$resulttmp) $resultko++; + if (!$resulttmp) { + $resultko++; + } } - if ($resultko == 0) - { + if ($resultko == 0) { setEventMessages($langs->trans("FilesDeleted"), null); } else { setEventMessages($langs->trans("ErrorSomeFilesCouldNotBeDeleted"), null, 'warnings'); @@ -1380,8 +1412,7 @@ if ($dirins && $action == 'confirm_deleteobject' && $objectname) } -if ($dirins && $action == 'generatepackage') -{ +if ($dirins && $action == 'generatepackage') { $modulelowercase = strtolower($module); // Dir for module @@ -1393,12 +1424,10 @@ if ($dirins && $action == 'generatepackage') dol_include_once($modulelowercase.'/core/modules/mod'.$module.'.class.php'); $class = 'mod'.$module; - if (class_exists($class)) - { + if (class_exists($class)) { try { $moduleobj = new $class($db); - } catch (Exception $e) - { + } catch (Exception $e) { $error++; dol_print_error($e->getMessage()); } @@ -1410,22 +1439,21 @@ if ($dirins && $action == 'generatepackage') } $arrayversion = explode('.', $moduleobj->version, 3); - if (count($arrayversion)) - { + if (count($arrayversion)) { $FILENAMEZIP = "module_".$modulelowercase.'-'.$arrayversion[0].'.'.$arrayversion[1].($arrayversion[2] ? ".".$arrayversion[2] : "").".zip"; $dirofmodule = dol_buildpath($modulelowercase, 0).'/bin'; $outputfilezip = $dirofmodule.'/'.$FILENAMEZIP; - if ($dirofmodule) - { - if (!dol_is_dir($dirofmodule)) dol_mkdir($dirofmodule); + if ($dirofmodule) { + if (!dol_is_dir($dirofmodule)) { + dol_mkdir($dirofmodule); + } $result = dol_compress_dir($dir, $outputfilezip, 'zip', '', $modulelowercase); } else { $result = -1; } - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans("ZipFileGeneratedInto", $outputfilezip), null); } else { $error++; @@ -1439,16 +1467,14 @@ if ($dirins && $action == 'generatepackage') } } -if ($dirins && $action == 'generatedoc') -{ +if ($dirins && $action == 'generatedoc') { $FILENAMEDOC = strtolower($module).'.html'; $dirofmodule = dol_buildpath(strtolower($module), 0).'/doc'; $util = new Utils($db); $result = $util->generateDoc($module); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans("DocFileGeneratedInto", $dirofmodule), null); } else { setEventMessages($util->error, $util->errors, 'errors'); @@ -1457,39 +1483,42 @@ if ($dirins && $action == 'generatedoc') // Save file -if ($action == 'savefile' && empty($cancel)) -{ +if ($action == 'savefile' && empty($cancel)) { $relofcustom = basename($dirins); - if ($relofcustom) - { + if ($relofcustom) { // Check that relative path ($file) start with name 'custom' - if (!preg_match('/^'.$relofcustom.'/', $file)) $file = $relofcustom.'/'.$file; + if (!preg_match('/^'.$relofcustom.'/', $file)) { + $file = $relofcustom.'/'.$file; + } $pathoffile = dol_buildpath($file, 0); $pathoffilebackup = dol_buildpath($file.'.back', 0); // Save old version - if (dol_is_file($pathoffile)) - { + if (dol_is_file($pathoffile)) { dol_copy($pathoffile, $pathoffilebackup, 0, 1); } $check = 'restricthtml'; $srclang = dol_mimetype($pathoffile, '', 3); - if ($srclang == 'md') $check = 'restricthtml'; - if ($srclang == 'lang') $check = 'restricthtml'; - if ($srclang == 'php') $check = 'none'; + if ($srclang == 'md') { + $check = 'restricthtml'; + } + if ($srclang == 'lang') { + $check = 'restricthtml'; + } + if ($srclang == 'php') { + $check = 'none'; + } $content = GETPOST('editfilecontent', $check); // Save file on disk - if ($content) - { + if ($content) { dol_delete_file($pathoffile); $result = file_put_contents($pathoffile, $content); - if ($result) - { + if ($result) { @chmod($pathoffile, octdec($newmask)); setEventMessages($langs->trans("FileSaved"), null); @@ -1505,32 +1534,37 @@ if ($action == 'savefile' && empty($cancel)) } // Enable module -if ($action == 'set' && $user->admin) -{ +if ($action == 'set' && $user->admin) { $param = ''; - if ($module) $param .= '&module='.urlencode($module); - if ($tab) $param .= '&tab='.urlencode($tab); - if ($tabobj) $param .= '&tabobj='.urlencode($tabobj); + if ($module) { + $param .= '&module='.urlencode($module); + } + if ($tab) { + $param .= '&tab='.urlencode($tab); + } + if ($tabobj) { + $param .= '&tabobj='.urlencode($tabobj); + } $value = GETPOST('value', 'alpha'); $resarray = activateModule($value); - if (!empty($resarray['errors'])) setEventMessages('', $resarray['errors'], 'errors'); - else { + if (!empty($resarray['errors'])) { + setEventMessages('', $resarray['errors'], 'errors'); + } else { //var_dump($resarray);exit; - if ($resarray['nbperms'] > 0) - { + if ($resarray['nbperms'] > 0) { $tmpsql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."user WHERE admin <> 1"; $resqltmp = $db->query($tmpsql); - if ($resqltmp) - { + if ($resqltmp) { $obj = $db->fetch_object($resqltmp); //var_dump($obj->nb);exit; - if ($obj && $obj->nb > 1) - { + if ($obj && $obj->nb > 1) { $msg = $langs->trans('ModuleEnabledAdminMustCheckRights'); setEventMessages($msg, null, 'warnings'); } - } else dol_print_error($db); + } else { + dol_print_error($db); + } } } header("Location: ".$_SERVER["PHP_SELF"]."?".$param); @@ -1538,16 +1572,23 @@ if ($action == 'set' && $user->admin) } // Disable module -if ($action == 'reset' && $user->admin) -{ +if ($action == 'reset' && $user->admin) { $param = ''; - if ($module) $param .= '&module='.urlencode($module); - if ($tab) $param .= '&tab='.urlencode($tab); - if ($tabobj) $param .= '&tabobj='.urlencode($tabobj); + if ($module) { + $param .= '&module='.urlencode($module); + } + if ($tab) { + $param .= '&tab='.urlencode($tab); + } + if ($tabobj) { + $param .= '&tabobj='.urlencode($tabobj); + } $value = GETPOST('value', 'alpha'); $result = unActivateModule($value); - if ($result) setEventMessages($result, null, 'errors'); + if ($result) { + setEventMessages($result, null, 'errors'); + } header("Location: ".$_SERVER["PHP_SELF"]."?".$param); exit; } @@ -1562,19 +1603,21 @@ $form = new Form($db); $formadmin = new FormAdmin($db); // Set dir where external modules are installed -if (!dol_is_dir($dirins)) -{ +if (!dol_is_dir($dirins)) { dol_mkdir($dirins); } $dirins_ok = (dol_is_dir($dirins)); -llxHeader('', $langs->trans("ModuleBuilder"), '', '', 0, 0, - array( +$help_url = ''; +$morejs = array( '/includes/ace/src/ace.js', '/includes/ace/src/ext-statusbar.js', '/includes/ace/src/ext-language_tools.js', //'/includes/ace/src/ext-chromevox.js' - ), array(), '', 'classforhorizontalscrolloftabs'); +); +$morecss = array(); + +llxHeader('', $langs->trans("ModuleBuilder"), $help_url, '', 0, 0, $morejs, $morecss, '', 'classforhorizontalscrolloftabs'); $text = $langs->trans("ModuleBuilder"); @@ -1589,15 +1632,12 @@ print '<br>'; $message = ''; -if (!$dirins) -{ +if (!$dirins) { $message = info_admin($langs->trans("ConfFileMustContainCustom", DOL_DOCUMENT_ROOT.'/custom', DOL_DOCUMENT_ROOT)); $allowfromweb = -1; } else { - if ($dirins_ok) - { - if (!is_writable(dol_osencode($dirins))) - { + if ($dirins_ok) { + if (!is_writable(dol_osencode($dirins))) { $langs->load("errors"); $message = info_admin($langs->trans("ErrorFailedToWriteInDir", $dirins)); $allowfromweb = 0; @@ -1607,8 +1647,7 @@ if (!$dirins) $allowfromweb = 0; } } -if ($message) -{ +if ($message) { print $message; } @@ -1621,8 +1660,7 @@ $error = 0; $moduleobj = null; -if (!empty($module) && $module != 'initmodule' && $module != 'deletemodule') -{ +if (!empty($module) && $module != 'initmodule' && $module != 'deletemodule') { $modulelowercase = strtolower($module); $loadclasserrormessage = ''; @@ -1640,8 +1678,7 @@ if (!empty($module) && $module != 'initmodule' && $module != 'deletemodule') $loadclasserrormessage .= 'Line: '.$e->getLine()."<br>\n"; } - if (class_exists($class)) - { + if (class_exists($class)) { try { $moduleobj = new $class($db); } catch (Exception $e) { @@ -1649,7 +1686,9 @@ if (!empty($module) && $module != 'initmodule' && $module != 'deletemodule') print $e->getMessage(); } } else { - if (empty($forceddirread)) $error++; + if (empty($forceddirread)) { + $error++; + } $langs->load("errors"); print img_warning('').' '.$langs->trans("ErrorFailedToLoadModuleDescriptorForXXX", $module).'<br>'; print $loadclasserrormessage; @@ -1677,13 +1716,18 @@ if (is_array($listofmodules) && count($listofmodules) > 0) { $const_name = 'MAIN_MODULE_'.strtoupper($module); $param = ''; - if ($tab) $param .= '&tab='.urlencode($tab); - if ($module) $param .= '&module='.urlencode($module); - if ($tabobj) $param .= '&tabobj='.urlencode($tabobj); + if ($tab) { + $param .= '&tab='.urlencode($tab); + } + if ($module) { + $param .= '&module='.urlencode($module); + } + if ($tabobj) { + $param .= '&tabobj='.urlencode($tabobj); + } $urltomodulesetup = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?search_keyword='.urlencode($module).'">'.$langs->trans('Home').'-'.$langs->trans("Setup").'-'.$langs->trans("Modules").'</a>'; - if (!empty($conf->global->$const_name)) // If module is already activated - { + if (!empty($conf->global->$const_name)) { // If module is already activated $linktoenabledisable .= '<a class="reposition asetresetmodule valignmiddle" href="'.$_SERVER["PHP_SELF"].'?id='.$moduleobj->numero.'&action=reset&value=mod'.$module.$param.'">'; $linktoenabledisable .= img_picto($langs->trans("Activated"), 'switch_on', '', false, 0, 0, '', '', 1); $linktoenabledisable .= '</a>'; @@ -1691,27 +1735,26 @@ if (is_array($listofmodules) && count($listofmodules) > 0) { $objMod = $moduleobj; $backtourlparam = ''; $backtourlparam .= ($backtourlparam ? '&' : '?').'module='.$module; // No urlencode here, done later - if ($tab) $backtourlparam .= ($backtourlparam ? '&' : '?').'tab='.$tab; // No urlencode here, done later + if ($tab) { + $backtourlparam .= ($backtourlparam ? '&' : '?').'tab='.$tab; // No urlencode here, done later + } $backtourl = $_SERVER["PHP_SELF"].$backtourlparam; $regs = array(); - if (is_array($objMod->config_page_url)) - { + if (is_array($objMod->config_page_url)) { $i = 0; - foreach ($objMod->config_page_url as $page) - { + foreach ($objMod->config_page_url as $page) { $urlpage = $page; - if ($i++) - { + if ($i++) { $linktoenabledisable .= ' <a href="'.$urlpage.'" title="'.$langs->trans($page).'">'.img_picto(ucfirst($page), "setup").'</a>'; // print '<a href="'.$page.'">'.ucfirst($page).'</a>&nbsp;'; } else { - if (preg_match('/^([^@]+)@([^@]+)$/i', $urlpage, $regs)) - { + if (preg_match('/^([^@]+)@([^@]+)$/i', $urlpage, $regs)) { $urltouse = dol_buildpath('/'.$regs[2].'/admin/'.$regs[1], 1); $linktoenabledisable .= ' &nbsp; <a href="'.$urltouse.(preg_match('/\?/', $urltouse) ? '&' : '?').'save_lastsearch_values=1&backtopage='.urlencode($backtourl).'" title="'.$langs->trans("Setup").'">'.img_picto($langs->trans("Setup"), "setup", 'style="padding-right: 6px"').'</a>'; } else { - // Case standard admin page (not a page provided by the module but a page + // Case standard admin page (not a page provided by the + // module but a page provided by dolibarr) $urltouse = DOL_URL_ROOT.'/admin/'.$urlpage; $linktoenabledisable .= ' &nbsp; <a href="'.$urltouse.(preg_match('/\?/', $urltouse) ? '&' : '?').'save_lastsearch_values=1&backtopage='.urlencode($backtourl).'" title="'.$langs->trans("Setup").'">'.img_picto($langs->trans("Setup"), "setup", 'style="padding-right: 6px"').'</a>'; } @@ -1726,14 +1769,12 @@ if (is_array($listofmodules) && count($listofmodules) > 0) { $linktoenabledisable .= "</a>\n"; } - if (!empty($conf->$modulelowercase->enabled)) - { + if (!empty($conf->$modulelowercase->enabled)) { $modulestatusinfo = $form->textwithpicto('', $langs->trans("Warning").' : '.$langs->trans("ModuleIsLive"), -1, 'warning'); } // Loop to show tab of each module - foreach ($listofmodules as $tmpmodule => $tmpmodulearray) - { + foreach ($listofmodules as $tmpmodule => $tmpmodulearray) { $head[$h][0] = $_SERVER["PHP_SELF"].'?module='.$tmpmodulearray['modulenamewithcase'].($forceddirread ? '@'.$dirread : ''); $head[$h][1] = $tmpmodulearray['modulenamewithcase']; $head[$h][2] = $tmpmodulearray['modulenamewithcase']; @@ -1754,8 +1795,7 @@ $h++; print dol_get_fiche_head($head, $module, '', -1, '', 0, $infomodulesfound, '', 8); // Modules -if ($module == 'initmodule') -{ +if ($module == 'initmodule') { // New module print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -1784,8 +1824,7 @@ if ($module == 'initmodule') print '</form>'; } elseif (!empty($module)) { // Tabs for module - if (!$error) - { + if (!$error) { $dirread = $listofmodules[strtolower($module)]['moduledescriptorrootpath']; $head2 = array(); @@ -1874,20 +1913,17 @@ if ($module == 'initmodule') // Note module is inside $dirread - if ($tab == 'description') - { + if ($tab == 'description') { $pathtofile = $listofmodules[strtolower($module)]['moduledescriptorrelpath']; $pathtofilereadme = $modulelowercase.'/README.md'; $pathtochangelog = $modulelowercase.'/ChangeLog.md'; - if ($action != 'editfile' || empty($file)) - { + if ($action != 'editfile' || empty($file)) { print dol_get_fiche_head($head2, $tab, '', -1, '', 0, '', '', 0, 'formodulesuffix'); // Description - level 2 print '<span class="opacitymedium">'.$langs->trans("ModuleBuilderDesc".$tab).'</span>'; $infoonmodulepath = ''; - if (realpath($dirread.'/'.$modulelowercase) != $dirread.'/'.$modulelowercase) - { + if (realpath($dirread.'/'.$modulelowercase) != $dirread.'/'.$modulelowercase) { $infoonmodulepath = '<span class="opacitymedium">'.$langs->trans("RealPathOfModule").' :</span> <strong>'.realpath($dirread.'/'.$modulelowercase).'</strong><br>'; print ' '.$infoonmodulepath; } @@ -1913,8 +1949,7 @@ if ($module == 'initmodule') print load_fiche_titre($langs->trans("DescriptorFile"), '', ''); - if (!empty($moduleobj)) - { + if (!empty($moduleobj)) { print '<div class="underbanner clearboth"></div>'; print '<div class="fichecenter">'; @@ -1975,16 +2010,18 @@ if ($module == 'initmodule') print $langs->trans("ErrorFailedToLoadModuleDescriptorForXXX", $module).'<br>'; } - if (!empty($moduleobj)) - { + if (!empty($moduleobj)) { print '<br><br>'; // Readme file print load_fiche_titre($langs->trans("ReadmeFile"), '', ''); print '<!-- readme file -->'; - if (dol_is_file($dirread.'/'.$pathtofilereadme)) print '<div class="underbanner clearboth"></div><div class="fichecenter">'.$moduleobj->getDescLong().'</div>'; - else print '<span class="opacitymedium">'.$langs->trans("ErrorFileNotFound", $pathtofilereadme).'</span>'; + if (dol_is_file($dirread.'/'.$pathtofilereadme)) { + print '<div class="underbanner clearboth"></div><div class="fichecenter">'.$moduleobj->getDescLong().'</div>'; + } else { + print '<span class="opacitymedium">'.$langs->trans("ErrorFileNotFound", $pathtofilereadme).'</span>'; + } print '<br><br>'; @@ -1992,16 +2029,18 @@ if ($module == 'initmodule') print load_fiche_titre($langs->trans("ChangeLog"), '', ''); print '<!-- changelog file -->'; - if (dol_is_file($dirread.'/'.$pathtochangelog)) print '<div class="underbanner clearboth"></div><div class="fichecenter">'.$moduleobj->getChangeLog().'</div>'; - else print '<span class="opacitymedium">'.$langs->trans("ErrorFileNotFound", $pathtochangelog).'</span>'; + if (dol_is_file($dirread.'/'.$pathtochangelog)) { + print '<div class="underbanner clearboth"></div><div class="fichecenter">'.$moduleobj->getChangeLog().'</div>'; + } else { + print '<span class="opacitymedium">'.$langs->trans("ErrorFileNotFound", $pathtochangelog).'</span>'; + } } print dol_get_fiche_end(); } else { // Edit text file $fullpathoffile = dol_buildpath($file, 0, 1); // Description - level 2 - if ($fullpathoffile) - { + if ($fullpathoffile) { $content = file_get_contents($fullpathoffile); } @@ -2032,10 +2071,8 @@ if ($module == 'initmodule') print dol_get_fiche_head($head2, $tab, '', -1, '', 0, '', '', 0, 'formodulesuffix'); // Level 2 } - if ($tab == 'languages') - { - if ($action != 'editfile' || empty($file)) - { + if ($tab == 'languages') { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'.$langs->trans("LanguageDefDesc").'</span><br>'; print '<br>'; @@ -2056,8 +2093,7 @@ if ($module == 'initmodule') $langfiles = dol_dir_list(dol_buildpath($modulelowercase.'/langs', 0), 'files', 1, '\.lang$'); print '<table class="none">'; - foreach ($langfiles as $langfile) - { + foreach ($langfiles as $langfile) { $pathtofile = $modulelowercase.'/langs/'.$langfile['relativename']; print '<tr><td><span class="fa fa-file-o"></span> '.$langs->trans("LanguageFile").' '.basename(dirname($pathtofile)).' : <strong>'.$pathtofile.'</strong>'; print '</td><td><a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=editfile&format=txt&file='.urlencode($pathtofile).'">'.img_picto($langs->trans("Edit"), 'edit').'</a>'; @@ -2095,14 +2131,12 @@ if ($module == 'initmodule') } } - if ($tab == 'dictionaries') - { + if ($tab == 'dictionaries') { $pathtofile = $listofmodules[strtolower($module)]['moduledescriptorrelpath']; $dicts = $moduleobj->dictionaries; - if ($action != 'editfile' || empty($file)) - { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'; $htmlhelp = $langs->trans("DictionariesDefDescTooltip", '<a href="'.DOL_URL_ROOT.'/admin/dict.php">'.$langs->trans('Setup').' - '.$langs->trans('Dictionaries').'</a>'); print $form->textwithpicto($langs->trans("DictionariesDefDesc"), $htmlhelp, 1, 'help', '', 0, 2, 'helpondesc').'<br>'; @@ -2143,12 +2177,10 @@ if ($module == 'initmodule') print_liste_field_titre("Condition", $_SERVER["PHP_SELF"], '', "", $param, '', $sortfield, $sortorder); print "</tr>\n"; - if (is_array($dicts) && is_array($dicts['tabname'])) - { + if (is_array($dicts) && is_array($dicts['tabname'])) { $i = 0; $maxi = count($dicts['tabname']); - while ($i < $maxi) - { + while ($i < $maxi) { print '<tr class="oddeven">'; print '<td>'; @@ -2228,8 +2260,7 @@ if ($module == 'initmodule') } } - if ($tab == 'objects') - { + if ($tab == 'objects') { $head3 = array(); $h = 0; @@ -2245,17 +2276,21 @@ if ($module == 'initmodule') $listofobject = dol_dir_list($dir, 'files', 0, '\.class\.php$'); $firstobjectname = ''; - foreach ($listofobject as $fileobj) - { - if (preg_match('/^api_/', $fileobj['name'])) continue; - if (preg_match('/^actions_/', $fileobj['name'])) continue; + foreach ($listofobject as $fileobj) { + if (preg_match('/^api_/', $fileobj['name'])) { + continue; + } + if (preg_match('/^actions_/', $fileobj['name'])) { + continue; + } $tmpcontent = file_get_contents($fileobj['fullname']); - if (preg_match('/class\s+([^\s]*)\s+extends\s+CommonObject/ims', $tmpcontent, $reg)) - { + if (preg_match('/class\s+([^\s]*)\s+extends\s+CommonObject/ims', $tmpcontent, $reg)) { //$objectname = preg_replace('/\.txt$/', '', $fileobj['name']); $objectname = $reg[1]; - if (empty($firstobjectname)) $firstobjectname = $objectname; + if (empty($firstobjectname)) { + $firstobjectname = $objectname; + } $head3[$h][0] = $_SERVER["PHP_SELF"].'?tab=objects&module='.$module.($forceddirread ? '@'.$dirread : '').'&tabobj='.$objectname; $head3[$h][1] = $objectname; @@ -2270,16 +2305,17 @@ if ($module == 'initmodule') $h++; // If tabobj was not defined, then we check if there is one obj. If yes, we force on it, if no, we will show tab to create new objects. - if ($tabobj == 'newobjectifnoobj') - { - if ($firstobjectname) $tabobj = $firstobjectname; - else $tabobj = 'newobject'; + if ($tabobj == 'newobjectifnoobj') { + if ($firstobjectname) { + $tabobj = $firstobjectname; + } else { + $tabobj = 'newobject'; + } } print dol_get_fiche_head($head3, $tabobj, '', -1, ''); // Level 3 - if ($tabobj == 'newobject') - { + if ($tabobj == 'newobject') { // New object tab print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -2321,19 +2357,22 @@ if ($module == 'initmodule') print '</form>'; } else { // tabobj = module - if ($action == 'deleteproperty') - { + if ($action == 'deleteproperty') { $formconfirm = $form->formconfirm( $_SERVER["PHP_SELF"].'?propertykey='.urlencode(GETPOST('propertykey', 'alpha')).'&objectname='.urlencode($objectname).'&tab='.urlencode($tab).'&module='.urlencode($module).'&tabobj='.urlencode($tabobj), - $langs->trans('Delete'), $langs->trans('ConfirmDeleteProperty', GETPOST('propertykey', 'alpha')), 'confirm_deleteproperty', '', 0, 1 - ); + $langs->trans('Delete'), + $langs->trans('ConfirmDeleteProperty', GETPOST('propertykey', 'alpha')), + 'confirm_deleteproperty', + '', + 0, + 1 + ); // Print form confirm print $formconfirm; } - if ($action != 'editfile' || empty($file)) - { + if ($action != 'editfile' || empty($file)) { try { //$pathtofile = $listofmodules[strtolower($module)]['moduledescriptorrelpath']; @@ -2374,8 +2413,7 @@ if ($module == 'initmodule') $realpathtopicto = $dirread.'/'.$pathtopicto; $realpathtoscript = $dirread.'/'.$pathtoscript; - if (empty($realpathtoapi)) // For compatibility with some old modules - { + if (empty($realpathtoapi)) { // For compatibility with some old modules $pathtoapi = strtolower($module).'/class/api_'.strtolower($module).'s.class.php'; $realpathtoapi = $dirread.'/'.$pathtoapi; } @@ -2389,15 +2427,14 @@ if ($module == 'initmodule') print '<span class="fa fa-file-o"></span> '.$langs->trans("ApiClassFile").' : <strong>'.($realpathtoapi ? '' : '<strike>').$pathtoapi.($realpathtoapi ? '' : '</strike>').'</strong>'; if (dol_is_file($realpathtoapi)) { print ' <a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&tabobj='.$tabobj.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=editfile&format=php&file='.urlencode($pathtoapi).'">'.img_picto($langs->trans("Edit"), 'edit').'</a>'; - print ' '; - print '<a class="reposition editfielda" href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&tabobj='.$tabobj.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=confirm_removefile&file='.urlencode($pathtoapi).'">'.img_picto($langs->trans("Delete"), 'delete').'</a>'; - print ' &nbsp; '; - if (empty($conf->global->$const_name)) // If module is not activated - { - print '<a href="#" class="classfortooltip" target="apiexplorer" title="'.$langs->trans("ModuleMustBeEnabled", $module).'"><strike>'.$langs->trans("GoToApiExplorer").'</strike></a>'; - } else { - print '<a href="'.DOL_URL_ROOT.'/api/index.php/explorer/" target="apiexplorer">'.$langs->trans("GoToApiExplorer").'</a>'; - } + print ' '; + print '<a class="reposition editfielda" href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&tabobj='.$tabobj.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=confirm_removefile&file='.urlencode($pathtoapi).'">'.img_picto($langs->trans("Delete"), 'delete').'</a>'; + print ' &nbsp; '; + if (empty($conf->global->$const_name)) { // If module is not activated + print '<a href="#" class="classfortooltip" target="apiexplorer" title="'.$langs->trans("ModuleMustBeEnabled", $module).'"><strike>'.$langs->trans("GoToApiExplorer").'</strike></a>'; + } else { + print '<a href="'.DOL_URL_ROOT.'/api/index.php/explorer/" target="apiexplorer">'.$langs->trans("GoToApiExplorer").'</a>'; + } } else { //print '<span class="opacitymedium">'.$langs->trans("FileNotYetGenerated").'</span> '; print '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&tabobj='.$tabobj.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=initapi&format=php&file='.urlencode($pathtoapi).'"><input type="button" class="button smallpaddingimp" value="'.$langs->trans("Generate").'"></a>'; @@ -2511,26 +2548,24 @@ if ($module == 'initmodule') print '<br><br><br>'; - if (function_exists('opcache_invalidate')) opcache_invalidate($dirread.'/'.$pathtoclass, true); // remove the include cache hell ! + if (function_exists('opcache_invalidate')) { + opcache_invalidate($dirread.'/'.$pathtoclass, true); // remove the include cache hell ! + } - if (empty($forceddirread) && empty($dirread)) - { + if (empty($forceddirread) && empty($dirread)) { $result = dol_include_once($pathtoclass); } else { $result = @include_once $dirread.'/'.$pathtoclass; } - if (class_exists($tabobj)) - { + if (class_exists($tabobj)) { try { $tmpobjet = @new $tabobj($db); - } catch (Exception $e) - { + } catch (Exception $e) { dol_syslog('Failed to load Constructor of class: '.$e->getMessage(), LOG_WARNING); } } - if (!empty($tmpobjet)) - { + if (!empty($tmpobjet)) { $reflector = new ReflectionClass($tabobj); $reflectorproperties = $reflector->getProperties(); // Can also use get_object_vars $reflectorpropdefault = $reflector->getDefaultProperties(); // Can also use get_object_vars @@ -2585,8 +2620,7 @@ if ($module == 'initmodule') //$properties = dol_sort_array($tmpobjet->fields, 'position'); $properties = dol_sort_array($reflectorpropdefault['fields'], 'position'); - if (!empty($properties)) - { + if (!empty($properties)) { // Line to add a property print '<tr>'; print '<td><input class="text maxwidth75" name="propname" value="'.dol_escape_htmltag(GETPOST('propname', 'alpha')).'"></td>'; @@ -2614,8 +2648,7 @@ if ($module == 'initmodule') print '</td></tr>'; // List of existing properties - foreach ($properties as $propkey => $propval) - { + foreach ($properties as $propkey => $propval) { /* If from Reflection if ($propval->class == $tabobj) { @@ -2720,8 +2753,7 @@ if ($module == 'initmodule') print '</span>'; print '</td>'; print '<td class="center">'; - if ($propname != 'rowid') - { + if ($propname != 'rowid') { print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteproperty&token='.newToken().'&propertykey='.urlencode($propname).'&tab='.urlencode($tab).'&module='.urlencode($module).'&tabobj='.urlencode($tabobj).'">'.img_delete().'</a>'; } print '</td>'; @@ -2729,20 +2761,19 @@ if ($module == 'initmodule') print '</tr>'; } } else { - if ($tab == 'specifications') - { - if ($action != 'editfile' || empty($file)) - { + if ($tab == 'specifications') { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'.$langs->trans("SpecDefDesc").'</span><br>'; print '<br>'; $specs = dol_dir_list(dol_buildpath($modulelowercase.'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/')); - foreach ($specs as $spec) - { + foreach ($specs as $spec) { $pathtofile = $modulelowercase.'/doc/'.$spec['relativename']; $format = 'asciidoc'; - if (preg_match('/\.md$/i', $spec['name'])) $format = 'markdown'; + if (preg_match('/\.md$/i', $spec['name'])) { + $format = 'markdown'; + } print '<span class="fa fa-file-o"></span> '.$langs->trans("SpecificationFile").' : <strong>'.$pathtofile.'</strong>'; print ' <a href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=editfile&format='.$format.'&file='.urlencode($pathtofile).'">'.img_picto($langs->trans("Edit"), 'edit').'</a>'; print '<br>'; @@ -2785,13 +2816,11 @@ if ($module == 'initmodule') } else { print '<tr><td><span class="warning">'.$langs->trans('Failed to init the object with the new.').'</warning></td></tr>'; } - } catch (Exception $e) - { + } catch (Exception $e) { print $e->getMessage(); } } else { - if (empty($forceddirread)) - { + if (empty($forceddirread)) { $fullpathoffile = dol_buildpath($file, 0); } else { $fullpathoffile = $dirread.'/'.$file; @@ -2824,14 +2853,12 @@ if ($module == 'initmodule') print dol_get_fiche_end(); // Level 3 } - if ($tab == 'menus') - { + if ($tab == 'menus') { $pathtofile = $listofmodules[strtolower($module)]['moduledescriptorrelpath']; $menus = $moduleobj->menu; - if ($action != 'editfile' || empty($file)) - { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'; $htmlhelp = $langs->trans("MenusDefDescTooltip", '<a href="'.DOL_URL_ROOT.'/admin/menus/index.php">'.$langs->trans('Setup').' - '.$langs->trans('Menus').'</a>'); print $form->textwithpicto($langs->trans("MenusDefDesc"), $htmlhelp, 1, 'help', '', 0, 2, 'helpondesc').'<br>'; @@ -2870,10 +2897,8 @@ if ($module == 'initmodule') print_liste_field_titre("UserType", $_SERVER["PHP_SELF"], '', "", $param, '', $sortfield, $sortorder, 'right '); print "</tr>\n"; - if (count($menus)) - { - foreach ($menus as $menu) - { + if (count($menus)) { + foreach ($menus as $menu) { print '<tr class="oddeven">'; print '<td>'; @@ -2927,7 +2952,7 @@ if ($module == 'initmodule') print '</tr>'; } } else { - print '<tr><td class="opacitymedium" colspan="5">'.$langs->trans("None").'</td></tr>'; + print '<tr><td class="opacitymedium" colspan="5">'.$langs->trans("None").'</td></tr>'; } print '</table>'; @@ -2960,14 +2985,12 @@ if ($module == 'initmodule') } } - if ($tab == 'permissions') - { + if ($tab == 'permissions') { $pathtofile = $listofmodules[strtolower($module)]['moduledescriptorrelpath']; $perms = $moduleobj->rights; - if ($action != 'editfile' || empty($file)) - { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'; $htmlhelp = $langs->trans("PermissionsDefDescTooltip", '<a href="'.DOL_URL_ROOT.'/admin/perms.php">'.$langs->trans('DefaultPermissions').'</a>'); print $form->textwithpicto($langs->trans("PermissionsDefDesc"), $htmlhelp, 1, 'help', '', 0, 2, 'helpondesc').'<br>'; @@ -2998,10 +3021,8 @@ if ($module == 'initmodule') print_liste_field_titre("", $_SERVER["PHP_SELF"], '', "", $param, '', $sortfield, $sortorder); print "</tr>\n"; - if (count($perms)) - { - foreach ($perms as $perm) - { + if (count($perms)) { + foreach ($perms as $perm) { print '<tr class="oddeven">'; print '<td>'; @@ -3056,10 +3077,8 @@ if ($module == 'initmodule') } } - if ($tab == 'hooks') - { - if ($action != 'editfile' || empty($file)) - { + if ($tab == 'hooks') { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'.$langs->trans("HooksDefDesc").'</span><br>'; print '<br>'; @@ -3075,8 +3094,7 @@ if ($module == 'initmodule') print '<tr><td>'; $pathtohook = strtolower($module).'/class/actions_'.strtolower($module).'.class.php'; print '<span class="fa fa-file-o"></span> '.$langs->trans("HooksFile").' : '; - if (dol_is_file($dirins.'/'.$pathtohook)) - { + if (dol_is_file($dirins.'/'.$pathtohook)) { print '<strong>'.$pathtohook.'</strong>'; print '</td>'; print '<td><a class="editfielda paddingleft paddingright" href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=editfile&format=php&file='.urlencode($pathtohook).'">'.img_picto($langs->trans("Edit"), 'edit').'</a> '; @@ -3113,15 +3131,13 @@ if ($module == 'initmodule') } } - if ($tab == 'triggers') - { + if ($tab == 'triggers') { require_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; $interfaces = new Interfaces($db); $triggers = $interfaces->getTriggersList(array('/'.strtolower($module).'/core/triggers')); - if ($action != 'editfile' || empty($file)) - { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'.$langs->trans("TriggerDefDesc").'</span><br>'; print '<br>'; @@ -3134,10 +3150,8 @@ if ($module == 'initmodule') print '<a class="editfielda paddingleft paddingright" href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=editfile&format=php&file='.urlencode($pathtofile).'">'.img_picto($langs->trans("Edit"), 'edit').'</a>'; print '</td></tr>'; - if (!empty($triggers)) - { - foreach ($triggers as $trigger) - { + if (!empty($triggers)) { + foreach ($triggers as $trigger) { $pathtofile = $trigger['relpath']; print '<tr><td>'; @@ -3181,10 +3195,8 @@ if ($module == 'initmodule') } } - if ($tab == 'css') - { - if ($action != 'editfile' || empty($file)) - { + if ($tab == 'css') { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'.$langs->trans("CSSDesc").'</span><br>'; print '<br>'; @@ -3193,8 +3205,7 @@ if ($module == 'initmodule') print '<tr><td>'; $pathtohook = strtolower($module).'/css/'.strtolower($module).'.css.php'; print '<span class="fa fa-file-o"></span> '.$langs->trans("CSSFile").' : '; - if (dol_is_file($dirins.'/'.$pathtohook)) - { + if (dol_is_file($dirins.'/'.$pathtohook)) { print '<strong>'.$pathtohook.'</strong>'; print '</td><td><a class="editfielda paddingleft paddingright" href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=editfile&format=php&file='.urlencode($pathtohook).'">'.img_picto($langs->trans("Edit"), 'edit').'</a></td>'; print '</td><td><a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=confirm_removefile&format='.$format.'&file='.urlencode($pathtohook).'">'.img_picto($langs->trans("Delete"), 'delete').'</a></td>'; @@ -3229,10 +3240,8 @@ if ($module == 'initmodule') } } - if ($tab == 'js') - { - if ($action != 'editfile' || empty($file)) - { + if ($tab == 'js') { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'.$langs->trans("JSDesc").'</span><br>'; print '<br>'; @@ -3241,8 +3250,7 @@ if ($module == 'initmodule') print '<tr><td>'; $pathtohook = strtolower($module).'/js/'.strtolower($module).'.js.php'; print '<span class="fa fa-file-o"></span> '.$langs->trans("JSFile").' : '; - if (dol_is_file($dirins.'/'.$pathtohook)) - { + if (dol_is_file($dirins.'/'.$pathtohook)) { print '<strong>'.$pathtohook.'</strong>'; print '</td><td><a class="editfielda paddingleft paddingright" href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=editfile&format=php&file='.urlencode($pathtohook).'">'.img_picto($langs->trans("Edit"), 'edit').'</a></td>'; print '</td><td><a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=confirm_removefile&format='.$format.'&file='.urlencode($pathtohook).'">'.img_picto($langs->trans("Delete"), 'delete').'</a></td>'; @@ -3277,22 +3285,18 @@ if ($module == 'initmodule') } } - if ($tab == 'widgets') - { + if ($tab == 'widgets') { require_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; $widgets = ModeleBoxes::getWidgetsList(array('/'.strtolower($module).'/core/boxes')); - if ($action != 'editfile' || empty($file)) - { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'.$langs->trans("WidgetDesc").'</span><br>'; print '<br>'; print '<table>'; - if (!empty($widgets)) - { - foreach ($widgets as $widget) - { + if (!empty($widgets)) { + foreach ($widgets as $widget) { $pathtofile = $widget['relpath']; print '<tr><td><span class="fa fa-file-o"></span> '.$langs->trans("WidgetFile").' : <strong>'.$pathtofile.'</strong>'; @@ -3332,29 +3336,28 @@ if ($module == 'initmodule') } } - if ($tab == 'cli') - { + if ($tab == 'cli') { $clifiles = array(); $i = 0; $dircli = array('/'.strtolower($module).'/scripts'); - foreach ($dircli as $reldir) - { + foreach ($dircli as $reldir) { $dir = dol_buildpath($reldir, 0); $newdir = dol_osencode($dir); // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php at each call) - if (!is_dir($newdir)) continue; + if (!is_dir($newdir)) { + continue; + } $handle = opendir($newdir); - if (is_resource($handle)) - { - while (($tmpfile = readdir($handle)) !== false) - { - if (is_readable($newdir.'/'.$file) && preg_match('/^(.+)\.php/', $tmpfile, $reg)) - { - if (preg_match('/\.back$/', $tmpfile)) continue; + if (is_resource($handle)) { + while (($tmpfile = readdir($handle)) !== false) { + if (is_readable($newdir.'/'.$file) && preg_match('/^(.+)\.php/', $tmpfile, $reg)) { + if (preg_match('/\.back$/', $tmpfile)) { + continue; + } $clifiles[$i]['relpath'] = preg_replace('/^\//', '', $reldir).'/'.$tmpfile; @@ -3365,16 +3368,13 @@ if ($module == 'initmodule') } } - if ($action != 'editfile' || empty($file)) - { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'.$langs->trans("CLIDesc").'</span><br>'; print '<br>'; print '<table>'; - if (!empty($clifiles)) - { - foreach ($clifiles as $clifile) - { + if (!empty($clifiles)) { + foreach ($clifiles as $clifile) { $pathtofile = $clifile['relpath']; print '<tr><td><span class="fa fa-file-o"></span> '.$langs->trans("CLIFile").' : <strong>'.$pathtofile.'</strong>'; @@ -3414,14 +3414,12 @@ if ($module == 'initmodule') } } - if ($tab == 'cron') - { + if ($tab == 'cron') { $pathtofile = $listofmodules[strtolower($module)]['moduledescriptorrelpath']; $cronjobs = $moduleobj->cronjobs; - if ($action != 'editfile' || empty($file)) - { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'.str_replace('{s1}', '<a href="'.DOL_URL_ROOT.'/cron/list.php">'.$langs->transnoentities('CronList').'</a>', $langs->trans("CronJobDefDesc", '{s1}')).'</span><br>'; print '<br>'; @@ -3450,10 +3448,8 @@ if ($module == 'initmodule') print_liste_field_titre("Comment", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder); print "</tr>\n"; - if (count($cronjobs)) - { - foreach ($cronjobs as $cron) - { + if (count($cronjobs)) { + foreach ($cronjobs as $cron) { print '<tr class="oddeven">'; print '<td>'; @@ -3461,8 +3457,7 @@ if ($module == 'initmodule') print '</td>'; print '<td>'; - if ($cron['jobtype'] == 'method') - { + if ($cron['jobtype'] == 'method') { $text = $langs->trans("CronClass"); $texttoshow = $langs->trans('CronModule').': '.$module.'<br>'; $texttoshow .= $langs->trans('CronClass').': '.$cron['class'].'<br>'; @@ -3470,8 +3465,7 @@ if ($module == 'initmodule') $texttoshow .= $langs->trans('CronMethod').': '.$cron['method']; $texttoshow .= '<br>'.$langs->trans('CronArgs').': '.$cron['parameters']; $texttoshow .= '<br>'.$langs->trans('Comment').': '.$langs->trans($cron['comment']); - } elseif ($cron['jobtype'] == 'command') - { + } elseif ($cron['jobtype'] == 'command') { $text = $langs->trans('CronCommand'); $texttoshow = $langs->trans('CronCommand').': '.dol_trunc($cron['command']); $texttoshow .= '<br>'.$langs->trans('CronArgs').': '.$cron['parameters']; @@ -3481,10 +3475,18 @@ if ($module == 'initmodule') print '</td>'; print '<td>'; - if ($cron['unitfrequency'] == "60") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Minutes'); - if ($cron['unitfrequency'] == "3600") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Hours'); - if ($cron['unitfrequency'] == "86400") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Days'); - if ($cron['unitfrequency'] == "604800") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Weeks'); + if ($cron['unitfrequency'] == "60") { + print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Minutes'); + } + if ($cron['unitfrequency'] == "3600") { + print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Hours'); + } + if ($cron['unitfrequency'] == "86400") { + print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Days'); + } + if ($cron['unitfrequency'] == "604800") { + print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Weeks'); + } print '</td>'; print '<td>'; @@ -3492,7 +3494,9 @@ if ($module == 'initmodule') print '</td>'; print '<td>'; - if (!empty($cron['comment'])) {print $cron['comment']; } + if (!empty($cron['comment'])) { + print $cron['comment']; + } print '</td>'; print '</tr>'; @@ -3531,23 +3535,21 @@ if ($module == 'initmodule') } } - if ($tab == 'specifications') - { + if ($tab == 'specifications') { $specs = dol_dir_list(dol_buildpath($modulelowercase.'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/')); - if ($action != 'editfile' || empty($file)) - { + if ($action != 'editfile' || empty($file)) { print '<span class="opacitymedium">'.$langs->trans("SpecDefDesc").'</span><br>'; print '<br>'; print '<table>'; - if (is_array($specs) && !empty($specs)) - { - foreach ($specs as $spec) - { + if (is_array($specs) && !empty($specs)) { + foreach ($specs as $spec) { $pathtofile = $modulelowercase.'/doc/'.$spec['relativename']; $format = 'asciidoc'; - if (preg_match('/\.md$/i', $spec['name'])) $format = 'markdown'; + if (preg_match('/\.md$/i', $spec['name'])) { + $format = 'markdown'; + } print '<tr><td>'; print '<span class="fa fa-file-o"></span> '.$langs->trans("SpecificationFile").' : <strong>'.$pathtofile.'</strong>'; print '</td><td><a class="editfielda paddingleft paddingright" href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.($forceddirread ? '@'.$dirread : '').'&action=editfile&format='.$format.'&file='.urlencode($pathtofile).'">'.img_picto($langs->trans("Edit"), 'edit').'</a></td>'; @@ -3601,8 +3603,9 @@ if ($module == 'initmodule') // HTML print '<span class="fa fa-file-o"></span> '.$langs->trans("PathToModuleDocumentation", "HTML").' : '; - if (!dol_is_file($outputfiledoc)) print '<span class="opacitymedium">'.$langs->trans("FileNotYetGenerated").'</span>'; - else { + if (!dol_is_file($outputfiledoc)) { + print '<span class="opacitymedium">'.$langs->trans("FileNotYetGenerated").'</span>'; + } else { print '<strong>'; print '<a href="'.$outputfiledocurl.'" target="_blank">'; print $outputfiledoc; @@ -3614,8 +3617,9 @@ if ($module == 'initmodule') // PDF print '<span class="fa fa-file-o"></span> '.$langs->trans("PathToModuleDocumentation", "PDF").' : '; - if (!dol_is_file($outputfiledocpdf)) print '<span class="opacitymedium">'.$langs->trans("FileNotYetGenerated").'</span>'; - else { + if (!dol_is_file($outputfiledocpdf)) { + print '<span class="opacitymedium">'.$langs->trans("FileNotYetGenerated").'</span>'; + } else { print '<strong>'; print '<a href="'.$outputfiledocurlpdf.'" target="_blank">'; print $outputfiledocpdf; @@ -3633,18 +3637,18 @@ if ($module == 'initmodule') print '<input type="hidden" name="tab" value="'.dol_escape_htmltag($tab).'">'; print '<input type="hidden" name="module" value="'.dol_escape_htmltag($module).'">'; print '<input type="submit" class="button" name="generatedoc" value="'.$langs->trans("BuildDocumentation").'"'; - if (!is_array($specs) || empty($specs)) print ' disabled="disabled"'; + if (!is_array($specs) || empty($specs)) { + print ' disabled="disabled"'; + } print '>'; print '</form>'; } - if ($tab == 'buildpackage') - { + if ($tab == 'buildpackage') { print '<span class="opacitymedium">'.$langs->trans("BuildPackageDesc").'</span>'; print '<br>'; - if (!class_exists('ZipArchive') && !defined('ODTPHP_PATHTOPCLZIP')) - { + if (!class_exists('ZipArchive') && !defined('ODTPHP_PATHTOPCLZIP')) { print img_warning().' '.$langs->trans("ErrNoZipEngine"); print '<br>'; } @@ -3659,8 +3663,7 @@ if ($module == 'initmodule') dol_include_once($pathtofile); $class = 'mod'.$module; - if (class_exists($class)) - { + if (class_exists($class)) { try { $moduleobj = new $class($db); } catch (Exception $e) { @@ -3675,8 +3678,7 @@ if ($module == 'initmodule') } $arrayversion = explode('.', $moduleobj->version, 3); - if (count($arrayversion)) - { + if (count($arrayversion)) { $FILENAMEZIP = "module_".$modulelowercase.'-'.$arrayversion[0].'.'.$arrayversion[1].($arrayversion[2] ? ".".$arrayversion[2] : "").".zip"; $outputfilezip = dol_buildpath($modulelowercase, 0).'/bin/'.$FILENAMEZIP; } @@ -3684,8 +3686,9 @@ if ($module == 'initmodule') print '<br>'; print '<span class="fa fa-file-o"></span> '.$langs->trans("PathToModulePackage").' : '; - if (!dol_is_file($outputfilezip)) print '<span class="opacitymedium">'.$langs->trans("FileNotYetGenerated").'</span>'; - else { + if (!dol_is_file($outputfilezip)) { + print '<span class="opacitymedium">'.$langs->trans("FileNotYetGenerated").'</span>'; + } else { $relativepath = $modulelowercase.'/bin/'.$FILENAMEZIP; print '<strong><a href="'.DOL_URL_ROOT.'/document.php?modulepart=packages&file='.urlencode($relativepath).'">'.$outputfilezip.'</a></strong>'; print ' ('.$langs->trans("GeneratedOn").' '.dol_print_date(dol_filemtime($outputfilezip), 'dayhour').')'; @@ -3703,8 +3706,7 @@ if ($module == 'initmodule') print '</form>'; } - if ($tab != 'description') - { + if ($tab != 'description') { print dol_get_fiche_end(); } } diff --git a/htdocs/modulebuilder/template/admin/about.php b/htdocs/modulebuilder/template/admin/about.php index d527f1978a9..30cc93a6d51 100644 --- a/htdocs/modulebuilder/template/admin/about.php +++ b/htdocs/modulebuilder/template/admin/about.php @@ -25,16 +25,30 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} // Libraries require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; diff --git a/htdocs/modulebuilder/template/admin/myobject_extrafields.php b/htdocs/modulebuilder/template/admin/myobject_extrafields.php index 41ca86a0ce2..cd2125547e8 100644 --- a/htdocs/modulebuilder/template/admin/myobject_extrafields.php +++ b/htdocs/modulebuilder/template/admin/myobject_extrafields.php @@ -29,16 +29,30 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once '../lib/mymodule.lib.php'; diff --git a/htdocs/modulebuilder/template/admin/setup.php b/htdocs/modulebuilder/template/admin/setup.php index e93b8686d79..06b169863f5 100644 --- a/htdocs/modulebuilder/template/admin/setup.php +++ b/htdocs/modulebuilder/template/admin/setup.php @@ -25,16 +25,30 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} global $langs, $user; @@ -61,8 +75,11 @@ $scandir = GETPOST('scan_dir', 'alpha'); $type = 'myobject'; $arrayofparameters = array( - 'MYMODULE_MYPARAM1'=>array('css'=>'minwidth200', 'enabled'=>1), - 'MYMODULE_MYPARAM2'=>array('css'=>'minwidth500', 'enabled'=>1) + 'MYMODULE_MYPARAM1'=>array('type'=>'string', 'css'=>'minwidth500' ,'enabled'=>1), + 'MYMODULE_MYPARAM2'=>array('type'=>'textarea','enabled'=>1), + //'MYMODULE_MYPARAM3'=>array('type'=>'category:'.Categorie::TYPE_CUSTOMER, 'enabled'=>1), + //'MYMODULE_MYPARAM4'=>array('type'=>'emailtemplate:thirdparty', 'enabled'=>1), + //'MYMODULE_MYPARAM5'=>array('type'=>'yesno', 'enabled'=>1), ); $error = 0; @@ -208,11 +225,57 @@ if ($action == 'edit') { print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>'; - foreach ($arrayofparameters as $key => $val) { - print '<tr class="oddeven"><td>'; - $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); - print $form->textwithpicto($langs->trans($key), $tooltiphelp); - print '</td><td><input name="'.$key.'" class="flat '.(empty($val['css']) ? 'minwidth200' : $val['css']).'" value="'.$conf->global->$key.'"></td></tr>'; + foreach ($arrayofparameters as $constname => $val) { + if ($val['enabled']==1) { + $setupnotempty++; + print '<tr class="oddeven"><td>'; + $tooltiphelp = (($langs->trans($constname . 'Tooltip') != $constname . 'Tooltip') ? $langs->trans($constname . 'Tooltip') : ''); + print '<span id="helplink'.$constname.'" class="spanforparamtooltip">'.$form->textwithpicto($langs->trans($constname), $tooltiphelp, 1, 'info', '', 0, 3, 'tootips'.$constname).'</span>'; + print '</td><td>'; + + if ($val['type'] == 'textarea') { + print '<textarea class="flat" name="'.$constname.'" id="'.$constname.'" cols="50" rows="5" wrap="soft">' . "\n"; + print $conf->global->{$constname}; + print "</textarea>\n"; + } elseif ($val['type']== 'html') { + require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; + $doleditor = new DolEditor($constname, $conf->global->{$constname}, '', 160, 'dolibarr_notes', '', false, false, $conf->fckeditor->enabled, ROWS_5, '90%'); + $doleditor->Create(); + } elseif ($val['type'] == 'yesno') { + print $form->selectyesno($constname, $conf->global->{$constname}, 1); + } elseif (preg_match('/emailtemplate:/', $val['type'])) { + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + + $tmp = explode(':', $val['type']); + $nboftemplates = $formmail->fetchAllEMailTemplate($tmp[1], $user, null, 1); // We set lang=null to get in priority record with no lang + //$arraydefaultmessage = $formmail->getEMailTemplate($db, $tmp[1], $user, null, 0, 1, ''); + $arrayofmessagename = array(); + if (is_array($formmail->lines_model)) { + foreach ($formmail->lines_model as $modelmail) { + //var_dump($modelmail); + $moreonlabel = ''; + if (!empty($arrayofmessagename[$modelmail->label])) { + $moreonlabel = ' <span class="opacitymedium">(' . $langs->trans("SeveralLangugeVariatFound") . ')</span>'; + } + // The 'label' is the key that is unique if we exclude the language + $arrayofmessagename[$modelmail->id] = $langs->trans(preg_replace('/\(|\)/', '', $modelmail->label)) . $moreonlabel; + } + } + print $form->selectarray($constname, $arrayofmessagename, $conf->global->{$constname}, 'None', 0, 0, '', 0, 0, 0, '', '', 1); + } elseif (preg_match('/category:/', $val['type'])) { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; + $formother = new FormOther($db); + + $tmp = explode(':', $val['type']); + print img_picto('', 'category', 'class="pictofixedwidth"'); + print $formother->select_categories($tmp[1], $conf->global->{$constname}, $constname, 0, $langs->trans('CustomersProspectsCategoriesShort')); + } else { + print '<input name="'.$constname.'" class="flat '.(empty($val['css']) ? 'minwidth200' : $val['css']).'" value="'.$conf->global->{$constname}.'">'; + } + print '</td></tr>'; + } } print '</table>'; @@ -227,13 +290,48 @@ if ($action == 'edit') { print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>'; - foreach ($arrayofparameters as $key => $val) { - $setupnotempty++; + foreach ($arrayofparameters as $constname => $val) { + if ($val['enabled']==1) { + $setupnotempty++; + print '<tr class="oddeven"><td>'; + $tooltiphelp = (($langs->trans($constname . 'Tooltip') != $constname . 'Tooltip') ? $langs->trans($constname . 'Tooltip') : ''); + print $form->textwithpicto($langs->trans($constname), $tooltiphelp); + print '</td><td>'; - print '<tr class="oddeven"><td>'; - $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); - print $form->textwithpicto($langs->trans($key), $tooltiphelp); - print '</td><td>'.$conf->global->$key.'</td></tr>'; + if ($val['type'] == 'textarea') { + print dol_nl2br($conf->global->{$constname}); + } elseif ($val['type']== 'html') { + print $conf->global->{$constname}; + } elseif ($val['type'] == 'yesno') { + print ajax_constantonoff($constname); + } elseif (preg_match('/emailtemplate:/', $val['type'])) { + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + + $tmp = explode(':', $val['type']); + + $template = $formmail->getEMailTemplate($db, $tmp[1], $user, $langs, $conf->global->{$constname}); + if ($template<0) { + setEventMessages(null, $formmail->errors, 'errors'); + } + print $langs->trans($template->label); + } elseif (preg_match('/category:/', $val['type'])) { + $c = new Categorie($db); + $result = $c->fetch($conf->global->{$constname}); + if ($result < 0) { + setEventMessages(null, $c->errors, 'errors'); + } + $ways = $c->print_all_ways(' &gt;&gt; ', 'none', 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text + $toprint = array(); + foreach ($ways as $way) { + $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #bbb"') . '>' . $way . '</li>'; + } + print '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>'; + } else { + print $conf->global->{$constname}; + } + print '</td></tr>'; + } } print '</table>'; diff --git a/htdocs/modulebuilder/template/class/actions_mymodule.class.php b/htdocs/modulebuilder/template/class/actions_mymodule.class.php index 13a2b8e895c..8559411a3d4 100644 --- a/htdocs/modulebuilder/template/class/actions_mymodule.class.php +++ b/htdocs/modulebuilder/template/class/actions_mymodule.class.php @@ -99,8 +99,7 @@ class ActionsMyModule $error = 0; // Error counter /* print_r($parameters); print_r($object); echo "action: " . $action; */ - if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' - { + if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) { // do something only for the context 'somecontext1' or 'somecontext2' // Do what you want here... // You can for example call global vars like $fieldstosearchall to overwrite them, or update database depending on $action and $_POST values. } @@ -132,10 +131,8 @@ class ActionsMyModule $error = 0; // Error counter /* print_r($parameters); print_r($object); echo "action: " . $action; */ - if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' - { - foreach ($parameters['toselect'] as $objectid) - { + if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) { // do something only for the context 'somecontext1' or 'somecontext2' + foreach ($parameters['toselect'] as $objectid) { // Do action on each object id } } @@ -168,8 +165,7 @@ class ActionsMyModule $disabled = 1; /* print_r($parameters); print_r($object); echo "action: " . $action; */ - if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' - { + if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) { // do something only for the context 'somecontext1' or 'somecontext2' $this->resprints = '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>'.$langs->trans("MyModuleMassAction").'</option>'; } @@ -204,8 +200,7 @@ class ActionsMyModule dol_syslog(get_class($this).'::executeHooks action='.$action); /* print_r($parameters); print_r($object); echo "action: " . $action; */ - if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' - { + if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) { // do something only for the context 'somecontext1' or 'somecontext2' } return $ret; diff --git a/htdocs/modulebuilder/template/class/api_mymodule.class.php b/htdocs/modulebuilder/template/class/api_mymodule.class.php index 2e04e34dcac..da616de0d82 100644 --- a/htdocs/modulebuilder/template/class/api_mymodule.class.php +++ b/htdocs/modulebuilder/template/class/api_mymodule.class.php @@ -119,29 +119,42 @@ class MyModuleApi extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; + if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." as t"; - if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= " WHERE 1 = 1"; // Example of use $mode //if ($mode == 1) $sql.= " AND s.client IN (1, 3)"; //if ($mode == 2) $sql.= " AND s.client IN (2, 3)"; - if ($tmpobject->ismultientitymanaged) $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')'; - if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($restrictonsocid && $socid) $sql .= " AND t.fk_soc = ".$socid; - if ($restrictonsocid && $search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ($tmpobject->ismultientitymanaged) { + $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')'; + } + if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($restrictonsocid && $socid) { + $sql .= " AND t.fk_soc = ".$socid; + } + if ($restrictonsocid && $search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter if ($restrictonsocid && $search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } - if ($sqlfilters) - { + if ($sqlfilters) { if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } @@ -161,11 +174,9 @@ class MyModuleApi extends DolibarrApi $result = $this->db->query($sql); $i = 0; - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $tmp_object = new MyObject($this->db); if ($tmp_object->fetch($obj->rowid)) { @@ -236,12 +247,13 @@ class MyModuleApi extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->myobject->$field = $value; } - if ($this->myobject->update(DolibarrApiAccess::$user, false) > 0) - { + if ($this->myobject->update(DolibarrApiAccess::$user, false) > 0) { return $this->get($id); } else { throw new RestException(500, $this->myobject->error); @@ -272,8 +284,7 @@ class MyModuleApi extends DolibarrApi throw new RestException(401, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login); } - if (!$this->myobject->delete(DolibarrApiAccess::$user)) - { + if (!$this->myobject->delete(DolibarrApiAccess::$user)) { throw new RestException(500, 'Error when deleting MyObject : '.$this->myobject->error); } @@ -338,8 +349,7 @@ class MyModuleApi extends DolibarrApi // If object has lines, remove $db property if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) { $nboflines = count($object->lines); - for ($i = 0; $i < $nboflines; $i++) - { + for ($i = 0; $i < $nboflines; $i++) { $this->_cleanObjectDatas($object->lines[$i]); unset($object->lines[$i]->lines); @@ -362,9 +372,12 @@ class MyModuleApi extends DolibarrApi { $myobject = array(); foreach ($this->myobject->fields as $field => $propfield) { - if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) continue; // Not a mandatory field - if (!isset($data[$field])) + if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) { + continue; // Not a mandatory field + } + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $myobject[$field] = $data[$field]; } return $myobject; diff --git a/htdocs/modulebuilder/template/class/myobject.class.php b/htdocs/modulebuilder/template/class/myobject.class.php index e7da913f39c..6a17e500a69 100644 --- a/htdocs/modulebuilder/template/class/myobject.class.php +++ b/htdocs/modulebuilder/template/class/myobject.class.php @@ -232,8 +232,12 @@ class MyObject extends CommonObject $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } // Example to show how to set values of fields definition dynamically /*if ($user->rights->mymodule->myobject->read) { @@ -242,23 +246,17 @@ class MyObject extends CommonObject }*/ // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } // Translate some data of arrayofkeyval - if (is_object($langs)) - { - foreach ($this->fields as $key => $val) - { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } @@ -298,7 +296,9 @@ class MyObject extends CommonObject // Load source object $result = $object->fetchCommon($fromid); - if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); + if ($result > 0 && !empty($object->table_element_line)) { + $object->fetchLines(); + } // get lines so they will be clone //foreach($this->lines as $line) @@ -310,21 +310,28 @@ class MyObject extends CommonObject unset($object->import_key); // Clear fields - if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; - if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; - if (property_exists($object, 'status')) { $object->status = self::STATUS_DRAFT; } - if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); } - if (property_exists($object, 'date_modification')) { $object->date_modification = null; } + if (property_exists($object, 'ref')) { + $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; + } + if (property_exists($object, 'label')) { + $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; + } + if (property_exists($object, 'status')) { + $object->status = self::STATUS_DRAFT; + } + if (property_exists($object, 'date_creation')) { + $object->date_creation = dol_now(); + } + if (property_exists($object, 'date_modification')) { + $object->date_modification = null; + } // ... // Clear extrafields that are unique - if (is_array($object->array_options) && count($object->array_options) > 0) - { + if (is_array($object->array_options) && count($object->array_options) > 0) { $extrafields->fetch_name_optionals_label($this->table_element); - foreach ($object->array_options as $key => $option) - { + foreach ($object->array_options as $key => $option) { $shortkey = preg_replace('/options_/', '', $key); - if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) - { + if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) { //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; unset($object->array_options[$key]); } @@ -340,22 +347,19 @@ class MyObject extends CommonObject $this->errors = $object->errors; } - if (!$error) - { + if (!$error) { // copy internal contacts - if ($this->copy_linked_contact($object, 'internal') < 0) - { + if ($this->copy_linked_contact($object, 'internal') < 0) { $error++; } } - if (!$error) - { + if (!$error) { // copy external contacts if same company - if (property_exists($this, 'socid') && $this->socid == $object->socid) - { - if ($this->copy_linked_contact($object, 'external') < 0) + if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) { + if ($this->copy_linked_contact($object, 'external') < 0) { $error++; + } } } @@ -381,7 +385,9 @@ class MyObject extends CommonObject public function fetch($id, $ref = null) { $result = $this->fetchCommon($id, $ref); - if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); + if ($result > 0 && !empty($this->table_element_line)) { + $this->fetchLines(); + } return $result; } @@ -419,10 +425,13 @@ class MyObject extends CommonObject $records = array(); $sql = 'SELECT '; - $sql .= $this->getFieldList(); + $sql .= $this->getFieldList('t'); $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; - else $sql .= ' WHERE 1 = 1'; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { + $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; + } else { + $sql .= ' WHERE 1 = 1'; + } // Manage filter $sqlwhere = array(); if (count($filter) > 0) { @@ -455,8 +464,7 @@ class MyObject extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < ($limit ? min($limit, $num) : $num)) - { + while ($i < ($limit ? min($limit, $num) : $num)) { $obj = $this->db->fetch_object($resql); $record = new self($this->db); @@ -512,8 +520,7 @@ class MyObject extends CommonObject */ public function deleteLine(User $user, $idline, $notrigger = false) { - if ($this->status < 0) - { + if ($this->status < 0) { $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; return -2; } @@ -538,8 +545,7 @@ class MyObject extends CommonObject $error = 0; // Protection - if ($this->status == self::STATUS_VALIDATED) - { + if ($this->status == self::STATUS_VALIDATED) { dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); return 0; } @@ -557,8 +563,7 @@ class MyObject extends CommonObject $this->db->begin(); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef(); } else { $num = $this->ref; @@ -570,57 +575,58 @@ class MyObject extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql .= " SET ref = '".$this->db->escape($num)."',"; $sql .= " status = ".self::STATUS_VALIDATED; - if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."'"; - if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".$user->id; + if (!empty($this->fields['date_validation'])) { + $sql .= ", date_validation = '".$this->db->idate($now)."'"; + } + if (!empty($this->fields['fk_user_valid'])) { + $sql .= ", fk_user_valid = ".$user->id; + } $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::validate()", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $this->error = $this->db->lasterror(); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('MYOBJECT_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'myobject/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'myobject/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->mymodule->dir_output.'/myobject/'.$oldref; $dirdest = $conf->mymodule->dir_output.'/myobject/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->mymodule->dir_output.'/myobject/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -633,14 +639,12 @@ class MyObject extends CommonObject } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $num; $this->status = self::STATUS_VALIDATED; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -660,8 +664,7 @@ class MyObject extends CommonObject public function setDraft($user, $notrigger = 0) { // Protection - if ($this->status <= self::STATUS_DRAFT) - { + if ($this->status <= self::STATUS_DRAFT) { return 0; } @@ -685,8 +688,7 @@ class MyObject extends CommonObject public function cancel($user, $notrigger = 0) { // Protection - if ($this->status != self::STATUS_VALIDATED) - { + if ($this->status != self::STATUS_VALIDATED) { return 0; } @@ -710,8 +712,7 @@ class MyObject extends CommonObject public function reopen($user, $notrigger = 0) { // Protection - if ($this->status != self::STATUS_CANCELED) - { + if ($this->status != self::STATUS_CANCELED) { return 0; } @@ -739,7 +740,9 @@ class MyObject extends CommonObject { global $conf, $langs, $hookmanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -752,34 +755,47 @@ class MyObject extends CommonObject $url = dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowMyObject"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } - $linkstart = '<a href="'.$url.'"'; + if ($option == 'nolink') { + $linkstart = '<span'; + } else { + $linkstart = '<a href="'.$url.'"'; + } $linkstart .= $linkclose.'>'; - $linkend = '</a>'; + if ($option == 'nolink') { + $linkend = '</span>'; + } else { + $linkend = '</a>'; + } $result .= $linkstart; if (empty($this->showphoto_on_popup)) { - 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) { + $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); + } } else { if ($withpicto) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -805,7 +821,9 @@ class MyObject extends CommonObject } } - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -814,8 +832,11 @@ class MyObject extends CommonObject $hookmanager->initHooks(array('myobjectdao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -842,8 +863,7 @@ class MyObject extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule@mymodule"); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); @@ -856,7 +876,9 @@ class MyObject extends CommonObject $statusType = 'status'.$status; //if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; - if ($status == self::STATUS_CANCELED) $statusType = 'status6'; + if ($status == self::STATUS_CANCELED) { + $statusType = 'status6'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -872,30 +894,25 @@ class MyObject 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; @@ -935,8 +952,7 @@ class MyObject extends CommonObject $objectline = new MyObjectLine($this->db); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_myobject = '.$this->id)); - if (is_numeric($result)) - { + if (is_numeric($result)) { $this->error = $this->error; $this->errors = $this->errors; return $result; @@ -960,8 +976,7 @@ class MyObject extends CommonObject $conf->global->MYMODULE_MYOBJECT_ADDON = 'mod_myobject_standard'; } - if (!empty($conf->global->MYMODULE_MYOBJECT_ADDON)) - { + if (!empty($conf->global->MYMODULE_MYOBJECT_ADDON)) { $mybool = false; $file = $conf->global->MYMODULE_MYOBJECT_ADDON.".php"; @@ -969,16 +984,14 @@ class MyObject extends CommonObject // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/mymodule/"); // Load file with numbering class (if found) $mybool |= @include_once $dir.$file; } - if ($mybool === false) - { + if ($mybool === false) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -987,8 +1000,7 @@ class MyObject extends CommonObject $obj = new $classname(); $numref = $obj->getNextValue($this); - if ($numref != '' && $numref != '-1') - { + if ($numref != '' && $numref != '-1') { return $numref; } else { $this->error = $obj->error; diff --git a/htdocs/modulebuilder/template/core/boxes/mymodulewidget1.php b/htdocs/modulebuilder/template/core/boxes/mymodulewidget1.php index e356792ed42..82632773c87 100644 --- a/htdocs/modulebuilder/template/core/boxes/mymodulewidget1.php +++ b/htdocs/modulebuilder/template/core/boxes/mymodulewidget1.php @@ -1,6 +1,6 @@ <?php /* Copyright (C) 2004-2017 Laurent Destailleur <eldy@users.sourceforge.net> - * Copyright (C) 2018-2020 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr> * Copyright (C) ---Put here your own copyright and developer email--- * * This program is free software: you can redistribute it and/or modify @@ -77,6 +77,12 @@ class mymodulewidget1 extends ModeleBoxes */ public $info_box_contents = array(); + /** + * @var string Widget type ('graph' means the widget is a graph widget) + */ + public $widgettype = 'graph'; + + /** * Constructor * @@ -200,12 +206,12 @@ class mymodulewidget1 extends ModeleBoxes * @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 void + * @return string */ public function showBox($head = null, $contents = null, $nooutput = 0) { // You may make your own code here… // … or use the parent's class function using the provided head and contents templates - parent::showBox($this->info_box_head, $this->info_box_contents); + return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); } } diff --git a/htdocs/modulebuilder/template/core/modules/mailings/mailinglist_mymodule_myobject.modules.php b/htdocs/modulebuilder/template/core/modules/mailings/mailinglist_mymodule_myobject.modules.php index cb6e15695c1..dc797b99a94 100644 --- a/htdocs/modulebuilder/template/core/modules/mailings/mailinglist_mymodule_myobject.modules.php +++ b/htdocs/modulebuilder/template/core/modules/mailings/mailinglist_mymodule_myobject.modules.php @@ -48,8 +48,7 @@ class mailing_mailinglist_mymodule_myobject extends MailingTargets global $conf; $this->db = $db; - if (is_array($conf->modules)) - { + if (is_array($conf->modules)) { $this->enabled = in_array('mymodule', $conf->modules) ? 1 : 0; } } @@ -73,8 +72,7 @@ class mailing_mailinglist_mymodule_myobject extends MailingTargets $s .= $langs->trans("Status").': '; $s .= '<select name="filter" class="flat">'; $s .= '<option value="none">&nbsp;</option>'; - foreach ($arraystatus as $status) - { + foreach ($arraystatus as $status) { $s .= '<option value="'.$status.'">'.$status.'</option>'; } $s .= '</select>'; @@ -112,24 +110,23 @@ class mailing_mailinglist_mymodule_myobject extends MailingTargets $sql = " select rowid as id, email, firstname, lastname, plan, partner"; $sql .= " from ".MAIN_DB_PREFIX."myobject"; $sql .= " where email IS NOT NULL AND email != ''"; - if (GETPOSTISSET('filter') && GETPOST('filter', 'alphanohtml') != 'none') $sql .= " AND status = '".$this->db->escape(GETPOST('filter', 'alphanohtml'))."'"; + if (GETPOSTISSET('filter') && GETPOST('filter', 'alphanohtml') != 'none') { + $sql .= " AND status = '".$this->db->escape(GETPOST('filter', 'alphanohtml'))."'"; + } $sql .= " ORDER BY email"; // Stocke destinataires dans target $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; dol_syslog("mailinglist_mymodule_myobject.modules.php: mailing ".$num." targets found"); $old = ''; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); - if ($old <> $obj->email) - { + if ($old <> $obj->email) { $target[$j] = array( 'email' => $obj->email, 'name' => $obj->lastname, @@ -197,7 +194,9 @@ class mailing_mailinglist_mymodule_myobject extends MailingTargets { $a = parent::getNbOfRecipients("select count(distinct(email)) as nb from ".MAIN_DB_PREFIX."myobject as p where email IS NOT NULL AND email != ''"); - if ($a < 0) return -1; + if ($a < 0) { + return -1; + } return $a; } } diff --git a/htdocs/modulebuilder/template/core/modules/mymodule/doc/doc_generic_myobject_odt.modules.php b/htdocs/modulebuilder/template/core/modules/mymodule/doc/doc_generic_myobject_odt.modules.php index d6cb191a405..3e389c1757f 100644 --- a/htdocs/modulebuilder/template/core/modules/mymodule/doc/doc_generic_myobject_odt.modules.php +++ b/htdocs/modulebuilder/template/core/modules/mymodule/doc/doc_generic_myobject_odt.modules.php @@ -98,7 +98,9 @@ class doc_generic_myobject_odt extends ModelePDFMyObject // Recupere emetteur $this->emetteur = $mysoc; - if (!$this->emetteur->country_code) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined + if (!$this->emetteur->country_code) { + $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined + } } @@ -129,8 +131,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject $texttitle = $langs->trans("ListOfDirectories"); $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->MYMODULE_MYOBJECT_ADDON_PDF_ODT_PATH))); $listoffiles = array(); - foreach ($listofdir as $key=>$tmpdir) - { + foreach ($listofdir as $key => $tmpdir) { $tmpdir = trim($tmpdir); $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); if (!$tmpdir) { @@ -140,7 +141,9 @@ class doc_generic_myobject_odt extends ModelePDFMyObject $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0); } else { $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)'); - if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); + if (count($tmpfiles)) { + $listoffiles = array_merge($listoffiles, $tmpfiles); + } } } $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT"); @@ -159,8 +162,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject // Scan directories $nbofiles = count($listoffiles); - if (!empty($conf->global->MYMODULE_MYOBJECT_ADDON_PDF_ODT_PATH)) - { + if (!empty($conf->global->MYMODULE_MYOBJECT_ADDON_PDF_ODT_PATH)) { $texte .= $langs->trans("NumberOfModelFilesFound").': <b>'; //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':''; $texte .= count($listoffiles); @@ -168,11 +170,9 @@ class doc_generic_myobject_odt extends ModelePDFMyObject $texte .= '</b>'; } - if ($nbofiles) - { + if ($nbofiles) { $texte .= '<div id="div_'.get_class($this).'" class="hidden">'; - foreach ($listoffiles as $file) - { + foreach ($listoffiles as $file) { $texte .= $file['name'].'<br>'; } $texte .= '</div>'; @@ -208,37 +208,34 @@ class doc_generic_myobject_odt extends ModelePDFMyObject // phpcs:enable global $user, $langs, $conf, $mysoc, $hookmanager; - if (empty($srctemplatepath)) - { + if (empty($srctemplatepath)) { dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); return -1; } // Add odtgeneration hook - if (!is_object($hookmanager)) - { + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('odtgeneration')); global $action; - if (!is_object($outputlangs)) $outputlangs = $langs; + if (!is_object($outputlangs)) { + $outputlangs = $langs; + } $sav_charset_output = $outputlangs->charset_output; $outputlangs->charset_output = 'UTF-8'; $outputlangs->loadLangs(array("main", "dict", "companies", "bills")); - if ($conf->commande->dir_output) - { + if ($conf->commande->dir_output) { // If $object is id instead of object - if (!is_object($object)) - { + if (!is_object($object)) { $id = $object; $object = new Commande($this->db); $result = $object->fetch($id); - if ($result < 0) - { + if ($result < 0) { dol_print_error($this->db, $object->error); return -1; } @@ -246,20 +243,19 @@ class doc_generic_myobject_odt extends ModelePDFMyObject $dir = $conf->commande->multidir_output[isset($object->entity) ? $object->entity : 1]; $objectref = dol_sanitizeFileName($object->ref); - if (!preg_match('/specimen/i', $objectref)) $dir .= "/".$objectref; + if (!preg_match('/specimen/i', $objectref)) { + $dir .= "/".$objectref; + } $file = $dir."/".$objectref.".odt"; - if (!file_exists($dir)) - { - if (dol_mkdir($dir) < 0) - { + if (!file_exists($dir)) { + if (dol_mkdir($dir) < 0) { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } - if (file_exists($dir)) - { + if (file_exists($dir)) { //print "srctemplatepath=".$srctemplatepath; // Src filename $newfile = basename($srctemplatepath); $newfiletmp = preg_replace('/\.od(t|s)/i', '', $newfile); @@ -269,10 +265,11 @@ class doc_generic_myobject_odt extends ModelePDFMyObject //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt'; // Get extension (ods or odt) $newfileformat = substr($newfile, strrpos($newfile, '.') + 1); - if (!empty($conf->global->MAIN_DOC_USE_TIMING)) - { + if (!empty($conf->global->MAIN_DOC_USE_TIMING)) { $format = $conf->global->MAIN_DOC_USE_TIMING; - if ($format == '1') $format = '%Y%m%d%H%M%S'; + if ($format == '1') { + $format = '%Y%m%d%H%M%S'; + } $filename = $newfiletmp.'-'.dol_print_date(dol_now(), $format).'.'.$newfileformat; } else { $filename = $newfiletmp.'.'.$newfileformat; @@ -289,16 +286,14 @@ class doc_generic_myobject_odt extends ModelePDFMyObject // If CUSTOMER contact defined on order, we use it $usecontact = false; $arrayidcontact = $object->getIdContact('external', 'CUSTOMER'); - if (count($arrayidcontact) > 0) - { + if (count($arrayidcontact) > 0) { $usecontact = true; $result = $object->fetch_contact($arrayidcontact[0]); } // Recipient name $contactobject = null; - if (!empty($usecontact)) - { + if (!empty($usecontact)) { if ($usecontact && ($object->contact->fk_soc != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)))) { $socobject = $object->contact; } else { @@ -326,8 +321,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject // Line of free text $newfreetext = ''; $paramfreetext = 'ORDER_FREE_TEXT'; - if (!empty($conf->global->$paramfreetext)) - { + if (!empty($conf->global->$paramfreetext)) { $newfreetext = make_substitutions($conf->global->$paramfreetext, $substitutionarray); } @@ -343,8 +337,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject 'DELIMITER_RIGHT' => '}' ) ); - } catch (Exception $e) - { + } catch (Exception $e) { $this->error = $e->getMessage(); dol_syslog($e->getMessage(), LOG_INFO); return -1; @@ -359,8 +352,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject // Make substitutions into odt of freetext try { $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8'); - } catch (OdfException $e) - { + } catch (OdfException $e) { dol_syslog($e->getMessage(), LOG_INFO); } @@ -374,7 +366,9 @@ class doc_generic_myobject_odt extends ModelePDFMyObject $array_other = $this->get_substitutionarray_other($outputlangs); // retrieve contact information for use in object as contact_xxx tags $array_thirdparty_contact = array(); - if ($usecontact && is_object($contactobject)) $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact'); + if ($usecontact && is_object($contactobject)) { + $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact'); + } $tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_thirdparty_contact); complete_substitutions_array($tmparray, $outputlangs, $object); @@ -383,19 +377,20 @@ class doc_generic_myobject_odt extends ModelePDFMyObject $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray); $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - foreach ($tmparray as $key=>$value) - { + foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { // Image - if (file_exists($value)) $odfHandler->setImage($key, $value); - else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); + if (file_exists($value)) { + $odfHandler->setImage($key, $value); + } else { + $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); + } } else { // Text $odfHandler->setVars($key, $value, true, 'UTF-8'); } - } catch (OdfException $e) - { + } catch (OdfException $e) { dol_syslog($e->getMessage(), LOG_INFO); } } @@ -404,32 +399,26 @@ class doc_generic_myobject_odt extends ModelePDFMyObject $foundtagforlines = 1; try { $listlines = $odfHandler->setSegment('lines'); - } catch (OdfException $e) - { + } catch (OdfException $e) { // We may arrive here if tags for lines not present into template $foundtagforlines = 0; dol_syslog($e->getMessage(), LOG_INFO); } - if ($foundtagforlines) - { + if ($foundtagforlines) { $linenumber = 0; - foreach ($object->lines as $line) - { + foreach ($object->lines as $line) { $linenumber++; $tmparray = $this->get_substitutionarray_lines($line, $outputlangs, $linenumber); complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines"); // Call the ODTSubstitutionLine hook $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray, 'line'=>$line); $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - foreach ($tmparray as $key => $val) - { + foreach ($tmparray as $key => $val) { try { $listlines->setVars($key, $val, true, 'UTF-8'); - } catch (OdfException $e) - { + } catch (OdfException $e) { dol_syslog($e->getMessage(), LOG_INFO); - } catch (SegmentException $e) - { + } catch (SegmentException $e) { dol_syslog($e->getMessage(), LOG_INFO); } } @@ -437,8 +426,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject } $odfHandler->mergeSegment($listlines); } - } catch (OdfException $e) - { + } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); return -1; @@ -446,12 +434,10 @@ class doc_generic_myobject_odt extends ModelePDFMyObject // Replace labels translated $tmparray = $outputlangs->get_translations_for_substitutions(); - foreach ($tmparray as $key=>$value) - { + foreach ($tmparray as $key => $value) { try { $odfHandler->setVars($key, $value, true, 'UTF-8'); - } catch (OdfException $e) - { + } catch (OdfException $e) { dol_syslog($e->getMessage(), LOG_INFO); } } @@ -483,8 +469,9 @@ class doc_generic_myobject_odt extends ModelePDFMyObject $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray); $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); + } $odfHandler = null; // Destroy object diff --git a/htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php b/htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php index 4546d7044bd..3d900bc06e7 100644 --- a/htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php +++ b/htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php @@ -163,7 +163,9 @@ class pdf_standard_myobject extends ModelePDFMyObject // Get source company $this->emetteur = $mysoc; - if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined + if (empty($this->emetteur->country_code)) { + $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined + } // Define position of columns $this->posxdesc = $this->marge_gauche + 1; // used for notes ans other stuff @@ -201,9 +203,13 @@ class pdf_standard_myobject extends ModelePDFMyObject dol_syslog("write_file outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); - if (!is_object($outputlangs)) $outputlangs = $langs; + if (!is_object($outputlangs)) { + $outputlangs = $langs; + } // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; + if (!empty($conf->global->MAIN_USE_FPDF)) { + $outputlangs->charset_output = 'ISO-8859-1'; + } // Load translation files required by the page $outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies")); @@ -226,67 +232,65 @@ class pdf_standard_myobject extends ModelePDFMyObject $realpatharray = array(); $this->atleastonephoto = false; /* - if (!empty($conf->global->MAIN_GENERATE_MYOBJECT_WITH_PICTURE)) - { - $objphoto = new Product($this->db); + if (!empty($conf->global->MAIN_GENERATE_MYOBJECT_WITH_PICTURE)) + { + $objphoto = new Product($this->db); - for ($i = 0; $i < $nblines; $i++) - { - if (empty($object->lines[$i]->fk_product)) continue; + for ($i = 0; $i < $nblines; $i++) + { + if (empty($object->lines[$i]->fk_product)) continue; - $objphoto->fetch($object->lines[$i]->fk_product); - //var_dump($objphoto->ref);exit; - if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) - { - $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; - $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; - } else { - $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; // default - $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; // alternative - } + $objphoto->fetch($object->lines[$i]->fk_product); + //var_dump($objphoto->ref);exit; + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) + { + $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; + $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; + } else { + $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; // default + $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; // alternative + } - $arephoto = false; - foreach ($pdir as $midir) - { - if (!$arephoto) - { - $dir = $conf->product->dir_output.'/'.$midir; + $arephoto = false; + foreach ($pdir as $midir) + { + if (!$arephoto) + { + $dir = $conf->product->dir_output.'/'.$midir; - foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) - { - if (empty($conf->global->CAT_HIGH_QUALITY_IMAGES)) // If CAT_HIGH_QUALITY_IMAGES not defined, we use thumb if defined and then original photo - { - if ($obj['photo_vignette']) - { - $filename = $obj['photo_vignette']; - } else { - $filename = $obj['photo']; - } - } else { - $filename = $obj['photo']; - } + foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) + { + if (empty($conf->global->CAT_HIGH_QUALITY_IMAGES)) // If CAT_HIGH_QUALITY_IMAGES not defined, we use thumb if defined and then original photo + { + if ($obj['photo_vignette']) + { + $filename = $obj['photo_vignette']; + } else { + $filename = $obj['photo']; + } + } else { + $filename = $obj['photo']; + } - $realpath = $dir.$filename; - $arephoto = true; - $this->atleastonephoto = true; - } - } - } + $realpath = $dir.$filename; + $arephoto = true; + $this->atleastonephoto = true; + } + } + } - if ($realpath && $arephoto) $realpatharray[$i] = $realpath; - } - } + if ($realpath && $arephoto) $realpatharray[$i] = $realpath; + } + } */ //if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; - if ($conf->mymodule->dir_output.'/myobject') - { + if ($conf->mymodule->dir_output.'/myobject') { $object->fetch_thirdparty(); // Definition of $dir and $file - if ($object->specimen) - { + if ($object->specimen) { $dir = $conf->mymodule->dir_output.'/myobject'; $file = $dir."/SPECIMEN.pdf"; } else { @@ -294,20 +298,16 @@ class pdf_standard_myobject extends ModelePDFMyObject $dir = $conf->mymodule->dir_output.'/myobject/'.$objectref; $file = $dir."/".$objectref.".pdf"; } - if (!file_exists($dir)) - { - if (dol_mkdir($dir) < 0) - { + if (!file_exists($dir)) { + if (dol_mkdir($dir) < 0) { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return 0; } } - if (file_exists($dir)) - { + if (file_exists($dir)) { // Add pdfgeneration hook - if (!is_object($hookmanager)) - { + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; $hookmanager = new HookManager($this->db); } @@ -328,16 +328,14 @@ class pdf_standard_myobject extends ModelePDFMyObject $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page $heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin) - if (class_exists('TCPDF')) - { + if (class_exists('TCPDF')) { $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); } $pdf->SetFont(pdf_getPDFFont($outputlangs)); // Set path to the background PDF File - if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) - { + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) { $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); $tplidx = $pdf->importPage(1); } @@ -351,7 +349,9 @@ class pdf_standard_myobject extends ModelePDFMyObject $pdf->SetCreator("Dolibarr ".DOL_VERSION); $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("PdfTitle")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); - if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) { + $pdf->SetCompression(false); + } // Set certificate $cert = empty($user->conf->CERTIFICATE_CRT) ? '' : $user->conf->CERTIFICATE_CRT; @@ -374,7 +374,9 @@ class pdf_standard_myobject extends ModelePDFMyObject // New page $pdf->AddPage(); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } $pagenb++; $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs, $outputlangsbis); @@ -386,7 +388,9 @@ class pdf_standard_myobject extends ModelePDFMyObject $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); $tab_height = 130 - $top_shift; $tab_height_newpage = 150; - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $tab_height_newpage -= $top_shift; + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { + $tab_height_newpage -= $top_shift; + } $nexY = $tab_top - 1; @@ -394,14 +398,12 @@ class pdf_standard_myobject extends ModelePDFMyObject $notetoshow = empty($object->note_public) ? '' : $object->note_public; // Extrafields in note $extranote = $this->getExtrafieldsInHtml($object, $outputlangs); - if (!empty($extranote)) - { + if (!empty($extranote)) { $notetoshow = dol_concatdesc($notetoshow, $extranote); } $pagenb = $pdf->getPage(); - if ($notetoshow) - { + if ($notetoshow) { $tab_top -= 2; $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite; @@ -420,16 +422,19 @@ class pdf_standard_myobject extends ModelePDFMyObject $pageposafternote = $pdf->getPage(); $posyafter = $pdf->GetY(); - if ($pageposafternote > $pageposbeforenote) - { + if ($pageposafternote > $pageposbeforenote) { $pdf->rollbackTransaction(true); // prepare pages to receive notes while ($pagenb < $pageposafternote) { $pdf->AddPage(); $pagenb++; - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { + $this->_pagehead($pdf, $object, 0, $outputlangs); + } // $this->_pagefoot($pdf,$object,$outputlangs,1); $pdf->setTopMargin($tab_top_newpage); // The only function to edit the bottom margin of current page to set it. @@ -445,8 +450,7 @@ class pdf_standard_myobject extends ModelePDFMyObject $posyafter = $pdf->GetY(); - if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) // There is no space left for total+free text - { + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) { // There is no space left for total+free text $pdf->AddPage('', '', true); $pagenb++; $pageposafternote++; @@ -483,8 +487,12 @@ class pdf_standard_myobject extends ModelePDFMyObject // apply note frame to last page $pdf->setPage($pageposafternote); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { + $this->_pagehead($pdf, $object, 0, $outputlangs); + } $height_note = $posyafter - $tab_top_newpage; $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); } else // No pagebreak @@ -495,15 +503,18 @@ class pdf_standard_myobject extends ModelePDFMyObject $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); - if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) - { + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) { // not enough space, need to add page $pdf->AddPage('', '', true); $pagenb++; $pageposafternote++; $pdf->setPage($pageposafternote); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { + $this->_pagehead($pdf, $object, 0, $outputlangs); + } $posyafter = $tab_top_newpage; } @@ -528,15 +539,16 @@ class pdf_standard_myobject extends ModelePDFMyObject // Loop on each lines $pageposbeforeprintlines = $pdf->getPage(); $pagenb = $pageposbeforeprintlines; - for ($i = 0; $i < $nblines; $i++) - { + for ($i = 0; $i < $nblines; $i++) { $curY = $nexY; $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); // Define size of image if we need it $imglinesize = array(); - if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); + if (!empty($realpatharray[$i])) { + $imglinesize = pdf_getSizeForImage($realpatharray[$i]); + } $pdf->setTopMargin($tab_top_newpage); $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. @@ -545,25 +557,26 @@ class pdf_standard_myobject extends ModelePDFMyObject $showpricebeforepagebreak = 1; $posYAfterImage = 0; - if ($this->getColumnStatus('photo')) - { + if ($this->getColumnStatus('photo')) { // We start with Photo of product line - if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page - { + if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // If photo too high, we moved completely on new page $pdf->AddPage('', '', true); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } $pdf->setPage($pageposbefore + 1); $curY = $tab_top_newpage; // Allows data in the first page if description is long enough to break in multiples pages - if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) { $showpricebeforepagebreak = 1; - else $showpricebeforepagebreak = 0; + } else { + $showpricebeforepagebreak = 0; + } } - if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) - { + if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) { $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi // $pdf->Image does not increase value return by getY, so we save it manually $posYAfterImage = $curY + $imglinesize['height']; @@ -571,15 +584,13 @@ class pdf_standard_myobject extends ModelePDFMyObject } // Description of product line - if ($this->getColumnStatus('desc')) - { + if ($this->getColumnStatus('desc')) { $pdf->startTransaction(); $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); $pageposafter = $pdf->getPage(); - if ($pageposafter > $pageposbefore) // There is a pagebreak - { + if ($pageposafter > $pageposbefore) { // There is a pagebreak $pdf->rollbackTransaction(true); $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. @@ -588,20 +599,22 @@ class pdf_standard_myobject extends ModelePDFMyObject $pageposafter = $pdf->getPage(); $posyafter = $pdf->GetY(); //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; - if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text - { - if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page - { + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // There is no space left for total+free text + if ($i == ($nblines - 1)) { // No more lines, and no space left to show total, so we create a new page $pdf->AddPage('', '', true); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } $pdf->setPage($pageposafter + 1); } } else { // We found a page break // Allows data in the first page if description is long enough to break in multiples pages - if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) { $showpricebeforepagebreak = 1; - else $showpricebeforepagebreak = 0; + } else { + $showpricebeforepagebreak = 0; + } } } else // No pagebreak { @@ -624,8 +637,7 @@ class pdf_standard_myobject extends ModelePDFMyObject // Quantity // Enough for 6 chars - if ($this->getColumnStatus('qty')) - { + if ($this->getColumnStatus('qty')) { $qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails); $this->printStdColumnContent($pdf, $curY, 'qty', $qty); $nexY = max($pdf->GetY(), $nexY); @@ -634,8 +646,7 @@ class pdf_standard_myobject extends ModelePDFMyObject // Extrafields if (!empty($object->lines[$i]->array_options)) { foreach ($object->lines[$i]->array_options as $extrafieldColKey => $extrafieldValue) { - if ($this->getColumnStatus($extrafieldColKey)) - { + if ($this->getColumnStatus($extrafieldColKey)) { $extrafieldValue = $this->getExtrafieldContent($object->lines[$i], $extrafieldColKey); $this->printStdColumnContent($pdf, $curY, $extrafieldColKey, $extrafieldValue); $nexY = max($pdf->GetY(), $nexY); @@ -659,13 +670,18 @@ class pdf_standard_myobject extends ModelePDFMyObject $sign = 1; // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva $prev_progress = $object->lines[$i]->get_prev_progress($object->id); - if ($prev_progress > 0 && !empty($object->lines[$i]->situation_percent)) // Compute progress from previous situation - { - if (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; - else $tvaligne = $sign * $object->lines[$i]->total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; + if ($prev_progress > 0 && !empty($object->lines[$i]->situation_percent)) { // Compute progress from previous situation + if (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) { + $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; + } else { + $tvaligne = $sign * $object->lines[$i]->total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; + } } else { - if (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva; - else $tvaligne = $sign * $object->lines[$i]->total_tva; + if (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) { + $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva; + } else { + $tvaligne = $sign * $object->lines[$i]->total_tva; + } } $localtax1ligne = $object->lines[$i]->total_localtax1; @@ -675,16 +691,21 @@ class pdf_standard_myobject extends ModelePDFMyObject $localtax1_type = $object->lines[$i]->localtax1_type; $localtax2_type = $object->lines[$i]->localtax2_type; - if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; - if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; - if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; + if ($object->remise_percent) { + $tvaligne -= ($tvaligne * $object->remise_percent) / 100; + } + if ($object->remise_percent) { + $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; + } + if ($object->remise_percent) { + $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; + } $vatrate = (string) $object->lines[$i]->tva_tx; // Retrieve type from database for backward compatibility with old records if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined - && (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax - { + && (!empty($localtax1_rate) || !empty($localtax2_rate))) { // and there is local tax $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); $localtax1_type = isset($localtaxtmp_array[0]) ? $localtaxtmp_array[0] : ''; $localtax2_type = isset($localtaxtmp_array[2]) ? $localtaxtmp_array[2] : ''; @@ -698,8 +719,12 @@ class pdf_standard_myobject extends ModelePDFMyObject $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; } - if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; - if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; + if (($object->lines[$i]->info_bits & 0x01) == 0x01) { + $vatrate .= '*'; + } + if (!isset($this->tva[$vatrate])) { + $this->tva[$vatrate] = 0; + } $this->tva[$vatrate] += $tvaligne; $nexY = max($nexY, $posYAfterImage); @@ -725,7 +750,9 @@ class pdf_standard_myobject extends ModelePDFMyObject $pagenb++; $pdf->setPage($pagenb); $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { + $this->_pagehead($pdf, $object, 0, $outputlangs); + } } if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { @@ -737,15 +764,18 @@ class pdf_standard_myobject extends ModelePDFMyObject $this->_pagefoot($pdf, $object, $outputlangs, 1); // New page $pdf->AddPage(); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } $pagenb++; - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { + $this->_pagehead($pdf, $object, 0, $outputlangs); + } } } // Show square - if ($pagenb == $pageposbeforeprintlines) - { + if ($pagenb == $pageposbeforeprintlines) { $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code, $outputlangsbis); $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } else { @@ -761,15 +791,17 @@ class pdf_standard_myobject extends ModelePDFMyObject // Display payment area /* - if (($deja_regle || $amount_credit_notes_included || $amount_deposits_included) && empty($conf->global->INVOICE_NO_PAYMENT_DETAILS)) - { - $posy = $this->drawPaymentsTable($pdf, $object, $posy, $outputlangs); - } - */ + if (($deja_regle || $amount_credit_notes_included || $amount_deposits_included) && empty($conf->global->INVOICE_NO_PAYMENT_DETAILS)) + { + $posy = $this->drawPaymentsTable($pdf, $object, $posy, $outputlangs); + } + */ // Pagefoot $this->_pagefoot($pdf, $object, $outputlangs); - if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages(); + if (method_exists($pdf, 'AliasNbPages')) { + $pdf->AliasNbPages(); + } $pdf->Close(); @@ -780,14 +812,14 @@ class pdf_standard_myobject extends ModelePDFMyObject $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) - { + if ($reshook < 0) { $this->error = $hookmanager->error; $this->errors = $hookmanager->errors; } - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); + } $this->result = array('fullpath'=>$file); @@ -837,7 +869,9 @@ class pdf_standard_myobject extends ModelePDFMyObject // Force to disable hidetop and hidebottom $hidebottom = 0; - if ($hidetop) $hidetop = -1; + if ($hidetop) { + $hidetop = -1; + } $currency = !empty($currency) ? $currency : $conf->currency; $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -846,8 +880,7 @@ class pdf_standard_myobject extends ModelePDFMyObject $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - if (empty($hidetop)) - { + if (empty($hidetop)) { $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && is_object($outputlangsbis)) { $titre .= ' - '.$outputlangsbis->transnoentities("AmountInCurrency", $outputlangsbis->transnoentitiesnoconv("Currency".$currency)); @@ -899,8 +932,7 @@ class pdf_standard_myobject extends ModelePDFMyObject pdf_pagehead($pdf, $outputlangs, $this->page_hauteur); // Show Draft Watermark - if ($object->statut == $object::STATUS_DRAFT && (!empty($conf->global->FACTURE_DRAFT_WATERMARK))) - { + if ($object->statut == $object::STATUS_DRAFT && (!empty($conf->global->FACTURE_DRAFT_WATERMARK))) { pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->FACTURE_DRAFT_WATERMARK); } @@ -915,20 +947,18 @@ class pdf_standard_myobject extends ModelePDFMyObject $pdf->SetXY($this->marge_gauche, $posy); // Logo - if (empty($conf->global->PDF_DISABLE_MYCOMPANY_LOGO)) - { - if ($this->emetteur->logo) - { + if (empty($conf->global->PDF_DISABLE_MYCOMPANY_LOGO)) { + if ($this->emetteur->logo) { $logodir = $conf->mycompany->dir_output; - if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; - if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) - { + if (!empty($conf->mycompany->multidir_output[$object->entity])) { + $logodir = $conf->mycompany->multidir_output[$object->entity]; + } + if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) { $logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small; } else { $logo = $logodir.'/logos/'.$this->emetteur->logo; } - if (is_readable($logo)) - { + if (is_readable($logo)) { $height = pdf_getHeightForLogo($logo); $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { @@ -959,8 +989,7 @@ class pdf_standard_myobject extends ModelePDFMyObject $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $textref = $outputlangs->transnoentities("Ref")." : ".$outputlangs->convToOutputCharset($object->ref); - if ($object->statut == $object::STATUS_DRAFT) - { + if ($object->statut == $object::STATUS_DRAFT) { $pdf->SetTextColor(128, 0, 0); $textref .= ' - '.$outputlangs->transnoentities("NotValidated"); } @@ -969,19 +998,16 @@ class pdf_standard_myobject extends ModelePDFMyObject $posy += 1; $pdf->SetFont('', '', $default_font_size - 2); - if ($object->ref_client) - { + if ($object->ref_client) { $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("RefCustomer")." : ".$outputlangs->convToOutputCharset($object->ref_client), '', 'R'); } - if (!empty($conf->global->PDF_SHOW_PROJECT_TITLE)) - { + if (!empty($conf->global->PDF_SHOW_PROJECT_TITLE)) { $object->fetch_projet(); - if (!empty($object->project->ref)) - { + if (!empty($object->project->ref)) { $posy += 3; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); @@ -989,11 +1015,9 @@ class pdf_standard_myobject extends ModelePDFMyObject } } - if (!empty($conf->global->PDF_SHOW_PROJECT)) - { + if (!empty($conf->global->PDF_SHOW_PROJECT)) { $object->fetch_projet(); - if (!empty($object->project->ref)) - { + if (!empty($object->project->ref)) { $posy += 3; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); @@ -1011,8 +1035,7 @@ class pdf_standard_myobject extends ModelePDFMyObject } $pdf->MultiCell($w, 3, $title." : ".dol_print_date($object->date, "day", false, $outputlangs), '', 'R'); - if ($object->thirdparty->code_client) - { + if ($object->thirdparty->code_client) { $posy += 3; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); @@ -1020,11 +1043,9 @@ class pdf_standard_myobject extends ModelePDFMyObject } // Get contact - if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP)) - { + if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP)) { $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); - if (count($arrayidcontact) > 0) - { + if (count($arrayidcontact) > 0) { $usertmp = new User($this->db); $usertmp->fetch($arrayidcontact[0]); $posy += 4; @@ -1040,13 +1061,11 @@ class pdf_standard_myobject extends ModelePDFMyObject // Show list of linked objects $current_y = $pdf->getY(); $posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, $w, 3, 'R', $default_font_size); - if ($current_y < $pdf->getY()) - { + if ($current_y < $pdf->getY()) { $top_shift = $pdf->getY() - $current_y; } - if ($showaddress) - { + if ($showaddress) { // Sender properties $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); @@ -1054,7 +1073,9 @@ class pdf_standard_myobject extends ModelePDFMyObject $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; $posy += $top_shift; $posx = $this->marge_gauche; - if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) { + $posx = $this->page_largeur - $this->marge_droite - 80; + } $hautcadre = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40; $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82; @@ -1084,8 +1105,7 @@ class pdf_standard_myobject extends ModelePDFMyObject // If BILLING contact defined on invoice, we use it $usecontact = false; $arrayidcontact = $object->getIdContact('external', 'BILLING'); - if (count($arrayidcontact) > 0) - { + if (count($arrayidcontact) > 0) { $usecontact = true; $result = $object->fetch_contact($arrayidcontact[0]); } @@ -1105,11 +1125,15 @@ class pdf_standard_myobject extends ModelePDFMyObject // Show recipient $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100; - if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format + if ($this->page_largeur < 210) { + $widthrecbox = 84; // To work with US executive format + } $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; $posy += $top_shift; $posx = $this->page_largeur - $this->marge_droite - $widthrecbox; - if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) { + $posx = $this->marge_gauche; + } // Show recipient frame $pdf->SetTextColor(0, 0, 0); @@ -1179,22 +1203,22 @@ class pdf_standard_myobject extends ModelePDFMyObject ); /* - * For exemple - $this->cols['theColKey'] = array( - 'rank' => $rank, // int : use for ordering columns - 'width' => 20, // the column width in mm - 'title' => array( - 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label - 'label' => ' ', // the final label : used fore final generated text - 'align' => 'L', // text alignement : R,C,L - 'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - 'content' => array( - 'align' => 'L', // text alignement : R,C,L - 'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - ); - */ + * For exemple + $this->cols['theColKey'] = array( + 'rank' => $rank, // int : use for ordering columns + 'width' => 20, // the column width in mm + 'title' => array( + 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label + 'label' => ' ', // the final label : used fore final generated text + 'align' => 'L', // text alignement : R,C,L + 'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + 'content' => array( + 'align' => 'L', // text alignement : R,C,L + 'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + ); + */ $rank = 0; // do not use negative rank $this->cols['desc'] = array( @@ -1230,8 +1254,7 @@ class pdf_standard_myobject extends ModelePDFMyObject 'border-left' => false, // remove left line separator ); - if (!empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE) && !empty($this->atleastonephoto)) - { + if (!empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE) && !empty($this->atleastonephoto)) { $this->cols['photo']['status'] = true; } @@ -1247,8 +1270,7 @@ class pdf_standard_myobject extends ModelePDFMyObject 'border-left' => true, // add left line separator ); - if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) - { + if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) { $this->cols['vat']['status'] = true; } @@ -1285,8 +1307,7 @@ class pdf_standard_myobject extends ModelePDFMyObject 'border-left' => true, // add left line separator ); - if ($this->situationinvoice) - { + if ($this->situationinvoice) { $this->cols['progress']['status'] = true; } @@ -1344,11 +1365,9 @@ class pdf_standard_myobject extends ModelePDFMyObject ); $reshook = $hookmanager->executeHooks('defineColumnField', $parameters, $this); // Note that $object may have been modified by hook - if ($reshook < 0) - { + if ($reshook < 0) { setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - } elseif (empty($reshook)) - { + } elseif (empty($reshook)) { $this->cols = array_replace($this->cols, $hookmanager->resArray); // array_replace is used to preserve keys } else { $this->cols = $hookmanager->resArray; diff --git a/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_advanced.php b/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_advanced.php index ae5f5d1e876..9c685e65d9a 100644 --- a/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_advanced.php +++ b/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_advanced.php @@ -113,8 +113,7 @@ class mod_myobject_advanced extends ModeleNumRefMyObject /*$mysoc->code_client = $old_code_client; $mysoc->typent_code = $old_code_type;*/ - if (!$numExample) - { + if (!$numExample) { $numExample = $langs->trans('NotConfigured'); } return $numExample; @@ -135,8 +134,7 @@ class mod_myobject_advanced extends ModeleNumRefMyObject // We get cursor rule $mask = $conf->global->MYMODULE_MYOBJECT_ADVANCED_MASK; - if (!$mask) - { + if (!$mask) { $this->error = 'NotConfigured'; return 0; } diff --git a/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_standard.php b/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_standard.php index 6f1a5da7dd3..75068cf8d57 100644 --- a/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_standard.php +++ b/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_standard.php @@ -96,13 +96,13 @@ class mod_myobject_standard extends ModeleNumRefMyObject } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $row = $db->fetch_row($resql); - if ($row) { $coyymm = substr($row[0], 0, 6); $max = $row[0]; } + if ($row) { + $coyymm = substr($row[0], 0, 6); $max = $row[0]; + } } - if ($coyymm && !preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) - { + if ($coyymm && !preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) { $langs->load("errors"); $this->error = $langs->trans('ErrorNumRefModel', $max); return false; @@ -133,11 +133,13 @@ class mod_myobject_standard extends ModeleNumRefMyObject } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $max = intval($obj->max); - else $max = 0; + if ($obj) { + $max = intval($obj->max); + } else { + $max = 0; + } } else { dol_syslog("mod_myobject_standard::getNextValue", LOG_DEBUG); return -1; @@ -147,8 +149,11 @@ class mod_myobject_standard extends ModeleNumRefMyObject $date = $object->date_creation; $yymm = strftime("%y%m", $date); - if ($max >= (pow(10, 4) - 1)) $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is - else $num = sprintf("%04s", $max + 1); + if ($max >= (pow(10, 4) - 1)) { + $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is + } else { + $num = sprintf("%04s", $max + 1); + } dol_syslog("mod_myobject_standard::getNextValue return ".$this->prefix.$yymm."-".$num); return $this->prefix.$yymm."-".$num; diff --git a/htdocs/modulebuilder/template/core/modules/mymodule/modules_myobject.php b/htdocs/modulebuilder/template/core/modules/mymodule/modules_myobject.php index 78711e33a4d..8f0d86e3823 100644 --- a/htdocs/modulebuilder/template/core/modules/mymodule/modules_myobject.php +++ b/htdocs/modulebuilder/template/core/modules/mymodule/modules_myobject.php @@ -141,10 +141,18 @@ abstract class ModeleNumRefMyObject global $langs; $langs->load("admin"); - if ($this->version == 'development') return $langs->trans("VersionDevelopment"); - if ($this->version == 'experimental') return $langs->trans("VersionExperimental"); - if ($this->version == 'dolibarr') return DOL_VERSION; - if ($this->version) return $this->version; + if ($this->version == 'development') { + return $langs->trans("VersionDevelopment"); + } + if ($this->version == 'experimental') { + return $langs->trans("VersionExperimental"); + } + if ($this->version == 'dolibarr') { + return DOL_VERSION; + } + if ($this->version) { + return $this->version; + } return $langs->trans("NotAvailable"); } } diff --git a/htdocs/modulebuilder/template/core/tpl/linkedobjectblock_myobject.tpl.php b/htdocs/modulebuilder/template/core/tpl/linkedobjectblock_myobject.tpl.php index 06e3498fca0..67aac8c0e98 100644 --- a/htdocs/modulebuilder/template/core/tpl/linkedobjectblock_myobject.tpl.php +++ b/htdocs/modulebuilder/template/core/tpl/linkedobjectblock_myobject.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -36,12 +35,13 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; $langs->load("mymodule"); $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> <tr class="<?php echo $trclass; ?>"> <td><?php echo $langs->trans("MyObject"); ?></td> diff --git a/htdocs/modulebuilder/template/core/triggers/interface_99_modMyModule_MyModuleTriggers.class.php b/htdocs/modulebuilder/template/core/triggers/interface_99_modMyModule_MyModuleTriggers.class.php index 8c0f39927bd..28868add880 100644 --- a/htdocs/modulebuilder/template/core/triggers/interface_99_modMyModule_MyModuleTriggers.class.php +++ b/htdocs/modulebuilder/template/core/triggers/interface_99_modMyModule_MyModuleTriggers.class.php @@ -92,7 +92,9 @@ class InterfaceMyModuleTriggers extends DolibarrTriggers */ public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) { - if (empty($conf->mymodule->enabled)) return 0; // If module is not enabled, we do nothing + if (empty($conf->mymodule) || empty($conf->mymodule->enabled)) { + return 0; // If module is not enabled, we do nothing + } // Put here code you want to execute when a Dolibarr business events occurs. // Data and type of action are stored into $object and $action diff --git a/htdocs/modulebuilder/template/css/mymodule.css.php b/htdocs/modulebuilder/template/css/mymodule.css.php index ecffe5dcf97..985cbe6aa18 100644 --- a/htdocs/modulebuilder/template/css/mymodule.css.php +++ b/htdocs/modulebuilder/template/css/mymodule.css.php @@ -23,14 +23,26 @@ //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled because need to load personalized language //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled. Language code is found on url. -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Not disabled because need to do translations -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); -if (!defined('NOLOGIN')) define('NOLOGIN', 1); // File must be accessed by logon page so without login +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', 1); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', 1); // File must be accessed by logon page so without login +} //if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU',1); // We need top menu content -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', 1); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} session_cache_limiter('public'); // false or '' = keep cache instruction added by server @@ -40,16 +52,30 @@ session_cache_limiter('public'); // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/../main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/../main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/../main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/../main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; diff --git a/htdocs/modulebuilder/template/js/mymodule.js.php b/htdocs/modulebuilder/template/js/mymodule.js.php index fea88d695ec..fe04cdc2ad9 100644 --- a/htdocs/modulebuilder/template/js/mymodule.js.php +++ b/htdocs/modulebuilder/template/js/mymodule.js.php @@ -17,16 +17,36 @@ * Library javascript to enable Browser notifications */ -if (!defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); -if (!defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); -if (!defined('NOLOGIN')) define('NOLOGIN', 1); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', 1); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIREUSER')) { + define('NOREQUIREUSER', '1'); +} +if (!defined('NOREQUIREDB')) { + define('NOREQUIREDB', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOREQUIRETRAN')) { + define('NOREQUIRETRAN', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', 1); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', 1); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', 1); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', 1); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} /** @@ -38,16 +58,30 @@ if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/../main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/../main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/../main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/../main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} // Define js type header('Content-Type: application/javascript'); diff --git a/htdocs/modulebuilder/template/lib/mymodule_myobject.lib.php b/htdocs/modulebuilder/template/lib/mymodule_myobject.lib.php index ebd5b837e3d..e3117d88303 100644 --- a/htdocs/modulebuilder/template/lib/mymodule_myobject.lib.php +++ b/htdocs/modulebuilder/template/lib/mymodule_myobject.lib.php @@ -41,14 +41,19 @@ function myobjectPrepareHead($object) $head[$h][2] = 'card'; $h++; - if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) - { + if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = dol_buildpath('/mymodule/myobject_note.php', 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbNote.'</span>' : ''); + if ($nbNote > 0) { + $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbNote.'</span>' : ''); + } $head[$h][2] = 'note'; $h++; } @@ -60,7 +65,9 @@ function myobjectPrepareHead($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = dol_buildpath("/mymodule/myobject_document.php", 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; + } $head[$h][2] = 'document'; $h++; diff --git a/htdocs/modulebuilder/template/mymoduleindex.php b/htdocs/modulebuilder/template/mymoduleindex.php index ee2fe6b28f0..2d262aeeb36 100644 --- a/htdocs/modulebuilder/template/mymoduleindex.php +++ b/htdocs/modulebuilder/template/mymoduleindex.php @@ -27,17 +27,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; diff --git a/htdocs/modulebuilder/template/myobject_agenda.php b/htdocs/modulebuilder/template/myobject_agenda.php index fbd156f2a97..0bb3244ebdd 100644 --- a/htdocs/modulebuilder/template/myobject_agenda.php +++ b/htdocs/modulebuilder/template/myobject_agenda.php @@ -46,17 +46,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; diff --git a/htdocs/modulebuilder/template/myobject_card.php b/htdocs/modulebuilder/template/myobject_card.php index dc4426f7df9..e99acc0b913 100644 --- a/htdocs/modulebuilder/template/myobject_card.php +++ b/htdocs/modulebuilder/template/myobject_card.php @@ -46,17 +46,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; @@ -117,9 +133,9 @@ $upload_dir = $conf->mymodule->multidir_output[isset($object->entity) ? $object- //if ($user->socid > 0) accessforbidden(); //if ($user->socid > 0) $socid = $user->socid; //$isdraft = (($object->statut == $object::STATUS_DRAFT) ? 1 : 0); -//$result = restrictedArea($user, 'mymodule', $object->id, '', '', 'fk_soc', 'rowid', $isdraft); +//$result = restrictedArea($user, $object->element, $object->id, '', '', 'fk_soc', 'rowid', $isdraft); -//if (!$permissiontoread) accessforbidden(); +//if (empty($permissiontoread)) accessforbidden(); /* @@ -464,7 +480,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<div class="tabsAction">'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } if (empty($reshook)) { // Send diff --git a/htdocs/modulebuilder/template/myobject_contact.php b/htdocs/modulebuilder/template/myobject_contact.php index 35e5be2716a..6d6345d9b99 100644 --- a/htdocs/modulebuilder/template/myobject_contact.php +++ b/htdocs/modulebuilder/template/myobject_contact.php @@ -25,17 +25,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; diff --git a/htdocs/modulebuilder/template/myobject_document.php b/htdocs/modulebuilder/template/myobject_document.php index 1cd3de2ebd9..c0765394135 100644 --- a/htdocs/modulebuilder/template/myobject_document.php +++ b/htdocs/modulebuilder/template/myobject_document.php @@ -46,17 +46,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -121,7 +137,7 @@ $permissiontoadd = $user->rights->mymodule->myobject->write; // Used by the incl * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* diff --git a/htdocs/modulebuilder/template/myobject_list.php b/htdocs/modulebuilder/template/myobject_list.php index e22de010459..aa616709a7d 100644 --- a/htdocs/modulebuilder/template/myobject_list.php +++ b/htdocs/modulebuilder/template/myobject_list.php @@ -46,17 +46,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; @@ -132,7 +148,9 @@ foreach ($object->fields as $key => $val) { // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); foreach ($object->fields as $key => $val) { - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of array of fields for columns @@ -161,7 +179,9 @@ $permissiontoadd = $user->rights->mymodule->myobject->write; $permissiontodelete = $user->rights->mymodule->myobject->delete; // Security check -if (empty($conf->mymodule->enabled)) accessforbidden('Module not enabled'); +if (empty($conf->mymodule->enabled)) { + accessforbidden('Module not enabled'); +} $socid = 0; if ($user->socid > 0) { // Protection if external user //$socid = $user->socid; @@ -231,14 +251,14 @@ $now = dol_now(); //$help_url="EN:Module_MyObject|FR:Module_MyObject_FR|ES:Módulo_MyObject"; $help_url = ''; $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("MyObjects")); +$morejs = array(); +$morecss = array(); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) { - $sql .= 't.'.$key.', '; -} +$sql .= $object->getFieldList('t'); // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { @@ -258,14 +278,21 @@ if (is_array($extrafields->attributes[$object->table_element]['label']) && count $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -else $sql .= " WHERE 1 = 1"; +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} foreach ($search as $key => $val) { - if (in_array($key, $object->fields)) { - if ($key == 'status' && $search[$key] == -1) continue; + if (array_key_exists($key, $object->fields)) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); - if (strpos($object->fields[$key]['type'], 'integer:') === 0) { - if ($search[$key] == '-1') $search[$key] = ''; + if ((strpos($object->fields[$key]['type'], 'integer:') === 0) || (strpos($object->fields[$key]['type'], 'sellist:') === 0)) { + if ($search[$key] == '-1' || $search[$key] === '0') { + $search[$key] = ''; + } $mode_search = 2; } if ($search[$key] != '') { @@ -328,7 +355,9 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); if (!$resql) { @@ -351,7 +380,7 @@ if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $ // Output page // -------------------------------------------------------------------- -llxHeader('', $title, $help_url); +llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', 'classforhorizontalscrolloftabs'); // Example : Adding jquery code print '<script type="text/javascript" language="javascript"> @@ -485,7 +514,7 @@ foreach ($object->fields as $key => $val) { print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - } elseif (strpos($val['type'], 'integer:') === 0) { + } elseif ((strpos($val['type'], 'integer:') === 0) || (strpos($val['type'], 'sellist:')=== 0)) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth125', 1); } elseif (!preg_match('/^(date|timestamp|datetime)/', $val['type'])) { print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; @@ -548,7 +577,9 @@ print '</tr>'."\n"; $needToFetchEachLine = 0; if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -569,7 +600,7 @@ while ($i < ($limit ? min($num, $limit) : $num)) { // Show here line of result print '<tr class="oddeven">'; 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') { @@ -616,11 +647,15 @@ while ($i < ($limit ? min($num, $limit) : $num)) { print '<td class="nowrap center">'; 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($object->id, $arrayofselected)) $selected = 1; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'."\n"; diff --git a/htdocs/modulebuilder/template/myobject_note.php b/htdocs/modulebuilder/template/myobject_note.php index abe8daf7622..0868cd3918d 100644 --- a/htdocs/modulebuilder/template/myobject_note.php +++ b/htdocs/modulebuilder/template/myobject_note.php @@ -46,17 +46,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} dol_include_once('/mymodule/class/myobject.class.php'); dol_include_once('/mymodule/lib/mymodule_myobject.lib.php'); diff --git a/htdocs/modulebuilder/template/scripts/mymodule.php b/htdocs/modulebuilder/template/scripts/mymodule.php index 0b8d7abfdfe..f0a7ca715a4 100644 --- a/htdocs/modulebuilder/template/scripts/mymodule.php +++ b/htdocs/modulebuilder/template/scripts/mymodule.php @@ -23,6 +23,29 @@ * \brief This file is an example for a command line script for module MyModule */ +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification +if (!defined('NOSESSION')) define('NOSESSION', '1'); // On CLI mode, no need to use web sessions + + $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); $path = __DIR__.'/'; @@ -46,13 +69,25 @@ define('EVEN_IF_ONLY_LOGIN_ALLOWED', 1); // Set this define to 0 if you want to $res = 0; // Try master.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/master.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/master.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/master.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/master.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/master.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/master.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/master.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/master.inc.php"; +} // Try master.inc.php using relative path -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 && 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) { print "Include of master fails"; exit(-1); @@ -65,7 +100,9 @@ $langs->load("main"); // To load language file for default language // Load user and its permissions $result = $user->fetch('', 'admin'); // Load user for login 'admin'. Comment line to run as anonymous user. -if (!$result > 0) { dol_print_error('', $user->error); exit; } +if (!$result > 0) { + dol_print_error('', $user->error); exit; +} $user->getrights(); @@ -162,8 +199,7 @@ else // -------------------- END OF YOUR CODE -------------------- -if (!$error) -{ +if (!$error) { $db->commit(); print '--- end ok'."\n"; } else { diff --git a/htdocs/mrp/ajax/ajax_bom.php b/htdocs/mrp/ajax/ajax_bom.php index adf4a8f4ee7..280a0c98cdd 100644 --- a/htdocs/mrp/ajax/ajax_bom.php +++ b/htdocs/mrp/ajax/ajax_bom.php @@ -22,13 +22,25 @@ //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} require '../../main.inc.php'; // Load $user and permissions require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php'; @@ -43,12 +55,11 @@ $action = GETPOST('action', 'aZ09'); $object = new BOM($db); $result = $object->fetch($idbom); -if ($result > 0) -{ +if ($result > 0) { // We remove properties we don't need in answer unset($object->fields); unset($object->db); echo json_encode($object); } else { - echo 'Failed to load category with id='.$idbom; + echo 'Failed to load category with id='.$idbom; } diff --git a/htdocs/mrp/class/mo.class.php b/htdocs/mrp/class/mo.class.php index 121909eb28a..d7635b9a78e 100644 --- a/htdocs/mrp/class/mo.class.php +++ b/htdocs/mrp/class/mo.class.php @@ -66,26 +66,30 @@ class Mo extends CommonObject const STATUS_CANCELED = 9; - /** - * '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. - * '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). 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) + * '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). - * 'default' is a default value for creation (can still be replaced by the global setup of default values) + * '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) + * '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 @@ -96,7 +100,7 @@ class Mo extends CommonObject 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",), 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'position'=>5, 'notnull'=>1, 'default'=>'1', 'index'=>1), 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>4, 'position'=>10, 'notnull'=>1, 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'showoncombobox'=>'1', 'noteditable'=>1), - 'fk_bom' => array('type'=>'integer:Bom:bom/class/bom.class.php:0:t.status=1', 'filter'=>'active=1', 'label'=>'BOM', 'enabled'=>1, 'visible'=>1, 'position'=>33, 'notnull'=>-1, 'index'=>1, 'comment'=>"Original BOM", 'css'=>'maxwidth300'), + 'fk_bom' => array('type'=>'integer:Bom:bom/class/bom.class.php:0:t.status=1', 'filter'=>'active=1', 'label'=>'BOM', 'enabled'=>1, 'visible'=>1, 'position'=>33, 'notnull'=>-1, 'index'=>1, 'comment'=>"Original BOM", 'css'=>'minwidth100 maxwidth300', 'csslist'=>'nowraponall'), 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:0', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>35, 'notnull'=>1, 'index'=>1, 'comment'=>"Product to produce", 'css'=>'maxwidth300', 'picto'=>'product'), 'qty' => array('type'=>'real', 'label'=>'QtyToProduce', 'enabled'=>1, 'visible'=>1, 'position'=>40, 'notnull'=>1, 'comment'=>"Qty to produce", 'css'=>'width75', 'default'=>1, 'isameasure'=>1), 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>42, 'notnull'=>-1, 'searchall'=>1, 'showoncombobox'=>'1',), @@ -168,7 +172,7 @@ class Mo extends CommonObject /** * @var string Name of subtable line */ - public $table_element_line = 'mo_production'; + public $table_element_line = 'mrp_production'; /** * @var string Field with ID of parent key if this field has a parent @@ -208,25 +212,24 @@ class Mo extends CommonObject $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } // Translate some data of arrayofkeyval - foreach ($this->fields as $key => $val) - { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } @@ -249,7 +252,8 @@ class Mo extends CommonObject $this->db->begin(); - if ($this->fk_product > 0) { + // Check that product is not a kit/virtual product + if (empty($conf->global->ALLOW_USE_KITS_INTO_BOM_AND_MO) and $this->fk_product > 0) { include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $tmpproduct = new Product($this->db); $tmpproduct->fetch($this->fk_product); @@ -261,7 +265,6 @@ class Mo extends CommonObject } } - // Check that product is not a kit/virtual product if (!$error) { $idcreated = $this->createCommon($user, $notrigger); if ($idcreated <= 0) { @@ -305,7 +308,9 @@ class Mo extends CommonObject // Load source object $result = $object->fetchCommon($fromid); - if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); + if ($result > 0 && !empty($object->table_element_line)) { + $object->fetchLines(); + } // get lines so they will be clone //foreach($this->lines as $line) @@ -322,14 +327,11 @@ class Mo extends CommonObject $object->status = self::STATUS_DRAFT; // ... // Clear extrafields that are unique - if (is_array($object->array_options) && count($object->array_options) > 0) - { + if (is_array($object->array_options) && count($object->array_options) > 0) { $extrafields->fetch_name_optionals_label($this->table_element); - foreach ($object->array_options as $key => $option) - { + foreach ($object->array_options as $key => $option) { $shortkey = preg_replace('/options_/', '', $key); - if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) - { + if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) { //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; unset($object->array_options[$key]); } @@ -345,22 +347,19 @@ class Mo extends CommonObject $this->errors = $object->errors; } - if (!$error) - { + if (!$error) { // copy internal contacts - if ($this->copy_linked_contact($object, 'internal') < 0) - { + if ($this->copy_linked_contact($object, 'internal') < 0) { $error++; } } - if (!$error) - { + if (!$error) { // copy external contacts if same company - if (property_exists($this, 'socid') && $this->socid == $object->socid) - { - if ($this->copy_linked_contact($object, 'external') < 0) + if (property_exists($this, 'socid') && $this->socid == $object->socid) { + if ($this->copy_linked_contact($object, 'external') < 0) { $error++; + } } } @@ -386,7 +385,9 @@ class Mo extends CommonObject public function fetch($id, $ref = null) { $result = $this->fetchCommon($id, $ref); - if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); + if ($result > 0 && !empty($this->table_element_line)) { + $this->fetchLines(); + } return $result; } @@ -426,8 +427,11 @@ class Mo extends CommonObject $sql = 'SELECT '; $sql .= $this->getFieldList(); $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; - else $sql .= ' WHERE 1 = 1'; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { + $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; + } else { + $sql .= ' WHERE 1 = 1'; + } // Manage filter $sqlwhere = array(); if (count($filter) > 0) { @@ -458,8 +462,7 @@ class Mo extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < min($limit, $num)) - { + while ($i < min($limit, $num)) { $obj = $this->db->fetch_object($resql); $record = new self($this->db); @@ -496,8 +499,11 @@ class Mo extends CommonObject $sql .= $mostatic->getFieldList(); $sql .= ' FROM '.MAIN_DB_PREFIX.$mostatic->table_element.' as t'; $sql .= " WHERE t.role = '".$this->db->escape($role)."'"; - if ($lineid > 0) $sql .= ' AND t.fk_mrp_production = '.$lineid; - else $sql .= 'AND t.fk_mo = '.$this->id; + if ($lineid > 0) { + $sql .= ' AND t.fk_mrp_production = '.$lineid; + } else { + $sql .= 'AND t.fk_mo = '.$this->id; + } $resql = $this->db->query($sql); if ($resql) { @@ -618,8 +624,7 @@ class Mo extends CommonObject $this->db->begin(); // Insert lines in mrp_production table from BOM data - if (!$error) - { + if (!$error) { // TODO Check that production has not started. If yes, we stop here. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'mrp_production WHERE fk_mo = '.$this->id; @@ -631,9 +636,21 @@ class Mo extends CommonObject $moline->fk_mo = $this->id; $moline->qty = $this->qty; $moline->fk_product = $this->fk_product; - $moline->role = 'toproduce'; $moline->position = 1; + if ($this->fk_bom > 0) { // If a BOM is defined, we know what to consume. + include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php'; + $bom = new Bom($this->db); + $bom->fetch($this->fk_bom); + if ($bom->bomtype == 1) { + $role = 'toproduce'; + $moline->role = 'toconsume'; + } else { + $role = 'toconsume'; + $moline->role = 'toproduce'; + } + } + $resultline = $moline->create($user, false); // Never use triggers here if ($resultline <= 0) { $error++; @@ -643,18 +660,15 @@ class Mo extends CommonObject } if ($this->fk_bom > 0) { // If a BOM is defined, we know what to consume. - include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php'; - $bom = new Bom($this->db); - $bom->fetch($this->fk_bom); - if ($bom->id > 0) - { + if ($bom->id > 0) { // Lines to consume if (!$error) { - foreach ($bom->lines as $line) - { + foreach ($bom->lines as $line) { $moline = new MoLine($this->db); $moline->fk_mo = $this->id; + $moline->origin_id = $line->id; + $moline->origin_type = 'bomline'; if ($line->qty_frozen) { $moline->qty = $line->qty; // Qty to consume does not depends on quantity to produce } else { @@ -666,7 +680,7 @@ class Mo extends CommonObject break; } else { $moline->fk_product = $line->fk_product; - $moline->role = 'toconsume'; + $moline->role = $role; $moline->position = $line->position; $moline->qty_frozen = $line->qty_frozen; $moline->disable_stock_change = $line->disable_stock_change; @@ -719,8 +733,7 @@ class Mo extends CommonObject */ public function deleteLine(User $user, $idline, $notrigger = false) { - if ($this->status < 0) - { + if ($this->status < 0) { $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; return -2; } @@ -741,8 +754,7 @@ class Mo extends CommonObject global $langs, $conf; $langs->load("mrp"); - if (!empty($conf->global->MRP_MO_ADDON)) - { + if (!empty($conf->global->MRP_MO_ADDON)) { $mybool = false; $file = $conf->global->MRP_MO_ADDON.".php"; @@ -750,16 +762,14 @@ class Mo extends CommonObject // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/mrp/"); // Load file with numbering class (if found) $mybool |= @include_once $dir.$file; } - if ($mybool === false) - { + if ($mybool === false) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -767,8 +777,7 @@ class Mo extends CommonObject $obj = new $classname(); $numref = $obj->getNextValue($prod, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -797,8 +806,7 @@ class Mo extends CommonObject $error = 0; // Protection - if ($this->status == self::STATUS_VALIDATED) - { + if ($this->status == self::STATUS_VALIDATED) { dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); return 0; } @@ -816,8 +824,7 @@ class Mo extends CommonObject $this->db->begin(); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $this->fetch_product(); $num = $this->getNextNumRef($this->product); } else { @@ -835,50 +842,47 @@ class Mo extends CommonObject dol_syslog(get_class($this)."::validate()", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $this->error = $this->db->lasterror(); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('MRP_MO_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'mrp/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->mrp->dir_output.'/'.$oldref; $dirdest = $conf->mrp->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->mrp->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -891,14 +895,12 @@ class Mo extends CommonObject } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $num; $this->status = self::STATUS_VALIDATED; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -917,8 +919,7 @@ class Mo extends CommonObject public function setDraft($user, $notrigger = 0) { // Protection - if ($this->status <= self::STATUS_DRAFT) - { + if ($this->status <= self::STATUS_DRAFT) { return 0; } @@ -942,8 +943,7 @@ class Mo extends CommonObject public function cancel($user, $notrigger = 0) { // Protection - if ($this->status != self::STATUS_VALIDATED && $this->status != self::STATUS_INPROGRESS) - { + if ($this->status != self::STATUS_VALIDATED && $this->status != self::STATUS_INPROGRESS) { return 0; } @@ -967,8 +967,7 @@ class Mo extends CommonObject public function reopen($user, $notrigger = 0) { // Protection - if ($this->status != self::STATUS_PRODUCED && $this->status != self::STATUS_CANCELED) - { + if ($this->status != self::STATUS_PRODUCED && $this->status != self::STATUS_CANCELED) { return 0; } @@ -996,7 +995,9 @@ class Mo extends CommonObject { global $conf, $langs, $hookmanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -1008,35 +1009,44 @@ class Mo extends CommonObject $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref; $url = dol_buildpath('/mrp/mo_card.php', 1).'?id='.$this->id; - if ($option == 'production') $url = dol_buildpath('/mrp/mo_production.php', 1).'?id='.$this->id; + if ($option == 'production') { + $url = dol_buildpath('/mrp/mo_production.php', 1).'?id='.$this->id; + } - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowMo"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = '<a href="'.$url.'"'; $linkstart .= $linkclose.'>'; $linkend = '</a>'; $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -1044,8 +1054,11 @@ class Mo extends CommonObject $hookmanager->initHooks(array('modao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -1072,8 +1085,7 @@ class Mo extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - if (empty($this->labelStatus)) - { + if (empty($this->labelStatus)) { global $langs; //$langs->load("mrp"); $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft'); @@ -1090,10 +1102,18 @@ class Mo extends CommonObject } $statusType = 'status'.$status; - if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; - if ($status == self::STATUS_INPROGRESS) $statusType = 'status4'; - if ($status == self::STATUS_PRODUCED) $statusType = 'status6'; - if ($status == self::STATUS_CANCELED) $statusType = 'status9'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status1'; + } + if ($status == self::STATUS_INPROGRESS) { + $statusType = 'status4'; + } + if ($status == self::STATUS_PRODUCED) { + $statusType = 'status6'; + } + if ($status == self::STATUS_CANCELED) { + $statusType = 'status9'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -1109,30 +1129,25 @@ class Mo 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; @@ -1172,8 +1187,7 @@ class Mo extends CommonObject $objectline = new MoLine($this->db); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_mo = '.$this->id)); - if (is_numeric($result)) - { + if (is_numeric($result)) { $this->error = $this->error; $this->errors = $this->errors; return $result; @@ -1213,7 +1227,9 @@ class Mo extends CommonObject $modelpath = "core/modules/mrp/doc/"; - if (empty($modele)) return 1; // Remove this once a pdf_standard.php exists. + if (empty($modele)) { + return 1; // Remove this once a pdf_standard.php exists. + } return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); } @@ -1273,10 +1289,8 @@ class Mo extends CommonObject print '</tr>'; $i = 0; - if (!empty($this->lines)) - { - foreach ($this->lines as $line) - { + if (!empty($this->lines)) { + foreach ($this->lines as $line) { /*if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) { if (empty($line->fk_parent_line)) @@ -1317,8 +1331,7 @@ class Mo extends CommonObject $this->tpl['id'] = $line->id; $this->tpl['label'] = ''; - if (!empty($line->fk_product)) - { + if (!empty($line->fk_product)) { $productstatic = new Product($this->db); $productstatic->fetch($line->fk_product); $this->tpl['label'] .= $productstatic->getNomUrl(1); @@ -1386,6 +1399,8 @@ class MoLine extends CommonObjectLine public $fields = array( 'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), 'fk_mo' =>array('type'=>'integer', 'label'=>'Mo', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15), + 'origin_id' =>array('type'=>'integer', 'label'=>'Origin', 'enabled'=>1, 'visible'=>-1, 'notnull'=>0, 'position'=>17), + 'origin_type' =>array('type'=>'varchar(10)', 'label'=>'Origin type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>0, 'position'=>18), 'position' =>array('type'=>'integer', 'label'=>'Position', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20), 'fk_product' =>array('type'=>'integer', 'label'=>'Product', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25), 'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>30), @@ -1405,6 +1420,8 @@ class MoLine extends CommonObjectLine public $rowid; public $fk_mo; + public $origin_id; + public $origin_type; public $position; public $fk_product; public $fk_warehouse; @@ -1432,27 +1449,25 @@ class MoLine extends CommonObjectLine $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } // Translate some data of arrayofkeyval - if (is_object($langs)) - { - foreach ($this->fields as $key => $val) - { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } @@ -1487,7 +1502,6 @@ class MoLine extends CommonObjectLine public function fetch($id, $ref = null) { $result = $this->fetchCommon($id, $ref); - if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); return $result; } @@ -1513,8 +1527,11 @@ class MoLine extends CommonObjectLine $sql = 'SELECT '; $sql .= $this->getFieldList(); $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; - else $sql .= ' WHERE 1 = 1'; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { + $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; + } else { + $sql .= ' WHERE 1 = 1'; + } // Manage filter $sqlwhere = array(); if (count($filter) > 0) { @@ -1545,8 +1562,7 @@ class MoLine extends CommonObjectLine if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < min($limit, $num)) - { + while ($i < min($limit, $num)) { $obj = $this->db->fetch_object($resql); $record = new self($this->db); diff --git a/htdocs/mrp/index.php b/htdocs/mrp/index.php index b84a77c2288..f86a52f4aae 100644 --- a/htdocs/mrp/index.php +++ b/htdocs/mrp/index.php @@ -61,16 +61,14 @@ print '<div class="fichecenter"><div class="fichethirdleft">'; * Statistics */ -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { $sql = "SELECT COUNT(t.rowid) as nb, status"; $sql .= " FROM ".MAIN_DB_PREFIX."mrp_mo as t"; $sql .= " GROUP BY t.status"; $sql .= " ORDER BY t.status ASC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -81,14 +79,12 @@ if ($conf->use_javascript_ajax) include_once DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $vals[$obj->status] = $obj->nb; - $totalnb += $obj->nb; + $totalnb += $obj->nb; } $i++; } @@ -98,25 +94,32 @@ if ($conf->use_javascript_ajax) print '<table class="noborder nohover centpercent">'; print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("ManufacturingOrder").'</th></tr>'."\n"; $listofstatus = array(0, 1, 2, 3, 9); - foreach ($listofstatus as $status) - { + foreach ($listofstatus as $status) { $dataseries[] = array($staticmo->LibStatut($status, 1), (isset($vals[$status]) ? (int) $vals[$status] : 0)); - if ($status == Mo::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; - if ($status == Mo::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus1; - if ($status == Mo::STATUS_INPROGRESS) $colorseries[$status] = $badgeStatus4; - if ($status == Mo::STATUS_PRODUCED) $colorseries[$status] = $badgeStatus6; - if ($status == Mo::STATUS_CANCELED) $colorseries[$status] = $badgeStatus9; + if ($status == Mo::STATUS_DRAFT) { + $colorseries[$status] = '-'.$badgeStatus0; + } + if ($status == Mo::STATUS_VALIDATED) { + $colorseries[$status] = $badgeStatus1; + } + if ($status == Mo::STATUS_INPROGRESS) { + $colorseries[$status] = $badgeStatus4; + } + if ($status == Mo::STATUS_PRODUCED) { + $colorseries[$status] = $badgeStatus6; + } + if ($status == Mo::STATUS_CANCELED) { + $colorseries[$status] = $badgeStatus9; + } - if (empty($conf->use_javascript_ajax)) - { + if (empty($conf->use_javascript_ajax)) { print '<tr class="oddeven">'; print '<td>'.$staticmo->LibStatut($status, 0).'</td>'; print '<td class="right"><a href="list.php?statut='.$status.'">'.(isset($vals[$status]) ? $vals[$status] : 0).'</a></td>'; print "</tr>\n"; } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<tr><td class="center" colspan="2">'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -159,19 +162,16 @@ $sql .= $db->order("a.tms", "DESC"); $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="4">'.$langs->trans("LatestBOMModified", $max).'</th></tr>'; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $staticbom->id = $obj->rowid; @@ -210,19 +210,16 @@ $sql .= $db->order("a.tms", "DESC"); $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="4">'.$langs->trans("LatestMOModified", $max).'</th></tr>'; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $staticmo->id = $obj->rowid; diff --git a/htdocs/mrp/js/lib_dispatch.js.php b/htdocs/mrp/js/lib_dispatch.js.php index a02bb0e8f84..8a5eef60211 100644 --- a/htdocs/mrp/js/lib_dispatch.js.php +++ b/htdocs/mrp/js/lib_dispatch.js.php @@ -21,13 +21,27 @@ * \brief File that include javascript functions used for dispatching qty/stock/lot */ -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); -if (!defined('NOLOGIN')) define('NOLOGIN', 1); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', 1); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', 1); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', 1); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', 1); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', 1); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} session_cache_limiter('public'); @@ -36,8 +50,11 @@ require_once '../../main.inc.php'; // Define javascript type top_httphead('text/javascript; charset=UTF-8'); // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. -if (empty($dolibarr_nocache)) header('Cache-Control: max-age=10800, public, must-revalidate'); -else header('Cache-Control: no-cache'); +if (empty($dolibarr_nocache)) { + header('Cache-Control: max-age=10800, public, must-revalidate'); +} else { + header('Cache-Control: no-cache'); +} ?> /** @@ -77,9 +94,9 @@ function addDispatchLine(index, type, mode) if (qtyOrdered <= 1) { window.alert("Quantity can't be split"); - } - if (qtyDispatched < qtyOrdered) - { + } else if (qtyDispatched >= qtyOrdered) { + window.alert("No remain qty to dispatch"); + } else if (qtyDispatched < qtyOrdered) { //replace tr suffix nbr var re1 = new RegExp('_'+index+'_1', 'g'); var re2 = new RegExp('-'+index+'-1', 'g'); diff --git a/htdocs/mrp/lib/mrp_mo.lib.php b/htdocs/mrp/lib/mrp_mo.lib.php index eb61c42e83d..62f74ce016e 100644 --- a/htdocs/mrp/lib/mrp_mo.lib.php +++ b/htdocs/mrp/lib/mrp_mo.lib.php @@ -59,14 +59,19 @@ function moPrepareHead($object) $head[$h][2] = 'stockmovement'; $h++; - if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) - { + if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = dol_buildpath('/mrp/mo_note.php', 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>'; + if ($nbNote > 0) { + $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>'; + } $head[$h][2] = 'note'; $h++; } @@ -78,7 +83,9 @@ function moPrepareHead($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = dol_buildpath("/mrp/mo_document.php", 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; + } $head[$h][2] = 'document'; $h++; diff --git a/htdocs/mrp/mo_agenda.php b/htdocs/mrp/mo_agenda.php index 0fe9ba63e08..69c64b1a027 100644 --- a/htdocs/mrp/mo_agenda.php +++ b/htdocs/mrp/mo_agenda.php @@ -44,10 +44,11 @@ $action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); -if (GETPOST('actioncode', 'array')) -{ +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)); } @@ -57,12 +58,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 (!$sortfield) $sortfield = 'a.datep,a.id'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} // Initialize technical objects $object = new Mo($db); @@ -75,7 +82,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->mrp->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->mrp->multidir_output[$object->entity]."/".$object->id; +} // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); @@ -90,20 +99,19 @@ $result = restrictedArea($user, 'mrp', $object->id, 'mrp_mo', '', 'fk_soc', 'row $parameters = array('id'=>$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)) -{ +if (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // 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 $actioncode = ''; $search_agenda_label = ''; } @@ -120,14 +128,15 @@ $contactstatic = new Contact($db); $form = new Form($db); $formproject = new FormProjets($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $title = $langs->trans("Agenda"); //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; $help_url = ''; llxHeader('', $title, $help_url); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = moPrepareHead($object); @@ -144,14 +153,13 @@ if ($object->id > 0) // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.(is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') + if ($permissiontoadd) { + if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; @@ -196,10 +204,11 @@ if ($object->id > 0) $out = '&origin='.$object->element.'&originid='.$object->id; $permok = $user->rights->agenda->myactions->create; - if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) - { + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { //$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'; - if (get_class($objthirdparty) == 'Societe') $out .= '&amp;socid='.$objthirdparty->id; + if (get_class($objthirdparty) == 'Societe') { + $out .= '&amp;socid='.$objthirdparty->id; + } $out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1'; //$out.=$langs->trans("AddAnAction").' '; //$out.=img_picto($langs->trans("AddAnAction"),'filenew'); @@ -209,10 +218,8 @@ if ($object->id > 0) print '<div class="tabsAction">'; - if (!empty($conf->agenda->enabled)) - { - if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) - { + if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'">'.$langs->trans("AddAction").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>'; @@ -221,11 +228,14 @@ if ($object->id > 0) print '</div>'; - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $param = '&id='.$object->id.'&socid='.$socid; - 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); + } //print load_fiche_titre($langs->trans("ActionsOnMo"), '', ''); diff --git a/htdocs/mrp/mo_card.php b/htdocs/mrp/mo_card.php index a95d92d67a1..9afbbaf9acf 100644 --- a/htdocs/mrp/mo_card.php +++ b/htdocs/mrp/mo_card.php @@ -61,18 +61,20 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. -if (GETPOST('fk_bom', 'int')) -{ +if (GETPOST('fk_bom', 'int')) { $objectbom->fetch(GETPOST('fk_bom', 'int')); if ($action != 'add') { @@ -103,18 +105,22 @@ $upload_dir = $conf->mrp->multidir_output[isset($object->entity) ? $object->enti $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 (empty($reshook)) { $error = 0; $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1); if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__'); + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__'); + } } } if ($cancel && !empty($backtopageforcancel)) { @@ -141,28 +147,27 @@ if (empty($reshook)) // Action to move up and down lines of object //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - if ($action == 'set_thirdparty' && $permissiontoadd) - { + if ($action == 'set_thirdparty' && $permissiontoadd) { $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY'); } - if ($action == 'classin' && $permissiontoadd) - { + if ($action == 'classin' && $permissiontoadd) { $object->setProject(GETPOST('projectid', 'int')); } // Action close produced - if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) - { + if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) { $result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED'); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -208,15 +213,18 @@ jQuery(document).ready(function() { // Part to create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("Mo")), '', 'mrp'); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } print dol_get_fiche_head(array(), ''); @@ -234,7 +242,7 @@ if ($action == 'create') ?> <script> - $(document).ready(function () { + $(document).ready(function () { jQuery('#fk_bom').change(function() { console.log('We change value of BOM with BOM of id '+jQuery('#fk_bom').val()); if (jQuery('#fk_bom').val() > 0) @@ -280,7 +288,7 @@ if ($action == 'create') $('#fk_warehouse').trigger('change'); // Notify any JS components that the value changed */ } - }); + }); //jQuery('#fk_bom').trigger('change'); }) @@ -312,16 +320,19 @@ if ($action == 'create') } // Part to edit record -if (($id || $ref) && $action == 'edit') -{ +if (($id || $ref) && $action == 'edit') { print load_fiche_titre($langs->trans("ManufacturingOrder"), '', 'mrp'); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } print dol_get_fiche_head(); @@ -347,8 +358,7 @@ if (($id || $ref) && $action == 'edit') } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_thirdparty(); $res = $object->fetch_optionals(); @@ -359,19 +369,16 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $formconfirm = ''; // Confirmation to delete - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line - if ($action == 'deleteline') - { + if ($action == 'deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); } // Confirmation of validation - if ($action == 'validate') - { + if ($action == 'validate') { // We check that object has a temporary ref $ref = substr($object->ref, 1, 4); if ($ref == 'PROV') { @@ -391,13 +398,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea }*/ $formquestion = array(); - if (!empty($conf->mrp->enabled)) - { + if (!empty($conf->mrp->enabled)) { $langs->load("mrp"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( // 'text' => $langs->trans("ConfirmClone"), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -418,8 +426,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -438,14 +449,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $morehtmlref .= $langs->trans('ThirdParty').' '; $morehtmlref .= ': '.(is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') + if ($permissiontoadd) { + if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; @@ -500,8 +510,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea * Lines */ - if (!empty($object->table_element_line)) - { + if (!empty($object->table_element_line)) { // Show object lines //$result = $object->getLinesArray(); $object->fetchLines(); @@ -514,11 +523,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea '; /*if (!empty($conf->use_javascript_ajax) && $object->status == 0) { - include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; - }*/ + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; + }*/ - if (!empty($object->lines)) - { + if (!empty($object->lines)) { print '<div class="div-table-responsive-no-min">'; print '<table id="tablelines" class="noborder noshadow" width="100%">'; @@ -530,12 +538,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<tr class="oddeven">'; print '<td>'.$langs->trans("ProductsToConsume").'</td>'; print '<td>'; - if (!empty($object->lines)) - { + if (!empty($object->lines)) { $i = 0; foreach ($object->lines as $line) { if ($line->role == 'toconsume') { - if ($i) print ', '; + if ($i) { + print ', '; + } $tmpproduct = new Product($db); $tmpproduct->fetch($line->fk_product); print $tmpproduct->getNomUrl(1); @@ -549,12 +558,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<tr class="oddeven">'; print '<td>'.$langs->trans("ProductsToProduce").'</td>'; print '<td>'; - if (!empty($object->lines)) - { + if (!empty($object->lines)) { $i = 0; foreach ($object->lines as $line) { if ($line->role == 'toproduce') { - if ($i) print ', '; + if ($i) { + print ', '; + } $tmpproduct = new Product($db); $tmpproduct->fetch($line->fk_product); print $tmpproduct->getNomUrl(1); @@ -579,20 +589,19 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<div class="tabsAction">'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Send //if (empty($user->socid)) { // print '<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a>'."\n"; //} // Back to draft - if ($object->status == $object::STATUS_VALIDATED) - { - if ($permissiontoadd) - { + if ($object->status == $object::STATUS_VALIDATED) { + if ($permissiontoadd) { // TODO Add test that production has not started print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes">'.$langs->trans("SetToDraft").'</a>'; } @@ -600,8 +609,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Modify if ($object->status == $object::STATUS_DRAFT) { - if ($permissiontoadd) - { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>'."\n"; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n"; @@ -609,12 +617,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Validate - if ($object->status == $object::STATUS_DRAFT) - { - if ($permissiontoadd) - { - if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) - { + if ($object->status == $object::STATUS_DRAFT) { + if ($permissiontoadd) { + if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=validate">'.$langs->trans("Validate").'</a>'; } else { $langs->load("errors"); @@ -624,16 +629,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Clone - if ($permissiontoadd) - { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->fk_soc.'&action=clone&object=mo">'.$langs->trans("ToClone").'</a>'; } // Cancel - Reopen - if ($permissiontoadd) - { - if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS) - { + if ($permissiontoadd) { + if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS) { $arrayproduced = $object->fetchLinesLinked('produced', 0); $nbProduced = 0; foreach ($arrayproduced as $lineproduced) { @@ -648,15 +650,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_close&confirm=yes">'.$langs->trans("Cancel").'</a>'."\n"; } - if ($object->status == $object::STATUS_PRODUCED || $object->status == $object::STATUS_CANCELED) - { + if ($object->status == $object::STATUS_PRODUCED || $object->status == $object::STATUS_CANCELED) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes">'.$langs->trans("ReOpen").'</a>'."\n"; } } // Delete (need delete permission, or if draft, just need create/modify permission) - if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) - { + if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n"; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n"; @@ -671,8 +671,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre @@ -707,7 +706,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } //Select mail models is same action as presend - if (GETPOST('modelselected')) $action = 'presend'; + if (GETPOST('modelselected')) { + $action = 'presend'; + } // Presend form $modelmail = 'mo'; diff --git a/htdocs/mrp/mo_document.php b/htdocs/mrp/mo_document.php index 01131b9ffa2..920f69b01af 100644 --- a/htdocs/mrp/mo_document.php +++ b/htdocs/mrp/mo_document.php @@ -47,12 +47,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"; +} //if (! $sortfield) $sortfield="position_name"; // Initialize technical objects @@ -67,7 +73,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->mrp->multidir_output[$object->entity ? $object->entity : $conf->entity]."/mo/".get_exdir(0, 0, 0, 1, $object); +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->mrp->multidir_output[$object->entity ? $object->entity : $conf->entity]."/mo/".get_exdir(0, 0, 0, 1, $object); +} // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); @@ -80,7 +88,7 @@ $result = restrictedArea($user, 'mrp', $object->id, 'mrp_mo', '', 'fk_soc', 'row * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -95,8 +103,7 @@ $help_url = ''; //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($object->id) -{ +if ($object->id) { /* * Show tabs */ @@ -107,8 +114,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -123,14 +129,13 @@ if ($object->id) // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.(is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') + if ($permissiontoadd) { + if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; diff --git a/htdocs/mrp/mo_list.php b/htdocs/mrp/mo_list.php index beeefbd19ff..841dba3ea20 100644 --- a/htdocs/mrp/mo_list.php +++ b/htdocs/mrp/mo_list.php @@ -54,7 +54,9 @@ $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; @@ -73,14 +75,19 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "t.ref"; // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Security check -if (empty($conf->mrp->enabled)) accessforbidden('Module not enabled'); +if (empty($conf->mrp->enabled)) { + accessforbidden('Module not enabled'); +} $socid = 0; -if ($user->socid > 0) // Protection if external user -{ +if ($user->socid > 0) { // Protection if external user //$socid = $user->socid; accessforbidden(); } @@ -90,30 +97,31 @@ if ($user->socid > 0) // Protection if external user // Initialize array of search criterias $search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of fields for list $arrayfields = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field - if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); + if (!empty($val['visible'])) { + $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); + } } // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], @@ -136,31 +144,33 @@ $permissiontodelete = $user->rights->mrp->delete; * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($object->fields as $key => $val) - { + 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 + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $toselect = ''; $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -189,13 +199,14 @@ $title = $langs->trans('ListOfManufacturingOrders'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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.', ' : ''); + 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(); @@ -203,20 +214,32 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -else $sql .= " WHERE 1 = 1"; -foreach ($search as $key => $val) -{ - if ($key == 'status' && $search[$key] == -1) continue; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); if (strpos($object->fields[$key]['type'], 'integer:') === 0) { - if ($search[$key] == '-1') $search[$key] = ''; + if ($search[$key] == '-1') { + $search[$key] = ''; + } $mode_search = 2; } - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -246,26 +269,24 @@ $sql .= $db->order($sortfield, $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 || empty($limit))) -{ +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -274,8 +295,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".dol_buildpath('/mrp/mo_card.php', 1).'?id='.$id); @@ -306,14 +326,24 @@ jQuery(document).ready(function() { $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ - if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); - else $param .= '&search_'.$key.'='.urlencode($search[$key]); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +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'; @@ -324,12 +354,18 @@ $arrayofmassactions = array( //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); -if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($permissiontodelete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -348,9 +384,10 @@ $objecttmp = new Mo($db); $trackid = 'mo'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } @@ -361,11 +398,13 @@ $moreforfilter.= '</div>';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -382,20 +421,26 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit // Fields title search // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - elseif (strpos($val['type'], 'integer:') === 0) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth125', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { + print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } print '</td>'; } } @@ -417,15 +462,18 @@ print '</tr>'."\n"; // Fields title label // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ - $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { +foreach ($object->fields as $key => $val) { + $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'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -442,11 +490,11 @@ print '</tr>'."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -455,38 +503,53 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->setVarsFromFetchObj($obj); // Show here line of result print '<tr class="oddeven">'; - foreach ($object->fields as $key => $val) - { - $cssforfield = (empty($val['css']) ? '' : $val['css']); - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + foreach ($object->fields as $key => $val) { + $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') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) { + $cssforfield = 'tdoverflowmax100'; + } - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>'; - if ($key == 'status') print $object->getLibStatut(5); - else print $object->showOutputField($val, $key, $object->$key, ''); + if ($key == 'status') { + print $object->getLibStatut(5); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $object->$key; } } @@ -499,14 +562,17 @@ while ($i < ($limit ? min($num, $limit) : $num)) print $hookmanager->resPrint; // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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($object->id, $arrayofselected)) $selected = 1; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'."\n"; @@ -518,10 +584,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } @@ -537,10 +606,11 @@ print '</div>'."\n"; print '</form>'."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/mrp/mo_movements.php b/htdocs/mrp/mo_movements.php index b4dbed059bc..59b4b07fe82 100644 --- a/htdocs/mrp/mo_movements.php +++ b/htdocs/mrp/mo_movements.php @@ -66,10 +66,16 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -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; -if (!$sortfield) $sortfield = "m.datem"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "m.datem"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} // Initialize technical objects $object = new Mo($db); @@ -85,12 +91,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = trim(GETPOST("search_all", 'alpha')); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. @@ -105,23 +114,24 @@ $objectlist = new MouvementStock($db); // Definition of fields for list $arrayfields = array( - 'm.rowid'=>array('label'=>$langs->trans("Ref"), 'checked'=>1, 'position'=>1), - 'm.datem'=>array('label'=>$langs->trans("Date"), 'checked'=>1, 'position'=>2), - 'p.ref'=>array('label'=>$langs->trans("ProductRef"), 'checked'=>1, 'css'=>'maxwidth100', 'position'=>10), - 'p.label'=>array('label'=>$langs->trans("ProductLabel"), 'checked'=>1, 'position'=>15), - 'm.batch'=>array('label'=>$langs->trans("BatchNumberShort"), 'checked'=>1, 'enabled'=>(!empty($conf->productbatch->enabled)), 'position'=>20), - 'pl.eatby'=>array('label'=>$langs->trans("EatByDate"), 'checked'=>0, 'position'=>10, 'enabled'=>(!empty($conf->productbatch->enabled)), 'position'=>21), - 'pl.sellby'=>array('label'=>$langs->trans("SellByDate"), 'checked'=>0, 'position'=>10, 'enabled'=>(!empty($conf->productbatch->enabled)), 'position'=>22), - 'e.ref'=>array('label'=>$langs->trans("Warehouse"), 'checked'=>1, 'position'=>30), - 'm.fk_user_author'=>array('label'=>$langs->trans("Author"), 'checked'=>0, 'position'=>40), - 'm.inventorycode'=>array('label'=>$langs->trans("InventoryCodeShort"), 'checked'=>1, 'position'=>42), - 'm.label'=>array('label'=>$langs->trans("MovementLabel"), 'checked'=>1, 'position'=>45), - 'm.type_mouvement'=>array('label'=>$langs->trans("TypeMovement"), 'checked'=>1, 'position'=>48), - 'origin'=>array('label'=>$langs->trans("Origin"), 'enabled'=>0, 'checked'=>0, 'position'=>50), - 'm.value'=>array('label'=>$langs->trans("Qty"), 'checked'=>1, 'position'=>60), - 'm.price'=>array('label'=>$langs->trans("UnitPurchaseValue"), 'enabled'=>0, 'checked'=>0, 'position'=>62), - //'m.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - //'m.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500) + 'm.rowid'=>array('label'=>"Ref", 'checked'=>1, 'position'=>1), + 'm.datem'=>array('label'=>"Date", 'checked'=>1, 'position'=>2), + 'p.ref'=>array('label'=>"ProductRef", 'checked'=>1, 'css'=>'maxwidth100', 'position'=>3), + 'p.label'=>array('label'=>"ProductLabel", 'checked'=>0, 'position'=>5), + 'm.batch'=>array('label'=>"BatchNumberShort", 'checked'=>1, 'position'=>8, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'pl.eatby'=>array('label'=>"EatByDate", 'checked'=>0, 'position'=>9, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'pl.sellby'=>array('label'=>"SellByDate", 'checked'=>0, 'position'=>10, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'e.ref'=>array('label'=>"Warehouse", 'checked'=>1, 'position'=>100, 'enabled'=>(!$id > 0)), // If we are on specific warehouse, we hide it + 'm.fk_user_author'=>array('label'=>"Author", 'checked'=>0, 'position'=>120), + 'm.inventorycode'=>array('label'=>"InventoryCodeShort", 'checked'=>1, 'position'=>130), + 'm.label'=>array('label'=>"MovementLabel", 'checked'=>1, 'position'=>140), + 'm.type_mouvement'=>array('label'=>"TypeMovement", 'checked'=>0, 'position'=>150), + 'origin'=>array('label'=>"Origin", 'checked'=>1, 'position'=>155), + 'm.fk_projet'=>array('label'=>'Project', 'checked'=>0, 'position'=>180), + 'm.value'=>array('label'=>"Qty", 'checked'=>1, 'position'=>200), + 'm.price'=>array('label'=>"UnitPurchaseValue", 'checked'=>0, 'position'=>210) + //'m.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500), + //'m.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500) ); if (!empty($conf->global->PRODUCT_DISABLE_EATBY)) { unset($arrayfields['pl.eatby']); @@ -139,24 +149,33 @@ $permissiontodelete = $user->rights->mrp->delete || ($permissiontoadd && isset($ $upload_dir = $conf->mrp->multidir_output[isset($object->entity) ? $object->entity : 1]; $permissiontoproduce = $permissiontoadd; +$permissiontoupdatecost = $user->rights->bom->write; // User who can define cost must have knowledge of pricing +if ($permissiontoupdatecost) { + $arrayfields['m.price']['enabled'] = 1; +} /* * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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'); +} include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $year = ''; $month = ''; $search_ref = ''; @@ -174,16 +193,18 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_array_options = array(); } -if (empty($reshook)) -{ +if (empty($reshook)) { $error = 0; $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1); if (empty($backtopage) || ($cancel && empty($id))) { //var_dump($backurlforlist);exit; - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = DOL_URL_ROOT.'/mrp/mo_production.php?id='.($id > 0 ? $id : '__ID__'); + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = DOL_URL_ROOT.'/mrp/mo_production.php?id='.($id > 0 ? $id : '__ID__'); + } } $triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record @@ -205,12 +226,10 @@ if (empty($reshook)) // Action to move up and down lines of object //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - if ($action == 'set_thirdparty' && $permissiontoadd) - { + if ($action == 'set_thirdparty' && $permissiontoadd) { $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY'); } - if ($action == 'classin' && $permissiontoadd) - { + if ($action == 'classin' && $permissiontoadd) { $object->setProject(GETPOST('projectid', 'int')); } @@ -236,8 +255,7 @@ $userstatic = new User($db); llxHeader('', $langs->trans('Mo'), ''); // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_thirdparty(); $res = $object->fetch_optionals(); @@ -248,13 +266,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $formconfirm = ''; // Confirmation to delete - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line - if ($action == 'deleteline') - { + if ($action == 'deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); } // Clone confirmation @@ -265,27 +281,29 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Confirmation of action xxxx - if ($action == 'xxx') - { + if ($action == 'xxx') { $formquestion = array(); /* $forcecombo=0; if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy - $formquestion = array( - // 'text' => $langs->trans("ConfirmClone"), - // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), - // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), - // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) - ); - */ + $formquestion = array( + // 'text' => $langs->trans("ConfirmClone"), + // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), + // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), + // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) + ); + */ $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); } // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -303,14 +321,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.(is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') + if ($permissiontoadd) { + if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; @@ -403,7 +420,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $sql .= " u.login, u.photo, u.lastname, u.firstname"; // Add fields from extrafields if (!empty($extrafields->attributes[$objectlist->table_element]['label'])) { - foreach ($extrafields->attributes[$objectlist->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$objectlist->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + foreach ($extrafields->attributes[$objectlist->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$objectlist->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } // Add fields from hooks $parameters = array(); @@ -412,26 +431,52 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,"; $sql .= " ".MAIN_DB_PREFIX."product as p,"; $sql .= " ".MAIN_DB_PREFIX."stock_mouvement as m"; - if (is_array($extrafields->attributes[$objectlist->table_element]['label']) && count($extrafields->attributes[$objectlist->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$objectlist->table_element."_extrafields as ef on (m.rowid = ef.fk_object)"; + if (is_array($extrafields->attributes[$objectlist->table_element]['label']) && count($extrafields->attributes[$objectlist->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$objectlist->table_element."_extrafields as ef on (m.rowid = ef.fk_object)"; + } $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON m.fk_user_author = u.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON m.batch = pl.batch AND m.fk_product = pl.fk_product"; $sql .= " WHERE m.fk_product = p.rowid"; $sql .= " AND m.origintype = 'mo' AND m.fk_origin = ".(int) $object->id; - if ($msid > 0) $sql .= " AND m.rowid = ".$msid; + if ($msid > 0) { + $sql .= " AND m.rowid = ".$msid; + } $sql .= " AND m.fk_entrepot = e.rowid"; $sql .= " AND e.entity IN (".getEntity('stock').")"; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= " AND p.fk_product_type = 0"; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $sql .= " AND p.fk_product_type = 0"; + } $sql .= dolSqlDateFilter('m.datem', 0, $month, $year); - if (!empty($search_ref)) $sql .= natural_search('m.rowid', $search_ref, 1); - if (!empty($search_movement)) $sql .= natural_search('m.label', $search_movement); - if (!empty($search_inventorycode)) $sql .= natural_search('m.inventorycode', $search_inventorycode); - if (!empty($search_product_ref)) $sql .= natural_search('p.ref', $search_product_ref); - if (!empty($search_product)) $sql .= natural_search('p.label', $search_product); - if ($search_warehouse != '' && $search_warehouse != '-1') $sql .= natural_search('e.rowid', $search_warehouse, 2); - if (!empty($search_user)) $sql .= natural_search('u.login', $search_user); - if (!empty($search_batch)) $sql .= natural_search('m.batch', $search_batch); - if ($search_qty != '') $sql .= natural_search('m.value', $search_qty, 1); - if ($search_type_mouvement != '' && $search_type_mouvement != '-1') $sql .= natural_search('m.type_mouvement', $search_type_mouvement, 2); + if (!empty($search_ref)) { + $sql .= natural_search('m.rowid', $search_ref, 1); + } + if (!empty($search_movement)) { + $sql .= natural_search('m.label', $search_movement); + } + if (!empty($search_inventorycode)) { + $sql .= natural_search('m.inventorycode', $search_inventorycode); + } + if (!empty($search_product_ref)) { + $sql .= natural_search('p.ref', $search_product_ref); + } + if (!empty($search_product)) { + $sql .= natural_search('p.label', $search_product); + } + if ($search_warehouse != '' && $search_warehouse != '-1') { + $sql .= natural_search('e.rowid', $search_warehouse, 2); + } + if (!empty($search_user)) { + $sql .= natural_search('u.login', $search_user); + } + if (!empty($search_batch)) { + $sql .= natural_search('m.batch', $search_batch); + } + if ($search_qty != '') { + $sql .= natural_search('m.value', $search_qty, 1); + } + if ($search_type_mouvement != '' && $search_type_mouvement != '-1') { + $sql .= natural_search('m.type_mouvement', $search_type_mouvement, 2); + } // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -441,12 +486,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -454,17 +497,39 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $sql .= $db->plimit($limit + 1, $offset); $param = ''; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($id > 0) $param .= '&id='.urlencode($id); - if ($search_movement) $param .= '&search_movement='.urlencode($search_movement); - if ($search_inventorycode) $param .= '&search_inventorycode='.urlencode($search_inventorycode); - if ($search_type_mouvement) $param .= '&search_type_mouvement='.urlencode($search_type_mouvement); - if ($search_product_ref) $param .= '&search_product_ref='.urlencode($search_product_ref); - if ($search_product) $param .= '&search_product='.urlencode($search_product); - if ($search_batch) $param .= '&search_batch='.urlencode($search_batch); - if ($search_warehouse > 0) $param .= '&search_warehouse='.urlencode($search_warehouse); - if ($search_user) $param .= '&search_user='.urlencode($search_user); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($id > 0) { + $param .= '&id='.urlencode($id); + } + if ($search_movement) { + $param .= '&search_movement='.urlencode($search_movement); + } + if ($search_inventorycode) { + $param .= '&search_inventorycode='.urlencode($search_inventorycode); + } + if ($search_type_mouvement) { + $param .= '&search_type_mouvement='.urlencode($search_type_mouvement); + } + if ($search_product_ref) { + $param .= '&search_product_ref='.urlencode($search_product_ref); + } + if ($search_product) { + $param .= '&search_product='.urlencode($search_product); + } + if ($search_batch) { + $param .= '&search_batch='.urlencode($search_batch); + } + if ($search_warehouse > 0) { + $param .= '&search_warehouse='.urlencode($search_warehouse); + } + if ($search_user) { + $param .= '&search_user='.urlencode($search_user); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -475,11 +540,15 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // 'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$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); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -487,20 +556,27 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="page" value="'.$page.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; - if ($id > 0) print '<input type="hidden" name="id" value="'.$id.'">'; + if ($id > 0) { + print '<input type="hidden" name="id" value="'.$id.'">'; + } - if ($id > 0) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit); - else print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, '', '', $limit); + if ($id > 0) { + print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit); + } else { + print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, '', '', $limit); + } $moreforfilter = ''; $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)) - { + if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -514,84 +590,74 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Fields title search print '<tr class="liste_titre_filter">'; - if (!empty($arrayfields['m.rowid']['checked'])) - { + if (!empty($arrayfields['m.rowid']['checked'])) { // Ref print '<td class="liste_titre left">'; print '<input class="flat maxwidth25" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; print '</td>'; } - if (!empty($arrayfields['m.datem']['checked'])) - { + if (!empty($arrayfields['m.datem']['checked'])) { print '<td class="liste_titre nowraponall">'; print '<input class="flat" type="text" size="2" maxlength="2" placeholder="'.dol_escape_htmltag($langs->trans("Month")).'" name="month" value="'.$month.'">'; - if (empty($conf->productbatch->enabled)) print '&nbsp;'; + if (empty($conf->productbatch->enabled)) { + print '&nbsp;'; + } //else print '<br>'; $syear = $year ? $year : -1; print '<input class="flat maxwidth50" type="text" maxlength="4" placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" name="year" value="'.($syear > 0 ? $syear : '').'">'; //print $formother->selectyear($syear,'year',1, 20, 5); print '</td>'; } - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { // Product Ref print '<td class="liste_titre left">'; print '<input class="flat maxwidth75" type="text" name="search_product_ref" value="'.dol_escape_htmltag($idproduct ? $product->ref : $search_product_ref).'">'; print '</td>'; } - if (!empty($arrayfields['p.label']['checked'])) - { + if (!empty($arrayfields['p.label']['checked'])) { // Product label print '<td class="liste_titre left">'; print '<input class="flat maxwidth100" type="text" name="search_product" value="'.dol_escape_htmltag($idproduct ? $product->label : $search_product).'">'; print '</td>'; } // Batch - if (!empty($arrayfields['m.batch']['checked'])) - { + if (!empty($arrayfields['m.batch']['checked'])) { print '<td class="liste_titre center"><input class="flat maxwidth75" type="text" name="search_batch" value="'.dol_escape_htmltag($search_batch).'"></td>'; } - if (!empty($arrayfields['pl.eatby']['checked'])) - { + if (!empty($arrayfields['pl.eatby']['checked'])) { print '<td class="liste_titre left">'; print '</td>'; } - if (!empty($arrayfields['pl.sellby']['checked'])) - { + if (!empty($arrayfields['pl.sellby']['checked'])) { print '<td class="liste_titre left">'; print '</td>'; } // Warehouse - if (!empty($arrayfields['e.ref']['checked'])) - { + if (!empty($arrayfields['e.ref']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone left">'; //print '<input class="flat" type="text" size="8" name="search_warehouse" value="'.($search_warehouse).'">'; print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print '</td>'; } - if (!empty($arrayfields['m.fk_user_author']['checked'])) - { + if (!empty($arrayfields['m.fk_user_author']['checked'])) { // Author print '<td class="liste_titre left">'; print '<input class="flat" type="text" size="6" name="search_user" value="'.dol_escape_htmltag($search_user).'">'; print '</td>'; } - if (!empty($arrayfields['m.inventorycode']['checked'])) - { + if (!empty($arrayfields['m.inventorycode']['checked'])) { // Inventory code print '<td class="liste_titre left">'; print '<input class="flat" type="text" size="4" name="search_inventorycode" value="'.dol_escape_htmltag($search_inventorycode).'">'; print '</td>'; } - if (!empty($arrayfields['m.label']['checked'])) - { + if (!empty($arrayfields['m.label']['checked'])) { // Label of movement print '<td class="liste_titre left">'; print '<input class="flat" type="text" size="8" name="search_movement" value="'.dol_escape_htmltag($search_movement).'">'; print '</td>'; } - if (!empty($arrayfields['m.type_mouvement']['checked'])) - { + if (!empty($arrayfields['m.type_mouvement']['checked'])) { // Type of movement print '<td class="liste_titre center">'; //print '<input class="flat" type="text" size="3" name="search_type_mouvement" value="'.dol_escape_htmltag($search_type_mouvement).'">'; @@ -607,22 +673,25 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print '</td>'; } - if (!empty($arrayfields['origin']['checked'])) - { + if (!empty($arrayfields['origin']['checked'])) { // Origin of movement print '<td class="liste_titre left">'; print '&nbsp; '; print '</td>'; } - if (!empty($arrayfields['m.value']['checked'])) - { + if (!empty($arrayfields['m.fk_projet']['checked'])) { + // fk_project + print '<td class="liste_titre" align="left">'; + print '&nbsp; '; + print '</td>'; + } + if (!empty($arrayfields['m.value']['checked'])) { // Qty print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_qty" value="'.dol_escape_htmltag($search_qty).'">'; print '</td>'; } - if (!empty($arrayfields['m.price']['checked'])) - { + if (!empty($arrayfields['m.price']['checked'])) { // Price print '<td class="liste_titre left">'; print '&nbsp; '; @@ -638,14 +707,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['m.datec']['checked'])) - { + if (!empty($arrayfields['m.datec']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Date modification - if (!empty($arrayfields['m.tms']['checked'])) - { + if (!empty($arrayfields['m.tms']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } @@ -657,38 +724,55 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print "</tr>\n"; print '<tr class="liste_titre">'; - if (!empty($arrayfields['m.rowid']['checked'])) + if (!empty($arrayfields['m.rowid']['checked'])) { print_liste_field_titre($arrayfields['m.rowid']['label'], $_SERVER["PHP_SELF"], 'm.rowid', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['m.datem']['checked'])) + } + if (!empty($arrayfields['m.datem']['checked'])) { print_liste_field_titre($arrayfields['m.datem']['label'], $_SERVER["PHP_SELF"], 'm.datem', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.ref']['checked'])) + } + if (!empty($arrayfields['p.ref']['checked'])) { print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], 'p.ref', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.label']['checked'])) + } + if (!empty($arrayfields['p.label']['checked'])) { print_liste_field_titre($arrayfields['p.label']['label'], $_SERVER["PHP_SELF"], 'p.label', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['m.batch']['checked'])) + } + if (!empty($arrayfields['m.batch']['checked'])) { print_liste_field_titre($arrayfields['m.batch']['label'], $_SERVER["PHP_SELF"], 'm.batch', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['pl.eatby']['checked'])) + } + if (!empty($arrayfields['pl.eatby']['checked'])) { print_liste_field_titre($arrayfields['pl.eatby']['label'], $_SERVER["PHP_SELF"], 'pl.eatby', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['pl.sellby']['checked'])) + } + if (!empty($arrayfields['pl.sellby']['checked'])) { print_liste_field_titre($arrayfields['pl.sellby']['label'], $_SERVER["PHP_SELF"], 'pl.sellby', '', $param, '', $sortfield, $sortorder, 'center '); + } if (!empty($arrayfields['e.ref']['checked'])) { // We are on a specific warehouse card, no filter on other should be possible print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, "", $sortfield, $sortorder); } - if (!empty($arrayfields['m.fk_user_author']['checked'])) + if (!empty($arrayfields['m.fk_user_author']['checked'])) { print_liste_field_titre($arrayfields['m.fk_user_author']['label'], $_SERVER["PHP_SELF"], "m.fk_user_author", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['m.inventorycode']['checked'])) + } + if (!empty($arrayfields['m.inventorycode']['checked'])) { print_liste_field_titre($arrayfields['m.inventorycode']['label'], $_SERVER["PHP_SELF"], "m.inventorycode", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['m.label']['checked'])) + } + if (!empty($arrayfields['m.label']['checked'])) { print_liste_field_titre($arrayfields['m.label']['label'], $_SERVER["PHP_SELF"], "m.label", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['m.type_mouvement']['checked'])) + } + if (!empty($arrayfields['m.type_mouvement']['checked'])) { print_liste_field_titre($arrayfields['m.type_mouvement']['label'], $_SERVER["PHP_SELF"], "m.type_mouvement", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['origin']['checked'])) + } + if (!empty($arrayfields['origin']['checked'])) { print_liste_field_titre($arrayfields['origin']['label'], $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['m.value']['checked'])) + } + if (!empty($arrayfields['m.fk_projet']['checked'])) { + print_liste_field_titre($arrayfields['m.fk_projet']['label'], $_SERVER["PHP_SELF"], "m.fk_projet", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['m.value']['checked'])) { print_liste_field_titre($arrayfields['m.value']['label'], $_SERVER["PHP_SELF"], "m.value", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['m.price']['checked'])) + } + if (!empty($arrayfields['m.price']['checked'])) { print_liste_field_titre($arrayfields['m.price']['label'], $_SERVER["PHP_SELF"], "m.price", "", $param, '', $sortfield, $sortorder, 'right '); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; @@ -763,21 +847,17 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } if (!empty($arrayfields['p.label']['checked'])) { // Product label - print '<td>'; - /* - * $productstatic->id=$objp->rowid; - * $productstatic->ref=$objp->produit; - * $productstatic->type=$objp->type; - * print $productstatic->getNomUrl(1,'',16); - */ + print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($productstatic->label).'">'; print $productstatic->label; print "</td>\n"; } if (!empty($arrayfields['m.batch']['checked'])) { print '<td class="center nowraponall">'; - if ($productlot->id > 0) + if ($productlot->id > 0) { print $productlot->getNomUrl(1); - else print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. + } else { + print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. + } print '</td>'; } if (!empty($arrayfields['pl.eatby']['checked'])) { @@ -808,7 +888,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } if (!empty($arrayfields['m.label']['checked'])) { // Label of movement - print '<td class="tdoverflowmax100aaa">'.$objp->label.'</td>'; + print '<td class="tdoverflowmax300" title="'.dol_escape_htmltag($objp->label).'">'.$objp->label.'</td>'; } if (!empty($arrayfields['m.type_mouvement']['checked'])) { // Type of movement @@ -831,33 +911,44 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Origin of movement print '<td class="nowraponall">'.$origin.'</td>'; } + if (!empty($arrayfields['m.fk_projet']['checked'])) { + // fk_project + print '<td>'; + if ($objp->fk_project != 0) { + print $movement->get_origin($objp->fk_project, 'project'); + } + print '</td>'; + } if (!empty($arrayfields['m.value']['checked'])) { // Qty print '<td class="right">'; - if ($objp->qt > 0) + if ($objp->qt > 0) { print '+'; + } print $objp->qty; print '</td>'; } if (!empty($arrayfields['m.price']['checked'])) { // Price print '<td class="right">'; - if ($objp->price != 0) + if ($objp->price != 0) { print price($objp->price); + } print '</td>'; } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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)) + if (in_array($obj->rowid, $arrayofselected)) { $selected = 1; + } print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) + if (!$i) { $totalarray['nbfield']++; + } print "</tr>\n"; $i++; diff --git a/htdocs/mrp/mo_note.php b/htdocs/mrp/mo_note.php index 564361c4b90..6bbfc503453 100644 --- a/htdocs/mrp/mo_note.php +++ b/htdocs/mrp/mo_note.php @@ -50,7 +50,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->mrp->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->mrp->multidir_output[$object->entity]."/".$object->id; +} // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); @@ -58,8 +60,7 @@ if ($id > 0 || !empty($ref)) $upload_dir = $conf->mrp->multidir_output[$object-> $isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0); $result = restrictedArea($user, 'mrp', $object->id, 'mrp_mo', '', 'fk_soc', 'rowid', $isdraft); -$permissionnote = 1; -//$permissionnote=$user->rights->mrp->creer; // Used by the include of actions_setnotes.inc.php +$permissionnote = $user->rights->mrp->write; // Used by the include of actions_setnotes.inc.php @@ -81,8 +82,7 @@ $formproject = new FormProjets($db); $help_url = ''; llxHeader('', $langs->trans('Mo'), $help_url); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = moPrepareHead($object); @@ -100,14 +100,13 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.(is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') + if ($permissiontoadd) { + if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; diff --git a/htdocs/mrp/mo_production.php b/htdocs/mrp/mo_production.php index c1b6fa64ec8..6f35f1f1a25 100644 --- a/htdocs/mrp/mo_production.php +++ b/htdocs/mrp/mo_production.php @@ -34,6 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; dol_include_once('/mrp/class/mo.class.php'); +dol_include_once('/bom/class/bom.class.php'); dol_include_once('/mrp/lib/mrp_mo.lib.php'); // Load translation files required by the page @@ -47,7 +48,7 @@ $confirm = GETPOST('confirm', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'mocard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); -//$lineid = GETPOST('lineid', 'int'); +$lineid = GETPOST('lineid', 'int'); $collapse = GETPOST('collapse', 'aZ09comma'); @@ -65,12 +66,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. @@ -88,6 +92,7 @@ $permissiontodelete = $user->rights->mrp->delete || ($permissiontoadd && isset($ $upload_dir = $conf->mrp->multidir_output[isset($object->entity) ? $object->entity : 1]; $permissiontoproduce = $permissiontoadd; +$permissiontoupdatecost = $user->rights->bom->read; // User who can define cost must have knowledge of pricing /* @@ -96,18 +101,22 @@ $permissiontoproduce = $permissiontoadd; $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 (empty($reshook)) { $error = 0; $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1); if (empty($backtopage) || ($cancel && empty($id))) { //var_dump($backurlforlist);exit; - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = DOL_URL_ROOT.'/mrp/mo_production.php?id='.($id > 0 ? $id : '__ID__'); + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = DOL_URL_ROOT.'/mrp/mo_production.php?id='.($id > 0 ? $id : '__ID__'); + } } $triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record @@ -129,12 +138,10 @@ if (empty($reshook)) // Action to move up and down lines of object //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - if ($action == 'set_thirdparty' && $permissiontoadd) - { + if ($action == 'set_thirdparty' && $permissiontoadd) { $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY'); } - if ($action == 'classin' && $permissiontoadd) - { + if ($action == 'classin' && $permissiontoadd) { $object->setProject(GETPOST('projectid', 'int')); } @@ -150,6 +157,7 @@ if (empty($reshook)) $moline->qty = GETPOST('qtytoadd', 'int'); ; $moline->fk_product = GETPOST('productidtoadd', 'int'); $moline->role = 'toconsume'; + $moline->origin_type = 'free'; // free consume line $moline->position = 0; $resultline = $moline->create($user, false); // Never use triggers here @@ -168,7 +176,7 @@ if (empty($reshook)) $codemovement = GETPOST('inventorycode', 'alphanohtml'); $db->begin(); - + $pos = 0; // Process line to consume foreach ($object->lines as $line) { if ($line->role == 'toconsume') { @@ -199,7 +207,11 @@ if (empty($reshook)) // Record stock movement $id_product_batch = 0; $stockmove->origin = $object; - $idstockmove = $stockmove->livraison($user, $line->fk_product, GETPOST('idwarehouse-'.$line->id.'-'.$i), $qtytoprocess, 0, $labelmovement, dol_now(), '', '', GETPOST('batch-'.$line->id.'-'.$i), $id_product_batch, $codemovement); + if ($qtytoprocess >= 0) { + $idstockmove = $stockmove->livraison($user, $line->fk_product, GETPOST('idwarehouse-'.$line->id.'-'.$i), $qtytoprocess, 0, $labelmovement, dol_now(), '', '', GETPOST('batch-'.$line->id.'-'.$i), $id_product_batch, $codemovement); + } else { + $idstockmove = $stockmove->reception($user, $line->fk_product, GETPOST('idwarehouse-'.$line->id.'-'.$i), $qtytoprocess, 0, $labelmovement, dol_now(), '', '', GETPOST('batch-'.$line->id.'-'.$i), $id_product_batch, $codemovement); + } if ($idstockmove < 0) { $error++; setEventMessages($stockmove->error, $stockmove->errors, 'errors'); @@ -207,7 +219,6 @@ if (empty($reshook)) } if (!$error) { - $pos = 0; // Record consumption $moline = new MoLine($db); $moline->fk_mo = $object->id; @@ -237,6 +248,7 @@ if (empty($reshook)) } // Process line to produce + $pos = 0; foreach ($object->lines as $line) { if ($line->role == 'toproduce') { $tmpproduct = new Product($db); @@ -245,6 +257,7 @@ if (empty($reshook)) $i = 1; while (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) { $qtytoprocess = price2num(GETPOST('qtytoproduce-'.$line->id.'-'.$i)); + $pricetoprocess = GETPOST('pricetoproduce-'.$line->id.'-'.$i) ? price2num(GETPOST('pricetoproduce-'.$line->id.'-'.$i)) : 0; if ($qtytoprocess != 0) { // Check warehouse is set if we should have to @@ -266,7 +279,7 @@ if (empty($reshook)) // Record stock movement $id_product_batch = 0; $stockmove->origin = $object; - $idstockmove = $stockmove->reception($user, $line->fk_product, GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i), $qtytoprocess, 0, $labelmovement, '', '', GETPOST('batchtoproduce-'.$line->id.'-'.$i), dol_now(), $id_product_batch, $codemovement); + $idstockmove = $stockmove->reception($user, $line->fk_product, GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i), $qtytoprocess, $pricetoprocess, $labelmovement, '', '', GETPOST('batchtoproduce-'.$line->id.'-'.$i), dol_now(), $id_product_batch, $codemovement); if ($idstockmove < 0) { $error++; setEventMessages($stockmove->error, $stockmove->errors, 'errors'); @@ -274,7 +287,6 @@ if (empty($reshook)) } if (!$error) { - $pos = 0; // Record production $moline = new MoLine($db); $moline->fk_mo = $object->id; @@ -364,18 +376,19 @@ if (empty($reshook)) } // Action close produced - if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) - { + if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) { $result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED'); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -402,13 +415,13 @@ $formproject = new FormProjets($db); $formproduct = new FormProduct($db); $tmpwarehouse = new Entrepot($db); $tmpbatch = new Productlot($db); +$tmpstockmovement = new MouvementStock($db); $help_url = 'EN:Module_Manufacturing_Orders|FR:Module_Ordres_de_Fabrication'; llxHeader('', $langs->trans('Mo'), $help_url, '', 0, 0, array('/mrp/js/lib_dispatch.js.php')); // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_thirdparty(); $res = $object->fetch_optionals(); @@ -419,13 +432,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $formconfirm = ''; // Confirmation to delete - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line - if ($action == 'deleteline') - { + if ($action == 'deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); } // Clone confirmation @@ -436,8 +447,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Confirmation of validation - if ($action == 'validate') - { + if ($action == 'validate') { // We check that object has a temporary ref $ref = substr($object->ref, 1, 4); if ($ref == 'PROV') { @@ -457,13 +467,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea }*/ $formquestion = array(); - if (!empty($conf->mrp->enabled)) - { + if (!empty($conf->mrp->enabled)) { $langs->load("mrp"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( // 'text' => $langs->trans("ConfirmClone"), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -477,8 +488,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -496,14 +510,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.(is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') + if ($permissiontoadd) { + if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; @@ -554,8 +567,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print dol_get_fiche_end(); - if (!in_array($action, array('consumeorproduce', 'consumeandproduceall'))) - { + if (!in_array($action, array('consumeorproduce', 'consumeandproduceall'))) { print '<div class="tabsAction">'; $parameters = array(); @@ -563,12 +575,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); if (empty($reshook)) { // Validate - if ($object->status == $object::STATUS_DRAFT) - { - if ($permissiontoadd) - { - if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) - { + if ($object->status == $object::STATUS_DRAFT) { + if ($permissiontoadd) { + if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=validate">'.$langs->trans("Validate").'</a>'; } else { $langs->load("errors"); @@ -600,10 +609,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Cancel - Reopen - if ($permissiontoadd) - { - if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS) - { + if ($permissiontoadd) { + if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS) { $arrayproduced = $object->fetchLinesLinked('produced', 0); $nbProduced = 0; foreach ($arrayproduced as $lineproduced) { @@ -618,8 +625,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_close&confirm=yes">'.$langs->trans("Cancel").'</a>'."\n"; } - if ($object->status == $object::STATUS_CANCELED) - { + if ($object->status == $object::STATUS_CANCELED) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes">'.$langs->trans("Re-Open").'</a>'."\n"; } @@ -636,8 +642,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '</div>'; } - if (in_array($action, array('consumeorproduce', 'consumeandproduceall', 'addconsumeline'))) - { + if (in_array($action, array('consumeorproduce', 'consumeandproduceall', 'addconsumeline'))) { print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="confirm_'.$action.'">'; @@ -651,8 +656,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $defaultstockmovementcode = GETPOST('inventorycode', 'alphanohtml') ? GETPOST('inventorycode', 'alphanohtml') : $langs->trans("ProductionForRef", $object->ref); print '<div class="center'.(in_array($action, array('consumeorproduce', 'consumeandproduceall')) ? ' formconsumeproduce' : '').'">'; - print '<span class="opacitymedium hideonsmartphone">'.$langs->trans("ConfirmProductionDesc", $langs->transnoentitiesnoconv("Confirm")).'<br></span>'; - print '<span class="fieldrequired">'.$langs->trans("InventoryCode").':</span> <input type="text" class="maxwidth200" name="inventorycode" value="'.$defaultstockmovementcode.'"> &nbsp; '; + print '<div class="opacitymedium hideonsmartphone paddingbottom">'.$langs->trans("ConfirmProductionDesc", $langs->transnoentitiesnoconv("Confirm")).'<br></div>'; + print '<span class="fieldrequired">'.$langs->trans("InventoryCode").':</span> <input type="text" class="minwidth200 maxwidth250" name="inventorycode" value="'.$defaultstockmovementcode.'"> &nbsp; '; print '<span class="clearbothonsmartphone"></span>'; print $langs->trans("MovementLabel").': <input type="text" class="minwidth300" name="inventorylabel" value="'.$defaultstockmovementlabel.'"><br><br>'; print '<input type="checkbox" id="autoclose" name="autoclose" value="1"'.(GETPOSTISSET('inventorylabel') ? (GETPOST('autoclose') ? ' checked="checked"' : '') : ' checked="checked"').'> <label for="autoclose">'.$langs->trans("AutoCloseMO").'</label><br>'; @@ -672,17 +677,27 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea */ $collapse = 1; - if (!empty($object->table_element_line)) - { + if (!empty($object->table_element_line)) { // Show object lines $object->fetchLines(); + $bomcost = 0; + if ($object->fk_bom > 0) { + $bom = new Bom($db); + $res = $bom->fetch($object->fk_bom); + if ($res > 0) { + $bomcost = $bom->unit_cost; + } + } + + // Lines to consume + print '<div class="fichecenter">'; print '<div class="fichehalfleft">'; print '<div class="clearboth"></div>'; $newlinetext = ''; - if ($action != 'consumeorproduce' && $action != 'consumeandproduceall') { + if ($object->status != $object::STATUS_PRODUCED && $object->status != $object::STATUS_CANCELED && $action != 'consumeorproduce' && $action != 'consumeandproduceall') { $newlinetext = '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=addconsumeline">'.$langs->trans("AddNewConsumeLines").'</a>'; } print load_fiche_titre($langs->trans('Consumption'), '', '', 0, '', '', $newlinetext); @@ -693,15 +708,25 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<tr class="liste_titre">'; print '<td>'.$langs->trans("Product").'</td>'; print '<td class="right">'.$langs->trans("Qty").'</td>'; + if ($permissiontoupdatecost && !empty($conf->global->MRP_SHOW_COST_FOR_CONSUMPTION)) { + print '<td class="right">'.$langs->trans("UnitCost").'</td>'; + } print '<td class="right">'.$langs->trans("QtyAlreadyConsumed").'</td>'; print '<td>'; - if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) print $langs->trans("Warehouse"); + if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) { + print $langs->trans("Warehouse"); + } print '</td>'; if ($conf->productbatch->enabled) { print '<td>'; - if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) print $langs->trans("Batch"); + if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) { + print $langs->trans("Batch"); + } print '</td>'; } + if ($permissiontodelete) { + print '<td></td>'; + } print '</tr>'; if ($action == 'addconsumeline') { @@ -711,6 +736,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print $form->select_produits('', 'productidtoadd', '', 0, 0, -1, 2, '', 0, array(), 0, '1', 0, 'maxwidth300'); print '</td>'; print '<td class="right"><input type="text" name="qtytoadd" value="1" class="width50 right"></td>'; + if ($permissiontoupdatecost && !empty($conf->global->MRP_SHOW_COST_FOR_CONSUMPTION)) { + print '<td></td>'; + } print '<td class="right"></td>'; print '<td>'; print '<input type="submit" class="button buttongen" name="addconsumelinebutton" value="'.$langs->trans("Add").'">'; @@ -723,8 +751,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Lines to consume - if (!empty($object->lines)) - { + if (!empty($object->lines)) { $nblinetoconsume = 0; foreach ($object->lines as $line) { if ($line->role == 'toconsume') { @@ -739,6 +766,29 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $tmpproduct = new Product($db); $tmpproduct->fetch($line->fk_product); + $linecost = price2num($tmpproduct->pmp, 'MT'); + + if ($line->origin_type == 'free' && $object->qty > 0) { + // add free consume line cost to bomcost + $costprice = price2num((!empty($tmpproduct->cost_price)) ? $tmpproduct->cost_price : $tmpproduct->pmp); + if (empty($costprice)) { + require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; + $productFournisseur = new ProductFournisseur($db); + if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) { + $costprice = $productFournisseur->fourn_unitprice; + } else { + $costprice = 0; + } + } + $linecost = price2num(($line->qty * $costprice) / $object->qty, 'MT'); + $bomcost += $linecost; + } elseif ($line->origin_id > 0 && $line->origin_type == 'bom' && $object->qty > 0) { + foreach ($bom->lines as $bomline) { + if ($bomline->id == $line->origin_id) { + $linecost = price2num(($line->qty * $bomline->unit_cost) / $object->qty, 'MT'); + } + } + } $arrayoflines = $object->fetchLinesLinked('consumed', $line->id); $alreadyconsumed = 0; @@ -752,14 +802,23 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '</td>'; print '<td class="right nowraponall">'; $help = ''; - if ($line->qty_frozen) $help .= ($help ? '<br>' : '').'<strong>'.$langs->trans("QuantityFrozen").'</strong>: '.yn(1).' ('.$langs->trans("QuantityConsumedInvariable").')'; - if ($line->disable_stock_change) $help .= ($help ? '<br>' : '').'<strong>'.$langs->trans("DisableStockChange").'</strong>: '.yn(1).' ('.(($tmpproduct->type == Product::TYPE_SERVICE && empty($conf->global->STOCK_SUPPORTS_SERVICES)) ? $langs->trans("NoStockChangeOnServices") : $langs->trans("DisableStockChangeHelp")).')'; + if ($line->qty_frozen) { + $help .= ($help ? '<br>' : '').'<strong>'.$langs->trans("QuantityFrozen").'</strong>: '.yn(1).' ('.$langs->trans("QuantityConsumedInvariable").')'; + } + if ($line->disable_stock_change) { + $help .= ($help ? '<br>' : '').'<strong>'.$langs->trans("DisableStockChange").'</strong>: '.yn(1).' ('.(($tmpproduct->type == Product::TYPE_SERVICE && empty($conf->global->STOCK_SUPPORTS_SERVICES)) ? $langs->trans("NoStockChangeOnServices") : $langs->trans("DisableStockChangeHelp")).')'; + } if ($help) { print $form->textwithpicto($line->qty, $help, -1); } else { print $line->qty; } print '</td>'; + if ($permissiontoupdatecost && !empty($conf->global->MRP_SHOW_COST_FOR_CONSUMPTION)) { + print '<td class="right nowraponall">'; + print price($linecost); + print '</td>'; + } print '<td class="right">'; if ($alreadyconsumed) { print '<script>'; @@ -774,9 +833,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea }); });'; print '</script>'; - if (empty($conf->use_javascript_ajax)) print '<a href="'.$_SERVER["PHP_SELF"].'?collapse='.$collapse.','.$line->id.'">'; + if (empty($conf->use_javascript_ajax)) { + print '<a href="'.$_SERVER["PHP_SELF"].'?collapse='.$collapse.','.$line->id.'">'; + } print img_picto($langs->trans("ShowDetails"), "chevron-down", 'id="expandtoproduce'.$line->id.'"'); - if (empty($conf->use_javascript_ajax)) print '</a>'; + if (empty($conf->use_javascript_ajax)) { + print '</a>'; + } } else { if ($nblinetoconsume == $nblinetoconsumecursor) { // If it is the last line print '<script>jQuery("#tablelines").removeClass("nobottom");</script>'; @@ -789,20 +852,38 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($conf->productbatch->enabled) { print '<td></td>'; // Lot } + if ($permissiontodelete) { + $href = $_SERVER["PHP_SELF"]; + $href .= '?id='.$object->id; + $href .= '&action=deleteline'; + $href .= '&lineid='.$line->id; + print '<td class="center">'; + print '<a href="'.$href.'">'; + print img_picto('', "delete"); + print '</a>'; + print '</td>'; + } print '</tr>'; // Show detailed of already consumed with js code to collapse foreach ($arrayoflines as $line2) { print '<tr class="expanddetail'.$line->id.' hideobject opacitylow">'; print '<td>'; - print dol_print_date($line2['date'], 'dayhour'); + $tmpstockmovement->id = $line2['fk_stock_movement']; + print '<a href="'.DOL_URL_ROOT.'/product/stock/movement_list.php?search_ref='.$tmpstockmovement->id.'">'.img_picto($langs->trans("StockMovement"), 'movement', 'class="paddingright"').'</a>'; + print dol_print_date($line2['date'], 'dayhour', 'tzuserrel'); print '</td>'; print '<td></td>'; print '<td class="right">'.$line2['qty'].'</td>'; + if ($permissiontoupdatecost && !empty($conf->global->MRP_SHOW_COST_FOR_CONSUMPTION)) { + print '<td></td>'; + } print '<td class="tdoverflowmax150">'; if ($line2['fk_warehouse'] > 0) { $result = $tmpwarehouse->fetch($line2['fk_warehouse']); - if ($result > 0) print $tmpwarehouse->getNomUrl(1); + if ($result > 0) { + print $tmpwarehouse->getNomUrl(1); + } } print '</td>'; // Lot Batch @@ -821,8 +902,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<tr>'; print '<td><span class="opacitymedium">'.$langs->trans("ToConsume").'</span></td>'; $preselected = (GETPOSTISSET('qty-'.$line->id.'-'.$i) ? GETPOST('qty-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyconsumed)); - if ($action == 'consumeorproduce' && !GETPOSTISSET('qty-'.$line->id.'-'.$i)) $preselected = 0; + if ($action == 'consumeorproduce' && !GETPOSTISSET('qty-'.$line->id.'-'.$i)) { + $preselected = 0; + } print '<td class="right"><input type="text" class="width50 right" name="qty-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>'; + if ($permissiontoupdatecost && !empty($conf->global->MRP_SHOW_COST_FOR_CONSUMPTION)) { + print '<td></td>'; + } print '<td></td>'; print '<td>'; if ($tmpproduct->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { @@ -851,9 +937,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } - print '</table>'; + print '</table>'; print '</div>'; + // Lines to produce print '</div>'; @@ -868,20 +955,30 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<tr class="liste_titre">'; print '<td>'.$langs->trans("Product").'</td>'; print '<td class="right">'.$langs->trans("Qty").'</td>'; + if ($permissiontoupdatecost) { + if (empty($bomcost)) { + print '<td class="right">'.$langs->trans("PMPValue").'</td>'; + } else { + print '<td class="right">'.$langs->trans("UnitCost").'</td>'; + } + } print '<td class="right">'.$langs->trans("QtyAlreadyProduced").'</td>'; print '<td>'; - if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) print $langs->trans("Warehouse"); + if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) { + print $langs->trans("Warehouse"); + } print '</td>'; if ($conf->productbatch->enabled) { print '<td>'; - if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) print $langs->trans("Batch"); + if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) { + print $langs->trans("Batch"); + } print '</td>'; print '<td></td>'; } print '</tr>'; - if (!empty($object->lines)) - { + if (!empty($object->lines)) { $nblinetoproduce = 0; foreach ($object->lines as $line) { if ($line->role == 'toproduce') { @@ -899,6 +996,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $tmpproduct = new Product($db); $tmpproduct->fetch($line->fk_product); + if (empty($bomcost)) { + $bomcost = $tmpproduct->pmp; + } + $arrayoflines = $object->fetchLinesLinked('produced', $line->id); $alreadyproduced = 0; foreach ($arrayoflines as $line2) { @@ -916,6 +1017,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<br><span class="opacitymedium small">'.$tmpproduct->label.'</span>'; print '</td>'; print '<td class="right">'.$line->qty.'</td>'; + if ($permissiontoupdatecost) { + print '<td class="right nowraponall">'; + print price($bomcost); + print '</td>'; + } print '<td class="right nowraponall">'; if ($alreadyproduced) { print '<script>'; @@ -930,9 +1036,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea }); });'; print '</script>'; - if (empty($conf->use_javascript_ajax)) print '<a href="'.$_SERVER["PHP_SELF"].'?collapse='.$collapse.','.$line->id.'">'; + if (empty($conf->use_javascript_ajax)) { + print '<a href="'.$_SERVER["PHP_SELF"].'?collapse='.$collapse.','.$line->id.'">'; + } print img_picto($langs->trans("ShowDetails"), "chevron-down", 'id="expandtoproduce'.$line->id.'"'); - if (empty($conf->use_javascript_ajax)) print '</a>'; + if (empty($conf->use_javascript_ajax)) { + print '</a>'; + } } print ' '.$alreadyproduced; print '</td>'; @@ -948,14 +1058,24 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea foreach ($arrayoflines as $line2) { print '<tr class="expanddetailtoproduce'.$line->id.' hideobject opacitylow">'; print '<td>'; - print dol_print_date($line2['date'], 'dayhour'); + $tmpstockmovement->id = $line2['fk_stock_movement']; + print '<a href="'.DOL_URL_ROOT.'/product/stock/movement_list.php?search_ref='.$tmpstockmovement->id.'">'.img_picto($langs->trans("StockMovement"), 'movement', 'class="paddingright"').'</a>'; + print dol_print_date($line2['date'], 'dayhour', 'tzuserrel'); print '</td>'; + // Qty print '<td></td>'; + // Cost price + if ($permissiontoupdatecost) { + print '<td></td>'; + } + // Qty already produced print '<td class="right">'.$line2['qty'].'</td>'; print '<td class="tdoverflowmax150">'; if ($line2['fk_warehouse'] > 0) { $result = $tmpwarehouse->fetch($line2['fk_warehouse']); - if ($result > 0) print $tmpwarehouse->getNomUrl(1); + if ($result > 0) { + print $tmpwarehouse->getNomUrl(1); + } } print '</td>'; if ($conf->productbatch->enabled) { @@ -975,8 +1095,18 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<tr name="batch_'.$line->id.'_'.$i.'">'; print '<td><span class="opacitymedium">'.$langs->trans("ToProduce").'</span></td>'; $preselected = (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i) ? GETPOST('qtytoproduce-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyproduced)); - if ($action == 'consumeorproduce' && !GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) $preselected = 0; + if ($action == 'consumeorproduce' && !GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) { + $preselected = 0; + } print '<td class="right"><input type="text" class="width50 right" id="qtytoproduce-'.$line->id.'-'.$i.'" name="qtytoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>'; + if ($permissiontoupdatecost) { + if ($tmpproduct->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $preselected = (GETPOSTISSET('pricetoproduce-'.$line->id.'-'.$i) ? GETPOST('pricetoproduce-'.$line->id.'-'.$i) : price($bomcost)); + print '<td class="right"><input type="text" class="width50 right" name="pricetoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>'; + } else { + print '<td><input type="hidden" class="width50 right" name="pricetoproduce-'.$line->id.'-'.$i.'" value="'.$bomcost.'"></td>'; + } + } print '<td></td>'; print '<td>'; if ($tmpproduct->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { @@ -993,6 +1123,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<input type="text" class="width50" name="batchtoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'">'; } print '</td>'; + // Batch number in same column than the stock movement picto print '<td>'; if ($tmpproduct->status_batch) { $type = 'batch'; @@ -1013,8 +1144,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '</div>'; } - if (in_array($action, array('consumeorproduce', 'consumeandproduceall', 'addconsumeline'))) - { + if (in_array($action, array('consumeorproduce', 'consumeandproduceall', 'addconsumeline'))) { print "</form>\n"; } } diff --git a/htdocs/mrp/tpl/originproductline.tpl.php b/htdocs/mrp/tpl/originproductline.tpl.php index 6f3b63f6d4e..75147a3c3f9 100644 --- a/htdocs/mrp/tpl/originproductline.tpl.php +++ b/htdocs/mrp/tpl/originproductline.tpl.php @@ -17,13 +17,14 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } -if (!is_object($form)) $form = new Form($db); +if (!is_object($form)) { + $form = new Form($db); +} $qtytoconsumeforline = $this->tpl['qty'] / $this->tpl['efficiency']; /*if ((empty($this->tpl['qty_frozen']) && $this->tpl['qty_bom'] > 1)) { @@ -43,7 +44,9 @@ print '<td class="center">'.($this->tpl['disable_stock_change'] ? yn($this->tpl[ //print '<td class="right">'.$this->tpl['efficiency'].'</td>'; $selected = 1; -if (!empty($selectedLines) && !in_array($this->tpl['id'], $selectedLines)) $selected = 0; +if (!empty($selectedLines) && !in_array($this->tpl['id'], $selectedLines)) { + $selected = 0; +} print '<td class="center">'; //print '<input id="cb'.$this->tpl['id'].'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$this->tpl['id'].'"'.($selected?' checked="checked"':'').'>'; print '</td>'; diff --git a/htdocs/multicurrency/class/multicurrency.class.php b/htdocs/multicurrency/class/multicurrency.class.php index bb4df7060e9..7886bd35774 100644 --- a/htdocs/multicurrency/class/multicurrency.class.php +++ b/htdocs/multicurrency/class/multicurrency.class.php @@ -121,14 +121,15 @@ class MultiCurrency extends CommonObject $error = 0; - if (self::checkCodeAlreadyExists($this->code)) - { + if (self::checkCodeAlreadyExists($this->code)) { $error++; $this->errors[] = $langs->trans('multicurrency_code_already_added'); return -1; } - if (empty($this->entity) || $this->entity <= 0) $this->entity = $conf->entity; + if (empty($this->entity) || $this->entity <= 0) { + $this->entity = $conf->entity; + } $now = date('Y-m-d H:i:s'); // Insert request @@ -163,7 +164,9 @@ class MultiCurrency extends CommonObject if ($trigger) { $result = $this->call_trigger('CURRENCY_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } } @@ -194,8 +197,11 @@ class MultiCurrency extends CommonObject $sql = 'SELECT'; $sql .= ' c.rowid, c.name, c.code, c.entity, c.date_create, c.fk_user'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' AS c'; - if (!empty($code)) $sql .= ' WHERE c.code = \''.$this->db->escape($code).'\' AND c.entity = '.$conf->entity; - else $sql .= ' WHERE c.rowid = '.$id; + if (!empty($code)) { + $sql .= ' WHERE c.code = \''.$this->db->escape($code).'\' AND c.entity = '.$conf->entity; + } else { + $sql .= ' WHERE c.rowid = '.((int) $id); + } dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); @@ -295,7 +301,7 @@ class MultiCurrency extends CommonObject $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET'; $sql .= ' name=\''.$this->db->escape($this->name).'\''; $sql .= ' code=\''.$this->db->escape($this->code).'\''; - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); $this->db->begin(); @@ -308,7 +314,9 @@ class MultiCurrency extends CommonObject if (!$error && $trigger) { $result = $this->call_trigger('CURRENCY_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } // Commit or rollback @@ -341,7 +349,9 @@ class MultiCurrency extends CommonObject if ($trigger) { $result = $this->call_trigger('CURRENCY_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } if (!$error) { @@ -353,7 +363,7 @@ class MultiCurrency extends CommonObject } $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); @@ -383,10 +393,8 @@ class MultiCurrency extends CommonObject */ public function deleteRates() { - foreach ($this->rates as &$rate) - { - if ($rate->delete() <= 0) - { + foreach ($this->rates as &$rate) { + if ($rate->delete() <= 0) { return false; } } @@ -402,11 +410,10 @@ class MultiCurrency extends CommonObject */ public function addRate($rate) { - $currencyRate = new CurrencyRate($this->db); + $currencyRate = new CurrencyRate($this->db); $currencyRate->rate = price2num($rate); - if ($currencyRate->create($this->id) > 0) - { + if ($currencyRate->create($this->id) > 0) { $this->rate = $currencyRate; return 1; } else { @@ -433,19 +440,20 @@ class MultiCurrency extends CommonObject $sql = 'SELECT label FROM '.MAIN_DB_PREFIX."c_currencies WHERE code_iso = '".$this->db->escape($code)."'"; - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $resql = $db->query($sql); - if ($resql && ($line = $db->fetch_object($resql))) - { + if ($resql && ($line = $db->fetch_object($resql))) { $currency->name = $line->label; } - if ($currency->create($user) > 0) - { + if ($currency->create($user) > 0) { $currency->addRate($rate); - if (!empty($line)) return 2; - else return 1; + if (!empty($line)) { + return 2; + } else { + return 1; + } } return -1; @@ -469,7 +477,7 @@ class MultiCurrency extends CommonObject */ public function getRate() { - $sql = 'SELECT cr.rowid'; + $sql = 'SELECT cr.rowid'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as cr'; $sql .= ' WHERE cr.fk_multicurrency = '.$this->id; $sql .= ' AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM '.MAIN_DB_PREFIX.$this->table_element_line.' AS cr2 WHERE cr2.fk_multicurrency = '.$this->id.')'; @@ -492,14 +500,17 @@ class MultiCurrency extends CommonObject */ public static function getIdFromCode($db, $code) { - global $conf; + global $conf; - $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX."multicurrency WHERE code = '".$db->escape($code)."' AND entity = ".$conf->entity; + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX."multicurrency WHERE code = '".$db->escape($code)."' AND entity = ".$conf->entity; - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $resql = $db->query($sql); - if ($resql && $obj = $db->fetch_object($resql)) return $obj->rowid; - else return 0; + if ($resql && $obj = $db->fetch_object($resql)) { + return $obj->rowid; + } else { + return 0; + } } /** @@ -516,7 +527,7 @@ class MultiCurrency extends CommonObject { global $conf; - $sql1 = 'SELECT m.rowid, mc.rate FROM '.MAIN_DB_PREFIX.'multicurrency m'; + $sql1 = 'SELECT m.rowid, mc.rate FROM '.MAIN_DB_PREFIX.'multicurrency m'; $sql1 .= ' LEFT JOIN '.MAIN_DB_PREFIX.'multicurrency_rate mc ON (m.rowid = mc.fk_multicurrency)'; $sql1 .= " WHERE m.code = '".$db->escape($code)."'"; @@ -531,12 +542,14 @@ class MultiCurrency extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $db->query($sql1.$sql2.$sql3); - if ($resql && $obj = $db->fetch_object($resql)) return array($obj->rowid, $obj->rate); - else { - if (!empty($conf->global->MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE)) - { + if ($resql && $obj = $db->fetch_object($resql)) { + return array($obj->rowid, $obj->rate); + } else { + if (!empty($conf->global->MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE)) { $resql = $db->query($sql1.$sql3); - if ($resql && $obj = $db->fetch_object($resql)) return array($obj->rowid, $obj->rate); + if ($resql && $obj = $db->fetch_object($resql)) { + return array($obj->rowid, $obj->rate); + } } return array(0, 1); @@ -556,11 +569,15 @@ class MultiCurrency extends CommonObject { $multicurrency_tx = self::getInvoiceRate($fk_facture, $table); - if ($multicurrency_tx) - { - if ($way == 'dolibarr') return price2num($amount * $multicurrency_tx, 'MU'); - else return price2num($amount / $multicurrency_tx, 'MU'); - } else return $amount; + if ($multicurrency_tx) { + if ($way == 'dolibarr') { + return price2num($amount * $multicurrency_tx, 'MU'); + } else { + return price2num($amount / $multicurrency_tx, 'MU'); + } + } else { + return $amount; + } } /** @@ -578,8 +595,7 @@ class MultiCurrency extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $db->query($sql); - if ($resql && ($line = $db->fetch_object($resql))) - { + if ($resql && ($line = $db->fetch_object($resql))) { return $line->multicurrency_tx; } @@ -597,14 +613,11 @@ class MultiCurrency extends CommonObject { global $conf; - if ($conf->currency != $conf->global->MULTICURRENCY_APP_SOURCE) - { + if ($conf->currency != $conf->global->MULTICURRENCY_APP_SOURCE) { $alternate_source = 'USD'.$conf->currency; - if (!empty($TRate->{$alternate_source})) - { + if (!empty($TRate->{$alternate_source})) { $coef = $TRate->USDUSD / $TRate->{$alternate_source}; - foreach ($TRate as $attr => &$rate) - { + foreach ($TRate as $attr => &$rate) { $rate *= $coef; } @@ -642,22 +655,17 @@ class MultiCurrency extends CommonObject $response = $resget['content']; $response = json_decode($response); - if ($response->success) - { + if ($response->success) { $TRate = $response->quotes; $timestamp = $response->timestamp; - if (self::recalculRates($TRate) >= 0) - { - foreach ($TRate as $currency_code => $rate) - { + if (self::recalculRates($TRate) >= 0) { + foreach ($TRate as $currency_code => $rate) { $code = substr($currency_code, 3, 3); $obj = new MultiCurrency($db); - if ($obj->fetch(null, $code) > 0) - { + if ($obj->fetch(null, $code) > 0) { $obj->updateRate($rate); - } elseif ($addifnotfound) - { + } elseif ($addifnotfound) { self::addRateFromDolibarr($code, $rate); } } @@ -681,11 +689,14 @@ class MultiCurrency extends CommonObject */ public static function checkCodeAlreadyExists($code) { - global $db; + global $db; - $currency = new MultiCurrency($db); - if ($currency->fetch('', $code) > 0) return true; - else return false; + $currency = new MultiCurrency($db); + if ($currency->fetch('', $code) > 0) { + return true; + } else { + return false; + } } } @@ -758,7 +769,9 @@ class CurrencyRate extends CommonObjectLine $error = 0; $this->rate = price2num($this->rate); - if (empty($this->entity) || $this->entity <= 0) $this->entity = $conf->entity; + if (empty($this->entity) || $this->entity <= 0) { + $this->entity = $conf->entity; + } $now = empty($this->date_sync) ? dol_now() : $this->date_sync; // Insert request @@ -791,7 +804,9 @@ class CurrencyRate extends CommonObjectLine if ($trigger) { $result = $this->call_trigger('CURRENCYRATE_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } } @@ -818,7 +833,7 @@ class CurrencyRate extends CommonObjectLine $sql = 'SELECT cr.rowid, cr.rate, cr.date_sync, cr.fk_multicurrency, cr.entity'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' AS cr'; - $sql .= ' WHERE cr.rowid = '.$id; + $sql .= ' WHERE cr.rowid = '.((int) $id); dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); @@ -867,9 +882,13 @@ class CurrencyRate extends CommonObjectLine // Update request $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET'; $sql .= ' rate='.$this->rate; - if (!empty($this->date_sync)) $sql .= ", date_sync='".$this->db->idate($this->date_sync)."'"; - if (!empty($this->fk_multicurrency)) $sql .= ', fk_multicurrency='.$this->fk_multicurrency; - $sql .= ' WHERE rowid='.$this->id; + if (!empty($this->date_sync)) { + $sql .= ", date_sync='".$this->db->idate($this->date_sync)."'"; + } + if (!empty($this->fk_multicurrency)) { + $sql .= ', fk_multicurrency='.$this->fk_multicurrency; + } + $sql .= ' WHERE rowid='.((int) $this->id); $this->db->begin(); @@ -883,7 +902,9 @@ class CurrencyRate extends CommonObjectLine if (!$error && $trigger) { $result = $this->call_trigger('CURRENCYRATE_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } // Commit or rollback @@ -916,12 +937,14 @@ class CurrencyRate extends CommonObjectLine if ($trigger) { $result = $this->call_trigger('CURRENCYRATE_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } if (!$error) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); diff --git a/htdocs/multicurrency/multicurrency_rate.php b/htdocs/multicurrency/multicurrency_rate.php index eae788b0587..da7921fa7fe 100644 --- a/htdocs/multicurrency/multicurrency_rate.php +++ b/htdocs/multicurrency/multicurrency_rate.php @@ -58,12 +58,18 @@ $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = (GETPOST("page", 'int') ?GETPOST("page", 'int') : 0); -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 = "cr.date_sync"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "cr.date_sync"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks @@ -74,7 +80,9 @@ $form = new Form($db); $hookmanager->initHooks(array('EditorRatelist', 'globallist')); -if (empty($action)) $action = 'list'; +if (empty($action)) { + $action = 'list'; +} // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -184,20 +192,24 @@ if ($action == "confirm_delete") { } -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) -{ +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 $sall = ""; $search_date_sync = ""; $search_rate = ""; @@ -324,10 +336,18 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // N $sql .= $hookmanager->resPrint; $sql .= ' FROM '.MAIN_DB_PREFIX.'multicurrency_rate as cr '; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."multicurrency AS m ON cr.fk_multicurrency = m.rowid"; -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if ($search_date_sync) $sql .= natural_search('cr.date_sync', $search_date_sync); -if ($search_rate) $sql .= natural_search('cr.rate', $search_rate); -if ($search_code) $sql .= natural_search('m.code', $search_code); +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} +if ($search_date_sync) { + $sql .= natural_search('cr.date_sync', $search_date_sync); +} +if ($search_rate) { + $sql .= natural_search('cr.rate', $search_rate); +} +if ($search_code) { + $sql .= natural_search('m.code', $search_code); +} $sql .= " WHERE m.code <> '".$db->escape($conf->currency)."'"; // Add where from hooks @@ -345,14 +365,12 @@ $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); if ($result) { $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -364,29 +382,46 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); $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 (!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_date_sync) $param = "&search_date_sync=".urlencode($search_date_sync); - if ($search_rate) $param = "&search_rate=".urlencode($search_rate); - if ($search_code != '') $param .= "&search_code=".urlencode($search_code); + if ($search_date_sync) { + $param = "&search_date_sync=".urlencode($search_date_sync); + } + if ($search_rate) { + $param = "&search_rate=".urlencode($search_rate); + } + if ($search_code != '') { + $param .= "&search_code=".urlencode($search_code); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; - if ($user->admin) $arrayofmassactions['predelete'] = $langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + if ($user->admin) { + $arrayofmassactions['predelete'] = $langs->trans("Delete"); + } + if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formulaire">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -399,9 +434,10 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } @@ -411,11 +447,13 @@ if ($resql) $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 ($moreforfilter) - { + if ($moreforfilter) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -423,7 +461,9 @@ if ($resql) $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 '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; @@ -432,22 +472,19 @@ if ($resql) print '<tr class="liste_titre_filter">'; // date - if (!empty($arrayfields['cr.date_sync']['checked'])) - { + if (!empty($arrayfields['cr.date_sync']['checked'])) { print '<td class="liste_titre" align="left">'; print '<input class="flat" type="text" name="search_date_sync" size="8" value="'.dol_escape_htmltag($search_date_sync).'">'; print '</td>'; } // code - if (!empty($arrayfields['m.code']['checked'])) - { + if (!empty($arrayfields['m.code']['checked'])) { print '<td class="liste_titre" align="left">'; print '<input class="flat" type="text" name="search_code" size="12" value="'.dol_escape_htmltag($search_code).'">'; print '</td>'; } // rate - if (!empty($arrayfields['cr.rate']['checked'])) - { + if (!empty($arrayfields['cr.rate']['checked'])) { print '<td class="liste_titre" align="left">'; print '<input class="flat" type="text" name="search_rate" size="8" value="'.dol_escape_htmltag($search_rate).'">'; print '</td>'; @@ -466,9 +503,15 @@ if ($resql) print '</tr>'; print '<tr class="liste_titre">'; - if (!empty($arrayfields['cr.date_sync']['checked'])) print_liste_field_titre($arrayfields['cr.date_sync']['label'], $_SERVER["PHP_SELF"], "cr.date_sync", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['m.code']['checked'])) print_liste_field_titre($arrayfields['m.code']['label'], $_SERVER["PHP_SELF"], "m.code", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['cr.rate']['checked'])) print_liste_field_titre($arrayfields['cr.rate']['label'], $_SERVER["PHP_SELF"], "cr.rate", "", $param, "", $sortfield, $sortorder); + if (!empty($arrayfields['cr.date_sync']['checked'])) { + print_liste_field_titre($arrayfields['cr.date_sync']['label'], $_SERVER["PHP_SELF"], "cr.date_sync", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['m.code']['checked'])) { + print_liste_field_titre($arrayfields['m.code']['label'], $_SERVER["PHP_SELF"], "m.code", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['cr.rate']['checked'])) { + print_liste_field_titre($arrayfields['cr.rate']['label'], $_SERVER["PHP_SELF"], "cr.rate", "", $param, "", $sortfield, $sortorder); + } // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); @@ -480,38 +523,40 @@ if ($resql) $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; // date_sync - if (!empty($arrayfields['cr.date_sync']['checked'])) - { + if (!empty($arrayfields['cr.date_sync']['checked'])) { print '<td class="tdoverflowmax200">'; print $obj->date_sync; print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // code - if (!empty($arrayfields['m.code']['checked'])) - { + if (!empty($arrayfields['m.code']['checked'])) { print '<td class="tdoverflowmax200">'; print $obj->code." ".$obj->name; print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // rate - if (!empty($arrayfields['cr.rate']['checked'])) - { + if (!empty($arrayfields['cr.rate']['checked'])) { print '<td class="tdoverflowmax200">'; print $obj->rate; print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Fields from hook @@ -521,16 +566,19 @@ if ($resql) // Action print '<td class="nowrap" align="center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '<a class="editfielda marginleftonly marginrightonly" href="'.$_SERVER["PHP_SELF"].'?action=updateRate&amp;id_rate='.$obj->rowid.'">'.img_picto('edit', 'edit').'</a>'; print '<a class="marginleftonly marginrightonly" href="'.$_SERVER["PHP_SELF"].'?action=deleteRate&amp;id_rate='.$obj->rowid.'">'.img_picto('delete', 'delete').'</a>'; print '<input id="cb'.$obj->rowid.'" class="flat checkforselect marginleftonly" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; $i++; @@ -542,8 +590,7 @@ if ($resql) print "</div>"; print '</form>'; -} -else { +} else { dol_print_error($db); } diff --git a/htdocs/opensurvey/card.php b/htdocs/opensurvey/card.php index ef583d08ff5..fd9fa3e0456 100644 --- a/htdocs/opensurvey/card.php +++ b/htdocs/opensurvey/card.php @@ -32,7 +32,9 @@ require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; // Security check -if (!$user->rights->opensurvey->read) accessforbidden(); +if (empty($user->rights->opensurvey->read)) { + accessforbidden(); +} // Initialisation des variables $action = GETPOST('action', 'aZ09'); @@ -62,17 +64,21 @@ $expiredate = dol_mktime(0, 0, 0, GETPOST('expiremonth'), GETPOST('expireday'), $parameters = array('id' => $numsondage); $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) $action = ''; +if (empty($reshook)) { + if ($cancel) { + $action = ''; + } // Delete - if ($action == 'delete_confirm') - { + if ($action == 'delete_confirm') { // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + if (!$user->rights->opensurvey->write) { + accessforbidden(); + } $result = $object->delete($user, '', $numsondage); @@ -81,36 +87,33 @@ if (empty($reshook)) } // Close - if ($action == 'close') - { + if ($action == 'close') { $object->status = Opensurveysondage::STATUS_CLOSED; $object->update($user); } // Reopend - if ($action == 'reopen') - { + if ($action == 'reopen') { $object->status = Opensurveysondage::STATUS_VALIDATED; $object->update($user); } // Update - if ($action == 'update') - { + if ($action == 'update') { // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + if (!$user->rights->opensurvey->write) { + accessforbidden(); + } $error = 0; - if (!GETPOST('nouveautitre')) - { + if (!GETPOST('nouveautitre')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); $error++; $action = 'edit'; } - if (!$error) - { + if (!$error) { $object->title = (string) GETPOST('nouveautitre', 'alphanohtml'); $object->description = (string) GETPOST('nouveauxcommentaires', 'restricthtml'); $object->mail_admin = (string) GETPOST('nouvelleadresse', 'alpha'); @@ -128,8 +131,7 @@ if (empty($reshook)) } // Add comment - if (GETPOST('ajoutcomment')) - { + if (GETPOST('ajoutcomment')) { $error = 0; if (!GETPOST('comment')) { @@ -147,8 +149,7 @@ if (empty($reshook)) $resql = $object->addComment($comment, $comment_user); - if (!$resql) - { + if (!$resql) { setEventMessages($langs->trans('ErrorInsertingComment'), null, 'errors'); } } @@ -156,17 +157,20 @@ if (empty($reshook)) // Delete comment $idcomment = GETPOST('deletecomment', 'int'); - if ($idcomment) - { + if ($idcomment) { // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + if (!$user->rights->opensurvey->write) { + accessforbidden(); + } $resql = $object->deleteComment($idcomment); } if ($action == 'edit') { // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + if (!$user->rights->opensurvey->write) { + accessforbidden(); + } } } @@ -177,8 +181,7 @@ if (empty($reshook)) $form = new Form($db); -if ($object->fk_user_creat) -{ +if ($object->fk_user_creat) { $userstatic = new User($db); $userstatic->fetch($object->fk_user_creat); } @@ -193,8 +196,7 @@ llxHeader('', $title, $helpurl, 0, 0, 0, $arrayofjs, $arrayofcss); // Define format of choices $toutsujet = explode(",", $object->sujet); $listofanswers = array(); -foreach ($toutsujet as $value) -{ +foreach ($toutsujet as $value) { $tmp = explode('@', $value); $listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox')); } @@ -232,16 +234,16 @@ print ' '.$langs->trans($type == 'classic' ? "TypeClassic" : "TypeDate").'</td>< print '<tr><td>'; $adresseadmin = $object->mail_admin; print $langs->trans("Title").'</td><td colspan="2">'; -if ($action == 'edit') -{ +if ($action == 'edit') { print '<input type="text" name="nouveautitre" style="width: 95%" value="'.dol_escape_htmltag(dol_htmlentities($object->title)).'">'; -} else print dol_htmlentities($object->title); +} else { + print dol_htmlentities($object->title); +} print '</td></tr>'; // Description print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td colspan="2">'; -if ($action == 'edit') -{ +if ($action == 'edit') { $doleditor = new DolEditor('nouveauxcommentaires', $object->description, '', 120, 'dolibarr_notes', 'In', 1, 1, 1, ROWS_7, '90%'); $doleditor->Create(0, ''); } else { @@ -253,17 +255,17 @@ print '</td></tr>'; //If linked user, then emails are going to be sent to users' email if (!$object->fk_user_creat) { print '<tr><td>'.$langs->trans("EMail").'</td><td colspan="2">'; - if ($action == 'edit') - { + if ($action == 'edit') { print '<input type="text" name="nouvelleadresse" class="minwith200" value="'.$object->mail_admin.'">'; - } else print dol_print_email($object->mail_admin, 0, 0, 1); + } else { + print dol_print_email($object->mail_admin, 0, 0, 1); + } print '</td></tr>'; } // Receive an email with each vote print '<tr><td>'.$langs->trans('ToReceiveEMailForEachVote').'</td><td colspan="2">'; -if ($action == 'edit') -{ +if ($action == 'edit') { print '<input type="checkbox" name="mailsonde" '.($object->mailsonde ? 'checked="checked"' : '').'">'; } else { print yn($object->mailsonde); @@ -279,26 +281,31 @@ print '</td></tr>'; // Users can comment print '<tr><td>'.$langs->trans('CanComment').'</td><td colspan="2">'; -if ($action == 'edit') -{ +if ($action == 'edit') { print '<input type="checkbox" name="cancomment" '.($object->allow_comments ? 'checked="checked"' : '').'">'; -} else print yn($object->allow_comments); +} else { + print yn($object->allow_comments); +} print '</td></tr>'; // Users can see others vote print '<tr><td>'.$langs->trans('CanSeeOthersVote').'</td><td colspan="2">'; -if ($action == 'edit') -{ +if ($action == 'edit') { print '<input type="checkbox" name="canseeothersvote" '.($object->allow_spy ? 'checked="checked"' : '').'">'; -} else print yn($object->allow_spy); +} else { + print yn($object->allow_spy); +} print '</td></tr>'; // Expire date print '<tr><td>'.$langs->trans('ExpireDate').'</td><td colspan="2">'; -if ($action == 'edit') print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0); -else { +if ($action == 'edit') { + print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0); +} else { print dol_print_date($object->date_fin, 'day'); - if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) print img_warning($langs->trans("Expired")); + if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) { + print img_warning($langs->trans("Expired")); + } } print '</td></tr>'; @@ -322,7 +329,9 @@ $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domai $url = $urlwithroot.'/public/opensurvey/studs.php?sondage='.$object->id_sondage; print '<input type="text" style="width: 60%" '.($action == 'edit' ? 'disabled' : '').' id="opensurveyurl" name="opensurveyurl" value="'.$url.'">'; -if ($action != 'edit') print ajax_autoselect("opensurveyurl", $url); +if ($action != 'edit') { + print ajax_autoselect("opensurveyurl", $url); +} print '</td></tr>'; @@ -332,8 +341,7 @@ print '</div>'; print dol_get_fiche_end(); -if ($action == 'edit') -{ +if ($action == 'edit') { print '<div class="center">'; print '<input type="submit" class="button button-save" name="save" value="'.dol_escape_htmltag($langs->trans("Save")).'">'; print ' &nbsp; '; @@ -346,7 +354,7 @@ print '</form>'."\n"; /* - * Barre d'actions + * Action bar */ print '<div class="tabsAction">'; @@ -354,13 +362,11 @@ if ($action != 'edit' && $user->rights->opensurvey->write) { //Modify button print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&id='.$numsondage.'">'.$langs->trans("Modify").'</a>'; - if ($object->status == Opensurveysondage::STATUS_VALIDATED) - { + if ($object->status == Opensurveysondage::STATUS_VALIDATED) { //Close button print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=close&id='.$numsondage.'">'.$langs->trans("Close").'</a>'; } - if ($object->status == Opensurveysondage::STATUS_CLOSED) - { + if ($object->status == Opensurveysondage::STATUS_CLOSED) { //Opened button print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=reopen&id='.$numsondage.'">'.$langs->trans("ReOpen").'</a>'; } @@ -371,8 +377,7 @@ if ($action != 'edit' && $user->rights->opensurvey->write) { print '</div>'; -if ($action == 'delete') -{ +if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"].'?&id='.$numsondage, $langs->trans("RemovePoll"), $langs->trans("ConfirmRemovalOfPoll", $id), 'delete_confirm', '', '', 1); } diff --git a/htdocs/opensurvey/class/opensurveysondage.class.php b/htdocs/opensurvey/class/opensurveysondage.class.php index c635c2430a7..badb3f60149 100644 --- a/htdocs/opensurvey/class/opensurveysondage.class.php +++ b/htdocs/opensurvey/class/opensurveysondage.class.php @@ -175,7 +175,7 @@ class Opensurveysondage extends CommonObject $sql .= "allow_comments,"; $sql .= "allow_spy,"; $sql .= "sujet,"; - $sql .= "entity"; + $sql .= "entity"; $sql .= ") VALUES ("; $sql .= "'".$this->db->escape($this->id_sondage)."',"; $sql .= " ".(empty($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").","; @@ -188,21 +188,25 @@ class Opensurveysondage extends CommonObject $sql .= " ".((int) $this->allow_comments).","; $sql .= " ".((int) $this->allow_spy).","; $sql .= " '".$this->db->escape($this->sujet)."',"; - $sql .= " ".((int) $conf->entity); + $sql .= " ".((int) $conf->entity); $sql .= ")"; $this->db->begin(); dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } if (!$error && !$notrigger) { global $langs, $conf; // Call trigger $result = $this->call_trigger('OPENSURVEY_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -250,10 +254,8 @@ class Opensurveysondage extends CommonObject dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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_sondage = $obj->id_sondage; @@ -336,15 +338,15 @@ class Opensurveysondage extends CommonObject if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('OPENSURVEY_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -369,8 +371,7 @@ class Opensurveysondage extends CommonObject global $conf, $langs; $error = 0; - if (empty($numsondage)) - { + if (empty($numsondage)) { $numsondage = $this->id_sondage; } @@ -379,12 +380,13 @@ class Opensurveysondage extends CommonObject if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('OPENSURVEY_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_comments WHERE id_sondage = '".$this->db->escape($numsondage)."'"; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); @@ -397,14 +399,14 @@ class Opensurveysondage extends CommonObject dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -431,7 +433,9 @@ class Opensurveysondage extends CommonObject global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -444,14 +448,16 @@ class Opensurveysondage extends CommonObject // 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'; + } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowMyObject"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -466,8 +472,12 @@ class Opensurveysondage extends CommonObject $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; return $result; @@ -488,19 +498,19 @@ class Opensurveysondage extends CommonObject $sql .= " WHERE id_sondage = '".$this->db->escape($this->id_sondage)."'"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $tmp = array('id_users'=>$obj->id_users, 'nom'=>$obj->name, 'reponses'=>$obj->reponses); $ret[] = $tmp; $i++; } - } else dol_print_error($this->db); + } else { + dol_print_error($this->db); + } $this->lines = $ret; @@ -543,14 +553,11 @@ class Opensurveysondage extends CommonObject $sql .= " ORDER BY id_comment"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_rows = $this->db->num_rows($resql); - if ($num_rows > 0) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($num_rows > 0) { + while ($obj = $this->db->fetch_object($resql)) { $comments[] = $obj; } } @@ -642,8 +649,7 @@ class Opensurveysondage extends CommonObject // phpcs:enable global $langs, $conf; - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); @@ -656,10 +662,15 @@ class Opensurveysondage extends CommonObject $statusType = 'status'.$status; if ($status == self::STATUS_VALIDATED) { - if (0) $statusType = 'status1'; - else $statusType = 'status4'; + if (0) { + $statusType = 'status1'; + } else { + $statusType = 'status4'; + } + } + if ($status == self::STATUS_CLOSED) { + $statusType = 'status6'; } - if ($status == self::STATUS_CLOSED) $statusType = 'status6'; return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } diff --git a/htdocs/opensurvey/exportcsv.php b/htdocs/opensurvey/exportcsv.php index 6f9a699273b..76e4ffd9023 100644 --- a/htdocs/opensurvey/exportcsv.php +++ b/htdocs/opensurvey/exportcsv.php @@ -30,14 +30,20 @@ require_once DOL_DOCUMENT_ROOT."/opensurvey/class/opensurveysondage.class.php"; $action = GETPOST('action', 'aZ09'); $numsondage = ''; -if (GETPOST('id')) -{ +if (GETPOST('id')) { $numsondage = GETPOST("id", 'alpha'); } $object = new Opensurveysondage($db); $result = $object->fetch(0, $numsondage); -if ($result <= 0) dol_print_error('', 'Failed to get survey id '.$numsondage); +if ($result <= 0) { + dol_print_error('', 'Failed to get survey id '.$numsondage); +} + +// Security check +if (empty($user->rights->opensurvey->read)) { + accessforbidden(); +} /* @@ -57,10 +63,8 @@ $toutsujet = explode(",", $object->sujet); // affichage des sujets du sondage $input .= $langs->trans("Name").";"; -for ($i = 0; $toutsujet[$i]; $i++) -{ - if ($object->format == "D") - { +for ($i = 0; $toutsujet[$i]; $i++) { + if ($object->format == "D") { $input .= ''.dol_print_date($toutsujet[$i], 'dayhour').';'; } else { $input .= ''.$toutsujet[$i].';'; @@ -69,11 +73,9 @@ for ($i = 0; $toutsujet[$i]; $i++) $input .= "\r\n"; -if (strpos($object->sujet, '@') !== false) -{ +if (strpos($object->sujet, '@') !== false) { $input .= ";"; - for ($i = 0; $toutsujet[$i]; $i++) - { + for ($i = 0; $toutsujet[$i]; $i++) { $heures = explode("@", $toutsujet[$i]); $input .= ''.$heures[1].';'; } @@ -87,12 +89,10 @@ $sql .= ' FROM '.MAIN_DB_PREFIX."opensurvey_user_studs"; $sql .= " WHERE id_sondage='".$db->escape($numsondage)."'"; $sql .= " ORDER BY id_users"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); // Le name de l'utilisateur @@ -101,15 +101,12 @@ if ($resql) //affichage des resultats $ensemblereponses = $obj->reponses; - for ($k = 0; $k < $nbcolonnes; $k++) - { + for ($k = 0; $k < $nbcolonnes; $k++) { $car = substr($ensemblereponses, $k, 1); - if ($car == "1") - { + if ($car == "1") { $input .= 'OK;'; $somme[$k]++; - } elseif ($car == "2") - { + } elseif ($car == "2") { $input .= 'KO;'; $somme[$k]++; } else { @@ -120,7 +117,9 @@ if ($resql) $input .= "\r\n"; $i++; } -} else dol_print_error($db); +} else { + dol_print_error($db); +} $filesize = strlen($input); diff --git a/htdocs/opensurvey/fonctions.php b/htdocs/opensurvey/fonctions.php index 0ea701ebf0b..7114dd5119f 100644 --- a/htdocs/opensurvey/fonctions.php +++ b/htdocs/opensurvey/fonctions.php @@ -31,7 +31,6 @@ */ function opensurvey_prepare_head(Opensurveysondage $object) { - global $langs, $conf; $h = 0; @@ -96,19 +95,16 @@ function llxHeaderSurvey($title, $head = "", $disablejs = 0, $disablehead = 0, $ // Define urllogo $urllogo = ''; $urllogofull = ''; - if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) - { + if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); - } elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) - { + } elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); } // Output html code for logo - if ($urllogo) - { + if ($urllogo) { print '<div class="backgreypublicpayment">'; print '<div class="logopublicpayment">'; print '<img id="dolpaymentlogo" src="'.$urllogo.'"'; diff --git a/htdocs/opensurvey/index.php b/htdocs/opensurvey/index.php index 50198e5202f..ba608723816 100644 --- a/htdocs/opensurvey/index.php +++ b/htdocs/opensurvey/index.php @@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; $langs->load("opensurvey"); // Security check -if (!$user->rights->opensurvey->read) accessforbidden(); +if (empty($user->rights->opensurvey->read)) { + accessforbidden(); +} $hookmanager = new HookManager($db); @@ -48,11 +50,12 @@ $sql = 'SELECT COUNT(*) as nb'; $sql .= ' FROM '.MAIN_DB_PREFIX.'opensurvey_sondage'; $sql .= ' WHERE entity IN ('.getEntity('survey').')'; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $obj = $db->fetch_object($resql); $nbsondages = $obj->nb; -} else dol_print_error($db, ''); +} else { + dol_print_error($db, ''); +} $title = $langs->trans("OpenSurveyArea"); diff --git a/htdocs/opensurvey/list.php b/htdocs/opensurvey/list.php index eaee1b696e1..56036b51aec 100644 --- a/htdocs/opensurvey/list.php +++ b/htdocs/opensurvey/list.php @@ -50,7 +50,9 @@ $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; @@ -67,24 +69,29 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "p.date_fin"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "p.date_fin"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} // Security check -if (!$user->rights->opensurvey->read) accessforbidden(); +if (!$user->rights->opensurvey->read) { + accessforbidden(); +} // Definition of fields for list $arrayfields = array(); -foreach ($arrayfields as $key => $val) -{ +foreach ($arrayfields as $key => $val) { // If $val['visible']==0, then we never show the field - if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); + if (!empty($val['visible'])) { + $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); + } } // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], @@ -107,21 +114,25 @@ $permissiontodelete = $user->rights->opensurvey->delete; * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_status = ''; $search_title = ''; $search_ref = ''; @@ -129,8 +140,7 @@ if (empty($reshook)) $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -160,11 +170,21 @@ $sql .= " u.login, u.firstname, u.lastname"; $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user u ON u.rowid = p.fk_user_creat"; $sql .= " WHERE p.entity IN (".getEntity('survey').")"; -if ($search_status != '-1' && $search_status != '') $sql .= natural_search("p.status", $search_status, 2); -if ($search_expired == 'expired') $sql .= " AND p.date_fin < '".$db->idate($now)."'"; -if ($search_expired == 'opened') $sql .= " AND p.date_fin >= '".$db->idate($now)."'"; -if ($search_ref) $sql .= natural_search("p.id_sondage", $search_ref); -if ($search_title) $sql .= natural_search("p.titre", $search_title); +if ($search_status != '-1' && $search_status != '') { + $sql .= natural_search("p.status", $search_status, 2); +} +if ($search_expired == 'expired') { + $sql .= " AND p.date_fin < '".$db->idate($now)."'"; +} +if ($search_expired == 'opened') { + $sql .= " AND p.date_fin >= '".$db->idate($now)."'"; +} +if ($search_ref) { + $sql .= natural_search("p.id_sondage", $search_ref); +} +if ($search_title) { + $sql .= natural_search("p.titre", $search_title); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -176,26 +196,22 @@ $sql .= $db->order($sortfield, $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; } @@ -204,8 +220,7 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".dol_buildpath('/opensurvey/card.php', 1).'?id='.$id); @@ -221,11 +236,17 @@ llxHeader('', $title, $help_url); $arrayofselected = is_array($toselect) ? $toselect : array(); $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); +} $fieldtosortuser = empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 'firstname' : 'lastname'; -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'; @@ -234,15 +255,21 @@ $arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($permissiontodelete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); // List of surveys into database print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -261,9 +288,10 @@ $objecttmp = new Opensurveysondage($db); $trackid = 'surv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($sall) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } @@ -274,11 +302,13 @@ $moreforfilter.= '</div>';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -346,18 +376,21 @@ print '</tr>'."\n"; // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < min($num, $limit)) -{ +$totalarray['nbfield'] = 0; +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } $sql2 = 'select COUNT(*) as nb from '.MAIN_DB_PREFIX."opensurvey_user_studs where id_sondage='".$db->escape($obj->rowid)."'"; $resql2 = $db->query($sql2); - if ($resql2) - { + if ($resql2) { $obj2 = $db->fetch_object($resql2); $nbuser = $obj2->nb; - } else dol_print_error($db); + } else { + dol_print_error($db); + } $opensurvey_static->id = $obj->rowid; $opensurvey_static->ref = $obj->rowid; @@ -372,11 +405,15 @@ while ($i < min($num, $limit)) print '<td>'; print $opensurvey_static->getNomUrl(1); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } // Title print '<td>'.dol_htmlentities($obj->title).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } // Type print '<td>'; @@ -384,7 +421,9 @@ while ($i < min($num, $limit)) print img_picto('', dol_buildpath('/opensurvey/img/'.($type == 'classic' ? 'chart-32.png' : 'calendar-32.png'), 1), 'width="16"', 1); print ' '.$langs->trans($type == 'classic' ? "TypeClassic" : "TypeDate"); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '<td>'; // Author @@ -400,23 +439,35 @@ while ($i < min($num, $limit)) print dol_htmlentities($obj->nom_admin); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } // Nb of voters print'<td class="right">'.$nbuser.'</td>'."\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '<td class="center">'.dol_print_date($db->jdate($obj->date_fin), 'day'); - if ($db->jdate($obj->date_fin) < $now && $obj->status == Opensurveysondage::STATUS_VALIDATED) { print img_warning($langs->trans("Expired")); } + if ($db->jdate($obj->date_fin) < $now && $obj->status == Opensurveysondage::STATUS_VALIDATED) { + print img_warning($langs->trans("Expired")); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '<td class="center">'.dol_print_date($db->jdate($obj->tms), 'dayhour'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '<td class="center">'.$opensurvey_static->getLibStatut(5).'</td>'."\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; @@ -426,14 +477,17 @@ while ($i < min($num, $limit)) print $hookmanager->resPrint; // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'."\n"; $i++; @@ -444,10 +498,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +if ($num == 0) { $colspan = 8; - foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } @@ -463,10 +520,11 @@ print '</div>'."\n"; print '</form>'."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/opensurvey/results.php b/htdocs/opensurvey/results.php index ea07900ba67..ede66c3e022 100644 --- a/htdocs/opensurvey/results.php +++ b/htdocs/opensurvey/results.php @@ -29,10 +29,10 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; require_once DOL_DOCUMENT_ROOT."/opensurvey/class/opensurveysondage.class.php"; require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; - // Security check -if (!$user->rights->opensurvey->read) accessforbidden(); - +if (empty($user->rights->opensurvey->read)) { + accessforbidden(); +} // Init vars $action = GETPOST('action', 'aZ09'); @@ -40,7 +40,9 @@ $numsondage = GETPOST("id"); $object = new Opensurveysondage($db); $result = $object->fetch(0, $numsondage); -if ($result <= 0) dol_print_error('', 'Failed to get survey id '.$numsondage); +if ($result <= 0) { + dol_print_error('', 'Failed to get survey id '.$numsondage); +} $nblines = $object->fetch_lines(); @@ -58,20 +60,15 @@ if (GETPOST('retoursondage')) { $nbcolonnes = substr_count($object->sujet, ',') + 1; // Add vote -if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // boutonp for chrome, boutonp.x for firefox -{ - if (GETPOST('nom')) - { +if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) { // boutonp for chrome, boutonp.x for firefox + if (GETPOST('nom')) { $erreur_prenom = false; $nouveauchoix = ''; - for ($i = 0; $i < $nbcolonnes; $i++) - { - if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1') - { + for ($i = 0; $i < $nbcolonnes; $i++) { + if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1') { $nouveauchoix .= "1"; - } elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') - { + } elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') { $nouveauchoix .= "2"; } else { // sinon c'est 0 $nouveauchoix .= "0"; @@ -87,15 +84,16 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout $sql .= ' ORDER BY id_users'; $resql = $db->query($sql); $num_rows = $db->num_rows($resql); - if ($num_rows > 0) - { + if ($num_rows > 0) { setEventMessages($langs->trans("VoteNameAlreadyExists"), null, 'errors'); $error++; } else { $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'opensurvey_user_studs (nom, id_sondage, reponses)'; $sql .= " VALUES ('".$db->escape($nom)."', '".$db->escape($numsondage)."','".$db->escape($nouveauchoix)."')"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } } } } @@ -104,35 +102,30 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout $testmodifier = false; $testligneamodifier = false; $ligneamodifier = -1; -for ($i = 0; $i < $nblines; $i++) -{ - if (isset($_POST['modifierligne'.$i])) - { +for ($i = 0; $i < $nblines; $i++) { + if (isset($_POST['modifierligne'.$i])) { $ligneamodifier = $i; $testligneamodifier = true; } //test pour voir si une ligne est a modifier - if (isset($_POST['validermodifier'.$i])) - { + if (isset($_POST['validermodifier'.$i])) { $modifier = $i; $testmodifier = true; } } -if ($testmodifier) -{ +if ($testmodifier) { // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + if (!$user->rights->opensurvey->write) { + accessforbidden(); + } $nouveauchoix = ''; - for ($i = 0; $i < $nbcolonnes; $i++) - { + for ($i = 0; $i < $nbcolonnes; $i++) { //var_dump($_POST["choix$i"]); - if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1') - { + if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1') { $nouveauchoix .= "1"; - } elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') - { + } elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') { $nouveauchoix .= "2"; } else { // sinon c'est 0 $nouveauchoix .= "0"; @@ -145,14 +138,17 @@ if ($testmodifier) $sql .= " WHERE id_users = '".$db->escape($idtomodify)."'"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } } // Add column (not for date) -if (GETPOST("ajoutercolonne") && GETPOST('nouvellecolonne') && $object->format == "A") -{ +if (GETPOST("ajoutercolonne") && GETPOST('nouvellecolonne') && $object->format == "A") { // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + if (!$user->rights->opensurvey->write) { + accessforbidden(); + } $nouveauxsujets = $object->sujet; @@ -165,17 +161,19 @@ if (GETPOST("ajoutercolonne") && GETPOST('nouvellecolonne') && $object->format = $sql .= " SET sujet = '".$db->escape($nouveauxsujets)."'"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); - else { + if (!$resql) { + dol_print_error($db); + } else { header('Location: results.php?id='.$object->id_sondage); } } // Add column (with format date) -if (isset($_POST["ajoutercolonne"]) && $object->format == "D") -{ +if (isset($_POST["ajoutercolonne"]) && $object->format == "D") { // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + if (!$user->rights->opensurvey->write) { + accessforbidden(); + } $nouveauxsujets = $object->sujet; @@ -223,8 +221,7 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D") $cleinsertion = count($datesbase); } else { $nbdatesbase = count($datesbase); - for ($i = 0; $i < $nbdatesbase; $i++) - { + for ($i = 0; $i < $nbdatesbase; $i++) { $j = $i + 1; if ($nouvelledate > $datesbase[$i] && $nouvelledate < $datesbase[$j]) { $cleinsertion = $j; @@ -244,14 +241,14 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D") $dateinsertion = substr("$dateinsertion", 1); // update with new topics into database - if (isset($erreur_ajout_date) && empty($erreur_ajout_date)) - { + if (isset($erreur_ajout_date) && empty($erreur_ajout_date)) { $sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage"; $sql .= " SET sujet = '".$db->escape($dateinsertion)."'"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); - else { + if (!$resql) { + dol_print_error($db); + } else { header('Location: results.php?id='.$object->id_sondage); } } @@ -263,12 +260,12 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D") } // Delete line -for ($i = 0; $i < $nblines; $i++) -{ - if (GETPOST("effaceligne".$i) || GETPOST("effaceligne".$i."_x") || GETPOST("effaceligne".$i.".x")) // effacelignei for chrome, effacelignei_x for firefox - { +for ($i = 0; $i < $nblines; $i++) { + if (GETPOST("effaceligne".$i) || GETPOST("effaceligne".$i."_x") || GETPOST("effaceligne".$i.".x")) { // effacelignei for chrome, effacelignei_x for firefox // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + if (!$user->rights->opensurvey->write) { + accessforbidden(); + } $compteur = 0; @@ -278,14 +275,14 @@ for ($i = 0; $i < $nblines; $i++) $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $num = $db->num_rows($resql); - while ($compteur < $num) - { + while ($compteur < $num) { $obj = $db->fetch_object($resql); - if ($compteur == $i) - { + if ($compteur == $i) { $sql2 = 'DELETE FROM '.MAIN_DB_PREFIX.'opensurvey_user_studs'; $sql2 .= ' WHERE id_users = '.$db->escape($obj->id_users); $resql2 = $db->query($sql2); @@ -297,13 +294,13 @@ for ($i = 0; $i < $nblines; $i++) } // Delete column -for ($i = 0; $i < $nbcolonnes; $i++) -{ +for ($i = 0; $i < $nbcolonnes; $i++) { if ((GETPOST("effacecolonne".$i) || GETPOST("effacecolonne".$i."_x") || GETPOST("effacecolonne".$i.".x")) - && $nbcolonnes > 1) // effacecolonnei for chrome, effacecolonnei_x for firefox - { + && $nbcolonnes > 1) { // effacecolonnei for chrome, effacecolonnei_x for firefox // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + if (!$user->rights->opensurvey->write) { + accessforbidden(); + } $db->begin(); @@ -312,12 +309,12 @@ for ($i = 0; $i < $nbcolonnes; $i++) $nouveauxsujets = ''; //parcours de tous les sujets actuels - while (isset($toutsujet[$j])) - { + while (isset($toutsujet[$j])) { //si le sujet n'est pas celui qui a été effacé alors on concatene - if ($i != $j) - { - if (!empty($nouveauxsujets)) $nouveauxsujets .= ','; + if ($i != $j) { + if (!empty($nouveauxsujets)) { + $nouveauxsujets .= ','; + } $nouveauxsujets .= $toutsujet[$j]; } @@ -328,7 +325,9 @@ for ($i = 0; $i < $nbcolonnes; $i++) $sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage"; $sql .= " SET sujet = '".$db->escape($nouveauxsujets)."' WHERE id_sondage = '".$db->escape($numsondage)."'"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } // Clean current answer to remove deleted columns $compteur = 0; @@ -337,22 +336,19 @@ for ($i = 0; $i < $nbcolonnes; $i++) $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; dol_syslog('sql='.$sql); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } $num = $db->num_rows($resql); - while ($compteur < $num) - { + while ($compteur < $num) { $obj = $db->fetch_object($resql); $newcar = ''; $ensemblereponses = $obj->reponses; // parcours de toutes les réponses actuelles - for ($j = 0; $j < $nbcolonnes; $j++) - { + for ($j = 0; $j < $nbcolonnes; $j++) { $car = substr($ensemblereponses, $j, 1); //si les reponses ne concerne pas la colonne effacée, on concatene if ($i != $j) { @@ -389,8 +385,7 @@ if ($object->fk_user_creat) { } $result = $object->fetch(0, $numsondage); -if ($result <= 0) -{ +if ($result <= 0) { dol_print_error($db, $object->error); exit; } @@ -405,8 +400,7 @@ llxHeader('', $title, $helpurl, 0, 0, 0, $arrayofjs, $arrayofcss); // Define format of choices $toutsujet = explode(",", $object->sujet); $listofanswers = array(); -foreach ($toutsujet as $value) -{ +foreach ($toutsujet as $value) { $tmp = explode('@', $value); $listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox')); } @@ -452,10 +446,13 @@ print '</td></tr>'; // Expire date print '<tr><td>'.$langs->trans('ExpireDate').'</td><td colspan="2">'; -if ($action == 'edit') print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0); -else { +if ($action == 'edit') { + print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0); +} else { print dol_print_date($object->date_fin, 'day'); - if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) print img_warning($langs->trans("Expired")); + if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) { + print img_warning($langs->trans("Expired")); + } } print '</td></tr>'; @@ -480,8 +477,7 @@ $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domai $url = $urlwithouturlroot.dol_buildpath('/public/opensurvey/studs.php', 1).'?sondage='.$object->id_sondage; $urllink = '<input type="text" style="width: 60%" '.($action == 'edit' ? 'disabled' : '').' id="opensurveyurl" name="opensurveyurl" value="'.$url.'">'; print $urllink; -if ($action != 'edit') -{ +if ($action != 'edit') { print '<script type="text/javascript"> jQuery(document).ready(function () { jQuery("#opensurveyurl").click(function() { jQuery(this).select(); } ); @@ -511,10 +507,11 @@ print '</div>'; // Show form to add a new field/column -if (GETPOST('ajoutsujet')) -{ +if (GETPOST('ajoutsujet')) { // Security check - if (!$user->rights->opensurvey->write) accessforbidden(); + if (!$user->rights->opensurvey->write) { + accessforbidden(); + } print '<form name="formulaire" action="" method="POST">'."\n"; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -524,8 +521,7 @@ if (GETPOST('ajoutsujet')) print "<br><br>\n"; // Add new column - if ($object->format == "A") - { + if ($object->format == "A") { print $langs->trans("AddNewColumn").':<br><br>'; print $langs->trans("Title").' <input type="text" name="nouvellecolonne" size="40"><br>'; $tmparray = array('checkbox'=>$langs->trans("CheckBox"), 'yesno'=>$langs->trans("YesNoList"), 'foragainst'=>$langs->trans("PourContreList")); @@ -596,7 +592,10 @@ if (GETPOST('ajoutsujet')) } if ($user->rights->opensurvey->write) { - print '<span class="opacitymedium">'.$langs->trans("PollAdminDesc", img_picto('', 'delete'), $langs->trans("Add")).'</span><br>'; + print '<span class="opacitymedium">'; + $s = $langs->trans("PollAdminDesc", '{s1}', $langs->trans("Add")); + print str_replace('{s1}', img_picto('', 'delete'), $s); + print '</span><br>'; } $nbcolonnes = substr_count($object->sujet, ',') + 1; @@ -628,8 +627,7 @@ print '</tr>'."\n"; // Show choice titles -if ($object->format == "D") -{ +if ($object->format == "D") { //affichage des sujets du sondage print '<tr>'."\n"; print '<td></td>'."\n"; @@ -638,8 +636,7 @@ if ($object->format == "D") //affichage des années $colspan = 1; $nbofsujet = count($toutsujet); - for ($i = 0; $i < $nbofsujet; $i++) - { + for ($i = 0; $i < $nbofsujet; $i++) { $current = $toutsujet[$i]; if (strpos($toutsujet[$i], '@') !== false) { @@ -653,15 +650,20 @@ if ($object->format == "D") } $currenty = 0; - if ($current) $currenty = strftime("%Y", $current); + if ($current) { + $currenty = strftime("%Y", $current); + } $next = 0; - if ($next) $nexty = strftime("%Y", $next); - if (isset($toutsujet[$i + 1]) && ($currenty == $nexty)) - { + if ($next) { + $nexty = strftime("%Y", $next); + } + if (isset($toutsujet[$i + 1]) && ($currenty == $nexty)) { $colspan++; } else { print '<td colspan='.$colspan.' class="annee">'; - if ($current) print strftime("%Y", $current); + if ($current) { + print strftime("%Y", $current); + } print '</td>'."\n"; $colspan = 1; } @@ -756,8 +758,7 @@ if ($object->format == "D") print '<td></td>'."\n"; print '<td></td>'."\n"; - for ($i = 0; isset($toutsujet[$i]); $i++) - { + for ($i = 0; isset($toutsujet[$i]); $i++) { $tmp = explode('@', $toutsujet[$i]); print '<td class="sujet">'.dol_htmlentities($tmp[0]).'</td>'."\n"; } @@ -776,14 +777,12 @@ $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; dol_syslog('sql='.$sql); $resql = $db->query($sql); -if (!$resql) -{ +if (!$resql) { dol_print_error($db); exit; } $num = $db->num_rows($resql); -while ($compteur < $num) -{ +while ($compteur < $num) { $obj = $db->fetch_object($resql); $ensemblereponses = $obj->reponses; @@ -798,121 +797,167 @@ while ($compteur < $num) print '</td><td class="nom">'.dol_htmlentities($obj->name).'</td>'."\n"; // si la ligne n'est pas a changer, on affiche les données - if (!$testligneamodifier) - { - for ($i = 0; $i < $nbcolonnes; $i++) - { + if (!$testligneamodifier) { + for ($i = 0; $i < $nbcolonnes; $i++) { $car = substr($ensemblereponses, $i, 1); //print 'xx'.$i."-".$car.'-'.$listofanswers[$i]['format'].'zz'; - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) - { - if (((string) $car) == "1") print '<td class="ok">OK</td>'."\n"; - else print '<td class="non">KO</td>'."\n"; + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { + if (((string) $car) == "1") { + print '<td class="ok">OK</td>'."\n"; + } else { + print '<td class="non">KO</td>'."\n"; + } // Total - if (!isset($sumfor[$i])) $sumfor[$i] = 0; - if (((string) $car) == "1") $sumfor[$i]++; + if (!isset($sumfor[$i])) { + $sumfor[$i] = 0; + } + if (((string) $car) == "1") { + $sumfor[$i]++; + } } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') - { - if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("Yes").'</td>'."\n"; - elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("No").'</td>'."\n"; - else print '<td class="vide">&nbsp;</td>'."\n"; + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { + if (((string) $car) == "1") { + print '<td class="ok">'.$langs->trans("Yes").'</td>'."\n"; + } elseif (((string) $car) == "0") { + print '<td class="non">'.$langs->trans("No").'</td>'."\n"; + } else { + print '<td class="vide">&nbsp;</td>'."\n"; + } // Total - if (!isset($sumfor[$i])) $sumfor[$i] = 0; - if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; - if (((string) $car) == "1") $sumfor[$i]++; - if (((string) $car) == "0") $sumagainst[$i]++; + if (!isset($sumfor[$i])) { + $sumfor[$i] = 0; + } + if (!isset($sumagainst[$i])) { + $sumagainst[$i] = 0; + } + if (((string) $car) == "1") { + $sumfor[$i]++; + } + if (((string) $car) == "0") { + $sumagainst[$i]++; + } } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') - { - if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; - elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; - else print '<td class="vide">&nbsp;</td>'."\n"; + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { + if (((string) $car) == "1") { + print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; + } elseif (((string) $car) == "0") { + print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; + } else { + print '<td class="vide">&nbsp;</td>'."\n"; + } // Total - if (!isset($sumfor[$i])) $sumfor[$i] = 0; - if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; - if (((string) $car) == "1") $sumfor[$i]++; - if (((string) $car) == "0") $sumagainst[$i]++; + if (!isset($sumfor[$i])) { + $sumfor[$i] = 0; + } + if (!isset($sumagainst[$i])) { + $sumagainst[$i] = 0; + } + if (((string) $car) == "1") { + $sumfor[$i]++; + } + if (((string) $car) == "0") { + $sumagainst[$i]++; + } } } } else { //sinon on remplace les choix de l'utilisateur par une ligne de checkbox pour recuperer de nouvelles valeurs - if ($compteur == $ligneamodifier) - { - for ($i = 0; $i < $nbcolonnes; $i++) - { + if ($compteur == $ligneamodifier) { + for ($i = 0; $i < $nbcolonnes; $i++) { $car = substr($ensemblereponses, $i, 1); print '<td class="vide">'; - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) - { + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { print '<input type="checkbox" name="choix'.$i.'" value="1" '; - if ($car == '1') print 'checked'; + if ($car == '1') { + print 'checked'; + } print '>'; } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') - { + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes")); print $form->selectarray("choix".$i, $arraychoice, $car); } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') - { + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For")); print $form->selectarray("choix".$i, $arraychoice, $car); } print '</td>'."\n"; } } else { - for ($i = 0; $i < $nbcolonnes; $i++) - { + for ($i = 0; $i < $nbcolonnes; $i++) { $car = substr($ensemblereponses, $i, 1); - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) - { - if (((string) $car) == "1") print '<td class="ok">OK</td>'."\n"; - else print '<td class="non">KO</td>'."\n"; + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { + if (((string) $car) == "1") { + print '<td class="ok">OK</td>'."\n"; + } else { + print '<td class="non">KO</td>'."\n"; + } // Total - if (!isset($sumfor[$i])) $sumfor[$i] = 0; - if (((string) $car) == "1") $sumfor[$i]++; + if (!isset($sumfor[$i])) { + $sumfor[$i] = 0; + } + if (((string) $car) == "1") { + $sumfor[$i]++; + } } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') - { - if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; - elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; - else print '<td class="vide">&nbsp;</td>'."\n"; + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { + if (((string) $car) == "1") { + print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; + } elseif (((string) $car) == "0") { + print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; + } else { + print '<td class="vide">&nbsp;</td>'."\n"; + } // Total - if (!isset($sumfor[$i])) $sumfor[$i] = 0; - if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; - if (((string) $car) == "1") $sumfor[$i]++; - if (((string) $car) == "0") $sumagainst[$i]++; + if (!isset($sumfor[$i])) { + $sumfor[$i] = 0; + } + if (!isset($sumagainst[$i])) { + $sumagainst[$i] = 0; + } + if (((string) $car) == "1") { + $sumfor[$i]++; + } + if (((string) $car) == "0") { + $sumagainst[$i]++; + } } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') - { - if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; - elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; - else print '<td class="vide">&nbsp;</td>'."\n"; + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { + if (((string) $car) == "1") { + print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; + } elseif (((string) $car) == "0") { + print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; + } else { + print '<td class="vide">&nbsp;</td>'."\n"; + } // Total - if (!isset($sumfor[$i])) $sumfor[$i] = 0; - if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; - if (((string) $car) == "1") $sumfor[$i]++; - if (((string) $car) == "0") $sumagainst[$i]++; + if (!isset($sumfor[$i])) { + $sumfor[$i] = 0; + } + if (!isset($sumagainst[$i])) { + $sumagainst[$i] = 0; + } + if (((string) $car) == "1") { + $sumfor[$i]++; + } + if (((string) $car) == "0") { + $sumagainst[$i]++; + } } } } } // Button edit at end of line - if ($compteur != $ligneamodifier && ($user->rights->opensurvey->write)) - { + if ($compteur != $ligneamodifier && ($user->rights->opensurvey->write)) { print '<td class="casevide"><input type="submit" class="button" name="modifierligne'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Edit")).'"></td>'."\n"; } //demande de confirmation pour modification de ligne - for ($i = 0; $i < $nblines; $i++) - { - if (GETPOSTISSET("modifierligne".$i)) - { - if ($compteur == $i) - { + for ($i = 0; $i < $nblines; $i++) { + if (GETPOSTISSET("modifierligne".$i)) { + if ($compteur == $i) { print '<td class="casevide">'; print '<input type="hidden" name="idtomodify'.$compteur.'" value="'.$obj->id_users.'">'; print '<input type="submit" class="button button-save" name="validermodifier'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Save")).'">'; @@ -926,33 +971,27 @@ while ($compteur < $num) } // Add line to add new record -if (empty($testligneamodifier)) -{ +if (empty($testligneamodifier)) { print '<tr>'."\n"; print '<td></td>'."\n"; print '<td class="nom">'."\n"; print '<input type="text" placeholder="'.dol_escape_htmltag($langs->trans("Name")).'" name="nom" maxlength="64" size="24">'."\n"; print '</td>'."\n"; - for ($i = 0; $i < $nbcolonnes; $i++) - { + for ($i = 0; $i < $nbcolonnes; $i++) { print '<td class="vide">'; - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) - { + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { print '<input type="checkbox" name="choix'.$i.'" value="1"'; - if (GETPOSTISSET('choix'.$i) && GETPOST('choix'.$i) == '1') - { + if (GETPOSTISSET('choix'.$i) && GETPOST('choix'.$i) == '1') { print ' checked'; } print '>'; } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') - { + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes")); print $form->selectarray("choix".$i, $arraychoice); } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') - { + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For")); print $form->selectarray("choix".$i, $arraychoice); } @@ -966,18 +1005,15 @@ if (empty($testligneamodifier)) // Select value of best choice (for checkbox columns only) $nbofcheckbox = 0; -for ($i = 0; $i < $nbcolonnes + 1; $i++) -{ - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) - $nbofcheckbox++; - if (isset($sumfor[$i])) - { - if ($i == 0) - { +for ($i = 0; $i < $nbcolonnes + 1; $i++) { + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { + $nbofcheckbox++; + } + if (isset($sumfor[$i])) { + if ($i == 0) { $meilleurecolonne = $sumfor[$i]; } - if (isset($sumfor[$i]) && $sumfor[$i] > $meilleurecolonne) - { + if (isset($sumfor[$i]) && $sumfor[$i] > $meilleurecolonne) { $meilleurecolonne = $sumfor[$i]; } } @@ -988,29 +1024,36 @@ for ($i = 0; $i < $nbcolonnes + 1; $i++) print '<tr>'."\n"; print '<td></td>'."\n"; print '<td class="center">'.$langs->trans("Total").'</td>'."\n"; -for ($i = 0; $i < $nbcolonnes; $i++) -{ +for ($i = 0; $i < $nbcolonnes; $i++) { $showsumfor = isset($sumfor[$i]) ? $sumfor[$i] : ''; $showsumagainst = isset($sumagainst[$i]) ? $sumagainst[$i] : ''; - if (empty($showsumfor)) $showsumfor = 0; - if (empty($showsumagainst)) $showsumagainst = 0; + if (empty($showsumfor)) { + $showsumfor = 0; + } + if (empty($showsumagainst)) { + $showsumagainst = 0; + } print '<td>'; - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) print $showsumfor; - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') print $langs->trans("Yes").': '.$showsumfor.'<br>'.$langs->trans("No").': '.$showsumagainst; - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') print $langs->trans("For").': '.$showsumfor.'<br>'.$langs->trans("Against").': '.$showsumagainst; + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { + print $showsumfor; + } + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { + print $langs->trans("Yes").': '.$showsumfor.'<br>'.$langs->trans("No").': '.$showsumagainst; + } + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { + print $langs->trans("For").': '.$showsumfor.'<br>'.$langs->trans("Against").': '.$showsumagainst; + } print '</td>'."\n"; } print '</tr>'; // Show picto winner -if ($nbofcheckbox >= 2) -{ +if ($nbofcheckbox >= 2) { print '<tr>'."\n"; print '<td></td>'."\n"; print '<td></td>'."\n"; for ($i = 0; $i < $nbcolonnes; $i++) { - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst')) && isset($sumfor[$i]) && isset($meilleurecolonne) && $sumfor[$i] == $meilleurecolonne) - { + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst')) && isset($sumfor[$i]) && isset($meilleurecolonne) && $sumfor[$i] == $meilleurecolonne) { print '<td class="somme"><img src="'.dol_buildpath('/opensurvey/img/medaille.png', 1).'"></td>'."\n"; } else { print '<td class="somme"></td>'."\n"; @@ -1041,10 +1084,8 @@ $toutsujet = explode(",", $object->sujet); // With old versions, this field was $compteursujet = 0; $meilleursujet = ''; -for ($i = 0; $i < $nbcolonnes; $i++) -{ - if (isset($sumfor[$i]) === true && isset($meilleurecolonne) === true && $sumfor[$i] == $meilleurecolonne) - { +for ($i = 0; $i < $nbcolonnes; $i++) { + if (isset($sumfor[$i]) === true && isset($meilleurecolonne) === true && $sumfor[$i] == $meilleurecolonne) { $meilleursujet .= ", "; if ($object->format == "D") { @@ -1068,8 +1109,7 @@ $meilleursujet = substr($meilleursujet, 1); $meilleursujet = str_replace("°", "'", $meilleursujet); // Show best choice -if ($nbofcheckbox >= 2) -{ +if ($nbofcheckbox >= 2) { $vote_str = $langs->trans('votes'); print '<p class="affichageresultats">'."\n"; diff --git a/htdocs/opensurvey/wizard/choix_autre.php b/htdocs/opensurvey/wizard/choix_autre.php index 42213af2ae2..4919006a5f1 100644 --- a/htdocs/opensurvey/wizard/choix_autre.php +++ b/htdocs/opensurvey/wizard/choix_autre.php @@ -28,7 +28,9 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; // Security check -if (!$user->rights->opensurvey->write) accessforbidden(); +if (!$user->rights->opensurvey->write) { + accessforbidden(); +} @@ -53,20 +55,16 @@ if (isset($_SESSION["nbrecases"])) { $_SESSION["nbrecases"] = 5; } -if (GETPOST("ajoutcases") || GETPOST("ajoutcases_x")) -{ +if (GETPOST("ajoutcases") || GETPOST("ajoutcases_x")) { $_SESSION["nbrecases"] = $_SESSION["nbrecases"] + 5; } // Create survey into database -if (GETPOSTISSET("confirmecreation")) -{ +if (GETPOSTISSET("confirmecreation")) { //recuperation des données de champs textes $toutchoix = ''; - for ($i = 0; $i < $_SESSION["nbrecases"] + 1; $i++) - { - if (!empty($arrayofchoices[$i])) - { + for ($i = 0; $i < $_SESSION["nbrecases"] + 1; $i++) { + if (!empty($arrayofchoices[$i])) { $toutchoix .= ','; $toutchoix .= str_replace(array(",", "@"), " ", $arrayofchoices[$i]).(empty($arrayoftypecolumn[$i]) ? '' : '@'.$arrayoftypecolumn[$i]); } @@ -77,10 +75,8 @@ if (GETPOSTISSET("confirmecreation")) //test de remplissage des cases $testremplissage = ''; - for ($i = 0; $i < $_SESSION["nbrecases"]; $i++) - { - if (isset($arrayofchoices[$i])) - { + for ($i = 0; $i < $_SESSION["nbrecases"]; $i++) { + if (isset($arrayofchoices[$i])) { $testremplissage = "ok"; } } @@ -107,8 +103,7 @@ $arrayofjs = array(); $arrayofcss = array('/opensurvey/css/style.css'); llxHeader('', $langs->trans("OpenSurvey"), "", '', 0, 0, $arrayofjs, $arrayofcss); -if (empty($_SESSION['title'])) -{ +if (empty($_SESSION['title'])) { dol_print_error('', $langs->trans('ErrorOpenSurveyFillFirstSection')); llxFooter(); exit; diff --git a/htdocs/opensurvey/wizard/choix_date.php b/htdocs/opensurvey/wizard/choix_date.php index ae64c1e6491..ce5f79b1174 100644 --- a/htdocs/opensurvey/wizard/choix_date.php +++ b/htdocs/opensurvey/wizard/choix_date.php @@ -28,7 +28,9 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; // Security check -if (!$user->rights->opensurvey->write) accessforbidden(); +if (!$user->rights->opensurvey->write) { + accessforbidden(); +} // Survey type is DATE $_SESSION["formatsondage"] = "D"; @@ -40,19 +42,15 @@ $erreur = false; */ // Insert survey -if (GETPOST('confirmation')) -{ +if (GETPOST('confirmation')) { // We save hours entered - if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('nbrecaseshoraires', $_SESSION) === true) - { + if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('nbrecaseshoraires', $_SESSION) === true) { $nbofchoice = count($_SESSION["totalchoixjour"]); $errheure = array(); - for ($i = 0; $i < $nbofchoice; $i++) - { + for ($i = 0; $i < $nbofchoice; $i++) { // Show hours choices - for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) - { + for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) { $_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j]; $tmphorairesi = GETPOST('horaires'.$i, 'array'); @@ -170,8 +168,7 @@ if (GETPOST('confirmation')) } // Add survey into database - if (!$erreur) - { + if (!$erreur) { $_SESSION["toutchoix"] = substr("$choixdate", 1); ajouter_sondage(); @@ -179,11 +176,9 @@ if (GETPOST('confirmation')) } // Reset days -if (GETPOST('reset')) -{ +if (GETPOST('reset')) { $nbofchoice = count($_SESSION["totalchoixjour"]); - for ($i = 0; $i < $nbofchoice; $i++) - { + for ($i = 0; $i < $nbofchoice; $i++) { for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) { unset($_SESSION["horaires$i"][$j]); } @@ -199,8 +194,7 @@ if (GETPOST('reset')) * View */ -if (!isset($_SESSION['description']) && !isset($_SESSION['mail'])) -{ +if (!isset($_SESSION['description']) && !isset($_SESSION['mail'])) { dol_print_error('', $langs->trans('ErrorOpenSurveyFillFirstSection')); exit; } @@ -210,11 +204,9 @@ $arrayofcss = array('/opensurvey/css/style.css'); llxHeader('', $langs->trans("OpenSurvey"), "", '', 0, 0, $arrayofjs, $arrayofcss); //nombre de cases par défaut -if (!isset($_SESSION["nbrecaseshoraires"])) -{ +if (!isset($_SESSION["nbrecaseshoraires"])) { $_SESSION["nbrecaseshoraires"] = 5; -} elseif (GETPOST('ajoutcases') && $_SESSION["nbrecaseshoraires"] == 5) -{ +} elseif (GETPOST('ajoutcases') && $_SESSION["nbrecaseshoraires"] == 5) { $_SESSION["nbrecaseshoraires"] = 10; } @@ -224,9 +216,15 @@ $moisAJ = date("n"); $anneeAJ = date("Y"); // Initialisation des jour, mois et année -if (!isset($_SESSION['jour'])) $_SESSION['jour'] = date('j'); -if (!isset($_SESSION['mois'])) $_SESSION['mois'] = date('n'); -if (!isset($_SESSION['annee'])) $_SESSION['annee'] = date('Y'); +if (!isset($_SESSION['jour'])) { + $_SESSION['jour'] = date('j'); +} +if (!isset($_SESSION['mois'])) { + $_SESSION['mois'] = date('n'); +} +if (!isset($_SESSION['annee'])) { + $_SESSION['annee'] = date('Y'); +} //mise a jour des valeurs de session si bouton retour a aujourd'hui if (!issetAndNoEmpty('choixjourajout') && !issetAndNoEmpty('choixjourretrait') && (issetAndNoEmpty('retourmois') || issetAndNoEmpty('retourmois_x'))) { @@ -245,8 +243,7 @@ if (issetAndNoEmpty('moisavant_x') || issetAndNoEmpty('moisavant')) { } //On sauvegarde les heures deja entrées - if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) - { + if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) { $nbofchoice = count($_SESSION["totalchoixjour"]); for ($i = 0; $i < $nbofchoice; $i++) { //affichage des 5 cases horaires @@ -267,11 +264,9 @@ if (issetAndNoEmpty('moisapres_x') || issetAndNoEmpty('moisapres')) { } //On sauvegarde les heures deja entrées - if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) - { + if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) { $nbofchoice = count($_SESSION["totalchoixjour"]); - for ($i = 0; $i < $nbofchoice; $i++) - { + for ($i = 0; $i < $nbofchoice; $i++) { //affichage des 5 cases horaires for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) { $_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j]; @@ -285,8 +280,7 @@ if (issetAndNoEmpty('anneeavant_x') || issetAndNoEmpty('anneeavant')) { $_SESSION["annee"] -= 1; //On sauvegarde les heures deja entrées - if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) - { + if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) { $nbofchoice = count($_SESSION["totalchoixjour"]); for ($i = 0; $i < $nbofchoice; $i++) { //affichage des 5 cases horaires @@ -302,8 +296,7 @@ if (issetAndNoEmpty('anneeapres_x') || issetAndNoEmpty('anneeapres')) { $_SESSION["annee"] += 1; //On sauvegarde les heures deja entrées - if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) - { + if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) { $nbofchoice = count($_SESSION["totalchoixjour"]); for ($i = 0; $i < $nbofchoice; $i++) { //affichage des 5 cases horaires @@ -319,8 +312,7 @@ $nbrejourmois = date("t", mktime(0, 0, 0, $_SESSION["mois"], 1, $_SESSION["annee $premierjourmois = date("N", mktime(0, 0, 0, $_SESSION["mois"], 1, $_SESSION["annee"])) - 1; //traduction de la valeur du mois -if (is_integer($_SESSION["mois"]) && $_SESSION["mois"] > 0 && $_SESSION["mois"] < 13) -{ +if (is_integer($_SESSION["mois"]) && $_SESSION["mois"] > 0 && $_SESSION["mois"] < 13) { $motmois = dol_print_date(mktime(0, 0, 0, $_SESSION["mois"], 10), '%B'); } else { $motmois = dol_print_date(dol_now(), '%B'); @@ -356,8 +348,7 @@ print '<table align="center">'."\n"; // The div class=center has no effect on ta print '<tr>'."\n"; //affichage des jours de la semaine en haut du tableau -for ($i = 0; $i < 7; $i++) -{ +for ($i = 0; $i < 7; $i++) { print '<td align="center" class="joursemaine">'.dol_print_date(mktime(0, 0, 0, 0, $i, 10), '%A').'</td>'; } @@ -371,8 +362,7 @@ if (issetAndNoEmpty('choixjourajout')) { // Test pour éviter les doublons dans la variable qui contient toutes les dates $journeuf = true; - if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('choixjourajout') === true) - { + if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('choixjourajout') === true) { $nbofchoice = count($_SESSION["totalchoixjour"]); for ($i = 0; $i < $nbofchoice; $i++) { if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourajout"][0], $_SESSION["annee"])) { @@ -421,10 +411,8 @@ if (issetAndNoEmpty('choixjourretrait')) { } } - for ($i = 0; $i < $nbofchoice; $i++) - { - if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourretrait"][0], $_SESSION["annee"])) - { + for ($i = 0; $i < $nbofchoice; $i++) { + if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourretrait"][0], $_SESSION["annee"])) { for ($j = $i; $j < $nbofchoice; $j++) { $k = $j + 1; $_SESSION["horaires$j"] = $_SESSION["horaires$k"]; @@ -468,8 +456,7 @@ for ($i = 0; $i < $nbrejourmois + $premierjourmois; $i++) { if ($i < $premierjourmois) { print '<td class="avant"></td>'."\n"; } else { - if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) - { + if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) { $nbofchoice = count($_SESSION["totalchoixjour"]); for ($j = 0; $j < $nbofchoice; $j++) { // show red buttons @@ -501,8 +488,7 @@ print '</div></div>'."\n"; print '<div class="bodydate"><div class="center">'."\n"; // affichage de tous les jours choisis -if (issetAndNoEmpty('totalchoixjour', $_SESSION) || $erreur) -{ +if (issetAndNoEmpty('totalchoixjour', $_SESSION) || $erreur) { //affichage des jours print '<br>'."\n"; print '<div align="left">'; @@ -528,8 +514,7 @@ if (issetAndNoEmpty('totalchoixjour', $_SESSION) || $erreur) //affichage de la liste des jours choisis $nbofchoice = count($_SESSION["totalchoixjour"]); - for ($i = 0; $i < $nbofchoice; $i++) - { + for ($i = 0; $i < $nbofchoice; $i++) { print '<tr>'."\n"; print '<td>'.dol_print_date($_SESSION["totalchoixjour"][$i], 'daytext').' ('.dol_print_date($_SESSION["totalchoixjour"][$i], '%A').')</td>'; diff --git a/htdocs/opensurvey/wizard/create_survey.php b/htdocs/opensurvey/wizard/create_survey.php index cbeb448d2d7..30e662be7ea 100644 --- a/htdocs/opensurvey/wizard/create_survey.php +++ b/htdocs/opensurvey/wizard/create_survey.php @@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT."/core/class/doleditor.class.php"; require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; // Security check -if (!$user->rights->opensurvey->write) accessforbidden(); +if (!$user->rights->opensurvey->write) { + accessforbidden(); +} $langs->load("opensurvey"); @@ -43,9 +45,10 @@ $creation_sondage_autre = GETPOST('creation_sondage_autre'); // We init some session variable to avoir warning $session_var = array('title', 'description', 'mailsonde'); -foreach ($session_var as $var) -{ - if (isset($_SESSION[$var])) $_SESSION[$var] = null; +foreach ($session_var as $var) { + if (isset($_SESSION[$var])) { + $_SESSION[$var] = null; + } } // On initialise également les autres variables @@ -53,8 +56,7 @@ $cocheplus = ''; $cochemail = ''; // Jump to correct page -if (!empty($creation_sondage_date) || !empty($creation_sondage_autre)) -{ +if (!empty($creation_sondage_date) || !empty($creation_sondage_autre)) { $_SESSION["title"] = $title; $_SESSION["description"] = $description; @@ -79,11 +81,9 @@ if (!empty($creation_sondage_date) || !empty($creation_sondage_autre)) $testdate = false; $champdatefin = dol_mktime(0, 0, 0, GETPOST('champdatefinmonth'), GETPOST('champdatefinday'), GETPOST('champdatefinyear')); - if ($champdatefin && ($champdatefin > 0)) // A date was provided - { + if ($champdatefin && ($champdatefin > 0)) { // A date was provided // Expire date is not before today - if ($champdatefin >= dol_now()) - { + if ($champdatefin >= dol_now()) { $testdate = true; $_SESSION['champdatefin'] = dol_print_date($champdatefin, 'dayrfc'); } else { @@ -99,16 +99,13 @@ if (!empty($creation_sondage_date) || !empty($creation_sondage_autre)) setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("ExpireDate")), null, 'errors'); } - if ($title && $testdate) - { - if (!empty($creation_sondage_date)) - { + if ($title && $testdate) { + if (!empty($creation_sondage_date)) { header("Location: choix_date.php"); exit(); } - if (!empty($creation_sondage_autre)) - { + if (!empty($creation_sondage_autre)) { header("Location: choix_autre.php"); exit(); } @@ -140,8 +137,7 @@ print dol_get_fiche_head(); print '<table class="border centpercent">'."\n"; print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("PollTitle").'</td><td><input type="text" name="title" class="minwidth300" maxlength="80" value="'.$_SESSION["title"].'"></td>'."\n"; -if (!$_SESSION["title"] && (GETPOST('creation_sondage_date') || GETPOST('creation_sondage_autre'))) -{ +if (!$_SESSION["title"] && (GETPOST('creation_sondage_date') || GETPOST('creation_sondage_autre'))) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PollTitle")), null, 'errors'); } @@ -170,22 +166,34 @@ print '<br>'."\n"; // Check or not -if ($_SESSION["mailsonde"]) $cochemail = "checked"; +if ($_SESSION["mailsonde"]) { + $cochemail = "checked"; +} print '<input type="checkbox" name="mailsonde" '.$cochemail.'> '.$langs->trans("ToReceiveEMailForEachVote").'<br>'."\n"; -if ($_SESSION['allow_comments']) $allow_comments = 'checked'; -if (GETPOSTISSET('allow_comments')) $allow_comments = GETPOST('allow_comments') ? 'checked' : ''; +if ($_SESSION['allow_comments']) { + $allow_comments = 'checked'; +} +if (GETPOSTISSET('allow_comments')) { + $allow_comments = GETPOST('allow_comments') ? 'checked' : ''; +} print '<input type="checkbox" name="allow_comments" '.$allow_comments.'"> '.$langs->trans('CanComment').'<br>'."\n"; -if ($_SESSION['allow_spy']) $allow_spy = 'checked'; -if (GETPOSTISSET('allow_spy')) $allow_spy = GETPOST('allow_spy') ? 'checked' : ''; +if ($_SESSION['allow_spy']) { + $allow_spy = 'checked'; +} +if (GETPOSTISSET('allow_spy')) { + $allow_spy = GETPOST('allow_spy') ? 'checked' : ''; +} print '<input type="checkbox" name="allow_spy" '.$allow_spy.'> '.$langs->trans('CanSeeOthersVote').'<br>'."\n"; -if (GETPOST('choix_sondage')) -{ - if (GETPOST('choix_sondage') == 'date') print '<input type="hidden" name="creation_sondage_date" value="date">'; - else print '<input type="hidden" name="creation_sondage_autre" value="autre">'; +if (GETPOST('choix_sondage')) { + if (GETPOST('choix_sondage') == 'date') { + print '<input type="hidden" name="creation_sondage_date" value="date">'; + } else { + print '<input type="hidden" name="creation_sondage_autre" value="autre">'; + } print '<input type="hidden" name="choix_sondage" value="'.GETPOST('choix_sondage').'">'; print '<br><input type="submit" class="button" name="submit" value="'.$langs->trans("CreatePoll").' ('.(GETPOST('choix_sondage') == 'date' ? $langs->trans("TypeDate") : $langs->trans("TypeClassic")).')">'; } else { diff --git a/htdocs/opensurvey/wizard/index.php b/htdocs/opensurvey/wizard/index.php index 68d660dff3d..fa3d734a488 100644 --- a/htdocs/opensurvey/wizard/index.php +++ b/htdocs/opensurvey/wizard/index.php @@ -19,7 +19,9 @@ */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; @@ -27,7 +29,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/opensurvey/fonctions.php'; // Security check -if (!$user->rights->opensurvey->write) accessforbidden(); +if (!$user->rights->opensurvey->write) { + accessforbidden(); +} $langs->load("opensurvey"); diff --git a/htdocs/paybox/admin/paybox.php b/htdocs/paybox/admin/paybox.php index a342e58b971..7bba308ba9c 100644 --- a/htdocs/paybox/admin/paybox.php +++ b/htdocs/paybox/admin/paybox.php @@ -32,55 +32,84 @@ $servicename = 'PayBox'; // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'paybox', 'paypal')); -if (!$user->admin) - accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); -if ($action == 'setvalue' && $user->admin) -{ +if ($action == 'setvalue' && $user->admin) { $db->begin(); //$result=dolibarr_set_const($db, "PAYBOX_IBS_DEVISE",$_POST["PAYBOX_IBS_DEVISE"],'chaine',0,'',$conf->entity); $result = dolibarr_set_const($db, "PAYBOX_CGI_URL_V1", GETPOST('PAYBOX_CGI_URL_V1', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYBOX_CGI_URL_V2", GETPOST('PAYBOX_CGI_URL_V2', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYBOX_IBS_SITE", GETPOST('PAYBOX_IBS_SITE', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYBOX_IBS_RANG", GETPOST('PAYBOX_IBS_RANG', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYBOX_PBX_IDENTIFIANT", GETPOST('PAYBOX_PBX_IDENTIFIANT', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_CREDITOR", GETPOST('ONLINE_PAYMENT_CREDITOR', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS", GETPOST('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS', 'int'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_CSS_URL", GETPOST('ONLINE_PAYMENT_CSS_URL', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_FORM", GETPOST('ONLINE_PAYMENT_MESSAGE_FORM', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_OK", GETPOST('ONLINE_PAYMENT_MESSAGE_OK', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_KO", GETPOST('ONLINE_PAYMENT_MESSAGE_KO', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_SENDEMAIL", GETPOST('ONLINE_PAYMENT_SENDEMAIL'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } // Payment token for URL $result = dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN", GETPOST('PAYMENT_SECURITY_TOKEN', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN_UNIQUE", GETPOST('PAYMENT_SECURITY_TOKEN_UNIQUE', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYBOX_HMAC_KEY", dol_encode(GETPOST('PAYBOX_HMAC_KEY', 'alpha')), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } - if (!$error) - { - $db->commit(); + if (!$error) { + $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - $db->rollback(); + } else { + $db->rollback(); dol_print_error($db); } } @@ -91,11 +120,17 @@ if ($action == 'setvalue' && $user->admin) */ $IBS_SITE = "1999888"; // Site test -if (empty($conf->global->PAYBOX_IBS_SITE)) $conf->global->PAYBOX_IBS_SITE = $IBS_SITE; +if (empty($conf->global->PAYBOX_IBS_SITE)) { + $conf->global->PAYBOX_IBS_SITE = $IBS_SITE; +} $IBS_RANG = "99"; // Rang test -if (empty($conf->global->PAYBOX_IBS_RANG)) $conf->global->PAYBOX_IBS_RANG = $IBS_RANG; +if (empty($conf->global->PAYBOX_IBS_RANG)) { + $conf->global->PAYBOX_IBS_RANG = $IBS_RANG; +} $IBS_DEVISE = "978"; // Euro -if (empty($conf->global->PAYBOX_IBS_DEVISE)) $conf->global->PAYBOX_IBS_DEVISE = $IBS_DEVISE; +if (empty($conf->global->PAYBOX_IBS_DEVISE)) { + $conf->global->PAYBOX_IBS_DEVISE = $IBS_DEVISE; +} llxHeader(); @@ -191,8 +226,7 @@ print '<br><span class="opacitymedium">'.$langs->trans("Example").': '.$mysoc->n print '</td></tr>'; -if (!empty($conf->banque->enabled)) -{ +if (!empty($conf->banque->enabled)) { print '<tr class="oddeven"><td>'; print $langs->trans("BankAccount").'</td><td>'; $form->select_comptes($conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS, 'PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1); @@ -237,8 +271,9 @@ print '</td></tr>'; print '<tr class="oddeven"><td>'; print $langs->trans("SecurityToken").'</td><td>'; print '<input size="48" type="text" id="PAYMENT_SECURITY_TOKEN" name="PAYMENT_SECURITY_TOKEN" value="'.$conf->global->PAYMENT_SECURITY_TOKEN.'">'; -if (!empty($conf->use_javascript_ajax)) +if (!empty($conf->use_javascript_ajax)) { print '&nbsp;'.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"'); +} print '</td></tr>'; print '<tr class="oddeven"><td>'; diff --git a/htdocs/paybox/lib/paybox.lib.php b/htdocs/paybox/lib/paybox.lib.php index d1f27bc0b0f..e5f53b34978 100644 --- a/htdocs/paybox/lib/paybox.lib.php +++ b/htdocs/paybox/lib/paybox.lib.php @@ -44,36 +44,46 @@ function print_paybox_redirect($PRICE, $CURRENCY, $EMAIL, $urlok, $urlko, $TAG) // Clean parameters $PBX_IDENTIFIANT = "2"; // Identifiant pour v2 test - if (!empty($conf->global->PAYBOX_PBX_IDENTIFIANT)) $PBX_IDENTIFIANT = $conf->global->PAYBOX_PBX_IDENTIFIANT; + if (!empty($conf->global->PAYBOX_PBX_IDENTIFIANT)) { + $PBX_IDENTIFIANT = $conf->global->PAYBOX_PBX_IDENTIFIANT; + } $IBS_SITE = "1999888"; // Site test - if (!empty($conf->global->PAYBOX_IBS_SITE)) $IBS_SITE = $conf->global->PAYBOX_IBS_SITE; + if (!empty($conf->global->PAYBOX_IBS_SITE)) { + $IBS_SITE = $conf->global->PAYBOX_IBS_SITE; + } $IBS_RANG = "99"; // Rang test - if (!empty($conf->global->PAYBOX_IBS_RANG)) $IBS_RANG = $conf->global->PAYBOX_IBS_RANG; + if (!empty($conf->global->PAYBOX_IBS_RANG)) { + $IBS_RANG = $conf->global->PAYBOX_IBS_RANG; + } $IBS_DEVISE = "840"; // Currency (Dollar US by default) - if ($CURRENCY == 'EUR') $IBS_DEVISE = "978"; - if ($CURRENCY == 'USD') $IBS_DEVISE = "840"; + if ($CURRENCY == 'EUR') { + $IBS_DEVISE = "978"; + } + if ($CURRENCY == 'USD') { + $IBS_DEVISE = "840"; + } $URLPAYBOX = ""; - if ($conf->global->PAYBOX_CGI_URL_V1) $URLPAYBOX = $conf->global->PAYBOX_CGI_URL_V1; - if ($conf->global->PAYBOX_CGI_URL_V2) $URLPAYBOX = $conf->global->PAYBOX_CGI_URL_V2; + if ($conf->global->PAYBOX_CGI_URL_V1) { + $URLPAYBOX = $conf->global->PAYBOX_CGI_URL_V1; + } + if ($conf->global->PAYBOX_CGI_URL_V2) { + $URLPAYBOX = $conf->global->PAYBOX_CGI_URL_V2; + } - if (empty($IBS_DEVISE)) - { + if (empty($IBS_DEVISE)) { dol_print_error('', "Paybox setup param PAYBOX_IBS_DEVISE not defined"); return -1; } - if (empty($URLPAYBOX)) - { + if (empty($URLPAYBOX)) { dol_print_error('', "Paybox setup param PAYBOX_CGI_URL_V1 and PAYBOX_CGI_URL_V2 undefined"); return -1; } - if (empty($IBS_SITE)) - { + if (empty($IBS_SITE)) { dol_print_error('', "Paybox setup param PAYBOX_IBS_SITE not defined"); return -1; } - if (empty($IBS_RANG)) - { + if (empty($IBS_RANG)) { dol_print_error('', "Paybox setup param PAYBOX_IBS_RANG not defined"); return -1; } @@ -93,12 +103,24 @@ function print_paybox_redirect($PRICE, $CURRENCY, $EMAIL, $urlok, $urlko, $TAG) $IBS_BKGD = "#FFFFFF"; $IBS_WAIT = "2000"; $IBS_LANG = "GBR"; // By default GBR=english (FRA, GBR, ESP, ITA et DEU...) - if (preg_match('/^FR/i', $langs->defaultlang)) $IBS_LANG = "FRA"; - if (preg_match('/^ES/i', $langs->defaultlang)) $IBS_LANG = "ESP"; - if (preg_match('/^IT/i', $langs->defaultlang)) $IBS_LANG = "ITA"; - if (preg_match('/^DE/i', $langs->defaultlang)) $IBS_LANG = "DEU"; - if (preg_match('/^NL/i', $langs->defaultlang)) $IBS_LANG = "NLD"; - if (preg_match('/^SE/i', $langs->defaultlang)) $IBS_LANG = "SWE"; + if (preg_match('/^FR/i', $langs->defaultlang)) { + $IBS_LANG = "FRA"; + } + if (preg_match('/^ES/i', $langs->defaultlang)) { + $IBS_LANG = "ESP"; + } + if (preg_match('/^IT/i', $langs->defaultlang)) { + $IBS_LANG = "ITA"; + } + if (preg_match('/^DE/i', $langs->defaultlang)) { + $IBS_LANG = "DEU"; + } + if (preg_match('/^NL/i', $langs->defaultlang)) { + $IBS_LANG = "NLD"; + } + if (preg_match('/^SE/i', $langs->defaultlang)) { + $IBS_LANG = "SWE"; + } $IBS_OUTPUT = 'E'; $PBX_SOURCE = 'HTML'; $PBX_TYPEPAIEMENT = 'CARTE'; diff --git a/htdocs/paypal/admin/paypal.php b/htdocs/paypal/admin/paypal.php index b16748f66b4..cfa7628297d 100644 --- a/htdocs/paypal/admin/paypal.php +++ b/htdocs/paypal/admin/paypal.php @@ -35,43 +35,72 @@ $servicename = 'PayPal'; // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'paypal', 'paybox')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); -if ($action == 'setvalue' && $user->admin) -{ +if ($action == 'setvalue' && $user->admin) { $db->begin(); $result = dolibarr_set_const($db, "PAYPAL_API_USER", GETPOST('PAYPAL_API_USER', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYPAL_API_PASSWORD", GETPOST('PAYPAL_API_PASSWORD', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYPAL_API_SIGNATURE", GETPOST('PAYPAL_API_SIGNATURE', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYPAL_SSLVERSION", GETPOST('PAYPAL_SSLVERSION', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_CREDITOR", GETPOST('ONLINE_PAYMENT_CREDITOR', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS", GETPOST('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS', 'int'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYPAL_API_INTEGRAL_OR_PAYPALONLY", GETPOST('PAYPAL_API_INTEGRAL_OR_PAYPALONLY', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_CSS_URL", GETPOST('ONLINE_PAYMENT_CSS_URL', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "PAYPAL_ADD_PAYMENT_URL", GETPOST('PAYPAL_ADD_PAYMENT_URL', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_FORM", GETPOST('ONLINE_PAYMENT_MESSAGE_FORM'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_OK", GETPOST('ONLINE_PAYMENT_MESSAGE_OK'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_KO", GETPOST('ONLINE_PAYMENT_MESSAGE_KO'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_SENDEMAIL", GETPOST('ONLINE_PAYMENT_SENDEMAIL'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } // Payment token for URL $result = dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN", GETPOST('PAYMENT_SECURITY_TOKEN', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } if (empty($conf->use_javascript_ajax)) { $result = dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN_UNIQUE", GETPOST('PAYMENT_SECURITY_TOKEN_UNIQUE', 'alpha'), 'chaine', 0, '', $conf->entity); if (!$result > 0) { @@ -80,21 +109,21 @@ if ($action == 'setvalue' && $user->admin) } if (!$error) { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - $db->rollback(); + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + $db->rollback(); dol_print_error($db); } } -if ($action == "setlive") -{ +if ($action == "setlive") { $liveenable = GETPOST('value', 'int') ? 0 : 1; $res = dolibarr_set_const($db, "PAYPAL_API_SANDBOX", $liveenable, 'yesno', 0, '', $conf->entity); - if (!($res > 0)) $error++; - if (!$error) - { + if (!($res > 0)) { + $error++; + } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -126,8 +155,7 @@ print dol_get_fiche_head($head, 'paypalaccount', '', -1); print '<span class="opacitymedium">'.$langs->trans("PaypalDesc")."</span><br>\n"; // Test if php curl exist -if (!function_exists('curl_version')) -{ +if (!function_exists('curl_version')) { $langs->load("errors"); setEventMessages($langs->trans("ErrorPhpCurlNotInstalled"), null, 'errors'); } @@ -147,8 +175,7 @@ print "</tr>\n"; print '<tr class="oddeven">'; print '<td>'; print $langs->trans("PaypalLiveEnabled").'</td><td>'; -if (empty($conf->global->PAYPAL_API_SANDBOX)) -{ +if (empty($conf->global->PAYPAL_API_SANDBOX)) { print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setlive&token='.newToken().'&value=0">'; print img_picto($langs->trans("Activated"), 'switch_on'); } else { @@ -217,8 +244,7 @@ print '<input size="64" type="text" name="ONLINE_PAYMENT_CREDITOR" value="'.$con print ' &nbsp; <span class="opacitymedium">'.$langs->trans("Example").': '.$mysoc->name.'</span>'; print '</td></tr>'; -if (!empty($conf->banque->enabled)) -{ +if (!empty($conf->banque->enabled)) { print '<tr class="oddeven"><td>'; print $langs->trans("BankAccount").'</td><td>'; print img_picto('', 'bank_account').' '; @@ -315,8 +341,9 @@ print '<br><br>'; // Help doc print '<u>'.$langs->trans("InformationToFindParameters", "Paypal").'</u>:<br>'; -if (!empty($conf->use_javascript_ajax)) +if (!empty($conf->use_javascript_ajax)) { print '<a class="reposition" id="apidoca">'.$langs->trans("ClickHere").'...</a>'; +} $realpaypalurl = 'www.paypal.com'; $sandboxpaypalurl = 'developer.paypal.com'; @@ -334,8 +361,7 @@ print 'Your API authentication information can be found with following steps. We '; print '</div>'; -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print "\n".'<script type="text/javascript">'; print '$(document).ready(function () { $("#apidoc").hide(); diff --git a/htdocs/paypal/lib/paypal.lib.php b/htdocs/paypal/lib/paypal.lib.php index 873678adcae..dee6476f773 100644 --- a/htdocs/paypal/lib/paypal.lib.php +++ b/htdocs/paypal/lib/paypal.lib.php @@ -82,25 +82,24 @@ function print_paypal_redirect($paymentAmount, $currencyCodeType, $paymentType, //' //'------------------------------------------------- - if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY = 'integral'; + if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) { + $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY = 'integral'; + } $solutionType = 'Sole'; $landingPage = 'Billing'; // For payment with Paypal only - if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') - { + if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') { $solutionType = 'Mark'; $landingPage = 'Login'; } // For payment with Credit card or Paypal - if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') - { + if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') { $solutionType = 'Sole'; $landingPage = 'Billing'; } // For payment with Credit card - if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'cconly') - { + if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'cconly') { $solutionType = 'Sole'; $landingPage = 'Billing'; } @@ -130,8 +129,7 @@ function print_paypal_redirect($paymentAmount, $currencyCodeType, $paymentType, dol_syslog("print_paypal_redirect resArray=".var_export($resArray, true), LOG_DEBUG); $ack = strtoupper($resArray["ACK"]); - if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") - { + if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") { $token = $resArray["TOKEN"]; // Redirect to paypal.com here @@ -146,8 +144,7 @@ function print_paypal_redirect($paymentAmount, $currencyCodeType, $paymentType, $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]); $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]); - if ($ErrorCode == 10729) - { + if ($ErrorCode == 10729) { $mesg .= "PayPal can't accept payments for this thirdparty. An address is defined but is not complete (missing State).<br>Ask system administrator to fix address or to setup Paypal module to accept payments even on not complete addresses (remove option PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS).<br>\n"; } else { $mesg = $langs->trans('SetExpressCheckoutAPICallFailed')."<br>\n"; @@ -216,26 +213,25 @@ function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, //$nvpstr = $nvpstr . "&VERSION=".$API_version; // Already added by hash_call $nvpstr = $nvpstr."&RETURNURL=".urlencode($returnURL); $nvpstr = $nvpstr."&CANCELURL=".urlencode($cancelURL); - if (!empty($conf->global->PAYPAL_ALLOW_NOTES)) - { + if (!empty($conf->global->PAYPAL_ALLOW_NOTES)) { $nvpstr = $nvpstr."&ALLOWNOTE=0"; } - if (empty($conf->global->PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS)) - { + if (empty($conf->global->PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS)) { $nvpstr = $nvpstr."&NOSHIPPING=1"; // An empty or not complete shipping address will be accepted } else { $nvpstr = $nvpstr."&NOSHIPPING=0"; // A valid shipping address is required (full required fields mandatory) } $nvpstr = $nvpstr."&SOLUTIONTYPE=".urlencode($solutionType); $nvpstr = $nvpstr."&LANDINGPAGE=".urlencode($landingPage); - if (!empty($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER)) - { + if (!empty($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER)) { $nvpstr = $nvpstr."&CUSTOMERSERVICENUMBER=".urlencode($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER); // Hotline phone number } $paypalprefix = 'PAYMENTREQUEST_0_'; //$paypalprefix = ''; - if (!empty($paypalprefix) && $paymentType == 'Sole') $paymentType = 'Sale'; + if (!empty($paypalprefix) && $paymentType == 'Sole') { + $paymentType = 'Sale'; + } $nvpstr = $nvpstr."&AMT=".urlencode($paymentAmount); // Total for all elements @@ -258,11 +254,14 @@ function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCOUNTRYCODE=".urlencode($shipToCountryCode); $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOZIP=".urlencode($shipToZip); $nvpstr = $nvpstr."&".$paypalprefix."PHONENUM=".urlencode($phoneNum); - if (!empty($email)) $nvpstr = $nvpstr."&".$paypalprefix."EMAIL=".urlencode($email); // EMAIL deprecated by paypal -> PAYMENTREQUEST_n_EMAIL - if (!empty($desc)) $nvpstr = $nvpstr."&".$paypalprefix."DESC=".urlencode($desc); // DESC deprecated by paypal -> PAYMENTREQUEST_n_DESC + if (!empty($email)) { + $nvpstr = $nvpstr."&".$paypalprefix."EMAIL=".urlencode($email); // EMAIL deprecated by paypal -> PAYMENTREQUEST_n_EMAIL + } + if (!empty($desc)) { + $nvpstr = $nvpstr."&".$paypalprefix."DESC=".urlencode($desc); // DESC deprecated by paypal -> PAYMENTREQUEST_n_DESC + } - if (!empty($conf->global->PAYPAL_LOGOIMG) && $mysoc->logo) - { + if (!empty($conf->global->PAYPAL_LOGOIMG) && $mysoc->logo) { global $dolibarr_main_url_root; // Define $urlwithroot @@ -273,12 +272,10 @@ function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $urllogo = $urlwithroot."/viewimage.php?modulepart=mycompany&file=".urlencode('logos/'.$mysoc->logo); $nvpstr = $nvpstr."&LOGOIMG=".urlencode($urllogo); } - if (!empty($conf->global->PAYPAL_BRANDNAME)) - { + if (!empty($conf->global->PAYPAL_BRANDNAME)) { $nvpstr = $nvpstr."&BRANDNAME=".urlencode($conf->global->PAYPAL_BRANDNAME); // BRANDNAME } - if (!empty($conf->global->PAYPAL_NOTETOBUYER)) - { + if (!empty($conf->global->PAYPAL_NOTETOBUYER)) { $nvpstr = $nvpstr."&NOTETOBUYER=".urlencode($conf->global->PAYPAL_NOTETOBUYER); // PAYPAL_NOTETOBUYER } @@ -294,8 +291,7 @@ function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, //'--------------------------------------------------------------------------------------------------------------- $resArray = hash_call("SetExpressCheckout", $nvpstr); $ack = strtoupper($resArray["ACK"]); - if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") - { + if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") { $token = urldecode($resArray["TOKEN"]); $_SESSION['TOKEN'] = $token; } @@ -339,8 +335,7 @@ function getDetails($token) //'--------------------------------------------------------------------------- $resArray = hash_call("GetExpressCheckoutDetails", $nvpstr); $ack = strtoupper($resArray["ACK"]); - if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") - { + if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") { $_SESSION['payer_id'] = $resArray['PAYERID']; } return $resArray; @@ -362,9 +357,9 @@ function getDetails($token) function confirmPayment($token, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $tag) { /* Gather the information to make the final call to - finalize the PayPal payment. The variable nvpstr - holds the name value pairs - */ + finalize the PayPal payment. The variable nvpstr + holds the name value pairs + */ //declaring of global variables global $conf, $langs; @@ -381,14 +376,14 @@ function confirmPayment($token, $paymentType, $currencyCodeType, $payerID, $ipad $nvpstr .= '&INVNUM='.urlencode($tag); /* Make the call to PayPal to finalize payment - If an error occured, show the resulting errors - */ + If an error occured, show the resulting errors + */ $resArray = hash_call("DoExpressCheckoutPayment", $nvpstr); /* Display the API response back to the browser. - If the response from PayPal was a success, display the response parameters' - If the response was an error, display the errors received using APIError.php. - */ + If the response from PayPal was a success, display the response parameters' + If the response was an error, display the errors received using APIError.php. + */ $ack = strtoupper($resArray["ACK"]); return $resArray; @@ -416,32 +411,32 @@ function confirmPayment($token, $paymentType, $currencyCodeType, $payerID, $ipad /* function DirectPayment($paymentType, $paymentAmount, $creditCardType, $creditCardNumber, $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip, $countryCode, $currencyCode, $tag) { - //declaring of global variables - global $conf, $langs; - global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT; - global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE; + //declaring of global variables + global $conf, $langs; + global $API_Endpoint, $API_Url, $API_version, $USE_PROXY, $PROXY_HOST, $PROXY_PORT; + global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE; - //Construct the parameter string that describes DoDirectPayment - $nvpstr = ''; - $nvpstr = $nvpstr . "&AMT=" . urlencode($paymentAmount); // deprecated by paypal - $nvpstr = $nvpstr . "&CURRENCYCODE=" . urlencode($currencyCode); - $nvpstr = $nvpstr . "&PAYMENTACTION=" . urlencode($paymentType); // deprecated by paypal - $nvpstr = $nvpstr . "&CREDITCARDTYPE=" . urlencode($creditCardType); - $nvpstr = $nvpstr . "&ACCT=" . urlencode($creditCardNumber); - $nvpstr = $nvpstr . "&EXPDATE=" . urlencode($expDate); - $nvpstr = $nvpstr . "&CVV2=" . urlencode($cvv2); - $nvpstr = $nvpstr . "&FIRSTNAME=" . urlencode($firstName); - $nvpstr = $nvpstr . "&LASTNAME=" . urlencode($lastName); - $nvpstr = $nvpstr . "&STREET=" . urlencode($street); - $nvpstr = $nvpstr . "&CITY=" . urlencode($city); - $nvpstr = $nvpstr . "&STATE=" . urlencode($state); - $nvpstr = $nvpstr . "&COUNTRYCODE=" . urlencode($countryCode); - $nvpstr = $nvpstr . "&IPADDRESS=" . getUserRemotIP(); - $nvpstr = $nvpstr . "&INVNUM=" . urlencode($tag); + //Construct the parameter string that describes DoDirectPayment + $nvpstr = ''; + $nvpstr = $nvpstr . "&AMT=" . urlencode($paymentAmount); // deprecated by paypal + $nvpstr = $nvpstr . "&CURRENCYCODE=" . urlencode($currencyCode); + $nvpstr = $nvpstr . "&PAYMENTACTION=" . urlencode($paymentType); // deprecated by paypal + $nvpstr = $nvpstr . "&CREDITCARDTYPE=" . urlencode($creditCardType); + $nvpstr = $nvpstr . "&ACCT=" . urlencode($creditCardNumber); + $nvpstr = $nvpstr . "&EXPDATE=" . urlencode($expDate); + $nvpstr = $nvpstr . "&CVV2=" . urlencode($cvv2); + $nvpstr = $nvpstr . "&FIRSTNAME=" . urlencode($firstName); + $nvpstr = $nvpstr . "&LASTNAME=" . urlencode($lastName); + $nvpstr = $nvpstr . "&STREET=" . urlencode($street); + $nvpstr = $nvpstr . "&CITY=" . urlencode($city); + $nvpstr = $nvpstr . "&STATE=" . urlencode($state); + $nvpstr = $nvpstr . "&COUNTRYCODE=" . urlencode($countryCode); + $nvpstr = $nvpstr . "&IPADDRESS=" . getUserRemotIP(); + $nvpstr = $nvpstr . "&INVNUM=" . urlencode($tag); - $resArray=hash_call("DoDirectPayment", $nvpstr); + $resArray=hash_call("DoDirectPayment", $nvpstr); - return $resArray; + return $resArray; } */ @@ -462,8 +457,7 @@ function hash_call($methodName, $nvpStr) // TODO problem with triggers $API_version = "98.0"; - if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha')) // We can force sand box with param 'forcesandbox' - { + if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha')) { // We can force sand box with param 'forcesandbox' $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp"; $API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token="; } else { @@ -473,13 +467,21 @@ function hash_call($methodName, $nvpStr) // Clean parameters $PAYPAL_API_USER = ""; - if (!empty($conf->global->PAYPAL_API_USER)) $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER; + if (!empty($conf->global->PAYPAL_API_USER)) { + $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER; + } $PAYPAL_API_PASSWORD = ""; - if (!empty($conf->global->PAYPAL_API_PASSWORD)) $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD; + if (!empty($conf->global->PAYPAL_API_PASSWORD)) { + $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD; + } $PAYPAL_API_SIGNATURE = ""; - if (!empty($conf->global->PAYPAL_API_SIGNATURE)) $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE; + if (!empty($conf->global->PAYPAL_API_SIGNATURE)) { + $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE; + } $PAYPAL_API_SANDBOX = ""; - if (!empty($conf->global->PAYPAL_API_SANDBOX)) $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX; + if (!empty($conf->global->PAYPAL_API_SANDBOX)) { + $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX; + } // TODO END problem with triggers dol_syslog("Paypal API endpoint ".$API_Endpoint); @@ -488,9 +490,9 @@ function hash_call($methodName, $nvpStr) $ch = curl_init(); /*print $API_Endpoint."-".$API_version."-".$PAYPAL_API_USER."-".$PAYPAL_API_PASSWORD."-".$PAYPAL_API_SIGNATURE."<br>"; - print $USE_PROXY."-".$gv_ApiErrorURL."<br>"; - print $nvpStr; - exit;*/ + print $USE_PROXY."-".$gv_ApiErrorURL."<br>"; + print $nvpStr; + exit;*/ curl_setopt($ch, CURLOPT_URL, $API_Endpoint); curl_setopt($ch, CURLOPT_VERBOSE, 1); // TLSv1 by default or change to TLSv1.2 in module configuration @@ -507,12 +509,13 @@ function hash_call($methodName, $nvpStr) curl_setopt($ch, CURLOPT_POST, 1); //if USE_PROXY constant set to true in Constants.php, then only proxy will be enabled. - if ($USE_PROXY) - { + if ($USE_PROXY) { dol_syslog("Paypal API hash_call set proxy to ".$PROXY_HOST.":".$PROXY_PORT." - ".$PROXY_USER.":".$PROXY_PASS); //curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Curl 7.10 curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT); - if ($PROXY_USER) curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS); + if ($PROXY_USER) { + curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS); + } } //NVPRequest for submitting to server @@ -564,8 +567,7 @@ function deformatNVP($nvpstr) $intial = 0; $nvpArray = array(); - while (strlen($nvpstr)) - { + while (strlen($nvpstr)) { //postion of Key $keypos = strpos($nvpstr, '='); //position of value @@ -592,13 +594,11 @@ function getApiError() $resArray = $_SESSION['reshash']; - if (isset($_SESSION['curl_error_no'])) - { + if (isset($_SESSION['curl_error_no'])) { $errors[] = $_SESSION['curl_error_no'].'-'.$_SESSION['curl_error_msg']; } - foreach ($resArray as $key => $value) - { + foreach ($resArray as $key => $value) { $errors[] = $key.'-'.$value; } diff --git a/htdocs/paypal/lib/paypalfunctions.lib.php b/htdocs/paypal/lib/paypalfunctions.lib.php index 5fbe0f6e9cd..713c304323b 100644 --- a/htdocs/paypal/lib/paypalfunctions.lib.php +++ b/htdocs/paypal/lib/paypalfunctions.lib.php @@ -22,14 +22,13 @@ * \brief Page with Paypal init var. */ -if (session_id() == "") -{ +if (session_id() == "") { session_start(); - if (ini_get('register_globals')) // To solve bug in using $_SESSION - { - foreach ($_SESSION as $key=>$value) - { - if (isset($GLOBALS[$key])) unset($GLOBALS[$key]); + if (ini_get('register_globals')) { // To solve bug in using $_SESSION + foreach ($_SESSION as $key => $value) { + if (isset($GLOBALS[$key])) { + unset($GLOBALS[$key]); + } } } } @@ -48,8 +47,7 @@ $API_version = "56"; ' For the sandbox, the URL is https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token= ' For the live site, the URL is https://www.paypal.com/webscr&cmd=_express-checkout&token= */ -if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha')) // We can force sand box with param 'forcesandbox' -{ +if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha')) { // We can force sand box with param 'forcesandbox' $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp"; $API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token="; } else { @@ -59,13 +57,21 @@ if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha' // Clean parameters $PAYPAL_API_USER = ""; -if (!empty($conf->global->PAYPAL_API_USER)) $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER; +if (!empty($conf->global->PAYPAL_API_USER)) { + $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER; +} $PAYPAL_API_PASSWORD = ""; -if (!empty($conf->global->PAYPAL_API_PASSWORD)) $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD; +if (!empty($conf->global->PAYPAL_API_PASSWORD)) { + $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD; +} $PAYPAL_API_SIGNATURE = ""; -if (!empty($conf->global->PAYPAL_API_SIGNATURE)) $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE; +if (!empty($conf->global->PAYPAL_API_SIGNATURE)) { + $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE; +} $PAYPAL_API_SANDBOX = ""; -if (!empty($conf->global->PAYPAL_API_SANDBOX)) $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX; +if (!empty($conf->global->PAYPAL_API_SANDBOX)) { + $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX; +} // Proxy $PROXY_HOST = $conf->global->MAIN_PROXY_HOST; diff --git a/htdocs/printing/admin/printing.php b/htdocs/printing/admin/printing.php index a67ad379ca9..5c79be62197 100644 --- a/htdocs/printing/admin/printing.php +++ b/htdocs/printing/admin/printing.php @@ -33,7 +33,9 @@ use OAuth\Common\Storage\DoliStorage; // Load translation files required by the page $langs->loadLangs(array('admin', 'printing', 'oauth')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $mode = GETPOST('mode', 'alpha'); @@ -41,9 +43,13 @@ $value = GETPOST('value', 'alpha', 0, null, null, 1); // The value may be __goog $varname = GETPOST('varname', 'alpha'); $driver = GETPOST('driver', 'alpha'); -if (!empty($driver)) $langs->load($driver); +if (!empty($driver)) { + $langs->load($driver); +} -if (!$mode) $mode = 'config'; +if (!$mode) { + $mode = 'config'; +} $OAUTH_SERVICENAME_GOOGLE = 'Google'; @@ -52,21 +58,21 @@ $OAUTH_SERVICENAME_GOOGLE = 'Google'; * Action */ -if (($mode == 'test' || $mode == 'setup') && empty($driver)) -{ +if (($mode == 'test' || $mode == 'setup') && empty($driver)) { setEventMessages($langs->trans('PleaseSelectaDriverfromList'), null); header("Location: ".$_SERVER['PHP_SELF'].'?mode=config'); exit; } -if ($action == 'setconst' && $user->admin) -{ +if ($action == 'setconst' && $user->admin) { $error = 0; $db->begin(); foreach ($_POST['setupdriver'] as $setupconst) { //print '<pre>'.print_r($setupconst, true).'</pre>'; $result = dolibarr_set_const($db, $setupconst['varname'], $setupconst['value'], 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } } if (!$error) { @@ -79,12 +85,13 @@ if ($action == 'setconst' && $user->admin) $action = ''; } -if ($action == 'setvalue' && $user->admin) -{ +if ($action == 'setvalue' && $user->admin) { $db->begin(); $result = dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + if (!$result > 0) { + $error++; + } if (!$error) { $db->commit(); @@ -110,8 +117,7 @@ print load_fiche_titre($langs->trans("PrintingSetup"), $linkback, 'title_setup') $head = printingAdminPrepareHead($mode); -if ($mode == 'setup' && $user->admin) -{ +if ($mode == 'setup' && $user->admin) { print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?mode=setup&amp;driver='.$driver.'" autocomplete="off">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="setconst">'; @@ -143,8 +149,7 @@ if ($mode == 'setup' && $user->admin) $i = 0; $submit_enabled = 0; - foreach ($printer->conf as $key) - { + foreach ($printer->conf as $key) { switch ($key['type']) { case "text": case "password": @@ -159,8 +164,7 @@ if ($mode == 'setup' && $user->admin) case "info": // Google Api setup or Google OAuth Token print '<tr class="oddeven">'; print '<td'.($key['required'] ? ' class=required' : '').'>'; - if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') - { + if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') { print $langs->trans("IsTokenGenerated"); } else { print $langs->trans($key['varname']); @@ -169,10 +173,11 @@ if ($mode == 'setup' && $user->admin) print '<td>'.$langs->trans($key['info']).'</td>'; print '<td>'; //var_dump($key); - if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') - { + if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') { // Delete remote tokens - if (!empty($key['delete'])) print '<a class="button" href="'.$key['delete'].'">'.$langs->trans('DeleteAccess').'</a><br><br>'; + if (!empty($key['delete'])) { + print '<a class="button" href="'.$key['delete'].'">'.$langs->trans('DeleteAccess').'</a><br><br>'; + } // Request remote token print '<a class="button" href="'.$key['renew'].'">'.$langs->trans('RequestAccess').'</a><br><br>'; // Check remote access @@ -182,13 +187,14 @@ if ($mode == 'setup' && $user->admin) print '</tr>'."\n"; break; case "submit": - if ($key['enabled']) $submit_enabled = 1; + if ($key['enabled']) { + $submit_enabled = 1; + } break; } $i++; - if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') - { + if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') { // Token print '<tr class="oddeven">'; print '<td>'.$langs->trans("Token").'</td>'; @@ -198,20 +204,18 @@ if ($mode == 'setup' && $user->admin) $storage = new DoliStorage($db, $conf); try { $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME_GOOGLE); - } catch (Exception $e) - { + } catch (Exception $e) { // Return an error if token not found } - if (is_object($tokenobj)) - { + if (is_object($tokenobj)) { //var_dump($tokenobj); print $tokenobj->getAccessToken().'<br>'; //print 'Refresh: '.$tokenobj->getRefreshToken().'<br>'; //print 'EndOfLife: '.$tokenobj->getEndOfLife().'<br>'; //var_dump($tokenobj->getExtraParams()); /*print '<br>Extra: <br><textarea class="quatrevingtpercent">'; - print ''.join(',',$tokenobj->getExtraParams()); - print '</textarea>';*/ + print ''.join(',',$tokenobj->getExtraParams()); + print '</textarea>';*/ } print '</td>'; print '</tr>'."\n"; @@ -225,8 +229,7 @@ if ($mode == 'setup' && $user->admin) print dol_get_fiche_end(); - if (!empty($driver)) - { + if (!empty($driver)) { if ($submit_enabled) { print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Modify")).'"></div>'; } @@ -234,8 +237,7 @@ if ($mode == 'setup' && $user->admin) print '</form>'; } -if ($mode == 'config' && $user->admin) -{ +if ($mode == 'config' && $user->admin) { print dol_get_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic'); print $langs->trans("PrintingDesc")."<br><br>\n"; @@ -287,8 +289,7 @@ if ($mode == 'config' && $user->admin) print dol_get_fiche_end(); } -if ($mode == 'test' && $user->admin) -{ +if ($mode == 'test' && $user->admin) { print dol_get_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic'); print $langs->trans('PrintTestDesc'.$driver)."<br><br>\n"; @@ -325,8 +326,7 @@ if ($mode == 'test' && $user->admin) print dol_get_fiche_end(); } -if ($mode == 'userconf' && $user->admin) -{ +if ($mode == 'userconf' && $user->admin) { print dol_get_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic'); print $langs->trans('PrintUserConfDesc'.$driver)."<br><br>\n"; diff --git a/htdocs/printing/lib/printing.lib.php b/htdocs/printing/lib/printing.lib.php index c899eb105b1..291ebd46ca8 100644 --- a/htdocs/printing/lib/printing.lib.php +++ b/htdocs/printing/lib/printing.lib.php @@ -57,10 +57,10 @@ function printingAdminPrepareHead($mode) } /** TODO This feature seem to be not ready yet. - $head[$h][0] = DOL_URL_ROOT."/printing/admin/printing.php?mode=userconf"; - $head[$h][1] = $langs->trans("UserConf"); - $head[$h][2] = 'userconf'; - $h++; + $head[$h][0] = DOL_URL_ROOT."/printing/admin/printing.php?mode=userconf"; + $head[$h][1] = $langs->trans("UserConf"); + $head[$h][2] = 'userconf'; + $h++; */ //$object=new stdClass(); diff --git a/htdocs/product/admin/dynamic_prices.php b/htdocs/product/admin/dynamic_prices.php index 4d2307d17ac..fdd42bd34d7 100644 --- a/htdocs/product/admin/dynamic_prices.php +++ b/htdocs/product/admin/dynamic_prices.php @@ -37,7 +37,9 @@ $cancel = GETPOST('cancel', 'alpha'); $selection = GETPOST('selection', 'int'); // Security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} //Objects $price_globals = new PriceGlobalVariable($db); @@ -157,8 +159,7 @@ print '<span class="opacitymedium">'.$langs->trans("DynamicPriceDesc").'</span>< print '<br>'; //Global variables table -if ($action != 'create_updater' && $action != 'edit_updater') -{ +if ($action != 'create_updater' && $action != 'edit_updater') { print load_fiche_titre($langs->trans("GlobalVariables"), '', ''); print '<table summary="listofattributes" class="noborder centpercent">'; @@ -171,7 +172,7 @@ if ($action != 'create_updater' && $action != 'edit_updater') $arrayglobalvars = $price_globals->listGlobalVariables(); if (!empty($arrayglobalvars)) { - foreach ($arrayglobalvars as $i=>$entry) { + foreach ($arrayglobalvars as $i => $entry) { print '<tr class="oddeven">'; print '<td>'.$entry->code.'</td>'; print '<td>'.$entry->description.'</td>'; @@ -187,9 +188,10 @@ if ($action != 'create_updater' && $action != 'edit_updater') } print '</table>'; - if (empty($action)) - { - //Action Buttons + if (empty($action)) { + /* + * Action bar + */ print '<div class="tabsAction">'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create_variable">'.$langs->trans("AddVariable").'</a>'; print '</div>'; @@ -234,8 +236,7 @@ if ($action == 'create_variable' || $action == 'edit_variable') { } // Updaters table -if ($action != 'create_variable' && $action != 'edit_variable') -{ +if ($action != 'create_variable' && $action != 'edit_variable') { print load_fiche_titre($langs->trans("GlobalVariableUpdaters"), '', ''); print '<table summary="listofattributes" class="noborder centpercent">'; @@ -250,9 +251,8 @@ if ($action != 'create_variable' && $action != 'edit_variable') print '</tr>'; $arraypriceupdaters = $price_updaters->listUpdaters(); - if (!empty($arraypriceupdaters)) - { - foreach ($arraypriceupdaters as $i=>$entry) { + if (!empty($arraypriceupdaters)) { + foreach ($arraypriceupdaters as $i => $entry) { $code = ""; if ($entry->fk_variable > 0) { $res = $price_globals->fetch($entry->fk_variable); @@ -278,9 +278,10 @@ if ($action != 'create_variable' && $action != 'edit_variable') } print '</table>'; - if (empty($action)) - { - //Action Buttons + if (empty($action)) { + /* + * Action bar + */ print '<div class="tabsAction">'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create_updater&token='.newToken().'">'.$langs->trans("AddUpdater").'</a>'; print '</div>'; diff --git a/htdocs/product/admin/price_rules.php b/htdocs/product/admin/price_rules.php index a38245d32c7..fada766f065 100644 --- a/htdocs/product/admin/price_rules.php +++ b/htdocs/product/admin/price_rules.php @@ -29,8 +29,9 @@ $langs->loadLangs(array('admin', 'products')); $action = GETPOST('action', 'aZ09'); // Security check -if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) +if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) { accessforbidden(); +} $error = 0; @@ -158,7 +159,7 @@ for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { <td></td> <td style="text-align: center"><input type="text" style="text-align: right" name="var_min_percent[1]" size="5" value="<?php echo price(isset($rules[1]) ? $rules[1]->var_min_percent : 0, 2) ?>"> <?php echo $langs->trans('PercentDiscountOver', $langs->trans('SellingPrice').' 1') ?></td> </tr> - <?php for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++): ?> + <?php for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) : ?> <tr> <td class="fieldrequired" style="text-align: center"><?php echo $langs->trans('SellingPrice').' '.$i; diff --git a/htdocs/product/admin/product.php b/htdocs/product/admin/product.php index f268003e1bb..0aa39a53bb3 100644 --- a/htdocs/product/admin/product.php +++ b/htdocs/product/admin/product.php @@ -40,8 +40,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php'; $langs->loadLangs(array("admin", "products")); // Security check -if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) +if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); @@ -56,9 +57,13 @@ $select_pricing_rules = array( 'PRODUIT_CUSTOMER_PRICES'=>$langs->trans('PriceByCustomer'), // Different price for each customer ); $keyforparam = 'PRODUIT_CUSTOMER_PRICES_BY_QTY'; -if ($conf->global->MAIN_FEATURES_LEVEL >= 1 || !empty($conf->global->$keyforparam)) $select_pricing_rules['PRODUIT_CUSTOMER_PRICES_BY_QTY'] = $langs->trans('PriceByQuantity').' ('.$langs->trans("VersionExperimental").')'; // TODO If this is enabled, price must be hidden when price by qty is enabled, also price for quantity must be used when adding product into order/propal/invoice +if ($conf->global->MAIN_FEATURES_LEVEL >= 1 || !empty($conf->global->$keyforparam)) { + $select_pricing_rules['PRODUIT_CUSTOMER_PRICES_BY_QTY'] = $langs->trans('PriceByQuantity').' ('.$langs->trans("VersionExperimental").')'; // TODO If this is enabled, price must be hidden when price by qty is enabled, also price for quantity must be used when adding product into order/propal/invoice +} $keyforparam = 'PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'; -if ($conf->global->MAIN_FEATURES_LEVEL >= 2 || !empty($conf->global->$keyforparam)) $select_pricing_rules['PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'] = $langs->trans('MultiPricesAbility').'+'.$langs->trans('PriceByQuantity').' ('.$langs->trans("VersionExperimental").')'; +if ($conf->global->MAIN_FEATURES_LEVEL >= 2 || !empty($conf->global->$keyforparam)) { + $select_pricing_rules['PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'] = $langs->trans('MultiPricesAbility').'+'.$langs->trans('PriceByQuantity').' ('.$langs->trans("VersionExperimental").')'; +} // Clean param if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_MULTIPRICES_LIMIT)) { @@ -75,10 +80,8 @@ $error = 0; $nomessageinsetmoduleoptions = 1; include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; -if ($action == 'setcodeproduct') -{ - if (dolibarr_set_const($db, "PRODUCT_CODEPRODUCT_ADDON", $value, 'chaine', 0, '', $conf->entity) > 0) - { +if ($action == 'setcodeproduct') { + if (dolibarr_set_const($db, "PRODUCT_CODEPRODUCT_ADDON", $value, 'chaine', 0, '', $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -86,33 +89,30 @@ if ($action == 'setcodeproduct') } } -if ($action == 'other' && GETPOST('value_PRODUIT_LIMIT_SIZE') >= 0) -{ +if ($action == 'other' && GETPOST('value_PRODUIT_LIMIT_SIZE') >= 0) { $res = dolibarr_set_const($db, "PRODUIT_LIMIT_SIZE", GETPOST('value_PRODUIT_LIMIT_SIZE'), 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } } -if ($action == 'other' && GETPOST('value_PRODUIT_MULTIPRICES_LIMIT') > 0) -{ +if ($action == 'other' && GETPOST('value_PRODUIT_MULTIPRICES_LIMIT') > 0) { $res = dolibarr_set_const($db, "PRODUIT_MULTIPRICES_LIMIT", GETPOST('value_PRODUIT_MULTIPRICES_LIMIT'), 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } } -if ($action == 'other') -{ +if ($action == 'other') { $princingrules = GETPOST('princingrule', 'alpha'); - foreach ($select_pricing_rules as $rule => $label) // Loop on each possible mode - { - if ($rule == $princingrules) // We are on selected rule, we enable it - { - if ($princingrules == 'PRODUCT_PRICE_UNIQ') // For this case, we disable entries manually - { + foreach ($select_pricing_rules as $rule => $label) { // Loop on each possible mode + if ($rule == $princingrules) { // We are on selected rule, we enable it + if ($princingrules == 'PRODUCT_PRICE_UNIQ') { // For this case, we disable entries manually $res = dolibarr_set_const($db, 'PRODUIT_MULTIPRICES', 0, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, 'PRODUIT_CUSTOMER_PRICES_BY_QTY', 0, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, 'PRODUIT_CUSTOMER_PRICES', 0, 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, 'PRODUCT_PRICE_UNIQ', 1, 'chaine', 0, '', $conf->entity); } else { $multirule = explode('&', $princingrules); - foreach ($multirule as $rulesselected) - { + foreach ($multirule as $rulesselected) { $res = dolibarr_set_const($db, $rulesselected, 1, 'chaine', 0, '', $conf->entity); } } @@ -151,8 +151,7 @@ if ($action == 'other') if ($value) { $sql_test = "SELECT count(desc_fourn) as cpt FROM ".MAIN_DB_PREFIX."product_fournisseur_price WHERE 1"; $resql = $db->query($sql_test); - if (!$resql && $db->lasterrno == 'DB_ERROR_NOSUCHFIELD') // if the field does not exist, we create it - { + if (!$resql && $db->lasterrno == 'DB_ERROR_NOSUCHFIELD') { // if the field does not exist, we create it $sql_new = "ALTER TABLE ".MAIN_DB_PREFIX."product_fournisseur_price ADD COLUMN desc_fourn text"; $resql_new = $db->query($sql_new); } @@ -163,16 +162,14 @@ if ($action == 'other') if ($value) { $sql_test = "SELECT count(packaging) as cpt FROM ".MAIN_DB_PREFIX."product_fournisseur_price WHERE 1"; $resql = $db->query($sql_test); - if (!$resql && $db->lasterrno == 'DB_ERROR_NOSUCHFIELD') // if the field does not exist, we create it - { + if (!$resql && $db->lasterrno == 'DB_ERROR_NOSUCHFIELD') { // if the field does not exist, we create it $sql_new = "ALTER TABLE ".MAIN_DB_PREFIX."product_fournisseur_price ADD COLUMN packaging double(24,8) DEFAULT 1"; $resql_new = $db->query($sql_new); } } } -if ($action == 'specimen') // For products -{ +if ($action == 'specimen') { // For products $modele = GETPOST('module', 'alpha'); $product = new Product($db); @@ -181,25 +178,21 @@ if ($action == 'specimen') // For products // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/product/doc/pdf_".$modele.".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db); - if ($module->write_file($product, $langs, '') > 0) - { + if ($module->write_file($product, $langs, '') > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=product&file=SPECIMEN.pdf"); return; } else { @@ -213,25 +206,22 @@ if ($action == 'specimen') // For products } // Activate a model -if ($action == 'set') -{ +if ($action == 'set') { $ret = addDocumentModel($value, $type, $label, $scandir); } -if ($action == 'del') -{ +if ($action == 'del') { $ret = delDocumentModel($value, $type); - if ($ret > 0) - { - if ($conf->global->PRODUCT_ADDON_PDF == "$value") dolibarr_del_const($db, 'PRODUCT_ADDON_PDF', $conf->entity); + if ($ret > 0) { + if ($conf->global->PRODUCT_ADDON_PDF == "$value") { + dolibarr_del_const($db, 'PRODUCT_ADDON_PDF', $conf->entity); + } } } // Set default model -if ($action == 'setdoc') -{ - if (dolibarr_set_const($db, "PRODUCT_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) - { +if ($action == 'setdoc') { + if (dolibarr_set_const($db, "PRODUCT_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { // La constante qui a ete lue en avant du nouveau set // on passe donc par une variable pour avoir un affichage coherent $conf->global->PRODUCT_ADDON_PDF = $value; @@ -239,20 +229,23 @@ if ($action == 'setdoc') // On active le modele $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, $type, $label, $scandir); } } -if ($action == 'set') -{ +if ($action == 'set') { $const = "PRODUCT_SPECIAL_".strtoupper(GETPOST('spe', 'alpha')); $value = GETPOST('value'); - if (GETPOST('value', 'alpha')) $res = dolibarr_set_const($db, $const, $value, 'chaine', 0, '', $conf->entity); - else $res = dolibarr_del_const($db, $const, $conf->entity); - if (!($res > 0)) $error++; + if (GETPOST('value', 'alpha')) { + $res = dolibarr_set_const($db, $const, $value, 'chaine', 0, '', $conf->entity); + } else { + $res = dolibarr_del_const($db, $const, $conf->entity); + } + if (!($res > 0)) { + $error++; + } } //if ($action == 'other') @@ -262,10 +255,8 @@ if ($action == 'set') // if (! $res > 0) $error++; //} -if ($action) -{ - if (!$error) - { +if ($action) { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("SetupNotError"), null, 'errors'); @@ -280,12 +271,10 @@ $formbarcode = new FormBarCode($db); $title = $langs->trans('ProductServiceSetup'); $tab = $langs->trans("ProductsAndServices"); -if (empty($conf->product->enabled)) -{ +if (empty($conf->product->enabled)) { $title = $langs->trans('ServiceSetup'); $tab = $langs->trans('Services'); -} elseif (empty($conf->service->enabled)) -{ +} elseif (empty($conf->service->enabled)) { $title = $langs->trans('ProductSetup'); $tab = $langs->trans('Products'); } @@ -315,50 +304,53 @@ print ' <td class="center" width="80">'.$langs->trans("Status").'</td>'; print ' <td class="center" width="60">'.$langs->trans("ShortInfo").'</td>'; print "</tr>\n"; -foreach ($dirproduct as $dirroot) -{ +foreach ($dirproduct as $dirroot) { $dir = dol_buildpath($dirroot, 0); $handle = @opendir($dir); - if (is_resource($handle)) - { + if (is_resource($handle)) { // Loop on each module find in opened directory - while (($file = readdir($handle)) !== false) - { - if (substr($file, 0, 16) == 'mod_codeproduct_' && substr($file, -3) == 'php') - { + while (($file = readdir($handle)) !== false) { + if (substr($file, 0, 16) == 'mod_codeproduct_' && substr($file, -3) == 'php') { $file = substr($file, 0, dol_strlen($file) - 4); try { dol_include_once($dirroot.$file.'.php'); - } catch (Exception $e) - { + } catch (Exception $e) { dol_syslog($e->getMessage(), LOG_ERR); } $modCodeProduct = new $file; // Show modules according to features level - if ($modCodeProduct->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($modCodeProduct->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($modCodeProduct->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($modCodeProduct->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } print '<tr class="oddeven">'."\n"; print '<td width="140">'.$modCodeProduct->name.'</td>'."\n"; print '<td>'.$modCodeProduct->info($langs).'</td>'."\n"; print '<td class="nowrap">'.$modCodeProduct->getExample($langs).'</td>'."\n"; - if (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) && $conf->global->PRODUCT_CODEPRODUCT_ADDON == $file) - { + if (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) && $conf->global->PRODUCT_CODEPRODUCT_ADDON == $file) { print '<td class="center">'."\n"; print img_picto($langs->trans("Activated"), 'switch_on'); print "</td>\n"; } else { $disabled = false; - if (!empty($conf->multicompany->enabled) && (is_object($mc) && !empty($mc->sharings['referent']) && $mc->sharings['referent'] == $conf->entity) ? false : true); + if (!empty($conf->multicompany->enabled) && (is_object($mc) && !empty($mc->sharings['referent']) && $mc->sharings['referent'] == $conf->entity) ? false : true) { + } print '<td class="center">'; - if (!$disabled) print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setcodeproduct&token='.newToken().'&value='.$file.'">'; + if (!$disabled) { + print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setcodeproduct&token='.newToken().'&value='.$file.'">'; + } print img_picto($langs->trans("Disabled"), 'switch_off'); - if (!$disabled) print '</a>'; + if (!$disabled) { + print '</a>'; + } print '</td>'; } @@ -382,12 +374,10 @@ $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; $sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -412,29 +402,21 @@ print "</tr>\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ - foreach (array('', '/doc') as $valdir) - { +foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { $dir = dol_buildpath($reldir."core/modules/product".$valdir); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -442,21 +424,26 @@ 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 == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print '<tr class="oddeven"><td width="100">'; print (empty($module->name) ? $name : $module->name); print "</td><td>\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print '</td>'; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print '<td class="center">'."\n"; print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&value='.$name.'">'; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -470,8 +457,7 @@ foreach ($dirmodels as $reldir) // Defaut print '<td class="center">'; - if ($conf->global->PRODUCT_ADDON_PDF == $name) - { + if ($conf->global->PRODUCT_ADDON_PDF == $name) { print img_picto($langs->trans("Default"), 'on'); } else { print '<a href="'.$_SERVER["PHP_SELF"].'?action=setdoc&amp;token='.newToken().'&amp;value='.$name.'&amp;scan_dir='.$module->scandir.'&amp;label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').'</a>'; @@ -481,8 +467,7 @@ foreach ($dirmodels as $reldir) // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } $htmltooltip .= '<br><br><u>'.$langs->trans("FeaturesSupported").':</u>'; @@ -496,8 +481,7 @@ foreach ($dirmodels as $reldir) // Preview print '<td class="center">'; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'">'.img_object($langs->trans("Preview"), 'contract').'</a>'; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); @@ -568,26 +552,32 @@ print '</tr>'; // Rule for price print '<tr class="oddeven">'; -if (empty($conf->multicompany->enabled)) -{ +if (empty($conf->multicompany->enabled)) { print '<td>'.$langs->trans("PricingRule").'</td>'; } else { print '<td>'.$form->textwithpicto($langs->trans("PricingRule"), $langs->trans("SamePriceAlsoForSharedCompanies"), 1).'</td>'; } print '<td class="right">'; $current_rule = 'PRODUCT_PRICE_UNIQ'; -if (!empty($conf->global->PRODUIT_MULTIPRICES)) $current_rule = 'PRODUIT_MULTIPRICES'; -if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) $current_rule = 'PRODUIT_CUSTOMER_PRICES_BY_QTY'; -if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) $current_rule = 'PRODUIT_CUSTOMER_PRICES'; -if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $current_rule = 'PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'; +if (!empty($conf->global->PRODUIT_MULTIPRICES)) { + $current_rule = 'PRODUIT_MULTIPRICES'; +} +if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { + $current_rule = 'PRODUIT_CUSTOMER_PRICES_BY_QTY'; +} +if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { + $current_rule = 'PRODUIT_CUSTOMER_PRICES'; +} +if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { + $current_rule = 'PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'; +} print $form->selectarray("princingrule", $select_pricing_rules, $current_rule, 0, 0, 0, '', 1, 0, 0, '', 'maxwidth400', 1); print '</td>'; print '</tr>'; // multiprix nombre de prix a proposer -if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) -{ +if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { print '<tr class="oddeven">'; print '<td>'.$langs->trans("MultiPricesNumPrices").'</td>'; print '<td class="right"><input size="3" type="text" class="flat" name="value_PRODUIT_MULTIPRICES_LIMIT" value="'.$conf->global->PRODUIT_MULTIPRICES_LIMIT.'"></td>'; @@ -606,8 +596,7 @@ print '</tr>'; print '<tr class="oddeven">'; print '<td>'.$form->textwithpicto($langs->trans("UseSearchToSelectProduct"), $langs->trans('UseSearchToSelectProductTooltip'), 1).'</td>'; -if (empty($conf->use_javascript_ajax)) -{ +if (empty($conf->use_javascript_ajax)) { print '<td class="nowrap right">'; print $langs->trans("NotAvailableWhenAjaxDisabled"); print '</td>'; @@ -624,8 +613,7 @@ if (empty($conf->use_javascript_ajax)) } print '</tr>'; -if (empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) -{ +if (empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) { print '<tr class="oddeven">'; print '<td>'.$langs->trans("NumberOfProductShowInSelect").'</td>'; print '<td class="right"><input size="3" type="text" class="flat" name="value_PRODUIT_LIMIT_SIZE" value="'.$conf->global->PRODUIT_LIMIT_SIZE.'"></td>'; @@ -685,8 +673,7 @@ print '</tr>'; */ // View product description in thirdparty language -if (!empty($conf->global->MAIN_MULTILANGS)) -{ +if (!empty($conf->global->MAIN_MULTILANGS)) { print '<tr class="oddeven">'; print '<td>'.$langs->trans("ViewProductDescInThirdpartyLanguageAbility").'</td>'; print '<td class="right">'; @@ -695,8 +682,7 @@ if (!empty($conf->global->MAIN_MULTILANGS)) print '</tr>'; } -if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) -{ +if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) { print '<tr class="oddeven">'; print '<td>'.$langs->trans("UseProductFournDesc").'</td>'; print '<td class="right">'; @@ -713,8 +699,7 @@ if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUP } -if (!empty($conf->global->PRODUCT_CANVAS_ABILITY)) -{ +if (!empty($conf->global->PRODUCT_CANVAS_ABILITY)) { // Add canvas feature $dir = DOL_DOCUMENT_ROOT."/product/canvas/"; @@ -723,17 +708,13 @@ if (!empty($conf->global->PRODUCT_CANVAS_ABILITY)) print '<td class="right">'.$langs->trans("Value").'</td>'."\n"; print '</tr>'."\n"; - if (is_dir($dir)) - { + if (is_dir($dir)) { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (file_exists($dir.$file.'/product.'.$file.'.class.php')) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (file_exists($dir.$file.'/product.'.$file.'.class.php')) { $classfile = $dir.$file.'/product.'.$file.'.class.php'; $classname = 'Product'.ucfirst($file); @@ -742,8 +723,7 @@ if (!empty($conf->global->PRODUCT_CANVAS_ABILITY)) $module = $object->module; - if ($conf->$module->enabled) - { + if ($conf->$module->enabled) { print '<tr class="oddeven"><td>'; print $object->description; @@ -752,8 +732,7 @@ if (!empty($conf->global->PRODUCT_CANVAS_ABILITY)) $const = "PRODUCT_SPECIAL_".strtoupper($file); - if ($conf->global->$const) - { + if ($conf->global->$const) { print img_picto($langs->trans("Active"), 'tick'); print '</td><td class="right">'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=set&amp;token='.newToken().'&amp;spe='.urlencode($file).'&amp;value=0">'.$langs->trans("Disable").'</a>'; diff --git a/htdocs/product/admin/product_extrafields.php b/htdocs/product/admin/product_extrafields.php index d82d175a9a7..0962d1ddf44 100644 --- a/htdocs/product/admin/product_extrafields.php +++ b/htdocs/product/admin/product_extrafields.php @@ -38,13 +38,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 = 'product'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -61,12 +65,10 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; $title = $langs->trans('ProductServiceSetup'); $textobject = $langs->trans("ProductsAndServices"); -if (empty($conf->product->enabled)) -{ +if (empty($conf->product->enabled)) { $title = $langs->trans('ServiceSetup'); $textobject = $langs->trans('Services'); -} elseif (empty($conf->service->enabled)) -{ +} elseif (empty($conf->service->enabled)) { $title = $langs->trans('ProductSetup'); $textobject = $langs->trans('Products'); } @@ -90,8 +92,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -104,8 +105,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -117,8 +117,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/product/admin/product_lot_extrafields.php b/htdocs/product/admin/product_lot_extrafields.php index e89e5741cce..91e19ee1fa7 100644 --- a/htdocs/product/admin/product_lot_extrafields.php +++ b/htdocs/product/admin/product_lot_extrafields.php @@ -38,13 +38,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 = 'product_lot'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -81,8 +85,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -95,8 +98,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -108,8 +110,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/product/admin/product_supplier_extrafields.php b/htdocs/product/admin/product_supplier_extrafields.php index 54d56ad9dd5..8c3a10a4b74 100644 --- a/htdocs/product/admin/product_supplier_extrafields.php +++ b/htdocs/product/admin/product_supplier_extrafields.php @@ -39,13 +39,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 = 'product_fournisseur_price'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -62,12 +66,10 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; $title = $langs->trans('ProductServiceSetup'); $textobject = $langs->trans("ProductsAndServices"); -if (empty($conf->product->enabled)) -{ +if (empty($conf->product->enabled)) { $title = $langs->trans('ServiceSetup'); $textobject = $langs->trans('Services'); -} elseif (empty($conf->service->enabled)) -{ +} elseif (empty($conf->service->enabled)) { $title = $langs->trans('ProductSetup'); $textobject = $langs->trans('Products'); } @@ -91,8 +93,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -105,8 +106,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -118,8 +118,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/product/admin/product_tools.php b/htdocs/product/admin/product_tools.php index 3bf85bdff4f..674e90f3614 100644 --- a/htdocs/product/admin/product_tools.php +++ b/htdocs/product/admin/product_tools.php @@ -35,7 +35,9 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $langs->loadLangs(array('admin', 'products')); // Security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $oldvatrate = GETPOST('oldvatrate', 'alpha'); @@ -48,19 +50,16 @@ $newvatrate = GETPOST('newvatrate', 'alpha'); * Actions */ -if ($action == 'convert') -{ +if ($action == 'convert') { $error = 0; - if ($oldvatrate == $newvatrate) - { + if ($oldvatrate == $newvatrate) { $langs->load("errors"); setEventMessages($langs->trans("ErrorNewValueCantMatchOldValue"), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $country_id = $mysoc->country_id; // TODO Allow to choose country into form $nbrecordsmodified = 0; @@ -69,62 +68,65 @@ if ($action == 'convert') // Clean vat code old $vat_src_code_old = ''; - if (preg_match('/\((.*)\)/', $oldvatrate, $reg)) - { + if (preg_match('/\((.*)\)/', $oldvatrate, $reg)) { $vat_src_code_old = $reg[1]; $oldvatrateclean = preg_replace('/\s*\(.*\)/', '', $oldvatrate); // Remove code into vatrate. - } else $oldvatrateclean = $oldvatrate; + } else { + $oldvatrateclean = $oldvatrate; + } // Clean vat code new $vat_src_code_new = ''; - if (preg_match('/\((.*)\)/', $newvatrate, $reg)) - { + if (preg_match('/\((.*)\)/', $newvatrate, $reg)) { $vat_src_code_new = $reg[1]; $newvatrateclean = preg_replace('/\s*\(.*\)/', '', $newvatrate); // Remove code into vatrate. - } else $newvatrateclean = $newvatrate; + } else { + $newvatrateclean = $newvatrate; + } // If country to edit is my country, so we change customer prices - if ($country_id == $mysoc->country_id) - { + if ($country_id == $mysoc->country_id) { $sql = 'SELECT rowid'; $sql .= ' FROM '.MAIN_DB_PREFIX.'product'; $sql .= ' WHERE entity IN ('.getEntity('product').')'; $sql .= " AND tva_tx = '".$db->escape($oldvatrateclean)."'"; - if ($vat_src_code_old) $sql .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'"; - else " AND default_vat_code = IS NULL"; + if ($vat_src_code_old) { + $sql .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'"; + } else { + " AND default_vat_code = IS NULL"; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $objectstatic = new Product($db); // Object init must be into loop to avoid to get value of previous step $ret = $objectstatic->fetch($obj->rowid); - if ($ret > 0) - { + if ($ret > 0) { $ret = 0; $retm = 0; $updatelevel1 = false; // Update multiprice $listofmulti = array_reverse($objectstatic->multiprices, true); // To finish with level 1 - foreach ($listofmulti as $level => $multiprices) - { + foreach ($listofmulti as $level => $multiprices) { $price_base_type = $objectstatic->multiprices_base_type[$level]; // Get price_base_type of product/service to keep the same for update - if (empty($price_base_type)) continue; // Discard not defined price levels + if (empty($price_base_type)) { + continue; // Discard not defined price levels + } - if ($price_base_type == 'TTC') - { + if ($price_base_type == 'TTC') { $newprice = price2num($objectstatic->multiprices_ttc[$level], 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals) $newminprice = $objectstatic->multiprices_min_ttc[$level]; } else { $newprice = price2num($objectstatic->multiprices[$level], 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals) $newminprice = $objectstatic->multiprices_min[$level]; } - if ($newminprice > $newprice) $newminprice = $newprice; + if ($newminprice > $newprice) { + $newminprice = $newprice; + } $newvat = str_replace('*', '', $newvatrate); $localtaxes_type = getLocalTaxesFromRate($newvat, 0, $mysoc, $mysoc); @@ -134,45 +136,51 @@ if ($action == 'convert') //print "$objectstatic->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n"; $retm = $objectstatic->updatePrice($newprice, $price_base_type, $user, $newvatrateclean, $newminprice, $newlevel, $newnpr, 0, 0, $localtaxes_type, $newdefaultvatcode); - if ($retm < 0) - { + if ($retm < 0) { $error++; break; } - if ($newlevel == 1) $updatelevel1 = true; + if ($newlevel == 1) { + $updatelevel1 = true; + } } // Update single price $price_base_type = $objectstatic->price_base_type; // Get price_base_type of product/service to keep the same for update - if ($price_base_type == 'TTC') - { + if ($price_base_type == 'TTC') { $newprice = price2num($objectstatic->price_ttc, 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals) $newminprice = $objectstatic->price_min_ttc; } else { $newprice = price2num($objectstatic->price, 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals) $newminprice = $objectstatic->price_min; } - if ($newminprice > $newprice) $newminprice = $newprice; + if ($newminprice > $newprice) { + $newminprice = $newprice; + } $newvat = str_replace('*', '', $newvatrate); $localtaxes_type = getLocalTaxesFromRate($newvat, 0, $mysoc, $mysoc); $newnpr = $objectstatic->recuperableonly; $newdefaultvatcode = $vat_src_code_new; $newlevel = 0; - if (!empty($price_base_type) && !$updatelevel1) - { + if (!empty($price_base_type) && !$updatelevel1) { //print "$objectstatic->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n"; $ret = $objectstatic->updatePrice($newprice, $price_base_type, $user, $newvatrateclean, $newminprice, $newlevel, $newnpr, 0, 0, $localtaxes_type, $newdefaultvatcode); } - if ($ret < 0 || $retm < 0) $error++; - else $nbrecordsmodified++; + if ($ret < 0 || $retm < 0) { + $error++; + } else { + $nbrecordsmodified++; + } } unset($objectstatic); $i++; } - } else dol_print_error($db); + } else { + dol_print_error($db); + } } $fourn = new Fournisseur($db); @@ -182,24 +190,24 @@ if ($action == 'convert') $sql .= ' FROM '.MAIN_DB_PREFIX.'product_fournisseur_price as pfp, '.MAIN_DB_PREFIX.'societe as s'; $sql .= ' WHERE pfp.fk_soc = s.rowid AND pfp.entity IN ('.getEntity('product').')'; $sql .= " AND tva_tx = '".$db->escape($oldvatrate)."'"; - if ($vat_src_code_old) $sql .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'"; - else " AND default_vat_code = IS NULL"; + if ($vat_src_code_old) { + $sql .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'"; + } else { + " AND default_vat_code = IS NULL"; + } $sql .= " AND s.fk_pays = ".((int) $country_id); //print $sql; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $objectstatic2 = new ProductFournisseur($db); // Object init must be into loop to avoid to get value of previous step $ret = $objectstatic2->fetch_product_fournisseur_price($obj->rowid); - if ($ret > 0) - { + if ($ret > 0) { $ret = 0; $retm = 0; $updatelevel1 = false; $price_base_type = 'HT'; @@ -226,34 +234,39 @@ if ($action == 'convert') $newsupplierreputation = $objectstatic2->supplier_reputation; $newlevel = 0; - if (!empty($price_base_type) && !$updatelevel1) - { + if (!empty($price_base_type) && !$updatelevel1) { //print "$objectstatic2->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n"; $fourn->id = $obj->fk_soc; $ret = $objectstatic2->update_buyprice($obj->qty, $newprice, $user, $price_base_type, $fourn, $obj->fk_availability, $obj->ref_fourn, $newvat, '', $newpercent, 0, $newnpr, $newdeliverydelay, $newsupplierreputation, $localtaxes_type, $newdefaultvatcode); } - if ($ret < 0 || $retm < 0) $error++; - else $nbrecordsmodified++; + if ($ret < 0 || $retm < 0) { + $error++; + } else { + $nbrecordsmodified++; + } } unset($objectstatic2); $i++; } - } else dol_print_error($db); + } else { + dol_print_error($db); + } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); } // Output result - if (!$error) - { - if ($nbrecordsmodified > 0) setEventMessages($langs->trans("RecordsModified", $nbrecordsmodified), null, 'mesgs'); - else setEventMessages($langs->trans("NoRecordFound"), null, 'warnings'); + if (!$error) { + if ($nbrecordsmodified > 0) { + setEventMessages($langs->trans("RecordsModified", $nbrecordsmodified), null, 'mesgs'); + } else { + setEventMessages($langs->trans("NoRecordFound"), null, 'warnings'); + } } else { setEventMessages($langs->trans("Error"), null, 'errors'); } @@ -274,8 +287,7 @@ print load_fiche_titre($title, '', 'title_setup'); print $langs->trans("ProductVatMassChangeDesc").'<br><br>'; -if (empty($mysoc->country_code)) -{ +if (empty($mysoc->country_code)) { $langs->load("errors"); $warnpicto = img_error($langs->trans("WarningMandatorySetupNotComplete")); print '<br><a href="'.DOL_URL_ROOT.'/admin/company.php?mainmenu=home">'.$warnpicto.' '.$langs->trans("WarningMandatorySetupNotComplete").'</a>'; diff --git a/htdocs/product/admin/stock_extrafields.php b/htdocs/product/admin/stock_extrafields.php index 9b5a0f23f07..3f860564b48 100644 --- a/htdocs/product/admin/stock_extrafields.php +++ b/htdocs/product/admin/stock_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 = 'entrepot'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -76,8 +80,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create">'.$langs->trans("NewAttribute").'</a></div>'; print "</div>"; @@ -90,8 +93,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print "<br>"; print load_fiche_titre($langs->trans('NewAttribute')); @@ -103,8 +105,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/product/agenda.php b/htdocs/product/agenda.php index 8a7ddf385d9..bf25675865f 100644 --- a/htdocs/product/agenda.php +++ b/htdocs/product/agenda.php @@ -36,10 +36,11 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; // Load translation files required by the page $langs->load("companies"); -if (GETPOST('actioncode', 'array')) -{ +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)); } @@ -48,19 +49,27 @@ $search_agenda_label = GETPOST('search_agenda_label'); // Security check $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -if ($user->socid) $id = $user->socid; +if ($user->socid) { + $id = $user->socid; +} $result = restrictedArea($user, 'produit|service', $id, 'product&product'); $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,DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC'; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('agendathirdparty')); @@ -72,20 +81,19 @@ $hookmanager->initHooks(array('agendathirdparty')); $parameters = array('id'=>$id); $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 (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // 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 $actioncode = ''; $search_agenda_label = ''; } @@ -101,8 +109,7 @@ $contactstatic = new Contact($db); $form = new Form($db); -if ($id > 0 || $ref) -{ +if ($id > 0 || $ref) { require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; @@ -113,12 +120,18 @@ if ($id > 0 || $ref) $result = $object->fetch($id, $ref); $title = $langs->trans("Agenda"); - if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/productnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name." - ".$title; + if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/productnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name." - ".$title; + } llxHeader('', $title); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $type = $langs->trans('Product'); - if ($object->isService()) $type = $langs->trans('Service'); + if ($object->isService()) { + $type = $langs->trans('Service'); + } $head = product_prepare_head($object); @@ -130,7 +143,9 @@ if ($id > 0 || $ref) $object->next_prev_filter = " fk_product_type = ".$object->type; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -154,10 +169,11 @@ if ($id > 0 || $ref) $out = ''; $permok = $user->rights->agenda->myactions->create; - if ((!empty($objproduct->id) || !empty($objcon->id)) && $permok) - { + if ((!empty($objproduct->id) || !empty($objcon->id)) && $permok) { //$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'; - if (get_class($objproduct) == 'Product') $out .= '&amp;prodid='.$objproduct->id.'&origin=product&originid='.$id; + if (get_class($objproduct) == 'Product') { + $out .= '&amp;prodid='.$objproduct->id.'&origin=product&originid='.$id; + } $out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1'; //$out.=$langs->trans("AddAnAction").' '; //$out.=img_picto($langs->trans("AddAnAction"),'filenew'); @@ -170,19 +186,21 @@ if ($id > 0 || $ref) $morehtmlcenter = ''; - if (!empty($conf->agenda->enabled)) - { + if (!empty($conf->agenda->enabled)) { $linktocreatetimeBtnStatus = !empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create); $morehtmlcenter = dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out, '', $linktocreatetimeBtnStatus); } - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { print '<br>'; $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("ActionsOnProduct"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $morehtmlcenter, '', 0, 1, 1); diff --git a/htdocs/product/ajax/products.php b/htdocs/product/ajax/products.php index 198d49defaf..9dacb4e547d 100644 --- a/htdocs/product/ajax/products.php +++ b/htdocs/product/ajax/products.php @@ -23,13 +23,27 @@ * \brief File to return Ajax response on product list request. */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (empty($_GET['keysearch']) && !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'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (empty($_GET['keysearch']) && !defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} require '../../main.inc.php'; @@ -58,8 +72,7 @@ $hidepriceinlabel = GETPOST('hidepriceinlabel', 'int'); dol_syslog(join(',', $_GET)); // print_r($_GET); -if (!empty($action) && $action == 'fetch' && !empty($id)) -{ +if (!empty($action) && $action == 'fetch' && !empty($id)) { // action='fetch' is used to get product information on a product. So when action='fetch', id must be the product id. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; @@ -68,8 +81,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id)) $object = new Product($db); $ret = $object->fetch($id); - if ($ret > 0) - { + if ($ret > 0) { $outref = $object->ref; $outlabel = $object->label; $outlabel_trans =''; @@ -82,7 +94,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id)) $found = false; $price_level = 1; - if ($socid > 0 ) { + if ($socid > 0) { $thirdpartytemp = new Societe($db); $thirdpartytemp->fetch($socid); @@ -107,8 +119,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id)) } // Price by qty - if (!empty($price_by_qty_rowid) && $price_by_qty_rowid >= 1 && (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) // If we need a particular price related to qty - { + if (!empty($price_by_qty_rowid) && $price_by_qty_rowid >= 1 && (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) { // If we need a particular price related to qty $sql = "SELECT price, unitprice, quantity, remise_percent"; $sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty "; $sql .= " WHERE rowid=".$price_by_qty_rowid.""; @@ -129,8 +140,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id)) } // Multiprice - if (!$found && isset($price_level) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) // If we need a particular price level (from 1 to 6) - { + if (!$found && isset($price_level) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) { // If we need a particular price level (from 1 to 6) $sql = "SELECT price, price_ttc, price_base_type, tva_tx"; $sql .= " FROM ".MAIN_DB_PREFIX."product_price "; $sql .= " WHERE fk_product = '".$id."'"; @@ -203,8 +213,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id)) top_httphead(); - if (empty($htmlname)) - { + if (empty($htmlname)) { print json_encode(array()); return; } @@ -214,8 +223,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id)) $idprod = (!empty($match[0]) ? $match[0] : ''); - if (GETPOST($htmlname, 'alpha') == '' && (!$idprod || !GETPOST($idprod, 'alpha'))) - { + if (GETPOST($htmlname, 'alpha') == '' && (!$idprod || !GETPOST($idprod, 'alpha'))) { print json_encode(array()); return; } @@ -233,6 +241,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id)) $db->close(); - if ($outjson) + if ($outjson) { print json_encode($arrayresult); + } } diff --git a/htdocs/product/canvas/product/actions_card_product.class.php b/htdocs/product/canvas/product/actions_card_product.class.php index e7e3c7ea4b3..55a8977a4bd 100644 --- a/htdocs/product/canvas/product/actions_card_product.class.php +++ b/htdocs/product/canvas/product/actions_card_product.class.php @@ -80,8 +80,10 @@ class ActionsCardProduct global $conf, $langs, $user, $mysoc, $canvas; global $form, $formproduct; - $tmpobject = new Product($this->db); - if (!empty($id) || !empty($ref)) $tmpobject->fetch($id, $ref); + $tmpobject = new Product($this->db); + if (!empty($id) || !empty($ref)) { + $tmpobject->fetch($id, $ref); + } $this->object = $tmpobject; //parent::assign_values($action); @@ -113,8 +115,7 @@ class ActionsCardProduct // Note $this->tpl['note'] = nl2br($this->note); - if ($action == 'create') - { + if ($action == 'create') { // Price $this->tpl['price'] = $this->price; $this->tpl['price_min'] = $this->price_min; @@ -124,8 +125,7 @@ class ActionsCardProduct $this->tpl['tva_tx'] = $form->load_tva("tva_tx", -1, $mysoc, ''); } - if ($action == 'view') - { + if ($action == 'view') { $head = product_prepare_head($this->object); $this->tpl['showrefnav'] = $form->showrefnav($this->object, 'ref', '', 1, 'ref'); @@ -152,19 +152,16 @@ class ActionsCardProduct $this->tpl['note'] = $this->object->note; $this->tpl['seuil_stock_alerte'] = $this->object->seuil_stock_alerte; - if ($action == 'create') - { + if ($action == 'create') { // Title $this->tpl['title'] = $langs->trans("NewProduct"); } - if ($action == 'edit') - { + if ($action == 'edit') { $this->tpl['title'] = $langs->trans('Modify').' '.$langs->trans('Product').' : '.$this->object->ref; } - if ($action == 'create' || $action == 'edit') - { + if ($action == 'create' || $action == 'edit') { // Status $statutarray = array('1' => $langs->trans("OnSell"), '0' => $langs->trans("NotOnSell")); $this->tpl['status'] = $form->selectarray('statut', $statutarray, $this->object->status); @@ -196,12 +193,10 @@ class ActionsCardProduct $this->tpl['volume_units'] = $formproduct->selectMeasuringUnits("volume_units", "volume", $this->object->volume_units, 0, 2); } - if ($action == 'view') - { + if ($action == 'view') { // Photo $this->tpl['nblines'] = 4; - if ($this->object->is_photo_available($conf->product->multidir_output[$this->object->entity])) - { + if ($this->object->is_photo_available($conf->product->multidir_output[$this->object->entity])) { $this->tpl['photos'] = $this->object->show_photos('product', $conf->product->multidir_output[$this->object->entity], 1, 1, 0, 0, 0, 80); } @@ -209,34 +204,29 @@ class ActionsCardProduct $this->tpl['finished'] = $this->object->getLibFinished(); // Weight - if ($this->object->weight != '') - { + if ($this->object->weight != '') { $this->tpl['weight'] = $this->object->weight." ".measuringUnitString(0, "weight", $this->object->weight_units); } // Length - if ($this->object->length != '') - { + if ($this->object->length != '') { $this->tpl['length'] = $this->object->length." ".measuringUnitString(0, "size", $this->object->length_units); } // Surface - if ($this->object->surface != '') - { + if ($this->object->surface != '') { $this->tpl['surface'] = $this->object->surface." ".measuringUnitString(0, "surface", $this->object->surface_units); } // Volume - if ($this->object->volume != '') - { + if ($this->object->volume != '') { $this->tpl['volume'] = $this->object->volume." ".measuringUnitString(0, "volume", $this->object->volume_units); } $this->tpl['fiche_end'] = dol_get_fiche_end(); } - if ($action == 'list') - { + if ($action == 'list') { $this->LoadListDatas($limit, $offset, $sortfield, $sortorder); } } @@ -260,13 +250,11 @@ class ActionsCardProduct $sql .= " ORDER BY rang ASC"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $fieldlist = array(); $obj = $this->db->fetch_object($resql); @@ -315,10 +303,8 @@ class ActionsCardProduct // Clean parameters $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); - foreach ($this->field_list as $field) - { - if ($field['enabled']) - { + foreach ($this->field_list as $field) { + if ($field['enabled']) { $fieldname = "s".$field['alias']; $$fieldname = GETPOST($fieldname); } @@ -330,10 +316,8 @@ class ActionsCardProduct $sql .= 'p.rowid, p.price_base_type, p.fk_product_type, p.seuil_stock_alerte, p.entity'; // Fields not requiered - foreach ($this->field_list as $field) - { - if ($field['enabled']) - { + foreach ($this->field_list as $field) { + if ($field['enabled']) { $sql .= ", ".$field['name']." as ".$field['alias']; } } @@ -341,37 +325,34 @@ class ActionsCardProduct $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; $sql .= " WHERE p.entity IN (".getEntity('product').")"; - if ($sall) - { + if ($sall) { $clause = ''; $sql .= " AND ("; - foreach ($this->field_list as $field) - { - if ($field['enabled']) - { + foreach ($this->field_list as $field) { + if ($field['enabled']) { $sql .= $clause." ".$field['name']." LIKE '%".$this->db->escape($sall)."%'"; - if ($clause == '') $clause = ' OR'; + if ($clause == '') { + $clause = ' OR'; + } } } $sql .= ")"; } // Search fields - foreach ($this->field_list as $field) - { - if ($field['enabled']) - { + foreach ($this->field_list as $field) { + if ($field['enabled']) { $fieldname = "s".$field['alias']; - if (${$fieldname}) $sql .= " AND ".$field['name']." LIKE '%".$this->db->escape(${$fieldname})."%'"; + if (${$fieldname}) { + $sql .= " AND ".$field['name']." LIKE '%".$this->db->escape(${$fieldname})."%'"; + } } } - if (isset($_GET["tosell"]) && dol_strlen($_GET["tosell"]) > 0) - { + if (isset($_GET["tosell"]) && dol_strlen($_GET["tosell"]) > 0) { $sql .= " AND p.tosell = ".$this->db->escape($_GET["tosell"]); } - if (isset($_GET["canvas"]) && dol_strlen($_GET["canvas"]) > 0) - { + if (isset($_GET["canvas"]) && dol_strlen($_GET["canvas"]) > 0) { $sql .= " AND p.canvas = '".$this->db->escape($_GET["canvas"])."'"; } $sql .= $this->db->order($sortfield, $sortorder); @@ -379,42 +360,45 @@ class ActionsCardProduct //print $sql; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $datas = array(); $obj = $this->db->fetch_object($resql); $datas["id"] = $obj->rowid; - foreach ($this->field_list as $field) - { - if ($field['enabled']) - { + foreach ($this->field_list as $field) { + if ($field['enabled']) { $alias = $field['alias']; - if ($alias == 'ref') - { + if ($alias == 'ref') { $this->id = $obj->rowid; $this->ref = $obj->$alias; $this->type = $obj->fk_product_type; $this->entity = $obj->entity; $datas[$alias] = $this->getNomUrl(1, '', 24); - } elseif ($alias == 'stock') - { + } elseif ($alias == 'stock') { $this->load_stock(); - if ($this->stock_reel < $obj->seuil_stock_alerte) $datas[$alias] = $this->stock_reel.' '.img_warning($langs->trans("StockTooLow")); - else $datas[$alias] = $this->stock_reel; - } elseif ($alias == 'label') $datas[$alias] = dol_trunc($obj->$alias, 40); - elseif (preg_match('/price/i', $alias)) $datas[$alias] = price($obj->$alias); - elseif ($alias == 'datem') $datas[$alias] = dol_print_date($this->db->jdate($obj->$alias), 'day'); - elseif ($alias == 'status') $datas[$alias] = $this->LibStatut($obj->$alias, 5); - else $datas[$alias] = $obj->$alias; + if ($this->stock_reel < $obj->seuil_stock_alerte) { + $datas[$alias] = $this->stock_reel.' '.img_warning($langs->trans("StockTooLow")); + } else { + $datas[$alias] = $this->stock_reel; + } + } elseif ($alias == 'label') { + $datas[$alias] = dol_trunc($obj->$alias, 40); + } elseif (preg_match('/price/i', $alias)) { + $datas[$alias] = price($obj->$alias); + } elseif ($alias == 'datem') { + $datas[$alias] = dol_print_date($this->db->jdate($obj->$alias), 'day'); + } elseif ($alias == 'status') { + $datas[$alias] = $this->LibStatut($obj->$alias, 5); + } else { + $datas[$alias] = $obj->$alias; + } } } diff --git a/htdocs/product/canvas/product/tpl/card_create.tpl.php b/htdocs/product/canvas/product/tpl/card_create.tpl.php index 042734f8fd3..b862eddefc5 100644 --- a/htdocs/product/canvas/product/tpl/card_create.tpl.php +++ b/htdocs/product/canvas/product/tpl/card_create.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -53,7 +52,9 @@ print dol_get_fiche_head(''); <tr> <td class="fieldrequired" width="20%"><?php echo $langs->trans("Ref"); ?></td> <td><input name="ref" size="40" maxlength="32" value="<?php echo $object->ref; ?>"> -<?php if ($refalreadyexists == 1) echo $langs->trans("RefAlreadyExists"); ?> +<?php if ($refalreadyexists == 1) { + echo $langs->trans("RefAlreadyExists"); +} ?> </td></tr> <tr> diff --git a/htdocs/product/canvas/product/tpl/card_edit.tpl.php b/htdocs/product/canvas/product/tpl/card_edit.tpl.php index 512ab13416b..21f2edefc2d 100644 --- a/htdocs/product/canvas/product/tpl/card_edit.tpl.php +++ b/htdocs/product/canvas/product/tpl/card_edit.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } diff --git a/htdocs/product/canvas/product/tpl/card_view.tpl.php b/htdocs/product/canvas/product/tpl/card_view.tpl.php index 2158be2b24d..a5f793e246d 100644 --- a/htdocs/product/canvas/product/tpl/card_view.tpl.php +++ b/htdocs/product/canvas/product/tpl/card_view.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -37,7 +36,9 @@ $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_value $object->next_prev_filter = " fk_product_type = ".$object->type; $shownav = 1; -if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; +if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; +} dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); ?> diff --git a/htdocs/product/canvas/service/actions_card_service.class.php b/htdocs/product/canvas/service/actions_card_service.class.php index 48f924bbb46..b27bbf5771c 100644 --- a/htdocs/product/canvas/service/actions_card_service.class.php +++ b/htdocs/product/canvas/service/actions_card_service.class.php @@ -79,14 +79,15 @@ class ActionsCardService global $conf, $langs, $user, $mysoc, $canvas; global $form, $formproduct; - $tmpobject = new Product($this->db); - if (!empty($id) || !empty($ref)) $tmpobject->fetch($id, $ref); + $tmpobject = new Product($this->db); + if (!empty($id) || !empty($ref)) { + $tmpobject->fetch($id, $ref); + } $this->object = $tmpobject; //parent::assign_values($action); - foreach ($this->object as $key => $value) - { + foreach ($this->object as $key => $value) { $this->tpl[$key] = $value; } @@ -113,8 +114,7 @@ class ActionsCardService // Note $this->tpl['note'] = nl2br($this->note); - if ($action == 'create') - { + if ($action == 'create') { // Price $this->tpl['price'] = $this->price; $this->tpl['price_min'] = $this->price_min; @@ -124,8 +124,7 @@ class ActionsCardService $this->tpl['tva_tx'] = $form->load_tva("tva_tx", -1, $mysoc, ''); } - if ($action == 'view') - { + if ($action == 'view') { $head = product_prepare_head($this->object); $this->tpl['showrefnav'] = $form->showrefnav($this->object, 'ref', '', 1, 'ref'); @@ -155,19 +154,16 @@ class ActionsCardService // Duration $this->tpl['duration_value'] = $this->object->duration_value; - if ($action == 'create') - { + if ($action == 'create') { // Title $this->tpl['title'] = $langs->trans("NewService"); } - if ($action == 'edit') - { + if ($action == 'edit') { $this->tpl['title'] = $langs->trans('Modify').' '.$langs->trans('Service').' : '.$this->object->ref; } - if ($action == 'create' || $action == 'edit') - { + if ($action == 'create' || $action == 'edit') { // Status $statutarray = array('1' => $langs->trans("OnSell"), '0' => $langs->trans("NotOnSell")); $this->tpl['status'] = $form->selectarray('statut', $statutarray, $this->object->status); @@ -192,21 +188,17 @@ class ActionsCardService $this->tpl['duration_unit'] = $duration_unit; } - if ($action == 'view') - { + if ($action == 'view') { // Photo $this->tpl['nblines'] = 4; - if ($this->object->is_photo_available($conf->service->multidir_output[$this->object->entity])) - { + if ($this->object->is_photo_available($conf->service->multidir_output[$this->object->entity])) { $this->tpl['photos'] = $this->object->show_photos('product', $conf->service->multidir_output[$this->object->entity], 1, 1, 0, 0, 0, 80); } // Duration - if ($this->object->duration_value > 1) - { + if ($this->object->duration_value > 1) { $dur = array("h"=>$langs->trans("Hours"), "d"=>$langs->trans("Days"), "w"=>$langs->trans("Weeks"), "m"=>$langs->trans("Months"), "y"=>$langs->trans("Years")); - } elseif ($this->object->duration_value > 0) - { + } elseif ($this->object->duration_value > 0) { $dur = array("h"=>$langs->trans("Hour"), "d"=>$langs->trans("Day"), "w"=>$langs->trans("Week"), "m"=>$langs->trans("Month"), "y"=>$langs->trans("Year")); } $this->tpl['duration_unit'] = $langs->trans($dur[$this->object->duration_unit]); @@ -214,8 +206,7 @@ class ActionsCardService $this->tpl['fiche_end'] = dol_get_fiche_end(); } - if ($action == 'list') - { + if ($action == 'list') { $this->LoadListDatas($limit, $offset, $sortfield, $sortorder); } } @@ -239,13 +230,11 @@ class ActionsCardService $sql .= " ORDER BY rang ASC"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $fieldlist = array(); $obj = $this->db->fetch_object($resql); @@ -294,40 +283,43 @@ class ActionsCardService $sql .= ' p.duration, p.tosell as statut, p.seuil_stock_alerte'; $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; // We'll need this table joined to the select in order to filter by categ - if ($search_categ) $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp"; - if (GETPOST("fourn_id", 'int') > 0) - { + if ($search_categ) { + $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp"; + } + if (GETPOST("fourn_id", 'int') > 0) { $fourn_id = GETPOST("fourn_id", 'int'); $sql .= ", ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; } $sql .= " WHERE p.entity IN (".getEntity('product').")"; - if ($search_categ) $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ - if ($sall) - { + if ($search_categ) { + $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ + } + if ($sall) { $sql .= " AND (p.ref LIKE '%".$this->db->escape($sall)."%' OR p.label LIKE '%".$this->db->escape($sall)."%' OR p.description LIKE '%".$this->db->escape($sall)."%' OR p.note LIKE '%".$this->db->escape($sall)."%')"; } - if ($sref) $sql .= " AND p.ref LIKE '%".$sref."%'"; - if ($search_barcode) $sql .= " AND p.barcode LIKE '%".$search_barcode."%'"; - if ($snom) $sql .= " AND p.label LIKE '%".$this->db->escape($snom)."%'"; - if (isset($_GET["tosell"]) && dol_strlen($_GET["tosell"]) > 0) - { + if ($sref) { + $sql .= " AND p.ref LIKE '%".$sref."%'"; + } + if ($search_barcode) { + $sql .= " AND p.barcode LIKE '%".$search_barcode."%'"; + } + if ($snom) { + $sql .= " AND p.label LIKE '%".$this->db->escape($snom)."%'"; + } + if (isset($_GET["tosell"]) && dol_strlen($_GET["tosell"]) > 0) { $sql .= " AND p.tosell = ".$this->db->escape($_GET["tosell"]); } - if (isset($_GET["canvas"]) && dol_strlen($_GET["canvas"]) > 0) - { + if (isset($_GET["canvas"]) && dol_strlen($_GET["canvas"]) > 0) { $sql .= " AND p.canvas = '".$this->db->escape($_GET["canvas"])."'"; } - if ($catid) - { + if ($catid) { $sql .= " AND cp.fk_categorie = ".$catid; } - if ($fourn_id > 0) - { + if ($fourn_id > 0) { $sql .= " AND p.rowid = pfp.fk_product AND pfp.fk_soc = ".$fourn_id; } // Insert categ filter - if ($search_categ) - { + if ($search_categ) { $sql .= " AND cp.fk_categorie = ".$this->db->escape($search_categ); } $sql .= $this->db->order($sortfield, $sortorder); @@ -336,13 +328,11 @@ class ActionsCardService $this->list_datas = array(); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $datas = array(); $obj = $this->db->fetch_object($resql); diff --git a/htdocs/product/canvas/service/tpl/card_create.tpl.php b/htdocs/product/canvas/service/tpl/card_create.tpl.php index 13fceff4e22..ce3c4f5cc58 100644 --- a/htdocs/product/canvas/service/tpl/card_create.tpl.php +++ b/htdocs/product/canvas/service/tpl/card_create.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -50,7 +49,9 @@ print dol_get_fiche_head(''); <tr> <td class="fieldrequired" width="20%"><?php echo $langs->trans("Ref"); ?></td> <td><input name="ref" size="40" maxlength="32" value="<?php echo $object->ref; ?>"> -<?php if ($refalreadyexists == 1) echo $langs->trans("RefAlreadyExists"); ?> +<?php if ($refalreadyexists == 1) { + echo $langs->trans("RefAlreadyExists"); +} ?> </td></tr> <tr> diff --git a/htdocs/product/canvas/service/tpl/card_edit.tpl.php b/htdocs/product/canvas/service/tpl/card_edit.tpl.php index 8e4613f21b0..4906b0dcf2c 100644 --- a/htdocs/product/canvas/service/tpl/card_edit.tpl.php +++ b/htdocs/product/canvas/service/tpl/card_edit.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } diff --git a/htdocs/product/canvas/service/tpl/card_view.tpl.php b/htdocs/product/canvas/service/tpl/card_view.tpl.php index d342d102af0..c816a36ae34 100644 --- a/htdocs/product/canvas/service/tpl/card_view.tpl.php +++ b/htdocs/product/canvas/service/tpl/card_view.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -37,7 +36,9 @@ $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_value $object->next_prev_filter = " fk_product_type = ".$object->type; $shownav = 1; -if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; +if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; +} dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); ?> diff --git a/htdocs/product/card.php b/htdocs/product/card.php index 55c29aa1381..352256f5c42 100644 --- a/htdocs/product/card.php +++ b/htdocs/product/card.php @@ -53,18 +53,36 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php'; -if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; -if (!empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -if (!empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +if (!empty($conf->propal->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +} +if (!empty($conf->facture->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +} +if (!empty($conf->commande->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +} +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +} +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +} +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('products', 'other')); -if (!empty($conf->stock->enabled)) $langs->load("stocks"); -if (!empty($conf->facture->enabled)) $langs->load("bills"); -if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); +if (!empty($conf->stock->enabled)) { + $langs->load("stocks"); +} +if (!empty($conf->facture->enabled)) { + $langs->load("bills"); +} +if (!empty($conf->productbatch->enabled)) { + $langs->load("productbatch"); +} $mesg = ''; $error = 0; $errors = array(); @@ -91,7 +109,9 @@ $accountancy_code_buy_export = GETPOST('accountancy_code_buy_export', 'alpha'); // by default 'alphanohtml' (better security); hidden conf MAIN_SECURITY_ALLOW_UNSECURED_LABELS_WITH_HTML allows basic html $label_security_check = empty($conf->global->MAIN_SECURITY_ALLOW_UNSECURED_LABELS_WITH_HTML) ? 'alphanohtml' : 'restricthtml'; -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $object = new Product($db); $object->type = $type; // so test later to fill $usercancxxx is correct @@ -100,17 +120,21 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref); - if (!empty($conf->product->enabled)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref); - elseif (!empty($conf->service->enabled)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref); + if (!empty($conf->product->enabled)) { + $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref); + } elseif (!empty($conf->service->enabled)) { + $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref); + } - if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs - { - if (!empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; - else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { // For backward compatiblity, we scan also old dirs + if (!empty($conf->product->enabled)) { + $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; + } else { + $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; + } } } @@ -119,8 +143,7 @@ $modulepart = 'product'; // Get object canvas (By default, this is not defined, so standard usage of dolibarr) $canvas = !empty($object->canvas) ? $object->canvas : GETPOST("canvas"); $objcanvas = null; -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('product', 'card', $canvas); @@ -140,23 +163,27 @@ $hookmanager->initHooks(array('productcard', 'globalcard')); * Actions */ -if ($cancel) $action = ''; +if ($cancel) { + $action = ''; +} $usercanread = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->lire) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->lire)); $usercancreate = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer)); $usercandelete = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->supprimer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->supprimer)); $createbarcode = empty($conf->barcode->enabled) ? 0 : 1; -if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->creer_advance)) $createbarcode = 0; +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->creer_advance)) { + $createbarcode = 0; +} $parameters = array('id'=>$id, 'ref'=>$ref, '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)) -{ +if (empty($reshook)) { // Type - if ($action == 'setfk_product_type' && $usercancreate) - { + if ($action == 'setfk_product_type' && $usercancreate) { $result = $object->setValueFrom('fk_product_type', GETPOST('fk_product_type'), '', null, 'text', '', $user, 'PRODUCT_MODIFY'); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; @@ -170,29 +197,31 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Barcode type - if ($action == 'setfk_barcode_type' && $createbarcode) - { + if ($action == 'setfk_barcode_type' && $createbarcode) { $result = $object->setValueFrom('fk_barcode_type', GETPOST('fk_barcode_type'), '', null, 'text', '', $user, 'PRODUCT_MODIFY'); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } // Barcode value - if ($action == 'setbarcode' && $createbarcode) - { + if ($action == 'setbarcode' && $createbarcode) { $result = $object->check_barcode(GETPOST('barcode'), GETPOST('barcode_type_code')); - if ($result >= 0) - { + if ($result >= 0) { $result = $object->setValueFrom('barcode', GETPOST('barcode'), '', null, 'text', '', $user, 'PRODUCT_MODIFY'); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { $langs->load("errors"); - if ($result == -1) $errors[] = 'ErrorBadBarCodeSyntax'; - elseif ($result == -2) $errors[] = 'ErrorBarCodeRequired'; - elseif ($result == -3) $errors[] = 'ErrorBarCodeAlreadyUsed'; - else $errors[] = 'FailedToValidateBarCode'; + if ($result == -1) { + $errors[] = 'ErrorBadBarCodeSyntax'; + } elseif ($result == -2) { + $errors[] = 'ErrorBarCodeRequired'; + } elseif ($result == -3) { + $errors[] = 'ErrorBarCodeAlreadyUsed'; + } else { + $errors[] = 'FailedToValidateBarCode'; + } $error++; setEventMessages($errors, null, 'errors'); @@ -200,43 +229,42 @@ if (empty($reshook)) } // Add a product or service - if ($action == 'add' && $usercancreate) - { + if ($action == 'add' && $usercancreate) { $error = 0; - if (!GETPOST('label', $label_security_check)) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Label')), null, 'errors'); - $action = "create"; - $error++; - } - if (empty($ref)) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Ref')), null, 'errors'); - $action = "create"; - $error++; - } - if (!empty($duration_value) && empty($duration_unit)) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Unit')), null, 'errors'); - $action = "create"; - $error++; - } + if (!GETPOST('label', $label_security_check)) { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Label')), null, 'errors'); + $action = "create"; + $error++; + } + if (empty($ref)) { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Ref')), null, 'errors'); + $action = "create"; + $error++; + } + if (!empty($duration_value) && empty($duration_unit)) { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Unit')), null, 'errors'); + $action = "create"; + $error++; + } - if (!$error) - { + if (!$error) { $units = GETPOST('units', 'int'); - $object->ref = $ref; - $object->label = GETPOST('label', $label_security_check); - $object->price_base_type = GETPOST('price_base_type', 'aZ09'); + $object->ref = $ref; + $object->label = GETPOST('label', $label_security_check); + $object->price_base_type = GETPOST('price_base_type', 'aZ09'); - if ($object->price_base_type == 'TTC') + if ($object->price_base_type == 'TTC') { $object->price_ttc = GETPOST('price'); - else $object->price = GETPOST('price'); - if ($object->price_base_type == 'TTC') + } else { + $object->price = GETPOST('price'); + } + if ($object->price_base_type == 'TTC') { $object->price_min_ttc = GETPOST('price_min'); - else $object->price_min = GETPOST('price_min'); + } else { + $object->price_min = GETPOST('price_min'); + } $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)' @@ -247,8 +275,7 @@ if (empty($reshook)) $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes $reg = array(); - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in update price. $vatratecode = $reg[1]; // Get record from code @@ -258,8 +285,7 @@ if (empty($reshook)) $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; $sql .= " AND t.code = '".$db->escape($vatratecode)."'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $npr = $obj->recuperableonly; $localtax1 = $obj->localtax1; @@ -289,8 +315,7 @@ if (empty($reshook)) $stdobject->element = 'product'; $stdobject->barcode_type = GETPOST('fk_barcode_type'); $result = $stdobject->fetch_barcode(); - if ($result < 0) - { + if ($result < 0) { $error++; $mesg = 'Failed to get bar code type information '; setEventMessages($mesg.$stdobject->error, $mesg.$stdobject->errors, 'errors'); @@ -345,20 +370,41 @@ if (empty($reshook)) $accountancy_code_buy_intra = GETPOST('accountancy_code_buy_intra', 'alpha'); $accountancy_code_buy_export = GETPOST('accountancy_code_buy_export', 'alpha'); - if ($accountancy_code_sell <= 0) { $object->accountancy_code_sell = ''; } else { $object->accountancy_code_sell = $accountancy_code_sell; } - if ($accountancy_code_sell_intra <= 0) { $object->accountancy_code_sell_intra = ''; } else { $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; } - if ($accountancy_code_sell_export <= 0) { $object->accountancy_code_sell_export = ''; } else { $object->accountancy_code_sell_export = $accountancy_code_sell_export; } - if ($accountancy_code_buy <= 0) { $object->accountancy_code_buy = ''; } else { $object->accountancy_code_buy = $accountancy_code_buy; } - if ($accountancy_code_buy_intra <= 0) { $object->accountancy_code_buy_intra = ''; } else { $object->accountancy_code_buy_intra = $accountancy_code_buy_intra; } - if ($accountancy_code_buy_export <= 0) { $object->accountancy_code_buy_export = ''; } else { $object->accountancy_code_buy_export = $accountancy_code_buy_export; } + if ($accountancy_code_sell <= 0) { + $object->accountancy_code_sell = ''; + } else { + $object->accountancy_code_sell = $accountancy_code_sell; + } + if ($accountancy_code_sell_intra <= 0) { + $object->accountancy_code_sell_intra = ''; + } else { + $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; + } + if ($accountancy_code_sell_export <= 0) { + $object->accountancy_code_sell_export = ''; + } else { + $object->accountancy_code_sell_export = $accountancy_code_sell_export; + } + if ($accountancy_code_buy <= 0) { + $object->accountancy_code_buy = ''; + } else { + $object->accountancy_code_buy = $accountancy_code_buy; + } + if ($accountancy_code_buy_intra <= 0) { + $object->accountancy_code_buy_intra = ''; + } else { + $object->accountancy_code_buy_intra = $accountancy_code_buy_intra; + } + if ($accountancy_code_buy_export <= 0) { + $object->accountancy_code_buy_export = ''; + } else { + $object->accountancy_code_buy_export = $accountancy_code_buy_export; + } // MultiPrix - if (!empty($conf->global->PRODUIT_MULTIPRICES)) - { - for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) - { - if (GETPOSTISSET("price_".$i)) - { + if (!empty($conf->global->PRODUIT_MULTIPRICES)) { + for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { + if (GETPOSTISSET("price_".$i)) { $object->multiprices["$i"] = price2num($_POST["price_".$i], 'MU'); $object->multiprices_base_type["$i"] = $_POST["multiprices_base_type_".$i]; } else { @@ -369,23 +415,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++; + } - if (!$error) - { + if (!$error) { $id = $object->create($user); } - if ($id > 0) - { + if ($id > 0) { // Category association $categories = GETPOST('categories', 'array'); $object->setCategories($categories); - if (!empty($backtopage)) - { + if (!empty($backtopage)) { $backtopage = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $backtopage); // New method to autoselect project after a New on another form object creation - if (preg_match('/\?/', $backtopage)) $backtopage .= '&socid='.$object->id; // Old method + if (preg_match('/\?/', $backtopage)) { + $backtopage .= '&socid='.$object->id; // Old method + } header("Location: ".$backtopage); exit; } else { @@ -393,22 +440,22 @@ if (empty($reshook)) exit; } } else { - if (count($object->errors)) setEventMessages($object->error, $object->errors, 'errors'); - else setEventMessages($langs->trans($object->error), null, 'errors'); + if (count($object->errors)) { + setEventMessages($object->error, $object->errors, 'errors'); + } else { + setEventMessages($langs->trans($object->error), null, 'errors'); + } $action = "create"; } } } // Update a product or service - if ($action == 'update' && $usercancreate) - { - if (GETPOST('cancel', 'alpha')) - { + if ($action == 'update' && $usercancreate) { + if (GETPOST('cancel', 'alpha')) { $action = ''; } else { - if ($object->id > 0) - { + if ($object->id > 0) { $object->oldcopy = clone $object; $object->ref = $ref; @@ -418,8 +465,7 @@ if (empty($reshook)) $object->description = $desc; $object->url = GETPOST('url'); - if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $object->note_private = dol_htmlcleanlastbr(GETPOST('note_private', 'restricthtml')); $object->note = $object->note_private; } @@ -432,9 +478,9 @@ if (empty($reshook)) $object->fk_default_warehouse = GETPOST('fk_default_warehouse'); // removed from update view so GETPOST always empty /* - $object->seuil_stock_alerte = GETPOST('seuil_stock_alerte'); - $object->desiredstock = GETPOST('desiredstock'); - */ + $object->seuil_stock_alerte = GETPOST('seuil_stock_alerte'); + $object->desiredstock = GETPOST('desiredstock'); + */ $object->duration_value = GETPOST('duration_value', 'int'); $object->duration_unit = GETPOST('duration_unit', 'alpha'); @@ -474,8 +520,7 @@ if (empty($reshook)) $stdobject->element = 'product'; $stdobject->barcode_type = GETPOST('fk_barcode_type'); $result = $stdobject->fetch_barcode(); - if ($result < 0) - { + if ($result < 0) { $error++; $mesg = 'Failed to get bar code type information '; setEventMessages($mesg.$stdobject->error, $mesg.$stdobject->errors, 'errors'); @@ -491,34 +536,64 @@ if (empty($reshook)) $accountancy_code_buy_intra = GETPOST('accountancy_code_buy_intra', 'alpha'); $accountancy_code_buy_export = GETPOST('accountancy_code_buy_export', 'alpha'); - if ($accountancy_code_sell <= 0) { $object->accountancy_code_sell = ''; } else { $object->accountancy_code_sell = $accountancy_code_sell; } - if ($accountancy_code_sell_intra <= 0) { $object->accountancy_code_sell_intra = ''; } else { $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; } - if ($accountancy_code_sell_export <= 0) { $object->accountancy_code_sell_export = ''; } else { $object->accountancy_code_sell_export = $accountancy_code_sell_export; } - if ($accountancy_code_buy <= 0) { $object->accountancy_code_buy = ''; } else { $object->accountancy_code_buy = $accountancy_code_buy; } - if ($accountancy_code_buy_intra <= 0) { $object->accountancy_code_buy_intra = ''; } else { $object->accountancy_code_buy_intra = $accountancy_code_buy_intra; } - if ($accountancy_code_buy_export <= 0) { $object->accountancy_code_buy_export = ''; } else { $object->accountancy_code_buy_export = $accountancy_code_buy_export; } + if ($accountancy_code_sell <= 0) { + $object->accountancy_code_sell = ''; + } else { + $object->accountancy_code_sell = $accountancy_code_sell; + } + if ($accountancy_code_sell_intra <= 0) { + $object->accountancy_code_sell_intra = ''; + } else { + $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; + } + if ($accountancy_code_sell_export <= 0) { + $object->accountancy_code_sell_export = ''; + } else { + $object->accountancy_code_sell_export = $accountancy_code_sell_export; + } + if ($accountancy_code_buy <= 0) { + $object->accountancy_code_buy = ''; + } else { + $object->accountancy_code_buy = $accountancy_code_buy; + } + if ($accountancy_code_buy_intra <= 0) { + $object->accountancy_code_buy_intra = ''; + } else { + $object->accountancy_code_buy_intra = $accountancy_code_buy_intra; + } + if ($accountancy_code_buy_export <= 0) { + $object->accountancy_code_buy_export = ''; + } else { + $object->accountancy_code_buy_export = $accountancy_code_buy_export; + } // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error && $object->check()) - { - if ($object->update($object->id, $user) > 0) - { + if (!$error && $object->check()) { + if ($object->update($object->id, $user) > 0) { // Category association $categories = GETPOST('categories', 'array'); $object->setCategories($categories); $action = 'view'; } else { - if (count($object->errors)) setEventMessages($object->error, $object->errors, 'errors'); - else setEventMessages($langs->trans($object->error), null, 'errors'); + if (count($object->errors)) { + setEventMessages($object->error, $object->errors, 'errors'); + } else { + setEventMessages($langs->trans($object->error), null, 'errors'); + } $action = 'edit'; } } else { - if (count($object->errors)) setEventMessages($object->error, $object->errors, 'errors'); - else setEventMessages($langs->trans("ErrorProductBadRefOrLabel"), null, 'errors'); + if (count($object->errors)) { + setEventMessages($object->error, $object->errors, 'errors'); + } else { + setEventMessages($langs->trans("ErrorProductBadRefOrLabel"), null, 'errors'); + } $action = 'edit'; } } @@ -526,36 +601,31 @@ if (empty($reshook)) } // Action clone object - if ($action == 'confirm_clone' && $confirm != 'yes') { $action = ''; } - if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) - { - if (!GETPOST('clone_content') && !GETPOST('clone_prices')) - { + if ($action == 'confirm_clone' && $confirm != 'yes') { + $action = ''; + } + if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) { + if (!GETPOST('clone_content') && !GETPOST('clone_prices')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { $db->begin(); $originalId = $id; - if ($object->id > 0) - { + if ($object->id > 0) { $object->ref = GETPOST('clone_ref', 'alphanohtml'); $object->status = 0; $object->status_buy = 0; $object->id = null; $object->barcode = -1; - if ($object->check()) - { + if ($object->check()) { $object->context['createfromclone'] = 'createfromclone'; $id = $object->create($user); - if ($id > 0) - { - if (GETPOST('clone_composition')) - { + if ($id > 0) { + if (GETPOST('clone_composition')) { $result = $object->clone_associations($originalId, $id); - if ($result < 1) - { + if ($result < 1) { $db->rollback(); setEventMessages($langs->trans('ErrorProductClone'), null, 'errors'); header("Location: ".$_SERVER["PHP_SELF"]."?id=".$originalId); @@ -563,12 +633,10 @@ if (empty($reshook)) } } - if (GETPOST('clone_categories')) - { + if (GETPOST('clone_categories')) { $result = $object->cloneCategories($originalId, $id); - if ($result < 1) - { + if ($result < 1) { $db->rollback(); setEventMessages($langs->trans('ErrorProductClone'), null, 'errors'); header("Location: ".$_SERVER["PHP_SELF"]."?id=".$originalId); @@ -597,8 +665,7 @@ if (empty($reshook)) } else { $id = $originalId; - if ($object->error == 'ErrorProductAlreadyExists') - { + if ($object->error == 'ErrorProductAlreadyExists') { $db->rollback(); $refalreadyexists++; @@ -610,8 +677,7 @@ if (empty($reshook)) $object->fetch($id); } else { $db->rollback(); - if (count($object->errors)) - { + if (count($object->errors)) { setEventMessages($object->error, $object->errors, 'errors'); dol_print_error($db, $object->errors); } else { @@ -631,13 +697,13 @@ if (empty($reshook)) } // Delete a product - if ($action == 'confirm_delete' && $confirm != 'yes') { $action = ''; } - if ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) - { + if ($action == 'confirm_delete' && $confirm != 'yes') { + $action = ''; + } + if ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) { $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { header('Location: '.DOL_URL_ROOT.'/product/list.php?type='.$object->type.'&delprod='.urlencode($object->ref)); exit; } else { @@ -649,35 +715,28 @@ if (empty($reshook)) // Add product into object - if ($object->id > 0 && $action == 'addin') - { + if ($object->id > 0 && $action == 'addin') { $thirpdartyid = 0; - if (GETPOST('propalid') > 0) - { + if (GETPOST('propalid') > 0) { $propal = new Propal($db); $result = $propal->fetch(GETPOST('propalid')); - if ($result <= 0) - { + if ($result <= 0) { dol_print_error($db, $propal->error); exit; } $thirpdartyid = $propal->socid; - } elseif (GETPOST('commandeid') > 0) - { + } elseif (GETPOST('commandeid') > 0) { $commande = new Commande($db); $result = $commande->fetch(GETPOST('commandeid')); - if ($result <= 0) - { + if ($result <= 0) { dol_print_error($db, $commande->error); exit; } $thirpdartyid = $commande->socid; - } elseif (GETPOST('factureid') > 0) - { + } elseif (GETPOST('factureid') > 0) { $facture = new Facture($db); $result = $facture->fetch(GETPOST('factureid')); - if ($result <= 0) - { + if ($result <= 0) { dol_print_error($db, $facture->error); exit; } @@ -696,7 +755,9 @@ if (empty($reshook)) $tva_tx = get_default_tva($mysoc, $soc, $object->id); $tva_npr = get_default_npr($mysoc, $soc, $object->id); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $localtax1_tx = get_localtax($tva_tx, 1, $soc, $mysoc, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $soc, $mysoc, $tva_npr); @@ -743,8 +804,7 @@ if (empty($reshook)) if (GETPOST('propalid') > 0) { // Define cost price for margin calculation $buyprice = 0; - if (($result = $propal->defineBuyPrice($pu_ht, price2num(GETPOST('remise_percent'), 2), $object->id)) < 0) - { + if (($result = $propal->defineBuyPrice($pu_ht, price2num(GETPOST('remise_percent'), 2), $object->id)) < 0) { dol_syslog($langs->trans('FailedToGetCostPrice')); setEventMessages($langs->trans('FailedToGetCostPrice'), null, 'errors'); } else { @@ -784,8 +844,7 @@ if (empty($reshook)) } elseif (GETPOST('commandeid') > 0) { // Define cost price for margin calculation $buyprice = 0; - if (($result = $commande->defineBuyPrice($pu_ht, GETPOST('remise_percent', 2), $object->id)) < 0) - { + if (($result = $commande->defineBuyPrice($pu_ht, GETPOST('remise_percent', 2), $object->id)) < 0) { dol_syslog($langs->trans('FailedToGetCostPrice')); setEventMessages($langs->trans('FailedToGetCostPrice'), null, 'errors'); } else { @@ -825,8 +884,7 @@ if (empty($reshook)) } elseif (GETPOST('factureid') > 0) { // Define cost price for margin calculation $buyprice = 0; - if (($result = $facture->defineBuyPrice($pu_ht, GETPOST('remise_percent', 2), $object->id)) < 0) - { + if (($result = $facture->defineBuyPrice($pu_ht, GETPOST('remise_percent', 2), $object->id)) < 0) { dol_syslog($langs->trans('FailedToGetCostPrice')); setEventMessages($langs->trans('FailedToGetCostPrice'), null, 'errors'); } else { @@ -885,15 +943,13 @@ if (empty($reshook)) $title = $langs->trans('ProductServiceCard'); $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); -if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) -{ +if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Card'); - $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos|DE:Modul_Produkte'; } -if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) -{ +if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Card'); - $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios|DE:Modul_Leistungen'; } llxHeader('', $title, $helpurl); @@ -902,36 +958,37 @@ $form = new Form($db); $formfile = new FormFile($db); $formproduct = new FormProduct($db); $formcompany = new FormCompany($db); -if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); +if (!empty($conf->accounting->enabled)) { + $formaccounting = new FormAccounting($db); +} // Load object modBarCodeProduct $res = 0; -if (!empty($conf->barcode->enabled) && !empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) -{ +if (!empty($conf->barcode->enabled) && !empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) { $module = strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM); $dirbarcode = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']); - foreach ($dirbarcode as $dirroot) - { + foreach ($dirbarcode as $dirroot) { $res = dol_include_once($dirroot.$module.'.php'); - if ($res) break; + if ($res) { + break; + } } - if ($res > 0) - { + if ($res > 0) { $modBarCodeProduct = new $module(); } } -if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) -{ +if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { // ----------------------------------------- // When used with CANVAS // ----------------------------------------- - if (empty($object->error) && $id) - { + if (empty($object->error) && $id) { $object = new Product($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->display_canvas($action); // Show template @@ -939,8 +996,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // ----------------------------------------- // When used in standard mode // ----------------------------------------- - if ($action == 'create' && $usercancreate) - { + if ($action == 'create' && $usercancreate) { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -955,13 +1011,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Load object modCodeProduct $module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard'); - if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') - { + if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $result = dol_include_once('/core/modules/product/'.$module.'.php'); - if ($result > 0) - { + if ($result > 0) { $modCodeProduct = new $module(); } @@ -971,10 +1025,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; print '<input type="hidden" name="type" value="'.$type.'">'."\n"; - if (!empty($modCodeProduct->code_auto)) + if (!empty($modCodeProduct->code_auto)) { print '<input type="hidden" name="code_auto" value="1">'; - if (!empty($modBarCodeProduct->code_auto)) + } + if (!empty($modBarCodeProduct->code_auto)) { print '<input type="hidden" name="barcode_auto" value="1">'; + } print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; if ($type == 1) { @@ -989,8 +1045,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // We set country_id, country_code and country for the selected country $object->country_id = GETPOSTISSET('country_id') ? GETPOST('country_id', 'int') : null; - if ($object->country_id > 0) - { + if ($object->country_id > 0) { $tmparray = getCountry($object->country_id, 'all'); $object->country_code = $tmparray['code']; $object->country = $tmparray['label']; @@ -1002,10 +1057,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr>'; $tmpcode = ''; - if (!empty($modCodeProduct->code_auto)) $tmpcode = $modCodeProduct->getNextValue($object, $type); + if (!empty($modCodeProduct->code_auto)) { + $tmpcode = $modCodeProduct->getNextValue($object, $type); + } print '<td class="titlefieldcreate fieldrequired">'.$langs->trans("Ref").'</td><td colspan="3"><input id="ref" name="ref" class="maxwidth200" maxlength="128" value="'.dol_escape_htmltag(GETPOSTISSET('ref') ? GETPOST('ref', 'alphanohtml') : $tmpcode).'">'; - if ($refalreadyexists) - { + if ($refalreadyexists) { print $langs->trans("RefAlreadyExists"); } print '</td></tr>'; @@ -1026,33 +1082,39 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Batch number management - if (!empty($conf->productbatch->enabled)) - { + if (!empty($conf->productbatch->enabled)) { print '<tr><td>'.$langs->trans("ManageLotSerial").'</td><td colspan="3">'; - $statutarray = array('0' => $langs->trans("ProductStatusNotOnBatch"), '1' => $langs->trans("ProductStatusOnBatch")); + $statutarray = array('0' => $langs->trans("ProductStatusNotOnBatch"), '1' => $langs->trans("ProductStatusOnBatch"), '2' => $langs->trans("ProductStatusOnSerial")); print $form->selectarray('status_batch', $statutarray, GETPOST('status_batch')); print '</td></tr>'; } $showbarcode = empty($conf->barcode->enabled) ? 0 : 1; - if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0; + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) { + $showbarcode = 0; + } - if ($showbarcode) - { - print '<tr><td>'.$langs->trans('BarcodeType').'</td><td>'; - if (GETPOSTISSET('fk_barcode_type')) { - $fk_barcode_type = GETPOST('fk_barcode_type'); + if ($showbarcode) { + print '<tr><td>'.$langs->trans('BarcodeType').'</td><td>'; + if (GETPOSTISSET('fk_barcode_type')) { + $fk_barcode_type = GETPOST('fk_barcode_type'); } else { - if (empty($fk_barcode_type) && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; + if (empty($fk_barcode_type) && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) { + $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; + } } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php'; $formbarcode = new FormBarCode($db); print $formbarcode->selectBarcodeType($fk_barcode_type, 'fk_barcode_type', 1); print '</td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td>'.$langs->trans("BarcodeValue").'</td><td>'; $tmpcode = GETPOSTISSET('barcode') ? GETPOST('barcode') : $object->barcode; - if (empty($tmpcode) && !empty($modBarCodeProduct->code_auto)) $tmpcode = $modBarCodeProduct->getNextValue($object, $fk_barcode_type); + if (empty($tmpcode) && !empty($modBarCodeProduct->code_auto)) { + $tmpcode = $modBarCodeProduct->getNextValue($object, $fk_barcode_type); + } print '<input class="maxwidth100" type="text" name="barcode" value="'.dol_escape_htmltag($tmpcode).'">'; print '</td></tr>'; } @@ -1070,8 +1132,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<input type="text" name="url" class="quatrevingtpercent" value="'.GETPOST('url').'">'; print '</td></tr>'; - if ($type != 1 && !empty($conf->stock->enabled)) - { + if ($type != 1 && !empty($conf->stock->enabled)) { // Default warehouse print '<tr><td>'.$langs->trans("DefaultWarehouse").'</td><td>'; print $formproduct->selectWarehouses(GETPOST('fk_default_warehouse'), 'fk_default_warehouse', 'warehouseopen', 1); @@ -1085,7 +1146,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr><td>'.$form->textwithpicto($langs->trans("StockLimit"), $langs->trans("StockLimitDesc"), 1).'</td><td>'; print '<input name="seuil_stock_alerte" class="maxwidth50" value="'.GETPOST('seuil_stock_alerte').'">'; print '</td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } // Stock desired level print '<td>'.$form->textwithpicto($langs->trans("DesiredStock"), $langs->trans("DesiredStockDesc"), 1).'</td><td>'; print '<input name="desiredstock" class="maxwidth50" value="'.GETPOST('desiredstock').'">'; @@ -1096,16 +1159,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Duration - if ($type == 1) - { + if ($type == 1) { print '<tr><td>'.$langs->trans("Duration").'</td><td colspan="3">'; print '<input name="duration_value" size="4" value="'.GETPOST('duration_value', 'int').'">'; print $formproduct->selectMeasuringUnits("duration_unit", "time", GETPOST('duration_value', 'alpha'), 0, 1); print '</td></tr>'; } - if ($type != 1) // Nature, Weight and volume only applies to products and not to services - { + if ($type != 1) { // Nature, Weight and volume only applies to products and not to services // Nature print '<tr><td>'.$form->textwithpicto($langs->trans("NatureOfProductShort"), $langs->trans("NatureOfProductDesc")).'</td><td colspan="3">'; $statutarray = array('1' => $langs->trans("Finished"), '0' => $langs->trans("RowMaterial")); @@ -1119,8 +1180,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Brut Length - if (empty($conf->global->PRODUCT_DISABLE_SIZE)) - { + if (empty($conf->global->PRODUCT_DISABLE_SIZE)) { print '<tr><td>'.$langs->trans("Length").' x '.$langs->trans("Width").' x '.$langs->trans("Height").'</td><td colspan="3">'; print '<input name="size" class="width50" value="'.GETPOST('size').'"> x '; print '<input name="sizewidth" class="width50" value="'.GETPOST('sizewidth').'"> x '; @@ -1128,16 +1188,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print $formproduct->selectMeasuringUnits("size_units", "size", GETPOSTISSET('size_units') ?GETPOST('size_units', 'alpha') : '0', 0, 2); print '</td></tr>'; } - if (empty($conf->global->PRODUCT_DISABLE_SURFACE)) - { + if (empty($conf->global->PRODUCT_DISABLE_SURFACE)) { // Brut Surface print '<tr><td>'.$langs->trans("Surface").'</td><td colspan="3">'; print '<input name="surface" size="4" value="'.GETPOST('surface').'">'; print $formproduct->selectMeasuringUnits("surface_units", "surface", GETPOSTISSET('surface_units') ?GETPOST('surface_units', 'alpha') : '0', 0, 2); print '</td></tr>'; } - if (empty($conf->global->PRODUCT_DISABLE_VOLUME)) - { + if (empty($conf->global->PRODUCT_DISABLE_VOLUME)) { // Brut Volume print '<tr><td>'.$langs->trans("Volume").'</td><td colspan="3">'; print '<input name="volume" size="4" value="'.GETPOST('volume').'">'; @@ -1145,8 +1203,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; } - if (!empty($conf->global->PRODUCT_ADD_NET_MEASURE)) - { + if (!empty($conf->global->PRODUCT_ADD_NET_MEASURE)) { // Net Measure print '<tr><td>'.$langs->trans("NetMeasure").'</td><td colspan="3">'; print '<input name="net_measure" size="4" value="'.GETPOST('net_measure').'">'; @@ -1156,8 +1213,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Units - if (!empty($conf->global->PRODUCT_USE_UNITS)) - { + if (!empty($conf->global->PRODUCT_USE_UNITS)) { print '<tr><td>'.$langs->trans('DefaultUnitToShow').'</td>'; print '<td colspan="3">'; print $form->selectUnits(empty($line->fk_unit) ? $conf->global->PRODUCT_USE_UNITS : $line->fk_unit, 'units'); @@ -1165,8 +1221,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Custom code - if (empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO) && empty($type)) - { + if (empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO) && empty($type)) { print '<tr><td>'.$langs->trans("CustomCode").'</td><td><input name="customcode" class="maxwidth100onsmartphone" value="'.GETPOST('customcode').'"></td></tr>'; // Origin country @@ -1174,15 +1229,17 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<td>'; print img_picto('', 'globe-americas', 'class="paddingrightonly"'); print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id') : $object->country_id), 'country_id', '', 0, 'minwidth300 widthcentpercentminusx'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '</td>'; // State - if (empty($conf->global->PRODUCT_DISABLE_STATE)) - { - if ($conf->browser->layout == 'phone') print '</tr><tr>'; - if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) - { + if (empty($conf->global->PRODUCT_DISABLE_STATE)) { + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } + if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) { print '<td>'.$form->editfieldkey('RegionStateOrigin', 'state_id', '', $object, 0).'</td><td colspan="3">'; } else { print '<td>'.$form->editfieldkey('StateOrigin', 'state_id', '', $object, 0).'</td><td colspan="3">'; @@ -1199,8 +1256,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $parameters = array('colspan' => 3, 'cols' => '3'); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } @@ -1228,8 +1284,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<hr>'; - if (!empty($conf->global->PRODUIT_MULTIPRICES)) - { + if (!empty($conf->global->PRODUIT_MULTIPRICES)) { // We do no show price array on create when multiprices enabled. // We must set them on prices tab. print '<table class="border centpercent">'; @@ -1269,8 +1324,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Accountancy codes print '<table class="border centpercent">'; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { // Accountancy_code_sell print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellCode").'</td>'; print '<td>'; @@ -1279,12 +1333,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } else { $accountancy_code_sell = (GETPOSTISSET('accountancy_code_sell') ? GETPOST('accountancy_code_sell', 'alpha') : $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT); } - print $formaccounting->select_account($accountancy_code_sell, 'accountancy_code_sell', 1, null, 1, 1, ''); + print $formaccounting->select_account($accountancy_code_sell, 'accountancy_code_sell', 1, null, 1, 1, 'minwidth100 maxwidth300 maxwidthonsmartphone', 1); print '</td></tr>'; // Accountancy_code_sell_intra - if ($mysoc->isInEEC()) - { + if ($mysoc->isInEEC()) { print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellIntraCode").'</td>'; print '<td>'; if ($type == 0) { @@ -1292,36 +1345,34 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } else { $accountancy_code_sell_intra = (GETPOSTISSET('accountancy_code_sell_intra') ? GETPOST('accountancy_code_sell_intra', 'alpha') : $conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT); } - print $formaccounting->select_account($accountancy_code_sell_intra, 'accountancy_code_sell_intra', 1, null, 1, 1, ''); + print $formaccounting->select_account($accountancy_code_sell_intra, 'accountancy_code_sell_intra', 1, null, 1, 1, 'minwidth100 maxwidth300 maxwidthonsmartphone', 1); print '</td></tr>'; } // Accountancy_code_sell_export print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellExportCode").'</td>'; print '<td>'; - if ($type == 0) - { + if ($type == 0) { $accountancy_code_sell_export = (GETPOST('accountancy_code_sell_export') ? GETPOST('accountancy_code_sell_export', 'alpha') : $conf->global->ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT); } else { $accountancy_code_sell_export = (GETPOST('accountancy_code_sell_export') ? GETPOST('accountancy_code_sell_export', 'alpha') : $conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT); } - print $formaccounting->select_account($accountancy_code_sell_export, 'accountancy_code_sell_export', 1, null, 1, 1, ''); + print $formaccounting->select_account($accountancy_code_sell_export, 'accountancy_code_sell_export', 1, null, 1, 1, 'minwidth100 maxwidth300 maxwidthonsmartphone', 1); print '</td></tr>'; // Accountancy_code_buy print '<tr><td>'.$langs->trans("ProductAccountancyBuyCode").'</td>'; print '<td>'; - if ($type == 0) { - $accountancy_code_buy = (GETPOST('accountancy_code_buy', 'alpha') ? (GETPOST('accountancy_code_buy', 'alpha')) : $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT); - } else { - $accountancy_code_buy = (GETPOST('accountancy_code_buy', 'alpha') ? (GETPOST('accountancy_code_buy', 'alpha')) : $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT); - } - print $formaccounting->select_account($accountancy_code_buy, 'accountancy_code_buy', 1, null, 1, 1, ''); + if ($type == 0) { + $accountancy_code_buy = (GETPOST('accountancy_code_buy', 'alpha') ? (GETPOST('accountancy_code_buy', 'alpha')) : $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT); + } else { + $accountancy_code_buy = (GETPOST('accountancy_code_buy', 'alpha') ? (GETPOST('accountancy_code_buy', 'alpha')) : $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT); + } + print $formaccounting->select_account($accountancy_code_buy, 'accountancy_code_buy', 1, null, 1, 1, 'minwidth100 maxwidth300 maxwidthonsmartphone', 1); print '</td></tr>'; // Accountancy_code_buy_intra - if ($mysoc->isInEEC()) - { + if ($mysoc->isInEEC()) { print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancyBuyIntraCode").'</td>'; print '<td>'; if ($type == 0) { @@ -1329,29 +1380,40 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } else { $accountancy_code_buy_intra = (GETPOSTISSET('accountancy_code_buy_intra') ? GETPOST('accountancy_code_buy_intra', 'alpha') : $conf->global->ACCOUNTING_SERVICE_BUY_INTRA_ACCOUNT); } - print $formaccounting->select_account($accountancy_code_buy_intra, 'accountancy_code_buy_intra', 1, null, 1, 1, ''); + print $formaccounting->select_account($accountancy_code_buy_intra, 'accountancy_code_buy_intra', 1, null, 1, 1, 'minwidth100 maxwidth300 maxwidthonsmartphone', 1); print '</td></tr>'; } // Accountancy_code_buy_export print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancyBuyExportCode").'</td>'; print '<td>'; - if ($type == 0) - { + if ($type == 0) { $accountancy_code_buy_export = (GETPOST('accountancy_code_buy_export') ? GETPOST('accountancy_code_buy_export', 'alpha') : $conf->global->ACCOUNTING_PRODUCT_BUY_EXPORT_ACCOUNT); } else { $accountancy_code_buy_export = (GETPOST('accountancy_code_buy_export') ? GETPOST('accountancy_code_buy_export', 'alpha') : $conf->global->ACCOUNTING_SERVICE_BUY_EXPORT_ACCOUNT); } - print $formaccounting->select_account($accountancy_code_buy_export, 'accountancy_code_buy_export', 1, null, 1, 1, ''); + print $formaccounting->select_account($accountancy_code_buy_export, 'accountancy_code_buy_export', 1, null, 1, 1, 'minwidth100 maxwidth300 maxwidthonsmartphone', 1); print '</td></tr>'; } else // For external software { - if (!empty($accountancy_code_sell)) { $object->accountancy_code_sell = $accountancy_code_sell; } - if (!empty($accountancy_code_sell_intra)) { $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; } - if (!empty($accountancy_code_sell_export)) { $object->accountancy_code_sell_export = $accountancy_code_sell_export; } - if (!empty($accountancy_code_buy)) { $object->accountancy_code_buy = $accountancy_code_buy; } - if (!empty($accountancy_code_buy_intra)) { $object->accountancy_code_buy_intra = $accountancy_code_buy_intra; } - if (!empty($accountancy_code_buy_export)) { $object->accountancy_code_buy_export = $accountancy_code_buy_export; } + if (!empty($accountancy_code_sell)) { + $object->accountancy_code_sell = $accountancy_code_sell; + } + if (!empty($accountancy_code_sell_intra)) { + $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; + } + if (!empty($accountancy_code_sell_export)) { + $object->accountancy_code_sell_export = $accountancy_code_sell_export; + } + if (!empty($accountancy_code_buy)) { + $object->accountancy_code_buy = $accountancy_code_buy; + } + if (!empty($accountancy_code_buy_intra)) { + $object->accountancy_code_buy_intra = $accountancy_code_buy_intra; + } + if (!empty($accountancy_code_buy_export)) { + $object->accountancy_code_buy_export = $accountancy_code_buy_export; + } // Accountancy_code_sell print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellCode").'</td>'; @@ -1359,8 +1421,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Accountancy_code_sell_intra - if ($mysoc->isInEEC()) - { + if ($mysoc->isInEEC()) { print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellIntraCode").'</td>'; print '<td class="maxwidthonsmartphone"><input class="minwidth100" name="accountancy_code_sell_intra" value="'.$object->accountancy_code_sell_intra.'">'; print '</td></tr>'; @@ -1377,8 +1438,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Accountancy_code_buy_intra - if ($mysoc->isInEEC()) - { + if ($mysoc->isInEEC()) { print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancyBuyIntraCode").'</td>'; print '<td class="maxwidthonsmartphone"><input class="minwidth100" name="accountancy_code_buy_intra" value="'.$object->accountancy_code_buy_intra.'">'; print '</td></tr>'; @@ -1402,11 +1462,10 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</form>'; } elseif ($object->id > 0) { /* - * Product card - */ + * Product card + */ // Fiche en mode edition - if ($action == 'edit' && $usercancreate) - { + if ($action == 'edit' && $usercancreate) { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -1421,8 +1480,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // We set country_id, country_code and country for the selected country $object->country_id = GETPOST('country_id') ? GETPOST('country_id') : $object->country_id; - if ($object->country_id) - { + if ($object->country_id) { $tmparray = getCountry($object->country_id, 'all'); $object->country_code = $tmparray['code']; $object->country = $tmparray['label']; @@ -1430,7 +1488,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $type = $langs->trans('Product'); - if ($object->isService()) $type = $langs->trans('Service'); + if ($object->isService()) { + $type = $langs->trans('Service'); + } //print load_fiche_titre($langs->trans('Modify').' '.$type.' : '.(is_object($object->oldcopy)?$object->oldcopy->ref:$object->ref), ""); // Main official, simple, and not duplicated code @@ -1449,7 +1509,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<table class="border allwidth">'; // Ref - print '<tr><td class="titlefield fieldrequired">'.$langs->trans("Ref").'</td><td colspan="3"><input name="ref" class="maxwidth200" maxlength="128" value="'.dol_escape_htmltag($object->ref).'"></td></tr>'; + print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Ref").'</td><td colspan="3"><input name="ref" class="maxwidth200" maxlength="128" value="'.dol_escape_htmltag($object->ref).'"></td></tr>'; // Label print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td><td colspan="3"><input name="label" class="minwidth300 maxwidth400onsmartphone" maxlength="255" value="'.dol_escape_htmltag($object->label).'"></td></tr>'; @@ -1457,8 +1517,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Status To sell print '<tr><td class="fieldrequired">'.$langs->trans("Status").' ('.$langs->trans("Sell").')</td><td colspan="3">'; print '<select class="flat" name="statut">'; - if ($object->status) - { + if ($object->status) { print '<option value="1" selected>'.$langs->trans("OnSell").'</option>'; print '<option value="0">'.$langs->trans("NotOnSell").'</option>'; } else { @@ -1471,8 +1530,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Status To Buy print '<tr><td class="fieldrequired">'.$langs->trans("Status").' ('.$langs->trans("Buy").')</td><td colspan="3">'; print '<select class="flat" name="statut_buy">'; - if ($object->status_buy) - { + if ($object->status_buy) { print '<option value="1" selected>'.$langs->trans("ProductStatusOnBuy").'</option>'; print '<option value="0">'.$langs->trans("ProductStatusNotOnBuy").'</option>'; } else { @@ -1483,12 +1541,10 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Batch number managment - if ($conf->productbatch->enabled) - { - if ($object->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if ($conf->productbatch->enabled) { + if ($object->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { print '<tr><td>'.$langs->trans("ManageLotSerial").'</td><td colspan="3">'; - $statutarray = array('0' => $langs->trans("ProductStatusNotOnBatch"), '1' => $langs->trans("ProductStatusOnBatch")); + $statutarray = array('0' => $langs->trans("ProductStatusNotOnBatch"), '1' => $langs->trans("ProductStatusOnBatch"), '2' => $langs->trans("ProductStatusOnSerial")); print $form->selectarray('status_batch', $statutarray, $object->status_batch); print '</td></tr>'; } @@ -1496,23 +1552,28 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Barcode $showbarcode = empty($conf->barcode->enabled) ? 0 : 1; - if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0; + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) { + $showbarcode = 0; + } - if ($showbarcode) - { + if ($showbarcode) { print '<tr><td>'.$langs->trans('BarcodeType').'</td><td>'; if (GETPOSTISSET('fk_barcode_type')) { - $fk_barcode_type = GETPOST('fk_barcode_type'); + $fk_barcode_type = GETPOST('fk_barcode_type'); } else { $fk_barcode_type = $object->barcode_type; - if (empty($fk_barcode_type) && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; + if (empty($fk_barcode_type) && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) { + $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; + } } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php'; $formbarcode = new FormBarCode($db); print $formbarcode->selectBarcodeType($fk_barcode_type, 'fk_barcode_type', 1); print '</td><td>'.$langs->trans("BarcodeValue").'</td><td>'; $tmpcode = GETPOSTISSET('barcode') ? GETPOST('barcode') : $object->barcode; - if (empty($tmpcode) && !empty($modBarCodeProduct->code_auto)) $tmpcode = $modBarCodeProduct->getNextValue($object, $fk_barcode_type); + if (empty($tmpcode) && !empty($modBarCodeProduct->code_auto)) { + $tmpcode = $modBarCodeProduct->getNextValue($object, $fk_barcode_type); + } print '<input size="40" class="maxwidthonsmartphone" type="text" name="barcode" value="'.dol_escape_htmltag($tmpcode).'">'; print '</td></tr>'; } @@ -1533,32 +1594,30 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Stock - if ($object->isProduct() && !empty($conf->stock->enabled)) - { + if ($object->isProduct() && !empty($conf->stock->enabled)) { // Default warehouse print '<tr><td>'.$langs->trans("DefaultWarehouse").'</td><td>'; print $formproduct->selectWarehouses($object->fk_default_warehouse, 'fk_default_warehouse', 'warehouseopen', 1); print ' <a href="'.DOL_URL_ROOT.'/product/stock/card.php?action=create&amp;backtopage='.urlencode($_SERVER['PHP_SELF'].'?action=create&type='.GETPOST('type', 'int')).'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddWarehouse").'"></span></a>'; print '</td>'; /* - print "<tr>".'<td>'.$langs->trans("StockLimit").'</td><td>'; - print '<input name="seuil_stock_alerte" size="4" value="'.$object->seuil_stock_alerte.'">'; - print '</td>'; + print "<tr>".'<td>'.$langs->trans("StockLimit").'</td><td>'; + print '<input name="seuil_stock_alerte" size="4" value="'.$object->seuil_stock_alerte.'">'; + print '</td>'; - print '<td>'.$langs->trans("DesiredStock").'</td><td>'; - print '<input name="desiredstock" size="4" value="'.$object->desiredstock.'">'; - print '</td></tr>'; - */ + print '<td>'.$langs->trans("DesiredStock").'</td><td>'; + print '<input name="desiredstock" size="4" value="'.$object->desiredstock.'">'; + print '</td></tr>'; + */ } /* - else - { - print '<input name="seuil_stock_alerte" type="hidden" value="'.$object->seuil_stock_alerte.'">'; - print '<input name="desiredstock" type="hidden" value="'.$object->desiredstock.'">'; - }*/ - - if ($object->isService()) + else { + print '<input name="seuil_stock_alerte" type="hidden" value="'.$object->seuil_stock_alerte.'">'; + print '<input name="desiredstock" type="hidden" value="'.$object->desiredstock.'">'; + }*/ + + if ($object->isService()) { // Duration print '<tr><td>'.$langs->trans("Duration").'</td><td colspan="3">'; print '<input name="duration_value" size="5" value="'.$object->duration_value.'"> '; @@ -1576,8 +1635,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print $formproduct->selectMeasuringUnits("weight_units", "weight", $object->weight_units, 0, 2); print '</td></tr>'; - if (empty($conf->global->PRODUCT_DISABLE_SIZE)) - { + if (empty($conf->global->PRODUCT_DISABLE_SIZE)) { // Brut Length print '<tr><td>'.$langs->trans("Length").' x '.$langs->trans("Width").' x '.$langs->trans("Height").'</td><td colspan="3">'; print '<input name="size" size="5" value="'.$object->length.'">x'; @@ -1586,16 +1644,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print $formproduct->selectMeasuringUnits("size_units", "size", $object->length_units, 0, 2); print '</td></tr>'; } - if (empty($conf->global->PRODUCT_DISABLE_SURFACE)) - { + if (empty($conf->global->PRODUCT_DISABLE_SURFACE)) { // Brut Surface print '<tr><td>'.$langs->trans("Surface").'</td><td colspan="3">'; print '<input name="surface" size="5" value="'.$object->surface.'"> '; print $formproduct->selectMeasuringUnits("surface_units", "surface", $object->surface_units, 0, 2); print '</td></tr>'; } - if (empty($conf->global->PRODUCT_DISABLE_VOLUME)) - { + if (empty($conf->global->PRODUCT_DISABLE_VOLUME)) { // Brut Volume print '<tr><td>'.$langs->trans("Volume").'</td><td colspan="3">'; print '<input name="volume" size="5" value="'.$object->volume.'"> '; @@ -1603,8 +1659,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; } - if (!empty($conf->global->PRODUCT_ADD_NET_MEASURE)) - { + if (!empty($conf->global->PRODUCT_ADD_NET_MEASURE)) { // Net Measure print '<tr><td>'.$langs->trans("NetMeasure").'</td><td colspan="3">'; print '<input name="net_measure" size="5" value="'.$object->net_measure.'"> '; @@ -1613,8 +1668,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } } // Units - if (!empty($conf->global->PRODUCT_USE_UNITS)) - { + if (!empty($conf->global->PRODUCT_USE_UNITS)) { print '<tr><td>'.$langs->trans('DefaultUnitToShow').'</td>'; print '<td colspan="3">'; print $form->selectUnits($object->fk_unit, 'units'); @@ -1622,22 +1676,23 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Custom code - if (!$object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO)) - { + if (!$object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO)) { print '<tr><td>'.$langs->trans("CustomCode").'</td><td><input name="customcode" class="maxwidth100onsmartphone" value="'.$object->customcode.'"></td></tr>'; // Origin country print '<td>'.$langs->trans("CountryOrigin").'</td>'; print '<td>'; print img_picto('', 'globe-americas', 'class="paddingrightonly"'); print $form->select_country($object->country_id, 'country_id', '', 0, 'minwidth100 maxwidthonsmartphone'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '</td>'; // State - if (empty($conf->global->PRODUCT_DISABLE_STATE)) - { - if ($conf->browser->layout == 'phone') print '</tr><tr>'; - if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) - { + if (empty($conf->global->PRODUCT_DISABLE_STATE)) { + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } + if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) { print '<td>'.$form->editfieldkey('RegionStateOrigin', 'state_id', '', $object, 0).'</td><td colspan="3">'; } else { print '<td>'.$form->editfieldkey('StateOrigin', 'state_id', '', $object, 0).'</td><td colspan="3">'; @@ -1653,14 +1708,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $parameters = array('colspan' => ' colspan="3"', 'cols' => 3); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } // Tags-Categories - if ($conf->categorie->enabled) - { + if ($conf->categorie->enabled) { print '<tr><td>'.$langs->trans("Categories").'</td><td colspan="3">'; $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, '', 'parent', 64, 0, 1); $c = new Categorie($db); @@ -1676,8 +1729,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Note private - if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { print '<tr><td class="tdtop">'.$langs->trans("NoteNotVisibleOnBill").'</td><td colspan="3">'; $doleditor = new DolEditor('note_private', $object->note_private, '', 140, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_4, '90%'); @@ -1692,25 +1744,23 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<table class="border centpercent">'; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { // Accountancy_code_sell - print '<tr><td class="titlefield">'.$langs->trans("ProductAccountancySellCode").'</td>'; + print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellCode").'</td>'; print '<td>'; print $formaccounting->select_account($object->accountancy_code_sell, 'accountancy_code_sell', 1, '', 1, 1); print '</td></tr>'; // Accountancy_code_sell_intra - if ($mysoc->isInEEC()) - { - print '<tr><td class="titlefield">'.$langs->trans("ProductAccountancySellIntraCode").'</td>'; + if ($mysoc->isInEEC()) { + print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellIntraCode").'</td>'; print '<td>'; print $formaccounting->select_account($object->accountancy_code_sell_intra, 'accountancy_code_sell_intra', 1, '', 1, 1); print '</td></tr>'; } // Accountancy_code_sell_export - print '<tr><td class="titlefield">'.$langs->trans("ProductAccountancySellExportCode").'</td>'; + print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellExportCode").'</td>'; print '<td>'; print $formaccounting->select_account($object->accountancy_code_sell_export, 'accountancy_code_sell_export', 1, '', 1, 1); print '</td></tr>'; @@ -1722,36 +1772,34 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Accountancy_code_buy_intra - if ($mysoc->isInEEC()) - { - print '<tr><td class="titlefield">'.$langs->trans("ProductAccountancyBuyIntraCode").'</td>'; + if ($mysoc->isInEEC()) { + print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancyBuyIntraCode").'</td>'; print '<td>'; print $formaccounting->select_account($object->accountancy_code_buy_intra, 'accountancy_code_buy_intra', 1, '', 1, 1); print '</td></tr>'; } // Accountancy_code_buy_export - print '<tr><td class="titlefield">'.$langs->trans("ProductAccountancyBuyExportCode").'</td>'; + print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancyBuyExportCode").'</td>'; print '<td>'; print $formaccounting->select_account($object->accountancy_code_buy_export, 'accountancy_code_buy_export', 1, '', 1, 1); print '</td></tr>'; } else { // For external software // Accountancy_code_sell - print '<tr><td class="titlefield">'.$langs->trans("ProductAccountancySellCode").'</td>'; + print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellCode").'</td>'; print '<td><input name="accountancy_code_sell" class="maxwidth200" value="'.$object->accountancy_code_sell.'">'; print '</td></tr>'; // Accountancy_code_sell_intra - if ($mysoc->isInEEC()) - { - print '<tr><td class="titlefield">'.$langs->trans("ProductAccountancySellIntraCode").'</td>'; + if ($mysoc->isInEEC()) { + print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellIntraCode").'</td>'; print '<td><input name="accountancy_code_sell_intra" class="maxwidth200" value="'.$object->accountancy_code_sell_intra.'">'; print '</td></tr>'; } // Accountancy_code_sell_export - print '<tr><td class="titlefield">'.$langs->trans("ProductAccountancySellExportCode").'</td>'; + print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellExportCode").'</td>'; print '<td><input name="accountancy_code_sell_export" class="maxwidth200" value="'.$object->accountancy_code_sell_export.'">'; print '</td></tr>'; @@ -1761,15 +1809,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Accountancy_code_buy_intra - if ($mysoc->isInEEC()) - { - print '<tr><td class="titlefield">'.$langs->trans("ProductAccountancyBuyIntraCode").'</td>'; + if ($mysoc->isInEEC()) { + print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancyBuyIntraCode").'</td>'; print '<td><input name="accountancy_code_buy_intra" class="maxwidth200" value="'.$object->accountancy_code_buy_intra.'">'; print '</td></tr>'; } // Accountancy_code_buy_export - print '<tr><td class="titlefield">'.$langs->trans("ProductAccountancyBuyExportCode").'</td>'; + print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancyBuyExportCode").'</td>'; print '<td><input name="accountancy_code_buy_export" class="maxwidth200" value="'.$object->accountancy_code_buy_export.'">'; print '</td></tr>'; } @@ -1786,8 +1833,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</form>'; } else { // Fiche en mode visu + $showbarcode = empty($conf->barcode->enabled) ? 0 : 1; - if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0; + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) { + $showbarcode = 0; + } $head = product_prepare_head($object); $titre = $langs->trans("CardProduct".$object->type); @@ -1799,7 +1849,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $object->next_prev_filter = " fk_product_type = ".$object->type; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -1811,9 +1863,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<table class="border tableforfield" width="100%">'; // Type - if (!empty($conf->product->enabled) && !empty($conf->service->enabled)) - { - // TODO change for compatibility with edit in place + if (!empty($conf->product->enabled) && !empty($conf->service->enabled)) { $typeformat = 'select;0:'.$langs->trans("Product").',1:'.$langs->trans("Service"); print '<tr><td class="titlefield">'; print (empty($conf->global->PRODUCT_DENY_CHANGE_PRODUCT_TYPE)) ? $form->editfieldkey("Type", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat) : $langs->trans('Type'); @@ -1822,25 +1872,24 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; } - if ($showbarcode) - { + if ($showbarcode) { // Barcode type print '<tr><td class="nowrap">'; print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">'; print $langs->trans("BarcodeType"); print '</td>'; - if (($action != 'editbarcodetype') && $usercancreate && $createbarcode) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbarcodetype&amp;id='.$object->id.'">'.img_edit($langs->trans('Edit'), 1).'</a></td>'; + if (($action != 'editbarcodetype') && $usercancreate && $createbarcode) { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbarcodetype&amp;id='.$object->id.'">'.img_edit($langs->trans('Edit'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td colspan="2">'; - if ($action == 'editbarcodetype' || $action == 'editbarcode') - { + if ($action == 'editbarcodetype' || $action == 'editbarcode') { require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php'; $formbarcode = new FormBarCode($db); } $fk_barcode_type=''; - if ($action == 'editbarcodetype') - { + if ($action == 'editbarcodetype') { print $formbarcode->formBarcodeType($_SERVER['PHP_SELF'].'?id='.$object->id, $object->barcode_type, 'fk_barcode_type'); $fk_barcode_type = $object->barcode_type; } else { @@ -1855,13 +1904,16 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">'; print $langs->trans("BarcodeValue"); print '</td>'; - if (($action != 'editbarcode') && $usercancreate && $createbarcode) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbarcode&amp;id='.$object->id.'">'.img_edit($langs->trans('Edit'), 1).'</a></td>'; + if (($action != 'editbarcode') && $usercancreate && $createbarcode) { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbarcode&amp;id='.$object->id.'">'.img_edit($langs->trans('Edit'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td colspan="2">'; - if ($action == 'editbarcode') - { + if ($action == 'editbarcode') { $tmpcode = GETPOSTISSET('barcode') ? GETPOST('barcode') : $object->barcode; - if (empty($tmpcode) && !empty($modBarCodeProduct->code_auto)) $tmpcode = $modBarCodeProduct->getNextValue($object, $fk_barcode_type); + if (empty($tmpcode) && !empty($modBarCodeProduct->code_auto)) { + $tmpcode = $modBarCodeProduct->getNextValue($object, $fk_barcode_type); + } print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -1871,7 +1923,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '&nbsp;<input type="submit" class="button" value="'.$langs->trans("Modify").'">'; print '</form>'; } else { - print $object->barcode; + print showValueWithClipboardCPButton($object->barcode); } print '</td></tr>'."\n"; } @@ -1880,10 +1932,8 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr><td class="nowrap">'; print $langs->trans("ProductAccountancySellCode"); print '</td><td colspan="2">'; - if (!empty($conf->accounting->enabled)) - { - if (!empty($object->accountancy_code_sell)) - { + if (!empty($conf->accounting->enabled)) { + if (!empty($object->accountancy_code_sell)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->accountancy_code_sell, 1); @@ -1895,15 +1945,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Accountancy sell code intra-community - if ($mysoc->isInEEC()) - { + if ($mysoc->isInEEC()) { print '<tr><td class="nowrap">'; print $langs->trans("ProductAccountancySellIntraCode"); print '</td><td colspan="2">'; - if (!empty($conf->accounting->enabled)) - { - if (!empty($object->accountancy_code_sell_intra)) - { + if (!empty($conf->accounting->enabled)) { + if (!empty($object->accountancy_code_sell_intra)) { $accountingaccount2 = new AccountingAccount($db); $accountingaccount2->fetch('', $object->accountancy_code_sell_intra, 1); @@ -1919,10 +1966,8 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr><td class="nowrap">'; print $langs->trans("ProductAccountancySellExportCode"); print '</td><td colspan="2">'; - if (!empty($conf->accounting->enabled)) - { - if (!empty($object->accountancy_code_sell_export)) - { + if (!empty($conf->accounting->enabled)) { + if (!empty($object->accountancy_code_sell_export)) { $accountingaccount3 = new AccountingAccount($db); $accountingaccount3->fetch('', $object->accountancy_code_sell_export, 1); @@ -1937,10 +1982,8 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr><td class="nowrap">'; print $langs->trans("ProductAccountancyBuyCode"); print '</td><td colspan="2">'; - if (!empty($conf->accounting->enabled)) - { - if (!empty($object->accountancy_code_buy)) - { + if (!empty($conf->accounting->enabled)) { + if (!empty($object->accountancy_code_buy)) { $accountingaccount4 = new AccountingAccount($db); $accountingaccount4->fetch('', $object->accountancy_code_buy, 1); @@ -1952,15 +1995,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Accountancy buy code intra-community - if ($mysoc->isInEEC()) - { + if ($mysoc->isInEEC()) { print '<tr><td class="nowrap">'; print $langs->trans("ProductAccountancyBuyIntraCode"); print '</td><td colspan="2">'; - if (!empty($conf->accounting->enabled)) - { - if (!empty($object->accountancy_code_buy_intra)) - { + if (!empty($conf->accounting->enabled)) { + if (!empty($object->accountancy_code_buy_intra)) { $accountingaccount5 = new AccountingAccount($db); $accountingaccount5->fetch('', $object->accountancy_code_buy_intra, 1); @@ -1976,10 +2016,8 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr><td class="nowrap">'; print $langs->trans("ProductAccountancyBuyExportCode"); print '</td><td colspan="2">'; - if (!empty($conf->accounting->enabled)) - { - if (!empty($object->accountancy_code_buy_export)) - { + if (!empty($conf->accounting->enabled)) { + if (!empty($object->accountancy_code_buy_export)) { $accountingaccount6 = new AccountingAccount($db); $accountingaccount6->fetch('', $object->accountancy_code_buy_export, 1); @@ -1991,16 +2029,10 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Batch number management (to batch) - if (!empty($conf->productbatch->enabled)) - { - if ($object->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if (!empty($conf->productbatch->enabled)) { + if ($object->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { print '<tr><td>'.$langs->trans("ManageLotSerial").'</td><td colspan="2">'; - if (!empty($conf->use_javascript_ajax) && $usercancreate && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - print ajax_object_onoff($object, 'status_batch', 'tobatch', 'ProductStatusOnBatch', 'ProductStatusNotOnBatch'); - } else { - print $object->getLibStatut(0, 2); - } + print $object->getLibStatut(0, 2); print '</td></tr>'; } } @@ -2014,8 +2046,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Default warehouse - if ($object->isProduct() && !empty($conf->stock->enabled)) - { + if ($object->isProduct() && !empty($conf->stock->enabled)) { $warehouse = new Entrepot($db); $warehouse->fetch($object->fk_default_warehouse); @@ -2046,15 +2077,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<div class="underbanner clearboth"></div>'; print '<table class="border tableforfield" width="100%">'; - if ($object->isService()) - { + if ($object->isService()) { // Duration print '<tr><td class="titlefield">'.$langs->trans("Duration").'</td><td colspan="2">'.$object->duration_value.'&nbsp;'; - if ($object->duration_value > 1) - { + if ($object->duration_value > 1) { $dur = array("i"=>$langs->trans("Minute"), "h"=>$langs->trans("Hours"), "d"=>$langs->trans("Days"), "w"=>$langs->trans("Weeks"), "m"=>$langs->trans("Months"), "y"=>$langs->trans("Years")); - } elseif ($object->duration_value > 0) - { + } elseif ($object->duration_value > 0) { $dur = array("i"=>$langs->trans("Minute"), "h"=>$langs->trans("Hour"), "d"=>$langs->trans("Day"), "w"=>$langs->trans("Week"), "m"=>$langs->trans("Month"), "y"=>$langs->trans("Year")); } print (!empty($object->duration_unit) && isset($dur[$object->duration_unit]) ? $langs->trans($dur[$object->duration_unit]) : '')."&nbsp;"; @@ -2068,47 +2096,44 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Brut Weight print '<tr><td class="titlefield">'.$langs->trans("Weight").'</td><td colspan="2">'; - if ($object->weight != '') - { + if ($object->weight != '') { print $object->weight." ".measuringUnitString(0, "weight", $object->weight_units); } else { print '&nbsp;'; } print "</td></tr>\n"; - if (empty($conf->global->PRODUCT_DISABLE_SIZE)) - { + if (empty($conf->global->PRODUCT_DISABLE_SIZE)) { // Brut Length print '<tr><td>'.$langs->trans("Length").' x '.$langs->trans("Width").' x '.$langs->trans("Height").'</td><td colspan="2">'; - if ($object->length != '' || $object->width != '' || $object->height != '') - { + if ($object->length != '' || $object->width != '' || $object->height != '') { print $object->length; - if ($object->width) print " x ".$object->width; - if ($object->height) print " x ".$object->height; + if ($object->width) { + print " x ".$object->width; + } + if ($object->height) { + print " x ".$object->height; + } print ' '.measuringUnitString(0, "size", $object->length_units); } else { print '&nbsp;'; } print "</td></tr>\n"; } - if (empty($conf->global->PRODUCT_DISABLE_SURFACE)) - { + if (empty($conf->global->PRODUCT_DISABLE_SURFACE)) { // Brut Surface print '<tr><td>'.$langs->trans("Surface").'</td><td colspan="2">'; - if ($object->surface != '') - { + if ($object->surface != '') { print $object->surface." ".measuringUnitString(0, "surface", $object->surface_units); } else { print '&nbsp;'; } print "</td></tr>\n"; } - if (empty($conf->global->PRODUCT_DISABLE_VOLUME)) - { + if (empty($conf->global->PRODUCT_DISABLE_VOLUME)) { // Brut Volume print '<tr><td>'.$langs->trans("Volume").'</td><td colspan="2">'; - if ($object->volume != '') - { + if ($object->volume != '') { print $object->volume." ".measuringUnitString(0, "volume", $object->volume_units); } else { print '&nbsp;'; @@ -2116,12 +2141,10 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print "</td></tr>\n"; } - if (!empty($conf->global->PRODUCT_ADD_NET_MEASURE)) - { + if (!empty($conf->global->PRODUCT_ADD_NET_MEASURE)) { // Net Measure print '<tr><td class="titlefield">'.$langs->trans("NetMeasure").'</td><td colspan="2">'; - if ($object->net_measure != '') - { + if ($object->net_measure != '') { print $object->net_measure." ".measuringUnitString($object->net_measure_units); } else { print '&nbsp;'; @@ -2130,8 +2153,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Unit - if (!empty($conf->global->PRODUCT_USE_UNITS)) - { + if (!empty($conf->global->PRODUCT_USE_UNITS)) { $unit = $object->getLabelOfUnit(); print '<tr><td>'.$langs->trans('DefaultUnitToShow').'</td><td>'; @@ -2142,13 +2164,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Custom code - if (!$object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO)) - { + if (!$object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO)) { print '<tr><td>'.$langs->trans("CustomCode").'</td><td colspan="2">'.$object->customcode.'</td>'; // Origin country code print '<tr><td>'.$langs->trans("Origin").'</td><td colspan="2">'.getCountry($object->country_id, 0, $db); - if (!empty($object->state_id)) print ' - '.getState($object->state_id, 0, $db); + if (!empty($object->state_id)) { + print ' - '.getState($object->state_id, 0, $db); + } print '</td>'; } @@ -2164,8 +2187,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Note private - if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { print '<!-- show Note --> '."\n"; print '<tr><td class="tdtop">'.$langs->trans("NotePrivate").'</td><td colspan="'.(2 + (($showphoto || $showbarcode) ? 1 : 0)).'">'.(dol_textishtml($object->note_private) ? $object->note_private : dol_nl2br($object->note_private, 1, true)).'</td></tr>'."\n"; print '<!-- End show Note --> '."\n"; @@ -2179,40 +2201,37 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print dol_get_fiche_end(); } - } elseif ($action != 'create') - { + } elseif ($action != 'create') { exit; } } // Load object modCodeProduct $module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard'); -if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') -{ +if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $result = dol_include_once('/core/modules/product/'.$module.'.php'); -if ($result > 0) -{ +if ($result > 0) { $modCodeProduct = new $module(); } $tmpcode = ''; -if (!empty($modCodeProduct->code_auto)) $tmpcode = $modCodeProduct->getNextValue($object, $object->type); +if (!empty($modCodeProduct->code_auto)) { + $tmpcode = $modCodeProduct->getNextValue($object, $object->type); +} $formconfirm = ''; // Confirm delete product if (($action == 'delete' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) // Output when action = clone if jmobile or no js - || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) // Always output when not jmobile nor js -{ + || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) { // Always output when not jmobile nor js $formconfirm = $form->formconfirm("card.php?id=".$object->id, $langs->trans("DeleteProduct"), $langs->trans("ConfirmDeleteProduct"), "confirm_delete", '', 0, "action-delete"); } // Clone confirmation if (($action == 'clone' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) // Output when action = clone if jmobile or no js - || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) // Always output when not jmobile nor js -{ + || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) { // Always output when not jmobile nor js // Define confirmation messages $formquestionclone = array( 'text' => $langs->trans("ConfirmClone"), @@ -2223,8 +2242,7 @@ if (($action == 'clone' && (empty($conf->use_javascript_ajax) || !empty($conf->d if (!empty($conf->global->PRODUIT_MULTIPRICES)) { $formquestionclone[] = array('type' => 'checkbox', 'name' => 'clone_prices', 'label' => $langs->trans("ClonePricesProduct").' ('.$langs->trans("CustomerPrices").')', 'value' => 0); } - if (!empty($conf->global->PRODUIT_SOUSPRODUITS)) - { + if (!empty($conf->global->PRODUIT_SOUSPRODUITS)) { $formquestionclone[] = array('type' => 'checkbox', 'name' => 'clone_composition', 'label' => $langs->trans('CloneCompositionProduct'), 'value' => 1); } @@ -2234,33 +2252,31 @@ if (($action == 'clone' && (empty($conf->use_javascript_ajax) || !empty($conf->d // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'object' => $object); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook -if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; -elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; +if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; +} elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; +} // Print form confirm print $formconfirm; -/* ************************************************************************** */ -/* */ -/* Barre d'action */ -/* */ -/* ************************************************************************** */ -if ($action != 'create' && $action != 'edit') -{ +/* + * Action bar + */ +if ($action != 'create' && $action != 'edit') { print "\n".'<div class="tabsAction">'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { - if ($usercancreate) - { - if (!isset($object->no_button_edit) || $object->no_button_edit <> 1) print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&amp;id='.$object->id.'">'.$langs->trans("Modify").'</a>'; + if (empty($reshook)) { + if ($usercancreate) { + if (!isset($object->no_button_edit) || $object->no_button_edit <> 1) { + print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&amp;id='.$object->id.'">'.$langs->trans("Modify").'</a>'; + } - if (!isset($object->no_button_copy) || $object->no_button_copy <> 1) - { - if (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)) - { + if (!isset($object->no_button_copy) || $object->no_button_copy <> 1) { + if (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)) { print '<span id="action-clone" class="butAction">'.$langs->trans('ToClone').'</span>'."\n"; } else { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=clone&amp;id='.$object->id.'">'.$langs->trans("ToClone").'</a>'; @@ -2269,12 +2285,9 @@ if ($action != 'create' && $action != 'edit') } $object_is_used = $object->isObjectUsed($object->id); - if ($usercandelete) - { - if (empty($object_is_used) && (!isset($object->no_button_delete) || $object->no_button_delete <> 1)) - { - if (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)) - { + if ($usercandelete) { + if (empty($object_is_used) && (!isset($object->no_button_delete) || $object->no_button_delete <> 1)) { + if (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)) { print '<span id="action-delete" class="butActionDelete">'.$langs->trans('Delete').'</span>'."\n"; } else { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=delete&amp;token='.newToken().'&amp;id='.$object->id.'">'.$langs->trans("Delete").'</a>'; @@ -2294,23 +2307,20 @@ if ($action != 'create' && $action != 'edit') * All the "Add to" areas */ -if (!empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action == '' || $action == 'view') && $object->status) -{ +if (!empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action == '' || $action == 'view') && $object->status) { //Variable used to check if any text is going to be printed $html = ''; //print '<div class="fichecenter"><div class="fichehalfleft">'; // Propals - if (!empty($conf->propal->enabled) && $user->rights->propale->creer) - { + if (!empty($conf->propal->enabled) && $user->rights->propale->creer) { $propal = new Propal($db); $langs->load("propal"); $otherprop = $propal->liste_array(2, 1, 0); - if (is_array($otherprop) && count($otherprop)) - { + if (is_array($otherprop) && count($otherprop)) { $html .= '<tr><td style="width: 200px;">'; $html .= $langs->trans("AddToDraftProposals").'</td><td>'; $html .= $form->selectarray("propalid", $otherprop, 0, 1); @@ -2324,15 +2334,13 @@ if (!empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action == } // Commande - if (!empty($conf->commande->enabled) && $user->rights->commande->creer) - { + if (!empty($conf->commande->enabled) && $user->rights->commande->creer) { $commande = new Commande($db); $langs->load("orders"); $othercom = $commande->liste_array(2, 1, null); - if (is_array($othercom) && count($othercom)) - { + if (is_array($othercom) && count($othercom)) { $html .= '<tr><td style="width: 200px;">'; $html .= $langs->trans("AddToDraftOrders").'</td><td>'; $html .= $form->selectarray("commandeid", $othercom, 0, 1); @@ -2346,15 +2354,13 @@ if (!empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action == } // Factures - if (!empty($conf->facture->enabled) && $user->rights->facture->creer) - { + if (!empty($conf->facture->enabled) && $user->rights->facture->creer) { $invoice = new Facture($db); $langs->load("bills"); $otherinvoice = $invoice->liste_array(2, 1, null); - if (is_array($otherinvoice) && count($otherinvoice)) - { + if (is_array($otherinvoice) && count($otherinvoice)) { $html .= '<tr><td style="width: 200px;">'; $html .= $langs->trans("AddToDraftInvoices").'</td><td>'; $html .= $form->selectarray("factureid", $otherinvoice, 0, 1); @@ -2368,8 +2374,7 @@ if (!empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action == } //If any text is going to be printed, then we show the table - if (!empty($html)) - { + if (!empty($html)) { print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="addin">'; @@ -2400,11 +2405,10 @@ if (!empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action == /* - * Documents generes + * Generated documents */ -if ($action != 'create' && $action != 'edit' && $action != 'delete') -{ +if ($action != 'create' && $action != 'edit' && $action != 'delete') { print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre diff --git a/htdocs/product/class/api_products.class.php b/htdocs/product/class/api_products.class.php index 189161712d5..c38437fb2f0 100644 --- a/htdocs/product/class/api_products.class.php +++ b/htdocs/product/class/api_products.class.php @@ -37,7 +37,7 @@ class Products extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'ref', 'label' ); @@ -165,9 +165,10 @@ class Products extends DolibarrApi * @param int $mode Use this param to filter list (0 for all, 1 for only product, 2 for only service) * @param int $category Use this param to filter list by category * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.tobuy:=:0) and (t.tosell:=:1)" + * @param bool $ids_only Return only IDs of product instead of all properties (faster, above all if list is long) * @return array Array of product objects */ - public function index($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '') + public function index($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '', $ids_only = false) { global $db, $conf; @@ -217,12 +218,15 @@ class Products extends DolibarrApi $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); - $product_static = new Product($this->db); - if ($product_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($product_static); + if (!$ids_only) { + $product_static = new Product($this->db); + if ($product_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($product_static); + } + } else { + $obj_ret[] = $obj->rowid; } $i++; } @@ -290,7 +294,8 @@ class Products extends DolibarrApi $oldproduct = dol_clone($this->product, 0); foreach ($request_data as $field => $value) { - if ($field == 'id') { continue; + if ($field == 'id') { + continue; } if ($field == 'stock_reel') { throw new RestException(400, 'Stock reel cannot be updated here. Use the /stockmovements endpoint instead'); @@ -309,24 +314,32 @@ class Products extends DolibarrApi if ($result > 0 && !empty($conf->global->PRODUCT_PRICE_UNIQ)) { // We update price only if it was changed $pricemodified = false; - if ($this->product->price_base_type != $oldproduct->price_base_type) { $pricemodified = true; + if ($this->product->price_base_type != $oldproduct->price_base_type) { + $pricemodified = true; } else { - if ($this->product->tva_tx != $oldproduct->tva_tx) { $pricemodified = true; + if ($this->product->tva_tx != $oldproduct->tva_tx) { + $pricemodified = true; } - if ($this->product->tva_npr != $oldproduct->tva_npr) { $pricemodified = true; + if ($this->product->tva_npr != $oldproduct->tva_npr) { + $pricemodified = true; } - if ($this->product->default_vat_code != $oldproduct->default_vat_code) { $pricemodified = true; + if ($this->product->default_vat_code != $oldproduct->default_vat_code) { + $pricemodified = true; } if ($this->product->price_base_type == 'TTC') { - if ($this->product->price_ttc != $oldproduct->price_ttc) { $pricemodified = true; + if ($this->product->price_ttc != $oldproduct->price_ttc) { + $pricemodified = true; } - if ($this->product->price_min_ttc != $oldproduct->price_min_ttc) { $pricemodified = true; + if ($this->product->price_min_ttc != $oldproduct->price_min_ttc) { + $pricemodified = true; } } else { - if ($this->product->price != $oldproduct->price) { $pricemodified = true; + if ($this->product->price != $oldproduct->price) { + $pricemodified = true; } - if ($this->product->price_min != $oldproduct->price_min) { $pricemodified = true; + if ($this->product->price_min != $oldproduct->price_min) { + $pricemodified = true; } } } @@ -586,7 +599,9 @@ class Products extends DolibarrApi $prodcustprice = new Productcustomerprice($this->db); $filter = array(); $filter['t.fk_product'] .= $id; - if ($thirdparty_id) $filter['t.fk_soc'] .= $thirdparty_id; + if ($thirdparty_id) { + $filter['t.fk_soc'] .= $thirdparty_id; + } $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); } @@ -805,8 +820,7 @@ class Products extends DolibarrApi $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $product_fourn = new ProductFournisseur($this->db); @@ -1149,7 +1163,8 @@ class Products extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'rowid') { continue; + if ($field == 'rowid') { + continue; } $prodattr->$field = $value; } @@ -1447,7 +1462,8 @@ class Products extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'rowid') { continue; + if ($field == 'rowid') { + continue; } $objectval->$field = $value; } @@ -1606,8 +1622,7 @@ class Products extends DolibarrApi $prodcomb = new ProductCombination($this->db); $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact, $reference, $ref_ext); - if ($result > 0) - { + if ($result > 0) { return $result; } else { throw new RestException(500, "Error creating new product variant"); @@ -1662,11 +1677,9 @@ class Products extends DolibarrApi } $prodcomb = new ProductCombination($this->db); - if (!$prodcomb->fetchByProductCombination2ValuePairs($this->product->id, $features)) - { + if (!$prodcomb->fetchByProductCombination2ValuePairs($this->product->id, $features)) { $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact); - if ($result > 0) - { + if ($result > 0) { return $result; } else { throw new RestException(500, "Error creating new product variant"); @@ -1698,14 +1711,14 @@ class Products extends DolibarrApi $prodcomb->fetch((int) $id); foreach ($request_data as $field => $value) { - if ($field == 'rowid') { continue; + if ($field == 'rowid') { + continue; } $prodcomb->$field = $value; } $result = $prodcomb->update(DolibarrApiAccess::$user); - if ($result > 0) - { + if ($result > 0) { return 1; } throw new RestException(500, "Error editing variant"); @@ -1731,8 +1744,7 @@ class Products extends DolibarrApi $prodcomb = new ProductCombination($this->db); $prodcomb->id = (int) $id; $result = $prodcomb->delete(DolibarrApiAccess::$user); - if ($result <= 0) - { + if ($result <= 0) { throw new RestException(500, "Error deleting variant"); } return $result; @@ -1787,24 +1799,24 @@ class Products extends DolibarrApi } /** - * Get properties of a product object - * + * Get properties of 1 product object. * Return an array with product information. * - * @param int $id ID of product - * @param string $ref Ref of element - * @param string $ref_ext Ref ext of element - * @param string $barcode Barcode of element - * @param int $includestockdata Load also information about stock (slower) - * @param bool $includesubproducts Load information about subproducts (if product is a virtual product) - * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product) - * @return array|mixed Data without useless information + * @param int $id ID of product + * @param string $ref Ref of element + * @param string $ref_ext Ref ext of element + * @param string $barcode Barcode of element + * @param int $includestockdata Load also information about stock (slower) + * @param bool $includesubproducts Load information about subproducts (if product is a virtual product) + * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product) + * @param bool $includeifobjectisused Check if product object is used and set is_object_used with result. + * @return array|mixed Data without useless information * * @throws RestException 401 * @throws RestException 403 * @throws RestException 404 */ - private function _fetch($id, $ref = '', $ref_ext = '', $barcode = '', $includestockdata = 0, $includesubproducts = false, $includeparentid = false) + private function _fetch($id, $ref = '', $ref_ext = '', $barcode = '', $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includeifobjectisused = false) { if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) { throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode'); @@ -1859,6 +1871,10 @@ class Products extends DolibarrApi } } + if ($includeifobjectisused) { + $this->product->is_object_used = ($this->product->isObjectUsed() > 0); + } + return $this->_cleanObjectDatas($this->product); } } diff --git a/htdocs/product/class/html.formproduct.class.php b/htdocs/product/class/html.formproduct.class.php index eed18bbf8bd..56efd8565d1 100644 --- a/htdocs/product/class/html.formproduct.class.php +++ b/htdocs/product/class/html.formproduct.class.php @@ -76,57 +76,54 @@ class FormProduct { global $conf, $langs; - if (empty($fk_product) && count($this->cache_warehouses)) return 0; // Cache already loaded and we do not want a list with information specific to a product + if (empty($fk_product) && count($this->cache_warehouses)) { + return 0; // Cache already loaded and we do not want a list with information specific to a product + } - if (is_array($exclude)) $excludeGroups = implode("','", $exclude); + if (is_array($exclude)) { + $excludeGroups = implode("','", $exclude); + } $warehouseStatus = array(); - if (preg_match('/warehouseclosed/', $status)) - { + if (preg_match('/warehouseclosed/', $status)) { $warehouseStatus[] = Entrepot::STATUS_CLOSED; } - if (preg_match('/warehouseopen/', $status)) - { + if (preg_match('/warehouseopen/', $status)) { $warehouseStatus[] = Entrepot::STATUS_OPEN_ALL; } - if (preg_match('/warehouseinternal/', $status)) - { + if (preg_match('/warehouseinternal/', $status)) { $warehouseStatus[] = Entrepot::STATUS_OPEN_INTERNAL; } $sql = "SELECT e.rowid, e.ref as label, e.description, e.fk_parent"; - if (!empty($fk_product)) - { - if (!empty($batch)) - { + if (!empty($fk_product)) { + if (!empty($batch)) { $sql .= ", pb.qty as stock"; } else { $sql .= ", ps.reel as stock"; } - } elseif ($sumStock) - { + } elseif ($sumStock) { $sql .= ", sum(ps.reel) as stock"; } $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_entrepot = e.rowid"; - if (!empty($fk_product)) - { + if (!empty($fk_product)) { $sql .= " AND ps.fk_product = ".((int) $fk_product); - if (!empty($batch)) - { + if (!empty($batch)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_batch as pb on pb.fk_product_stock = ps.rowid AND pb.batch = '".$this->db->escape($batch)."'"; } } $sql .= " WHERE e.entity IN (".getEntity('stock').")"; - if (count($warehouseStatus)) - { + if (count($warehouseStatus)) { $sql .= " AND e.statut IN (".$this->db->sanitize($this->db->escape(implode(',', $warehouseStatus))).")"; } else { $sql .= " AND e.statut = 1"; } - if (!empty($exclude)) $sql .= ' AND e.rowid NOT IN('.$this->db->escape(implode(',', $exclude)).')'; + if (!empty($exclude)) { + $sql .= ' AND e.rowid NOT IN('.$this->db->escape(implode(',', $exclude)).')'; + } // minimum stock if ($stockMin !== false) { @@ -151,14 +148,14 @@ class FormProduct dol_syslog(get_class($this).'::loadWarehouses', LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); - if ($sumStock) $obj->stock = price2num($obj->stock, 5); + if ($sumStock) { + $obj->stock = price2num($obj->stock, 5); + } $this->cache_warehouses[$obj->rowid]['id'] = $obj->rowid; $this->cache_warehouses[$obj->rowid]['label'] = $obj->label; $this->cache_warehouses[$obj->rowid]['parent_id'] = $obj->fk_parent; @@ -168,7 +165,7 @@ class FormProduct } // Full label init - foreach ($this->cache_warehouses as $obj_rowid=>$tab) { + foreach ($this->cache_warehouses as $obj_rowid => $tab) { $this->cache_warehouses[$obj_rowid]['full_label'] = $this->get_parent_path($tab); } @@ -190,10 +187,13 @@ class FormProduct private function get_parent_path($tab, $final_label = '') { //phpcs:enable - if (empty($final_label)) $final_label = $tab['label']; + if (empty($final_label)) { + $final_label = $tab['label']; + } - if (empty($tab['parent_id'])) return $final_label; - else { + if (empty($tab['parent_id'])) { + return $final_label; + } else { if (!empty($this->cache_warehouses[$tab['parent_id']])) { $final_label = $this->cache_warehouses[$tab['parent_id']]['label'].' >> '.$final_label; return $this->get_parent_path($this->cache_warehouses[$tab['parent_id']], $final_label); @@ -235,14 +235,17 @@ class FormProduct dol_syslog(get_class($this)."::selectWarehouses $selected, $htmlname, $filterstatus, $empty, $disabled, $fk_product, $empty_label, $showstock, $forcecombo, $morecss", LOG_DEBUG); $out = ''; - if (empty($conf->global->ENTREPOT_EXTRA_STATUS)) $filterstatus = ''; - if (!empty($fk_product)) $this->cache_warehouses = array(); + if (empty($conf->global->ENTREPOT_EXTRA_STATUS)) { + $filterstatus = ''; + } + if (!empty($fk_product)) { + $this->cache_warehouses = array(); + } $this->loadWarehouses($fk_product, '', $filterstatus, true, $exclude, $stockMin, $orderBy); $nbofwarehouses = count($this->cache_warehouses); - if ($conf->use_javascript_ajax && !$forcecombo) - { + if ($conf->use_javascript_ajax && !$forcecombo) { include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $comboenhancement = ajax_combobox($htmlname, $events); $out .= $comboenhancement; @@ -250,22 +253,28 @@ class FormProduct if (strpos($htmlname, 'search_') !== 0) { if (empty($user->fk_warehouse) || $user->fk_warehouse == -1) { - if (($selected == '-2' || $selected == 'ifone') && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) $selected = $conf->global->MAIN_DEFAULT_WAREHOUSE; - } - else { - if (($selected == '-2' || $selected == 'ifone') && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) $selected = $user->fk_warehouse; + if (($selected == '-2' || $selected == 'ifone') && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) { + $selected = $conf->global->MAIN_DEFAULT_WAREHOUSE; + } + } else { + if (($selected == '-2' || $selected == 'ifone') && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) { + $selected = $user->fk_warehouse; + } } } $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled' : '').' id="'.$htmlname.'" name="'.($htmlname.($disabled ? '_disabled' : '')).'">'; - if ($empty) $out .= '<option value="-1">'.($empty_label ? $empty_label : '&nbsp;').'</option>'; - foreach ($this->cache_warehouses as $id => $arraytypes) - { + if ($empty) { + $out .= '<option value="-1">'.($empty_label ? $empty_label : '&nbsp;').'</option>'; + } + foreach ($this->cache_warehouses as $id => $arraytypes) { $label = ''; - if ($showfullpath) $label .= $arraytypes['full_label']; - else $label .= $arraytypes['label']; - if (($fk_product || ($showstock > 0)) && ($arraytypes['stock'] != 0 || ($showstock > 0))) - { + if ($showfullpath) { + $label .= $arraytypes['full_label']; + } else { + $label .= $arraytypes['label']; + } + if (($fk_product || ($showstock > 0)) && ($arraytypes['stock'] != 0 || ($showstock > 0))) { if ($arraytypes['stock'] <= 0) { $label .= ' <span class= \'text-warning\'>('.$langs->trans("Stock").':'.$arraytypes['stock'].')</span>'; } else { @@ -274,14 +283,18 @@ class FormProduct } $out .= '<option value="'.$id.'"'; - if ($selected == $id || ($selected == 'ifone' && $nbofwarehouses == 1)) $out .= ' selected'; + if ($selected == $id || ($selected == 'ifone' && $nbofwarehouses == 1)) { + $out .= ' selected'; + } $out .= ' data-html="'.dol_escape_htmltag($label).'"'; $out .= '>'; $out .= $label; $out .= '</option>'; } $out .= '</select>'; - if ($disabled) $out .= '<input type="hidden" name="'.$htmlname.'" value="'.(($selected > 0) ? $selected : '').'">'; + if ($disabled) { + $out .= '<input type="hidden" name="'.$htmlname.'" value="'.(($selected > 0) ? $selected : '').'">'; + } $parameters = array( 'selected' => $selected, @@ -302,8 +315,11 @@ class FormProduct ); $reshook = $hookmanager->executeHooks('selectWarehouses', $parameters, $this); - if ($reshook > 0) $out = $hookmanager->resPrint; - elseif ($reshook == 0) $out .= $hookmanager->resPrint; + if ($reshook > 0) { + $out = $hookmanager->resPrint; + } elseif ($reshook == 0) { + $out .= $hookmanager->resPrint; + } return $out; } @@ -385,7 +401,9 @@ class FormProduct $filter = array(); $filter['t.active'] = 1; - if ($measuring_style) $filter['t.unit_type'] = $measuring_style; + if ($measuring_style) { + $filter['t.unit_type'] = $measuring_style; + } $result = $measuringUnits->fetchAll( '', @@ -399,24 +417,33 @@ class FormProduct return -1; } else { $return .= '<select class="flat" name="'.$name.'">'; - if ($adddefault || $adddefault === '') - { + if ($adddefault || $adddefault === '') { $return .= '<option value="0">'.($adddefault ? $langs->trans("Default") : '').'</option>'; } - foreach ($measuringUnits->records as $lines) - { + foreach ($measuringUnits->records as $lines) { $return .= '<option value="'; - if ($mode == 1) $return .= $lines->short_label; - elseif ($mode == 2) $return .= $lines->scale; - else $return .= $lines->id; + if ($mode == 1) { + $return .= $lines->short_label; + } elseif ($mode == 2) { + $return .= $lines->scale; + } else { + $return .= $lines->id; + } $return .= '"'; - if ($mode == 1 && $lines->short_label == $default) $return .= ' selected'; - elseif ($mode == 2 && $lines->scale == $default) $return .= ' selected'; - elseif ($mode == 0 && $lines->id == $default) $return .= ' selected'; + if ($mode == 1 && $lines->short_label == $default) { + $return .= ' selected'; + } elseif ($mode == 2 && $lines->scale == $default) { + $return .= ' selected'; + } elseif ($mode == 0 && $lines->id == $default) { + $return .= ' selected'; + } $return .= '>'; - if ($measuring_style == 'time') $return .= $langs->trans(ucfirst($lines->label)); - else $return .= $langs->trans($lines->label); + if ($measuring_style == 'time') { + $return .= $langs->trans(ucfirst($lines->label)); + } else { + $return .= $langs->trans($lines->label); + } $return .= '</option>'; } $return .= '</select>'; @@ -472,8 +499,11 @@ class FormProduct if (!empty($productNature->records) && is_array($productNature->records)) { foreach ($productNature->records as $lines) { $return .= '<option value="'; - if ($mode == 1) $return .= $lines->label; - else $return .= $lines->code; + if ($mode == 1) { + $return .= $lines->label; + } else { + $return .= $lines->code; + } $return .= '"'; @@ -520,42 +550,41 @@ class FormProduct $out = ''; $productIdArray = array(); - if (!is_array($objectLines) || !count($objectLines)) - { - if (!empty($fk_product)) $productIdArray[] = $fk_product; + if (!is_array($objectLines) || !count($objectLines)) { + if (!empty($fk_product)) { + $productIdArray[] = $fk_product; + } } else { foreach ($objectLines as $line) { - if ($line->fk_product) $productIdArray[] = $line->fk_product; + if ($line->fk_product) { + $productIdArray[] = $line->fk_product; + } } } $nboflot = $this->loadLotStock($productIdArray); - if ($conf->use_javascript_ajax && !$forcecombo) - { + if ($conf->use_javascript_ajax && !$forcecombo) { include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $comboenhancement = ajax_combobox($htmlname, $events); $out .= $comboenhancement; } $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled' : '').' id="'.$htmlname.'" name="'.($htmlname.($disabled ? '_disabled' : '')).'">'; - if ($empty) $out .= '<option value="-1">'.($empty_label ? $empty_label : '&nbsp;').'</option>'; - if (!empty($fk_product)) - { + if ($empty) { + $out .= '<option value="-1">'.($empty_label ? $empty_label : '&nbsp;').'</option>'; + } + if (!empty($fk_product)) { $productIdArray = array($fk_product); // only show lot stock for product } else { - foreach ($this->cache_lot as $key => $value) - { + foreach ($this->cache_lot as $key => $value) { $productIdArray[] = $key; } } - foreach ($productIdArray as $productId) - { - foreach ($this->cache_lot[$productId] as $id => $arraytypes) - { - if (empty($fk_entrepot) || $fk_entrepot == $arraytypes['entrepot_id']) - { + foreach ($productIdArray as $productId) { + foreach ($this->cache_lot[$productId] as $id => $arraytypes) { + if (empty($fk_entrepot) || $fk_entrepot == $arraytypes['entrepot_id']) { $label = $arraytypes['entrepot_label'].' - '; $label .= $arraytypes['batch']; if ($arraytypes['qty'] <= 0) { @@ -565,7 +594,9 @@ class FormProduct } $out .= '<option value="'.$id.'"'; - if ($selected == $id || ($selected == 'ifone' && $nboflot == 1)) $out .= ' selected'; + if ($selected == $id || ($selected == 'ifone' && $nboflot == 1)) { + $out .= ' selected'; + } $out .= ' data-html="'.dol_escape_htmltag($label).'"'; $out .= '>'; $out .= $label; @@ -574,7 +605,9 @@ class FormProduct } } $out .= '</select>'; - if ($disabled) $out .= '<input type="hidden" name="'.$htmlname.'" value="'.(($selected > 0) ? $selected : '').'">'; + if ($disabled) { + $out .= '<input type="hidden" name="'.$htmlname.'" value="'.(($selected > 0) ? $selected : '').'">'; + } return $out; } @@ -591,22 +624,18 @@ class FormProduct global $conf, $langs; $cacheLoaded = false; - if (empty($productIdArray)) - { + if (empty($productIdArray)) { // only Load lot stock for given products $this->cache_lot = array(); return 0; } - if (count($productIdArray) && count($this->cache_lot)) - { + if (count($productIdArray) && count($this->cache_lot)) { // check cache already loaded for product id's - foreach ($productIdArray as $productId) - { + foreach ($productIdArray as $productId) { $cacheLoaded = !empty($this->cache_lot[$productId]) ? true : false; } } - if ($cacheLoaded) - { + if ($cacheLoaded) { return count($this->cache_lot); } else { // clear cache @@ -616,20 +645,17 @@ class FormProduct $sql .= " FROM ".MAIN_DB_PREFIX."product_batch as pb"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.rowid = pb.fk_product_stock"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on e.rowid = ps.fk_entrepot AND e.entity IN (".getEntity('stock').")"; - if (!empty($productIdList)) - { + if (!empty($productIdList)) { $sql .= " WHERE ps.fk_product IN (".$productIdList.")"; } $sql .= " ORDER BY e.ref, pb.batch"; dol_syslog(get_class($this).'::loadLotStock', LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $this->cache_lot[$obj->fk_product][$obj->rowid]['id'] = $obj->rowid; $this->cache_lot[$obj->fk_product][$obj->rowid]['batch'] = $obj->batch; diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index 9a71faa5665..f195fa0c5e7 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -92,10 +92,10 @@ class Product extends CommonObject public $regeximgext = '\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.webp|\.xpm|\.xbm'; // See also into images.lib.php - /* - * @deprecated - * @see label - */ + /** + * @deprecated + * @see $label + */ public $libelle; /** @@ -227,8 +227,8 @@ class Product extends CommonObject public $desiredstock = 0; /* - * Service expiration - */ + * Service expiration + */ public $duration_value; /** @@ -407,15 +407,24 @@ class Product extends CommonObject */ public $supplierprices; + /** + * Property set to save result of isObjectUsed(). Used for example by Product API. + * + * @var boolean + */ + public $is_object_used; + + /** * @var array fields of object product */ public $fields = array( 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'), 'ref' =>array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'), - 'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>'!empty($conf->barcode->enabled)', 'visible'=>-1, 'showoncombobox'=>1), - 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20), - 'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>5), + 'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>15), + 'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>'!empty($conf->barcode->enabled)', 'position'=>20, 'visible'=>-1, 'showoncombobox'=>1), + 'fk_barcode_type' => array('type'=>'integer', 'label'=>'BarcodeType', 'enabled'=>'1', 'position'=>21, 'notnull'=>0, 'visible'=>-1,), 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61), 'note' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62), 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500), @@ -424,6 +433,10 @@ class Product extends CommonObject 'fk_user_author'=>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'), 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511), //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512), + 'localtax1_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax1tx', 'enabled'=>'1', 'position'=>150, 'notnull'=>0, 'visible'=>-1,), + 'localtax1_type' => array('type'=>'varchar(10)', 'label'=>'Localtax1type', 'enabled'=>'1', 'position'=>155, 'notnull'=>1, 'visible'=>-1,), + 'localtax2_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax2tx', 'enabled'=>'1', 'position'=>160, 'notnull'=>0, 'visible'=>-1,), + 'localtax2_type' => array('type'=>'varchar(10)', 'label'=>'Localtax2type', 'enabled'=>'1', 'position'=>165, 'notnull'=>1, 'visible'=>-1,), 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000), //'tosell' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')), //'tobuy' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')), @@ -588,8 +601,7 @@ class Product extends CommonObject if (empty($this->ref) || $this->ref == 'auto') { // Load object modCodeProduct $module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard'); - if ($module != 'mod_codeproduct_leopard') // Do not load module file for leopard - { + if ($module != 'mod_codeproduct_leopard') { // Do not load module file for leopard if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } @@ -728,7 +740,8 @@ class Product extends CommonObject if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('PRODUCT_CREATE', $user); - if ($result < 0) { $error++; + if ($result < 0) { + $error++; } // End call triggers } @@ -802,10 +815,10 @@ class Product extends CommonObject $module = strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM); $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']); - foreach ($dirsociete as $dirroot) - { + foreach ($dirsociete as $dirroot) { $res = dol_include_once($dirroot.$module.'.php'); - if ($res) { break; + if ($res) { + break; } } @@ -947,16 +960,16 @@ class Product extends CommonObject if ($this->hasbatch() && !$this->oldcopy->hasbatch()) { //$valueforundefinedlot = 'Undefined'; // In previous version, 39 and lower $valueforundefinedlot = '000000'; - if (!empty($conf->global->STOCK_DEFAULT_BATCH)) $valueforundefinedlot = $conf->global->STOCK_DEFAULT_BATCH; + if (!empty($conf->global->STOCK_DEFAULT_BATCH)) { + $valueforundefinedlot = $conf->global->STOCK_DEFAULT_BATCH; + } dol_syslog("Flag batch of product id=".$this->id." is set to ON, so we will create missing records into product_batch"); $this->load_stock(); - foreach ($this->stock_warehouse as $idW => $ObjW) // For each warehouse where we have stocks defined for this product (for each lines in product_stock) - { + foreach ($this->stock_warehouse as $idW => $ObjW) { // For each warehouse where we have stocks defined for this product (for each lines in product_stock) $qty_batch = 0; - foreach ($ObjW->detail_batch as $detail) // Each lines of detail in product_batch of the current $ObjW = product_stock - { + foreach ($ObjW->detail_batch as $detail) { // Each lines of detail in product_batch of the current $ObjW = product_stock if ($detail->batch == $valueforundefinedlot || $detail->batch == 'Undefined') { // We discard this line, we will create it later $sqlclean = "DELETE FROM ".MAIN_DB_PREFIX."product_batch WHERE batch in('Undefined', '".$this->db->escape($valueforundefinedlot)."') AND fk_product_stock = ".$ObjW->id; @@ -987,7 +1000,8 @@ class Product extends CommonObject } // For automatic creation - if ($this->barcode == -1) { $this->barcode = $this->get_barcode($this, $this->barcode_type_code); + if ($this->barcode == -1) { + $this->barcode = $this->get_barcode($this, $this->barcode_type_code); } $sql = "UPDATE ".MAIN_DB_PREFIX."product"; @@ -1051,7 +1065,7 @@ class Product extends CommonObject $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : 'NULL'); // stock field is not here because it is a denormalized value from product_stock. - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); dol_syslog(get_class($this)."::update", LOG_DEBUG); @@ -1201,8 +1215,7 @@ class Product extends CommonObject // Delete all child tables if (!$error) { $elements = array('product_fournisseur_price', 'product_price', 'product_lang', 'categorie_product', 'product_stock', 'product_customer_price', 'product_lot'); // product_batch is done before - foreach ($elements as $table) - { + foreach ($elements as $table) { if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table; $sql .= " WHERE fk_product = ".(int) $this->id; @@ -1287,8 +1300,7 @@ class Product extends CommonObject $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -1314,8 +1326,7 @@ class Product extends CommonObject $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 0, 2); $current_lang = $langs->getDefaultLang(); - foreach ($langs_available as $key => $value) - { + foreach ($langs_available as $key => $value) { if ($key == $current_lang) { $sql = "SELECT rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; @@ -1324,18 +1335,19 @@ class Product extends CommonObject $result = $this->db->query($sql); - if ($this->db->num_rows($result)) // if there is already a description line for this language - { + if ($this->db->num_rows($result)) { // if there is already a description line for this language $sql2 = "UPDATE ".MAIN_DB_PREFIX."product_lang"; $sql2 .= " SET "; $sql2 .= " label='".$this->db->escape($this->label)."',"; $sql2 .= " description='".$this->db->escape($this->description)."'"; - if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2 .= ", note='".$this->db->escape($this->other)."'"; + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { + $sql2 .= ", note='".$this->db->escape($this->other)."'"; } $sql2 .= " WHERE fk_product=".$this->id." AND lang='".$this->db->escape($key)."'"; } else { $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_lang (fk_product, lang, label, description"; - if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2 .= ", note"; + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { + $sql2 .= ", note"; } $sql2 .= ")"; $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->label)."',"; @@ -1351,6 +1363,11 @@ class Product extends CommonObject return -1; } } elseif (isset($this->multilangs[$key])) { + if (empty($this->multilangs["$key"]["label"])) { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")); + return -1; + } + $sql = "SELECT rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sql .= " WHERE fk_product=".$this->id; @@ -1358,8 +1375,7 @@ class Product extends CommonObject $result = $this->db->query($sql); - if ($this->db->num_rows($result)) // if there is already a description line for this language - { + if ($this->db->num_rows($result)) { // if there is already a description line for this language $sql2 = "UPDATE ".MAIN_DB_PREFIX."product_lang"; $sql2 .= " SET "; $sql2 .= " label='".$this->db->escape($this->multilangs["$key"]["label"])."',"; @@ -1370,7 +1386,8 @@ class Product extends CommonObject $sql2 .= " WHERE fk_product=".$this->id." AND lang='".$this->db->escape($key)."'"; } else { $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_lang (fk_product, lang, label, description"; - if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2 .= ", note"; + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { + $sql2 .= ", note"; } $sql2 .= ")"; $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->multilangs["$key"]["label"])."',"; @@ -1478,7 +1495,9 @@ class Product extends CommonObject if ($resql) { // Call trigger $result = $this->call_trigger('PRODUCT_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers if ($error) { @@ -1514,11 +1533,9 @@ class Product extends CommonObject $result = $this->db->query($sql); if ($result) { - while ($obj = $this->db->fetch_object($result)) - { + while ($obj = $this->db->fetch_object($result)) { //print 'lang='.$obj->lang.' current='.$current_lang.'<br>'; - if ($obj->lang == $current_lang) // si on a les traduct. dans la langue courante on les charge en infos principales. - { + if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales. $this->label = $obj->label; $this->description = $obj->description; $this->other = $obj->other; @@ -1618,7 +1635,9 @@ class Product extends CommonObject // Update if prices fields are defined $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $this->id); $tva_npr = get_default_npr($thirdparty_seller, $thirdparty_buyer, $this->id); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $pu_ht = $this->price; $pu_ttc = $this->price_ttc; @@ -1631,11 +1650,16 @@ class Product extends CommonObject $pu_ttc = $this->multiprices_ttc[$thirdparty_buyer->price_level]; $price_min = $this->multiprices_min[$thirdparty_buyer->price_level]; $price_base_type = $this->multiprices_base_type[$thirdparty_buyer->price_level]; - if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility - { - if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level]; - if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level]; - if (empty($tva_tx)) $tva_npr = 0; + if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility + if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) { + $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level]; + } + if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) { + $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level]; + } + if (empty($tva_tx)) { + $tva_npr = 0; + } } } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { // If price per customer @@ -1653,9 +1677,13 @@ class Product extends CommonObject $pu_ttc = price($prodcustprice->lines[0]->price_ttc); $price_base_type = $prodcustprice->lines[0]->price_base_type; $tva_tx = $prodcustprice->lines[0]->tva_tx; - if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; + if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) { + $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; + } $tva_npr = $prodcustprice->lines[0]->recuperableonly; - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } } } } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { @@ -1664,10 +1692,11 @@ class Product extends CommonObject // yes, this product has some prices per quantity // Search price into product_price_by_qty from $this->id foreach ($this->prices_by_qty_list[0] as $priceforthequantityarray) { - if ($priceforthequantityarray['rowid'] != $pqp) continue; + if ($priceforthequantityarray['rowid'] != $pqp) { + continue; + } // We found the price - if ($priceforthequantityarray['price_base_type'] == 'HT') - { + if ($priceforthequantityarray['price_base_type'] == 'HT') { $pu_ht = $priceforthequantityarray['unitprice']; } else { $pu_ttc = $priceforthequantityarray['unitprice']; @@ -1680,12 +1709,12 @@ class Product extends CommonObject if ($this->prices_by_qty[$thirdparty_buyer->price_level]) { // yes, this product has some prices per quantity // Search price into product_price_by_qty from $this->id - foreach ($this->prices_by_qty_list[$thirdparty_buyer->price_level] as $priceforthequantityarray) - { - if ($priceforthequantityarray['rowid'] != $pqp) continue; + foreach ($this->prices_by_qty_list[$thirdparty_buyer->price_level] as $priceforthequantityarray) { + if ($priceforthequantityarray['rowid'] != $pqp) { + continue; + } // We found the price - if ($priceforthequantityarray['price_base_type'] == 'HT') - { + if ($priceforthequantityarray['price_base_type'] == 'HT') { $pu_ht = $priceforthequantityarray['unitprice']; } else { $pu_ttc = $priceforthequantityarray['unitprice']; @@ -1723,10 +1752,13 @@ class Product extends CommonObject $sql .= " pfp.fk_product, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_soc, pfp.tva_tx, pfp.fk_supplier_price_expression,"; $sql .= " pfp.default_vat_code,"; $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code"; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", pfp.packaging"; + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + $sql .= ", pfp.packaging"; + } $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; $sql .= " WHERE pfp.rowid = ".$prodfournprice; - if ($qty > 0) { $sql .= " AND pfp.quantity <= ".$qty; + if ($qty > 0) { + $sql .= " AND pfp.quantity <= ".$qty; } $sql .= " ORDER BY pfp.quantity DESC"; @@ -1734,8 +1766,7 @@ class Product extends CommonObject $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj && $obj->quantity > 0) // If we found a supplier prices from the id of supplier price - { + if ($obj && $obj->quantity > 0) { // If we found a supplier prices from the id of supplier price if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) { include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; $prod_supplier = new ProductFournisseur($this->db); @@ -1766,7 +1797,9 @@ class Product extends CommonObject $this->fourn_multicurrency_tx = $obj->multicurrency_tx; $this->fourn_multicurrency_id = $obj->fk_multicurrency; $this->fourn_multicurrency_code = $obj->multicurrency_code; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $this->packaging = $obj->packaging; + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + $this->packaging = $obj->packaging; + } $result = $obj->fk_product; return $result; } else { // If not found @@ -1778,11 +1811,14 @@ class Product extends CommonObject $sql .= " pfp.packaging"; $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; $sql .= " WHERE pfp.fk_product = ".$product_id; - if ($fourn_ref != 'none') { $sql .= " AND pfp.ref_fourn = '".$this->db->escape($fourn_ref)."'"; + if ($fourn_ref != 'none') { + $sql .= " AND pfp.ref_fourn = '".$this->db->escape($fourn_ref)."'"; } - if ($fk_soc > 0) { $sql .= " AND pfp.fk_soc = ".$fk_soc; + if ($fk_soc > 0) { + $sql .= " AND pfp.fk_soc = ".$fk_soc; } - if ($qty > 0) { $sql .= " AND pfp.quantity <= ".$qty; + if ($qty > 0) { + $sql .= " AND pfp.quantity <= ".$qty; } $sql .= " ORDER BY pfp.quantity DESC"; $sql .= " LIMIT 1"; @@ -1791,8 +1827,7 @@ class Product extends CommonObject $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj && $obj->quantity > 0) // If found - { + if ($obj && $obj->quantity > 0) { // If found if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) { include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; $prod_supplier = new ProductFournisseur($this->db); @@ -1824,7 +1859,9 @@ class Product extends CommonObject $this->fourn_multicurrency_tx = $obj->multicurrency_tx; $this->fourn_multicurrency_id = $obj->fk_multicurrency; $this->fourn_multicurrency_code = $obj->multicurrency_code; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $this->packaging = $obj->packaging; + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + $this->packaging = $obj->packaging; + } $result = $obj->fk_product; return $result; } else { @@ -1963,7 +2000,7 @@ class Product extends CommonObject $sql .= " default_vat_code=".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").","; $sql .= " tva_tx='".price2num($newvat)."',"; $sql .= " recuperableonly='".$this->db->escape($newnpr)."'"; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); dol_syslog(get_class($this)."::update_price", LOG_DEBUG); $resql = $this->db->query($sql); @@ -2184,10 +2221,8 @@ class Product extends CommonObject } // Load multiprices array - if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($ignore_price_load)) // prices per segment - { - for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) - { + if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($ignore_price_load)) { // prices per segment + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { $sql = "SELECT price, price_ttc, price_min, price_min_ttc,"; $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly"; $sql .= " FROM ".MAIN_DB_PREFIX."product_price"; @@ -2211,49 +2246,47 @@ class Product extends CommonObject // Price by quantity /* - $this->prices_by_qty[$i]=$result["price_by_qty"]; - $this->prices_by_qty_id[$i]=$result["rowid"]; - // Récuperation de la liste des prix selon qty si flag positionné - if ($this->prices_by_qty[$i] == 1) - { - $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty"; - $sql.= " WHERE fk_product_price = ".$this->prices_by_qty_id[$i]; - $sql.= " ORDER BY quantity ASC"; - $resultat=array(); - $resql = $this->db->query($sql); - if ($resql) - { - $ii=0; - while ($result= $this->db->fetch_array($resql)) { - $resultat[$ii]=array(); - $resultat[$ii]["rowid"]=$result["rowid"]; - $resultat[$ii]["price"]= $result["price"]; - $resultat[$ii]["unitprice"]= $result["unitprice"]; - $resultat[$ii]["quantity"]= $result["quantity"]; - $resultat[$ii]["remise_percent"]= $result["remise_percent"]; - $resultat[$ii]["remise"]= $result["remise"]; // deprecated - $resultat[$ii]["price_base_type"]= $result["price_base_type"]; - $ii++; - } - $this->prices_by_qty_list[$i]=$resultat; - } - else - { - dol_print_error($this->db); - return -1; - } - }*/ + $this->prices_by_qty[$i]=$result["price_by_qty"]; + $this->prices_by_qty_id[$i]=$result["rowid"]; + // Récuperation de la liste des prix selon qty si flag positionné + if ($this->prices_by_qty[$i] == 1) + { + $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type"; + $sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty"; + $sql.= " WHERE fk_product_price = ".$this->prices_by_qty_id[$i]; + $sql.= " ORDER BY quantity ASC"; + $resultat=array(); + $resql = $this->db->query($sql); + if ($resql) + { + $ii=0; + while ($result= $this->db->fetch_array($resql)) { + $resultat[$ii]=array(); + $resultat[$ii]["rowid"]=$result["rowid"]; + $resultat[$ii]["price"]= $result["price"]; + $resultat[$ii]["unitprice"]= $result["unitprice"]; + $resultat[$ii]["quantity"]= $result["quantity"]; + $resultat[$ii]["remise_percent"]= $result["remise_percent"]; + $resultat[$ii]["remise"]= $result["remise"]; // deprecated + $resultat[$ii]["price_base_type"]= $result["price_base_type"]; + $ii++; + } + $this->prices_by_qty_list[$i]=$resultat; + } + else + { + dol_print_error($this->db); + return -1; + } + }*/ } else { $this->error = $this->db->lasterror; return -1; } } - } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && empty($ignore_price_load)) // prices per customers - { + } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && empty($ignore_price_load)) { // prices per customers // Nothing loaded by default. List may be very long. - } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && empty($ignore_price_load)) // prices per quantity - { + } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && empty($ignore_price_load)) { // prices per quantity $sql = "SELECT price, price_ttc, price_min, price_min_ttc,"; $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."product_price"; @@ -2298,10 +2331,8 @@ class Product extends CommonObject $this->error = $this->db->lasterror; return -1; } - } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES) && empty($ignore_price_load)) // prices per customer and quantity - { - for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) - { + } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES) && empty($ignore_price_load)) { // prices per customer and quantity + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { $sql = "SELECT price, price_ttc, price_min, price_min_ttc,"; $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly"; $sql .= " FROM ".MAIN_DB_PREFIX."product_price"; @@ -2439,7 +2470,9 @@ class Product extends CommonObject $parameters = array('socid' => $socid); $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action); - if ($reshook > 0) $this->stats_mo = $hookmanager->resArray['stats_mo']; + if ($reshook > 0) { + $this->stats_mo = $hookmanager->resArray['stats_mo']; + } return 1; } @@ -2464,7 +2497,7 @@ class Product extends CommonObject $this->stats_bom['qty_toconsume'] = 0; $sql = "SELECT COUNT(DISTINCT b.rowid) as nb_toproduce,"; - $sql .= " b.qty as qty_toproduce"; + $sql .= " SUM(b.qty) as qty_toproduce"; $sql .= " FROM ".MAIN_DB_PREFIX."bom_bom as b"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."bom_bomline as bl ON bl.fk_bom=b.rowid"; $sql .= " WHERE "; @@ -2506,7 +2539,9 @@ class Product extends CommonObject $parameters = array('socid' => $socid); $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action); - if ($reshook > 0) $this->stats_bom = $hookmanager->resArray['stats_bom']; + if ($reshook > 0) { + $this->stats_bom = $hookmanager->resArray['stats_bom']; + } return 1; } @@ -2574,7 +2609,9 @@ class Product extends CommonObject $parameters = array('socid' => $socid); $reshook = $hookmanager->executeHooks('loadStatsCustomerProposal', $parameters, $this, $action); - if ($reshook > 0) $this->stats_propale = $hookmanager->resArray['stats_propale']; + if ($reshook > 0) { + $this->stats_propale = $hookmanager->resArray['stats_propale']; + } return 1; } else { @@ -2626,7 +2663,9 @@ class Product extends CommonObject $parameters = array('socid' => $socid); $reshook = $hookmanager->executeHooks('loadStatsSupplierProposal', $parameters, $this, $action); - if ($reshook > 0) $this->stats_proposal_supplier = $hookmanager->resArray['stats_proposal_supplier']; + if ($reshook > 0) { + $this->stats_proposal_supplier = $hookmanager->resArray['stats_proposal_supplier']; + } return 1; } else { @@ -2728,7 +2767,9 @@ class Product extends CommonObject $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock); $reshook = $hookmanager->executeHooks('loadStatsCustomerOrder', $parameters, $this, $action); - if ($reshook > 0) $this->stats_commande = $hookmanager->resArray['stats_commande']; + if ($reshook > 0) { + $this->stats_commande = $hookmanager->resArray['stats_commande']; + } return 1; } else { $this->error = $this->db->error(); @@ -2782,7 +2823,9 @@ class Product extends CommonObject $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock); $reshook = $hookmanager->executeHooks('loadStatsSupplierOrder', $parameters, $this, $action); - if ($reshook > 0) $this->stats_commande_fournisseur = $hookmanager->resArray['stats_commande_fournisseur']; + if ($reshook > 0) { + $this->stats_commande_fournisseur = $hookmanager->resArray['stats_commande_fournisseur']; + } return 1; } else { @@ -2831,7 +2874,9 @@ class Product extends CommonObject if ($filtrestatut <> '') { $sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")"; } - if (!empty($filterShipmentStatus)) $sql .= " AND e.fk_statut IN (".$this->db->sanitize($filterShipmentStatus).")"; + if (!empty($filterShipmentStatus)) { + $sql .= " AND e.fk_statut IN (".$this->db->sanitize($filterShipmentStatus).")"; + } $result = $this->db->query($sql); if ($result) { @@ -2864,7 +2909,9 @@ class Product extends CommonObject $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock, 'filterShipmentStatus' => $filterShipmentStatus); $reshook = $hookmanager->executeHooks('loadStatsSending', $parameters, $this, $action); - if ($reshook > 0) $this->stats_expedition = $hookmanager->resArray['stats_expedition']; + if ($reshook > 0) { + $this->stats_expedition = $hookmanager->resArray['stats_expedition']; + } return 1; } else { @@ -2919,7 +2966,9 @@ class Product extends CommonObject $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock); $reshook = $hookmanager->executeHooks('loadStatsReception', $parameters, $this, $action); - if ($reshook > 0) $this->stats_reception = $hookmanager->resArray['stats_reception']; + if ($reshook > 0) { + $this->stats_reception = $hookmanager->resArray['stats_reception']; + } return 1; } else { @@ -3003,12 +3052,18 @@ class Product extends CommonObject } // Clean data - if ($this->stats_mrptoconsume['qty'] < 0) $this->stats_mrptoconsume['qty'] = 0; - if ($this->stats_mrptoproduce['qty'] < 0) $this->stats_mrptoproduce['qty'] = 0; + if ($this->stats_mrptoconsume['qty'] < 0) { + $this->stats_mrptoconsume['qty'] = 0; + } + if ($this->stats_mrptoproduce['qty'] < 0) { + $this->stats_mrptoproduce['qty'] = 0; + } $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock); $reshook = $hookmanager->executeHooks('loadStatsInProduction', $parameters, $this, $action); - if ($reshook > 0) $this->stats_mrptoproduce = $hookmanager->resArray['stats_mrptoproduce']; + if ($reshook > 0) { + $this->stats_mrptoproduce = $hookmanager->resArray['stats_mrptoproduce']; + } return 1; } else { @@ -3080,7 +3135,9 @@ class Product extends CommonObject $parameters = array('socid' => $socid); $reshook = $hookmanager->executeHooks('loadStatsContract', $parameters, $this, $action); - if ($reshook > 0) $this->stats_contrat = $hookmanager->resArray['stats_contrat']; + if ($reshook > 0) { + $this->stats_contrat = $hookmanager->resArray['stats_contrat']; + } return 1; } else { @@ -3152,7 +3209,9 @@ class Product extends CommonObject $parameters = array('socid' => $socid); $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoice', $parameters, $this, $action); - if ($reshook > 0) $this->stats_facture = $hookmanager->resArray['stats_facture']; + if ($reshook > 0) { + $this->stats_facture = $hookmanager->resArray['stats_facture']; + } return 1; } else { @@ -3203,7 +3262,9 @@ class Product extends CommonObject $parameters = array('socid' => $socid); $reshook = $hookmanager->executeHooks('loadStatsSupplierInvoice', $parameters, $this, $action); - if ($reshook > 0) $this->stats_facture_fournisseur = $hookmanager->resArray['stats_facture_fournisseur']; + if ($reshook > 0) { + $this->stats_facture_fournisseur = $hookmanager->resArray['stats_facture_fournisseur']; + } return 1; } else { @@ -3230,8 +3291,7 @@ class Product extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $arr = $this->db->fetch_array($resql); $keyfortab = (string) $arr[1]; if ($year == -1) { @@ -3262,8 +3322,7 @@ class Product extends CommonObject $result = array(); - for ($j = 0; $j < 12; $j++) - { + for ($j = 0; $j < 12; $j++) { // $ids is 'D', 'N', 'O', 'S', ... (First letter of month in user language) $idx = ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, 1970), "%b"), 1, 'right', 'UTF-8', 1)); @@ -3912,8 +3971,10 @@ class Product extends CommonObject $sql = "SELECT rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; $sql .= " WHERE fk_soc = ".$id_fourn; - if ($ref_fourn) { $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'"; - } else { $sql .= " AND (ref_fourn = '' OR ref_fourn IS NULL)"; + if ($ref_fourn) { + $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'"; + } else { + $sql .= " AND (ref_fourn = '' OR ref_fourn IS NULL)"; } $sql .= " AND quantity = ".$quantity; $sql .= " AND fk_product = ".$this->id; @@ -3986,8 +4047,7 @@ class Product extends CommonObject if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $list[$i] = $obj->fk_soc; $i++; @@ -4129,16 +4189,16 @@ class Product extends CommonObject // les fournisseurs /*$sql = "INSERT ".MAIN_DB_PREFIX."product_fournisseur (" - . " datec, fk_product, fk_soc, ref_fourn, fk_user_author )" - . " SELECT '".$this->db->idate($now)."', ".$toId.", fk_soc, ref_fourn, fk_user_author" - . " FROM ".MAIN_DB_PREFIX."product_fournisseur" - . " WHERE fk_product = ".$fromId; + . " datec, fk_product, fk_soc, ref_fourn, fk_user_author )" + . " SELECT '".$this->db->idate($now)."', ".$toId.", fk_soc, ref_fourn, fk_user_author" + . " FROM ".MAIN_DB_PREFIX."product_fournisseur" + . " WHERE fk_product = ".$fromId; - if ( ! $this->db->query($sql ) ) - { - $this->db->rollback(); - return -1; - }*/ + if ( ! $this->db->query($sql ) ) + { + $this->db->rollback(); + return -1; + }*/ // les prix de fournisseurs. $sql = "INSERT ".MAIN_DB_PREFIX."product_fournisseur_price ("; @@ -4163,39 +4223,43 @@ class Product extends CommonObject * Fonction recursive uniquement utilisee par get_arbo_each_prod, recompose l'arborescence des sousproduits * Define value of this->res * - * @param array $prod Products array - * @param string $compl_path Directory path of parents to add before - * @param int $multiply Because each sublevel must be multiplicated by parent nb - * @param int $level Init level - * @param int $id_parent Id parent + * @param array $prod Products array + * @param string $compl_path Directory path of parents to add before + * @param int $multiply Because each sublevel must be multiplicated by parent nb + * @param int $level Init level + * @param int $id_parent Id parent + * @param int $ignore_stock_load Ignore stock load * @return void */ - public function fetch_prod_arbo($prod, $compl_path = "", $multiply = 1, $level = 1, $id_parent = 0) + public function fetch_prod_arbo($prod, $compl_path = '', $multiply = 1, $level = 1, $id_parent = 0, $ignore_stock_load = 0) { // phpcs:enable global $conf, $langs; $tmpproduct = null; //var_dump($prod); - foreach ($prod as $id_product => $desc_pere) // $id_product is 0 (first call starting with root top) or an id of a sub_product - { - if (is_array($desc_pere)) // If desc_pere is an array, this means it's a child - { + foreach ($prod as $id_product => $desc_pere) { // $id_product is 0 (first call starting with root top) or an id of a sub_product + if (is_array($desc_pere)) { // If desc_pere is an array, this means it's a child $id = (!empty($desc_pere[0]) ? $desc_pere[0] : ''); $nb = (!empty($desc_pere[1]) ? $desc_pere[1] : ''); $type = (!empty($desc_pere[2]) ? $desc_pere[2] : ''); $label = (!empty($desc_pere[3]) ? $desc_pere[3] : ''); - $incdec = !empty($desc_pere[4]) ? $desc_pere[4] : 0; + $incdec = (!empty($desc_pere[4]) ? $desc_pere[4] : 0); - if ($multiply < 1) { $multiply = 1; + if ($multiply < 1) { + $multiply = 1; } //print "XXX We add id=".$id." - label=".$label." - nb=".$nb." - multiply=".$multiply." fullpath=".$compl_path.$label."\n"; - if (is_null($tmpproduct)) $tmpproduct = new Product($this->db); // So we initialize tmpproduct only once for all loop. + if (is_null($tmpproduct)) { + $tmpproduct = new Product($this->db); // So we initialize tmpproduct only once for all loop. + } $tmpproduct->fetch($id); // Load product to get ->ref - $tmpproduct->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel - //$this->fetch($id); // Load product to get ->ref - //$this->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel + + if (empty($ignore_stock_load) && ($tmpproduct->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) { + $tmpproduct->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel + } + $this->res[] = array( 'id'=>$id, // Id product 'id_parent'=>$id_parent, @@ -4216,7 +4280,7 @@ class Product extends CommonObject // Recursive call if there is childs to child if (is_array($desc_pere['childs'])) { //print 'YYY We go down for '.$desc_pere[3]." -> \n"; - $this->fetch_prod_arbo($desc_pere['childs'], $compl_path.$desc_pere[3]." -> ", $desc_pere[1] * $multiply, $level + 1, $id); + $this->fetch_prod_arbo($desc_pere['childs'], $compl_path.$desc_pere[3]." -> ", $desc_pere[1] * $multiply, $level + 1, $id, $ignore_stock_load); } } } @@ -4224,20 +4288,21 @@ class Product extends CommonObject // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Build the tree of subproducts into an array - * this->sousprods is loaded by this->get_sousproduits_arbo() + * Build the tree of subproducts into an array ->res and return it. + * this->sousprods must have been loaded by this->get_sousproduits_arbo() * - * @param int $multiply Because each sublevel must be multiplicated by parent nb - * @return array $this->res + * @param int $multiply Because each sublevel must be multiplicated by parent nb + * @param int $ignore_stock_load Ignore stock load + * @return array $this->res */ - public function get_arbo_each_prod($multiply = 1) + public function get_arbo_each_prod($multiply = 1, $ignore_stock_load = 0) { // phpcs:enable $this->res = array(); if (isset($this->sousprods) && is_array($this->sousprods)) { foreach ($this->sousprods as $prod_name => $desc_product) { if (is_array($desc_product)) { - $this->fetch_prod_arbo($desc_product, "", $multiply, 1, $this->id); + $this->fetch_prod_arbo($desc_product, "", $multiply, 1, $this->id, $ignore_stock_load); } } } @@ -4269,7 +4334,9 @@ class Product extends CommonObject $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) { $nb = $obj->nb; } + if ($obj) { + $nb = $obj->nb; + } } else { return -1; } @@ -4291,7 +4358,8 @@ class Product extends CommonObject $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) { $nb = $obj->nb; + if ($obj) { + $nb = $obj->nb; } } @@ -4376,6 +4444,10 @@ class Product extends CommonObject { global $alreadyfound; + if (empty($id)) { + return array(); + } + $sql = "SELECT p.rowid, p.ref, p.label as label, p.fk_product_type,"; $sql .= " pa.qty as qty, pa.fk_product_fils as id, pa.incdec"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p,"; @@ -4386,17 +4458,18 @@ class Product extends CommonObject dol_syslog(get_class($this).'::getChildsArbo id='.$id.' level='.$level, LOG_DEBUG); - if ($level == 1) { $alreadyfound = array($id=>1); // We init array of found object to start of tree, so if we found it later (should not happened), we stop immediatly + if ($level == 1) { + $alreadyfound = array($id=>1); // We init array of found object to start of tree, so if we found it later (should not happened), we stop immediatly } // Protection against infinite loop - if ($level > 30) { return array(); + if ($level > 30) { + return array(); } $res = $this->db->query($sql); if ($res) { $prods = array(); - while ($rec = $this->db->fetch_array($res)) - { + while ($rec = $this->db->fetch_array($res)) { if (!empty($alreadyfound[$rec['rowid']])) { dol_syslog(get_class($this).'::getChildsArbo the product id='.$rec['rowid'].' was already found at a higher level in tree. We discard to avoid infinite loop', LOG_WARNING); continue; @@ -4414,8 +4487,7 @@ class Product extends CommonObject //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty']); if (empty($firstlevelonly)) { $listofchilds = $this->getChildsArbo($rec['rowid'], 0, $level + 1); - foreach ($listofchilds as $keyChild => $valueChild) - { + foreach ($listofchilds as $keyChild => $valueChild) { $prods[$rec['rowid']]['childs'][$keyChild] = $valueChild; } } @@ -4440,12 +4512,10 @@ class Product extends CommonObject // phpcs:enable $parent = array(); - foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product - { + foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) { // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product $parent[$this->label][$keyChild] = $valueChild; } - foreach ($parent as $key => $value) // key=label, value is array of childs - { + foreach ($parent as $key => $value) { // key=label, value is array of childs $this->sousprods[$key] = $value; } } @@ -4507,8 +4577,7 @@ class Product extends CommonObject $label .= '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode; } - if ($this->type == Product::TYPE_PRODUCT) - { + if ($this->type == Product::TYPE_PRODUCT) { if ($this->weight) { $label .= "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units); } @@ -4522,7 +4591,9 @@ class Product extends CommonObject if ($this->height) { $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units); } - if ($labelsize) $label .= "<br>".$labelsize; + if ($labelsize) { + $label .= "<br>".$labelsize; + } $labelsurfacevolume = ""; if ($this->surface) { @@ -4531,7 +4602,12 @@ class Product extends CommonObject if ($this->volume) { $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units); } - if ($labelsurfacevolume) $label .= "<br>".$labelsurfacevolume; + if ($labelsurfacevolume) { + $label .= "<br>".$labelsurfacevolume; + } + } + if (!empty($this->pmp) && $this->pmp) { + $label .= "<br><b>".$langs->trans("PMPValue").'</b>: '.price($this->pmp, 0, '', 1, -1, -1, $conf->currency); } if (!empty($conf->accounting->enabled) && $this->status) { @@ -4573,9 +4649,11 @@ class Product extends CommonObject 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 ($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 ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; } } @@ -4584,13 +4662,12 @@ class Product extends CommonObject $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) - { + if ($withpicto) { if ($this->type == Product::TYPE_PRODUCT) { $result .= (img_object(($notooltip ? '' : $label), 'product', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1)); } if ($this->type == Product::TYPE_SERVICE) { - $result .= (img_object(($notooltip ? '' : $label), 'service', ($notooltip ? 'class="paddinright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1)); + $result .= (img_object(($notooltip ? '' : $label), 'service', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1)); } } $result .= $newref; @@ -4650,17 +4727,16 @@ class Product extends CommonObject */ public function getLibStatut($mode = 0, $type = 0) { - switch ($type) - { + switch ($type) { case 0: - return $this->LibStatut($this->status, $mode, $type); + return $this->LibStatut($this->status, $mode, $type); case 1: - return $this->LibStatut($this->status_buy, $mode, $type); + return $this->LibStatut($this->status_buy, $mode, $type); case 2: - return $this->LibStatut($this->status_batch, $mode, $type); + return $this->LibStatut($this->status_batch, $mode, $type); default: //Simulate previous behavior but should return an error string - return $this->LibStatut($this->status_buy, $mode, $type); + return $this->LibStatut($this->status_buy, $mode, $type); } } @@ -4681,17 +4757,17 @@ class Product extends CommonObject $labelStatus = $labelStatusShort = ''; $langs->load('products'); - if (!empty($conf->productbatch->enabled)) { $langs->load("productbatch"); + if (!empty($conf->productbatch->enabled)) { + $langs->load("productbatch"); } if ($type == 2) { - switch ($mode) - { + switch ($mode) { case 0: - $label = ($status == 0 ? $langs->trans('ProductStatusNotOnBatch') : $langs->trans('ProductStatusOnBatch')); + $label = ($status == 0 ? $langs->trans('ProductStatusNotOnBatch') : ($status == 1 ? $langs->trans('ProductStatusOnBatch') : $langs->trans('ProductStatusOnSerial'))); return dolGetStatus($label); case 1: - $label = ($status == 0 ? $langs->trans('ProductStatusNotOnBatchShort') : $langs->trans('ProductStatusOnBatchShort')); + $label = ($status == 0 ? $langs->trans('ProductStatusNotOnBatchShort') : ($status == 1 ? $langs->trans('ProductStatusOnBatchShort') : $langs->trans('ProductStatusOnSerialShort'))); return dolGetStatus($label); case 2: return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 1, 2); @@ -4729,12 +4805,14 @@ class Product extends CommonObject $labelStatus = $langs->trans('ProductStatusOnBuyShort'); $labelStatusShort = $langs->trans('ProductStatusOnBuy'); } elseif ($type == 2) { - $labelStatus = $langs->trans('ProductStatusOnBatch'); - $labelStatusShort = $langs->trans('ProductStatusOnBatchShort'); + $labelStatus = ($status == 1 ? $langs->trans('ProductStatusOnBatch') : $langs->trans('ProductStatusOnSerial')); + $labelStatusShort = ($status == 1 ? $langs->trans('ProductStatusOnBatchShort') : $langs->trans('ProductStatusOnSerialShort')); } + } elseif ( $type == 2 && $status == 2 ) { + $labelStatus = $langs->trans('ProductStatusOnSerial'); + $labelStatusShort = $langs->trans('ProductStatusOnSerialShort'); } - if ($mode > 6) { return dolGetStatus($langs->trans('Unknown'), '', '', 'status0', 0); } else { @@ -4911,8 +4989,7 @@ class Product extends CommonObject $num = $this->db->num_rows($result); $i = 0; if ($num > 0) { - while ($i < $num) - { + while ($i < $num) { $row = $this->db->fetch_object($result); $this->stock_warehouse[$row->fk_entrepot] = new stdClass(); $this->stock_warehouse[$row->fk_entrepot]->real = $row->reel; @@ -4960,14 +5037,14 @@ class Product extends CommonObject //dol_syslog("load_virtual_stock"); - if (!empty($conf->commande->enabled)) - { + if (!empty($conf->commande->enabled)) { $result = $this->load_stats_commande(0, '1,2', 1); - if ($result < 0) dol_print_error($this->db, $this->error); + if ($result < 0) { + dol_print_error($this->db, $this->error); + } $stock_commande_client = $this->stats_commande['qty']; } - if (!empty($conf->expedition->enabled)) - { + if (!empty($conf->expedition->enabled)) { require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; $filterShipmentStatus = ''; if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) { @@ -4976,37 +5053,49 @@ class Product extends CommonObject $filterShipmentStatus = Expedition::STATUS_CLOSED; } $result = $this->load_stats_sending(0, '1,2', 1, $filterShipmentStatus); - if ($result < 0) dol_print_error($this->db, $this->error); + if ($result < 0) { + dol_print_error($this->db, $this->error); + } $stock_sending_client = $this->stats_expedition['qty']; } - if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) - { + if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) { $filterStatus = '1,2,3,4'; - if (isset($includedraftpoforvirtual)) $filterStatus = '0,'.$filterStatus; + if (isset($includedraftpoforvirtual)) { + $filterStatus = '0,'.$filterStatus; + } $result = $this->load_stats_commande_fournisseur(0, $filterStatus, 1); - if ($result < 0) dol_print_error($this->db, $this->error); + if ($result < 0) { + dol_print_error($this->db, $this->error); + } $stock_commande_fournisseur = $this->stats_commande_fournisseur['qty']; } - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && empty($conf->reception->enabled)) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && empty($conf->reception->enabled)) { $filterStatus = '4'; - if (isset($includedraftpoforvirtual)) $filterStatus = '0,'.$filterStatus; + if (isset($includedraftpoforvirtual)) { + $filterStatus = '0,'.$filterStatus; + } $result = $this->load_stats_reception(0, $filterStatus, 1); - if ($result < 0) dol_print_error($this->db, $this->error); + if ($result < 0) { + dol_print_error($this->db, $this->error); + } $stock_reception_fournisseur = $this->stats_reception['qty']; } - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && empty($conf->reception->enabled)) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && empty($conf->reception->enabled)) { $filterStatus = '4'; - if (isset($includedraftpoforvirtual)) $filterStatus = '0,'.$filterStatus; + if (isset($includedraftpoforvirtual)) { + $filterStatus = '0,'.$filterStatus; + } $result = $this->load_stats_reception(0, $filterStatus, 1); // Use same tables than when module reception is not used. - if ($result < 0) dol_print_error($this->db, $this->error); + if ($result < 0) { + dol_print_error($this->db, $this->error); + } $stock_reception_fournisseur = $this->stats_reception['qty']; } - if (!empty($conf->mrp->enabled)) - { + if (!empty($conf->mrp->enabled)) { $result = $this->load_stats_inproduction(0, '1,2', 1); - if ($result < 0) dol_print_error($this->db, $this->error); + if ($result < 0) { + dol_print_error($this->db, $this->error); + } $stock_inproduction = $this->stats_mrptoproduce['qty'] - $this->stats_mrptoconsume['qty']; } @@ -5039,7 +5128,9 @@ class Product extends CommonObject $parameters = array('id'=>$this->id, 'includedraftpoforvirtual' => $includedraftpoforvirtual); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action); - if ($reshook > 0) $this->stock_theorique = $hookmanager->resArray['stock_theorique']; + if ($reshook > 0) { + $this->stock_theorique = $hookmanager->resArray['stock_theorique']; + } return 1; } @@ -5064,8 +5155,7 @@ class Product extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $result[] = array('batch'=>$batch, 'eatby'=>$this->db->jdate($obj->eatby), 'sellby'=>$this->db->jdate($obj->sellby), 'qty'=>$obj->qty); $i++; @@ -5153,8 +5243,7 @@ class Product extends CommonObject if (file_exists($dir_osencoded)) { $handle = opendir($dir_osencoded); if (is_resource($handle)) { - while (($file = readdir($handle)) !== false) - { + while (($file = readdir($handle)) !== false) { if (!utf8_check($file)) { $file = utf8_encode($file); // To be sure data is stored in UTF8 in memory } @@ -5187,9 +5276,9 @@ class Product extends CommonObject $dir_osencoded = dol_osencode($dir); $handle = @opendir($dir_osencoded); if (is_resource($handle)) { - while (($file = readdir($handle)) !== false) - { - if (!utf8_check($file)) { $file = utf8_encode($file); // readdir returns ISO + while (($file = readdir($handle)) !== false) { + if (!utf8_check($file)) { + $file = utf8_encode($file); // readdir returns ISO } if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) { $nbphoto++; @@ -5206,14 +5295,17 @@ class Product extends CommonObject // Objet $obj = array(); $obj['photo'] = $photo; - if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) { $obj['photo_vignette'] = 'thumbs/'.$photo_vignette; - } else { $obj['photo_vignette'] = ""; + if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) { + $obj['photo_vignette'] = 'thumbs/'.$photo_vignette; + } else { + $obj['photo_vignette'] = ""; } $tabobj[$nbphoto - 1] = $obj; // On continue ou on arrete de boucler ? - if ($nbmax && $nbphoto >= $nbmax) { break; + if ($nbmax && $nbphoto >= $nbmax) { + break; } } } @@ -5300,10 +5392,11 @@ class Product extends CommonObject $resql = $this->db->query($sql); if ($resql) { - while ($obj = $this->db->fetch_object($resql)) - { - if ($obj->fk_product_type == 1) { $this->nb["services"] = $obj->nb; - } else { $this->nb["products"] = $obj->nb; + while ($obj = $this->db->fetch_object($resql)) { + if ($obj->fk_product_type == 1) { + $this->nb["services"] = $obj->nb; + } else { + $this->nb["products"] = $obj->nb; } } $this->db->free($resql); @@ -5352,10 +5445,10 @@ class Product extends CommonObject $result = ''; if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) { $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']); - foreach ($dirsociete as $dirroot) - { + foreach ($dirsociete as $dirroot) { $res = dol_include_once($dirroot.$conf->global->BARCODE_PRODUCT_ADDON_NUM.'.php'); - if ($res) { break; + if ($res) { + break; } } $var = $conf->global->BARCODE_PRODUCT_ADDON_NUM; @@ -5456,7 +5549,7 @@ class Product extends CommonObject */ public function hasbatch() { - return ($this->status_batch == 1 ? true : false); + return ($this->status_batch > 0 ? true : false); } @@ -5479,8 +5572,7 @@ class Product extends CommonObject $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->id, '', ''); if (is_array($product_fourn_list) && count($product_fourn_list) > 0) { - foreach ($product_fourn_list as $productfourn) - { + foreach ($product_fourn_list as $productfourn) { if ($productfourn->fourn_unitprice > $maxpricesupplier) { $maxpricesupplier = $productfourn->fourn_unitprice; } @@ -5618,7 +5710,7 @@ class Product extends CommonObject $sql = "SELECT p.rowid, p.ref, p.datec as date_creation, p.tms as date_modification,"; $sql .= " p.fk_user_author, p.fk_user_modif"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p"; - $sql .= " WHERE p.rowid = ".$id; + $sql .= " WHERE p.rowid = ".((int) $id); $result = $this->db->query($sql); if ($result) { diff --git a/htdocs/product/class/productbatch.class.php b/htdocs/product/class/productbatch.class.php index a97437f6a45..10704f2f53e 100644 --- a/htdocs/product/class/productbatch.class.php +++ b/htdocs/product/class/productbatch.class.php @@ -107,15 +107,15 @@ class Productbatch extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (!$error) - { + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.self::$_table_element); } // Commit or rollback - if ($error) - { + if ($error) { $this->db->rollback(); return -1 * $error; } else { @@ -151,14 +151,12 @@ class Productbatch extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."product_batch as t INNER JOIN ".MAIN_DB_PREFIX."product_stock w on t.fk_product_stock = w.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl on pl.fk_product = w.fk_product and pl.batch = t.batch"; - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".((int) $id); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -197,8 +195,7 @@ class Productbatch extends CommonObject $this->cleanParam(); // TODO Check qty is ok for stock move. Negative may not be allowed. - if ($this->qty < 0) - { + if ($this->qty < 0) { } // Update request @@ -209,19 +206,19 @@ class Productbatch extends CommonObject $sql .= " batch=".(isset($this->batch) ? "'".$this->db->escape($this->batch)."'" : "null").","; $sql .= " qty=".(isset($this->qty) ? $this->qty : "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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -247,21 +244,20 @@ class Productbatch extends CommonObject $this->db->begin(); - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.self::$_table_element.""; - $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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -288,7 +284,7 @@ class Productbatch extends CommonObject $object = new Productbatch($this->db); - $this->db->begin(); + $this->db->begin(); // Load source object $object->fetch($fromid); @@ -303,22 +299,19 @@ class Productbatch extends CommonObject $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $this->errors = array_merge($this->errors, $object->errors); $error++; } - if (!$error) - { + if (!$error) { } unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { @@ -353,10 +346,18 @@ class Productbatch extends CommonObject */ private function cleanParam() { - if (isset($this->fk_product_stock)) $this->fk_product_stock = (int) trim($this->fk_product_stock); - if (isset($this->batch)) $this->batch = trim($this->batch); - if (isset($this->qty)) $this->qty = (float) trim($this->qty); - if (isset($this->import_key)) $this->import_key = trim($this->import_key); + if (isset($this->fk_product_stock)) { + $this->fk_product_stock = (int) trim($this->fk_product_stock); + } + if (isset($this->batch)) { + $this->batch = trim($this->batch); + } + if (isset($this->qty)) { + $this->qty = (float) trim($this->qty); + } + if (isset($this->import_key)) { + $this->import_key = trim($this->import_key); + } } /** @@ -385,19 +386,25 @@ class Productbatch extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX.self::$_table_element." as t"; $sql .= " WHERE fk_product_stock=".$fk_product_stock; - if (!empty($eatby)) array_push($where, " eatby = '".$this->db->idate($eatby)."'"); // deprecated - if (!empty($sellby)) array_push($where, " sellby = '".$this->db->idate($sellby)."'"); // deprecated + if (!empty($eatby)) { + array_push($where, " eatby = '".$this->db->idate($eatby)."'"); // deprecated + } + if (!empty($sellby)) { + array_push($where, " sellby = '".$this->db->idate($sellby)."'"); // deprecated + } - if (!empty($batch_number)) $sql .= " AND batch = '".$this->db->escape($batch_number)."'"; + if (!empty($batch_number)) { + $sql .= " AND batch = '".$this->db->escape($batch_number)."'"; + } - if (!empty($where)) $sql .= " AND (".implode(" OR ", $where).")"; + if (!empty($where)) { + $sql .= " AND (".implode(" OR ", $where).")"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -414,7 +421,7 @@ class Productbatch extends CommonObject return 1; } else { - $this->error = "Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -441,27 +448,26 @@ class Productbatch extends CommonObject $sql .= " t.batch,"; $sql .= " t.qty,"; $sql .= " t.import_key"; - if ($fk_product > 0) - { + if ($fk_product > 0) { $sql .= ", pl.rowid as lotid, pl.eatby as eatby, pl.sellby as sellby"; // TODO May add extrafields to ? } $sql .= " FROM ".MAIN_DB_PREFIX."product_batch as t"; - if ($fk_product > 0) - { + if ($fk_product > 0) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON pl.fk_product = ".$fk_product." AND pl.batch = t.batch"; // TODO May add extrafields to ? } $sql .= " WHERE fk_product_stock=".$fk_product_stock; - if ($with_qty) $sql .= " AND t.qty <> 0"; + if ($with_qty) { + $sql .= " AND t.qty <> 0"; + } dol_syslog("productbatch::findAll", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $tmp = new Productbatch($db); diff --git a/htdocs/product/class/productcustomerprice.class.php b/htdocs/product/class/productcustomerprice.class.php index af767c98cd6..046aed05a10 100644 --- a/htdocs/product/class/productcustomerprice.class.php +++ b/htdocs/product/class/productcustomerprice.class.php @@ -107,36 +107,51 @@ class Productcustomerprice extends CommonObject // Clean parameters - if (isset($this->entity)) + if (isset($this->entity)) { $this->entity = trim($this->entity); - if (isset($this->fk_product)) + } + if (isset($this->fk_product)) { $this->fk_product = trim($this->fk_product); - if (isset($this->fk_soc)) + } + if (isset($this->fk_soc)) { $this->fk_soc = trim($this->fk_soc); - if (isset($this->ref_customer)) + } + if (isset($this->ref_customer)) { $this->ref_customer = trim($this->ref_customer); - if (isset($this->price)) + } + if (isset($this->price)) { $this->price = trim($this->price); - if (isset($this->price_ttc)) + } + if (isset($this->price_ttc)) { $this->price_ttc = trim($this->price_ttc); - if (isset($this->price_min)) + } + if (isset($this->price_min)) { $this->price_min = trim($this->price_min); - if (isset($this->price_min_ttc)) + } + if (isset($this->price_min_ttc)) { $this->price_min_ttc = trim($this->price_min_ttc); - if (isset($this->price_base_type)) + } + if (isset($this->price_base_type)) { $this->price_base_type = trim($this->price_base_type); - if (isset($this->tva_tx)) + } + if (isset($this->tva_tx)) { $this->tva_tx = trim($this->tva_tx); - if (isset($this->recuperableonly)) + } + if (isset($this->recuperableonly)) { $this->recuperableonly = trim($this->recuperableonly); - if (isset($this->localtax1_tx)) + } + if (isset($this->localtax1_tx)) { $this->localtax1_tx = trim($this->localtax1_tx); - if (isset($this->localtax2_tx)) + } + if (isset($this->localtax2_tx)) { $this->localtax2_tx = trim($this->localtax2_tx); - if (isset($this->fk_user)) + } + if (isset($this->fk_user)) { $this->fk_user = trim($this->fk_user); - if (isset($this->import_key)) + } + if (isset($this->import_key)) { $this->import_key = trim($this->import_key); + } // Check parameters // Put here code to add control on parameters values @@ -259,8 +274,8 @@ class Productcustomerprice extends CommonObject /** * Load object in memory from the database * - * @param int $id object - * @return int <0 if KO, >0 if OK + * @param int $id ID of customer price + * @return int <0 if KO, 0 if not found, >0 if OK */ public function fetch($id) { @@ -286,9 +301,8 @@ class Productcustomerprice extends CommonObject $sql .= " t.localtax2_tx,"; $sql .= " t.fk_user,"; $sql .= " t.import_key"; - $sql .= " FROM ".MAIN_DB_PREFIX."product_customer_price 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); @@ -316,10 +330,15 @@ class Productcustomerprice extends CommonObject $this->localtax2_tx = $obj->localtax2_tx; $this->fk_user = $obj->fk_user; $this->import_key = $obj->import_key; - } - $this->db->free($resql); - return 1; + $this->db->free($resql); + + return 1; + } else { + $this->db->free($resql); + + return 0; + } } else { $this->error = "Error ".$this->db->lasterror(); return -1; @@ -342,8 +361,12 @@ class Productcustomerprice extends CommonObject // phpcs:enable global $langs; - if (empty($sortfield)) $sortfield = "t.rowid"; - if (empty($sortorder)) $sortorder = "DESC"; + if (empty($sortfield)) { + $sortfield = "t.rowid"; + } + if (empty($sortorder)) { + $sortorder = "DESC"; + } $sql = "SELECT"; $sql .= " t.rowid,"; @@ -394,7 +417,9 @@ class Productcustomerprice extends CommonObject } } $sql .= $this->db->order($sortfield, $sortorder); - if (!empty($limit)) $sql .= ' '.$this->db->plimit($limit + 1, $offset); + if (!empty($limit)) { + $sql .= ' '.$this->db->plimit($limit + 1, $offset); + } dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); $resql = $this->db->query($sql); @@ -430,7 +455,7 @@ class Productcustomerprice extends CommonObject $line->socname = $obj->socname; $line->prodref = $obj->prodref; - $this->lines [] = $line; + $this->lines[] = $line; } $this->db->free($resql); @@ -457,12 +482,15 @@ class Productcustomerprice extends CommonObject // phpcs:enable global $langs; - if (!empty($sortfield)) $sortfield = "t.rowid"; - if (!empty($sortorder)) $sortorder = "DESC"; + if (!empty($sortfield)) { + $sortfield = "t.rowid"; + } + if (!empty($sortorder)) { + $sortorder = "DESC"; + } $sql = "SELECT"; $sql .= " t.rowid,"; - $sql .= " t.entity,"; $sql .= " t.datec,"; $sql .= " t.fk_product,"; @@ -482,30 +510,29 @@ class Productcustomerprice extends CommonObject $sql .= " t.import_key,"; $sql .= " soc.nom as socname,"; $sql .= " prod.ref as prodref"; - $sql .= " FROM ".MAIN_DB_PREFIX."product_customer_price_log as t "; - $sql .= " ,".MAIN_DB_PREFIX."product as prod "; - $sql .= " ,".MAIN_DB_PREFIX."societe as soc "; - $sql .= " WHERE soc.rowid=t.fk_soc "; + $sql .= " FROM ".MAIN_DB_PREFIX."product_customer_price_log as t"; + $sql .= " ,".MAIN_DB_PREFIX."product as prod"; + $sql .= " ,".MAIN_DB_PREFIX."societe as soc"; + $sql .= " WHERE soc.rowid=t.fk_soc"; $sql .= " AND prod.rowid=t.fk_product "; $sql .= " AND prod.entity IN (".getEntity('product').")"; $sql .= " AND t.entity IN (".getEntity('productprice').")"; - // Manage filter if (count($filter) > 0) { foreach ($filter as $key => $value) { - if (strpos($key, 'date')) // To allow $filter['YEAR(s.dated)']=>$year - { + if (strpos($key, 'date')) { // To allow $filter['YEAR(s.dated)']=>$year $sql .= ' AND '.$key.' = \''.$value.'\''; } elseif ($key == 'soc.nom') { - $sql .= ' AND '.$key.' LIKE \'%'.$value.'%\''; + $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\''; } else { - $sql .= ' AND '.$key.' = '.$value; + $sql .= ' AND '.$key.' = '.((int) $value); } } } - $sql .= $this->db->order($sortfield, $sortorder); - if (!empty($limit)) $sql .= ' '.$this->db->plimit($limit + 1, $offset); + if (!empty($limit)) { + $sql .= ' '.$this->db->plimit($limit + 1, $offset); + } dol_syslog(get_class($this)."::fetch_all_log", LOG_DEBUG); $resql = $this->db->query($sql); @@ -566,36 +593,51 @@ class Productcustomerprice extends CommonObject // Clean parameters - if (isset($this->entity)) + if (isset($this->entity)) { $this->entity = trim($this->entity); - if (isset($this->fk_product)) + } + if (isset($this->fk_product)) { $this->fk_product = trim($this->fk_product); - if (isset($this->fk_soc)) + } + if (isset($this->fk_soc)) { $this->fk_soc = trim($this->fk_soc); - if (isset($this->ref_customer)) + } + if (isset($this->ref_customer)) { $this->ref_customer = trim($this->ref_customer); - if (isset($this->price)) + } + if (isset($this->price)) { $this->price = trim($this->price); - if (isset($this->price_ttc)) + } + if (isset($this->price_ttc)) { $this->price_ttc = trim($this->price_ttc); - if (isset($this->price_min)) + } + if (isset($this->price_min)) { $this->price_min = trim($this->price_min); - if (isset($this->price_min_ttc)) + } + if (isset($this->price_min_ttc)) { $this->price_min_ttc = trim($this->price_min_ttc); - if (isset($this->price_base_type)) + } + if (isset($this->price_base_type)) { $this->price_base_type = trim($this->price_base_type); - if (isset($this->tva_tx)) + } + if (isset($this->tva_tx)) { $this->tva_tx = trim($this->tva_tx); - if (isset($this->recuperableonly)) + } + if (isset($this->recuperableonly)) { $this->recuperableonly = trim($this->recuperableonly); - if (isset($this->localtax1_tx)) + } + if (isset($this->localtax1_tx)) { $this->localtax1_tx = trim($this->localtax1_tx); - if (isset($this->localtax2_tx)) + } + if (isset($this->localtax2_tx)) { $this->localtax2_tx = trim($this->localtax2_tx); - if (isset($this->fk_user)) + } + if (isset($this->fk_user)) { $this->fk_user = trim($this->fk_user); - if (isset($this->import_key)) + } + if (isset($this->import_key)) { $this->import_key = trim($this->import_key); + } // Check parameters // Put here code to add a control on parameters values @@ -713,7 +755,7 @@ class Productcustomerprice extends CommonObject $sql .= " fk_user=".$user->id.","; $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); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); @@ -722,11 +764,12 @@ class Productcustomerprice extends CommonObject $this->errors [] = "Error ".$this->db->lasterror(); } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('PRODUCT_CUSTOMER_PRICE_UPDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -855,7 +898,6 @@ class Productcustomerprice extends CommonObject */ public function delete($user, $notrigger = 0) { - global $conf, $langs; $error = 0; @@ -870,7 +912,7 @@ class Productcustomerprice extends CommonObject if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_customer_price"; - $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/product/class/propalmergepdfproduct.class.php b/htdocs/product/class/propalmergepdfproduct.class.php index c917201b645..f7cf48df5e0 100644 --- a/htdocs/product/class/propalmergepdfproduct.class.php +++ b/htdocs/product/class/propalmergepdfproduct.class.php @@ -79,12 +79,24 @@ class Propalmergepdfproduct extends CommonObject // Clean parameters - if (isset($this->fk_product)) $this->fk_product = trim($this->fk_product); - if (isset($this->file_name)) $this->file_name = trim($this->file_name); - if (isset($this->fk_user_author)) $this->fk_user_author = trim($this->fk_user_author); - if (isset($this->fk_user_mod)) $this->fk_user_mod = trim($this->fk_user_mod); - if (isset($this->lang)) $this->lang = trim($this->lang); - if (isset($this->import_key)) $this->import_key = trim($this->import_key); + if (isset($this->fk_product)) { + $this->fk_product = trim($this->fk_product); + } + if (isset($this->file_name)) { + $this->file_name = trim($this->file_name); + } + if (isset($this->fk_user_author)) { + $this->fk_user_author = trim($this->fk_user_author); + } + if (isset($this->fk_user_mod)) { + $this->fk_user_mod = trim($this->fk_user_mod); + } + if (isset($this->lang)) { + $this->lang = trim($this->lang); + } + if (isset($this->import_key)) { + $this->import_key = trim($this->import_key); + } @@ -120,20 +132,19 @@ class Propalmergepdfproduct extends CommonObject $this->db->begin(); - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal_merge_pdf_product"); } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -170,14 +181,12 @@ class Propalmergepdfproduct extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product as t"; - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".((int) $id); dol_syslog(__METHOD__, LOG_DEBUG); $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; @@ -197,7 +206,7 @@ class Propalmergepdfproduct extends CommonObject return 1; } else { - $this->error = "Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } @@ -237,10 +246,8 @@ class Propalmergepdfproduct extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { while ($obj = $this->db->fetch_object($resql)) { $line = new PropalmergepdfproductLine(); @@ -290,10 +297,18 @@ class Propalmergepdfproduct extends CommonObject // Clean parameters - if (isset($this->fk_product)) $this->fk_product = trim($this->fk_product); - if (isset($this->file_name)) $this->file_name = trim($this->file_name); - if (isset($this->fk_user_mod)) $this->fk_user_mod = trim($this->fk_user_mod); - if (isset($this->lang)) $this->lang = trim($this->lang); + if (isset($this->fk_product)) { + $this->fk_product = trim($this->fk_product); + } + if (isset($this->file_name)) { + $this->file_name = trim($this->file_name); + } + if (isset($this->fk_user_mod)) { + $this->fk_user_mod = trim($this->fk_user_mod); + } + if (isset($this->lang)) { + $this->lang = trim($this->lang); + } // Check parameters // Put here code to add a control on parameters values @@ -309,19 +324,19 @@ class Propalmergepdfproduct extends CommonObject $sql .= " fk_user_mod=".$user->id; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -334,13 +349,13 @@ class Propalmergepdfproduct extends CommonObject } - /** - * Delete object in database - * - * @param User $user User that deletes - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + /** + * Delete object in database + * + * @param User $user User that deletes + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function delete($user, $notrigger = 0) { global $conf, $langs; @@ -348,21 +363,20 @@ class Propalmergepdfproduct extends CommonObject $this->db->begin(); - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -392,8 +406,7 @@ class Propalmergepdfproduct extends CommonObject $this->db->begin(); - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product"; $sql .= " WHERE fk_product=".$product_id; @@ -403,14 +416,14 @@ class Propalmergepdfproduct extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -437,21 +450,20 @@ class Propalmergepdfproduct extends CommonObject $this->db->begin(); - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product"; $sql .= " WHERE fk_product=".$this->fk_product." AND file_name='".$this->db->escape($this->file_name)."'"; dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -493,22 +505,19 @@ class Propalmergepdfproduct extends CommonObject $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $this->errors = array_merge($this->errors, $object->errors); $error++; } - if (!$error) - { + if (!$error) { } unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { diff --git a/htdocs/product/composition/card.php b/htdocs/product/composition/card.php index 620bd69f60a..9a1fa1adf69 100644 --- a/htdocs/product/composition/card.php +++ b/htdocs/product/composition/card.php @@ -45,15 +45,16 @@ $key = GETPOST('key'); $parent = GETPOST('parent'); // Security check -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $object = new Product($db); $objectid = 0; -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref); $objectid = $object->id; $id = $object->id; @@ -64,21 +65,19 @@ if ($id > 0 || !empty($ref)) * Actions */ -if ($cancel) $action = ''; +if ($cancel) { + $action = ''; +} // Add subproduct to product -if ($action == 'add_prod' && ($user->rights->produit->creer || $user->rights->service->creer)) -{ +if ($action == 'add_prod' && ($user->rights->produit->creer || $user->rights->service->creer)) { $error = 0; $maxprod = GETPOST("max_prod", 'int'); - for ($i = 0; $i < $maxprod; $i++) - { + for ($i = 0; $i < $maxprod; $i++) { $qty = price2num(GETPOST("prod_qty_".$i, 'alpha'), 'MS'); - if ($qty > 0) - { - if ($object->add_sousproduit($id, GETPOST("prod_id_".$i, 'int'), $qty, GETPOST("prod_incdec_".$i, 'int')) > 0) - { + if ($qty > 0) { + if ($object->add_sousproduit($id, GETPOST("prod_id_".$i, 'int'), $qty, GETPOST("prod_incdec_".$i, 'int')) > 0) { //var_dump($i.' '.GETPOST("prod_id_".$i, 'int'), $qty, GETPOST("prod_incdec_".$i, 'int')); $action = 'edit'; } else { @@ -91,8 +90,7 @@ if ($action == 'add_prod' && ($user->rights->produit->creer || $user->rights->se } } } else { - if ($object->del_sousproduit($id, GETPOST("prod_id_".$i, 'int')) > 0) - { + if ($object->del_sousproduit($id, GETPOST("prod_id_".$i, 'int')) > 0) { $action = 'edit'; } else { $error++; @@ -102,20 +100,19 @@ if ($action == 'add_prod' && ($user->rights->produit->creer || $user->rights->se } } - if (!$error) - { + if (!$error) { header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } -} elseif ($action === 'save_composed_product') -{ +} elseif ($action === 'save_composed_product') { $TProduct = GETPOST('TProduct', 'array'); - if (!empty($TProduct)) - { - foreach ($TProduct as $id_product => $row) - { - if ($row['qty'] > 0) $object->update_sousproduit($id, $id_product, $row['qty'], isset($row['incdec']) ? 1 : 0); - else $object->del_sousproduit($id, $id_product); + if (!empty($TProduct)) { + foreach ($TProduct as $id_product => $row) { + if ($row['qty'] > 0) { + $object->update_sousproduit($id, $id_product, $row['qty'], isset($row['incdec']) ? 1 : 0); + } else { + $object->del_sousproduit($id, $id_product); + } } setEventMessages('RecordSaved', null); } @@ -132,17 +129,20 @@ $productstatic = new Product($db); $form = new Form($db); // action recherche des produits par mot-cle et/ou par categorie -if ($action == 'search') -{ +if ($action == 'search') { $current_lang = $langs->getDefaultLang(); $sql = 'SELECT DISTINCT p.rowid, p.ref, p.label, p.fk_product_type as type, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,'; $sql .= ' p.fk_product_type, p.tms as datem, p.tobatch'; $sql .= ', p.tosell as status, p.tobuy as status_buy'; - if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= ', pl.label as labelm, pl.description as descriptionm'; + if (!empty($conf->global->MAIN_MULTILANGS)) { + $sql .= ', pl.label as labelm, pl.description as descriptionm'; + } $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON p.rowid = cp.fk_product'; - if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND lang='".($current_lang)."'"; + if (!empty($conf->global->MAIN_MULTILANGS)) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND lang='".($current_lang)."'"; + } $sql .= ' WHERE p.entity IN ('.getEntity('product').')'; if ($key != "") { // For natural search @@ -186,41 +186,37 @@ $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); print dol_get_fiche_head($head, 'subproduct', $titre, -1, $picto); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { /* * Fiche en mode edition */ - if ($user->rights->produit->lire || $user->rights->service->lire) - { + if ($user->rights->produit->lire || $user->rights->service->lire) { $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', '', '', '', 0, '', '', 0); - if ($object->type != Product::TYPE_SERVICE || !empty($conf->global->STOCK_SUPPORTS_SERVICES) || empty($conf->global->PRODUIT_MULTIPRICES)) - { + if ($object->type != Product::TYPE_SERVICE || !empty($conf->global->STOCK_SUPPORTS_SERVICES) || empty($conf->global->PRODUIT_MULTIPRICES)) { print '<div class="fichecenter">'; print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent tableforfield">'; // Nature - if ($object->type != Product::TYPE_SERVICE) - { - print '<tr><td class="titlefield">'.$langs->trans("Nature").'</td><td>'; + if ($object->type != Product::TYPE_SERVICE) { + print '<tr><td class="titlefieldcreate">'.$langs->trans("Nature").'</td><td>'; print $object->getLibFinished(); print '</td></tr>'; } - if (empty($conf->global->PRODUIT_MULTIPRICES)) - { + if (empty($conf->global->PRODUIT_MULTIPRICES)) { // Price - print '<tr><td class="titlefield">'.$langs->trans("SellingPrice").'</td><td>'; - if ($object->price_base_type == 'TTC') - { + print '<tr><td class="titlefieldcreate">'.$langs->trans("SellingPrice").'</td><td>'; + if ($object->price_base_type == 'TTC') { print price($object->price_ttc).' '.$langs->trans($object->price_base_type); } else { print price($object->price).' '.$langs->trans($object->price_base_type ? $object->price_base_type : 'HT'); @@ -229,8 +225,7 @@ if ($id > 0 || !empty($ref)) // Price minimum print '<tr><td>'.$langs->trans("MinPrice").'</td><td>'; - if ($object->price_base_type == 'TTC') - { + if ($object->price_base_type == 'TTC') { print price($object->price_min_ttc).' '.$langs->trans($object->price_base_type); } else { print price($object->price_min).' '.$langs->trans($object->price_base_type ? $object->price_base_type : 'HT'); @@ -310,7 +305,9 @@ if ($id > 0 || !empty($ref)) print '<td>'.$langs->trans('Label').'</td>'; print '<td class="right" colspan="2">'.$langs->trans('MinSupplierPrice').'</td>'; print '<td class="right" colspan="2">'.$langs->trans('MinCustomerPrice').'</td>'; - if (!empty($conf->stock->enabled)) print '<td class="right">'.$langs->trans('Stock').'</td>'; + if (!empty($conf->stock->enabled)) { + print '<td class="right">'.$langs->trans('Stock').'</td>'; + } print '<td class="center">'.$langs->trans('Qty').'</td>'; print '<td class="center">'.$langs->trans('ComposedProductIncDecStock').'</td>'; print '</tr>'."\n"; @@ -331,11 +328,13 @@ if ($id > 0 || !empty($ref)) // Best buying price print '<td class="right">'; - if ($product_fourn->find_min_price_product_fournisseur($productstatic->id) > 0) - { + if ($product_fourn->find_min_price_product_fournisseur($productstatic->id) > 0) { print $langs->trans("BuyingPriceMinShort").': '; - if ($product_fourn->product_fourn_price_id > 0) print $product_fourn->display_price_product_fournisseur(0, 0); - else { print $langs->trans("NotDefined"); $notdefined++; $atleastonenotdefined++; } + if ($product_fourn->product_fourn_price_id > 0) { + print $product_fourn->display_price_product_fournisseur(0, 0); + } else { + print $langs->trans("NotDefined"); $notdefined++; $atleastonenotdefined++; + } } print '</td>'; @@ -354,8 +353,7 @@ if ($id > 0 || !empty($ref)) // Best selling price $pricesell = $productstatic->price; - if (!empty($conf->global->PRODUIT_MULTIPRICES)) - { + if (!empty($conf->global->PRODUIT_MULTIPRICES)) { $pricesell = 'Variable'; } else { $totallinesell = price2num($value['nb'] * ($pricesell), 'MT'); @@ -363,16 +361,20 @@ if ($id > 0 || !empty($ref)) } print '<td class="right" colspan="2">'; print ($notdefined ? '' : ($value['nb'] > 1 ? $value['nb'].'x' : '')); - if (is_numeric($pricesell)) print price($pricesell, '', '', 0, 0, -1, $conf->currency); - else print $langs->trans($pricesell); + if (is_numeric($pricesell)) { + print price($pricesell, '', '', 0, 0, -1, $conf->currency); + } else { + print $langs->trans($pricesell); + } print '</td>'; // Stock - if (!empty($conf->stock->enabled)) print '<td class="right">'.$value['stock'].'</td>'; // Real stock + if (!empty($conf->stock->enabled)) { + print '<td class="right">'.$value['stock'].'</td>'; // Real stock + } // Qty + IncDec - if ($user->rights->produit->creer || $user->rights->service->creer) - { + if ($user->rights->produit->creer || $user->rights->service->creer) { print '<td class="center"><input type="text" value="'.$nb_of_subproduct.'" name="TProduct['.$productstatic->id.'][qty]" size="4" class="right" /></td>'; print '<td class="center"><input type="checkbox" name="TProduct['.$productstatic->id.'][incdec]" value="1" '.($value['incdec'] == 1 ? 'checked' : '').' /></td>'; } else { @@ -383,14 +385,18 @@ if ($id > 0 || !empty($ref)) print '</tr>'."\n"; } else { $hide = ''; - if (empty($conf->global->PRODUCT_SHOW_SUB_SUB_PRODUCTS)) $hide = ' hideobject'; // By default, we do not show this. It makes screen very difficult to understand + if (empty($conf->global->PRODUCT_SHOW_SUB_SUB_PRODUCTS)) { + $hide = ' hideobject'; // By default, we do not show this. It makes screen very difficult to understand + } print '<tr class="oddeven'.$hide.'" id="sub-'.$value['id_parent'].'">'; //$productstatic->ref=$value['label']; $productstatic->ref = $value['ref']; print '<td>'; - for ($i = 0; $i < $value['level']; $i++) print ' &nbsp; &nbsp; '; // Add indentation + for ($i = 0; $i < $value['level']; $i++) { + print ' &nbsp; &nbsp; '; // Add indentation + } print $productstatic->getNomUrl(1, 'composition').'</td>'; print '<td>'.$productstatic->label.'</td>'; @@ -401,7 +407,9 @@ if ($id > 0 || !empty($ref)) print '<td>&nbsp;</td>'; print '<td>&nbsp;</td>'; - if (!empty($conf->stock->enabled)) print '<td></td>'; // Real stock + if (!empty($conf->stock->enabled)) { + print '<td></td>'; // Real stock + } print '<td class="center">'.$value['nb'].'</td>'; print '<td>&nbsp;</td>'; @@ -419,7 +427,9 @@ if ($id > 0 || !empty($ref)) print '</td>'; print '<td class="liste_total right">'; - if ($atleastonenotdefined) print $langs->trans("Unknown").' ('.$langs->trans("SomeSubProductHaveNoPrices").')'; + if ($atleastonenotdefined) { + print $langs->trans("Unknown").' ('.$langs->trans("SomeSubProductHaveNoPrices").')'; + } print ($atleastonenotdefined ? '' : price($total, '', '', 0, 0, -1, $conf->currency)); print '</td>'; @@ -429,23 +439,28 @@ if ($id > 0 || !empty($ref)) print '</td>'; print '<td class="liste_total right">'; - if ($atleastonenotdefined) print $langs->trans("Unknown").' ('.$langs->trans("SomeSubProductHaveNoPrices").')'; + if ($atleastonenotdefined) { + print $langs->trans("Unknown").' ('.$langs->trans("SomeSubProductHaveNoPrices").')'; + } print ($atleastonenotdefined ? '' : price($totalsell, '', '', 0, 0, -1, $conf->currency)); print '</td>'; // Stock - if (!empty($conf->stock->enabled)) print '<td class="liste_total right">&nbsp;</td>'; + if (!empty($conf->stock->enabled)) { + print '<td class="liste_total right">&nbsp;</td>'; + } print '<td class="right" colspan="2">'; - if ($user->rights->produit->creer || $user->rights->service->creer) - { + if ($user->rights->produit->creer || $user->rights->service->creer) { print '<input type="submit" class="button button-save" value="'.$langs->trans("Save").'">'; } print '</td>'; print '</tr>'."\n"; } else { $colspan = 8; - if (!empty($conf->stock->enabled)) $colspan++; + if (!empty($conf->stock->enabled)) { + $colspan++; + } print '<tr class="oddeven">'; print '<td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("None").'</td>'; @@ -464,12 +479,13 @@ if ($id > 0 || !empty($ref)) // Form with product to add - if ((empty($action) || $action == 'view' || $action == 'edit' || $action == 'search' || $action == 're-edit') && ($user->rights->produit->creer || $user->rights->service->creer)) - { + if ((empty($action) || $action == 'view' || $action == 'edit' || $action == 'search' || $action == 're-edit') && ($user->rights->produit->creer || $user->rights->service->creer)) { print '<br>'; $rowspan = 1; - if (!empty($conf->categorie->enabled)) $rowspan++; + if (!empty($conf->categorie->enabled)) { + $rowspan++; + } print load_fiche_titre($langs->trans("ProductToAddSearch"), '', ''); print '<form action="'.DOL_URL_ROOT.'/product/composition/card.php?id='.$id.'" method="POST">'; @@ -480,8 +496,7 @@ if ($id > 0 || !empty($ref)) print $langs->trans("KeywordFilter").': '; print '<input type="text" name="key" value="'.$key.'"> &nbsp; '; print '</div>'; - if (!empty($conf->categorie->enabled)) - { + if (!empty($conf->categorie->enabled)) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; print '<div class="inline-block">'.$langs->trans("CategoryFilter").': '; print $form->select_all_categories(Categorie::TYPE_PRODUCT, $parent, 'parent').' &nbsp; </div>'; @@ -495,8 +510,7 @@ if ($id > 0 || !empty($ref)) // List of products - if ($action == 'search') - { + if ($action == 'search') { print '<br>'; print '<form action="'.DOL_URL_ROOT.'/product/composition/card.php?id='.$id.'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -510,20 +524,19 @@ if ($id > 0 || !empty($ref)) print '<th class="liste_titre right">'.$langs->trans("Qty").'</td>'; print '<th class="center">'.$langs->trans('ComposedProductIncDecStock').'</th>'; print '</tr>'; - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num == 0) print '<tr><td colspan="4">'.$langs->trans("NoMatchFound").'</td></tr>'; + if ($num == 0) { + print '<tr><td colspan="4">'.$langs->trans("NoMatchFound").'</td></tr>'; + } $MAX = 100; - while ($i < min($num, $MAX)) - { + while ($i < min($num, $MAX)) { $objp = $db->fetch_object($resql); - if ($objp->rowid != $id) - { + if ($objp->rowid != $id) { // check if a product is not already a parent product of this one $prod_arbo = new Product($db); $prod_arbo->id = $objp->rowid; @@ -560,13 +573,14 @@ if ($id > 0 || !empty($ref)) print '<td>'.$productstatic->getNomUrl(1, '', 24).'</td>'; $labeltoshow = $objp->label; - if ($conf->global->MAIN_MULTILANGS && $objp->labelm) $labeltoshow = $objp->labelm; + if ($conf->global->MAIN_MULTILANGS && $objp->labelm) { + $labeltoshow = $objp->labelm; + } print '<td>'.$labeltoshow.'</td>'; - if ($object->is_sousproduit($id, $objp->rowid)) - { + if ($object->is_sousproduit($id, $objp->rowid)) { //$addchecked = ' checked'; $qty = $object->is_sousproduit_qty; $incdec = $object->is_sousproduit_incdec; @@ -583,8 +597,9 @@ if ($id > 0 || !empty($ref)) // Inc Dec print '<td class="center">'; - if ($qty) print '<input type="checkbox" name="prod_incdec_'.$i.'" value="1" '.($incdec ? 'checked' : '').'>'; - else { + if ($qty) { + print '<input type="checkbox" name="prod_incdec_'.$i.'" value="1" '.($incdec ? 'checked' : '').'>'; + } else { // TODO Hide field and show it when setting a qty print '<input type="checkbox" name="prod_incdec_'.$i.'" value="1" checked>'; //print '<input type="checkbox" disabled name="prod_incdec_'.$i.'" value="1" checked>'; @@ -609,8 +624,7 @@ if ($id > 0 || !empty($ref)) print '</table>'; print '<input type="hidden" name="max_prod" value="'.$i.'">'; - if ($num > 0) - { + if ($num > 0) { print '<br><div class="center">'; print '<input type="submit" class="button" name="save" value="'.$langs->trans("Add").'/'.$langs->trans("Update").'">'; print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; diff --git a/htdocs/product/document.php b/htdocs/product/document.php index f8f5322f2f8..c218d753d88 100644 --- a/htdocs/product/document.php +++ b/htdocs/product/document.php @@ -34,8 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -if (!empty($conf->global->PRODUIT_PDF_MERGE_PROPAL)) +if (!empty($conf->global->PRODUIT_PDF_MERGE_PROPAL)) { require_once DOL_DOCUMENT_ROOT.'/product/class/propalmergepdfproduct.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('other', 'products')); @@ -48,7 +49,9 @@ $confirm = GETPOST('confirm', 'alpha'); // 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; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -59,26 +62,36 @@ $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 = "position_name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "position_name"; +} $object = new Product($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref); - if (!empty($conf->product->enabled)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product'); - elseif (!empty($conf->service->enabled)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product'); + if (!empty($conf->product->enabled)) { + $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product'); + } elseif (!empty($conf->service->enabled)) { + $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product'); + } - if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs - { - if (!empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; - else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { // For backward compatiblity, we scan also old dirs + if (!empty($conf->product->enabled)) { + $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; + } else { + $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; + } } } $modulepart = 'produit'; @@ -92,15 +105,14 @@ $permissiontoadd = (($object->type == Product::TYPE_PRODUCT && $user->rights->pr $parameters = array('id'=>$id); $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 (empty($reshook)) { // Delete line if product propal merge is linked to a file - if (!empty($conf->global->PRODUIT_PDF_MERGE_PROPAL)) - { - if ($action == 'confirm_deletefile' && $confirm == 'yes') - { + if (!empty($conf->global->PRODUIT_PDF_MERGE_PROPAL)) { + if ($action == 'confirm_deletefile' && $confirm == 'yes') { //extract file name $urlfile = GETPOST('urlfile', 'alpha'); $filename = basename($urlfile); @@ -115,11 +127,10 @@ if (empty($reshook)) } // Action submit/delete file/link - include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; + include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; } -if ($action == 'filemerge') -{ +if ($action == 'filemerge') { $is_refresh = GETPOST('refresh'); if (empty($is_refresh)) { $filetomerge_file_array = GETPOST('filetoadd'); @@ -171,13 +182,11 @@ $form = new Form($db); $title = $langs->trans('ProductServiceCard'); $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); -if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) -{ +if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Documents'); $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; } -if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) -{ +if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Documents'); $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; } @@ -185,8 +194,7 @@ if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) llxHeader('', $title, $helpurl); -if ($object->id) -{ +if ($object->id) { $head = product_prepare_head($object); $titre = $langs->trans("CardProduct".$object->type); $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -196,20 +204,20 @@ if ($object->id) $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); - if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs - { + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { // For backward compatiblity, we scan also old dirs $filearrayold = dol_dir_list($upload_dirold, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $filearray = array_merge($filearray, $filearrayold); } $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -218,7 +226,9 @@ if ($object->id) $object->next_prev_filter = " fk_product_type = ".$object->type; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -241,8 +251,7 @@ if ($object->id) // Merge propal PDF document PDF files - if (!empty($conf->global->PRODUIT_PDF_MERGE_PROPAL)) - { + if (!empty($conf->global->PRODUIT_PDF_MERGE_PROPAL)) { $filetomerge = new Propalmergepdfproduct($db); if ($conf->global->MAIN_MULTILANGS) { @@ -257,14 +266,12 @@ if ($object->id) $filearray = dol_dir_list($upload_dir, "files", 0, '', '\.meta$', 'name', SORT_ASC, 1); - if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs - { + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { // For backward compatiblity, we scan also old dirs $filearray = array_merge($filearray, dol_dir_list($upload_dirold, "files", 0, '', '\.meta$', 'name', SORT_ASC, 1)); } // For each file build select list with PDF extention - if (count($filearray) > 0) - { + if (count($filearray) > 0) { print '<br>'; // Actual file to merge is : if (count($filetomerge->lines) > 0) { @@ -299,23 +306,18 @@ if ($object->id) print '</td></tr>'; } - foreach ($filearray as $filetoadd) - { - if ($ext = pathinfo($filetoadd['name'], PATHINFO_EXTENSION) == 'pdf') - { + foreach ($filearray as $filetoadd) { + if ($ext = pathinfo($filetoadd['name'], PATHINFO_EXTENSION) == 'pdf') { $checked = ''; $filename = $filetoadd['name']; - if ($conf->global->MAIN_MULTILANGS) - { - if (array_key_exists($filetoadd['name'].'_'.$default_lang, $filetomerge->lines)) - { + if ($conf->global->MAIN_MULTILANGS) { + if (array_key_exists($filetoadd['name'].'_'.$default_lang, $filetomerge->lines)) { $filename = $filetoadd['name'].' - '.$langs->trans('Language_'.$default_lang); $checked = ' checked '; } } else { - if (array_key_exists($filetoadd['name'], $filetomerge->lines)) - { + if (array_key_exists($filetoadd['name'], $filetomerge->lines)) { $checked = ' checked '; } } diff --git a/htdocs/product/dynamic_price/class/price_expression.class.php b/htdocs/product/dynamic_price/class/price_expression.class.php index 218780cce44..546c2050990 100644 --- a/htdocs/product/dynamic_price/class/price_expression.class.php +++ b/htdocs/product/dynamic_price/class/price_expression.class.php @@ -80,8 +80,12 @@ class PriceExpression $error = 0; // Clean parameters - if (isset($this->title)) $this->title = trim($this->title); - if (isset($this->expression)) $this->expression = trim($this->expression); + if (isset($this->title)) { + $this->title = trim($this->title); + } + if (isset($this->expression)) { + $this->expression = trim($this->expression); + } // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." ("; @@ -95,10 +99,11 @@ class PriceExpression dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); //if (! $notrigger) @@ -114,10 +119,8 @@ class PriceExpression } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -139,23 +142,20 @@ class PriceExpression public function fetch($id) { // Check parameters - if (empty($id)) - { + if (empty($id)) { $this->error = 'ErrorWrongParameters'; return -1; } $sql = "SELECT title, expression"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $this->id = $id; $this->title = $obj->title; $this->expression = $obj->expression; @@ -184,12 +184,10 @@ class PriceExpression dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $retarray = array(); - while ($record = $this->db->fetch_array($resql)) - { + while ($record = $this->db->fetch_array($resql)) { $price_expression_obj = new PriceExpression($this->db); $price_expression_obj->id = $record["rowid"]; $price_expression_obj->title = $record["title"]; @@ -222,11 +220,9 @@ class PriceExpression dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { return (int) $obj->rowid; } else { return 0; @@ -250,8 +246,12 @@ class PriceExpression $error = 0; // Clean parameters - if (isset($this->title)) $this->title = trim($this->title); - if (isset($this->expression)) $this->expression = trim($this->expression); + if (isset($this->title)) { + $this->title = trim($this->title); + } + if (isset($this->expression)) { + $this->expression = trim($this->expression); + } // Update request $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; @@ -263,7 +263,9 @@ class PriceExpression dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // if (! $error) // { @@ -280,10 +282,8 @@ class PriceExpression // } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -325,21 +325,20 @@ class PriceExpression // } //} - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; $sql .= " WHERE rowid = ".$rowid; dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } diff --git a/htdocs/product/dynamic_price/class/price_global_variable.class.php b/htdocs/product/dynamic_price/class/price_global_variable.class.php index fbe5956db7c..29505ff8573 100644 --- a/htdocs/product/dynamic_price/class/price_global_variable.class.php +++ b/htdocs/product/dynamic_price/class/price_global_variable.class.php @@ -100,14 +100,14 @@ class PriceGlobalVariable dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - if (!$notrigger) - { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -119,10 +119,8 @@ class PriceGlobalVariable } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -145,15 +143,13 @@ class PriceGlobalVariable { $sql = "SELECT code, description, value"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $this->id = $id; $this->code = $obj->code; $this->description = $obj->description; @@ -193,7 +189,9 @@ class PriceGlobalVariable dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // if (! $error) // { @@ -210,10 +208,8 @@ class PriceGlobalVariable // } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -240,10 +236,8 @@ class PriceGlobalVariable $this->db->begin(); - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -254,21 +248,20 @@ class PriceGlobalVariable } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; $sql .= " WHERE rowid = ".$rowid; dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -302,11 +295,17 @@ class PriceGlobalVariable public function checkParameters() { // Clean parameters - if (isset($this->code)) $this->code = trim($this->code); - if (isset($this->description)) $this->description = trim($this->description); + if (isset($this->code)) { + $this->code = trim($this->code); + } + if (isset($this->description)) { + $this->description = trim($this->description); + } // Check parameters - if (empty($this->value) || !is_numeric($this->value)) $this->value = 0; + if (empty($this->value) || !is_numeric($this->value)) { + $this->value = 0; + } } /** @@ -322,12 +321,10 @@ class PriceGlobalVariable dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $retarray = array(); - while ($record = $this->db->fetch_array($resql)) - { + while ($record = $this->db->fetch_array($resql)) { $variable_obj = new PriceGlobalVariable($this->db); $variable_obj->id = $record["rowid"]; $variable_obj->code = $record["code"]; diff --git a/htdocs/product/dynamic_price/class/price_global_variable_updater.class.php b/htdocs/product/dynamic_price/class/price_global_variable_updater.class.php index 256e3525ead..f43d6bc731d 100644 --- a/htdocs/product/dynamic_price/class/price_global_variable_updater.class.php +++ b/htdocs/product/dynamic_price/class/price_global_variable_updater.class.php @@ -116,14 +116,14 @@ class PriceGlobalVariableUpdater dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - if (!$notrigger) - { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -135,10 +135,8 @@ class PriceGlobalVariableUpdater } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -161,15 +159,13 @@ class PriceGlobalVariableUpdater { $sql = "SELECT type, description, parameters, fk_variable, update_interval, next_update, last_status"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $this->id = $id; $this->type = $obj->type; $this->description = $obj->description; @@ -217,7 +213,9 @@ class PriceGlobalVariableUpdater dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // if (! $error) // { @@ -234,10 +232,8 @@ class PriceGlobalVariableUpdater // } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -277,21 +273,20 @@ class PriceGlobalVariableUpdater // } //} - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; $sql .= " WHERE rowid = ".$rowid; dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -345,15 +340,28 @@ class PriceGlobalVariableUpdater public function checkParameters() { // Clean parameters - if (isset($this->description)) $this->description = trim($this->description); - if (isset($this->parameters)) $this->parameters = trim($this->parameters); - else $this->parameters = ""; - if (isset($this->last_status)) $this->last_status = trim($this->last_status); + if (isset($this->description)) { + $this->description = trim($this->description); + } + if (isset($this->parameters)) { + $this->parameters = trim($this->parameters); + } else { + $this->parameters = ""; + } + if (isset($this->last_status)) { + $this->last_status = trim($this->last_status); + } // Check parameters - if (empty($this->type) || !is_numeric($this->type) || !in_array($this->type, $this->types)) $this->type = 0; - if (empty($this->update_interval) || !is_numeric($this->update_interval) || $this->update_interval < 1) $this->update_interval = $this->update_min; - if (empty($this->next_update) || !is_numeric($this->next_update) || $this->next_update < 0) $this->next_update = 0; + if (empty($this->type) || !is_numeric($this->type) || !in_array($this->type, $this->types)) { + $this->type = 0; + } + if (empty($this->update_interval) || !is_numeric($this->update_interval) || $this->update_interval < 1) { + $this->update_interval = $this->update_min; + } + if (empty($this->next_update) || !is_numeric($this->next_update) || $this->next_update < 0) { + $this->next_update = 0; + } } /** @@ -368,12 +376,10 @@ class PriceGlobalVariableUpdater dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $retarray = array(); - while ($record = $this->db->fetch_array($resql)) - { + while ($record = $this->db->fetch_array($resql)) { $updater_obj = new PriceGlobalVariableUpdater($this->db); $updater_obj->id = $record["rowid"]; $updater_obj->type = $record["type"]; @@ -408,12 +414,10 @@ class PriceGlobalVariableUpdater dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $retarray = array(); - while ($record = $this->db->fetch_array($resql)) - { + while ($record = $this->db->fetch_array($resql)) { $updater_obj = new PriceGlobalVariableUpdater($this->db); $updater_obj->id = $record["rowid"]; $updater_obj->type = $record["type"]; @@ -572,13 +576,13 @@ class PriceGlobalVariableUpdater dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -616,13 +620,13 @@ class PriceGlobalVariableUpdater dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } diff --git a/htdocs/product/dynamic_price/class/price_parser.class.php b/htdocs/product/dynamic_price/class/price_parser.class.php index 47cb58c2a7f..3d28f4b6011 100644 --- a/htdocs/product/dynamic_price/class/price_parser.class.php +++ b/htdocs/product/dynamic_price/class/price_parser.class.php @@ -64,53 +64,49 @@ class PriceParser global $langs; $langs->load("errors"); /* - -No arg - 9, an unexpected error occured - 14, division by zero - 19, expression not found - 20, empty expression + -No arg + 9, an unexpected error occured + 14, division by zero + 19, expression not found + 20, empty expression - -1 Arg - 1, cannot assign to constant '%s' - 2, cannot redefine built-in function '%s' - 3, undefined variable '%s' in function definition - 4, illegal character '%s' - 5, unexpected '%s' - 8, unexpected operator '%s' - 10, operator '%s' lacks operand - 11, expecting '%s' - 17, undefined variable '%s' - 21, empty result '%s' - 22, negative result '%s' - 24, variable '%s' exists but has no value + -1 Arg + 1, cannot assign to constant '%s' + 2, cannot redefine built-in function '%s' + 3, undefined variable '%s' in function definition + 4, illegal character '%s' + 5, unexpected '%s' + 8, unexpected operator '%s' + 10, operator '%s' lacks operand + 11, expecting '%s' + 17, undefined variable '%s' + 21, empty result '%s' + 22, negative result '%s' + 24, variable '%s' exists but has no value - -2 Args - 6, wrong number of arguments (%s given, %s expected) - 23, unknown or non set variable '%s' after %s + -2 Args + 6, wrong number of arguments (%s given, %s expected) + 23, unknown or non set variable '%s' after %s - -internal errors - 7, internal error - 12, internal error - 13, internal error - 15, internal error - 16, internal error - 18, internal error - */ + -internal errors + 7, internal error + 12, internal error + 13, internal error + 15, internal error + 16, internal error + 18, internal error + */ if (empty($this->error_parser)) { return $langs->trans("ErrorPriceExpressionUnknown", 0); //this is not supposed to happen } list($code, $info) = $this->error_parser; - if (in_array($code, array(9, 14, 19, 20))) //Errors which have 0 arg - { + if (in_array($code, array(9, 14, 19, 20))) { //Errors which have 0 arg return $langs->trans("ErrorPriceExpression".$code); - } elseif (in_array($code, array(1, 2, 3, 4, 5, 8, 10, 11, 17, 21, 22))) //Errors which have 1 arg - { + } elseif (in_array($code, array(1, 2, 3, 4, 5, 8, 10, 11, 17, 21, 22))) { //Errors which have 1 arg return $langs->trans("ErrorPriceExpression".$code, $info); - } elseif (in_array($code, array(6, 23))) //Errors which have 2 args - { + } elseif (in_array($code, array(6, 23))) { //Errors which have 2 args return $langs->trans("ErrorPriceExpression".$code, $info[0], $info[1]); - } elseif (in_array($code, array(7, 12, 13, 15, 16, 18))) //Internal errors - { + } elseif (in_array($code, array(7, 12, 13, 15, 16, 18))) { //Internal errors return $langs->trans("ErrorPriceExpressionInternal", $code); } else //Unknown errors { @@ -140,8 +136,7 @@ class PriceParser } //Check if empty $expression = trim($expression); - if (empty($expression)) - { + if (empty($expression)) { $this->error_parser = array(20, null); return -2; } @@ -161,10 +156,8 @@ class PriceParser $extrafields = new ExtraFields($this->db); $extrafields->fetch_name_optionals_label('product', true); $product->fetch_optionals(); - if (is_array($extrafields->attributes[$product->table_element]['label'])) - { - foreach ($extrafields->attributes[$product->table_element]['label'] as $key=>$label) - { + if (is_array($extrafields->attributes[$product->table_element]['label'])) { + foreach ($extrafields->attributes[$product->table_element]['label'] as $key => $label) { $values["extrafield_".$key] = $product->array_options['options_'.$key]; } } @@ -182,8 +175,7 @@ class PriceParser //Get all global values $price_globals = new PriceGlobalVariable($this->db); - foreach ($price_globals->listGlobalVariables() as $entry) - { + foreach ($price_globals->listGlobalVariables() as $entry) { $values["global_".$entry->code] = $entry->value; } @@ -198,8 +190,7 @@ class PriceParser //Fill each variable in expression from values $expression = str_replace("\n", $this->separator_chr, $expression); - foreach ($values as $key => $value) - { + foreach ($values as $key => $value) { if ($value === null && strpos($expression, $key) !== false) { $this->error_parser = array(24, $key); return -7; @@ -208,11 +199,12 @@ class PriceParser } //Check if there is unfilled variable - if (strpos($expression, $this->special_chr) !== false) - { + if (strpos($expression, $this->special_chr) !== false) { $data = explode($this->special_chr, $expression); $variable = $this->special_chr.$data[1]; - if (isset($data[2])) $variable .= $this->special_chr; + if (isset($data[2])) { + $variable .= $this->special_chr; + } $this->error_parser = array(23, array($variable, $expression)); return -6; } @@ -222,8 +214,7 @@ class PriceParser $expressions = array_slice($expressions, 0, $this->limit); foreach ($expressions as $expr) { $expr = trim($expr); - if (!empty($expr)) - { + if (!empty($expr)) { $last_result = $em->evaluate($expr); $this->error_parser = $em->last_error_code; if ($this->error_parser !== null) { //$em->last_error_code is null if no error happened, so just check if error_parser is not null @@ -236,13 +227,11 @@ class PriceParser if (empty($vars["price"])) { $vars["price"] = $last_result; } - if (!isset($vars["price"])) - { + if (!isset($vars["price"])) { $this->error_parser = array(21, $expression); return -4; } - if ($vars["price"] < 0) - { + if ($vars["price"] < 0) { $this->error_parser = array(22, $expression); return -5; } @@ -305,8 +294,7 @@ class PriceParser //Get the expression from db $price_expression = new PriceExpression($this->db); $res = $price_expression->fetch($product_supplier->fk_supplier_price_expression); - if ($res < 1) - { + if ($res < 1) { $this->error_parser = array(19, null); return -1; } diff --git a/htdocs/product/dynamic_price/editor.php b/htdocs/product/dynamic_price/editor.php index 24f4856698f..418a71166a8 100644 --- a/htdocs/product/dynamic_price/editor.php +++ b/htdocs/product/dynamic_price/editor.php @@ -51,11 +51,9 @@ $price_expression = new PriceExpression($db); $price_globals = new PriceGlobalVariable($db); //Fetch expression data -if (empty($eid)) //This also disables fetch when eid == 0 -{ +if (empty($eid)) { //This also disables fetch when eid == 0 $eid = 0; -} elseif ($action != 'delete') -{ +} elseif ($action != 'delete') { $price_expression->fetch($eid); } @@ -64,13 +62,10 @@ if (empty($eid)) //This also disables fetch when eid == 0 * Actions */ -if ($action == 'add') -{ - if ($eid == 0) - { +if ($action == 'add') { + if ($eid == 0) { $result = $price_expression->find_title($title); - if ($result == 0) //No existing entry found with title, ok - { + if ($result == 0) { //No existing entry found with title, ok //Check the expression validity by parsing it $priceparser = new PriceParser($db); $price_result = $priceparser->testExpression($id, $expression); @@ -80,16 +75,14 @@ if ($action == 'add') $price_expression->title = $title; $price_expression->expression = $expression; $result = $price_expression->create($user); - if ($result > 0) //created successfully, set the eid to newly created entry - { + if ($result > 0) { //created successfully, set the eid to newly created entry $eid = $price_expression->id; setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); } else { setEventMessages("add: ".$price_expression->error, $price_expression->errors, 'errors'); } } - } elseif ($result < 0) - { + } elseif ($result < 0) { setEventMessages("add find: ".$price_expression->error, $price_expression->errors, 'errors'); } else { setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors'); @@ -97,13 +90,10 @@ if ($action == 'add') } } -if ($action == 'update') -{ - if ($eid != 0) - { +if ($action == 'update') { + if ($eid != 0) { $result = $price_expression->find_title($title); - if ($result == 0 || $result == $eid) //No existing entry found with title or existing one is the current one, ok - { + if ($result == 0 || $result == $eid) { //No existing entry found with title or existing one is the current one, ok //Check the expression validity by parsing it $priceparser = new PriceParser($db); $price_result = $priceparser->testExpression($id, $expression); @@ -114,15 +104,13 @@ if ($action == 'update') $price_expression->title = $title; $price_expression->expression = $expression; $result = $price_expression->update($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages("update: ".$price_expression->error, $price_expression->errors, 'errors'); } else { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); } } - } elseif ($result < 0) - { + } elseif ($result < 0) { setEventMessages("update find: ".$price_expression->error, $price_expression->errors, 'errors'); } else { setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors'); @@ -130,14 +118,11 @@ if ($action == 'update') } } -if ($action == 'delete') -{ - if ($eid != 0) - { +if ($action == 'delete') { + if ($eid != 0) { $price_expression->fetch($eid); $result = $price_expression->delete($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages("delete: ".$price_expression->error, $price_expression->errors, 'errors'); } $eid = 0; @@ -202,8 +187,7 @@ print dol_get_fiche_end(); print '<div class="center">'; print '<input type="submit" class="butAction button-save" value="'.$langs->trans("Save").'">'; print '<span id="back" class="butAction">'.$langs->trans("Back").'</span>'; -if ($eid == 0) -{ +if ($eid == 0) { print '<div class="inline-block divButAction"><span id="action-delete" class="butActionRefused classfortooltip">'.$langs->trans('Delete').'</span></div>'."\n"; } else { print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&amp;tab='.$tab.'&amp;eid='.$eid.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans("Delete").'</a></div>'; diff --git a/htdocs/product/fournisseurs.php b/htdocs/product/fournisseurs.php index 88c5259f48d..371713f0250 100644 --- a/htdocs/product/fournisseurs.php +++ b/htdocs/product/fournisseurs.php @@ -40,7 +40,9 @@ require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_expression.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; -if (!empty($conf->barcode->enabled)) dol_include_once('/core/class/html.formbarcode.class.php'); +if (!empty($conf->barcode->enabled)) { + dol_include_once('/core/class/html.formbarcode.class.php'); +} // Load translation files required by the page $langs->loadLangs(array('products', 'suppliers', 'bills', 'margins', 'stocks')); @@ -59,8 +61,7 @@ $error = 0; $extrafields = new ExtraFields($db); // If socid provided by ajax company selector -if (!empty($_REQUEST['search_fourn_id'])) -{ +if (!empty($_REQUEST['search_fourn_id'])) { $_GET['id_fourn'] = $_GET['search_fourn_id']; $_POST['id_fourn'] = $_POST['search_fourn_id']; $_REQUEST['id_fourn'] = $_REQUEST['search_fourn_id']; @@ -69,62 +70,75 @@ if (!empty($_REQUEST['search_fourn_id'])) // 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; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); -if (empty($user->rights->fournisseur->lire)) accessforbidden(); +if (empty($user->rights->fournisseur->lire)) { + accessforbidden(); +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = (GETPOST("page", 'int') ?GETPOST("page", 'int') : 0); -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 = "s.nom"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "s.nom"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('pricesuppliercard', 'globalcard')); $object = new ProductFournisseur($db); -if ($id > 0 || $ref) -{ +if ($id > 0 || $ref) { $object->fetch($id, $ref); } $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -if (!$sortfield) $sortfield = "s.nom"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "s.nom"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} /* * Actions */ -if ($cancel) $action = ''; +if ($cancel) { + $action = ''; +} $usercanread = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->lire) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->lire)); $usercancreate = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer)); $parameters = array('socid'=>$socid, 'id_prod'=>$id); $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 == 'setcost_price') - { - if ($id) - { +if (empty($reshook)) { + if ($action == 'setcost_price') { + if ($id) { $result = $object->fetch($id); $object->cost_price = price2num($cost_price); $result = $object->update($object->id, $user); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); $action = ''; } else { @@ -134,10 +148,8 @@ if (empty($reshook)) } } - if ($action == 'confirm_remove_pf') - { - if ($rowid) // id of product supplier price to remove - { + if ($action == 'confirm_remove_pf') { + if ($rowid) { // id of product supplier price to remove $action = ''; $result = $object->remove_product_fournisseur_price($rowid); if ($result > 0) { @@ -150,19 +162,28 @@ if (empty($reshook)) } } - if ($action == 'save_price') - { + if ($action == 'save_price') { $id_fourn = GETPOST("id_fourn"); - if (empty($id_fourn)) $id_fourn = GETPOST("search_id_fourn"); + if (empty($id_fourn)) { + $id_fourn = GETPOST("search_id_fourn"); + } $ref_fourn = GETPOST("ref_fourn"); - if (empty($ref_fourn)) $ref_fourn = GETPOST("search_ref_fourn"); + if (empty($ref_fourn)) { + $ref_fourn = GETPOST("search_ref_fourn"); + } $ref_fourn_old = GETPOST("ref_fourn_old"); - if (empty($ref_fourn_old)) $ref_fourn_old = $ref_fourn; + if (empty($ref_fourn_old)) { + $ref_fourn_old = $ref_fourn; + } $quantity = price2num(GETPOST("qty", 'nohtml'), 'MS'); $remise_percent = price2num(GETPOST('remise_percent', 'alpha')); + $npr = preg_match('/\*/', GETPOST('tva_tx', 'alpha')) ? 1 : 0; $tva_tx = str_replace('*', '', GETPOST('tva_tx', 'alpha')); - $tva_tx = price2num($tva_tx); + if (!preg_match('/\((.*)\)/', $tva_tx)) { + $tva_tx = price2num($tva_tx); + } + $price_expression = GETPOST('eid', 'int') ? GETPOST('eid', 'int') : ''; // Discard expression if not in expression mode $delivery_time_days = GETPOST('delivery_time_days', 'int') ? GETPOST('delivery_time_days', 'int') : ''; $supplier_reputation = GETPOST('supplier_reputation'); @@ -171,40 +192,33 @@ if (empty($reshook)) $fk_barcode_type = GETPOST('fk_barcode_type', 'int'); $packaging = price2num(GETPOST("packaging", 'alphanohtml'), 'MS'); - if ($tva_tx == '') - { + if ($tva_tx == '') { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("VATRateForSupplierProduct")), null, 'errors'); } - if (!is_numeric($tva_tx)) - { + if (!is_numeric($tva_tx)) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentities("VATRateForSupplierProduct")), null, 'errors'); } - if (empty($quantity)) - { + if (empty($quantity)) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Qty")), null, 'errors'); } - if (empty($ref_fourn)) - { + if (empty($ref_fourn)) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("RefSupplier")), null, 'errors'); } - if ($id_fourn <= 0) - { + if ($id_fourn <= 0) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Supplier")), null, 'errors'); } - if (price2num($_POST["price"]) < 0 || $_POST["price"] == '') - { - if ($price_expression === '') // Return error of missing price only if price_expression not set - { + if (price2num($_POST["price"]) < 0 || $_POST["price"] == '') { + if ($price_expression === '') { // Return error of missing price only if price_expression not set $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Price")), null, 'errors'); @@ -213,47 +227,42 @@ if (empty($reshook)) } } if (!empty($conf->multicurrency->enabled)) { - if (empty($_POST["multicurrency_code"])) { + if (!GETPOST("multicurrency_code")) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Currency")), null, 'errors'); } - if (price2num($_POST["multicurrency_tx"]) <= 0 || $_POST["multicurrency_tx"] == '') { + if (price2num(GETPOST("multicurrency_tx")) <= 0 || GETPOST("multicurrency_tx") == '') { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("CurrencyRate")), null, 'errors'); } - if (price2num($_POST["multicurrency_price"]) < 0 || $_POST["multicurrency_price"] == '') { + if (price2num(GETPOST("multicurrency_price")) < 0 || GETPOST("multicurrency_price") == '') { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("PriceCurrency")), null, 'errors'); } } - if (!$error) - { + if (!$error) { $db->begin(); - if (!$error) - { + if (!$error) { $ret = $object->add_fournisseur($user, $id_fourn, $ref_fourn_old, $quantity); // This insert record with no value for price. Values are update later with update_buyprice - if ($ret == -3) - { + if ($ret == -3) { $error++; $object->fetch($object->product_id_already_linked); $productLink = $object->getNomUrl(1, 'supplier'); setEventMessages($langs->trans("ReferenceSupplierIsAlreadyAssociatedWithAProduct", $productLink), null, 'errors'); - } elseif ($ret < 0) - { + } elseif ($ret < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } } - if (!$error) - { + if (!$error) { $supplier = new Fournisseur($db); $result = $supplier->fetch($id_fourn); if (GETPOSTISSET('ref_fourn_price_id')) { @@ -290,12 +299,15 @@ if (empty($reshook)) $newprice = price2num(GETPOST("price", "alpha")); - if (empty($packaging)) $packaging = 1; - if ($packaging < $quantity) $packaging = $quantity; + if (empty($packaging)) { + $packaging = 1; + } + if ($packaging < $quantity) { + $packaging = $quantity; + } $object->packaging = $packaging; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { $multicurrency_tx = price2num(GETPOST("multicurrency_tx", 'alpha')); $multicurrency_price = price2num(GETPOST("multicurrency_price", 'alpha')); $multicurrency_code = GETPOST("multicurrency_code", 'alpha'); @@ -304,13 +316,11 @@ if (empty($reshook)) } else { $ret = $object->update_buyprice($quantity, $newprice, $user, GETPOST("price_base_type"), $supplier, GETPOST("oselDispo"), $ref_fourn, $tva_tx, GETPOST("charges"), $remise_percent, 0, $npr, $delivery_time_days, $supplier_reputation, array(), '', 0, 'HT', 1, '', $supplier_description, $barcode, $fk_barcode_type); } - if ($ret < 0) - { + if ($ret < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } else { - if (!empty($conf->dynamicprices->enabled) && $price_expression !== '') - { + if (!empty($conf->dynamicprices->enabled) && $price_expression !== '') { //Check the expression validity by parsing it $priceparser = new PriceParser($db); $object->fk_supplier_price_expression = $price_expression; @@ -320,12 +330,10 @@ if (empty($reshook)) setEventMessages($priceparser->translatedError(), null, 'errors'); } } - if (!$error && !empty($conf->dynamicprices->enabled)) - { + if (!$error && !empty($conf->dynamicprices->enabled)) { //Set the price expression for this supplier price $ret = $object->setSupplierPriceExpression($price_expression); - if ($ret < 0) - { + if ($ret < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } @@ -333,8 +341,7 @@ if (empty($reshook)) } } - if (!$error) - { + if (!$error) { $db->commit(); $action = ''; } else { @@ -351,36 +358,31 @@ if (empty($reshook)) * view */ +$form = new Form($db); + $title = $langs->trans('ProductServiceCard'); $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); -if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) -{ +if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('BuyingPrices'); $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; } -if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) -{ +if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('BuyingPrices'); $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; } llxHeader('', $title, $helpurl, '', 0, 0, '', '', '', 'classforhorizontalscrolloftabs'); -$form = new Form($db); - -if ($id > 0 || $ref) -{ - if ($result) - { +if ($id > 0 || $ref) { + if ($result) { if ($action == 'ask_remove_pf') { $form = new Form($db); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$id.'&rowid='.$rowid, $langs->trans('DeleteProductBuyPrice'), $langs->trans('ConfirmDeleteProductBuyPrice'), 'confirm_remove_pf', '', 0, 1); echo $formconfirm; } - if ($action <> 'edit' && $action <> 're-edit') - { + if ($action <> 'edit' && $action <> 're-edit') { $head = product_prepare_head($object); $titre = $langs->trans("CardProduct".$object->type); $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -391,14 +393,16 @@ if ($id > 0 || $ref) $object->next_prev_filter = " fk_product_type = ".$object->type; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); print '<div class="fichecenter">'; print '<div class="underbanner clearboth"></div>'; - print '<table class="border tableforfield" width="100%">'; + print '<table class="border tableforfield centpercent">'; // Cost price. Can be used for margin module for option "calculate margin on explicit cost price print '<tr><td>'; @@ -411,20 +415,24 @@ if ($id > 0 || $ref) print '</td></tr>'; // PMP - print '<tr><td class="titlefield">'.$form->textwithpicto($langs->trans("AverageUnitPricePMPShort"), $langs->trans("AverageUnitPricePMPDesc")).'</td>'; + print '<tr><td class="titlefieldcreate">'.$form->textwithpicto($langs->trans("AverageUnitPricePMPShort"), $langs->trans("AverageUnitPricePMPDesc")).'</td>'; print '<td>'; - if ($object->pmp > 0) print price($object->pmp).' '.$langs->trans("HT"); + if ($object->pmp > 0) { + print price($object->pmp).' '.$langs->trans("HT"); + } print '</td>'; print '</tr>'; // Best buying Price - print '<tr><td class="titlefield">'.$langs->trans("BuyingPriceMin").'</td>'; + print '<tr><td class="titlefieldcreate">'.$langs->trans("BuyingPriceMin").'</td>'; print '<td colspan="2">'; $product_fourn = new ProductFournisseur($db); - if ($product_fourn->find_min_price_product_fournisseur($object->id) > 0) - { - if ($product_fourn->product_fourn_price_id > 0) print $product_fourn->display_price_product_fournisseur(); - else print $langs->trans("NotDefined"); + if ($product_fourn->find_min_price_product_fournisseur($object->id) > 0) { + if ($product_fourn->product_fourn_price_id > 0) { + print $product_fourn->display_price_product_fournisseur(); + } else { + print $langs->trans("NotDefined"); + } } print '</td></tr>'; @@ -437,12 +445,10 @@ if ($id > 0 || $ref) // Form to add or update a price - if (($action == 'add_price' || $action == 'update_price') && $usercancreate) - { + if (($action == 'add_price' || $action == 'update_price') && $usercancreate) { $langs->load("suppliers"); - if ($rowid) - { + if ($rowid) { $object->fetch_product_fournisseur_price($rowid, 1); //Ignore the math expression when getting the price print load_fiche_titre($langs->trans("ChangeSupplierPrice")); } else { @@ -458,9 +464,8 @@ if ($id > 0 || $ref) print '<table class="border centpercent">'; // Supplier - print '<tr><td class="titlefield fieldrequired">'.$langs->trans("Supplier").'</td><td>'; - if ($rowid) - { + print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Supplier").'</td><td>'; + if ($rowid) { $supplier = new Fournisseur($db); $supplier->fetch($socid); print $supplier->getNomUrl(1); @@ -475,10 +480,8 @@ if ($id > 0 || $ref) $parameters = array('filtre'=>"fournisseur=1", 'html_name'=>'id_fourn', 'selected'=>GETPOST("id_fourn"), 'showempty'=>1, 'prod_id'=>$object->id); $reshook = $hookmanager->executeHooks('formCreateThirdpartyOptions', $parameters, $object, $action); - if (empty($reshook)) - { - if (empty($form->result)) - { + if (empty($reshook)) { + if (empty($form->result)) { print ' - <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&type=f&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id.'&action='.$action).'">'.$langs->trans("CreateDolibarrThirdPartySupplier").'</a>'; } } @@ -487,8 +490,7 @@ if ($id > 0 || $ref) // Ref supplier print '<tr><td class="fieldrequired">'.$langs->trans("SupplierRef").'</td><td>'; - if ($rowid) - { + if ($rowid) { print '<input type="hidden" name="ref_fourn_old" value="'.$object->ref_supplier.'">'; print '<input class="flat width150" maxlength="30" name="ref_fourn" value="'.$object->ref_supplier.'">'; } else { @@ -498,8 +500,7 @@ if ($id > 0 || $ref) print '</tr>'; // Availability - if (!empty($conf->global->FOURN_PRODUCT_AVAILABILITY)) - { + if (!empty($conf->global->FOURN_PRODUCT_AVAILABILITY)) { $langs->load("propal"); print '<tr><td>'.$langs->trans("Availability").'</td><td>'; $form->selectAvailabilityDelay($object->fk_availability, "oselDispo", 1); @@ -511,8 +512,7 @@ if ($id > 0 || $ref) print '<td class="fieldrequired">'.$langs->trans("QtyMin").'</td>'; print '<td>'; $quantity = GETPOSTISSET('qty') ? price2num(GETPOST('qty', 'nohtml'), 'MS') : "1"; - if ($rowid) - { + if ($rowid) { print '<input type="hidden" name="qty" value="'.$object->fourn_qty.'">'; print $object->fourn_qty; } else { @@ -554,20 +554,20 @@ if ($id > 0 || $ref) $mysoc2->tva_assuj = 1; $default_vat = get_default_tva($mysoc2, $mysoc, $object->id, 0); $default_npr = get_default_npr($mysoc2, $mysoc, $object->id, 0); - if (empty($default_vat)) $default_npr = $default_vat; + if (empty($default_vat)) { + $default_npr = $default_vat; + } print '<tr><td class="fieldrequired">'.$langs->trans("VATRateForSupplierProduct").'</td>'; print '<td>'; //print $form->load_tva('tva_tx',$object->tva_tx,$supplier,$mysoc); // Do not use list here as it may be any vat rates for any country - if (!empty($rowid)) // If we have a supplier, it is an update, we must show the vat of current supplier price - { + if (!empty($rowid)) { // If we have a supplier, it is an update, we must show the vat of current supplier price $tmpproductsupplier = new ProductFournisseur($db); $tmpproductsupplier->fetch_product_fournisseur_price($rowid, 1); $default_vat = $tmpproductsupplier->fourn_tva_tx; $default_npr = $tmpproductsupplier->fourn_tva_npr; } else { - if (empty($default_vat)) - { + if (empty($default_vat)) { $default_vat = $object->tva_tx; } } @@ -576,8 +576,7 @@ if ($id > 0 || $ref) print '<input type="text" class="flat" size="5" name="tva_tx" value="'.$vattosuggest.'">'; print '</td></tr>'; - if (!empty($conf->dynamicprices->enabled)) //Only show price mode and expression selector if module is enabled - { + if (!empty($conf->dynamicprices->enabled)) { //Only show price mode and expression selector if module is enabled // Price mode selector print '<tr><td class="fieldrequired">'.$langs->trans("PriceMode").'</td><td>'; $price_expression = new PriceExpression($db); @@ -615,7 +614,9 @@ if ($id > 0 || $ref) print '<tr><td class="fieldrequired">'.$langs->trans("Currency").'</td>'; print '<td>'; $currencycodetouse = GETPOST('multicurrency_code') ?GETPOST('multicurrency_code') : (isset($object->fourn_multicurrency_code) ? $object->fourn_multicurrency_code : ''); - if (empty($currencycodetouse) && $object->fourn_multicurrency_tx == 1) $currencycodetouse = $conf->currency; + if (empty($currencycodetouse) && $object->fourn_multicurrency_tx == 1) { + $currencycodetouse = $conf->currency; + } print $form->selectMultiCurrency($currencycodetouse, "multicurrency_code", 1); print ' &nbsp; '.$langs->trans("CurrencyRate").' '; print '<input class="flat" name="multicurrency_tx" size="4" value="'.vatrate(GETPOST('multicurrency_tx') ? GETPOST('multicurrency_tx') : (isset($object->fourn_multicurrency_tx) ? $object->fourn_multicurrency_tx : '')).'">'; @@ -720,12 +721,11 @@ END; print '</td></tr>'; // Barcode - if (!empty($conf->barcode->enabled)) - { + if (!empty($conf->barcode->enabled)) { // Option to define a transport cost on supplier price print '<tr>'; print '<td>'.$langs->trans('BarcodeValue').'</td>'; - print '<td><input class="flat" name="barcode" value="'.($rowid ? $object->supplier_barcode : '').'"></td>'; + print '<td>'.img_picto('', 'barcode', 'class="pictofixedwidth"').'<input class="flat" name="barcode" value="'.($rowid ? $object->supplier_barcode : '').'"></td>'; print '</tr>'; $formbarcode = new FormBarCode($db); @@ -739,10 +739,8 @@ END; } // Option to define a transport cost on supplier price - if ($conf->global->PRODUCT_CHARGES) - { - if (!empty($conf->margin->enabled)) - { + if ($conf->global->PRODUCT_CHARGES) { + if (!empty($conf->margin->enabled)) { print '<tr>'; print '<td>'.$langs->trans("Charges").'</td>'; print '<td><input class="flat" name="charges" size="8" value="'.(GETPOST('charges') ?price(GETPOST('charges')) : (isset($object->fourn_charges) ?price($object->fourn_charges) : '')).'">'; @@ -752,8 +750,7 @@ END; } // Product description of the supplier - if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) - { + if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -776,11 +773,16 @@ END; if (empty($rowid)) { foreach ($extralabels as $key => $value) { if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && ($extrafields->attributes["product_fournisseur_price"]['list'][$key] == 1 || $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 3 || ($action == "update_price" && $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 4))) { - if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) $langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]); + if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) { + $langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]); + } print '<tr><td'.($extrafields->attributes["product_fournisseur_price"]['required'][$key] ? ' class="fieldrequired"' : '').'>'; - if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) print $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key])); - else print $langs->trans($value); + if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) { + print $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key])); + } else { + print $langs->trans($value); + } print '</td><td>'.$extrafields->showInputField($key, GETPOSTISSET('options_'.$key) ? $extrafield_values['options_'.$key] : '', '', '', '', '', 0, 'product_fournisseur_price').'</td></tr>'; } } @@ -797,11 +799,16 @@ END; $obj = $db->fetch_object($resql); foreach ($extralabels as $key => $value) { if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && ($extrafields->attributes["product_fournisseur_price"]['list'][$key] == 1 || $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 3 || ($action == "update_price" && $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 4))) { - if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) $langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]); + if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) { + $langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]); + } print '<tr><td'.($extrafields->attributes["product_fournisseur_price"]['required'][$key] ? ' class="fieldrequired"' : '').'>'; - if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) print $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key])); - else print $langs->trans($value); + if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) { + print $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key])); + } else { + print $langs->trans($value); + } print '</td><td>'.$extrafields->showInputField($key, GETPOSTISSET('options_'.$key) ? $extrafield_values['options_'.$key] : $obj->{$key}, '', '', '', '', 0, 'product_fournisseur_price'); print '</td></tr>'; @@ -812,8 +819,7 @@ END; } } - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('id_fourn'=>$id_fourn, 'prod_id'=>$object->id); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); print $hookmanager->resPrint; @@ -836,14 +842,11 @@ END; print "\n<div class=\"tabsAction\">\n"; - if ($action != 'add_price' && $action != 'update_price') - { + if ($action != 'add_price' && $action != 'update_price') { $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { - if ($usercancreate) - { + if (empty($reshook)) { + if ($usercancreate) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/product/fournisseurs.php?id='.$object->id.'&amp;action=add_price">'; print $langs->trans("AddSupplierPrice").'</a>'; } @@ -853,11 +856,14 @@ END; print "\n</div>\n"; print '<br>'; - if ($user->rights->fournisseur->lire) // Duplicate ? this check is already in the head of this file - { + if ($user->rights->fournisseur->lire) { // Duplicate ? this check is already in the head of this file $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 .= '&ref='.urlencode($object->ref); $product_fourn = new ProductFournisseur($db); @@ -865,7 +871,9 @@ END; $product_fourn_list_all = $product_fourn->list_product_fournisseur_price($object->id, $sortfield, $sortorder, 0, 0); $nbtotalofrecords = count($product_fourn_list_all); $num = count($product_fourn_list); - if (($num + ($offset * $limit)) < $nbtotalofrecords) $num++; + if (($num + ($offset * $limit)) < $nbtotalofrecords) { + $num++; + } print_barre_liste($langs->trans('SupplierPrices'), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy.png', 0, '', '', $limit, 1); @@ -920,24 +928,52 @@ END; $param = "&id=".$object->id; print '<tr class="liste_titre">'; - if (!empty($arrayfields['pfp.datec']['checked'])) print_liste_field_titre("AppliedPricesFrom", $_SERVER["PHP_SELF"], "pfp.datec", "", $param, "", $sortfield, $sortorder, '', '', 1); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre("Suppliers", $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder, '', '', 1); + if (!empty($arrayfields['pfp.datec']['checked'])) { + print_liste_field_titre("AppliedPricesFrom", $_SERVER["PHP_SELF"], "pfp.datec", "", $param, "", $sortfield, $sortorder, '', '', 1); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre("Suppliers", $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder, '', '', 1); + } print_liste_field_titre("SupplierRef", $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder, '', '', 1); - if (!empty($arrayfields['pfp.fk_availability']['checked'])) print_liste_field_titre("Availability", $_SERVER["PHP_SELF"], "pfp.fk_availability", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['pfp.quantity']['checked'])) print_liste_field_titre("QtyMin", $_SERVER["PHP_SELF"], "pfp.quantity", "", $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['pfp.fk_availability']['checked'])) { + print_liste_field_titre("Availability", $_SERVER["PHP_SELF"], "pfp.fk_availability", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['pfp.quantity']['checked'])) { + print_liste_field_titre("QtyMin", $_SERVER["PHP_SELF"], "pfp.quantity", "", $param, '', $sortfield, $sortorder, 'right '); + } print_liste_field_titre("VATRate", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("PriceQtyMinHT", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($conf->multicurrency->enabled)) print_liste_field_titre("PriceQtyMinHTCurrency", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['pfp.unitprice']['checked'])) print_liste_field_titre("UnitPriceHT", $_SERVER["PHP_SELF"], "pfp.unitprice", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['pfp.multicurrency_unitprice']['checked'])) print_liste_field_titre("UnitPriceHTCurrency", $_SERVER["PHP_SELF"], "pfp.multicurrency_unitprice", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($conf->multicurrency->enabled)) print_liste_field_titre("Currency", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); + if (!empty($conf->multicurrency->enabled)) { + print_liste_field_titre("PriceQtyMinHTCurrency", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['pfp.unitprice']['checked'])) { + print_liste_field_titre("UnitPriceHT", $_SERVER["PHP_SELF"], "pfp.unitprice", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['pfp.multicurrency_unitprice']['checked'])) { + print_liste_field_titre("UnitPriceHTCurrency", $_SERVER["PHP_SELF"], "pfp.multicurrency_unitprice", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($conf->multicurrency->enabled)) { + print_liste_field_titre("Currency", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); + } print_liste_field_titre("DiscountQtyMin", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['pfp.delivery_time_days']['checked'])) print_liste_field_titre("NbDaysToDelivery", $_SERVER["PHP_SELF"], "pfp.delivery_time_days", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['pfp.supplier_reputation']['checked'])) print_liste_field_titre("ReputationForThisProduct", $_SERVER["PHP_SELF"], "pfp.supplier_reputation", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['pfp.barcode']['checked'])) print_liste_field_titre("BarcodeValue", $_SERVER["PHP_SELF"], "pfp.barcode", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['pfp.fk_barcode_type']['checked'])) print_liste_field_titre("BarcodeType", $_SERVER["PHP_SELF"], "pfp.fk_barcode_type", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['pfp.packaging']['checked'])) print_liste_field_titre("PackagingForThisProduct", $_SERVER["PHP_SELF"], "pfp.packaging", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['pfp.tms']['checked'])) print_liste_field_titre("DateModification", $_SERVER["PHP_SELF"], "pfp.tms", "", $param, '', $sortfield, $sortorder, 'right ', '', 1); + if (!empty($arrayfields['pfp.delivery_time_days']['checked'])) { + print_liste_field_titre("NbDaysToDelivery", $_SERVER["PHP_SELF"], "pfp.delivery_time_days", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['pfp.supplier_reputation']['checked'])) { + print_liste_field_titre("ReputationForThisProduct", $_SERVER["PHP_SELF"], "pfp.supplier_reputation", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['pfp.barcode']['checked'])) { + print_liste_field_titre("BarcodeValue", $_SERVER["PHP_SELF"], "pfp.barcode", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['pfp.fk_barcode_type']['checked'])) { + print_liste_field_titre("BarcodeType", $_SERVER["PHP_SELF"], "pfp.fk_barcode_type", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['pfp.packaging']['checked'])) { + print_liste_field_titre("PackagingForThisProduct", $_SERVER["PHP_SELF"], "pfp.packaging", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['pfp.tms']['checked'])) { + print_liste_field_titre("DateModification", $_SERVER["PHP_SELF"], "pfp.tms", "", $param, '', $sortfield, $sortorder, 'right ', '', 1); + } // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label("product_fournisseur_price"); @@ -947,26 +983,30 @@ END; foreach ($extralabels as $key => $value) { // Show field if not hidden if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && $extrafields->attributes["product_fournisseur_price"]['list'][$key] != 3) { - if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) $langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]); - if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) $extratitle = $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key])); - else $extratitle = $langs->trans($value); - if (!empty($arrayfields['ef.'.$key]['checked'])) print_liste_field_titre($extratitle, $_SERVER["PHP_SELF"], 'ef.'.$key, '', $param, '', $sortfield, $sortorder, 'right '); + if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) { + $langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]); + } + if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) { + $extratitle = $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key])); + } else { + $extratitle = $langs->trans($value); + } + if (!empty($arrayfields['ef.'.$key]['checked'])) { + print_liste_field_titre($extratitle, $_SERVER["PHP_SELF"], 'ef.'.$key, '', $param, '', $sortfield, $sortorder, 'right '); + } } } } - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('id_fourn'=>$id_fourn, 'prod_id'=>$object->id); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; - if (is_array($product_fourn_list)) - { - foreach ($product_fourn_list as $productfourn) - { + if (is_array($product_fourn_list)) { + foreach ($product_fourn_list as $productfourn) { print '<tr class="oddeven">'; // Date from @@ -987,8 +1027,7 @@ END; } // Availability - if (!empty($arrayfields['pfp.fk_availability']['checked'])) - { + if (!empty($arrayfields['pfp.fk_availability']['checked'])) { $form->load_cache_availability(); $availability = $form->cache_availability[$productfourn->fk_availability]['label']; print '<td class="left">'.$availability.'</td>'; @@ -1037,11 +1076,12 @@ END; if (!empty($arrayfields['pfp.multicurrency_unitprice']['checked'])) { print '<td class="right">'; print price($productfourn->fourn_multicurrency_unitprice); - print '</td>'; } + print '</td>'; + } // Currency if (!empty($conf->multicurrency->enabled)) { - print '<td class="right">'; + print '<td class="right nowraponall">'; print $productfourn->fourn_multicurrency_code ? currency_name($productfourn->fourn_multicurrency_code) : ''; print '</td>'; } @@ -1090,9 +1130,9 @@ END; print '</td>'; } - // Date + // Date modification if (!empty($arrayfields['pfp.tms']['checked'])) { - print '<td align="right">'; + print '<td class="right nowraponall">'; print dol_print_date(($productfourn->fourn_date_modification ? $productfourn->fourn_date_modification : $productfourn->date_modification), "dayhour"); print '</td>'; } @@ -1126,8 +1166,7 @@ END; } } - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('id_pfp'=>$productfourn->product_fourn_price_id, 'id_fourn'=>$id_fourn, 'prod_id'=>$object->id); $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); } @@ -1135,8 +1174,7 @@ END; // Modify-Remove print '<td class="center nowraponall">'; - if ($usercancreate) - { + if ($usercancreate) { print '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$productfourn->fourn_id.'&amp;action=update_price&amp;rowid='.$productfourn->product_fourn_price_id.'">'.img_edit()."</a>"; print ' &nbsp; '; print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$productfourn->fourn_id.'&amp;action=ask_remove_pf&amp;rowid='.$productfourn->product_fourn_price_id.'">'.img_picto($langs->trans("Remove"), 'delete').'</a>'; diff --git a/htdocs/product/index.php b/htdocs/product/index.php index 9c9852b22ef..9cdbe85cf4b 100644 --- a/htdocs/product/index.php +++ b/htdocs/product/index.php @@ -5,7 +5,7 @@ * Copyright (C) 2014-2016 Charlie BENKE <charlie@patas-monkey.com> * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr> * Copyright (C) 2019 Pierre Ardoin <mapiolca@me.com> - * Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr> * Copyright (C) 2019 Nicolas ZABOURI <info@inovea-conseil.com> * * This program is free software; you can redistribute it and/or modify @@ -34,13 +34,21 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; $type = GETPOST("type", 'int'); -if ($type == '' && !$user->rights->produit->lire) $type = '1'; // Force global page on service page only -if ($type == '' && !$user->rights->service->lire) $type = '0'; // Force global page on product page only +if ($type == '' && !$user->rights->produit->lire) { + $type = '1'; // Force global page on service page only +} +if ($type == '' && !$user->rights->service->lire) { + $type = '0'; // Force global page on product page only +} // Security check -if ($type == '0') $result = restrictedArea($user, 'produit'); -elseif ($type == '1') $result = restrictedArea($user, 'service'); -else $result = restrictedArea($user, 'produit|service|expedition'); +if ($type == '0') { + $result = restrictedArea($user, 'produit'); +} elseif ($type == '1') { + $result = restrictedArea($user, 'service'); +} else { + $result = restrictedArea($user, 'produit|service|expedition'); +} // Load translation files required by the page $langs->loadLangs(array('products', 'stocks')); @@ -58,18 +66,15 @@ $product_static = new Product($db); $transAreaType = $langs->trans("ProductsAndServicesArea"); $helpurl = ''; -if (!isset($_GET["type"])) -{ +if (!isset($_GET["type"])) { $transAreaType = $langs->trans("ProductsAndServicesArea"); $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; } -if ((isset($_GET["type"]) && $_GET["type"] == 0) || empty($conf->service->enabled)) -{ +if ((isset($_GET["type"]) && $_GET["type"] == 0) || empty($conf->service->enabled)) { $transAreaType = $langs->trans("ProductsArea"); $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; } -if ((isset($_GET["type"]) && $_GET["type"] == 1) || empty($conf->product->enabled)) -{ +if ((isset($_GET["type"]) && $_GET["type"] == 1) || empty($conf->product->enabled)) { $transAreaType = $langs->trans("ServicesArea"); $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; } @@ -83,27 +88,27 @@ print load_fiche_titre($transAreaType, $linkback, 'product'); print '<div class="fichecenter"><div class="fichethirdleft">'; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo // Search contract - if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) - { + if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) { $listofsearchfields['search_product'] = array('text'=>'ProductOrService'); } - if (count($listofsearchfields)) - { + if (count($listofsearchfields)) { print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<div class="div-table-responsive-no-min">'; print '<table class="noborder nohover centpercent">'; $i = 0; - foreach ($listofsearchfields as $key => $value) - { - if ($i == 0) print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>'; + foreach ($listofsearchfields as $key => $value) { + if ($i == 0) { + print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>'; + } print '<tr class="oddeven">'; print '<td class="nowrap"><label for="'.$key.'">'.$langs->trans($value["text"]).'</label></td><td><input type="text" class="flat inputsearch" name="'.$key.'" id="'.$key.'" size="18"></td>'; - if ($i == 0) print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>'; + if ($i == 0) { + print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>'; + } print '</tr>'; $i++; } @@ -117,11 +122,16 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useles /* * Number of products and/or services */ -if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) -{ +if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) { $prodser = array(); $prodser[0][0] = $prodser[0][1] = $prodser[0][2] = $prodser[0][3] = 0; + $prodser[0]['sell'] = 0; + $prodser[0]['buy'] = 0; + $prodser[0]['none'] = 0; $prodser[1][0] = $prodser[1][1] = $prodser[1][2] = $prodser[1][3] = 0; + $prodser[1]['sell'] = 0; + $prodser[1]['buy'] = 0; + $prodser[1]['none'] = 0; $sql = "SELECT COUNT(p.rowid) as total, p.fk_product_type, p.tosell, p.tobuy"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; @@ -132,20 +142,30 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us $sql .= $hookmanager->resPrint; $sql .= " GROUP BY p.fk_product_type, p.tosell, p.tobuy"; $result = $db->query($sql); - while ($objp = $db->fetch_object($result)) - { + while ($objp = $db->fetch_object($result)) { $status = 3; // On sale + On purchase - if (!$objp->tosell && !$objp->tobuy) $status = 0; // Not on sale, not on purchase - if ($objp->tosell && !$objp->tobuy) $status = 1; // On sale only - if (!$objp->tosell && $objp->tobuy) $status = 2; // On purchase only + if (!$objp->tosell && !$objp->tobuy) { + $status = 0; // Not on sale, not on purchase + } + if ($objp->tosell && !$objp->tobuy) { + $status = 1; // On sale only + } + if (!$objp->tosell && $objp->tobuy) { + $status = 2; // On purchase only + } $prodser[$objp->fk_product_type][$status] = $objp->total; - if ($objp->tosell) $prodser[$objp->fk_product_type]['sell'] += $objp->total; - if ($objp->tobuy) $prodser[$objp->fk_product_type]['buy'] += $objp->total; - if (!$objp->tosell && !$objp->tobuy) $prodser[$objp->fk_product_type]['none'] += $objp->total; + if ($objp->tosell) { + $prodser[$objp->fk_product_type]['sell'] += $objp->total; + } + if ($objp->tobuy) { + $prodser[$objp->fk_product_type]['buy'] += $objp->total; + } + if (!$objp->tosell && !$objp->tobuy) { + $prodser[$objp->fk_product_type]['none'] += $objp->total; + } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><th>'.$langs->trans("Statistics").'</th></tr>'; @@ -164,14 +184,12 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us $total = $SommeA + $SommeB + $SommeC + $SommeD + $SommeE + $SommeF; $dataseries = array(); - if (!empty($conf->product->enabled)) - { + if (!empty($conf->product->enabled)) { $dataseries[] = array($langs->transnoentitiesnoconv("ProductsOnSale"), round($SommeA)); $dataseries[] = array($langs->transnoentitiesnoconv("ProductsOnPurchase"), round($SommeB)); $dataseries[] = array($langs->transnoentitiesnoconv("ProductsNotOnSell"), round($SommeC)); } - if (!empty($conf->service->enabled)) - { + if (!empty($conf->service->enabled)) { $dataseries[] = array($langs->transnoentitiesnoconv("ServicesOnSale"), round($SommeD)); $dataseries[] = array($langs->transnoentitiesnoconv("ServicesOnPurchase"), round($SommeE)); $dataseries[] = array($langs->transnoentitiesnoconv("ServicesNotOnSell"), round($SommeF)); @@ -193,14 +211,13 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us } -if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTATS_ON_PRODUCTS)) -{ +if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTATS_ON_PRODUCTS)) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; print '<br>'; print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Categories").'</th></tr>'; - print '<tr class="oddeven"><td class="center" colspan="2">'; + print '<tr><td class="center" colspan="2">'; $sql = "SELECT c.label, count(*) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."categorie_product as cs"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie as c ON cs.fk_categorie = c.rowid"; @@ -209,20 +226,16 @@ if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTA $sql .= " GROUP BY c.label"; $total = 0; $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $i = 0; - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { $dataseries = array(); $rest = 0; $nbmax = 10; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); - if ($i < $nbmax) - { + if ($i < $nbmax) { $dataseries[] = array($obj->label, round($obj->nb)); } else { $rest += $obj->nb; @@ -230,8 +243,7 @@ if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTA $total += $obj->nb; $i++; } - if ($i > $nbmax) - { + if ($i > $nbmax) { $dataseries[] = array($langs->trans("Other"), round($rest)); } @@ -245,8 +257,7 @@ if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTA $dolgraph->draw('idstatscategproduct'); print $dolgraph->show($total ? 0 : 1); } else { - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); print '<tr><td>'.$obj->label.'</td><td>'.$obj->nb.'</td></tr>'; @@ -268,15 +279,16 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; /* * Latest modified products */ -if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) -{ +if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) { $max = 15; $sql = "SELECT p.rowid, p.label, p.price, p.ref, p.fk_product_type, p.tosell, p.tobuy, p.tobatch, p.fk_price_expression,"; $sql .= " p.entity,"; $sql .= " p.tms as datem"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " WHERE p.entity IN (".getEntity($product_static->element, 1).")"; - if ($type != '') $sql .= " AND p.fk_product_type = ".$type; + if ($type != '') { + $sql .= " AND p.fk_product_type = ".$type; + } // Add where from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook @@ -286,30 +298,33 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us //print $sql; $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $i = 0; - if ($num > 0) - { + if ($num > 0) { $transRecordedType = $langs->trans("LastModifiedProductsAndServices", $max); - if (isset($_GET["type"]) && $_GET["type"] == 0) $transRecordedType = $langs->trans("LastRecordedProducts", $max); - if (isset($_GET["type"]) && $_GET["type"] == 1) $transRecordedType = $langs->trans("LastRecordedServices", $max); + if (isset($_GET["type"]) && $_GET["type"] == 0) { + $transRecordedType = $langs->trans("LastRecordedProducts", $max); + } + if (isset($_GET["type"]) && $_GET["type"] == 1) { + $transRecordedType = $langs->trans("LastRecordedServices", $max); + } print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; $colnb = 2; - if (empty($conf->global->PRODUIT_MULTIPRICES)) $colnb++; + if (empty($conf->global->PRODUIT_MULTIPRICES)) { + $colnb++; + } print '<tr class="liste_titre"><th colspan="'.$colnb.'">'.$transRecordedType.'</th>'; print '<th class="right" colspan="3"><a href="'.DOL_URL_ROOT.'/product/list.php?sortfield=p.tms&sortorder=DESC">'.$langs->trans("FullList").'</td>'; print '</tr>'; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($result); $product_static->id = $objp->rowid; @@ -322,18 +337,18 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us $product_static->status_batch = $objp->tobatch; //Multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { $sql = "SELECT label"; $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sql .= " WHERE fk_product=".$objp->rowid; $sql .= " AND lang='".$db->escape($langs->getDefaultLang())."'"; $resultd = $db->query($sql); - if ($resultd) - { + if ($resultd) { $objtp = $db->fetch_object($resultd); - if ($objtp && $objtp->label != '') $objp->label = $objtp->label; + if ($objtp && $objtp->label != '') { + $objp->label = $objtp->label; + } } } @@ -347,10 +362,8 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us print dol_print_date($db->jdate($objp->datem), 'day'); print "</td>"; // Sell price - if (empty($conf->global->PRODUIT_MULTIPRICES)) - { - if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) - { + if (empty($conf->global->PRODUIT_MULTIPRICES)) { + if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) { $product = new Product($db); $product->fetch($objp->rowid); $priceparser = new PriceParser($db); @@ -360,8 +373,11 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us } } print '<td class="nowrap right">'; - if (isset($objp->price_base_type) && $objp->price_base_type == 'TTC') print price($objp->price_ttc).' '.$langs->trans("TTC"); - else print price($objp->price).' '.$langs->trans("HT"); + if (isset($objp->price_base_type) && $objp->price_base_type == 'TTC') { + print price($objp->price_ttc).' '.$langs->trans("TTC"); + } else { + print price($objp->price).' '.$langs->trans("HT"); + } print '</td>'; } print '<td class="right nowrap width25"><span class="statusrefsell">'; @@ -389,10 +405,13 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us // TODO Move this into a page that should be available into menu "accountancy - report - turnover - per quarter" // Also method used for counting must provide the 2 possible methods like done by all other reports into menu "accountancy - report - turnover": // "commitment engagment" method and "cash accounting" method -if (!empty($conf->global->MAIN_SHOW_PRODUCT_ACTIVITY_TRIM)) -{ - if (!empty($conf->product->enabled)) activitytrim(0); - if (!empty($conf->service->enabled)) activitytrim(1); +if (!empty($conf->global->MAIN_SHOW_PRODUCT_ACTIVITY_TRIM)) { + if (!empty($conf->product->enabled)) { + activitytrim(0); + } + if (!empty($conf->service->enabled)) { + activitytrim(1); + } } @@ -433,8 +452,7 @@ function activitytrim($product_type) $sql .= " ORDER BY annee, mois "; $result = $db->query($sql); - if ($result) - { + if ($result) { $tmpyear = 0; $trim1 = 0; $trim2 = 0; @@ -443,14 +461,15 @@ function activitytrim($product_type) $lgn = 0; $num = $db->num_rows($result); - if ($num > 0) - { + if ($num > 0) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder" width="75%">'; - if ($product_type == 0) + if ($product_type == 0) { print '<tr class="liste_titre"><td class=left>'.$langs->trans("ProductSellByQuarterHT").'</td>'; - else print '<tr class="liste_titre"><td class=left>'.$langs->trans("ServiceSellByQuarterHT").'</td>'; + } else { + print '<tr class="liste_titre"><td class=left>'.$langs->trans("ServiceSellByQuarterHT").'</td>'; + } print '<td class=right>'.$langs->trans("Quarter1").'</td>'; print '<td class=right>'.$langs->trans("Quarter2").'</td>'; print '<td class=right>'.$langs->trans("Quarter3").'</td>'; @@ -460,13 +479,10 @@ function activitytrim($product_type) } $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($result); - if ($tmpyear != $objp->annee) - { - if ($trim1 + $trim2 + $trim3 + $trim4 > 0) - { + if ($tmpyear != $objp->annee) { + if ($trim1 + $trim2 + $trim3 + $trim4 > 0) { print '<tr class="oddeven"><td class=left>'.$tmpyear.'</td>'; print '<td class="nowrap right">'.price($trim1).'</td>'; print '<td class="nowrap right">'.price($trim2).'</td>'; @@ -484,22 +500,25 @@ function activitytrim($product_type) $trim4 = 0; } - if ($objp->mois == "01" || $objp->mois == "02" || $objp->mois == "03") + if ($objp->mois == "01" || $objp->mois == "02" || $objp->mois == "03") { $trim1 += $objp->Mnttot; + } - if ($objp->mois == "04" || $objp->mois == "05" || $objp->mois == "06") + if ($objp->mois == "04" || $objp->mois == "05" || $objp->mois == "06") { $trim2 += $objp->Mnttot; + } - if ($objp->mois == "07" || $objp->mois == "08" || $objp->mois == "09") + if ($objp->mois == "07" || $objp->mois == "08" || $objp->mois == "09") { $trim3 += $objp->Mnttot; + } - if ($objp->mois == "10" || $objp->mois == "11" || $objp->mois == "12") + if ($objp->mois == "10" || $objp->mois == "11" || $objp->mois == "12") { $trim4 += $objp->Mnttot; + } $i++; } - if ($trim1 + $trim2 + $trim3 + $trim4 > 0) - { + if ($trim1 + $trim2 + $trim3 + $trim4 > 0) { print '<tr class="oddeven"><td class=left>'.$tmpyear.'</td>'; print '<td class="nowrap right">'.price($trim1).'</td>'; print '<td class="nowrap right">'.price($trim2).'</td>'; @@ -508,7 +527,8 @@ function activitytrim($product_type) print '<td class="nowrap right">'.price($trim1 + $trim2 + $trim3 + $trim4).'</td>'; print '</tr>'; } - if ($num > 0) + if ($num > 0) { print '</table></div>'; + } } } diff --git a/htdocs/product/inventory/ajax/ajax.inventory.php b/htdocs/product/inventory/ajax/ajax.inventory.php index 85dd488df6f..920607f4c1e 100644 --- a/htdocs/product/inventory/ajax/ajax.inventory.php +++ b/htdocs/product/inventory/ajax/ajax.inventory.php @@ -6,16 +6,16 @@ require_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php'; $get = GETPOST('get', 'alpha'); $put = GETPOST('put', 'alpha'); -switch ($put) -{ +switch ($put) { case 'qty': - if (empty($user->rights->stock->creer)) { echo -1; exit; } + if (empty($user->rights->stock->creer)) { + echo -1; exit; + } $fk_det_inventory = GETPOST('fk_det_inventory'); $det = new InventoryLine($db); - if ($det->fetch($fk_det_inventory)) - { + if ($det->fetch($fk_det_inventory)) { $det->qty_view += GETPOST('qty'); $res = $det->update($user); @@ -27,13 +27,14 @@ switch ($put) break; case 'pmp': - if (empty($user->rights->stock->creer) || empty($user->rights->stock->changePMP)) { echo -1; exit; } + if (empty($user->rights->stock->creer) || empty($user->rights->stock->changePMP)) { + echo -1; exit; + } $fk_det_inventory = GETPOST('fk_det_inventory'); $det = new InventoryLine($db); - if ($det->fetch($fk_det_inventory)) - { + if ($det->fetch($fk_det_inventory)) { $det->new_pmp = price2num(GETPOST('pmp')); $det->update($user); diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php index 425dd3622e3..92ad4c2176b 100644 --- a/htdocs/product/inventory/card.php +++ b/htdocs/product/inventory/card.php @@ -40,8 +40,7 @@ $cancel = GETPOST('cancel', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'inventorycard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); -if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $result = restrictedArea($user, 'stock', $id); } else { $result = restrictedArea($user, 'stock', $id, '', 'inventory_advance'); @@ -61,12 +60,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. @@ -76,8 +78,7 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ //if ($user->socid > 0) $socid = $user->socid; //$result = restrictedArea($user, 'mymodule', $id); -if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $permissiontoread = $user->rights->stock->lire; $permissiontoadd = $user->rights->stock->creer; $permissiontodelete = $user->rights->stock->supprimer; @@ -100,18 +101,22 @@ if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) $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 (empty($reshook)) { $error = 0; $backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php'; if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = dol_buildpath('/product/inventory/card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('/product/inventory/card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + } } } $triggermodname = 'STOCK_INVENTORY_MODIFY'; // Name of trigger action code to execute when we modify record @@ -135,8 +140,7 @@ if (empty($reshook)) { $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MYOBJECT_MODIFY'); }*/ - if ($action == 'classin' && $permissiontoadd) - { + if ($action == 'classin' && $permissiontoadd) { $object->setProject(GETPOST('projectid', 'int')); } @@ -159,7 +163,9 @@ $formfile = new FormFile($db); $formproject = new FormProjets($db); $title = $langs->trans("Inventory"); -$help_url = ''; + +$help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks|DE:Modul_Bestände'; + llxHeader('', $title, $help_url); // Example : Adding jquery code @@ -179,15 +185,18 @@ jQuery(document).ready(function() { // Part to create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewInventory"), '', 'product'); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } print dol_get_fiche_head(array(), ''); @@ -218,16 +227,19 @@ if ($action == 'create') } // Part to edit record -if (($id || $ref) && $action == 'edit') -{ +if (($id || $ref) && $action == 'edit') { print load_fiche_titre($langs->trans("Inventory"), '', 'product'); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } print dol_get_fiche_head(); @@ -251,8 +263,7 @@ if (($id || $ref) && $action == 'edit') } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_optionals(); $head = inventoryPrepareHead($object); @@ -277,8 +288,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Confirmation of action xxxx - if ($action == 'xxx') - { + if ($action == 'xxx') { $formquestion = array(); /* $forcecombo=0; @@ -296,8 +306,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -317,34 +330,34 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='<br>'.$langs->trans('Project') . ' '; - if ($permissiontoadd) - { - if ($action != 'classify') - { - $morehtmlref .= '<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; - if ($action == 'classify') { - //$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; - $morehtmlref .= '<input type="hidden" name="action" value="classin">'; - $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; - $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; - $morehtmlref .= '</form>'; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref .= $proj->getNomUrl(); - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='<br>'.$langs->trans('Project') . ' '; + if ($permissiontoadd) + { + if ($action != 'classify') + { + $morehtmlref .= '<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; + if ($action == 'classify') { + //$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref .= '<input type="hidden" name="action" value="classin">'; + $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref .= '</form>'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= $proj->getNomUrl(); + } else { + $morehtmlref.=''; + } + } } */ $morehtmlref .= '</div>'; @@ -378,29 +391,26 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<div class="tabsAction">'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Send if (empty($user->socid)) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>'."\n"; } // Back to draft - if ($object->status == $object::STATUS_VALIDATED) - { - if ($permissiontoadd) - { + if ($object->status == $object::STATUS_VALIDATED) { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes">'.$langs->trans("SetToDraft").'</a>'; } } // Modify - if ($object->status == $object::STATUS_DRAFT) - { - if ($permissiontoadd) - { + if ($object->status == $object::STATUS_DRAFT) { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit">'.$langs->trans("Modify").'</a>'."\n"; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n"; @@ -408,23 +418,20 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Validate - if ($object->status == $object::STATUS_DRAFT) - { - if ($permissiontoadd) - { + if ($object->status == $object::STATUS_DRAFT) { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes">'.$langs->trans("Validate").' ('.$langs->trans("Start").')</a>'; } } // Clone /*if ($permissiontoadd) - { - print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->socid.'&action=clone&object=myobject">'.$langs->trans("ToClone").'</a>'."\n"; - }*/ + { + print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->socid.'&action=clone&object=myobject">'.$langs->trans("ToClone").'</a>'."\n"; + }*/ // Delete (need delete permission, or if draft, just need create/modify permission) - if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) - { + if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n"; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n"; @@ -439,8 +446,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre @@ -478,7 +484,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea //Select mail models is same action as presend - if (GETPOST('modelselected')) $action = 'presend'; + if (GETPOST('modelselected')) { + $action = 'presend'; + } // Presend form $modelmail = 'inventory'; diff --git a/htdocs/product/inventory/class/inventory.class.php b/htdocs/product/inventory/class/inventory.class.php index 47d9425530f..ce585c51a10 100644 --- a/htdocs/product/inventory/class/inventory.class.php +++ b/htdocs/product/inventory/class/inventory.class.php @@ -57,7 +57,7 @@ class Inventory extends CommonObject /** * @var string String with name of icon for inventory */ - public $picto = 'stock'; + public $picto = 'inventory'; const STATUS_DRAFT = 0; const STATUS_VALIDATED = 1; @@ -222,8 +222,12 @@ class Inventory extends CommonObject $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled)) { + $this->fields['entity']['enabled'] = 0; + } } @@ -272,20 +276,24 @@ class Inventory extends CommonObject $sql .= ' '.MAIN_DB_PREFIX.'product as p, '.MAIN_DB_PREFIX.'entrepot as e'; $sql .= ' WHERE p.entity IN ('.getEntity('product').')'; $sql .= ' AND ps.fk_product = p.rowid AND ps.fk_entrepot = e.rowid'; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= " AND p.fk_product_type = 0"; - if ($this->fk_product > 0) $sql .= ' AND ps.fk_product = '.$this->fk_product; - if ($this->fk_warehouse > 0) $sql .= ' AND ps.fk_entrepot = '.$this->fk_warehouse; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $sql .= " AND p.fk_product_type = 0"; + } + if ($this->fk_product > 0) { + $sql .= ' AND ps.fk_product = '.$this->fk_product; + } + if ($this->fk_warehouse > 0) { + $sql .= ' AND ps.fk_entrepot = '.$this->fk_warehouse; + } $inventoryline = new InventoryLine($this->db); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $inventoryline->fk_inventory = $this->id; @@ -464,8 +472,7 @@ class Inventory extends CommonObject */ public function deleteLine(User $user, $idline, $notrigger = false) { - if ($this->status < 0) - { + if ($this->status < 0) { $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; return -2; } @@ -489,7 +496,9 @@ class Inventory extends CommonObject global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; $companylink = ''; @@ -501,24 +510,28 @@ class Inventory extends CommonObject $url = dol_buildpath('/product/inventory/card.php', 1).'?id='.$this->id; $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowInventory"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = '<a href="'.$url.'"'; $linkstart .= $linkclose.'>'; $linkend = '</a>'; $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -571,30 +584,25 @@ class Inventory 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; diff --git a/htdocs/product/inventory/inventory.php b/htdocs/product/inventory/inventory.php index d5c9ec4966b..dea3b46c946 100644 --- a/htdocs/product/inventory/inventory.php +++ b/htdocs/product/inventory/inventory.php @@ -45,8 +45,7 @@ $fk_product = GETPOST('fk_product', 'int'); $lineid = GETPOST('lineid', 'int'); $batch = GETPOST('batch', 'alphanohtml'); -if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $result = restrictedArea($user, 'stock', $id); } else { $result = restrictedArea($user, 'stock', $id, '', 'inventory_advance'); @@ -66,12 +65,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. @@ -81,8 +83,7 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ //if ($user->socid > 0) $socid = $user->socid; //$result = restrictedArea($user, 'mymodule', $id); -if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $permissiontoadd = $user->rights->stock->creer; $permissiontodelete = $user->rights->stock->supprimer; } else { @@ -99,10 +100,11 @@ $now = dol_now(); $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 (empty($reshook)) { $error = 0; $backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php'; @@ -197,8 +199,7 @@ jQuery(document).ready(function() { // Part to show record -if ($object->id > 0) -{ +if ($object->id > 0) { $res = $object->fetch_optionals(); $head = inventoryPrepareHead($object); @@ -211,8 +212,7 @@ if ($object->id > 0) $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteInventory'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line - if ($action == 'deleteline') - { + if ($action == 'deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); } @@ -226,8 +226,11 @@ if ($object->id > 0) // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -247,34 +250,34 @@ if ($object->id > 0) // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='<br>'.$langs->trans('Project') . ' '; - if ($user->rights->inventory->creer) - { - if ($action != 'classify') - { - $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; - $morehtmlref.='<input type="hidden" name="action" value="classin">'; - $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; - $morehtmlref.='</form>'; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=$proj->getNomUrl(); - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='<br>'.$langs->trans('Project') . ' '; + if ($user->rights->inventory->creer) + { + if ($action != 'classify') + { + $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref.='<input type="hidden" name="action" value="classin">'; + $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref.='</form>'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=$proj->getNomUrl(); + } else { + $morehtmlref.=''; + } + } } */ $morehtmlref .= '</div>'; @@ -309,7 +312,9 @@ if ($object->id > 0) print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } print '<div class="center">'; print '<span class="opacitymedium">'.$langs->trans("InventoryDesc").'</span><br>'; @@ -323,31 +328,28 @@ if ($object->id > 0) print '<div class="tabsAction">'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { - if ($object->status == Inventory::STATUS_DRAFT) - { - if ($permissiontoadd) - { + if (empty($reshook)) { + if ($object->status == Inventory::STATUS_DRAFT) { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_validate&confirm=yes">'.$langs->trans("Validate").' ('.$langs->trans("Start").')</a>'."\n"; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Validate').' ('.$langs->trans("Start").')</a>'."\n"; } } - if ($object->status == Inventory::STATUS_VALIDATED) - { - if ($permissiontoadd) - { + if ($object->status == Inventory::STATUS_VALIDATED) { + if ($permissiontoadd) { /* - if (!empty($conf->barcode->enabled)) { - print '<a href="#" class="butAction">'.$langs->trans("UpdateByScaningProductBarcode").'</a>'; - } - if (!empty($conf->productbatch->enabled)) { - print '<a href="#" class="butAction">'.$langs->trans('UpdateByScaningLot').'</a>'; - }*/ + if (!empty($conf->barcode->enabled)) { + print '<a href="#" class="butAction">'.$langs->trans("UpdateByScaningProductBarcode").'</a>'; + } + if (!empty($conf->productbatch->enabled)) { + print '<a href="#" class="butAction">'.$langs->trans('UpdateByScaningLot').'</a>'; + }*/ if (!empty($conf->barcode->enabled) || !empty($conf->productbatch->enabled)) { print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=updatebyscaning" class="butAction">'.$langs->trans("UpdateByScaning").'</a>'; } @@ -356,10 +358,8 @@ if ($object->id > 0) } } - if ($object->status == Inventory::STATUS_VALIDATED) - { - if ($permissiontoadd) - { + if ($object->status == Inventory::STATUS_VALIDATED) { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=record">'.$langs->trans("Finish").'</a>'."\n"; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Finish').'</a>'."\n"; @@ -367,16 +367,16 @@ if ($object->id > 0) } /*if ($object->status == Inventory::STATUS_VALIDATED) - { - if ($permissiontoadd) - { - print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("RecordVerb").'</a>'."\n"; - } - else - { - print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('RecordVerb').'</a>'."\n"; - } - }*/ + { + if ($permissiontoadd) + { + print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("RecordVerb").'</a>'."\n"; + } + else + { + print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('RecordVerb').'</a>'."\n"; + } + }*/ } print '</div>'."\n"; } @@ -394,7 +394,9 @@ if ($object->id > 0) print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="updateinventorylines">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } print '<div class="fichecenter">'; //print '<div class="fichehalfleft">'; @@ -423,7 +425,6 @@ if ($object->id > 0) print '</tr>'; // Line to add a new line in inventory - //if ($action == 'addline') { if ($object->status == $object::STATUS_VALIDATED) { print '<tr>'; print '<td>'; @@ -459,14 +460,12 @@ if ($object->id > 0) //$sql = ''; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; $totalarray = array(); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); if (is_object($cacheOfWarehouses[$obj->fk_warehouse])) { diff --git a/htdocs/product/inventory/list.php b/htdocs/product/inventory/list.php index 747abda86b8..3585b84547f 100644 --- a/htdocs/product/inventory/list.php +++ b/htdocs/product/inventory/list.php @@ -48,7 +48,9 @@ $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; @@ -63,18 +65,20 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Security check $socid = 0; -if ($user->socid > 0) // Protection if external user -{ +if ($user->socid > 0) { // Protection if external user //$socid = $user->socid; accessforbidden(); } -if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $result = restrictedArea($user, 'stock', $objectid); } else { $result = restrictedArea($user, 'stock', $objectid, '', 'inventory_advance'); @@ -83,30 +87,31 @@ if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of fields for list $arrayfields = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field - if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); + if (!empty($val['visible'])) { + $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); + } } // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], @@ -129,31 +134,33 @@ $permissiontodelete = $user->rights->stock->supprimer; * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($object->fields as $key => $val) - { + 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 + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $toselect = ''; $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -182,13 +189,14 @@ $title = $langs->trans('ListOfInventories'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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.', ' : ''); + 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(); @@ -196,20 +204,32 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -else $sql .= " WHERE 1 = 1"; -foreach ($search as $key => $val) -{ - if ($key == 'status' && $search[$key] == -1) continue; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); if (strpos($object->fields[$key]['type'], 'integer:') === 0) { - if ($search[$key] == '-1') $search[$key] = ''; + if ($search[$key] == '-1') { + $search[$key] = ''; + } $mode_search = 2; } - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -222,7 +242,7 @@ $sql .= $hookmanager->resPrint; $sql.= " GROUP BY " foreach($object->fields as $key => $val) { - $sql.='t.'.$key.', '; + $sql.='t.'.$key.', '; } // Add fields from extrafields if (! empty($extrafields->attributes[$object->table_element]['label'])) { @@ -239,26 +259,24 @@ $sql .= $db->order($sortfield, $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 || empty($limit))) -{ +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -267,8 +285,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/inventory/card.php?id='.$id); @@ -284,14 +301,24 @@ llxHeader('', $title, $help_url); $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ - if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); - else $param .= '&search_'.$key.'='.urlencode($search[$key]); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +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'; @@ -302,12 +329,18 @@ $arrayofmassactions = array( //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); -if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($permissiontodelete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -318,7 +351,7 @@ print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; $newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/product/inventory/card.php?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); -print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'product', 0, $newcardbutton, '', $limit); +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $object->picto, 0, $newcardbutton, '', $limit); // Add code for pre mass action (confirmation or email presend form) $topicmail = "Information"; @@ -327,9 +360,10 @@ $objecttmp = new Inventory($db); $trackid = 'stockinv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } @@ -340,11 +374,13 @@ $moreforfilter.= '</div>';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -361,20 +397,26 @@ print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : // Fields title search // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - elseif (strpos($val['type'], 'integer:') === 0) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { + print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } print '</td>'; } } @@ -396,15 +438,18 @@ print '</tr>'."\n"; // Fields title label // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -421,11 +466,11 @@ print '</tr>'."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -433,37 +478,50 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->setVarsFromFetchObj($obj); // Show here line of result print '<tr class="oddeven">'; - foreach ($object->fields as $key => $val) - { + foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>'; - if ($key == 'status') print $object->getLibStatut(5); - else print $object->showOutputField($val, $key, $object->$key, ''); + if ($key == 'status') { + print $object->getLibStatut(5); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $object->$key; } } @@ -476,14 +534,17 @@ while ($i < ($limit ? min($num, $limit) : $num)) print $hookmanager->resPrint; // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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($object->id, $arrayofselected)) $selected = 1; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'."\n"; @@ -495,10 +556,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } @@ -514,10 +578,11 @@ print '</div>'."\n"; print '</form>'."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/product/list.php b/htdocs/product/list.php index d081c07b2c8..b10e3aadcc8 100644 --- a/htdocs/product/list.php +++ b/htdocs/product/list.php @@ -41,12 +41,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; -if (!empty($conf->categorie->enabled)) +if (!empty($conf->categorie->enabled)) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('products', 'stocks', 'suppliers', 'companies', 'margins')); -if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); +if (!empty($conf->productbatch->enabled)) { + $langs->load("productbatch"); +} $action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); @@ -92,17 +95,31 @@ $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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $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 = "p.ref"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "p.ref"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Initialize context for list $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'productservicelist'; -if ((string) $type == '1') { $contextpage = 'servicelist'; if ($search_type == '') $search_type = '1'; } -if ((string) $type == '0') { $contextpage = 'productlist'; if ($search_type == '') $search_type = '0'; } +if ((string) $type == '1') { + $contextpage = 'servicelist'; if ($search_type == '') { + $search_type = '1'; + } +} +if ((string) $type == '0') { + $contextpage = 'productlist'; if ($search_type == '') { + $search_type = '0'; + } +} // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks $object = new Product($db); @@ -116,22 +133,27 @@ $formproduct = new FormProduct($db); $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); -if (empty($action)) $action = 'list'; +if (empty($action)) { + $action = 'list'; +} // Get object canvas (By default, this is not defined, so standard usage of dolibarr) $canvas = GETPOST("canvas"); $objcanvas = null; -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('product', 'list', $canvas); } // Security check -if ($search_type == '0') $result = restrictedArea($user, 'produit', '', '', '', '', '', 0); -elseif ($search_type == '1') $result = restrictedArea($user, 'service', '', '', '', '', '', 0); -else $result = restrictedArea($user, 'produit|service', '', '', '', '', '', 0); +if ($search_type == '0') { + $result = restrictedArea($user, 'produit', '', '', '', '', '', 0); +} elseif ($search_type == '1') { + $result = restrictedArea($user, 'service', '', '', '', '', '', 0); +} else { + $result = restrictedArea($user, 'produit|service', '', '', '', '', '', 0); +} // Define virtualdiffersfromphysical $virtualdiffersfromphysical = 0; @@ -140,8 +162,7 @@ if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE) - || !empty($conf->mrp->enabled)) -{ + || !empty($conf->mrp->enabled)) { $virtualdiffersfromphysical = 1; // According to increase/decrease stock options, virtual and physical stock may differs. } @@ -155,8 +176,7 @@ $fieldstosearchall = array( ); // multilang -if (!empty($conf->global->MAIN_MULTILANGS)) -{ +if (!empty($conf->global->MAIN_MULTILANGS)) { $fieldstosearchall['pl.label'] = 'ProductLabelTranslated'; $fieldstosearchall['pl.description'] = 'ProductDescriptionTranslated'; $fieldstosearchall['pl.note'] = 'ProductNoteTranslated'; @@ -166,13 +186,13 @@ if (!empty($conf->barcode->enabled)) { $fieldstosearchall['pfp.barcode'] = 'GencodBuyPrice'; } // Personalized search criterias. Example: $conf->global->PRODUCT_QUICKSEARCH_ON_FIELDS = 'p.ref=ProductRef;p.label=ProductLabel' -if (!empty($conf->global->PRODUCT_QUICKSEARCH_ON_FIELDS)) $fieldstosearchall = dolExplodeIntoArray($conf->global->PRODUCT_QUICKSEARCH_ON_FIELDS); +if (!empty($conf->global->PRODUCT_QUICKSEARCH_ON_FIELDS)) { + $fieldstosearchall = dolExplodeIntoArray($conf->global->PRODUCT_QUICKSEARCH_ON_FIELDS); +} -if (empty($conf->global->PRODUIT_MULTIPRICES)) -{ +if (empty($conf->global->PRODUIT_MULTIPRICES)) { $titlesellprice = $langs->trans("SellingPrice"); - if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) - { + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { $titlesellprice = $form->textwithpicto($langs->trans("SellingPrice"), $langs->trans("DefaultPriceRealPriceMayDependOnCustomer")); } } @@ -181,62 +201,61 @@ $isInEEC = isInEEC($mysoc); // Definition of fields for lists $arrayfields = array( - 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'p.ref'=>array('label'=>"Ref", 'checked'=>1), //'pfp.ref_fourn'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1, 'enabled'=>(! empty($conf->barcode->enabled))), - 'p.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1, 'position'=>10), - 'p.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->service->enabled)), 'position'=>11), - 'p.barcode'=>array('label'=>$langs->trans("Gencod"), 'checked'=>1, 'enabled'=>(!empty($conf->barcode->enabled)), 'position'=>12), - 'p.duration'=>array('label'=>$langs->trans("Duration"), 'checked'=>($contextpage != 'productlist'), 'enabled'=>(!empty($conf->service->enabled) && (string) $type == '1'), 'position'=>13), - 'p.finished'=>array('label'=>$langs->trans("Nature"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && $type != '1'), 'position'=>19), - 'p.weight'=>array('label'=>$langs->trans('Weight'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && $type != '1'), 'position'=>20), - 'p.weight_units'=>array('label'=>$langs->trans('WeightUnits'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && $type != '1'), 'position'=>21), - 'p.length'=>array('label'=>$langs->trans('Length'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>22), - 'p.length_units'=>array('label'=>$langs->trans('LengthUnits'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>23), - 'p.width'=>array('label'=>$langs->trans('Width'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>24), - 'p.width_units'=>array('label'=>$langs->trans('WidthUnits'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>25), - 'p.height'=>array('label'=>$langs->trans('Height'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>26), - 'p.height_units'=>array('label'=>$langs->trans('HeightUnits'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>27), - 'p.surface'=>array('label'=>$langs->trans('Surface'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SURFACE) && $type != '1'), 'position'=>28), - 'p.surface_units'=>array('label'=>$langs->trans('SurfaceUnits'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SURFACE) && $type != '1'), 'position'=>29), - 'p.volume'=>array('label'=>$langs->trans('Volume'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_VOLUME) && $type != '1'), 'position'=>30), - 'p.volume_units'=>array('label'=>$langs->trans('VolumeUnits'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_VOLUME) && $type != '1'), 'position'=>31), - 'cu.label'=>array('label'=>$langs->trans("DefaultUnitToShow"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->global->PRODUCT_USE_UNITS)), 'position'=>32), - 'p.sellprice'=>array('label'=>$langs->trans("SellingPrice"), 'checked'=>1, 'enabled'=>empty($conf->global->PRODUIT_MULTIPRICES), 'position'=>40), - 'p.tva_tx'=>array('label'=>$langs->trans("VATRate"), 'checked'=>0, 'enabled'=>empty($conf->global->PRODUIT_MULTIPRICES), 'position'=>41), - 'p.minbuyprice'=>array('label'=>$langs->trans("BuyingPriceMinShort"), 'checked'=>1, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>42), - 'p.numbuyprice'=>array('label'=>$langs->trans("BuyingPriceNumShort"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>43), - 'p.pmp'=>array('label'=>$langs->trans("PMPValueShort"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>44), - 'p.cost_price'=>array('label'=>$langs->trans("CostPrice"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>45), - 'p.seuil_stock_alerte'=>array('label'=>$langs->trans("StockLimit"), 'checked'=>0, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'), 'position'=>50), - 'p.desiredstock'=>array('label'=>$langs->trans("DesiredStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'), 'position'=>51), - 'p.stock'=>array('label'=>$langs->trans("PhysicalStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'), 'position'=>52), - 'stock_virtual'=>array('label'=>$langs->trans("VirtualStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service' && $virtualdiffersfromphysical), 'position'=>53), - 'p.tobatch'=>array('label'=>$langs->trans("ManageLotSerial"), 'checked'=>0, 'enabled'=>(!empty($conf->productbatch->enabled)), 'position'=>60), - 'p.fk_country'=>array('label'=>$langs->trans("Country"), 'checked'=>0, 'position'=>100), - 'p.fk_state'=>array('label'=>$langs->trans("State"), 'checked'=>0, 'position'=>101), - 'p.accountancy_code_sell'=>array('label'=>$langs->trans("ProductAccountancySellCode"), 'checked'=>0, 'position'=>400), - 'p.accountancy_code_sell_intra'=>array('label'=>$langs->trans("ProductAccountancySellIntraCode"), 'checked'=>0, 'enabled'=>$isInEEC, 'position'=>401), - 'p.accountancy_code_sell_export'=>array('label'=>$langs->trans("ProductAccountancySellExportCode"), 'checked'=>0, 'position'=>402), - 'p.accountancy_code_buy'=>array('label'=>$langs->trans("ProductAccountancyBuyCode"), 'checked'=>0, 'position'=>403), - 'p.accountancy_code_buy_intra'=>array('label'=>$langs->trans("ProductAccountancyBuyIntraCode"), 'checked'=>0, 'enabled'=>$isInEEC, 'position'=>404), - 'p.accountancy_code_buy_export'=>array('label'=>$langs->trans("ProductAccountancyBuyExportCode"), 'checked'=>0, 'position'=>405), - 'p.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'p.tosell'=>array('label'=>$langs->trans("Status").' ('.$langs->trans("Sell").')', 'checked'=>1, 'position'=>1000), - 'p.tobuy'=>array('label'=>$langs->trans("Status").' ('.$langs->trans("Buy").')', 'checked'=>1, 'position'=>1000) + 'p.label'=>array('label'=>"Label", 'checked'=>1, 'position'=>10), + 'p.fk_product_type'=>array('label'=>"Type", 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->service->enabled)), 'position'=>11), + 'p.barcode'=>array('label'=>"Gencod", 'checked'=>1, 'enabled'=>(!empty($conf->barcode->enabled)), 'position'=>12), + 'p.duration'=>array('label'=>"Duration", 'checked'=>($contextpage != 'productlist'), 'enabled'=>(!empty($conf->service->enabled) && (string) $type == '1'), 'position'=>13), + 'p.finished'=>array('label'=>"Nature", 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && $type != '1'), 'position'=>19), + 'p.weight'=>array('label'=>'Weight', 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && $type != '1'), 'position'=>20), + 'p.weight_units'=>array('label'=>'WeightUnits', 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && $type != '1'), 'position'=>21), + 'p.length'=>array('label'=>'Length', 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>22), + 'p.length_units'=>array('label'=>'LengthUnits', 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>23), + 'p.width'=>array('label'=>'Width', 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>24), + 'p.width_units'=>array('label'=>'WidthUnits', 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>25), + 'p.height'=>array('label'=>'Height', 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>26), + 'p.height_units'=>array('label'=>'HeightUnits', 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>27), + 'p.surface'=>array('label'=>'Surface', 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SURFACE) && $type != '1'), 'position'=>28), + 'p.surface_units'=>array('label'=>'SurfaceUnits', 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SURFACE) && $type != '1'), 'position'=>29), + 'p.volume'=>array('label'=>'Volume', 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_VOLUME) && $type != '1'), 'position'=>30), + 'p.volume_units'=>array('label'=>'VolumeUnits', 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_VOLUME) && $type != '1'), 'position'=>31), + 'cu.label'=>array('label'=>"DefaultUnitToShow", 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->global->PRODUCT_USE_UNITS)), 'position'=>32), + 'p.sellprice'=>array('label'=>"SellingPrice", 'checked'=>1, 'enabled'=>empty($conf->global->PRODUIT_MULTIPRICES), 'position'=>40), + 'p.tva_tx'=>array('label'=>"VATRate", 'checked'=>0, 'enabled'=>empty($conf->global->PRODUIT_MULTIPRICES), 'position'=>41), + 'p.minbuyprice'=>array('label'=>"BuyingPriceMinShort", 'checked'=>1, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>42), + 'p.numbuyprice'=>array('label'=>"BuyingPriceNumShort", 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>43), + 'p.pmp'=>array('label'=>"PMPValueShort", 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>44), + 'p.cost_price'=>array('label'=>"CostPrice", 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>45), + 'p.seuil_stock_alerte'=>array('label'=>"StockLimit", 'checked'=>0, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'), 'position'=>50), + 'p.desiredstock'=>array('label'=>"DesiredStock", 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'), 'position'=>51), + 'p.stock'=>array('label'=>"PhysicalStock", 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'), 'position'=>52), + 'stock_virtual'=>array('label'=>"VirtualStock", 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service' && $virtualdiffersfromphysical), 'position'=>53), + 'p.tobatch'=>array('label'=>"ManageLotSerial", 'checked'=>0, 'enabled'=>(!empty($conf->productbatch->enabled)), 'position'=>60), + 'p.fk_country'=>array('label'=>"Country", 'checked'=>0, 'position'=>100), + 'p.fk_state'=>array('label'=>"State", 'checked'=>0, 'position'=>101), + 'p.accountancy_code_sell'=>array('label'=>"ProductAccountancySellCode", 'checked'=>0, 'position'=>400), + 'p.accountancy_code_sell_intra'=>array('label'=>"ProductAccountancySellIntraCode", 'checked'=>0, 'enabled'=>$isInEEC, 'position'=>401), + 'p.accountancy_code_sell_export'=>array('label'=>"ProductAccountancySellExportCode", 'checked'=>0, 'position'=>402), + 'p.accountancy_code_buy'=>array('label'=>"ProductAccountancyBuyCode", 'checked'=>0, 'position'=>403), + 'p.accountancy_code_buy_intra'=>array('label'=>"ProductAccountancyBuyIntraCode", 'checked'=>0, 'enabled'=>$isInEEC, 'position'=>404), + 'p.accountancy_code_buy_export'=>array('label'=>"ProductAccountancyBuyExportCode", 'checked'=>0, 'position'=>405), + 'p.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500), + 'p.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), + 'p.tosell'=>array('label'=>$langs->transnoentitiesnoconv("Status").' ('.$langs->transnoentitiesnoconv("Sell").')', 'checked'=>1, 'position'=>1000), + 'p.tobuy'=>array('label'=>$langs->transnoentitiesnoconv("Status").' ('.$langs->transnoentitiesnoconv("Buy").')', 'checked'=>1, 'position'=>1000) ); // MultiPrices if ($conf->global->PRODUIT_MULTIPRICES) { - for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) - { + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i; if (!empty($conf->global->$keyforlabel)) { - $labelp = $i.' - '.$langs->trans($conf->global->$keyforlabel); + $labelp = $i.' - '.$langs->transnoentitiesnoconv($conf->global->$keyforlabel); } else { - $labelp = $langs->trans("SellingPrice")." ".$i; + $labelp = $langs->transnoentitiesnoconv("SellingPrice")." ".$i; } - $arrayfields['p.sellprice'.$i] = array('label'=>$labelp, 'checked'=>1, 'enabled'=>$conf->global->PRODUIT_MULTIPRICES, 'position'=>floatval('40.'.sprintf('%03s', $i))); + $arrayfields['p.sellprice'.$i] = array('label'=>$labelp, 'checked'=>($i == 1 ? 1 : 0), 'enabled'=>$conf->global->PRODUIT_MULTIPRICES, 'position'=>floatval('40.'.sprintf('%03s', $i))); $arraypricelevel[$i] = array($i); } } @@ -254,24 +273,30 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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'); +} $rightskey = 'produit'; -if ($type == Product::TYPE_SERVICE) $rightskey = 'service'; +if ($type == Product::TYPE_SERVICE) { + $rightskey = 'service'; +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 $sall = ""; $search_ref = ""; $search_label = ""; @@ -299,8 +324,12 @@ if (empty($reshook)) // Mass actions $objectclass = 'Product'; - if ((string) $search_type == '1') { $objectlabel = 'Services'; } - if ((string) $search_type == '0') { $objectlabel = 'Products'; } + if ((string) $search_type == '1') { + $objectlabel = 'Services'; + } + if ((string) $search_type == '0') { + $objectlabel = 'Products'; + } $permissiontoread = $user->rights->{$rightskey}->lire; $permissiontodelete = $user->rights->{$rightskey}->supprimer; @@ -316,10 +345,8 @@ if (empty($reshook)) $title = $langs->trans("ProductsAndServices"); -if ($search_type != '' && $search_type != '-1') -{ - if ($search_type == 1) - { +if ($search_type != '' && $search_type != '-1') { + if ($search_type == 1) { $texte = $langs->trans("Services"); } else { $texte = $langs->trans("Products"); @@ -334,55 +361,91 @@ $sql .= ' p.tobatch, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.a $sql .= ' p.accountancy_code_buy, p.accountancy_code_buy_intra, p.accountancy_code_buy_export,'; $sql .= ' p.datec as date_creation, p.tms as date_update, p.pmp, p.stock, p.cost_price,'; $sql .= ' p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units, fk_country, fk_state,'; -if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= ' p.fk_unit, cu.label as cu_label,'; +if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $sql .= ' p.fk_unit, cu.label as cu_label,'; +} $sql .= ' MIN(pfp.unitprice) as minsellprice'; if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && !$show_childproducts)) { $sql .= ', pac.rowid prod_comb_id'; } // 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 : ''); + 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 $sql .= $hookmanager->resPrint; $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_extrafields as ef on (p.rowid = ef.fk_object)"; -if (!empty($searchCategoryProductList) || !empty($catid)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product"; // We'll need this table joined to the select in order to filter by categ +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_extrafields as ef on (p.rowid = ef.fk_object)"; +} +if (!empty($searchCategoryProductList) || !empty($catid)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product"; // We'll need this table joined to the select in order to filter by categ +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; // multilang -if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang = '".$db->escape($langs->getDefaultLang())."'"; +if (!empty($conf->global->MAIN_MULTILANGS)) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang = '".$db->escape($langs->getDefaultLang())."'"; +} if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && !$show_childproducts)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid"; } -if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units cu ON cu.rowid = p.fk_unit"; +if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units cu ON cu.rowid = p.fk_unit"; +} $sql .= ' WHERE p.entity IN ('.getEntity('product').')'; -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} // if the type is not 1, we show all products (type = 0,2,3) -if (dol_strlen($search_type) && $search_type != '-1') -{ - if ($search_type == 1) $sql .= " AND p.fk_product_type = 1"; - else $sql .= " AND p.fk_product_type <> 1"; +if (dol_strlen($search_type) && $search_type != '-1') { + if ($search_type == 1) { + $sql .= " AND p.fk_product_type = 1"; + } else { + $sql .= " AND p.fk_product_type <> 1"; + } } if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && !$show_childproducts)) { $sql .= " AND pac.rowid IS NULL"; } -if ($search_ref) $sql .= natural_search('p.ref', $search_ref); -if ($search_label) $sql .= natural_search('p.label', $search_label); -if ($search_barcode) $sql .= natural_search('p.barcode', $search_barcode); -if (isset($search_tosell) && dol_strlen($search_tosell) > 0 && $search_tosell != -1) $sql .= " AND p.tosell = ".((int) $search_tosell); -if (isset($search_tobuy) && dol_strlen($search_tobuy) > 0 && $search_tobuy != -1) $sql .= " AND p.tobuy = ".((int) $search_tobuy); -if (isset($search_tobatch) && dol_strlen($search_tobatch) > 0 && $search_tobatch != -1) $sql .= " AND p.tobatch = ".((int) $search_tobatch); -if ($search_vatrate) $sql .= natural_search('p.tva_tx', $search_vatrate, 1); -if (dol_strlen($canvas) > 0) $sql .= " AND p.canvas = '".$db->escape($canvas)."'"; -if ($catid > 0) $sql .= " AND cp.fk_categorie = ".$catid; -if ($catid == -2) $sql .= " AND cp.fk_categorie IS NULL"; +if ($search_ref) { + $sql .= natural_search('p.ref', $search_ref); +} +if ($search_label) { + $sql .= natural_search('p.label', $search_label); +} +if ($search_barcode) { + $sql .= natural_search('p.barcode', $search_barcode); +} +if (isset($search_tosell) && dol_strlen($search_tosell) > 0 && $search_tosell != -1) { + $sql .= " AND p.tosell = ".((int) $search_tosell); +} +if (isset($search_tobuy) && dol_strlen($search_tobuy) > 0 && $search_tobuy != -1) { + $sql .= " AND p.tobuy = ".((int) $search_tobuy); +} +if (isset($search_tobatch) && dol_strlen($search_tobatch) > 0 && $search_tobatch != -1) { + $sql .= " AND p.tobatch = ".((int) $search_tobatch); +} +if ($search_vatrate) { + $sql .= natural_search('p.tva_tx', $search_vatrate, 1); +} +if (dol_strlen($canvas) > 0) { + $sql .= " AND p.canvas = '".$db->escape($canvas)."'"; +} +if ($catid > 0) { + $sql .= " AND cp.fk_categorie = ".$catid; +} +if ($catid == -2) { + $sql .= " AND cp.fk_categorie IS NULL"; +} $searchCategoryProductSqlList = array(); if ($searchCategoryProductOperator == 1) { foreach ($searchCategoryProductList as $searchCategoryProduct) { @@ -407,16 +470,36 @@ if ($searchCategoryProductOperator == 1) { $sql .= " AND (".implode(' AND ', $searchCategoryProductSqlList).")"; } } -if ($fourn_id > 0) $sql .= " AND pfp.fk_soc = ".((int) $fourn_id); -if ($search_country) $sql .= " AND p.fk_country = ".$search_country; -if ($search_state) $sql .= " AND p.fk_state = ".$search_state; -if ($search_finished >= 0 && $search_finished !== '') $sql .= " AND p.finished = ".$search_finished; -if ($search_accountancy_code_sell) $sql .= natural_search('p.accountancy_code_sell', $search_accountancy_code_sell); -if ($search_accountancy_code_sell_intra) $sql .= natural_search('p.accountancy_code_sell_intra', $search_accountancy_code_sell_intra); -if ($search_accountancy_code_sell_export) $sql .= natural_search('p.accountancy_code_sell_export', $search_accountancy_code_sell_export); -if ($search_accountancy_code_buy) $sql .= natural_search('p.accountancy_code_buy', $search_accountancy_code_buy); -if ($search_accountancy_code_buy_intra) $sql .= natural_search('p.accountancy_code_buy_intra', $search_accountancy_code_buy_intra); -if ($search_accountancy_code_buy_export) $sql .= natural_search('p.accountancy_code_buy_export', $search_accountancy_code_buy_export); +if ($fourn_id > 0) { + $sql .= " AND pfp.fk_soc = ".((int) $fourn_id); +} +if ($search_country) { + $sql .= " AND p.fk_country = ".$search_country; +} +if ($search_state) { + $sql .= " AND p.fk_state = ".$search_state; +} +if ($search_finished >= 0 && $search_finished !== '') { + $sql .= " AND p.finished = ".$search_finished; +} +if ($search_accountancy_code_sell) { + $sql .= natural_search('p.accountancy_code_sell', $search_accountancy_code_sell); +} +if ($search_accountancy_code_sell_intra) { + $sql .= natural_search('p.accountancy_code_sell_intra', $search_accountancy_code_sell_intra); +} +if ($search_accountancy_code_sell_export) { + $sql .= natural_search('p.accountancy_code_sell_export', $search_accountancy_code_sell_export); +} +if ($search_accountancy_code_buy) { + $sql .= natural_search('p.accountancy_code_buy', $search_accountancy_code_buy); +} +if ($search_accountancy_code_buy_intra) { + $sql .= natural_search('p.accountancy_code_buy_intra', $search_accountancy_code_buy_intra); +} +if ($search_accountancy_code_buy_export) { + $sql .= natural_search('p.accountancy_code_buy_export', $search_accountancy_code_buy_export); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -429,14 +512,18 @@ $sql .= " p.fk_product_type, p.duration, p.finished, p.tosell, p.tobuy, p.seuil_ $sql .= ' p.datec, p.tms, p.entity, p.tobatch, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export,'; $sql .= ' p.accountancy_code_buy, p.accountancy_code_buy_intra, p.accountancy_code_buy_export, p.pmp, p.cost_price, p.stock,'; $sql .= ' p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units, p.fk_country, p.fk_state'; -if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= ', p.fk_unit, cu.label'; +if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $sql .= ', p.fk_unit, cu.label'; +} if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && !$show_childproducts)) { $sql .= ', pac.rowid'; } // 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 : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key : ''); + } } // Add fields from hooks $parameters = array(); @@ -446,12 +533,10 @@ $sql .= $hookmanager->resPrint; $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -461,14 +546,12 @@ $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); - if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) - { + if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/product/card.php?id='.$id); @@ -476,22 +559,19 @@ if ($resql) } $helpurl = ''; - if ($search_type != '') - { - if ($search_type == 0) - { + if ($search_type != '') { + if ($search_type == 0) { $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; - } elseif ($search_type == 1) - { + } elseif ($search_type == 1) { $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; } } - foreach ($searchCategoryProductList as $searchCategoryProduct) { - $paramsCat .= "&search_category_product_list[]=".urlencode($searchCategoryProduct); - } - llxHeader('', $title, $helpurl, '', 0, 0, "", "", $paramsCat); + foreach ($searchCategoryProductList as $searchCategoryProduct) { + $paramsCat .= "&search_category_product_list[]=".urlencode($searchCategoryProduct); + } + llxHeader('', $title, $helpurl, '', 0, 0, array(), array(), $paramsCat, 'classforhorizontalscrolloftabs'); // Displays product removal confirmation if (GETPOST('delprod')) { @@ -499,36 +579,88 @@ if ($resql) } $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 ($searchCategoryProductOperator == 1) $param .= "&search_category_product_operator=".urlencode($searchCategoryProductOperator); + 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 ($searchCategoryProductOperator == 1) { + $param .= "&search_category_product_operator=".urlencode($searchCategoryProductOperator); + } foreach ($searchCategoryProductList as $searchCategoryProduct) { $param .= "&search_category_product_list[]=".urlencode($searchCategoryProduct); } - if ($search_ref) $param = "&search_ref=".urlencode($search_ref); - if ($search_ref_supplier) $param = "&search_ref_supplier=".urlencode($search_ref_supplier); - if ($search_barcode) $param .= ($search_barcode ? "&search_barcode=".urlencode($search_barcode) : ""); - if ($search_label) $param .= "&search_label=".urlencode($search_label); - if ($search_tosell != '') $param .= "&search_tosell=".urlencode($search_tosell); - if ($search_tobuy != '') $param .= "&search_tobuy=".urlencode($search_tobuy); - if ($search_tobatch) $param = "&search_tobatch=".urlencode($search_tobatch); - if ($search_country != '') $param .= "&search_country=".urlencode($search_country); - if ($search_state != '') $param .= "&search_state=".urlencode($search_state); - if ($search_vatrate) $param = "&search_vatrate=".urlencode($search_vatrate); - if ($fourn_id > 0) $param .= ($fourn_id ? "&fourn_id=".$fourn_id : ""); + if ($search_ref) { + $param = "&search_ref=".urlencode($search_ref); + } + if ($search_ref_supplier) { + $param = "&search_ref_supplier=".urlencode($search_ref_supplier); + } + if ($search_barcode) { + $param .= ($search_barcode ? "&search_barcode=".urlencode($search_barcode) : ""); + } + if ($search_label) { + $param .= "&search_label=".urlencode($search_label); + } + if ($search_tosell != '') { + $param .= "&search_tosell=".urlencode($search_tosell); + } + if ($search_tobuy != '') { + $param .= "&search_tobuy=".urlencode($search_tobuy); + } + if ($search_tobatch) { + $param = "&search_tobatch=".urlencode($search_tobatch); + } + if ($search_country != '') { + $param .= "&search_country=".urlencode($search_country); + } + if ($search_state != '') { + $param .= "&search_state=".urlencode($search_state); + } + if ($search_vatrate) { + $param = "&search_vatrate=".urlencode($search_vatrate); + } + if ($fourn_id > 0) { + $param .= ($fourn_id ? "&fourn_id=".$fourn_id : ""); + } //if ($seach_categ) $param.=($search_categ?"&search_categ=".urlencode($search_categ):""); - if ($show_childproducts) $param .= ($show_childproducts ? "&search_show_childproducts=".urlencode($show_childproducts) : ""); - if ($type != '') $param .= '&type='.urlencode($type); - if ($search_type != '') $param .= '&search_type='.urlencode($search_type); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($search_accountancy_code_sell) $param = "&search_accountancy_code_sell=".urlencode($search_accountancy_code_sell); - if ($search_accountancy_code_sell_intra) $param = "&search_accountancy_code_sell_intra=".urlencode($search_accountancy_code_sell_intra); - if ($search_accountancy_code_sell_export) $param = "&search_accountancy_code_sell_export=".urlencode($search_accountancy_code_sell_export); - if ($search_accountancy_code_buy) $param = "&search_accountancy_code_buy=".urlencode($search_accountancy_code_buy); - if ($search_accountancy_code_buy_intra) $param = "&search_accountancy_code_buy_intra=".urlencode($search_accountancy_code_buy_intra); - if ($search_accountancy_code_buy_export) $param = "&search_accountancy_code_buy_export=".urlencode($search_accountancy_code_buy_export); - if ($search_finished) $param = "&search_finished=".urlencode($search_finished); + if ($show_childproducts) { + $param .= ($show_childproducts ? "&search_show_childproducts=".urlencode($show_childproducts) : ""); + } + if ($type != '') { + $param .= '&type='.urlencode($type); + } + if ($search_type != '') { + $param .= '&search_type='.urlencode($search_type); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($search_accountancy_code_sell) { + $param = "&search_accountancy_code_sell=".urlencode($search_accountancy_code_sell); + } + if ($search_accountancy_code_sell_intra) { + $param = "&search_accountancy_code_sell_intra=".urlencode($search_accountancy_code_sell_intra); + } + if ($search_accountancy_code_sell_export) { + $param = "&search_accountancy_code_sell_export=".urlencode($search_accountancy_code_sell_export); + } + if ($search_accountancy_code_buy) { + $param = "&search_accountancy_code_buy=".urlencode($search_accountancy_code_buy); + } + if ($search_accountancy_code_buy_intra) { + $param = "&search_accountancy_code_buy_intra=".urlencode($search_accountancy_code_buy_intra); + } + if ($search_accountancy_code_buy_export) { + $param = "&search_accountancy_code_buy_export=".urlencode($search_accountancy_code_buy_export); + } + if ($search_finished) { + $param = "&search_finished=".urlencode($search_finished); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -539,30 +671,46 @@ if ($resql) //'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->{$rightskey}->supprimer) $arrayofmassactions['predelete'] = "<span class='fa fa-trash paddingrightonly'></span>".$langs->trans("Delete"); - if ($user->rights->{$rightskey}->creer) $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); - if (in_array($massaction, array('presend', 'predelete','preaffecttag'))) $arrayofmassactions = array(); + if ($user->rights->{$rightskey}->supprimer) { + $arrayofmassactions['predelete'] = "<span class='fa fa-trash paddingrightonly'></span>".$langs->trans("Delete"); + } + if ($user->rights->{$rightskey}->creer) { + $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); + } + if (in_array($massaction, array('presend', 'predelete','preaffecttag'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $newcardbutton = ''; - if ($type === "") $perm = ($user->rights->produit->creer || $user->rights->service->creer); - elseif ($type == Product::TYPE_SERVICE) $perm = $user->rights->service->creer; - elseif ($type == Product::TYPE_PRODUCT) $perm = $user->rights->produit->creer; + if ($type === "") { + $perm = ($user->rights->produit->creer || $user->rights->service->creer); + } elseif ($type == Product::TYPE_SERVICE) { + $perm = $user->rights->service->creer; + } elseif ($type == Product::TYPE_PRODUCT) { + $perm = $user->rights->produit->creer; + } $oldtype = $type; $params = array(); - if ($type === "") $params['forcenohideoftext'] = 1; + if ($type === "") { + $params['forcenohideoftext'] = 1; + } if ($type === "") { $newcardbutton .= dolGetButtonTitle($langs->trans('NewProduct'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/product/card.php?action=create&type=0', '', $perm, $params); $type = Product::TYPE_SERVICE; } $label = 'NewProduct'; - if ($type == Product::TYPE_SERVICE) $label = 'NewService'; + if ($type == Product::TYPE_SERVICE) { + $label = 'NewService'; + } $newcardbutton .= dolGetButtonTitle($langs->trans($label), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/product/card.php?action=create&type='.$type, '', $perm, $params); $type = $oldtype; print '<form action="'.$_SERVER["PHP_SELF"].'" method="post" name="formulaire">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -570,10 +718,14 @@ if ($resql) print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; //print '<input type="hidden" name="page" value="'.$page.'">'; print '<input type="hidden" name="type" value="'.$type.'">'; - if (empty($arrayfields['p.fk_product_type']['checked'])) print '<input type="hidden" name="search_type" value="'.dol_escape_htmltag($search_type).'">'; + if (empty($arrayfields['p.fk_product_type']['checked'])) { + print '<input type="hidden" name="search_type" value="'.dol_escape_htmltag($search_type).'">'; + } $picto = 'product'; - if ($type == 1) $picto = 'service'; + if ($type == 1) { + $picto = 'service'; + } print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $picto, 0, $newcardbutton, '', $limit, 0, 0, 1); @@ -583,8 +735,7 @@ if ($resql) $trackid = 'prod'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if (!empty($catid)) - { + if (!empty($catid)) { print "<div id='ways'>"; $c = new Categorie($db); $ways = $c->print_all_ways(' &gt; ', 'product/list.php'); @@ -592,16 +743,16 @@ if ($resql) print "</div><br>"; } - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } // Filter on categories $moreforfilter = ''; - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) - { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('Categories').': '; $categoriesProductArr = $form->select_all_categories(Categorie::TYPE_PRODUCT, '', '', 64, 0, 1); @@ -621,11 +772,13 @@ if ($resql) $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 ($moreforfilter) - { + if ($moreforfilter) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -633,63 +786,57 @@ if ($resql) $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 '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; // Lines with input filters print '<tr class="liste_titre_filter">'; - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print '<td class="liste_titre left">'; print '<input class="flat" type="text" name="search_ref" size="8" value="'.dol_escape_htmltag($search_ref).'">'; print '</td>'; } - if (!empty($arrayfields['pfp.ref_fourn']['checked'])) - { + if (!empty($arrayfields['pfp.ref_fourn']['checked'])) { print '<td class="liste_titre left">'; print '<input class="flat" type="text" name="search_ref_supplier" size="8" value="'.dol_escape_htmltag($search_ref_supplier).'">'; print '</td>'; } - if (!empty($arrayfields['p.label']['checked'])) - { + if (!empty($arrayfields['p.label']['checked'])) { print '<td class="liste_titre left">'; print '<input class="flat" type="text" name="search_label" size="12" value="'.dol_escape_htmltag($search_label).'">'; print '</td>'; } // Type - if (!empty($arrayfields['p.fk_product_type']['checked'])) - { + if (!empty($arrayfields['p.fk_product_type']['checked'])) { print '<td class="liste_titre center">'; $array = array('-1'=>'&nbsp;', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service')); print $form->selectarray('search_type', $array, $search_type); print '</td>'; } // Barcode - if (!empty($arrayfields['p.barcode']['checked'])) - { + if (!empty($arrayfields['p.barcode']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat" type="text" name="search_barcode" size="6" value="'.dol_escape_htmltag($search_barcode).'">'; print '</td>'; } // Duration - if (!empty($arrayfields['p.duration']['checked'])) - { + if (!empty($arrayfields['p.duration']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Finished - if (!empty($arrayfields['p.finished']['checked'])) - { + if (!empty($arrayfields['p.finished']['checked'])) { print '<td class="liste_titre">'; print $formproduct->selectProductNature('search_finished', $search_finished); print '</td>'; } // Weight - if (!empty($arrayfields['p.weight']['checked'])) - { + if (!empty($arrayfields['p.weight']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } @@ -699,8 +846,7 @@ if ($resql) print '</td>'; } // Length - if (!empty($arrayfields['p.length']['checked'])) - { + if (!empty($arrayfields['p.length']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } @@ -720,8 +866,7 @@ if ($resql) print '</td>'; } // Height - if (!empty($arrayfields['p.height']['checked'])) - { + if (!empty($arrayfields['p.height']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } @@ -731,8 +876,7 @@ if ($resql) print '</td>'; } // Surface - if (!empty($arrayfields['p.surface']['checked'])) - { + if (!empty($arrayfields['p.surface']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } @@ -742,8 +886,7 @@ if ($resql) print '</td>'; } // Volume - if (!empty($arrayfields['p.volume']['checked'])) - { + if (!empty($arrayfields['p.volume']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } @@ -754,25 +897,21 @@ if ($resql) } // Unit - if (!empty($arrayfields['cu.label']['checked'])) - { + if (!empty($arrayfields['cu.label']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Sell price - if (!empty($arrayfields['p.sellprice']['checked'])) - { + if (!empty($arrayfields['p.sellprice']['checked'])) { print '<td class="liste_titre right">'; print '</td>'; } // Multiprice if ($conf->global->PRODUIT_MULTIPRICES) { - foreach ($arraypricelevel as $key => $value) - { - if (!empty($arrayfields['p.sellprice'.$key]['checked'])) - { + foreach ($arraypricelevel as $key => $value) { + if (!empty($arrayfields['p.sellprice'.$key]['checked'])) { print '<td class="liste_titre right">'; print '</td>'; } @@ -780,72 +919,95 @@ if ($resql) } // Minimum buying Price - if (!empty($arrayfields['p.minbuyprice']['checked'])) - { + if (!empty($arrayfields['p.minbuyprice']['checked'])) { print '<td class="liste_titre">'; print '&nbsp;'; print '</td>'; } // Number buying Price - if (!empty($arrayfields['p.numbuyprice']['checked'])) - { + if (!empty($arrayfields['p.numbuyprice']['checked'])) { print '<td class="liste_titre">'; print '&nbsp;'; print '</td>'; } // Sell price - if (!empty($arrayfields['p.tva_tx']['checked'])) - { + if (!empty($arrayfields['p.tva_tx']['checked'])) { print '<td class="liste_titre right">'; print '<input class="right flat maxwidth50" placeholder="%" type="text" name="search_vatrate" size="1" value="'.dol_escape_htmltag($search_vatrate).'">'; print '</td>'; } // WAP - if (!empty($arrayfields['p.pmp']['checked'])) - { + if (!empty($arrayfields['p.pmp']['checked'])) { print '<td class="liste_titre">'; print '&nbsp;'; print '</td>'; } // cost_price - if (!empty($arrayfields['p.cost_price']['checked'])) - { + if (!empty($arrayfields['p.cost_price']['checked'])) { print '<td class="liste_titre">'; print '&nbsp;'; print '</td>'; } // Limit for alert - if (!empty($arrayfields['p.seuil_stock_alerte']['checked'])) - { + if (!empty($arrayfields['p.seuil_stock_alerte']['checked'])) { print '<td class="liste_titre">'; print '&nbsp;'; print '</td>'; } // Desired stock - if (!empty($arrayfields['p.desiredstock']['checked'])) - { + if (!empty($arrayfields['p.desiredstock']['checked'])) { print '<td class="liste_titre">'; print '&nbsp;'; print '</td>'; } // Stock - if (!empty($arrayfields['p.stock']['checked'])) print '<td class="liste_titre">&nbsp;</td>'; + if (!empty($arrayfields['p.stock']['checked'])) { + print '<td class="liste_titre">&nbsp;</td>'; + } // Stock - if (!empty($arrayfields['stock_virtual']['checked'])) print '<td class="liste_titre">&nbsp;</td>'; + if (!empty($arrayfields['stock_virtual']['checked'])) { + print '<td class="liste_titre">&nbsp;</td>'; + } // To batch - if (!empty($arrayfields['p.tobatch']['checked'])) print '<td class="liste_titre center">'.$form->selectyesno('search_tobatch', $search_tobatch, 1, false, 1).'</td>'; + if (!empty($arrayfields['p.tobatch']['checked'])) { + print '<td class="liste_titre center">'; + $statutarray = array( + '-1' => '', + '0' => $langs->trans("ProductStatusNotOnBatchShort"), + '1' => $langs->trans("ProductStatusOnBatchShort"), + '2' => $langs->trans("ProductStatusOnSerialShort") + ); + print $form->selectarray('search_tobatch', $statutarray, $search_tobatch); + print '</td>'; + } // Country - if (!empty($arrayfields['p.fk_country']['checked'])) print '<td class="liste_titre center">'.$form->select_country($search_country, 'search_country', '', 0).'</td>'; + if (!empty($arrayfields['p.fk_country']['checked'])) { + print '<td class="liste_titre center">'.$form->select_country($search_country, 'search_country', '', 0).'</td>'; + } // State - if (!empty($arrayfields['p.fk_state']['checked'])) print '<td class="liste_titre center">'.$formcompany->select_state($search_state, $search_country).'</td>'; + if (!empty($arrayfields['p.fk_state']['checked'])) { + print '<td class="liste_titre center">'.$formcompany->select_state($search_state, $search_country).'</td>'; + } // Accountancy code sell - if (!empty($arrayfields['p.accountancy_code_sell']['checked'])) print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_accountancy_code_sell" value="'.dol_escape_htmltag($search_accountancy_code_sell).'"></td>'; - if (!empty($arrayfields['p.accountancy_code_sell_intra']['checked'])) print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_accountancy_code_sell_intra" value="'.dol_escape_htmltag($search_accountancy_code_sell_intra).'"></td>'; - if (!empty($arrayfields['p.accountancy_code_sell_export']['checked'])) print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_accountancy_code_sell_export" value="'.dol_escape_htmltag($search_accountancy_code_sell_export).'"></td>'; + if (!empty($arrayfields['p.accountancy_code_sell']['checked'])) { + print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_accountancy_code_sell" value="'.dol_escape_htmltag($search_accountancy_code_sell).'"></td>'; + } + if (!empty($arrayfields['p.accountancy_code_sell_intra']['checked'])) { + print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_accountancy_code_sell_intra" value="'.dol_escape_htmltag($search_accountancy_code_sell_intra).'"></td>'; + } + if (!empty($arrayfields['p.accountancy_code_sell_export']['checked'])) { + print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_accountancy_code_sell_export" value="'.dol_escape_htmltag($search_accountancy_code_sell_export).'"></td>'; + } // Accountancy code buy - if (!empty($arrayfields['p.accountancy_code_buy']['checked'])) print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_accountancy_code_buy" value="'.dol_escape_htmltag($search_accountancy_code_buy).'"></td>'; - if (!empty($arrayfields['p.accountancy_code_buy_intra']['checked'])) print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_accountancy_code_buy_intra" value="'.dol_escape_htmltag($search_accountancy_code_buy_intra).'"></td>'; - if (!empty($arrayfields['p.accountancy_code_buy_export']['checked'])) print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_accountancy_code_buy_export" value="'.dol_escape_htmltag($search_accountancy_code_buy_export).'"></td>'; + if (!empty($arrayfields['p.accountancy_code_buy']['checked'])) { + print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_accountancy_code_buy" value="'.dol_escape_htmltag($search_accountancy_code_buy).'"></td>'; + } + if (!empty($arrayfields['p.accountancy_code_buy_intra']['checked'])) { + print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_accountancy_code_buy_intra" value="'.dol_escape_htmltag($search_accountancy_code_buy_intra).'"></td>'; + } + if (!empty($arrayfields['p.accountancy_code_buy_export']['checked'])) { + print '<td class="liste_titre"><input class="flat maxwidth75" type="text" name="search_accountancy_code_buy_export" value="'.dol_escape_htmltag($search_accountancy_code_buy_export).'"></td>'; + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook @@ -853,26 +1015,22 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['p.datec']['checked'])) - { + if (!empty($arrayfields['p.datec']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Date modification - if (!empty($arrayfields['p.tms']['checked'])) - { + if (!empty($arrayfields['p.tms']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } - if (!empty($arrayfields['p.tosell']['checked'])) - { - print '<td class="liste_titre right">'; + if (!empty($arrayfields['p.tosell']['checked'])) { + print '<td class="liste_titre center">'; print $form->selectarray('search_tosell', array('0'=>$langs->trans('ProductStatusNotOnSellShort'), '1'=>$langs->trans('ProductStatusOnSellShort')), $search_tosell, 1); print '</td >'; } - if (!empty($arrayfields['p.tobuy']['checked'])) - { - print '<td class="liste_titre right">'; + if (!empty($arrayfields['p.tobuy']['checked'])) { + print '<td class="liste_titre center">'; print $form->selectarray('search_tobuy', array('0'=>$langs->trans('ProductStatusNotOnBuyShort'), '1'=>$langs->trans('ProductStatusOnBuyShort')), $search_tobuy, 1); print '</td>'; } @@ -906,29 +1064,53 @@ if ($resql) print_liste_field_titre($arrayfields['p.finished']['label'], $_SERVER["PHP_SELF"], "p.finished", "", $param, '', $sortfield, $sortorder, 'center '); } - if (!empty($arrayfields['p.weight']['checked'])) print_liste_field_titre($arrayfields['p.weight']['label'], $_SERVER['PHP_SELF'], 'p.weight', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.weight_units']['checked'])) print_liste_field_titre($arrayfields['p.weight_units']['label'], $_SERVER['PHP_SELF'], 'p.weight_units', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.length']['checked'])) print_liste_field_titre($arrayfields['p.length']['label'], $_SERVER['PHP_SELF'], 'p.length', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.length_units']['checked'])) print_liste_field_titre($arrayfields['p.length_units']['label'], $_SERVER['PHP_SELF'], 'p.length_units', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.width']['checked'])) print_liste_field_titre($arrayfields['p.width']['label'], $_SERVER['PHP_SELF'], 'p.width', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.width_units']['checked'])) print_liste_field_titre($arrayfields['p.width_units']['label'], $_SERVER['PHP_SELF'], 'p.width_units', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.height']['checked'])) print_liste_field_titre($arrayfields['p.height']['label'], $_SERVER['PHP_SELF'], 'p.height', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.height_units']['checked'])) print_liste_field_titre($arrayfields['p.height_units']['label'], $_SERVER['PHP_SELF'], 'p.height_units', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.surface']['checked'])) print_liste_field_titre($arrayfields['p.surface']['label'], $_SERVER['PHP_SELF'], "p.surface", '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.surface_units']['checked'])) print_liste_field_titre($arrayfields['p.surface_units']['label'], $_SERVER['PHP_SELF'], 'p.surface_units', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.volume']['checked'])) print_liste_field_titre($arrayfields['p.volume']['label'], $_SERVER['PHP_SELF'], 'p.volume', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.volume_units']['checked'])) print_liste_field_titre($arrayfields['p.volume_units']['label'], $_SERVER['PHP_SELF'], 'p.volume_units', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['cu.label']['checked'])) print_liste_field_titre($arrayfields['cu.label']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.weight']['checked'])) { + print_liste_field_titre($arrayfields['p.weight']['label'], $_SERVER['PHP_SELF'], 'p.weight', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.weight_units']['checked'])) { + print_liste_field_titre($arrayfields['p.weight_units']['label'], $_SERVER['PHP_SELF'], 'p.weight_units', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.length']['checked'])) { + print_liste_field_titre($arrayfields['p.length']['label'], $_SERVER['PHP_SELF'], 'p.length', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.length_units']['checked'])) { + print_liste_field_titre($arrayfields['p.length_units']['label'], $_SERVER['PHP_SELF'], 'p.length_units', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.width']['checked'])) { + print_liste_field_titre($arrayfields['p.width']['label'], $_SERVER['PHP_SELF'], 'p.width', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.width_units']['checked'])) { + print_liste_field_titre($arrayfields['p.width_units']['label'], $_SERVER['PHP_SELF'], 'p.width_units', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.height']['checked'])) { + print_liste_field_titre($arrayfields['p.height']['label'], $_SERVER['PHP_SELF'], 'p.height', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.height_units']['checked'])) { + print_liste_field_titre($arrayfields['p.height_units']['label'], $_SERVER['PHP_SELF'], 'p.height_units', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.surface']['checked'])) { + print_liste_field_titre($arrayfields['p.surface']['label'], $_SERVER['PHP_SELF'], "p.surface", '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.surface_units']['checked'])) { + print_liste_field_titre($arrayfields['p.surface_units']['label'], $_SERVER['PHP_SELF'], 'p.surface_units', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.volume']['checked'])) { + print_liste_field_titre($arrayfields['p.volume']['label'], $_SERVER['PHP_SELF'], 'p.volume', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.volume_units']['checked'])) { + print_liste_field_titre($arrayfields['p.volume_units']['label'], $_SERVER['PHP_SELF'], 'p.volume_units', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['cu.label']['checked'])) { + print_liste_field_titre($arrayfields['cu.label']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'center '); + } if (!empty($arrayfields['p.sellprice']['checked'])) { print_liste_field_titre($arrayfields['p.sellprice']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); } // Multiprices if ($conf->global->PRODUIT_MULTIPRICES) { - foreach ($arraypricelevel as $key => $value) - { - if (!empty($arrayfields['p.sellprice'.$key]['checked'])) - { + foreach ($arraypricelevel as $key => $value) { + if (!empty($arrayfields['p.sellprice'.$key]['checked'])) { print_liste_field_titre($arrayfields['p.sellprice'.$key]['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); } } @@ -1001,10 +1183,10 @@ if ($resql) print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); } if (!empty($arrayfields['p.tosell']['checked'])) { - print_liste_field_titre($arrayfields['p.tosell']['label'], $_SERVER["PHP_SELF"], "p.tosell", "", $param, '', $sortfield, $sortorder, 'right '); + print_liste_field_titre($arrayfields['p.tosell']['label'], $_SERVER["PHP_SELF"], "p.tosell", "", $param, '', $sortfield, $sortorder, 'center '); } if (!empty($arrayfields['p.tobuy']['checked'])) { - print_liste_field_titre($arrayfields['p.tobuy']['label'], $_SERVER["PHP_SELF"], "p.tobuy", "", $param, '', $sortfield, $sortorder, 'right '); + print_liste_field_titre($arrayfields['p.tobuy']['label'], $_SERVER["PHP_SELF"], "p.tobuy", "", $param, '', $sortfield, $sortorder, 'center '); } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; @@ -1015,13 +1197,12 @@ if ($resql) $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + $totalarray['nbfield'] = 0; + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); // Multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) // If multilang is enabled - { + if (!empty($conf->global->MAIN_MULTILANGS)) { // If multilang is enabled $sql = "SELECT label"; $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sql .= " WHERE fk_product=".$obj->rowid; @@ -1029,10 +1210,11 @@ if ($resql) $sql .= " LIMIT 1"; $result = $db->query($sql); - if ($result) - { + if ($result) { $objtp = $db->fetch_object($result); - if (!empty($objtp->label)) $obj->label = $objtp->label; + if (!empty($objtp->label)) { + $obj->label = $objtp->label; + } } } @@ -1071,12 +1253,12 @@ if ($resql) } // STOCK_DISABLE_OPTIM_LOAD can be set to force load_stock whatever is permissions on stock. - if ((!empty($conf->stock->enabled) && $user->rights->stock->lire && $search_type != 1) || !empty($conf->global->STOCK_DISABLE_OPTIM_LOAD)) // To optimize call of load_stock - { - if ($obj->fk_product_type != 1 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) // Not a service - { + if ((!empty($conf->stock->enabled) && $user->rights->stock->lire && $search_type != 1) || !empty($conf->global->STOCK_DISABLE_OPTIM_LOAD)) { // To optimize call of load_stock + if ($obj->fk_product_type != 1 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { // Not a service $option = 'nobatch'; - if (empty($arrayfields['stock_virtual']['checked'])) $option .= ',novirtual'; + if (empty($arrayfields['stock_virtual']['checked'])) { + $option .= ',novirtual'; + } $product_static->load_stock($option); // Load stock_reel + stock_warehouse. This can also call load_virtual_stock() } } @@ -1084,208 +1266,238 @@ if ($resql) print '<tr class="oddeven">'; // Ref - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print '<td class="tdoverflowmax200">'; print $product_static->getNomUrl(1); print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Ref supplier - if (!empty($arrayfields['pfp.ref_fourn']['checked'])) - { + if (!empty($arrayfields['pfp.ref_fourn']['checked'])) { print '<td class="tdoverflowmax200">'; print $product_static->getNomUrl(1); print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Label - if (!empty($arrayfields['p.label']['checked'])) - { + if (!empty($arrayfields['p.label']['checked'])) { print '<td class="tdoverflowmax200" title="'.dol_escape_htmltag($obj->label).'">'.$obj->label.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type - if (!empty($arrayfields['p.fk_product_type']['checked'])) - { + if (!empty($arrayfields['p.fk_product_type']['checked'])) { print '<td class="center">'; $s = ''; - if ($obj->fk_product_type == 0) - { - //$s .= '<a class="product-type-back" title="'.$langs->trans("Product").'">'; + if ($obj->fk_product_type == 0) { $s .= img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"'); - //$s .= dol_substr($langs->trans("Product"), 0, 1); - //$s .= '</a>'; } else { - //$s .= '<span class="service-type-back" title="'.$langs->trans("Service").'">'; $s .= img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"'); - //$s .= dol_substr($langs->trans("Service"), 0, 1); - //$s .= '</a>'; } print $s; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Barcode - if (!empty($arrayfields['p.barcode']['checked'])) - { + if (!empty($arrayfields['p.barcode']['checked'])) { print '<td>'.$obj->barcode.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Duration - if (!empty($arrayfields['p.duration']['checked'])) - { + if (!empty($arrayfields['p.duration']['checked'])) { print '<td class="center nowraponall">'; - if (preg_match('/([^a-z]+)[a-z]$/i', $obj->duration)) - { + if (preg_match('/([^a-z]+)[a-z]$/i', $obj->duration)) { $duration_value = substr($obj->duration, 0, dol_strlen($obj->duration) - 1); $duration_unit = substr($obj->duration, -1); - if ((float) $duration_value > 1) - { + if ((float) $duration_value > 1) { $dur = array("i"=>$langs->trans("Minutes"), "h"=>$langs->trans("Hours"), "d"=>$langs->trans("Days"), "w"=>$langs->trans("Weeks"), "m"=>$langs->trans("Months"), "y"=>$langs->trans("Years")); - } elseif ((float) $duration_value > 0) - { + } elseif ((float) $duration_value > 0) { $dur = array("i"=>$langs->trans("Minute"), "h"=>$langs->trans("Hour"), "d"=>$langs->trans("Day"), "w"=>$langs->trans("Week"), "m"=>$langs->trans("Month"), "y"=>$langs->trans("Year")); } print $duration_value; print ((!empty($duration_unit) && isset($dur[$duration_unit]) && $duration_value != '') ? ' '.$langs->trans($dur[$duration_unit]) : ''); - } elseif (!preg_match('/^[a-z]$/i', $obj->duration)) // If duration is a simple char (like 's' of 'm'), we do not show value - { + } elseif (!preg_match('/^[a-z]$/i', $obj->duration)) { // If duration is a simple char (like 's' of 'm'), we do not show value print $obj->duration; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Finished - if (!empty($arrayfields['p.finished']['checked'])) - { + if (!empty($arrayfields['p.finished']['checked'])) { print '<td class="center">'; print $product_static->getLibFinished(); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Weight - if (!empty($arrayfields['p.weight']['checked'])) - { + if (!empty($arrayfields['p.weight']['checked'])) { print '<td class="center">'; print $obj->weight; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Weight units if (!empty($arrayfields['p.weight_units']['checked'])) { print '<td class="center">'; - if ($product_static->weight != '') print measuringUnitString(0, 'weight', $product_static->weight_units); + if ($product_static->weight != '') { + print measuringUnitString(0, 'weight', $product_static->weight_units); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Length - if (!empty($arrayfields['p.length']['checked'])) - { + if (!empty($arrayfields['p.length']['checked'])) { print '<td class="center">'; print $obj->length; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Length units if (!empty($arrayfields['p.length_units']['checked'])) { print '<td class="center">'; - if ($product_static->length != '') print measuringUnitString(0, 'size', $product_static->length_units); + if ($product_static->length != '') { + print measuringUnitString(0, 'size', $product_static->length_units); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Width - if (!empty($arrayfields['p.width']['checked'])) - { + if (!empty($arrayfields['p.width']['checked'])) { print '<td align="center">'; print $obj->width; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Width units if (!empty($arrayfields['p.width_units']['checked'])) { print '<td class="center">'; - if ($product_static->width != '') print measuringUnitString(0, 'size', $product_static->width_units); + if ($product_static->width != '') { + print measuringUnitString(0, 'size', $product_static->width_units); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Height - if (!empty($arrayfields['p.height']['checked'])) - { + if (!empty($arrayfields['p.height']['checked'])) { print '<td align="center">'; print $obj->height; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Height units if (!empty($arrayfields['p.height_units']['checked'])) { print '<td class="center">'; - if ($product_static->height != '') print measuringUnitString(0, 'size', $product_static->height_units); + if ($product_static->height != '') { + print measuringUnitString(0, 'size', $product_static->height_units); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Surface - if (!empty($arrayfields['p.surface']['checked'])) - { + if (!empty($arrayfields['p.surface']['checked'])) { print '<td class="center">'; print $obj->surface; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Surface units if (!empty($arrayfields['p.surface_units']['checked'])) { print '<td class="center">'; - if ($product_static->surface != '') print measuringUnitString(0, 'surface', $product_static->surface_units); + if ($product_static->surface != '') { + print measuringUnitString(0, 'surface', $product_static->surface_units); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Volume - if (!empty($arrayfields['p.volume']['checked'])) - { + if (!empty($arrayfields['p.volume']['checked'])) { print '<td class="center">'; print $obj->volume; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Volume units if (!empty($arrayfields['p.volume_units']['checked'])) { print '<td class="center">'; - if ($product_static->volume != '') print measuringUnitString(0, 'volume', $product_static->volume_units); + if ($product_static->volume != '') { + print measuringUnitString(0, 'volume', $product_static->volume_units); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Unit - if (!empty($arrayfields['cu.label']['checked'])) - { + if (!empty($arrayfields['cu.label']['checked'])) { print '<td align="center">'; if (!empty($obj->cu_label)) { print $langs->trans($obj->cu_label); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Sell price - if (!empty($arrayfields['p.sellprice']['checked'])) - { + if (!empty($arrayfields['p.sellprice']['checked'])) { print '<td class="right nowraponall">'; - if ($obj->tosell) - { - if ($obj->price_base_type == 'TTC') print price($obj->price_ttc).' '.$langs->trans("TTC"); - else print price($obj->price).' '.$langs->trans("HT"); + if ($obj->tosell) { + if ($obj->price_base_type == 'TTC') { + print price($obj->price_ttc).' '.$langs->trans("TTC"); + } else { + print price($obj->price).' '.$langs->trans("HT"); + } } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } @@ -1298,8 +1510,7 @@ if ($resql) $productpricescache[$obj->rowid] = array(); } - if ($obj->tosell) - { + if ($obj->tosell) { // Make 1 request for all price levels (without filter on price_level) and saved result into an cache array // then reuse the cache array if we need prices for other price levels $sqlp = "SELECT p.rowid, p.fk_product, p.price, p.price_ttc, p.price_level, p.date_price, p.price_base_type"; @@ -1307,16 +1518,13 @@ if ($resql) $sqlp .= " WHERE fk_product = ".$obj->rowid; $sqlp .= " ORDER BY p.date_price DESC, p.rowid DESC, p.price_level ASC"; $resultp = $db->query($sqlp); - if ($resultp) - { + if ($resultp) { $nump = $db->num_rows($resultp); $j = 0; - while ($j < $nump) - { + while ($j < $nump) { $objp = $db->fetch_object($resultp); - if (empty($productpricescache[$obj->rowid][$objp->price_level])) - { + if (empty($productpricescache[$obj->rowid][$objp->price_level])) { $productpricescache[$obj->rowid][$objp->price_level]['price'] = $objp->price; $productpricescache[$obj->rowid][$objp->price_level]['price_ttc'] = $objp->price_ttc; $productpricescache[$obj->rowid][$objp->price_level]['price_base_type'] = $objp->price_base_type; @@ -1331,13 +1539,10 @@ if ($resql) } } - foreach ($arraypricelevel as $key => $value) - { - if (!empty($arrayfields['p.sellprice'.$key]['checked'])) - { + foreach ($arraypricelevel as $key => $value) { + if (!empty($arrayfields['p.sellprice'.$key]['checked'])) { print '<td class="right nowraponall">'; - if (!empty($productpricescache[$obj->rowid])) - { + if (!empty($productpricescache[$obj->rowid])) { if ($productpricescache[$obj->rowid][$key]['price_base_type'] == 'TTC') { print price($productpricescache[$obj->rowid][$key]['price_ttc']).' '.$langs->trans("TTC"); } else { @@ -1345,42 +1550,40 @@ if ($resql) } } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } } } // Better buy price - if (!empty($arrayfields['p.minbuyprice']['checked'])) - { + if (!empty($arrayfields['p.minbuyprice']['checked'])) { print '<td class="right nowraponall">'; - if ($obj->tobuy && $obj->minsellprice != '') - { + if ($obj->tobuy && $obj->minsellprice != '') { //print price($obj->minsellprice).' '.$langs->trans("HT"); - if ($product_fourn->find_min_price_product_fournisseur($obj->rowid) > 0) - { - if ($product_fourn->product_fourn_price_id > 0) - { - if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire) - { + if ($product_fourn->find_min_price_product_fournisseur($obj->rowid) > 0) { + if ($product_fourn->product_fourn_price_id > 0) { + if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire) { $htmltext = $product_fourn->display_price_product_fournisseur(1, 1, 0, 1); print $form->textwithpicto(price($product_fourn->fourn_unitprice * (1 - $product_fourn->fourn_remise_percent / 100) - $product_fourn->fourn_remise).' '.$langs->trans("HT"), $htmltext); - } else print price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"); + } else { + print price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"); + } } } } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Number of buy prices - if (!empty($arrayfields['p.numbuyprice']['checked'])) - { + if (!empty($arrayfields['p.numbuyprice']['checked'])) { print '<td class="right">'; - if ($obj->tobuy) - { - if (count($productFournList = $product_fourn->list_product_fournisseur_price($obj->rowid)) > 0) - { + if ($obj->tobuy) { + if (count($productFournList = $product_fourn->list_product_fournisseur_price($obj->rowid)) > 0) { $htmltext = $product_fourn->display_price_product_fournisseur(1, 1, 0, 1, $productFournList); print $form->textwithpicto(count($productFournList), $htmltext); } @@ -1389,24 +1592,23 @@ if ($resql) } // VAT or Sell Tax Rate - if (!empty($arrayfields['p.tva_tx']['checked'])) - { + if (!empty($arrayfields['p.tva_tx']['checked'])) { print '<td class="right">'; print vatrate($obj->tva_tx, true); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // WAP - if (!empty($arrayfields['p.pmp']['checked'])) - { + if (!empty($arrayfields['p.pmp']['checked'])) { print '<td class="nowrap right">'; print price($product_static->pmp, 1, $langs); print '</td>'; } // Cost price - if (!empty($arrayfields['p.cost_price']['checked'])) - { + if (!empty($arrayfields['p.cost_price']['checked'])) { print '<td class="nowrap right">'; //print $obj->cost_price; print price($obj->cost_price).' '.$langs->trans("HT"); @@ -1414,104 +1616,119 @@ if ($resql) } // Limit alert - if (!empty($arrayfields['p.seuil_stock_alerte']['checked'])) - { + if (!empty($arrayfields['p.seuil_stock_alerte']['checked'])) { print '<td class="right">'; - if ($obj->fk_product_type != 1) - { + if ($obj->fk_product_type != 1) { print $obj->seuil_stock_alerte; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Desired stock - if (!empty($arrayfields['p.desiredstock']['checked'])) - { + if (!empty($arrayfields['p.desiredstock']['checked'])) { print '<td class="right">'; - if ($obj->fk_product_type != 1) - { + if ($obj->fk_product_type != 1) { print $obj->desiredstock; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Stock real - if (!empty($arrayfields['p.stock']['checked'])) - { + if (!empty($arrayfields['p.stock']['checked'])) { print '<td class="right">'; - if ($obj->fk_product_type != 1) - { - if ($obj->seuil_stock_alerte != '' && $product_static->stock_reel < (float) $obj->seuil_stock_alerte) print img_warning($langs->trans("StockLowerThanLimit", $obj->seuil_stock_alerte)).' '; + if ($obj->fk_product_type != 1) { + if ($obj->seuil_stock_alerte != '' && $product_static->stock_reel < (float) $obj->seuil_stock_alerte) { + print img_warning($langs->trans("StockLowerThanLimit", $obj->seuil_stock_alerte)).' '; + } print price2num($product_static->stock_reel, 'MS'); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Stock virtual - if (!empty($arrayfields['stock_virtual']['checked'])) - { + if (!empty($arrayfields['stock_virtual']['checked'])) { print '<td class="right">'; - if ($obj->fk_product_type != 1) - { - if ($obj->seuil_stock_alerte != '' && $product_static->stock_theorique < (float) $obj->seuil_stock_alerte) print img_warning($langs->trans("StockLowerThanLimit", $obj->seuil_stock_alerte)).' '; + if ($obj->fk_product_type != 1) { + if ($obj->seuil_stock_alerte != '' && $product_static->stock_theorique < (float) $obj->seuil_stock_alerte) { + print img_warning($langs->trans("StockLowerThanLimit", $obj->seuil_stock_alerte)).' '; + } print price2num($product_static->stock_theorique, 'MS'); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Lot/Serial - if (!empty($arrayfields['p.tobatch']['checked'])) - { + if (!empty($arrayfields['p.tobatch']['checked'])) { print '<td class="center">'; - print yn($obj->tobatch); + print $product_static->getLibStatut(1, 2); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['p.fk_country']['checked'])) - { + if (!empty($arrayfields['p.fk_country']['checked'])) { print '<td>'.getCountry($obj->fk_country, 0, $db).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State - if (!empty($arrayfields['p.fk_state']['checked'])) - { + if (!empty($arrayfields['p.fk_state']['checked'])) { print '<td>'; - if (!empty($obj->fk_state)) print getState($obj->fk_state, 0, $db); + if (!empty($obj->fk_state)) { + print getState($obj->fk_state, 0, $db); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Accountancy code sell - if (!empty($arrayfields['p.accountancy_code_sell']['checked'])) - { + if (!empty($arrayfields['p.accountancy_code_sell']['checked'])) { print '<td>'.$obj->accountancy_code_sell.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['p.accountancy_code_sell_intra']['checked'])) - { + if (!empty($arrayfields['p.accountancy_code_sell_intra']['checked'])) { print '<td>'.$obj->accountancy_code_sell_intra.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['p.accountancy_code_sell_export']['checked'])) - { + if (!empty($arrayfields['p.accountancy_code_sell_export']['checked'])) { print '<td>'.$obj->accountancy_code_sell_export.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Accountancy code buy - if (!empty($arrayfields['p.accountancy_code_buy']['checked'])) - { + if (!empty($arrayfields['p.accountancy_code_buy']['checked'])) { print '<td>'.$obj->accountancy_code_buy.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['p.accountancy_code_buy_intra']['checked'])) - { + if (!empty($arrayfields['p.accountancy_code_buy_intra']['checked'])) { print '<td>'.$obj->accountancy_code_buy_intra.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['p.accountancy_code_buy_export']['checked'])) - { + if (!empty($arrayfields['p.accountancy_code_buy_export']['checked'])) { print '<td>'.$obj->accountancy_code_buy_export.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; @@ -1520,57 +1737,64 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['p.datec']['checked'])) - { + if (!empty($arrayfields['p.datec']['checked'])) { print '<td class="center nowraponall">'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['p.tms']['checked'])) - { + if (!empty($arrayfields['p.tms']['checked'])) { print '<td class="center nowraponall">'; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status (to sell) - if (!empty($arrayfields['p.tosell']['checked'])) - { - print '<td class="right nowrap">'; + if (!empty($arrayfields['p.tosell']['checked'])) { + print '<td class="center nowrap">'; if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { print ajax_object_onoff($product_static, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); } else { print $product_static->LibStatut($obj->tosell, 5, 0); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status (to buy) - if (!empty($arrayfields['p.tobuy']['checked'])) - { - print '<td class="right nowrap">'; + if (!empty($arrayfields['p.tobuy']['checked'])) { + print '<td class="center nowrap">'; if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { print ajax_object_onoff($product_static, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); } else { print $product_static->LibStatut($obj->tobuy, 5, 1); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; $i++; diff --git a/htdocs/product/note.php b/htdocs/product/note.php index f0a6293383d..348d5956588 100644 --- a/htdocs/product/note.php +++ b/htdocs/product/note.php @@ -40,11 +40,15 @@ $action = GETPOST('action', 'aZ09'); // 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; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $object = new Product($db); -if ($id > 0 || !empty($ref)) $object->fetch($id, $ref); +if ($id > 0 || !empty($ref)) { + $object->fetch($id, $ref); +} $permissionnote = $user->rights->produit->creer; // Used by the include of actions_setnotes.inc.php @@ -63,30 +67,33 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, $form = new Form($db); $helpurl = ''; -if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; -if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; +if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; +} +if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; +} $title = $langs->trans('ProductServiceCard'); $shortlabel = dol_trunc($object->label, 16); -if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) -{ +if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Notes'); $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; } -if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) -{ +if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Notes'); $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; } llxHeader('', $title, $help_url); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { /* - * Affichage onglets - */ - if (!empty($conf->notification->enabled)) $langs->load("mails"); + * Affichage onglets + */ + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = product_prepare_head($object); $titre = $langs->trans("CardProduct".$object->type); @@ -98,7 +105,9 @@ if ($id > 0 || !empty($ref)) $object->next_prev_filter = " fk_product_type = ".$object->type; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); diff --git a/htdocs/product/popuprop.php b/htdocs/product/popuprop.php index 37019616e96..001635be24b 100644 --- a/htdocs/product/popuprop.php +++ b/htdocs/product/popuprop.php @@ -39,16 +39,24 @@ $type = GETPOST("type", "int"); $mode = GETPOST('mode', 'alpha') ? GETPOST('mode', 'alpha') : ''; // Security check -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service'); $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 (!$sortfield) $sortfield = "c"; -if (!$sortorder) $sortorder = "DESC"; +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 +if (!$sortfield) { + $sortfield = "c"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -88,8 +96,12 @@ if ((string) $type == '0') { $title = $langs->trans("ListProductByPopularity"); } -if ($type != '') $param .= '&type='.urlencode($type); -if ($mode != '') $param .= '&mode='.urlencode($mode); +if ($type != '') { + $param .= '&type='.urlencode($type); +} +if ($mode != '') { + $param .= '&mode='.urlencode($mode); +} $h = 0; $head = array(); @@ -134,8 +146,7 @@ $sql .= " GROUP BY p.rowid, p.label, p.ref, p.fk_product_type"; if (!empty($mode) && $mode != '-1') { $result = $db->query($sql); - if ($result) - { + if ($result) { $totalnboflines = $db->num_rows($result); } @@ -143,13 +154,11 @@ if (!empty($mode) && $mode != '-1') { $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $infoprod[$objp->rowid] = array('type'=>$objp->type, 'ref'=>$objp->ref, 'label'=>$objp->label); @@ -179,8 +188,12 @@ print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="mode" value="'.$mode.'">'; print '<input type="hidden" name="type" value="'.$type.'">'; print '<input type="hidden" name="action" value="add">'; -if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; -if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; +if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; +} +if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; +} print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, "", $num, $totalnboflines, '', 0, '', '', -1, 0, 0, 1); @@ -195,11 +208,9 @@ print_liste_field_titre($textforqty, $_SERVER["PHP_SELF"], 'c', '', $param, '', print "</tr>\n"; if ($mode && $mode != '-1') { - foreach ($infoprod as $prodid => $vals) - { + foreach ($infoprod as $prodid => $vals) { // Multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) // si l'option est active - { + if (!empty($conf->global->MAIN_MULTILANGS)) { // si l'option est active $sql = "SELECT label"; $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sql .= " WHERE fk_product=".$prodid; @@ -207,22 +218,29 @@ if ($mode && $mode != '-1') { $sql .= " LIMIT 1"; $resultp = $db->query($sql); - if ($resultp) - { + if ($resultp) { $objtp = $db->fetch_object($resultp); - if (!empty($objtp->label)) $vals['label'] = $objtp->label; + if (!empty($objtp->label)) { + $vals['label'] = $objtp->label; + } } } print "<tr>"; print '<td><a href="'.DOL_URL_ROOT.'/product/stats/card.php?id='.$prodid.'">'; - if ($vals['type'] == 1) print img_object($langs->trans("ShowService"), "service"); - else print img_object($langs->trans("ShowProduct"), "product"); + if ($vals['type'] == 1) { + print img_object($langs->trans("ShowService"), "service"); + } else { + print img_object($langs->trans("ShowProduct"), "product"); + } print " "; print $vals['ref'].'</a></td>'; print '<td>'; - if ($vals['type'] == 1) print $langs->trans("Service"); - else print $langs->trans("Product"); + if ($vals['type'] == 1) { + print $langs->trans("Service"); + } else { + print $langs->trans("Product"); + } print '</td>'; print '<td>'.$vals['label'].'</td>'; print '<td class="right">'.$vals['nbline'].'</td>'; diff --git a/htdocs/product/price.php b/htdocs/product/price.php index 89695690d38..015b061119b 100644 --- a/htdocs/product/price.php +++ b/htdocs/product/price.php @@ -65,17 +65,20 @@ $search_soc = GETPOST('search_soc'); // 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; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object = new Product($db); $object->fetch($id, $ref); } // Clean param -if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($conf->global->PRODUIT_MULTIPRICES_LIMIT)) $conf->global->PRODUIT_MULTIPRICES_LIMIT = 5; +if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($conf->global->PRODUIT_MULTIPRICES_LIMIT)) { + $conf->global->PRODUIT_MULTIPRICES_LIMIT = 5; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('productpricecard', 'globalcard')); @@ -85,37 +88,36 @@ $hookmanager->initHooks(array('productpricecard', 'globalcard')); * Actions */ -if ($cancel) $action = ''; +if ($cancel) { + $action = ''; +} $parameters = array('id'=>$id, 'ref'=>$ref); $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 (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 (empty($reshook)) { + 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_soc = ''; } - if ($action == 'setlabelsellingprice' && $user->admin) - { + if ($action == 'setlabelsellingprice' && $user->admin) { require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.GETPOST('pricelevel'); dolibarr_set_const($db, $keyforlabel, GETPOST('labelsellingprice', 'alpha'), 'chaine', 0, '', $conf->entity); $action = ''; } - if (($action == 'update_vat') && !$cancel && ($user->rights->produit->creer || $user->rights->service->creer)) - { + if (($action == 'update_vat') && !$cancel && ($user->rights->produit->creer || $user->rights->service->creer)) { $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)' // We must define tva_tx, npr and local taxes $tva_tx = $tva_tx_txt; $reg = array(); $vatratecode = ''; - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { $vat_src_code = $reg[1]; $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. } @@ -124,8 +126,7 @@ if (empty($reshook)) $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in create product. $vatratecode = $reg[1]; // Get record from code @@ -135,8 +136,7 @@ if (empty($reshook)) $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $npr = $obj->recuperableonly; $localtax1 = $obj->localtax1; @@ -157,21 +157,18 @@ if (empty($reshook)) $db->begin(); $resql = $object->update($object->id, $user); - if ($resql <= 0) - { + if ($resql <= 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } - if ($error) - { + if ($error) { //$localtaxarray=array('0'=>$localtax1_type,'1'=>$localtax1,'2'=>$localtax2_type,'3'=>$localtax2); $localtaxarray = array(); // We do not store localtaxes into product, we will use instead the "vat code" to retrieve them. $object->updatePrice(0, $object->price_base_type, $user, $tva_tx, '', 0, $npr, 0, 0, $localtaxarray, $vatratecode); } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -180,8 +177,7 @@ if (empty($reshook)) $action = ''; } - if (($action == 'update_price') && !$cancel && $object->getRights()->creer) - { + if (($action == 'update_price') && !$cancel && $object->getRights()->creer) { $error = 0; $pricestoupdate = array(); @@ -218,8 +214,7 @@ if (empty($reshook)) //Shall we generate prices using price rules? $object->price_autogen = GETPOST('usePriceRules') == 'on'; - for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) - { + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { if (!isset($newprice[$i])) { continue; } @@ -229,8 +224,7 @@ if (empty($reshook)) $tva_tx = $tva_tx_txt; $vatratecode = ''; $reg = array(); - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { $vat_src_code = $reg[1]; $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. } @@ -241,8 +235,7 @@ if (empty($reshook)) $localtax1_type = $newlocaltax1_type[$i]; $localtax2 = $newlocaltax2_tx[$i]; $localtax2_type = $newlocaltax2_type[$i]; - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code $vatratecode = $reg[1]; // Get record from code @@ -252,8 +245,7 @@ if (empty($reshook)) $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $npr = $obj->recuperableonly; $localtax1 = $obj->localtax1; @@ -278,8 +270,7 @@ if (empty($reshook)) break; } } - } elseif (!$error) - { + } elseif (!$error) { $newprice = price2num(GETPOST('price', 'alpha'), '', 2); $newprice_min = price2num(GETPOST('price_min', 'alpha'), '', 2); $newpricebase = GETPOST('price_base_type', 'alpha'); @@ -288,8 +279,7 @@ if (empty($reshook)) $tva_tx = $tva_tx_txt; $vatratecode = ''; $reg = array(); - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { $vat_src_code = $reg[1]; $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. } @@ -298,8 +288,7 @@ if (empty($reshook)) $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code $vatratecode = $reg[1]; // Get record from code @@ -309,8 +298,7 @@ if (empty($reshook)) $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $npr = $obj->recuperableonly; $localtax1 = $obj->localtax1; @@ -319,10 +307,9 @@ if (empty($reshook)) $localtax2_type = $obj->localtax2_type; // If spain, we don't use the localtax found into tax record in database with same code, but using the get_localtax rule - if (in_array($mysoc->country_code, array('ES'))) - { + if (in_array($mysoc->country_code, array('ES'))) { $localtax1 = get_localtax($tva_tx, 1); - $localtax2 = get_localtax($tva_tx, 2); + $localtax2 = get_localtax($tva_tx, 2); } } } @@ -356,9 +343,11 @@ if (empty($reshook)) break; } - if ($object->multiprices[$key] != $newprice || $object->multiprices_min[$key] != $newprice_min || $object->multiprices_base_type[$key] != $val['price_base_type']) - $res = $object->updatePrice($newprice, $val['price_base_type'], $user, $val['vat_tx'], $newprice_min, $key, $val['npr'], $psq, 0, $val['localtaxes_array'], $val['default_vat_code']); - else $res = 0; + if ($object->multiprices[$key] != $newprice || $object->multiprices_min[$key] != $newprice_min || $object->multiprices_base_type[$key] != $val['price_base_type']) { + $res = $object->updatePrice($newprice, $val['price_base_type'], $user, $val['vat_tx'], $newprice_min, $key, $val['npr'], $psq, 0, $val['localtaxes_array'], $val['default_vat_code']); + } else { + $res = 0; + } if ($res < 0) { @@ -385,8 +374,7 @@ if (empty($reshook)) } - if ($action == 'delete' && $user->rights->produit->supprimer) - { + if ($action == 'delete' && $user->rights->produit->supprimer) { $result = $object->log_price_delete($user, GETPOST('lineid', 'int')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -394,28 +382,24 @@ if (empty($reshook)) } // Set Price by quantity - if ($action == 'activate_price_by_qty') - { + if ($action == 'activate_price_by_qty') { // Activating product price by quantity add a new price line with price_by_qty set to 1 $level = GETPOST('level', 'int'); $object->updatePrice(0, $object->price_base_type, $user, $object->tva_tx, 0, $level, $object->tva_npr, 1); } // Unset Price by quantity - if ($action == 'disable_price_by_qty') - { + if ($action == 'disable_price_by_qty') { // Disabling product price by quantity add a new price line with price_by_qty set to 0 $level = GETPOST('level', 'int'); $object->updatePrice(0, $object->price_base_type, $user, $object->tva_tx, 0, $level, $object->tva_npr, 0); } - if ($action == 'edit_price_by_qty') - { // Edition d'un prix par quantité + if ($action == 'edit_price_by_qty') { // Edition d'un prix par quantité $rowid = GETPOST('rowid', 'int'); } // Add or update price by quantity - if ($action == 'update_price_by_qty') - { + if ($action == 'update_price_by_qty') { // Récupération des variables $rowid = GETPOST('rowid', 'int'); $priceid = GETPOST('priceid', 'int'); @@ -453,7 +437,9 @@ if (empty($reshook)) $sql .= " WHERE rowid = ".$rowid; $result = $db->query($sql); - if (!$result) dol_print_error($db); + if (!$result) { + dol_print_error($db); + } } else { $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_price_by_qty (fk_product_price,price,unitprice,quantity,remise_percent,remise) values ("; $sql .= $priceid.','.$price.','.$unitPrice.','.$quantity.','.$remise_percent.','.$remise.')'; @@ -470,8 +456,7 @@ if (empty($reshook)) } } - if ($action == 'delete_price_by_qty') - { + if ($action == 'delete_price_by_qty') { $rowid = GETPOST('rowid', 'int'); if (!empty($rowid)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_price_by_qty"; @@ -517,8 +502,7 @@ if (empty($reshook)) $tva_tx = $tva_tx_txt; $vatratecode = ''; - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { $vat_src_code = $reg[1]; $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. } @@ -527,8 +511,7 @@ if (empty($reshook)) $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code $vatratecode = $reg[1]; // Get record from code @@ -538,8 +521,7 @@ if (empty($reshook)) $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $npr = $obj->recuperableonly; $localtax1 = $obj->localtax1; @@ -557,23 +539,20 @@ if (empty($reshook)) $prodcustprice->localtax1_type = $localtax1_type; $prodcustprice->localtax2_type = $localtax2_type; - if (!($prodcustprice->fk_soc > 0)) - { + if (!($prodcustprice->fk_soc > 0)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors'); $error++; $action = 'add_customer_price'; } - if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE) && $prodcustprice->price_min < $maxpricesupplier) - { + if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE) && $prodcustprice->price_min < $maxpricesupplier) { $langs->load("errors"); setEventMessages($langs->trans("MinimumPriceLimit", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')), null, 'errors'); $error++; $action = 'add_customer_price'; } - if (!$error) - { + if (!$error) { $result = $prodcustprice->create($user, 0, $update_child_soc); if ($result < 0) { @@ -586,8 +565,7 @@ if (empty($reshook)) } } - if ($action == 'delete_customer_price' && ($user->rights->produit->supprimer || $user->rights->service->supprimer)) - { + if ($action == 'delete_customer_price' && ($user->rights->produit->supprimer || $user->rights->service->supprimer)) { // Delete price by customer $prodcustprice->id = GETPOST('lineid'); $result = $prodcustprice->delete($user); @@ -600,8 +578,7 @@ if (empty($reshook)) $action = ''; } - if ($action == 'update_customer_price_confirm' && !$cancel && ($user->rights->produit->creer || $user->rights->service->creer)) - { + if ($action == 'update_customer_price_confirm' && !$cancel && ($user->rights->produit->creer || $user->rights->service->creer)) { $maxpricesupplier = $object->min_recommended_price(); $update_child_soc = GETPOST('updatechildprice', 'int'); @@ -618,8 +595,7 @@ if (empty($reshook)) $tva_tx = $tva_tx_txt; $vatratecode = ''; - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { $vat_src_code = $reg[1]; $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. } @@ -628,8 +604,7 @@ if (empty($reshook)) $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code $vatratecode = $reg[1]; // Get record from code @@ -639,8 +614,7 @@ if (empty($reshook)) $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $npr = $obj->recuperableonly; $localtax1 = $obj->localtax1; @@ -658,15 +632,13 @@ if (empty($reshook)) $prodcustprice->localtax1_type = $localtax1_type; $prodcustprice->localtax2_type = $localtax2_type; - if ($prodcustprice->price_min < $maxpricesupplier && !empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) - { + if ($prodcustprice->price_min < $maxpricesupplier && !empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { setEventMessages($langs->trans("MinimumPriceLimit", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')), null, 'errors'); $error++; $action = 'update_customer_price'; } - if (!$error) - { + if (!$error) { $result = $prodcustprice->update($user, 0, $update_child_soc); if ($result < 0) { @@ -687,8 +659,7 @@ if (empty($reshook)) $form = new Form($db); -if (!empty($id) || !empty($ref)) -{ +if (!empty($id) || !empty($ref)) { // fetch updated prices $object->fetch($id, $ref); } @@ -696,13 +667,11 @@ if (!empty($id) || !empty($ref)) $title = $langs->trans('ProductServiceCard'); $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); -if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) -{ +if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('SellingPrices'); $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; } -if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) -{ +if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('SellingPrices'); $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; } @@ -719,7 +688,9 @@ $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_value $object->next_prev_filter = " fk_product_type = ".$object->type; $shownav = 1; -if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; +if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; +} dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -730,11 +701,9 @@ print '<div class="underbanner clearboth"></div>'; print '<table class="border tableforfield" width="100%">'; // Price per customer segment/level -if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) -{ +if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { // Price and min price are variable (depends on level of company). - if (!empty($socid)) - { + if (!empty($socid)) { $soc = new Societe($db); $soc->id = $socid; $soc->fetch($socid); @@ -758,24 +727,30 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ // Price min print '<tr><td>'.$langs->trans("MinPrice").'</td><td colspan="2">'; - if ($object->multiprices_base_type[$soc->price_level] == 'TTC') - { + if ($object->multiprices_base_type[$soc->price_level] == 'TTC') { print price($object->multiprices_min_ttc[$soc->price_level]).' '.$langs->trans($object->multiprices_base_type[$soc->price_level]); } else { print price($object->multiprices_min[$soc->price_level]).' '.$langs->trans(empty($object->multiprices_base_type[$soc->price_level]) ? 'HT' : $object->multiprices_base_type[$soc->price_level]); } print '</td></tr>'; - if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility - { + if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility // TVA print '<tr><td>'.$langs->trans("DefaultTaxRate").'</td><td colspan="2">'; $positiverates = ''; - if (price2num($object->multiprices_tva_tx[$soc->price_level])) $positiverates .= ($positiverates ? '/' : '').price2num($object->multiprices_tva_tx[$soc->price_level]); - if (price2num($object->multiprices_localtax1_type[$soc->price_level])) $positiverates .= ($positiverates ? '/' : '').price2num($object->multiprices_localtax1_tx[$soc->price_level]); - if (price2num($object->multiprices_localtax2_type[$soc->price_level])) $positiverates .= ($positiverates ? '/' : '').price2num($object->multiprices_localtax2_tx[$soc->price_level]); - if (empty($positiverates)) $positiverates = '0'; + if (price2num($object->multiprices_tva_tx[$soc->price_level])) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->multiprices_tva_tx[$soc->price_level]); + } + if (price2num($object->multiprices_localtax1_type[$soc->price_level])) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->multiprices_localtax1_tx[$soc->price_level]); + } + if (price2num($object->multiprices_localtax2_type[$soc->price_level])) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->multiprices_localtax2_tx[$soc->price_level]); + } + if (empty($positiverates)) { + $positiverates = '0'; + } echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); //print vatrate($object->multiprices_tva_tx[$soc->price_level], true); print '</td></tr>'; @@ -784,22 +759,29 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print '<tr><td>'.$langs->trans("DefaultTaxRate").'</td><td>'; $positiverates = ''; - if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates = '0'; + if (price2num($object->tva_tx)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + } + if (price2num($object->localtax1_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + } + if (price2num($object->localtax2_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + } + if (empty($positiverates)) { + $positiverates = '0'; + } echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); /* if ($object->default_vat_code) - { - print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; - } - else print vatrate($object->tva_tx . ($object->tva_npr ? '*' : ''), true);*/ + { + print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; + } + else print vatrate($object->tva_tx . ($object->tva_npr ? '*' : ''), true);*/ print '</td></tr>'; } } else { - if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility - { + if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility // We show only vat for level 1 print '<tr><td class="titlefield">'.$langs->trans("DefaultTaxRate").'</td>'; print '<td colspan="2">'.vatrate($object->multiprices_tva_tx[1], true).'</td>'; @@ -809,17 +791,25 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print '<tr><td class="titlefield">'.$langs->trans("DefaultTaxRate").'</td><td>'; $positiverates = ''; - if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates = '0'; + if (price2num($object->tva_tx)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + } + if (price2num($object->localtax1_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + } + if (price2num($object->localtax2_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + } + if (empty($positiverates)) { + $positiverates = '0'; + } echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); /* - if ($object->default_vat_code) - { - print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; - } - else print vatrate($object->tva_tx . ($object->tva_npr ? '*' : ''), true);*/ + if ($object->default_vat_code) + { + print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; + } + else print vatrate($object->tva_tx . ($object->tva_npr ? '*' : ''), true);*/ print '</td></tr>'; } print '</table>'; @@ -829,21 +819,21 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print '<table class="noborder tableforfield" width="100%">'; print '<tr class="liste_titre"><td>'; print $langs->trans("PriceLevel"); - if ($user->admin) print ' <a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editlabelsellingprice&amp;pricelevel='.$i.'&amp;id='.$object->id.'">'.img_edit($langs->trans('EditSellingPriceLabel'), 0).'</a>'; + if ($user->admin) { + print ' <a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editlabelsellingprice&amp;pricelevel='.$i.'&amp;id='.$object->id.'">'.img_edit($langs->trans('EditSellingPriceLabel'), 0).'</a>'; + } print '</td>'; print '<td style="text-align: right">'.$langs->trans("SellingPrice").'</td>'; print '<td style="text-align: right">'.$langs->trans("MinPrice").'</td>'; print '</tr>'; - for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) - { + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { print '<tr class="oddeven">'; // Label of price print '<td>'; $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i; - if (preg_match('/editlabelsellingprice/', $action)) - { + if (preg_match('/editlabelsellingprice/', $action)) { print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="setlabelsellingprice">'; @@ -854,7 +844,9 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print '</form>'; } else { print $langs->trans("SellingPrice").' '.$i; - if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); + if (!empty($conf->global->$keyforlabel)) { + print ' - '.$langs->trans($conf->global->$keyforlabel); + } } print '</td>'; @@ -872,9 +864,10 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ // Prix min print '<td style="text-align: right">'; - if (empty($object->multiprices_base_type[$i])) $object->multiprices_base_type[$i] = "HT"; - if ($object->multiprices_base_type[$i] == 'TTC') - { + if (empty($object->multiprices_base_type[$i])) { + $object->multiprices_base_type[$i] = "HT"; + } + if ($object->multiprices_base_type[$i] == 'TTC') { print price($object->multiprices_min_ttc[$i]).' '.$langs->trans($object->multiprices_base_type[$i]); } else { print price($object->multiprices_min[$i]).' '.$langs->trans($object->multiprices_base_type[$i]); @@ -882,10 +875,11 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print '</td></tr>'; // Price by quantity - if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) // TODO Fix the form included into a tr instead of a td - { + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { // TODO Fix the form included into a tr instead of a td print '<tr><td>'.$langs->trans("PriceByQuantity").' '.$i; - if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); + if (!empty($conf->global->$keyforlabel)) { + print ' - '.$langs->trans($conf->global->$keyforlabel); + } print '</td><td colspan="2">'; if ($object->prices_by_qty[$i] == 1) { @@ -898,8 +892,7 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print '<td class="right">'.$langs->trans("Discount").'</td>'; print '<td>&nbsp;</td>'; print '</tr>'; - foreach ($object->prices_by_qty_list[$i] as $ii => $prices) - { + foreach ($object->prices_by_qty_list[$i] as $ii => $prices) { if ($action == 'edit_price_by_qty' && $rowid == $prices['rowid'] && ($user->rights->produit->creer || $user->rights->service->creer)) { print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -963,15 +956,23 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print '<tr><td class="titlefield">'.$langs->trans("DefaultTaxRate").'</td><td>'; $positiverates = ''; - if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates = '0'; + if (price2num($object->tva_tx)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + } + if (price2num($object->localtax1_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + } + if (price2num($object->localtax2_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + } + if (empty($positiverates)) { + $positiverates = '0'; + } echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); /* if ($object->default_vat_code) { - print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; + print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; } else print vatrate($object->tva_tx, true, $object->tva_npr, true);*/ print '</td></tr>'; @@ -995,8 +996,7 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print '</td></tr>'; // Price by quantity - if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) // TODO Fix the form inside tr instead of td - { + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { // TODO Fix the form inside tr instead of td print '<tr><td>'.$langs->trans("PriceByQuantity"); if ($object->prices_by_qty[0] == 0) { print '&nbsp; <a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=activate_price_by_qty&level=1">('.$langs->trans("Activate").')'; @@ -1005,8 +1005,7 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ } print '</td><td>'; - if ($object->prices_by_qty[0] == 1) - { + if ($object->prices_by_qty[0] == 1) { print '<table width="50%" class="border" summary="List of quantities">'; print '<tr class="liste_titre">'; //print '<td>' . $langs->trans("PriceByQuantityRange") . '</td>'; @@ -1017,8 +1016,7 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print '<td class="right">'.$langs->trans("Discount").'</td>'; print '<td>&nbsp;</td>'; print '</tr>'; - if ($action != 'edit_price_by_qty') - { + if ($action != 'edit_price_by_qty') { print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">'; // FIXME a form into a table is not allowed print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update_price_by_qty">'; @@ -1038,10 +1036,8 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print '</form>'; } - foreach ($object->prices_by_qty_list[0] as $ii => $prices) - { - if ($action == 'edit_price_by_qty' && $rowid == $prices['rowid'] && ($user->rights->produit->creer || $user->rights->service->creer)) - { + foreach ($object->prices_by_qty_list[0] as $ii => $prices) { + if ($action == 'edit_price_by_qty' && $rowid == $prices['rowid'] && ($user->rights->produit->creer || $user->rights->service->creer)) { print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update_price_by_qty">'; @@ -1070,8 +1066,7 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print '<td class="right">'.price($prices['unitprice']).'</td>'; print '<td class="right">'.price($prices['remise_percent']).' %</td>'; print '<td class="center">'; - if (($user->rights->produit->creer || $user->rights->service->creer)) - { + if (($user->rights->produit->creer || $user->rights->service->creer)) { print '<a class="editfielda marginleftonly marginrightonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit_price_by_qty&amp;rowid='.$prices["rowid"].'">'; print img_edit().'</a>'; print '<a class="marginleftonly marginrightonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete_price_by_qty&amp;token='.newToken().'&amp;rowid='.$prices["rowid"].'">'; @@ -1101,15 +1096,11 @@ print dol_get_fiche_end(); -/* ************************************************************************** */ -/* */ -/* Barre d'action */ -/* */ -/* ************************************************************************** */ - +/* + * Action bar + */ if (!$action || $action == 'delete' || $action == 'showlog_customer_price' || $action == 'showlog_default_price' || $action == 'add_customer_price' - || $action == 'activate_price_by_qty' || $action == 'disable_price_by_qty') -{ + || $action == 'activate_price_by_qty' || $action == 'disable_price_by_qty') { print "\n".'<div class="tabsAction">'."\n"; if ($object->isVariant()) { @@ -1149,8 +1140,7 @@ if (!$action || $action == 'delete' || $action == 'showlog_customer_price' || $a * Edit price area */ -if ($action == 'edit_vat' && ($user->rights->produit->creer || $user->rights->service->creer)) -{ +if ($action == 'edit_vat' && ($user->rights->produit->creer || $user->rights->service->creer)) { print load_fiche_titre($langs->trans("UpdateVAT"), ''); print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">'; @@ -1180,12 +1170,10 @@ if ($action == 'edit_vat' && ($user->rights->produit->creer || $user->rights->se print '<br></form><br>'; } -if ($action == 'edit_price' && $object->getRights()->creer) -{ +if ($action == 'edit_price' && $object->getRights()->creer) { print load_fiche_titre($langs->trans("NewPrice"), ''); - if (empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) - { + if (empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { print '<!-- Edit price -->'."\n"; print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -1194,6 +1182,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) print dol_get_fiche_head(''); + print '<div class="div-table-responsive-no-min">'; print '<table class="border centpercent">'; // VAT @@ -1210,7 +1199,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) print '</td>'; print '</tr>'; - // Only show price mode and expression selector if module is enabled + // Only show price mode and expression selector if module is enabled if (!empty($conf->dynamicprices->enabled)) { // Price mode selector print '<tr><td>'.$langs->trans("PriceMode").'</td><td>'; @@ -1270,8 +1259,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) } else { print '<input name="price_min" size="10" value="'.price($object->price_min).'">'; } - if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) - { + if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { print ' &nbsp; '.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')).' '.img_warning().'</td>'; } print '</td>'; @@ -1281,6 +1269,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print '</table>'; + print '</div>'; print dol_get_fiche_end(); @@ -1328,13 +1317,17 @@ if ($action == 'edit_price' && $object->getRights()->creer) print $langs->trans('UseMultipriceRules').' <input type="checkbox" id="usePriceRules" name="usePriceRules" '.($object->price_autogen ? 'checked' : '').'><br><br>'; } + print '<div class="div-table-responsive-no-min">'; print '<table class="noborder">'; print '<thead><tr class="liste_titre">'; print '<td>'.$langs->trans("PriceLevel").'</td>'; - if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) print '<td style="text-align: center">'.$langs->trans("DefaultTaxRate").'</td>'; - else print '<td></td>'; + if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { + print '<td style="text-align: center">'.$langs->trans("DefaultTaxRate").'</td>'; + } else { + print '<td></td>'; + } print '<td class="center">'.$langs->trans("SellingPrice").'</td>'; @@ -1347,8 +1340,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) print '<tbody>'; - for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) - { + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { print '<tr class="oddeven">'; print '<td>'; $text = $langs->trans('SellingPrice').' '.$i; @@ -1389,8 +1381,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) } else { print '<input name="price_min['.$i.']" size="10" value="'.price($object->multiprices_min [$i]).'">'; } - if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) - { + if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { print '<td class="left">'.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')).' '.img_warning().'</td>'; } print '</td>'; @@ -1401,6 +1392,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) print '</tbody>'; print '</table>'; + print '</div>'; //print dol_get_fiche_end(); @@ -1415,8 +1407,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) // List of price changes - log historic (ordered by descending date) -if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action == 'showlog_default_price') && !in_array($action, array('edit_price', 'edit_vat'))) -{ +if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action == 'showlog_default_price') && !in_array($action, array('edit_price', 'edit_vat'))) { $sql = "SELECT p.rowid, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.default_vat_code, p.recuperableonly, p.localtax1_tx, p.localtax1_type, p.localtax2_tx, p.localtax2_type,"; $sql .= " p.price_level, p.price_min, p.price_min_ttc,p.price_by_qty,"; $sql .= " p.date_price as dp, p.fk_price_expression, u.rowid as user_id, u.login"; @@ -1425,29 +1416,29 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action == 'showlog_defaul $sql .= " WHERE fk_product = ".$object->id; $sql .= " AND p.entity IN (".getEntity('productprice').")"; $sql .= " AND p.fk_user_author = u.rowid"; - if (!empty($socid) && !empty($conf->global->PRODUIT_MULTIPRICES)) $sql .= " AND p.price_level = ".$soc->price_level; + if (!empty($socid) && !empty($conf->global->PRODUIT_MULTIPRICES)) { + $sql .= " AND p.price_level = ".$soc->price_level; + } $sql .= " ORDER BY p.date_price DESC, p.rowid DESC, p.price_level ASC"; // $sql .= $db->plimit(); $result = $db->query($sql); - if ($result) - { + if ($result) { print '<div class="divlogofpreviouscustomerprice">'; $num = $db->num_rows($result); - if (!$num) - { + if (!$num) { $db->free($result); - // Il doit au moins y avoir la ligne de prix initial. - // On l'ajoute donc pour remettre a niveau (pb vieilles versions) - // We emulate the change of the price from interface with the same value than the one into table llx_product - if (!empty($conf->global->PRODUIT_MULTIPRICES)) { - $object->updatePrice(($object->multiprices_base_type[1] == 'TTC' ? $object->multiprices_ttc[1] : $object->multiprices[1]), $object->multiprices_base_type[1], $user, (empty($object->multiprices_tva_tx[1]) ? 0 : $object->multiprices_tva_tx[1]), ($object->multiprices_base_type[1] == 'TTC' ? $object->multiprices_min_ttc[1] : $object->multiprices_min[1]), 1); - } else { - $object->updatePrice(($object->price_base_type == 'TTC' ? $object->price_ttc : $object->price), $object->price_base_type, $user, $object->tva_tx, ($object->price_base_type == 'TTC' ? $object->price_min_ttc : $object->price_min)); - } + // Il doit au moins y avoir la ligne de prix initial. + // On l'ajoute donc pour remettre a niveau (pb vieilles versions) + // We emulate the change of the price from interface with the same value than the one into table llx_product + if (!empty($conf->global->PRODUIT_MULTIPRICES)) { + $object->updatePrice(($object->multiprices_base_type[1] == 'TTC' ? $object->multiprices_ttc[1] : $object->multiprices[1]), $object->multiprices_base_type[1], $user, (empty($object->multiprices_tva_tx[1]) ? 0 : $object->multiprices_tva_tx[1]), ($object->multiprices_base_type[1] == 'TTC' ? $object->multiprices_min_ttc[1] : $object->multiprices_min[1]), 1); + } else { + $object->updatePrice(($object->price_base_type == 'TTC' ? $object->price_ttc : $object->price), $object->price_base_type, $user, $object->tva_tx, ($object->price_base_type == 'TTC' ? $object->price_min_ttc : $object->price_min)); + } $result = $db->query($sql); $num = $db->num_rows($result); @@ -1458,8 +1449,11 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action == 'showlog_defaul // Log of previous customer prices $backbutton = '<a class="justalink" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'">'.$langs->trans("Back").'</a>'; - if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print_barre_liste($langs->trans("DefaultPriceLog"), 0, $_SERVER["PHP_SELF"], '', '', '', $backbutton, 0, $num, 'title_accountancy.png'); - else print_barre_liste($langs->trans("PriceByCustomerLog"), 0, $_SERVER["PHP_SELF"], '', '', '', '', 0, $num, 'title_accountancy.png'); + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { + print_barre_liste($langs->trans("DefaultPriceLog"), 0, $_SERVER["PHP_SELF"], '', '', '', $backbutton, 0, $num, 'title_accountancy.png'); + } else { + print_barre_liste($langs->trans("PriceByCustomerLog"), 0, $_SERVER["PHP_SELF"], '', '', '', '', 0, $num, 'title_accountancy.png'); + } print '<div class="div-table-responsive">'; print '<table class="liste centpercent">'; @@ -1476,7 +1470,9 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action == 'showlog_defaul print '<td class="center">'.$langs->trans("PriceBase").'</td>'; print $conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL; - if (empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) print '<td class="right">'.$langs->trans("DefaultTaxRate").'</td>'; + if (empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { + print '<td class="right">'.$langs->trans("DefaultTaxRate").'</td>'; + } print '<td class="right">'.$langs->trans("HT").'</td>'; print '<td class="right">'.$langs->trans("TTC").'</td>'; if (!empty($conf->dynamicprices->enabled)) { @@ -1485,28 +1481,27 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action == 'showlog_defaul print '<td class="right">'.$langs->trans("MinPrice").' '.$langs->trans("HT").'</td>'; print '<td class="right">'.$langs->trans("MinPrice").' '.$langs->trans("TTC").'</td>'; print '<td class="right">'.$langs->trans("ChangedBy").'</td>'; - if ($user->rights->produit->supprimer) + if ($user->rights->produit->supprimer) { print '<td class="right">&nbsp;</td>'; + } print '</tr>'; $notfirstlineforlevel = array(); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($result); print '<tr class="oddeven">'; // Date - print "<td>".dol_print_date($db->jdate($objp->dp), "dayhour")."</td>"; + print "<td>".dol_print_date($db->jdate($objp->dp), "dayhour", 'tzuserrel')."</td>"; // Price level if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { print '<td class="center">'.$objp->price_level."</td>"; } // Price by quantity - if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) - { + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { $type = ($objp->price_by_qty == 1) ? 'PriceByQuantity' : 'Standard'; print '<td class="center">'.$langs->trans($type)."</td>"; } @@ -1517,31 +1512,37 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action == 'showlog_defaul } print "</td>"; - if (empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) - { + if (empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { print '<td class="right">'; if (empty($objp->price_by_qty)) { $positiverates = ''; - if (price2num($objp->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($objp->tva_tx); - if (price2num($objp->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($objp->localtax1_tx); - if (price2num($objp->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($objp->localtax2_tx); - if (empty($positiverates)) $positiverates = '0'; + if (price2num($objp->tva_tx)) { + $positiverates .= ($positiverates ? '/' : '').price2num($objp->tva_tx); + } + if (price2num($objp->localtax1_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($objp->localtax1_tx); + } + if (price2num($objp->localtax2_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($objp->localtax2_tx); + } + if (empty($positiverates)) { + $positiverates = '0'; + } echo vatrate($positiverates.($objp->default_vat_code ? ' ('.$objp->default_vat_code.')' : ''), '%', $objp->tva_npr); /* - if ($objp->default_vat_code) - { - print vatrate($objp->tva_tx, true) . ' ('.$objp->default_vat_code.')'; - } - else print vatrate($objp->tva_tx, true, $objp->recuperableonly);*/ + if ($objp->default_vat_code) + { + print vatrate($objp->tva_tx, true) . ' ('.$objp->default_vat_code.')'; + } + else print vatrate($objp->tva_tx, true, $objp->recuperableonly);*/ } print "</td>"; } // Price - if (!empty($objp->fk_price_expression) && !empty($conf->dynamicprices->enabled)) - { + if (!empty($objp->fk_price_expression) && !empty($conf->dynamicprices->enabled)) { $price_expression = new PriceExpression($db); $res = $price_expression->fetch($objp->fk_price_expression); $title = $price_expression->title; @@ -1586,22 +1587,26 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action == 'showlog_defaul print '</td>'; // Action - if ($user->rights->produit->supprimer) - { + if ($user->rights->produit->supprimer) { $candelete = 0; - if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) - { - if (empty($notfirstlineforlevel[$objp->price_level])) $notfirstlineforlevel[$objp->price_level] = 1; - else $candelete = 1; - } elseif ($i > 0) $candelete = 1; + if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { + if (empty($notfirstlineforlevel[$objp->price_level])) { + $notfirstlineforlevel[$objp->price_level] = 1; + } else { + $candelete = 1; + } + } elseif ($i > 0) { + $candelete = 1; + } print '<td class="right">'; - if ($candelete) - { + if ($candelete) { print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete&amp;token='.newToken().'&amp;id='.$object->id.'&amp;lineid='.$objp->rowid.'">'; print img_delete(); print '</a>'; - } else print '&nbsp;'; // Can not delete last price (it's current price) + } else { + print '&nbsp;'; // Can not delete last price (it's current price) + } print '</td>'; } @@ -1623,22 +1628,25 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action == 'showlog_defaul // Add area to show/add/edit a price for a dedicated customer -if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) -{ +if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { $prodcustprice = new Productcustomerprice($db); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = (GETPOST("page", 'int') ?GETPOST("page", 'int') : 0); - 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) + if (!$sortorder) { $sortorder = "ASC"; - if (!$sortfield) + } + if (!$sortfield) { $sortfield = "soc.nom"; + } // Build filter to diplay only concerned lines $filter = array('t.fk_product' => $object->id); @@ -1647,8 +1655,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) $filter['soc.nom'] = $search_soc; } - if ($action == 'add_customer_price') - { + if ($action == 'add_customer_price') { // Form to add a new customer price $maxpricesupplier = $object->min_recommended_price(); @@ -1659,13 +1666,11 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<input type="hidden" name="action" value="add_customer_price_confirm">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; - print dol_get_fiche_head(); - print '<table class="liste centpercent">'; print '<tr>'; print '<td class="fieldrequired">'.$langs->trans('ThirdParty').'</td>'; print '<td>'; - print $form->select_company('', 'socid', 's.client IN (1,2,3)', 'SelectThirdParty', 0, 0, array(), 0, 'minwidth300'); + print img_picto('', 'company').$form->select_company('', 'socid', 's.client IN (1,2,3)', 'SelectThirdParty', 0, 0, array(), 0, 'minwidth300'); print '</td>'; print '</tr>'; @@ -1708,22 +1713,20 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) } else { print '<td><input name="price_min" size="10" value="'.price($object->price_min).'">'; } - if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) - { + if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { print '<td class="left">'.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')).' '.img_warning().'</td>'; } print '</td></tr>'; print '</table>'; - print dol_get_fiche_end(); print '<div class="center">'; // Update all child soc print '<div class="marginbottomonly">'; - print '<input type="checkbox" name="updatechildprice" value="1"> '; - print $langs->trans('ForceUpdateChildPriceSoc'); + print '<input type="checkbox" name="updatechildprice" id="updatechildprice" value="1"> '; + print '<label for="updatechildprice">'.$langs->trans('ForceUpdateChildPriceSoc').'</label>'; print '</div>'; print '<input type="submit" class="button button-save" value="'.$langs->trans("Save").'">'; @@ -1732,8 +1735,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '</div>'; print '</form>'; - } elseif ($action == 'edit_customer_price') - { + } elseif ($action == 'edit_customer_price') { // Edit mode $maxpricesupplier = $object->min_recommended_price(); @@ -1749,14 +1751,12 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<input type="hidden" name="action" value="update_customer_price_confirm">'; print '<input type="hidden" name="lineid" value="'.$prodcustprice->id.'">'; - print dol_get_fiche_head(); - print '<table class="liste centpercent">'; print '<tr>'; - print '<td class="titlefield">'.$langs->trans('ThirdParty').'</td>'; + print '<td class="titlefield fieldrequired">'.$langs->trans('ThirdParty').'</td>'; $staticsoc = new Societe($db); $staticsoc->fetch($prodcustprice->fk_soc); - print "<td colspan='2'>".$staticsoc->getNomUrl(1)."</td>"; + print "<td>".$staticsoc->getNomUrl(1)."</td>"; print '</tr>'; // Ref. Customer @@ -1764,12 +1764,12 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<td><input name="ref_customer" size="12" value="' . dol_escape_htmltag($prodcustprice->ref_customer) . '"></td></tr>'; // VAT - print '<tr><td>'.$langs->trans("DefaultTaxRate").'</td><td colspan="2">'; + print '<tr><td class="fieldrequired">'.$langs->trans("DefaultTaxRate").'</td><td>'; print $form->load_tva("tva_tx", $prodcustprice->default_vat_code ? $prodcustprice->tva_tx.' ('.$prodcustprice->default_vat_code.')' : $prodcustprice->tva_tx, $mysoc, '', $object->id, $prodcustprice->recuperableonly, $object->type, false, 1); print '</td></tr>'; // Price base - print '<tr><td>'; + print '<tr><td class="fieldrequired">'; print $langs->trans('PriceBase'); print '</td>'; print '<td>'; @@ -1778,7 +1778,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '</tr>'; // Price - print '<tr><td>'; + print '<tr><td class="fieldrequired">'; $text = $langs->trans('SellingPrice'); print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); print '</td><td>'; @@ -1800,27 +1800,18 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<input name="price_min" size="10" value="'.price($prodcustprice->price_min).'">'; } print '</td>'; - if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) - { + if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { print '<td class="left">'.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')).' '.img_warning().'</td>'; } print '</tr>'; - // Update all child soc - print '<tr><td>'; - print '</td>'; - print '<td>'; - print '</td>'; - print '</tr>'; - print '</table>'; - print dol_get_fiche_end(); print '<div class="center">'; print '<div class="marginbottomonly">'; - print '<input type="checkbox" name="updatechildprice" value="1"> '; - print $langs->trans('ForceUpdateChildPriceSoc'); + print '<input type="checkbox" name="updatechildprice" id="updatechildprice" value="1"> '; + print '<label for="updatechildprice">'.$langs->trans('ForceUpdateChildPriceSoc').'</label>'; print "</div>"; print '<input type="submit" class="button button-save" value="'.$langs->trans("Save").'">'; @@ -1829,8 +1820,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '</div>'; print '<br></form>'; - } elseif ($action == 'showlog_customer_price') - { + } elseif ($action == 'showlog_customer_price') { // List of all log of prices by customers print '<!-- list of all log of prices per customer -->'."\n"; @@ -1859,12 +1849,12 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print_barre_liste($title, $page, $_SERVER['PHP_SELF'], $option, $sortfield, $sortorder, $backbutton, count($prodcustprice->lines), $nbtotalofrecords, 'title_accountancy.png'); - if (count($prodcustprice->lines) > 0) - { + if (count($prodcustprice->lines) > 0) { print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; + print '<div class="div-table-responsive-no-min">'; print '<table class="liste centpercent">'; print '<tr class="liste_titre">'; @@ -1874,8 +1864,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<td class="center">'.$langs->trans("PriceBase").'</td>'; print '<td class="right">'.$langs->trans("DefaultTaxRate").'</td>'; print '<td class="right">'.$langs->trans("HT").'</td>'; - if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") - { + if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") { //print '<td class="right">' . $langs->trans("INCVATONLY") . '</td>'; print '<td class="right">'.$langs->trans("INCT").'</td>'; } else { @@ -1887,8 +1876,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<td>&nbsp;</td>'; print '</tr>'; - foreach ($prodcustprice->lines as $line) - { + foreach ($prodcustprice->lines as $line) { // Date $staticsoc = new Societe($db); $staticsoc->fetch($line->fk_soc); @@ -1896,8 +1884,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) $tva_tx = $line->default_vat_code ? $line->tva_tx.' ('.$line->default_vat_code.')' : $line->tva_tx; // Line for default price - if ($line->price_base_type == 'HT') - { + if ($line->price_base_type == 'HT') { $pu = $line->price; } else { $pu = $line->price_ttc; @@ -1917,16 +1904,24 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<tr class="oddeven">'; print "<td>".$staticsoc->getNomUrl(1)."</td>"; - print '<td>' . $line->ref_customer . '</td>'; - print "<td>".dol_print_date($line->datec, "dayhour")."</td>"; + print '<td>'.$line->ref_customer.'</td>'; + print "<td>".dol_print_date($line->datec, "dayhour", 'tzuserrel')."</td>"; print '<td class="center">'.$langs->trans($line->price_base_type)."</td>"; print '<td class="right">'; $positiverates = ''; - if (price2num($line->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($line->tva_tx); - if (price2num($line->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax1_tx); - if (price2num($line->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax2_tx); - if (empty($positiverates)) $positiverates = '0'; + if (price2num($line->tva_tx)) { + $positiverates .= ($positiverates ? '/' : '').price2num($line->tva_tx); + } + if (price2num($line->localtax1_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax1_tx); + } + if (price2num($line->localtax2_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax2_tx); + } + if (empty($positiverates)) { + $positiverates = '0'; + } echo vatrate($positiverates.($line->default_vat_code ? ' ('.$line->default_vat_code.')' : ''), '%', ($line->tva_npr ? $line->tva_npr : $line->recuperableonly)); @@ -1934,8 +1929,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print "</td>"; print '<td class="right">'.price($line->price)."</td>"; - if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") - { + if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") { //print '<td class="right">' . price($line->price_ttc) . "</td>"; print '<td class="right">'.price($resultarray[2]).'</td>'; } else { @@ -1955,11 +1949,11 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '</tr>'; } print "</table>"; + print '</div>'; } else { print $langs->trans('None'); } - } elseif ($action != 'showlog_default_price' && $action != 'edit_price') - { + } elseif ($action != 'showlog_default_price' && $action != 'edit_price') { // List of all prices by customers print '<!-- list of all prices per customer -->'."\n"; @@ -1982,10 +1976,10 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; + print '<div class="div-table-responsive-no-min">'; print '<table class="liste centpercent">'; - if (count($prodcustprice->lines) > 0 || $search_soc) - { + if (count($prodcustprice->lines) > 0 || $search_soc) { $colspan = 9; //if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") $colspan++; @@ -2007,8 +2001,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<td class="center">'.$langs->trans("PriceBase").'</td>'; print '<td class="right">'.$langs->trans("DefaultTaxRate").'</td>'; print '<td class="right">'.$langs->trans("HT").'</td>'; - if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") - { + if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") { //print '<td class="right">' . $langs->trans("INCVATONLY") . '</td>'; print '<td class="right">'.$langs->trans("INCT").'</td>'; } else { @@ -2018,12 +2011,11 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<td class="right">'.$langs->trans("MinPrice").' '.$langs->trans("HT").'</td>'; print '<td class="right">'.$langs->trans("MinPrice").' '.$langs->trans("TTC").'</td>'; print '<td class="right">'.$langs->trans("ChangedBy").'</td>'; - print '<td>&nbsp;</td>'; + print '<td></td>'; print '</tr>'; // Line for default price - if ($object->price_base_type == 'HT') - { + if ($object->price_base_type == 'HT') { $pu = $object->price; } else { $pu = $object->price_ttc; @@ -2047,10 +2039,18 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<td class="right">'; $positiverates = ''; - if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates = '0'; + if (price2num($object->tva_tx)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + } + if (price2num($object->localtax1_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + } + if (price2num($object->localtax2_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + } + if (empty($positiverates)) { + $positiverates = '0'; + } echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); //print vatrate($object->tva_tx, true, $object->tva_npr); @@ -2059,8 +2059,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<td class="right">'.price($object->price)."</td>"; - if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") - { + if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") { //print '<td class="right">' . price($object->price_ttc) . "</td>"; print '<td class="right">'.price($resultarray[2]).'</td>'; } else { @@ -2072,25 +2071,21 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '<td class="right">'.price($object->price_min_ttc).'</td>'; print '<td class="right">'; print '</td>'; - if ($user->rights->produit->supprimer || $user->rights->service->supprimer) - { - print '<td class="right">'; - print '<a href="'.$_SERVER["PHP_SELF"].'?action=showlog_default_price&amp;id='.$object->id.'">'; + if ($user->rights->produit->supprimer || $user->rights->service->supprimer) { + print '<td class="nowraponall">'; + print '<a class="marginleftonly marginrightonly" href="'.$_SERVER["PHP_SELF"].'?action=showlog_default_price&amp;id='.$object->id.'">'; print img_info($langs->trans('PriceByCustomerLog')); print '</a>'; print ' '; - print '<a class="marginleftonly editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edit_price&amp;id='.$object->id.'">'; + print '<a class="marginleftonly marginrightonly editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edit_price&amp;id='.$object->id.'">'; print img_edit('default', 0, 'style="vertical-align: middle;"'); print '</a>'; - print ' &nbsp; '; print '</td>'; } print "</tr>\n"; - if (count($prodcustprice->lines) > 0) - { - foreach ($prodcustprice->lines as $line) - { + if (count($prodcustprice->lines) > 0) { + foreach ($prodcustprice->lines as $line) { // Date $staticsoc = new Societe($db); $staticsoc->fetch($line->fk_soc); @@ -2098,8 +2093,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) $tva_tx = $line->default_vat_code ? $line->tva_tx.' ('.$line->default_vat_code.')' : $line->tva_tx; // Line for default price - if ($line->price_base_type == 'HT') - { + if ($line->price_base_type == 'HT') { $pu = $line->price; } else { $pu = $line->price_ttc; @@ -2120,23 +2114,30 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print "<td>".$staticsoc->getNomUrl(1)."</td>"; print '<td>' . $line->ref_customer . '</td>'; - print "<td>".dol_print_date($line->datec, "dayhour")."</td>"; - + print "<td>".dol_print_date($line->datec, "dayhour", 'tzuserrel')."</td>"; print '<td class="center">'.$langs->trans($line->price_base_type)."</td>"; print '<td class="right">'; $positiverates = ''; - if (price2num($line->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($line->tva_tx); - if (price2num($line->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax1_tx); - if (price2num($line->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax2_tx); - if (empty($positiverates)) $positiverates = '0'; + if (price2num($line->tva_tx)) { + $positiverates .= ($positiverates ? '/' : '').price2num($line->tva_tx); + } + if (price2num($line->localtax1_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax1_tx); + } + if (price2num($line->localtax2_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax2_tx); + } + if (empty($positiverates)) { + $positiverates = '0'; + } + echo vatrate($positiverates.($line->default_vat_code ? ' ('.$line->default_vat_code.')' : ''), '%', ($line->tva_npr ? $line->tva_npr : $line->recuperableonly)); print "</td>"; print '<td class="right">'.price($line->price)."</td>"; - if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") - { + if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") { //print '<td class="right">' . price($line->price_ttc) . "</td>"; print '<td class="right">'.price($resultarray[2]).'</td>'; } else { @@ -2155,8 +2156,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) // Todo Edit or delete button // Action - if ($user->rights->produit->supprimer || $user->rights->service->supprimer) - { + if ($user->rights->produit->supprimer || $user->rights->service->supprimer) { print '<td class="right nowraponall">'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=showlog_customer_price&amp;id='.$object->id.'&amp;socid='.$line->fk_soc.'">'; print img_info($langs->trans('PriceByCustomerLog')); @@ -2175,16 +2175,9 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print "</tr>\n"; } } - /*else - { - $colspan=9; - if ($user->rights->produit->supprimer || $user->rights->service->supprimer) $colspan+=1; - print "<tr ".$bc[false].">"; - print '<td colspan="'.$colspan.'">'.$langs->trans('None').'</td>'; - print "</tr>"; - }*/ print "</table>"; + print '</div>'; print "</form>"; } diff --git a/htdocs/product/reassort.php b/htdocs/product/reassort.php index 715ad66e977..e0d1d7447a0 100644 --- a/htdocs/product/reassort.php +++ b/htdocs/product/reassort.php @@ -36,7 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $langs->loadLangs(array('products', 'stocks')); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service'); @@ -55,11 +57,19 @@ $fourn_id = GETPOST("fourn_id", 'int'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page < 0) $page = 0; -if (!$sortfield) $sortfield = "p.ref"; -if (!$sortorder) $sortorder = "ASC"; +if (empty($page) || $page < 0) { + $page = 0; +} +if (!$sortfield) { + $sortfield = "p.ref"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -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; // Load sale and categ filters @@ -69,8 +79,7 @@ $search_categ = GETPOST("search_categ"); // Get object canvas (By default, this is not defined, so standard usage of dolibarr) $canvas = GETPOST("canvas"); $objcanvas = null; -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('product', 'list', $canvas); @@ -83,8 +92,7 @@ if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE) - || !empty($conf->mrp->enabled)) -{ + || !empty($conf->mrp->enabled)) { $virtualdiffersfromphysical = 1; // According to increase/decrease stock options, virtual and physical stock may differs. } @@ -97,8 +105,7 @@ $hookmanager->initHooks(array('productreassortlist')); * Actions */ -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 $sref = ""; $snom = ""; $sall = ""; @@ -128,7 +135,9 @@ $sql = 'SELECT p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price $sql .= ' p.fk_product_type, p.tms as datem,'; $sql .= ' p.duration, p.tosell as statut, p.tobuy, p.seuil_stock_alerte, p.desiredstock,'; $sql .= ' SUM(s.reel) as stock_physique'; -if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= ', u.short_label as unit_short'; +if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $sql .= ', u.short_label as unit_short'; +} // Add fields from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook @@ -136,49 +145,73 @@ $sql .= $hookmanager->resPrint; $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as s ON p.rowid = s.fk_product'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot as e ON s.fk_entrepot = e.rowid AND e.entity IN ('.getEntity('entrepot').')'; -if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_units as u on p.fk_unit = u.rowid'; +if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_units as u on p.fk_unit = u.rowid'; +} // We'll need this table joined to the select in order to filter by categ -if ($search_categ) $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp"; +if ($search_categ) { + $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp"; +} $sql .= " WHERE p.entity IN (".getEntity('product').")"; -if ($search_categ) $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ -if ($sall) $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); +if ($search_categ) { + $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ +} +if ($sall) { + $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); +} // if the type is not 1, we show all products (type = 0,2,3) -if (dol_strlen($type)) -{ - if ($type == 1) - { +if (dol_strlen($type)) { + if ($type == 1) { $sql .= " AND p.fk_product_type = '1'"; } else { $sql .= " AND p.fk_product_type <> '1'"; } } -if ($sref) $sql .= natural_search('p.ref', $sref); -if ($search_barcode) $sql .= natural_search('p.barcode', $search_barcode); -if ($snom) $sql .= natural_search('p.label', $snom); -if (!empty($tosell)) $sql .= " AND p.tosell = ".$tosell; -if (!empty($tobuy)) $sql .= " AND p.tobuy = ".$tobuy; -if (!empty($canvas)) $sql .= " AND p.canvas = '".$db->escape($canvas)."'"; -if ($catid) $sql .= " AND cp.fk_categorie = ".$catid; -if ($fourn_id > 0) $sql .= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id; +if ($sref) { + $sql .= natural_search('p.ref', $sref); +} +if ($search_barcode) { + $sql .= natural_search('p.barcode', $search_barcode); +} +if ($snom) { + $sql .= natural_search('p.label', $snom); +} +if (!empty($tosell)) { + $sql .= " AND p.tosell = ".$tosell; +} +if (!empty($tobuy)) { + $sql .= " AND p.tobuy = ".$tobuy; +} +if (!empty($canvas)) { + $sql .= " AND p.canvas = '".$db->escape($canvas)."'"; +} +if ($catid) { + $sql .= " AND cp.fk_categorie = ".$catid; +} +if ($fourn_id > 0) { + $sql .= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id; +} // Insert categ filter -if ($search_categ) $sql .= " AND cp.fk_categorie = ".$db->escape($search_categ); +if ($search_categ) { + $sql .= " AND cp.fk_categorie = ".$db->escape($search_categ); +} $sql .= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,"; $sql .= " p.fk_product_type, p.tms, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock"; // Add fields from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldSelect', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; -if ($toolowstock) $sql .= " HAVING SUM(".$db->ifsql('s.reel IS NULL', '0', 's.reel').") < p.seuil_stock_alerte"; +if ($toolowstock) { + $sql .= " HAVING SUM(".$db->ifsql('s.reel IS NULL', '0', 's.reel').") < p.seuil_stock_alerte"; +} $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -187,41 +220,68 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num == 1 && GETPOST('autojumpifoneonly') && ($sall || $snom || $sref)) - { + if ($num == 1 && GETPOST('autojumpifoneonly') && ($sall || $snom || $sref)) { $objp = $db->fetch_object($resql); header("Location: card.php?id=$objp->rowid"); exit; } - if (isset($type)) - { - if ($type == 1) { $texte = $langs->trans("Services"); } else { $texte = $langs->trans("Products"); } + if (isset($type)) { + if ($type == 1) { + $texte = $langs->trans("Services"); + } else { + $texte = $langs->trans("Products"); + } } else { $texte = $langs->trans("ProductsAndServices"); } $texte .= ' ('.$langs->trans("MenuStocks").')'; $param = ''; - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($sall) $param .= "&sall=".urlencode($sall); - if ($tosell) $param .= "&tosell=".urlencode($tosell); - if ($tobuy) $param .= "&tobuy=".urlencode($tobuy); - if ($type) $param .= "&type=".urlencode($type); - if ($fourn_id) $param .= "&fourn_id=".urlencode($fourn_id); - if ($snom) $param .= "&snom=".urlencode($snom); - if ($sref) $param .= "&sref=".urlencode($sref); - if ($search_sale) $param .= "&search_sale=".urlencode($search_sale); - if ($search_categ) $param .= "&search_categ=".urlencode($search_categ); - if ($toolowstock) $param .= "&toolowstock=".urlencode($toolowstock); - if ($sbarcode) $param .= "&sbarcode=".urlencode($sbarcode); - if ($catid) $param .= "&catid=".urlencode($catid); + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($sall) { + $param .= "&sall=".urlencode($sall); + } + if ($tosell) { + $param .= "&tosell=".urlencode($tosell); + } + if ($tobuy) { + $param .= "&tobuy=".urlencode($tobuy); + } + if ($type) { + $param .= "&type=".urlencode($type); + } + if ($fourn_id) { + $param .= "&fourn_id=".urlencode($fourn_id); + } + if ($snom) { + $param .= "&snom=".urlencode($snom); + } + if ($sref) { + $param .= "&sref=".urlencode($sref); + } + if ($search_sale) { + $param .= "&search_sale=".urlencode($search_sale); + } + if ($search_categ) { + $param .= "&search_categ=".urlencode($search_categ); + } + if ($toolowstock) { + $param .= "&toolowstock=".urlencode($toolowstock); + } + if ($sbarcode) { + $param .= "&sbarcode=".urlencode($sbarcode); + } + if ($catid) { + $param .= "&catid=".urlencode($catid); + } llxHeader("", $texte, $helpurl); @@ -234,8 +294,7 @@ if ($resql) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'product', 0, '', '', $limit); - if (!empty($catid)) - { + if (!empty($catid)) { print "<div id='ways'>"; $c = new Categorie($db); $c->fetch($catid); @@ -245,21 +304,19 @@ if ($resql) } // Filter on categories - $moreforfilter = ''; - if (!empty($conf->categorie->enabled)) - { - $moreforfilter .= '<div class="divsearchfield">'; - $moreforfilter .= $langs->trans('Categories').': '; + $moreforfilter = ''; + if (!empty($conf->categorie->enabled)) { + $moreforfilter .= '<div class="divsearchfield">'; + $moreforfilter .= $langs->trans('Categories').': '; $moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ'); - $moreforfilter .= '</div>'; + $moreforfilter .= '</div>'; } $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans("StockTooLow").' <input type="checkbox" name="toolowstock" value="1"'.($toolowstock ? ' checked' : '').'>'; $moreforfilter .= '</div>'; - if (!empty($moreforfilter)) - { + if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; $parameters = array(); @@ -269,21 +326,39 @@ if ($resql) } $param = ''; - if ($tosell) $param .= "&tosell=".urlencode($tosell); - if ($tobuy) $param .= "&tobuy=".urlencode($tobuy); - if ($type) $param .= "&type=".urlencode($type); - if ($fourn_id) $param .= "&fourn_id=".urlencode($fourn_id); - if ($snom) $param .= "&snom=".urlencode($snom); - if ($sref) $param .= "&sref=".urlencode($sref); - if ($toolowstock) $param .= "&toolowstock=".urlencode($toolowstock); - if ($search_categ) $param .= "&search_categ=".urlencode($search_categ); + if ($tosell) { + $param .= "&tosell=".urlencode($tosell); + } + if ($tobuy) { + $param .= "&tobuy=".urlencode($tobuy); + } + if ($type) { + $param .= "&type=".urlencode($type); + } + if ($fourn_id) { + $param .= "&fourn_id=".urlencode($fourn_id); + } + if ($snom) { + $param .= "&snom=".urlencode($snom); + } + if ($sref) { + $param .= "&sref=".urlencode($sref); + } + if ($toolowstock) { + $param .= "&toolowstock=".urlencode($toolowstock); + } + if ($search_categ) { + $param .= "&search_categ=".urlencode($search_categ); + } $formProduct = new FormProduct($db); $formProduct->loadWarehouses(); $warehouses_list = $formProduct->cache_warehouses; $nb_warehouse = count($warehouses_list); $colspan_warehouse = 1; - if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) { $colspan_warehouse = $nb_warehouse > 1 ? $nb_warehouse + 1 : 1; } + if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) { + $colspan_warehouse = $nb_warehouse > 1 ? $nb_warehouse + 1 : 1; + } print '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'; @@ -297,8 +372,7 @@ if ($resql) print '<input class="flat" type="text" name="snom" size="8" value="'.$snom.'">'; print '</td>'; // Duration - if (!empty($conf->service->enabled) && $type == 1) - { + if (!empty($conf->service->enabled) && $type == 1) { print '<td class="liste_titre">'; print '&nbsp;'; print '</td>'; @@ -307,7 +381,9 @@ if ($resql) print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre right">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>'; - if ($virtualdiffersfromphysical) print '<td class="liste_titre">&nbsp;</td>'; + if ($virtualdiffersfromphysical) { + print '<td class="liste_titre">&nbsp;</td>'; + } print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre" colspan="'.$colspan_warehouse.'">&nbsp;</td>'; print '<td class="liste_titre"></td>'; @@ -315,8 +391,8 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '<td class="liste_titre maxwidthsearch">'; - $searchpicto = $form->showFilterAndCheckAddButtons(0); - print $searchpicto; + $searchpicto = $form->showFilterAndCheckAddButtons(0); + print $searchpicto; print '</td>'; print '</tr>'; @@ -324,20 +400,23 @@ if ($resql) print "<tr class=\"liste_titre\">"; print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", $param, "", "", $sortfield, $sortorder); - if (!empty($conf->service->enabled) && $type == 1) print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center '); + if (!empty($conf->service->enabled) && $type == 1) { + print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center '); + } print_liste_field_titre("StockLimit", $_SERVER["PHP_SELF"], "p.seuil_stock_alerte", $param, "", '', $sortfield, $sortorder, 'right '); print_liste_field_titre("DesiredStock", $_SERVER["PHP_SELF"], "p.desiredstock", $param, "", '', $sortfield, $sortorder, 'right '); print_liste_field_titre("PhysicalStock", $_SERVER["PHP_SELF"], "stock_physique", $param, "", '', $sortfield, $sortorder, 'right '); // Details per warehouse - if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context) - { + if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) { // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context) if ($nb_warehouse > 1) { foreach ($warehouses_list as &$wh) { print_liste_field_titre($wh['label'], '', '', '', '', '', '', '', 'right '); } } } - if ($virtualdiffersfromphysical) print_liste_field_titre("VirtualStock", $_SERVER["PHP_SELF"], "", $param, "", '', $sortfield, $sortorder, 'right ', 'VirtualStockDesc'); + if ($virtualdiffersfromphysical) { + print_liste_field_titre("VirtualStock", $_SERVER["PHP_SELF"], "", $param, "", '', $sortfield, $sortorder, 'right ', 'VirtualStockDesc'); + } // Units if (!empty($conf->global->PRODUCT_USE_UNITS)) { print_liste_field_titre("Unit", $_SERVER["PHP_SELF"], "unit_short", $param, "", 'align="right"', $sortfield, $sortorder); @@ -352,8 +431,7 @@ if ($resql) print_liste_field_titre(''); print "</tr>\n"; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($resql); $product = new Product($db); @@ -367,13 +445,17 @@ if ($resql) print '</td>'; print '<td>'.$product->label.'</td>'; - if (!empty($conf->service->enabled) && $type == 1) - { + if (!empty($conf->service->enabled) && $type == 1) { print '<td class="center">'; - if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationYear"); - elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationMonth"); - elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationDay"); - else print $objp->duration; + if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) { + print $regs[1].' '.$langs->trans("DurationYear"); + } elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) { + print $regs[1].' '.$langs->trans("DurationMonth"); + } elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) { + print $regs[1].' '.$langs->trans("DurationDay"); + } else { + print $objp->duration; + } print '</td>'; } //print '<td class="right">'.$objp->stock_theorique.'</td>'; @@ -381,13 +463,14 @@ if ($resql) print '<td class="right">'.$objp->desiredstock.'</td>'; // Real stock print '<td class="right">'; - if ($objp->seuil_stock_alerte != '' && ($objp->stock_physique < $objp->seuil_stock_alerte)) print img_warning($langs->trans("StockTooLow")).' '; + if ($objp->seuil_stock_alerte != '' && ($objp->stock_physique < $objp->seuil_stock_alerte)) { + print img_warning($langs->trans("StockTooLow")).' '; + } print price2num($objp->stock_physique, 'MS'); print '</td>'; // Details per warehouse - if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context) - { + if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) { // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context) if ($nb_warehouse > 1) { foreach ($warehouses_list as &$wh) { print '<td class="right">'; @@ -398,10 +481,11 @@ if ($resql) } // Virtual stock - if ($virtualdiffersfromphysical) - { + if ($virtualdiffersfromphysical) { print '<td class="right">'; - if ($objp->seuil_stock_alerte != '' && ($product->stock_theorique < $objp->seuil_stock_alerte)) print img_warning($langs->trans("StockTooLow")).' '; + if ($objp->seuil_stock_alerte != '' && ($product->stock_theorique < $objp->seuil_stock_alerte)) { + print img_warning($langs->trans("StockTooLow")).' '; + } print price2num($product->stock_theorique, 'MS'); print '</td>'; } diff --git a/htdocs/product/reassortlot.php b/htdocs/product/reassortlot.php index 7949c5441c1..5983d5e6b4e 100644 --- a/htdocs/product/reassortlot.php +++ b/htdocs/product/reassortlot.php @@ -38,7 +38,9 @@ require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; $langs->loadLangs(array('products', 'stocks', 'productbatch')); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service'); @@ -59,11 +61,19 @@ $fourn_id = GETPOST("fourn_id", 'int'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page < 0) $page = 0; -if (!$sortfield) $sortfield = "p.ref"; -if (!$sortorder) $sortorder = "ASC"; +if (empty($page) || $page < 0) { + $page = 0; +} +if (!$sortfield) { + $sortfield = "p.ref"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -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; // Load sale and categ filters @@ -73,8 +83,7 @@ $search_categ = GETPOST("search_categ"); // Get object canvas (By default, this is not defined, so standard usage of dolibarr) $canvas = GETPOST("canvas"); $objcanvas = null; -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('product', 'list', $canvas); @@ -86,8 +95,7 @@ if (!empty($canvas)) * Actions */ -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 $sref = ""; $snom = ""; $sall = ""; @@ -129,32 +137,58 @@ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot as e on ps.fk_entrepot = e.rowid' $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_batch as pb on pb.fk_product_stock = ps.rowid'; // Detail for each lot on each warehouse $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_lot as pl on pl.fk_product = p.rowid AND pl.batch = pb.batch'; // Link on unique key // We'll need this table joined to the select in order to filter by categ -if ($search_categ) $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp"; +if ($search_categ) { + $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp"; +} $sql .= " WHERE p.entity IN (".getEntity('product').")"; -if ($search_categ) $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ -if ($sall) $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); +if ($search_categ) { + $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ +} +if ($sall) { + $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); +} // if the type is not 1, we show all products (type = 0,2,3) -if (dol_strlen($type)) -{ - if ($type == 1) - { +if (dol_strlen($type)) { + if ($type == 1) { $sql .= " AND p.fk_product_type = '1'"; } else { $sql .= " AND p.fk_product_type <> '1'"; } } -if ($sref) $sql .= natural_search("p.ref", $sref); -if ($search_barcode) $sql .= natural_search("p.barcode", $search_barcode); -if ($snom) $sql .= natural_search("p.label", $snom); -if (!empty($tosell)) $sql .= " AND p.tosell = ".$tosell; -if (!empty($tobuy)) $sql .= " AND p.tobuy = ".$tobuy; -if (!empty($canvas)) $sql .= " AND p.canvas = '".$db->escape($canvas)."'"; -if ($catid) $sql .= " AND cp.fk_categorie = ".$catid; -if ($fourn_id > 0) $sql .= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id; +if ($sref) { + $sql .= natural_search("p.ref", $sref); +} +if ($search_barcode) { + $sql .= natural_search("p.barcode", $search_barcode); +} +if ($snom) { + $sql .= natural_search("p.label", $snom); +} +if (!empty($tosell)) { + $sql .= " AND p.tosell = ".$tosell; +} +if (!empty($tobuy)) { + $sql .= " AND p.tobuy = ".$tobuy; +} +if (!empty($canvas)) { + $sql .= " AND p.canvas = '".$db->escape($canvas)."'"; +} +if ($catid) { + $sql .= " AND cp.fk_categorie = ".$catid; +} +if ($fourn_id > 0) { + $sql .= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id; +} // Insert categ filter -if ($search_categ) $sql .= " AND cp.fk_categorie = ".$db->escape($search_categ); -if ($search_warehouse) $sql .= natural_search("e.ref", $search_warehouse); -if ($search_batch) $sql .= natural_search("pb.batch", $search_batch); +if ($search_categ) { + $sql .= " AND cp.fk_categorie = ".$db->escape($search_categ); +} +if ($search_warehouse) { + $sql .= natural_search("e.ref", $search_warehouse); +} +if ($search_batch) { + $sql .= natural_search("pb.batch", $search_batch); +} $sql .= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,"; $sql .= " p.fk_product_type, p.tms,"; $sql .= " p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p.stock, p.tosell, p.tobuy, p.tobatch,"; @@ -162,16 +196,16 @@ $sql .= " ps.fk_entrepot,"; $sql .= " e.ref, e.lieu, e.fk_parent,"; $sql .= " pb.batch, pb.eatby, pb.sellby,"; $sql .= " pl.rowid, pl.eatby, pl.sellby"; -if ($toolowstock) $sql .= " HAVING SUM(".$db->ifsql('ps.reel IS NULL', '0', 'ps.reel').") < p.seuil_stock_alerte"; // Not used yet +if ($toolowstock) { + $sql .= " HAVING SUM(".$db->ifsql('ps.reel IS NULL', '0', 'ps.reel').") < p.seuil_stock_alerte"; // Not used yet +} $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -180,43 +214,74 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num == 1 && GETPOST('autojumpifoneonly') && ($sall or $snom or $sref)) - { + if ($num == 1 && GETPOST('autojumpifoneonly') && ($sall or $snom or $sref)) { $objp = $db->fetch_object($resql); header("Location: card.php?id=$objp->rowid"); exit; } - if (isset($type)) - { - if ($type == 1) { $texte = $langs->trans("Services"); } else { $texte = $langs->trans("Products"); } + if (isset($type)) { + if ($type == 1) { + $texte = $langs->trans("Services"); + } else { + $texte = $langs->trans("Products"); + } } else { $texte = $langs->trans("ProductsAndServices"); } $texte .= ' ('.$langs->trans("StocksByLotSerial").')'; $param = ''; - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($sall) $param .= "&sall=".urlencode($sall); - if ($tosell) $param .= "&tosell=".urlencode($tosell); - if ($tobuy) $param .= "&tobuy=".urlencode($tobuy); - if ($type) $param .= "&type=".urlencode($type); - if ($fourn_id) $param .= "&fourn_id=".urlencode($fourn_id); - if ($snom) $param .= "&snom=".urlencode($snom); - if ($sref) $param .= "&sref=".urlencode($sref); - if ($search_batch) $param .= "&search_batch=".urlencode($search_batch); - if ($sbarcode) $param .= "&sbarcode=".urlencode($sbarcode); - if ($search_warehouse) $param .= "&search_warehouse=".urlencode($search_warehouse); - if ($catid) $param .= "&catid=".urlencode($catid); - if ($toolowstock) $param .= "&toolowstock=".urlencode($toolowstock); - if ($search_sale) $param .= "&search_sale=".urlencode($search_sale); - if ($search_categ) $param .= "&search_categ=".urlencode($search_categ); + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($sall) { + $param .= "&sall=".urlencode($sall); + } + if ($tosell) { + $param .= "&tosell=".urlencode($tosell); + } + if ($tobuy) { + $param .= "&tobuy=".urlencode($tobuy); + } + if ($type) { + $param .= "&type=".urlencode($type); + } + if ($fourn_id) { + $param .= "&fourn_id=".urlencode($fourn_id); + } + if ($snom) { + $param .= "&snom=".urlencode($snom); + } + if ($sref) { + $param .= "&sref=".urlencode($sref); + } + if ($search_batch) { + $param .= "&search_batch=".urlencode($search_batch); + } + if ($sbarcode) { + $param .= "&sbarcode=".urlencode($sbarcode); + } + if ($search_warehouse) { + $param .= "&search_warehouse=".urlencode($search_warehouse); + } + if ($catid) { + $param .= "&catid=".urlencode($catid); + } + if ($toolowstock) { + $param .= "&toolowstock=".urlencode($toolowstock); + } + if ($search_sale) { + $param .= "&search_sale=".urlencode($search_sale); + } + if ($search_categ) { + $param .= "&search_categ=".urlencode($search_categ); + } /*if ($eatby) $param.="&eatby=".$eatby; if ($sellby) $param.="&sellby=".$sellby;*/ @@ -231,8 +296,7 @@ if ($resql) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'product', 0, '', '', $limit, 0, 0, 1); - if (!empty($catid)) - { + if (!empty($catid)) { print "<div id='ways'>"; $c = new Categorie($db); $c->fetch($catid); @@ -242,18 +306,16 @@ if ($resql) } // Filter on categories - $moreforfilter = ''; - if (!empty($conf->categorie->enabled)) - { - $moreforfilter .= '<div class="divsearchfield">'; - $moreforfilter .= $langs->trans('Categories').': '; + $moreforfilter = ''; + if (!empty($conf->categorie->enabled)) { + $moreforfilter .= '<div class="divsearchfield">'; + $moreforfilter .= $langs->trans('Categories').': '; $moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ'); - $moreforfilter .= '</div>'; + $moreforfilter .= '</div>'; } //$moreforfilter.=$langs->trans("StockTooLow").' <input type="checkbox" name="toolowstock" value="1"'.($toolowstock?' checked':'').'>'; - if (!empty($moreforfilter)) - { + if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; $parameters = array(); @@ -274,8 +336,7 @@ if ($resql) print '<td class="liste_titre">'; print '<input class="flat" type="text" name="snom" size="8" value="'.$snom.'">'; print '</td>'; - if (!empty($conf->service->enabled) && $type == 1) - { + if (!empty($conf->service->enabled) && $type == 1) { print '<td class="liste_titre">'; print '&nbsp;'; print '</td>'; @@ -302,7 +363,9 @@ if ($resql) print "<tr class=\"liste_titre\">"; print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", $param, "", "", $sortfield, $sortorder); - if (!empty($conf->service->enabled) && $type == 1) print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center '); + if (!empty($conf->service->enabled) && $type == 1) { + print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center '); + } print_liste_field_titre("Warehouse", $_SERVER["PHP_SELF"], "e.ref", $param, "", '', $sortfield, $sortorder); //print_liste_field_titre("DesiredStock", $_SERVER["PHP_SELF"], "p.desiredstock",$param,"",'',$sortfield,$sortorder, 'right ); print_liste_field_titre("Batch", $_SERVER["PHP_SELF"], "pb.batch", $param, "", '', $sortfield, $sortorder, 'center '); @@ -325,13 +388,11 @@ if ($resql) $product_lot_static = new Productlot($db); $warehousetmp = new Entrepot($db); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($resql); // Multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) // si l'option est active - { + if (!empty($conf->global->MAIN_MULTILANGS)) { // si l'option est active $sql = "SELECT label"; $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sql .= " WHERE fk_product=".$objp->rowid; @@ -339,10 +400,11 @@ if ($resql) $sql .= " LIMIT 1"; $result = $db->query($sql); - if ($result) - { + if ($result) { $objtp = $db->fetch_object($result); - if (!empty($objtp->label)) $objp->label = $objtp->label; + if (!empty($objtp->label)) { + $objp->label = $objtp->label; + } } } @@ -379,13 +441,17 @@ if ($resql) // Label print '<td>'.$objp->label.'</td>'; - if (!empty($conf->service->enabled) && $type == 1) - { + if (!empty($conf->service->enabled) && $type == 1) { print '<td class="center">'; - if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationYear"); - elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationMonth"); - elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationDay"); - else print $objp->duration; + if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) { + print $regs[1].' '.$langs->trans("DurationYear"); + } elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) { + print $regs[1].' '.$langs->trans("DurationMonth"); + } elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) { + print $regs[1].' '.$langs->trans("DurationDay"); + } else { + print $objp->duration; + } print '</td>'; } //print '<td class="right">'.$objp->stock_theorique.'</td>'; @@ -394,16 +460,14 @@ if ($resql) // Warehouse print '<td class="nowrap">'; - if ($objp->fk_entrepot > 0) - { + if ($objp->fk_entrepot > 0) { print $warehousetmp->getNomUrl(1); } print '</td>'; // Lot print '<td class="center nowrap">'; - if ($product_lot_static->batch) - { + if ($product_lot_static->batch) { print $product_lot_static->getNomUrl(1); } print '</td>'; diff --git a/htdocs/product/stats/bom.php b/htdocs/product/stats/bom.php index 1582646cd8a..053d9d6b1a8 100644 --- a/htdocs/product/stats/bom.php +++ b/htdocs/product/stats/bom.php @@ -38,7 +38,9 @@ $ref = GETPOST('ref', 'alpha'); // 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; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -52,12 +54,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 = "b.date_valid"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "b.date_valid"; +} /* @@ -66,8 +74,7 @@ if (!$sortfield) $sortfield = "b.date_valid"; $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $product = new Product($db); $result = $product->fetch($id, $ref); @@ -75,12 +82,13 @@ if ($id > 0 || !empty($ref)) $parameters = array('id'=>$id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $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'); + } llxHeader("", "", $langs->trans("CardProduct".$product->type)); - if ($result > 0) - { + if ($result > 0) { $head = product_prepare_head($product); $titre = $langs->trans("CardProduct".$product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -88,12 +96,16 @@ if ($id > 0 || !empty($ref)) $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -130,8 +142,7 @@ if ($id > 0 || !empty($ref)) // Count total nb of records $totalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); if ($result) { $totalofrecords = $db->num_rows($result); @@ -180,8 +191,7 @@ if ($id > 0 || !empty($ref)) // Count total nb of records $totalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); if ($result) { $totalofrecords = $db->num_rows($result); @@ -223,20 +233,32 @@ if ($id > 0 || !empty($ref)) $db->free($result); - if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); - if (!empty($id)) $option .= '&id='.$product->id; - if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); - if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); + if ($limit > 0 && $limit != $conf->liste_limit) { + $option .= '&limit='.urlencode($limit); + } + if (!empty($id)) { + $option .= '&id='.$product->id; + } + if (!empty($search_month)) { + $option .= '&search_month='.urlencode($search_month); + } + if (!empty($search_year)) { + $option .= '&search_year='.urlencode($search_year); + } print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; - if (!empty($sortfield)) + if (!empty($sortfield)) { print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; - if (!empty($sortorder)) + } + if (!empty($sortorder)) { print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; + } print_barre_liste($langs->trans("BOMs"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', count($bom_data_result), count($bom_data_result), '', 0, '', '', $limit, 0, 0, 1); - if (!empty($page)) $option .= '&page='.urlencode($page); + if (!empty($page)) { + $option .= '&page='.urlencode($page); + } print '<div class="div-table-responsive">'; print '<table class="tagtable liste listwithfilterbefore" width="100%">'; @@ -244,14 +266,13 @@ if ($id > 0 || !empty($ref)) print '<tr class="liste_titre">'; print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "b.rowid", "", "&amp;id=".$product->id, '', $sortfield, $sortorder); print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "b.date_valid", "", "&amp;id=".$product->id, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre("ToConsume", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$product->id, '', $sortfield, $sortorder, 'center '); - print_liste_field_titre("QtyToProduce", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$product->id, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre("RowMaterial", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$product->id, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre("Finished", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$product->id, '', $sortfield, $sortorder, 'center '); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "b.status", "", "&amp;id=".$product->id, '', $sortfield, $sortorder, 'center '); print "</tr>\n"; if (!empty($bom_data_result)) { - foreach ($bom_data_result as $data) - { + foreach ($bom_data_result as $data) { print '<tr class="oddeven">'; print '<td>'; print $data['link']; diff --git a/htdocs/product/stats/card.php b/htdocs/product/stats/card.php index e899cee797f..a47bc79c84a 100644 --- a/htdocs/product/stats/card.php +++ b/htdocs/product/stats/card.php @@ -51,7 +51,9 @@ $mesg = ''; $graphfiles = array(); $socid = ''; -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} // Security check $fieldvalue = (!empty($id) ? $id : $ref); @@ -60,7 +62,9 @@ $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product $tmp = dol_getdate(dol_now()); $currentyear = $tmp['year']; -if (empty($search_year)) $search_year = $currentyear; +if (empty($search_year)) { + $search_year = $currentyear; +} /* @@ -83,7 +87,7 @@ if (!$id && empty($ref)) { $type = GETPOST('type', 'int'); - $helpurl = ''; + $helpurl = ''; if ($type == '0') { $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; //$title=$langs->trans("StatisticsOfProducts"); @@ -99,7 +103,9 @@ if (!$id && empty($ref)) { } $picto = 'product'; - if ($type == 1) $picto = 'service'; + if ($type == 1) { + $picto = 'service'; + } print load_fiche_titre($title, $mesg, $picto); } else { @@ -189,42 +195,65 @@ if ($result || empty($id)) { // Year print '<tr><td class="titlefield">'.$langs->trans("Year").'</td><td>'; $arrayyears = array(); - for ($year = $currentyear - 25; $year < $currentyear; $year++) - { + for ($year = $currentyear - 25; $year < $currentyear; $year++) { $arrayyears[$year] = $year; } - if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; - if (!in_array($currentyear, $arrayyears)) $arrayyears[$currentyear] = $currentyear; + if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; + } + if (!in_array($currentyear, $arrayyears)) { + $arrayyears[$currentyear] = $currentyear; + } arsort($arrayyears); print $form->selectarray('search_year', $arrayyears, $search_year, 1); print '</td></tr>'; print '</table>'; print '<div class="center"><input type="submit" name="submit" class="button" value="'.$langs->trans("Refresh").'"></div>'; - print '</form>'; + print '</form><br>'; print '<br>'; // Choice of stats mode (byunit or bynumber) - if (!empty($conf->dol_use_jmobile)) print "\n".'<div class="fichecenter"><div class="nowrap">'."\n"; + if (!empty($conf->dol_use_jmobile)) { + print "\n".'<div class="fichecenter"><div class="nowrap">'."\n"; + } - if ($mode == 'bynumber') print '<a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?id='.(GETPOST('id') ?GETPOST('id') : $object->id).($type != '' ? '&type='.$type : '').'&mode=byunit&search_year='.$search_year.'">'; - else print '<span class="a-mesure">'; + if ($mode == 'bynumber') { + print '<a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?id='.(GETPOST('id') ?GETPOST('id') : $object->id).($type != '' ? '&type='.$type : '').'&mode=byunit&search_year='.$search_year.'">'; + } else { + print '<span class="a-mesure">'; + } print $langs->trans("StatsByNumberOfUnits"); - if ($mode == 'bynumber') print '</a>'; - else print '</span>'; + if ($mode == 'bynumber') { + print '</a>'; + } else { + print '</span>'; + } - if (!empty($conf->dol_use_jmobile)) print '</div>'."\n".'<div class="nowrap">'."\n"; - else print ' &nbsp; '; + if (!empty($conf->dol_use_jmobile)) { + print '</div>'."\n".'<div class="nowrap">'."\n"; + } else { + print ' &nbsp; '; + } - if ($mode == 'byunit') print '<a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?id='.(GETPOST('id') ?GETPOST('id') : $object->id).($type != '' ? '&type='.$type : '').'&mode=bynumber&search_year='.$search_year.'">'; - else print '<span class="a-mesure">'; + if ($mode == 'byunit') { + print '<a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?id='.(GETPOST('id') ?GETPOST('id') : $object->id).($type != '' ? '&type='.$type : '').'&mode=bynumber&search_year='.$search_year.'">'; + } else { + print '<span class="a-mesure">'; + } print $langs->trans("StatsByNumberOfEntities"); - if ($mode == 'byunit') print '</a>'; - else print '</span>'; + if ($mode == 'byunit') { + print '</a>'; + } else { + print '</span>'; + } - if (!empty($conf->dol_use_jmobile)) print '</div></div>'; - else print '<br>'; + if (!empty($conf->dol_use_jmobile)) { + print '</div></div>'; + } else { + print '<br>'; + } print '<br>'; //print '<table width="100%">'; @@ -294,7 +323,9 @@ if ($result || empty($id)) { $mesg = $px->isGraphKo(); if (!$mesg) { foreach ($graphfiles as $key => $val) { - if (!$graphfiles[$key]['file']) continue; + if (!$graphfiles[$key]['file']) { + continue; + } $graph_data = array(); @@ -312,14 +343,30 @@ if ($result || empty($id)) { $morefilters = ' AND d.fk_product NOT IN (SELECT cp.fk_product from '.MAIN_DB_PREFIX.'categorie_product as cp)'; } - if ($key == 'propal') $graph_data = $object->get_nb_propal($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); - if ($key == 'orders') $graph_data = $object->get_nb_order($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); - if ($key == 'invoices') $graph_data = $object->get_nb_vente($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); - if ($key == 'proposalssuppliers') $graph_data = $object->get_nb_propalsupplier($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); - if ($key == 'invoicessuppliers') $graph_data = $object->get_nb_achat($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); - if ($key == 'orderssuppliers') $graph_data = $object->get_nb_ordersupplier($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); - if ($key == 'contracts') $graph_data = $object->get_nb_contract($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); - if ($key == 'mrp') $graph_data = $object->get_nb_mos($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + if ($key == 'propal') { + $graph_data = $object->get_nb_propal($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + } + if ($key == 'orders') { + $graph_data = $object->get_nb_order($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + } + if ($key == 'invoices') { + $graph_data = $object->get_nb_vente($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + } + if ($key == 'proposalssuppliers') { + $graph_data = $object->get_nb_propalsupplier($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + } + if ($key == 'invoicessuppliers') { + $graph_data = $object->get_nb_achat($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + } + if ($key == 'orderssuppliers') { + $graph_data = $object->get_nb_ordersupplier($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + } + if ($key == 'contracts') { + $graph_data = $object->get_nb_contract($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + } + if ($key == 'mrp') { + $graph_data = $object->get_nb_mos($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + } // TODO Save cachefile $graphfiles[$key]['file'] } @@ -354,15 +401,31 @@ if ($result || empty($id)) { $i = 0; if (count($graphfiles) > 0) { foreach ($graphfiles as $key => $val) { - if (!$graphfiles[$key]['file']) continue; + if (!$graphfiles[$key]['file']) { + continue; + } - if ($graphfiles == 'propal' && !$user->rights->propale->lire) continue; - if ($graphfiles == 'order' && !$user->rights->commande->lire) continue; - if ($graphfiles == 'invoices' && !$user->rights->facture->lire) continue; - if ($graphfiles == 'proposals_suppliers' && !$user->rights->supplier_proposal->lire) continue; - if ($graphfiles == 'invoices_suppliers' && !$user->rights->fournisseur->facture->lire) continue; - if ($graphfiles == 'orders_suppliers' && !$user->rights->fournisseur->commande->lire) continue; - if ($graphfiles == 'mrp' && empty($user->rights->mrp->mo->read)) continue; + if ($graphfiles == 'propal' && !$user->rights->propale->lire) { + continue; + } + if ($graphfiles == 'order' && !$user->rights->commande->lire) { + continue; + } + if ($graphfiles == 'invoices' && !$user->rights->facture->lire) { + continue; + } + if ($graphfiles == 'proposals_suppliers' && !$user->rights->supplier_proposal->lire) { + continue; + } + if ($graphfiles == 'invoices_suppliers' && !$user->rights->fournisseur->facture->lire) { + continue; + } + if ($graphfiles == 'orders_suppliers' && !$user->rights->fournisseur->commande->lire) { + continue; + } + if ($graphfiles == 'mrp' && empty($user->rights->mrp->mo->read)) { + continue; + } if ($i % 2 == 0) { @@ -373,8 +436,11 @@ if ($result || empty($id)) { // Date generation if ($graphfiles[$key]['output'] && !$px->isGraphKo()) { - if (file_exists($dir."/".$graphfiles[$key]['file']) && filemtime($dir."/".$graphfiles[$key]['file'])) $dategenerated = $langs->trans("GeneratedOn", dol_print_date(filemtime($dir."/".$graphfiles[$key]['file']), "dayhour")); - else $dategenerated = $langs->trans("GeneratedOn", dol_print_date(dol_now(), "dayhour")); + if (file_exists($dir."/".$graphfiles[$key]['file']) && filemtime($dir."/".$graphfiles[$key]['file'])) { + $dategenerated = $langs->trans("GeneratedOn", dol_print_date(filemtime($dir."/".$graphfiles[$key]['file']), "dayhour")); + } else { + $dategenerated = $langs->trans("GeneratedOn", dol_print_date(dol_now(), "dayhour")); + } } else { $dategenerated = ($mesg ? '<font class="error">'.$mesg.'</font>' : $langs->trans("ChartNotGenerated")); } diff --git a/htdocs/product/stats/commande.php b/htdocs/product/stats/commande.php index f89305b4d95..cb5087c63f2 100644 --- a/htdocs/product/stats/commande.php +++ b/htdocs/product/stats/commande.php @@ -40,7 +40,9 @@ $ref = GETPOST('ref', 'alpha'); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $socid = ''; -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -53,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.date_commande"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "c.date_commande"; +} $search_month = GETPOST('search_month', 'int'); $search_year = GETPOST('search_year', 'int'); @@ -77,8 +85,7 @@ $societestatic = new Societe($db); $form = new Form($db); $formother = new FormOther($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $product = new Product($db); $result = $product->fetch($id, $ref); @@ -86,12 +93,13 @@ if ($id > 0 || !empty($ref)) $parameters = array('id'=>$id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $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'); + } llxHeader("", "", $langs->trans("CardProduct".$product->type)); - if ($result > 0) - { + if ($result > 0) { $head = product_prepare_head($product); $titre = $langs->trans("CardProduct".$product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -99,12 +107,16 @@ if ($id > 0 || !empty($ref)) $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -123,26 +135,35 @@ if ($id > 0 || !empty($ref)) print dol_get_fiche_end(); - if ($user->rights->commande->lire) - { + if ($user->rights->commande->lire) { $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client, c.rowid, d.total_ht as total_ht, c.ref,"; $sql .= " c.ref_client,"; $sql .= " c.date_commande, c.fk_statut as statut, c.facture, c.rowid as commandeid, d.rowid, d.qty"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."commande as c"; $sql .= ", ".MAIN_DB_PREFIX."commandedet as d"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity('commande').")"; $sql .= " AND d.fk_commande = c.rowid"; $sql .= " AND d.fk_product =".$product->id; - if (!empty($search_month)) - $sql .= ' AND MONTH(c.date_commande) IN ('.$search_month.')'; - if (!empty($search_year)) - $sql .= ' AND YEAR(c.date_commande) IN ('.$search_year.')'; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND c.fk_soc = ".$socid; + if (!empty($search_month)) { + $sql .= ' AND MONTH(c.date_commande) IN ('.$search_month.')'; + } + if (!empty($search_year)) { + $sql .= ' AND YEAR(c.date_commande) IN ('.$search_year.')'; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; + } $sql .= $db->order($sortfield, $sortorder); //Calcul total qty and amount for global if full scan list @@ -151,8 +172,7 @@ if ($id > 0 || !empty($ref)) // Count total nb of records $totalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $totalofrecords = $db->num_rows($result); } @@ -160,25 +180,36 @@ if ($id > 0 || !empty($ref)) $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); - if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); - if (!empty($id)) $option .= '&id='.$product->id; - if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); - if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); + if ($limit > 0 && $limit != $conf->liste_limit) { + $option .= '&limit='.urlencode($limit); + } + if (!empty($id)) { + $option .= '&id='.$product->id; + } + if (!empty($search_month)) { + $option .= '&search_month='.urlencode($search_month); + } + if (!empty($search_year)) { + $option .= '&search_year='.urlencode($search_year); + } print '<form method="post" action="'.$_SERVER ['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; print '<input type="hidden" name="token" value="'.newToken().'">'; - if (!empty($sortfield)) + if (!empty($sortfield)) { print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; - if (!empty($sortorder)) + } + if (!empty($sortorder)) { print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; + } print_barre_liste($langs->trans("CustomersOrders"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); - if (!empty($page)) $option .= '&page='.urlencode($page); + if (!empty($page)) { + $option .= '&page='.urlencode($page); + } print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="divsearchfield">'; @@ -205,10 +236,8 @@ if ($id > 0 || !empty($ref)) print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "c.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print "</tr>\n"; - if ($num > 0) - { - while ($i < min($num, $limit)) - { + if ($num > 0) { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($result); $total_ht += $objp->total_ht; @@ -220,7 +249,7 @@ if ($id > 0 || !empty($ref)) $societestatic->fetch($objp->socid); print '<tr class="oddeven">'; - print '<td>'; + print '<td>'; print $orderstatic->getNomUrl(1); print "</td>\n"; print '<td>'.$societestatic->getNomUrl(1).'</td>'; @@ -235,8 +264,11 @@ if ($id > 0 || !empty($ref)) } } print '<tr class="liste_total">'; - if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>'; - else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + if ($num < $limit) { + print '<td class="left">'.$langs->trans("Total").'</td>'; + } else { + print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + } print '<td colspan="3"></td>'; print '<td class="center">'.$total_qty.'</td>'; print '<td align="right">'.price($total_ht).'</td>'; diff --git a/htdocs/product/stats/commande_fournisseur.php b/htdocs/product/stats/commande_fournisseur.php index 611047f7f13..16dd040887d 100644 --- a/htdocs/product/stats/commande_fournisseur.php +++ b/htdocs/product/stats/commande_fournisseur.php @@ -39,8 +39,9 @@ $ref = GETPOST('ref', 'alpha'); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $socid = ''; -if (!empty($user->socid)) +if (!empty($user->socid)) { $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -53,14 +54,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) { $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) +if (!$sortorder) { $sortorder = "DESC"; -if (!$sortfield) +} +if (!$sortfield) { $sortfield = "c.date_commande"; +} $search_month = GETPOST('search_month', 'int'); $search_year = GETPOST('search_year', 'int'); @@ -88,13 +93,13 @@ if ($id > 0 || !empty($ref)) { $parameters = array('id' => $id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) + if ($reshook < 0) { setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } llxHeader("", "", $langs->trans("CardProduct".$product->type)); - if ($result > 0) - { + if ($result > 0) { $head = product_prepare_head($product); $titre = $langs->trans("CardProduct".$product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -102,12 +107,16 @@ if ($id > 0 || !empty($ref)) { $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -126,30 +135,35 @@ if ($id > 0 || !empty($ref)) { print dol_get_fiche_end(); - if ($user->rights->fournisseur->commande->lire) - { + if ($user->rights->fournisseur->commande->lire) { $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client,"; $sql .= " c.rowid, d.total_ht as total_ht, c.ref,"; $sql .= " c.date_commande, c.fk_statut as statut, c.rowid as commandeid, d.rowid, d.qty"; - if (!$user->rights->societe->client->voir && !$socid) + if (!$user->rights->societe->client->voir && !$socid) { $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as c"; $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as d"; - if (!$user->rights->societe->client->voir && !$socid) + if (!$user->rights->societe->client->voir && !$socid) { $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity = ".$conf->entity; $sql .= " AND d.fk_commande = c.rowid"; $sql .= " AND d.fk_product =".$product->id; - if (!empty($search_month)) + if (!empty($search_month)) { $sql .= ' AND MONTH(c.date_commande) IN ('.$search_month.')'; - if (!empty($search_year)) + } + if (!empty($search_year)) { $sql .= ' AND YEAR(c.date_commande) IN ('.$search_year.')'; - if (!$user->rights->societe->client->voir && !$socid) + } + if (!$user->rights->societe->client->voir && !$socid) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) + } + if ($socid) { $sql .= " AND c.fk_soc = ".$socid; + } $sql .= $db->order($sortfield, $sortorder); // Calcul total qty and amount for global if full scan list @@ -158,8 +172,7 @@ if ($id > 0 || !empty($ref)) { // Count total nb of records $totalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $totalofrecords = $db->num_rows($result); } @@ -170,20 +183,32 @@ if ($id > 0 || !empty($ref)) { if ($result) { $num = $db->num_rows($result); - if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); - if (!empty($id)) $option .= '&id='.$product->id; - if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); - if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); + if ($limit > 0 && $limit != $conf->liste_limit) { + $option .= '&limit='.urlencode($limit); + } + if (!empty($id)) { + $option .= '&id='.$product->id; + } + if (!empty($search_month)) { + $option .= '&search_month='.urlencode($search_month); + } + if (!empty($search_year)) { + $option .= '&search_year='.urlencode($search_year); + } print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; - if (!empty($sortfield)) + if (!empty($sortfield)) { print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; - if (!empty($sortorder)) + } + if (!empty($sortorder)) { print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; + } print_barre_liste($langs->trans("SuppliersOrders"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); - if (!empty($page)) $option .= '&page='.urlencode($page); + if (!empty($page)) { + $option .= '&page='.urlencode($page); + } print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="divsearchfield">'; @@ -210,10 +235,8 @@ if ($id > 0 || !empty($ref)) { print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "c.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print "</tr>\n"; - if ($num > 0) - { - while ($i < min($num, $limit)) - { + if ($num > 0) { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($result); $total_ht += $objp->total_ht; @@ -240,8 +263,11 @@ if ($id > 0 || !empty($ref)) { } } print '<tr class="liste_total">'; - if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>'; - else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + if ($num < $limit) { + print '<td class="left">'.$langs->trans("Total").'</td>'; + } else { + print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + } print '<td colspan="3"></td>'; print '<td class="center">'.$total_qty.'</td>'; print '<td align="right">'.price($total_ht).'</td>'; diff --git a/htdocs/product/stats/contrat.php b/htdocs/product/stats/contrat.php index 91ca0bd87e2..93778a19047 100644 --- a/htdocs/product/stats/contrat.php +++ b/htdocs/product/stats/contrat.php @@ -37,7 +37,9 @@ $ref = GETPOST('ref', 'alpha'); // 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; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -50,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 = "c.date_contrat"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "c.date_contrat"; +} /* @@ -67,8 +75,7 @@ $staticcontratligne = new ContratLigne($db); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $product = new Product($db); $result = $product->fetch($id, $ref); @@ -76,12 +83,13 @@ if ($id > 0 || !empty($ref)) $parameters = array('id'=>$id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $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'); + } llxHeader("", "", $langs->trans("CardProduct".$product->type)); - if ($result > 0) - { + if ($result > 0) { $head = product_prepare_head($product); $titre = $langs->trans("CardProduct".$product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -89,12 +97,16 @@ if ($id > 0 || !empty($ref)) $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -123,15 +135,21 @@ if ($id > 0 || !empty($ref)) $sql .= " c.rowid as rowid, c.ref, c.ref_customer, c.ref_supplier, c.date_contrat, c.statut as statut,"; $sql .= " s.nom as name, s.rowid as socid, s.code_client"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= ", ".MAIN_DB_PREFIX."contrat as c"; $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= " WHERE c.rowid = cd.fk_contrat"; $sql .= " AND c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity('contract').")"; $sql .= " AND cd.fk_product =".$product->id; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } $sql .= " GROUP BY c.rowid, c.ref, c.ref_customer, c.ref_supplier, c.date_contrat, c.statut, s.nom, s.rowid, s.code_client"; $sql .= $db->order($sortfield, $sortorder); @@ -141,8 +159,7 @@ if ($id > 0 || !empty($ref)) // Count total nb of records $totalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $totalofrecords = $db->num_rows($result); } @@ -150,25 +167,36 @@ if ($id > 0 || !empty($ref)) $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); - if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); - if (!empty($id)) $option .= '&id='.$product->id; - if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); - if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); + if ($limit > 0 && $limit != $conf->liste_limit) { + $option .= '&limit='.urlencode($limit); + } + if (!empty($id)) { + $option .= '&id='.$product->id; + } + if (!empty($search_month)) { + $option .= '&search_month='.urlencode($search_month); + } + if (!empty($search_year)) { + $option .= '&search_year='.urlencode($search_year); + } print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; - if (!empty($sortfield)) + if (!empty($sortfield)) { print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; - if (!empty($sortorder)) + } + if (!empty($sortorder)) { print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; + } print_barre_liste($langs->trans("Contrats"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); - if (!empty($page)) $option .= '&page='.urlencode($page); + if (!empty($page)) { + $option .= '&page='.urlencode($page); + } $i = 0; print '<div class="div-table-responsive">'; @@ -187,10 +215,8 @@ if ($id > 0 || !empty($ref)) $contracttmp = new Contrat($db); - if ($num > 0) - { - while ($i < min($num, $limit)) - { + if ($num > 0) { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($result); $contracttmp->id = $objp->rowid; diff --git a/htdocs/product/stats/facture.php b/htdocs/product/stats/facture.php index 8091de9c320..271a834570b 100644 --- a/htdocs/product/stats/facture.php +++ b/htdocs/product/stats/facture.php @@ -41,7 +41,9 @@ $ref = GETPOST('ref', 'alpha'); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $socid = ''; -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -54,12 +56,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 = "f.datef"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "f.datef"; +} $search_month = GETPOST('search_month', 'int'); $search_year = GETPOST('search_year', 'int'); @@ -81,8 +89,7 @@ $societestatic = new Societe($db); $form = new Form($db); $formother = new FormOther($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $product = new Product($db); $result = $product->fetch($id, $ref); @@ -90,26 +97,25 @@ if ($id > 0 || !empty($ref)) $parameters = array('id'=>$id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $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'); + } $title = $langs->trans('ProductServiceCard'); $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); - if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) - { + if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Referers'); $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; } - if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) - { + if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Referers'); $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; } llxHeader('', $title, $helpurl); - if ($result > 0) - { + if ($result > 0) { $head = product_prepare_head($product); $titre = $langs->trans("CardProduct".$product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -117,12 +123,16 @@ if ($id > 0 || !empty($ref)) $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -140,29 +150,37 @@ if ($id > 0 || !empty($ref)) print dol_get_fiche_end(); - if ($showmessage && $nboflines > 1) - { + if ($showmessage && $nboflines > 1) { print '<span class="opacitymedium">'.$langs->trans("ClinkOnALinkOfColumn", $langs->transnoentitiesnoconv("Referers")).'</span>'; - } elseif ($user->rights->facture->lire) - { + } elseif ($user->rights->facture->lire) { $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client,"; $sql .= " f.ref, f.datef, f.paye, f.type, f.fk_statut as statut, f.rowid as facid,"; $sql .= " d.rowid, d.total_ht as total_ht, d.qty"; // We must keep the d.rowid here to not loose record because of the distinct used to ignore duplicate line when link on societe_commerciaux is used - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."facture as f"; $sql .= ", ".MAIN_DB_PREFIX."facturedet as d"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('invoice').")"; $sql .= " AND d.fk_facture = f.rowid"; $sql .= " AND d.fk_product =".$product->id; - if (!empty($search_month)) + if (!empty($search_month)) { $sql .= ' AND MONTH(f.datef) IN ('.$search_month.')'; - if (!empty($search_year)) + } + if (!empty($search_year)) { $sql .= ' AND YEAR(f.datef) IN ('.$search_year.')'; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } $sql .= $db->order($sortfield, $sortorder); // Calcul total qty and amount for global if full scan list @@ -171,8 +189,7 @@ if ($id > 0 || !empty($ref)) // Count total nb of records $totalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $totalofrecords = $db->num_rows($result); } @@ -180,24 +197,35 @@ if ($id > 0 || !empty($ref)) $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); - if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); - if (!empty($id)) $option .= '&id='.$product->id; - if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); - if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); + if ($limit > 0 && $limit != $conf->liste_limit) { + $option .= '&limit='.urlencode($limit); + } + if (!empty($id)) { + $option .= '&id='.$product->id; + } + if (!empty($search_month)) { + $option .= '&search_month='.urlencode($search_month); + } + if (!empty($search_year)) { + $option .= '&search_year='.urlencode($search_year); + } print '<form method="post" action="'.$_SERVER ['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; - if (!empty($sortfield)) + if (!empty($sortfield)) { print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; - if (!empty($sortorder)) + } + if (!empty($sortorder)) { print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; + } print_barre_liste($langs->trans("CustomersInvoices"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); - if (!empty($page)) $option .= '&page='.urlencode($page); + if (!empty($page)) { + $option .= '&page='.urlencode($page); + } print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="divsearchfield">'; @@ -224,13 +252,13 @@ if ($id > 0 || !empty($ref)) print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print "</tr>\n"; - if ($num > 0) - { - while ($i < min($num, $limit)) - { + if ($num > 0) { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($result); - if ($objp->type == Facture::TYPE_CREDIT_NOTE) $objp->qty = -($objp->qty); + if ($objp->type == Facture::TYPE_CREDIT_NOTE) { + $objp->qty = -($objp->qty); + } $total_ht += $objp->total_ht; $total_qty += $objp->qty; @@ -256,8 +284,11 @@ if ($id > 0 || !empty($ref)) } } print '<tr class="liste_total">'; - if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>'; - else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + if ($num < $limit) { + print '<td class="left">'.$langs->trans("Total").'</td>'; + } else { + print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + } print '<td colspan="3"></td>'; print '<td class="center">'.$total_qty.'</td>'; print '<td align="right">'.price($total_ht).'</td>'; diff --git a/htdocs/product/stats/facture_fournisseur.php b/htdocs/product/stats/facture_fournisseur.php index 7e0e463e1a5..a42615fdaa9 100644 --- a/htdocs/product/stats/facture_fournisseur.php +++ b/htdocs/product/stats/facture_fournisseur.php @@ -41,7 +41,9 @@ $ref = GETPOST('ref', 'alpha'); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $socid = ''; -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -54,12 +56,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 = "f.datef"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "f.datef"; +} $search_month = GETPOST('search_month', 'int'); $search_year = GETPOST('search_year', 'int'); @@ -78,8 +86,7 @@ $societestatic = new Societe($db); $form = new Form($db); $formother = new FormOther($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $product = new Product($db); $result = $product->fetch($id, $ref); @@ -87,12 +94,13 @@ if ($id > 0 || !empty($ref)) $parameters = array('id' => $id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $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'); + } llxHeader("", "", $langs->trans("CardProduct".$product->type)); - if ($result > 0) - { + if ($result > 0) { $head = product_prepare_head($product); $titre = $langs->trans("CardProduct".$product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -100,12 +108,16 @@ if ($id > 0 || !empty($ref)) $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -124,26 +136,34 @@ if ($id > 0 || !empty($ref)) print dol_get_fiche_end(); - if ($user->rights->fournisseur->facture->lire) - { + if ($user->rights->fournisseur->facture->lire) { $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client, d.rowid, d.total_ht as line_total_ht,"; $sql .= " f.rowid as facid, f.ref, f.ref_supplier, f.datef, f.libelle as label, f.total_ht, f.total_ttc, f.total_tva, f.paye, f.fk_statut as statut, d.qty"; - if (!$user->rights->societe->client->voir && !$socid) + if (!$user->rights->societe->client->voir && !$socid) { $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."facture_fourn as f"; $sql .= ", ".MAIN_DB_PREFIX."facture_fourn_det as d"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture_fourn').")"; $sql .= " AND d.fk_facture_fourn = f.rowid"; $sql .= " AND d.fk_product =".$product->id; - if (!empty($search_month)) + if (!empty($search_month)) { $sql .= ' AND MONTH(f.datef) IN ('.$search_month.')'; - if (!empty($search_year)) + } + if (!empty($search_year)) { $sql .= ' AND YEAR(f.datef) IN ('.$search_year.')'; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } $sql .= " ORDER BY $sortfield $sortorder "; // Calcul total qty and amount for global if full scan list @@ -152,8 +172,7 @@ if ($id > 0 || !empty($ref)) // Count total nb of records $totalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $totalofrecords = $db->num_rows($result); } @@ -161,24 +180,35 @@ if ($id > 0 || !empty($ref)) $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); - if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); - if (!empty($id)) $option .= '&id='.$product->id; - if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); - if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); + if ($limit > 0 && $limit != $conf->liste_limit) { + $option .= '&limit='.urlencode($limit); + } + if (!empty($id)) { + $option .= '&id='.$product->id; + } + if (!empty($search_month)) { + $option .= '&search_month='.urlencode($search_month); + } + if (!empty($search_year)) { + $option .= '&search_year='.urlencode($search_year); + } print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; - if (!empty($sortfield)) + if (!empty($sortfield)) { print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; - if (!empty($sortorder)) + } + if (!empty($sortorder)) { print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; + } print_barre_liste($langs->trans("SuppliersInvoices"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); - if (!empty($page)) $option .= '&page='.urlencode($page); + if (!empty($page)) { + $option .= '&page='.urlencode($page); + } print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="divsearchfield">'; @@ -205,10 +235,8 @@ if ($id > 0 || !empty($ref)) print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print "</tr>\n"; - if ($num > 0) - { - while ($i < min($num, $limit)) - { + if ($num > 0) { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($result); $total_ht += $objp->line_total_ht; @@ -231,7 +259,7 @@ if ($id > 0 || !empty($ref)) print "</td>\n"; print '<td>'.$societestatic->getNomUrl(1).'</td>'; print "<td>".$objp->code_client."</td>\n"; - print '<td class="center">'; + print '<td class="center">'; print dol_print_date($db->jdate($objp->datef), 'dayhour')."</td>"; print '<td class="center">'.$objp->qty."</td>\n"; print '<td align="right">'.price($objp->line_total_ht)."</td>\n"; @@ -241,8 +269,11 @@ if ($id > 0 || !empty($ref)) } } print '<tr class="liste_total">'; - if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>'; - else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + if ($num < $limit) { + print '<td class="left">'.$langs->trans("Total").'</td>'; + } else { + print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + } print '<td colspan="3"></td>'; print '<td class="center">'.$total_qty.'</td>'; print '<td align="right">'.price($total_ht).'</td>'; diff --git a/htdocs/product/stats/mo.php b/htdocs/product/stats/mo.php index cb159646047..479dbdd1a17 100644 --- a/htdocs/product/stats/mo.php +++ b/htdocs/product/stats/mo.php @@ -37,7 +37,9 @@ $ref = GETPOST('ref', 'alpha'); // 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; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -50,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 = "c.date_valid"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "c.date_valid"; +} /* @@ -67,8 +75,7 @@ $staticmoligne = new MoLine($db); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $product = new Product($db); $result = $product->fetch($id, $ref); @@ -76,12 +83,13 @@ if ($id > 0 || !empty($ref)) $parameters = array('id'=>$id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $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'); + } llxHeader("", "", $langs->trans("CardProduct".$product->type)); - if ($result > 0) - { + if ($result > 0) { $head = product_prepare_head($product); $titre = $langs->trans("CardProduct".$product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -89,12 +97,16 @@ if ($id > 0 || !empty($ref)) $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -127,7 +139,9 @@ if ($id > 0 || !empty($ref)) $sql .= " WHERE c.rowid = cd.fk_mo"; $sql .= " AND c.entity IN (".getEntity('mo').")"; $sql .= " AND cd.fk_product =".$product->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } $sql .= " GROUP BY c.rowid, c.ref, c.date_valid, c.status"; //$sql .= ", s.nom, s.rowid, s.code_client"; $sql .= $db->order($sortfield, $sortorder); @@ -138,8 +152,7 @@ if ($id > 0 || !empty($ref)) // Count total nb of records $totalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $totalofrecords = $db->num_rows($result); } @@ -147,24 +160,35 @@ if ($id > 0 || !empty($ref)) $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); - if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); - if (!empty($id)) $option .= '&id='.$product->id; - if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); - if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); + if ($limit > 0 && $limit != $conf->liste_limit) { + $option .= '&limit='.urlencode($limit); + } + if (!empty($id)) { + $option .= '&id='.$product->id; + } + if (!empty($search_month)) { + $option .= '&search_month='.urlencode($search_month); + } + if (!empty($search_year)) { + $option .= '&search_year='.urlencode($search_year); + } print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; - if (!empty($sortfield)) + if (!empty($sortfield)) { print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; - if (!empty($sortorder)) + } + if (!empty($sortorder)) { print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; + } print_barre_liste($langs->trans("Mos"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); - if (!empty($page)) $option .= '&page='.urlencode($page); + if (!empty($page)) { + $option .= '&page='.urlencode($page); + } $i = 0; print '<div class="div-table-responsive">'; @@ -183,10 +207,8 @@ if ($id > 0 || !empty($ref)) $motmp = new Mo($db); - if ($num > 0) - { - while ($i < min($num, $limit)) - { + if ($num > 0) { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($result); $motmp->id = $objp->rowid; diff --git a/htdocs/product/stats/propal.php b/htdocs/product/stats/propal.php index 9e9a078d8f0..7d08f3ab9c3 100644 --- a/htdocs/product/stats/propal.php +++ b/htdocs/product/stats/propal.php @@ -40,7 +40,9 @@ $ref = GETPOST('ref', 'alpha'); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $socid = ''; -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -53,12 +55,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) { $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 = "p.datep"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "p.datep"; +} $search_month = GETPOST('search_month', 'int'); $search_year = GETPOST('search_year', 'int'); @@ -78,8 +86,7 @@ $societestatic = new Societe($db); $form = new Form($db); $formother = new FormOther($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $product = new Product($db); $result = $product->fetch($id, $ref); @@ -87,12 +94,13 @@ if ($id > 0 || !empty($ref)) $parameters = array('id' => $id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $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'); + } llxHeader("", "", $langs->trans("CardProduct".$product->type)); - if ($result > 0) - { + if ($result > 0) { $head = product_prepare_head($product); $titre = $langs->trans("CardProduct".$product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -100,12 +108,16 @@ if ($id > 0 || !empty($ref)) $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -124,30 +136,35 @@ if ($id > 0 || !empty($ref)) print dol_get_fiche_end(); - if ($user->rights->propale->lire) - { + if ($user->rights->propale->lire) { $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, p.rowid as propalid, p.ref, d.total_ht as amount,"; $sql .= " p.ref_client,"; $sql .= "p.datep, p.fk_statut as statut, d.rowid, d.qty"; - if (!$user->rights->societe->client->voir && !$socid) + if (!$user->rights->societe->client->voir && !$socid) { $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ",".MAIN_DB_PREFIX."propal as p"; $sql .= ", ".MAIN_DB_PREFIX."propaldet as d"; - if (!$user->rights->societe->client->voir && !$socid) + if (!$user->rights->societe->client->voir && !$socid) { $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE p.fk_soc = s.rowid"; $sql .= " AND p.entity IN (".getEntity('propal').")"; $sql .= " AND d.fk_propal = p.rowid"; $sql .= " AND d.fk_product =".$product->id; - if (!empty($search_month)) + if (!empty($search_month)) { $sql .= ' AND MONTH(p.datep) IN ('.$search_month.')'; - if (!empty($search_year)) + } + if (!empty($search_year)) { $sql .= ' AND YEAR(p.datep) IN ('.$search_year.')'; - if (!$user->rights->societe->client->voir && !$socid) + } + if (!$user->rights->societe->client->voir && !$socid) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) + } + if ($socid) { $sql .= " AND p.fk_soc = ".$socid; + } $sql .= $db->order($sortfield, $sortorder); // Calcul total qty and amount for global if full scan list @@ -156,8 +173,7 @@ if ($id > 0 || !empty($ref)) // Count total nb of records $totalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $totalofrecords = $db->num_rows($result); } @@ -165,24 +181,35 @@ if ($id > 0 || !empty($ref)) $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); - if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); - if (!empty($id)) $option .= '&id='.$product->id; - if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); - if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); + if ($limit > 0 && $limit != $conf->liste_limit) { + $option .= '&limit='.urlencode($limit); + } + if (!empty($id)) { + $option .= '&id='.$product->id; + } + if (!empty($search_month)) { + $option .= '&search_month='.urlencode($search_month); + } + if (!empty($search_year)) { + $option .= '&search_year='.urlencode($search_year); + } print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; - if (!empty($sortfield)) + if (!empty($sortfield)) { print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; - if (!empty($sortorder)) + } + if (!empty($sortorder)) { print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; + } print_barre_liste($langs->trans("Proposals"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); - if (!empty($page)) $option .= '&page='.urlencode($page); + if (!empty($page)) { + $option .= '&page='.urlencode($page); + } print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="divsearchfield">'; @@ -208,10 +235,8 @@ if ($id > 0 || !empty($ref)) print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "p.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print "</tr>\n"; - if ($num > 0) - { - while ($i < min($num, $limit)) - { + if ($num > 0) { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($result); $total_ht += $objp->amount; @@ -238,8 +263,11 @@ if ($id > 0 || !empty($ref)) } print '<tr class="liste_total">'; - if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>'; - else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + if ($num < $limit) { + print '<td class="left">'.$langs->trans("Total").'</td>'; + } else { + print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + } print '<td colspan="2"></td>'; print '<td class="center">'.$total_qty.'</td>'; print '<td align="right">'.price($total_ht).'</td>'; diff --git a/htdocs/product/stats/supplier_proposal.php b/htdocs/product/stats/supplier_proposal.php index b4816028d98..e18dc17867f 100644 --- a/htdocs/product/stats/supplier_proposal.php +++ b/htdocs/product/stats/supplier_proposal.php @@ -40,7 +40,9 @@ $ref = GETPOST('ref', 'alpha'); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $socid = ''; -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -53,12 +55,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) { $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 = "p.date_valid"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "p.date_valid"; +} $search_month = GETPOST('search_month', 'int'); $search_year = GETPOST('search_year', 'int'); @@ -78,8 +86,7 @@ $societestatic = new Societe($db); $form = new Form($db); $formother = new FormOther($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $product = new Product($db); $result = $product->fetch($id, $ref); @@ -87,12 +94,13 @@ if ($id > 0 || !empty($ref)) $parameters = array('id' => $id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $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'); + } llxHeader("", "", $langs->trans("CardProduct".$product->type)); - if ($result > 0) - { + if ($result > 0) { $head = product_prepare_head($product); $titre = $langs->trans("CardProduct".$product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -100,12 +108,16 @@ if ($id > 0 || !empty($ref)) $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -124,30 +136,35 @@ if ($id > 0 || !empty($ref)) print dol_get_fiche_end(); - if ($user->rights->propale->lire) - { + if ($user->rights->propale->lire) { $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, p.rowid as propalid, p.ref, d.total_ht as amount,"; //$sql .= " p.ref_supplier,"; $sql .= "p.date_valid, p.fk_statut as statut, d.rowid, d.qty"; - if (!$user->rights->societe->client->voir && !$socid) + if (!$user->rights->societe->client->voir && !$socid) { $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ",".MAIN_DB_PREFIX."supplier_proposal as p"; $sql .= ", ".MAIN_DB_PREFIX."supplier_proposaldet as d"; - if (!$user->rights->societe->client->voir && !$socid) + if (!$user->rights->societe->client->voir && !$socid) { $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE p.fk_soc = s.rowid"; $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; $sql .= " AND d.fk_supplier_proposal = p.rowid"; $sql .= " AND d.fk_product =".$product->id; - if (!empty($search_month)) + if (!empty($search_month)) { $sql .= ' AND MONTH(p.datep) IN ('.$search_month.')'; - if (!empty($search_year)) + } + if (!empty($search_year)) { $sql .= ' AND YEAR(p.datep) IN ('.$search_year.')'; - if (!$user->rights->societe->client->voir && !$socid) + } + if (!$user->rights->societe->client->voir && !$socid) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) + } + if ($socid) { $sql .= " AND p.fk_soc = ".$socid; + } $sql .= $db->order($sortfield, $sortorder); // Calcul total qty and amount for global if full scan list @@ -156,8 +173,7 @@ if ($id > 0 || !empty($ref)) // Count total nb of records $totalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $totalofrecords = $db->num_rows($result); } @@ -165,24 +181,35 @@ if ($id > 0 || !empty($ref)) $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); - if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); - if (!empty($id)) $option .= '&id='.$product->id; - if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); - if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); + if ($limit > 0 && $limit != $conf->liste_limit) { + $option .= '&limit='.urlencode($limit); + } + if (!empty($id)) { + $option .= '&id='.$product->id; + } + if (!empty($search_month)) { + $option .= '&search_month='.urlencode($search_month); + } + if (!empty($search_year)) { + $option .= '&search_year='.urlencode($search_year); + } print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; - if (!empty($sortfield)) + if (!empty($sortfield)) { print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; - if (!empty($sortorder)) + } + if (!empty($sortorder)) { print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; + } print_barre_liste($langs->trans("Proposals"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); - if (!empty($page)) $option .= '&page='.urlencode($page); + if (!empty($page)) { + $option .= '&page='.urlencode($page); + } print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="divsearchfield">'; @@ -204,14 +231,12 @@ if ($id > 0 || !empty($ref)) print_liste_field_titre("Company", $_SERVER["PHP_SELF"], "s.nom", "", $option, '', $sortfield, $sortorder); print_liste_field_titre("DatePropal", $_SERVER["PHP_SELF"], "p.date_valid", "", $option, 'align="center"', $sortfield, $sortorder); print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "d.qty", "", $option, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre("AmountHT", $_SERVER["PHP_SELF"], "p.total", "", $option, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre("AmountHT", $_SERVER["PHP_SELF"], "p.total_ht", "", $option, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "p.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print "</tr>\n"; - if ($num > 0) - { - while ($i < min($num, $limit)) - { + if ($num > 0) { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($result); $total_ht += $objp->amount; @@ -237,8 +262,11 @@ if ($id > 0 || !empty($ref)) } print '<tr class="liste_total">'; - if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>'; - else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + if ($num < $limit) { + print '<td class="left">'.$langs->trans("Total").'</td>'; + } else { + print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + } print '<td colspan="2"></td>'; print '<td class="center">'.$total_qty.'</td>'; print '<td align="right">'.price($total_ht).'</td>'; diff --git a/htdocs/product/stock/card.php b/htdocs/product/stock/card.php index ffd7add3c20..294c31d49ba 100644 --- a/htdocs/product/stock/card.php +++ b/htdocs/product/stock/card.php @@ -47,8 +47,12 @@ $ref = GETPOST('ref', 'alpha'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -if (!$sortfield) $sortfield = "p.ref"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "p.ref"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} $backtopage = GETPOST('backtopage', 'alpha'); @@ -87,12 +91,12 @@ $usercandelete = (($user->rights->stock->supprimer)); $parameters = array('id'=>$id, 'ref'=>$ref); $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 (empty($reshook)) -{ +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} +if (empty($reshook)) { // Ajout entrepot - if ($action == 'add' && $user->rights->stock->creer) - { + if ($action == 'add' && $user->rights->stock->creer) { $object->ref = (string) GETPOST("ref", "alpha"); $object->fk_parent = (int) GETPOST("fk_parent", "int"); $object->label = (string) GETPOST("libelle", "alpha"); @@ -140,12 +144,10 @@ if (empty($reshook)) } // Delete warehouse - if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->stock->supprimer) - { + if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->stock->supprimer) { $object->fetch(GETPOST('id', 'int')); $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); header("Location: ".DOL_URL_ROOT.'/product/stock/list.php?restore_lastsearch_values=1'); exit; @@ -156,10 +158,8 @@ if (empty($reshook)) } // Modification entrepot - if ($action == 'update' && $cancel <> $langs->trans("Cancel")) - { - if ($object->fetch($id)) - { + if ($action == 'update' && $cancel <> $langs->trans("Cancel")) { + if ($object->fetch($id)) { $object->label = GETPOST("libelle"); $object->fk_parent = GETPOST("fk_parent"); $object->description = GETPOST("desc"); @@ -174,11 +174,15 @@ 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++; + } if (!$error) { $ret = $object->update($id, $user); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } if ($error) { @@ -198,7 +202,9 @@ if (empty($reshook)) // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } if (!$error) { $result = $object->insertExtraFields(); if ($result < 0) { @@ -206,11 +212,12 @@ if (empty($reshook)) $error++; } } - if ($error) $action = 'edit_extras'; + if ($error) { + $action = 'edit_extras'; + } } - if ($cancel == $langs->trans("Cancel")) - { + if ($cancel == $langs->trans("Cancel")) { $action = ''; } @@ -236,8 +243,7 @@ $help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks'; llxHeader("", $langs->trans("WarehouseCard"), $help_url); -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewWarehouse"), '', 'stock'); dol_set_focus('input[name="libelle"]'); @@ -285,7 +291,9 @@ if ($action == 'create') print '<tr><td>'.$langs->trans('Country').'</td><td>'; print img_picto('', 'globe-americas', 'class="paddingright"'); print $form->select_country((!empty($object->country_id) ? $object->country_id : $mysoc->country_code), 'country_id'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '</td></tr>'; // Phone / Fax @@ -300,10 +308,8 @@ if ($action == 'create') // Status print '<tr><td>'.$langs->trans("Status").'</td><td>'; print '<select name="statut" class="flat">'; - foreach ($object->statuts as $key => $value) - { - if ($key == 1) - { + foreach ($object->statuts as $key => $value) { + if ($key == 1) { print '<option value="'.$key.'" selected>'.$langs->trans($value).'</option>'; } else { print '<option value="'.$key.'">'.$langs->trans($value).'</option>'; @@ -335,12 +341,10 @@ if ($action == 'create') print '</form>'; } else { $id = GETPOST("id", 'int'); - if ($id > 0 || $ref) - { + if ($id > 0 || $ref) { $object = new Entrepot($db); $result = $object->fetch($id, $ref); - if ($result <= 0) - { + if ($result <= 0) { print 'No record found'; exit; } @@ -348,8 +352,7 @@ if ($action == 'create') /* * Affichage fiche */ - if ($action <> 'edit' && $action <> 're-edit') - { + if ($action <> 'edit' && $action <> 're-edit') { $head = stock_prepare_head($object); print dol_get_fiche_head($head, 'card', $langs->trans("Warehouse"), -1, 'stock'); @@ -357,16 +360,18 @@ if ($action == 'create') $formconfirm = ''; // Confirm delete warehouse - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("DeleteAWarehouse"), $langs->trans("ConfirmDeleteWarehouse", $object->label), "confirm_delete", '', 0, 2); } // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -379,7 +384,9 @@ if ($action == 'create') $morehtmlref .= '</div>'; $shownav = 1; - if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref); @@ -471,31 +478,24 @@ if ($action == 'create') print dol_get_fiche_end(); - /* ************************************************************************** */ - /* */ - /* Barre d'action */ - /* */ - /* ************************************************************************** */ - + /* + * Action bar + */ print "<div class=\"tabsAction\">\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { - if (empty($action)) - { + if (empty($reshook)) { + if (empty($action)) { if ($user->rights->stock->creer) { print '<a class="butAction" href="card.php?action=edit&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Modify").'</a>'; - } - else { + } else { print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("Modify").'</a>'; } if ($user->rights->stock->supprimer) { print '<a class="butActionDelete" href="card.php?action=delete&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Delete").'</a>'; - } - else { + } else { print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("Delete").'</a>'; } } @@ -516,7 +516,9 @@ if ($action == 'create') print_liste_field_titre("Product", "", "p.ref", "&amp;id=".$id, "", "", $sortfield, $sortorder); print_liste_field_titre("Label", "", "p.label", "&amp;id=".$id, "", "", $sortfield, $sortorder); print_liste_field_titre("Units", "", "ps.reel", "&amp;id=".$id, "", '', $sortfield, $sortorder, 'right '); - if (!empty($conf->global->PRODUCT_USE_UNITS)) print_liste_field_titre("Unit", "", "p.fk_unit", "&amp;id=".$id, "", 'align="left"', $sortfield, $sortorder); + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + print_liste_field_titre("Unit", "", "p.fk_unit", "&amp;id=".$id, "", 'align="left"', $sortfield, $sortorder); + } print_liste_field_titre("AverageUnitPricePMPShort", "", "p.pmp", "&amp;id=".$id, "", '', $sortfield, $sortorder, 'right '); print_liste_field_titre("EstimatedStockValueShort", "", "", "&amp;id=".$id, "", '', $sortfield, $sortorder, 'right '); if (empty($conf->global->PRODUIT_MULTIPRICES)) { @@ -538,7 +540,9 @@ if ($action == 'create') $sql = "SELECT p.rowid as rowid, p.ref, p.label as produit, p.tobatch, p.fk_product_type as type, p.pmp as ppmp, p.price, p.price_ttc, p.entity,"; $sql .= " ps.reel as value"; - if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= ",fk_unit"; + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $sql .= ",fk_unit"; + } $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps, ".MAIN_DB_PREFIX."product as p"; $sql .= " WHERE ps.fk_product = p.rowid"; $sql .= " AND ps.reel <> 0"; // We do not show if stock is 0 (no product in this warehouse) @@ -547,17 +551,14 @@ if ($action == 'create') dol_syslog('List products', LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); // Multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) // si l'option est active - { + if (!empty($conf->global->MAIN_MULTILANGS)) { // si l'option est active $sql = "SELECT label"; $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sql .= " WHERE fk_product=".$objp->rowid; @@ -565,10 +566,11 @@ if ($action == 'create') $sql .= " LIMIT 1"; $result = $db->query($sql); - if ($result) - { + if ($result) { $objtp = $db->fetch_object($result); - if ($objtp->label != '') $objp->produit = $objtp->label; + if ($objtp->label != '') { + $objp->produit = $objtp->label; + } } } @@ -598,7 +600,9 @@ if ($action == 'create') if (!empty($conf->global->PRODUCT_USE_UNITS)) { // Units print '<td align="left">'; - if (is_null($productstatic->fk_unit))$productstatic->fk_unit = 1; + if (is_null($productstatic->fk_unit)) { + $productstatic->fk_unit = 1; + } print $langs->trans($productstatic->getLabelOfUnit()); print '</td>'; } @@ -610,8 +614,7 @@ if ($action == 'create') $totalvalue += price2num($objp->ppmp * $objp->value, 'MT'); // Price sell min - if (empty($conf->global->PRODUIT_MULTIPRICES)) - { + if (empty($conf->global->PRODUIT_MULTIPRICES)) { $pricemin = $objp->price; print '<td class="right">'; print price(price2num($pricemin, 'MU'), 1); @@ -623,22 +626,23 @@ if ($action == 'create') } $totalvaluesell += price2num($pricemin * $objp->value, 'MT'); - if ($user->rights->stock->mouvement->creer) - { + if ($user->rights->stock->mouvement->creer) { print '<td class="center"><a href="'.DOL_URL_ROOT.'/product/stock/product.php?dwid='.$object->id.'&id='.$objp->rowid.'&action=transfert&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$id).'">'; print img_picto($langs->trans("StockMovement"), 'uparrow.png', 'class="hideonsmartphone"').' '.$langs->trans("StockMovement"); print "</a></td>"; } - if ($user->rights->stock->creer) - { + if ($user->rights->stock->creer) { print '<td class="center"><a href="'.DOL_URL_ROOT.'/product/stock/product.php?dwid='.$object->id.'&id='.$objp->rowid.'&action=correction&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$id).'">'; print $langs->trans("StockCorrection"); print "</a></td>"; } if (!empty($conf->global->PRODUCT_USE_UNITS)) { - if ($i == 0) $units = $productstatic->fk_unit; - elseif ($productstatic->fk_unit != $units) $sameunits = false; + if ($i == 0) { + $units = $productstatic->fk_unit; + } elseif ($productstatic->fk_unit != $units) { + $sameunits = false; + } } print "</tr>"; $i++; @@ -648,14 +652,17 @@ if ($action == 'create') print '<tr class="liste_total"><td class="liste_total" colspan="2">'.$langs->trans("Total").'</td>'; print '<td class="liste_total right">'; $valtoshow = price2num($totalunit, 'MS'); - if (empty($conf->global->PRODUCT_USE_UNITS) || $sameunits) print empty($valtoshow) ? '0' : $valtoshow; + if (empty($conf->global->PRODUCT_USE_UNITS) || $sameunits) { + print empty($valtoshow) ? '0' : $valtoshow; + } print '</td>'; print '<td class="liste_total">'; - if (empty($conf->global->PRODUCT_USE_UNITS) && $sameunits) print $langs->trans($productstatic->getLabelOfUnit()); + if (empty($conf->global->PRODUCT_USE_UNITS) && $sameunits) { + print $langs->trans($productstatic->getLabelOfUnit()); + } print '</td>'; print '<td class="liste_total right">'.price(price2num($totalvalue, 'MT')).'</td>'; - if (empty($conf->global->PRODUIT_MULTIPRICES)) - { + if (empty($conf->global->PRODUIT_MULTIPRICES)) { print '<td class="liste_total">&nbsp;</td>'; print '<td class="liste_total right">'.price(price2num($totalvaluesell, 'MT')).'</td>'; } @@ -672,8 +679,7 @@ if ($action == 'create') /* * Edition fiche */ - if ($action == 'edit' || $action == 're-edit') - { + if ($action == 'edit' || $action == 're-edit') { $langs->trans("WarehouseEdit"); print '<form action="card.php" method="POST">'; @@ -721,7 +727,9 @@ if ($action == 'create') print '<tr><td>'.$langs->trans('Country').'</td><td>'; print img_picto('', 'globe-americas', 'class="paddingright"'); print $form->select_country($object->country_id ? $object->country_id : $mysoc->country_code, 'country_id'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '</td></tr>'; // Phone / Fax @@ -735,10 +743,8 @@ if ($action == 'create') // Status print '<tr><td>'.$langs->trans("Status").'</td><td>'; print '<select name="statut" class="flat">'; - foreach ($object->statuts as $key => $value) - { - if ($key == $object->statut) - { + foreach ($object->statuts as $key => $value) { + if ($key == $object->statut) { print '<option value="'.$key.'" selected>'.$langs->trans($value).'</option>'; } else { print '<option value="'.$key.'">'.$langs->trans($value).'</option>'; @@ -751,14 +757,12 @@ if ($action == 'create') $parameters = array('colspan' => ' colspan="3"', 'cols' => '3'); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } // Tags-Categories - if ($conf->categorie->enabled) - { + if ($conf->categorie->enabled) { print '<tr><td class="tdtop">'.$langs->trans("Categories").'</td><td colspan="3">'; $cate_arbo = $form->select_all_categories(Categorie::TYPE_WAREHOUSE, '', 'parent', 64, 0, 1); $c = new Categorie($db); @@ -792,8 +796,7 @@ if ($action == 'create') $modulepart = 'stock'; -if ($action != 'create' && $action != 'edit' && $action != 'delete') -{ +if ($action != 'create' && $action != 'edit' && $action != 'delete') { print '<br>'; print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre diff --git a/htdocs/product/stock/class/api_stockmovements.class.php b/htdocs/product/stock/class/api_stockmovements.class.php index dba209e5b6f..90b3895c0f2 100644 --- a/htdocs/product/stock/class/api_stockmovements.class.php +++ b/htdocs/product/stock/class/api_stockmovements.class.php @@ -31,7 +31,7 @@ class StockMovements extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'product_id', 'warehouse_id', 'qty' @@ -63,23 +63,23 @@ class StockMovements extends DolibarrApi * @throws RestException */ /* - public function get($id) - { - if(! DolibarrApiAccess::$user->rights->stock->lire) { - throw new RestException(401); - } + public function get($id) + { + if(! DolibarrApiAccess::$user->rights->stock->lire) { + throw new RestException(401); + } - $result = $this->stockmovement->fetch($id); - if( ! $result ) { - throw new RestException(404, 'warehouse not found'); - } + $result = $this->stockmovement->fetch($id); + if( ! $result ) { + throw new RestException(404, 'warehouse not found'); + } - if( ! DolibarrApi::_checkAccessToResource('warehouse',$this->stockmovement->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if( ! DolibarrApi::_checkAccessToResource('warehouse',$this->stockmovement->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - return $this->_cleanObjectDatas($this->stockmovement); - }*/ + return $this->_cleanObjectDatas($this->stockmovement); + }*/ /** * Get a list of stock movement @@ -108,10 +108,8 @@ class StockMovements extends DolibarrApi //$sql.= ' WHERE t.entity IN ('.getEntity('stock').')'; $sql .= ' WHERE 1 = 1'; // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -120,8 +118,7 @@ class StockMovements extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -130,13 +127,11 @@ class StockMovements extends DolibarrApi } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $i = 0; $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $stockmovement_static = new MouvementStock($this->db); if ($stockmovement_static->fetch($obj->rowid)) { @@ -196,7 +191,9 @@ class StockMovements extends DolibarrApi if ($this->stockmovement->_create(DolibarrApiAccess::$user, $product_id, $warehouse_id, $qty, $type, $price, $movementlabel, $movementcode, '', $eatBy, $sellBy, $lot) <= 0) { $errormessage = $this->stockmovement->error; - if (empty($errormessage)) $errormessage = join(',', $this->stockmovement->errors); + if (empty($errormessage)) { + $errormessage = join(',', $this->stockmovement->errors); + } throw new RestException(503, 'Error when create stock movement : '.$errormessage); } @@ -211,31 +208,31 @@ class StockMovements extends DolibarrApi * @return int */ /* - public function put($id, $request_data = null) - { - if(! DolibarrApiAccess::$user->rights->stock->creer) { - throw new RestException(401); - } + public function put($id, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->stock->creer) { + throw new RestException(401); + } - $result = $this->stockmovement->fetch($id); - if( ! $result ) { - throw new RestException(404, 'stock movement not found'); - } + $result = $this->stockmovement->fetch($id); + if( ! $result ) { + throw new RestException(404, 'stock movement not found'); + } - if( ! DolibarrApi::_checkAccessToResource('stock',$this->stockmovement->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if( ! DolibarrApi::_checkAccessToResource('stock',$this->stockmovement->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - foreach($request_data as $field => $value) { - if ($field == 'id') continue; - $this->stockmovement->$field = $value; - } + foreach($request_data as $field => $value) { + if ($field == 'id') continue; + $this->stockmovement->$field = $value; + } - if($this->stockmovement->update($id, DolibarrApiAccess::$user)) - return $this->get ($id); + if($this->stockmovement->update($id, DolibarrApiAccess::$user)) + return $this->get ($id); - return false; - }*/ + return false; + }*/ /** * Delete stock movement @@ -244,31 +241,31 @@ class StockMovements extends DolibarrApi * @return array */ /* - public function delete($id) - { - if(! DolibarrApiAccess::$user->rights->stock->supprimer) { - throw new RestException(401); - } - $result = $this->stockmovement->fetch($id); - if( ! $result ) { - throw new RestException(404, 'stock movement not found'); - } + public function delete($id) + { + if(! DolibarrApiAccess::$user->rights->stock->supprimer) { + throw new RestException(401); + } + $result = $this->stockmovement->fetch($id); + if( ! $result ) { + throw new RestException(404, 'stock movement not found'); + } - if( ! DolibarrApi::_checkAccessToResource('stock',$this->stockmovement->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if( ! DolibarrApi::_checkAccessToResource('stock',$this->stockmovement->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - if (! $this->stockmovement->delete(DolibarrApiAccess::$user)) { - throw new RestException(401,'error when delete stock movement'); - } + if (! $this->stockmovement->delete(DolibarrApiAccess::$user)) { + throw new RestException(401,'error when delete stock movement'); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Warehouse deleted' - ) - ); - }*/ + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Warehouse deleted' + ) + ); + }*/ @@ -341,8 +338,9 @@ class StockMovements extends DolibarrApi { $stockmovement = array(); foreach (self::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $stockmovement[$field] = $data[$field]; } return $stockmovement; diff --git a/htdocs/product/stock/class/api_warehouses.class.php b/htdocs/product/stock/class/api_warehouses.class.php index d6f2333f3ef..34338232169 100644 --- a/htdocs/product/stock/class/api_warehouses.class.php +++ b/htdocs/product/stock/class/api_warehouses.class.php @@ -31,7 +31,7 @@ class Warehouses extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'label', ); @@ -115,10 +115,8 @@ class Warehouses extends DolibarrApi $sql .= " AND c.fk_warehouse = t.rowid "; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -127,8 +125,7 @@ class Warehouses extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -137,13 +134,11 @@ class Warehouses extends DolibarrApi } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $i = 0; $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $warehouse_static = new Entrepot($this->db); if ($warehouse_static->fetch($obj->rowid)) { @@ -208,12 +203,15 @@ class Warehouses extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->warehouse->$field = $value; } - if ($this->warehouse->update($id, DolibarrApiAccess::$user)) + if ($this->warehouse->update($id, DolibarrApiAccess::$user)) { return $this->get($id); + } return false; } @@ -282,8 +280,9 @@ class Warehouses extends DolibarrApi { $warehouse = array(); foreach (Warehouses::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $warehouse[$field] = $data[$field]; } return $warehouse; diff --git a/htdocs/product/stock/class/entrepot.class.php b/htdocs/product/stock/class/entrepot.class.php index ac3ce4636e6..9d601dc9687 100644 --- a/htdocs/product/stock/class/entrepot.class.php +++ b/htdocs/product/stock/class/entrepot.class.php @@ -203,37 +203,29 @@ class Entrepot extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $id = $this->db->last_insert_id(MAIN_DB_PREFIX."entrepot"); - if ($id > 0) - { + if ($id > 0) { $this->id = $id; - if (!$error) - { + if (!$error) { $result = $this->update($id, $user); - if ($result <= 0) - { + if ($result <= 0) { $error++; } } // Actions on extra fields - if (!$error) - { - if (!$error) - { + if (!$error) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } } - if (!$error) - { + if (!$error) { $this->db->commit(); return $id; } else { @@ -267,16 +259,18 @@ class Entrepot extends CommonObject $error = 0; - if (empty($id)) $id = $this->id; - if (empty($this->label)) $this->label = $this->libelle; // For backward compatibility + if (empty($id)) { + $id = $this->id; + } + if (empty($this->label)) { + $this->label = $this->libelle; // For backward compatibility + } // Check if new parent is already a child of current warehouse - if (!empty($this->fk_parent)) - { + if (!empty($this->fk_parent)) { $TChildWarehouses = array($id); $TChildWarehouses = $this->get_children_warehouses($this->id, $TChildWarehouses); - if (in_array($this->fk_parent, $TChildWarehouses)) - { + if (in_array($this->fk_parent, $TChildWarehouses)) { $this->error = 'ErrorCannotAddThisParentWarehouse'; return -2; } @@ -305,7 +299,7 @@ class Entrepot extends CommonObject $sql .= ", fk_pays = ".$this->country_id; $sql .= ", phone = '".$this->db->escape($this->phone)."'"; $sql .= ", fax = '".$this->db->escape($this->fax)."'"; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); $this->db->begin(); @@ -319,8 +313,7 @@ class Entrepot extends CommonObject if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } @@ -353,25 +346,23 @@ class Entrepot extends CommonObject $this->db->begin(); - if (!$error && empty($notrigger)) - { + if (!$error && empty($notrigger)) { // Call trigger $result = $this->call_trigger('WAREHOUSE_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } $elements = array('stock_mouvement', 'product_stock', 'product_warehouse_properties'); - foreach ($elements as $table) - { - if (!$error) - { + foreach ($elements as $table) { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table; $sql .= " WHERE fk_entrepot = ".$this->id; $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $error++; $this->errors[] = $this->db->lasterror(); } @@ -379,47 +370,39 @@ class Entrepot extends CommonObject } // Removed extrafields - if (!$error) - { - if (!$error) - { + if (!$error) { + if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete Error ".$this->error, LOG_ERR); } } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."entrepot"; $sql .= " WHERE rowid = ".$this->id; $resql1 = $this->db->query($sql); - if (!$resql1) - { + if (!$resql1) { $error++; $this->errors[] = $this->db->lasterror(); dol_syslog(get_class($this)."::delete Error ".$this->db->lasterror(), LOG_ERR); } } - if (!$error) - { + if (!$error) { // Update denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql $sql = "UPDATE ".MAIN_DB_PREFIX."product as p SET stock = (SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)"; $resql2 = $this->db->query($sql); - if (!$resql2) - { + if (!$resql2) { $error++; $this->errors[] = $this->db->lasterror(); dol_syslog(get_class($this)."::delete Error ".$this->db->lasterror(), LOG_ERR); } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -443,8 +426,7 @@ class Entrepot extends CommonObject dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref); // Check parameters - if (!$id && !$ref) - { + if (!$id && !$ref) { $this->error = 'ErrorWrongParameters'; dol_syslog(get_class($this)."::fetch ".$this->error); return -1; @@ -453,19 +435,18 @@ class Entrepot extends CommonObject $sql = "SELECT rowid, entity, fk_parent, ref as label, description, statut, lieu, address, zip, town, fk_pays as country_id, phone, fax,"; $sql .= " model_pdf, import_key"; $sql .= " FROM ".MAIN_DB_PREFIX."entrepot"; - if ($id) - { + if ($id) { $sql .= " WHERE rowid = '".$id."'"; } else { $sql .= " WHERE entity = ".$conf->entity; - if ($ref) $sql .= " AND ref = '".$this->db->escape($ref)."'"; + if ($ref) { + $sql .= " AND ref = '".$this->db->escape($ref)."'"; + } } $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result) > 0) - { + if ($result) { + if ($this->db->num_rows($result) > 0) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -518,14 +499,12 @@ class Entrepot extends CommonObject { $sql = "SELECT e.rowid, e.datec, e.tms as datem, e.fk_user_author"; $sql .= " FROM ".MAIN_DB_PREFIX."entrepot 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); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -573,10 +552,8 @@ class Entrepot extends CommonObject $result = $this->db->query($sql); $i = 0; $num = $this->db->num_rows($result); - if ($result) - { - while ($i < $num) - { + if ($result) { + while ($i < $num) { $row = $this->db->fetch_row($result); $liste[$row[0]] = $row[1]; $i++; @@ -605,8 +582,7 @@ class Entrepot extends CommonObject //print $sql; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $obj = $this->db->fetch_object($result); $ret['nb'] = $obj->nb; $this->db->free($result); @@ -637,8 +613,7 @@ class Entrepot extends CommonObject //print $sql; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $obj = $this->db->fetch_object($result); $ret['nb'] = $obj->nb; $ret['value'] = $obj->value; @@ -676,7 +651,9 @@ class Entrepot extends CommonObject global $langs; $statusType = 'status5'; - if ($status > 0) $statusType = 'status4'; + if ($status > 0) { + $statusType = 'status4'; + } $langs->load('stocks'); $label = $langs->trans($this->statuts[$status]); @@ -700,9 +677,13 @@ class Entrepot extends CommonObject global $conf, $langs, $hookmanager; $langs->load("stocks"); - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) $withpicto = 0; + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) { + $withpicto = 0; + } $result = ''; @@ -718,10 +699,8 @@ class Entrepot extends CommonObject $url = DOL_URL_ROOT.'/product/stock/card.php?id='.$this->id; $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("Warehouse"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -734,8 +713,12 @@ class Entrepot extends CommonObject $linkend = '</a>'; $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 .= (($showfullpath || !empty($conf->global->STOCK_ALWAYS_SHOW_FULL_ARBO)) ? $this->get_full_arbo() : (empty($this->label) ? $this->libelle : $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 .= (($showfullpath || !empty($conf->global->STOCK_ALWAYS_SHOW_FULL_ARBO)) ? $this->get_full_arbo() : (empty($this->label) ? $this->libelle : $this->label)); + } $result .= $linkend; global $action; @@ -798,20 +781,21 @@ class Entrepot extends CommonObject $parentid = $this->fk_parent; // If parent_id not defined on current object, we do not start consecutive searches of parents $i = 0; - while ($parentid > 0 && $i < $protection) - { + while ($parentid > 0 && $i < $protection) { $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'entrepot WHERE rowid = '.$parentid; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $objarbo = $this->db->fetch_object($resql); - if ($objarbo) - { + if ($objarbo) { $warehousetmp->fetch($parentid); $TArbo[] = $warehousetmp->label; - $parentid = $objarbo->fk_parent; - } else break; - } else dol_print_error($this->db); + $parentid = $objarbo->fk_parent; + } else { + break; + } + } else { + dol_print_error($this->db); + } $i++; } diff --git a/htdocs/product/stock/class/mouvementstock.class.php b/htdocs/product/stock/class/mouvementstock.class.php index 639816f842d..3c04618c900 100644 --- a/htdocs/product/stock/class/mouvementstock.class.php +++ b/htdocs/product/stock/class/mouvementstock.class.php @@ -164,35 +164,35 @@ class MouvementStock extends CommonObject $hookmanager->initHooks(array('mouvementstock')); // Hook of thirdparty module if (is_object($hookmanager)) { - $parameters = array( - 'currentcontext' => 'mouvementstock', - 'user' => &$user, - 'fk_product' => &$fk_product, - 'entrepot_id' => &$entrepot_id, - 'qty' => &$qty, - 'type' => &$type, - 'price' => &$price, - 'label' => &$label, - 'inventorycode' => &$inventorycode, - 'datem' => &$datem, - 'eatby' => &$eatby, - 'sellby' => &$sellby, - 'batch' => &$batch, - 'skip_batch' => &$skip_batch, - 'id_product_batch' => &$id_product_batch - ); - $reshook = $hookmanager->executeHooks('stockMovementCreate', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array( + 'currentcontext' => 'mouvementstock', + 'user' => &$user, + 'fk_product' => &$fk_product, + 'entrepot_id' => &$entrepot_id, + 'qty' => &$qty, + 'type' => &$type, + 'price' => &$price, + 'label' => &$label, + 'inventorycode' => &$inventorycode, + 'datem' => &$datem, + 'eatby' => &$eatby, + 'sellby' => &$sellby, + 'batch' => &$batch, + 'skip_batch' => &$skip_batch, + 'id_product_batch' => &$id_product_batch + ); + $reshook = $hookmanager->executeHooks('stockMovementCreate', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) { - if (!empty($hookmanager->resPrint)) - dol_print_error('', $hookmanager->resPrint); - return $reshook; - } elseif ($reshook > 0) { - return $hookmanager->resPrint; - } + if ($reshook < 0) { + if (!empty($hookmanager->resPrint)) + dol_print_error('', $hookmanager->resPrint); + return $reshook; + } elseif ($reshook > 0) { + return $hookmanager->resPrint; + } } // end hook at beginning - + // Clean parameters $price = price2num($price, 'MU'); // Clean value for the casse we receive a float zero value, to have it a real zero value. if (empty($price)) $price = 0; @@ -568,14 +568,32 @@ class MouvementStock extends CommonObject // Update detail stock for batch product if (!$error && !empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch) { - if ($id_product_batch > 0) + // check unicity for serial numbered equipments ( different for lots managed products) + if ( $product->status_batch == 2 && $qty > 0 ) { - $result = $this->createBatch($id_product_batch, $qty); - } else { - $param_batch = array('fk_product_stock' =>$fk_product_stock, 'batchnumber'=>$batch); - $result = $this->createBatch($param_batch, $qty); + if ( $this->getBatchCount($fk_product, $batch) > 0 ) + { + $error++; + $this->errors[] = $langs->trans("SerialNumberAlreadyInUse", $batch, $product->ref); + } + elseif ( $qty > 1 ) + { + $error++; + $this->errors[] = $langs->trans("TooManyQtyForSerialNumber", $product->ref, $batch); + } + } + + if ( ! $error ) + { + if ($id_product_batch > 0) + { + $result = $this->createBatch($id_product_batch, $qty); + } else { + $param_batch = array('fk_product_stock' =>$fk_product_stock, 'batchnumber'=>$batch); + $result = $this->createBatch($param_batch, $qty); + } + if ($result < 0) $error++; } - if ($result < 0) $error++; } // Update PMP and denormalized value of stock qty at product level @@ -669,7 +687,7 @@ class MouvementStock extends CommonObject //if (null !== $ref) { //$sql .= ' AND t.ref = ' . '\'' . $ref . '\''; //} else { - $sql .= ' AND t.rowid = '.$id; + $sql .= ' AND t.rowid = '.((int) $id); //} $resql = $this->db->query($sql); @@ -1020,15 +1038,13 @@ class MouvementStock extends CommonObject break; default: - if ($origintype) - { + if ($origintype) { // Separate originetype with "@" : left part is class name, right part is module name $origintype_array = explode('@', $origintype); $classname = ucfirst($origintype_array[0]); $modulename = empty($origintype_array[1]) ? $classname : $origintype_array[1]; $result = dol_include_once('/'.$modulename.'/class/'.strtolower($classname).'.class.php'); - if ($result) - { + if ($result) { $classname = ucfirst($classname); $origin = new $classname($this->db); } @@ -1036,7 +1052,9 @@ class MouvementStock extends CommonObject break; } - if (empty($origin) || !is_object($origin)) return ''; + if (empty($origin) || !is_object($origin)) { + return ''; + } if ($origin->fetch($fk_origin) > 0) { return $origin->getNomUrl(1); @@ -1055,17 +1073,16 @@ class MouvementStock extends CommonObject */ public function setOrigin($origin_element, $origin_id) { - if (!empty($origin_element) && $origin_id > 0) - { + if (!empty($origin_element) && $origin_id > 0) { $origin = ''; - if ($origin_element == 'project') - { - if (!class_exists('Project')) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + if ($origin_element == 'project') { + if (!class_exists('Project')) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + } $origin = new Project($this->db); } - if (!empty($origin)) - { + if (!empty($origin)) { $this->origin = $origin; $this->origin->id = $origin_id; } @@ -1119,10 +1136,11 @@ class MouvementStock extends CommonObject $link .= '>'; $linkend = '</a>'; - if ($withpicto) - { + if ($withpicto) { $result .= ($link.img_object(($notooltip ? '' : $label), 'stock', ($notooltip ? '' : 'class="classfortooltip"')).$linkend); - if ($withpicto != 2) $result .= ' '; + if ($withpicto != 2) { + $result .= ' '; + } } $result .= $link.$this->id.$linkend; return $result; @@ -1208,4 +1226,39 @@ class MouvementStock extends CommonObject return $this->deleteCommon($user, $notrigger); //return $this->deleteCommon($user, $notrigger, 1); } + + /** + * Retrieve number of equipments for a product batch + * + * @param int $fk_product Product id + * @param varchar $batch batch number + * @return int <0 if KO, number of equipments if OK + */ + private function getBatchCount($fk_product, $batch) + { + global $conf; + + $cpt = 0; + + $sql = "SELECT sum(pb.qty) as cpt"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_batch as pb"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."product_stock as ps ON ps.rowid = pb.fk_product_stock"; + $sql .= " WHERE ps.fk_product = " . $fk_product; + $sql .= " AND pb.batch = '" . $this->db->escape($batch) . "'"; + + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $cpt = $obj->cpt; + } + + $this->db->free($result); + } else { + dol_print_error($this->db); + return -1; + } + + return $cpt; + } } diff --git a/htdocs/product/stock/class/productlot.class.php b/htdocs/product/stock/class/productlot.class.php index 3e7c23a6e92..9b6c0a38a1c 100644 --- a/htdocs/product/stock/class/productlot.class.php +++ b/htdocs/product/stock/class/productlot.class.php @@ -95,7 +95,8 @@ class Productlot extends CommonObject 'datec' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>500), 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501), 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'), - 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511) + 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511), + 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000), ); /** @@ -214,11 +215,9 @@ class Productlot extends CommonObject $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } @@ -229,7 +228,9 @@ class Productlot extends CommonObject // Call triggers $result = $this->call_trigger('PRODUCTLOT_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } } @@ -276,7 +277,7 @@ class Productlot extends CommonObject if ($product_id > 0 && $batch != '') { $sql .= " WHERE t.batch = '".$this->db->escape($batch)."' AND t.fk_product = ".$product_id; } else { - $sql .= ' WHERE t.rowid = '.$id; + $sql .= ' WHERE t.rowid = '.((int) $id); } $resql = $this->db->query($sql); @@ -357,8 +358,7 @@ class Productlot extends CommonObject // Check parameters // Put here code to add a control on parameters values - if (empty($this->oldcopy)) - { + if (empty($this->oldcopy)) { $org = new self($this->db); $org->fetch($this->id); $this->oldcopy = $org; @@ -376,7 +376,7 @@ class Productlot extends CommonObject $sql .= ' fk_user_creat = '.(isset($this->fk_user_creat) ? $this->fk_user_creat : "null").','; $sql .= ' fk_user_modif = '.(isset($this->fk_user_modif) ? $this->fk_user_modif : "null").','; $sql .= ' import_key = '.(isset($this->import_key) ? $this->import_key : "null"); - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); $this->db->begin(); @@ -388,11 +388,9 @@ class Productlot extends CommonObject } // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } @@ -400,7 +398,9 @@ class Productlot extends CommonObject if (!$error && !$notrigger) { // Call triggers $result = $this->call_trigger('PRODUCTLOT_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -446,7 +446,7 @@ class Productlot extends CommonObject if (!$error) { $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) { @@ -568,47 +568,60 @@ class Productlot extends CommonObject $result = ''; - $label = '<u>'.$langs->trans("Batch").'</u>'; + $label = img_picto('', $this->picto).' <u>'.$langs->trans("Batch").'</u>'; $label .= '<div width="100%">'; $label .= '<b>'.$langs->trans('Batch').':</b> '.$this->batch; - if ($this->eatby) - { + if ($this->eatby && empty($conf->global->PRODUCT_DISABLE_EATBY)) { $label .= '<br><b>'.$langs->trans('EatByDate').':</b> '.dol_print_date($this->eatby, 'day'); } - if ($this->sellby) - { + if ($this->sellby && empty($conf->global->PRODUCT_DISABLE_SELLBY)) { $label .= '<br><b>'.$langs->trans('SellByDate').':</b> '.dol_print_date($this->sellby, 'day'); } $url = DOL_URL_ROOT.'/product/stock/productlot_card.php?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowMyObject"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } - $linkstart = '<a href="'.$url.'"'; + if ($option == 'nolink') { + $linkstart = '<span'; + } else { + $linkstart = '<a href="'.$url.'"'; + } $linkstart .= $linkclose.'>'; - $linkend = '</a>'; + if ($option == 'nolink') { + $linkend = '</span>'; + } else { + $linkend = '</a>'; + } $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 .= $this->batch; + 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 .= $this->batch; + } $result .= $linkend; return $result; diff --git a/htdocs/product/stock/class/productstockentrepot.class.php b/htdocs/product/stock/class/productstockentrepot.class.php index ad36dc43c15..88fc636e07e 100644 --- a/htdocs/product/stock/class/productstockentrepot.class.php +++ b/htdocs/product/stock/class/productstockentrepot.class.php @@ -93,11 +93,21 @@ class ProductStockEntrepot extends CommonObject // Clean parameters - if (isset($this->fk_product)) $this->fk_product = (int) $this->fk_product; - if (isset($this->fk_entrepot)) $this->fk_entrepot = (int) $this->fk_entrepot; - if (isset($this->seuil_stock_alerte)) $this->seuil_stock_alerte = trim($this->seuil_stock_alerte); - if (isset($this->desiredstock)) $this->desiredstock = trim($this->desiredstock); - if (isset($this->import_key)) $this->import_key = trim($this->import_key); + if (isset($this->fk_product)) { + $this->fk_product = (int) $this->fk_product; + } + if (isset($this->fk_entrepot)) { + $this->fk_entrepot = (int) $this->fk_entrepot; + } + if (isset($this->seuil_stock_alerte)) { + $this->seuil_stock_alerte = trim($this->seuil_stock_alerte); + } + if (isset($this->desiredstock)) { + $this->desiredstock = trim($this->desiredstock); + } + if (isset($this->import_key)) { + $this->import_key = trim($this->import_key); + } // Check parameters // Put here code to add control on parameters values @@ -168,7 +178,9 @@ class ProductStockEntrepot extends CommonObject */ public function fetch($id, $fk_product = 0, $fk_entrepot = 0) { - if (empty($id) && (empty($fk_product) || empty($fk_entrepot))) return -1; + if (empty($id) && (empty($fk_product) || empty($fk_entrepot))) { + return -1; + } dol_syslog(__METHOD__, LOG_DEBUG); @@ -181,15 +193,16 @@ class ProductStockEntrepot extends CommonObject $sql .= " t.desiredstock,"; $sql .= " t.import_key"; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if (!empty($id)) $sql .= ' WHERE t.rowid = '.$id; - else $sql .= ' WHERE t.fk_product = '.$fk_product.' AND t.fk_entrepot = '.$fk_entrepot; + if (!empty($id)) { + $sql .= ' WHERE t.rowid = '.((int) $id); + } else { + $sql .= ' WHERE t.fk_product = '.$fk_product.' AND t.fk_entrepot = '.$fk_entrepot; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $numrows = $this->db->num_rows($resql); - if ($numrows) - { + if ($numrows) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -263,14 +276,23 @@ class ProductStockEntrepot extends CommonObject $sqlwhere [] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; } } - if (count($sqlwhere) > 0) $sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere); + if (count($sqlwhere) > 0) { + $sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere); + } - if (!empty($fk_product)) $sql .= ' AND fk_product = '.$fk_product; - elseif (!empty($fk_entrepot)) $sql .= ' AND fk_entrepot = '.$fk_entrepot; + if (!empty($fk_product)) { + $sql .= ' AND fk_product = '.$fk_product; + } elseif (!empty($fk_entrepot)) { + $sql .= ' AND fk_entrepot = '.$fk_entrepot; + } // "elseif" used instead of "if" because getting list with specified fk_product and specified fk_entrepot would be the same as doing a fetch - if (!empty($sortfield)) $sql .= $this->db->order($sortfield, $sortorder); - if (!empty($limit)) $sql .= ' '.$this->db->plimit($limit, $offset); + if (!empty($sortfield)) { + $sql .= $this->db->order($sortfield, $sortorder); + } + if (!empty($limit)) { + $sql .= ' '.$this->db->plimit($limit, $offset); + } $lines = array(); @@ -312,11 +334,21 @@ class ProductStockEntrepot extends CommonObject // Clean parameters - if (isset($this->fk_product)) $this->fk_product = (int) $this->fk_product; - if (isset($this->fk_entrepot)) $this->fk_entrepot = (int) $this->fk_entrepot; - if (isset($this->seuil_stock_alerte)) $this->seuil_stock_alerte = trim($this->seuil_stock_alerte); - if (isset($this->desiredstock)) $this->desiredstock = trim($this->desiredstock); - if (isset($this->import_key)) $this->import_key = trim($this->import_key); + if (isset($this->fk_product)) { + $this->fk_product = (int) $this->fk_product; + } + if (isset($this->fk_entrepot)) { + $this->fk_entrepot = (int) $this->fk_entrepot; + } + if (isset($this->seuil_stock_alerte)) { + $this->seuil_stock_alerte = trim($this->seuil_stock_alerte); + } + if (isset($this->desiredstock)) { + $this->desiredstock = trim($this->desiredstock); + } + if (isset($this->import_key)) { + $this->import_key = trim($this->import_key); + } // Check parameters @@ -333,7 +365,7 @@ class ProductStockEntrepot extends CommonObject $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(); @@ -394,7 +426,7 @@ class ProductStockEntrepot extends CommonObject if (!$error) { $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) { @@ -495,10 +527,11 @@ class ProductStockEntrepot extends CommonObject $link .= '>'; $linkend = '</a>'; - if ($withpicto) - { + if ($withpicto) { $result .= ($link.img_object(($notooltip ? '' : $label), 'label', ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend); - if ($withpicto != 2) $result .= ' '; + if ($withpicto != 2) { + $result .= ' '; + } } $result .= $link.$this->ref.$linkend; return $result; @@ -528,30 +561,42 @@ class ProductStockEntrepot extends CommonObject // phpcs:enable global $langs; - if ($mode == 0) - { - if ($status == 1) return $langs->trans('Enabled'); - elseif ($status == 0) return $langs->trans('Disabled'); - } elseif ($mode == 1) - { - if ($status == 1) return $langs->trans('Enabled'); - elseif ($status == 0) return $langs->trans('Disabled'); - } elseif ($mode == 2) - { - if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled'); - elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled'); - } elseif ($mode == 3) - { - if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4'); - elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5'); - } elseif ($mode == 4) - { - if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled'); - elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled'); - } elseif ($mode == 5) - { - if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4'); - elseif ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5'); + if ($mode == 0) { + if ($status == 1) { + return $langs->trans('Enabled'); + } elseif ($status == 0) { + return $langs->trans('Disabled'); + } + } elseif ($mode == 1) { + if ($status == 1) { + return $langs->trans('Enabled'); + } elseif ($status == 0) { + return $langs->trans('Disabled'); + } + } elseif ($mode == 2) { + if ($status == 1) { + return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled'); + } elseif ($status == 0) { + return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled'); + } + } elseif ($mode == 3) { + if ($status == 1) { + return img_picto($langs->trans('Enabled'), 'statut4'); + } elseif ($status == 0) { + return img_picto($langs->trans('Disabled'), 'statut5'); + } + } elseif ($mode == 4) { + if ($status == 1) { + return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled'); + } elseif ($status == 0) { + return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled'); + } + } elseif ($mode == 5) { + if ($status == 1) { + return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4'); + } elseif ($status == 0) { + return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5'); + } } } diff --git a/htdocs/product/stock/fiche-valo.php b/htdocs/product/stock/fiche-valo.php index 55ac057985b..34380efbe7a 100644 --- a/htdocs/product/stock/fiche-valo.php +++ b/htdocs/product/stock/fiche-valo.php @@ -43,14 +43,14 @@ $form = new Form($db); $help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks'; llxHeader("", $langs->trans("WarehouseCard"), $help_url); -if ($_GET["id"]) -{ - if ($mesg) print $mesg; +if ($_GET["id"]) { + if ($mesg) { + print $mesg; + } $entrepot = new Entrepot($db); $result = $entrepot->fetch($_GET["id"]); - if ($result < 0) - { + if ($result < 0) { dol_print_error($db); } @@ -120,13 +120,11 @@ if ($_GET["id"]) - if (file_exists($file)) - { + if (file_exists($file)) { $url = DOL_URL_ROOT.'/viewimage.php?modulepart=graph_stock&amp;file=entrepot-'.$entrepot->id.'-'.$year.'.png'; print '<img src="'.$url.'" alt="Valorisation du stock annee '.($year).'">'; - if (file_exists(DOL_DATA_ROOT.'/entrepot/temp/entrepot-'.$entrepot->id.'-'.($year - 1).'.png')) - { + if (file_exists(DOL_DATA_ROOT.'/entrepot/temp/entrepot-'.$entrepot->id.'-'.($year - 1).'.png')) { $url = DOL_URL_ROOT.'/viewimage.php?modulepart=graph_stock&amp;file=entrepot-'.$entrepot->id.'-'.($year - 1).'.png'; print '<br><img src="'.$url.'" alt="Valorisation du stock annee '.($year - 1).'">'; } diff --git a/htdocs/product/stock/index.php b/htdocs/product/stock/index.php index 1c93d1ee943..ff2c99c0b09 100644 --- a/htdocs/product/stock/index.php +++ b/htdocs/product/stock/index.php @@ -28,6 +28,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; $hookmanager = new HookManager($db); @@ -59,8 +60,7 @@ print load_fiche_titre($langs->trans("StocksArea"), '', 'stock'); print '<div class="fichecenter"><div class="fichethirdleft">'; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo print '<form method="post" action="'.DOL_URL_ROOT.'/product/stock/list.php">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<div class="div-table-responsive-no-min">'; @@ -83,8 +83,7 @@ $sql .= $db->plimit($max + 1, 0); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); print '<div class="div-table-responsive-no-min">'; @@ -101,10 +100,8 @@ if ($result) print '</tr>'; $i = 0; - if ($num) - { - while ($i < min($max, $num)) - { + if ($num) { + while ($i < min($max, $num)) { $objp = $db->fetch_object($result); $warehouse->id = $objp->rowid; @@ -152,14 +149,15 @@ $sql .= ", ".MAIN_DB_PREFIX."product as p"; $sql .= " WHERE m.fk_product = p.rowid"; $sql .= " AND m.fk_entrepot = e.rowid"; $sql .= " AND e.entity IN (".getEntity('stock').")"; -if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= " AND p.fk_product_type = ".Product::TYPE_PRODUCT; +if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $sql .= " AND p.fk_product_type = ".Product::TYPE_PRODUCT; +} $sql .= $db->order("datem", "DESC"); $sql .= $db->plimit($max, 0); dol_syslog("Index:list stock movements", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); print '<div class="div-table-responsive-no-min">'; @@ -167,23 +165,23 @@ if ($resql) print "<tr class=\"liste_titre\">"; print '<th>'.$langs->trans("LastMovements", min($num, $max)).'</th>'; print '<th>'.$langs->trans("Product").'</th>'; - if (!empty($conf->productbatch->enabled)) - { + if (!empty($conf->productbatch->enabled)) { print '<th>'.$langs->trans("Batch").'</th>'; - if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { + /*if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { print '<th>'.$langs->trans("SellByDate").'</th>'; } if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { print '<th>'.$langs->trans("EatByDate").'</th>'; - } + }*/ } print '<th>'.$langs->trans("Warehouse").'</th>'; print '<th class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/product/stock/movement_list.php">'.$langs->trans("FullList").'</a></th>'; print "</tr>\n"; + $tmplotstatic = new Productlot($db); + $i = 0; - while ($i < min($num, $max)) - { + while ($i < min($num, $max)) { $objp = $db->fetch_object($resql); $producttmp->id = $objp->rowid; @@ -198,26 +196,33 @@ if ($resql) $warehouse->label = $objp->warehouse_label; $warehouse->lieu = $objp->lieu; + $tmplotstatic->batch = $objp->batch; + $tmplotstatic->sellby = $objp->sellby; + $tmplotstatic->eatby = $objp->eatby; + print '<tr class="oddeven">'; print '<td class="nowraponall">'.dol_print_date($db->jdate($objp->datem), 'dayhour').'</td>'; print '<td class="tdoverflowmax200">'; print $producttmp->getNomUrl(1); print "</td>\n"; - if (!empty($conf->productbatch->enabled)) - { - print '<td>'.$objp->batch.'</td>'; - if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { + if (!empty($conf->productbatch->enabled)) { + print '<td>'; + print $tmplotstatic->getNomUrl(0, 'nolink'); + print '</td>'; + /*if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { print '<td>'.dol_print_date($db->jdate($objp->sellby), 'day').'</td>'; } if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { print '<td>'.dol_print_date($db->jdate($objp->eatby), 'day').'</td>'; - } + }*/ } print '<td class="tdoverflowmax200">'; print $warehouse->getNomUrl(1); print "</td>\n"; print '<td class="right">'; - if ($objp->qty > 0) print '+'; + if ($objp->qty > 0) { + print '+'; + } print $objp->qty.'</td>'; print "</tr>\n"; $i++; diff --git a/htdocs/product/stock/info.php b/htdocs/product/stock/info.php index 884deaaefff..84c0111f290 100644 --- a/htdocs/product/stock/info.php +++ b/htdocs/product/stock/info.php @@ -60,7 +60,9 @@ $morehtmlref .= $langs->trans("LocationSummary").' : '.$object->lieu; $morehtmlref .= '</div>'; $shownav = 1; -if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; +if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; +} dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref); diff --git a/htdocs/product/stock/lib/replenishment.lib.php b/htdocs/product/stock/lib/replenishment.lib.php index b6ce237a2b5..d0415ccad78 100644 --- a/htdocs/product/stock/lib/replenishment.lib.php +++ b/htdocs/product/stock/lib/replenishment.lib.php @@ -43,30 +43,33 @@ function dolDispatchToDo($order_id) $sql .= ' GROUP BY fk_product'; $sql .= ' ORDER by fk_product'; $resql = $db->query($sql); - if ($resql && $db->num_rows($resql)) - { - while ($obj = $db->fetch_object($resql)) + if ($resql && $db->num_rows($resql)) { + while ($obj = $db->fetch_object($resql)) { $dispatched[$obj->fk_product] = $obj; + } } // Count nb of quantity to dispatch per product $sql = 'SELECT fk_product, SUM(qty) FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet'; $sql .= ' WHERE fk_commande = '.$order_id; $sql .= ' AND fk_product > 0'; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= ' AND product_type = 0'; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $sql .= ' AND product_type = 0'; + } $sql .= ' GROUP BY fk_product'; $sql .= ' ORDER by fk_product'; $resql = $db->query($sql); - if ($resql && $db->num_rows($resql)) - { - while ($obj = $db->fetch_object($resql)) + if ($resql && $db->num_rows($resql)) { + while ($obj = $db->fetch_object($resql)) { $ordered[$obj->fk_product] = $obj; + } } $todispatch = 0; - foreach ($ordered as $key => $val) - { - if ($ordered[$key] > $dispatched[$key]) $todispatch++; + foreach ($ordered as $key => $val) { + if ($ordered[$key] > $dispatched[$key]) { + $todispatch++; + } } return ($todispatch ? true : false); @@ -85,19 +88,15 @@ function dispatchedOrders() $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'commande_fournisseur'; $resql = $db->query($sql); $resarray = array(); - if ($resql && $db->num_rows($resql) > 0) - { - while ($obj = $db->fetch_object($resql)) - { - if (!dolDispatchToDo($obj->rowid)) - { + if ($resql && $db->num_rows($resql) > 0) { + while ($obj = $db->fetch_object($resql)) { + if (!dolDispatchToDo($obj->rowid)) { $resarray[] = $obj->rowid; } } } - if (count($resarray)) - { + if (count($resarray)) { $res = '('.implode(',', $resarray).')'; } else { //hack to make sure ordered SQL request won't syntax error @@ -131,11 +130,9 @@ function ordered($product_id) $sql .= ' GROUP BY cfd.fk_product'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $exists = $db->num_rows($resql); - if ($exists) - { + if ($exists) { $obj = $db->fetch_array($resql); return $obj['qty']; //. ' ' . img_picto('','tick'); } else { diff --git a/htdocs/product/stock/list.php b/htdocs/product/stock/list.php index c823042eba0..1aafe3c6ae2 100644 --- a/htdocs/product/stock/list.php +++ b/htdocs/product/stock/list.php @@ -28,8 +28,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; -if (!empty($conf->categorie->enabled)) -{ +if (!empty($conf->categorie->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcategory.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; } @@ -54,8 +53,7 @@ $search_ref = GETPOST("sref", "alpha") ?GETPOST("sref", "alpha") : GETPOST("sear $search_label = GETPOST("snom", "alpha") ?GETPOST("snom", "alpha") : GETPOST("search_label", "alpha"); $search_status = GETPOST("search_status", "int"); -if (!empty($conf->categorie->enabled)) -{ +if (!empty($conf->categorie->enabled)) { $search_category_list = GETPOST("search_category_".Categorie::TYPE_WAREHOUSE."_list", "array"); } @@ -64,12 +62,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 = "t.ref"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "t.ref"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Security check $result = restrictedArea($user, 'stock'); @@ -89,18 +93,22 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $search_key = $key; - if ($search_key == 'statut') $search_key = 'status'; // remove this after refactor entrepot.class property statut to status - if (GETPOST('search_'.$search_key, 'alpha') !== '') $search[$search_key] = GETPOST('search_'.$search_key, 'alpha'); + if ($search_key == 'statut') { + $search_key = 'status'; // remove this after refactor entrepot.class property statut to status + } + if (GETPOST('search_'.$search_key, 'alpha') !== '') { + $search[$search_key] = GETPOST('search_'.$search_key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of array of fields for columns @@ -133,31 +141,33 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($object->fields as $key => $val) - { + 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 + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $toselect = array(); $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -189,13 +199,14 @@ $title = $langs->trans("ListOfWarehouses"); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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.', ' : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); + } } $sql .= " SUM(p.pmp * ps.reel) as estimatedvalue, SUM(p.price * ps.reel) as sellvalue, SUM(ps.reel) as stockqty"; // Add fields from hooks @@ -204,33 +215,42 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= $hookmanager->resPrint; $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (!empty($conf->categorie->enabled)) -{ +if (!empty($conf->categorie->enabled)) { $sql .= Categorie::getFilterJoinQuery(Categorie::TYPE_WAREHOUSE, "t.rowid"); } -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON t.rowid = ps.fk_entrepot"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON ps.fk_product = p.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as c_dep ON c_dep.rowid = t.fk_departement"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as ccount ON ccount.rowid = t.fk_pays"; $sql .= " WHERE t.entity IN (".getEntity('stock').")"; -if (!empty($conf->categorie->enabled)) -{ +if (!empty($conf->categorie->enabled)) { $sql .= Categorie::getFilterSelectQuery(Categorie::TYPE_WAREHOUSE, "t.rowid", $search_category_list); } -foreach ($search as $key => $val) -{ +foreach ($search as $key => $val) { $class_key = $key; - if ($class_key == 'status') $class_key = 'statut'; // remove this after refactor entrepot.class property statut to status - if (($key == 'status' && $search[$key] == -1) || $key == 'entity') continue; + if ($class_key == 'status') { + $class_key = 'statut'; // remove this after refactor entrepot.class property statut to status + } + if (($key == 'status' && $search[$key] == -1) || $key == 'entity') { + continue; + } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); if (strpos($object->fields[$key]['type'], 'integer:') === 0) { - if ($search[$key] == '-1') $search[$key] = ''; + if ($search[$key] == '-1') { + $search[$key] = ''; + } $mode_search = 2; } - if ($search[$key] != '') $sql .= natural_search((($key == 'ref') ? 't.ref' : 't.'.$class_key), $search[$key], (($key == 'status') ? 2 : $mode_search)); + if ($search[$key] != '') { + $sql .= natural_search((($key == 'ref') ? 't.ref' : 't.'.$class_key), $search[$key], (($key == 'status') ? 2 : $mode_search)); + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -238,13 +258,14 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; $sql .= " GROUP BY "; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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.', ' : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : ''); + } } // Add where from hooks $parameters = array(); @@ -253,13 +274,11 @@ $sql .= $hookmanager->resPrint; $sql = preg_replace('/,\s*$/', '', $sql); $totalnboflines = 0; $result = $db->query($sql); -if ($result) -{ +if ($result) { $totalnboflines = $db->num_rows($result); // fetch totals $line = $total = $totalsell = $totalStock = 0; - while ($line < $totalnboflines) - { + while ($line < $totalnboflines) { $objp = $db->fetch_object($result); $total += price2num($objp->estimatedvalue, 'MU'); $totalsell += price2num($objp->sellvalue, 'MU'); @@ -274,26 +293,22 @@ $sql .= $db->order($sortfield, $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; } @@ -302,8 +317,7 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/product/stock/card.php?id='.$id); @@ -319,14 +333,24 @@ llxHeader('', $title, $help_url); $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ - if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); - else $param .= '&search_'.$key.'='.urlencode($search[$key]); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +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'; @@ -336,12 +360,18 @@ $arrayofmassactions = array( //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete','preaffecttag'))) $arrayofmassactions = array(); -if ($user->rights->stock->creer) $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete','preaffecttag'))) { + $arrayofmassactions = array(); +} +if ($user->rights->stock->creer) { + $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form action="'.$_SERVER["PHP_SELF"].'" id="searchFormList" method="POST" name="formulaire">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -361,16 +391,16 @@ $trackid = 'ware'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } $moreforfilter = ''; -if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) -{ +if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { $formcategory = new FormCategory($db); $moreforfilter .= $formcategory->getFilterBox(Categorie::TYPE_WAREHOUSE, $search_category_list); } @@ -381,11 +411,13 @@ if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -402,21 +434,29 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit // -------------------------------------------------------------------- print '<tr class="liste_titre_filter">'; -foreach ($object->fields as $key => $val) -{ - if ($key == 'statut') { continue; } +foreach ($object->fields as $key => $val) { + if ($key == 'statut') { + continue; + } $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - elseif (strpos($val['type'], 'integer:') === 0 || strpos($val['type'], 'sellist:') === 0) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif (strpos($val['type'], 'integer:') === 0 || strpos($val['type'], 'sellist:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { + print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } print '</td>'; } } @@ -459,16 +499,21 @@ print '</tr>'."\n"; // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ - if ($key == 'statut') { continue; } +foreach ($object->fields as $key => $val) { + if ($key == 'statut') { + continue; + } $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -504,14 +549,14 @@ print '</tr>'."\n"; // Loop on record // -------------------------------------------------------------------- $i = 0; -if ($num) -{ +if ($num) { $warehouse = new Entrepot($db); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } $warehouse->id = $obj->rowid; $warehouse->ref = $obj->ref; @@ -527,22 +572,32 @@ if ($num) // Show here line of result print '<tr class="oddeven">'; - foreach ($warehouse->fields as $key => $val) - { - if ($key == 'statut') { continue; } + foreach ($warehouse->fields as $key => $val) { + if ($key == 'statut') { + continue; + } $cssforfield = (empty($val['css']) ? '' : $val['css']); - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>'; - if ($key == 'statut') print $warehouse->getLibStatut(5); + if ($key == 'statut') { + print $warehouse->getLibStatut(5); + } if ($key == 'phone') { print dol_print_phone($obj->phone, '', 0, $obj->rowid, 'AC_TEL'); } elseif ($key == 'fax') { @@ -551,10 +606,13 @@ if ($num) print $warehouse->showOutputField($val, $key, $warehouse->$key, ''); } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $warehouse->$key; } } @@ -563,31 +621,47 @@ if ($num) // Stock qty if (!empty($arrayfields["stockqty"]['checked'])) { print '<td class="right">'.price2num($obj->stockqty, 5).'</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'stockqty'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'stockqty'; + } } // PMP value if (!empty($arrayfields["estimatedvalue"]['checked'])) { print '<td class="right">'; - if (price2num($obj->estimatedvalue, 'MT')) print price(price2num($obj->estimatedvalue, 'MT'), 1); - else print ''; + if (price2num($obj->estimatedvalue, 'MT')) { + print price(price2num($obj->estimatedvalue, 'MT'), 1); + } else { + print ''; + } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'estimatedvalue'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'estimatedvalue'; + } } // Selling value if (!empty($arrayfields["estimatedstockvaluesell"]['checked'])) { print '<td class="right">'; - if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($obj->sellvalue, 'MT'), 1); - else { + if (empty($conf->global->PRODUIT_MULTIPRICES)) { + print price(price2num($obj->sellvalue, 'MT'), 1); + } else { $htmltext = $langs->trans("OptionMULTIPRICESIsOn"); print $form->textwithtooltip($langs->trans("Variable"), $htmltext); } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'estimatedstockvaluesell'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'estimatedstockvaluesell'; + } } // Extra fields @@ -600,19 +674,24 @@ if ($num) // Status if (!empty($arrayfields['t.statut']['checked'])) { print '<td class="center">'.$warehouse->LibStatut($obj->statut, 5).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'."\n"; @@ -620,8 +699,7 @@ if ($num) $i++; } - if ($totalnboflines - $offset <= $limit) - { + if ($totalnboflines - $offset <= $limit) { // Show total line include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; } @@ -638,10 +716,11 @@ print '</div>'."\n"; print '</form>'."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/product/stock/massstockmove.php b/htdocs/product/stock/massstockmove.php index 4e35d3832e5..830e8aa56e9 100644 --- a/htdocs/product/stock/massstockmove.php +++ b/htdocs/product/stock/massstockmove.php @@ -56,7 +56,9 @@ $idline = GETPOST('idline'); $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 if (!$sortfield) { $sortfield = 'p.ref'; @@ -69,51 +71,44 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; $listofdata = array(); -if (!empty($_SESSION['massstockmove'])) $listofdata = json_decode($_SESSION['massstockmove'], true); +if (!empty($_SESSION['massstockmove'])) { + $listofdata = json_decode($_SESSION['massstockmove'], true); +} /* * Actions */ -if ($action == 'addline') -{ - if (!($id_product > 0)) - { +if ($action == 'addline') { + if (!($id_product > 0)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); } - if (!($id_sw > 0)) - { + if (!($id_sw > 0)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseSource")), null, 'errors'); } - if (!($id_tw > 0)) - { + if (!($id_tw > 0)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseTarget")), null, 'errors'); } - if ($id_sw > 0 && $id_tw == $id_sw) - { + if ($id_sw > 0 && $id_tw == $id_sw) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorWarehouseMustDiffers"), null, 'errors'); } - if (!$qty) - { + if (!$qty) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); } // Check a batch number is provided if product need it - if (!$error) - { + if (!$error) { $producttmp = new Product($db); $producttmp->fetch($id_product); - if ($producttmp->hasbatch()) - { - if (empty($batch)) - { + if ($producttmp->hasbatch()) { + if (empty($batch)) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorTryToMakeMoveOnProductRequiringBatchData", $producttmp->ref), null, 'errors'); @@ -123,19 +118,19 @@ if ($action == 'addline') // TODO Check qty is ok for stock move. Note qty may not be enough yet, but we make a check now to report a warning. // What is more important is to have qty when doing action 'createmovements' - if (!$error) - { + if (!$error) { // Warning, don't forget lines already added into the $_SESSION['massstockmove'] - if ($producttmp->hasbatch()) - { + if ($producttmp->hasbatch()) { } else { } } - if (!$error) - { - if (count(array_keys($listofdata)) > 0) $id = max(array_keys($listofdata)) + 1; - else $id = 1; + if (!$error) { + if (count(array_keys($listofdata)) > 0) { + $id = max(array_keys($listofdata)) + 1; + } else { + $id = 1; + } $listofdata[$id] = array('id'=>$id, 'id_product'=>$id_product, 'qty'=>$qty, 'id_sw'=>$id_sw, 'id_tw'=>$id_tw, 'batch'=>$batch); $_SESSION['massstockmove'] = json_encode($listofdata); @@ -147,31 +142,31 @@ if ($action == 'addline') } } -if ($action == 'delline' && $idline != '') -{ - if (!empty($listofdata[$idline])) unset($listofdata[$idline]); - if (count($listofdata) > 0) $_SESSION['massstockmove'] = json_encode($listofdata); - else unset($_SESSION['massstockmove']); +if ($action == 'delline' && $idline != '') { + if (!empty($listofdata[$idline])) { + unset($listofdata[$idline]); + } + if (count($listofdata) > 0) { + $_SESSION['massstockmove'] = json_encode($listofdata); + } else { + unset($_SESSION['massstockmove']); + } } -if ($action == 'createmovements') -{ +if ($action == 'createmovements') { $error = 0; - if (!GETPOST("label")) - { + if (!GETPOST("label")) { $error++; setEventMessages($langs->trans("ErrorFieldRequired"), $langs->transnoentitiesnoconv("MovementLabel"), null, 'errors'); } $db->begin(); - if (!$error) - { + if (!$error) { $product = new Product($db); - foreach ($listofdata as $key => $val) // Loop on each movement to do - { + foreach ($listofdata as $key => $val) { // Loop on each movement to do $id = $val['id']; $id_product = $val['id_product']; $id_sw = $val['id_sw']; @@ -181,21 +176,21 @@ if ($action == 'createmovements') $dlc = -1; // They are loaded later from serial $dluo = -1; // They are loaded later from serial - if (!$error && $id_sw <> $id_tw && is_numeric($qty) && $id_product) - { + if (!$error && $id_sw <> $id_tw && is_numeric($qty) && $id_product) { $result = $product->fetch($id_product); $product->load_stock('novirtual'); // Load array product->stock_warehouse // Define value of products moved $pricesrc = 0; - if (!empty($product->pmp)) $pricesrc = $product->pmp; + if (!empty($product->pmp)) { + $pricesrc = $product->pmp; + } $pricedest = $pricesrc; //print 'price src='.$pricesrc.', price dest='.$pricedest;exit; - if (empty($conf->productbatch->enabled) || !$product->hasbatch()) // If product does not need lot/serial - { + if (empty($conf->productbatch->enabled) || !$product->hasbatch()) { // If product does not need lot/serial // Remove stock $result1 = $product->correct_stock( $user, @@ -206,8 +201,7 @@ if ($action == 'createmovements') $pricesrc, GETPOST("codemove") ); - if ($result1 < 0) - { + if ($result1 < 0) { $error++; setEventMessages($product->errors, $product->errorss, 'errors'); } @@ -222,15 +216,13 @@ if ($action == 'createmovements') $pricedest, GETPOST("codemove") ); - if ($result2 < 0) - { + if ($result2 < 0) { $error++; setEventMessages($product->errors, $product->errorss, 'errors'); } } else { $arraybatchinfo = $product->loadBatchInfo($batch); - if (count($arraybatchinfo) > 0) - { + if (count($arraybatchinfo) > 0) { $firstrecord = array_shift($arraybatchinfo); $dlc = $firstrecord['eatby']; $dluo = $firstrecord['sellby']; @@ -253,8 +245,7 @@ if ($action == 'createmovements') $batch, GETPOST("codemove") ); - if ($result1 < 0) - { + if ($result1 < 0) { $error++; setEventMessages($product->errors, $product->errorss, 'errors'); } @@ -272,8 +263,7 @@ if ($action == 'createmovements') $batch, GETPOST("codemove") ); - if ($result2 < 0) - { + if ($result2 < 0) { $error++; setEventMessages($product->errors, $product->errorss, 'errors'); } @@ -285,8 +275,7 @@ if ($action == 'createmovements') } } - if (!$error) - { + if (!$error) { unset($_SESSION['massstockmove']); $db->commit(); @@ -313,9 +302,11 @@ $productstatic = new Product($db); $warehousestatics = new Entrepot($db); $warehousestatict = new Entrepot($db); +$help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks|DE:Modul_Bestände'; + $title = $langs->trans('MassMovement'); -llxHeader('', $title); +llxHeader('', $title, $help_url); print load_fiche_titre($langs->trans("MassStockTransferShort"), '', 'stock'); @@ -362,7 +353,9 @@ print '</td>'; // Product print '<td class="titlefield">'; $filtertype = 0; -if (!empty($conf->global->STOCK_SUPPORTS_SERVICES)) $filtertype = ''; +if (!empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $filtertype = ''; +} if ($conf->global->PRODUIT_LIMIT_SIZE <= 0) { $limit = ''; } else { @@ -372,8 +365,7 @@ if ($conf->global->PRODUIT_LIMIT_SIZE <= 0) { $form->select_produits($id_product, 'productid', $filtertype, $limit, 0, -1, 2, '', 1, array(), 0, '1', 0, 'minwidth200imp maxwidth300', 1); print '</td>'; // Batch number -if ($conf->productbatch->enabled) -{ +if ($conf->productbatch->enabled) { print '<td>'; print '<input type="text" name="batch" class="flat maxwidth50" value="'.$batch.'">'; print '</td>'; @@ -386,8 +378,7 @@ print '<td class="right"><input type="submit" class="button" name="addline" valu print '</tr>'; -foreach ($listofdata as $key => $val) -{ +foreach ($listofdata as $key => $val) { $productstatic->fetch($val['id_product']); $warehousestatics->fetch($val['id_sw']); $warehousestatict->fetch($val['id_tw']); @@ -402,8 +393,7 @@ foreach ($listofdata as $key => $val) print '<td>'; print $productstatic->getNomUrl(1).' - '.$productstatic->label; print '</td>'; - if ($conf->productbatch->enabled) - { + if ($conf->productbatch->enabled) { print '<td>'; print $val['batch']; print '</td>'; diff --git a/htdocs/product/stock/movement_card.php b/htdocs/product/stock/movement_card.php index cf3cc67bdc2..6dc3c665e15 100644 --- a/htdocs/product/stock/movement_card.php +++ b/htdocs/product/stock/movement_card.php @@ -44,7 +44,9 @@ if (!empty($conf->projet->enabled)) { // Load translation files required by the page $langs->loadLangs(array('products', 'stocks', 'orders')); -if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); +if (!empty($conf->productbatch->enabled)) { + $langs->load("productbatch"); +} // Security check $result = restrictedArea($user, 'stock'); @@ -75,10 +77,16 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -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; -if (!$sortfield) $sortfield = "m.datem"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "m.datem"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} $pdluoid = GETPOST('pdluoid', 'int'); @@ -123,18 +131,23 @@ $usercandelete = (($user->rights->stock->mouvement->supprimer)); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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'); +} include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $year = ''; $month = ''; $search_ref = ''; @@ -153,39 +166,35 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' } // Correct stock -if ($action == "correct_stock") -{ +if ($action == "correct_stock") { $product = new Product($db); - if (!empty($product_id)) $result = $product->fetch($product_id); + if (!empty($product_id)) { + $result = $product->fetch($product_id); + } $error = 0; - if (empty($product_id)) - { + if (empty($product_id)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); $action = 'correction'; } - if (!is_numeric($_POST["nbpiece"])) - { + if (!is_numeric($_POST["nbpiece"])) { $error++; setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); $action = 'correction'; } - if (!$error) - { + if (!$error) { $origin_element = ''; $origin_id = null; - if (GETPOST('projectid', 'int')) - { + if (GETPOST('projectid', 'int')) { $origin_element = 'project'; $origin_id = GETPOST('projectid', 'int'); } - if ($product->hasbatch()) - { + if ($product->hasbatch()) { $batch = GETPOST('batch_number', 'alpha'); //$eatby=GETPOST('eatby'); @@ -221,8 +230,7 @@ if ($action == "correct_stock") ); // We do not change value of stock for a correction } - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { @@ -232,57 +240,52 @@ if ($action == "correct_stock") } } - if (!$error) $action = ''; + if (!$error) { + $action = ''; + } } // Transfer stock from a warehouse to another warehouse -if ($action == "transfert_stock" && !$cancel) -{ +if ($action == "transfert_stock" && !$cancel) { $product = new Product($db); - if (!empty($product_id)) $result = $product->fetch($product_id); + if (!empty($product_id)) { + $result = $product->fetch($product_id); + } - if (!(GETPOST("id_entrepot_destination", 'int') > 0)) - { + if (!(GETPOST("id_entrepot_destination", 'int') > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $error++; $action = 'transfert'; } - if (empty($product_id)) - { + if (empty($product_id)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); $action = 'transfert'; } - if (!GETPOST("nbpiece", 'int')) - { + if (!GETPOST("nbpiece", 'int')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); $error++; $action = 'transfert'; } - if ($id == GETPOST("id_entrepot_destination", 'int')) - { + if ($id == GETPOST("id_entrepot_destination", 'int')) { setEventMessages($langs->trans("ErrorSrcAndTargetWarehouseMustDiffers"), null, 'errors'); $error++; $action = 'transfert'; } - if (!empty($conf->productbatch->enabled)) - { + if (!empty($conf->productbatch->enabled)) { $product = new Product($db); $result = $product->fetch($product_id); - if ($product->hasbatch() && !GETPOST("batch_number", 'alpha')) - { + if ($product->hasbatch() && !GETPOST("batch_number", 'alpha')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); $error++; $action = 'transfert'; } } - if (!$error) - { - if ($id) - { + if (!$error) { + if ($id) { $object = new Entrepot($db); $result = $object->fetch($id); @@ -292,18 +295,17 @@ if ($action == "transfert_stock" && !$cancel) // Define value of products moved $pricesrc = 0; - if (isset($product->pmp)) $pricesrc = $product->pmp; + if (isset($product->pmp)) { + $pricesrc = $product->pmp; + } $pricedest = $pricesrc; - if ($product->hasbatch()) - { + if ($product->hasbatch()) { $pdluo = new Productbatch($db); - if ($pdluoid > 0) - { + if ($pdluoid > 0) { $result = $pdluo->fetch($pdluoid); - if ($result) - { + if ($result) { $srcwarehouseid = $pdluo->warehouseid; $batch = $pdluo->batch; $eatby = $pdluo->eatby; @@ -319,8 +321,7 @@ if ($action == "transfert_stock" && !$cancel) $sellby = $d_sellby; } - if (!$error) - { + if (!$error) { // Remove stock $result1 = $product->correct_stock_batch( $user, @@ -371,12 +372,10 @@ if ($action == "transfert_stock" && !$cancel) GETPOST('inventorycode', 'alpha') ); } - if (!$error && $result1 >= 0 && $result2 >= 0) - { + if (!$error && $result1 >= 0 && $result2 >= 0) { $db->commit(); - if ($backtopage) - { + if ($backtopage) { header("Location: ".$backtopage); exit; } else { @@ -403,8 +402,7 @@ $permissiontoadd = $user->rights->stock->creer; include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; -if (empty($reshook) && $action != 'remove_file') -{ +if (empty($reshook) && $action != 'remove_file') { $objectclass = 'MouvementStock'; $objectlabel = 'Movements'; $permissiontoread = $user->rights->stock->lire; @@ -427,7 +425,9 @@ $userstatic = new User($db); $form = new Form($db); $formother = new FormOther($db); $formproduct = new FormProduct($db); -if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $sql = "SELECT p.rowid, p.ref as product_ref, p.label as produit, p.tobatch, p.fk_product_type as type, p.entity,"; $sql .= " e.ref as warehouse_ref, e.rowid as entrepot_id, e.lieu,"; @@ -438,7 +438,9 @@ $sql .= " pl.rowid as lotid, pl.eatby, pl.sellby,"; $sql .= " u.login, u.photo, u.lastname, u.firstname"; // 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 : ''); + 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(); @@ -447,27 +449,57 @@ $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,"; $sql .= " ".MAIN_DB_PREFIX."product as p,"; $sql .= " ".MAIN_DB_PREFIX."stock_mouvement as m"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (m.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (m.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON m.fk_user_author = u.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON m.batch = pl.batch AND m.fk_product = pl.fk_product"; $sql .= " WHERE m.fk_product = p.rowid"; -if ($msid > 0) $sql .= " AND m.rowid = ".$msid; +if ($msid > 0) { + $sql .= " AND m.rowid = ".$msid; +} $sql .= " AND m.fk_entrepot = e.rowid"; $sql .= " AND e.entity IN (".getEntity('stock').")"; -if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= " AND p.fk_product_type = 0"; -if ($id > 0) $sql .= " AND e.rowid ='".$id."'"; +if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $sql .= " AND p.fk_product_type = 0"; +} +if ($id > 0) { + $sql .= " AND e.rowid ='".$id."'"; +} $sql .= dolSqlDateFilter('m.datem', 0, $month, $year); -if ($idproduct > 0) $sql .= " AND p.rowid = ".((int) $idproduct); -if (!empty($search_ref)) $sql .= natural_search('m.rowid', $search_ref, 1); -if (!empty($search_movement)) $sql .= natural_search('m.label', $search_movement); -if (!empty($search_inventorycode)) $sql .= natural_search('m.inventorycode', $search_inventorycode); -if (!empty($search_product_ref)) $sql .= natural_search('p.ref', $search_product_ref); -if (!empty($search_product)) $sql .= natural_search('p.label', $search_product); -if ($search_warehouse != '' && $search_warehouse != '-1') $sql .= natural_search('e.rowid', $search_warehouse, 2); -if (!empty($search_user)) $sql .= natural_search('u.login', $search_user); -if (!empty($search_batch)) $sql .= natural_search('m.batch', $search_batch); -if ($search_qty != '') $sql .= natural_search('m.value', $search_qty, 1); -if ($search_type_mouvement != '' && $search_type_mouvement != '-1') $sql .= natural_search('m.type_mouvement', $search_type_mouvement, 2); +if ($idproduct > 0) { + $sql .= " AND p.rowid = ".((int) $idproduct); +} +if (!empty($search_ref)) { + $sql .= natural_search('m.rowid', $search_ref, 1); +} +if (!empty($search_movement)) { + $sql .= natural_search('m.label', $search_movement); +} +if (!empty($search_inventorycode)) { + $sql .= natural_search('m.inventorycode', $search_inventorycode); +} +if (!empty($search_product_ref)) { + $sql .= natural_search('p.ref', $search_product_ref); +} +if (!empty($search_product)) { + $sql .= natural_search('p.label', $search_product); +} +if ($search_warehouse != '' && $search_warehouse != '-1') { + $sql .= natural_search('e.rowid', $search_warehouse, 2); +} +if (!empty($search_user)) { + $sql .= natural_search('u.login', $search_user); +} +if (!empty($search_batch)) { + $sql .= natural_search('m.batch', $search_batch); +} +if ($search_qty != '') { + $sql .= natural_search('m.value', $search_qty, 1); +} +if ($search_type_mouvement != '' && $search_type_mouvement != '-1') { + $sql .= natural_search('m.type_mouvement', $search_type_mouvement, 2); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -477,12 +509,10 @@ $sql .= $hookmanager->resPrint; $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -492,20 +522,16 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $product = new Product($db); $object = new Entrepot($db); - if ($idproduct > 0) - { + if ($idproduct > 0) { $product->fetch($idproduct); } - if ($id > 0 || $ref) - { + if ($id > 0 || $ref) { $result = $object->fetch($id, $ref); - if ($result < 0) - { + if ($result < 0) { dol_print_error($db); } } @@ -517,18 +543,20 @@ if ($resql) $i = 0; $help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks'; - if ($msid) $texte = $langs->trans('StockMovementForId', $msid); - else { + if ($msid) { + $texte = $langs->trans('StockMovementForId', $msid); + } else { $texte = $langs->trans("ListOfStockMovements"); - if ($id) $texte .= ' ('.$langs->trans("ForThisWarehouse").')'; + if ($id) { + $texte .= ' ('.$langs->trans("ForThisWarehouse").')'; + } } llxHeader("", $texte, $help_url); /* - * Show tab only if we ask a particular warehouse - */ - if ($object->id > 0) - { + * Show tab only if we ask a particular warehouse + */ + if ($object->id > 0) { $head = stock_prepare_head($object); print dol_get_fiche_head($head, 'movements', $langs->trans("Warehouse"), -1, 'stock'); @@ -541,7 +569,9 @@ if ($resql) $morehtmlref .= '</div>'; $shownav = 1; - if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref); @@ -590,8 +620,7 @@ if ($resql) $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as m"; $sql .= " WHERE m.fk_entrepot = ".(int) $object->id; $resqlbis = $db->query($sql); - if ($resqlbis) - { + if ($resqlbis) { $obj = $db->fetch_object($resqlbis); $lastmovementdate = $db->jdate($obj->datem); } else { @@ -599,8 +628,7 @@ if ($resql) } print '<tr><td>'.$langs->trans("LastMovement").'</td><td>'; - if ($lastmovementdate) - { + if ($lastmovementdate) { print dol_print_date($lastmovementdate, 'dayhour'); } else { print $langs->trans("None"); @@ -622,8 +650,7 @@ if ($resql) /* * Correct stock */ - if ($action == "correction") - { + if ($action == "correction") { include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stockcorrection.tpl.php'; print '<br>'; } @@ -631,30 +658,23 @@ if ($resql) /* * Transfer of units */ - if ($action == "transfert") - { + if ($action == "transfert") { include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stocktransfer.tpl.php'; print '<br>'; } - /* ************************************************************************** */ - /* */ - /* Barre d'action */ - /* */ - /* ************************************************************************** */ - - if ((empty($action) || $action == 'list') && $id > 0) - { + /* + * Action bar + */ + if ((empty($action) || $action == 'list') && $id > 0) { print "<div class=\"tabsAction\">\n"; - if ($user->rights->stock->mouvement->creer) - { + if ($user->rights->stock->mouvement->creer) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=correction">'.$langs->trans("CorrectStock").'</a>'; } - if ($user->rights->stock->mouvement->creer) - { + if ($user->rights->stock->mouvement->creer) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=transfert">'.$langs->trans("TransferStock").'</a>'; } @@ -662,18 +682,42 @@ if ($resql) } $param = ''; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($id > 0) $param .= '&id='.urlencode($id); - if ($search_movement) $param .= '&search_movement='.urlencode($search_movement); - if ($search_inventorycode) $param .= '&search_inventorycode='.urlencode($search_inventorycode); - if ($search_type_mouvement) $param .= '&search_type_mouvement='.urlencode($search_type_mouvement); - if ($search_product_ref) $param .= '&search_product_ref='.urlencode($search_product_ref); - if ($search_product) $param .= '&search_product='.urlencode($search_product); - if ($search_batch) $param .= '&search_batch='.urlencode($search_batch); - if ($search_warehouse > 0) $param .= '&search_warehouse='.urlencode($search_warehouse); - if ($search_user) $param .= '&search_user='.urlencode($search_user); - if ($idproduct > 0) $param .= '&idproduct='.urlencode($idproduct); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($id > 0) { + $param .= '&id='.urlencode($id); + } + if ($search_movement) { + $param .= '&search_movement='.urlencode($search_movement); + } + if ($search_inventorycode) { + $param .= '&search_inventorycode='.urlencode($search_inventorycode); + } + if ($search_type_mouvement) { + $param .= '&search_type_mouvement='.urlencode($search_type_mouvement); + } + if ($search_product_ref) { + $param .= '&search_product_ref='.urlencode($search_product_ref); + } + if ($search_product) { + $param .= '&search_product='.urlencode($search_product); + } + if ($search_batch) { + $param .= '&search_batch='.urlencode($search_batch); + } + if ($search_warehouse > 0) { + $param .= '&search_warehouse='.urlencode($search_warehouse); + } + if ($search_user) { + $param .= '&search_user='.urlencode($search_user); + } + if ($idproduct > 0) { + $param .= '&idproduct='.urlencode($idproduct); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -683,11 +727,15 @@ if ($resql) // 'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$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); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -695,14 +743,20 @@ if ($resql) print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="page" value="'.$page.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; - if ($id > 0) print '<input type="hidden" name="id" value="'.$id.'">'; + if ($id > 0) { + print '<input type="hidden" name="id" value="'.$id.'">'; + } - if ($id > 0) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit); - else print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, '', '', $limit); + if ($id > 0) { + print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit); + } else { + print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, '', '', $limit); + } - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } @@ -710,11 +764,13 @@ if ($resql) $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)) - { + if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -728,84 +784,74 @@ if ($resql) // Fields title search print '<tr class="liste_titre_filter">'; - if (!empty($arrayfields['m.rowid']['checked'])) - { + if (!empty($arrayfields['m.rowid']['checked'])) { // Ref print '<td class="liste_titre left">'; print '<input class="flat maxwidth25" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; print '</td>'; } - if (!empty($arrayfields['m.datem']['checked'])) - { + if (!empty($arrayfields['m.datem']['checked'])) { print '<td class="liste_titre nowraponall">'; print '<input class="flat" type="text" size="2" maxlength="2" placeholder="'.dol_escape_htmltag($langs->trans("Month")).'" name="month" value="'.$month.'">'; - if (empty($conf->productbatch->enabled)) print '&nbsp;'; + if (empty($conf->productbatch->enabled)) { + print '&nbsp;'; + } //else print '<br>'; $syear = $year ? $year : -1; print '<input class="flat maxwidth50" type="text" maxlength="4" placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" name="year" value="'.($syear > 0 ? $syear : '').'">'; //print $formother->selectyear($syear,'year',1, 20, 5); print '</td>'; } - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { // Product Ref print '<td class="liste_titre left">'; print '<input class="flat maxwidth75" type="text" name="search_product_ref" value="'.dol_escape_htmltag($idproduct ? $product->ref : $search_product_ref).'">'; print '</td>'; } - if (!empty($arrayfields['p.label']['checked'])) - { + if (!empty($arrayfields['p.label']['checked'])) { // Product label print '<td class="liste_titre left">'; print '<input class="flat maxwidth100" type="text" name="search_product" value="'.dol_escape_htmltag($idproduct ? $product->label : $search_product).'">'; print '</td>'; } // Batch - if (!empty($arrayfields['m.batch']['checked'])) - { + if (!empty($arrayfields['m.batch']['checked'])) { print '<td class="liste_titre center"><input class="flat maxwidth75" type="text" name="search_batch" value="'.dol_escape_htmltag($search_batch).'"></td>'; } - if (!empty($arrayfields['pl.eatby']['checked'])) - { + if (!empty($arrayfields['pl.eatby']['checked'])) { print '<td class="liste_titre left">'; print '</td>'; } - if (!empty($arrayfields['pl.sellby']['checked'])) - { + if (!empty($arrayfields['pl.sellby']['checked'])) { print '<td class="liste_titre left">'; print '</td>'; } // Warehouse - if (!empty($arrayfields['e.ref']['checked'])) - { + if (!empty($arrayfields['e.ref']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone left">'; //print '<input class="flat" type="text" size="8" name="search_warehouse" value="'.($search_warehouse).'">'; print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print '</td>'; } - if (!empty($arrayfields['m.fk_user_author']['checked'])) - { + if (!empty($arrayfields['m.fk_user_author']['checked'])) { // Author print '<td class="liste_titre left">'; print '<input class="flat" type="text" size="6" name="search_user" value="'.dol_escape_htmltag($search_user).'">'; print '</td>'; } - if (!empty($arrayfields['m.inventorycode']['checked'])) - { + if (!empty($arrayfields['m.inventorycode']['checked'])) { // Inventory code print '<td class="liste_titre left">'; print '<input class="flat" type="text" size="4" name="search_inventorycode" value="'.dol_escape_htmltag($search_inventorycode).'">'; print '</td>'; } - if (!empty($arrayfields['m.label']['checked'])) - { + if (!empty($arrayfields['m.label']['checked'])) { // Label of movement print '<td class="liste_titre left">'; print '<input class="flat" type="text" size="8" name="search_movement" value="'.dol_escape_htmltag($search_movement).'">'; print '</td>'; } - if (!empty($arrayfields['m.type_mouvement']['checked'])) - { + if (!empty($arrayfields['m.type_mouvement']['checked'])) { // Type of movement print '<td class="liste_titre center">'; //print '<input class="flat" type="text" size="3" name="search_type_mouvement" value="'.dol_escape_htmltag($search_type_mouvement).'">'; @@ -821,22 +867,19 @@ if ($resql) // print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print '</td>'; } - if (!empty($arrayfields['origin']['checked'])) - { + if (!empty($arrayfields['origin']['checked'])) { // Origin of movement print '<td class="liste_titre left">'; print '&nbsp; '; print '</td>'; } - if (!empty($arrayfields['m.value']['checked'])) - { + if (!empty($arrayfields['m.value']['checked'])) { // Qty print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_qty" value="'.dol_escape_htmltag($search_qty).'">'; print '</td>'; } - if (!empty($arrayfields['m.price']['checked'])) - { + if (!empty($arrayfields['m.price']['checked'])) { // Price print '<td class="liste_titre left">'; print '&nbsp; '; @@ -852,14 +895,12 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['m.datec']['checked'])) - { + if (!empty($arrayfields['m.datec']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Date modification - if (!empty($arrayfields['m.tms']['checked'])) - { + if (!empty($arrayfields['m.tms']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } @@ -871,38 +912,52 @@ if ($resql) print "</tr>\n"; print '<tr class="liste_titre">'; - if (!empty($arrayfields['m.rowid']['checked'])) + if (!empty($arrayfields['m.rowid']['checked'])) { print_liste_field_titre($arrayfields['m.rowid']['label'], $_SERVER["PHP_SELF"], 'm.rowid', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['m.datem']['checked'])) + } + if (!empty($arrayfields['m.datem']['checked'])) { print_liste_field_titre($arrayfields['m.datem']['label'], $_SERVER["PHP_SELF"], 'm.datem', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.ref']['checked'])) + } + if (!empty($arrayfields['p.ref']['checked'])) { print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], 'p.ref', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.label']['checked'])) + } + if (!empty($arrayfields['p.label']['checked'])) { print_liste_field_titre($arrayfields['p.label']['label'], $_SERVER["PHP_SELF"], 'p.label', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['m.batch']['checked'])) + } + if (!empty($arrayfields['m.batch']['checked'])) { print_liste_field_titre($arrayfields['m.batch']['label'], $_SERVER["PHP_SELF"], 'm.batch', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['pl.eatby']['checked'])) + } + if (!empty($arrayfields['pl.eatby']['checked'])) { print_liste_field_titre($arrayfields['pl.eatby']['label'], $_SERVER["PHP_SELF"], 'pl.eatby', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['pl.sellby']['checked'])) + } + if (!empty($arrayfields['pl.sellby']['checked'])) { print_liste_field_titre($arrayfields['pl.sellby']['label'], $_SERVER["PHP_SELF"], 'pl.sellby', '', $param, '', $sortfield, $sortorder, 'center '); + } if (!empty($arrayfields['e.ref']['checked'])) { // We are on a specific warehouse card, no filter on other should be possible print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, "", $sortfield, $sortorder); } - if (!empty($arrayfields['m.fk_user_author']['checked'])) + if (!empty($arrayfields['m.fk_user_author']['checked'])) { print_liste_field_titre($arrayfields['m.fk_user_author']['label'], $_SERVER["PHP_SELF"], "m.fk_user_author", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['m.inventorycode']['checked'])) + } + if (!empty($arrayfields['m.inventorycode']['checked'])) { print_liste_field_titre($arrayfields['m.inventorycode']['label'], $_SERVER["PHP_SELF"], "m.inventorycode", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['m.label']['checked'])) + } + if (!empty($arrayfields['m.label']['checked'])) { print_liste_field_titre($arrayfields['m.label']['label'], $_SERVER["PHP_SELF"], "m.label", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['m.type_mouvement']['checked'])) + } + if (!empty($arrayfields['m.type_mouvement']['checked'])) { print_liste_field_titre($arrayfields['m.type_mouvement']['label'], $_SERVER["PHP_SELF"], "m.type_mouvement", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['origin']['checked'])) + } + if (!empty($arrayfields['origin']['checked'])) { print_liste_field_titre($arrayfields['origin']['label'], $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['m.value']['checked'])) + } + if (!empty($arrayfields['m.value']['checked'])) { print_liste_field_titre($arrayfields['m.value']['label'], $_SERVER["PHP_SELF"], "m.value", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['m.price']['checked'])) + } + if (!empty($arrayfields['m.price']['checked'])) { print_liste_field_titre($arrayfields['m.price']['label'], $_SERVER["PHP_SELF"], "m.price", "", $param, '', $sortfield, $sortorder, 'right '); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; @@ -956,65 +1011,58 @@ if ($resql) print '<tr class="oddeven">'; // Id movement - if (!empty($arrayfields['m.rowid']['checked'])) - { + if (!empty($arrayfields['m.rowid']['checked'])) { // This is primary not movement id print '<td>'.$objp->mid.'</td>'; } - if (!empty($arrayfields['m.datem']['checked'])) - { + if (!empty($arrayfields['m.datem']['checked'])) { // Date print '<td>'.dol_print_date($db->jdate($objp->datem), 'dayhour').'</td>'; } - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { // Product ref print '<td class="nowraponall">'; print $productstatic->getNomUrl(1, 'stock', 16); print "</td>\n"; } - if (!empty($arrayfields['p.label']['checked'])) - { + if (!empty($arrayfields['p.label']['checked'])) { // Product label print '<td>'; /*$productstatic->id=$objp->rowid; - $productstatic->ref=$objp->produit; - $productstatic->type=$objp->type; - print $productstatic->getNomUrl(1,'',16);*/ + $productstatic->ref=$objp->produit; + $productstatic->type=$objp->type; + print $productstatic->getNomUrl(1,'',16);*/ print $productstatic->label; print "</td>\n"; } - if (!empty($arrayfields['m.batch']['checked'])) - { + if (!empty($arrayfields['m.batch']['checked'])) { print '<td class="center nowraponall">'; - if ($productlot->id > 0) print $productlot->getNomUrl(1); - else print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. + if ($productlot->id > 0) { + print $productlot->getNomUrl(1); + } else { + print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. + } print '</td>'; } - if (!empty($arrayfields['pl.eatby']['checked'])) - { + if (!empty($arrayfields['pl.eatby']['checked'])) { print '<td class="center">'.dol_print_date($objp->eatby, 'day').'</td>'; } - if (!empty($arrayfields['pl.sellby']['checked'])) - { + if (!empty($arrayfields['pl.sellby']['checked'])) { print '<td class="center">'.dol_print_date($objp->sellby, 'day').'</td>'; } // Warehouse - if (!empty($arrayfields['e.ref']['checked'])) - { + if (!empty($arrayfields['e.ref']['checked'])) { print '<td>'; print $warehousestatic->getNomUrl(1); print "</td>\n"; } // Author - if (!empty($arrayfields['m.fk_user_author']['checked'])) - { + if (!empty($arrayfields['m.fk_user_author']['checked'])) { print '<td class="tdoverflowmax100">'; print $userstatic->getNomUrl(-1); print "</td>\n"; } - if (!empty($arrayfields['m.inventorycode']['checked'])) - { + if (!empty($arrayfields['m.inventorycode']['checked'])) { // Inventory code print '<td><a href="' .DOL_URL_ROOT.'/product/stock/movement_card.php?id='.urlencode($objp->entrepot_id) @@ -1024,13 +1072,11 @@ if ($resql) .$objp->inventorycode .'</a></td>'; } - if (!empty($arrayfields['m.label']['checked'])) - { + if (!empty($arrayfields['m.label']['checked'])) { // Label of movement print '<td class="tdoverflowmax100aaa">'.$objp->label.'</td>'; } - if (!empty($arrayfields['m.type_mouvement']['checked'])) - { + if (!empty($arrayfields['m.type_mouvement']['checked'])) { // Type of movement switch ($objp->type_mouvement) { case "0": @@ -1047,36 +1093,40 @@ if ($resql) break; } } - if (!empty($arrayfields['origin']['checked'])) - { + if (!empty($arrayfields['origin']['checked'])) { // Origin of movement print '<td class="nowraponall">'.$origin.'</td>'; } - if (!empty($arrayfields['m.value']['checked'])) - { + if (!empty($arrayfields['m.value']['checked'])) { // Qty print '<td class="right">'; - if ($objp->qt > 0) print '+'; + if ($objp->qt > 0) { + print '+'; + } print $objp->qty; print '</td>'; } - if (!empty($arrayfields['m.price']['checked'])) - { + if (!empty($arrayfields['m.price']['checked'])) { // Price print '<td class="right">'; - if ($objp->price != 0) print price($objp->price); + if ($objp->price != 0) { + print price($objp->price); + } print '</td>'; } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; $i++; @@ -1088,8 +1138,7 @@ if ($resql) print "</form>"; // Add number of product when there is a filter on period - if (count($arrayofuniqueproduct) == 1 && is_numeric($year)) - { + if (count($arrayofuniqueproduct) == 1 && is_numeric($year)) { print "<br>"; $productidselected = 0; @@ -1124,13 +1173,12 @@ if ($resql) /* - * Documents generes + * Generated documents */ //Area for doc and last events of warehouse are stored on the main card of warehouse $modulepart = 'movement'; -if ($action != 'create' && $action != 'edit' && $action != 'delete' && $id > 0) -{ +if ($action != 'create' && $action != 'edit' && $action != 'delete' && $id > 0) { print '<br/>'; print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre @@ -1138,8 +1186,12 @@ if ($action != 'create' && $action != 'edit' && $action != 'delete' && $id > 0) // Documents $objectref = dol_sanitizeFileName($object->ref); // Add inventorycode & type_mouvement to filename of the pdf - if (!empty($search_inventorycode)) $objectref .= "_".$id."_".$search_inventorycode; - if ($search_type_mouvement) $objectref .= "_".$search_type_mouvement; + if (!empty($search_inventorycode)) { + $objectref .= "_".$id."_".$search_inventorycode; + } + if ($search_type_mouvement) { + $objectref .= "_".$search_type_mouvement; + } $relativepath = $comref.'/'.$objectref.'.pdf'; $filedir = $conf->stock->dir_output.'/movement/'.$objectref; diff --git a/htdocs/product/stock/movement_list.php b/htdocs/product/stock/movement_list.php index 6ab8a99ac76..7c2e2df67e5 100644 --- a/htdocs/product/stock/movement_list.php +++ b/htdocs/product/stock/movement_list.php @@ -45,7 +45,9 @@ if (!empty($conf->projet->enabled)) { // Load translation files required by the page $langs->loadLangs(array('products', 'stocks', 'orders')); -if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); +if (!empty($conf->productbatch->enabled)) { + $langs->load("productbatch"); +} // Security check $result = restrictedArea($user, 'stock'); @@ -66,8 +68,14 @@ $toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected $result = restrictedArea($user, 'stock'); $idproduct = GETPOST('idproduct', 'int'); -$year = GETPOST("year"); -$month = GETPOST("month"); +$search_date_startday = GETPOST('search_date_startday', 'int'); +$search_date_startmonth = GETPOST('search_date_startmonth', 'int'); +$search_date_startyear = GETPOST('search_date_startyear', 'int'); +$search_date_endday = GETPOST('search_date_endday', 'int'); +$search_date_endmonth = GETPOST('search_date_endmonth', 'int'); +$search_date_endyear = GETPOST('search_date_endyear', 'int'); +$search_date_start = dol_mktime(0, 0, 0, GETPOST('search_date_startmonth', 'int'), GETPOST('search_date_startday', 'int'), GETPOST('search_date_startyear', 'int'), 'tzuserrel'); +$search_date_end = dol_mktime(23, 59, 59, GETPOST('search_date_endmonth', 'int'), GETPOST('search_date_endday', 'int'), GETPOST('search_date_endyear', 'int'), 'tzuserrel'); $search_ref = GETPOST('search_ref', 'alpha'); $search_movement = GETPOST("search_movement"); $search_product_ref = trim(GETPOST("search_product_ref")); @@ -83,10 +91,16 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -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; -if (!$sortfield) $sortfield = "m.datem"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "m.datem"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} $pdluoid = GETPOST('pdluoid', 'int'); @@ -102,24 +116,24 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); $arrayfields = array( - 'm.rowid'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'm.datem'=>array('label'=>$langs->trans("Date"), 'checked'=>1), - 'p.ref'=>array('label'=>$langs->trans("ProductRef"), 'checked'=>1, 'css'=>'maxwidth100'), - 'p.label'=>array('label'=>$langs->trans("ProductLabel"), 'checked'=>1), - 'm.batch'=>array('label'=>$langs->trans("BatchNumberShort"), 'checked'=>1, 'enabled'=>(!empty($conf->productbatch->enabled))), - 'pl.eatby'=>array('label'=>$langs->trans("EatByDate"), 'checked'=>0, 'enabled'=>(!empty($conf->productbatch->enabled))), - 'pl.sellby'=>array('label'=>$langs->trans("SellByDate"), 'checked'=>0, 'position'=>10, 'enabled'=>(!empty($conf->productbatch->enabled))), - 'e.ref'=>array('label'=>$langs->trans("Warehouse"), 'checked'=>1, 'enabled'=>(!$id > 0)), // If we are on specific warehouse, we hide it - 'm.fk_user_author'=>array('label'=>$langs->trans("Author"), 'checked'=>0), - 'm.inventorycode'=>array('label'=>$langs->trans("InventoryCodeShort"), 'checked'=>1), - 'm.label'=>array('label'=>$langs->trans("MovementLabel"), 'checked'=>1), - 'm.type_mouvement'=>array('label'=>$langs->trans("TypeMovement"), 'checked'=>1), - 'origin'=>array('label'=>$langs->trans("Origin"), 'checked'=>1), - 'm.value'=>array('label'=>$langs->trans("Qty"), 'checked'=>1), - 'm.price'=>array('label'=>$langs->trans("UnitPurchaseValue"), 'checked'=>0), - 'm.fk_projet'=>array('label'=>$langs->trans('Project'), 'checked'=>0) - //'m.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - //'m.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500) + 'm.rowid'=>array('label'=>"Ref", 'checked'=>1, 'position'=>1), + 'm.datem'=>array('label'=>"Date", 'checked'=>1, 'position'=>2), + 'p.ref'=>array('label'=>"ProductRef", 'checked'=>1, 'css'=>'maxwidth100', 'position'=>3), + 'p.label'=>array('label'=>"ProductLabel", 'checked'=>0, 'position'=>5), + 'm.batch'=>array('label'=>"BatchNumberShort", 'checked'=>1, 'position'=>8, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'pl.eatby'=>array('label'=>"EatByDate", 'checked'=>0, 'position'=>9, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'pl.sellby'=>array('label'=>"SellByDate", 'checked'=>0, 'position'=>10, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'e.ref'=>array('label'=>"Warehouse", 'checked'=>1, 'position'=>100, 'enabled'=>(!$id > 0)), // If we are on specific warehouse, we hide it + 'm.fk_user_author'=>array('label'=>"Author", 'checked'=>0, 'position'=>120), + 'm.inventorycode'=>array('label'=>"InventoryCodeShort", 'checked'=>1, 'position'=>130), + 'm.label'=>array('label'=>"MovementLabel", 'checked'=>1, 'position'=>140), + 'm.type_mouvement'=>array('label'=>"TypeMovement", 'checked'=>0, 'position'=>150), + 'origin'=>array('label'=>"Origin", 'checked'=>1, 'position'=>155), + 'm.fk_projet'=>array('label'=>'Project', 'checked'=>0, 'position'=>180), + 'm.value'=>array('label'=>"Qty", 'checked'=>1, 'position'=>200), + 'm.price'=>array('label'=>"UnitPurchaseValue", 'checked'=>0, 'position'=>210) + //'m.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500), + //'m.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500) ); if (!empty($conf->global->PRODUCT_DISABLE_EATBY)) { unset($arrayfields['pl.eatby']); @@ -148,22 +162,32 @@ $error = 0; * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers - { - $year = ''; - $month = ''; + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers + $search_date_startday = ''; + $search_date_startmonth = ''; + $search_date_startyear = ''; + $search_date_endday = ''; + $search_date_endmonth = ''; + $search_date_endyear = ''; + $search_date_start = ''; + $search_date_end = ''; $search_ref = ''; $search_movement = ""; $search_type_mouvement = ""; @@ -194,7 +218,9 @@ if ($action == 'update_extras') { // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $tmpwarehouse, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } if (!$error) { $result = $tmpwarehouse->insertExtraFields(); if ($result < 0) { @@ -202,43 +228,41 @@ if ($action == 'update_extras') { $error++; } } - if ($error) $action = 'edit_extras'; + if ($error) { + $action = 'edit_extras'; + } } // Correct stock -if ($action == "correct_stock") -{ +if ($action == "correct_stock") { $product = new Product($db); - if (!empty($product_id)) $result = $product->fetch($product_id); + if (!empty($product_id)) { + $result = $product->fetch($product_id); + } $error = 0; - if (empty($product_id)) - { + if (empty($product_id)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); $action = 'correction'; } - if (!is_numeric($_POST["nbpiece"])) - { + if (!is_numeric($_POST["nbpiece"])) { $error++; setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); $action = 'correction'; } - if (!$error) - { + if (!$error) { $origin_element = ''; $origin_id = null; - if (GETPOST('projectid', 'int')) - { + if (GETPOST('projectid', 'int')) { $origin_element = 'project'; $origin_id = GETPOST('projectid', 'int'); } - if ($product->hasbatch()) - { + if ($product->hasbatch()) { $batch = GETPOST('batch_number', 'alphanohtml'); //$eatby=GETPOST('eatby'); @@ -253,7 +277,9 @@ if ($action == "correct_stock") GETPOST("mouvement"), GETPOST("label", 'san_alpha'), GETPOST('unitprice'), - $eatby, $sellby, $batch, + $eatby, + $sellby, + $batch, GETPOST('inventorycode', 'alphanohtml'), $origin_element, $origin_id @@ -272,8 +298,7 @@ if ($action == "correct_stock") ); // We do not change value of stock for a correction } - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { @@ -283,57 +308,52 @@ if ($action == "correct_stock") } } - if (!$error) $action = ''; + if (!$error) { + $action = ''; + } } // Transfer stock from a warehouse to another warehouse -if ($action == "transfert_stock" && !$cancel) -{ +if ($action == "transfert_stock" && !$cancel) { $product = new Product($db); - if (!empty($product_id)) $result = $product->fetch($product_id); + if (!empty($product_id)) { + $result = $product->fetch($product_id); + } - if (!(GETPOST("id_entrepot_destination", 'int') > 0)) - { + if (!(GETPOST("id_entrepot_destination", 'int') > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $error++; $action = 'transfert'; } - if (empty($product_id)) - { + if (empty($product_id)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); $action = 'transfert'; } - if (!GETPOST("nbpiece", 'int')) - { + if (!GETPOST("nbpiece", 'int')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); $error++; $action = 'transfert'; } - if ($id == GETPOST("id_entrepot_destination", 'int')) - { + if ($id == GETPOST("id_entrepot_destination", 'int')) { setEventMessages($langs->trans("ErrorSrcAndTargetWarehouseMustDiffers"), null, 'errors'); $error++; $action = 'transfert'; } - if (!empty($conf->productbatch->enabled)) - { + if (!empty($conf->productbatch->enabled)) { $product = new Product($db); $result = $product->fetch($product_id); - if ($product->hasbatch() && !GETPOST("batch_number")) - { + if ($product->hasbatch() && !GETPOST("batch_number")) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); $error++; $action = 'transfert'; } } - if (!$error) - { - if ($id) - { + if (!$error) { + if ($id) { $object = new Entrepot($db); $result = $object->fetch($id); @@ -343,18 +363,17 @@ if ($action == "transfert_stock" && !$cancel) // Define value of products moved $pricesrc = 0; - if (isset($product->pmp)) $pricesrc = $product->pmp; + if (isset($product->pmp)) { + $pricesrc = $product->pmp; + } $pricedest = $pricesrc; - if ($product->hasbatch()) - { + if ($product->hasbatch()) { $pdluo = new Productbatch($db); - if ($pdluoid > 0) - { + if ($pdluoid > 0) { $result = $pdluo->fetch($pdluoid); - if ($result) - { + if ($result) { $srcwarehouseid = $pdluo->warehouseid; $batch = $pdluo->batch; $eatby = $pdluo->eatby; @@ -370,8 +389,7 @@ if ($action == "transfert_stock" && !$cancel) $sellby = $d_sellby; } - if (!$error) - { + if (!$error) { // Remove stock $result1 = $product->correct_stock_batch( $user, @@ -380,9 +398,11 @@ if ($action == "transfert_stock" && !$cancel) 1, GETPOST("label", 'san_alpha'), $pricesrc, - $eatby, $sellby, $batch, + $eatby, + $sellby, + $batch, GETPOST('inventorycode') - ); + ); // Add stock $result2 = $product->correct_stock_batch( $user, @@ -391,9 +411,11 @@ if ($action == "transfert_stock" && !$cancel) 0, GETPOST("label", 'san_alpha'), $pricedest, - $eatby, $sellby, $batch, + $eatby, + $sellby, + $batch, GETPOST('inventorycode', 'alphanohtml') - ); + ); } } else { // Remove stock @@ -405,7 +427,7 @@ if ($action == "transfert_stock" && !$cancel) GETPOST("label", 'san_alpha'), $pricesrc, GETPOST('inventorycode', 'alphanohtml') - ); + ); // Add stock $result2 = $product->correct_stock( @@ -416,14 +438,12 @@ if ($action == "transfert_stock" && !$cancel) GETPOST("label", 'san_alpha'), $pricedest, GETPOST('inventorycode', 'alphanohtml') - ); + ); } - if (!$error && $result1 >= 0 && $result2 >= 0) - { + if (!$error && $result1 >= 0 && $result2 >= 0) { $db->commit(); - if ($backtopage) - { + if ($backtopage) { header("Location: ".$backtopage); exit; } else { @@ -450,9 +470,10 @@ $warehousestatic = new Entrepot($db); $movement = new MouvementStock($db); $userstatic = new User($db); $form = new Form($db); -$formother = new FormOther($db); $formproduct = new FormProduct($db); -if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $sql = "SELECT p.rowid, p.ref as product_ref, p.label as produit, p.tosell, p.tobuy, p.tobatch, p.fk_product_type as type, p.entity,"; $sql .= " e.ref as warehouse_ref, e.rowid as entrepot_id, e.lieu, e.fk_parent, e.statut,"; @@ -461,10 +482,12 @@ $sql .= " m.batch, m.price,"; $sql .= " m.type_mouvement,"; $sql .= " m.fk_projet as fk_project,"; $sql .= " pl.rowid as lotid, pl.eatby, pl.sellby,"; -$sql .= " u.login, u.photo, u.lastname, u.firstname"; +$sql .= " u.login, u.photo, u.lastname, u.firstname, u.email as user_email, u.statut as user_status"; // 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 : ''); + 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(); @@ -473,28 +496,65 @@ $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,"; $sql .= " ".MAIN_DB_PREFIX."product as p,"; $sql .= " ".MAIN_DB_PREFIX."stock_mouvement as m"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (m.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (m.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON m.fk_user_author = u.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON m.batch = pl.batch AND m.fk_product = pl.fk_product"; $sql .= " WHERE m.fk_product = p.rowid"; -if ($msid > 0) $sql .= " AND m.rowid = ".$msid; +if ($msid > 0) { + $sql .= " AND m.rowid = ".$msid; +} $sql .= " AND m.fk_entrepot = e.rowid"; $sql .= " AND e.entity IN (".getEntity('stock').")"; -if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= " AND p.fk_product_type = 0"; -if ($id > 0) $sql .= " AND e.rowid ='".$id."'"; -$sql .= dolSqlDateFilter('m.datem', 0, $month, $year); -if ($idproduct > 0) $sql .= " AND p.rowid = ".((int) $idproduct); -if (!empty($search_ref)) $sql .= natural_search('m.rowid', $search_ref, 1); -if (!empty($search_movement)) $sql .= natural_search('m.label', $search_movement); -if (!empty($search_inventorycode)) $sql .= natural_search('m.inventorycode', $search_inventorycode); -if (!empty($search_product_ref)) $sql .= natural_search('p.ref', $search_product_ref); -if (!empty($search_product)) $sql .= natural_search('p.label', $search_product); -if ($search_warehouse != '' && $search_warehouse != '-1') $sql .= natural_search('e.rowid', $search_warehouse, 2); -if (!empty($search_user)) $sql .= natural_search('u.login', $search_user); -if (!empty($search_batch)) $sql .= natural_search('m.batch', $search_batch); -if (!empty($product_id)) $sql .= natural_search('p.rowid', $product_id); -if ($search_qty != '') $sql .= natural_search('m.value', $search_qty, 1); -if ($search_type_mouvement != '' && $search_type_mouvement != '-1') $sql .= natural_search('m.type_mouvement', $search_type_mouvement, 2); +if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + $sql .= " AND p.fk_product_type = 0"; +} +if ($id > 0) { + $sql .= " AND e.rowid ='".$id."'"; +} +if (!empty($search_date_start)) { + $sql .= " AND m.datem >= '" . $db->idate($search_date_start) . "'"; +} +if (!empty($search_date_end)) { + $sql .= " AND m.datem <= '" . $db->idate($search_date_end) . "'"; +} +if ($idproduct > 0) { + $sql .= " AND p.rowid = ".((int) $idproduct); +} +if (!empty($search_ref)) { + $sql .= natural_search('m.rowid', $search_ref, 1); +} +if (!empty($search_movement)) { + $sql .= natural_search('m.label', $search_movement); +} +if (!empty($search_inventorycode)) { + $sql .= natural_search('m.inventorycode', $search_inventorycode); +} +if (!empty($search_product_ref)) { + $sql .= natural_search('p.ref', $search_product_ref); +} +if (!empty($search_product)) { + $sql .= natural_search('p.label', $search_product); +} +if ($search_warehouse != '' && $search_warehouse != '-1') { + $sql .= natural_search('e.rowid', $search_warehouse, 2); +} +if (!empty($search_user)) { + $sql .= natural_search('u.login', $search_user); +} +if (!empty($search_batch)) { + $sql .= natural_search('m.batch', $search_batch); +} +if (!empty($product_id)) { + $sql .= natural_search('p.rowid', $product_id); +} +if ($search_qty != '') { + $sql .= natural_search('m.value', $search_qty, 1); +} +if ($search_type_mouvement != '' && $search_type_mouvement != '-1') { + $sql .= natural_search('m.type_mouvement', $search_type_mouvement, 2); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -504,44 +564,31 @@ $sql .= $hookmanager->resPrint; $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } } -if (empty($search_inventorycode)) -{ - $sql .= $db->plimit($limit + 1, $offset); -} else { - $limit = 0; -} +$sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if (!empty($search_inventorycode)) $limit = $db->num_rows($resql); - -if ($resql) -{ +if ($resql) { $product = new Product($db); $object = new Entrepot($db); - if ($idproduct > 0) - { + if ($idproduct > 0) { $product->fetch($idproduct); } - if ($id > 0 || $ref) - { + if ($id > 0 || $ref) { $result = $object->fetch($id, $ref); - if ($result < 0) - { + if ($result < 0) { dol_print_error($db); } } @@ -553,18 +600,20 @@ if ($resql) $i = 0; $help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks'; - if ($msid) $texte = $langs->trans('StockMovementForId', $msid); - else { + if ($msid) { + $texte = $langs->trans('StockMovementForId', $msid); + } else { $texte = $langs->trans("ListOfStockMovements"); - if ($id) $texte .= ' ('.$langs->trans("ForThisWarehouse").')'; + if ($id) { + $texte .= ' ('.$langs->trans("ForThisWarehouse").')'; + } } llxHeader("", $texte, $help_url); /* - * Show tab only if we ask a particular warehouse - */ - if ($object->id > 0) - { + * Show tab only if we ask a particular warehouse + */ + if ($object->id > 0) { $head = stock_prepare_head($object); print dol_get_fiche_head($head, 'movements', $langs->trans("Warehouse"), -1, 'stock'); @@ -577,7 +626,9 @@ if ($resql) $morehtmlref .= '</div>'; $shownav = 1; - if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref); @@ -626,8 +677,7 @@ if ($resql) $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as m"; $sql .= " WHERE m.fk_entrepot = ".((int) $object->id); $resqlbis = $db->query($sql); - if ($resqlbis) - { + if ($resqlbis) { $objbis = $db->fetch_object($resqlbis); $lastmovementdate = $db->jdate($objbis->datem); } else { @@ -635,8 +685,7 @@ if ($resql) } print '<tr><td>'.$langs->trans("LastMovement").'</td><td>'; - if ($lastmovementdate) - { + if ($lastmovementdate) { print dol_print_date($lastmovementdate, 'dayhour'); } else { print $langs->trans("None"); @@ -668,8 +717,7 @@ if ($resql) /* * Correct stock */ - if ($action == "correction") - { + if ($action == "correction") { include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stockcorrection.tpl.php'; print '<br>'; } @@ -677,30 +725,23 @@ if ($resql) /* * Transfer of units */ - if ($action == "transfert") - { + if ($action == "transfert") { include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stocktransfer.tpl.php'; print '<br>'; } - /* ************************************************************************** */ - /* */ - /* Barre d'action */ - /* */ - /* ************************************************************************** */ - - if ((empty($action) || $action == 'list') && $id > 0) - { + /* + * Action bar + */ + if ((empty($action) || $action == 'list') && $id > 0) { print "<div class=\"tabsAction\">\n"; - if ($user->rights->stock->mouvement->creer) - { + if ($user->rights->stock->mouvement->creer) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=correction">'.$langs->trans("CorrectStock").'</a>'; } - if ($user->rights->stock->mouvement->creer) - { + if ($user->rights->stock->mouvement->creer) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=transfert">'.$langs->trans("TransferStock").'</a>'; } @@ -708,18 +749,60 @@ if ($resql) } $param = ''; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($id > 0) $param .= '&id='.urlencode($id); - if ($search_movement) $param .= '&search_movement='.urlencode($search_movement); - if ($search_inventorycode) $param .= '&search_inventorycode='.urlencode($search_inventorycode); - if ($search_type_mouvement) $param .= '&search_type_mouvement='.urlencode($search_type_mouvement); - if ($search_product_ref) $param .= '&search_product_ref='.urlencode($search_product_ref); - if ($search_product) $param .= '&search_product='.urlencode($search_product); - if ($search_batch) $param .= '&search_batch='.urlencode($search_batch); - if ($search_warehouse > 0) $param .= '&search_warehouse='.urlencode($search_warehouse); - if ($search_user) $param .= '&search_user='.urlencode($search_user); - if ($idproduct > 0) $param .= '&idproduct='.urlencode($idproduct); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($id > 0) { + $param .= '&id='.urlencode($id); + } + if ($search_date_startday) { + $param .= '&search_date_startday='.urlencode($search_date_startday); + } + if ($search_date_startmonth) { + $param .= '&search_date_startmonth='.urlencode($search_date_startmonth); + } + if ($search_date_startyear) { + $param .= '&search_date_startyear='.urlencode($search_date_startyear); + } + if ($search_date_endday) { + $param .= '&search_date_endday='.urlencode($search_date_endday); + } + if ($search_date_endmonth) { + $param .= '&search_date_endmonth='.urlencode($search_date_endmonth); + } + if ($search_date_endyear) { + $param .= '&search_date_endyear='.urlencode($search_date_endyear); + } + if ($search_movement) { + $param .= '&search_movement='.urlencode($search_movement); + } + if ($search_inventorycode) { + $param .= '&search_inventorycode='.urlencode($search_inventorycode); + } + if ($search_type_mouvement) { + $param .= '&search_type_mouvement='.urlencode($search_type_mouvement); + } + if ($search_product_ref) { + $param .= '&search_product_ref='.urlencode($search_product_ref); + } + if ($search_product) { + $param .= '&search_product='.urlencode($search_product); + } + if ($search_batch) { + $param .= '&search_batch='.urlencode($search_batch); + } + if ($search_warehouse > 0) { + $param .= '&search_warehouse='.urlencode($search_warehouse); + } + if ($search_user) { + $param .= '&search_user='.urlencode($search_user); + } + if ($idproduct > 0) { + $param .= '&idproduct='.urlencode($idproduct); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -729,12 +812,18 @@ if ($resql) // 'builddoc'=>$langs->trans("PDFMerge"), ); // By default, we should never accept deletion of stock movement. - if (!empty($conf->global->STOCK_ALLOW_DELETE_OF_MOVEMENT) && $permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); - if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + if (!empty($conf->global->STOCK_ALLOW_DELETE_OF_MOVEMENT) && $permissiontodelete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); + } + if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -742,10 +831,15 @@ if ($resql) print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="type" value="'.$type.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; - if ($id > 0) print '<input type="hidden" name="id" value="'.$id.'">'; + if ($id > 0) { + print '<input type="hidden" name="id" value="'.$id.'">'; + } - if ($id > 0) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'stock', 0, '', '', $limit, 0, 0, 1); - else print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'stock', 0, '', '', $limit, 0, 0, 1); + if ($id > 0) { + print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'stock', 0, '', '', $limit, 0, 0, 1); + } else { + print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'stock', 0, '', '', $limit, 0, 0, 1); + } // Add code for pre mass action (confirmation or email presend form) $topicmail = "SendStockMovement"; @@ -754,9 +848,10 @@ if ($resql) $trackid = 'mov'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } @@ -764,11 +859,13 @@ if ($resql) $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)) - { + if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -782,85 +879,72 @@ if ($resql) // Fields title search print '<tr class="liste_titre_filter">'; - if (!empty($arrayfields['m.rowid']['checked'])) - { + if (!empty($arrayfields['m.rowid']['checked'])) { // Ref print '<td class="liste_titre left">'; print '<input class="flat maxwidth25" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; print '</td>'; } - if (!empty($arrayfields['m.datem']['checked'])) - { - // Date - print '<td class="liste_titre nowraponall">'; - print '<input class="flat" type="text" size="2" maxlength="2" placeholder="'.dol_escape_htmltag($langs->trans("Month")).'" name="month" value="'.$month.'">'; - if (empty($conf->productbatch->enabled)) print '&nbsp;'; - //else print '<br>'; - $syear = $year ? $year : -1; - print '<input class="flat maxwidth50" type="text" maxlength="4" placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" name="year" value="'.($syear > 0 ? $syear : '').'">'; - //print $formother->selectyear($syear,'year',1, 20, 5); + if (! empty($arrayfields['m.datem']['checked'])) { + print '<td class="liste_titre center">'; + print '<div class="nowrap">'; + print $form->selectDate($search_date_start?$search_date_start:-1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'), 'tzuserrel'); + print '</div>'; + print '<div class="nowrap">'; + print $form->selectDate($search_date_end?$search_date_end:-1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'), 'tzuserrel'); + print '</div>'; print '</td>'; } - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { // Product Ref print '<td class="liste_titre left">'; print '<input class="flat maxwidth75" type="text" name="search_product_ref" value="'.dol_escape_htmltag($idproduct ? $product->ref : $search_product_ref).'">'; print '</td>'; } - if (!empty($arrayfields['p.label']['checked'])) - { + if (!empty($arrayfields['p.label']['checked'])) { // Product label print '<td class="liste_titre left">'; print '<input class="flat maxwidth100" type="text" name="search_product" value="'.dol_escape_htmltag($idproduct ? $product->label : $search_product).'">'; print '</td>'; } // Batch - if (!empty($arrayfields['m.batch']['checked'])) - { + if (!empty($arrayfields['m.batch']['checked'])) { print '<td class="liste_titre center"><input class="flat maxwidth75" type="text" name="search_batch" value="'.dol_escape_htmltag($search_batch).'"></td>'; } - if (!empty($arrayfields['pl.eatby']['checked'])) - { + if (!empty($arrayfields['pl.eatby']['checked'])) { print '<td class="liste_titre left">'; print '</td>'; } - if (!empty($arrayfields['pl.sellby']['checked'])) - { + if (!empty($arrayfields['pl.sellby']['checked'])) { print '<td class="liste_titre left">'; print '</td>'; } // Warehouse - if (!empty($arrayfields['e.ref']['checked'])) - { + if (!empty($arrayfields['e.ref']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone left">'; //print '<input class="flat" type="text" size="8" name="search_warehouse" value="'.($search_warehouse).'">'; print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print '</td>'; } - if (!empty($arrayfields['m.fk_user_author']['checked'])) - { + if (!empty($arrayfields['m.fk_user_author']['checked'])) { // Author print '<td class="liste_titre left">'; print '<input class="flat" type="text" size="6" name="search_user" value="'.dol_escape_htmltag($search_user).'">'; print '</td>'; } - if (!empty($arrayfields['m.inventorycode']['checked'])) - { + if (!empty($arrayfields['m.inventorycode']['checked'])) { // Inventory code print '<td class="liste_titre left">'; print '<input class="flat" type="text" size="4" name="search_inventorycode" value="'.dol_escape_htmltag($search_inventorycode).'">'; print '</td>'; } - if (!empty($arrayfields['m.label']['checked'])) - { + if (!empty($arrayfields['m.label']['checked'])) { // Label of movement print '<td class="liste_titre left">'; print '<input class="flat" type="text" size="8" name="search_movement" value="'.dol_escape_htmltag($search_movement).'">'; print '</td>'; } - if (!empty($arrayfields['m.type_mouvement']['checked'])) - { + if (!empty($arrayfields['m.type_mouvement']['checked'])) { // Type of movement print '<td class="liste_titre center">'; //print '<input class="flat" type="text" size="3" name="search_type_mouvement" value="'.dol_escape_htmltag($search_type_mouvement).'">'; @@ -876,35 +960,30 @@ if ($resql) // print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print '</td>'; } - if (!empty($arrayfields['origin']['checked'])) - { + if (!empty($arrayfields['origin']['checked'])) { // Origin of movement print '<td class="liste_titre left">'; print '&nbsp; '; print '</td>'; } - if (!empty($arrayfields['m.value']['checked'])) - { - // Qty - print '<td class="liste_titre right">'; - print '<input class="flat" type="text" size="4" name="search_qty" value="'.dol_escape_htmltag($search_qty).'">'; - print '</td>'; - } - if (!empty($arrayfields['m.price']['checked'])) - { - // Price - print '<td class="liste_titre" align="left">'; - print '&nbsp; '; - print '</td>'; - } - if (!empty($arrayfields['m.fk_projet']['checked'])) - { + if (!empty($arrayfields['m.fk_projet']['checked'])) { // fk_project print '<td class="liste_titre" align="left">'; print '&nbsp; '; print '</td>'; } - + if (!empty($arrayfields['m.value']['checked'])) { + // Qty + print '<td class="liste_titre right">'; + print '<input class="flat" type="text" size="4" name="search_qty" value="'.dol_escape_htmltag($search_qty).'">'; + print '</td>'; + } + if (!empty($arrayfields['m.price']['checked'])) { + // Price + print '<td class="liste_titre" align="left">'; + print '&nbsp; '; + print '</td>'; + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; @@ -914,14 +993,12 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['m.datec']['checked'])) - { + if (!empty($arrayfields['m.datec']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Date modification - if (!empty($arrayfields['m.tms']['checked'])) - { + if (!empty($arrayfields['m.tms']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } @@ -973,15 +1050,15 @@ if ($resql) if (!empty($arrayfields['origin']['checked'])) { print_liste_field_titre($arrayfields['origin']['label'], $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder); } + if (!empty($arrayfields['m.fk_projet']['checked'])) { + print_liste_field_titre($arrayfields['m.fk_projet']['label'], $_SERVER["PHP_SELF"], "m.fk_projet", "", $param, '', $sortfield, $sortorder); + } if (!empty($arrayfields['m.value']['checked'])) { print_liste_field_titre($arrayfields['m.value']['label'], $_SERVER["PHP_SELF"], "m.value", "", $param, '', $sortfield, $sortorder, 'right '); } if (!empty($arrayfields['m.price']['checked'])) { print_liste_field_titre($arrayfields['m.price']['label'], $_SERVER["PHP_SELF"], "m.price", "", $param, '', $sortfield, $sortorder, 'right '); } - if (!empty($arrayfields['m.fk_projet']['checked'])) { - print_liste_field_titre($arrayfields['m.fk_projet']['label'], $_SERVER["PHP_SELF"], "m.fk_projet", "", $param, 'align="right"', $sortfield, $sortorder); - } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; @@ -1004,8 +1081,7 @@ if ($resql) $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($resql); $userstatic->id = $objp->fk_user_author; @@ -1013,6 +1089,8 @@ if ($resql) $userstatic->lastname = $objp->lastname; $userstatic->firstname = $objp->firstname; $userstatic->photo = $objp->photo; + $userstatic->email = $objp->user_email; + $userstatic->statut = $objp->user_status; $productstatic->id = $objp->rowid; $productstatic->ref = $objp->product_ref; @@ -1044,78 +1122,61 @@ if ($resql) print '<tr class="oddeven">'; // Id movement - if (!empty($arrayfields['m.rowid']['checked'])) - { + if (!empty($arrayfields['m.rowid']['checked'])) { print '<td>'.$objp->mid.'</td>'; // This is primary not movement id } - if (!empty($arrayfields['m.datem']['checked'])) - { + if (!empty($arrayfields['m.datem']['checked'])) { // Date print '<td class="nowraponall">'.dol_print_date($db->jdate($objp->datem), 'dayhour', 'tzuserrel').'</td>'; } - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { // Product ref print '<td class="nowraponall">'; print $productstatic->getNomUrl(1, 'stock', 16); print "</td>\n"; } - if (!empty($arrayfields['p.label']['checked'])) - { + if (!empty($arrayfields['p.label']['checked'])) { // Product label - print '<td>'; - /*$productstatic->id=$objp->rowid; - $productstatic->ref=$objp->produit; - $productstatic->type=$objp->type; - print $productstatic->getNomUrl(1,'',16);*/ + print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($productstatic->label).'">'; print $productstatic->label; print "</td>\n"; } - if (!empty($arrayfields['m.batch']['checked'])) - { + if (!empty($arrayfields['m.batch']['checked'])) { print '<td class="center nowraponall">'; - if ($productlot->id > 0) print $productlot->getNomUrl(1); - else print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. + if ($productlot->id > 0) { + print $productlot->getNomUrl(1); + } else { + print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. + } print '</td>'; } - if (!empty($arrayfields['pl.eatby']['checked'])) - { + if (!empty($arrayfields['pl.eatby']['checked'])) { print '<td class="center">'.dol_print_date($objp->eatby, 'day').'</td>'; } - if (!empty($arrayfields['pl.sellby']['checked'])) - { + if (!empty($arrayfields['pl.sellby']['checked'])) { print '<td class="center">'.dol_print_date($objp->sellby, 'day').'</td>'; } // Warehouse - if (!empty($arrayfields['e.ref']['checked'])) - { - print '<td>'; + if (!empty($arrayfields['e.ref']['checked'])) { + print '<td class="tdoverflowmax100">'; print $warehousestatic->getNomUrl(1); print "</td>\n"; } // Author - if (!empty($arrayfields['m.fk_user_author']['checked'])) - { + if (!empty($arrayfields['m.fk_user_author']['checked'])) { print '<td class="tdoverflowmax100">'; print $userstatic->getNomUrl(-1); print "</td>\n"; } - if (!empty($arrayfields['m.inventorycode']['checked'])) - { + if (!empty($arrayfields['m.inventorycode']['checked'])) { // Inventory code - print '<td><a href="' - .DOL_URL_ROOT.'/product/stock/movement_card.php?id='.urlencode($objp->entrepot_id) - .'&search_inventorycode='.urlencode($objp->inventorycode) - .'&search_type_mouvement='.urlencode($objp->type_mouvement) - .'">'.$objp->inventorycode.'</a></td>'; + print '<td><a href="'.$_SERVER["PHP_SELF"].'?search_inventorycode='.urlencode('^'.$objp->inventorycode.'$').'&search_type_mouvement='.urlencode($objp->type_mouvement).'">'.$objp->inventorycode.'</a></td>'; } - if (!empty($arrayfields['m.label']['checked'])) - { + if (!empty($arrayfields['m.label']['checked'])) { // Label of movement - print '<td class="tdoverflowmax100aaa">'.$objp->label.'</td>'; + print '<td class="tdoverflowmax200" title="'.dol_escape_htmltag($objp->label).'">'.$objp->label.'</td>'; } - if (!empty($arrayfields['m.type_mouvement']['checked'])) - { + if (!empty($arrayfields['m.type_mouvement']['checked'])) { // Type of movement switch ($objp->type_mouvement) { case "0": @@ -1132,43 +1193,48 @@ if ($resql) break; } } - if (!empty($arrayfields['origin']['checked'])) - { + if (!empty($arrayfields['origin']['checked'])) { // Origin of movement print '<td class="nowraponall">'.$origin.'</td>'; } - if (!empty($arrayfields['m.value']['checked'])) - { + if (!empty($arrayfields['m.fk_projet']['checked'])) { + // fk_project + print '<td>'; + if ($objp->fk_project != 0) { + print $movement->get_origin($objp->fk_project, 'project'); + } + print '</td>'; + } + if (!empty($arrayfields['m.value']['checked'])) { // Qty print '<td class="right">'; - if ($objp->qt > 0) print '+'; + if ($objp->qt > 0) { + print '+'; + } print $objp->qty; print '</td>'; } - if (!empty($arrayfields['m.price']['checked'])) - { + if (!empty($arrayfields['m.price']['checked'])) { // Price print '<td class="right">'; - if ($objp->price != 0) print price($objp->price); - print '</td>'; - } - if (!empty($arrayfields['m.fk_projet']['checked'])) - { - // fk_project - print '<td align="right">'; - if ($objp->fk_project != 0) print $movement->get_origin($objp->fk_project, 'project'); + if ($objp->price != 0) { + print price($objp->price); + } print '</td>'; } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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($objp->mid, $arrayofselected)) $selected = 1; + if (in_array($objp->mid, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$objp->mid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$objp->mid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; $i++; @@ -1180,13 +1246,11 @@ if ($resql) print "</form>"; // Add number of product when there is a filter on period - if (count($arrayofuniqueproduct) == 1 && is_numeric($year)) - { + if (count($arrayofuniqueproduct) == 1 && is_numeric($year)) { print "<br>"; $productidselected = 0; - foreach ($arrayofuniqueproduct as $key => $val) - { + foreach ($arrayofuniqueproduct as $key => $val) { $productidselected = $key; $productlabelselected = $val; } diff --git a/htdocs/product/stock/product.php b/htdocs/product/stock/product.php index d1c1ea99ff7..e45f48d9ef8 100644 --- a/htdocs/product/stock/product.php +++ b/htdocs/product/stock/product.php @@ -55,7 +55,9 @@ if (!empty($conf->variants->enabled)) { // Load translation files required by the page $langs->loadlangs(array('products', 'suppliers', 'orders', 'bills', 'stocks', 'sendings', 'margins')); -if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); +if (!empty($conf->productbatch->enabled)) { + $langs->load("productbatch"); +} $backtopage = GETPOST('backtopage', 'alpha'); $action = GETPOST('action', 'aZ09'); @@ -76,7 +78,9 @@ if (!empty($batchnumber)) { } // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit&stock', $id, 'product&product', '', '', $fieldid); @@ -86,20 +90,20 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref); } -if (empty($id) && !empty($object->id)) $id = $object->id; +if (empty($id) && !empty($object->id)) { + $id = $object->id; +} $modulepart = 'product'; // Get object canvas (By default, this is not defined, so standard usage of dolibarr) $canvas = !empty($object->canvas) ? $object->canvas : GETPOST("canvas"); $objcanvas = null; -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('stockproduct', 'card', $canvas); @@ -115,14 +119,17 @@ $error = 0; * Actions */ -if ($cancel) $action = ''; +if ($cancel) { + $action = ''; +} $parameters = array('id'=>$id, 'ref'=>$ref, '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 ($action == 'addlimitstockwarehouse' && !empty($user->rights->produit->creer)) -{ +if ($action == 'addlimitstockwarehouse' && !empty($user->rights->produit->creer)) { $seuil_stock_alerte = GETPOST('seuil_stock_alerte'); $desiredstock = GETPOST('desiredstock'); @@ -142,14 +149,18 @@ if ($action == 'addlimitstockwarehouse' && !empty($user->rights->produit->creer) // Update $pse->seuil_stock_alerte = $seuil_stock_alerte; $pse->desiredstock = $desiredstock; - if ($pse->update($user) > 0) setEventMessages($langs->trans('ProductStockWarehouseUpdated'), null, 'mesgs'); + if ($pse->update($user) > 0) { + setEventMessages($langs->trans('ProductStockWarehouseUpdated'), null, 'mesgs'); + } } else { // Create $pse->fk_entrepot = GETPOST('fk_entrepot', 'int'); $pse->fk_product = $id; $pse->seuil_stock_alerte = GETPOST('seuil_stock_alerte'); $pse->desiredstock = GETPOST('desiredstock'); - if ($pse->create($user) > 0) setEventMessages($langs->trans('ProductStockWarehouseCreated'), null, 'mesgs'); + if ($pse->create($user) > 0) { + setEventMessages($langs->trans('ProductStockWarehouseCreated'), null, 'mesgs'); + } } } @@ -157,66 +168,62 @@ if ($action == 'addlimitstockwarehouse' && !empty($user->rights->produit->creer) exit; } -if ($action == 'delete_productstockwarehouse' && !empty($user->rights->produit->creer)) -{ +if ($action == 'delete_productstockwarehouse' && !empty($user->rights->produit->creer)) { $pse = new ProductStockEntrepot($db); $pse->fetch(GETPOST('fk_productstockwarehouse', 'int')); - if ($pse->delete($user) > 0) setEventMessages($langs->trans('ProductStockWarehouseDeleted'), null, 'mesgs'); + if ($pse->delete($user) > 0) { + setEventMessages($langs->trans('ProductStockWarehouseDeleted'), null, 'mesgs'); + } $action = ''; } // Set stock limit -if ($action == 'setseuil_stock_alerte' && !empty($user->rights->produit->creer)) -{ +if ($action == 'setseuil_stock_alerte' && !empty($user->rights->produit->creer)) { $object = new Product($db); $result = $object->fetch($id); $object->seuil_stock_alerte = $stocklimit; $result = $object->update($object->id, $user, 0, 'update'); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } //else // setEventMessages($lans->trans("SavedRecordSuccessfully"), null, 'mesgs'); $action = ''; } // Set desired stock -if ($action == 'setdesiredstock' && !empty($user->rights->produit->creer)) -{ +if ($action == 'setdesiredstock' && !empty($user->rights->produit->creer)) { $object = new Product($db); $result = $object->fetch($id); $object->desiredstock = $desiredstock; $result = $object->update($object->id, $user, 0, 'update'); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } $action = ''; } // Correct stock -if ($action == "correct_stock" && !$cancel) -{ - if (!(GETPOST("id_entrepot", 'int') > 0)) - { +if ($action == "correct_stock" && !$cancel) { + if (!(GETPOST("id_entrepot", 'int') > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $error++; $action = 'correction'; } - if (!GETPOST("nbpiece")) - { + if (!GETPOST("nbpiece")) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); $error++; $action = 'correction'; } - if (!empty($conf->productbatch->enabled)) - { + if (!empty($conf->productbatch->enabled)) { $object = new Product($db); $result = $object->fetch($id); - if ($object->hasbatch() && !$batchnumber) - { + if ($object->hasbatch() && !$batchnumber) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); $error++; $action = 'correction'; @@ -293,43 +300,35 @@ if ($action == "correct_stock" && !$cancel) } // Transfer stock from a warehouse to another warehouse -if ($action == "transfert_stock" && !$cancel) -{ - if (!(GETPOST("id_entrepot", 'int') > 0) || !(GETPOST("id_entrepot_destination", 'int') > 0)) - { +if ($action == "transfert_stock" && !$cancel) { + if (!(GETPOST("id_entrepot", 'int') > 0) || !(GETPOST("id_entrepot_destination", 'int') > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $error++; $action = 'transfert'; } - if (!GETPOST("nbpiece", 'int')) - { + if (!GETPOST("nbpiece", 'int')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); $error++; $action = 'transfert'; } - if (GETPOST("id_entrepot", 'int') == GETPOST("id_entrepot_destination", 'int')) - { + if (GETPOST("id_entrepot", 'int') == GETPOST("id_entrepot_destination", 'int')) { setEventMessages($langs->trans("ErrorSrcAndTargetWarehouseMustDiffers"), null, 'errors'); $error++; $action = 'transfert'; } - if (!empty($conf->productbatch->enabled)) - { + if (!empty($conf->productbatch->enabled)) { $object = new Product($db); $result = $object->fetch($id); - if ($object->hasbatch() && !$batchnumber) - { + if ($object->hasbatch() && !$batchnumber) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); $error++; $action = 'transfert'; } } - if (!$error) - { - if ($id) - { + if (!$error) { + if ($id) { $object = new Product($db); $result = $object->fetch($id); @@ -339,20 +338,19 @@ if ($action == "transfert_stock" && !$cancel) // Define value of products moved $pricesrc = 0; - if (isset($object->pmp)) $pricesrc = $object->pmp; + if (isset($object->pmp)) { + $pricesrc = $object->pmp; + } $pricedest = $pricesrc; $nbpiece = price2num(GETPOST("nbpiece", 'alphanohtml')); - if ($object->hasbatch()) - { + if ($object->hasbatch()) { $pdluo = new Productbatch($db); - if ($pdluoid > 0) - { + if ($pdluoid > 0) { $result = $pdluo->fetch($pdluoid); - if ($result) - { + if ($result) { $srcwarehouseid = $pdluo->warehouseid; $batch = $pdluo->batch; $eatby = $pdluo->eatby; @@ -370,8 +368,7 @@ if ($action == "transfert_stock" && !$cancel) $nbpiece = price2num(GETPOST("nbpiece", 'alphanohtml')); - if (!$error) - { + if (!$error) { // Remove stock $result1 = $object->correct_stock_batch( $user, @@ -380,13 +377,16 @@ if ($action == "transfert_stock" && !$cancel) 1, GETPOST("label", 'alphanohtml'), $pricesrc, - $eatby, $sellby, $batch, + $eatby, + $sellby, + $batch, GETPOST('inventorycode', 'alphanohtml') ); - if ($result1 < 0) $error++; + if ($result1 < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { // Add stock $result2 = $object->correct_stock_batch( $user, @@ -395,14 +395,17 @@ if ($action == "transfert_stock" && !$cancel) 0, GETPOST("label", 'alphanohtml'), $pricedest, - $eatby, $sellby, $batch, + $eatby, + $sellby, + $batch, GETPOST('inventorycode', 'alphanohtml') ); - if ($result2 < 0) $error++; + if ($result2 < 0) { + $error++; + } } } else { - if (!$error) - { + if (!$error) { // Remove stock $result1 = $object->correct_stock( $user, @@ -413,10 +416,11 @@ if ($action == "transfert_stock" && !$cancel) $pricesrc, GETPOST('inventorycode', 'alphanohtml') ); - if ($result1 < 0) $error++; + if ($result1 < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { // Add stock $result2 = $object->correct_stock( $user, @@ -427,17 +431,17 @@ if ($action == "transfert_stock" && !$cancel) $pricedest, GETPOST('inventorycode', 'alphanohtml') ); - if ($result2 < 0) $error++; + if ($result2 < 0) { + $error++; + } } } - if (!$error && $result1 >= 0 && $result2 >= 0) - { + if (!$error && $result1 >= 0 && $result2 >= 0) { $db->commit(); - if ($backtopage) - { + if ($backtopage) { header("Location: ".$backtopage); exit; } else { @@ -454,15 +458,12 @@ if ($action == "transfert_stock" && !$cancel) } // Update batch information -if ($action == 'updateline' && GETPOST('save') == $langs->trans("Save")) -{ +if ($action == 'updateline' && GETPOST('save') == $langs->trans("Save")) { $pdluo = new Productbatch($db); $result = $pdluo->fetch(GETPOST('pdluoid', 'int')); - if ($result > 0) - { - if ($pdluo->id) - { + if ($result > 0) { + if ($pdluo->id) { if ((!GETPOST("sellby")) && (!GETPOST("eatby")) && (!$batchnumber)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("atleast1batchfield")), null, 'errors'); } else { @@ -472,8 +473,7 @@ if ($action == 'updateline' && GETPOST('save') == $langs->trans("Save")) $pdluo->eatby = $d_eatby; $pdluo->sellby = $d_sellby; $result = $pdluo->update($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($pdluo->error, $pdluo->errors, 'errors'); } } @@ -495,10 +495,11 @@ if ($action == 'updateline' && GETPOST('save') == $langs->trans("Save")) $form = new Form($db); $formproduct = new FormProduct($db); -if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} -if ($id > 0 || $ref) -{ +if ($id > 0 || $ref) { $object = new Product($db); $result = $object->fetch($id, $ref); @@ -509,21 +510,18 @@ if ($id > 0 || $ref) $title = $langs->trans('ProductServiceCard'); $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); - if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) - { + if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Stock'); $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; } - if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) - { + if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Stock'); $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; } llxHeader('', $title, $helpurl); - if ($result > 0) - { + if ($result > 0) { $head = product_prepare_head($object); $titre = $langs->trans("CardProduct".$object->type); $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -535,7 +533,9 @@ if ($id > 0 || $ref) $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -566,7 +566,9 @@ if ($id > 0 || $ref) // AWP print '<tr><td class="titlefield">'.$form->textwithpicto($langs->trans("AverageUnitPricePMPShort"), $langs->trans("AverageUnitPricePMPDesc")).'</td>'; print '<td>'; - if ($object->pmp > 0) print price($object->pmp).' '.$langs->trans("HT"); + if ($object->pmp > 0) { + print price($object->pmp).' '.$langs->trans("HT"); + } print '</td>'; print '</tr>'; @@ -575,8 +577,11 @@ if ($id > 0 || $ref) print '<td>'; $product_fourn = new ProductFournisseur($db); if ($product_fourn->find_min_price_product_fournisseur($object->id) > 0) { - if ($product_fourn->product_fourn_price_id > 0) print $product_fourn->display_price_product_fournisseur(); - else print $langs->trans("NotDefined"); + if ($product_fourn->product_fourn_price_id > 0) { + print $product_fourn->display_price_product_fournisseur(); + } else { + print $langs->trans("NotDefined"); + } } print '</td></tr>'; @@ -648,7 +653,9 @@ if ($id > 0 || $ref) print $form->textwithpicto($langs->trans("PhysicalStock"), $text_stock_options, 1); print '</td>'; print '<td>'.price2num($object->stock_reel, 'MS'); - if ($object->seuil_stock_alerte != '' && ($object->stock_reel < $object->seuil_stock_alerte)) print ' '.img_warning($langs->trans("StockLowerThanLimit", $object->seuil_stock_alerte)); + if ($object->seuil_stock_alerte != '' && ($object->stock_reel < $object->seuil_stock_alerte)) { + print ' '.img_warning($langs->trans("StockLowerThanLimit", $object->seuil_stock_alerte)); + } print ' &nbsp; &nbsp;<a href="'.DOL_URL_ROOT.'/product/stock/stockatdate.php?productid='.$object->id.'">'.$langs->trans("StockAtDate").'</a>'; print '</td>'; @@ -660,10 +667,16 @@ if ($id > 0 || $ref) $helpondiff = '<strong>'.$langs->trans("StockDiffPhysicTeoric").':</strong><br>'; // Number of customer orders running if (!empty($conf->commande->enabled)) { - if ($found) $helpondiff .= '<br>'; else $found = 1; + if ($found) { + $helpondiff .= '<br>'; + } else { + $found = 1; + } $helpondiff .= $langs->trans("ProductQtyInCustomersOrdersRunning").': '.$object->stats_commande['qty']; $result = $object->load_stats_commande(0, '0', 1); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + dol_print_error($db, $object->error); + } $helpondiff .= ' ('.$langs->trans("ProductQtyInDraft").': '.$object->stats_commande['qty'].')'; } @@ -676,31 +689,48 @@ if ($id > 0 || $ref) } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { $filterShipmentStatus = Expedition::STATUS_CLOSED; } - if ($found) $helpondiff .= '<br>'; else $found = 1; + if ($found) { + $helpondiff .= '<br>'; + } else { + $found = 1; + } $result = $object->load_stats_sending(0, '2', 1, $filterShipmentStatus); $helpondiff .= $langs->trans("ProductQtyInShipmentAlreadySent").': '.$object->stats_expedition['qty']; } // Number of supplier order running - if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) - { - if ($found) $helpondiff .= '<br>'; else $found = 1; + if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) { + if ($found) { + $helpondiff .= '<br>'; + } else { + $found = 1; + } $result = $object->load_stats_commande_fournisseur(0, '3,4', 1); $helpondiff .= $langs->trans("ProductQtyInSuppliersOrdersRunning").': '.$object->stats_commande_fournisseur['qty']; $result = $object->load_stats_commande_fournisseur(0, '0,1,2', 1); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + dol_print_error($db, $object->error); + } $helpondiff .= ' ('.$langs->trans("ProductQtyInDraftOrWaitingApproved").': '.$object->stats_commande_fournisseur['qty'].')'; } // Number of product from supplier order already received (partial receipt) if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) { - if ($found) $helpondiff .= '<br>'; else $found = 1; + if ($found) { + $helpondiff .= '<br>'; + } else { + $found = 1; + } $helpondiff .= $langs->trans("ProductQtyInSuppliersShipmentAlreadyRecevied").': '.$object->stats_reception['qty']; } // Number of product in production if (!empty($conf->mrp->enabled)) { - if ($found) $helpondiff .= '<br>'; else $found = 1; + if ($found) { + $helpondiff .= '<br>'; + } else { + $found = 1; + } $helpondiff .= $langs->trans("ProductQtyToConsumeByMO").': '.$object->stats_mrptoconsume['qty'].'<br>'; $helpondiff .= $langs->trans("ProductQtyToProduceByMO").': '.$object->stats_mrptoproduce['qty']; } @@ -713,14 +743,15 @@ if ($id > 0 || $ref) print "<td>"; //print (empty($stocktheo)?0:$stocktheo); print $form->textwithpicto((empty($stocktheo) ? 0 : $stocktheo), $helpondiff); - if ($object->seuil_stock_alerte != '' && ($object->stock_theorique < $object->seuil_stock_alerte)) print ' '.img_warning($langs->trans("StockLowerThanLimit", $object->seuil_stock_alerte)); + if ($object->seuil_stock_alerte != '' && ($object->stock_theorique < $object->seuil_stock_alerte)) { + print ' '.img_warning($langs->trans("StockLowerThanLimit", $object->seuil_stock_alerte)); + } print ' &nbsp; &nbsp;<a href="'.DOL_URL_ROOT.'/product/stock/stockatdate.php?mode=future&productid='.$object->id.'">'.$langs->trans("VirtualStockAtDate").'</a>'; print '</td>'; print '</tr>'; // Last movement - if (!empty($user->rights->stock->mouvement->lire)) - { + if (!empty($user->rights->stock->mouvement->lire)) { $sql = "SELECT max(m.datem) as datem"; $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as m"; $sql .= " WHERE m.fk_product = ".((int) $object->id); @@ -754,15 +785,13 @@ if ($id > 0 || $ref) } // Correct stock - if ($action == "correction") - { + if ($action == "correction") { include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stockcorrection.tpl.php'; print '<br><br>'; } // Transfer of units - if ($action == "transfert") - { + if ($action == "transfert") { include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stocktransfer.tpl.php'; print '<br><br>'; } @@ -776,14 +805,11 @@ if ($id > 0 || $ref) $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook -if (empty($reshook)) -{ - if (empty($action) && $object->id) - { +if (empty($reshook)) { + if (empty($action) && $object->id) { print "<div class=\"tabsAction\">\n"; - if ($user->rights->stock->mouvement->creer) - { + if ($user->rights->stock->mouvement->creer) { if (!$variants || !empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=correction">'.$langs->trans("CorrectStock").'</a>'; } else { @@ -794,8 +820,7 @@ if (empty($reshook)) } //if (($user->rights->stock->mouvement->creer) && ! $object->hasbatch()) - if ($user->rights->stock->mouvement->creer) - { + if ($user->rights->stock->mouvement->creer) { if (!$variants || !empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=transfert">'.$langs->trans("TransferStock").'</a>'; } else { @@ -888,22 +913,32 @@ if (!$variants) { print '<td class="right">'.(price2num($object->pmp) ? price(price2num($object->pmp * $obj->reel, 'MT')) : '').'</td>'; // Sell price print '<td class="right">'; - if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($object->price, 'MU'), 1); - else print $langs->trans("Variable"); + if (empty($conf->global->PRODUIT_MULTIPRICES)) { + print price(price2num($object->price, 'MU'), 1); + } else { + print $langs->trans("Variable"); + } print '</td>'; // Value sell print '<td class="right">'; - if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($object->price * $obj->reel, 'MT'), 1).'</td>'; - else print $langs->trans("Variable"); + if (empty($conf->global->PRODUIT_MULTIPRICES)) { + print price(price2num($object->price * $obj->reel, 'MT'), 1).'</td>'; + } else { + print $langs->trans("Variable"); + } print '</tr>'; $total += $obj->reel; - if (price2num($object->pmp)) $totalwithpmp += $obj->reel; + if (price2num($object->pmp)) { + $totalwithpmp += $obj->reel; + } $totalvalue = $totalvalue + ($object->pmp * $obj->reel); $totalvaluesell = $totalvaluesell + ($object->price * $obj->reel); // Batch Detail if ((!empty($conf->productbatch->enabled)) && $object->hasbatch()) { $details = Productbatch::findAll($db, $obj->product_stock_id, 0, $object->id); - if ($details < 0) dol_print_error($db); + if ($details < 0) { + dol_print_error($db); + } foreach ($details as $pdluo) { $product_lot_static->id = $pdluo->lotid; $product_lot_static->batch = $pdluo->batch; @@ -961,7 +996,9 @@ if (!$variants) { } $i++; } - } else dol_print_error($db); + } else { + dol_print_error($db); + } // Total line print '<tr class="liste_total"><td class="right liste_total" colspan="4">'.$langs->trans("Total").':</td>'; @@ -974,13 +1011,19 @@ if (!$variants) { print $totalvalue ? price(price2num($totalvalue, 'MT'), 1) : '&nbsp;'; print '</td>'; print '<td class="liste_total right">'; - if (empty($conf->global->PRODUIT_MULTIPRICES)) print ($total ? price($totalvaluesell / $total, 1) : '&nbsp;'); - else print $langs->trans("Variable"); + if (empty($conf->global->PRODUIT_MULTIPRICES)) { + print ($total ? price($totalvaluesell / $total, 1) : '&nbsp;'); + } else { + print $langs->trans("Variable"); + } print '</td>'; // Value to sell print '<td class="liste_total right">'; - if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($totalvaluesell, 'MT'), 1); - else print $langs->trans("Variable"); + if (empty($conf->global->PRODUIT_MULTIPRICES)) { + print price(price2num($totalvaluesell, 'MT'), 1); + } else { + print $langs->trans("Variable"); + } print '</td>'; print "</tr>"; @@ -1068,11 +1111,9 @@ if (!$variants) { </tr> <?php - if (count($productCombinations)) - { + if (count($productCombinations)) { $stock_total = 0; - foreach ($productCombinations as $currcomb) - { + foreach ($productCombinations as $currcomb) { $prodstatic->fetch($currcomb->fk_product_child); $prodstatic->load_stock(); $stock_total += $prodstatic->stock_reel; diff --git a/htdocs/product/stock/productlot_card.php b/htdocs/product/stock/productlot_card.php index 8601ce25ebc..94ecdc8e13a 100644 --- a/htdocs/product/stock/productlot_card.php +++ b/htdocs/product/stock/productlot_card.php @@ -36,8 +36,35 @@ $langs->loadLangs(array('stocks', 'other', 'productbatch')); // Get parameters $id = GETPOST('id', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'myobjectcard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); + +// Initialize technical objects +$object = new ProductLot($db); +$extrafields = new ExtraFields($db); +$hookmanager->initHooks(array('productlotcard', 'globalcard')); // Note that conf->hooks_modules contains array + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Initialize array of search criterias +$search_all = GETPOST("search_all", 'alpha'); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } +} + +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} + $batch = GETPOST('batch', 'alpha'); $productid = GETPOST('productid', 'int'); $ref = GETPOST('ref', 'alpha'); // ref is productid_batch @@ -49,30 +76,14 @@ $search_fk_user_creat = GETPOST('search_fk_user_creat', 'int'); $search_fk_user_modif = GETPOST('search_fk_user_modif', 'int'); $search_import_key = GETPOST('search_import_key', 'int'); -if (empty($action) && empty($id) && empty($ref)) $action = 'list'; - - -// Protection if external user -if ($user->socid > 0) -{ - //accessforbidden(); +if (empty($action) && empty($id) && empty($ref)) { + $action = 'list'; } -//$result = restrictedArea($user, 'mymodule', $id); - - -$object = new ProductLot($db); -$extrafields = new ExtraFields($db); -$formfile = new FormFile($db); - -// fetch optionals attributes and labels -$extrafields->fetch_name_optionals_label($object->table_element); // Load object //include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id || $ref) -{ - if ($ref) - { +if ($id || $ref) { + if ($ref) { $tmp = explode('_', $ref); $productid = $tmp[0]; $batch = $tmp[1]; @@ -81,6 +92,14 @@ if ($id || $ref) $object->ref = $object->batch; // For document management ( it use $object->ref) } +// Protection if external user +if ($user->socid > 0) { + //accessforbidden(); +} +//$result = restrictedArea($user, 'mymodule', $id); + + + // Initialize technical object to manage hooks of modules. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('productlotcard', 'globalcard')); @@ -93,30 +112,53 @@ $usercanread = $user->rights->produit->lire; $usercancreate = $user->rights->produit->creer; $usercandelete = $user->rights->produit->supprimer; +$upload_dir = $conf->productbatch->multidir_output[$conf->entity]; + +$permissiontoadd = $usercancreate; + + /* * Actions */ $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 == 'seteatby' && $user->rights->stock->creer) - { - $newvalue = dol_mktime(12, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']); +if (empty($reshook)) { + $error = 0; + + $backurlforlist = dol_buildpath('/product/stock/productlot_list.php', 1); + + if ($action == 'seteatby' && $user->rights->stock->creer) { + $newvalue = dol_mktime(12, 0, 0, GETPOST('eatbymonth', 'int'), GETPOST('eatbyday', 'int'), GETPOST('eatbyyear', 'int')); $result = $object->setValueFrom('eatby', $newvalue, '', null, 'date', '', $user, 'PRODUCTLOT_MODIFY'); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + setEventMessages($object->error, null, 'errors'); + $action == 'editeatby'; + } else { + $action = 'view'; + } } - if ($action == 'setsellby' && $user->rights->stock->creer) - { - $newvalue = dol_mktime(12, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']); + if ($action == 'setsellby' && $user->rights->stock->creer) { + $newvalue = dol_mktime(12, 0, 0, GETPOST('sellbymonth', 'int'), GETPOST('sellbyday', 'int'), GETPOST('sellbyyear', 'int')); $result = $object->setValueFrom('sellby', $newvalue, '', null, 'date', '', $user, 'PRODUCTLOT_MODIFY'); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + setEventMessages($object->error, null, 'errors'); + $action == 'editsellby'; + } else { + $action = 'view'; + } } + $triggermodname = 'PRODUCT_LOT_MODIFY'; // Name of trigger action code to execute when we modify record + + // Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen + include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; + /* if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); @@ -136,8 +178,9 @@ if (empty($reshook)) } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } // Action to add record @@ -152,8 +195,6 @@ if (empty($reshook)) $error = 0; - /* object_prop_getpost_prop */ - $object->entity = GETPOST('entity', 'int'); $object->fk_product = GETPOST('fk_product', 'int'); $object->batch = GETPOST('batch', 'alpha'); @@ -241,11 +282,15 @@ if (empty($reshook)) else setEventMessages($object->error, null, 'errors'); } } - - // Actions to build doc - $upload_dir = $conf->productbatch->multidir_output[$conf->entity]; - $permissiontoadd = $usercancreate; + */ + // Action to build doc include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + + // Actions to send emails + $triggersendname = 'PRODUCT_LOT_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_PRODUCT_LOT_TO'; + $trackid = 'productlot'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; } @@ -255,69 +300,100 @@ if (empty($reshook)) * View */ -llxHeader('', 'ProductLot', ''); - $form = new Form($db); +$formfile = new FormFile($db); + +$title = $langs->trans("ProductLot"); +$help_url = ''; +llxHeader('', $title, $help_url); + // Part to create -if ($action == 'create') -{ - print load_fiche_titre($langs->trans("Batch")); +if ($action == 'create') { + print load_fiche_titre($langs->trans("Batch"), '', 'object_'.$object->picto); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; + print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; - print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } - print dol_get_fiche_head(); + print dol_get_fiche_head(array(), ''); - print '<table class="border centpercent">'."\n"; - // print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td><td><input class="flat" type="text" size="36" name="label" value="'.$label.'"></td></tr>'; - // - print '<tr><td class="fieldrequired">'.$langs->trans("Fieldfk_product").'</td><td><input class="flat" type="text" name="fk_product" value="'.GETPOST('fk_product').'"></td></tr>'; - print '<tr><td class="fieldrequired">'.$langs->trans("Fieldbatch").'</td><td><input class="flat" type="text" name="batch" value="'.GETPOST('batch').'"></td></tr>'; - print '<tr><td class="fieldrequired">'.$langs->trans("Fieldfk_user_creat").'</td><td><input class="flat" type="text" name="fk_user_creat" value="'.GETPOST('fk_user_creat').'"></td></tr>'; - print '<tr><td class="fieldrequired">'.$langs->trans("Fieldfk_user_modif").'</td><td><input class="flat" type="text" name="fk_user_modif" value="'.GETPOST('fk_user_modif').'"></td></tr>'; - print '<tr><td class="fieldrequired">'.$langs->trans("Fieldimport_key").'</td><td><input class="flat" type="text" name="import_key" value="'.GETPOST('import_key').'"></td></tr>'; + // Set some default values + //if (! GETPOSTISSET('fieldname')) $_POST['fieldname'] = 'myvalue'; + + print '<table class="border centpercent tableforfieldcreate">'."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; print '</table>'."\n"; print dol_get_fiche_end(); - print '<div class="center"><input type="submit" class="button" name="add" value="'.$langs->trans("Create").'"> &nbsp; <input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'"></div>'; + print '<div class="center">'; + print '<input type="submit" class="button" name="add" value="'.dol_escape_htmltag($langs->trans("Create")).'">'; + print '&nbsp; '; + print '<input type="'.($backtopage ? "submit" : "button").'" class="button button-cancel" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'"'.($backtopage ? '' : ' onclick="javascript:history.go(-1)"').'>'; // Cancel for create does not post form if we don't know the backtopage + print '</div>'; print '</form>'; + + //dol_set_focus('input[name="ref"]'); } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_optionals(); - //print load_fiche_titre($langs->trans("Batch")); - $head = productlot_prepare_head($object); - print dol_get_fiche_head($head, 'card', $langs->trans("Batch"), -1, 'barcode'); + print dol_get_fiche_head($head, 'card', $langs->trans("Batch"), -1, $object->picto); + $formconfirm = ''; + // Confirmation to delete if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBatch'), $langs->trans('ConfirmDeleteBatch'), 'confirm_delete', '', 0, 1); - print $formconfirm; } + // Call Hook formConfirm + $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); + $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } + // Print form confirm + print $formconfirm; + + // Object card + // ------------------------------------------------------------ $linkback = '<a href="'.DOL_URL_ROOT.'/product/stock/productlot_list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } - dol_banner_tab($object, 'id', $linkback, $shownav, 'rowid', 'batch'); + $morehtmlref = ''; + + dol_banner_tab($object, 'id', $linkback, $shownav, 'rowid', 'batch', $morehtmlref); print '<div class="fichecenter">'; print '<div class="underbanner clearboth"></div>'; - - print '<table class="border centpercent">'."\n"; + print '<table class="border centpercent tableforfield">'."\n"; // Product print '<tr><td class="titlefield">'.$langs->trans("Product").'</td><td>'; @@ -345,67 +421,84 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '</td>'; print '</tr>'; } + // Other attributes - $cols = 2; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '</table>'; print '</div>'; + print '<div class="clearboth"></div>'; + print dol_get_fiche_end(); - - // Buttons - print '<div class="tabsAction">'."\n"; - $parameters = array(); - $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - - if (empty($reshook)) - { - /*TODO if ($user->rights->stock->lire) - { - print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'."\n"; - } - - if ($user->rights->stock->supprimer) - { - print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>'."\n"; - } - */ - } - print '</div>'."\n"; - - + // Link to other lists print '<a href="'.DOL_URL_ROOT.'/product/reassortlot.php?sref='.urlencode($producttmp->ref).'&search_batch='.urlencode($object->batch).'">'.$langs->trans("ShowCurrentStockOfLot").'</a><br>'; print '<br>'; print '<a href="'.DOL_URL_ROOT.'/product/stock/movement_list.php?search_product_ref='.urlencode($producttmp->ref).'&search_batch='.urlencode($object->batch).'">'.$langs->trans("ShowLogOfMovementIfLot").'</a><br>'; print '<br>'; + + + // Buttons for actions + if ($action != 'presend' && $action != 'editline') { + print '<div class="tabsAction">'."\n"; + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } + + if (empty($reshook)) { + /*TODO if ($user->rights->stock->lire) + { + print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'."\n"; + } + + if ($user->rights->stock->supprimer) + { + print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>'."\n"; + } + */ + } + + print '</div>'."\n"; + } } /* - * Documents generes + * Generated documents */ -if (empty($action)) -{ +if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre + $includedocgeneration = 1; + // Documents - $filedir = $conf->productbatch->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product_batch').dol_sanitizeFileName($object->ref); - $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed = $usercanread; - $delallowed = $usercancreate; + if ($includedocgeneration) { + $objref = dol_sanitizeFileName($object->ref); + $relativepath = $objref.'/'.$objref.'.pdf'; + $filedir = $conf->productbatch->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product_batch'); + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $usercanread; // If you can read, you can build the PDF to read content + $delallowed = $usercancreate; // If you can create/edit, you can remove a file on card + print $formfile->showdocuments('product_batch', $objref, $filedir, $urlsource, $genallowed, $delallowed, '', 0, 0, 0, 28, 0, '', 0, '', $langs->default_lang, '', $object); + } - print $formfile->showdocuments('product_batch', dol_sanitizeFileName($object->ref), $filedir, $urlsource, $genallowed, $delallowed, '', 0, 0, 0, 28, 0, '', 0, '', $object->default_lang, '', $object); - $somethingshown = $formfile->numoffiles; + print '</div><div class="fichehalfright"><div class="ficheaddleft">'; - print '</div>'; + $MAXEVENT = 10; + + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'productlot', 0, 1, '', $MAXEVENT); + + print '</div></div></div>'; } // End of page diff --git a/htdocs/product/stock/productlot_document.php b/htdocs/product/stock/productlot_document.php index 535486f8c62..81f68487cf6 100644 --- a/htdocs/product/stock/productlot_document.php +++ b/htdocs/product/stock/productlot_document.php @@ -26,7 +26,7 @@ /** * \file htdocs/product/stock/productlot_document.php * \ingroup product - * \brief Page des documents joints sur les lots produits + * \brief Page of attached documents for porudct lots */ require '../../main.inc.php'; @@ -48,7 +48,9 @@ $confirm = GETPOST('confirm', 'alpha'); // Security check $fieldvalue = (!empty($id) ? $id : ''); $fieldtype = 'rowid'; -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service'); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -59,19 +61,23 @@ $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 = "position_name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "position_name"; +} $modulepart = 'product_batch'; $object = new Productlot($db); -if ($id || $ref) -{ - if ($ref) - { +if ($id || $ref) { + if ($ref) { $tmp = explode('_', $ref); $productid = $tmp[0]; $batch = $tmp[1]; @@ -79,7 +85,9 @@ if ($id || $ref) $object->fetch($id, $productid, $batch); $object->ref = $object->batch; // For document management ( it use $object->ref) - if (!empty($conf->productbatch->enabled)) $upload_dir = $conf->productbatch->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, $modulepart).dol_sanitizeFileName($object->ref); + if (!empty($conf->productbatch->enabled)) { + $upload_dir = $conf->productbatch->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, $modulepart); + } } @@ -89,12 +97,13 @@ if ($id || $ref) $parameters = array('id'=>$id); $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 (empty($reshook)) { // Action submit/delete file/link - include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; + include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; } $permtoedit = $user->rights->produit->creer; @@ -109,8 +118,7 @@ $form = new Form($db); llxHeader('', $langs->trans('ProductLot'), ''); -if ($object->id) -{ +if ($object->id) { $head = productlot_prepare_head($object); print dol_get_fiche_head($head, 'documents', $langs->trans("Batch"), -1, 'barcode'); @@ -118,14 +126,15 @@ if ($object->id) $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -133,7 +142,9 @@ if ($object->id) $linkback = '<a href="'.DOL_URL_ROOT.'/product/stock/productlot_list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; - if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'id', $linkback, $shownav, 'rowid', 'batch'); @@ -142,6 +153,13 @@ if ($object->id) print '<div class="underbanner clearboth"></div>'; print '<table class="border tableforfield" width="100%">'; + // Product + print '<tr><td class="titlefield">'.$langs->trans("Product").'</td><td>'; + $producttmp = new Product($db); + $producttmp->fetch($object->fk_product); + print $producttmp->getNomUrl(1, 'stock')." - ".$producttmp->label; + print '</td></tr>'; + print '<tr><td class="titlefield">'.$langs->trans("NbOfAttachedFiles").'</td><td colspan="3">'.count($filearray).'</td></tr>'; print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td colspan="3">'.dol_print_size($totalsize, 1, 1).'</td></tr>'; print '</table>'; diff --git a/htdocs/product/stock/productlot_list.php b/htdocs/product/stock/productlot_list.php index e03de931a58..e04b3f2e59b 100644 --- a/htdocs/product/stock/productlot_list.php +++ b/htdocs/product/stock/productlot_list.php @@ -54,7 +54,9 @@ $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; @@ -72,28 +74,33 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Initialize array of search criterias $search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of array of fields for columns $arrayfields = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field if (!empty($val['visible'])) { $visible = dol_eval($val['visible'], 1); @@ -106,10 +113,8 @@ foreach ($object->fields as $key => $val) } } // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], @@ -124,9 +129,9 @@ if (is_array($extrafields->attributes[$object->table_element]['label']) && count $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); -$permissiontoread = $user->rights->stock->read; -$permissiontoadd = $user->rights->stock->write; -$permissiontodelete = $user->rights->stock->delete; +$permissiontoread = $user->rights->stock->lire; +$permissiontoadd = $user->rights->stock->mouvement->creer; +//$permissiontodelete = $user->rights->stock->supprimer; @@ -134,31 +139,33 @@ $permissiontodelete = $user->rights->stock->delete; * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($object->fields as $key => $val) - { + 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 + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $toselect = ''; $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -179,21 +186,22 @@ $form = new Form($db); $now = dol_now(); -//$help_url="EN:Module_MyObject|FR:Module_MyObject_FR|ES:Módulo_MyObject"; -$help_url = ''; +$help_url = 'EN:Module_Lot_/_Serial|FR:Module_Lot_/_Série'; + $title = $langs->trans('LotSerialList'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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.', ' : ''); + 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(); @@ -201,20 +209,32 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -else $sql .= " WHERE 1 = 1"; -foreach ($search as $key => $val) -{ - if ($key == 'status' && $search[$key] == -1) continue; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); if (strpos($object->fields[$key]['type'], 'integer:') === 0) { - if ($search[$key] == '-1') $search[$key] = ''; + if ($search[$key] == '-1') { + $search[$key] = ''; + } $mode_search = 2; } - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -244,26 +264,24 @@ $sql .= $db->order($sortfield, $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 || empty($limit))) -{ +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -272,8 +290,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$id); @@ -289,14 +306,24 @@ llxHeader('', $title, $help_url); $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ - if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); - else $param .= '&search_'.$key.'='.urlencode($search[$key]); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +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'; @@ -307,12 +334,18 @@ $arrayofmassactions = array( //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); -if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($permissiontodelete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -321,8 +354,7 @@ print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; //print '<input type="hidden" name="page" value="'.$page.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; -$newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/mymodule/myobject_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); -$newcardbutton = ''; +$newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/product/stock/productlot_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_'.$object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); @@ -333,9 +365,10 @@ $objecttmp = new Productlot($db); $trackid = 'lot'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } @@ -346,11 +379,13 @@ $moreforfilter = ''; $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -367,20 +402,26 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit // Fields title search // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - elseif (strpos($val['type'], 'integer:') === 0) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { + print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } print '</td>'; } } @@ -402,15 +443,18 @@ print '</tr>'."\n"; // Fields title label // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -427,11 +471,11 @@ print '</tr>'."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -440,34 +484,43 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->setVarsFromFetchObj($obj); // Show here line of result print '<tr class="oddeven">'; - foreach ($object->fields as $key => $val) - { + foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref' || $key == 'batch') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref' || $key == 'batch') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>'; - if ($key == 'status') print $object->getLibStatut(5); - elseif ($key == 'rowid') print $object->id; - else { + if ($key == 'status') { + print $object->getLibStatut(5); + } elseif ($key == 'rowid') { + print $object->id; + } else { if ($key == 'batch') { print $object->getNomUrl(1); } else { @@ -475,10 +528,13 @@ while ($i < ($limit ? min($num, $limit) : $num)) } } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $object->$key; } } @@ -491,14 +547,17 @@ while ($i < ($limit ? min($num, $limit) : $num)) print $hookmanager->resPrint; // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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($object->id, $arrayofselected)) $selected = 1; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'."\n"; @@ -509,10 +568,13 @@ while ($i < ($limit ? min($num, $limit) : $num)) include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } @@ -528,10 +590,11 @@ print '</div>'."\n"; print '</form>'."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/product/stock/replenish.php b/htdocs/product/stock/replenish.php index 64dd485671d..904fa9b7e94 100644 --- a/htdocs/product/stock/replenish.php +++ b/htdocs/product/stock/replenish.php @@ -68,7 +68,9 @@ $texte = ''; $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 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; @@ -86,8 +88,7 @@ if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE) - || !empty($conf->mrp->enabled)) -{ + || !empty($conf->mrp->enabled)) { $virtualdiffersfromphysical = 1; // According to increase/decrease stock options, virtual and physical stock may differs. } @@ -96,20 +97,25 @@ if ($virtualdiffersfromphysical) { } else { $usevirtualstock = 0; } -if ($mode == 'physical') $usevirtualstock = 0; -if ($mode == 'virtual') $usevirtualstock = 1; +if ($mode == 'physical') { + $usevirtualstock = 0; +} +if ($mode == 'virtual') { + $usevirtualstock = 1; +} $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'); +} /* * Actions */ -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') || GETPOST('valid')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') || GETPOST('valid')) { // Both test are required to be compatible with all browsers $search_ref = ''; $search_label = ''; $sall = ''; @@ -117,26 +123,24 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $includeproductswithoutdesiredqty = ''; $draftorder = ''; } -if ($draftorder == 'on') $draftchecked = "checked"; +if ($draftorder == 'on') { + $draftchecked = "checked"; +} // Create orders -if ($action == 'order' && GETPOST('valid')) -{ +if ($action == 'order' && GETPOST('valid')) { $linecount = GETPOST('linecount', 'int'); $box = 0; $errorQty = 0; unset($_POST['linecount']); - if ($linecount > 0) - { + if ($linecount > 0) { $db->begin(); $suppliers = array(); require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $productsupplier = new ProductFournisseur($db); - for ($i = 0; $i < $linecount; $i++) - { - if (GETPOST('choose'.$i, 'alpha') === 'on' && GETPOST('fourn'.$i, 'int') > 0) - { + for ($i = 0; $i < $linecount; $i++) { + if (GETPOST('choose'.$i, 'alpha') === 'on' && GETPOST('fourn'.$i, 'int') > 0) { //one line $box = $i; $supplierpriceid = GETPOST('fourn'.$i, 'int'); @@ -144,10 +148,8 @@ if ($action == 'order' && GETPOST('valid')) $qty = GETPOST('tobuy'.$i, 'int'); $idprod = $productsupplier->get_buyprice($supplierpriceid, $qty); $res = $productsupplier->fetch($idprod); - if ($res && $idprod > 0) - { - if ($qty) - { + if ($res && $idprod > 0) { + if ($qty) { //might need some value checks $line = new CommandeFournisseurLigne($db); $line->qty = $qty; @@ -155,8 +157,7 @@ if ($action == 'order' && GETPOST('valid')) //$product = new Product($db); //$product->fetch($obj->fk_product); - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { $productsupplier->getMultiLangs(); } @@ -167,8 +168,7 @@ if ($action == 'order' && GETPOST('valid')) $desc = $productsupplier->description; } $line->desc = $desc; - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { // TODO Get desc in language of thirdparty } @@ -184,8 +184,7 @@ if ($action == 'order' && GETPOST('valid')) $line->fk_unit = $productsupplier->fk_unit; $suppliers[$productsupplier->fourn_socid]['lines'][] = $line; } - } elseif ($idprod == -1) - { + } elseif ($idprod == -1) { $errorQty++; } else { $error = $db->lasterror(); @@ -202,8 +201,7 @@ if ($action == 'order' && GETPOST('valid')) $fail = 0; $orders = array(); $suppliersid = array_keys($suppliers); - foreach ($suppliers as $supplier) - { + foreach ($suppliers as $supplier) { $order = new CommandeFournisseur($db); // Check if an order for the supplier exists $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur"; @@ -267,10 +265,11 @@ if ($action == 'order' && GETPOST('valid')) } } - if ($errorQty) setEventMessages($langs->trans('ErrorOrdersNotCreatedQtyTooLow'), null, 'warnings'); + if ($errorQty) { + setEventMessages($langs->trans('ErrorOrdersNotCreatedQtyTooLow'), null, 'warnings'); + } - if (!$fail && $id) - { + if (!$fail && $id) { $db->commit(); setEventMessages($langs->trans('OrderCreated'), null, 'mesgs'); @@ -280,8 +279,7 @@ if ($action == 'order' && GETPOST('valid')) $db->rollback(); } } - if ($box == 0) - { + if ($box == 0) { setEventMessages($langs->trans('SelectProductWithNotNullQty'), null, 'warnings'); } } @@ -340,7 +338,9 @@ $reshook = $hookmanager->executeHooks('printFieldListJoin', $parameters); // Not $sql .= $hookmanager->resPrint; $sql .= ' WHERE p.entity IN ('.getEntity('product').')'; -if ($sall) $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); +if ($sall) { + $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); +} // if the type is not 1, we show all products (type = 0,2,3) if (dol_strlen($type)) { if ($type == 1) { @@ -349,8 +349,12 @@ if (dol_strlen($type)) { $sql .= ' AND p.fk_product_type <> 1'; } } -if ($search_ref) $sql .= natural_search('p.ref', $search_ref); -if ($search_label) $sql .= natural_search('p.label', $search_label); +if ($search_ref) { + $sql .= natural_search('p.ref', $search_ref); +} +if ($search_label) { + $sql .= natural_search('p.label', $search_label); +} $sql .= ' AND p.tobuy = 1'; if (empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) { // Add test to exclude products that has variants $sql .= ' AND p.rowid NOT IN (SELECT pac.fk_product_parent FROM '.MAIN_DB_PREFIX.'product_attribute_combination as pac WHERE pac.entity IN ('.getEntity('product').'))'; @@ -366,8 +370,7 @@ if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entre } $sql .= ', s.fk_product'; -if ($usevirtualstock) -{ +if ($usevirtualstock) { if (!empty($conf->commande->enabled)) { $sqlCommandesCli = "(SELECT ".$db->ifsql("SUM(cd1.qty) IS NULL", "0", "SUM(cd1.qty)")." as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL $sqlCommandesCli .= " FROM ".MAIN_DB_PREFIX."commandedet as cd1, ".MAIN_DB_PREFIX."commande as c1"; @@ -446,8 +449,7 @@ if ($usevirtualstock) $sql .= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.') + ('.$sqlProductionToProduce.' - '.$sqlProductionToConsume.')))'; $sql .= ')'; - if ($salert == 'on') // Option to see when stock is lower than alert - { + if ($salert == 'on') { // Option to see when stock is lower than alert $sql .= ' AND ('; if ($includeproductswithoutdesiredqty == 'on') { $sql .= '('.$sqlalertstock.' >= 0 OR '.$sqlalertstock.' IS NULL) AND ('.$db->ifsql("$sqlalertstock IS NULL", "0", $sqlalertstock).' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; @@ -469,8 +471,7 @@ if ($usevirtualstock) } $sql .= ')'; - if ($salert == 'on') // Option to see when stock is lower than alert - { + if ($salert == 'on') { // Option to see when stock is lower than alert $sql .= ' AND ('; if ($includeproductswithoutdesiredqty == 'on') { $sql .= ' ('.$sqlalertstock.' >= 0 OR '.$sqlalertstock.' IS NULL) AND ('.$db->ifsql("$sqlalertstock IS NULL", "0", $sqlalertstock).' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").'))'; @@ -507,8 +508,7 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if (empty($resql)) -{ +if (empty($resql)) { dol_print_error($db); exit; } @@ -541,15 +541,13 @@ if (empty($fk_warhouse) && !empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_ print '<span class="opacitymedium">'.$langs->trans("ReplenishmentStatusDescPerWarehouse").'</span>'."\n"; } print '<br><br>'; -if ($usevirtualstock == 1) -{ +if ($usevirtualstock == 1) { print $langs->trans("CurentSelectionMode").': '; print '<span class="a-mesure">'.$langs->trans("UseVirtualStock").'</span>'; print ' <a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?mode=physical'.($fk_supplier > 0 ? '&fk_supplier='.$fk_supplier : '').($fk_entrepot > 0 ? '&fk_entrepot='.$fk_entrepot : '').'">'.$langs->trans("UsePhysicalStock").'</a>'; print '<br>'; } -if ($usevirtualstock == 0) -{ +if ($usevirtualstock == 0) { print $langs->trans("CurentSelectionMode").': '; print '<a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?mode=virtual'.($fk_supplier > 0 ? '&fk_supplier='.$fk_supplier : '').($fk_entrepot > 0 ? '&fk_entrepot='.$fk_entrepot : '').'">'.$langs->trans("UseVirtualStock").'</a>'; print ' <span class="a-mesure">'.$langs->trans("UsePhysicalStock").'</span>'; @@ -569,8 +567,7 @@ print '<input type="hidden" name="mode" value="'.$mode.'">'; if ($limit > 0 && $limit != $conf->liste_limit) { print '<input type="hidden" name="limit" value="'.$limit.'">'; } -if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE)) -{ +if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE)) { print '<div class="inline-block valignmiddle" style="padding-right: 20px;">'; print $langs->trans('Warehouse').' '.$formproduct->selectWarehouses($fk_entrepot, 'fk_entrepot', '', 1); print '</div>'; @@ -581,7 +578,9 @@ print '</div>'; $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook -if (empty($reshook)) print $hookmanager->resPrint; +if (empty($reshook)) { + print $hookmanager->resPrint; +} print '<div class="inline-block valignmiddle">'; print '<input class="button" type="submit" name="valid" value="'.$langs->trans('ToFilter').'">'; @@ -607,8 +606,12 @@ if ($search_ref || $search_label || $sall || $salert || $draftorder || GETPOST(' $filters .= '&salert='.urlencode($salert); $filters .= '&draftorder='.urlencode($draftorder); $filters .= '&mode='.urlencode($mode); - if ($fk_supplier > 0) $filters .= '&fk_supplier='.urlencode($fk_supplier); - if ($fk_entrepot > 0) $filters .= '&fk_entrepot='.urlencode($fk_entrepot); + if ($fk_supplier > 0) { + $filters .= '&fk_supplier='.urlencode($fk_supplier); + } + if ($fk_entrepot > 0) { + $filters .= '&fk_entrepot='.urlencode($fk_entrepot); + } } else { $filters = '&search_ref='.urlencode($search_ref).'&search_label='.urlencode($search_label); $filters .= '&fourn_id='.urlencode($fourn_id); @@ -616,8 +619,12 @@ if ($search_ref || $search_label || $sall || $salert || $draftorder || GETPOST(' $filters .= '&='.urlencode($salert); $filters .= '&draftorder='.urlencode($draftorder); $filters .= '&mode='.urlencode($mode); - if ($fk_supplier > 0) $filters .= '&fk_supplier='.urlencode($fk_supplier); - if ($fk_entrepot > 0) $filters .= '&fk_entrepot='.urlencode($fk_entrepot); + if ($fk_supplier > 0) { + $filters .= '&fk_supplier='.urlencode($fk_supplier); + } + if ($fk_entrepot > 0) { + $filters .= '&fk_entrepot='.urlencode($fk_entrepot); + } } if ($limit > 0 && $limit != $conf->liste_limit) { $filters .= '&limit='.urlencode($limit); @@ -632,10 +639,13 @@ $param .= '&fk_entrepot='.urlencode($fk_entrepot); $stocklabel = $langs->trans('Stock'); $stocklabelbis = $langs->trans('Stock'); -if ($usevirtualstock == 1) $stocklabel = $langs->trans('VirtualStock'); -if ($usevirtualstock == 0) $stocklabel = $langs->trans('PhysicalStock'); -if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) -{ +if ($usevirtualstock == 1) { + $stocklabel = $langs->trans('VirtualStock'); +} +if ($usevirtualstock == 0) { + $stocklabel = $langs->trans('PhysicalStock'); +} +if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { $stocklabelbis = $stocklabel.' (Selected warehouse)'; $stocklabel .= ' ('.$langs->trans("AllWarehouses").')'; } @@ -684,12 +694,13 @@ print '<tr class="liste_titre_filter">'; print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre"><input class="flat" type="text" name="search_ref" size="8" value="'.dol_escape_htmltag($search_ref).'"></td>'; print '<td class="liste_titre"><input class="flat" type="text" name="search_label" size="8" value="'.dol_escape_htmltag($search_label).'"></td>'; -if (!empty($conf->service->enabled) && $type == 1) print '<td class="liste_titre">&nbsp;</td>'; +if (!empty($conf->service->enabled) && $type == 1) { + print '<td class="liste_titre">&nbsp;</td>'; +} print '<td class="liste_titre right">'.$form->textwithpicto($langs->trans('IncludeEmptyDesiredStock'), $langs->trans('IncludeProductWithUndefinedAlerts')).'&nbsp;<input type="checkbox" id="includeproductswithoutdesiredqty" name="includeproductswithoutdesiredqty" '.(!empty($includeproductswithoutdesiredqtychecked) ? $includeproductswithoutdesiredqtychecked : '').'></td>'; print '<td class="liste_titre right"></td>'; print '<td class="liste_titre right">'.$langs->trans('AlertOnly').'&nbsp;<input type="checkbox" id="salert" name="salert" '.(!empty($alertchecked) ? $alertchecked : '').'></td>'; -if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) -{ +if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { print '<td class="liste_titre">&nbsp;</td>'; } print '<td class="liste_titre right">'; @@ -714,12 +725,13 @@ print '<tr class="liste_titre">'; print_liste_field_titre('<input type="checkbox" onClick="toggle(this)" />', $_SERVER["PHP_SELF"], ''); print_liste_field_titre('Ref', $_SERVER["PHP_SELF"], 'p.ref', $param, '', '', $sortfield, $sortorder); print_liste_field_titre('Label', $_SERVER["PHP_SELF"], 'p.label', $param, '', '', $sortfield, $sortorder); -if (!empty($conf->service->enabled) && $type == 1) print_liste_field_titre('Duration', $_SERVER["PHP_SELF"], 'p.duration', $param, '', '', $sortfield, $sortorder, 'center '); +if (!empty($conf->service->enabled) && $type == 1) { + print_liste_field_titre('Duration', $_SERVER["PHP_SELF"], 'p.duration', $param, '', '', $sortfield, $sortorder, 'center '); +} print_liste_field_titre('DesiredStock', $_SERVER["PHP_SELF"], 'p.desiredstock', $param, '', '', $sortfield, $sortorder, 'right '); print_liste_field_titre('StockLimitShort', $_SERVER["PHP_SELF"], 'p.seuil_stock_alerte', $param, '', '', $sortfield, $sortorder, 'right '); print_liste_field_titre($stocklabel, $_SERVER["PHP_SELF"], 'stock_physique', $param, '', '', $sortfield, $sortorder, 'right '); -if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) -{ +if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { print_liste_field_titre($stocklabelbis, $_SERVER["PHP_SELF"], 'stock_real_warehouse', $param, '', '', $sortfield, $sortorder, 'right '); } print_liste_field_titre('Ordered', $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right '); @@ -733,18 +745,15 @@ print $hookmanager->resPrint; print "</tr>\n"; -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $objp = $db->fetch_object($resql); - if (!empty($conf->global->STOCK_SUPPORTS_SERVICES) || $objp->fk_product_type == 0) - { + if (!empty($conf->global->STOCK_SUPPORTS_SERVICES) || $objp->fk_product_type == 0) { $prod->fetch($objp->rowid); $prod->load_stock('warehouseopen, warehouseinternal', $draftchecked); // Multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { $sql = 'SELECT label,description'; $sql .= ' FROM '.MAIN_DB_PREFIX.'product_lang'; $sql .= ' WHERE fk_product = '.$objp->rowid; @@ -752,17 +761,19 @@ while ($i < ($limit ? min($num, $limit) : $num)) $sql .= ' LIMIT 1'; $resqlm = $db->query($sql); - if ($resqlm) - { + if ($resqlm) { $objtp = $db->fetch_object($resqlm); - if (!empty($objtp->description)) $objp->description = $objtp->description; - if (!empty($objtp->label)) $objp->label = $objtp->label; + if (!empty($objtp->description)) { + $objp->description = $objtp->description; + } + if (!empty($objtp->label)) { + $objp->label = $objtp->label; + } } } $stockwarehouse = 0; - if ($usevirtualstock) - { + if ($usevirtualstock) { // If option to increase/decrease is not on an object validation, virtual stock may differs from physical stock. $stock = $prod->stock_theorique; //TODO $stockwarehouse = $prod->stock_warehouse[$fk_entrepot]->; @@ -790,27 +801,30 @@ while ($i < ($limit ? min($num, $limit) : $num)) $alertstockwarehouse = ($objp->seuil_stock_alertepse ? $objp->seuil_stock_alertepse : 0); $warning = ''; - if ($alertstock && ($stock < $alertstock)) - { + if ($alertstock && ($stock < $alertstock)) { $warning = img_warning($langs->trans('StockTooLow')).' '; } $warningwarehouse = ''; - if ($alertstockwarehouse && ($stockwarehouse < $alertstockwarehouse)) - { + if ($alertstockwarehouse && ($stockwarehouse < $alertstockwarehouse)) { $warningwarehouse = img_warning($langs->trans('StockTooLow')).' '; } //depending on conf, use either physical stock or //virtual stock to compute the stock to buy value - if (empty($usevirtualstock)) $stocktobuy = max(max($desiredstock, $alertstock) - $stock - $ordered, 0); - else $stocktobuy = max(max($desiredstock, $alertstock) - $stock, 0); //ordered is already in $stock in virtual mode - if (empty($usevirtualstock)) $stocktobuywarehouse = max(max($desiredstockwarehouse, $alertstockwarehouse) - $stockwarehouse - $ordered, 0); - else $stocktobuywarehouse = max(max($desiredstockwarehouse, $alertstockwarehouse) - $stockwarehouse, 0); //ordered is already in $stock in virtual mode + if (empty($usevirtualstock)) { + $stocktobuy = max(max($desiredstock, $alertstock) - $stock - $ordered, 0); + } else { + $stocktobuy = max(max($desiredstock, $alertstock) - $stock, 0); //ordered is already in $stock in virtual mode + } + if (empty($usevirtualstock)) { + $stocktobuywarehouse = max(max($desiredstockwarehouse, $alertstockwarehouse) - $stockwarehouse - $ordered, 0); + } else { + $stocktobuywarehouse = max(max($desiredstockwarehouse, $alertstockwarehouse) - $stockwarehouse, 0); //ordered is already in $stock in virtual mode + } $picto = ''; - if ($ordered > 0) - { + if ($ordered > 0) { $stockforcompare = ($usevirtualstock ? $stock : $stock + $ordered); /*if ($stockforcompare >= $desiredstock) { @@ -833,8 +847,7 @@ while ($i < ($limit ? min($num, $limit) : $num)) print '<input type="hidden" name="desc'.$i.'" value="'.dol_escape_htmltag($objp->description).'">'; // TODO Remove this and make a fetch to get description when creating order instead of a GETPOST print '</td>'; - if (!empty($conf->service->enabled) && $type == 1) - { + if (!empty($conf->service->enabled) && $type == 1) { $regs = array(); if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) { $duration = $regs[1].' '.$langs->trans('DurationYear'); @@ -858,8 +871,7 @@ while ($i < ($limit ? min($num, $limit) : $num)) print '<td class="right">'.$warning.$stock.'</td>'; // Current stock (warehouse selected only) - if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) - { + if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { print '<td class="right">'.$warningwarehouse.$stockwarehouse.'</td>'; } diff --git a/htdocs/product/stock/replenishorders.php b/htdocs/product/stock/replenishorders.php index c73c7b1ca39..f5978313a1e 100644 --- a/htdocs/product/stock/replenishorders.php +++ b/htdocs/product/stock/replenishorders.php @@ -38,7 +38,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $langs->loadLangs(array('products', 'stocks', 'orders')); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'produit|service'); $sall = GETPOST('search_all', 'alphanohtml'); @@ -56,10 +58,16 @@ $search_date = dol_mktime(0, 0, 0, $search_datemonth, $search_dateday, $search_d $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -if (!$sortorder) $sortorder = 'DESC'; -if (!$sortfield) $sortfield = 'cf.date_creation'; +if (!$sortorder) { + $sortorder = 'DESC'; +} +if (!$sortfield) { + $sortfield = 'cf.date_creation'; +} $page = GETPOST('page', 'int') ? GETPOST('page', 'int') : 0; -if ($page < 0) $page = 0; +if ($page < 0) { + $page = 0; +} $offset = $limit * $page; @@ -67,8 +75,7 @@ $offset = $limit * $page; * Actions */ -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $sall = ""; $sref = ""; $snom = ""; @@ -130,13 +137,25 @@ if ($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) { if (!$user->rights->societe->client->voir && !$socid) { $sql .= ' AND s.rowid = sc.fk_soc AND sc.fk_user = '.$user->id; } -if ($sref) $sql .= natural_search('cf.ref', $sref); -if ($snom) $sql .= natural_search('s.nom', $snom); -if ($suser) $sql .= natural_search('u.login', $suser); -if ($sttc) $sql .= natural_search('cf.total_ttc', $sttc, 1); +if ($sref) { + $sql .= natural_search('cf.ref', $sref); +} +if ($snom) { + $sql .= natural_search('s.nom', $snom); +} +if ($suser) { + $sql .= natural_search('u.login', $suser); +} +if ($sttc) { + $sql .= natural_search('cf.total_ttc', $sttc, 1); +} $sql .= dolSqlDateFilter('cf.date_creation', $search_dateday, $search_datemonth, $search_dateyear); -if ($sall) $sql .= natural_search(array('cf.ref', 'cf.note'), $sall); -if (!empty($socid)) $sql .= ' AND s.rowid = '.$socid; +if ($sall) { + $sql .= natural_search(array('cf.ref', 'cf.note'), $sall); +} +if (!empty($socid)) { + $sql .= ' AND s.rowid = '.$socid; +} if (GETPOST('statut', 'int')) { $sql .= ' AND fk_statut = '.GETPOST('statut', 'int'); } @@ -148,8 +167,7 @@ if (!$search_product) { } $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -160,16 +178,36 @@ if ($resql) print_barre_liste('', $page, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', $num, 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 ($sref) $param .= '&search_ref='.urlencode($sref); - if ($snom) $param .= '&search_nom='.urlencode($snom); - if ($suser) $param .= '&search_user='.urlencode($suser); - if ($sttc) $param .= '&search_ttc='.urlencode($sttc); - if ($search_dateyear) $param .= '&search_dateyear='.urlencode($search_dateyear); - if ($search_datemonth) $param .= '&search_datemonth='.urlencode($search_datemonth); - if ($search_dateday) $param .= '&search_dateday='.urlencode($search_dateday); - 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 ($sref) { + $param .= '&search_ref='.urlencode($sref); + } + if ($snom) { + $param .= '&search_nom='.urlencode($snom); + } + if ($suser) { + $param .= '&search_user='.urlencode($suser); + } + if ($sttc) { + $param .= '&search_ttc='.urlencode($sttc); + } + if ($search_dateyear) { + $param .= '&search_dateyear='.urlencode($search_dateyear); + } + if ($search_datemonth) { + $param .= '&search_datemonth='.urlencode($search_datemonth); + } + if ($search_dateday) { + $param .= '&search_dateday='.urlencode($search_dateday); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } print '<table class="noborder centpercent">'; @@ -261,14 +299,12 @@ if ($resql) $userstatic = new User($db); - while ($i < min($num, $search_product ? $num : $conf->liste_limit)) - { + while ($i < min($num, $search_product ? $num : $conf->liste_limit)) { $obj = $db->fetch_object($resql); $showline = dolDispatchToDo($obj->rowid) && (!$search_product || in_array($search_product, getProducts($obj->rowid))); - if ($showline) - { + if ($showline) { $href = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$obj->rowid; print '<tr>'; diff --git a/htdocs/product/stock/stockatdate.php b/htdocs/product/stock/stockatdate.php index 91159984a35..cbdaa62014b 100644 --- a/htdocs/product/stock/stockatdate.php +++ b/htdocs/product/stock/stockatdate.php @@ -4,7 +4,7 @@ * Copyright (C) 2014 Regis Houssin <regis.houssin@inodbox.com> * Copyright (C) 2016 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2016 ATM Consulting <support@atm-consulting.fr> - * Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -71,7 +71,9 @@ $fk_warehouse = GETPOST('fk_warehouse', 'int'); $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 $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; if (!$sortfield) { @@ -83,7 +85,9 @@ if (!$sortorder) { $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'); +} $dateIsValid = true; if ($mode == 'future') { @@ -103,8 +107,7 @@ if ($mode == 'future') { * Actions */ -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $date = ''; $productid = 0; $fk_warehouse = 0; @@ -142,8 +145,7 @@ if ($date && $dateIsValid) { // Avoid heavy sql if mandatory date is not defined //print $sql; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -197,8 +199,7 @@ if ($date && $dateIsValid) { $sql .= " GROUP BY sm.fk_product, sm.fk_entrepot"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -243,9 +244,12 @@ $title = $langs->trans('StockAtDate'); $sql = 'SELECT p.rowid, p.ref, p.label, p.description, p.price,'; $sql .= ' p.price_ttc, p.price_base_type, p.fk_product_type, p.desiredstock, p.seuil_stock_alerte,'; -$sql .= ' p.tms as datem, p.duration, p.tobuy, p.stock'; +$sql .= ' p.tms as datem, p.duration, p.tobuy, p.stock, '; if ($fk_warehouse > 0) { + $sql .= " SUM(p.pmp * ps.reel) as estimatedvalue, SUM(p.price * ps.reel) as sellvalue"; $sql .= ', SUM(ps.reel) as stock_reel'; +} else { + $sql .= " SUM(p.pmp * p.stock) as estimatedvalue, SUM(p.price * p.stock) as sellvalue"; } // Add fields from hooks $parameters = array(); @@ -267,10 +271,15 @@ if ($productid > 0) { if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $sql .= " AND p.fk_product_type = 0"; } -if (!empty($canvas)) $sql .= ' AND p.canvas = "'.$db->escape($canvas).'"'; +if (!empty($canvas)) { + $sql .= ' AND p.canvas = "'.$db->escape($canvas).'"'; +} if ($fk_warehouse > 0) { $sql .= ' GROUP BY p.rowid, p.ref, p.label, p.description, p.price, p.price_ttc, p.price_base_type, p.fk_product_type, p.desiredstock, p.seuil_stock_alerte,'; $sql .= ' p.tms, p.duration, p.tobuy, p.stock'; +} else { + $sql .= ' GROUP BY p.rowid, p.ref, p.label, p.description, p.price, p.price_ttc, p.price_base_type, p.fk_product_type, p.desiredstock, p.seuil_stock_alerte,'; + $sql .= ' p.tms, p.duration, p.tobuy, p.stock'; } // Add where from hooks $parameters = array(); @@ -287,12 +296,10 @@ $sql .= $db->order($sortfield, $sortorder); if ($date && $dateIsValid) { // We avoid a heavy sql if mandatory parameter date not yet defined $nbtotalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -302,8 +309,7 @@ if ($date && $dateIsValid) { // We avoid a heavy sql if mandatory parameter date //print $sql; $resql = $db->query($sql); - if (empty($resql)) - { + if (empty($resql)) { dol_print_error($db); exit; } @@ -335,7 +341,9 @@ print load_fiche_titre($langs->trans('StockAtDate'), '', 'stock'); print dol_get_fiche_head($head, ($mode == 'future' ? 'stockatdatefuture' : 'stockatdatepast'), '', -1, ''); $desc = $langs->trans("StockAtDatePastDesc"); -if ($mode == 'future') $desc = $langs->trans("StockAtDateFutureDesc"); +if ($mode == 'future') { + $desc = $langs->trans("StockAtDateFutureDesc"); +} print '<span class="opacitymedium">'.$desc.'</span><br>'."\n"; print '<br>'."\n"; @@ -347,12 +355,12 @@ print '<input type="hidden" name="mode" value="'.$mode.'">'; print '<div class="inline-block valignmiddle" style="padding-right: 20px;">'; print '<span class="fieldrequired">'.$langs->trans('Date').'</span> '.$form->selectDate(($date ? $date : -1), 'date'); -print ' <span class="clearbothonsmartphone marginleftonly paddingleftonly marginrightonly paddinrightonly">&nbsp;</span> '; +print ' <span class="clearbothonsmartphone marginleftonly paddingleftonly marginrightonly paddingrightonly">&nbsp;</span> '; print img_picto('', 'product').' '; print $langs->trans('Product').'</span> '; $form->select_produits($productid, 'productid', '', 0, 0, -1, 2, '', 0, array(), 0, '1', 0, 'maxwidth300'); -print ' <span class="clearbothonsmartphone marginleftonly paddingleftonly marginrightonly paddinrightonly">&nbsp;</span> '; +print ' <span class="clearbothonsmartphone marginleftonly paddingleftonly marginrightonly paddingrightonly">&nbsp;</span> '; print img_picto('', 'stock').' '; print $langs->trans('Warehouse').'</span> '; print $formproduct->selectWarehouses((GETPOSTISSET('fk_warehouse') ? $fk_warehouse : 'ifone'), 'fk_warehouse', '', 1); @@ -360,7 +368,9 @@ print '</div>'; $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook -if (empty($reshook)) print $hookmanager->resPrint; +if (empty($reshook)) { + print $hookmanager->resPrint; +} print '<div class="inline-block valignmiddle">'; print '<input class="button" type="submit" name="valid" value="'.$langs->trans('Refresh').'">'; @@ -369,14 +379,28 @@ print '</div>'; //print '</form>'; $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 .= '&mode='.$mode; -if ($fk_warehouse > 0) $param .= '&fk_warehouse='.$fk_warehouse; -if ($productid > 0) $param .= '&productid='.$productid; -if (GETPOST('dateday', 'int') > 0) $param .= '&dateday='.GETPOST('dateday', 'int'); -if (GETPOST('datemonth', 'int') > 0) $param .= '&datemonth='.GETPOST('datemonth', 'int'); -if (GETPOST('dateyear', 'int') > 0) $param .= '&dateyear='.GETPOST('dateyear', 'int'); +if ($fk_warehouse > 0) { + $param .= '&fk_warehouse='.$fk_warehouse; +} +if ($productid > 0) { + $param .= '&productid='.$productid; +} +if (GETPOST('dateday', 'int') > 0) { + $param .= '&dateday='.GETPOST('dateday', 'int'); +} +if (GETPOST('datemonth', 'int') > 0) { + $param .= '&datemonth='.GETPOST('datemonth', 'int'); +} +if (GETPOST('dateyear', 'int') > 0) { + $param .= '&dateyear='.GETPOST('dateyear', 'int'); +} // TODO Move this into the title line ? print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'stock', 0, '', '', $limit, 0, 0, 1); @@ -385,7 +409,9 @@ print '<div class="div-table-responsive">'; // You can use div-table-responsive- print '<table class="liste centpercent">'; $stocklabel = $langs->trans('StockAtDate'); -if ($mode == 'future') $stocklabel = $langs->trans("VirtualStockAtDate"); +if ($mode == 'future') { + $stocklabel = $langs->trans("VirtualStockAtDate"); +} //print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formulaire">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -403,6 +429,9 @@ print '<td class="liste_titre"></td>'; print '<td class="liste_titre"></td>'; if ($mode == 'future') { print '<td class="liste_titre"></td>'; +} else { + print '<td class="liste_titre"></td>'; + print '<td class="liste_titre"></td>'; } // Fields from hook $parameters = array('param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); @@ -424,6 +453,7 @@ if ($fk_warehouse > 0) { print '<tr class="liste_titre">'; print_liste_field_titre('Ref', $_SERVER["PHP_SELF"], 'p.ref', $param, '', '', $sortfield, $sortorder); print_liste_field_titre('Label', $_SERVER["PHP_SELF"], 'p.label', $param, '', '', $sortfield, $sortorder); + if ($mode == 'future') { print_liste_field_titre('CurrentStock', $_SERVER["PHP_SELF"], $fieldtosortcurrentstock, $param, '', '', $sortfield, $sortorder, 'right '); print_liste_field_titre('', $_SERVER["PHP_SELF"]); @@ -431,6 +461,8 @@ if ($mode == 'future') { print_liste_field_titre('VirtualStock', $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right ', 'VirtualStockDesc'); } else { print_liste_field_titre($stocklabel, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right '); + print_liste_field_titre("EstimatedStockValue", $_SERVER["PHP_SELF"], "estimatedvalue", '', $param, '', $sortfield, $sortorder, 'right ', $langs->trans("AtDate"), 1); + print_liste_field_titre("EstimatedStockValueSell", $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', $langs->trans("AtDate"), 1); print_liste_field_titre('', $_SERVER["PHP_SELF"]); print_liste_field_titre('CurrentStock', $_SERVER["PHP_SELF"], $fieldtosortcurrentstock, $param, '', '', $sortfield, $sortorder, 'right '); } @@ -444,12 +476,10 @@ print $hookmanager->resPrint; print "</tr>\n"; $i = 0; -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $objp = $db->fetch_object($resql); - if (!empty($conf->global->STOCK_SUPPORTS_SERVICES) || $objp->fk_product_type == 0) - { + if (!empty($conf->global->STOCK_SUPPORTS_SERVICES) || $objp->fk_product_type == 0) { $prod->fetch($objp->rowid); // Multilangs @@ -471,8 +501,7 @@ while ($i < ($limit ? min($num, $limit) : $num)) }*/ $currentstock = ''; - if ($fk_warehouse > 0) - { + if ($fk_warehouse > 0) { //if ($productid > 0) { $currentstock = $stock_prod_warehouse[$objp->rowid][$fk_warehouse]; //} else { @@ -531,6 +560,25 @@ while ($i < ($limit ? min($num, $limit) : $num)) // Stock at date print '<td class="right">'.($stock ? $stock : '<span class="opacitymedium">'.$stock.'</span>').'</td>'; + // PMP value + print '<td class="right">'; + if (price2num($objp->estimatedvalue, 'MT')) { + print price(price2num($objp->estimatedvalue, 'MT'), 1); + } else { + print ''; + } + print '</td>'; + + // Selling value + print '<td class="right">'; + if (empty($conf->global->PRODUIT_MULTIPRICES)) { + print price(price2num($objp->sellvalue, 'MT'), 1); + } else { + $htmltext = $langs->trans("OptionMULTIPRICESIsOn"); + print $form->textwithtooltip($langs->trans("Variable"), $htmltext); + } + print'</td>'; + print '<td class="right">'; if ($nbofmovement > 0) { print '<a href="'.DOL_URL_ROOT.'/product/stock/movement_list.php?idproduct='.$objp->rowid.($fk_warehouse > 0 ? '&search_warehouse='.$fk_warehouse : '').'">'.$langs->trans("Movements").'</a>'; @@ -560,8 +608,10 @@ $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // N print $hookmanager->resPrint; if (empty($date) || ! $dateIsValid) { - $colspan = 6; - if ($mode == 'future') $colspan++; + $colspan = 8; + if ($mode == 'future') { + $colspan++; + } print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("EnterADateCriteria").'</span></td></tr>'; } diff --git a/htdocs/product/stock/tpl/stockcorrection.tpl.php b/htdocs/product/stock/tpl/stockcorrection.tpl.php index 4f88b448239..6e2ab53dd0e 100644 --- a/htdocs/product/stock/tpl/stockcorrection.tpl.php +++ b/htdocs/product/stock/tpl/stockcorrection.tpl.php @@ -30,12 +30,16 @@ if (empty($conf) || !is_object($conf)) { <!-- BEGIN PHP TEMPLATE STOCKCORRECTION.TPL.PHP --> <?php $productref = ''; -if ($object->element == 'product') $productref = $object->ref; +if ($object->element == 'product') { + $productref = $object->ref; +} $langs->load("productbatch"); -if (empty($id)) $id = $object->id; +if (empty($id)) { + $id = $object->id; +} print '<script type="text/javascript" language="javascript"> jQuery(document).ready(function() { @@ -69,7 +73,9 @@ if ($object->element == 'product') { print '<td class="fieldrequired">'.$langs->trans("Warehouse").'</td>'; print '<td>'; $ident = (GETPOST("dwid") ?GETPOST("dwid", 'int') : (GETPOST('id_entrepot') ? GETPOST('id_entrepot', 'int') : ($object->element == 'product' && $object->fk_default_warehouse ? $object->fk_default_warehouse : 'ifone'))); - if (empty($ident) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) $ident = $conf->global->MAIN_DEFAULT_WAREHOUSE; + if (empty($ident) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) { + $ident = $conf->global->MAIN_DEFAULT_WAREHOUSE; + } print img_picto('', 'stock').$formproduct->selectWarehouses($ident, 'id_entrepot', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'minwidth100'); print ' &nbsp; <select class="button buttongen" name="mouvement" id="mouvement">'; print '<option value="0">'.$langs->trans("Add").'</option>'; @@ -107,8 +113,7 @@ if (!empty($conf->global->PRODUIT_SOUSPRODUITS) && $object->element == 'product' if (!empty($conf->productbatch->enabled) && (($object->element == 'product' && $object->hasbatch()) || ($object->element == 'stock')) -) -{ +) { print '<tr>'; print '<td'.($object->element == 'stock' ? '' : ' class="fieldrequired"').'>'.$langs->trans("batch_number").'</td><td colspan="3">'; print '<input type="text" name="batch_number" size="40" value="'.GETPOST("batch_number").'">'; @@ -134,8 +139,7 @@ if (!empty($conf->productbatch->enabled) && print '<tr>'; print '<td>'.$langs->trans("UnitPurchaseValue").'</td>'; print '<td colspan="'.(!empty($conf->projet->enabled) ? '1' : '3').'"><input name="unitprice" id="unitprice" size="10" value="'.GETPOST("unitprice").'"></td>'; -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { print '<td>'.$langs->trans('Project').'</td>'; print '<td>'; print img_picto('', 'project'); diff --git a/htdocs/product/stock/tpl/stocktransfer.tpl.php b/htdocs/product/stock/tpl/stocktransfer.tpl.php index 20445445e8e..e98244e5eed 100644 --- a/htdocs/product/stock/tpl/stocktransfer.tpl.php +++ b/htdocs/product/stock/tpl/stocktransfer.tpl.php @@ -30,21 +30,23 @@ if (empty($conf) || !is_object($conf)) { <!-- BEGIN PHP TEMPLATE STOCKCORRECTION.TPL.PHP --> <?php $productref = ''; -if ($object->element == 'product') $productref = $object->ref; +if ($object->element == 'product') { + $productref = $object->ref; +} $langs->load("productbatch"); -if (empty($id)) $id = $object->id; +if (empty($id)) { + $id = $object->id; +} $pdluoid = GETPOST('pdluoid', 'int'); $pdluo = new Productbatch($db); -if ($pdluoid > 0) -{ +if ($pdluoid > 0) { $result = $pdluo->fetch($pdluoid); - if ($result > 0) - { + if ($result > 0) { $pdluoid = $pdluo->id; } else { dol_print_error($db, $pdluo->error, $pdluo->errors); @@ -60,8 +62,7 @@ print dol_get_fiche_head(); print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="transfert_stock">'; print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; -if ($pdluoid) -{ +if ($pdluoid) { print '<input type="hidden" name="pdluoid" value="'.$pdluoid.'">'; } print '<table class="border centpercent">'; @@ -92,12 +93,10 @@ print '</tr>'; if (!empty($conf->productbatch->enabled) && (($object->element == 'product' && $object->hasbatch()) || ($object->element == 'stock')) -) -{ +) { print '<tr>'; print '<td'.($object->element == 'stock' ? '' : ' class="fieldrequired"').'>'.$langs->trans("batch_number").'</td><td colspan="3">'; - if ($pdluoid > 0) - { + if ($pdluoid > 0) { // If form was opened for a specific pdluoid, field is disabled print '<input type="text" name="batch_number_bis" size="40" disabled="disabled" value="'.(GETPOST('batch_number') ?GETPOST('batch_number') : $pdluo->batch).'">'; print '<input type="hidden" name="batch_number" value="'.(GETPOST('batch_number') ?GETPOST('batch_number') : $pdluo->batch).'">'; diff --git a/htdocs/product/stock/valo.php b/htdocs/product/stock/valo.php index 35e82abdafc..7f7f9610d1f 100644 --- a/htdocs/product/stock/valo.php +++ b/htdocs/product/stock/valo.php @@ -38,10 +38,16 @@ $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -if (!$sortfield) $sortfield = "e.ref"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "e.ref"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} $page = $_GET["page"]; -if ($page < 0) $page = 0; +if ($page < 0) { + $page = 0; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; @@ -58,9 +64,10 @@ $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON e.rowid = ps.fk_entrepot"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON ps.fk_product = p.rowid"; $sql .= " WHERE e.entity IN (".getEntity('stock').")"; -if ($sref) $sql .= natural_search("e.ref", $sref); -if ($sall) -{ +if ($sref) { + $sql .= natural_search("e.ref", $sref); +} +if ($sall) { $sql .= " AND (e.ref LIKE '%".$db->escape($sall)."%'"; $sql .= " OR e.description LIKE '%".$db->escape($sall)."%'"; $sql .= " OR e.lieu LIKE '%".$db->escape($sall)."%'"; @@ -72,8 +79,7 @@ $sql .= $db->order($sortfield, $sortorder); $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; @@ -92,26 +98,30 @@ if ($result) print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "e.statut", '', '', '', $sortfield, $sortorder, 'right '); print "</tr>\n"; - if ($num) - { + if ($num) { $entrepot = new Entrepot($db); $total = $totalsell = 0; $var = false; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($result); print '<tr class="oddeven">'; print '<td><a href="card.php?id='.$objp->rowid.'">'.img_object($langs->trans("ShowWarehouse"), 'stock').' '.$objp->ref.'</a></td>'; print '<td>'.$objp->lieu.'</td>'; // PMP value print '<td class="right">'; - if (price2num($objp->estimatedvalue, 'MT')) print price(price2num($objp->estimatedvalue, 'MT'), 1); - else print ''; + if (price2num($objp->estimatedvalue, 'MT')) { + print price(price2num($objp->estimatedvalue, 'MT'), 1); + } else { + print ''; + } print '</td>'; // Selling value print '<td class="right">'; - if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($objp->sellvalue, 'MT'), 1); - else print $langs->trans("Variable"); + if (empty($conf->global->PRODUIT_MULTIPRICES)) { + print price(price2num($objp->sellvalue, 'MT'), 1); + } else { + print $langs->trans("Variable"); + } print '</td>'; // Status print '<td class="right">'.$entrepot->LibStatut($objp->statut, 5).'</td>'; @@ -137,15 +147,13 @@ if ($result) print '<br>'; $file = 'entrepot-'.$year.'.png'; - if (file_exists($conf->stock->dir_temp.'/'.$file)) - { + if (file_exists($conf->stock->dir_temp.'/'.$file)) { $url = DOL_URL_ROOT.'/viewimage.php?modulepart=graph_stock&amp;file='.$file; print '<img src="'.$url.'">'; } $file = 'entrepot-'.($year - 1).'.png'; - if (file_exists($conf->stock->dir_temp.'/'.$file)) - { + if (file_exists($conf->stock->dir_temp.'/'.$file)) { $url = DOL_URL_ROOT.'/viewimage.php?modulepart=graph_stock&amp;file='.$file; print '<br><img src="'.$url.'">'; } diff --git a/htdocs/product/traduction.php b/htdocs/product/traduction.php index 97eb37a2689..45b45136410 100644 --- a/htdocs/product/traduction.php +++ b/htdocs/product/traduction.php @@ -42,7 +42,9 @@ $cancel = GETPOST('cancel', 'alpha'); // 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; +} $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); @@ -51,41 +53,46 @@ $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product */ // retour a l'affichage des traduction si annulation -if ($cancel == $langs->trans("Cancel")) -{ +if ($cancel == $langs->trans("Cancel")) { $action = ''; } -if ($action == 'delete' && GETPOST('langtodelete', 'alpha')) -{ +if ($action == 'delete' && GETPOST('langtodelete', 'alpha')) { $object = new Product($db); $object->fetch($id); $object->delMultiLangs(GETPOST('langtodelete', 'alpha'), $user); + setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); + $action = ''; } // Add translation -if ($action == 'vadd' && -$cancel != $langs->trans("Cancel") && -($user->rights->produit->creer || $user->rights->service->creer)) -{ +if ($action == 'vadd' && $cancel != $langs->trans("Cancel") && ($user->rights->produit->creer || $user->rights->service->creer)) { $object = new Product($db); $object->fetch($id); $current_lang = $langs->getDefaultLang(); // update de l'objet - if ($_POST["forcelangprod"] == $current_lang) { - $object->label = $_POST["libelle"]; - $object->description = dol_htmlcleanlastbr($_POST["desc"]); - $object->other = dol_htmlcleanlastbr($_POST["other"]); + if (GETPOST("forcelangprod") == $current_lang) { + $object->label = GETPOST("libelle"); + $object->description = dol_htmlcleanlastbr(GETPOST("desc", 'restricthtml')); + $object->other = dol_htmlcleanlastbr(GETPOST("other", 'restricthtml')); + $object->update($object->id, $user); } else { - $object->multilangs[$_POST["forcelangprod"]]["label"] = $_POST["libelle"]; - $object->multilangs[$_POST["forcelangprod"]]["description"] = dol_htmlcleanlastbr($_POST["desc"]); - $object->multilangs[$_POST["forcelangprod"]]["other"] = dol_htmlcleanlastbr($_POST["other"]); + $object->multilangs[GETPOST("forcelangprod")]["label"] = GETPOST("libelle"); + $object->multilangs[GETPOST("forcelangprod")]["description"] = dol_htmlcleanlastbr(GETPOST("desc", 'restricthtml')); + $object->multilangs[GETPOST("forcelangprod")]["other"] = dol_htmlcleanlastbr(GETPOST("other", 'restricthtml')); } - // sauvegarde en base - if ($object->setMultiLangs($user) > 0) { + // save in database + if (GETPOST("forcelangprod")) { + $result = $object->setMultiLangs($user); + } else { + $object->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Language")); + $result = -1; + } + + if ($result > 0) { $action = ''; } else { $action = 'add'; @@ -94,30 +101,25 @@ $cancel != $langs->trans("Cancel") && } // Edit translation -if ($action == 'vedit' && -$cancel != $langs->trans("Cancel") && -($user->rights->produit->creer || $user->rights->service->creer)) -{ +if ($action == 'vedit' && $cancel != $langs->trans("Cancel") && ($user->rights->produit->creer || $user->rights->service->creer)) { $object = new Product($db); $object->fetch($id); $current_lang = $langs->getDefaultLang(); - foreach ($object->multilangs as $key => $value) // enregistrement des nouvelles valeurs dans l'objet - { - if ($key == $current_lang) - { - $object->label = $_POST["libelle-".$key]; - $object->description = dol_htmlcleanlastbr($_POST["desc-".$key]); - $object->other = dol_htmlcleanlastbr($_POST["other-".$key]); + foreach ($object->multilangs as $key => $value) { // enregistrement des nouvelles valeurs dans l'objet + if ($key == $current_lang) { + $object->label = GETPOST("libelle-".$key); + $object->description = dol_htmlcleanlastbr(GETPOST("desc-".$key, 'restricthtml')); + $object->other = dol_htmlcleanlastbr(GETPOST("other-".$key, 'restricthtml')); } else { - $object->multilangs[$key]["label"] = $_POST["libelle-".$key]; - $object->multilangs[$key]["description"] = dol_htmlcleanlastbr($_POST["desc-".$key]); - $object->multilangs[$key]["other"] = dol_htmlcleanlastbr($_POST["other-".$key]); + $object->multilangs[$key]["label"] = GETPOST("libelle-".$key); + $object->multilangs[$key]["description"] = dol_htmlcleanlastbr(GETPOST("desc-".$key, 'restricthtml')); + $object->multilangs[$key]["other"] = dol_htmlcleanlastbr(GETPOST("other-".$key, 'restricthtml')); } } - if ($object->setMultiLangs($user) > 0) - { + $result = $object->setMultiLangs($user); + if ($result > 0) { $action = ''; } else { $action = 'edit'; @@ -126,17 +128,13 @@ $cancel != $langs->trans("Cancel") && } // Delete translation -if ($action == 'vdelete' && -$cancel != $langs->trans("Cancel") && -($user->rights->produit->creer || $user->rights->service->creer)) -{ +if ($action == 'vdelete' && $cancel != $langs->trans("Cancel") && ($user->rights->produit->creer || $user->rights->service->creer)) { $object = new Product($db); $object->fetch($id); $langtodelete = GETPOST('langdel', 'alpha'); - - if ($object->delMultiLangs($langtodelete, $user) > 0) - { + $result = $object->delMultiLangs($langtodelete, $user); + if ($result > 0) { $action = ''; } else { $action = 'edit'; @@ -155,13 +153,11 @@ $result = $object->fetch($id, $ref); $title = $langs->trans('ProductServiceCard'); $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); -if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) -{ +if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Translation'); $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; } -if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) -{ +if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Translation'); $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; } @@ -178,10 +174,8 @@ $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); // Calculate $cnt_trans $cnt_trans = 0; -if (!empty($object->multilangs)) -{ - foreach ($object->multilangs as $key => $value) - { +if (!empty($object->multilangs)) { + foreach ($object->multilangs as $key => $value) { $cnt_trans++; } } @@ -192,7 +186,9 @@ print dol_get_fiche_head($head, 'translation', $titre, 0, $picto); $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; -if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; +if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; +} dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', '', '', '', 0, '', '', 1); @@ -200,29 +196,25 @@ print dol_get_fiche_end(); -/* ************************************************************************** */ -/* */ -/* Barre d'action */ -/* */ -/* ************************************************************************** */ +/* + * Action bar + */ +print "\n".'<div class="tabsAction">'."\n"; -print "\n<div class=\"tabsAction\">\n"; - -if ($action == '') -{ - if ($user->rights->produit->creer || $user->rights->service->creer) - { +if ($action == '') { + if ($user->rights->produit->creer || $user->rights->service->creer) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/product/traduction.php?action=add&id='.$object->id.'">'.$langs->trans("Add").'</a>'; - if ($cnt_trans > 0) print '<a class="butAction" href="'.DOL_URL_ROOT.'/product/traduction.php?action=edit&id='.$object->id.'">'.$langs->trans("Update").'</a>'; + if ($cnt_trans > 0) { + print '<a class="butAction" href="'.DOL_URL_ROOT.'/product/traduction.php?action=edit&id='.$object->id.'">'.$langs->trans("Update").'</a>'; + } } } -print "\n</div>\n"; +print "\n".'</div>'."\n"; -if ($action == 'edit') -{ +if ($action == 'edit') { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -231,12 +223,13 @@ if ($action == 'edit') print '<input type="hidden" name="action" value="vedit">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; - if (!empty($object->multilangs)) - { - foreach ($object->multilangs as $key => $value) - { + if (!empty($object->multilangs)) { + $i = 0; + foreach ($object->multilangs as $key => $value) { + $i++; + $s = picto_from_langcode($key); - print "<br>".($s ? $s.' ' : '')." <b>".$langs->trans('Language_'.$key).":</b> ".'<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'&langtodelete='.$key.'">'.img_delete('', 'class="valigntextbottom"')."</a><br>"; + print ($i > 1 ? "<br>" : "").($s ? $s.' ' : '').' <div class="inline-block margintop marginbottomonly"><b>'.$langs->trans('Language_'.$key).'</b></div><div class="inline-block floatright"><a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'&langtodelete='.$key.'">'.img_delete('', 'class="valigntextbottom marginrightonly"').'</a></div>'; print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent">'; @@ -245,8 +238,7 @@ if ($action == 'edit') $doleditor = new DolEditor("desc-$key", $object->multilangs[$key]["description"], '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); $doleditor->Create(); print '</td></tr>'; - if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) - { + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { print '<tr><td class="tdtop">'.$langs->trans('Other').' ('.$langs->trans("NotUsed").')</td><td>'; $doleditor = new DolEditor("other-$key", $object->multilangs[$key]["other"], '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); $doleditor->Create(); @@ -265,29 +257,30 @@ if ($action == 'edit') print '</div>'; print '</form>'; -} elseif ($action != 'add') -{ - if (!empty($object->multilangs)) - { - foreach ($object->multilangs as $key => $value) - { +} elseif ($action != 'add') { + if (!empty($object->multilangs)) { + $i = 0; + foreach ($object->multilangs as $key => $value) { + $i++; + $s = picto_from_langcode($key); - print ($s ? $s.' ' : '')." <b>".$langs->trans('Language_'.$key).":</b> ".'<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'&langtodelete='.$key.'">'.img_delete('', 'class="valigntextbottom"').'</a>'; + print ($i > 1 ? "<br>" : "").($s ? $s.' ' : '').' <div class="inline-block marginbottomonly"><b>'.$langs->trans('Language_'.$key).'</b></div><div class="inline-block floatright"><a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'&langtodelete='.$key.'">'.img_delete('', 'class="valigntextbottom marginrightonly"').'</a></div>'; print '<div class="fichecenter">'; print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent">'; print '<tr><td class="titlefieldcreate">'.$langs->trans('Label').'</td><td>'.$object->multilangs[$key]["label"].'</td></tr>'; print '<tr><td class="tdtop">'.$langs->trans('Description').'</td><td>'.$object->multilangs[$key]["description"].'</td></tr>'; - if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) - { + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { print '<tr><td>'.$langs->trans('Other').' ('.$langs->trans("NotUsed").')</td><td>'.$object->multilangs[$key]["other"].'</td></tr>'; } print '</table>'; print '</div>'; } } - if (!$cnt_trans && $action != 'add') print '<div class="opacitymedium">'.$langs->trans('NoTranslation').'</div>'; + if (!$cnt_trans && $action != 'add') { + print '<div class="opacitymedium">'.$langs->trans('NoTranslation').'</div>'; + } } @@ -296,8 +289,7 @@ if ($action == 'edit') * Form to add a new translation */ -if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service->creer)) -{ +if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service->creer)) { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -311,7 +303,7 @@ if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service print '<table class="border centpercent">'; print '<tr><td class="tdtop titlefieldcreate fieldrequired">'.$langs->trans('Language').'</td><td>'; - print $formadmin->select_language('', 'forcelangprod', 0, $object->multilangs, 1); + print $formadmin->select_language(GETPOST('forcelangprod'), 'forcelangprod', 0, $object->multilangs, 1); print '</td></tr>'; print '<tr><td class="tdtop fieldrequired">'.$langs->trans('Label').'</td><td><input name="libelle" size="40"></td></tr>'; print '<tr><td class="tdtop">'.$langs->trans('Description').'</td><td>'; @@ -319,8 +311,7 @@ if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service $doleditor->Create(); print '</td></tr>'; // Other field (not used) - if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) - { + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { print '<tr><td class="tdtop">'.$langs->trans('Other').' ('.$langs->trans("NotUsed").'</td><td>'; $doleditor = new DolEditor('other', '', '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); $doleditor->Create(); diff --git a/htdocs/projet/activity/index.php b/htdocs/projet/activity/index.php index 2ca149a18ca..c49ca736bbb 100644 --- a/htdocs/projet/activity/index.php +++ b/htdocs/projet/activity/index.php @@ -32,13 +32,19 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $search_project_user = GETPOST('search_project_user', 'int'); $mine = GETPOST('mode', 'aZ09') == 'mine' ? 1 : 0; -if ($search_project_user == $user->id) $mine = 1; +if ($search_project_user == $user->id) { + $mine = 1; +} // Security check $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} //$result = restrictedArea($user, 'projet', $projectid); -if (!$user->rights->projet->lire) accessforbidden(); +if (!$user->rights->projet->lire) { + accessforbidden(); +} $hookmanager = new HookManager($db); @@ -73,8 +79,11 @@ llxHeader("", $title); // Title for combo list see all projects $titleall = $langs->trans("AllAllowedProjects"); -if (!empty($user->rights->projet->all->lire) && !$socid) $titleall = $langs->trans("AllProjects"); -else $titleall = $langs->trans("AllAllowedProjects").'<br><br>'; +if (!empty($user->rights->projet->all->lire) && !$socid) { + $titleall = $langs->trans("AllProjects"); +} else { + $titleall = $langs->trans("AllAllowedProjects").'<br><br>'; +} $morehtml = ''; @@ -85,10 +94,14 @@ $morehtml .= '<option name="mine" value="'.$user->id.'"'.(($search_project_user $morehtml .= '</SELECT>'; $morehtml .= '<input type="submit" class="button" name="refresh" value="'.$langs->trans("Refresh").'">'; -if ($mine) $tooltiphelp = $langs->trans("MyTasksDesc"); -else { - if ($user->rights->projet->all->lire && !$socid) $tooltiphelp = $langs->trans("TasksDesc"); - else $tooltiphelp = $langs->trans("TasksPublicDesc"); +if ($mine) { + $tooltiphelp = $langs->trans("MyTasksDesc"); +} else { + if ($user->rights->projet->all->lire && !$socid) { + $tooltiphelp = $langs->trans("TasksDesc"); + } else { + $tooltiphelp = $langs->trans("TasksPublicDesc"); + } } print_barre_liste($form->textwithpicto($title, $tooltiphelp), 0, $_SERVER["PHP_SELF"], '', '', '', '', 0, -1, 'projecttask', 0, $morehtml); @@ -96,27 +109,27 @@ print_barre_liste($form->textwithpicto($title, $tooltiphelp), 0, $_SERVER["PHP_S print '<div class="fichecenter"><div class="fichethirdleft">'; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo // Search project - if (!empty($conf->projet->enabled) && $user->rights->projet->lire) - { + if (!empty($conf->projet->enabled) && $user->rights->projet->lire) { $listofsearchfields['search_task'] = array('text'=>'Task'); } - if (count($listofsearchfields)) - { + if (count($listofsearchfields)) { print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<div class="div-table-responsive-no-min">'; print '<table class="noborder nohover centpercent">'; $i = 0; - foreach ($listofsearchfields as $key => $value) - { - if ($i == 0) print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>'; + foreach ($listofsearchfields as $key => $value) { + if ($i == 0) { + print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>'; + } print '<tr '.$bc[false].'>'; print '<td class="nowrap"><label for="'.$key.'">'.$langs->trans($value["text"]).'</label></td><td><input type="text" class="flat inputsearch" name="'.$key.'" id="'.$key.'" size="18"></td>'; - if ($i == 0) print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>'; + if ($i == 0) { + print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>'; + } print '</tr>'; $i++; } @@ -149,12 +162,10 @@ $sql .= " AND p.rowid in (".$db->sanitize($projectsListId).")"; $sql .= " GROUP BY p.rowid, p.ref, p.title, p.public"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $total = 0; - while ($row = $db->fetch_object($resql)) - { + while ($row = $db->fetch_object($resql)) { print '<tr class="oddeven">'; print '<td>'; $projectstatic->id = $row->rowid; @@ -204,12 +215,10 @@ $sql .= " AND p.rowid in (".$db->sanitize($projectsListId).")"; $sql .= " GROUP BY p.rowid, p.ref, p.title, p.public"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $total = 0; - while ($row = $db->fetch_object($resql)) - { + while ($row = $db->fetch_object($resql)) { print '<tr class="oddeven">'; print '<td>'; $projectstatic->id = $row->rowid; @@ -239,66 +248,65 @@ print '</div>'; /* if ($db->type != 'pgsql') { - print '<br>'; + print '<br>'; - // Affichage de la liste des projets de la semaine - print '<div class="div-table-responsive-no-min">'; - print '<table class="noborder centpercent">'; - print '<tr class="liste_titre">'; - print '<td>'.$langs->trans("ActivityOnProjectThisWeek").'</td>'; - print '<td class="right">'.$langs->trans("Time").'</td>'; - print "</tr>\n"; + // Affichage de la liste des projets de la semaine + print '<div class="div-table-responsive-no-min">'; + print '<table class="noborder centpercent">'; + print '<tr class="liste_titre">'; + print '<td>'.$langs->trans("ActivityOnProjectThisWeek").'</td>'; + print '<td class="right">'.$langs->trans("Time").'</td>'; + print "</tr>\n"; - $sql = "SELECT p.rowid, p.ref, p.title, p.public, SUM(tt.task_duration) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; - $sql.= " , ".MAIN_DB_PREFIX."projet_task as t"; - $sql.= " , ".MAIN_DB_PREFIX."projet_task_time as tt"; - $sql.= " WHERE t.fk_projet = p.rowid"; - $sql.= " AND p.entity = ".$conf->entity; - $sql.= " AND tt.fk_task = t.rowid"; - $sql.= " AND tt.fk_user = ".$user->id; - $sql.= " AND task_date >= '".$db->idate(dol_get_first_day($year, $month)).'" AND ..."; - $sql.= " AND p.rowid in (".$db->sanitize($projectsListId).")"; - $sql.= " GROUP BY p.rowid, p.ref, p.title"; + $sql = "SELECT p.rowid, p.ref, p.title, p.public, SUM(tt.task_duration) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; + $sql.= " , ".MAIN_DB_PREFIX."projet_task as t"; + $sql.= " , ".MAIN_DB_PREFIX."projet_task_time as tt"; + $sql.= " WHERE t.fk_projet = p.rowid"; + $sql.= " AND p.entity = ".$conf->entity; + $sql.= " AND tt.fk_task = t.rowid"; + $sql.= " AND tt.fk_user = ".$user->id; + $sql.= " AND task_date >= '".$db->idate(dol_get_first_day($year, $month)).'" AND ..."; + $sql.= " AND p.rowid in (".$db->sanitize($projectsListId).")"; + $sql.= " GROUP BY p.rowid, p.ref, p.title"; - $resql = $db->query($sql); - if ( $resql ) - { - $total = 0; + $resql = $db->query($sql); + if ( $resql ) + { + $total = 0; - while ($row = $db->fetch_object($resql)) - { - print '<tr class="oddeven">'; - print '<td>'; - $projectstatic->id=$row->rowid; - $projectstatic->ref=$row->ref; - $projectstatic->title=$row->title; - $projectstatic->public=$row->public; - print $projectstatic->getNomUrl(1, '', 1); - print '</td>'; - print '<td class="right">'.convertSecondToTime($row->nb, 'allhourmin').'</td>'; - print "</tr>\n"; - $total += $row->nb; - } + while ($row = $db->fetch_object($resql)) + { + print '<tr class="oddeven">'; + print '<td>'; + $projectstatic->id=$row->rowid; + $projectstatic->ref=$row->ref; + $projectstatic->title=$row->title; + $projectstatic->public=$row->public; + print $projectstatic->getNomUrl(1, '', 1); + print '</td>'; + print '<td class="right">'.convertSecondToTime($row->nb, 'allhourmin').'</td>'; + print "</tr>\n"; + $total += $row->nb; + } - $db->free($resql); - } - else - { - dol_print_error($db); - } - print '<tr class="liste_total">'; - print '<td>'.$langs->trans('Total').'</td>'; - print '<td class="right">'.convertSecondToTime($total, 'allhourmin').'</td>'; - print "</tr>\n"; - print "</table></div><br>"; + $db->free($resql); + } + else + { + dol_print_error($db); + } + print '<tr class="liste_total">'; + print '<td>'.$langs->trans('Total').'</td>'; + print '<td class="right">'.convertSecondToTime($total, 'allhourmin').'</td>'; + print "</tr>\n"; + print "</table></div><br>"; } */ /* Affichage de la liste des projets du mois */ -if (!empty($conf->global->PROJECT_TASK_TIME_MONTH)) -{ +if (!empty($conf->global->PROJECT_TASK_TIME_MONTH)) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; @@ -319,10 +327,8 @@ if (!empty($conf->global->PROJECT_TASK_TIME_MONTH)) $sql .= " GROUP BY p.rowid, p.ref, p.title, p.public"; $resql = $db->query($sql); - if ($resql) - { - while ($row = $db->fetch_object($resql)) - { + if ($resql) { + while ($row = $db->fetch_object($resql)) { print '<tr class="oddeven">'; print '<td>'; $projectstatic->id = $row->rowid; @@ -346,8 +352,7 @@ if (!empty($conf->global->PROJECT_TASK_TIME_MONTH)) } /* Affichage de la liste des projets de l'annee */ -if (!empty($conf->global->PROJECT_TASK_TIME_YEAR)) -{ +if (!empty($conf->global->PROJECT_TASK_TIME_YEAR)) { print '<div class="div-table-responsive-no-min">'; print '<br><table class="noborder centpercent">'; print '<tr class="liste_titre">'; @@ -368,10 +373,8 @@ if (!empty($conf->global->PROJECT_TASK_TIME_YEAR)) $sql .= " GROUP BY p.rowid, p.ref, p.title, p.public"; $resql = $db->query($sql); - if ($resql) - { - while ($row = $db->fetch_object($resql)) - { + if ($resql) { + while ($row = $db->fetch_object($resql)) { print '<tr class="oddeven">'; print '<td>'; $projectstatic->id = $row->rowid; @@ -395,36 +398,39 @@ if (!empty($conf->global->PROJECT_TASK_TIME_YEAR)) print '</div>'; } -if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SHOW_TASK_LIST_ON_PROJECT_AREA)) -{ +if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SHOW_TASK_LIST_ON_PROJECT_AREA)) { // Get id of types of contacts for projects (This list never contains a lot of elements) $listofprojectcontacttype = array(); $sql = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc"; $sql .= " WHERE ctc.element = '".$db->escape($projectstatic->element)."'"; $sql .= " AND ctc.source = 'internal'"; $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $db->fetch_object($resql)) { $listofprojectcontacttype[$obj->rowid] = $obj->code; } - } else dol_print_error($db); - if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0] = '0'; // To avoid sql syntax error if not found + } else { + dol_print_error($db); + } + if (count($listofprojectcontacttype) == 0) { + $listofprojectcontacttype[0] = '0'; // To avoid sql syntax error if not found + } // Get id of types of contacts for tasks (This list never contains a lot of elements) $listoftaskcontacttype = array(); $sql = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc"; $sql .= " WHERE ctc.element = '".$db->escape($taskstatic->element)."'"; $sql .= " AND ctc.source = 'internal'"; $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $db->fetch_object($resql)) { $listoftaskcontacttype[$obj->rowid] = $obj->code; } - } else dol_print_error($db); - if (count($listoftaskcontacttype) == 0) $listoftaskcontacttype[0] = '0'; // To avoid sql syntax error if not found + } else { + dol_print_error($db); + } + if (count($listoftaskcontacttype) == 0) { + $listoftaskcontacttype[0] = '0'; // To avoid sql syntax error if not found + } // Tasks for all resources of all opened projects and time spent for each task/resource @@ -440,17 +446,19 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_time as tasktime on tasktime.fk_task = t.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on tasktime.fk_user = u.rowid"; - if ($mine) - { + if ($mine) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ect"; } $sql .= " WHERE p.entity IN (".getEntity('project').")"; - if ($mine || empty($user->rights->projet->all->lire)) $sql .= " AND p.rowid IN (".$db->sanitize($projectsListId).")"; // project i have permission on - if ($mine) // this may duplicate record if we are contact twice - { + if ($mine || empty($user->rights->projet->all->lire)) { + $sql .= " AND p.rowid IN (".$db->sanitize($projectsListId).")"; // project i have permission on + } + if ($mine) { // this may duplicate record if we are contact twice $sql .= " AND ect.fk_c_type_contact IN (".join(',', array_keys($listoftaskcontacttype)).") AND ect.element_id = t.rowid AND ect.fk_socpeople = ".$user->id; } - if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + if ($socid) { + $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + } $sql .= " AND p.fk_statut=1"; $sql .= " GROUP BY p.ref, p.title, p.rowid, p.fk_statut, p.fk_opp_status, p.public, t.label, t.rowid, t.planned_workload, t.duration_effective, t.progress, t.dateo, t.datee"; $sql .= " ORDER BY t.dateo desc, t.rowid desc, t.datee"; @@ -458,8 +466,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH dol_syslog('projet:index.php: affectationpercent', LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -470,7 +477,9 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH print '<tr class="liste_titre">'; //print '<th>'.$langs->trans('TaskRessourceLinks').'</th>'; print '<th>'.$langs->trans('OpenedProjects').'</th>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) print '<th>'.$langs->trans('OpportunityStatus').'</th>'; + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { + print '<th>'.$langs->trans('OpportunityStatus').'</th>'; + } print '<th>'.$langs->trans('Task').'</th>'; print '<th class="center">'.$langs->trans('DateStart').'</th>'; print '<th class="center">'.$langs->trans('DateEnd').'</th>'; @@ -480,8 +489,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH print '<th class="right">'.$langs->trans("ProgressDeclared").'</td>'; print '</tr>'; - while ($i < $num && $i < $max) - { + while ($i < $num && $i < $max) { $obj = $db->fetch_object($resql); $projectstatic->id = $obj->projectid; @@ -499,37 +507,44 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH $taskstatic->datee = $db->jdate($obj->datee); $username = ''; - if ($obj->userid && $userstatic->id != $obj->userid) // We have a user and it is not last loaded user - { + if ($obj->userid && $userstatic->id != $obj->userid) { // We have a user and it is not last loaded user $result = $userstatic->fetch($obj->userid); - if (!$result) $userstatic->id = 0; + if (!$result) { + $userstatic->id = 0; + } + } + if ($userstatic->id) { + $username = $userstatic->getNomUrl(0, 0); } - if ($userstatic->id) $username = $userstatic->getNomUrl(0, 0); print '<tr class="oddeven">'; //print '<td>'.$username.'</td>'; print '<td>'; print $projectstatic->getNomUrl(1, '', 0, '', '<br>'); print '</td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<td>'; $code = dol_getIdFromCode($db, $obj->opp_status, 'c_lead_status', 'rowid', 'code'); - if ($code) print $langs->trans("OppStatus".$code); + if ($code) { + print $langs->trans("OppStatus".$code); + } print '</td>'; } print '<td>'; - if (!empty($obj->taskid)) - { + if (!empty($obj->taskid)) { $tasktmp->id = $obj->taskid; $tasktmp->ref = $obj->ref; $tasktmp->label = $obj->label; print $tasktmp->getNomUrl(1, 'withproject', 'task', 1, '<br>'); - } else print $langs->trans("NoTasks"); + } else { + print $langs->trans("NoTasks"); + } print '</td>'; print '<td class="center">'.dol_print_date($db->jdate($obj->dateo), 'day').'</td>'; print '<td class="center">'.dol_print_date($db->jdate($obj->datee), 'day'); - if ($taskstatic->hasDelay()) print img_warning($langs->trans("Late")); + if ($taskstatic->hasDelay()) { + print img_warning($langs->trans("Late")); + } print '</td>'; print '<td class="right"><a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$obj->taskid.'&withproject=1">'; print convertSecondToTime($obj->planned_workload, 'allhourmin'); @@ -538,8 +553,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH print convertSecondToTime($obj->timespent, 'allhourmin'); print '</a></td>'; print '<td class="right">'; - if (!empty($obj->taskid)) - { + if (!empty($obj->taskid)) { if (empty($obj->planned_workload) > 0) { $percentcompletion = $langs->trans("WorkloadNotDefined"); } else { @@ -556,10 +570,11 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH $i++; } - if ($num > $max) - { + if ($num > $max) { $colspan = 6; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $colspan++; + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { + $colspan++; + } print '<tr><td colspan="'.$colspan.'">'.$langs->trans("WarningTooManyDataPleaseUseMoreFilters").'</td></tr>'; } diff --git a/htdocs/projet/activity/perday.php b/htdocs/projet/activity/perday.php index c6b38390ac9..1309ae4455e 100644 --- a/htdocs/projet/activity/perday.php +++ b/htdocs/projet/activity/perday.php @@ -46,7 +46,9 @@ $taskid = GETPOST('taskid', 'int'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'perdaycard'; $mine = 0; -if ($mode == 'mine') $mine = 1; +if ($mode == 'mine') { + $mine = 1; +} $projectid = isset($_GET["id"]) ? GETPOST("id", "int", 1) : GETPOST("projectid", "int"); @@ -84,16 +86,17 @@ $dayofday = GETPOST('addtimeday'); $yearofday = GETPOST('addtimeyear'); $daytoparse = $now; -if ($yearofday && $monthofday && $dayofday) $daytoparse = dol_mktime(0, 0, 0, $monthofday, $dayofday, $yearofday); // xxxofday is value of day after submit action 'addtime' -elseif ($year && $month && $day) $daytoparse = dol_mktime(0, 0, 0, $month, $day, $year); // this are value submited after submit of action 'submitdateselect' +if ($yearofday && $monthofday && $dayofday) { + $daytoparse = dol_mktime(0, 0, 0, $monthofday, $dayofday, $yearofday); // xxxofday is value of day after submit action 'addtime' +} elseif ($year && $month && $day) { + $daytoparse = dol_mktime(0, 0, 0, $month, $day, $year); // this are value submited after submit of action 'submitdateselect' +} -if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) -{ +if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) { $usertoprocess = $user; $search_usertoprocessid = $usertoprocess->id; -} elseif ($search_usertoprocessid > 0) -{ +} elseif ($search_usertoprocessid > 0) { $usertoprocess = new User($db); $usertoprocess->fetch($search_usertoprocessid); $search_usertoprocessid = $usertoprocess->id; @@ -124,12 +127,11 @@ $arrayfields['t.progress'] = array('label'=>'ProgressDeclared', 'checked'=>1, 'e ); */ // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { - if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["efpt.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs((int) $extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + } } } $arrayfields = dol_sort_array($arrayfields, 'position'); @@ -145,10 +147,11 @@ $search_array_options_task = $extrafields->getOptionalsFromPost($object->table_e $parameters = array('id' => $id, 'taskid' => $taskid, 'projectid' => $projectid); $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'); +} // Purge 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 $action = ''; $search_categ = ''; $search_usertoprocessid = $user->id; @@ -164,15 +167,12 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' // We redefine $usertoprocess $usertoprocess = $user; } -if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha')) -{ +if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha')) { $action = ''; } -if (GETPOST('submitdateselect')) -{ - if (GETPOST('remonth', 'int') && GETPOST('reday', 'int') && GETPOST('reyear', 'int')) - { +if (GETPOST('submitdateselect')) { + if (GETPOST('remonth', 'int') && GETPOST('reday', 'int') && GETPOST('reyear', 'int')) { $daytoparse = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); } @@ -181,46 +181,40 @@ if (GETPOST('submitdateselect')) include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; -if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') && GETPOST('formfilteraction') != 'listafterchangingselectedfields') -{ +if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') && GETPOST('formfilteraction') != 'listafterchangingselectedfields') { $action = 'assigntask'; - if ($taskid > 0) - { + if ($taskid > 0) { $result = $object->fetch($taskid, $ref); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } else { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors'); $error++; } - if (!GETPOST('type')) - { + if (!GETPOST('type')) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors'); $error++; } - if (!$error) - { + if (!$error) { $idfortaskuser = $usertoprocess->id; $result = $object->add_contact($idfortaskuser, GETPOST("type"), 'internal'); - if ($result >= 0 || $result == -2) // Contact add ok or already contact of task - { + if ($result >= 0 || $result == -2) { // Contact add ok or already contact of task // Test if we are already contact of the project (should be rare but sometimes we can add as task contact without being contact of project, like when admin user has been removed from contact of project) $sql = 'SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact'; $sql .= ' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if (!$obj) // User is not already linked to project, so we will create link to first type - { + if (!$obj) { // User is not already linked to project, so we will create link to first type $project = new Project($db); $project->fetch($object->fk_project); // Get type $listofprojcontact = $project->liste_type_contact('internal'); - if (count($listofprojcontact)) - { + if (count($listofprojcontact)) { $typeforprojectcontact = reset(array_keys($listofprojcontact)); $result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal'); } @@ -231,11 +225,9 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') } } - if ($result < 0) - { + if ($result < 0) { $error++; - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorTaskAlreadyAssigned"), null, 'warnings'); } else { @@ -243,8 +235,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') } } - if (!$error) - { + if (!$error) { setEventMessages("TaskAssignedToEnterTime", null); $taskid = 0; } @@ -252,49 +243,47 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') $action = ''; } -if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilteraction') != 'listafterchangingselectedfields') -{ +if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilteraction') != 'listafterchangingselectedfields') { $timespent_duration = array(); - if (is_array($_POST)) - { - foreach ($_POST as $key => $time) - { - if (intval($time) > 0) - { + if (is_array($_POST)) { + foreach ($_POST as $key => $time) { + if (intval($time) > 0) { $matches = array(); // Hours or minutes of duration - if (preg_match("/([0-9]+)duration(hour|min)/", $key, $matches)) - { + if (preg_match("/([0-9]+)duration(hour|min)/", $key, $matches)) { $id = $matches[1]; - if ($id > 0) - { + if ($id > 0) { // We store HOURS in seconds - if ($matches[2] == 'hour') $timespent_duration[$id] += $time * 60 * 60; + if ($matches[2] == 'hour') { + $timespent_duration[$id] += $time * 60 * 60; + } // We store MINUTES in seconds - if ($matches[2] == 'min') $timespent_duration[$id] += $time * 60; + if ($matches[2] == 'min') { + $timespent_duration[$id] += $time * 60; + } } } } } } - if (count($timespent_duration) > 0) - { - foreach ($timespent_duration as $key => $val) - { + if (count($timespent_duration) > 0) { + foreach ($timespent_duration as $key => $val) { $object->fetch($key); $taskid = $object->id; - if (GETPOSTISSET($taskid.'progress')) $object->progress = GETPOST($taskid.'progress', 'int'); - else unset($object->progress); + if (GETPOSTISSET($taskid.'progress')) { + $object->progress = GETPOST($taskid.'progress', 'int'); + } else { + unset($object->progress); + } $object->timespent_duration = $val; $object->timespent_fk_user = $usertoprocess->id; $object->timespent_note = GETPOST($key.'note'); - if (GETPOST($key."hour", 'int') != '' && GETPOST($key."hour", 'int') >= 0) // If hour was entered - { + if (GETPOST($key."hour", 'int') != '' && GETPOST($key."hour", 'int') >= 0) { // If hour was entered $object->timespent_datehour = dol_mktime(GETPOST($key."hour", 'int'), GETPOST($key."min", 'int'), 0, $monthofday, $dayofday, $yearofday); $object->timespent_withhour = 1; } else { @@ -302,8 +291,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac } $object->timespent_date = $object->timespent_datehour; - if ($object->timespent_date > 0) - { + if ($object->timespent_date > 0) { $result = $object->addTimeSpent($user); } else { setEventMessages("ErrorBadDate", null, 'errors'); @@ -311,16 +299,14 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac break; } - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; break; } } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); // Redirect to avoid submit twice on back @@ -328,7 +314,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac exit; } } else { - setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors'); + setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors'); } } @@ -362,8 +348,7 @@ $title = $langs->trans("TimeSpent"); $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess, (empty($usertoprocess->id) ? 2 : 0), 1); // Return all project i have permission on. I want my tasks and some of my task may be on a public projet that is not my project -if ($id) -{ +if ($id) { $project->fetch($id); $project->fetch_thirdparty(); } @@ -371,11 +356,21 @@ if ($id) $onlyopenedproject = 1; // or -1 $morewherefilter = ''; -if ($search_project_ref) $morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref); -if ($search_task_ref) $morewherefilter .= natural_search("t.ref", $search_task_ref); -if ($search_task_label) $morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label); -if ($search_thirdparty) $morewherefilter .= natural_search("s.nom", $search_thirdparty); -if ($search_declared_progress) $morewherefilter .= natural_search("t.progress", $search_declared_progress, 1); +if ($search_project_ref) { + $morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref); +} +if ($search_task_ref) { + $morewherefilter .= natural_search("t.ref", $search_task_ref); +} +if ($search_task_label) { + $morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label); +} +if ($search_thirdparty) { + $morewherefilter .= natural_search("s.nom", $search_thirdparty); +} +if ($search_declared_progress) { + $morewherefilter .= natural_search("t.progress", $search_declared_progress, 1); +} $sql = &$morewherefilter; @@ -392,8 +387,7 @@ $extrafieldsobjectkey = 'projet_task'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; $tasksarray = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid ? $search_usertoprocessid : 0), 0, $extrafields); // We want to see all task of opened project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. -if ($morewherefilter) // Get all task without any filter, so we can show total of time spent for not visible tasks -{ +if ($morewherefilter) { // Get all task without any filter, so we can show total of time spent for not visible tasks $tasksarraywithoutfilter = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, '', $onlyopenedproject, '', ($search_usertoprocessid ? $search_usertoprocessid : 0)); // We want to see all task of opened project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. } $projectsrole = $taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id ? $project->id : 0), 0, $onlyopenedproject); @@ -451,16 +445,18 @@ print dol_get_fiche_head($head, 'inputperday', $langs->trans('TimeSpent'), -1, $ // Show description of content print '<div class="hideonsmartphone opacitymedium">'; -if ($mine || ($usertoprocess->id == $user->id)) print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; -else { - if (empty($usertoprocess->id) || $usertoprocess->id < 0) - { - if ($user->rights->projet->all->lire && !$socid) print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; - else print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; +if ($mine || ($usertoprocess->id == $user->id)) { + print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; +} else { + if (empty($usertoprocess->id) || $usertoprocess->id < 0) { + if ($user->rights->projet->all->lire && !$socid) { + print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; + } else { + print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; + } } } -if ($mine || ($usertoprocess->id == $user->id)) -{ +if ($mine || ($usertoprocess->id == $user->id)) { print $langs->trans("OnlyYourTaskAreVisible").'<br>'; } else { print $langs->trans("AllTaskVisibleButEditIfYouAreAssigned").'<br>'; @@ -474,7 +470,9 @@ print '<div class="floatright right'.($conf->dol_optimize_smallscreen ? ' centpe print '<div class="colorbacktimesheet float valignmiddle">'; $titleassigntask = $langs->transnoentities("AssignTaskToMe"); -if ($usertoprocess->id != $user->id) $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs)); +if ($usertoprocess->id != $user->id) { + $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs)); +} print '<div class="taskiddiv inline-block">'; print img_picto('', 'projecttask'); $formproject->selectTasks($socid ? $socid : -1, $taskid, 'taskid', 32, 0, '-- '.$langs->trans("ChooseANotYetAssignedTask").' --', 1, 0, 0, '', '', 'all', $usertoprocess); @@ -503,12 +501,13 @@ $moreforfilter = ''; $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= '<div class="inline-block hideonsmartphone"></div>'; $includeonly = 'hierarchyme'; -if (empty($user->rights->user->user->lire)) $includeonly = array($user->id); +if (empty($user->rights->user->user->lire)) { + $includeonly = array($user->id); +} $moreforfilter .= img_picto($langs->trans('Filter').' '.$langs->trans('User'), 'user').$form->select_dolusers($search_usertoprocessid ? $search_usertoprocessid : $usertoprocess->id, 'search_usertoprocessid', $user->rights->user->user->lire ? 0 : 0, null, 0, $includeonly, null, 0, 0, 0, '', 0, '', 'maxwidth200 marginleftonly'); $moreforfilter .= '</div>'; -if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) -{ +if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= '<div class="inline-block"></div>'; $moreforfilter .= img_picto($langs->trans('Filter').' '.$langs->trans('Project'), 'project').'<input type="text" size="4" name="search_project_ref" class="marginleftonly" value="'.dol_escape_htmltag($search_project_ref).'">'; @@ -520,8 +519,7 @@ if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) $moreforfilter .= '</div>'; } -if (!empty($moreforfilter)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; $parameters = array(); @@ -535,19 +533,28 @@ $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfi // This must be after the $selectedfields $addcolspan = 0; -if (!empty($arrayfields['t.planned_workload']['checked'])) $addcolspan++; -if (!empty($arrayfields['t.progress']['checked'])) $addcolspan++; -foreach ($arrayfields as $key => $val) -{ - if ($val['checked'] && substr($key, 0, 5) == 'efpt.') $addcolspan++; +if (!empty($arrayfields['t.planned_workload']['checked'])) { + $addcolspan++; +} +if (!empty($arrayfields['t.progress']['checked'])) { + $addcolspan++; +} +foreach ($arrayfields as $key => $val) { + if ($val['checked'] && substr($key, 0, 5) == 'efpt.') { + $addcolspan++; + } } print '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'" id="tablelines3">'."\n"; print '<tr class="liste_titre_filter">'; -if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>'; -if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>'; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { + print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>'; +} +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { + print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>'; +} print '<td class="liste_titre"><input type="text" size="4" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'"></td>'; // TASK fields $search_options_pattern = 'search_task_options_'; @@ -555,12 +562,10 @@ $extrafieldsobjectkey = 'projet_task'; $extrafieldsobjectprefix = 'efpt.'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; print '<td class="liste_titre"></td>'; -if (!empty($arrayfields['t.planned_workload']['checked'])) -{ +if (!empty($arrayfields['t.planned_workload']['checked'])) { print '<td class="liste_titre right"><input type="text" size="4" name="search_declared_progress" value="'.dol_escape_htmltag($search_declared_progress).'"></td>'; } -if (!empty($arrayfields['t.progress']['checked'])) -{ +if (!empty($arrayfields['t.progress']['checked'])) { print '<td class="liste_titre"></td>'; } print '<td class="liste_titre"></td>'; @@ -575,25 +580,30 @@ print '</td>'; print "</tr>\n"; print '<tr class="liste_titre">'; -if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<th>'.$langs->trans("Project").'</th>'; -if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<th>'.$langs->trans("ThirdParty").'</th>'; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { + print '<th>'.$langs->trans("Project").'</th>'; +} +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { + print '<th>'.$langs->trans("ThirdParty").'</th>'; +} print '<th>'.$langs->trans("Task").'</th>'; // TASK fields $extrafieldsobjectkey = 'projet_task'; $extrafieldsobjectprefix = 'efpt.'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; -if (!empty($arrayfields['t.planned_workload']['checked'])) -{ +if (!empty($arrayfields['t.planned_workload']['checked'])) { print '<th class="right leftborder plannedworkload maxwidth100">'.$langs->trans("PlannedWorkload").'</th>'; } -if (!empty($arrayfields['t.progress']['checked'])) -{ +if (!empty($arrayfields['t.progress']['checked'])) { print '<th class="right maxwidth100">'.$langs->trans("ProgressDeclared").'</th>'; } /*print '<td class="right maxwidth100">'.$langs->trans("TimeSpent").'</td>'; if ($usertoprocess->id == $user->id) print '<td class="right maxwidth100">'.$langs->trans("TimeSpentByYou").'</td>'; else print '<td class="right maxwidth100">'.$langs->trans("TimeSpentByUser").'</td>';*/ -print '<th class="right maxwidth100">'.$langs->trans("TimeSpent").'<br><span class="opacitymedium">'.$langs->trans("Everybody").'</span></th>'; +print '<th class="right maxwidth100">'.$langs->trans("TimeSpent").'<br>'; +print '<span class="opacitymedium nopadding userimg"><img alt="Photo" class="photouserphoto userphoto" src="'.DOL_URL_ROOT.'/theme/common/everybody.png"></span>'; +print '<span class="opacitymedium paddingleft">'.$langs->trans("Everybody").'</span>'; +print '</th>'; print '<th class="right maxwidth100">'.$langs->trans("TimeSpent").($usertoprocess->firstname ? '<br>'.$usertoprocess->getNomUrl(-2).'<span class="opacitymedium paddingleft">'.dol_trunc($usertoprocess->firstname, 10).'</span>' : '').'</th>'; print '<th class="center leftborder">'.$langs->trans("HourStart").'</td>'; @@ -602,11 +612,9 @@ $restrictviewformytask = ((!isset($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSI // Get if user is available or not for each day $isavailable = array(); -if (!empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) -{ +if (!empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) { $tmparray = explode('-', $conf->global->MAIN_DEFAULT_WORKING_DAYS); - if (count($tmparray) >= 2) - { + if (count($tmparray) >= 2) { $numstartworkingday = $tmparray[0]; $numendworkingday = $tmparray[1]; } @@ -617,24 +625,29 @@ $isavailablefordayanduser = $holiday->verifDateHolidayForTimestamp($usertoproces $isavailable[$daytoparse] = $isavailablefordayanduser; // in projectLinesPerWeek later, we are using $firstdaytoshow and dol_time_plus_duree to loop on each day $test = num_public_holiday($daytoparse, $daytoparse + 86400, $mysoc->country_code); -if ($test) $isavailable[$daytoparse] = array('morning'=>false, 'afternoon'=>false, 'morning_reason'=>'public_holiday', 'afternoon_reason'=>'public_holiday'); +if ($test) { + $isavailable[$daytoparse] = array('morning'=>false, 'afternoon'=>false, 'morning_reason'=>'public_holiday', 'afternoon_reason'=>'public_holiday'); +} $tmparray = dol_getdate($daytoparse, true); // detail of current day // For monday, must be 0 for monday if MAIN_START_WEEK = 1, must be 1 for monday if MAIN_START_WEEK = 0 $idw = ($tmparray['wday'] - (empty($conf->global->MAIN_START_WEEK) ? 0 : 1)); // numstartworkingday and numendworkingday are default start and end date of working days (1 means sunday if MAIN_START_WEEK is 0, 1 means monday if MAIN_START_WEEK is 1) $cssweekend = ''; -if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. -{ +if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) { // This is a day is not inside the setup of working days, so we use a week-end css. $cssweekend = 'weekend'; } $tmpday = dol_time_plus_duree($daytoparse, $idw, 'd'); $cssonholiday = ''; -if (!$isavailable[$daytoparse]['morning'] && !$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayallday '; -elseif (!$isavailable[$daytoparse]['morning']) $cssonholiday .= 'onholidaymorning '; -elseif (!$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayafternoon '; +if (!$isavailable[$daytoparse]['morning'] && !$isavailable[$daytoparse]['afternoon']) { + $cssonholiday .= 'onholidayallday '; +} elseif (!$isavailable[$daytoparse]['morning']) { + $cssonholiday .= 'onholidaymorning '; +} elseif (!$isavailable[$daytoparse]['afternoon']) { + $cssonholiday .= 'onholidayafternoon '; +} print '<th class="center'.($cssonholiday ? ' '.$cssonholiday : '').($cssweekend ? ' '.$cssweekend : '').'">'.$langs->trans("Duration").'</th>'; print '<th class="center">'.$langs->trans("Note").'</th>'; @@ -645,8 +658,7 @@ print "</tr>\n"; $colspan = 4 + (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : 2); -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print '<tr class="liste_total">'; print '<td class="liste_total" colspan="'.($colspan - 1 + $addcolspan).'">'; print $langs->trans("Total"); @@ -663,8 +675,7 @@ if ($conf->use_javascript_ajax) } -if (count($tasksarray) > 0) -{ +if (count($tasksarray) > 0) { //var_dump($tasksarray); // contains only selected tasks //var_dump($tasksarraywithoutfilter); // contains all tasks (if there is a filter, not defined if no filter) //var_dump($tasksrole); @@ -678,21 +689,17 @@ if (count($tasksarray) > 0) // Calculate total for all tasks $listofdistinctprojectid = array(); // List of all distinct projects - if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter)) - { - foreach ($tasksarraywithoutfilter as $tmptask) - { + if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter)) { + foreach ($tasksarraywithoutfilter as $tmptask) { $listofdistinctprojectid[$tmptask->fk_project] = $tmptask->fk_project; } } //var_dump($listofdistinctprojectid); $totalforeachday = array(); - foreach ($listofdistinctprojectid as $tmpprojectid) - { + foreach ($listofdistinctprojectid as $tmpprojectid) { $projectstatic->id = $tmpprojectid; $projectstatic->loadTimeSpent($daytoparse, 0, $usertoprocess->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week - for ($idw = 0; $idw < 7; $idw++) - { + for ($idw = 0; $idw < 7; $idw++) { $tmpday = dol_time_plus_duree($daytoparse, $idw, 'd'); $totalforeachday[$tmpday] += $projectstatic->weekWorkLoad[$tmpday]; } @@ -701,18 +708,15 @@ if (count($tasksarray) > 0) // Is there a diff between selected/filtered tasks and all tasks ? $isdiff = 0; - if (count($totalforeachday)) - { + if (count($totalforeachday)) { $timeonothertasks = ($totalforeachday[$daytoparse] - $totalforvisibletasks[$daytoparse]); - if ($timeonothertasks) - { + if ($timeonothertasks) { $isdiff = 1; } } // There is a diff between total shown on screen and total spent by user, so we add a line with all other cumulated time of user - if ($isdiff) - { + if ($isdiff) { print '<tr class="oddeven othertaskwithtime">'; print '<td colspan="'.($colspan - 1).'" class="opacitymedium">'; print $langs->trans("OtherFilteredTasks"); @@ -723,7 +727,9 @@ if (count($tasksarray) > 0) //if ($timeonothertasks) //{ print '<span class="timesheetalreadyrecorded" title="texttoreplace"><input type="text" class="center" size="2" disabled="" id="timespent[-1][0]" name="task[-1][0]" value="'; - if ($timeonothertasks) print convertSecondToTime($timeonothertasks, 'allhourmin'); + if ($timeonothertasks) { + print convertSecondToTime($timeonothertasks, 'allhourmin'); + } print '"></span>'; //} print '</td>'; @@ -732,8 +738,7 @@ if (count($tasksarray) > 0) print '</tr>'; } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<tr class="liste_total">'; print '<td class="liste_total" colspan="'.($colspan - 1 + $addcolspan).'">'; print $langs->trans("Total"); @@ -764,8 +769,7 @@ print '</form>'; $modeinput = 'hours'; -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print "\n<!-- JS CODE TO ENABLE Tooltips on all object with class classfortooltip -->\n"; print '<script type="text/javascript">'."\n"; print "jQuery(document).ready(function () {\n"; diff --git a/htdocs/projet/activity/permonth.php b/htdocs/projet/activity/permonth.php index 626634b13cd..d023dcc69d3 100644 --- a/htdocs/projet/activity/permonth.php +++ b/htdocs/projet/activity/permonth.php @@ -44,7 +44,9 @@ $id = GETPOST('id', 'int'); $taskid = GETPOST('taskid', 'int'); $mine = 0; -if ($mode == 'mine') $mine = 1; +if ($mode == 'mine') { + $mine = 1; +} $projectid = isset($_GET["id"]) ? GETPOST("id", "int", 1) : GETPOST("projectid", "int"); @@ -91,12 +93,10 @@ $TFirstDays = getFirstDayOfEachWeek($TWeek, $year); $TFirstDays[reset($TWeek)] = '01'; //first day of month $TLastDays = getLastDayOfEachWeek($TWeek, $year); $TLastDays[end($TWeek)] = date("t", strtotime($year.'-'.$month.'-'.$day)); //last day of month -if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) -{ +if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) { $usertoprocess = $user; $search_usertoprocessid = $usertoprocess->id; -} elseif ($search_usertoprocessid > 0) -{ +} elseif ($search_usertoprocessid > 0) { $usertoprocess = new User($db); $usertoprocess->fetch($search_usertoprocessid); $search_usertoprocessid = $usertoprocess->id; @@ -112,11 +112,12 @@ $object = new Task($db); */ $parameters = array('id' => $id, 'taskid' => $taskid, 'projectid' => $projectid, 'TWeek' => $TWeek, 'TFirstDays' => $TFirstDays, 'TLastDays' => $TLastDays); $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'); +} // Purge 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 $action = ''; $search_categ = ''; $search_usertoprocessid = $user->id; @@ -126,58 +127,50 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_thirdparty = ''; $search_declared_progress = ''; } -if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha')) -{ +if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha')) { $action = ''; } -if (GETPOST('submitdateselect')) -{ +if (GETPOST('submitdateselect')) { $daytoparse = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); $action = ''; } -if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')) -{ +if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')) { $action = 'assigntask'; - if ($taskid > 0) - { + if ($taskid > 0) { $result = $object->fetch($taskid, $ref); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } else { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors'); $error++; } - if (!GETPOST('type')) - { + if (!GETPOST('type')) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors'); $error++; } - if (!$error) - { + if (!$error) { $idfortaskuser = $usertoprocess->id; $result = $object->add_contact($idfortaskuser, GETPOST("type"), 'internal'); - if ($result >= 0 || $result == -2) // Contact add ok or already contact of task - { + if ($result >= 0 || $result == -2) { // Contact add ok or already contact of task // Test if we are already contact of the project (should be rare but sometimes we can add as task contact without being contact of project, like when admin user has been removed from contact of project) $sql = 'SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact'; $sql .= ' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if (!$obj) // User is not already linked to project, so we will create link to first type - { + if (!$obj) { // User is not already linked to project, so we will create link to first type $project = new Project($db); $project->fetch($object->fk_project); // Get type $listofprojcontact = $project->liste_type_contact('internal'); - if (count($listofprojcontact)) - { + if (count($listofprojcontact)) { $typeforprojectcontact = reset(array_keys($listofprojcontact)); $result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal'); } @@ -188,11 +181,9 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') } } - if ($result < 0) - { + if ($result < 0) { $error++; - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorTaskAlreadyAssigned"), null, 'warnings'); } else { @@ -200,8 +191,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') } } - if (!$error) - { + if (!$error) { setEventMessages("TaskAssignedToEnterTime", null); $taskid = 0; } @@ -209,29 +199,29 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') $action = ''; } -if ($action == 'addtime' && $user->rights->projet->lire) -{ +if ($action == 'addtime' && $user->rights->projet->lire) { $timetoadd = $_POST['task']; - if (empty($timetoadd)) - { + if (empty($timetoadd)) { setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors'); } else { - foreach ($timetoadd as $taskid => $value) // Loop on each task - { + foreach ($timetoadd as $taskid => $value) { // Loop on each task $updateoftaskdone = 0; - foreach ($value as $key => $val) // Loop on each day - { + foreach ($value as $key => $val) { // Loop on each day $amountoadd = $timetoadd[$taskid][$key]; - if (!empty($amountoadd)) - { + if (!empty($amountoadd)) { $tmpduration = explode(':', $amountoadd); $newduration = 0; - if (!empty($tmpduration[0])) $newduration += ($tmpduration[0] * 3600); - if (!empty($tmpduration[1])) $newduration += ($tmpduration[1] * 60); - if (!empty($tmpduration[2])) $newduration += ($tmpduration[2]); + if (!empty($tmpduration[0])) { + $newduration += ($tmpduration[0] * 3600); + } + if (!empty($tmpduration[1])) { + $newduration += ($tmpduration[1] * 60); + } + if (!empty($tmpduration[2])) { + $newduration += ($tmpduration[2]); + } - if ($newduration > 0) - { + if ($newduration > 0) { $object->fetch($taskid); $object->progress = GETPOST($taskid.'progress', 'int'); $object->timespent_duration = $newduration; @@ -240,8 +230,7 @@ if ($action == 'addtime' && $user->rights->projet->lire) $object->timespent_datehour = $object->timespent_date; $result = $object->addTimeSpent($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; break; @@ -252,16 +241,13 @@ if ($action == 'addtime' && $user->rights->projet->lire) } } - if (!$updateoftaskdone) // Check to update progress if no update were done on task. - { + if (!$updateoftaskdone) { // Check to update progress if no update were done on task. $object->fetch($taskid); //var_dump($object->progress);var_dump(GETPOST($taskid . 'progress', 'int')); exit; - if ($object->progress != GETPOST($taskid.'progress', 'int')) - { + if ($object->progress != GETPOST($taskid.'progress', 'int')) { $object->progress = GETPOST($taskid.'progress', 'int'); $result = $object->update($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; break; @@ -270,8 +256,7 @@ if ($action == 'addtime' && $user->rights->projet->lire) } } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); $param = ''; @@ -313,8 +298,7 @@ $title = $langs->trans("TimeSpent"); $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess, (empty($usertoprocess->id) ? 2 : 0), 1); // Return all project i have permission on (assigned to me+public). I want my tasks and some of my task may be on a public projet that is not my project //var_dump($projectsListId); -if ($id) -{ +if ($id) { $project->fetch($id); $project->fetch_thirdparty(); } @@ -322,15 +306,24 @@ if ($id) $onlyopenedproject = 1; // or -1 $morewherefilter = ''; -if ($search_project_ref) $morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref); -if ($search_task_ref) $morewherefilter .= natural_search("t.ref", $search_task_ref); -if ($search_task_label) $morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label); -if ($search_thirdparty) $morewherefilter .= natural_search("s.nom", $search_thirdparty); -if ($search_declared_progress) $morewherefilter .= natural_search("t.progress", $search_declared_progress, 1); +if ($search_project_ref) { + $morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref); +} +if ($search_task_ref) { + $morewherefilter .= natural_search("t.ref", $search_task_ref); +} +if ($search_task_label) { + $morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label); +} +if ($search_thirdparty) { + $morewherefilter .= natural_search("s.nom", $search_thirdparty); +} +if ($search_declared_progress) { + $morewherefilter .= natural_search("t.progress", $search_declared_progress, 1); +} $tasksarray = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid ? $search_usertoprocessid : 0)); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. -if ($morewherefilter) // Get all task without any filter, so we can show total of time spent for not visible tasks -{ +if ($morewherefilter) { // Get all task without any filter, so we can show total of time spent for not visible tasks $tasksarraywithoutfilter = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, '', $onlyopenedproject, '', ($search_usertoprocessid ? $search_usertoprocessid : 0)); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. } $projectsrole = $taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id ? $project->id : 0), 0, $onlyopenedproject); @@ -376,16 +369,18 @@ print dol_get_fiche_head($head, 'inputpermonth', $langs->trans('TimeSpent'), -1, // Show description of content print '<div class="hideonsmartphone opacitymedium">'; -if ($mine || ($usertoprocess->id == $user->id)) print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; -else { - if (empty($usertoprocess->id) || $usertoprocess->id < 0) - { - if ($user->rights->projet->all->lire && !$socid) print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; - else print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; +if ($mine || ($usertoprocess->id == $user->id)) { + print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; +} else { + if (empty($usertoprocess->id) || $usertoprocess->id < 0) { + if ($user->rights->projet->all->lire && !$socid) { + print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; + } else { + print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; + } } } -if ($mine || ($usertoprocess->id == $user->id)) -{ +if ($mine || ($usertoprocess->id == $user->id)) { print $langs->trans("OnlyYourTaskAreVisible").'<br>'; } else { print $langs->trans("AllTaskVisibleButEditIfYouAreAssigned").'<br>'; @@ -398,7 +393,9 @@ print '<div class="floatright right'.($conf->dol_optimize_smallscreen ? ' centpe print '<div class="colorbacktimesheet float valignmiddle">'; $titleassigntask = $langs->transnoentities("AssignTaskToMe"); -if ($usertoprocess->id != $user->id) $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs)); +if ($usertoprocess->id != $user->id) { + $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs)); +} print '<div class="taskiddiv inline-block">'; print img_picto('', 'projecttask'); $formproject->selectTasks($socid ? $socid : -1, $taskid, 'taskid', 32, 0, '-- '.$langs->trans("ChooseANotYetAssignedTask").' --', 1); @@ -428,12 +425,13 @@ if (! empty($conf->categorie->enabled)) $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= '<div class="inline-block hideonsmartphone"></div>'; $includeonly = 'hierachyme'; -if (empty($user->rights->user->user->lire)) $includeonly = array($user->id); +if (empty($user->rights->user->user->lire)) { + $includeonly = array($user->id); +} $moreforfilter .= img_picto($langs->trans('Filter').' '.$langs->trans('User'), 'user').$form->select_dolusers($search_usertoprocessid ? $search_usertoprocessid : $usertoprocess->id, 'search_usertoprocessid', $user->rights->user->user->lire ? 0 : 0, null, 0, $includeonly, null, 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter .= '</div>'; -if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) -{ +if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= '<div class="inline-block"></div>'; $moreforfilter .= img_picto($langs->trans('Filter').' '.$langs->trans('Project'), 'project').'<input type="text" size="4" name="search_project_ref" class="marginleftonly" value="'.dol_escape_htmltag($search_project_ref).'">'; @@ -445,8 +443,7 @@ if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) $moreforfilter .= '</div>'; } -if (!empty($moreforfilter)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; $parameters = array(); @@ -460,15 +457,18 @@ print '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'" id="tablelines3">'."\n"; print '<tr class="liste_titre_filter">'; -if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>'; -if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>'; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { + print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>'; +} +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { + print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>'; +} print '<td class="liste_titre"><input type="text" size="4" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'"></td>'; print '<td class="liste_titre"></td>'; print '<td class="liste_titre right"><input type="text" size="4" name="search_declared_progress" value="'.dol_escape_htmltag($search_declared_progress).'"></td>'; print '<td class="liste_titre"></td>'; print '<td class="liste_titre"></td>'; -foreach ($TWeek as $week_number) -{ +foreach ($TWeek as $week_number) { print '<td class="liste_titre"></td>'; } // Action column @@ -479,19 +479,25 @@ print '</td>'; print "</tr>\n"; print '<tr class="liste_titre">'; -if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td>'.$langs->trans("Project").'</td>'; -if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td>'.$langs->trans("ThirdParty").'</td>'; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { + print '<td>'.$langs->trans("Project").'</td>'; +} +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { + print '<td>'.$langs->trans("ThirdParty").'</td>'; +} print '<td>'.$langs->trans("Task").'</td>'; print '<td align="right" class="leftborder plannedworkload maxwidth75">'.$langs->trans("PlannedWorkload").'</td>'; print '<td align="right" class="maxwidth75">'.$langs->trans("ProgressDeclared").'</td>'; /*print '<td align="right" class="maxwidth75">'.$langs->trans("TimeSpent").'</td>'; if ($usertoprocess->id == $user->id) print '<td align="right" class="maxwidth75">'.$langs->trans("TimeSpentByYou").'</td>'; else print '<td align="right" class="maxwidth75">'.$langs->trans("TimeSpentByUser").'</td>';*/ -print '<td align="right" class="maxwidth75">'.$langs->trans("TimeSpent").'<br><span class="opacitymedium">'.$langs->trans("Everybody").'</span></td>'; +print '<td align="right" class="maxwidth75">'.$langs->trans("TimeSpent").'<br>'; +print '<span class="opacitymedium nopadding userimg"><img alt="Photo" class="photouserphoto userphoto" src="'.DOL_URL_ROOT.'/theme/common/everybody.png"></span>'; +print '<span class="opacitymedium paddingleft">'.$langs->trans("Everybody").'</span>'; +print '</td>'; print '<td align="right" class="maxwidth75">'.$langs->trans("TimeSpent").($usertoprocess->firstname ? '<br>'.$usertoprocess->getNomUrl(-2).'<span class="opacitymedium paddingleft">'.dol_trunc($usertoprocess->firstname, 10).'</span>' : '').'</td>'; -foreach ($TWeek as $week_number) -{ +foreach ($TWeek as $week_number) { print '<td width="6%" align="center" class="bold hide">'.$langs->trans("Week").' '.$week_number.'<br>('.$TFirstDays[$week_number].'...'.$TLastDays[$week_number].')</td>'; } print '<td></td>'; @@ -507,8 +513,7 @@ $isavailable = array(); // TODO See code into perweek.php to initialize isavailable array -if (count($tasksarray) > 0) -{ +if (count($tasksarray) > 0) { //var_dump($tasksarray); // contains only selected tasks //var_dump($tasksarraywithoutfilter); // contains all tasks (if there is a filter, not defined if no filter) //var_dump($tasksrole); @@ -522,21 +527,17 @@ if (count($tasksarray) > 0) // Calculate total for all tasks $listofdistinctprojectid = array(); // List of all distinct projects - if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter)) - { - foreach ($tasksarraywithoutfilter as $tmptask) - { + if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter)) { + foreach ($tasksarraywithoutfilter as $tmptask) { $listofdistinctprojectid[$tmptask->fk_project] = $tmptask->fk_project; } } //var_dump($listofdistinctprojectid); $totalforeachweek = array(); - foreach ($listofdistinctprojectid as $tmpprojectid) - { + foreach ($listofdistinctprojectid as $tmpprojectid) { $projectstatic->id = $tmpprojectid; $projectstatic->loadTimeSpentMonth($firstdaytoshow, 0, $usertoprocess->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week - foreach ($TWeek as $weekNb) - { + foreach ($TWeek as $weekNb) { $totalforeachweek[$weekNb] += $projectstatic->monthWorkLoad[$weekNb]; } } @@ -546,13 +547,10 @@ if (count($tasksarray) > 0) // Is there a diff between selected/filtered tasks and all tasks ? $isdiff = 0; - if (count($totalforeachweek)) - { - foreach ($TWeek as $weekNb) - { + if (count($totalforeachweek)) { + foreach ($TWeek as $weekNb) { $timeonothertasks = ($totalforeachweek[$weekNb] - $totalforvisibletasks[$weekNb]); - if ($timeonothertasks) - { + if ($timeonothertasks) { $isdiff = 1; break; } @@ -560,19 +558,16 @@ if (count($tasksarray) > 0) } // There is a diff between total shown on screen and total spent by user, so we add a line with all other cumulated time of user - if ($isdiff) - { + if ($isdiff) { print '<tr class="oddeven othertaskwithtime">'; print '<td colspan="'.$colspan.'" class="opacitymedium">'; print $langs->trans("OtherFilteredTasks"); print '</td>'; - foreach ($TWeek as $weekNb) - { + foreach ($TWeek as $weekNb) { print '<td class="center hide">'; $timeonothertasks = ($totalforeachweek[$weekNb] - $totalforvisibletasks[$weekNb]); - if ($timeonothertasks) - { + if ($timeonothertasks) { print '<span class="timesheetalreadyrecorded" title="texttoreplace"><input type="text" class="center smallpadd" size="2" disabled="" id="timespent[-1]['.$weekNb.']" name="task[-1]['.$weekNb.']" value="'; print convertSecondToTime($timeonothertasks, 'allhourmin'); print '"></span>'; @@ -583,16 +578,14 @@ if (count($tasksarray) > 0) print '</tr>'; } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<tr class="liste_total"> <td class="liste_total" colspan="'.$colspan.'">'; print $langs->trans("Total"); print '<span class="opacitymediumbycolor"> - '.$langs->trans("ExpectedWorkedHours").': <strong>'.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).'</strong></span>'; print '</td>'; - foreach ($TWeek as $weekNb) - { + foreach ($TWeek as $weekNb) { print '<td class="liste_total hide'.$weekNb.'" align="center"><div class="totalDay'.$weekNb.'">'.convertSecondToTime($totalforvisibletasks[$weekNb], 'allhourmin').'</div></td>'; } print '<td class="liste_total center"><div class="totalDayAll">&nbsp;</div></td> @@ -615,8 +608,7 @@ print '</form>'."\n\n"; $modeinput = 'hours'; -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print "\n<!-- JS CODE TO ENABLE Tooltips on all object with class classfortooltip -->\n"; print '<script type="text/javascript">'."\n"; print "jQuery(document).ready(function () {\n"; @@ -629,8 +621,7 @@ if ($conf->use_javascript_ajax) } });'."\n"; - foreach ($TWeek as $week_number) - { + foreach ($TWeek as $week_number) { print ' updateTotal('.$week_number.',\''.$modeinput.'\');'; } print "\n});\n"; diff --git a/htdocs/projet/activity/perweek.php b/htdocs/projet/activity/perweek.php index f001a73d0f4..028bb97726c 100644 --- a/htdocs/projet/activity/perweek.php +++ b/htdocs/projet/activity/perweek.php @@ -46,7 +46,9 @@ $taskid = GETPOST('taskid', 'int'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'perweekcard'; $mine = 0; -if ($mode == 'mine') $mine = 1; +if ($mode == 'mine') { + $mine = 1; +} $projectid = isset($_GET["id"]) ? GETPOST("id", "int", 1) : GETPOST("projectid", "int"); @@ -99,12 +101,10 @@ $next_day = $next['day']; $firstdaytoshow = dol_mktime(0, 0, 0, $first_month, $first_day, $first_year); $lastdaytoshow = dol_time_plus_duree($firstdaytoshow, 7, 'd'); -if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) -{ +if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) { $usertoprocess = $user; $search_usertoprocessid = $usertoprocess->id; -} elseif ($search_usertoprocessid > 0) -{ +} elseif ($search_usertoprocessid > 0) { $usertoprocess = new User($db); $usertoprocess->fetch($search_usertoprocessid); $search_usertoprocessid = $usertoprocess->id; @@ -122,28 +122,27 @@ $extrafields->fetch_name_optionals_label($object->table_element); $arrayfields = array(); /*$arrayfields=array( - // Project - 'p.opp_amount'=>array('label'=>$langs->trans("OpportunityAmountShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>103), - 'p.fk_opp_status'=>array('label'=>$langs->trans("OpportunityStatusShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>104), - 'p.opp_percent'=>array('label'=>$langs->trans("OpportunityProbabilityShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>105), - 'p.budget_amount'=>array('label'=>$langs->trans("Budget"), 'checked'=>0, 'position'=>110), - 'p.usage_bill_time'=>array('label'=>$langs->trans("BillTimeShort"), 'checked'=>0, 'position'=>115), + // Project + 'p.opp_amount'=>array('label'=>$langs->trans("OpportunityAmountShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>103), + 'p.fk_opp_status'=>array('label'=>$langs->trans("OpportunityStatusShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>104), + 'p.opp_percent'=>array('label'=>$langs->trans("OpportunityProbabilityShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>105), + 'p.budget_amount'=>array('label'=>$langs->trans("Budget"), 'checked'=>0, 'position'=>110), + 'p.usage_bill_time'=>array('label'=>$langs->trans("BillTimeShort"), 'checked'=>0, 'position'=>115), );*/ $arrayfields['t.planned_workload'] = array('label'=>'PlannedWorkload', 'checked'=>1, 'enabled'=>1, 'position'=>0); $arrayfields['t.progress'] = array('label'=>'ProgressDeclared', 'checked'=>1, 'enabled'=>1, 'position'=>0); /*foreach($object->fields as $key => $val) { - // If $val['visible']==0, then we never show the field - if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); + // If $val['visible']==0, then we never show the field + if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); }*/ // Definition of fields for list // Extra fields -if (is_array($extrafields->attributes['projet_task']['label']) && count($extrafields->attributes['projet_task']['label']) > 0) -{ - foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) - { - if (!empty($extrafields->attributes['projet_task']['list'][$key])) +if (is_array($extrafields->attributes['projet_task']['label']) && count($extrafields->attributes['projet_task']['label']) > 0) { + foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) { + if (!empty($extrafields->attributes['projet_task']['list'][$key])) { $arrayfields["efpt.".$key] = array('label'=>$extrafields->attributes['projet_task']['label'][$key], 'checked'=>(($extrafields->attributes['projet_task']['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes['projet_task']['pos'][$key], 'enabled'=>(abs((int) $extrafields->attributes['projet_task']['list'][$key]) != 3 && $extrafields->attributes['projet_task']['perms'][$key])); + } } } $arrayfields = dol_sort_array($arrayfields, 'position'); @@ -160,10 +159,11 @@ $search_array_options_task = $extrafields->getOptionalsFromPost('projet_task', ' $parameters = array('id' => $id, 'taskid' => $taskid, 'projectid' => $projectid); $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'); +} // Purge 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 $action = ''; $search_categ = ''; $search_usertoprocessid = $user->id; @@ -179,13 +179,11 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' // We redefine $usertoprocess $usertoprocess = $user; } -if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha')) -{ +if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha')) { $action = ''; } -if (GETPOST('submitdateselect')) -{ +if (GETPOST('submitdateselect')) { $daytoparse = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); $action = ''; @@ -193,47 +191,41 @@ if (GETPOST('submitdateselect')) include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; -if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') && GETPOST('formfilteraction') != 'listafterchangingselectedfields') -{ +if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') && GETPOST('formfilteraction') != 'listafterchangingselectedfields') { $action = 'assigntask'; - if ($taskid > 0) - { + if ($taskid > 0) { $result = $object->fetch($taskid, $ref); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } else { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors'); $error++; } - if (!GETPOST('type')) - { + if (!GETPOST('type')) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors'); $error++; } - if (!$error) - { + if (!$error) { $idfortaskuser = $usertoprocess->id; $result = $object->add_contact($idfortaskuser, GETPOST("type"), 'internal'); - if ($result >= 0 || $result == -2) // Contact add ok or already contact of task - { + if ($result >= 0 || $result == -2) { // Contact add ok or already contact of task // Test if we are already contact of the project (should be rare but sometimes we can add as task contact without being contact of project, like when admin user has been removed from contact of project) $sql = 'SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact'; $sql .= ' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if (!$obj) // User is not already linked to project, so we will create link to first type - { + if (!$obj) { // User is not already linked to project, so we will create link to first type $project = new Project($db); $project->fetch($object->fk_project); // Get type $listofprojcontact = $project->liste_type_contact('internal'); - if (count($listofprojcontact)) - { + if (count($listofprojcontact)) { $typeforprojectcontact = reset(array_keys($listofprojcontact)); $result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal'); } @@ -244,11 +236,9 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') } } - if ($result < 0) - { + if ($result < 0) { $error++; - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorTaskAlreadyAssigned"), null, 'warnings'); } else { @@ -256,8 +246,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') } } - if (!$error) - { + if (!$error) { setEventMessages("TaskAssignedToEnterTime", null); $taskid = 0; } @@ -265,33 +254,36 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') $action = ''; } -if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilteraction') != 'listafterchangingselectedfields') -{ +if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilteraction') != 'listafterchangingselectedfields') { $timetoadd = $_POST['task']; - if (empty($timetoadd)) - { + if (empty($timetoadd)) { setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors'); } else { - foreach ($timetoadd as $taskid => $value) // Loop on each task - { + foreach ($timetoadd as $taskid => $value) { // Loop on each task $updateoftaskdone = 0; - foreach ($value as $key => $val) // Loop on each day - { + foreach ($value as $key => $val) { // Loop on each day $amountoadd = $timetoadd[$taskid][$key]; - if (!empty($amountoadd)) - { + if (!empty($amountoadd)) { $tmpduration = explode(':', $amountoadd); $newduration = 0; - if (!empty($tmpduration[0])) $newduration += ($tmpduration[0] * 3600); - if (!empty($tmpduration[1])) $newduration += ($tmpduration[1] * 60); - if (!empty($tmpduration[2])) $newduration += ($tmpduration[2]); + if (!empty($tmpduration[0])) { + $newduration += ($tmpduration[0] * 3600); + } + if (!empty($tmpduration[1])) { + $newduration += ($tmpduration[1] * 60); + } + if (!empty($tmpduration[2])) { + $newduration += ($tmpduration[2]); + } - if ($newduration > 0) - { - $object->fetch($taskid); + if ($newduration > 0) { + $object->fetch($taskid); - if (GETPOSTISSET($taskid.'progress')) $object->progress = GETPOST($taskid.'progress', 'int'); - else unset($object->progress); + if (GETPOSTISSET($taskid.'progress')) { + $object->progress = GETPOST($taskid.'progress', 'int'); + } else { + unset($object->progress); + } $object->timespent_duration = $newduration; $object->timespent_fk_user = $usertoprocess->id; @@ -300,8 +292,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac $object->timespent_note = $object->description; $result = $object->addTimeSpent($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; break; @@ -312,16 +303,13 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac } } - if (!$updateoftaskdone) // Check to update progress if no update were done on task. - { + if (!$updateoftaskdone) { // Check to update progress if no update were done on task. $object->fetch($taskid); //var_dump($object->progress);var_dump(GETPOST($taskid . 'progress', 'int')); exit; - if ($object->progress != GETPOST($taskid.'progress', 'int')) - { + if ($object->progress != GETPOST($taskid.'progress', 'int')) { $object->progress = GETPOST($taskid.'progress', 'int'); $result = $object->update($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; break; @@ -330,8 +318,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac } } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); $param = ''; @@ -347,18 +334,18 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac $param .= ($search_task_label ? '&search_task_label='.urlencode($search_task_label) : ''); /*$search_array_options=$search_array_options_project; - $search_options_pattern='search_options_'; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; - */ + $search_options_pattern='search_options_'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + */ $search_array_options = $search_array_options_task; $search_options_pattern = 'search_task_options_'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; - // Redirect to avoid submit twice on back - header('Location: '.$_SERVER["PHP_SELF"].'?'.$param); - exit; - } + // Redirect to avoid submit twice on back + header('Location: '.$_SERVER["PHP_SELF"].'?'.$param); + exit; + } } } @@ -381,8 +368,7 @@ $title = $langs->trans("TimeSpent"); $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess, (empty($usertoprocess->id) ? 2 : 0), 1); // Return all project i have permission on (assigned to me+public). I want my tasks and some of my task may be on a public projet that is not my project //var_dump($projectsListId); -if ($id) -{ +if ($id) { $project->fetch($id); $project->fetch_thirdparty(); } @@ -390,11 +376,21 @@ if ($id) $onlyopenedproject = 1; // or -1 $morewherefilter = ''; -if ($search_project_ref) $morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref); -if ($search_task_ref) $morewherefilter .= natural_search("t.ref", $search_task_ref); -if ($search_task_label) $morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label); -if ($search_thirdparty) $morewherefilter .= natural_search("s.nom", $search_thirdparty); -if ($search_declared_progress) $morewherefilter .= natural_search("t.progress", $search_declared_progress, 1); +if ($search_project_ref) { + $morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref); +} +if ($search_task_ref) { + $morewherefilter .= natural_search("t.ref", $search_task_ref); +} +if ($search_task_label) { + $morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label); +} +if ($search_thirdparty) { + $morewherefilter .= natural_search("s.nom", $search_thirdparty); +} +if ($search_declared_progress) { + $morewherefilter .= natural_search("t.progress", $search_declared_progress, 1); +} $sql = &$morewherefilter; @@ -411,8 +407,7 @@ $extrafieldsobjectkey = 'projet_task'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; $tasksarray = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid ? $search_usertoprocessid : 0), 0, $extrafields); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. -if ($morewherefilter) // Get all task without any filter, so we can show total of time spent for not visible tasks -{ +if ($morewherefilter) { // Get all task without any filter, so we can show total of time spent for not visible tasks $tasksarraywithoutfilter = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, '', $onlyopenedproject, '', ($search_usertoprocessid ? $search_usertoprocessid : 0)); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. } $projectsrole = $taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id ? $project->id : 0), 0, $onlyopenedproject); @@ -468,16 +463,18 @@ print dol_get_fiche_head($head, 'inputperweek', $langs->trans('TimeSpent'), -1, // Show description of content print '<div class="hideonsmartphone opacitymedium">'; -if ($mine || ($usertoprocess->id == $user->id)) print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; -else { - if (empty($usertoprocess->id) || $usertoprocess->id < 0) - { - if ($user->rights->projet->all->lire && !$socid) print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; - else print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; +if ($mine || ($usertoprocess->id == $user->id)) { + print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; +} else { + if (empty($usertoprocess->id) || $usertoprocess->id < 0) { + if ($user->rights->projet->all->lire && !$socid) { + print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; + } else { + print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>'; + } } } -if ($mine || ($usertoprocess->id == $user->id)) -{ +if ($mine || ($usertoprocess->id == $user->id)) { print $langs->trans("OnlyYourTaskAreVisible").'<br>'; } else { print $langs->trans("AllTaskVisibleButEditIfYouAreAssigned").'<br>'; @@ -490,7 +487,9 @@ print '<div class="floatright right'.($conf->dol_optimize_smallscreen ? ' centpe print '<div class="colorbacktimesheet float valignmiddle">'; $titleassigntask = $langs->transnoentities("AssignTaskToMe"); -if ($usertoprocess->id != $user->id) $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs)); +if ($usertoprocess->id != $user->id) { + $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs)); +} print '<div class="taskiddiv inline-block">'; print img_picto('', 'projecttask'); $formproject->selectTasks($socid ? $socid : -1, $taskid, 'taskid', 32, 0, '-- '.$langs->trans("ChooseANotYetAssignedTask").' --', 1, 0, 0, '', '', 'all', $usertoprocess); @@ -507,18 +506,15 @@ $startday = dol_mktime(12, 0, 0, $startdayarray['first_month'], $startdayarray[' // Get if user is available or not for each day $isavailable = array(); -if (!empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) -{ +if (!empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) { $tmparray = explode('-', $conf->global->MAIN_DEFAULT_WORKING_DAYS); - if (count($tmparray) >= 2) - { + if (count($tmparray) >= 2) { $numstartworkingday = $tmparray[0]; $numendworkingday = $tmparray[1]; } } -for ($idw = 0; $idw < 7; $idw++) -{ +for ($idw = 0; $idw < 7; $idw++) { $dayinloopfromfirstdaytoshow = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); // $firstdaytoshow is a date with hours = 0 $dayinloop = dol_time_plus_duree($startday, $idw, 'd'); @@ -535,7 +531,9 @@ for ($idw = 0; $idw < 7; $idw++) $isavailable[$dayinloopfromfirstdaytoshow] = $isavailablefordayanduser; // in projectLinesPerWeek later, we are using $firstdaytoshow and dol_time_plus_duree to loop on each day $test = num_public_holiday($dayinloopfromfirstdaytoshow, $dayinloopfromfirstdaytoshow + 86400, $mysoc->country_code); - if ($test) $isavailable[$dayinloopfromfirstdaytoshow] = array('morning'=>false, 'afternoon'=>false, 'morning_reason'=>'public_holiday', 'afternoon_reason'=>'public_holiday'); + if ($test) { + $isavailable[$dayinloopfromfirstdaytoshow] = array('morning'=>false, 'afternoon'=>false, 'morning_reason'=>'public_holiday', 'afternoon_reason'=>'public_holiday'); + } } //var_dump($isavailable); @@ -558,12 +556,13 @@ if (! empty($conf->categorie->enabled)) $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= '<div class="inline-block hideonsmartphone"></div>'; $includeonly = 'hierarchyme'; -if (empty($user->rights->user->user->lire)) $includeonly = array($user->id); +if (empty($user->rights->user->user->lire)) { + $includeonly = array($user->id); +} $moreforfilter .= img_picto($langs->trans('Filter').' '.$langs->trans('User'), 'user').$form->select_dolusers($search_usertoprocessid ? $search_usertoprocessid : $usertoprocess->id, 'search_usertoprocessid', $user->rights->user->user->lire ? 0 : 0, null, 0, $includeonly, null, 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter .= '</div>'; -if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) -{ +if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= '<div class="inline-block"></div>'; $moreforfilter .= img_picto($langs->trans('Filter').' '.$langs->trans('Project'), 'project').'<input type="text" size="4" name="search_project_ref" class="marginleftonly" value="'.dol_escape_htmltag($search_project_ref).'">'; @@ -575,8 +574,7 @@ if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) $moreforfilter .= '</div>'; } -if (!empty($moreforfilter)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; $parameters = array(); @@ -592,19 +590,28 @@ $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfi // This must be after the $selectedfields $addcolspan = 0; -if (!empty($arrayfields['t.planned_workload']['checked'])) $addcolspan++; -if (!empty($arrayfields['t.progress']['checked'])) $addcolspan++; -foreach ($arrayfields as $key => $val) -{ - if ($val['checked'] && substr($key, 0, 5) == 'efpt.') $addcolspan++; +if (!empty($arrayfields['t.planned_workload']['checked'])) { + $addcolspan++; +} +if (!empty($arrayfields['t.progress']['checked'])) { + $addcolspan++; +} +foreach ($arrayfields as $key => $val) { + if ($val['checked'] && substr($key, 0, 5) == 'efpt.') { + $addcolspan++; + } } print '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'" id="tablelines3">'."\n"; print '<tr class="liste_titre_filter">'; -if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>'; -if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>'; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { + print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>'; +} +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { + print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>'; +} print '<td class="liste_titre"><input type="text" size="4" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'"></td>'; // TASK fields $search_options_pattern = 'search_task_options_'; @@ -612,17 +619,14 @@ $extrafieldsobjectkey = 'projet_task'; $extrafieldsobjectprefix = 'efpt.'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; print '<td class="liste_titre"></td>'; -if (!empty($arrayfields['t.planned_workload']['checked'])) -{ +if (!empty($arrayfields['t.planned_workload']['checked'])) { print '<td class="liste_titre right"><input type="text" size="4" name="search_declared_progress" value="'.dol_escape_htmltag($search_declared_progress).'"></td>'; } -if (!empty($arrayfields['t.progress']['checked'])) -{ +if (!empty($arrayfields['t.progress']['checked'])) { print '<td class="liste_titre"></td>'; } print '<td class="liste_titre"></td>'; -for ($idw = 0; $idw < 7; $idw++) -{ +for ($idw = 0; $idw < 7; $idw++) { print '<td class="liste_titre"></td>'; } // Action column @@ -633,44 +637,51 @@ print '</td>'; print "</tr>\n"; print '<tr class="liste_titre">'; -if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<th>'.$langs->trans("Project").'</th>'; -if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<th>'.$langs->trans("ThirdParty").'</th>'; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { + print '<th>'.$langs->trans("Project").'</th>'; +} +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { + print '<th>'.$langs->trans("ThirdParty").'</th>'; +} print '<th>'.$langs->trans("Task").'</th>'; // TASK fields $extrafieldsobjectkey = 'projet_task'; $extrafieldsobjectprefix = 'efpt.'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; -if (!empty($arrayfields['t.planned_workload']['checked'])) -{ +if (!empty($arrayfields['t.planned_workload']['checked'])) { print '<th class="leftborder plannedworkload maxwidth75 right">'.$langs->trans("PlannedWorkload").'</th>'; } -if (!empty($arrayfields['t.progress']['checked'])) -{ +if (!empty($arrayfields['t.progress']['checked'])) { print '<th class="maxwidth75 right">'.$langs->trans("ProgressDeclared").'</th>'; } /*print '<td class="maxwidth75 right">'.$langs->trans("TimeSpent").'</td>'; if ($usertoprocess->id == $user->id) print '<td class="maxwidth75 right">'.$langs->trans("TimeSpentByYou").'</td>'; else print '<td class="maxwidth75 right">'.$langs->trans("TimeSpentByUser").'</td>';*/ -print '<th class="maxwidth75 right">'.$langs->trans("TimeSpent").'<br><span class="opacitymedium">'.$langs->trans("Everybody").'</span></th>'; +print '<th class="maxwidth75 right">'.$langs->trans("TimeSpent").'<br>'; +print '<span class="opacitymedium nopadding userimg"><img alt="Photo" class="photouserphoto userphoto" src="'.DOL_URL_ROOT.'/theme/common/everybody.png"></span>'; +print '<span class="opacitymedium paddingleft">'.$langs->trans("Everybody").'</span>'; +print '</th>'; print '<th class="maxwidth75 right">'.$langs->trans("TimeSpent").($usertoprocess->firstname ? '<br>'.$usertoprocess->getNomUrl(-2).'<span class="opacitymedium paddingleft">'.dol_trunc($usertoprocess->firstname, 10).'</span>' : '').'</th>'; -for ($idw = 0; $idw < 7; $idw++) -{ +for ($idw = 0; $idw < 7; $idw++) { $dayinloopfromfirstdaytoshow = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); // $firstdaytoshow is a date with hours = 0 $dayinloop = dol_time_plus_duree($startday, $idw, 'd'); $cssweekend = ''; - if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. - { + if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) { // This is a day is not inside the setup of working days, so we use a week-end css. $cssweekend = 'weekend'; } $tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); $cssonholiday = ''; - if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayallday '; - elseif (!$isavailable[$tmpday]['morning']) $cssonholiday .= 'onholidaymorning '; - elseif (!$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; + if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) { + $cssonholiday .= 'onholidayallday '; + } elseif (!$isavailable[$tmpday]['morning']) { + $cssonholiday .= 'onholidaymorning '; + } elseif (!$isavailable[$tmpday]['afternoon']) { + $cssonholiday .= 'onholidayafternoon '; + } print '<th width="6%" align="center" class="bold hide'.$idw.($cssonholiday ? ' '.$cssonholiday : '').($cssweekend ? ' '.$cssweekend : '').'">'.dol_print_date($dayinloopfromfirstdaytoshow, '%a').'<br>'.dol_print_date($dayinloopfromfirstdaytoshow, 'dayreduceformat').'</th>'; } @@ -682,28 +693,29 @@ print "</tr>\n"; $colspan = 3 + (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : 2); -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print '<tr class="liste_total">'; print '<td class="liste_total" colspan="'.($colspan + $addcolspan).'">'; print $langs->trans("Total"); print '<span class="opacitymediumbycolor"> - '.$langs->trans("ExpectedWorkedHours").': <strong>'.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).'</strong></span>'; print '</td>'; - for ($idw = 0; $idw < 7; $idw++) - { + for ($idw = 0; $idw < 7; $idw++) { $cssweekend = ''; - if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. - { + if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) { // This is a day is not inside the setup of working days, so we use a week-end css. $cssweekend = 'weekend'; } $tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); $cssonholiday = ''; - if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayallday '; - elseif (!$isavailable[$tmpday]['morning']) $cssonholiday .= 'onholidaymorning '; - elseif (!$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; + if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) { + $cssonholiday .= 'onholidayallday '; + } elseif (!$isavailable[$tmpday]['morning']) { + $cssonholiday .= 'onholidaymorning '; + } elseif (!$isavailable[$tmpday]['afternoon']) { + $cssonholiday .= 'onholidayafternoon '; + } print '<td class="liste_total hide'.$idw.($cssonholiday ? ' '.$cssonholiday : '').($cssweekend ? ' '.$cssweekend : '').'" align="center"><div class="totalDay'.$idw.'">&nbsp;</div></td>'; } print '<td class="liste_total center"><div class="totalDayAll">&nbsp;</div></td>'; @@ -714,8 +726,7 @@ if ($conf->use_javascript_ajax) // By default, we can edit only tasks we are assigned to $restrictviewformytask = ((!isset($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED)) ? 2 : $conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED); -if (count($tasksarray) > 0) -{ +if (count($tasksarray) > 0) { //var_dump($tasksarray); // contains only selected tasks //var_dump($tasksarraywithoutfilter); // contains all tasks (if there is a filter, not defined if no filter) //var_dump($tasksrole); @@ -729,21 +740,17 @@ if (count($tasksarray) > 0) // Calculate total for all tasks $listofdistinctprojectid = array(); // List of all distinct projects - if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter)) - { - foreach ($tasksarraywithoutfilter as $tmptask) - { + if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter)) { + foreach ($tasksarraywithoutfilter as $tmptask) { $listofdistinctprojectid[$tmptask->fk_project] = $tmptask->fk_project; } } //var_dump($listofdistinctprojectid); $totalforeachday = array(); - foreach ($listofdistinctprojectid as $tmpprojectid) - { + foreach ($listofdistinctprojectid as $tmpprojectid) { $projectstatic->id = $tmpprojectid; $projectstatic->loadTimeSpent($firstdaytoshow, 0, $usertoprocess->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week - for ($idw = 0; $idw < 7; $idw++) - { + for ($idw = 0; $idw < 7; $idw++) { $tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); $totalforeachday[$tmpday] += $projectstatic->weekWorkLoad[$tmpday]; } @@ -754,14 +761,11 @@ if (count($tasksarray) > 0) // Is there a diff between selected/filtered tasks and all tasks ? $isdiff = 0; - if (count($totalforeachday)) - { - for ($idw = 0; $idw < 7; $idw++) - { + if (count($totalforeachday)) { + for ($idw = 0; $idw < 7; $idw++) { $tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); $timeonothertasks = ($totalforeachday[$tmpday] - $totalforvisibletasks[$tmpday]); - if ($timeonothertasks) - { + if ($timeonothertasks) { $isdiff = 1; break; } @@ -769,25 +773,21 @@ if (count($tasksarray) > 0) } // There is a diff between total shown on screen and total spent by user, so we add a line with all other cumulated time of user - if ($isdiff) - { + if ($isdiff) { print '<tr class="oddeven othertaskwithtime">'; print '<td colspan="'.($colspan + $addcolspan).'" class="opacitymedium">'; print $langs->trans("OtherFilteredTasks"); print '</td>'; - for ($idw = 0; $idw < 7; $idw++) - { + for ($idw = 0; $idw < 7; $idw++) { $cssweekend = ''; - if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. - { + if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) { // This is a day is not inside the setup of working days, so we use a week-end css. $cssweekend = 'weekend'; } print '<td class="center hide'.$idw.' '.($cssweekend ? ' '.$cssweekend : '').'">'; $tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); $timeonothertasks = ($totalforeachday[$tmpday] - $totalforvisibletasks[$tmpday]); - if ($timeonothertasks) - { + if ($timeonothertasks) { print '<span class="timesheetalreadyrecorded" title="texttoreplace"><input type="text" class="center smallpadd" size="2" disabled="" id="timespent[-1]['.$idw.']" name="task[-1]['.$idw.']" value="'; print convertSecondToTime($timeonothertasks, 'allhourmin'); print '"></span>'; @@ -798,8 +798,7 @@ if (count($tasksarray) > 0) print '</tr>'; } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<tr class="liste_total"> <td class="liste_total" colspan="'.($colspan + $addcolspan).'">'; print $langs->trans("Total"); @@ -808,17 +807,20 @@ if (count($tasksarray) > 0) for ($idw = 0; $idw < 7; $idw++) { $cssweekend = ''; - if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. - { + if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) { // This is a day is not inside the setup of working days, so we use a week-end css. $cssweekend = 'weekend'; } $tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); $cssonholiday = ''; - if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayallday '; - elseif (!$isavailable[$tmpday]['morning']) $cssonholiday .= 'onholidaymorning '; - elseif (!$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; + if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) { + $cssonholiday .= 'onholidayallday '; + } elseif (!$isavailable[$tmpday]['morning']) { + $cssonholiday .= 'onholidaymorning '; + } elseif (!$isavailable[$tmpday]['afternoon']) { + $cssonholiday .= 'onholidayafternoon '; + } print '<td class="liste_total hide'.$idw.($cssonholiday ? ' '.$cssonholiday : '').($cssweekend ? ' '.$cssweekend : '').'" align="center"><div class="totalDay'.$idw.'">&nbsp;</div></td>'; } @@ -841,8 +843,7 @@ print '</form>'."\n\n"; $modeinput = 'hours'; -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print "\n<!-- JS CODE TO ENABLE Tooltips on all object with class classfortooltip -->\n"; print '<script type="text/javascript">'."\n"; print "jQuery(document).ready(function () {\n"; @@ -856,8 +857,7 @@ if ($conf->use_javascript_ajax) });'."\n"; $idw = 0; - while ($idw < 7) - { + while ($idw < 7) { print ' updateTotal('.$idw.',\''.$modeinput.'\');'; $idw++; } diff --git a/htdocs/projet/admin/project.php b/htdocs/projet/admin/project.php index f36aae34c4f..e0018aa0e4b 100644 --- a/htdocs/projet/admin/project.php +++ b/htdocs/projet/admin/project.php @@ -36,7 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'errors', 'other', 'projects')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $value = GETPOST('value', 'alpha'); $action = GETPOST('action', 'aZ09'); @@ -51,40 +53,43 @@ $type = 'project'; include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; -if ($action == 'updateMask') -{ +if ($action == 'updateMask') { $maskconstproject = GETPOST('maskconstproject', 'alpha'); $maskproject = GETPOST('maskproject', 'alpha'); - if ($maskconstproject) $res = dolibarr_set_const($db, $maskconstproject, $maskproject, 'chaine', 0, '', $conf->entity); + if ($maskconstproject) { + $res = dolibarr_set_const($db, $maskconstproject, $maskproject, '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'); } } -if ($action == 'updateMaskTask') -{ +if ($action == 'updateMaskTask') { $maskconstmasktask = GETPOST('maskconsttask', 'alpha'); $masktaskt = GETPOST('masktask', 'alpha'); - if ($maskconstmasktask) $res = dolibarr_set_const($db, $maskconstmasktask, $masktaskt, 'chaine', 0, '', $conf->entity); + if ($maskconstmasktask) { + $res = dolibarr_set_const($db, $maskconstmasktask, $masktaskt, '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'); } -} elseif ($action == 'specimen') -{ +} elseif ($action == 'specimen') { $modele = GETPOST('module', 'alpha'); $project = new Project($db); @@ -93,25 +98,21 @@ if ($action == 'updateMaskTask') // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/project/doc/pdf_".$modele.".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db); - if ($module->write_file($project, $langs) > 0) - { + if ($module->write_file($project, $langs) > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=project&file=SPECIMEN.pdf"); return; } else { @@ -122,8 +123,7 @@ if ($action == 'updateMaskTask') setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); } -} elseif ($action == 'specimentask') -{ +} elseif ($action == 'specimentask') { $modele = GETPOST('module', 'alpha'); $project = new Project($db); @@ -132,25 +132,21 @@ if ($action == 'updateMaskTask') // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/project/task/doc/pdf_".$modele.".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db); - if ($module->write_file($project, $langs) > 0) - { + if ($module->write_file($project, $langs) > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=project_task&file=SPECIMEN.pdf"); return; } else { @@ -161,49 +157,37 @@ if ($action == 'updateMaskTask') setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); } -} - -// Activate a model -elseif ($action == 'set') -{ +} elseif ($action == 'set') { + // Activate a model $ret = addDocumentModel($value, $type, $label, $scandir); -} -// Activate a model for task -elseif ($action == 'settask') -{ +} elseif ($action == 'settask') { + // Activate a model for task $ret = addDocumentModel($value, 'project_task', $label, $scandir); -} elseif ($action == 'del') -{ +} elseif ($action == 'del') { $ret = delDocumentModel($value, $type); - if ($ret > 0) - { - if ($conf->global->PROJECT_ADDON_PDF == "$value") dolibarr_del_const($db, 'PROJECT_ADDON_PDF', $conf->entity); + if ($ret > 0) { + if ($conf->global->PROJECT_ADDON_PDF == "$value") { + dolibarr_del_const($db, 'PROJECT_ADDON_PDF', $conf->entity); + } } -} -if ($action == 'deltask') -{ +} elseif ($action == 'deltask') { $ret = delDocumentModel($value, 'project_task'); - if ($ret > 0) - { - if ($conf->global->PROJECT_TASK_ADDON_PDF == "$value") dolibarr_del_const($db, 'PROJECT_TASK_ADDON_PDF', $conf->entity); + if ($ret > 0) { + if ($conf->global->PROJECT_TASK_ADDON_PDF == "$value") { + dolibarr_del_const($db, 'PROJECT_TASK_ADDON_PDF', $conf->entity); + } } -} - -// Set default model -elseif ($action == 'setdoc') -{ +} elseif ($action == 'setdoc') { + // Set default model dolibarr_set_const($db, "PROJECT_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity); // On active le modele $ret = delDocumentModel($value, $type); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, $type, $label, $scandir); } -} elseif ($action == 'setdoctask') -{ - if (dolibarr_set_const($db, "PROJECT_TASK_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) - { +} elseif ($action == 'setdoctask') { + if (dolibarr_set_const($db, "PROJECT_TASK_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { // La constante qui a ete lue en avant du nouveau set // on passe donc par une variable pour avoir un affichage coherent $conf->global->PROJECT_TASK_ADDON_PDF = $value; @@ -211,40 +195,37 @@ elseif ($action == 'setdoc') // On active le modele $ret = delDocumentModel($value, 'project_task'); - if ($ret > 0) - { + if ($ret > 0) { $ret = addDocumentModel($value, 'project_task', $label, $scandir); } -} elseif ($action == 'setmod') -{ +} elseif ($action == 'setmod') { // TODO Verifier si module numerotation choisi peut etre active // par appel methode canBeActivated dolibarr_set_const($db, "PROJECT_ADDON", $value, 'chaine', 0, '', $conf->entity); -} elseif ($action == 'setmodtask') -{ +} elseif ($action == 'setmodtask') { // TODO Verifier si module numerotation choisi peut etre active // par appel methode canBeActivated dolibarr_set_const($db, "PROJECT_TASK_ADDON", $value, 'chaine', 0, '', $conf->entity); -} elseif ($action == 'updateoptions') -{ - if (GETPOST('PROJECT_USE_SEARCH_TO_SELECT')) - { +} elseif ($action == 'updateoptions') { + if (GETPOST('PROJECT_USE_SEARCH_TO_SELECT')) { $companysearch = GETPOST('activate_PROJECT_USE_SEARCH_TO_SELECT', 'alpha'); - if (dolibarr_set_const($db, "PROJECT_USE_SEARCH_TO_SELECT", $companysearch, 'chaine', 0, '', $conf->entity)) - { + if (dolibarr_set_const($db, "PROJECT_USE_SEARCH_TO_SELECT", $companysearch, 'chaine', 0, '', $conf->entity)) { $conf->global->PROJECT_USE_SEARCH_TO_SELECT = $companysearch; } } - if (GETPOST('PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY')) - { + if (GETPOST('PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY')) { $projectToSelect = GETPOST('projectToSelect', 'alpha'); dolibarr_set_const($db, 'PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY', $projectToSelect, 'chaine', 0, '', $conf->entity); //Allow to disable this configuration if empty value } +} elseif (preg_match('/^(set|del)_?([A-Z_]+)$/', $action, $reg)) { + // Set boolean (on/off) constants + if (!dolibarr_set_const($db, $reg[2], ($reg[1] === 'set' ? '1' : '0'), 'chaine', 0, '', $conf->entity) > 0) { + dol_print_error($db); + } } - /* * View */ @@ -317,19 +298,14 @@ print "</tr>\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ +foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/project/"); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/^(mod_.*)\.php$/i', $file, $reg)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/^(mod_.*)\.php$/i', $file, $reg)) { $file = $reg[1]; $classname = substr($file, 4); @@ -338,11 +314,14 @@ foreach ($dirmodels as $reldir) $module = new $file; // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } - if ($module->isEnabled()) - { + if ($module->isEnabled()) { print '<tr class="oddeven"><td>'.$module->name."</td><td>\n"; print $module->info(); print '</td>'; @@ -353,13 +332,15 @@ foreach ($dirmodels as $reldir) if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '<div class="error">'.$langs->trans($tmp).'</div>'; - } elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); - else print $tmp; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; + } print '</td>'."\n"; print '<td class="center">'; - if ($conf->global->PROJECT_ADDON == 'mod_'.$classname) - { + if ($conf->global->PROJECT_ADDON == 'mod_'.$classname) { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setmod&amp;token='.newToken().'&amp;value=mod_'.$classname.'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'switch_off').'</a>'; @@ -373,11 +354,9 @@ foreach ($dirmodels as $reldir) $htmltooltip = ''; $htmltooltip .= ''.$langs->trans("Version").': <b>'.$module->getVersion().'</b><br>'; $nextval = $module->getNextValue($mysoc, $project); - if ("$nextval" != $langs->trans("NotAvailable")) // Keep " on nextval - { + if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= ''.$langs->trans("NextValue").': '; - if ($nextval) - { + if ($nextval) { $htmltooltip .= $nextval.'<br>'; } else { $htmltooltip .= $langs->trans($module->error).'<br>'; @@ -400,8 +379,7 @@ foreach ($dirmodels as $reldir) print '</table><br>'; -if (empty($conf->global->PROJECT_HIDE_TASKS)) -{ +if (empty($conf->global->PROJECT_HIDE_TASKS)) { // Task numbering module print load_fiche_titre($langs->trans("TasksNumberingModules"), '', ''); @@ -416,19 +394,14 @@ if (empty($conf->global->PROJECT_HIDE_TASKS)) clearstatcache(); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/project/task/"); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/^(mod_.*)\.php$/i', $file, $reg)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/^(mod_.*)\.php$/i', $file, $reg)) { $file = $reg[1]; $classname = substr($file, 4); @@ -437,11 +410,14 @@ if (empty($conf->global->PROJECT_HIDE_TASKS)) $module = new $file; // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } - if ($module->isEnabled()) - { + if ($module->isEnabled()) { print '<tr class="oddeven"><td>'.$module->name."</td><td>\n"; print $module->info(); print '</td>'; @@ -452,13 +428,15 @@ if (empty($conf->global->PROJECT_HIDE_TASKS)) if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '<div class="error">'.$langs->trans($tmp).'</div>'; - } elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); - else print $tmp; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; + } print '</td>'."\n"; print '<td class="center">'; - if ($conf->global->PROJECT_TASK_ADDON == 'mod_'.$classname) - { + if ($conf->global->PROJECT_TASK_ADDON == 'mod_'.$classname) { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setmodtask&amp;token='.newToken().'&amp;value=mod_'.$classname.'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'switch_off').'</a>'; @@ -472,11 +450,9 @@ if (empty($conf->global->PROJECT_HIDE_TASKS)) $htmltooltip = ''; $htmltooltip .= ''.$langs->trans("Version").': <b>'.$module->getVersion().'</b><br>'; $nextval = $module->getNextValue($mysoc, $project); - if ("$nextval" != $langs->trans("NotAvailable")) // Keep " on nextval - { + if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= ''.$langs->trans("NextValue").': '; - if ($nextval) - { + if ($nextval) { $htmltooltip .= $nextval.'<br>'; } else { $htmltooltip .= $langs->trans($module->error).'<br>'; @@ -516,12 +492,10 @@ $sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -542,30 +516,22 @@ print "</tr>\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ - foreach (array('', '/doc') as $valdir) - { +foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { $dir = dol_buildpath($reldir."core/modules/project/".$valdir); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -573,21 +539,26 @@ 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 == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print '<tr class="oddeven"><td width="100">'; print (empty($module->name) ? $name : $module->name); print "</td><td>\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print "</td>\n"; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print "<td class=\"center\">\n"; print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&amp;token='.newToken().'&amp;value='.$name.'&amp;scan_dir='.$module->scandir.'&amp;label='.urlencode($module->name).'">'; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -601,8 +572,7 @@ foreach ($dirmodels as $reldir) // Default print "<td class=\"center\">"; - if ($conf->global->PROJECT_ADDON_PDF == "$name") - { + if ($conf->global->PROJECT_ADDON_PDF == "$name") { print img_picto($langs->trans("Default"), 'on'); } else { print '<a href="'.$_SERVER["PHP_SELF"].'?action=setdoc&amp;token='.newToken().'&amp;value='.$name.'&amp;scan_dir='.$module->scandir.'&amp;label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').'</a>'; @@ -612,8 +582,7 @@ foreach ($dirmodels as $reldir) // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } $htmltooltip .= '<br><br><u>'.$langs->trans("FeaturesSupported").':</u>'; @@ -625,8 +594,7 @@ foreach ($dirmodels as $reldir) // Preview print '<td class="center">'; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'">'.img_object($langs->trans("Preview"), 'bill').'</a>'; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); @@ -647,8 +615,7 @@ print '</table><br/>'; -if (empty($conf->global->PROJECT_HIDE_TASKS)) -{ +if (empty($conf->global->PROJECT_HIDE_TASKS)) { /* * Modeles documents for Task */ @@ -665,12 +632,10 @@ if (empty($conf->global->PROJECT_HIDE_TASKS)) $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -691,30 +656,22 @@ if (empty($conf->global->PROJECT_HIDE_TASKS)) clearstatcache(); - foreach ($dirmodels as $reldir) - { - foreach (array('', '/doc') as $valdir) - { + foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { $dir = dol_buildpath($reldir."core/modules/project/task/".$valdir); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -722,21 +679,26 @@ if (empty($conf->global->PROJECT_HIDE_TASKS)) $module = new $classname($db); $modulequalified = 1; - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print '<tr class="oddeven"><td width="100">'; print (empty($module->name) ? $name : $module->name); print "</td><td>\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print "</td>\n"; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print "<td class=\"center\">\n"; print '<a href="'.$_SERVER["PHP_SELF"].'?action=deltask&amp;value='.$name.'&amp;scan_dir='.$module->scandir.'&amp;label='.urlencode($module->name).'">'; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -750,8 +712,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS)) // Defaut print "<td class=\"center\">"; - if ($conf->global->PROJECT_TASK_ADDON_PDF == "$name") - { + if ($conf->global->PROJECT_TASK_ADDON_PDF == "$name") { print img_picto($langs->trans("Default"), 'on'); } else { print '<a href="'.$_SERVER["PHP_SELF"].'?action=setdoctask&amp;token='.newToken().'&amp;value='.$name.'&amp;scan_dir='.$module->scandir.'&amp;label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').'</a>'; @@ -761,8 +722,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS)) // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } $htmltooltip .= '<br><br><u>'.$langs->trans("FeaturesSupported").':</u>'; @@ -774,8 +734,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS)) // Preview print '<td class="center">'; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimentask&module='.$name.'">'.img_object($langs->trans("Preview"), 'bill').'</a>'; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); @@ -812,8 +771,7 @@ print '<td width="80">&nbsp;</td></tr>'."\n"; print '<tr class="oddeven">'; print '<td width="80%">'.$langs->trans("UseSearchToSelectProject").'</td>'; -if (!$conf->use_javascript_ajax) -{ +if (!$conf->use_javascript_ajax) { print '<td class="nowrap right" colspan="2">'; print $langs->trans("NotAvailableWhenAjaxDisabled"); print "</td>"; @@ -840,6 +798,16 @@ print $form->textwithpicto('', $langs->trans('AllowToLinkFromOtherCompany')); print '<input type="submit" class="button" name="PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY" value="'.$langs->trans("Modify").'">'; print '</td>'; +$key = 'PROJECT_CLASSIFY_CLOSED_WHEN_ALL_TASKS_DONE'; +echo '<tr class="oddeven">', + '<td class="left">', + $form->textwithpicto($langs->transnoentities($key), $langs->transnoentities($key . '_help')), + '</td>', + '<td class="right" colspan="2">', + ajax_constantonoff($key), + '</td>', + '</tr>'; + print '</table>'; diff --git a/htdocs/projet/admin/project_extrafields.php b/htdocs/projet/admin/project_extrafields.php index 6c92e6d66c9..e011b1a02c3 100644 --- a/htdocs/projet/admin/project_extrafields.php +++ b/htdocs/projet/admin/project_extrafields.php @@ -38,13 +38,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 = 'projet'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -77,8 +81,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"]."?action=create\">".$langs->trans("NewAttribute").'</a></div>'; print "</div>"; @@ -91,8 +94,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print "<br>"; print load_fiche_titre($langs->trans('NewAttribute')); @@ -104,8 +106,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/projet/admin/project_task_extrafields.php b/htdocs/projet/admin/project_task_extrafields.php index 9f7efbb7096..5222706d7d0 100644 --- a/htdocs/projet/admin/project_task_extrafields.php +++ b/htdocs/projet/admin/project_task_extrafields.php @@ -39,13 +39,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 = 'projet_task'; -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -77,8 +81,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"]."?action=create\">".$langs->trans("NewAttribute").'</a></div>'; print "</div>"; @@ -91,8 +94,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print "<br>"; print load_fiche_titre($langs->trans('NewAttribute')); @@ -104,8 +106,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/projet/admin/website.php b/htdocs/projet/admin/website.php new file mode 100644 index 00000000000..04acbaa44aa --- /dev/null +++ b/htdocs/projet/admin/website.php @@ -0,0 +1,167 @@ +<?php +/* Copyright (C) 2001-2002 Rodolphe Quiedeville <rodolphe@quiedeville.org> + * Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net> + * Copyright (C) 2006-2012 Regis Houssin <regis.houssin@inodbox.com> + * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es> + * + * 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 <https://www.gnu.org/licenses/>. + */ + +/** + * \file htdocs/projet/admin/website.php + * \ingroup member + * \brief File of main public page for project module to catch lead + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("admin", "members")); + +$action = GETPOST('action', 'aZ09'); + +if (!$user->admin) { + accessforbidden(); +} + + +/* + * Actions + */ + +if ($action == 'setPROJECT_ENABLE_PUBLIC') { + if (GETPOST('value')) { + dolibarr_set_const($db, 'PROJECT_ENABLE_PUBLIC', 1, 'chaine', 0, '', $conf->entity); + } else { + dolibarr_set_const($db, 'PROJECT_ENABLE_PUBLIC', 0, 'chaine', 0, '', $conf->entity); + } +} + +if ($action == 'update') { + $public = GETPOST('PROJECT_ENABLE_PUBLIC'); + + $res = dolibarr_set_const($db, "PROJECT_ENABLE_PUBLIC", $public, 'chaine', 0, '', $conf->entity); + + if (!($res > 0)) { + $error++; + } + + if (!$error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'errors'); + } +} + + +/* + * View + */ + +$form = new Form($db); + +$help_url = ''; +llxHeader('', $langs->trans("ProjectsSetup"), $help_url); + + +$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>'; +print load_fiche_titre($langs->trans("ProjectsSetup"), $linkback, 'title_setup'); + +$head = project_admin_prepare_head(); + +$param = ''; + +print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">'; +print '<input type="hidden" name="action" value="update">'; +print '<input type="hidden" name="token" value="'.newToken().'">'; + +print dol_get_fiche_head($head, 'website', $langs->trans("Projects"), -1, 'user'); + + +print '<span class="opacitymedium">'.$langs->trans("LeadPublicFormDesc").'</span><br><br>'; + + +$enabledisablehtml = $langs->trans("EnablePublicLeadForm").' '; +if (empty($conf->global->PROJECT_ENABLE_PUBLIC)) { + // Button off, click to enable + $enabledisablehtml .= '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=setPROJECT_ENABLE_PUBLIC&token='.newToken().'&value=1'.$param.'">'; + $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); + $enabledisablehtml .= '</a>'; +} else { + // Button on, click to disable + $enabledisablehtml .= '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=setPROJECT_ENABLE_PUBLIC&token='.newToken().'&value=0'.$param.'">'; + $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on'); + $enabledisablehtml .= '</a>'; +} +print $enabledisablehtml; +print '<input type="hidden" id="PROJECT_ENABLE_PUBLIC" name="PROJECT_ENABLE_PUBLIC" value="'.(empty($conf->global->PROJECT_ENABLE_PUBLIC) ? 0 : 1).'">'; + +/* +print '<br>'; + +if (!empty($conf->global->PROJECT_ENABLE_PUBLIC)) { + print '<br>'; + + print '<table class="noborder centpercent">'; + + print '<tr class="liste_titre">'; + print '<td>'.$langs->trans("Parameter").'</td>'; + print '<td class="right">'.$langs->trans("Value").'</td>'; + print "</tr>\n"; + + // param + print '<tr class="oddeven" id="tredit"><td>'; + print $langs->trans("CanEditAmount"); + print '</td><td class="right">'; + print $form->selectyesno("MEMBER_NEWFORM_EDITAMOUNT", (!empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT) ? $conf->global->MEMBER_NEWFORM_EDITAMOUNT : 0), 1); + print "</td></tr>\n"; + + print '</table>'; + + print '<div class="center">'; + print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">'; + print '</div>'; +} +*/ + +print dol_get_fiche_end(); + +print '</form>'; + + +if (!empty($conf->global->PROJECT_ENABLE_PUBLIC)) { + print '<br>'; + //print $langs->trans('FollowingLinksArePublic').'<br>'; + print img_picto('', 'globe').' '.$langs->trans('BlankSubscriptionForm').':<br>'; + if ($conf->multicompany->enabled) { + $entity_qr = '?entity='.$conf->entity; + } else { + $entity_qr = ''; + } + + // Define $urlwithroot + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); + $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current + + print '<a target="_blank" href="'.$urlwithroot.'/public/project/new.php'.$entity_qr.'">'.$urlwithroot.'/public/project/new.php'.$entity_qr.'</a>'; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/projet/ajax/projects.php b/htdocs/projet/ajax/projects.php index 0036ae64353..74d9236d26d 100644 --- a/htdocs/projet/ajax/projects.php +++ b/htdocs/projet/ajax/projects.php @@ -23,13 +23,27 @@ * \brief File to return Ajax response on product list request */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (empty($_GET['keysearch']) && !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'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (empty($_GET['keysearch']) && !defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} require '../../main.inc.php'; @@ -49,7 +63,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; top_httphead(); -if (empty($htmlname) && !GETPOST('mode', 'aZ09')) return; +if (empty($htmlname) && !GETPOST('mode', 'aZ09')) { + return; +} // Mode to get list of projects if (!GETPOST('mode', 'aZ09') || GETPOST('mode', 'aZ09') != 'gettasks') { diff --git a/htdocs/projet/card.php b/htdocs/projet/card.php index 364cb30633a..c1cff4ce944 100644 --- a/htdocs/projet/card.php +++ b/htdocs/projet/card.php @@ -35,7 +35,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; // Load translation files required by the page -$langs->loadLangs(array('projects', 'companies')); +$langsLoad=array('projects', 'companies'); +if (!empty($conf->eventorganization->enabled)) { + $langsLoad[]='eventorganization'; +} + +$langs->loadLangs($langsLoad); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); @@ -47,7 +52,9 @@ $status = GETPOST('status', 'int'); $opp_status = GETPOST('opp_status', 'int'); $opp_percent = price2num(GETPOST('opp_percent', 'alpha')); -if ($id == '' && $ref == '' && ($action != "create" && $action != "add" && $action != "update" && !$_POST["cancel"])) accessforbidden(); +if ($id == '' && $ref == '' && ($action != "create" && $action != "add" && $action != "update" && !$_POST["cancel"])) { + accessforbidden(); +} $mine = GETPOST('mode') == 'mine' ? 1 : 0; //if (! $user->rights->projet->all->lire) $mine=1; // Special for projects @@ -60,12 +67,13 @@ $extrafields = new ExtraFields($db); // Load object //include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Can't use generic include because when creating a project, ref is defined and we dont want error if fetch fails from ref. -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $ret = $object->fetch($id, $ref); // If we create project, ref may be defined into POST but record does not yet exists into database if ($ret > 0) { $object->fetch_thirdparty(); - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); + } $id = $object->id; } } @@ -88,18 +96,16 @@ $date_end = dol_mktime(0, 0, 0, GETPOST('projectendmonth', 'int'), GETPOST('proj $parameters = array('id'=>$socid, '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)) -{ +if (empty($reshook)) { // Cancel - if ($cancel) - { - if (GETPOST("comefromclone") == 1) - { + if ($cancel) { + if (GETPOST("comefromclone") == 1) { $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { header("Location: index.php"); exit; } else { @@ -107,8 +113,7 @@ if (empty($reshook)) setEventMessages($langs->trans("CantRemoveProject", $langs->transnoentitiesnoconv("ProjectOverview")), null, 'errors'); } } - if ($backtopage) - { + if ($backtopage) { header("Location: ".$backtopage); exit; } @@ -116,34 +121,28 @@ if (empty($reshook)) $action = ''; } - if ($action == 'add' && $user->rights->projet->creer) - { + if ($action == 'add' && $user->rights->projet->creer) { $error = 0; - if (!GETPOST('ref')) - { + if (!GETPOST('ref')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); $error++; } - if (!GETPOST('title')) - { + if (!GETPOST('title')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ProjectLabel")), null, 'errors'); $error++; } - if (GETPOST('opp_amount') != '' && !(GETPOST('opp_status') > 0)) - { + if (GETPOST('opp_amount') != '' && !(GETPOST('opp_status') > 0)) { $error++; setEventMessages($langs->trans("ErrorOppStatusRequiredIfAmount"), null, 'errors'); } // Create with status validated immediatly - if (!empty($conf->global->PROJECT_CREATE_NO_DRAFT)) - { + if (!empty($conf->global->PROJECT_CREATE_NO_DRAFT)) { $status = Project::STATUS_VALIDATED; } - if (!$error) - { + if (!$error) { $error = 0; $db->begin(); @@ -168,16 +167,16 @@ 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++; + } $result = $object->create($user); - if (!$error && $result > 0) - { + if (!$error && $result > 0) { // Add myself as project leader $typeofcontact = 'PROJECTLEADER'; // TODO If use rename this code in dictionary, the add_contact will generate an error. $result = $object->add_contact($user->id, $typeofcontact, 'internal'); - if ($result < 0) - { + if ($result < 0) { $langs->load("errors"); setEventMessages($object->error, $object->errors, 'errors'); $error++; @@ -187,8 +186,7 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); $error++; } - if (!$error && !empty($object->id) > 0) - { + if (!$error && !empty($object->id) > 0) { // Category association $categories = GETPOST('categories', 'array'); $result = $object->setCategories($categories); @@ -199,12 +197,10 @@ if (empty($reshook)) } } - if (!$error) - { + if (!$error) { $db->commit(); - if (!empty($backtopage)) - { + if (!empty($backtopage)) { $backtopage = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $backtopage); // New method to autoselect project after a New on another form object creation $backtopage = $backtopage.'&projectid='.$object->id; // Old method header("Location: ".$backtopage); @@ -215,7 +211,7 @@ if (empty($reshook)) } } else { $db->rollback(); - + unset($_POST["ref"]); $action = 'create'; } } else { @@ -223,18 +219,15 @@ if (empty($reshook)) } } - if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer) - { + if ($action == 'update' && empty(GETPOST('cancel')) && $user->rights->projet->creer) { $error = 0; - if (empty($ref)) - { + if (empty($ref)) { $error++; //$_GET["id"]=$_POST["id"]; // We return on the project card setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); } - if (empty($_POST["title"])) - { + if (empty($_POST["title"])) { $error++; //$_GET["id"]=$_POST["id"]; // We return on the project card setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ProjectLabel")), null, 'errors'); @@ -242,8 +235,7 @@ if (empty($reshook)) $db->begin(); - if (!$error) - { + if (!$error) { $object->oldcopy = clone $object; $old_start_date = $object->date_start; @@ -256,10 +248,18 @@ if (empty($reshook)) $object->public = GETPOST('public', 'alpha'); $object->date_start = (!GETPOST('projectstart')) ? '' : $date_start; $object->date_end = (!GETPOST('projectend')) ? '' : $date_end; - if (GETPOSTISSET('opp_amount')) $object->opp_amount = price2num(GETPOST('opp_amount', 'alpha')); - if (GETPOSTISSET('budget_amount')) $object->budget_amount = price2num(GETPOST('budget_amount', 'alpha')); - if (GETPOSTISSET('opp_status')) $object->opp_status = $opp_status; - if (GETPOSTISSET('opp_percent')) $object->opp_percent = $opp_percent; + if (GETPOSTISSET('opp_amount')) { + $object->opp_amount = price2num(GETPOST('opp_amount', 'alpha')); + } + if (GETPOSTISSET('budget_amount')) { + $object->budget_amount = price2num(GETPOST('budget_amount', 'alpha')); + } + if (GETPOSTISSET('opp_status')) { + $object->opp_status = $opp_status; + } + if (GETPOSTISSET('opp_percent')) { + $object->opp_percent = $opp_percent; + } $object->usage_opportunity = (GETPOST('usage_opportunity', 'alpha') == 'on' ? 1 : 0); $object->usage_task = (GETPOST('usage_task', 'alpha') == 'on' ? 1 : 0); $object->usage_bill_time = (GETPOST('usage_bill_time', 'alpha') == 'on' ? 1 : 0); @@ -267,42 +267,40 @@ 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++; + } } - if ($object->opp_amount && ($object->opp_status <= 0)) - { - $error++; + if ($object->opp_amount && ($object->opp_status <= 0)) { + $error++; setEventMessages($langs->trans("ErrorOppStatusRequiredIfAmount"), null, 'errors'); } - if (!$error) - { + if (!$error) { $result = $object->update($user); - if ($result < 0) - { + if ($result < 0) { $error++; - if ($result == -4) setEventMessages($langs->trans("ErrorRefAlreadyExists"), null, 'errors'); - else setEventMessages($object->error, $object->errors, 'errors'); + if ($result == -4) { + setEventMessages($langs->trans("ErrorRefAlreadyExists"), null, 'errors'); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } } else { // Category association $categories = GETPOST('categories', 'array'); $result = $object->setCategories($categories); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } } } - if (!$error) - { - if (GETPOST("reportdate") && ($object->date_start != $old_start_date)) - { + if (!$error) { + if (GETPOST("reportdate") && ($object->date_start != $old_start_date)) { $result = $object->shiftTaskDate($old_start_date); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($langs->trans("ErrorShiftTaskDate").':'.$object->error, $object->errors, 'errors'); } @@ -310,101 +308,92 @@ if (empty($reshook)) } // Check if we must change status - if (GETPOST('closeproject')) - { + if (GETPOST('closeproject')) { $resclose = $object->setClose($user); - if ($resclose < 0) - { + if ($resclose < 0) { $error++; setEventMessages($langs->trans("FailedToCloseProject").':'.$object->error, $object->errors, 'errors'); } } - if ($error) - { + if ($error) { $db->rollback(); $action = 'edit'; } else { $db->commit(); - if (GETPOST('socid', 'int') > 0) $object->fetch_thirdparty(GETPOST('socid', 'int')); - else unset($object->thirdparty); + if (GETPOST('socid', 'int') > 0) { + $object->fetch_thirdparty(GETPOST('socid', 'int')); + } else { + unset($object->thirdparty); + } } } // Build doc - if ($action == 'builddoc' && $user->rights->projet->creer) - { + if ($action == 'builddoc' && $user->rights->projet->creer) { // Save last template used to generate document - if (GETPOST('model')) $object->setDocModel($user, GETPOST('model', 'alpha')); + if (GETPOST('model')) { + $object->setDocModel($user, GETPOST('model', 'alpha')); + } $outputlangs = $langs; - if (GETPOST('lang_id', 'aZ09')) - { + if (GETPOST('lang_id', 'aZ09')) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang(GETPOST('lang_id', 'aZ09')); } $result = $object->generateDocument($object->model_pdf, $outputlangs); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = ''; } } // Delete file in doc form - if ($action == 'remove_file' && $user->rights->projet->creer) - { - if ($object->id > 0) - { + if ($action == 'remove_file' && $user->rights->projet->creer) { + if ($object->id > 0) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $langs->load("other"); $upload_dir = $conf->projet->dir_output; $file = $upload_dir.'/'.GETPOST('file'); $ret = dol_delete_file($file, 0, 0, 0, $object); - if ($ret) + if ($ret) { setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + } $action = ''; } } - if ($action == 'confirm_validate' && $confirm == 'yes') - { + if ($action == 'confirm_validate' && $confirm == 'yes') { $result = $object->setValid($user); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); } } - if ($action == 'confirm_close' && $confirm == 'yes') - { + if ($action == 'confirm_close' && $confirm == 'yes') { $result = $object->setClose($user); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); } } - if ($action == 'confirm_reopen' && $confirm == 'yes') - { + if ($action == 'confirm_reopen' && $confirm == 'yes') { $result = $object->setValid($user); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); } } - if ($action == 'confirm_delete' && GETPOST("confirm") == "yes" && $user->rights->projet->supprimer) - { + if ($action == 'confirm_delete' && GETPOST("confirm") == "yes" && $user->rights->projet->supprimer) { $object->fetch($id); $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); header("Location: list.php?restore_lastsearch_values=1"); exit; @@ -414,8 +403,7 @@ if (empty($reshook)) } } - if ($action == 'confirm_clone' && $user->rights->projet->creer && $confirm == 'yes') - { + if ($action == 'confirm_clone' && $user->rights->projet->creer && $confirm == 'yes') { $clone_contacts = GETPOST('clone_contacts') ? 1 : 0; $clone_tasks = GETPOST('clone_tasks') ? 1 : 0; $clone_project_files = GETPOST('clone_project_files') ? 1 : 0; @@ -425,8 +413,7 @@ if (empty($reshook)) $clone_thirdparty = GETPOST('socid', 'int') ?GETPOST('socid', 'int') : 0; $result = $object->createFromClone($user, $object->id, $clone_contacts, $clone_tasks, $clone_project_files, $clone_task_files, $clone_notes, $move_date, 0, $clone_thirdparty); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); } else { // Load new object @@ -459,8 +446,10 @@ $formproject = new FormProjets($db); $userstatic = new User($db); $title = $langs->trans("Project").' - '.$object->ref.($object->thirdparty->name ? ' - '.$object->thirdparty->name : '').($object->title ? ' - '.$object->title : ''); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE)) $title = $object->ref.($object->thirdparty->name ? ' - '.$object->thirdparty->name : '').($object->title ? ' - '.$object->title : ''); -$help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos"; +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE)) { + $title = $object->ref.($object->thirdparty->name ? ' - '.$object->thirdparty->name : '').($object->title ? ' - '.$object->title : ''); +} +$help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos|DE:Modul_Projekte"; llxHeader("", $title, $help_url); @@ -475,14 +464,15 @@ if ($conf->global->PROJECT_USE_OPPORTUNITIES == 2) { // 2 = leads only $titlenew = $langs->trans("NewLead"); } -if ($action == 'create' && $user->rights->projet->creer) -{ +if ($action == 'create' && $user->rights->projet->creer) { /* - * Create - */ + * Create + */ $thirdparty = new Societe($db); - if ($socid > 0) $thirdparty->fetch($socid); + if ($socid > 0) { + $thirdparty->fetch($socid); + } print load_fiche_titre($titlenew, '', 'project'); @@ -501,26 +491,25 @@ if ($action == 'create' && $user->rights->projet->creer) // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/project/".$modele.'.php', 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = $modele; break; } } - if ($filefound) - { + if ($filefound) { $result = dol_include_once($reldir."core/modules/project/".$modele.'.php'); $modProject = new $classname; $defaultref = $modProject->getNextValue($thirdparty, $object); } - if (is_numeric($defaultref) && $defaultref <= 0) $defaultref = ''; + if (is_numeric($defaultref) && $defaultref <= 0) { + $defaultref = ''; + } // Ref $suggestedref = ($_POST["ref"] ? $_POST["ref"] : $defaultref); @@ -555,50 +544,54 @@ if ($action == 'create' && $user->rights->projet->creer) print '</script>'; print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" id="usage_task" name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ' checked="checked"').'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print '<label for="usage_task">'.$form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext).'</label>'; print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" id="usage_bill_time" name="usage_bill_time"'.(GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '').'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print '<label for="usage_bill_time">'.$form->textwithpicto($langs->trans("BillTime"), $htmltext).'</label>'; print '<br>'; } - /* - print '<input type="checkbox" name="usage_organize_event"'.(GETPOST('usage_organize_event', 'alpha')!=''?' checked="checked"':'').'"> '; - $htmltext = $langs->trans("OrganizeEvent"); - print $form->textwithpicto($langs->trans("OrganizeEvent"), $htmltext);*/ + + if (!empty($conf->eventorganization->enabled)) { + print '<input type="checkbox" name="usage_organize_event"'.(GETPOST('usage_organize_event', 'alpha')!=''?' checked="checked"':'').'"> '; + $htmltext = $langs->trans("EventOrganizationDescriptionLong"); + print $form->textwithpicto($langs->trans("ManageOrganizeEvent"), $htmltext); + } + print '</td>'; print '</tr>'; // Thirdparty - if ($conf->societe->enabled) - { + if ($conf->societe->enabled) { print '<tr><td>'; print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED) ? '' : '<span class="fieldrequired">'); print $langs->trans("ThirdParty"); print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED) ? '' : '</span>'); print '</td><td class="maxwidthonsmartphone">'; $filteronlist = ''; - if (!empty($conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST)) $filteronlist = $conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST; - $text = img_picto('', 'company').$form->select_company(GETPOST('socid', 'int'), 'socid', $filteronlist, 'SelectThirdParty', 1, 0, array(), 0, 'minwidth300 widthcentpercentminusxx'); - if (empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) && empty($conf->dol_use_jmobile)) - { + if (!empty($conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST)) { + $filteronlist = $conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST; + } + $text = img_picto('', 'company').$form->select_company(GETPOST('socid', 'int'), 'socid', $filteronlist, 'SelectThirdParty', 1, 0, array(), 0, 'minwidth300 widthcentpercentminusxx'); + if (empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) && empty($conf->dol_use_jmobile)) { $texthelp = $langs->trans("IfNeedToUseOtherObjectKeepEmpty"); print $form->textwithtooltip($text.' '.img_help(), $texthelp, 1); - } else print $text; - if (!GETPOSTISSET('backtopage')) print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>'; + } else { + print $text; + } + if (!GETPOSTISSET('backtopage')) { + print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>'; + } print '</td></tr>'; } // Status - if ($status != '') - { + if ($status != '') { print '<tr><td>'.$langs->trans("Status").'</td><td>'; print '<input type="hidden" name="status" value="'.$status.'">'; print $object->LibStatut($status, 4); @@ -608,8 +601,12 @@ if ($action == 'create' && $user->rights->projet->creer) // Visibility print '<tr><td>'.$langs->trans("Visibility").'</td><td class="maxwidthonsmartphone">'; $array = array(); - if (empty($conf->global->PROJECT_DISABLE_PRIVATE_PROJECT)) $array[0] = $langs->trans("PrivateProject"); - if (empty($conf->global->PROJECT_DISABLE_PUBLIC_PROJECT)) $array[1] = $langs->trans("SharedProject"); + if (empty($conf->global->PROJECT_DISABLE_PRIVATE_PROJECT)) { + $array[0] = $langs->trans("PrivateProject"); + } + if (empty($conf->global->PROJECT_DISABLE_PUBLIC_PROJECT)) { + $array[1] = $langs->trans("SharedProject"); + } print $form->selectarray('public', $array, GETPOST('public') ?GETPOST('public') : $object->public, 0, 0, 0, '', 0, 0, 0, '', '', 1); print '</td></tr>'; @@ -623,8 +620,7 @@ if ($action == 'create' && $user->rights->projet->creer) print $form->selectDate(($date_end ? $date_end : -1), 'projectend', 0, 0, 0, '', 1, 0); print '</td></tr>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { // Opportunity status print '<tr class="classuseopportunity"><td>'.$langs->trans("OpportunityStatus").'</td>'; print '<td class="maxwidthonsmartphone">'; @@ -669,8 +665,7 @@ if ($action == 'create' && $user->rights->projet->creer) $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'create'); } @@ -680,8 +675,7 @@ if ($action == 'create' && $user->rights->projet->creer) print '<div class="center">'; print '<input type="submit" class="button" value="'.$langs->trans("CreateDraft").'">'; - if (!empty($backtopage)) - { + if (!empty($backtopage)) { print ' &nbsp; &nbsp; '; print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; } else { @@ -722,11 +716,10 @@ if ($action == 'create' && $user->rights->projet->creer) }); }); </script>'; -} elseif ($object->id > 0) -{ +} elseif ($object->id > 0) { /* - * Show or edit - */ + * Show or edit + */ $res = $object->fetch_optionals(); @@ -738,34 +731,31 @@ if ($action == 'create' && $user->rights->projet->creer) // Confirmation validation - if ($action == 'validate') - { + if ($action == 'validate') { print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateProject'), $langs->trans('ConfirmValidateProject'), 'confirm_validate', '', 0, 1); } // Confirmation close - if ($action == 'close') - { + if ($action == 'close') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("CloseAProject"), $langs->trans("ConfirmCloseAProject"), "confirm_close", '', '', 1); } // Confirmation reopen - if ($action == 'reopen') - { + if ($action == 'reopen') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("ReOpenAProject"), $langs->trans("ConfirmReOpenAProject"), "confirm_reopen", '', '', 1); } // Confirmation delete - if ($action == 'delete') - { + if ($action == 'delete') { $text = $langs->trans("ConfirmDeleteAProject"); $task = new Task($db); $taskarray = $task->getTasksArray(0, 0, $object->id, 0, 0); $nboftask = count($taskarray); - if ($nboftask) $text .= '<br>'.img_warning().' '.$langs->trans("ThisWillAlsoRemoveTasks", $nboftask); + if ($nboftask) { + $text .= '<br>'.img_warning().' '.$langs->trans("ThisWillAlsoRemoveTasks", $nboftask); + } print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("DeleteAProject"), $text, "confirm_delete", '', '', 1); } // Clone confirmation - if ($action == 'clone') - { + if ($action == 'clone') { $formquestion = array( 'text' => $langs->trans("ConfirmClone"), array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int') > 0 ?GETPOST('socid', 'int') : $object->socid, 'socid', '', "None", 0, 0, null, 0, 'minwidth200')), @@ -789,8 +779,7 @@ if ($action == 'create' && $user->rights->projet->creer) $head = project_prepare_head($object); - if ($action == 'edit' && $userWrite > 0) - { + if ($action == 'edit' && $userWrite > 0) { print dol_get_fiche_head($head, 'project', $langs->trans("Project"), 0, ($object->public ? 'projectpub' : 'project')); print '<table class="border centpercent">'; @@ -809,8 +798,7 @@ if ($action == 'create' && $user->rights->projet->creer) // Status print '<tr><td class="fieldrequired">'.$langs->trans("Status").'</td><td>'; print '<select class="flat" name="status">'; - foreach ($object->statuts_short as $key => $val) - { + foreach ($object->statuts_short as $key => $val) { print '<option value="'.$key.'"'.((GETPOSTISSET('status') ?GETPOST('status') : $object->statut) == $key ? ' selected="selected"' : '').'>'.$langs->trans($val).'</option>'; } print '</select>'; @@ -821,8 +809,7 @@ if ($action == 'create' && $user->rights->projet->creer) print $langs->trans("Usage"); print '</td>'; print '<td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" id="usage_opportunity" name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); @@ -841,51 +828,59 @@ if ($action == 'create' && $user->rights->projet->creer) print '</script>'; print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); print '<br>'; } + if (!empty($conf->eventorganization->enabled)) { + print '<input type="checkbox" name="usage_organize_event"'.(GETPOST('usage_organize_event', 'alpha')!=''?' checked="checked"':'').'"> '; + $htmltext = $langs->trans("EventOrganizationDescriptionLong"); + print $form->textwithpicto($langs->trans("ManageOrganizeEvent"), $htmltext); + } print '</td></tr>'; // Thirdparty - if ($conf->societe->enabled) - { + if ($conf->societe->enabled) { print '<tr><td>'; print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED) ? '' : '<span class="fieldrequired">'); print $langs->trans("ThirdParty"); print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED) ? '' : '</span>'); print '</td><td>'; $filteronlist = ''; - if (!empty($conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST)) $filteronlist = $conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST; + if (!empty($conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST)) { + $filteronlist = $conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST; + } $text = $form->select_company($object->thirdparty->id, 'socid', $filteronlist, 'None', 1, 0, array(), 0, 'minwidth300'); - if (empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) && empty($conf->dol_use_jmobile)) - { + if (empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) && empty($conf->dol_use_jmobile)) { $texthelp = $langs->trans("IfNeedToUseOtherObjectKeepEmpty"); print $form->textwithtooltip($text.' '.img_help(), $texthelp, 1, 0, '', '', 2); - } else print $text; + } else { + print $text; + } print '</td></tr>'; } // Visibility print '<tr><td>'.$langs->trans("Visibility").'</td><td>'; $array = array(); - if (empty($conf->global->PROJECT_DISABLE_PRIVATE_PROJECT)) $array[0] = $langs->trans("PrivateProject"); - if (empty($conf->global->PROJECT_DISABLE_PUBLIC_PROJECT)) $array[1] = $langs->trans("SharedProject"); + if (empty($conf->global->PROJECT_DISABLE_PRIVATE_PROJECT)) { + $array[0] = $langs->trans("PrivateProject"); + } + if (empty($conf->global->PROJECT_DISABLE_PUBLIC_PROJECT)) { + $array[1] = $langs->trans("SharedProject"); + } print $form->selectarray('public', $array, $object->public, 0, 0, 0, '', 0, 0, 0, '', '', 1); print '</td></tr>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { $classfortr = ($object->usage_opportunity ? '' : ' hideobject'); // Opportunity status print '<tr class="classuseopportunity'.$classfortr.'"><td>'.$langs->trans("OpportunityStatus").'</td>'; @@ -915,7 +910,9 @@ if ($action == 'create' && $user->rights->projet->creer) print '<tr><td>'.$langs->trans("DateStart").'</td><td>'; print $form->selectDate($object->date_start ? $object->date_start : -1, 'projectstart', 0, 0, 0, '', 1, 0); print ' &nbsp; &nbsp; <input type="checkbox" class="valignmiddle" name="reportdate" value="yes" '; - if ($comefromclone) {print ' checked '; } + if ($comefromclone) { + print ' checked '; + } print '/> '.$langs->trans("ProjectReportDate"); print '</td></tr>'; @@ -937,8 +934,7 @@ if ($action == 'create' && $user->rights->projet->creer) print '</td></tr>'; // Tags-Categories - if ($conf->categorie->enabled) - { + if ($conf->categorie->enabled) { print '<tr><td>'.$langs->trans("Categories").'</td><td>'; $cate_arbo = $form->select_all_categories(Categorie::TYPE_PROJECT, '', 'parent', 64, 0, 1); $c = new Categorie($db); @@ -954,8 +950,7 @@ if ($action == 'create' && $user->rights->projet->creer) $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } @@ -972,15 +967,13 @@ if ($action == 'create' && $user->rights->projet->creer) $morehtmlref .= dol_escape_htmltag($object->title); // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '; - if ($object->thirdparty->id > 0) - { + if ($object->thirdparty->id > 0) { $morehtmlref .= $object->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); $object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -999,60 +992,73 @@ if ($action == 'create' && $user->rights->projet->creer) print $langs->trans("Usage"); print '</td>'; print '<td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } - if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); print '<br>'; } + + if (!empty($conf->eventorganization->enabled)) { + print '<input type="checkbox" disabled name="usage_organize_event"'.(GETPOSTISSET('usage_organize_event') ? (GETPOST('usage_organize_event', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_organize_event ? ' checked="checked"' : '')).'"> '; + $htmltext = $langs->trans("EventOrganizationDescriptionLong"); + print $form->textwithpicto($langs->trans("ManageOrganizeEvent"), $htmltext); + } print '</td></tr>'; // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; - if ($object->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); + if ($object->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } print '</td></tr>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && !empty($object->usage_opportunity)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && !empty($object->usage_opportunity)) { // Opportunity status print '<tr><td>'.$langs->trans("OpportunityStatus").'</td><td>'; $code = dol_getIdFromCode($db, $object->opp_status, 'c_lead_status', 'rowid', 'code'); - if ($code) print $langs->trans("OppStatus".$code); + if ($code) { + print $langs->trans("OppStatus".$code); + } print '</td></tr>'; // Opportunity percent print '<tr><td>'.$langs->trans("OpportunityProbability").'</td><td>'; - if (strcmp($object->opp_percent, '')) print price($object->opp_percent, 0, $langs, 1, 0).' %'; + if (strcmp($object->opp_percent, '')) { + print price($object->opp_percent, 0, $langs, 1, 0).' %'; + } print '</td></tr>'; // Opportunity Amount print '<tr><td>'.$langs->trans("OpportunityAmount").'</td><td>'; /*if ($object->opp_status) - { - print price($obj->opp_amount, 1, $langs, 1, 0, -1, $conf->currency); - }*/ - if (strcmp($object->opp_amount, '')) print price($object->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); + { + print price($obj->opp_amount, 1, $langs, 1, 0, -1, $conf->currency); + }*/ + if (strcmp($object->opp_amount, '')) { + print price($object->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); + } print '</td></tr>'; // Opportunity Weighted Amount print '<tr><td>'.$langs->trans('OpportunityWeightedAmount').'</td><td>'; - if (strcmp($object->opp_amount, '') && strcmp($object->opp_percent, '')) print price($object->opp_amount * $object->opp_percent / 100, 0, $langs, 1, 0, -1, $conf->currency); + if (strcmp($object->opp_amount, '') && strcmp($object->opp_percent, '')) { + print price($object->opp_amount * $object->opp_percent / 100, 0, $langs, 1, 0, -1, $conf->currency); + } print '</td></tr>'; } @@ -1063,12 +1069,16 @@ if ($action == 'create' && $user->rights->projet->creer) $end = dol_print_date($object->date_end, 'day'); print ' - '; print ($end ? $end : '?'); - if ($object->hasDelay()) print img_warning("Late"); + if ($object->hasDelay()) { + print img_warning("Late"); + } print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; - if (strcmp($object->budget_amount, '')) print price($object->budget_amount, 0, $langs, 1, 0, 0, $conf->currency); + if (strcmp($object->budget_amount, '')) { + print price($object->budget_amount, 0, $langs, 1, 0, 0, $conf->currency); + } print '</td></tr>'; // Other attributes @@ -1107,10 +1117,9 @@ if ($action == 'create' && $user->rights->projet->creer) print dol_get_fiche_end(); - if ($action == 'edit' && $userWrite > 0) - { + if ($action == 'edit' && $userWrite > 0) { print '<div class="center">'; - print '<input name="update" class="button" type="submit" value="'.$langs->trans("Modify").'">&nbsp; &nbsp; &nbsp;'; + print '<input name="update" class="button" type="submit" value="'.$langs->trans("Save").'">&nbsp; &nbsp; &nbsp;'; print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; print '</div>'; } @@ -1118,11 +1127,12 @@ if ($action == 'create' && $user->rights->projet->creer) print '</form>'; // Change probability from status - if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { // Default value to close or not when we set opp to 'WON'. $defaultcheckedwhenoppclose = 1; - if (empty($conf->global->PROJECT_HIDE_TASKS)) $defaultcheckedwhenoppclose = 0; + if (empty($conf->global->PROJECT_HIDE_TASKS)) { + $defaultcheckedwhenoppclose = 0; + } print '<!-- Javascript to manage opportunity status change -->'; print '<script type="text/javascript" language="javascript"> @@ -1181,16 +1191,14 @@ if ($action == 'create' && $user->rights->projet->creer) } /* - * Actions Buttons - */ + * Actions Buttons + */ print '<div class="tabsAction">'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { - if ($action != "edit" && $action != 'presend') - { + if (empty($reshook)) { + if ($action != "edit" && $action != 'presend') { // Create event /*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a // "workflow" action so should appears somewhere else on @@ -1201,17 +1209,14 @@ if ($action == 'create' && $user->rights->projet->creer) // Send if (empty($user->socid)) { - if ($object->statut != 2) - { + if ($object->statut != Project::STATUS_CLOSED) { print '<a class="butAction" href="card.php?id='.$object->id.'&amp;action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>'; } } // Modify - if ($object->statut != 2 && $user->rights->projet->creer) - { - if ($userWrite > 0) - { + if ($object->statut != Project::STATUS_CLOSED && $user->rights->projet->creer) { + if ($userWrite > 0) { print '<a class="butAction" href="card.php?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotOwnerOfProject").'">'.$langs->trans('Modify').'</a>'; @@ -1219,10 +1224,8 @@ if ($action == 'create' && $user->rights->projet->creer) } // Validate - if ($object->statut == 0 && $user->rights->projet->creer) - { - if ($userWrite > 0) - { + if ($object->statut == Project::STATUS_DRAFT && $user->rights->projet->creer) { + if ($userWrite > 0) { print '<a class="butAction" href="card.php?id='.$object->id.'&action=validate">'.$langs->trans("Validate").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotOwnerOfProject").'">'.$langs->trans('Validate').'</a>'; @@ -1230,10 +1233,8 @@ if ($action == 'create' && $user->rights->projet->creer) } // Close - if ($object->statut == 1 && $user->rights->projet->creer) - { - if ($userWrite > 0) - { + if ($object->statut == Project::STATUS_VALIDATED && $user->rights->projet->creer) { + if ($userWrite > 0) { print '<a class="butAction" href="card.php?id='.$object->id.'&amp;action=close">'.$langs->trans("Close").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotOwnerOfProject").'">'.$langs->trans('Close').'</a>'; @@ -1241,10 +1242,8 @@ if ($action == 'create' && $user->rights->projet->creer) } // Reopen - if ($object->statut == 2 && $user->rights->projet->creer) - { - if ($userWrite > 0) - { + if ($object->statut == Project::STATUS_CLOSED && $user->rights->projet->creer) { + if ($userWrite > 0) { print '<a class="butAction" href="card.php?id='.$object->id.'&amp;action=reopen">'.$langs->trans("ReOpen").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotOwnerOfProject").'">'.$langs->trans('ReOpen').'</a>'; @@ -1252,65 +1251,52 @@ if ($action == 'create' && $user->rights->projet->creer) } // Add button to create objects from project - if (!empty($conf->global->PROJECT_SHOW_CREATE_OBJECT_BUTTON)) - { - if (!empty($conf->propal->enabled) && $user->rights->propal->creer) - { + if (!empty($conf->global->PROJECT_SHOW_CREATE_OBJECT_BUTTON)) { + if (!empty($conf->propal->enabled) && $user->rights->propal->creer) { $langs->load("propal"); print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/propal/card.php?action=create&projectid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("AddProp").'</a>'; } - if (!empty($conf->commande->enabled) && $user->rights->commande->creer) - { + if (!empty($conf->commande->enabled) && $user->rights->commande->creer) { $langs->load("orders"); print '<a class="butAction" href="'.DOL_URL_ROOT.'/commande/card.php?action=create&projectid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("CreateOrder").'</a>'; } - if (!empty($conf->facture->enabled) && $user->rights->facture->creer) - { + if (!empty($conf->facture->enabled) && $user->rights->facture->creer) { $langs->load("bills"); print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&projectid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("CreateBill").'</a>'; } - if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->creer) - { + if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->creer) { $langs->load("supplier_proposal"); print '<a class="butAction" href="'.DOL_URL_ROOT.'/supplier_proposal/card.php?action=create&projectid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("AddSupplierProposal").'</a>'; } - if (!empty($conf->supplier_order->enabled) && $user->rights->fournisseur->commande->creer) - { + if (!empty($conf->supplier_order->enabled) && $user->rights->fournisseur->commande->creer) { $langs->load("suppliers"); print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/commande/card.php?action=create&projectid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("AddSupplierOrder").'</a>'; } - if (!empty($conf->supplier_invoice->enabled) && $user->rights->fournisseur->facture->creer) - { + if (!empty($conf->supplier_invoice->enabled) && $user->rights->fournisseur->facture->creer) { $langs->load("suppliers"); print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?action=create&projectid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("AddSupplierInvoice").'</a>'; } - if (!empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer) - { + if (!empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer) { $langs->load("interventions"); print '<a class="butAction" href="'.DOL_URL_ROOT.'/fichinter/card.php?action=create&projectid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("AddIntervention").'</a>'; } - if (!empty($conf->contrat->enabled) && $user->rights->contrat->creer) - { + if (!empty($conf->contrat->enabled) && $user->rights->contrat->creer) { $langs->load("contracts"); print '<a class="butAction" href="'.DOL_URL_ROOT.'/contrat/card.php?action=create&projectid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("AddContract").'</a>'; } - if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->creer) - { + if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->creer) { $langs->load("trips"); print '<a class="butAction" href="'.DOL_URL_ROOT.'/expensereport/card.php?action=create&projectid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("AddTrip").'</a>'; } - if (!empty($conf->don->enabled) && $user->rights->don->creer) - { + if (!empty($conf->don->enabled) && $user->rights->don->creer) { $langs->load("donations"); print '<a class="butAction" href="'.DOL_URL_ROOT.'/don/card.php?action=create&projectid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("AddDonation").'</a>'; } } // Clone - if ($user->rights->projet->creer) - { - if ($userWrite > 0) - { + if ($user->rights->projet->creer) { + if ($userWrite > 0) { print '<a class="butAction" href="card.php?id='.$object->id.'&action=clone">'.$langs->trans('ToClone').'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotOwnerOfProject").'">'.$langs->trans('ToClone').'</a>'; @@ -1318,10 +1304,8 @@ if ($action == 'create' && $user->rights->projet->creer) } // Delete - if ($user->rights->projet->supprimer || ($object->statut == 0 && $user->rights->projet->creer)) - { - if ($userDelete > 0 || ($object->statut == 0 && $user->rights->projet->creer)) - { + if ($user->rights->projet->supprimer || ($object->statut == Project::STATUS_DRAFT && $user->rights->projet->creer)) { + if ($userDelete > 0 || ($object->statut == Project::STATUS_DRAFT && $user->rights->projet->creer)) { print '<a class="butActionDelete" href="card.php?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans("Delete").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotOwnerOfProject").'">'.$langs->trans('Delete').'</a>'; @@ -1336,14 +1320,13 @@ if ($action == 'create' && $user->rights->projet->creer) $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre /* - * Documents generes - */ + * Generated documents + */ $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->projet->dir_output."/".dol_sanitizeFileName($object->ref); $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; diff --git a/htdocs/projet/class/api_projects.class.php b/htdocs/projet/class/api_projects.class.php index c8ca952f9ed..c650512c5dd 100644 --- a/htdocs/projet/class/api_projects.class.php +++ b/htdocs/projet/class/api_projects.class.php @@ -33,7 +33,7 @@ class Projects extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'ref', 'title' ); @@ -110,23 +110,34 @@ class Projects extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."projet as t"; if ($category > 0) { $sql .= ", ".MAIN_DB_PREFIX."categorie_project as c"; } - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= ' WHERE t.entity IN ('.getEntity('project').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Select projects of given category @@ -134,10 +145,8 @@ class Projects extends DolibarrApi $sql .= " AND c.fk_categorie = ".$this->db->escape($category)." AND c.fk_project = t.rowid "; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -157,8 +166,7 @@ class Projects extends DolibarrApi dol_syslog("API Rest request"); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; @@ -197,12 +205,12 @@ class Projects extends DolibarrApi $this->project->$field = $value; } /*if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->project->lines = $lines; - }*/ + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->project->lines = $lines; + }*/ if ($this->project->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating project", array_merge(array($this->project->error), $this->project->errors)); } @@ -236,14 +244,11 @@ class Projects extends DolibarrApi } $this->project->getLinesArray(DolibarrApiAccess::$user); $result = array(); - foreach ($this->project->lines as $line) // $line is a task - { - if ($includetimespent == 1) - { + foreach ($this->project->lines as $line) { // $line is a task + if ($includetimespent == 1) { $timespent = $line->getSummaryOfTimeSpent(0); } - if ($includetimespent == 1) - { + if ($includetimespent == 1) { // TODO // Add class for timespent records and loop and fill $line->lines with records of timespent } @@ -283,8 +288,7 @@ class Projects extends DolibarrApi require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; $taskstatic = new Task($this->db); $userp = DolibarrApiAccess::$user; - if ($userid > 0) - { + if ($userid > 0) { $userp = new User($this->db); $userp->fetch($userid); } @@ -308,56 +312,56 @@ class Projects extends DolibarrApi * @return int */ /* - public function postLine($id, $request_data = null) - { - if(! DolibarrApiAccess::$user->rights->projet->creer) { - throw new RestException(401); - } + public function postLine($id, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->projet->creer) { + throw new RestException(401); + } - $result = $this->project->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Project not found'); - } + $result = $this->project->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Project not found'); + } - if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->project->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - $request_data->info_bits, - $request_data->fk_remise_except, - 'HT', - 0, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->array_options, - $request_data->fk_unit, - $this->element, - $request_data->id - ); + if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->project->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + $request_data->info_bits, + $request_data->fk_remise_except, + 'HT', + 0, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->array_options, + $request_data->fk_unit, + $this->element, + $request_data->id + ); - if ($updateRes > 0) { - return $updateRes; + if ($updateRes > 0) { + return $updateRes; - } - return false; - } - */ + } + return false; + } + */ /** * Update a task to given project @@ -371,52 +375,52 @@ class Projects extends DolibarrApi * @return object */ /* - public function putLine($id, $lineid, $request_data = null) - { - if(! DolibarrApiAccess::$user->rights->projet->creer) { - throw new RestException(401); - } + public function putLine($id, $lineid, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->projet->creer) { + throw new RestException(401); + } - $result = $this->project->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Project not found'); - } + $result = $this->project->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Project not found'); + } - if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->project->updateline( - $lineid, - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->remise_percent, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - 'HT', - $request_data->info_bits, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->fk_parent_line, - 0, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->special_code, - $request_data->array_options, - $request_data->fk_unit - ); + if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->project->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + 'HT', + $request_data->info_bits, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->fk_parent_line, + 0, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->special_code, + $request_data->array_options, + $request_data->fk_unit + ); - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } - return false; - }*/ + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; + }*/ @@ -443,12 +447,13 @@ class Projects extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->project->$field = $value; } - if ($this->project->update(DolibarrApiAccess::$user) >= 0) - { + if ($this->project->update(DolibarrApiAccess::$user) >= 0) { return $this->get($id); } else { throw new RestException(500, $this->project->error); @@ -600,8 +605,9 @@ class Projects extends DolibarrApi { $object = array(); foreach (self::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $object[$field] = $data[$field]; } return $object; diff --git a/htdocs/projet/class/api_tasks.class.php b/htdocs/projet/class/api_tasks.class.php index e7bf2c67ce8..518b3576e34 100644 --- a/htdocs/projet/class/api_tasks.class.php +++ b/htdocs/projet/class/api_tasks.class.php @@ -33,7 +33,7 @@ class Tasks extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'ref', 'label', 'fk_project' @@ -80,12 +80,10 @@ class Tasks extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if ($includetimespent == 1) - { + if ($includetimespent == 1) { $timespent = $this->task->getSummaryOfTimeSpent(0); } - if ($includetimespent == 1) - { + if ($includetimespent == 1) { // TODO // Add class for timespent records and loop and fill $line->lines with records of timespent } @@ -118,28 +116,37 @@ class Tasks extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= ' WHERE t.entity IN ('.getEntity('project').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -148,8 +155,7 @@ class Tasks extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -160,13 +166,11 @@ class Tasks extends DolibarrApi dol_syslog("API Rest request"); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $task_static = new Task($this->db); if ($task_static->fetch($obj->rowid)) { @@ -201,12 +205,12 @@ class Tasks extends DolibarrApi $this->task->$field = $value; } /*if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->project->lines = $lines; - }*/ + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->project->lines = $lines; + }*/ if ($this->task->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating task", array_merge(array($this->task->error), $this->task->errors)); } @@ -223,38 +227,38 @@ class Tasks extends DolibarrApi // * @url GET {id}/tasks // */ /* - public function getLines($id, $includetimespent=0) - { - if(! DolibarrApiAccess::$user->rights->projet->lire) { - throw new RestException(401); - } + public function getLines($id, $includetimespent=0) + { + if(! DolibarrApiAccess::$user->rights->projet->lire) { + throw new RestException(401); + } - $result = $this->project->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Project not found'); - } + $result = $this->project->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Project not found'); + } - if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->project->getLinesArray(DolibarrApiAccess::$user); - $result = array(); - foreach ($this->project->lines as $line) // $line is a task - { - if ($includetimespent == 1) - { - $timespent = $line->getSummaryOfTimeSpent(0); - } - if ($includetimespent == 1) - { - // TODO - // Add class for timespent records and loop and fill $line->lines with records of timespent - } - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } - */ + if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->project->getLinesArray(DolibarrApiAccess::$user); + $result = array(); + foreach ($this->project->lines as $line) // $line is a task + { + if ($includetimespent == 1) + { + $timespent = $line->getSummaryOfTimeSpent(0); + } + if ($includetimespent == 1) + { + // TODO + // Add class for timespent records and loop and fill $line->lines with records of timespent + } + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + */ /** * Get roles a user is assigned to a task with @@ -284,8 +288,7 @@ class Tasks extends DolibarrApi } $usert = DolibarrApiAccess::$user; - if ($userid > 0) - { + if ($userid > 0) { $usert = new User($this->db); $usert->fetch($userid); } @@ -309,56 +312,56 @@ class Tasks extends DolibarrApi // * @return int // */ /* - public function postLine($id, $request_data = null) - { - if(! DolibarrApiAccess::$user->rights->projet->creer) { - throw new RestException(401); - } + public function postLine($id, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->projet->creer) { + throw new RestException(401); + } - $result = $this->project->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Project not found'); - } + $result = $this->project->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Project not found'); + } - if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->project->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - $request_data->info_bits, - $request_data->fk_remise_except, - 'HT', - 0, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->array_options, - $request_data->fk_unit, - $this->element, - $request_data->id - ); + if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->project->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + $request_data->info_bits, + $request_data->fk_remise_except, + 'HT', + 0, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->array_options, + $request_data->fk_unit, + $this->element, + $request_data->id + ); - if ($updateRes > 0) { - return $updateRes; + if ($updateRes > 0) { + return $updateRes; - } - return false; - } - */ + } + return false; + } + */ // /** // * Update a task to given project @@ -372,52 +375,52 @@ class Tasks extends DolibarrApi // * @return object // */ /* - public function putLine($id, $lineid, $request_data = null) - { - if(! DolibarrApiAccess::$user->rights->projet->creer) { - throw new RestException(401); - } + public function putLine($id, $lineid, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->projet->creer) { + throw new RestException(401); + } - $result = $this->project->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Project not found'); - } + $result = $this->project->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Project not found'); + } - if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->project->updateline( - $lineid, - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->remise_percent, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - 'HT', - $request_data->info_bits, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->fk_parent_line, - 0, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->special_code, - $request_data->array_options, - $request_data->fk_unit - ); + if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->project->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + 'HT', + $request_data->info_bits, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->fk_parent_line, + 0, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->special_code, + $request_data->array_options, + $request_data->fk_unit + ); - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } - return false; - }*/ + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; + }*/ /** @@ -443,12 +446,13 @@ class Tasks extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->task->$field = $value; } - if ($this->task->update(DolibarrApiAccess::$user) > 0) - { + if ($this->task->update(DolibarrApiAccess::$user) > 0) { return $this->get($id); } else { throw new RestException(500, $this->task->error); @@ -519,7 +523,9 @@ class Tasks extends DolibarrApi } $uid = $user_id; - if (empty($uid)) $uid = DolibarrApiAccess::$user->id; + if (empty($uid)) { + $uid = DolibarrApiAccess::$user->id; + } $newdate = dol_stringtotime($date, 1); $this->task->timespent_date = $newdate; @@ -607,8 +613,9 @@ class Tasks extends DolibarrApi { $object = array(); foreach (self::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $object[$field] = $data[$field]; } return $object; diff --git a/htdocs/projet/class/project.class.php b/htdocs/projet/class/project.class.php index 4fff4297854..137757eae1a 100644 --- a/htdocs/projet/class/project.class.php +++ b/htdocs/projet/class/project.class.php @@ -200,7 +200,11 @@ class Project extends CommonObject 'usage_bill_time' =>array('type'=>'integer', 'label'=>'UsageBillTimeShort', 'enabled'=>1, 'visible'=>-1, 'position'=>130), 'usage_opportunity' =>array('type'=>'integer', 'label'=>'UsageOpportunity', 'enabled'=>1, 'visible'=>-1, 'position'=>135), 'usage_task' =>array('type'=>'integer', 'label'=>'UsageTasks', 'enabled'=>1, 'visible'=>-1, 'position'=>140), - 'usage_organize_event' =>array('type'=>'integer', 'label'=>'Usage organize event', 'enabled'=>1, 'visible'=>-1, 'position'=>145), + 'usage_organize_event' =>array('type'=>'integer', 'label'=>'UsageOrganizeEvent', 'enabled'=>1, 'visible'=>-1, 'position'=>145), + 'accept_conference_suggestions' =>array('type'=>'integer', 'label'=>'AllowUnknownPeopleSuggestConf', 'enabled'=>1, 'visible'=>-1, 'position'=>146), + 'accept_booth_suggestions' =>array('type'=>'integer', 'label'=>'AllowUnknownPeopleSuggestBooth', 'enabled'=>1, 'visible'=>-1, 'position'=>147), + 'price_registration' =>array('type'=>'double(24,8)', 'label'=>'PriceOfRegistration', 'enabled'=>1, 'visible'=>-1, 'position'=>148), + 'price_booth' =>array('type'=>'double(24,8)', 'label'=>'PriceOfBooth', 'enabled'=>1, 'visible'=>-1, 'position'=>149), 'datec' =>array('type'=>'datetime', 'label'=>'DateCreationShort', 'enabled'=>1, 'visible'=>-2, 'position'=>200), 'tms' =>array('type'=>'timestamp', 'label'=>'DateModificationShort', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>205), 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserCreation', 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>210), @@ -232,6 +236,8 @@ class Project extends CommonObject */ public function __construct($db) { + global $conf; + $this->db = $db; $this->statuts_short = array(0 => 'Draft', 1 => 'Opened', 2 => 'Closed'); @@ -239,22 +245,28 @@ class Project extends CommonObject global $conf; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { + $this->fields['rowid']['visible'] = 0; + } - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { + if (empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { $this->fields['fk_opp_status']['enabled'] = 0; $this->fields['opp_percent']['enabled'] = 0; $this->fields['opp_amount']['enabled'] = 0; $this->fields['usage_opportunity']['enabled'] = 0; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) { + if (!empty($conf->global->PROJECT_HIDE_TASKS)) { $this->fields['usage_bill_time']['visible'] = 0; $this->fields['usage_task']['visible'] = 0; } - if (empty($conf->global->PROJECT_ORGANIZE_EVENTS)) { + if (empty($conf->eventorganization->enabled)) { $this->fields['usage_organize_event']['visible'] = 0; + $this->fields['accept_conference_suggestions']['enabled'] = 0; + $this->fields['accept_booth_suggestions']['enabled'] = 0; + $this->fields['price_registration']['enabled'] = 0; + $this->fields['price_booth']['enabled'] = 0; } } @@ -279,14 +291,12 @@ class Project extends CommonObject $this->note_public = dol_substr($this->note_public, 0, 65535); // Check parameters - if (!trim($this->ref)) - { + if (!trim($this->ref)) { $this->error = 'ErrorFieldsRequired'; dol_syslog(get_class($this)."::create error -1 ref null", LOG_ERR); return -1; } - if (!empty($conf->global->PROJECT_THIRDPARTY_REQUIRED) && !($this->socid > 0)) - { + if (!empty($conf->global->PROJECT_THIRDPARTY_REQUIRED) && !($this->socid > 0)) { $this->error = 'ErrorFieldsRequired'; dol_syslog(get_class($this)."::create error -1 thirdparty not defined and option PROJECT_THIRDPARTY_REQUIRED is set", LOG_ERR); return -1; @@ -314,6 +324,10 @@ class Project extends CommonObject $sql .= ", usage_task"; $sql .= ", usage_bill_time"; $sql .= ", usage_organize_event"; + $sql .= ", accept_conference_suggestions"; + $sql .= ", accept_booth_suggestions"; + $sql .= ", price_registration"; + $sql .= ", price_booth"; $sql .= ", email_msgid"; $sql .= ", note_private"; $sql .= ", note_public"; @@ -337,6 +351,10 @@ class Project extends CommonObject $sql .= ", ".($this->usage_task ? 1 : 0); $sql .= ", ".($this->usage_bill_time ? 1 : 0); $sql .= ", ".($this->usage_organize_event ? 1 : 0); + $sql .= ", ".($this->accept_conference_suggestions ? 1 : 0); + $sql .= ", ".($this->accept_booth_suggestions ? 1 : 0); + $sql .= ", ".(strcmp($this->price_registration, '') ? price2num($this->price_registration) : 'null'); + $sql .= ", ".(strcmp($this->price_booth, '') ? price2num($this->price_booth) : 'null'); $sql .= ", ".($this->email_msgid ? "'".$this->db->escape($this->email_msgid)."'" : 'null'); $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : 'null'); $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : 'null'); @@ -345,16 +363,16 @@ class Project extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet"); $ret = $this->id; - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('PROJECT_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } else { @@ -366,20 +384,19 @@ class Project extends CommonObject // Update extrafield if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !empty($conf->global->MAIN_DISABLEDRAFTSTATUS)) - { + if (!$error && !empty($conf->global->MAIN_DISABLEDRAFTSTATUS)) { $res = $this->setValid($user); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { $this->db->commit(); return $ret; } else { @@ -404,10 +421,13 @@ class Project extends CommonObject // Clean parameters $this->title = trim($this->title); $this->description = trim($this->description); - if ($this->opp_amount < 0) $this->opp_amount = ''; - if ($this->opp_percent < 0) $this->opp_percent = ''; - if ($this->date_end && $this->date_end < $this->date_start) - { + if ($this->opp_amount < 0) { + $this->opp_amount = ''; + } + if ($this->opp_percent < 0) { + $this->opp_percent = ''; + } + if ($this->date_end && $this->date_end < $this->date_start) { $this->error = $langs->trans("ErrorDateEndLowerThanDateStart"); $this->errors[] = $this->error; $this->db->rollback(); @@ -415,8 +435,7 @@ class Project extends CommonObject return -3; } - if (dol_strlen(trim($this->ref)) > 0) - { + if (dol_strlen(trim($this->ref)) > 0) { $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."projet SET"; @@ -440,43 +459,41 @@ class Project extends CommonObject $sql .= ", usage_task = ".($this->usage_task ? 1 : 0); $sql .= ", usage_bill_time = ".($this->usage_bill_time ? 1 : 0); $sql .= ", usage_organize_event = ".($this->usage_organize_event ? 1 : 0); + $sql .= ", accept_conference_suggestions = ".($this->accept_conference_suggestions ? 1 : 0); + $sql .= ", accept_booth_suggestions = ".($this->accept_booth_suggestions ? 1 : 0); + $sql .= ", price_registration = ".(strcmp($this->price_registration, '') ? price2num($this->price_registration) : "null"); + $sql .= ", price_booth = ".(strcmp($this->price_booth, '') ? price2num($this->price_booth) : "null"); $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Update extrafield - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('PROJECT_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) - { + if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) { // We remove directory - if ($conf->projet->dir_output) - { + if ($conf->projet->dir_output) { $olddir = $conf->projet->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref); $newdir = $conf->projet->dir_output."/".dol_sanitizeFileName($this->ref); - if (file_exists($olddir)) - { + if (file_exists($olddir)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $res = @rename($olddir, $newdir); - if (!$res) - { + if (!$res) { $langs->load("errors"); $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir); $error++; @@ -484,8 +501,7 @@ class Project extends CommonObject } } } - if (!$error) - { + if (!$error) { $this->db->commit(); $result = 1; } else { @@ -496,8 +512,7 @@ class Project extends CommonObject $this->error = $this->db->lasterror(); $this->errors[] = $this->error; $this->db->rollback(); - if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $result = -4; } else { $result = -2; @@ -525,15 +540,17 @@ class Project extends CommonObject { global $conf; - if (empty($id) && empty($ref)) return -1; + if (empty($id) && empty($ref)) { + return -1; + } $sql = "SELECT rowid, entity, ref, title, description, public, datec, opp_amount, budget_amount,"; $sql .= " tms, dateo, datee, date_close, fk_soc, fk_user_creat, fk_user_modif, fk_user_close, fk_statut as status, fk_opp_status, opp_percent,"; - $sql .= " note_private, note_public, model_pdf, usage_opportunity, usage_task, usage_bill_time, usage_organize_event, email_msgid"; + $sql .= " note_private, note_public, model_pdf, usage_opportunity, usage_task, usage_bill_time, usage_organize_event, email_msgid,"; + $sql .= " accept_conference_suggestions, accept_booth_suggestions, price_registration, price_booth"; $sql .= " FROM ".MAIN_DB_PREFIX."projet"; - if (!empty($id)) - { - $sql .= " WHERE rowid = ".$id; + if (!empty($id)) { + $sql .= " WHERE rowid = ".((int) $id); } else { $sql .= " WHERE entity IN (".getEntity('project').")"; if (!empty($ref)) { @@ -547,12 +564,10 @@ class Project extends CommonObject dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_rows = $this->db->num_rows($resql); - if ($num_rows) - { + if ($num_rows) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -586,6 +601,10 @@ class Project extends CommonObject $this->usage_task = (int) $obj->usage_task; $this->usage_bill_time = (int) $obj->usage_bill_time; $this->usage_organize_event = (int) $obj->usage_organize_event; + $this->accept_conference_suggestions = (int) $obj->accept_conference_suggestions; + $this->accept_booth_suggestions = (int) $obj->accept_booth_suggestions; + $this->price_registration = $obj->price_registration; + $this->price_booth = $obj->price_booth; $this->email_msgid = $obj->email_msgid; $this->db->free($resql); @@ -602,6 +621,7 @@ class Project extends CommonObject return 0; } else { $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); return -1; } } @@ -626,27 +646,23 @@ class Project extends CommonObject $elements = array(); - if ($this->id <= 0) return $elements; + if ($this->id <= 0) { + return $elements; + } $ids = $this->id; - if ($type == 'agenda') - { + if ($type == 'agenda') { $sql = "SELECT id as rowid FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project IN (".$ids.") AND entity IN (".getEntity('agenda').")"; - } elseif ($type == 'expensereport') - { + } elseif ($type == 'expensereport') { $sql = "SELECT ed.rowid FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."expensereport_det as ed WHERE e.rowid = ed.fk_expensereport AND e.entity IN (".getEntity('expensereport').") AND ed.fk_projet IN (".$ids.")"; - } elseif ($type == 'project_task') - { + } elseif ($type == 'project_task') { $sql = "SELECT DISTINCT pt.rowid FROM ".MAIN_DB_PREFIX."projet_task as pt WHERE pt.fk_projet IN (".$ids.")"; - } elseif ($type == 'project_task_time') // Case we want to duplicate line foreach user - { + } elseif ($type == 'project_task_time') { // Case we want to duplicate line foreach user $sql = "SELECT DISTINCT pt.rowid, ptt.fk_user FROM ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."projet_task_time as ptt WHERE pt.rowid = ptt.fk_task AND pt.fk_projet IN (".$ids.")"; - } elseif ($type == 'stock_mouvement') - { + } elseif ($type == 'stock_mouvement') { $sql = 'SELECT ms.rowid, ms.fk_user_author as fk_user FROM '.MAIN_DB_PREFIX."stock_mouvement as ms, ".MAIN_DB_PREFIX."entrepot as e WHERE e.rowid = ms.fk_entrepot AND e.entity IN (".getEntity('stock').") AND ms.origintype = 'project' AND ms.fk_origin IN (".$ids.") AND ms.type_mouvement = 1"; - } elseif ($type == 'loan') - { + } elseif ($type == 'loan') { $sql = 'SELECT l.rowid, l.fk_user_author as fk_user FROM '.MAIN_DB_PREFIX."loan as l WHERE l.entity IN (".getEntity('loan').") AND l.fk_projet IN (".$ids.")"; } else { $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." IN (".$ids.") AND entity IN (".getEntity($type).")"; @@ -654,19 +670,25 @@ class Project extends CommonObject if ($dates > 0 && $type == 'loan') { $sql .= " AND (dateend > '".$this->db->idate($dates)."' OR dateend IS NULL)"; - } elseif ($dates > 0 && ($type != 'project_task')) // For table project_taks, we want the filter on date apply on project_time_spent table - { - if (empty($datefieldname) && !empty($this->table_element_date)) $datefieldname = $this->table_element_date; - if (empty($datefieldname)) return 'Error this object has no date field defined'; + } elseif ($dates > 0 && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table + if (empty($datefieldname) && !empty($this->table_element_date)) { + $datefieldname = $this->table_element_date; + } + if (empty($datefieldname)) { + return 'Error this object has no date field defined'; + } $sql .= " AND (".$datefieldname." >= '".$this->db->idate($dates)."' OR ".$datefieldname." IS NULL)"; } if ($datee > 0 && $type == 'loan') { $sql .= " AND (datestart < '".$this->db->idate($datee)."' OR datestart IS NULL)"; - } elseif ($datee > 0 && ($type != 'project_task')) // For table project_taks, we want the filter on date apply on project_time_spent table - { - if (empty($datefieldname) && !empty($this->table_element_date)) $datefieldname = $this->table_element_date; - if (empty($datefieldname)) return 'Error this object has no date field defined'; + } elseif ($datee > 0 && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table + if (empty($datefieldname) && !empty($this->table_element_date)) { + $datefieldname = $this->table_element_date; + } + if (empty($datefieldname)) { + return 'Error this object has no date field defined'; + } $sql .= " AND (".$datefieldname." <= '".$this->db->idate($datee)."' OR ".$datefieldname." IS NULL)"; } @@ -680,22 +702,24 @@ class Project extends CommonObject 'fk_projet' => $projectkey ); $reshook = $hookmanager->executeHooks('getElementList', $parameters, $object, $action); - if ($reshook > 0) $sql = $hookmanager->resPrint; - else $sql .= $hookmanager->resPrint; + if ($reshook > 0) { + $sql = $hookmanager->resPrint; + } else { + $sql .= $hookmanager->resPrint; + } - if (!$sql) return -1; + if (!$sql) { + return -1; + } //print $sql; dol_syslog(get_class($this)."::get_element_list", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $nump = $this->db->num_rows($result); - if ($nump) - { + if ($nump) { $i = 0; - while ($i < $nump) - { + while ($i < $nump) { $obj = $this->db->fetch_object($result); $elements[$i] = $obj->rowid.(empty($obj->fk_user) ? '' : '_'.$obj->fk_user); @@ -728,12 +752,10 @@ class Project extends CommonObject $this->db->begin(); - if (!$error) - { + if (!$error) { // Delete linked contacts $res = $this->delete_linked_contact(); - if ($res < 0) - { + if ($res < 0) { $this->error = 'ErrorFailToDeleteLinkedContact'; //$error++; $this->db->rollback(); @@ -748,12 +770,10 @@ class Project extends CommonObject 'expensereport_det'=>'fk_projet', 'contrat'=>'fk_projet', 'fichinter'=>'fk_projet', 'don'=>'fk_projet', 'actioncomm'=>'fk_project', 'mrp_mo'=>'fk_project' ); - foreach ($listoftables as $key => $value) - { + foreach ($listoftables as $key => $value) { $sql = "UPDATE ".MAIN_DB_PREFIX.$key." SET ".$value." = NULL where ".$value." = ".$this->id; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->lasterror(); $error++; break; @@ -777,14 +797,15 @@ class Project extends CommonObject // Delete tasks $ret = $this->deleteTasks($user); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } // Delete all child tables if (!$error) { $elements = array('categorie_project'); // elements to delete. TODO Make goodway to delete - foreach ($elements as $table) - { + foreach ($elements as $table) { if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table; $sql .= " WHERE fk_project = ".$this->id; @@ -798,28 +819,24 @@ class Project extends CommonObject } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_extrafields"; $sql .= " WHERE fk_object=".$this->id; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->lasterror(); $error++; } } // Delete project - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $langs->trans("CantRemoveProject", $langs->transnoentitiesnoconv("ProjectOverview")); $error++; } @@ -841,8 +858,7 @@ class Project extends CommonObject } } - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('PROJECT_DELETE', $user); @@ -853,13 +869,11 @@ class Project extends CommonObject } } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -879,7 +893,9 @@ class Project extends CommonObject */ public function getElementCount($type, $tablename, $projectkey = 'fk_projet') { - if ($this->id <= 0) return 0; + if ($this->id <= 0) { + return 0; + } if ($type == 'agenda') { $sql = "SELECT COUNT(id) as nb FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project = ".$this->id." AND entity IN (".getEntity('agenda').")"; @@ -899,7 +915,9 @@ class Project extends CommonObject $result = $this->db->query($sql); - if (!$result) return 0; + if (!$result) { + return 0; + } $obj = $this->db->fetch_object($result); @@ -918,15 +936,12 @@ class Project extends CommonObject { $countTasks = count($this->lines); $deleted = false; - if ($countTasks) - { - foreach ($this->lines as $task) - { + if ($countTasks) { + foreach ($this->lines as $task) { if ($task->hasChildren() <= 0) { // If there is no children (or error to detect them) $deleted = true; $ret = $task->delete($user); - if ($ret <= 0) - { + if ($ret <= 0) { $this->errors[] = $this->db->lasterror(); return -1; } @@ -934,9 +949,10 @@ class Project extends CommonObject } } $this->getLinesArray($user); - if ($deleted && count($this->lines) < $countTasks) - { - if (count($this->lines)) $this->deleteTasks($this->lines); + if ($deleted && count($this->lines) < $countTasks) { + if (count($this->lines)) { + $this->deleteTasks($this->lines); + } } return 1; @@ -955,11 +971,9 @@ class Project extends CommonObject $error = 0; - if ($this->statut != 1) - { + if ($this->statut != 1) { // Check parameters - if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->title)) - { + if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->title)) { $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("Label")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf")); return -1; } @@ -973,18 +987,17 @@ class Project extends CommonObject dol_syslog(get_class($this)."::setValid", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger - if (empty($notrigger)) - { + if (empty($notrigger)) { $result = $this->call_trigger('PROJECT_VALIDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->statut = 1; $this->db->commit(); return 1; @@ -1016,8 +1029,7 @@ class Project extends CommonObject $error = 0; - if ($this->statut != self::STATUS_CLOSED) - { + if ($this->statut != self::STATUS_CLOSED) { $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."projet"; @@ -1025,22 +1037,21 @@ class Project extends CommonObject $sql .= " WHERE rowid = ".$this->id; $sql .= " AND fk_statut = ".self::STATUS_VALIDATED; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { // TODO What to do if fk_opp_status is not code 'WON' or 'LOST' } dol_syslog(get_class($this)."::setClose", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger $result = $this->call_trigger('PROJECT_CLOSE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers - if (!$error) - { + if (!$error) { $this->statut = 2; $this->db->commit(); return 1; @@ -1115,7 +1126,9 @@ class Project extends CommonObject { global $conf, $langs, $user, $hookmanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; if (!empty($conf->global->PROJECT_OPEN_ALWAYS_ON_TAB)) { @@ -1123,7 +1136,9 @@ class Project extends CommonObject } $label = ''; - if ($option != 'nolink') $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Project").'</u>'; + if ($option != 'nolink') { + $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Project").'</u>'; + } if (isset($this->status)) { $label .= ' '.$this->getLibStatut(5); } @@ -1141,60 +1156,75 @@ class Project extends CommonObject if (!empty($this->datee)) { $label .= ($label ? '<br>' : '').'<b>'.$langs->trans('DateEnd').': </b>'.dol_print_date($this->datee, 'day'); // The space must be after the : to not being explode when showing the title in img_picto } - if ($moreinpopup) $label .= '<br>'.$moreinpopup; + if ($moreinpopup) { + $label .= '<br>'.$moreinpopup; + } $url = ''; - if ($option != 'nolink') - { + if ($option != 'nolink') { if (preg_match('/\.php$/', $option)) { $url = dol_buildpath($option, 1).'?id='.$this->id; - } elseif ($option == 'task') - { + } elseif ($option == 'task') { $url = DOL_URL_ROOT.'/projet/tasks.php?id='.$this->id; - } elseif ($option == 'preview') - { + } elseif ($option == 'preview') { $url = DOL_URL_ROOT.'/projet/element.php?id='.$this->id; + } elseif ($option == 'eventorganization') { + $url = DOL_URL_ROOT.'/eventorganization/conferenceorbooth_list.php?projectid='.$this->id; } else { $url = DOL_URL_ROOT.'/projet/card.php?id='.$this->id; } // 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'; + } } $linkclose = ''; - if (empty($notooltip) && $user->rights->projet->lire) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip) && $user->rights->projet->lire) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowProject"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } - else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $picto = 'projectpub'; - if (!$this->public) $picto = 'project'; + if (!$this->public) { + $picto = 'project'; + } $linkstart = '<a href="'.$url.'"'; $linkstart .= $linkclose.'>'; $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; - if ($withpicto != 2) $result .= (($addlabel && $this->title) ? $sep.dol_trunc($this->title, ($addlabel > 1 ? $addlabel : 0)) : ''); + if ($withpicto != 2) { + $result .= (($addlabel && $this->title) ? $sep.dol_trunc($this->title, ($addlabel > 1 ? $addlabel : 0)) : ''); + } global $action; $hookmanager->initHooks(array('projectdao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -1258,32 +1288,38 @@ class Project extends CommonObject { // To verify role of users $userAccess = 0; - if (($mode == 'read' && !empty($user->rights->projet->all->lire)) || ($mode == 'write' && !empty($user->rights->projet->all->creer)) || ($mode == 'delete' && !empty($user->rights->projet->all->supprimer))) - { + if (($mode == 'read' && !empty($user->rights->projet->all->lire)) || ($mode == 'write' && !empty($user->rights->projet->all->creer)) || ($mode == 'delete' && !empty($user->rights->projet->all->supprimer))) { $userAccess = 1; - } elseif ($this->public && (($mode == 'read' && !empty($user->rights->projet->lire)) || ($mode == 'write' && !empty($user->rights->projet->creer)) || ($mode == 'delete' && !empty($user->rights->projet->supprimer)))) - { + } elseif ($this->public && (($mode == 'read' && !empty($user->rights->projet->lire)) || ($mode == 'write' && !empty($user->rights->projet->creer)) || ($mode == 'delete' && !empty($user->rights->projet->supprimer)))) { $userAccess = 1; } else { // No access due to permission to read all projects, so we check if we are a contact of project - foreach (array('internal', 'external') as $source) - { + foreach (array('internal', 'external') as $source) { $userRole = $this->liste_contact(4, $source); $num = count($userRole); $nblinks = 0; - while ($nblinks < $num) - { - if ($source == 'internal' && $user->id == $userRole[$nblinks]['id']) // $userRole[$nblinks]['id'] is id of user (llx_user) for internal contacts - { - if ($mode == 'read' && $user->rights->projet->lire) $userAccess++; - if ($mode == 'write' && $user->rights->projet->creer) $userAccess++; - if ($mode == 'delete' && $user->rights->projet->supprimer) $userAccess++; + while ($nblinks < $num) { + if ($source == 'internal' && $user->id == $userRole[$nblinks]['id']) { // $userRole[$nblinks]['id'] is id of user (llx_user) for internal contacts + if ($mode == 'read' && $user->rights->projet->lire) { + $userAccess++; + } + if ($mode == 'write' && $user->rights->projet->creer) { + $userAccess++; + } + if ($mode == 'delete' && $user->rights->projet->supprimer) { + $userAccess++; + } } - if ($source == 'external' && $user->socid > 0 && $user->socid == $userRole[$nblinks]['socid']) // $userRole[$nblinks]['id'] is id of contact (llx_socpeople) or external contacts - { - if ($mode == 'read' && $user->rights->projet->lire) $userAccess++; - if ($mode == 'write' && $user->rights->projet->creer) $userAccess++; - if ($mode == 'delete' && $user->rights->projet->supprimer) $userAccess++; + if ($source == 'external' && $user->socid > 0 && $user->socid == $userRole[$nblinks]['socid']) { // $userRole[$nblinks]['id'] is id of contact (llx_socpeople) or external contacts + if ($mode == 'read' && $user->rights->projet->lire) { + $userAccess++; + } + if ($mode == 'write' && $user->rights->projet->creer) { + $userAccess++; + } + if ($mode == 'delete' && $user->rights->projet->supprimer) { + $userAccess++; + } } $nblinks++; } @@ -1317,20 +1353,19 @@ class Project extends CommonObject $sql = "SELECT ".(($mode == 0 || $mode == 1) ? "DISTINCT " : "")."p.rowid, p.ref"; $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; - if ($mode == 0) - { + if ($mode == 0) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_contact as ec ON ec.element_id = p.rowid"; - } elseif ($mode == 1) - { + } elseif ($mode == 1) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; - } elseif ($mode == 2) - { + } elseif ($mode == 2) { // No filter. Use this if user has permission to see all project } $sql .= " WHERE p.entity IN (".getEntity('project').")"; // Internal users must see project he is contact to even if project linked to a third party he can't see. //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; - if ($socid > 0) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + if ($socid > 0) { + $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + } // Get id of types of contacts for projects (This list never contains a lot of elements) $listofprojectcontacttype = array(); @@ -1338,30 +1373,29 @@ class Project extends CommonObject $sql2 .= " WHERE ctc.element = '".$this->db->escape($this->element)."'"; $sql2 .= " AND ctc.source = 'internal'"; $resql = $this->db->query($sql2); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $listofprojectcontacttype[$obj->rowid] = $obj->code; } - } else dol_print_error($this->db); - if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0] = '0'; // To avoid syntax error if not found + } else { + dol_print_error($this->db); + } + if (count($listofprojectcontacttype) == 0) { + $listofprojectcontacttype[0] = '0'; // To avoid syntax error if not found + } - if ($mode == 0) - { + if ($mode == 0) { $sql .= " AND ( p.public = 1"; $sql .= " OR ( ec.fk_c_type_contact IN (".join(',', array_keys($listofprojectcontacttype)).")"; $sql .= " AND ec.fk_socpeople = ".$user->id.")"; $sql .= " )"; - } elseif ($mode == 1) - { + } elseif ($mode == 1) { $sql .= " AND ec.element_id = p.rowid"; $sql .= " AND ("; $sql .= " ( ec.fk_c_type_contact IN (".join(',', array_keys($listofprojectcontacttype)).")"; $sql .= " AND ec.fk_socpeople = ".$user->id.")"; $sql .= " )"; - } elseif ($mode == 2) - { + } elseif ($mode == 2) { // No filter. Use this if user has permission to see all project } @@ -1369,12 +1403,10 @@ class Project extends CommonObject //print $sql; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $row = $this->db->fetch_row($resql); $projects[$row[0]] = $row[1]; $temp[] = $row[0]; @@ -1383,9 +1415,10 @@ class Project extends CommonObject $this->db->free($resql); - if ($list) - { - if (empty($temp)) return '0'; + if ($list) { + if (empty($temp)) { + return '0'; + } $result = implode(',', $temp); return $result; } @@ -1430,7 +1463,9 @@ class Project extends CommonObject // Load source object $clone_project->fetch($fromid); $clone_project->fetch_optionals(); - if ($newthirdpartyid > 0) $clone_project->socid = $newthirdpartyid; + if ($newthirdpartyid > 0) { + $clone_project->socid = $newthirdpartyid; + } $clone_project->fetch_thirdparty(); $orign_dt_start = $clone_project->date_start; @@ -1439,16 +1474,14 @@ class Project extends CommonObject $clone_project->id = 0; if ($move_date) { $clone_project->date_start = $now; - if (!(empty($clone_project->date_end))) - { + if (!(empty($clone_project->date_end))) { $clone_project->date_end = $clone_project->date_end + ($now - $orign_dt_start); } } $clone_project->datec = $now; - if (!$clone_note) - { + if (!$clone_note) { $clone_project->note_private = ''; $clone_project->note_public = ''; } @@ -1459,11 +1492,9 @@ class Project extends CommonObject // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/project/".$obj.'.php', 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; dol_include_once($reldir."core/modules/project/".$obj.'.php'); $modProject = new $obj; @@ -1471,7 +1502,9 @@ class Project extends CommonObject break; } } - if (is_numeric($defaultref) && $defaultref <= 0) $defaultref = ''; + if (is_numeric($defaultref) && $defaultref <= 0) { + $defaultref = ''; + } $clone_project->ref = $defaultref; $clone_project->title = $langs->trans("CopyOf").' '.$clone_project->title; @@ -1480,27 +1513,23 @@ class Project extends CommonObject $result = $clone_project->create($user, $notrigger); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error .= $clone_project->error; $error++; } - if (!$error) - { + if (!$error) { //Get the new project id $clone_project_id = $clone_project->id; //Note Update - if (!$clone_note) - { + if (!$clone_note) { $clone_project->note_private = ''; $clone_project->note_public = ''; } else { $this->db->begin(); $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_public, ENT_QUOTES | ENT_HTML5), '_public'); - if ($res < 0) - { + if ($res < 0) { $this->error .= $clone_project->error; $error++; $this->db->rollback(); @@ -1510,8 +1539,7 @@ class Project extends CommonObject $this->db->begin(); $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_private, ENT_QUOTES | ENT_HTML5), '_private'); - if ($res < 0) - { + if ($res < 0) { $this->error .= $clone_project->error; $error++; $this->db->rollback(); @@ -1521,26 +1549,21 @@ class Project extends CommonObject } //Duplicate contact - if ($clone_contact) - { + if ($clone_contact) { $origin_project = new Project($this->db); $origin_project->fetch($fromid); - foreach (array('internal', 'external') as $source) - { + foreach (array('internal', 'external') as $source) { $tab = $origin_project->liste_contact(-1, $source); - foreach ($tab as $contacttoadd) - { + foreach ($tab as $contacttoadd) { $clone_project->add_contact($contacttoadd['id'], $contacttoadd['code'], $contacttoadd['source'], $notrigger); - if ($clone_project->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($clone_project->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); $this->error .= $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); $error++; } else { - if ($clone_project->error != '') - { + if ($clone_project->error != '') { $this->error .= $clone_project->error; $error++; } @@ -1550,21 +1573,17 @@ class Project extends CommonObject } //Duplicate file - if ($clone_project_file) - { + if ($clone_project_file) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $clone_project_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($defaultref); $ori_project_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($orign_project_ref); - if (dol_mkdir($clone_project_dir) >= 0) - { + if (dol_mkdir($clone_project_dir) >= 0) { $filearray = dol_dir_list($ori_project_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1); - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $rescopy = dol_copy($ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name'], 0, 1); - if (is_numeric($rescopy) && $rescopy < 0) - { + if (is_numeric($rescopy) && $rescopy < 0) { $this->error .= $langs->trans("ErrorFailToCopyFile", $ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name']); $error++; } @@ -1576,26 +1595,25 @@ class Project extends CommonObject } //Duplicate task - if ($clone_task) - { + if ($clone_task) { require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; $taskstatic = new Task($this->db); // Security check $socid = 0; - if ($user->socid > 0) $socid = $user->socid; + if ($user->socid > 0) { + $socid = $user->socid; + } $tasksarray = $taskstatic->getTasksArray(0, 0, $fromid, $socid, 0); $tab_conv_child_parent = array(); // Loop on each task, to clone it - foreach ($tasksarray as $tasktoclone) - { + foreach ($tasksarray as $tasktoclone) { $result_clone = $taskstatic->createFromClone($user, $tasktoclone->id, $clone_project_id, $tasktoclone->fk_parent, $move_date, true, false, $clone_task_file, true, false); - if ($result_clone <= 0) - { + if ($result_clone <= 0) { $this->error .= $result_clone->error; $error++; } else { @@ -1604,8 +1622,7 @@ class Project extends CommonObject //manage new parent clone task id // if the current task has child we store the original task id and the equivalent clone task id - if (($taskstatic->hasChildren()) && !array_key_exists($tasktoclone->id, $tab_conv_child_parent)) - { + if (($taskstatic->hasChildren()) && !array_key_exists($tasktoclone->id, $tab_conv_child_parent)) { $tab_conv_child_parent[$tasktoclone->id] = $new_task_id; } } @@ -1613,16 +1630,13 @@ class Project extends CommonObject //Parse all clone node to be sure to update new parent $tasksarray = $taskstatic->getTasksArray(0, 0, $clone_project_id, $socid, 0); - foreach ($tasksarray as $task_cloned) - { + foreach ($tasksarray as $task_cloned) { $taskstatic->fetch($task_cloned->id); - if ($taskstatic->fk_task_parent != 0) - { + if ($taskstatic->fk_task_parent != 0) { $taskstatic->fk_task_parent = $tab_conv_child_parent[$taskstatic->fk_task_parent]; } $res = $taskstatic->update($user, $notrigger); - if ($result_clone <= 0) - { + if ($result_clone <= 0) { $this->error .= $taskstatic->error; $error++; } @@ -1632,8 +1646,7 @@ class Project extends CommonObject unset($clone_project->context['createfromclone']); - if (!$error) - { + if (!$error) { $this->db->commit(); return $clone_project_id; } else { @@ -1660,22 +1673,21 @@ class Project extends CommonObject // Security check $socid = 0; - if ($user->socid > 0) $socid = $user->socid; + if ($user->socid > 0) { + $socid = $user->socid; + } $tasksarray = $taskstatic->getTasksArray(0, 0, $this->id, $socid, 0); - foreach ($tasksarray as $tasktoshiftdate) - { + foreach ($tasksarray as $tasktoshiftdate) { $to_update = false; // Fetch only if update of date will be made - if ((!empty($tasktoshiftdate->date_start)) || (!empty($tasktoshiftdate->date_end))) - { + if ((!empty($tasktoshiftdate->date_start)) || (!empty($tasktoshiftdate->date_end))) { //dol_syslog(get_class($this)."::shiftTaskDate to_update", LOG_DEBUG); $to_update = true; $task = new Task($this->db); $result = $task->fetch($tasktoshiftdate->id); - if (!$result) - { + if (!$result) { $error++; $this->error .= $task->error; } @@ -1683,29 +1695,24 @@ class Project extends CommonObject //print "$this->date_start + $tasktoshiftdate->date_start - $old_project_dt_start";exit; //Calcultate new task start date with difference between old proj start date and origin task start date - if (!empty($tasktoshiftdate->date_start)) - { + if (!empty($tasktoshiftdate->date_start)) { $task->date_start = $this->date_start + ($tasktoshiftdate->date_start - $old_project_dt_start); } //Calcultate new task end date with difference between origin proj end date and origin task end date - if (!empty($tasktoshiftdate->date_end)) - { + if (!empty($tasktoshiftdate->date_end)) { $task->date_end = $this->date_start + ($tasktoshiftdate->date_end - $old_project_dt_start); } - if ($to_update) - { + if ($to_update) { $result = $task->update($user); - if (!$result) - { + if (!$result) { $error++; $this->error .= $task->error; } } } - if ($error != 0) - { + if ($error != 0) { return -1; } return $result; @@ -1725,8 +1732,7 @@ class Project extends CommonObject // phpcs:enable $sql = "UPDATE ".MAIN_DB_PREFIX.$tableName; - if ($tableName == "actioncomm") - { + if ($tableName == "actioncomm") { $sql .= " SET fk_project=".$this->id; $sql .= " WHERE id=".$elementSelectId; } else { @@ -1759,8 +1765,7 @@ class Project extends CommonObject // phpcs:enable $sql = "UPDATE ".MAIN_DB_PREFIX.$tableName; - if ($tableName == "actioncomm") - { + if ($tableName == "actioncomm") { $sql .= " SET fk_project=NULL"; $sql .= " WHERE id=".$elementSelectId; } else { @@ -1826,7 +1831,9 @@ class Project extends CommonObject $this->weekWorkLoad = array(); $this->weekWorkLoadPerTask = array(); - if (empty($datestart)) dol_print_error('', 'Error datestart parameter is empty'); + if (empty($datestart)) { + dol_print_error('', 'Error datestart parameter is empty'); + } $sql = "SELECT ptt.rowid as taskid, ptt.task_duration, ptt.task_date, ptt.task_datehour, ptt.fk_task"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt"; @@ -1834,24 +1841,25 @@ class Project extends CommonObject $sql .= " AND pt.fk_projet = ".$this->id; $sql .= " AND (ptt.task_date >= '".$this->db->idate($datestart)."' "; $sql .= " AND ptt.task_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'w') - 1)."')"; - if ($taskid) $sql .= " AND ptt.fk_task=".$taskid; - if (is_numeric($userid)) $sql .= " AND ptt.fk_user=".$userid; + if ($taskid) { + $sql .= " AND ptt.fk_task=".$taskid; + } + if (is_numeric($userid)) { + $sql .= " AND ptt.fk_user=".$userid; + } //print $sql; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $daylareadyfound = array(); $num = $this->db->num_rows($resql); $i = 0; // Loop on each record found, so each couple (project id, task id) - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $day = $this->db->jdate($obj->task_date); // task_date is date without hours - if (empty($daylareadyfound[$day])) - { + if (empty($daylareadyfound[$day])) { $this->weekWorkLoad[$day] = $obj->task_duration; $this->weekWorkLoadPerTask[$day][$obj->fk_task] = $obj->task_duration; } else { @@ -1886,7 +1894,9 @@ class Project extends CommonObject $this->monthWorkLoad = array(); $this->monthWorkLoadPerTask = array(); - if (empty($datestart)) dol_print_error('', 'Error datestart parameter is empty'); + if (empty($datestart)) { + dol_print_error('', 'Error datestart parameter is empty'); + } $sql = "SELECT ptt.rowid as taskid, ptt.task_duration, ptt.task_date, ptt.task_datehour, ptt.fk_task"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt"; @@ -1894,27 +1904,28 @@ class Project extends CommonObject $sql .= " AND pt.fk_projet = ".$this->id; $sql .= " AND (ptt.task_date >= '".$this->db->idate($datestart)."' "; $sql .= " AND ptt.task_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'm') - 1)."')"; - if ($task_id) $sql .= " AND ptt.fk_task=".$taskid; - if (is_numeric($userid)) $sql .= " AND ptt.fk_user=".$userid; + if ($task_id) { + $sql .= " AND ptt.fk_task=".$taskid; + } + if (is_numeric($userid)) { + $sql .= " AND ptt.fk_user=".$userid; + } //print $sql; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $weekalreadyfound = array(); $num = $this->db->num_rows($resql); $i = 0; // Loop on each record found, so each couple (project id, task id) - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); if (!empty($obj->task_date)) { $date = explode('-', $obj->task_date); $week_number = getWeekNumber($date[2], $date[1], $date[0]); } - if (empty($weekalreadyfound[$week_number])) - { + if (empty($weekalreadyfound[$week_number])) { $this->monthWorkLoad[$week_number] = $obj->task_duration; $this->monthWorkLoadPerTask[$week_number][$obj->fk_task] = $obj->task_duration; } else { @@ -1950,7 +1961,9 @@ class Project extends CommonObject //$socid=$user->socid; $projectsListId = null; - if (!$user->rights->projet->all->lire) $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1); + if (!$user->rights->projet->all->lire) { + $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1); + } $sql = "SELECT p.rowid, p.fk_statut as status, p.fk_opp_status, p.datee as datee"; $sql .= " FROM (".MAIN_DB_PREFIX."projet as p"; @@ -1960,7 +1973,9 @@ class Project extends CommonObject //if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid"; $sql .= " WHERE p.fk_statut = 1"; $sql .= " AND p.entity IN (".getEntity('project').')'; - if (!empty($projectsListId)) $sql .= " AND p.rowid IN (".$projectsListId.")"; + if (!empty($projectsListId)) { + $sql .= " AND p.rowid IN (".$projectsListId.")"; + } // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; // For external user, no check is done on company permission because readability is managed by public status of project and assignement. @@ -1968,21 +1983,22 @@ class Project extends CommonObject //print $sql; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $project_static = new Project($this->db); $response = new WorkboardResponse(); $response->warning_delay = $conf->projet->warning_delay / 60 / 60 / 24; $response->label = $langs->trans("OpenedProjects"); $response->labelShort = $langs->trans("Opened"); - if ($user->rights->projet->all->lire) $response->url = DOL_URL_ROOT.'/projet/list.php?search_status=1&mainmenu=project'; - else $response->url = DOL_URL_ROOT.'/projet/list.php?search_project_user=-1&search_status=1&mainmenu=project'; + if ($user->rights->projet->all->lire) { + $response->url = DOL_URL_ROOT.'/projet/list.php?search_status=1&mainmenu=project'; + } else { + $response->url = DOL_URL_ROOT.'/projet/list.php?search_project_user=-1&search_status=1&mainmenu=project'; + } $response->img = img_object('', "projectpub"); // This assignment in condition is not a bug. It allows walking the results. - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; $project_static->statut = $obj->status; @@ -2037,17 +2053,14 @@ class Project extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; $sql .= " WHERE"; $sql .= " p.entity IN (".getEntity('project').")"; - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1); $sql .= "AND p.rowid IN (".$projectsListId.")"; } $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["projects"] = $obj->nb; } $this->db->free($resql); @@ -2069,8 +2082,12 @@ class Project extends CommonObject { global $conf; - if (!($this->statut == self::STATUS_VALIDATED)) return false; - if (!$this->datee && !$this->date_end) return false; + if (!($this->statut == self::STATUS_VALIDATED)) { + return false; + } + if (!$this->datee && !$this->date_end) { + return false; + } $now = dol_now(); @@ -2090,23 +2107,19 @@ class Project extends CommonObject $sql .= ' date_close as datecloture,'; $sql .= ' fk_user_creat as fk_user_author, fk_user_close as fk_use_cloture'; $sql .= ' FROM '.MAIN_DB_PREFIX.'projet 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; diff --git a/htdocs/projet/class/projectstats.class.php b/htdocs/projet/class/projectstats.class.php index e1a19e293f0..3ec82edf366 100644 --- a/htdocs/projet/class/projectstats.class.php +++ b/htdocs/projet/class/projectstats.class.php @@ -85,21 +85,23 @@ class ProjectStats extends Stats $other = 0; while ($i < $num) { $row = $this->db->fetch_row($resql); - if ($i < $limit || $num == $limit) - { + if ($i < $limit || $num == $limit) { $label = (($langs->trans("OppStatus".$row[2]) != "OppStatus".$row[2]) ? $langs->trans("OppStatus".$row[2]) : $row[2]); $result[$i] = array( $label.' ('.price(price2num($row[0], 'MT'), 1, $langs, 1, -1, -1, $conf->currency).')', $row[0] ); - } else $other += $row[1]; + } else { + $other += $row[1]; + } $i++; } - if ($num > $limit) + if ($num > $limit) { $result[$i] = array( $langs->transnoentitiesnoconv("Other"), $other ); + } $this->db->free($resql); } else { $this->error = "Error ".$this->db->lasterror(); @@ -156,25 +158,34 @@ class ProjectStats extends Stats // Get list of project id allowed to user (in a string list separated by coma) $object = new Project($this->db); $projectsListId = ''; - if (!$user->rights->projet->all->lire) $projectsListId = $object->getProjectsAuthorizedForUser($user, 0, 1, $user->socid); + if (!$user->rights->projet->all->lire) { + $projectsListId = $object->getProjectsAuthorizedForUser($user, 0, 1, $user->socid); + } $sqlwhere[] = ' t.entity IN ('.getEntity('project').')'; - if (!empty($this->userid)) + if (!empty($this->userid)) { $sqlwhere[] = ' t.fk_user_resp='.$this->userid; + } // Forced filter on socid is similar to forced filter on project. TODO Use project assignement to allow to not use filter on project - if (!empty($this->socid)) + if (!empty($this->socid)) { $sqlwhere[] = ' t.fk_soc='.$this->socid; - if (!empty($this->year) && empty($this->yearmonth)) + } + if (!empty($this->year) && empty($this->yearmonth)) { $sqlwhere[] = " date_format(t.datec,'%Y')='".$this->db->escape($this->year)."'"; - if (!empty($this->yearmonth)) + } + if (!empty($this->yearmonth)) { $sqlwhere[] = " t.datec BETWEEN '".$this->db->idate(dol_get_first_day($this->yearmonth))."' AND '".$this->db->idate(dol_get_last_day($this->yearmonth))."'"; + } - if (!empty($this->status)) + if (!empty($this->status)) { $sqlwhere[] = " t.fk_opp_status IN (".$this->status.")"; + } - if (!$user->rights->projet->all->lire) $sqlwhere[] = " t.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users + if (!$user->rights->projet->all->lire) { + $sqlwhere[] = " t.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users + } if (count($sqlwhere) > 0) { $sqlwhere_str = ' WHERE '.implode(' AND ', $sqlwhere); @@ -254,13 +265,14 @@ class ProjectStats extends Stats { global $conf, $user, $langs; - if ($startyear > $endyear) return -1; + if ($startyear > $endyear) { + return -1; + } $datay = array(); // Search into cache - if (!empty($cachedelay)) - { + if (!empty($cachedelay)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; } @@ -271,11 +283,9 @@ class ProjectStats extends Stats $nowgmt = dol_now(); $foundintocache = 0; - if ($cachedelay > 0) - { + if ($cachedelay > 0) { $filedate = dol_filemtime($newpathofdestfile); - if ($filedate >= ($nowgmt - $cachedelay)) - { + if ($filedate >= ($nowgmt - $cachedelay)) { $foundintocache = 1; $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate; @@ -285,26 +295,22 @@ class ProjectStats extends Stats } // Load file into $data - if ($foundintocache) // Cache file found and is not too old - { + if ($foundintocache) { // Cache file found and is not too old dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate."."); $data = json_decode(file_get_contents($newpathofdestfile), true); } else { $year = $startyear; - while ($year <= $endyear) - { + while ($year <= $endyear) { $datay[$year] = $this->getWeightedAmountByMonth($year, $wonlostfilter); $year++; } $data = array(); // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...) - for ($i = 0; $i < 12; $i++) - { + for ($i = 0; $i < 12; $i++) { $data[$i][] = $datay[$endyear][$i][0]; // set label $year = $startyear; - while ($year <= $endyear) - { + while ($year <= $endyear) { $data[$i][] = $datay[$year][$i][1]; // set yval for x=i $year++; } @@ -312,18 +318,22 @@ class ProjectStats extends Stats } // Save cache file - if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) - { + if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) { dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk."); - if (!dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp); + if (!dol_is_dir($conf->user->dir_temp)) { + dol_mkdir($conf->user->dir_temp); + } $fp = fopen($newpathofdestfile, 'w'); - if ($fp) - { + if ($fp) { fwrite($fp, json_encode($data)); fclose($fp); - if (!empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK; + if (!empty($conf->global->MAIN_UMASK)) { + $newmask = $conf->global->MAIN_UMASK; + } @chmod($newpathofdestfile, octdec($newmask)); - } else dol_syslog("Failed to write cache file", LOG_ERR); + } else { + dol_syslog("Failed to write cache file", LOG_ERR); + } $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt; } @@ -371,13 +381,14 @@ class ProjectStats extends Stats { global $conf, $user, $langs; - if ($startyear > $endyear) return -1; + if ($startyear > $endyear) { + return -1; + } $datay = array(); // Search into cache - if (!empty($cachedelay)) - { + if (!empty($cachedelay)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; } @@ -400,8 +411,7 @@ class ProjectStats extends Stats } // Load file into $data - if ($foundintocache) // Cache file found and is not too old - { + if ($foundintocache) { // Cache file found and is not too old dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate."."); $data = json_decode(file_get_contents($newpathofdestfile), true); } else { @@ -426,13 +436,15 @@ class ProjectStats extends Stats // Save cache file if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == - 1)) { dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk."); - if (!dol_is_dir($conf->user->dir_temp)) + if (!dol_is_dir($conf->user->dir_temp)) { dol_mkdir($conf->user->dir_temp); + } $fp = fopen($newpathofdestfile, 'w'); fwrite($fp, json_encode($data)); fclose($fp); - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { $newmask = $conf->global->MAIN_UMASK; + } @chmod($newpathofdestfile, octdec($newmask)); $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt; @@ -483,7 +495,7 @@ class ProjectStats extends Stats $res = array(); - foreach ($res_total as $key=>$total_row) { + foreach ($res_total as $key => $total_row) { //var_dump($total_row); if (!empty($total_row[1])) { $res[$key] = array($total_row[0], (100 * $res_only_wined[$key][1]) / $total_row[1]); diff --git a/htdocs/projet/class/task.class.php b/htdocs/projet/class/task.class.php index b4733de05ae..9a72124199c 100644 --- a/htdocs/projet/class/task.class.php +++ b/htdocs/projet/class/task.class.php @@ -190,39 +190,36 @@ class Task extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task"); - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('TASK_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } // Update extrafield - if (!$error) - { - if (!$error) - { + if (!$error) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -267,28 +264,27 @@ class Task extends CommonObject $sql .= " t.note_private,"; $sql .= " t.note_public,"; $sql .= " t.rang"; - if (!empty($loadparentdata)) - { + if (!empty($loadparentdata)) { $sql .= ", t2.ref as task_parent_ref"; $sql .= ", t2.rang as task_parent_position"; } $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as t"; - if (!empty($loadparentdata)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t2 ON t.fk_task_parent = t2.rowid"; + if (!empty($loadparentdata)) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t2 ON t.fk_task_parent = t2.rowid"; + } $sql .= " WHERE "; if (!empty($ref)) { $sql .= "t.ref = '".$this->db->escape($ref)."'"; } else { - $sql .= "t.rowid = ".$id; + $sql .= "t.rowid = ".((int) $id); } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_rows = $this->db->num_rows($resql); - if ($num_rows) - { + if ($num_rows) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -311,8 +307,7 @@ class Task extends CommonObject $this->note_public = $obj->note_public; $this->rang = $obj->rang; - if (!empty($loadparentdata)) - { + if (!empty($loadparentdata)) { $this->task_parent_ref = $obj->task_parent_ref; $this->task_parent_position = $obj->task_parent_position; } @@ -323,8 +318,7 @@ class Task extends CommonObject $this->db->free($resql); - if ($num_rows) - { + if ($num_rows) { return 1; } else { return 0; @@ -349,13 +343,27 @@ class Task extends CommonObject $error = 0; // Clean parameters - if (isset($this->fk_project)) $this->fk_project = trim($this->fk_project); - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->fk_task_parent)) $this->fk_task_parent = (int) $this->fk_task_parent; - if (isset($this->label)) $this->label = trim($this->label); - if (isset($this->description)) $this->description = trim($this->description); - if (isset($this->duration_effective)) $this->duration_effective = trim($this->duration_effective); - if (isset($this->planned_workload)) $this->planned_workload = trim($this->planned_workload); + if (isset($this->fk_project)) { + $this->fk_project = trim($this->fk_project); + } + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->fk_task_parent)) { + $this->fk_task_parent = (int) $this->fk_task_parent; + } + if (isset($this->label)) { + $this->label = trim($this->label); + } + if (isset($this->description)) { + $this->description = trim($this->description); + } + if (isset($this->duration_effective)) { + $this->duration_effective = trim($this->duration_effective); + } + if (isset($this->planned_workload)) { + $this->planned_workload = trim($this->planned_workload); + } // Check parameters // Put here code to add control on parameters values @@ -373,53 +381,72 @@ class Task extends CommonObject $sql .= " datee=".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null').","; $sql .= " progress=".(($this->progress != '' && $this->progress >= 0) ? $this->progress : 'null').","; $sql .= " rang=".((!empty($this->rang)) ? $this->rang : "0"); - $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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Update extrafield if (!$error) { - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } + $result = $this->insertExtraFields(); + if ($result < 0) { + $error++; } } - if (!$error) - { - if (!$notrigger) - { + if (!$error && !empty($conf->global->PROJECT_CLASSIFY_CLOSED_WHEN_ALL_TASKS_DONE)) { + // Close the parent project if it is open (validated) and its tasks are 100% completed + $project = new Project($this->db); + if ($project->fetch($this->fk_project) > 0 && $project->statut == Project::STATUS_VALIDATED) { + $project->getLinesArray(null); // this method does not return <= 0 if fails + $projectCompleted = array_reduce( + $project->lines, + function ($allTasksCompleted, $task) { + return $allTasksCompleted && $task->progress >= 100; + }, + 1 + ); + if ($projectCompleted) { + if ($project->setClose($user) <= 0) { + $error++; + } + } + } else { + $error++; + } + if ($error) { + $this->errors[] = $project->error; + } + } + + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('TASK_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } - if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) - { + if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) { // We remove directory - if ($conf->projet->dir_output) - { + if ($conf->projet->dir_output) { $project = new Project($this->db); $project->fetch($this->fk_project); $olddir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->oldcopy->ref); $newdir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->ref); - if (file_exists($olddir)) - { + if (file_exists($olddir)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $res = dol_move($olddir, $newdir); - if (!$res) - { + if (!$res) { $langs->load("errors"); $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir); $error++; @@ -429,10 +456,8 @@ class Task extends CommonObject } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -462,8 +487,7 @@ class Task extends CommonObject $this->db->begin(); - if ($this->hasChildren() > 0) - { + if ($this->hasChildren() > 0) { dol_syslog(get_class($this)."::delete Can't delete record as it has some sub tasks", LOG_WARNING); $this->error = 'ErrorRecordHasSubTasks'; $this->db->rollback(); @@ -471,20 +495,17 @@ class Task extends CommonObject } $objectisused = $this->isObjectUsed($this->id); - if (!empty($objectisused)) - { + if (!empty($objectisused)) { dol_syslog(get_class($this)."::delete Can't delete record as it has some child", LOG_WARNING); $this->error = 'ErrorRecordHasChildren'; $this->db->rollback(); return 0; } - if (!$error) - { + if (!$error) { // Delete linked contacts $res = $this->delete_linked_contact(); - if ($res < 0) - { + if ($res < 0) { $this->error = 'ErrorFailToDeleteLinkedContact'; //$error++; $this->db->rollback(); @@ -492,49 +513,50 @@ class Task extends CommonObject } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time"; $sql .= " WHERE fk_task=".$this->id; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_extrafields"; $sql .= " WHERE fk_object=".$this->id; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task"; - $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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('TASK_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -542,19 +564,16 @@ class Task extends CommonObject return -1 * $error; } else { //Delete associated link file - if ($conf->projet->dir_output) - { + if ($conf->projet->dir_output) { $projectstatic = new Project($this->db); $projectstatic->fetch($this->fk_project); $dir = $conf->projet->dir_output."/".dol_sanitizeFileName($projectstatic->ref).'/'.dol_sanitizeFileName($this->id); dol_syslog(get_class($this)."::delete dir=".$dir, LOG_DEBUG); - if (file_exists($dir)) - { + if (file_exists($dir)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $res = @dol_delete_dir_recursive($dir); - if (!$res) - { + if (!$res) { $this->error = 'ErrorFailToDeleteDir'; $this->db->rollback(); return 0; @@ -584,14 +603,17 @@ class Task extends CommonObject dol_syslog(get_class($this)."::hasChildren", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } else { + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } else { $obj = $this->db->fetch_object($resql); - if ($obj) $ret = $obj->nb; + if ($obj) { + $ret = $obj->nb; + } $this->db->free($resql); } - if (!$error) - { + if (!$error) { return $ret; } else { return -1; @@ -614,14 +636,17 @@ class Task extends CommonObject dol_syslog(get_class($this)."::hasTimeSpent", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } else { + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } else { $obj = $this->db->fetch_object($resql); - if ($obj) $ret = $obj->nb; + if ($obj) { + $ret = $obj->nb; + } $this->db->free($resql); } - if (!$error) - { + if (!$error) { return $ret; } else { return -1; @@ -645,30 +670,35 @@ class Task extends CommonObject { global $conf, $langs, $user; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; $label = img_picto('', $this->picto).' <u>'.$langs->trans("Task").'</u>'; - if (!empty($this->ref)) + if (!empty($this->ref)) { $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref; - if (!empty($this->label)) + } + if (!empty($this->label)) { $label .= '<br><b>'.$langs->trans('LabelTask').':</b> '.$this->label; - if ($this->date_start || $this->date_end) - { + } + if ($this->date_start || $this->date_end) { $label .= "<br>".get_date_range($this->date_start, $this->date_end, '', $langs, 0); } $url = DOL_URL_ROOT.'/projet/tasks/'.$mode.'.php?id='.$this->id.($option == 'withproject' ? '&withproject=1' : ''); // 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'; + } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowTask"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -685,10 +715,16 @@ class Task extends CommonObject $picto = 'projecttask'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; - if ($withpicto != 2) $result .= (($addlabel && $this->label) ? $sep.dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + if ($withpicto != 2) { + $result .= (($addlabel && $this->label) ? $sep.dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + } return $result; } @@ -744,23 +780,26 @@ class Task extends CommonObject // List of tasks (does not care about permissions. Filtering will be done later) $sql = "SELECT "; - if ($filteronprojuser > 0 || $filterontaskuser > 0) $sql .= " DISTINCT"; // We may get several time the same record if user has several roles on same project/task + if ($filteronprojuser > 0 || $filterontaskuser > 0) { + $sql .= " DISTINCT"; // We may get several time the same record if user has several roles on same project/task + } $sql .= " p.rowid as projectid, p.ref, p.title as plabel, p.public, p.fk_statut as projectstatus, p.usage_bill_time,"; $sql .= " t.rowid as taskid, t.ref as taskref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut as status,"; $sql .= " t.dateo as date_start, t.datee as date_end, t.planned_workload, t.rang,"; $sql .= " t.description, "; $sql .= " s.rowid as thirdparty_id, s.nom as thirdparty_name, s.email as thirdparty_email,"; $sql .= " p.fk_opp_status, p.opp_amount, p.opp_percent, p.budget_amount"; - if (!empty($extrafields->attributes['projet']['label'])) - { - foreach ($extrafields->attributes['projet']['label'] as $key => $val) $sql .= ($extrafields->attributes['projet']['type'][$key] != 'separate' ? ",efp.".$key.' as options_'.$key : ''); + if (!empty($extrafields->attributes['projet']['label'])) { + foreach ($extrafields->attributes['projet']['label'] as $key => $val) { + $sql .= ($extrafields->attributes['projet']['type'][$key] != 'separate' ? ",efp.".$key.' as options_'.$key : ''); + } } - if (!empty($extrafields->attributes['projet_task']['label'])) - { - foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) $sql .= ($extrafields->attributes['projet_task']['type'][$key] != 'separate' ? ",efpt.".$key.' as options_'.$key : ''); + if (!empty($extrafields->attributes['projet_task']['label'])) { + foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) { + $sql .= ($extrafields->attributes['projet_task']['type'][$key] != 'separate' ? ",efpt.".$key.' as options_'.$key : ''); + } } - if ($includebilltime) - { + if ($includebilltime) { $sql .= ", SUM(tt.task_duration * ".$this->db->ifsql("invoice_id IS NULL", "1", "0").") as tobill, SUM(tt.task_duration * ".$this->db->ifsql("invoice_id IS NULL", "0", "1").") as billed"; } @@ -768,55 +807,47 @@ class Task extends CommonObject $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_extrafields as efp ON (p.rowid = efp.fk_object)"; - if ($mode == 0) - { - if ($filteronprojuser > 0) - { + if ($mode == 0) { + if ($filteronprojuser > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc"; } $sql .= ", ".MAIN_DB_PREFIX."projet_task as t"; - if ($includebilltime) - { + if ($includebilltime) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_time as tt ON tt.fk_task = t.rowid"; } - if ($filterontaskuser > 0) - { + if ($filterontaskuser > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec2"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2"; } $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_extrafields as efpt ON (t.rowid = efpt.fk_object)"; $sql .= " WHERE p.entity IN (".getEntity('project').")"; $sql .= " AND t.fk_projet = p.rowid"; - } elseif ($mode == 1) - { - if ($filteronprojuser > 0) - { + } elseif ($mode == 1) { + if ($filteronprojuser > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc"; } - if ($filterontaskuser > 0) - { + if ($filterontaskuser > 0) { $sql .= ", ".MAIN_DB_PREFIX."projet_task as t"; - if ($includebilltime) - { + if ($includebilltime) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_time as tt ON tt.fk_task = t.rowid"; } $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec2"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2"; } else { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid"; - if ($includebilltime) - { + if ($includebilltime) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_time as tt ON tt.fk_task = t.rowid"; } } $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_extrafields as efpt ON (t.rowid = efpt.fk_object)"; $sql .= " WHERE p.entity IN (".getEntity('project').")"; - } else return 'BadValueForParameterMode'; + } else { + return 'BadValueForParameterMode'; + } - if ($filteronprojuser > 0) - { + if ($filteronprojuser > 0) { $sql .= " AND p.rowid = ec.element_id"; $sql .= " AND ctc.rowid = ec.fk_c_type_contact"; $sql .= " AND ctc.element = 'project'"; @@ -824,8 +855,7 @@ class Task extends CommonObject $sql .= " AND ec.statut = 4"; $sql .= " AND ctc.source = 'internal'"; } - if ($filterontaskuser > 0) - { + if ($filterontaskuser > 0) { $sql .= " AND t.fk_projet = p.rowid"; $sql .= " AND p.rowid = ec2.element_id"; $sql .= " AND ctc2.rowid = ec2.fk_c_type_contact"; @@ -834,11 +864,21 @@ class Task extends CommonObject $sql .= " AND ec2.statut = 4"; $sql .= " AND ctc2.source = 'internal'"; } - if ($socid) $sql .= " AND p.fk_soc = ".$socid; - if ($projectid) $sql .= " AND p.rowid in (".$projectid.")"; - if ($filteronproj) $sql .= natural_search(array("p.ref", "p.title"), $filteronproj); - if ($filteronprojstatus && $filteronprojstatus != '-1') $sql .= " AND p.fk_statut IN (".$filteronprojstatus.")"; - if ($morewherefilter) $sql .= $morewherefilter; + if ($socid) { + $sql .= " AND p.fk_soc = ".$socid; + } + if ($projectid) { + $sql .= " AND p.rowid in (".$projectid.")"; + } + if ($filteronproj) { + $sql .= natural_search(array("p.ref", "p.title"), $filteronproj); + } + if ($filteronprojstatus && $filteronprojstatus != '-1') { + $sql .= " AND p.fk_statut IN (".$filteronprojstatus.")"; + } + if ($morewherefilter) { + $sql .= $morewherefilter; + } // Add where from extra fields $extrafieldsobjectkey = 'projet_task'; $extrafieldsobjectprefix = 'efpt.'; @@ -847,8 +887,7 @@ class Task extends CommonObject $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; - if ($includebilltime) - { + if ($includebilltime) { $sql .= " GROUP BY p.rowid, p.ref, p.title, p.public, p.fk_statut, p.usage_bill_time,"; $sql .= " t.datec, t.dateo, t.datee, t.tms,"; $sql .= " t.rowid, t.ref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut,"; @@ -856,13 +895,15 @@ class Task extends CommonObject $sql .= " t.description, "; $sql .= " s.rowid, s.nom, s.email,"; $sql .= " p.fk_opp_status, p.opp_amount, p.opp_percent, p.budget_amount"; - if (!empty($extrafields->attributes['projet']['label'])) - { - foreach ($extrafields->attributes['projet']['label'] as $key => $val) $sql .= ($extrafields->attributes['projet']['type'][$key] != 'separate' ? ",efp.".$key : ''); + if (!empty($extrafields->attributes['projet']['label'])) { + foreach ($extrafields->attributes['projet']['label'] as $key => $val) { + $sql .= ($extrafields->attributes['projet']['type'][$key] != 'separate' ? ",efp.".$key : ''); + } } - if (!empty($extrafields->attributes['projet_task']['label'])) - { - foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) $sql .= ($extrafields->attributes['projet_task']['type'][$key] != 'separate' ? ",efpt.".$key : ''); + if (!empty($extrafields->attributes['projet_task']['label'])) { + foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) { + $sql .= ($extrafields->attributes['projet_task']['type'][$key] != 'separate' ? ",efpt.".$key : ''); + } } } @@ -872,34 +913,27 @@ class Task extends CommonObject //print $sql;exit; dol_syslog(get_class($this)."::getTasksArray", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; // Loop on each record found, so each couple (project id, task id) - while ($i < $num) - { + while ($i < $num) { $error = 0; $obj = $this->db->fetch_object($resql); - if ((!$obj->public) && (is_object($userp))) // If not public project and we ask a filter on project owned by a user - { - if (!$this->getUserRolesForProjectsOrTasks($userp, 0, $obj->projectid, 0)) - { + if ((!$obj->public) && (is_object($userp))) { // If not public project and we ask a filter on project owned by a user + if (!$this->getUserRolesForProjectsOrTasks($userp, 0, $obj->projectid, 0)) { $error++; } } - if (is_object($usert)) // If we ask a filter on a user affected to a task - { - if (!$this->getUserRolesForProjectsOrTasks(0, $usert, $obj->projectid, $obj->taskid)) - { + if (is_object($usert)) { // If we ask a filter on a user affected to a task + if (!$this->getUserRolesForProjectsOrTasks(0, $usert, $obj->projectid, $obj->taskid)) { $error++; } } - if (!$error) - { + if (!$error) { $tasks[$i] = new Task($this->db); $tasks[$i]->id = $obj->taskid; $tasks[$i]->ref = $obj->taskref; @@ -938,21 +972,19 @@ class Task extends CommonObject $tasks[$i]->thirdparty_name = $obj->thirdparty_name; $tasks[$i]->thirdparty_email = $obj->thirdparty_email; - if (!empty($extrafields->attributes['projet']['label'])) - { - foreach ($extrafields->attributes['projet']['label'] as $key => $val) - { - if ($extrafields->attributes['projet']['type'][$key] != 'separate') + if (!empty($extrafields->attributes['projet']['label'])) { + foreach ($extrafields->attributes['projet']['label'] as $key => $val) { + if ($extrafields->attributes['projet']['type'][$key] != 'separate') { $tasks[$i]->{'options_'.$key} = $obj->{'options_'.$key}; + } } } - if (!empty($extrafields->attributes['projet_task']['label'])) - { - foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) - { - if ($extrafields->attributes['projet_task']['type'][$key] != 'separate') + if (!empty($extrafields->attributes['projet_task']['label'])) { + foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) { + if ($extrafields->attributes['projet_task']['type'][$key] != 'separate') { $tasks[$i]->{'options_'.$key} = $obj->{'options_'.$key}; + } } } } @@ -984,57 +1016,80 @@ class Task extends CommonObject dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks userp=".is_object($userp)." usert=".is_object($usert)." projectid=".$projectid." taskid=".$taskid); // We want role of user for a projet or role of user for a task. Both are not possible. - if (empty($userp) && empty($usert)) - { + if (empty($userp) && empty($usert)) { $this->error = "CallWithWrongParameters"; return -1; } - if (!empty($userp) && !empty($usert)) - { + if (!empty($userp) && !empty($usert)) { $this->error = "CallWithWrongParameters"; return -1; } /* Liste des taches et role sur les projets ou taches */ $sql = "SELECT pt.rowid as pid, ec.element_id, ctc.code, ctc.source"; - if ($userp) $sql .= " FROM ".MAIN_DB_PREFIX."projet as pt"; - if ($usert && $filteronprojstatus > -1) $sql .= " FROM ".MAIN_DB_PREFIX."projet as p, ".MAIN_DB_PREFIX."projet_task as pt"; - if ($usert && $filteronprojstatus <= -1) $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as pt"; + if ($userp) { + $sql .= " FROM ".MAIN_DB_PREFIX."projet as pt"; + } + if ($usert && $filteronprojstatus > -1) { + $sql .= " FROM ".MAIN_DB_PREFIX."projet as p, ".MAIN_DB_PREFIX."projet_task as pt"; + } + if ($usert && $filteronprojstatus <= -1) { + $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as pt"; + } $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc"; $sql .= " WHERE pt.rowid = ec.element_id"; - if ($userp && $filteronprojstatus > -1) $sql .= " AND pt.fk_statut = ".$filteronprojstatus; - if ($usert && $filteronprojstatus > -1) $sql .= " AND pt.fk_projet = p.rowid AND p.fk_statut = ".$filteronprojstatus; - if ($userp) $sql .= " AND ctc.element = 'project'"; - if ($usert) $sql .= " AND ctc.element = 'project_task'"; + if ($userp && $filteronprojstatus > -1) { + $sql .= " AND pt.fk_statut = ".$filteronprojstatus; + } + if ($usert && $filteronprojstatus > -1) { + $sql .= " AND pt.fk_projet = p.rowid AND p.fk_statut = ".$filteronprojstatus; + } + if ($userp) { + $sql .= " AND ctc.element = 'project'"; + } + if ($usert) { + $sql .= " AND ctc.element = 'project_task'"; + } $sql .= " AND ctc.rowid = ec.fk_c_type_contact"; - if ($userp) $sql .= " AND ec.fk_socpeople = ".$userp->id; - if ($usert) $sql .= " AND ec.fk_socpeople = ".$usert->id; + if ($userp) { + $sql .= " AND ec.fk_socpeople = ".$userp->id; + } + if ($usert) { + $sql .= " AND ec.fk_socpeople = ".$usert->id; + } $sql .= " AND ec.statut = 4"; $sql .= " AND ctc.source = 'internal'"; - if ($projectid) - { - if ($userp) $sql .= " AND pt.rowid in (".$projectid.")"; - if ($usert) $sql .= " AND pt.fk_projet in (".$projectid.")"; + if ($projectid) { + if ($userp) { + $sql .= " AND pt.rowid in (".$projectid.")"; + } + if ($usert) { + $sql .= " AND pt.fk_projet in (".$projectid.")"; + } } - if ($taskid) - { - if ($userp) $sql .= " ERROR SHOULD NOT HAPPENS"; - if ($usert) $sql .= " AND pt.rowid = ".$taskid; + if ($taskid) { + if ($userp) { + $sql .= " ERROR SHOULD NOT HAPPENS"; + } + if ($usert) { + $sql .= " AND pt.rowid = ".$taskid; + } } //print $sql; dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks execute request", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); - if (empty($arrayroles[$obj->pid])) $arrayroles[$obj->pid] = $obj->code; - else $arrayroles[$obj->pid] .= ','.$obj->code; + if (empty($arrayroles[$obj->pid])) { + $arrayroles[$obj->pid] = $obj->code; + } else { + $arrayroles[$obj->pid] .= ','.$obj->code; + } $i++; } $this->db->free($resql); @@ -1059,10 +1114,12 @@ class Task extends CommonObject //var_dump($tab); $num = count($tab); $i = 0; - while ($i < $num) - { - if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid']; - else $contactAlreadySelected[$i] = $tab[$i]['id']; + while ($i < $num) { + if ($source == 'thirdparty') { + $contactAlreadySelected[$i] = $tab[$i]['socid']; + } else { + $contactAlreadySelected[$i] = $tab[$i]['id']; + } $i++; } return $contactAlreadySelected; @@ -1085,15 +1142,18 @@ class Task extends CommonObject $ret = 0; // Check parameters - if (!is_object($user)) - { + if (!is_object($user)) { dol_print_error('', "Method addTimeSpent was called with wrong parameter user"); return -1; } // Clean parameters - if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note); - if (empty($this->timespent_datehour)) $this->timespent_datehour = $this->timespent_date; + if (isset($this->timespent_note)) { + $this->timespent_note = trim($this->timespent_note); + } + if (empty($this->timespent_datehour)) { + $this->timespent_datehour = $this->timespent_date; + } $this->db->begin(); @@ -1116,17 +1176,17 @@ class Task extends CommonObject $sql .= ")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $tasktime_id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task_time"); $ret = $tasktime_id; $this->timespent_id = $ret; - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('TASK_TIMESPENT_CREATE', $user); - if ($result < 0) { $ret = -1; } + if ($result < 0) { + $ret = -1; + } // End call triggers } } else { @@ -1134,17 +1194,17 @@ class Task extends CommonObject $ret = -1; } - if ($ret > 0) - { + if ($ret > 0) { // Recalculate amount of time spent for task and update denormalized field $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task"; $sql .= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->id.")"; - if (isset($this->progress)) $sql .= ", progress = ".$this->progress; // Do not overwrite value if not provided + if (isset($this->progress)) { + $sql .= ", progress = ".$this->progress; // Do not overwrite value if not provided + } $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG); - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $this->error = $this->db->lasterror(); $ret = -2; } @@ -1154,15 +1214,13 @@ class Task extends CommonObject $sql .= " WHERE rowid = ".$tasktime_id; dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG); - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $this->error = $this->db->lasterror(); $ret = -2; } } - if ($ret > 0) - { + if ($ret > 0) { $this->db->commit(); } else { $this->db->rollback(); @@ -1181,12 +1239,14 @@ class Task extends CommonObject { global $langs; - if (is_object($userobj)) $userid = $userobj->id; - else $userid = $userobj; // old method + if (is_object($userobj)) { + $userid = $userobj->id; + } else { + $userid = $userobj; // old method + } $id = $this->id; - if (empty($id) && empty($userid)) - { + if (empty($id) && empty($userid)) { dol_syslog("getSummaryOfTimeSpent called on a not loaded task without user param defined", LOG_ERR); return -1; } @@ -1202,14 +1262,19 @@ class Task extends CommonObject $sql .= " SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t"; $sql .= " WHERE 1 = 1"; - if ($morewherefilter) $sql .= $morewherefilter; - if ($id > 0) $sql .= " AND t.fk_task = ".$id; - if ($userid > 0) $sql .= " AND t.fk_user = ".$userid; + if ($morewherefilter) { + $sql .= $morewherefilter; + } + if ($id > 0) { + $sql .= " AND t.fk_task = ".$id; + } + if ($userid > 0) { + $sql .= " AND t.fk_user = ".$userid; + } dol_syslog(get_class($this)."::getSummaryOfTimeSpent", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $result['min_date'] = $obj->min_date; // deprecated. use the ->timespent_xxx instead @@ -1242,7 +1307,9 @@ class Task extends CommonObject { global $langs; - if (empty($id)) $id = $this->id; + if (empty($id)) { + $id = $this->id; + } $result = array(); @@ -1251,17 +1318,14 @@ class Task extends CommonObject $sql .= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as amount, SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t"; $sql .= " WHERE t.fk_task = ".$id; - if (is_object($fuser) && $fuser->id > 0) - { + if (is_object($fuser) && $fuser->id > 0) { $sql .= " AND fk_user = ".$fuser->id; } - if ($dates > 0) - { + if ($dates > 0) { $datefieldname = "task_datehour"; $sql .= " AND (".$datefieldname." >= '".$this->db->idate($dates)."' OR ".$datefieldname." IS NULL)"; } - if ($datee > 0) - { + if ($datee > 0) { $datefieldname = "task_datehour"; $sql .= " AND (".$datefieldname." <= '".$this->db->idate($datee)."' OR ".$datefieldname." IS NULL)"; } @@ -1269,8 +1333,7 @@ class Task extends CommonObject dol_syslog(get_class($this)."::getSumOfAmount", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $result['amount'] = $obj->amount; @@ -1306,14 +1369,12 @@ class Task extends CommonObject $sql .= " t.thm,"; $sql .= " t.note"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t"; - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".((int) $id); dol_syslog(get_class($this)."::fetchTimeSpent", LOG_DEBUG); $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->timespent_id = $obj->rowid; @@ -1373,17 +1434,17 @@ class Task extends CommonObject $sql .= " WHERE ptt.fk_task = pt.rowid AND pt.fk_projet = p.rowid"; $sql .= " AND ptt.fk_user = ".$userobj->id; $sql .= " AND pt.entity IN (".getEntity('project').")"; - if ($morewherefilter) $sql .= $morewherefilter; + if ($morewherefilter) { + $sql .= $morewherefilter; + } dol_syslog(get_class($this)."::fetchAllTimeSpent", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $newobj = new stdClass(); @@ -1438,20 +1499,22 @@ class Task extends CommonObject $ret = 0; // Check parameters - if ($this->timespent_date == '') - { + if ($this->timespent_date == '') { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")); return -1; } - if (!($this->timespent_fk_user > 0)) - { + if (!($this->timespent_fk_user > 0)) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("User")); return -1; } // Clean parameters - if (empty($this->timespent_datehour)) $this->timespent_datehour = $this->timespent_date; - if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note); + if (empty($this->timespent_datehour)) { + $this->timespent_datehour = $this->timespent_date; + } + if (isset($this->timespent_note)) { + $this->timespent_note = trim($this->timespent_note); + } $this->db->begin(); @@ -1465,27 +1528,27 @@ class Task extends CommonObject $sql .= " WHERE rowid = ".$this->timespent_id; dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG); - if ($this->db->query($sql)) - { - if (!$notrigger) - { + if ($this->db->query($sql)) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('TASK_TIMESPENT_MODIFY', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); $ret = -1; - } else $ret = 1; + } else { + $ret = 1; + } // End call triggers - } else $ret = 1; + } else { + $ret = 1; + } } else { $this->error = $this->db->lasterror(); $this->db->rollback(); $ret = -1; } - if ($ret == 1 && ($this->timespent_old_duration != $this->timespent_duration)) - { + if ($ret == 1 && ($this->timespent_old_duration != $this->timespent_duration)) { $newDuration = $this->timespent_duration - $this->timespent_old_duration; $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task"; @@ -1493,15 +1556,16 @@ class Task extends CommonObject $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG); - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $this->error = $this->db->lasterror(); $this->db->rollback(); $ret = -2; } } - if ($ret >= 0) $this->db->commit(); + if ($ret >= 0) { + $this->db->commit(); + } return $ret; } @@ -1525,28 +1589,28 @@ class Task extends CommonObject dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('TASK_TIMESPENT_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } - if (!$error) - { + if (!$error) { $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task"; $sql .= " SET duration_effective = duration_effective - ".$this->db->escape($this->timespent_duration ? $this->timespent_duration : 0); $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $result = 0; } else { $this->error = $this->db->lasterror(); @@ -1555,10 +1619,8 @@ class Task extends CommonObject } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delTimeSpent ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -1611,8 +1673,7 @@ class Task extends CommonObject $defaultref = ''; $obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON; - if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php")) - { + if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php")) { require_once DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php'; $modTask = new $obj; $defaultref = $modTask->getNextValue(0, $clone_task); @@ -1629,8 +1690,7 @@ class Task extends CommonObject $clone_task->rang = $origin_task->rang; //Manage Task Date - if ($clone_change_dt) - { + if ($clone_change_dt) { $projectstatic = new Project($this->db); $projectstatic->fetch($ori_project_id); @@ -1638,20 +1698,17 @@ class Task extends CommonObject $orign_project_dt_start = $projectstatic->date_start; //Calcultate new task start date with difference between origin proj start date and origin task start date - if (!empty($clone_task->date_start)) - { + if (!empty($clone_task->date_start)) { $clone_task->date_start = $now + $clone_task->date_start - $orign_project_dt_start; } //Calcultate new task end date with difference between origin proj end date and origin task end date - if (!empty($clone_task->date_end)) - { + if (!empty($clone_task->date_end)) { $clone_task->date_end = $now + $clone_task->date_end - $orign_project_dt_start; } } - if (!$clone_prog) - { + if (!$clone_prog) { $clone_task->progress = 0; } @@ -1659,28 +1716,24 @@ class Task extends CommonObject $result = $clone_task->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $clone_task->error; $error++; } // End - if (!$error) - { + if (!$error) { $clone_task_id = $clone_task->id; $clone_task_ref = $clone_task->ref; - //Note Update - if (!$clone_note) - { + //Note Update + if (!$clone_note) { $clone_task->note_private = ''; $clone_task->note_public = ''; } else { $this->db->begin(); $res = $clone_task->update_note(dol_html_entity_decode($clone_task->note_public, ENT_QUOTES | ENT_HTML5), '_public'); - if ($res < 0) - { + if ($res < 0) { $this->error .= $clone_task->error; $error++; $this->db->rollback(); @@ -1690,8 +1743,7 @@ class Task extends CommonObject $this->db->begin(); $res = $clone_task->update_note(dol_html_entity_decode($clone_task->note_private, ENT_QUOTES | ENT_HTML5), '_private'); - if ($res < 0) - { + if ($res < 0) { $this->error .= $clone_task->error; $error++; $this->db->rollback(); @@ -1701,8 +1753,7 @@ class Task extends CommonObject } //Duplicate file - if ($clone_file) - { + if ($clone_file) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; //retrieve project origin ref to know folder to copy @@ -1710,8 +1761,7 @@ class Task extends CommonObject $projectstatic->fetch($ori_project_id); $ori_project_ref = $projectstatic->ref; - if ($ori_project_id != $project_id) - { + if ($ori_project_id != $project_id) { $projectstatic->fetch($project_id); $clone_project_ref = $projectstatic->ref; } else { @@ -1722,20 +1772,16 @@ class Task extends CommonObject $ori_task_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($ori_project_ref)."/".dol_sanitizeFileName($fromid); $filearray = dol_dir_list($ori_task_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1); - foreach ($filearray as $key => $file) - { - if (!file_exists($clone_task_dir)) - { - if (dol_mkdir($clone_task_dir) < 0) - { + foreach ($filearray as $key => $file) { + if (!file_exists($clone_task_dir)) { + if (dol_mkdir($clone_task_dir) < 0) { $this->error .= $langs->trans('ErrorInternalErrorDetected').':dol_mkdir'; $error++; } } $rescopy = dol_copy($ori_task_dir.'/'.$file['name'], $clone_task_dir.'/'.$file['name'], 0, 1); - if (is_numeric($rescopy) && $rescopy < 0) - { + if (is_numeric($rescopy) && $rescopy < 0) { $this->error .= $langs->trans("ErrorFailToCopyFile", $ori_task_dir.'/'.$file['name'], $clone_task_dir.'/'.$file['name']); $error++; } @@ -1743,27 +1789,22 @@ class Task extends CommonObject } // clone affectation - if ($clone_affectation) - { + if ($clone_affectation) { $origin_task = new Task($this->db); $origin_task->fetch($fromid); - foreach (array('internal', 'external') as $source) - { + foreach (array('internal', 'external') as $source) { $tab = $origin_task->liste_contact(-1, $source); $num = count($tab); $i = 0; - while ($i < $num) - { + while ($i < $num) { $clone_task->add_contact($tab[$i]['id'], $tab[$i]['code'], $tab[$i]['source']); - if ($clone_task->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($clone_task->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); $this->error .= $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); $error++; } else { - if ($clone_task->error != '') - { + if ($clone_task->error != '') { $this->error .= $clone_task->error; $error++; } @@ -1773,16 +1814,14 @@ class Task extends CommonObject } } - if ($clone_time) - { + if ($clone_time) { //TODO clone time of affectation } } unset($clone_task->context['createfromclone']); - if (!$error) - { + if (!$error) { $this->db->commit(); return $clone_task_id; } else { @@ -1829,38 +1868,53 @@ class Task extends CommonObject $this->statuts_short[3] = 'Completed'; $this->statuts_short[4] = 'Transfered'; - if ($mode == 0) - { + if ($mode == 0) { return $langs->trans($this->statuts[$status]); - } elseif ($mode == 1) - { + } elseif ($mode == 1) { return $langs->trans($this->statuts_short[$status]); - } elseif ($mode == 2) - { - if ($status == 0) return img_picto($langs->trans($this->statuts_short[$status]), 'statut0').' '.$langs->trans($this->statuts_short[$status]); - elseif ($status == 1) return img_picto($langs->trans($this->statuts_short[$status]), 'statut1').' '.$langs->trans($this->statuts_short[$status]); - elseif ($status == 2) return img_picto($langs->trans($this->statuts_short[$status]), 'statut3').' '.$langs->trans($this->statuts_short[$status]); - elseif ($status == 3) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts_short[$status]); - elseif ($status == 4) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts_short[$status]); - elseif ($status == 5) return img_picto($langs->trans($this->statuts_short[$status]), 'statut5').' '.$langs->trans($this->statuts_short[$status]); - } elseif ($mode == 3) - { - if ($status == 0) return img_picto($langs->trans($this->statuts_short[$status]), 'statut0'); - elseif ($status == 1) return img_picto($langs->trans($this->statuts_short[$status]), 'statut1'); - elseif ($status == 2) return img_picto($langs->trans($this->statuts_short[$status]), 'statut3'); - elseif ($status == 3) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6'); - elseif ($status == 4) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6'); - elseif ($status == 5) return img_picto($langs->trans($this->statuts_short[$status]), 'statut5'); - } elseif ($mode == 4) - { - if ($status == 0) return img_picto($langs->trans($this->statuts_short[$status]), 'statut0').' '.$langs->trans($this->statuts[$status]); - elseif ($status == 1) return img_picto($langs->trans($this->statuts_short[$status]), 'statut1').' '.$langs->trans($this->statuts[$status]); - elseif ($status == 2) return img_picto($langs->trans($this->statuts_short[$status]), 'statut3').' '.$langs->trans($this->statuts[$status]); - elseif ($status == 3) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts[$status]); - elseif ($status == 4) return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts[$status]); - elseif ($status == 5) return img_picto($langs->trans($this->statuts_short[$status]), 'statut5').' '.$langs->trans($this->statuts[$status]); - } elseif ($mode == 5) - { + } elseif ($mode == 2) { + if ($status == 0) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut0').' '.$langs->trans($this->statuts_short[$status]); + } elseif ($status == 1) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut1').' '.$langs->trans($this->statuts_short[$status]); + } elseif ($status == 2) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut3').' '.$langs->trans($this->statuts_short[$status]); + } elseif ($status == 3) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts_short[$status]); + } elseif ($status == 4) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts_short[$status]); + } elseif ($status == 5) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut5').' '.$langs->trans($this->statuts_short[$status]); + } + } elseif ($mode == 3) { + if ($status == 0) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut0'); + } elseif ($status == 1) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut1'); + } elseif ($status == 2) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut3'); + } elseif ($status == 3) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut6'); + } elseif ($status == 4) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut6'); + } elseif ($status == 5) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut5'); + } + } elseif ($mode == 4) { + if ($status == 0) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut0').' '.$langs->trans($this->statuts[$status]); + } elseif ($status == 1) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut1').' '.$langs->trans($this->statuts[$status]); + } elseif ($status == 2) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut3').' '.$langs->trans($this->statuts[$status]); + } elseif ($status == 3) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts[$status]); + } elseif ($status == 4) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut6').' '.$langs->trans($this->statuts[$status]); + } elseif ($status == 5) { + return img_picto($langs->trans($this->statuts_short[$status]), 'statut5').' '.$langs->trans($this->statuts[$status]); + } + } elseif ($mode == 5) { /*if ($status==0) return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut0'); elseif ($status==1) return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut1'); elseif ($status==2) return $langs->trans($this->statuts_short[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut3'); @@ -1870,8 +1924,7 @@ class Task extends CommonObject */ //else return $this->progress.' %'; return '&nbsp;'; - } elseif ($mode == 6) - { + } elseif ($mode == 6) { /*if ($status==0) return $langs->trans($this->statuts[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut0'); elseif ($status==1) return $langs->trans($this->statuts[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut1'); elseif ($status==2) return $langs->trans($this->statuts[$status]).' '.img_picto($langs->trans($this->statuts_short[$status]),'statut3'); @@ -1948,29 +2001,34 @@ class Task extends CommonObject $sql .= " AND p.fk_statut = 1"; $sql .= " AND t.fk_projet = p.rowid"; $sql .= " AND (t.progress IS NULL OR t.progress < 100)"; // tasks to do - if (!$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".$projectsListId.")"; + if (!$user->rights->projet->all->lire) { + $sql .= " AND p.rowid IN (".$projectsListId.")"; + } // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; - if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + if ($socid) { + $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + } // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser // if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))"; //print $sql; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $task_static = new Task($this->db); $response = new WorkboardResponse(); $response->warning_delay = $conf->projet->task->warning_delay / 60 / 60 / 24; $response->label = $langs->trans("OpenedTasks"); - if ($user->rights->projet->all->lire) $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mainmenu=project'; - else $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mode=mine&amp;mainmenu=project'; + if ($user->rights->projet->all->lire) { + $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mainmenu=project'; + } else { + $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mode=mine&amp;mainmenu=project'; + } $response->img = img_object('', "task"); // This assignment in condition is not a bug. It allows walking the results. - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; $task_static->projectstatus = $obj->projectstatus; @@ -2011,22 +2069,28 @@ class Task extends CommonObject $sql = "SELECT count(p.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid"; + } $sql .= ", ".MAIN_DB_PREFIX."projet_task as t"; $sql .= " WHERE p.entity IN (".getEntity('project', 0).')'; $sql .= " AND t.fk_projet = p.rowid"; // tasks to do - if ($mine || !$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".$projectsListId.")"; + if ($mine || !$user->rights->projet->all->lire) { + $sql .= " AND p.rowid IN (".$projectsListId.")"; + } // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; - if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id.") OR (s.rowid IS NULL))"; + if ($socid) { + $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id.") OR (s.rowid IS NULL))"; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // This assignment in condition is not a bug. It allows walking the results. - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["tasks"] = $obj->nb; } $this->db->free($resql); diff --git a/htdocs/projet/class/taskstats.class.php b/htdocs/projet/class/taskstats.class.php index 296a36c2dcf..d18950ec482 100644 --- a/htdocs/projet/class/taskstats.class.php +++ b/htdocs/projet/class/taskstats.class.php @@ -59,8 +59,9 @@ class TaskStats extends Stats $sql = "SELECT"; $sql .= " COUNT(t.rowid), t.priority"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as t INNER JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = t.fk_projet"; - if (!$user->rights->societe->client->voir && !$user->soc_id) + if (!$user->rights->societe->client->voir && !$user->soc_id) { $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=".$user->id; + } $sql .= $this->buildWhere(); //$sql .= " AND t.fk_statut <> 0"; // We want historic also, so all task not draft $sql .= " GROUP BY t.priority"; @@ -76,20 +77,22 @@ class TaskStats extends Stats $other = 0; while ($i < $num) { $row = $this->db->fetch_row($resql); - if ($i < $limit || $num == $limit) - { + if ($i < $limit || $num == $limit) { $result[$i] = array( $row[1], $row[0] ); - } else $other += $row[1]; + } else { + $other += $row[1]; + } $i++; } - if ($num > $limit) + if ($num > $limit) { $result[$i] = array( $langs->transnoentitiesnoconv("Other"), $other ); + } $this->db->free($resql); } else { $this->error = "Error ".$this->db->lasterror(); @@ -115,8 +118,9 @@ class TaskStats extends Stats $sql = "SELECT date_format(t.datec,'%Y') as year, COUNT(t.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as t INNER JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = t.fk_projet"; - if (!$user->rights->societe->client->voir && !$user->soc_id) + if (!$user->rights->societe->client->voir && !$user->soc_id) { $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=".$user->id; + } $sql .= $this->buildWhere(); $sql .= " GROUP BY year"; $sql .= $this->db->order('year', 'DESC'); @@ -137,18 +141,23 @@ class TaskStats extends Stats $sqlwhere[] = ' t.entity IN ('.getEntity('project').')'; - if (!empty($this->userid)) + if (!empty($this->userid)) { $sqlwhere[] = ' t.fk_user_resp='.$this->userid; + } // Forced filter on socid is similar to forced filter on project. TODO Use project assignement to allow to not use filter on project - if (!empty($this->socid)) + if (!empty($this->socid)) { $sqlwhere[] = ' p.fk_soc='.$this->socid; // Link on thirdparty is on project, not on task - if (!empty($this->year) && empty($this->yearmonth)) + } + if (!empty($this->year) && empty($this->yearmonth)) { $sqlwhere[] = " date_format(t.datec,'%Y')='".$this->db->escape($this->year)."'"; - if (!empty($this->yearmonth)) + } + if (!empty($this->yearmonth)) { $sqlwhere[] = " t.datec BETWEEN '".$this->db->idate(dol_get_first_day($this->yearmonth))."' AND '".$this->db->idate(dol_get_last_day($this->yearmonth))."'"; + } - if (!empty($this->status)) + if (!empty($this->status)) { $sqlwhere[] = " t.priority IN (".$this->priority.")"; + } if (count($sqlwhere) > 0) { $sqlwhere_str = ' WHERE '.implode(' AND ', $sqlwhere); @@ -172,8 +181,9 @@ class TaskStats extends Stats $sql = "SELECT date_format(t.datec,'%m') as dm, COUNT(t.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as t INNER JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = t.fk_projet"; - if (!$user->rights->societe->client->voir && !$user->soc_id) + if (!$user->rights->societe->client->voir && !$user->soc_id) { $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=".$user->id; + } $sql .= $this->buildWhere(); $sql .= " GROUP BY dm"; $sql .= $this->db->order('dm', 'DESC'); diff --git a/htdocs/projet/comment.php b/htdocs/projet/comment.php index 1200e0bc060..ac00e0adfad 100644 --- a/htdocs/projet/comment.php +++ b/htdocs/projet/comment.php @@ -50,7 +50,9 @@ $planned_workload = ((GETPOST('planned_workloadhour', 'int') != '' || GETPOST('p // Security check $socid = 0; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. -if (!$user->rights->projet->lire) accessforbidden(); +if (!$user->rights->projet->lire) { + accessforbidden(); +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('projectcard', 'globalcard')); @@ -62,12 +64,13 @@ $object = new Project($db); $extrafields->fetch_name_optionals_label($object->table_element); // Load object -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $ret = $object->fetch($id, $ref); // If we create project, ref may be defined into POST but record does not yet exists into database if ($ret > 0) { $object->fetch_thirdparty(); - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); + } $id = $object->id; } } @@ -122,20 +125,27 @@ print '<table class="border centpercent">'; // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; -if ($object->public) print $langs->trans('SharedProject'); -else print $langs->trans('PrivateProject'); +if ($object->public) { + print $langs->trans('SharedProject'); +} else { + print $langs->trans('PrivateProject'); +} print '</td></tr>'; // Date start - end print '<tr><td>'.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").'</td><td>'; print dol_print_date($object->date_start, 'day'); $end = dol_print_date($object->date_end, 'day'); -if ($end) print ' - '.$end; +if ($end) { + print ' - '.$end; +} print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; -if (strcmp($object->budget_amount, '')) print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency); +if (strcmp($object->budget_amount, '')) { + print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency); +} print '</td></tr>'; // Other attributes diff --git a/htdocs/projet/contact.php b/htdocs/projet/contact.php index a7cb95ec666..7f6c6c4f009 100644 --- a/htdocs/projet/contact.php +++ b/htdocs/projet/contact.php @@ -28,10 +28,17 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; -if ($conf->categorie->enabled) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; } +if ($conf->categorie->enabled) { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +} // Load translation files required by the page -$langs->loadLangs(array('projects', 'companies')); +$langsLoad=array('projects', 'companies'); +if (!empty($conf->eventorganization->enabled)) { + $langsLoad[]='eventorganization'; +} + +$langs->loadLangs($langsLoad); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); @@ -45,7 +52,9 @@ $mine = GETPOST('mode') == 'mine' ? 1 : 0; $object = new Project($db); include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once -if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); +if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); +} // Security check $socid = 0; @@ -140,8 +149,7 @@ if ($action == 'addcontact') { } // Add new contact -if ($action == 'addcontact_confirm' && $user->rights->projet->creer) -{ +if ($action == 'addcontact_confirm' && $user->rights->projet->creer) { $contactid = (GETPOST('userid') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); @@ -154,15 +162,13 @@ if ($action == 'addcontact_confirm' && $user->rights->projet->creer) $result = 0; $result = $object->fetch($id); - if (!$error && $result > 0 && $id > 0) - { - $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); + if (!$error && $result > 0 && $id > 0) { + $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); - if ($result == 0) { - $langs->load("errors"); - setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); - } - elseif ($result < 0) { + if ($result == 0) { + $langs->load("errors"); + setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); + } elseif ($result < 0) { if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); @@ -171,13 +177,13 @@ if ($action == 'addcontact_confirm' && $user->rights->projet->creer) } } - $affecttotask=GETPOST('tasksavailable', 'intcomma'); + $affecttotask=GETPOST('tasksavailable', 'intcomma'); if (!empty($affecttotask)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; $task_to_affect = explode(',', $affecttotask); if (!empty($task_to_affect)) { foreach ($task_to_affect as $task_id) { - if (GETPOSTISSET('person_'.$task_id, 'san_alpha') && GETPOST('person_'.$task_id, 'san_alpha')) { + if (GETPOSTISSET('person_'.$task_id) && GETPOST('person_'.$task_id, 'san_alpha')) { $tasksToAffect = new Task($db); $result=$tasksToAffect->fetch($task_id); if ($result < 0) { @@ -199,18 +205,15 @@ if ($action == 'addcontact_confirm' && $user->rights->projet->creer) } } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } } // Change contact's status -if ($action == 'swapstatut' && $user->rights->projet->creer) -{ - if ($object->fetch($id)) - { +if ($action == 'swapstatut' && $user->rights->projet->creer) { + if ($object->fetch($id)) { $result = $object->swapContactStatus(GETPOST('ligne', 'int')); } else { dol_print_error($db); @@ -218,13 +221,11 @@ if ($action == 'swapstatut' && $user->rights->projet->creer) } // Delete a contact -if (($action == 'deleteline' || $action == 'deletecontact') && $user->rights->projet->creer) -{ +if (($action == 'deleteline' || $action == 'deletecontact') && $user->rights->projet->creer) { $object->fetch($id); $result = $object->delete_contact(GETPOST("lineid")); - if ($result >= 0) - { + if ($result >= 0) { header("Location: contact.php?id=".$object->id); exit; } else { @@ -239,7 +240,9 @@ if (($action == 'deleteline' || $action == 'deletecontact') && $user->rights->pr */ $title = $langs->trans("ProjectContact").' - '.$object->ref.' '.$object->name; -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("ProjectContact"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->ref.' '.$object->name.' - '.$langs->trans("ProjectContact"); +} $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos"; llxHeader('', $title, $help_url); @@ -254,9 +257,10 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); +if ($id > 0 || !empty($ref)) { + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); + } // To verify role of users //$userAccess = $object->restrictedProjectArea($user,'read'); $userWrite = $object->restrictedProjectArea($user, 'write'); @@ -271,8 +275,11 @@ if ($id > 0 || !empty($ref)) // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -285,15 +292,13 @@ if ($id > 0 || !empty($ref)) // Title $morehtmlref .= $object->title; // Thirdparty - if ($object->thirdparty->id > 0) - { + if ($object->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); $object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -312,51 +317,61 @@ if ($id > 0 || !empty($ref)) print $langs->trans("Usage"); print '</td>'; print '<td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } - if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); print '<br>'; } + if (!empty($conf->eventorganization->enabled)) { + print '<input type="checkbox" disabled name="usage_organize_event"'.(GETPOSTISSET('usage_organize_event') ? (GETPOST('usage_organize_event', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_organize_event ? ' checked="checked"' : '')).'"> '; + $htmltext = $langs->trans("EventOrganizationDescriptionLong"); + print $form->textwithpicto($langs->trans("ManageOrganizeEvent"), $htmltext); + } print '</td></tr>'; // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; - if ($object->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); + if ($object->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } print '</td></tr>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && $object->opp_status) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && $object->opp_status) { // Opportunity status print '<tr><td>'.$langs->trans("OpportunityStatus").'</td><td>'; $code = dol_getIdFromCode($db, $object->opp_status, 'c_lead_status', 'rowid', 'code'); - if ($code) print $langs->trans("OppStatus".$code); + if ($code) { + print $langs->trans("OppStatus".$code); + } print '</td></tr>'; // Opportunity percent print '<tr><td>'.$langs->trans("OpportunityProbability").'</td><td>'; - if (strcmp($object->opp_percent, '')) print price($object->opp_percent, '', $langs, 1, 0).' %'; + if (strcmp($object->opp_percent, '')) { + print price($object->opp_percent, '', $langs, 1, 0).' %'; + } print '</td></tr>'; // Opportunity Amount print '<tr><td>'.$langs->trans("OpportunityAmount").'</td><td>'; - if (strcmp($object->opp_amount, '')) print price($object->opp_amount, '', $langs, 0, 0, 0, $conf->currency); + if (strcmp($object->opp_amount, '')) { + print price($object->opp_amount, '', $langs, 0, 0, 0, $conf->currency); + } print '</td></tr>'; } @@ -367,12 +382,16 @@ if ($id > 0 || !empty($ref)) $end = dol_print_date($object->date_end, 'day'); print ' - '; print ($end ? $end : '?'); - if ($object->hasDelay()) print img_warning("Late"); + if ($object->hasDelay()) { + print img_warning("Late"); + } print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; - if (strcmp($object->budget_amount, '')) print price($object->budget_amount, '', $langs, 0, 0, 0, $conf->currency); + if (strcmp($object->budget_amount, '')) { + print price($object->budget_amount, '', $langs, 0, 0, 0, $conf->currency); + } print '</td></tr>'; // Other attributes @@ -414,10 +433,11 @@ if ($id > 0 || !empty($ref)) // Contacts lines (modules that overwrite templates must declare this into descriptor) $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); - foreach ($dirtpls as $reldir) - { + foreach ($dirtpls as $reldir) { $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); - if ($res) break; + if ($res) { + break; + } } } diff --git a/htdocs/projet/document.php b/htdocs/projet/document.php index bed7f6a43e1..795e10f2739 100644 --- a/htdocs/projet/document.php +++ b/htdocs/projet/document.php @@ -48,7 +48,9 @@ $result = restrictedArea($user, 'projet', $id, 'projet&project'); $object = new Project($db); include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once -if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); +if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); +} if ($id > 0 || !empty($ref)) { $upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($object->ref); @@ -59,16 +61,26 @@ $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 (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; } -if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; } +if (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { + $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; +} +if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { + $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; +} -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} @@ -76,7 +88,7 @@ if (!$sortfield) $sortfield = "name"; * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -84,15 +96,16 @@ include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; */ $title = $langs->trans("Project").' - '.$langs->trans("Document").' - '.$object->ref.' '.$object->name; -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Document"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->ref.' '.$object->name.' - '.$langs->trans("Document"); +} $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos"; llxHeader('', $title, $help_url); $form = new Form($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $upload_dir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($object->ref); // To verify role of users @@ -107,8 +120,7 @@ if ($object->id > 0) // Files list constructor $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -121,15 +133,13 @@ if ($object->id > 0) // Title $morehtmlref .= $object->title; // Thirdparty - if ($object->thirdparty->id > 0) - { + if ($object->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); $object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } diff --git a/htdocs/projet/element.php b/htdocs/projet/element.php index 3df802018ef..ac8ed3879cd 100644 --- a/htdocs/projet/element.php +++ b/htdocs/projet/element.php @@ -6,6 +6,7 @@ * Copyright (C) 2015-2019 Alexandre Spangaro <aspangaro@open-dsi.fr> * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com> * Copyright (C) 2016 Josep Lluís Amador <joseplluis@lliuretic.cat> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -34,41 +35,108 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; -if (!empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -if (!empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; -if (!empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; -if (!empty($conf->supplier_proposal->enabled)) require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; -if (!empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; -if (!empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; -if (!empty($conf->contrat->enabled)) require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; -if (!empty($conf->ficheinter->enabled)) require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; -if (!empty($conf->expedition->enabled)) require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; -if (!empty($conf->deplacement->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php'; -if (!empty($conf->expensereport->enabled)) require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; -if (!empty($conf->agenda->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; -if (!empty($conf->don->enabled)) require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; -if (!empty($conf->loan->enabled)) require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; -if (!empty($conf->loan->enabled)) require_once DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php'; -if (!empty($conf->stock->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; -if (!empty($conf->tax->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; -if (!empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php'; -if (!empty($conf->salaries->enabled)) require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; -if (!empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; -if (!empty($conf->mrp->enabled)) require_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php'; +if (!empty($conf->propal->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +} +if (!empty($conf->facture->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +} +if (!empty($conf->facture->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; +} +if (!empty($conf->commande->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +} +if (!empty($conf->supplier_proposal->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; +} +if (!empty($conf->fournisseur->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +} +if (!empty($conf->fournisseur->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; +} +if (!empty($conf->contrat->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; +} +if (!empty($conf->ficheinter->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; +} +if (!empty($conf->expedition->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; +} +if (!empty($conf->deplacement->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php'; +} +if (!empty($conf->expensereport->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +} +if (!empty($conf->agenda->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; +} +if (!empty($conf->don->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; +} +if (!empty($conf->loan->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; +} +if (!empty($conf->loan->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php'; +} +if (!empty($conf->stock->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; +} +if (!empty($conf->tax->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; +} +if (!empty($conf->banque->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php'; +} +if (!empty($conf->salaries->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php'; +} +if (!empty($conf->categorie->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +} +if (!empty($conf->mrp->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('projects', 'companies', 'suppliers', 'compta')); -if (!empty($conf->facture->enabled)) $langs->load("bills"); -if (!empty($conf->commande->enabled)) $langs->load("orders"); -if (!empty($conf->propal->enabled)) $langs->load("propal"); -if (!empty($conf->ficheinter->enabled)) $langs->load("interventions"); -if (!empty($conf->deplacement->enabled)) $langs->load("trips"); -if (!empty($conf->expensereport->enabled)) $langs->load("trips"); -if (!empty($conf->don->enabled)) $langs->load("donations"); -if (!empty($conf->loan->enabled)) $langs->load("loan"); -if (!empty($conf->salaries->enabled)) $langs->load("salaries"); -if (!empty($conf->mrp->enabled)) $langs->load("mrp"); +if (!empty($conf->facture->enabled)) { + $langs->load("bills"); +} +if (!empty($conf->commande->enabled)) { + $langs->load("orders"); +} +if (!empty($conf->propal->enabled)) { + $langs->load("propal"); +} +if (!empty($conf->ficheinter->enabled)) { + $langs->load("interventions"); +} +if (!empty($conf->deplacement->enabled)) { + $langs->load("trips"); +} +if (!empty($conf->expensereport->enabled)) { + $langs->load("trips"); +} +if (!empty($conf->don->enabled)) { + $langs->load("donations"); +} +if (!empty($conf->loan->enabled)) { + $langs->load("loan"); +} +if (!empty($conf->salaries->enabled)) { + $langs->load("salaries"); +} +if (!empty($conf->mrp->enabled)) { + $langs->load("mrp"); +} +if (!empty($conf->eventorganization->enabled)) { + $langs->load("eventorganization"); +} $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); @@ -77,8 +145,12 @@ $datesrfc = GETPOST('datesrfc'); $dateerfc = GETPOST('dateerfc'); $dates = dol_mktime(0, 0, 0, GETPOST('datesmonth'), GETPOST('datesday'), GETPOST('datesyear')); $datee = dol_mktime(23, 59, 59, GETPOST('dateemonth'), GETPOST('dateeday'), GETPOST('dateeyear')); -if (empty($dates) && !empty($datesrfc)) $dates = dol_stringtotime($datesrfc); -if (empty($datee) && !empty($dateerfc)) $datee = dol_stringtotime($dateerfc); +if (empty($dates) && !empty($datesrfc)) { + $dates = dol_stringtotime($datesrfc); +} +if (empty($datee) && !empty($dateerfc)) { + $datee = dol_stringtotime($dateerfc); +} if (!GETPOSTISSET('datesrfc') && !GETPOSTISSET('datesday') && !empty($conf->global->PROJECT_LINKED_ELEMENT_DEFAULT_FILTER_YEAR)) { $new = dol_now(); $tmp = dol_getdate($new); @@ -86,8 +158,7 @@ if (!GETPOSTISSET('datesrfc') && !GETPOSTISSET('datesday') && !empty($conf->glob //$dates=dol_time_plus_duree($datee, -1, 'y'); $dates = dol_get_first_day($tmp['year'], 1); } -if ($id == '' && $ref == '') -{ +if ($id == '' && $ref == '') { setEventMessage($langs->trans('ErrorBadParameters'), 'errors'); header('Location: list.php'); exit(); @@ -99,7 +170,9 @@ $mine = $_REQUEST['mode'] == 'mine' ? 1 : 0; $object = new Project($db); include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once -if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); +if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); +} // Security check $socid = $object->socid; @@ -114,7 +187,9 @@ $hookmanager->initHooks(array('projectOverview')); */ $title = $langs->trans("ProjectReferers").' - '.$object->ref.' '.$object->name; -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("ProjectReferers"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->ref.' '.$object->name.' - '.$langs->trans("ProjectReferers"); +} $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos"; llxHeader("", $langs->trans("Referers"), $help_url); @@ -139,15 +214,13 @@ $morehtmlref = '<div class="refidno">'; // Title $morehtmlref .= $object->title; // Thirdparty -if ($object->thirdparty->id > 0) -{ +if ($object->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. -if (!$user->rights->projet->all->lire) -{ +if (!$user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); $object->next_prev_filter = " te.rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -166,51 +239,61 @@ print '<tr><td class="tdtop">'; print $langs->trans("Usage"); print '</td>'; print '<td>'; -if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) -{ +if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '<br>'; } -if (empty($conf->global->PROJECT_HIDE_TASKS)) -{ +if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } -if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) -{ +if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); print '<br>'; } +if (!empty($conf->eventorganization->enabled)) { + print '<input type="checkbox" disabled name="usage_organize_event"'.(GETPOSTISSET('usage_organize_event') ? (GETPOST('usage_organize_event', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_organize_event ? ' checked="checked"' : '')).'"> '; + $htmltext = $langs->trans("EventOrganizationDescriptionLong"); + print $form->textwithpicto($langs->trans("ManageOrganizeEvent"), $htmltext); +} print '</td></tr>'; // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; -if ($object->public) print $langs->trans('SharedProject'); -else print $langs->trans('PrivateProject'); +if ($object->public) { + print $langs->trans('SharedProject'); +} else { + print $langs->trans('PrivateProject'); +} print '</td></tr>'; -if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) -{ +if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { // Opportunity status print '<tr><td>'.$langs->trans("OpportunityStatus").'</td><td>'; $code = dol_getIdFromCode($db, $object->opp_status, 'c_lead_status', 'rowid', 'code'); - if ($code) print $langs->trans("OppStatus".$code); + if ($code) { + print $langs->trans("OppStatus".$code); + } print '</td></tr>'; // Opportunity percent print '<tr><td>'.$langs->trans("OpportunityProbability").'</td><td>'; - if (strcmp($object->opp_percent, '')) print price($object->opp_percent, '', $langs, 1, 0).' %'; + if (strcmp($object->opp_percent, '')) { + print price($object->opp_percent, '', $langs, 1, 0).' %'; + } print '</td></tr>'; // Opportunity Amount print '<tr><td>'.$langs->trans("OpportunityAmount").'</td><td>'; - if (strcmp($object->opp_amount, '')) print price($object->opp_amount, '', $langs, 1, 0, 0, $conf->currency); + if (strcmp($object->opp_amount, '')) { + print price($object->opp_amount, '', $langs, 1, 0, 0, $conf->currency); + } print '</td></tr>'; } @@ -221,12 +304,16 @@ print ($start ? $start : '?'); $end = dol_print_date($object->date_end, 'day'); print ' - '; print ($end ? $end : '?'); -if ($object->hasDelay()) print img_warning("Late"); +if ($object->hasDelay()) { + print img_warning("Late"); +} print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; -if (strcmp($object->budget_amount, '')) print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency); +if (strcmp($object->budget_amount, '')) { + print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency); +} print '</td></tr>'; // Other attributes @@ -486,7 +573,7 @@ $listofreferent = array( 'salaries'=>array( 'name'=>"Salaries", 'title'=>"ListSalariesAssociatedProject", - 'class'=>'PaymentSalary', + 'class'=>'Salary', 'table'=>'payment_salary', 'datefieldname'=>'datev', 'margin'=>'minus', @@ -517,11 +604,11 @@ $listofreferent = array( 'table'=>'actioncomm', 'datefieldname'=>'datep', 'disableamount'=>1, - 'urlnew'=>DOL_URL_ROOT.'/comm/action/card.php?action=create&projectid='.$id.'&socid='.$socid, - 'lang'=>'agenda', - 'buttonnew'=>'AddEvent', - 'testnew'=>$user->rights->agenda->myactions->create, - 'test'=>$conf->agenda->enabled && $user->rights->agenda->myactions->read), + 'urlnew'=>DOL_URL_ROOT.'/comm/action/card.php?action=create&projectid='.$id.'&socid='.$socid, + 'lang'=>'agenda', + 'buttonnew'=>'AddEvent', + 'testnew'=>$user->rights->agenda->myactions->create, + 'test'=>$conf->agenda->enabled && $user->rights->agenda->myactions->read), */ ); @@ -558,24 +645,20 @@ if (!empty($hookmanager->resArray)) { $listofreferent = array_merge($listofreferent, $hookmanager->resArray); } -if ($action == "addelement") -{ +if ($action == "addelement") { $tablename = GETPOST("tablename"); $elementselectid = GETPOST("elementselect"); $result = $object->update_element($tablename, $elementselectid); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } -} elseif ($action == "unlink") -{ +} elseif ($action == "unlink") { $tablename = GETPOST("tablename", "aZ09"); $projectField = GETPOSTISSET('projectfield') ? GETPOST('projectfield', 'aZ09') : 'fk_projet'; $elementselectid = GETPOST("elementselect", "int"); $result = $object->remove_element($tablename, $elementselectid, $projectField); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } } @@ -586,8 +669,7 @@ $elementuser = new User($db); $showdatefilter = 0; // Show the filter on date on top of element list -if (!$showdatefilter) -{ +if (!$showdatefilter) { print '<div class="center centpercent">'; print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -614,7 +696,9 @@ if (!$showdatefilter) $langs->loadLangs(array("suppliers", "bills", "orders", "proposals", "margins")); -if (!empty($conf->stock->enabled)) $langs->load('stocks'); +if (!empty($conf->stock->enabled)) { + $langs->load('stocks'); +} print load_fiche_titre($langs->trans("Profit"), '', 'title_accountancy'); @@ -623,13 +707,11 @@ print '<tr class="liste_titre">'; print '<td class="left" width="200">'; $tooltiponprofit = $langs->trans("ProfitIsCalculatedWith")."<br>\n"; $tooltiponprofitplus = $tooltiponprofitminus = ''; -foreach ($listofreferent as $key => $value) -{ +foreach ($listofreferent as $key => $value) { $name = $langs->trans($value['name']); $qualified = $value['test']; $margin = $value['margin']; - if ($qualified && isset($margin)) // If this element must be included into profit calculation ($margin is 'minus' or 'add') - { + if ($qualified && isset($margin)) { // If this element must be included into profit calculation ($margin is 'minus' or 'add') if ($margin == 'add') { $tooltiponprofitplus .= ' &gt; '.$name." (+)<br>\n"; } @@ -651,8 +733,7 @@ $total_revenue_ht = 0; $balance_ht = 0; $balance_ttc = 0; -foreach ($listofreferent as $key => $value) -{ +foreach ($listofreferent as $key => $value) { $parameters = array( 'total_revenue_ht' =>& $total_revenue_ht, 'balance_ht' =>& $balance_ht, @@ -694,25 +775,38 @@ foreach ($listofreferent as $key => $value) $idofelementuser = $tmp[1]; $element->fetch($idofelement); - if ($idofelementuser) $elementuser->fetch($idofelementuser); + if ($idofelementuser) { + $elementuser->fetch($idofelementuser); + } // Define if record must be used for total or not $qualifiedfortotal = true; if ($key == 'invoice') { - if (!empty($element->close_code) && $element->close_code == 'replaced') $qualifiedfortotal = false; // Replacement invoice, do not include into total - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS) && $element->type == Facture::TYPE_DEPOSIT) $qualifiedfortotal = false; // If hidden option to use deposits as payment (deprecated, not recommended to use this), deposits are not included + if (!empty($element->close_code) && $element->close_code == 'replaced') { + $qualifiedfortotal = false; // Replacement invoice, do not include into total + } + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS) && $element->type == Facture::TYPE_DEPOSIT) { + $qualifiedfortotal = false; // If hidden option to use deposits as payment (deprecated, not recommended to use this), deposits are not included + } } if ($key == 'propal') { - if ($element->status != Propal::STATUS_SIGNED && $element->status != Propal::STATUS_BILLED) $qualifiedfortotal = false; // Only signed proposal must not be included in total + if ($element->status != Propal::STATUS_SIGNED && $element->status != Propal::STATUS_BILLED) { + $qualifiedfortotal = false; // Only signed proposal must not be included in total + } } - if ($tablename != 'expensereport_det' && method_exists($element, 'fetch_thirdparty')) $element->fetch_thirdparty(); + if ($tablename != 'expensereport_det' && method_exists($element, 'fetch_thirdparty')) { + $element->fetch_thirdparty(); + } // Define $total_ht_by_line - if ($tablename == 'don' || $tablename == 'chargesociales' || $tablename == 'payment_various' || $tablename == 'payment_salary') $total_ht_by_line = $element->amount; - elseif ($tablename == 'fichinter') $total_ht_by_line = $element->getAmount(); - elseif ($tablename == 'stock_mouvement') $total_ht_by_line = $element->price * abs($element->qty); - elseif ($tablename == 'projet_task') { + if ($tablename == 'don' || $tablename == 'chargesociales' || $tablename == 'payment_various' || $tablename == 'payment_salary') { + $total_ht_by_line = $element->amount; + } elseif ($tablename == 'fichinter') { + $total_ht_by_line = $element->getAmount(); + } elseif ($tablename == 'stock_mouvement') { + $total_ht_by_line = $element->price * abs($element->qty); + } elseif ($tablename == 'projet_task') { if ($idofelementuser) { $tmp = $element->getSumOfAmount($elementuser, $dates, $datee); $total_ht_by_line = price2num($tmp['amount'], 'MT'); @@ -743,18 +837,25 @@ foreach ($listofreferent as $key => $value) } } } - } else $total_ht_by_line = $element->total_ht; + } else { + $total_ht_by_line = $element->total_ht; + } // Define $total_ttc_by_line - if ($tablename == 'don' || $tablename == 'chargesociales' || $tablename == 'payment_various' || $tablename == 'payment_salary') $total_ttc_by_line = $element->amount; - elseif ($tablename == 'fichinter') $total_ttc_by_line = $element->getAmount(); - elseif ($tablename == 'stock_mouvement') $total_ttc_by_line = $element->price * abs($element->qty); - elseif ($tablename == 'projet_task') { + if ($tablename == 'don' || $tablename == 'chargesociales' || $tablename == 'payment_various' || $tablename == 'payment_salary') { + $total_ttc_by_line = $element->amount; + } elseif ($tablename == 'fichinter') { + $total_ttc_by_line = $element->getAmount(); + } elseif ($tablename == 'stock_mouvement') { + $total_ttc_by_line = $element->price * abs($element->qty); + } elseif ($tablename == 'projet_task') { $defaultvat = get_default_tva($mysoc, $mysoc); $total_ttc_by_line = price2num($total_ht_by_line * (1 + ($defaultvat / 100)), 'MT'); } elseif ($key == 'loan') { $total_ttc_by_line = $total_ht_by_line; // For loan there is actually no taxe managed in Dolibarr - } else $total_ttc_by_line = $element->total_ttc; + } else { + $total_ttc_by_line = $element->total_ttc; + } // Change sign of $total_ht_by_line and $total_ttc_by_line for some cases if ($tablename == 'payment_various') { @@ -773,7 +874,9 @@ foreach ($listofreferent as $key => $value) // Each element with at least one line is output $qualifiedforfinalprofit = true; - if ($key == 'intervention' && empty($conf->global->PROJECT_INCLUDE_INTERVENTION_AMOUNT_IN_PROFIT)) $qualifiedforfinalprofit = false; + if ($key == 'intervention' && empty($conf->global->PROJECT_INCLUDE_INTERVENTION_AMOUNT_IN_PROFIT)) { + $qualifiedforfinalprofit = false; + } //var_dump($key.' '.$qualifiedforfinalprofit); // Calculate margin @@ -798,18 +901,24 @@ foreach ($listofreferent as $key => $value) print '<td class="right">'.$i.'</td>'; // Amount HT print '<td class="right">'; - if ($key == 'intervention' && !$qualifiedforfinalprofit) print '<span class="opacitymedium">'.$form->textwithpicto($langs->trans("NA"), $langs->trans("AmountOfInteventionNotIncludedByDefault")).'</span>'; - else { + if ($key == 'intervention' && !$qualifiedforfinalprofit) { + print '<span class="opacitymedium">'.$form->textwithpicto($langs->trans("NA"), $langs->trans("AmountOfInteventionNotIncludedByDefault")).'</span>'; + } else { print price($total_ht); - if ($key == 'propal') print '<span class="opacitymedium">'.$form->textwithpicto('', $langs->trans("SignedOnly")).'</span>'; + if ($key == 'propal') { + print '<span class="opacitymedium">'.$form->textwithpicto('', $langs->trans("SignedOnly")).'</span>'; + } } print '</td>'; // Amount TTC print '<td class="right">'; - if ($key == 'intervention' && !$qualifiedforfinalprofit) print '<span class="opacitymedium">'.$form->textwithpicto($langs->trans("NA"), $langs->trans("AmountOfInteventionNotIncludedByDefault")).'</span>'; - else { + if ($key == 'intervention' && !$qualifiedforfinalprofit) { + print '<span class="opacitymedium">'.$form->textwithpicto($langs->trans("NA"), $langs->trans("AmountOfInteventionNotIncludedByDefault")).'</span>'; + } else { print price($total_ttc); - if ($key == 'propal') print '<span class="opacitymedium">'.$form->textwithpicto('', $langs->trans("SignedOnly")).'</span>'; + if ($key == 'propal') { + print '<span class="opacitymedium">'.$form->textwithpicto('', $langs->trans("SignedOnly")).'</span>'; + } } print '</td>'; print '</tr>'; @@ -841,8 +950,7 @@ print '<br>'; // Detail -foreach ($listofreferent as $key => $value) -{ +foreach ($listofreferent as $key => $value) { $parameters = array( 'key' => $key, 'value' =>& $value, @@ -869,13 +977,17 @@ foreach ($listofreferent as $key => $value) $project_field = $value['project_field']; $exclude_select_element = array('payment_various'); - if (!empty($value['exclude_select_element'])) $exclude_select_element[] = $value['exclude_select_element']; + if (!empty($value['exclude_select_element'])) { + $exclude_select_element[] = $value['exclude_select_element']; + } if ($qualified) { // If we want the project task array to have details of users //if ($key == 'project_task') $key = 'project_task_time'; - if ($langtoload) $langs->load($langtoload); + if ($langtoload) { + $langs->load($langtoload); + } $element = new $classname($db); @@ -883,20 +995,18 @@ foreach ($listofreferent as $key => $value) $idtofilterthirdparty = 0; $array_of_element_linkable_with_different_thirdparty = array('facture_fourn', 'commande_fournisseur'); - if (!in_array($tablename, $array_of_element_linkable_with_different_thirdparty)) - { + if (!in_array($tablename, $array_of_element_linkable_with_different_thirdparty)) { $idtofilterthirdparty = $object->thirdparty->id; - if (!empty($conf->global->PROJECT_OTHER_THIRDPARTY_ID_TO_ADD_ELEMENTS)) $idtofilterthirdparty .= ','.$conf->global->PROJECT_OTHER_THIRDPARTY_ID_TO_ADD_ELEMENTS; + if (!empty($conf->global->PROJECT_OTHER_THIRDPARTY_ID_TO_ADD_ELEMENTS)) { + $idtofilterthirdparty .= ','.$conf->global->PROJECT_OTHER_THIRDPARTY_ID_TO_ADD_ELEMENTS; + } } - if (empty($conf->global->PROJECT_LINK_ON_OVERWIEW_DISABLED) && $idtofilterthirdparty && !in_array($tablename, $exclude_select_element)) - { + if (empty($conf->global->PROJECT_LINK_ON_OVERWIEW_DISABLED) && $idtofilterthirdparty && !in_array($tablename, $exclude_select_element)) { $selectList = $formproject->select_element($tablename, $idtofilterthirdparty, 'minwidth300 minwidth75imp', -2, !empty($project_field) ? $project_field : 'fk_projet'); - if ($selectList < 0) - { + if ($selectList < 0) { setEventMessages($formproject->error, $formproject->errors, 'errors'); - } elseif ($selectList) - { + } elseif ($selectList) { // Define form with the combo list of elements to link $addform .= '<div class="inline-block valignmiddle">'; $addform .= '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">'; @@ -913,11 +1023,11 @@ foreach ($listofreferent as $key => $value) $addform .= '</div>'; } } - if (empty($conf->global->PROJECT_CREATE_ON_OVERVIEW_DISABLED) && $urlnew) - { + if (empty($conf->global->PROJECT_CREATE_ON_OVERVIEW_DISABLED) && $urlnew) { $addform .= '<div class="inline-block valignmiddle">'; - if ($testnew) $addform .= '<a class="buttonxxx" href="'.$urlnew.'"><span class="valignmiddle text-plus-circle hideonsmartphone">'.($buttonnew ? $langs->trans($buttonnew) : $langs->trans("Create")).'</span><span class="fa fa-plus-circle valignmiddle paddingleft"></span></a>'; - elseif (empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { + if ($testnew) { + $addform .= '<a class="buttonxxx" href="'.$urlnew.'"><span class="valignmiddle text-plus-circle hideonsmartphone">'.($buttonnew ? $langs->trans($buttonnew) : $langs->trans("Create")).'</span><span class="fa fa-plus-circle valignmiddle paddingleft"></span></a>'; + } elseif (empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { $addform .= '<a class="buttonxxx buttonRefused" disabled="disabled" href="#"><span class="valignmiddle text-plus-circle hideonsmartphone">'.($buttonnew ? $langs->trans($buttonnew) : $langs->trans("Create")).'</span><span class="fa fa-plus-circle valignmiddle paddingleft"></span></a>'; } $addform .= '<div>'; @@ -936,19 +1046,27 @@ foreach ($listofreferent as $key => $value) print '<td'.(($tablename != 'actioncomm' && $tablename != 'projet_task') ? ' style="width: 200px"' : '').'>'.$langs->trans("Ref").'</td>'; // Date print '<td'.(($tablename != 'actioncomm' && $tablename != 'projet_task') ? ' style="width: 200px"' : '').' class="center">'; - if (in_array($tablename, array('projet_task'))) print $langs->trans("TimeSpent"); - if (!in_array($tablename, array('projet_task'))) print $langs->trans("Date"); + if (in_array($tablename, array('projet_task'))) { + print $langs->trans("TimeSpent"); + } + if (!in_array($tablename, array('projet_task'))) { + print $langs->trans("Date"); + } print '</td>'; // Thirdparty or user print '<td>'; - if (in_array($tablename, array('projet_task')) && $key == 'project_task') print ''; // if $key == 'project_task', we don't want details per user - elseif (in_array($tablename, array('payment_various'))) print ''; // if $key == 'payment_various', we don't have any thirdparty - elseif (in_array($tablename, array('expensereport_det', 'don', 'projet_task', 'stock_mouvement', 'payment_salary'))) print $langs->trans("User"); - else print $langs->trans("ThirdParty"); + if (in_array($tablename, array('projet_task')) && $key == 'project_task') { + print ''; // if $key == 'project_task', we don't want details per user + } elseif (in_array($tablename, array('payment_various'))) { + print ''; // if $key == 'payment_various', we don't have any thirdparty + } elseif (in_array($tablename, array('expensereport_det', 'don', 'projet_task', 'stock_mouvement', 'payment_salary'))) { + print $langs->trans("User"); + } else { + print $langs->trans("ThirdParty"); + } print '</td>'; // Duration of intervention - if ($tablename == 'fichinter') - { + if ($tablename == 'fichinter') { print '<td>'; print $langs->trans("TotalDuration"); $total_duration = 0; @@ -957,22 +1075,32 @@ foreach ($listofreferent as $key => $value) // Amount HT //if (empty($value['disableamount']) && ! in_array($tablename, array('projet_task'))) print '<td class="right" width="120">'.$langs->trans("AmountHT").'</td>'; //elseif (empty($value['disableamount']) && in_array($tablename, array('projet_task'))) print '<td class="right" width="120">'.$langs->trans("Amount").'</td>'; - if ($key == 'loan') print '<td class="right" width="120">'.$langs->trans("LoanCapital").'</td>'; - elseif (empty($value['disableamount'])) print '<td class="right" width="120">'.$langs->trans("AmountHT").'</td>'; - else print '<td width="120"></td>'; + if ($key == 'loan') { + print '<td class="right" width="120">'.$langs->trans("LoanCapital").'</td>'; + } elseif (empty($value['disableamount'])) { + print '<td class="right" width="120">'.$langs->trans("AmountHT").'</td>'; + } else { + print '<td width="120"></td>'; + } // Amount TTC //if (empty($value['disableamount']) && ! in_array($tablename, array('projet_task'))) print '<td class="right" width="120">'.$langs->trans("AmountTTC").'</td>'; - if ($key == 'loan') print '<td class="right" width="120">'.$langs->trans("RemainderToPay").'</td>'; - elseif (empty($value['disableamount'])) print '<td class="right" width="120">'.$langs->trans("AmountTTC").'</td>'; - else print '<td width="120"></td>'; + if ($key == 'loan') { + print '<td class="right" width="120">'.$langs->trans("RemainderToPay").'</td>'; + } elseif (empty($value['disableamount'])) { + print '<td class="right" width="120">'.$langs->trans("AmountTTC").'</td>'; + } else { + print '<td width="120"></td>'; + } // Status - if (in_array($tablename, array('projet_task'))) print '<td class="right" width="200">'.$langs->trans("ProgressDeclared").'</td>'; - else print '<td class="right" width="200">'.$langs->trans("Status").'</td>'; + if (in_array($tablename, array('projet_task'))) { + print '<td class="right" width="200">'.$langs->trans("ProgressDeclared").'</td>'; + } else { + print '<td class="right" width="200">'.$langs->trans("Status").'</td>'; + } print '</tr>'; $elementarray = $object->get_element_list($key, $tablename, $datefieldname, $dates, $datee, !empty($project_field) ? $project_field : 'fk_projet'); - if (is_array($elementarray) && count($elementarray) > 0) - { + if (is_array($elementarray) && count($elementarray) > 0) { $total_ht = 0; $total_ttc = 0; @@ -982,26 +1110,27 @@ foreach ($listofreferent as $key => $value) $saved_third_id = 0; $breakline = ''; - if (canApplySubtotalOn($tablename)) - { + if (canApplySubtotalOn($tablename)) { // Sort $elementarray = sortElementsByClientName($elementarray); } $num = count($elementarray); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $tmp = explode('_', $elementarray[$i]); $idofelement = $tmp[0]; $idofelementuser = $tmp[1]; $element->fetch($idofelement); - if ($idofelementuser) $elementuser->fetch($idofelementuser); + if ($idofelementuser) { + $elementuser->fetch($idofelementuser); + } // Special cases - if ($tablename != 'expensereport_det') - { - if (method_exists($element, 'fetch_thirdparty')) $element->fetch_thirdparty(); + if ($tablename != 'expensereport_det') { + if (method_exists($element, 'fetch_thirdparty')) { + $element->fetch_thirdparty(); + } } else { $expensereport = new ExpenseReport($db); $expensereport->fetch($element->fk_expensereport); @@ -1009,8 +1138,7 @@ foreach ($listofreferent as $key => $value) //print 'xxx'.$tablename.'yyy'.$classname; - if ($breakline && $saved_third_id != $element->thirdparty->id) - { + if ($breakline && $saved_third_id != $element->thirdparty->id) { print $breakline; $saved_third_id = $element->thirdparty->id; @@ -1022,19 +1150,18 @@ foreach ($listofreferent as $key => $value) $saved_third_id = $element->thirdparty->id; $qualifiedfortotal = true; - if ($key == 'invoice') - { - if (!empty($element->close_code) && $element->close_code == 'replaced') $qualifiedfortotal = false; // Replacement invoice, do not include into total + if ($key == 'invoice') { + if (!empty($element->close_code) && $element->close_code == 'replaced') { + $qualifiedfortotal = false; // Replacement invoice, do not include into total + } } print '<tr class="oddeven">'; // Remove link print '<td style="width: 24px">'; - if ($tablename != 'projet_task' && $tablename != 'stock_mouvement') - { - if (empty($conf->global->PROJECT_DISABLE_UNLINK_FROM_OVERVIEW) || $user->admin) // PROJECT_DISABLE_UNLINK_FROM_OVERVIEW is empty by defaut, so this test true - { + if ($tablename != 'projet_task' && $tablename != 'stock_mouvement') { + if (empty($conf->global->PROJECT_DISABLE_UNLINK_FROM_OVERVIEW) || $user->admin) { // PROJECT_DISABLE_UNLINK_FROM_OVERVIEW is empty by defaut, so this test true print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=unlink&tablename='.$tablename.'&elementselect='.$element->id.($project_field ? '&projectfield='.$project_field : '').'" class="reposition">'; print img_picto($langs->trans('Unlink'), 'unlink'); print '</a>'; @@ -1044,19 +1171,19 @@ foreach ($listofreferent as $key => $value) // Ref print '<td class="left nowraponall">'; - if ($tablename == 'expensereport_det') - { + if ($tablename == 'expensereport_det') { print $expensereport->getNomUrl(1); } else { // Show ref with link - if ($element instanceof Task) - { + if ($element instanceof Task) { print $element->getNomUrl(1, 'withproject', 'time'); print ' - '.dol_trunc($element->label, 48); } elseif ($key == 'loan') { print $element->getNomUrl(1); print ' - '.dol_trunc($element->label, 48); - } else print $element->getNomUrl(1); + } else { + print $element->getNomUrl(1); + } $element_doc = $element->element; $filename = dol_sanitizeFileName($element->ref); @@ -1074,32 +1201,48 @@ foreach ($listofreferent as $key => $value) print '<div class="inline-block valignmiddle">'.$formfile->getDocumentsLink($element_doc, $filename, $filedir).'</div>'; // Show supplier ref - if (!empty($element->ref_supplier)) print ' - '.$element->ref_supplier; + if (!empty($element->ref_supplier)) { + print ' - '.$element->ref_supplier; + } // Show customer ref - if (!empty($element->ref_customer)) print ' - '.$element->ref_customer; + if (!empty($element->ref_customer)) { + print ' - '.$element->ref_customer; + } } print "</td>\n"; // Date or TimeSpent $date = ''; $total_time_by_line = null; - if ($tablename == 'expensereport_det') $date = $element->date; // No draft status on lines - elseif ($tablename == 'stock_mouvement') $date = $element->datem; - elseif ($tablename == 'payment_salary') $date = $element->datev; - elseif ($tablename == 'payment_various') $date = $element->datev; - elseif ($tablename == 'chargesociales') $date = $element->date_ech; - elseif (!empty($element->status) || !empty($element->statut) || !empty($element->fk_status)) - { - if ($tablename == 'don') $date = $element->datedon; - if ($tablename == 'commande_fournisseur' || $tablename == 'supplier_order') - { + if ($tablename == 'expensereport_det') { + $date = $element->date; // No draft status on lines + } elseif ($tablename == 'stock_mouvement') { + $date = $element->datem; + } elseif ($tablename == 'payment_salary') { + $date = $element->datev; + } elseif ($tablename == 'payment_various') { + $date = $element->datev; + } elseif ($tablename == 'chargesociales') { + $date = $element->date_ech; + } elseif (!empty($element->status) || !empty($element->statut) || !empty($element->fk_status)) { + if ($tablename == 'don') { + $date = $element->datedon; + } + if ($tablename == 'commande_fournisseur' || $tablename == 'supplier_order') { $date = ($element->date_commande ? $element->date_commande : $element->date_valid); - } elseif ($tablename == 'supplier_proposal') $date = $element->date_validation; // There is no other date for this - elseif ($tablename == 'fichinter') $date = $element->datev; // There is no other date for this - elseif ($tablename == 'projet_task') $date = ''; // We show no date. Showing date of beginning of task make user think it is date of time consumed - else { + } elseif ($tablename == 'supplier_proposal') { + $date = $element->date_validation; // There is no other date for this + } elseif ($tablename == 'fichinter') { + $date = $element->datev; // There is no other date for this + } elseif ($tablename == 'projet_task') { + $date = ''; // We show no date. Showing date of beginning of task make user think it is date of time consumed + } else { $date = $element->date; // invoice, ... - if (empty($date)) $date = $element->date_contrat; - if (empty($date)) $date = $element->datev; + if (empty($date)) { + $date = $element->date_contrat; + } + if (empty($date)) { + $date = $element->datev; + } if (empty($date) && !empty($datefieldname)) { $date = $element->$datefieldname; } @@ -1109,18 +1252,20 @@ foreach ($listofreferent as $key => $value) } print '<td class="center">'; - if ($tablename == 'actioncomm') - { + if ($tablename == 'actioncomm') { print dol_print_date($element->datep, 'dayhour'); - if ($element->datef && $element->datef > $element->datep) print " - ".dol_print_date($element->datef, 'dayhour'); - } elseif (in_array($tablename, array('projet_task'))) - { + if ($element->datef && $element->datef > $element->datep) { + print " - ".dol_print_date($element->datef, 'dayhour'); + } + } elseif (in_array($tablename, array('projet_task'))) { $tmpprojtime = $element->getSumOfAmount($elementuser, $dates, $datee); // $element is a task. $elementuser may be empty print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$idofelement.'&withproject=1">'; print convertSecondToTime($tmpprojtime['nbseconds'], 'allhourmin'); print '</a>'; $total_time_by_line = $tmpprojtime['nbseconds']; - } else print dol_print_date($date, 'day'); + } else { + print dol_print_date($date, 'day'); + } print '</td>'; // Third party or user @@ -1131,28 +1276,23 @@ foreach ($listofreferent as $key => $value) $tmpuser = new User($db); $tmpuser->fetch($expensereport->fk_user_author); print $tmpuser->getNomUrl(1, '', 48); - } elseif ($tablename == 'payment_salary') - { + } elseif ($tablename == 'payment_salary') { $tmpuser = new User($db); $tmpuser->fetch($element->fk_user); print $tmpuser->getNomUrl(1, '', 48); - } elseif ($tablename == 'don' || $tablename == 'stock_mouvement') - { - if ($element->fk_user_author > 0) - { + } elseif ($tablename == 'don' || $tablename == 'stock_mouvement') { + if ($element->fk_user_author > 0) { $tmpuser2 = new User($db); $tmpuser2->fetch($element->fk_user_author); print $tmpuser2->getNomUrl(1, '', 48); } - } elseif ($tablename == 'projet_task' && $key == 'project_task_time') // if $key == 'project_task', we don't want details per user - { + } elseif ($tablename == 'projet_task' && $key == 'project_task_time') { // if $key == 'project_task', we don't want details per user print $elementuser->getNomUrl(1); } print '</td>'; // Add duration and store it in counter for fichinter - if ($tablename == 'fichinter') - { + if ($tablename == 'fichinter') { print '<td>'; print convertSecondToTime($element->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY); $total_duration += $element->duration; @@ -1161,113 +1301,123 @@ foreach ($listofreferent as $key => $value) // Amount without tax $warning = ''; - if (empty($value['disableamount'])) - { + if (empty($value['disableamount'])) { $total_ht_by_line = null; $othermessage = ''; - if ($tablename == 'don' || $tablename == 'chargesociales' || $tablename == 'payment_various' || $tablename == 'payment_salary') $total_ht_by_line = $element->amount; - elseif ($tablename == 'fichinter') $total_ht_by_line = $element->getAmount(); - elseif ($tablename == 'stock_mouvement') $total_ht_by_line = $element->price * abs($element->qty); - elseif (in_array($tablename, array('projet_task'))) - { - if (!empty($conf->salaries->enabled)) - { + if ($tablename == 'don' || $tablename == 'chargesociales' || $tablename == 'payment_various' || $tablename == 'payment_salary') { + $total_ht_by_line = $element->amount; + } elseif ($tablename == 'fichinter') { + $total_ht_by_line = $element->getAmount(); + } elseif ($tablename == 'stock_mouvement') { + $total_ht_by_line = $element->price * abs($element->qty); + } elseif (in_array($tablename, array('projet_task'))) { + if (!empty($conf->salaries->enabled)) { // TODO Permission to read daily rate to show value $total_ht_by_line = price2num($tmpprojtime['amount'], 'MT'); - if ($tmpprojtime['nblinesnull'] > 0) - { + if ($tmpprojtime['nblinesnull'] > 0) { $langs->load("errors"); $warning = $langs->trans("WarningSomeLinesWithNullHourlyRate", $conf->currency); } } else { $othermessage = $form->textwithpicto($langs->trans("NotAvailable"), $langs->trans("ModuleSalaryToDefineHourlyRateMustBeEnabled")); } - } elseif ($key == 'loan') $total_ht_by_line = $element->capital; - else { + } elseif ($key == 'loan') { + $total_ht_by_line = $element->capital; + } else { $total_ht_by_line = $element->total_ht; } // Change sign of $total_ht_by_line and $total_ttc_by_line for some cases - if ($tablename == 'payment_various') - { - if ($element->sens == 0) - { + if ($tablename == 'payment_various') { + if ($element->sens == 0) { $total_ht_by_line = -$total_ht_by_line; } } print '<td class="right">'; - if ($othermessage) print $othermessage; - if (isset($total_ht_by_line)) - { - if (!$qualifiedfortotal) print '<strike>'; - print price($total_ht_by_line); - if (!$qualifiedfortotal) print '</strike>'; + if ($othermessage) { + print $othermessage; + } + if (isset($total_ht_by_line)) { + if (!$qualifiedfortotal) { + print '<strike>'; + } + print price($total_ht_by_line); + if (!$qualifiedfortotal) { + print '</strike>'; + } + } + if ($warning) { + print ' '.img_warning($warning); } - if ($warning) print ' '.img_warning($warning); print '</td>'; - } else print '<td></td>'; + } else { + print '<td></td>'; + } // Amount inc tax - if (empty($value['disableamount'])) - { + if (empty($value['disableamount'])) { $total_ttc_by_line = null; - if ($tablename == 'don' || $tablename == 'chargesociales' || $tablename == 'payment_various' || $tablename == 'payment_salary') $total_ttc_by_line = $element->amount; - elseif ($tablename == 'fichinter') $total_ttc_by_line = $element->getAmount(); - elseif ($tablename == 'stock_mouvement') $total_ttc_by_line = $element->price * abs($element->qty); - elseif ($tablename == 'projet_task') - { - if (!empty($conf->salaries->enabled)) - { + if ($tablename == 'don' || $tablename == 'chargesociales' || $tablename == 'payment_various' || $tablename == 'payment_salary') { + $total_ttc_by_line = $element->amount; + } elseif ($tablename == 'fichinter') { + $total_ttc_by_line = $element->getAmount(); + } elseif ($tablename == 'stock_mouvement') { + $total_ttc_by_line = $element->price * abs($element->qty); + } elseif ($tablename == 'projet_task') { + if (!empty($conf->salaries->enabled)) { // TODO Permission to read daily rate $defaultvat = get_default_tva($mysoc, $mysoc); $total_ttc_by_line = price2num($total_ht_by_line * (1 + ($defaultvat / 100)), 'MT'); } else { $othermessage = $form->textwithpicto($langs->trans("NotAvailable"), $langs->trans("ModuleSalaryToDefineHourlyRateMustBeEnabled")); } - } elseif ($key == 'loan') $total_ttc_by_line = $element->capital - $element->getSumPayment(); - else { + } elseif ($key == 'loan') { + $total_ttc_by_line = $element->capital - $element->getSumPayment(); + } else { $total_ttc_by_line = $element->total_ttc; } // Change sign of $total_ht_by_line and $total_ttc_by_line for some cases - if ($tablename == 'payment_various') - { - if ($element->sens == 0) - { + if ($tablename == 'payment_various') { + if ($element->sens == 0) { $total_ttc_by_line = -$total_ttc_by_line; } } print '<td class="right">'; - if ($othermessage) print $othermessage; - if (isset($total_ttc_by_line)) - { - if (!$qualifiedfortotal) print '<strike>'; - print price($total_ttc_by_line); - if (!$qualifiedfortotal) print '</strike>'; + if ($othermessage) { + print $othermessage; + } + if (isset($total_ttc_by_line)) { + if (!$qualifiedfortotal) { + print '<strike>'; + } + print price($total_ttc_by_line); + if (!$qualifiedfortotal) { + print '</strike>'; + } + } + if ($warning) { + print ' '.img_warning($warning); } - if ($warning) print ' '.img_warning($warning); print '</td>'; - } else print '<td></td>'; + } else { + print '<td></td>'; + } // Status print '<td class="right">'; - if ($tablename == 'expensereport_det') - { + if ($tablename == 'expensereport_det') { print $expensereport->getLibStatut(5); - } elseif ($element instanceof CommonInvoice) - { + } elseif ($element instanceof CommonInvoice) { //This applies for Facture and FactureFournisseur print $element->getLibStatut(5, $element->getSommePaiement()); - } elseif ($element instanceof Task) - { - if ($element->progress != '') - { + } elseif ($element instanceof Task) { + if ($element->progress != '') { print $element->progress.' %'; } - } elseif ($tablename == 'stock_mouvement') - { + } elseif ($tablename == 'stock_mouvement') { print $element->getLibStatut(3); } else { print $element->getLibStatut(5); @@ -1276,8 +1426,7 @@ foreach ($listofreferent as $key => $value) print '</tr>'; - if ($qualifiedfortotal) - { + if ($qualifiedfortotal) { $total_ht = $total_ht + $total_ht_by_line; $total_ttc = $total_ttc + $total_ttc_by_line; @@ -1287,8 +1436,7 @@ foreach ($listofreferent as $key => $value) $total_time = $total_time + $total_time_by_line; } - if (canApplySubtotalOn($tablename)) - { + if (canApplySubtotalOn($tablename)) { $breakline = '<tr class="liste_total liste_sub_total">'; $breakline .= '<td colspan="2">'; $breakline .= '</td>'; @@ -1296,7 +1444,9 @@ foreach ($listofreferent as $key => $value) $breakline .= '</td>'; $breakline .= '<td class="right">'; $breakline .= $langs->trans('SubTotal').' : '; - if (is_object($element->thirdparty)) $breakline .= $element->thirdparty->getNomUrl(0, '', 48); + if (is_object($element->thirdparty)) { + $breakline .= $element->thirdparty->getNomUrl(0, '', 48); + } $breakline .= '</td>'; $breakline .= '<td class="right">'.price($total_ht_by_third).'</td>'; $breakline .= '<td class="right">'.price($total_ttc_by_third).'</td>'; @@ -1307,14 +1457,17 @@ foreach ($listofreferent as $key => $value) //var_dump($element->thirdparty->name.' - '.$saved_third_id.' - '.$element->thirdparty->id); } - if ($breakline) print $breakline; + if ($breakline) { + print $breakline; + } // Total $colspan = 4; - if (in_array($tablename, array('projet_task'))) $colspan = 2; + if (in_array($tablename, array('projet_task'))) { + $colspan = 2; + } print '<tr class="liste_total"><td colspan="'.$colspan.'">'.$langs->trans("Number").': '.$i.'</td>'; - if (in_array($tablename, array('projet_task'))) - { + if (in_array($tablename, array('projet_task'))) { print '<td class="center">'; print convertSecondToTime($total_time, 'allhourmin'); print '</td>'; @@ -1324,28 +1477,33 @@ foreach ($listofreferent as $key => $value) //if (empty($value['disableamount']) && ! in_array($tablename, array('projet_task'))) print '<td class="right" width="100">'.$langs->trans("TotalHT").' : '.price($total_ht).'</td>'; //elseif (empty($value['disableamount']) && in_array($tablename, array('projet_task'))) print '<td class="right" width="100">'.$langs->trans("Total").' : '.price($total_ht).'</td>'; // If fichinter add the total_duration - if ($tablename == 'fichinter') print '<td class="left">'.convertSecondToTime($total_duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'</td>'; + if ($tablename == 'fichinter') { + print '<td class="left">'.convertSecondToTime($total_duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'</td>'; + } print '<td class="right">'; - if (empty($value['disableamount'])) - { - if ($key == 'loan') print $langs->trans("Total").' '.$langs->trans("LoanCapital").' : '.price($total_ttc); - elseif ($tablename != 'projet_task' || !empty($conf->salaries->enabled)) print ''.$langs->trans("TotalHT").' : '.price($total_ht); + if (empty($value['disableamount'])) { + if ($key == 'loan') { + print $langs->trans("Total").' '.$langs->trans("LoanCapital").' : '.price($total_ttc); + } elseif ($tablename != 'projet_task' || !empty($conf->salaries->enabled)) { + print ''.$langs->trans("TotalHT").' : '.price($total_ht); + } } print '</td>'; //if (empty($value['disableamount']) && ! in_array($tablename, array('projet_task'))) print '<td class="right" width="100">'.$langs->trans("TotalTTC").' : '.price($total_ttc).'</td>'; //elseif (empty($value['disableamount']) && in_array($tablename, array('projet_task'))) print '<td class="right" width="100"></td>'; print '<td class="right">'; - if (empty($value['disableamount'])) - { - if ($key == 'loan') print $langs->trans("Total").' '.$langs->trans("RemainderToPay").' : '.price($total_ttc); - elseif ($tablename != 'projet_task' || !empty($conf->salaries->enabled)) print $langs->trans("TotalTTC").' : '.price($total_ttc); + if (empty($value['disableamount'])) { + if ($key == 'loan') { + print $langs->trans("Total").' '.$langs->trans("RemainderToPay").' : '.price($total_ttc); + } elseif ($tablename != 'projet_task' || !empty($conf->salaries->enabled)) { + print $langs->trans("TotalTTC").' : '.price($total_ttc); + } } print '</td>'; print '<td>&nbsp;</td>'; print '</tr>'; } else { - if (!is_array($elementarray)) // error - { + if (!is_array($elementarray)) { // error print $elementarray; } } @@ -1356,8 +1514,7 @@ foreach ($listofreferent as $key => $value) } // Enhance with select2 -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $comboenhancement = ajax_combobox('.elementselect'); @@ -1380,7 +1537,9 @@ function canApplySubtotalOn($tablename) { global $conf; - if (empty($conf->global->PROJECT_ADD_SUBTOTAL_LINES)) return false; + if (empty($conf->global->PROJECT_ADD_SUBTOTAL_LINES)) { + return false; + } return in_array($tablename, array('facture_fourn', 'commande_fournisseur')); } @@ -1397,10 +1556,8 @@ function sortElementsByClientName($elementarray) $element = new $classname($db); $clientname = array(); - foreach ($elementarray as $key => $id) // id = id of object - { - if (empty($clientname[$id])) - { + foreach ($elementarray as $key => $id) { // id = id of object + if (empty($clientname[$id])) { $element->fetch($id); $element->fetch_thirdparty(); @@ -1412,8 +1569,7 @@ function sortElementsByClientName($elementarray) asort($clientname); // sort on name $elementarray = array(); - foreach ($clientname as $id => $name) - { + foreach ($clientname as $id => $name) { $elementarray[] = $id; } diff --git a/htdocs/projet/ganttchart.inc.php b/htdocs/projet/ganttchart.inc.php index bacd7607f82..d83c10ec6bd 100644 --- a/htdocs/projet/ganttchart.inc.php +++ b/htdocs/projet/ganttchart.inc.php @@ -116,12 +116,10 @@ if (g.getDivId() != null) $level = 0; $tnums = count($tasks); $old_project_id = 0; - for ($tcursor = 0; $tcursor < $tnums; $tcursor++) - { + for ($tcursor = 0; $tcursor < $tnums; $tcursor++) { $t = $tasks[$tcursor]; - if (empty($old_project_id) || $old_project_id != $t['task_project_id']) - { + if (empty($old_project_id) || $old_project_id != $t['task_project_id']) { // Break on project, create a fictive task for project id $t['task_project_id'] $projecttmp = new Project($db); $projecttmp->fetch($t['task_project_id']); @@ -140,8 +138,7 @@ if (g.getDivId() != null) $old_project_id = $t['task_project_id']; } - if ($t["task_parent"] <= 0) - { + if ($t["task_parent"] <= 0) { constructGanttLine($tasks, $t, $task_dependencies, $level, $t['task_project_id']); findChildGanttLine($tasks, $t["task_id"], $task_dependencies, $level + 1); } @@ -180,7 +177,9 @@ function constructGanttLine($tarr, $task, $task_dependencies, $level = 0, $proje $start_date = $task["task_start_date"]; $end_date = $task["task_end_date"]; - if (!$end_date) $end_date = $start_date; + if (!$end_date) { + $end_date = $start_date; + } $start_date = dol_print_date($start_date, $dateformatinput2); $end_date = dol_print_date($end_date, $dateformatinput2); // Resources @@ -198,8 +197,7 @@ function constructGanttLine($tarr, $task, $task_dependencies, $level = 0, $proje } // $depend .= "\""; // Define parent - if ($project_id && $level < 0) - { + if ($project_id && $level < 0) { $parent = '-'.$project_id; } else { $parent = $task["task_parent_alternate_id"]; @@ -208,8 +206,7 @@ function constructGanttLine($tarr, $task, $task_dependencies, $level = 0, $proje // Define percent $percent = $task['task_percent_complete'] ? $task['task_percent_complete'] : 0; // Link (more information) - if ($task["task_id"] < 0) - { + if ($task["task_id"] < 0) { //$link=DOL_URL_ROOT.'/projet/tasks.php?withproject=1&id='.abs($task["task_id"]); $link = ''; } else { @@ -221,8 +218,8 @@ function constructGanttLine($tarr, $task, $task_dependencies, $level = 0, $proje $name = $task['task_name']; /*for($i=0; $i < $level; $i++) { - $name=' - '.$name; - }*/ + $name=' - '.$name; + }*/ // Add line to gantt /* g.AddTaskItem(new JSGantt.TaskItem(1, 'Define Chart API','', '', 'ggroupblack','', 0, 'Brian', 0, 1,0,1,'','','Some Notes text',g)); @@ -247,7 +244,7 @@ function constructGanttLine($tarr, $task, $task_dependencies, $level = 0, $proje <dt>pCaption</dt><dd>(optional) caption that will be added after task bar if CaptionType set to "Caption"</dd> <dt>pNotes</dt><dd>(optional) Detailed task information that will be displayed in tool tip for this task</dd> <dt>pGantt</dt><dd>(required) javascript JSGantt.GanttChart object from which to take settings. Defaults to &quot;g&quot; for backwards compatibility</dd> - */ + */ //$note=""; @@ -289,18 +286,16 @@ function findChildGanttLine($tarr, $parent, $task_dependencies, $level) $n = count($tarr); $old_parent_id = 0; - for ($x = 0; $x < $n; $x++) - { - if ($tarr[$x]["task_parent"] == $parent && $tarr[$x]["task_parent"] != $tarr[$x]["task_id"]) - { + for ($x = 0; $x < $n; $x++) { + if ($tarr[$x]["task_parent"] == $parent && $tarr[$x]["task_parent"] != $tarr[$x]["task_id"]) { // Create a grouping parent task for the new level /*if (empty($old_parent_id) || $old_parent_id != $tarr[$x]['task_project_id']) { $tmpt = array( - 'task_id'=> -98, 'task_name'=>'Level '.$level, 'task_resources'=>'', 'task_start_date'=>'', 'task_end_date'=>'', - 'task_is_group'=>1, 'task_css'=>'ggroupblack', 'task_milestone'=> 0, 'task_parent'=>$tarr[$x]["task_parent"], 'task_notes'=>''); - constructGanttLine($tasks, $tmpt, array(), 0, $tarr[$x]['task_project_id']); - $old_parent_id = $tarr[$x]['task_project_id']; + 'task_id'=> -98, 'task_name'=>'Level '.$level, 'task_resources'=>'', 'task_start_date'=>'', 'task_end_date'=>'', + 'task_is_group'=>1, 'task_css'=>'ggroupblack', 'task_milestone'=> 0, 'task_parent'=>$tarr[$x]["task_parent"], 'task_notes'=>''); + constructGanttLine($tasks, $tmpt, array(), 0, $tarr[$x]['task_project_id']); + $old_parent_id = $tarr[$x]['task_project_id']; }*/ constructGanttLine($tarr, $tarr[$x], $task_dependencies, $level, null); diff --git a/htdocs/projet/ganttview.php b/htdocs/projet/ganttview.php index 8b2f41554d3..b4dbc21e894 100644 --- a/htdocs/projet/ganttview.php +++ b/htdocs/projet/ganttview.php @@ -43,7 +43,9 @@ $mine = ($mode == 'mine' ? 1 : 0); $object = new Project($db); include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once -if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); +if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); +} // Security check $socid = 0; @@ -74,8 +76,7 @@ $task = new Task($db); $arrayofcss = array('/includes/jsgantt/jsgantt.css'); -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { $arrayofjs = array( '/includes/jsgantt/jsgantt.js', '/projet/jsgantt_language.js.php?lang='.$langs->defaultlang @@ -84,12 +85,13 @@ if (!empty($conf->use_javascript_ajax)) //$title=$langs->trans("Gantt").($object->ref?' - '.$object->ref.' '.$object->name:''); $title = $langs->trans("Gantt"); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = ($object->ref ? $object->ref.' '.$object->name.' - ' : '').$langs->trans("Gantt"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = ($object->ref ? $object->ref.' '.$object->name.' - ' : '').$langs->trans("Gantt"); +} $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos"; llxHeader("", $title, $help_url, '', 0, 0, $arrayofjs, $arrayofcss); -if (($id > 0 && is_numeric($id)) || !empty($ref)) -{ +if (($id > 0 && is_numeric($id)) || !empty($ref)) { // To verify role of users //$userAccess = $object->restrictedProjectArea($user,'read'); $userWrite = $object->restrictedProjectArea($user, 'write'); @@ -113,15 +115,13 @@ if (($id > 0 && is_numeric($id)) || !empty($ref)) // Title $morehtmlref .= $object->title; // Thirdparty - if ($object->thirdparty->id > 0) - { + if ($object->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); $object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -140,22 +140,19 @@ if (($id > 0 && is_numeric($id)) || !empty($ref)) print $langs->trans("Usage"); print '</td>'; print '<td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } - if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); @@ -165,8 +162,11 @@ if (($id > 0 && is_numeric($id)) || !empty($ref)) // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; - if ($object->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); + if ($object->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } print '</td></tr>'; // Date start - end @@ -176,12 +176,16 @@ if (($id > 0 && is_numeric($id)) || !empty($ref)) $end = dol_print_date($object->date_end, 'day'); print ' - '; print ($end ? $end : '?'); - if ($object->hasDelay()) print img_warning("Late"); + if ($object->hasDelay()) { + print img_warning("Late"); + } print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; - if (strcmp($object->budget_amount, '')) print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + if (strcmp($object->budget_amount, '')) { + print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + } print '</td></tr>'; // Other attributes @@ -252,8 +256,7 @@ $tasksarray = $task->getTasksArray(0, 0, ($object->id ? $object->id : $id), $soc //var_dump($tasksrole); -if (count($tasksarray) > 0) -{ +if (count($tasksarray) > 0) { // Show Gant diagram from $taskarray using JSGantt $dateformat = $langs->trans("FormatDateShortJQuery"); // Used by include ganttchart.inc.php later @@ -262,8 +265,7 @@ if (count($tasksarray) > 0) $tasks = array(); $task_dependencies = array(); $taskcursor = 0; - foreach ($tasksarray as $key => $val) // Task array are sorted by "project, position, date" - { + foreach ($tasksarray as $key => $val) { // Task array are sorted by "project, position, date" $task->fetch($val->id, ''); $idparent = ($val->fk_parent ? $val->fk_parent : '-'.$val->fk_project); // If start with -, id is a project id @@ -299,34 +301,34 @@ if (count($tasksarray) > 0) $idofusers = $task->getListContactId('internal'); $idofcontacts = $task->getListContactId('external'); - $s = ''; - if (count($idofusers) > 0) - { + $s = ''; + if (count($idofusers) > 0) { $s .= $langs->trans("Internals").': '; $i = 0; - foreach ($idofusers as $valid) - { + foreach ($idofusers as $valid) { $userstatic->fetch($valid); - if ($i) $s .= ', '; + if ($i) { + $s .= ', '; + } $s .= $userstatic->login; $i++; } } //if (count($idofusers)>0 && (count($idofcontacts)>0)) $s.=' - '; - if (count($idofcontacts) > 0) - { - if ($s) $s .= ' - '; + if (count($idofcontacts) > 0) { + if ($s) { + $s .= ' - '; + } $s .= $langs->trans("Externals").': '; $i = 0; $contactidfound = array(); - foreach ($idofcontacts as $valid) - { - if (empty($contactidfound[$valid])) - { + foreach ($idofcontacts as $valid) { + if (empty($contactidfound[$valid])) { $res = $contactstatic->fetch($valid); - if ($res > 0) - { - if ($i) $s .= ', '; + if ($res > 0) { + if ($i) { + $s .= ', '; + } $s .= $contactstatic->getFullName($langs); $contactidfound[$valid] = 1; $i++; @@ -338,30 +340,30 @@ if (count($tasksarray) > 0) /* For JSGanttImproved */ //if ($s) $tasks[$taskcursor]['task_resources']=implode(',',$idofusers); $tasks[$taskcursor]['task_resources'] = $s; - if ($s) $tasks[$taskcursor]['task_resources'] = '<a href="'.DOL_URL_ROOT.'/projet/tasks/contact.php?id='.$val->id.'&withproject=1" title="'.dol_escape_htmltag($s).'">'.$langs->trans("List").'</a>'; + if ($s) { + $tasks[$taskcursor]['task_resources'] = '<a href="'.DOL_URL_ROOT.'/projet/tasks/contact.php?id='.$val->id.'&withproject=1" title="'.dol_escape_htmltag($s).'">'.$langs->trans("List").'</a>'; + } //print "xxx".$val->id.$tasks[$taskcursor]['task_resources']; $tasks[$taskcursor]['note'] = $task->note_public; $taskcursor++; } // Search parent to set task_parent_alternate_id (requird by ganttchart) - foreach ($tasks as $tmpkey => $tmptask) - { - foreach ($tasks as $tmptask2) - { - if ($tmptask2['task_id'] == $tmptask['task_parent']) - { + foreach ($tasks as $tmpkey => $tmptask) { + foreach ($tasks as $tmptask2) { + if ($tmptask2['task_id'] == $tmptask['task_parent']) { $tasks[$tmpkey]['task_parent_alternate_id'] = $tmptask2['task_alternate_id']; break; } } - if (empty($tasks[$tmpkey]['task_parent_alternate_id'])) $tasks[$tmpkey]['task_parent_alternate_id'] = $tasks[$tmpkey]['task_parent']; + if (empty($tasks[$tmpkey]['task_parent_alternate_id'])) { + $tasks[$tmpkey]['task_parent_alternate_id'] = $tasks[$tmpkey]['task_parent']; + } } print "\n"; - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { //var_dump($_SESSION); // How the date for data are formated (format used bu jsgantt) @@ -369,7 +371,7 @@ if (count($tasksarray) > 0) // How the date for data are formated (format used by dol_print_date) $dateformatinput2 = 'standard'; //var_dump($dateformatinput); - //var_dump($dateformatinput2); + //var_dump($dateformatinput2); $moreforfilter = '<div class="liste_titre liste_titre_bydiv centpercent">'; diff --git a/htdocs/projet/graph_opportunities.inc.php b/htdocs/projet/graph_opportunities.inc.php index 66b04527772..cf8cc1dd34d 100644 --- a/htdocs/projet/graph_opportunities.inc.php +++ b/htdocs/projet/graph_opportunities.inc.php @@ -17,22 +17,25 @@ // variable $listofopplabel and $listofoppstatus should be defined -if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) -{ +if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { $sql = "SELECT p.fk_opp_status as opp_status, cls.code, COUNT(p.rowid) as nb, SUM(p.opp_amount) as opp_amount, SUM(p.opp_amount * p.opp_percent) as ponderated_opp_amount"; $sql .= " FROM ".MAIN_DB_PREFIX."projet as p LEFT JOIN ".MAIN_DB_PREFIX."c_lead_status as cls ON p.fk_opp_status = cls.rowid"; // If lead status has been removed, we must show it in stats as unknown $sql .= " WHERE p.entity IN (".getEntity('project').")"; $sql .= " AND p.fk_statut = 1"; // Opend projects only - if ($mine || empty($user->rights->projet->all->lire)) $sql .= " AND p.rowid IN (".$projectsListId.")"; - if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + if ($mine || empty($user->rights->projet->all->lire)) { + $sql .= " AND p.rowid IN (".$projectsListId.")"; + } + if ($socid) { + $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + } $sql .= " GROUP BY p.fk_opp_status, cls.code"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; + $total = 0; $totalnb = 0; $totaloppnb = 0; $totalamount = 0; @@ -41,15 +44,15 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $valsamount = array(); $dataseries = array(); // -1=Canceled, 0=Draft, 1=Validated, (2=Accepted/On process not managed for customer orders), 3=Closed (Sent/Received, billed or not) - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $valsnb[$obj->opp_status] = $obj->nb; $valsamount[$obj->opp_status] = $obj->opp_amount; $totalnb += $obj->nb; - if ($obj->opp_status) $totaloppnb += $obj->nb; + if ($obj->opp_status) { + $totaloppnb += $obj->nb; + } if (!in_array($obj->code, array('WON', 'LOST'))) { $totalamount += $obj->opp_amount; $ponderated_opp_amount += $obj->ponderated_opp_amount; @@ -63,40 +66,43 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $ponderated_opp_amount = $ponderated_opp_amount / 100; print '<div class="div-table-responsive-no-min">'; - print '<table class="noborder nohover centpercent">'; - print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("OpportunitiesStatusForOpenedProjects").'</th></tr>'."\n"; + print '<table class="noborder nohover centpercent">'; + print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("OpportunitiesStatusForOpenedProjects").'</th></tr>'."\n"; - $listofstatus = array_keys($listofoppstatus); + $listofstatus = array_keys($listofoppstatus); // Complete with values found into database and not into the dictionary - foreach ($valsamount as $key => $val) { - if (!in_array($key, $listofstatus) && $key) { - $listofstatus[] = $key; - } - } + foreach ($valsamount as $key => $val) { + if (!in_array($key, $listofstatus) && $key) { + $listofstatus[] = $key; + } + } - foreach ($listofstatus as $status) - { - $labelStatus = ''; + foreach ($listofstatus as $status) { + $labelStatus = ''; $code = dol_getIdFromCode($db, $status, 'c_lead_status', 'rowid', 'code'); - if ($code) $labelStatus = $langs->transnoentitiesnoconv("OppStatus".$code); - if (empty($labelStatus)) $labelStatus = $listofopplabel[$status]; - if (empty($labelStatus)) $labelStatus = $langs->transnoentitiesnoconv('OldValue', $status); // When id is id of an entry no more in dictionary for example. + if ($code) { + $labelStatus = $langs->transnoentitiesnoconv("OppStatus".$code); + } + if (empty($labelStatus)) { + $labelStatus = $listofopplabel[$status]; + } + if (empty($labelStatus)) { + $labelStatus = $langs->transnoentitiesnoconv('OldValue', $status); // When id is id of an entry no more in dictionary for example. + } //$labelStatus .= ' ('.$langs->trans("Coeff").': '.price2num($listofoppstatus[$status]).')'; //$labelStatus .= ' - '.price2num($listofoppstatus[$status]).'%'; $dataseries[] = array($labelStatus, (isset($valsamount[$status]) ? (float) $valsamount[$status] : 0)); - if (!$conf->use_javascript_ajax) - { + if (!$conf->use_javascript_ajax) { print '<tr class="oddeven">'; print '<td>'.$labelStatus.'</td>'; print '<td class="right"><a href="list.php?statut='.$status.'">'.price((isset($valsamount[$status]) ? (float) $valsamount[$status] : 0), 0, '', 1, -1, -1, $conf->currency).'</a></td>'; print "</tr>\n"; } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<tr><td class="center nopaddingleftimp nopaddingrightimp" colspan="2">'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; diff --git a/htdocs/projet/index.php b/htdocs/projet/index.php index f2b1820c019..600a246cf94 100644 --- a/htdocs/projet/index.php +++ b/htdocs/projet/index.php @@ -42,13 +42,19 @@ $langs->loadLangs(array('projects', 'companies')); $action = GETPOST('action', 'aZ09'); $search_project_user = GETPOST('search_project_user', 'int'); $mine = GETPOST('mode', 'aZ09') == 'mine' ? 1 : 0; -if ($mine == 0 && $search_project_user === '') $search_project_user = $user->conf->MAIN_SEARCH_PROJECT_USER_PROJECTSINDEX; -if ($search_project_user == $user->id) $mine = 1; +if ($mine == 0 && $search_project_user === '') { + $search_project_user = (empty($user->conf->MAIN_SEARCH_PROJECT_USER_PROJECTSINDEX) ? '' : $user->conf->MAIN_SEARCH_PROJECT_USER_PROJECTSINDEX); +} +if ($search_project_user == $user->id) { + $mine = 1; +} // Security check $socid = 0; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. -if (!$user->rights->projet->lire) accessforbidden(); +if (!$user->rights->projet->lire) { + accessforbidden(); +} $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); @@ -62,7 +68,9 @@ $max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; $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 == 'refresh_search_project_user') { $search_project_user = GETPOST('search_project_user', 'int'); @@ -95,8 +103,11 @@ $title = $langs->trans("ProjectsArea"); // Title for combo list see all projects $titleall = $langs->trans("AllAllowedProjects"); -if (!empty($user->rights->projet->all->lire) && !$socid) $titleall = $langs->trans("AllProjects"); -else $titleall = $langs->trans("AllAllowedProjects").'<br><br>'; +if (!empty($user->rights->projet->all->lire) && !$socid) { + $titleall = $langs->trans("AllProjects"); +} else { + $titleall = $langs->trans("AllAllowedProjects").'<br><br>'; +} $morehtml = ''; $morehtml .= '<form name="projectform" method="POST">'; @@ -109,10 +120,14 @@ $morehtml .= '</SELECT>'; $morehtml .= '<input type="submit" class="button smallpaddingimp" name="refresh" value="'.$langs->trans("Refresh").'">'; $morehtml .= '</form>'; -if ($mine) $tooltiphelp = $langs->trans("MyProjectsDesc"); -else { - if (!empty($user->rights->projet->all->lire) && !$socid) $tooltiphelp = $langs->trans("ProjectsDesc"); - else $tooltiphelp = $langs->trans("ProjectsPublicDesc"); +if ($mine) { + $tooltiphelp = $langs->trans("MyProjectsDesc"); +} else { + if (!empty($user->rights->projet->all->lire) && !$socid) { + $tooltiphelp = $langs->trans("ProjectsDesc"); + } else { + $tooltiphelp = $langs->trans("ProjectsPublicDesc"); + } } print_barre_liste($form->textwithpicto($title, $tooltiphelp), 0, $_SERVER["PHP_SELF"], '', '', '', '', 0, -1, 'project', 0, $morehtml); @@ -125,13 +140,11 @@ $sql = "SELECT cls.rowid, cls.code, cls.percent, cls.label"; $sql .= " FROM ".MAIN_DB_PREFIX."c_lead_status as cls"; $sql .= " WHERE active=1"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $listofoppstatus[$objp->rowid] = $objp->percent; $listofopplabel[$objp->rowid] = $objp->label; @@ -161,34 +174,36 @@ if ($resql) } $i++; } -} else dol_print_error($db); +} else { + dol_print_error($db); +} //var_dump($listofoppcode); print '<div class="fichecenter"><div class="fichethirdleft">'; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo // Search project - if (!empty($conf->projet->enabled) && $user->rights->projet->lire) - { + if (!empty($conf->projet->enabled) && $user->rights->projet->lire) { $listofsearchfields['search_project'] = array('text'=>'Project'); } - if (count($listofsearchfields)) - { + if (count($listofsearchfields)) { print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<div class="div-table-responsive-no-min">'; print '<table class="noborder nohover centpercent">'; $i = 0; - foreach ($listofsearchfields as $key => $value) - { - if ($i == 0) print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>'; + foreach ($listofsearchfields as $key => $value) { + if ($i == 0) { + print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>'; + } print '<tr>'; print '<td class="nowrap"><label for="'.$key.'">'.$langs->trans($value["text"]).'</label></td><td><input type="text" class="flat inputsearch" name="'.$key.'" id="'.$key.'" size="18"></td>'; - if ($i == 0) print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>'; + if ($i == 0) { + print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>'; + } print '</tr>'; $i++; } @@ -222,14 +237,17 @@ $sql .= ", s.canvas, s.status as thirdpartystatus"; $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; $sql .= " WHERE p.entity IN (".getEntity('project').")"; -if ($mine || empty($user->rights->projet->all->lire)) $sql .= " AND p.rowid IN (".$projectsListId.")"; // If we have this test true, it also means projectset is not 2 -if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; +if ($mine || empty($user->rights->projet->all->lire)) { + $sql .= " AND p.rowid IN (".$projectsListId.")"; // If we have this test true, it also means projectset is not 2 +} +if ($socid) { + $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; +} $sql .= " ORDER BY p.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; @@ -238,11 +256,9 @@ if ($resql) $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -290,8 +306,7 @@ if ($resql) print '</td>'; print '<td class="nowrap">'; - if ($companystatic->id > 0) - { + if ($companystatic->id > 0) { print $companystatic->getNomUrl(1, 'company', 16); } print '</td>'; @@ -304,7 +319,9 @@ if ($resql) print '<tr><td colspan="4"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>'; } print "</table></div>"; -} else dol_print_error($db); +} else { + dol_print_error($db); +} $companystatic = new Societe($db); // We need a clean new object for next loop because current one has some properties set. @@ -320,15 +337,18 @@ $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; $sql .= " WHERE p.entity IN (".getEntity('project').")"; $sql .= " AND p.fk_statut = 1"; -if ($mine || empty($user->rights->projet->all->lire)) $sql .= " AND p.rowid IN (".$projectsListId.")"; // If we have this test true, it also means projectset is not 2 -if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; +if ($mine || empty($user->rights->projet->all->lire)) { + $sql .= " AND p.rowid IN (".$projectsListId.")"; // If we have this test true, it also means projectset is not 2 +} +if ($socid) { + $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; +} $sql .= " GROUP BY s.rowid, s.nom, s.name_alias, s.code_client, s.code_compta, s.client, s.code_fournisseur, s.code_compta_fournisseur, s.fournisseur, s.logo, s.email, s.entity, s.canvas, s.status"; $sql .= $db->order($sortfield, $sortorder); //$sql .= $db->plimit($max + 1, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; $othernb = 0; @@ -345,8 +365,7 @@ if ($resql) print "</tr>\n"; } - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); if ($i >= $max) { @@ -357,8 +376,7 @@ if ($resql) print '<tr class="oddeven">'; print '<td class="nowraponall tdoverflowmax100">'; - if ($obj->socid > 0) - { + if ($obj->socid > 0) { $companystatic->id = $obj->socid; $companystatic->name = $obj->name; $companystatic->name_alias = $obj->name_alias; @@ -380,8 +398,11 @@ if ($resql) } print '</td>'; print '<td class="right">'; - if ($obj->socid) print '<a href="'.DOL_URL_ROOT.'/projet/list.php?socid='.$obj->socid.'&search_status=1">'.$obj->nb.'</a>'; - else print '<a href="'.DOL_URL_ROOT.'/projet/list.php?search_societe='.urlencode('^$').'&search_status=1">'.$obj->nb.'</a>'; + if ($obj->socid) { + print '<a href="'.DOL_URL_ROOT.'/projet/list.php?socid='.$obj->socid.'&search_status=1">'.$obj->nb.'</a>'; + } else { + print '<a href="'.DOL_URL_ROOT.'/projet/list.php?search_societe='.urlencode('^$').'&search_status=1">'.$obj->nb.'</a>'; + } print '</td>'; print "</tr>\n"; @@ -408,8 +429,7 @@ if ($resql) dol_print_error($db); } -if (empty($conf->global->PROJECT_HIDE_PROJECT_LIST_ON_PROJECT_AREA)) -{ +if (empty($conf->global->PROJECT_HIDE_PROJECT_LIST_ON_PROJECT_AREA)) { // This list can be very long, so we allow to hide it to prefer to use the list page. // Add constant PROJECT_HIDE_PROJECT_LIST_ON_PROJECT_AREA to hide this list diff --git a/htdocs/projet/info.php b/htdocs/projet/info.php index e87aa25dadb..d99da02caa6 100644 --- a/htdocs/projet/info.php +++ b/htdocs/projet/info.php @@ -42,16 +42,21 @@ $sortorder = GETPOST("sortorder", 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = is_numeric($page) ? $page : 0; $page = $page == -1 ? 0 : $page; -if (!$sortfield) $sortfield = "a.datep,a.id"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "a.datep,a.id"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (GETPOST('actioncode', 'array')) -{ +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)); } @@ -63,7 +68,9 @@ $socid = 0; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. $result = restrictedArea($user, 'projet', $id, 'projet&project'); -if (!$user->rights->projet->lire) accessforbidden(); +if (!$user->rights->projet->lire) { + accessforbidden(); +} @@ -73,11 +80,12 @@ if (!$user->rights->projet->lire) accessforbidden(); $parameters = array('id'=>$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'); +} // Purge search criteria -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers $actioncode = ''; $search_agenda_label = ''; } @@ -91,16 +99,19 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $form = new Form($db); $object = new Project($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch($id, $ref); $object->fetch_thirdparty(); - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); + } $object->info($object->id); } $title = $langs->trans("Project").' - '.$object->ref.' '.$object->name; -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Info"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->ref.' '.$object->name.' - '.$langs->trans("Info"); +} $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos"; llxHeader("", $title, $help_url); @@ -117,15 +128,13 @@ $morehtmlref = '<div class="refidno">'; // Title $morehtmlref .= $object->title; // Thirdparty -if ($object->thirdparty->id > 0) -{ +if ($object->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. -if (!$user->rights->projet->all->lire) -{ +if (!$user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); $object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -149,29 +158,30 @@ print dol_get_fiche_end(); $out = ''; $permok = $user->rights->agenda->myactions->create; -if ($permok) -{ +if ($permok) { $out .= '&projectid='.$object->id; } //print '<div class="tabsAction">'; $morehtmlcenter = ''; -if (!empty($conf->agenda->enabled)) -{ +if (!empty($conf->agenda->enabled)) { $addActionBtnRight = !empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create); - $morehtmlcenter .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'&socid='.$object->socid.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id), '', $addActionBtnRight); + $morehtmlcenter .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'&socid='.$object->socid.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id), '', $addActionBtnRight); } //print '</div>'; -if (!empty($object->id)) -{ +if (!empty($object->id)) { print '<br>'; $param = '&id='.$object->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("ActionsOnProject"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $morehtmlcenter, '', 0, 1, 1); diff --git a/htdocs/projet/jsgantt_language.js.php b/htdocs/projet/jsgantt_language.js.php index 41fcd1934ae..35ab1132ae7 100644 --- a/htdocs/projet/jsgantt_language.js.php +++ b/htdocs/projet/jsgantt_language.js.php @@ -20,13 +20,27 @@ * \brief Fichier de javascript de traduction pour JSGantt */ -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); -if (!defined('NOLOGIN')) define('NOLOGIN', 1); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', 1); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', 1); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', 1); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', 1); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', 1); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} require_once __DIR__.'/../main.inc.php'; @@ -40,20 +54,22 @@ $langs->load("projects"); var vLangs={'<?php print $langs->getDefaultLang(1); ?>': { 'format':'<?php print $langs->transnoentities('Period'); ?>','hour':'"<?php print $langs->transnoentities('Hour'); ?>','day':'<?php print $langs->transnoentities('Day'); ?>', - 'week':'<?php print $langs->transnoentities('Week'); ?>','month':'<?php print $langs->transnoentities('Month'); ?>','quarter':'<?php print $langs->transnoentities('Quadri'); ?>', - 'hours':'<?php print $langs->transnoentities('Hours'); ?>','days':'<?php print $langs->transnoentities('Days'); ?>','weeks':'<?php print $langs->transnoentities('Weeks'); ?>', - 'months':'<?php print $langs->transnoentities('Months'); ?>','quarters':'<?php print $langs->transnoentities('Quadri'); ?>','hr':'Hr','dy':'<?php print $langs->transnoentities('Day'); ?>','wk':'<?php print $langs->transnoentities('Week'); ?>','mth':'<?php print $langs->transnoentities('Month'); ?>','qtr':'<?php print $langs->transnoentities('Quadri'); ?>','hrs':'<?php print $langs->transnoentities('Hours'); ?>', - 'dys':'<?php print $langs->transnoentities('Days'); ?>','wks':'<?php print $langs->transnoentities('Weeks'); ?>','mths':'<?php print $langs->transnoentities('Months'); ?>','qtrs':'<?php print $langs->transnoentities('Quadri'); ?>','resource':'<?php print dol_escape_js($langs->transnoentities('Resource')); ?>','duration':'<?php print dol_escape_js($langs->transnoentities('Duration')); ?>','comp':'%', - 'completion':'<?php print $langs->transnoentities('Total'); ?>','startdate':'<?php print $langs->transnoentities('DateStart'); ?>','enddate':'<?php print $langs->transnoentities('DateEnd'); ?>','moreinfo':'<?php print dol_escape_js($langs->transnoentities('ShowTask')); ?>', - 'notes':'<?php print $langs->transnoentities('NotePublic'); ?>', - 'january':'<?php print $langs->transnoentities('January'); ?>','february':'<?php print $langs->transnoentities('February'); ?>','march':'<?php print $langs->transnoentities('March'); ?>','april':'<?php print $langs->transnoentities('April'); ?>','maylong':'<?php print $langs->transnoentities('May'); ?>','june':'<?php print $langs->transnoentities('June'); ?>','july':'<?php print $langs->transnoentities('July'); ?>', - 'august':'<?php print $langs->transnoentities('August'); ?>','september':'<?php print $langs->transnoentities('September'); ?>','october':'<?php print $langs->transnoentities('October'); ?>','november':'<?php print $langs->transnoentities('November'); ?>','december':'<?php print $langs->transnoentities('December'); ?>', - 'jan':'<?php print $langs->transnoentities('MonthShort01'); ?>','feb':'<?php print $langs->transnoentities('MonthShort02'); ?>','mar':'<?php print $langs->transnoentities('MonthShort03'); ?>','apr':'<?php print $langs->transnoentities('MonthShort04'); ?>','may':'<?php print $langs->transnoentities('MonthShort05'); ?>','jun':'<?php print $langs->transnoentities('MonthShort06'); ?>','jul':'<?php print $langs->transnoentities('MonthShort07'); ?>', - 'aug':'<?php print $langs->transnoentities('MonthShort08'); ?>','sep':'<?php print $langs->transnoentities('MonthShort09'); ?>','oct':'<?php print $langs->transnoentities('MonthShort10'); ?>','nov':'<?php print $langs->transnoentities('MonthShort11'); ?>','dec':'<?php print $langs->transnoentities('MonthShort12'); ?>', - 'sunday':'<?php print $langs->transnoentities('Sunday'); ?>','monday':'<?php print $langs->transnoentities('Monday'); ?>','tuesday':'<?php print $langs->transnoentities('Tuesday'); ?>','wednesday':'<?php print $langs->transnoentities('Wednesday'); ?>','thursday':'<?php print $langs->transnoentities('Thursday'); ?>','friday':'<?php print $langs->transnoentities('Friday'); ?>','saturday':'<?php print $langs->transnoentities('Saturday'); ?>', - 'sun':'<?php print $langs->transnoentities('SundayMin'); ?>','mon':'<?php print $langs->transnoentities('MondayMin'); ?>','tue':'<?php print $langs->transnoentities('TuesdayMin'); ?>','wed':'<?php print $langs->transnoentities('WednesdayMin'); ?>','thu':'<?php print $langs->transnoentities('ThursdayMin'); ?>','fri':'<?php print $langs->transnoentities('FridayMin'); ?>','sat':'<?php print $langs->transnoentities('SaturdayMin'); ?>' - } + 'week':'<?php print $langs->transnoentities('Week'); ?>','month':'<?php print $langs->transnoentities('Month'); ?>','quarter':'<?php print $langs->transnoentities('Quadri'); ?>', + 'hours':'<?php print $langs->transnoentities('Hours'); ?>','days':'<?php print $langs->transnoentities('Days'); ?>','weeks':'<?php print $langs->transnoentities('Weeks'); ?>', + 'months':'<?php print $langs->transnoentities('Months'); ?>','quarters':'<?php print $langs->transnoentities('Quadri'); ?>','hr':'Hr','dy':'<?php print $langs->transnoentities('Day'); ?>','wk':'<?php print $langs->transnoentities('Week'); ?>','mth':'<?php print $langs->transnoentities('Month'); ?>','qtr':'<?php print $langs->transnoentities('Quadri'); ?>','hrs':'<?php print $langs->transnoentities('Hours'); ?>', + 'dys':'<?php print $langs->transnoentities('Days'); ?>','wks':'<?php print $langs->transnoentities('Weeks'); ?>','mths':'<?php print $langs->transnoentities('Months'); ?>','qtrs':'<?php print $langs->transnoentities('Quadri'); ?>','resource':'<?php print dol_escape_js($langs->transnoentities('Resource')); ?>','duration':'<?php print dol_escape_js($langs->transnoentities('Duration')); ?>','comp':'%', + 'completion':'<?php print $langs->transnoentities('Total'); ?>','startdate':'<?php print $langs->transnoentities('DateStart'); ?>','enddate':'<?php print $langs->transnoentities('DateEnd'); ?>','moreinfo':'<?php print dol_escape_js($langs->transnoentities('ShowTask')); ?>', + 'notes':'<?php print $langs->transnoentities('NotePublic'); ?>', + 'january':'<?php print $langs->transnoentities('January'); ?>','february':'<?php print $langs->transnoentities('February'); ?>','march':'<?php print $langs->transnoentities('March'); ?>','april':'<?php print $langs->transnoentities('April'); ?>','maylong':'<?php print $langs->transnoentities('May'); ?>','june':'<?php print $langs->transnoentities('June'); ?>','july':'<?php print $langs->transnoentities('July'); ?>', + 'august':'<?php print $langs->transnoentities('August'); ?>','september':'<?php print $langs->transnoentities('September'); ?>','october':'<?php print $langs->transnoentities('October'); ?>','november':'<?php print $langs->transnoentities('November'); ?>','december':'<?php print $langs->transnoentities('December'); ?>', + 'jan':'<?php print $langs->transnoentities('MonthShort01'); ?>','feb':'<?php print $langs->transnoentities('MonthShort02'); ?>','mar':'<?php print $langs->transnoentities('MonthShort03'); ?>','apr':'<?php print $langs->transnoentities('MonthShort04'); ?>','may':'<?php print $langs->transnoentities('MonthShort05'); ?>','jun':'<?php print $langs->transnoentities('MonthShort06'); ?>','jul':'<?php print $langs->transnoentities('MonthShort07'); ?>', + 'aug':'<?php print $langs->transnoentities('MonthShort08'); ?>','sep':'<?php print $langs->transnoentities('MonthShort09'); ?>','oct':'<?php print $langs->transnoentities('MonthShort10'); ?>','nov':'<?php print $langs->transnoentities('MonthShort11'); ?>','dec':'<?php print $langs->transnoentities('MonthShort12'); ?>', + 'sunday':'<?php print $langs->transnoentities('Sunday'); ?>','monday':'<?php print $langs->transnoentities('Monday'); ?>','tuesday':'<?php print $langs->transnoentities('Tuesday'); ?>','wednesday':'<?php print $langs->transnoentities('Wednesday'); ?>','thursday':'<?php print $langs->transnoentities('Thursday'); ?>','friday':'<?php print $langs->transnoentities('Friday'); ?>','saturday':'<?php print $langs->transnoentities('Saturday'); ?>', + 'sun':'<?php print $langs->transnoentities('SundayMin'); ?>','mon':'<?php print $langs->transnoentities('MondayMin'); ?>','tue':'<?php print $langs->transnoentities('TuesdayMin'); ?>','wed':'<?php print $langs->transnoentities('WednesdayMin'); ?>','thu':'<?php print $langs->transnoentities('ThursdayMin'); ?>','fri':'<?php print $langs->transnoentities('FridayMin'); ?>','sat':'<?php print $langs->transnoentities('SaturdayMin'); ?>' + } }; var vLang='<?php print $langs->getDefaultLang(1); ?>'; <?php -if (is_object($db)) $db->close(); +if (is_object($db)) { + $db->close(); +} diff --git a/htdocs/projet/list.php b/htdocs/projet/list.php index ad8418dfc0e..e6b381a6650 100644 --- a/htdocs/projet/list.php +++ b/htdocs/projet/list.php @@ -35,14 +35,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; -if (!empty($conf->categorie->enabled)) -{ +if (!empty($conf->categorie->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcategory.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; } // Load translation files required by the page $langs->loadLangs(array('projects', 'companies', 'commercial')); +if ($conf->eventorganization->enabled) { + $langs->loadLangs(array('eventorganization')); +} $action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); @@ -56,13 +58,14 @@ $title = $langs->trans("Projects"); // Security check $socid = (is_numeric($_GET["socid"]) ? $_GET["socid"] : 0); //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. -if ($socid > 0) -{ +if ($socid > 0) { $soc = new Societe($db); $soc->fetch($socid); $title .= ' (<a href="list.php">'.$soc->name.'</a>)'; } -if (!$user->rights->projet->lire) accessforbidden(); +if (!$user->rights->projet->lire) { + accessforbidden(); +} $diroutputmassaction = $conf->projet->dir_output.'/temp/massgeneration/'.$user->id; @@ -70,9 +73,15 @@ $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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters -if (!$sortfield) $sortfield = "p.ref"; -if (!$sortorder) $sortorder = "ASC"; +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters +if (!$sortfield) { + $sortfield = "p.ref"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -92,10 +101,17 @@ $search_sale = GETPOST('search_sale', 'int'); $search_usage_opportunity = GETPOST('search_usage_opportunity', 'int'); $search_usage_task = GETPOST('search_usage_task', 'int'); $search_usage_bill_time = GETPOST('search_usage_bill_time', 'int'); +$search_usage_event_organization = GETPOST('search_usage_event_organization', 'int'); +$search_accept_conference_suggestions = GETPOST('search_accept_conference_suggestions', 'int'); +$search_accept_booth_suggestions = GETPOST('search_accept_booth_suggestions', 'int'); +$search_price_registration = GETPOST("search_price_registration", 'alpha'); +$search_price_booth = GETPOST("search_price_booth", 'alpha'); $optioncss = GETPOST('optioncss', 'alpha'); $mine = $_REQUEST['mode'] == 'mine' ? 1 : 0; -if ($mine) { $search_project_user = $user->id; $mine = 0; } +if ($mine) { + $search_project_user = $user->id; $mine = 0; +} $search_sday = GETPOST('search_sday', 'int'); $search_smonth = GETPOST('search_smonth', 'int'); @@ -104,10 +120,11 @@ $search_eday = GETPOST('search_eday', 'int'); $search_emonth = GETPOST('search_emonth', 'int'); $search_eyear = GETPOST('search_eyear', 'int'); -if ($search_status == '') $search_status = -1; // -1 or 1 +if ($search_status == '') { + $search_status = -1; // -1 or 1 +} -if (!empty($conf->categorie->enabled)) -{ +if (!empty($conf->categorie->enabled)) { $search_category_array = GETPOST("search_category_".Categorie::TYPE_PROJECT."_list", "array"); } @@ -171,21 +188,25 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * 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)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_all = ''; $search_ref = ""; $search_label = ""; @@ -207,6 +228,11 @@ if (empty($reshook)) $search_usage_opportunity = ''; $search_usage_task = ''; $search_usage_bill_time = ''; + $search_usage_event_organization = ''; + $search_accept_conference_suggestions = ''; + $search_accept_booth_suggestions = ''; + $search_price_registration = ''; + $search_price_booth = ''; $toselect = ''; $search_array_options = array(); $search_category_array = array(); @@ -223,17 +249,14 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; // Close records - if (!$error && $massaction == 'close' && $user->rights->projet->creer) - { + if (!$error && $massaction == 'close' && $user->rights->projet->creer) { $db->begin(); $objecttmp = new $objectclass($db); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $userWrite = $object->restrictedProjectArea($user, 'write'); if ($userWrite > 0 && $objecttmp->statut == 1) { $result = $objecttmp->setClose($user); @@ -241,7 +264,9 @@ if (empty($reshook)) setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } elseif ($userWrite <= 0) { setEventMessages($langs->trans("DontHavePermissionForCloseProject", $objecttmp->ref), null, 'warnings'); } else { @@ -254,10 +279,12 @@ if (empty($reshook)) } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsClosed", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsClosed", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsClosed", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsClosed", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -281,7 +308,9 @@ $title = $langs->trans("Projects"); // Get list of project id allowed to user (in a string list separated by comma) $projectsListId = ''; -if (!$user->rights->projet->all->lire) $projectsListId = $object->getProjectsAuthorizedForUser($user, 0, 1, $socid); +if (!$user->rights->projet->all->lire) { + $projectsListId = $object->getProjectsAuthorizedForUser($user, 0, 1, $socid); +} // Get id of types of contacts for projects (This list never contains a lot of elements) $listofprojectcontacttype = array(); @@ -289,23 +318,29 @@ $sql = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc" $sql .= " WHERE ctc.element = '".$db->escape($object->element)."'"; $sql .= " AND ctc.source = 'internal'"; $resql = $db->query($sql); -if ($resql) -{ - while ($obj = $db->fetch_object($resql)) - { +if ($resql) { + while ($obj = $db->fetch_object($resql)) { $listofprojectcontacttype[$obj->rowid] = $obj->code; } -} else dol_print_error($db); -if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0] = '0'; // To avoid sql syntax error if not found +} else { + dol_print_error($db); +} +if (count($listofprojectcontacttype) == 0) { + $listofprojectcontacttype[0] = '0'; // To avoid sql syntax error if not found +} $distinct = 'DISTINCT'; // We add distinct until we are added a protection to be sure a contact of a project and task is only once. $sql = "SELECT ".$distinct." p.rowid as id, p.ref, p.title, p.fk_statut as status, p.fk_opp_status, p.public, p.fk_user_creat"; -$sql .= ", p.datec as date_creation, p.dateo as date_start, p.datee as date_end, p.opp_amount, p.opp_percent, (p.opp_amount*p.opp_percent/100) as opp_weighted_amount, p.tms as date_update, p.budget_amount, p.usage_opportunity, p.usage_task, p.usage_bill_time"; +$sql .= ", p.datec as date_creation, p.dateo as date_start, p.datee as date_end, p.opp_amount, p.opp_percent, (p.opp_amount*p.opp_percent/100) as opp_weighted_amount, p.tms as date_update, p.budget_amount "; +$sql .= ", p.usage_opportunity, p.usage_task, p.usage_bill_time, p.usage_organize_event"; +$sql .= ", accept_conference_suggestions, accept_booth_suggestions, price_registration, price_booth"; $sql .= ", s.rowid as socid, s.nom as name, s.email"; $sql .= ", cls.code as opp_status_code"; // 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 : ''); + 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(); @@ -313,62 +348,121 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as p"; -if (!empty($conf->categorie->enabled)) -{ +if (!empty($conf->categorie->enabled)) { $sql .= Categorie::getFilterJoinQuery(Categorie::TYPE_PROJECT, "p.rowid"); } -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (p.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (p.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_lead_status as cls on p.fk_opp_status = cls.rowid"; // We'll need this table joined to the select in order to filter by sale // No check is done on company permission because readability is managed by public status of project and assignement. //if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid"; -if ($search_sale > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid"; -if ($search_project_user > 0) -{ +if ($search_sale > 0) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid"; +} +if ($search_project_user > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ecp"; } $sql .= " WHERE p.entity IN (".getEntity('project').')'; -if (!empty($conf->categorie->enabled)) -{ +if (!empty($conf->categorie->enabled)) { $sql .= Categorie::getFilterSelectQuery(Categorie::TYPE_PROJECT, "p.rowid", $search_category_array); } -if (!$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users +if (!$user->rights->projet->all->lire) { + $sql .= " AND p.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users +} // No need to check if company is external user, as filtering of projects must be done by getProjectsAuthorizedForUser -if ($socid > 0) $sql .= " AND (p.fk_soc = ".$socid.")"; // This filter if when we use a hard coded filter on company on url (not related to filter for external users) -if ($search_ref) $sql .= natural_search('p.ref', $search_ref); -if ($search_label) $sql .= natural_search('p.title', $search_label); -if ($search_societe) $sql .= natural_search('s.nom', $search_societe); -if ($search_opp_amount) $sql .= natural_search('p.opp_amount', $search_opp_amount, 1); -if ($search_opp_percent) $sql .= natural_search('p.opp_percent', $search_opp_percent, 1); +if ($socid > 0) { + $sql .= " AND (p.fk_soc = ".$socid.")"; // This filter if when we use a hard coded filter on company on url (not related to filter for external users) +} +if ($search_ref) { + $sql .= natural_search('p.ref', $search_ref); +} +if ($search_label) { + $sql .= natural_search('p.title', $search_label); +} +if ($search_societe) { + $sql .= natural_search('s.nom', $search_societe); +} +if ($search_opp_amount) { + $sql .= natural_search('p.opp_amount', $search_opp_amount, 1); +} +if ($search_opp_percent) { + $sql .= natural_search('p.opp_percent', $search_opp_percent, 1); +} $sql .= dolSqlDateFilter('p.dateo', $search_sday, $search_smonth, $search_syear); $sql .= dolSqlDateFilter('p.datee', $search_eday, $search_emonth, $search_eyear); -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); -if ($search_status >= 0) -{ - if ($search_status == 99) $sql .= " AND p.fk_statut <> 2"; - else $sql .= " AND p.fk_statut = ".$db->escape($search_status); +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if ($search_opp_status) -{ - if (is_numeric($search_opp_status) && $search_opp_status > 0) $sql .= " AND p.fk_opp_status = ".$db->escape($search_opp_status); - if ($search_opp_status == 'all') $sql .= " AND (p.fk_opp_status IS NOT NULL AND p.fk_opp_status <> -1)"; - if ($search_opp_status == 'openedopp') $sql .= " AND p.fk_opp_status IS NOT NULL AND p.fk_opp_status <> -1 AND p.fk_opp_status NOT IN (SELECT rowid FROM ".MAIN_DB_PREFIX."c_lead_status WHERE code IN ('WON','LOST'))"; - if ($search_opp_status == 'notopenedopp') $sql .= " AND (p.fk_opp_status IS NULL OR p.fk_opp_status = -1 OR p.fk_opp_status IN (SELECT rowid FROM ".MAIN_DB_PREFIX."c_lead_status WHERE code IN ('WON')))"; - if ($search_opp_status == 'none') $sql .= " AND (p.fk_opp_status IS NULL OR p.fk_opp_status = -1)"; +if ($search_status >= 0) { + if ($search_status == 99) { + $sql .= " AND p.fk_statut <> 2"; + } else { + $sql .= " AND p.fk_statut = ".$db->escape($search_status); + } +} +if ($search_opp_status) { + if (is_numeric($search_opp_status) && $search_opp_status > 0) { + $sql .= " AND p.fk_opp_status = ".$db->escape($search_opp_status); + } + if ($search_opp_status == 'all') { + $sql .= " AND (p.fk_opp_status IS NOT NULL AND p.fk_opp_status <> -1)"; + } + if ($search_opp_status == 'openedopp') { + $sql .= " AND p.fk_opp_status IS NOT NULL AND p.fk_opp_status <> -1 AND p.fk_opp_status NOT IN (SELECT rowid FROM ".MAIN_DB_PREFIX."c_lead_status WHERE code IN ('WON','LOST'))"; + } + if ($search_opp_status == 'notopenedopp') { + $sql .= " AND (p.fk_opp_status IS NULL OR p.fk_opp_status = -1 OR p.fk_opp_status IN (SELECT rowid FROM ".MAIN_DB_PREFIX."c_lead_status WHERE code IN ('WON')))"; + } + if ($search_opp_status == 'none') { + $sql .= " AND (p.fk_opp_status IS NULL OR p.fk_opp_status = -1)"; + } +} +if ($search_public != '') { + $sql .= " AND p.public = ".$db->escape($search_public); } -if ($search_public != '') $sql .= " AND p.public = ".$db->escape($search_public); // For external user, no check is done on company permission because readability is managed by public status of project and assignement. //if ($socid > 0) $sql.= " AND s.rowid = ".$socid; -if ($search_sale > 0) $sql .= " AND sc.fk_user = ".$search_sale; +if ($search_sale > 0) { + $sql .= " AND sc.fk_user = ".$search_sale; +} // No check is done on company permission because readability is managed by public status of project and assignement. //if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))"; -if ($search_project_user > 0) $sql .= " AND ecp.fk_c_type_contact IN (".join(',', array_keys($listofprojectcontacttype)).") AND ecp.element_id = p.rowid AND ecp.fk_socpeople = ".$search_project_user; -if ($search_opp_amount != '') $sql .= natural_search('p.opp_amount', $search_opp_amount, 1); -if ($search_budget_amount != '') $sql .= natural_search('p.budget_amount', $search_budget_amount, 1); -if ($search_usage_opportunity != '' && $search_usage_opportunity >= 0) $sql .= natural_search('p.usage_opportunity', $search_usage_opportunity, 2); -if ($search_usage_task != '' && $search_usage_task >= 0) $sql .= natural_search('p.usage_task', $search_usage_task, 2); -if ($search_usage_bill_time != '' && $search_usage_bill_time >= 0) $sql .= natural_search('p.usage_bill_time', $search_usage_bill_time, 2); +if ($search_project_user > 0) { + $sql .= " AND ecp.fk_c_type_contact IN (".join(',', array_keys($listofprojectcontacttype)).") AND ecp.element_id = p.rowid AND ecp.fk_socpeople = ".$search_project_user; +} +if ($search_opp_amount != '') { + $sql .= natural_search('p.opp_amount', $search_opp_amount, 1); +} +if ($search_budget_amount != '') { + $sql .= natural_search('p.budget_amount', $search_budget_amount, 1); +} +if ($search_usage_opportunity != '' && $search_usage_opportunity >= 0) { + $sql .= natural_search('p.usage_opportunity', $search_usage_opportunity, 2); +} +if ($search_usage_task != '' && $search_usage_task >= 0) { + $sql .= natural_search('p.usage_task', $search_usage_task, 2); +} +if ($search_usage_bill_time != '' && $search_usage_bill_time >= 0) { + $sql .= natural_search('p.usage_bill_time', $search_usage_bill_time, 2); +} +if ($search_usage_event_organization != '' && $search_usage_event_organization >= 0) { + $sql .= natural_search('p.usage_organize_event', $search_usage_event_organization, 2); +} +if ($search_accept_conference_suggestions != '' && $search_accept_conference_suggestions >= 0) { + $sql .= natural_search('p.accept_conference_suggestions', $search_accept_conference_suggestions, 2); +} +if ($search_accept_booth_suggestions != '' && $search_accept_booth_suggestions >= 0) { + $sql .= natural_search('p.accept_booth_suggestions', $search_accept_booth_suggestions, 2); +} +if ($search_price_registration != '') { + $sql .= natural_search('p.price_registration', $search_price_registration, 1); +} +if ($search_price_booth != '') { + $sql .= natural_search('p.price_booth', $search_price_booth, 1); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -391,7 +485,9 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); if (!$resql) { @@ -403,8 +499,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); header("Location: ".DOL_URL_ROOT.'/projet/card.php?id='.$obj->id); exit; @@ -421,29 +516,96 @@ llxHeader('', $title, $help_url); $arrayofselected = is_array($toselect) ? $toselect : array(); $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_all != '') $param .= '&search_all='.urlencode($search_all); -if ($search_sday) $param .= '&search_sday='.urlencode($search_sday); -if ($search_smonth) $param .= '&search_smonth='.urlencode($search_smonth); -if ($search_syear) $param .= '&search_syear='.urlencode($search_syear); -if ($search_eday) $param .= '&search_eday='.urlencode($search_eday); -if ($search_emonth) $param .= '&search_emonth='.urlencode($search_emonth); -if ($search_eyear) $param .= '&search_eyear='.urlencode($search_eyear); -if ($socid) $param .= '&socid='.urlencode($socid); -if ($search_categ) $param .= '&search_categ='.urlencode($search_categ); -if ($search_ref != '') $param .= '&search_ref='.urlencode($search_ref); -if ($search_label != '') $param .= '&search_label='.urlencode($search_label); -if ($search_societe != '') $param .= '&search_societe='.urlencode($search_societe); -if ($search_status >= 0) $param .= '&search_status='.urlencode($search_status); -if ((is_numeric($search_opp_status) && $search_opp_status >= 0) || in_array($search_opp_status, array('all', 'openedopp', 'notopenedopp', 'none'))) $param .= '&search_opp_status='.urlencode($search_opp_status); -if ($search_opp_percent != '') $param .= '&search_opp_percent='.urlencode($search_opp_percent); -if ($search_public != '') $param .= '&search_public='.urlencode($search_public); -if ($search_project_user != '') $param .= '&search_project_user='.urlencode($search_project_user); -if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); -if ($search_opp_amount != '') $param .= '&search_opp_amount='.urlencode($search_opp_amount); -if ($search_budget_amount != '') $param .= '&search_budget_amount='.urlencode($search_budget_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 ($search_all != '') { + $param .= '&search_all='.urlencode($search_all); +} +if ($search_sday) { + $param .= '&search_sday='.urlencode($search_sday); +} +if ($search_smonth) { + $param .= '&search_smonth='.urlencode($search_smonth); +} +if ($search_syear) { + $param .= '&search_syear='.urlencode($search_syear); +} +if ($search_eday) { + $param .= '&search_eday='.urlencode($search_eday); +} +if ($search_emonth) { + $param .= '&search_emonth='.urlencode($search_emonth); +} +if ($search_eyear) { + $param .= '&search_eyear='.urlencode($search_eyear); +} +if ($socid) { + $param .= '&socid='.urlencode($socid); +} +if ($search_categ) { + $param .= '&search_categ='.urlencode($search_categ); +} +if ($search_ref != '') { + $param .= '&search_ref='.urlencode($search_ref); +} +if ($search_label != '') { + $param .= '&search_label='.urlencode($search_label); +} +if ($search_societe != '') { + $param .= '&search_societe='.urlencode($search_societe); +} +if ($search_status >= 0) { + $param .= '&search_status='.urlencode($search_status); +} +if ((is_numeric($search_opp_status) && $search_opp_status >= 0) || in_array($search_opp_status, array('all', 'openedopp', 'notopenedopp', 'none'))) { + $param .= '&search_opp_status='.urlencode($search_opp_status); +} +if ($search_opp_percent != '') { + $param .= '&search_opp_percent='.urlencode($search_opp_percent); +} +if ($search_public != '') { + $param .= '&search_public='.urlencode($search_public); +} +if ($search_project_user != '') { + $param .= '&search_project_user='.urlencode($search_project_user); +} +if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); +} +if ($search_opp_amount != '') { + $param .= '&search_opp_amount='.urlencode($search_opp_amount); +} +if ($search_budget_amount != '') { + $param .= '&search_budget_amount='.urlencode($search_budget_amount); +} +if ($search_usage_task != '') { + $param .= '&search_usage_task='.urlencode($search_usage_task); +} +if ($search_usage_bill_time != '') { + $param .= '&search_usage_opportunity='.urlencode($search_usage_bill_time); +} +if ($search_usage_event_organization != '') { + $param .= '&search_usage_event_organization='.urlencode($search_usage_event_organization); +} +if ($search_accept_conference_suggestions != '') { + $param .= '&search_accept_conference_suggestions='.urlencode($search_accept_conference_suggestions); +} +if ($search_accept_booth_suggestions != '') { + $param .= '&search_accept_booth_suggestions='.urlencode($search_accept_booth_suggestions); +} +if ($search_price_registration != '') { + $param .= '&search_price_registration='.urlencode($search_price_registration); +} +if ($search_price_booth != '') { + $param .= '&search_price_booth='.urlencode($search_price_booth); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -454,19 +616,31 @@ $arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), ); //if($user->rights->societe->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); -if ($user->rights->projet->creer) $arrayofmassactions['close'] = $langs->trans("Close"); -if ($user->rights->projet->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if ($user->rights->projet->creer) $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); -if (in_array($massaction, array('presend', 'predelete', 'preaffecttag'))) $arrayofmassactions = array(); +if ($user->rights->projet->creer) { + $arrayofmassactions['close'] = $langs->trans("Close"); +} +if ($user->rights->projet->supprimer) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if ($user->rights->projet->creer) { + $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); +} +if (in_array($massaction, array('presend', 'predelete', 'preaffecttag'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $url = DOL_URL_ROOT.'/projet/card.php?action=create'; -if (!empty($socid)) $url .= '&socid='.$socid; +if (!empty($socid)) { + $url .= '&socid='.$socid; +} $newcardbutton = dolGetButtonTitle($langs->trans('NewProject'), '', 'fa fa-plus-circle', $url, '', $user->rights->projet->creer); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -476,10 +650,14 @@ print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; // Show description of content $texthelp = ''; -if ($search_project_user == $user->id) $texthelp .= $langs->trans("MyProjectsDesc"); -else { - if ($user->rights->projet->all->lire && !$socid) $texthelp .= $langs->trans("ProjectsDesc"); - else $texthelp .= $langs->trans("ProjectsPublicDesc"); +if ($search_project_user == $user->id) { + $texthelp .= $langs->trans("MyProjectsDesc"); +} else { + if ($user->rights->projet->all->lire && !$socid) { + $texthelp .= $langs->trans("ProjectsDesc"); + } else { + $texthelp .= $langs->trans("ProjectsPublicDesc"); + } } print_barre_liste($form->textwithpicto($title, $texthelp), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'project', 0, $newcardbutton, '', $limit, 0, 0, 1); @@ -491,17 +669,17 @@ $objecttmp = new Project($db); $trackid = 'proj'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } $moreforfilter = ''; // Filter on categories -if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) -{ +if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { $formcategory = new FormCategory($db); $moreforfilter .= $formcategory->getFilterBox(Categorie::TYPE_PROJECT, $search_category_array); } @@ -511,13 +689,14 @@ $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('ProjectsWithThisUserAsContact').': '; //$includeonly = 'hierarchyme'; $includeonly = ''; -if (empty($user->rights->user->user->lire)) $includeonly = array($user->id); +if (empty($user->rights->user->user->lire)) { + $includeonly = array($user->id); +} $moreforfilter .= $form->select_dolusers($search_project_user ? $search_project_user : '', 'search_project_user', 1, '', 0, $includeonly, '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter .= '</div>'; // If the user can view thirdparties other than his' -if ($user->rights->societe->client->voir || $socid) -{ +if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; @@ -525,8 +704,7 @@ if ($user->rights->societe->client->voir || $socid) $moreforfilter .= '</div>'; } -if (!empty($moreforfilter)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; $parameters = array(); @@ -546,22 +724,19 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit // -------------------------------------------------------------------- print '<tr class="liste_titre_filter">'; // Project ref -if (!empty($arrayfields['p.ref']['checked'])) -{ +if (!empty($arrayfields['p.ref']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_ref" value="'.dol_escape_htmltag($search_ref).'" size="6">'; print '</td>'; } // Project label -if (!empty($arrayfields['p.title']['checked'])) -{ +if (!empty($arrayfields['p.title']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_label" size="8" value="'.dol_escape_htmltag($search_label).'">'; print '</td>'; } // Third party -if (!empty($arrayfields['s.nom']['checked'])) -{ +if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="liste_titre">'; if ($socid > 0) { $tmpthirdparty = new Societe($db); @@ -572,84 +747,101 @@ if (!empty($arrayfields['s.nom']['checked'])) print '</td>'; } // Sale representative -if (!empty($arrayfields['commercial']['checked'])) -{ +if (!empty($arrayfields['commercial']['checked'])) { print '<td class="liste_titre">&nbsp;</td>'; } // Start date -if (!empty($arrayfields['p.dateo']['checked'])) -{ +if (!empty($arrayfields['p.dateo']['checked'])) { print '<td class="liste_titre center nowraponall">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_sday" value="'.dol_escape_htmltag($search_sday).'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_sday" value="'.dol_escape_htmltag($search_sday).'">'; + } print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_smonth" value="'.dol_escape_htmltag($search_smonth).'">'; $formother->select_year($search_syear ? $search_syear : -1, 'search_syear', 1, 20, 5, 0, 0, '', 'widthauto valignmiddle'); print '</td>'; } // End date -if (!empty($arrayfields['p.datee']['checked'])) -{ +if (!empty($arrayfields['p.datee']['checked'])) { print '<td class="liste_titre center nowraponall">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_eday" value="'.dol_escape_htmltag($search_eday).'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_eday" value="'.dol_escape_htmltag($search_eday).'">'; + } print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_emonth" value="'.dol_escape_htmltag($search_emonth).'">'; $formother->select_year($search_eyear ? $search_eyear : -1, 'search_eyear', 1, 20, 5, 0, 0, '', 'widthauto valignmiddle'); print '</td>'; } -if (!empty($arrayfields['p.public']['checked'])) -{ +if (!empty($arrayfields['p.public']['checked'])) { print '<td class="liste_titre">'; $array = array(''=>'', 0 => $langs->trans("PrivateProject"), 1 => $langs->trans("SharedProject")); print $form->selectarray('search_public', $array, $search_public); print '</td>'; } // Opp status -if (!empty($arrayfields['p.fk_opp_status']['checked'])) -{ +if (!empty($arrayfields['p.fk_opp_status']['checked'])) { print '<td class="liste_titre nowrap center">'; print $formproject->selectOpportunityStatus('search_opp_status', $search_opp_status, 1, 0, 1, 0, 'maxwidth100'); print '</td>'; } -if (!empty($arrayfields['p.opp_amount']['checked'])) -{ +if (!empty($arrayfields['p.opp_amount']['checked'])) { print '<td class="liste_titre nowrap right">'; print '<input type="text" class="flat" name="search_opp_amount" size="3" value="'.$search_opp_amount.'">'; print '</td>'; } -if (!empty($arrayfields['p.opp_percent']['checked'])) -{ +if (!empty($arrayfields['p.opp_percent']['checked'])) { print '<td class="liste_titre nowrap right">'; print '<input type="text" class="flat" name="search_opp_percent" size="2" value="'.$search_opp_percent.'">'; print '</td>'; } -if (!empty($arrayfields['opp_weighted_amount']['checked'])) -{ +if (!empty($arrayfields['opp_weighted_amount']['checked'])) { print '<td class="liste_titre nowrap right">'; print '</td>'; } -if (!empty($arrayfields['p.budget_amount']['checked'])) -{ +if (!empty($arrayfields['p.budget_amount']['checked'])) { print '<td class="liste_titre nowrap right">'; print '<input type="text" class="flat" name="search_budget_amount" size="4" value="'.$search_budget_amount.'">'; print '</td>'; } -if (!empty($arrayfields['p.usage_opportunity']['checked'])) -{ +if (!empty($arrayfields['p.usage_opportunity']['checked'])) { print '<td class="liste_titre nowrap right">'; print $form->selectyesno('search_usage_opportunity', $search_usage_opportunity, 1, false, 1); print ''; print '</td>'; } -if (!empty($arrayfields['p.usage_task']['checked'])) -{ +if (!empty($arrayfields['p.usage_task']['checked'])) { print '<td class="liste_titre nowrap right">'; print $form->selectyesno('search_usage_task', $search_usage_task, 1, false, 1); print '</td>'; } -if (!empty($arrayfields['p.usage_bill_time']['checked'])) -{ +if (!empty($arrayfields['p.usage_bill_time']['checked'])) { print '<td class="liste_titre nowrap right">'; print $form->selectyesno('search_usage_bill_time', $search_usage_bill_time, 1, false, 1); print '</td>'; } +if (!empty($arrayfields['p.usage_organize_event']['checked'])) { + print '<td class="liste_titre nowrap right">'; + print $form->selectyesno('search_usage_event_organization', $search_usage_event_organization, 1, false, 1); + print '</td>'; +} +if (!empty($arrayfields['p.accept_conference_suggestions']['checked'])) { + print '<td class="liste_titre nowrap right">'; + print $form->selectyesno('search_accept_conference_suggestions', $search_accept_conference_suggestions, 1, false, 1); + print '</td>'; +} +if (!empty($arrayfields['p.accept_booth_suggestions']['checked'])) { + print '<td class="liste_titre nowrap right">'; + print $form->selectyesno('search_accept_booth_suggestions', $search_accept_booth_suggestions, 1, false, 1); + print '</td>'; +} +if (!empty($arrayfields['p.price_registration']['checked'])) { + print '<td class="liste_titre nowrap right">'; + print '<input type="text" class="flat" name="search_price_registration" size="4" value="'.$search_price_registration.'">'; + print '</td>'; +} +if (!empty($arrayfields['p.price_booth']['checked'])) { + print '<td class="liste_titre nowrap right">'; + print '<input type="text" class="flat" name="search_price_booth" size="4" value="'.$search_price_booth.'">'; + print '</td>'; +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; @@ -657,23 +849,22 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (!empty($arrayfields['p.datec']['checked'])) -{ +if (!empty($arrayfields['p.datec']['checked'])) { // Date creation print '<td class="liste_titre">'; print '</td>'; } -if (!empty($arrayfields['p.tms']['checked'])) -{ +if (!empty($arrayfields['p.tms']['checked'])) { // Date modification print '<td class="liste_titre">'; print '</td>'; } -if (!empty($arrayfields['p.fk_statut']['checked'])) -{ +if (!empty($arrayfields['p.fk_statut']['checked'])) { print '<td class="liste_titre nowrap right">'; $arrayofstatus = array(); - foreach ($object->statuts_short as $key => $val) $arrayofstatus[$key] = $langs->trans($val); + foreach ($object->statuts_short as $key => $val) { + $arrayofstatus[$key] = $langs->trans($val); + } $arrayofstatus['99'] = $langs->trans("NotClosed").' ('.$langs->trans('Draft').' + '.$langs->trans('Opened').')'; print $form->selectarray('search_status', $arrayofstatus, $search_status, 1, 0, 0, '', 0, 0, 0, '', 'minwidth75imp maxwidth150 selectarrowonleft'); print ajax_combobox('search_status'); @@ -688,30 +879,81 @@ print '</td>'; print '</tr>'."\n"; print '<tr class="liste_titre">'; -if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], "p.ref", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['p.title']['checked'])) print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER["PHP_SELF"], "p.title", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['commercial']['checked'])) print_liste_field_titre($arrayfields['commercial']['label'], $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder, 'tdoverflowmax100imp '); -if (!empty($arrayfields['p.dateo']['checked'])) print_liste_field_titre($arrayfields['p.dateo']['label'], $_SERVER["PHP_SELF"], "p.dateo", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['p.datee']['checked'])) print_liste_field_titre($arrayfields['p.datee']['label'], $_SERVER["PHP_SELF"], "p.datee", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['p.public']['checked'])) print_liste_field_titre($arrayfields['p.public']['label'], $_SERVER["PHP_SELF"], "p.public", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER['PHP_SELF'], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['opp_weighted_amount']['checked'])) print_liste_field_titre($arrayfields['opp_weighted_amount']['label'], $_SERVER['PHP_SELF'], 'opp_weighted_amount', '', $param, '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['p.usage_opportunity']['checked'])) print_liste_field_titre($arrayfields['p.usage_opportunity']['label'], $_SERVER["PHP_SELF"], 'p.usage_opportunity', "", $param, '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['p.usage_task']['checked'])) print_liste_field_titre($arrayfields['p.usage_task']['label'], $_SERVER["PHP_SELF"], 'p.usage_task', "", $param, '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right '); +if (!empty($arrayfields['p.ref']['checked'])) { + print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], "p.ref", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['p.title']['checked'])) { + print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER["PHP_SELF"], "p.title", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['commercial']['checked'])) { + print_liste_field_titre($arrayfields['commercial']['label'], $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder, 'tdoverflowmax100imp '); +} +if (!empty($arrayfields['p.dateo']['checked'])) { + print_liste_field_titre($arrayfields['p.dateo']['label'], $_SERVER["PHP_SELF"], "p.dateo", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['p.datee']['checked'])) { + print_liste_field_titre($arrayfields['p.datee']['label'], $_SERVER["PHP_SELF"], "p.datee", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['p.public']['checked'])) { + print_liste_field_titre($arrayfields['p.public']['label'], $_SERVER["PHP_SELF"], "p.public", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['p.fk_opp_status']['checked'])) { + print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['p.opp_amount']['checked'])) { + print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['p.opp_percent']['checked'])) { + print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER['PHP_SELF'], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['opp_weighted_amount']['checked'])) { + print_liste_field_titre($arrayfields['opp_weighted_amount']['label'], $_SERVER['PHP_SELF'], 'opp_weighted_amount', '', $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['p.budget_amount']['checked'])) { + print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['p.usage_opportunity']['checked'])) { + print_liste_field_titre($arrayfields['p.usage_opportunity']['label'], $_SERVER["PHP_SELF"], 'p.usage_opportunity', "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['p.usage_task']['checked'])) { + print_liste_field_titre($arrayfields['p.usage_task']['label'], $_SERVER["PHP_SELF"], 'p.usage_task', "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['p.usage_bill_time']['checked'])) { + print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['p.usage_organize_event']['checked'])) { + print_liste_field_titre($arrayfields['p.usage_organize_event']['label'], $_SERVER["PHP_SELF"], 'p.usage_organize_event', "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['p.accept_conference_suggestions']['checked'])) { + print_liste_field_titre($arrayfields['p.accept_conference_suggestions']['label'], $_SERVER["PHP_SELF"], 'p.accept_conference_suggestions', "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['p.accept_booth_suggestions']['checked'])) { + print_liste_field_titre($arrayfields['p.accept_booth_suggestions']['label'], $_SERVER["PHP_SELF"], 'p.accept_booth_suggestions', "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['p.price_registration']['checked'])) { + print_liste_field_titre($arrayfields['p.price_registration']['label'], $_SERVER["PHP_SELF"], 'p.price_registration', "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['p.price_booth']['checked'])) { + print_liste_field_titre($arrayfields['p.price_booth']['label'], $_SERVER["PHP_SELF"], 'p.price_booth', "", $param, '', $sortfield, $sortorder, 'right '); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $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['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'], $_SERVER["PHP_SELF"], "p.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['p.fk_statut']['checked'])) print_liste_field_titre($arrayfields['p.fk_statut']['label'], $_SERVER["PHP_SELF"], "p.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); +if (!empty($arrayfields['p.datec']['checked'])) { + print_liste_field_titre($arrayfields['p.datec']['label'], $_SERVER["PHP_SELF"], "p.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['p.tms']['checked'])) { + print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['p.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['p.fk_statut']['label'], $_SERVER["PHP_SELF"], "p.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); +} print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; @@ -720,8 +962,7 @@ $totalarray = array( 'nbfield' => 0, 'val' => array(), ); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $object->id = $obj->id; @@ -736,8 +977,7 @@ while ($i < min($num, $limit)) $object->title = $obj->title; $userAccess = $object->restrictedProjectArea($user); // why this ? - if ($userAccess >= 0) - { + if ($userAccess >= 0) { $socstatic->id = $obj->socid; $socstatic->name = $obj->name; $socstatic->email = $obj->email; @@ -745,25 +985,28 @@ while ($i < min($num, $limit)) print '<tr class="oddeven">'; // Project url - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print '<td class="nowraponall">'; - print $object->getNomUrl(1); - if ($object->hasDelay()) print img_warning($langs->trans('Late')); + print $object->getNomUrl(1, (!empty(GETPOST('search_usage_event_organization', 'int'))?'eventorganization':'')); + if ($object->hasDelay()) { + print img_warning($langs->trans('Late')); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Title - if (!empty($arrayfields['p.title']['checked'])) - { + if (!empty($arrayfields['p.title']['checked'])) { print '<td class="tdoverflowmax200">'; print dol_trunc($obj->title, 80); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Company - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="tdoverflowmax100">'; if ($obj->socid) { print $socstatic->getNomUrl(1); @@ -771,7 +1014,9 @@ while ($i < min($num, $limit)) print '&nbsp;'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Sales Representatives if (!empty($arrayfields['commercial']['checked'])) { @@ -811,121 +1056,207 @@ while ($i < min($num, $limit)) print '&nbsp;'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date start - if (!empty($arrayfields['p.dateo']['checked'])) - { + if (!empty($arrayfields['p.dateo']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_start), 'day'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date end - if (!empty($arrayfields['p.datee']['checked'])) - { + if (!empty($arrayfields['p.datee']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_end), 'day'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Visibility - if (!empty($arrayfields['p.public']['checked'])) - { + if (!empty($arrayfields['p.public']['checked'])) { print '<td class="left">'; - if ($obj->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); + if ($obj->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Opp Status - if (!empty($arrayfields['p.fk_opp_status']['checked'])) - { + if (!empty($arrayfields['p.fk_opp_status']['checked'])) { print '<td class="center">'; - if ($obj->opp_status_code) print $langs->trans("OppStatus".$obj->opp_status_code); + if ($obj->opp_status_code) { + print $langs->trans("OppStatus".$obj->opp_status_code); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Opp Amount - if (!empty($arrayfields['p.opp_amount']['checked'])) - { + if (!empty($arrayfields['p.opp_amount']['checked'])) { print '<td class="right">'; //if ($obj->opp_status_code) - if (strcmp($obj->opp_amount, '')) - { + if (strcmp($obj->opp_amount, '')) { print price($obj->opp_amount, 1, $langs, 1, -1, -1, ''); $totalarray['val']['p.opp_amount'] += $obj->opp_amount; } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.opp_amount'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'p.opp_amount'; + } } // Opp percent - if (!empty($arrayfields['p.opp_percent']['checked'])) - { + if (!empty($arrayfields['p.opp_percent']['checked'])) { print '<td class="right">'; - if ($obj->opp_percent) print price($obj->opp_percent, 1, $langs, 1, 0).'%'; + if ($obj->opp_percent) { + print price($obj->opp_percent, 1, $langs, 1, 0).'%'; + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Opp weighted amount - if (!empty($arrayfields['opp_weighted_amount']['checked'])) - { - if (!isset($totalarray['val']['opp_weighted_amount'])) $totalarray['val']['opp_weighted_amount'] = 0; + if (!empty($arrayfields['opp_weighted_amount']['checked'])) { + if (!isset($totalarray['val']['opp_weighted_amount'])) { + $totalarray['val']['opp_weighted_amount'] = 0; + } print '<td align="right">'; if ($obj->opp_weighted_amount) { print price($obj->opp_weighted_amount, 1, $langs, 1, -1, -1, ''); $totalarray['val']['opp_weighted_amount'] += $obj->opp_weighted_amount; } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'opp_weighted_amount'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'opp_weighted_amount'; + } } // Budget - if (!empty($arrayfields['p.budget_amount']['checked'])) - { + if (!empty($arrayfields['p.budget_amount']['checked'])) { print '<td class="right">'; - if ($obj->budget_amount != '') - { + if ($obj->budget_amount != '') { print price($obj->budget_amount, 1, $langs, 1, -1, -1); $totalarray['val']['p.budget_amount'] += $obj->budget_amount; } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.budget_amount'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'p.budget_amount'; + } } // Usage opportunity - if (!empty($arrayfields['p.usage_opportunity']['checked'])) - { + if (!empty($arrayfields['p.usage_opportunity']['checked'])) { print '<td class="right">'; - if ($obj->usage_opportunity) - { + if ($obj->usage_opportunity) { print yn($obj->usage_opportunity); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Usage task - if (!empty($arrayfields['p.usage_task']['checked'])) - { + if (!empty($arrayfields['p.usage_task']['checked'])) { print '<td class="right">'; - if ($obj->usage_task) - { + if ($obj->usage_task) { print yn($obj->usage_task); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Bill time - if (!empty($arrayfields['p.usage_bill_time']['checked'])) - { + if (!empty($arrayfields['p.usage_bill_time']['checked'])) { print '<td class="right">'; - if ($obj->usage_bill_time) - { + if ($obj->usage_bill_time) { print yn($obj->usage_bill_time); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } + } + // Event Organization + if (!empty($arrayfields['p.usage_organize_event']['checked'])) { + print '<td class="right">'; + if ($obj->usage_organize_event) { + print yn($obj->usage_organize_event); + } + print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } + } + // Allow unknown people to suggest conferences + if (!empty($arrayfields['p.accept_conference_suggestions']['checked'])) { + print '<td class="right">'; + if ($obj->accept_conference_suggestions) { + print yn($obj->accept_conference_suggestions); + } + print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } + } + // Allow unknown people to suggest booth + if (!empty($arrayfields['p.accept_booth_suggestions']['checked'])) { + print '<td class="right">'; + if ($obj->accept_booth_suggestions) { + print yn($obj->accept_booth_suggestions); + } + print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } + } + // Price of registration + if (!empty($arrayfields['p.price_registration']['checked'])) { + print '<td class="right">'; + if ($obj->price_registration != '') { + print price($obj->price_registration, 1, $langs, 1, -1, -1); + $totalarray['val']['p.price_registration'] += $obj->price_registration; + } + print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'p.price_registration'; + } + } + // PriceOfBooth + if (!empty($arrayfields['p.price_booth']['checked'])) { + print '<td class="right">'; + if ($obj->price_booth != '') { + print price($obj->price_booth, 1, $langs, 1, -1, -1); + $totalarray['val']['p.price_booth'] += $obj->price_booth; + } + print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'p.price_booth'; + } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; @@ -934,37 +1265,43 @@ while ($i < min($num, $limit)) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['p.datec']['checked'])) - { + if (!empty($arrayfields['p.datec']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['p.tms']['checked'])) - { + if (!empty($arrayfields['p.tms']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['p.fk_statut']['checked'])) - { + if (!empty($arrayfields['p.fk_statut']['checked'])) { print '<td class="right">'.$object->getLibStatut(5).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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->id, $arrayofselected)) $selected = 1; + if (in_array($obj->id, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$obj->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; } diff --git a/htdocs/projet/note.php b/htdocs/projet/note.php index 65172311441..a1ef737ddc7 100644 --- a/htdocs/projet/note.php +++ b/htdocs/projet/note.php @@ -39,7 +39,9 @@ $mine = $_REQUEST['mode'] == 'mine' ? 1 : 0; $object = new Project($db); include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once -if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); +if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); +} // Security check $socid = 0; @@ -61,7 +63,9 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, */ $title = $langs->trans("Project").' - '.$langs->trans("Note").' - '.$object->ref.' '.$object->name; -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Note"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->ref.' '.$object->name.' - '.$langs->trans("Note"); +} $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos"; llxHeader("", $title, $help_url); @@ -70,8 +74,7 @@ $userstatic = new User($db); $now = dol_now(); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { // To verify role of users //$userAccess = $object->restrictedProjectArea($user,'read'); $userWrite = $object->restrictedProjectArea($user, 'write'); @@ -90,15 +93,13 @@ if ($id > 0 || !empty($ref)) // Title $morehtmlref .= $object->title; // Thirdparty - if ($object->thirdparty->id > 0) - { + if ($object->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); $object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } diff --git a/htdocs/projet/stats/index.php b/htdocs/projet/stats/index.php index add142f1f57..6b1b0eac4c1 100644 --- a/htdocs/projet/stats/index.php +++ b/htdocs/projet/stats/index.php @@ -28,8 +28,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/projectstats.class.php'; // Security check -if (!$user->rights->projet->lire) +if (!$user->rights->projet->lire) { accessforbidden(); +} $WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); @@ -38,8 +39,7 @@ $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); $userid = GETPOST('userid', 'int'); $socid = GETPOST('socid', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -65,7 +65,7 @@ $includeuserlist = array(); llxHeader('', $langs->trans('Projects')); $title = $langs->trans("ProjectsStatistics"); -$dir = $conf->projet->dir_output.'/temp'; +$dir = $conf->project->dir_output.'/temp'; print load_fiche_titre($title, '', 'project'); @@ -73,9 +73,15 @@ dol_mkdir($dir); $stats_project = new ProjectStats($db); -if (!empty($userid) && $userid != -1) $stats_project->userid = $userid; -if (!empty($socid) && $socid != -1) $stats_project->socid = $socid; -if (!empty($year)) $stats_project->year = $year; +if (!empty($userid) && $userid != -1) { + $stats_project->userid = $userid; +} +if (!empty($socid) && $socid != -1) { + $stats_project->socid = $socid; +} +if (!empty($year)) { + $stats_project->year = $year; +} /* if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) @@ -149,12 +155,10 @@ $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=projectstats&amp;file=proje $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -172,8 +176,7 @@ if (!$mesg) } -if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) -{ +if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { // Build graphic amount of object $data = $stats_project->getAmountByMonthWithPrevYear($endyear, $startyear); //var_dump($data); @@ -184,11 +187,9 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); - if (!$mesg) - { + if (!$mesg) { $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -210,8 +211,7 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) } } -if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) -{ +if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { // Build graphic with transformation rate $data = $stats_project->getWeightedAmountByMonthWithPrevYear($endyear, $startyear, 0, 0); //var_dump($data); @@ -222,12 +222,11 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); - if (!$mesg) - { + if (!$mesg) { $px3->SetData($data); - $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + $i = $startyear; + $legend = array(); + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -251,12 +250,16 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $stats_project->year = 0; $data_all_year = $stats_project->getAllByYear(); -if (!empty($year)) $stats_project->year = $year; +if (!empty($year)) { + $stats_project->year = $year; +} $arrayyears = array(); foreach ($data_all_year as $val) { $arrayyears[$val['year']] = $val['year']; } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; @@ -266,7 +269,7 @@ $head[$h][1] = $langs->trans("ByMonthYear"); $head[$h][2] = 'byyear'; $h++; -complete_head_from_modules($conf, $langs, null, $head, $h, $type); +complete_head_from_modules($conf, $langs, null, $head, $h, 'project_stats'); print dol_get_fiche_head($head, 'byyear', $langs->trans("Statistics"), -1, ''); @@ -288,8 +291,12 @@ print $form->select_dolusers($userid, 'userid', 1, array(),0,$includeuserlist); print '</td></tr>';*/ // Year print '<tr><td>'.$langs->trans("Year").'</td><td>'; -if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; -if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} +if (!in_array($nowyear, $arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print '</td></tr>'; @@ -303,8 +310,7 @@ print '<table class="noborder centpercent">'; print '<tr class="liste_titre" height="24">'; print '<td class="center">'.$langs->trans("Year").'</td>'; print '<td class="right">'.$langs->trans("NbOfProjects").'</td>'; -if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) -{ +if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<td class="right">'.$langs->trans("OpportunityAmountShort").'</td>'; print '<td class="right">'.$langs->trans("OpportunityAmountAverageShort").'</td>'; print '<td class="right">'.$langs->trans("OpportunityAmountWeigthedShort").'</td>'; @@ -312,17 +318,14 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) print '</tr>'; $oldyear = 0; -foreach ($data_all_year as $val) -{ +foreach ($data_all_year as $val) { $year = $val['year']; - while ($year && $oldyear > $year + 1) - { // If we have empty year + while ($year && $oldyear > $year + 1) { // If we have empty year $oldyear--; print '<tr class="oddeven" height="24">'; print '<td class="center"><a href="'.$_SERVER["PHP_SELF"].'?year='.$oldyear.($socid > 0 ? '&socid='.$socid : '').($userid > 0 ? '&userid='.$userid : '').'">'.$oldyear.'</a></td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<td class="right">0</td>'; print '<td class="right">0</td>'; print '<td class="right">0</td>'; @@ -334,11 +337,10 @@ foreach ($data_all_year as $val) print '<tr class="oddeven" height="24">'; print '<td class="center"><a href="'.$_SERVER["PHP_SELF"].'?year='.$year.($socid > 0 ? '&socid='.$socid : '').($userid > 0 ? '&userid='.$userid : '').'">'.$year.'</a></td>'; print '<td class="right">'.$val['nb'].'</td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { - print '<td class="right">'.($val['total'] ?price(price2num($val['total'], 'MT'), 1) : '0').'</td>'; - print '<td class="right">'.($val['avg'] ?price(price2num($val['avg'], 'MT'), 1) : '0').'</td>'; - print '<td class="right">'.($val['weighted'] ?price(price2num($val['weighted'], 'MT'), 1) : '0').'</td>'; + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { + print '<td class="right">'.($val['total'] ? price(price2num($val['total'], 'MT'), 1) : '0').'</td>'; + print '<td class="right">'.($val['avg'] ? price(price2num($val['avg'], 'MT'), 1) : '0').'</td>'; + print '<td class="right">'.(isset($val['weighted']) ? price(price2num($val['weighted'], 'MT'), 1) : '0').'</td>'; } print '</tr>'; $oldyear = $year; @@ -349,12 +351,13 @@ print '</div>'; print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; -$stringtoshow .= '<table class="border centpercent"><tr class="pair nohover"><td class="center">'; -if ($mesg) { print $mesg; } else { +$stringtoshow = '<table class="border centpercent"><tr class="pair nohover"><td class="center">'; +if ($mesg) { + print $mesg; +} else { $stringtoshow .= $px1->show(); $stringtoshow .= "<br>\n"; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { //$stringtoshow .= $px->show(); //$stringtoshow .= "<br>\n"; $stringtoshow .= $px2->show(); diff --git a/htdocs/projet/tasks.php b/htdocs/projet/tasks.php index c9994dcf108..eb5b0ae7b0a 100644 --- a/htdocs/projet/tasks.php +++ b/htdocs/projet/tasks.php @@ -31,10 +31,17 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; -if ($conf->categorie->enabled) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; } +if ($conf->categorie->enabled) { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +} // Load translation files required by the page -$langs->loadLangs(array('projects', 'users', 'companies')); +$langsLoad=array('projects', 'users', 'companies'); +if (!empty($conf->eventorganization->enabled)) { + $langsLoad[]='eventorganization'; +} + +$langs->loadLangs($langsLoad); $action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); @@ -51,7 +58,9 @@ $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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -83,10 +92,11 @@ $taskstatic = new Task($db); $extrafields = new ExtraFields($db); include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once -if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); +if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); +} -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); } @@ -95,8 +105,12 @@ $search_array_options = $extrafields->getOptionalsFromPost($taskstatic->table_el // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) { reset($object->fields); $sortfield="t.".key($object->fields); } // Set here default search field. By default 1st field in definition. Reset is required to avoid key() to return null. -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + reset($object->fields); $sortfield="t.".key($object->fields); +} // Set here default search field. By default 1st field in definition. Reset is required to avoid key() to return null. +if (!$sortorder) { + $sortorder = "ASC"; +} // Security check @@ -128,6 +142,7 @@ $arrayfields = array( 't.progress_calculated'=>array('label'=>$langs->trans("ProgressCalculated"), 'checked'=>1, 'position'=>8), 't.progress'=>array('label'=>$langs->trans("ProgressDeclared"), 'checked'=>1, 'position'=>9), 't.progress_summary'=>array('label'=>$langs->trans("TaskProgressSummary"), 'checked'=>1, 'position'=>10), + 'c.assigned'=>array('label'=>$langs->trans("TaskRessourceLinks"), 'checked'=>1, 'position'=>11), ); if ($object->usage_bill_time) { $arrayfields['t.tobill'] = array('label'=>$langs->trans("TimeToBill"), 'checked'=>0, 'position'=>11); @@ -148,16 +163,16 @@ $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $parameters = array('id'=>$id); $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_user_id = ""; $search_taskref = ''; $search_tasklabel = ''; @@ -195,10 +210,14 @@ if (!empty($search_tasklabel)) { } $moresql = dolSqlDateFilter('t.dateo', $search_dtstartday, $search_dtstartmonth, $search_dtstartyear, 1); -if ($moresql) $morewherefilterarray[] = $moresql; +if ($moresql) { + $morewherefilterarray[] = $moresql; +} $moresql = dolSqlDateFilter('t.datee', $search_dtendday, $search_dtendmonth, $search_dtendyear, 1); -if ($moresql) $morewherefilterarray[] = $moresql; +if ($moresql) { + $morewherefilterarray[] = $moresql; +} if (!empty($search_planedworkload)) { $morewherefilterarray[] = natural_search('t.planned_workload', $search_planedworkload, 1, 1); @@ -223,8 +242,7 @@ if (count($morewherefilterarray) > 0) { $morewherefilter = ' AND '.implode(' AND ', $morewherefilterarray); } -if ($action == 'createtask' && $user->rights->projet->creer) -{ +if ($action == 'createtask' && $user->rights->projet->creer) { $error = 0; // If we use user timezone, we must change also view/list to use user timezone everywhere @@ -233,33 +251,32 @@ if ($action == 'createtask' && $user->rights->projet->creer) $date_start = dol_mktime(GETPOST('dateohour', 'int'), GETPOST('dateomin', 'int'), 0, GETPOST('dateomonth', 'int'), GETPOST('dateoday', 'int'), GETPOST('dateoyear', 'int')); $date_end = dol_mktime(GETPOST('dateehour', 'int'), GETPOST('dateemin', 'int'), 0, GETPOST('dateemonth', 'int'), GETPOST('dateeday', 'int'), GETPOST('dateeyear', 'int')); - if (!$cancel) - { - if (empty($taskref)) - { + if (!$cancel) { + if (empty($taskref)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); $action = 'create'; $error++; } - if (empty($label)) - { + if (empty($label)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); $action = 'create'; $error++; - } elseif (empty($_POST['task_parent'])) - { + } elseif (empty($_POST['task_parent'])) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ChildOfProjectTask")), null, 'errors'); $action = 'create'; $error++; } - if (!$error) - { + if (!$error) { $tmparray = explode('_', GETPOST('task_parent')); $projectid = $tmparray[0]; - if (empty($projectid)) $projectid = $id; // If projectid is '' + if (empty($projectid)) { + $projectid = $id; // If projectid is '' + } $task_parent = $tmparray[1]; - if (empty($task_parent)) $task_parent = 0; // If task_parent is '' + if (empty($task_parent)) { + $task_parent = 0; // If task_parent is '' + } $task = new Task($db); @@ -279,12 +296,10 @@ if ($action == 'createtask' && $user->rights->projet->creer) $taskid = $task->create($user); - if ($taskid > 0) - { + if ($taskid > 0) { $result = $task->add_contact($_POST["userid"], 'TASKEXECUTIVE', 'internal'); } else { - if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("projects"); setEventMessages($langs->trans('NewTaskRefSuggested'), '', 'warnings'); $duplicate_code_error = true; @@ -296,26 +311,21 @@ if ($action == 'createtask' && $user->rights->projet->creer) } } - if (!$error) - { - if (!empty($backtopage)) - { + if (!$error) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; - } elseif (empty($projectid)) - { + } elseif (empty($projectid)) { header("Location: ".DOL_URL_ROOT.'/projet/tasks/list.php'.(empty($mode) ? '' : '?mode='.$mode)); exit; } $id = $projectid; } } else { - if (!empty($backtopage)) - { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; - } elseif (empty($id)) - { + } elseif (empty($id)) { // We go back on task list header("Location: ".DOL_URL_ROOT.'/projet/tasks/list.php'.(empty($mode) ? '' : '?mode='.$mode)); exit; @@ -337,17 +347,28 @@ $taskstatic = new Task($db); $userstatic = new User($db); $title = $langs->trans("Project").' - '.$langs->trans("Tasks").' - '.$object->ref.' '.$object->name; -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Tasks"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->ref.' '.$object->name.' - '.$langs->trans("Tasks"); +} $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos"; llxHeader("", $title, $help_url); -if ($id > 0 || !empty($ref)) -{ - $object->fetch($id, $ref); - $object->fetch_thirdparty(); - $res = $object->fetch_optionals(); +if ($id > 0 || !empty($ref)) { + $result = $object->fetch($id, $ref); + if ($result < 0) { + setEventMessages(null, $object->errors, 'errors'); + } + $result = $object->fetch_thirdparty(); + if ($result < 0) { + setEventMessages(null, $object->errors, 'errors'); + } + $result = $object->fetch_optionals(); + if ($result < 0) { + setEventMessages(null, $object->errors, 'errors'); + } + // To verify role of users //$userAccess = $object->restrictedProjectArea($user,'read'); @@ -362,22 +383,54 @@ if ($id > 0 || !empty($ref)) print dol_get_fiche_head($head, $tab, $langs->trans("Project"), -1, ($object->public ? 'projectpub' : 'project')); $param = '&id='.$object->id; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($search_user_id) $param .= '&search_user_id='.urlencode($search_user_id); - if ($search_taskref) $param .= '&search_taskref='.urlencode($search_taskref); - if ($search_tasklabel) $param .= '&search_tasklabel='.urlencode($search_tasklabel); - if ($search_taskdescription) $param .= '&search_taskdescription='.urlencode($search_taskdescription); - if ($search_dtstartday) $param .= '&search_dtstartday='.urlencode($search_dtstartday); - if ($search_dtstartmonth) $param .= '&search_dtstartmonth='.urlencode($search_dtstartmonth); - if ($search_dtstartyear) $param .= '&search_dtstartyear='.urlencode($search_dtstartyear); - if ($search_dtendday) $param .= '&search_dtendday='.urlencode($search_dtendday); - if ($search_dtendmonth) $param .= '&search_dtendmonth='.urlencode($search_dtendmonth); - if ($search_dtendyear) $param .= '&search_dtendyear='.urlencode($search_dtendyear); - if ($search_planedworkload) $param .= '&search_planedworkload='.urlencode($search_planedworkload); - if ($search_timespend) $param .= '&search_timespend='.urlencode($search_timespend); - if ($search_progresscalc) $param .= '&search_progresscalc='.urlencode($search_progresscalc); - if ($search_progressdeclare) $param .= '&search_progressdeclare='.urlencode($search_progressdeclare); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($search_user_id) { + $param .= '&search_user_id='.urlencode($search_user_id); + } + if ($search_taskref) { + $param .= '&search_taskref='.urlencode($search_taskref); + } + if ($search_tasklabel) { + $param .= '&search_tasklabel='.urlencode($search_tasklabel); + } + if ($search_taskdescription) { + $param .= '&search_taskdescription='.urlencode($search_taskdescription); + } + if ($search_dtstartday) { + $param .= '&search_dtstartday='.urlencode($search_dtstartday); + } + if ($search_dtstartmonth) { + $param .= '&search_dtstartmonth='.urlencode($search_dtstartmonth); + } + if ($search_dtstartyear) { + $param .= '&search_dtstartyear='.urlencode($search_dtstartyear); + } + if ($search_dtendday) { + $param .= '&search_dtendday='.urlencode($search_dtendday); + } + if ($search_dtendmonth) { + $param .= '&search_dtendmonth='.urlencode($search_dtendmonth); + } + if ($search_dtendyear) { + $param .= '&search_dtendyear='.urlencode($search_dtendyear); + } + if ($search_planedworkload) { + $param .= '&search_planedworkload='.urlencode($search_planedworkload); + } + if ($search_timespend) { + $param .= '&search_timespend='.urlencode($search_timespend); + } + if ($search_progresscalc) { + $param .= '&search_progresscalc='.urlencode($search_progresscalc); + } + if ($search_progressdeclare) { + $param .= '&search_progressdeclare='.urlencode($search_progressdeclare); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -389,15 +442,13 @@ if ($id > 0 || !empty($ref)) // Title $morehtmlref .= $object->title; // Thirdparty - if ($object->thirdparty->id > 0) - { + if ($object->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); $object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -415,33 +466,38 @@ if ($id > 0 || !empty($ref)) print $langs->trans("Usage"); print '</td>'; print '<td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } - if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); print '<br>'; } + if (!empty($conf->eventorganization->enabled)) { + print '<input type="checkbox" disabled name="usage_organize_event"'.(GETPOSTISSET('usage_organize_event') ? (GETPOST('usage_organize_event', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_organize_event ? ' checked="checked"' : '')).'"> '; + $htmltext = $langs->trans("EventOrganizationDescriptionLong"); + print $form->textwithpicto($langs->trans("ManageOrganizeEvent"), $htmltext); + } print '</td></tr>'; // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; - if ($object->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); + if ($object->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } print '</td></tr>'; // Date start - end @@ -451,12 +507,16 @@ if ($id > 0 || !empty($ref)) $end = dol_print_date($object->date_end, 'day'); print ' - '; print ($end ? $end : '?'); - if ($object->hasDelay()) print img_warning("Late"); + if ($object->hasDelay()) { + print img_warning("Late"); + } print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; - if (strcmp($object->budget_amount, '')) print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + if (strcmp($object->budget_amount, '')) { + print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + } print '</td></tr>'; // Other attributes @@ -497,9 +557,10 @@ if ($id > 0 || !empty($ref)) } -if ($action == 'create' && $user->rights->projet->creer && (empty($object->thirdparty->id) || $userWrite > 0)) -{ - if ($id > 0 || !empty($ref)) print '<br>'; +if ($action == 'create' && $user->rights->projet->creer && (empty($object->thirdparty->id) || $userWrite > 0)) { + if ($id > 0 || !empty($ref)) { + print '<br>'; + } print load_fiche_titre($langs->trans("NewTask"), '', 'projecttask'); @@ -521,7 +582,9 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="createtask">'; print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if (!empty($object->id)) print '<input type="hidden" name="id" value="'.$object->id.'">'; + if (!empty($object->id)) { + print '<input type="hidden" name="id" value="'.$object->id.'">'; + } print dol_get_fiche_head(''); @@ -529,19 +592,19 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third $defaultref = ''; $obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON; - if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php")) - { + if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php")) { require_once DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php'; $modTask = new $obj; $defaultref = $modTask->getNextValue($object->thirdparty, null); } - if (is_numeric($defaultref) && $defaultref <= 0) $defaultref = ''; + if (is_numeric($defaultref) && $defaultref <= 0) { + $defaultref = ''; + } // Ref print '<tr><td class="titlefieldcreate"><span class="fieldrequired">'.$langs->trans("Ref").'</span></td><td>'; - if (empty($duplicate_code_error)) - { + if (empty($duplicate_code_error)) { print (GETPOSTISSET("ref") ? GETPOST("ref", 'alpha') : $defaultref); } else { print $defaultref; @@ -561,8 +624,7 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third print '<tr><td>'.$langs->trans("AffectedTo").'</td><td>'; $contactsofproject = (!empty($object->id) ? $object->getListContactId('internal') : ''); - if (is_array($contactsofproject) && count($contactsofproject)) - { + if (is_array($contactsofproject) && count($contactsofproject)) { print $form->select_dolusers($user->id, 'userid', 0, '', 0, '', $contactsofproject, 0, 0, 0, '', 0, '', 'maxwidth300'); } else { print $langs->trans("NoUserAssignedToTheProject"); @@ -600,8 +662,7 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $taskstatic, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook) && !empty($extrafields->attributes[$taskstatic->table_element]['label'])) - { + if (empty($reshook) && !empty($extrafields->attributes[$taskstatic->table_element]['label'])) { print $taskstatic->showOptionals($extrafields, 'edit'); // Do not use $object here that is object of project but use $taskstatic } @@ -639,7 +700,9 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third $linktocreatetask = dolGetButtonTitle($langs->trans('AddTask'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/projet/tasks.php?action=create'.$param.'&backtopage='.urlencode($_SERVER['PHP_SELF'].'?id='.$object->id), '', $linktocreatetaskUserRight, $linktocreatetaskParam); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; @@ -662,28 +725,27 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third // We load also tasks limited to a particular user $tmpuser = new User($db); - if ($search_user_id > 0) $tmpuser->fetch($search_user_id); + if ($search_user_id > 0) { + $tmpuser->fetch($search_user_id); + } $tasksrole = ($tmpuser->id > 0 ? $taskstatic->getUserRolesForProjectsOrTasks(0, $tmpuser, $object->id, 0) : ''); //var_dump($tasksarray); //var_dump($tasksrole); - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; } // Filter on categories $moreforfilter = ''; - if (count($tasksarray) > 0) - { + if (count($tasksarray) > 0) { $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans("TasksAssignedTo").': '; $moreforfilter .= $form->select_dolusers($tmpuser->id > 0 ? $tmpuser->id : '', 'search_user_id', 1); $moreforfilter .= '</div>'; } - if ($moreforfilter) - { + if ($moreforfilter) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -756,8 +818,7 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third // progress resume not searchable print '<td class="liste_titre right"></td>'; - if ($object->usage_bill_time) - { + if ($object->usage_bill_time) { if (!empty($arrayfields['t.tobill']['checked'])) { print '<td class="liste_titre right">'; print '</td>'; @@ -768,8 +829,17 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third print '</td>'; } } + // Contacts of task, disabled because available by default jsut after + /* + if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) { + print '<td class="liste_titre"></td>'; + } + */ - if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) print '<td class="liste_titre"></td>'; + if (!empty($arrayfields['c.assigned']['checked'])) { + print '<td class="liste_titre right">'; + print '</td>'; + } $extrafieldsobjectkey = $taskstatic->table_element; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; @@ -783,22 +853,53 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third print '<tr class="liste_titre nodrag nodrop">'; // print '<td>'.$langs->trans("Project").'</td>'; - if (!empty($arrayfields['t.ref']['checked'])) print_liste_field_titre($arrayfields['t.ref']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, ''); - if (!empty($arrayfields['t.label']['checked'])) print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, ''); - if (!empty($arrayfields['t.description']['checked'])) print_liste_field_titre($arrayfields['t.description']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, ''); - if (!empty($arrayfields['t.dateo']['checked'])) print_liste_field_titre($arrayfields['t.dateo']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['t.datee']['checked'])) print_liste_field_titre($arrayfields['t.datee']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['t.planned_workload']['checked'])) print_liste_field_titre($arrayfields['t.planned_workload']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1); - if (!empty($arrayfields['t.duration_effective']['checked'])) print_liste_field_titre($arrayfields['t.duration_effective']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1); - if (!empty($arrayfields['t.progress_calculated']['checked'])) print_liste_field_titre($arrayfields['t.progress_calculated']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1); - if (!empty($arrayfields['t.progress']['checked'])) print_liste_field_titre($arrayfields['t.progress']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1); - if (!empty($arrayfields['t.progress_summary']['checked'])) print_liste_field_titre($arrayfields['t.progress_summary']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center ', '', 1); - if ($object->usage_bill_time) - { - if (!empty($arrayfields['t.tobill']['checked'])) print_liste_field_titre($arrayfields['t.tobill']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['t.billed']['checked'])) print_liste_field_titre($arrayfields['t.billed']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['t.ref']['checked'])) { + print_liste_field_titre($arrayfields['t.ref']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, ''); + } + if (!empty($arrayfields['t.label']['checked'])) { + print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, ''); + } + if (!empty($arrayfields['t.description']['checked'])) { + print_liste_field_titre($arrayfields['t.description']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, ''); + } + if (!empty($arrayfields['t.dateo']['checked'])) { + print_liste_field_titre($arrayfields['t.dateo']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['t.datee']['checked'])) { + print_liste_field_titre($arrayfields['t.datee']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['t.planned_workload']['checked'])) { + print_liste_field_titre($arrayfields['t.planned_workload']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1); + } + if (!empty($arrayfields['t.duration_effective']['checked'])) { + print_liste_field_titre($arrayfields['t.duration_effective']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1); + } + if (!empty($arrayfields['t.progress_calculated']['checked'])) { + print_liste_field_titre($arrayfields['t.progress_calculated']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1); + } + if (!empty($arrayfields['t.progress']['checked'])) { + print_liste_field_titre($arrayfields['t.progress']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1); + } + if (!empty($arrayfields['t.progress_summary']['checked'])) { + print_liste_field_titre($arrayfields['t.progress_summary']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center ', '', 1); + } + if ($object->usage_bill_time) { + if (!empty($arrayfields['t.tobill']['checked'])) { + print_liste_field_titre($arrayfields['t.tobill']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['t.billed']['checked'])) { + print_liste_field_titre($arrayfields['t.billed']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right '); + } + } + // Contacts of task, disabled because available by default jsut after + /* + if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) { + print_liste_field_titre("TaskRessourceLinks", $_SERVER["PHP_SELF"], '', '', $param, $sortfield, $sortorder); + } + */ + if (!empty($arrayfields['c.assigned']['checked'])) { + print_liste_field_titre($arrayfields['c.assigned']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', ''); } - if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) print_liste_field_titre("TaskRessourceLinks", $_SERVER["PHP_SELF"], '', '', $param, $sortfield, $sortorder); // Extra fields $disablesortlink = 1; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; @@ -809,14 +910,15 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; - if (count($tasksarray) > 0) - { + if (count($tasksarray) > 0) { // Show all lines in taskarray (recursive function to go down on tree) $j = 0; $level = 0; $nboftaskshown = projectLinesa($j, 0, $tasksarray, $level, true, 0, $tasksrole, $object->id, 1, $object->id, $filterprogresscalc, ($object->usage_bill_time ? 1 : 0), $arrayfields); } else { $colspan = 10; - if ($object->usage_bill_time) $colspan += 2; + if ($object->usage_bill_time) { + $colspan += 2; + } print '<tr class="oddeven nobottom"><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoTasks").'</span></td></tr>'; } @@ -828,18 +930,14 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third // Test if database is clean. If not we clean it. //print 'mode='.$_REQUEST["mode"].' $nboftaskshown='.$nboftaskshown.' count($tasksarray)='.count($tasksarray).' count($tasksrole)='.count($tasksrole).'<br>'; - if (!empty($user->rights->projet->all->lire)) // We make test to clean only if user has permission to see all (test may report false positive otherwise) - { - if ($search_user_id == $user->id) - { - if ($nboftaskshown < count($tasksrole)) - { + if (!empty($user->rights->projet->all->lire)) { // We make test to clean only if user has permission to see all (test may report false positive otherwise) + if ($search_user_id == $user->id) { + if ($nboftaskshown < count($tasksrole)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; cleanCorruptedTree($db, 'projet_task', 'fk_task_parent'); } } else { - if ($nboftaskshown < count($tasksarray) && !GETPOST('search_user_id', 'int')) - { + if ($nboftaskshown < count($tasksarray) && !GETPOST('search_user_id', 'int')) { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; cleanCorruptedTree($db, 'projet_task', 'fk_task_parent'); } diff --git a/htdocs/projet/tasks/comment.php b/htdocs/projet/tasks/comment.php index 51bf3b6dfa8..9829e079da6 100644 --- a/htdocs/projet/tasks/comment.php +++ b/htdocs/projet/tasks/comment.php @@ -50,7 +50,9 @@ $planned_workload = ((GETPOST('planned_workloadhour', 'int') != '' || GETPOST('p // Security check $socid = 0; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. -if (!$user->rights->projet->lire) accessforbidden(); +if (!$user->rights->projet->lire) { + accessforbidden(); +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('projecttaskcommentcard', 'globalcard')); @@ -66,13 +68,10 @@ $extrafields->fetch_name_optionals_label($object->table_element); include DOL_DOCUMENT_ROOT.'/core/actions_comments.inc.php'; // Retrieve First Task ID of Project if withprojet is on to allow project prev next to work -if (!empty($project_ref) && !empty($withproject)) -{ - if ($projectstatic->fetch('', $project_ref) > 0) - { +if (!empty($project_ref) && !empty($withproject)) { + if ($projectstatic->fetch('', $project_ref) > 0) { $objectsarray = $object->getTasksArray(0, 0, $projectstatic->id, $socid, 0); - if (count($objectsarray) > 0) - { + if (count($objectsarray) > 0) { $id = $objectsarray[0]->id; } else { header("Location: ".DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.(empty($mode) ? '' : '&mode='.$mode)); @@ -91,10 +90,8 @@ $form = new Form($db); $formother = new FormOther($db); $formfile = new FormFile($db); -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref) > 0) - { +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { $result = $object->fetch_optionals(); $result = $object->fetchComments(); @@ -103,15 +100,18 @@ if ($id > 0 || !empty($ref)) } $result = $projectstatic->fetch($object->fk_project); - if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) $projectstatic->fetchComments(); + if (!empty($projectstatic->socid)) { + $projectstatic->fetch_thirdparty(); + } + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) { + $projectstatic->fetchComments(); + } $object->project = clone $projectstatic; $userWrite = $projectstatic->restrictedProjectArea($user, 'write'); - if (!empty($withproject)) - { + if (!empty($withproject)) { // Tabs for project $tab = 'tasks'; $head = project_prepare_head($projectstatic); @@ -127,15 +127,13 @@ if ($id > 0 || !empty($ref)) // Title $morehtmlref .= $projectstatic->title; // Thirdparty - if ($projectstatic->thirdparty->id > 0) - { + if ($projectstatic->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0); $projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -153,22 +151,19 @@ if ($id > 0 || !empty($ref)) print $langs->trans("Usage"); print '</td>'; print '<td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } - if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); @@ -178,31 +173,39 @@ if ($id > 0 || !empty($ref)) // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; - if ($projectstatic->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); + if ($projectstatic->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } print '</td></tr>'; // Usage - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && !empty($object->usage_opportunity)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && !empty($object->usage_opportunity)) { // Opportunity status print '<tr><td>'.$langs->trans("OpportunityStatus").'</td><td>'; $code = dol_getIdFromCode($db, $projectstatic->opp_status, 'c_lead_status', 'rowid', 'code'); - if ($code) print $langs->trans("OppStatus".$code); + if ($code) { + print $langs->trans("OppStatus".$code); + } print '</td></tr>'; // Opportunity percent print '<tr><td>'.$langs->trans("OpportunityProbability").'</td><td>'; - if (strcmp($object->opp_percent, '')) print price($projectstatic->opp_percent, 0, $langs, 1, 0).' %'; + if (strcmp($object->opp_percent, '')) { + print price($projectstatic->opp_percent, 0, $langs, 1, 0).' %'; + } print '</td></tr>'; // Opportunity Amount print '<tr><td>'.$langs->trans("OpportunityAmount").'</td><td>'; /*if ($object->opp_status) - { - print price($obj->opp_amount, 1, $langs, 1, 0, -1, $conf->currency); - }*/ - if (strcmp($projectstatic->opp_amount, '')) print price($projectstatic->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); + { + print price($obj->opp_amount, 1, $langs, 1, 0, -1, $conf->currency); + }*/ + if (strcmp($projectstatic->opp_amount, '')) { + print price($projectstatic->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); + } print '</td></tr>'; } @@ -213,12 +216,16 @@ if ($id > 0 || !empty($ref)) $end = dol_print_date($projectstatic->date_end, 'day'); print ' - '; print ($end ? $end : '?'); - if ($projectstatic->hasDelay()) print img_warning("Late"); + if ($projectstatic->hasDelay()) { + print img_warning("Late"); + } print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; - if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + if (strcmp($projectstatic->budget_amount, '')) { + print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + } print '</td></tr>'; // Other attributes @@ -269,22 +276,21 @@ if ($id > 0 || !empty($ref)) print dol_get_fiche_head($head, 'task_comment', $langs->trans("Task"), -1, 'projecttask'); - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$_GET["id"].'&withproject='.$withproject, $langs->trans("DeleteATask"), $langs->trans("ConfirmDeleteATask"), "confirm_delete"); } - if (!GETPOST('withproject') || empty($projectstatic->id)) - { + if (!GETPOST('withproject') || empty($projectstatic->id)) { $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1); $object->next_prev_filter = " fk_projet in (".$projectsListId.")"; - } else $object->next_prev_filter = " fk_projet = ".$projectstatic->id; + } else { + $object->next_prev_filter = " fk_projet = ".$projectstatic->id; + } $morehtmlref = ''; // Project - if (empty($withproject)) - { + if (empty($withproject)) { $morehtmlref .= '<div class="refidno">'; $morehtmlref .= $langs->trans("Project").': '; $morehtmlref .= $projectstatic->getNomUrl(1); diff --git a/htdocs/projet/tasks/contact.php b/htdocs/projet/tasks/contact.php index 1b12bf166f2..854e57bbd1f 100644 --- a/htdocs/projet/tasks/contact.php +++ b/htdocs/projet/tasks/contact.php @@ -44,7 +44,9 @@ $project_ref = GETPOST('project_ref', 'alpha'); $socid = 0; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. //$result = restrictedArea($user, 'projet', $id, 'projet_task'); -if (!$user->rights->projet->lire) accessforbidden(); +if (!$user->rights->projet->lire) { + accessforbidden(); +} $object = new Task($db); $projectstatic = new Project($db); @@ -55,8 +57,7 @@ $projectstatic = new Project($db); */ // Add new contact -if ($action == 'addcontact' && $user->rights->projet->creer) -{ +if ($action == 'addcontact' && $user->rights->projet->creer) { $source = 'internal'; if (GETPOST("addsourceexternal")) { $source ='external'; @@ -64,8 +65,7 @@ if ($action == 'addcontact' && $user->rights->projet->creer) $result = $object->fetch($id, $ref); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { if ($source == 'internal') { $idfortaskuser = ((GETPOST("userid") != 0 && GETPOST('userid') != -1) ? GETPOST("userid") : 0); // GETPOST('contactid') may val -1 to mean empty or -2 to means "everybody" $typeid = GETPOST('type'); @@ -73,16 +73,13 @@ if ($action == 'addcontact' && $user->rights->projet->creer) $idfortaskuser = ((GETPOST("contactid") > 0) ? GETPOST("contactid", 'int') : 0); // GETPOST('contactid') may val -1 to mean empty or -2 to means "everybody" $typeid = GETPOST('typecontact'); } - if ($idfortaskuser == -2) - { + if ($idfortaskuser == -2) { $result = $projectstatic->fetch($object->fk_project); - if ($result <= 0) - { + if ($result <= 0) { dol_print_error($db, $projectstatic->error, $projectstatic->errors); } else { $contactsofproject = $projectstatic->getListContactId('internal'); - foreach ($contactsofproject as $key => $val) - { + foreach ($contactsofproject as $key => $val) { $result = $object->add_contact($val, $typeid, $source); } } @@ -105,8 +102,7 @@ if ($action == 'addcontact' && $user->rights->projet->creer) } // bascule du statut d'un contact -if ($action == 'swapstatut' && $user->rights->projet->creer) -{ +if ($action == 'swapstatut' && $user->rights->projet->creer) { if ($object->fetch($id, $ref)) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { @@ -115,13 +111,11 @@ if ($action == 'swapstatut' && $user->rights->projet->creer) } // Efface un contact -if ($action == 'deleteline' && $user->rights->projet->creer) -{ +if ($action == 'deleteline' && $user->rights->projet->creer) { $object->fetch($id, $ref); $result = $object->delete_contact($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id.($withproject ? '&withproject=1' : '')); exit; } else { @@ -130,13 +124,10 @@ if ($action == 'deleteline' && $user->rights->projet->creer) } // Retrieve First Task ID of Project if withprojet is on to allow project prev next to work -if (!empty($project_ref) && !empty($withproject)) -{ - if ($projectstatic->fetch(0, $project_ref) > 0) - { +if (!empty($project_ref) && !empty($withproject)) { + if ($projectstatic->fetch(0, $project_ref) > 0) { $tasksarray = $object->getTasksArray(0, 0, $projectstatic->id, $socid, 0); - if (count($tasksarray) > 0) - { + if (count($tasksarray) > 0) { $id = $tasksarray[0]->id; } else { header("Location: ".DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.($withproject ? '&withproject=1' : '').(empty($mode) ? '' : '&mode='.$mode)); @@ -163,23 +154,26 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref) > 0) - { - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); + } $id = $object->id; // So when doing a search from ref, id is also set correctly. $result = $projectstatic->fetch($object->fk_project); - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) $projectstatic->fetchComments(); - if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) { + $projectstatic->fetchComments(); + } + if (!empty($projectstatic->socid)) { + $projectstatic->fetch_thirdparty(); + } $object->project = clone $projectstatic; $userWrite = $projectstatic->restrictedProjectArea($user, 'write'); - if ($withproject) - { + if ($withproject) { // Tabs for project $tab = 'tasks'; $head = project_prepare_head($projectstatic); @@ -195,15 +189,13 @@ if ($id > 0 || !empty($ref)) // Title $morehtmlref .= $projectstatic->title; // Thirdparty - if ($projectstatic->thirdparty->id > 0) - { + if ($projectstatic->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0); $projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -221,22 +213,19 @@ if ($id > 0 || !empty($ref)) print $langs->trans("Usage"); print '</td>'; print '<td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } - if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); @@ -246,8 +235,11 @@ if ($id > 0 || !empty($ref)) // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; - if ($projectstatic->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); + if ($projectstatic->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } print '</td></tr>'; // Date start - end @@ -257,12 +249,16 @@ if ($id > 0 || !empty($ref)) $end = dol_print_date($projectstatic->date_end, 'day'); print ' - '; print ($end ? $end : '?'); - if ($projectstatic->hasDelay()) print img_warning("Late"); + if ($projectstatic->hasDelay()) { + print img_warning("Late"); + } print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; - if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + if (strcmp($projectstatic->budget_amount, '')) { + print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + } print '</td></tr>'; // Other attributes @@ -315,17 +311,17 @@ if ($id > 0 || !empty($ref)) $param = (GETPOST('withproject') ? '&withproject=1' : ''); $linkback = GETPOST('withproject') ? '<a href="'.DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.'">'.$langs->trans("BackToList").'</a>' : ''; - if (!GETPOST('withproject') || empty($projectstatic->id)) - { + if (!GETPOST('withproject') || empty($projectstatic->id)) { $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1); $object->next_prev_filter = " fk_projet in (".$projectsListId.")"; - } else $object->next_prev_filter = " fk_projet = ".$projectstatic->id; + } else { + $object->next_prev_filter = " fk_projet = ".$projectstatic->id; + } $morehtmlref = ''; // Project - if (empty($withproject)) - { + if (empty($withproject)) { $result = $projectstatic->fetch($object->fk_project); $morehtmlref .= '<div class="refidno">'; $morehtmlref .= $langs->trans("Project").': '; @@ -354,8 +350,8 @@ if ($id > 0 || !empty($ref)) $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); foreach($dirtpls as $reldir) { - $res=@include dol_buildpath($reldir.'/contacts.tpl.php'); - if ($res) break; + $res=@include dol_buildpath($reldir.'/contacts.tpl.php'); + if ($res) break; } */ @@ -366,12 +362,13 @@ if ($id > 0 || !empty($ref)) print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="addcontact">'; print '<input type="hidden" name="id" value="'.$id.'">'; - if ($withproject) print '<input type="hidden" name="withproject" value="'.$withproject.'">'; + if ($withproject) { + print '<input type="hidden" name="withproject" value="'.$withproject.'">'; + } print '<table class="noborder centpercent">'; - if ($action != 'editline' && $user->rights->projet->creer) - { + if ($action != 'editline' && $user->rights->projet->creer) { print '<tr class="liste_titre">'; print '<td>'.$langs->trans("NatureOfContact").'</td>'; print '<td>'.$langs->trans("ThirdParty").'</td>'; @@ -393,8 +390,11 @@ if ($id > 0 || !empty($ref)) print '<td>'; // On recupere les id des users deja selectionnes - if ($object->project->public) $contactsofproject = ''; // Everybody - else $contactsofproject = $projectstatic->getListContactId('internal'); + if ($object->project->public) { + $contactsofproject = ''; // Everybody + } else { + $contactsofproject = $projectstatic->getListContactId('internal'); + } print $form->select_dolusers((GETPOSTISSET('userid') ? GETPOST('userid', 'int') : $user->id), 'userid', 0, '', 0, '', $contactsofproject, 0, 0, 0, '', 1, $langs->trans("ResourceNotAssignedToProject")); print '</td>'; print '<td>'; @@ -404,8 +404,7 @@ if ($id > 0 || !empty($ref)) print '</tr>'; // Line to add an external contact. Only if project linked to a third party. - if ($projectstatic->socid) - { + if ($projectstatic->socid) { print '<tr class="oddeven">'; print '<td class="nowrap">'; @@ -427,7 +426,9 @@ if ($id > 0 || !empty($ref)) $formcompany->selectTypeContact($object, '', 'typecontact', 'external', 'rowid'); print '</td>'; print '<td class="right" colspan="3" ><input type="submit" class="button" id="add-customer-contact" name="addsourceexternal" value="'.$langs->trans("Add").'"'; - if (!$nbofcontacts) print ' disabled'; + if (!$nbofcontacts) { + print ' disabled'; + } print '></td>'; print '</tr>'; } @@ -445,44 +446,42 @@ if ($id > 0 || !empty($ref)) $companystatic = new Societe($db); - foreach (array('internal', 'external') as $source) - { + foreach (array('internal', 'external') as $source) { $tab = $object->liste_contact(-1, $source); $num = count($tab); $i = 0; - while ($i < $num) - { + while ($i < $num) { print '<tr class="oddeven" valign="top">'; // Source print '<td class="left">'; - if ($tab[$i]['source'] == 'internal') print $langs->trans("User"); - if ($tab[$i]['source'] == 'external') print $langs->trans("ThirdPartyContact"); + if ($tab[$i]['source'] == 'internal') { + print $langs->trans("User"); + } + if ($tab[$i]['source'] == 'external') { + print $langs->trans("ThirdPartyContact"); + } print '</td>'; // Societe print '<td class="left">'; - if ($tab[$i]['socid'] > 0) - { + if ($tab[$i]['socid'] > 0) { $companystatic->fetch($tab[$i]['socid']); print $companystatic->getNomUrl(1); } - if ($tab[$i]['socid'] < 0) - { + if ($tab[$i]['socid'] < 0) { print $conf->global->MAIN_INFO_SOCIETE_NOM; } - if (!$tab[$i]['socid']) - { + if (!$tab[$i]['socid']) { print '&nbsp;'; } print '</td>'; // Contact print '<td>'; - if ($tab[$i]['source'] == 'internal') - { + if ($tab[$i]['source'] == 'internal') { $userstatic->id = $tab[$i]['id']; $userstatic->lastname = $tab[$i]['lastname']; $userstatic->firstname = $tab[$i]['firstname']; @@ -493,8 +492,7 @@ if ($id > 0 || !empty($ref)) print $userstatic->getNomUrl(-1); } - if ($tab[$i]['source'] == 'external') - { + if ($tab[$i]['source'] == 'external') { $contactstatic->id = $tab[$i]['id']; $contactstatic->lastname = $tab[$i]['lastname']; $contactstatic->firstname = $tab[$i]['firstname']; @@ -510,15 +508,18 @@ if ($id > 0 || !empty($ref)) // Statut print '<td class="center">'; // Activation desativation du contact - if ($object->statut >= 0) print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=swapstatut&ligne='.$tab[$i]['rowid'].($withproject ? '&withproject=1' : '').'">'; + if ($object->statut >= 0) { + print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=swapstatut&ligne='.$tab[$i]['rowid'].($withproject ? '&withproject=1' : '').'">'; + } print $contactstatic->LibStatut($tab[$i]['status'], 3); - if ($object->statut >= 0) print '</a>'; + if ($object->statut >= 0) { + print '</a>'; + } print '</td>'; // Icon update et delete print '<td class="center nowrap">'; - if ($user->rights->projet->creer) - { + if ($user->rights->projet->creer) { print '&nbsp;'; print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deleteline&token='.newToken().'&lineid='.$tab[$i]['rowid'].($withproject ? '&withproject=1' : '').'">'; print img_picto($langs->trans('Unlink'), 'unlink'); @@ -539,8 +540,7 @@ if ($id > 0 || !empty($ref)) } } -if (is_object($hookmanager)) -{ +if (is_object($hookmanager)) { $hookmanager->initHooks(array('contacttpl')); $parameters = array(); $reshook = $hookmanager->executeHooks('formContactTpl', $parameters, $object, $action); diff --git a/htdocs/projet/tasks/document.php b/htdocs/projet/tasks/document.php index ca273bb36ef..9e2ea202601 100644 --- a/htdocs/projet/tasks/document.php +++ b/htdocs/projet/tasks/document.php @@ -48,19 +48,27 @@ $project_ref = GETPOST('project_ref', 'alpha'); $socid = 0; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. //$result=restrictedArea($user,'projet',$id,''); -if (!$user->rights->projet->lire) accessforbidden(); +if (!$user->rights->projet->lire) { + accessforbidden(); +} // Get parameters $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"; +} $object = new Task($db); $projectstatic = new Project($db); @@ -70,13 +78,10 @@ $projectstatic = new Project($db); */ // Retrieve First Task ID of Project if withprojet is on to allow project prev next to work -if (!empty($project_ref) && !empty($withproject)) -{ - if ($projectstatic->fetch(0, $project_ref) > 0) - { +if (!empty($project_ref) && !empty($withproject)) { + if ($projectstatic->fetch(0, $project_ref) > 0) { $tasksarray = $object->getTasksArray(0, 0, $projectstatic->id, $socid, 0); - if (count($tasksarray) > 0) - { + if (count($tasksarray) > 0) { $id = $tasksarray[0]->id; $object->fetch($id); } else { @@ -86,13 +91,15 @@ if (!empty($project_ref) && !empty($withproject)) } } -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref) > 0) - { - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); + } $projectstatic->fetch($object->fk_project); - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) $projectstatic->fetchComments(); + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) { + $projectstatic->fetchComments(); + } if (!empty($projectstatic->socid)) { $projectstatic->fetch_thirdparty(); @@ -106,7 +113,7 @@ if ($id > 0 || !empty($ref)) } } -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -117,14 +124,12 @@ $form = new Form($db); llxHeader('', $langs->trans('Task')); -if ($object->id > 0) -{ +if ($object->id > 0) { $projectstatic->fetch_thirdparty(); $userWrite = $projectstatic->restrictedProjectArea($user, 'write'); - if (!empty($withproject)) - { + if (!empty($withproject)) { // Tabs for project $tab = 'tasks'; $head = project_prepare_head($projectstatic); @@ -141,15 +146,13 @@ if ($object->id > 0) // Title $morehtmlref .= $projectstatic->title; // Thirdparty - if ($projectstatic->thirdparty->id > 0) - { + if ($projectstatic->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0); $projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -167,22 +170,19 @@ if ($object->id > 0) print $langs->trans("Usage"); print '</td>'; print '<td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } - if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); @@ -192,8 +192,11 @@ if ($object->id > 0) // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; - if ($projectstatic->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); + if ($projectstatic->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } print '</td></tr>'; // Date start - end @@ -203,12 +206,16 @@ if ($object->id > 0) $end = dol_print_date($projectstatic->date_end, 'day'); print ' - '; print ($end ? $end : '?'); - if ($projectstatic->hasDelay()) print img_warning("Late"); + if ($projectstatic->hasDelay()) { + print img_warning("Late"); + } print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; - if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + if (strcmp($projectstatic->budget_amount, '')) { + print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + } print '</td></tr>'; // Other attributes @@ -255,25 +262,24 @@ if ($object->id > 0) // Files list constructor $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } $param = (GETPOST('withproject') ? '&withproject=1' : ''); $linkback = GETPOST('withproject') ? '<a href="'.DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.'">'.$langs->trans("BackToList").'</a>' : ''; - if (!GETPOST('withproject') || empty($projectstatic->id)) - { + if (!GETPOST('withproject') || empty($projectstatic->id)) { $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1); $object->next_prev_filter = " fk_projet in (".$projectsListId.")"; - } else $object->next_prev_filter = " fk_projet = ".$projectstatic->id; + } else { + $object->next_prev_filter = " fk_projet = ".$projectstatic->id; + } $morehtmlref = ''; // Project - if (empty($withproject)) - { + if (empty($withproject)) { $morehtmlref .= '<div class="refidno">'; $morehtmlref .= $langs->trans("Project").': '; $morehtmlref .= $projectstatic->getNomUrl(1); @@ -307,7 +313,9 @@ if ($object->id > 0) print '<br>'; $param = ''; - if ($withproject) $param .= '&withproject=1'; + if ($withproject) { + $param .= '&withproject=1'; + } $modulepart = 'project_task'; $permission = $user->rights->projet->creer; $permtoedit = $user->rights->projet->creer; diff --git a/htdocs/projet/tasks/list.php b/htdocs/projet/tasks/list.php index b318b44f053..57f9ec2b24f 100644 --- a/htdocs/projet/tasks/list.php +++ b/htdocs/projet/tasks/list.php @@ -47,10 +47,12 @@ $search_categ = GETPOST("search_categ", 'alpha'); $search_project = GETPOST('search_project'); $search_projectstatus = GETPOST('search_projectstatus'); -if (!isset($search_projectstatus) || $search_projectstatus === '') -{ - if ($search_all != '') $search_projectstatus = -1; - else $search_projectstatus = 1; +if (!isset($search_projectstatus) || $search_projectstatus === '') { + if ($search_all != '') { + $search_projectstatus = -1; + } else { + $search_projectstatus = 1; + } } $search_project_ref = GETPOST('search_project_ref'); @@ -65,7 +67,9 @@ $search_task_progress = GETPOST('search_task_progress'); $search_societe = GETPOST('search_societe'); $mine = $_REQUEST['mode'] == 'mine' ? 1 : 0; -if ($mine) { $search_task_user = $user->id; $mine = 0; } +if ($mine) { + $search_task_user = $user->id; $mine = 0; +} $search_sday = GETPOST('search_sday', 'int'); $search_smonth = GETPOST('search_smonth', 'int'); @@ -89,7 +93,9 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Security check $socid = 0; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. -if (!$user->rights->projet->lire) accessforbidden(); +if (!$user->rights->projet->lire) { + accessforbidden(); +} $diroutputmassaction = $conf->projet->dir_output.'/tasks/temp/massgeneration/'.$user->id; @@ -97,12 +103,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 (!$sortfield) $sortfield = 'p.ref'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'p.ref'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -111,7 +123,9 @@ $fieldstosearchall = array( 't.description'=>"Description", 't.note_public'=>"NotePublic", ); -if (empty($user->socid)) $fieldstosearchall['t.note_private'] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall['t.note_private'] = "NotePrivate"; +} $arrayfields = array( 't.fk_task_parent'=>array('label'=>$langs->trans("RefTaskParent"), 'checked'=>0, 'position'=>70), @@ -146,21 +160,25 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * 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)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_all = ""; $search_categ = ""; $search_project = ""; @@ -193,7 +211,9 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } -if (empty($search_projectstatus) && $search_projectstatus == '') $search_projectstatus = 1; +if (empty($search_projectstatus) && $search_projectstatus == '') { + $search_projectstatus = 1; +} @@ -209,8 +229,12 @@ $socstatic = new Societe($db); $projectstatic = new Project($db); $puser = new User($db); $tuser = new User($db); -if ($search_project_user > 0) $puser->fetch($search_project_user); -if ($search_task_user > 0) $tuser->fetch($search_task_user); +if ($search_project_user > 0) { + $puser->fetch($search_project_user); +} +if ($search_task_user > 0) { + $tuser->fetch($search_task_user); +} $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; @@ -220,14 +244,15 @@ $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfi $title = $langs->trans("Activities"); //if ($search_task_user == $user->id) $title=$langs->trans("MyActivities"); -if ($id) -{ +if ($id) { $projectstatic->fetch($id); $projectstatic->fetch_thirdparty(); } // Get list of project id allowed to user (in a string list separated by coma) -if (!$user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid); +if (!$user->rights->projet->all->lire) { + $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid); +} //var_dump($projectsListId); // Get id of types of contacts for projects (This list never contains a lot of elements) @@ -236,28 +261,32 @@ $sql = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc" $sql .= " WHERE ctc.element = '".$db->escape($projectstatic->element)."'"; $sql .= " AND ctc.source = 'internal'"; $resql = $db->query($sql); -if ($resql) -{ - while ($obj = $db->fetch_object($resql)) - { +if ($resql) { + while ($obj = $db->fetch_object($resql)) { $listofprojectcontacttype[$obj->rowid] = $obj->code; } -} else dol_print_error($db); -if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0] = '0'; // To avoid sql syntax error if not found +} else { + dol_print_error($db); +} +if (count($listofprojectcontacttype) == 0) { + $listofprojectcontacttype[0] = '0'; // To avoid sql syntax error if not found +} // Get id of types of contacts for tasks (This list never contains a lot of elements) $listoftaskcontacttype = array(); $sql = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc"; $sql .= " WHERE ctc.element = '".$db->escape($object->element)."'"; $sql .= " AND ctc.source = 'internal'"; $resql = $db->query($sql); -if ($resql) -{ - while ($obj = $db->fetch_object($resql)) - { +if ($resql) { + while ($obj = $db->fetch_object($resql)) { $listoftaskcontacttype[$obj->rowid] = $obj->code; } -} else dol_print_error($db); -if (count($listoftaskcontacttype) == 0) $listoftaskcontacttype[0] = '0'; // To avoid sql syntax error if not found +} else { + dol_print_error($db); +} +if (count($listoftaskcontacttype) == 0) { + $listoftaskcontacttype[0] = '0'; // To avoid sql syntax error if not found +} $distinct = 'DISTINCT'; // We add distinct until we are added a protection to be sure a contact of a project and task is assigned only once. $sql = "SELECT ".$distinct." p.rowid as projectid, p.ref as projectref, p.title as projecttitle, p.fk_statut as projectstatus, p.datee as projectdatee, p.fk_opp_status, p.public, p.fk_user_creat as projectusercreate, p.usage_bill_time,"; @@ -266,15 +295,18 @@ $sql .= " t.datec as date_creation, t.dateo as date_start, t.datee as date_end, $sql .= " t.rowid as id, t.ref, t.label, t.planned_workload, t.duration_effective, t.progress, t.fk_statut, "; $sql .= " t.description, t.fk_task_parent"; // We'll need these fields in order to filter by categ -if ($search_categ) $sql .= ", cs.fk_categorie, cs.fk_project"; +if ($search_categ) { + $sql .= ", cs.fk_categorie, cs.fk_project"; +} // Add sum fields -if (!empty($arrayfields['t.tobill']['checked']) || !empty($arrayfields['t.billed']['checked'])) -{ +if (!empty($arrayfields['t.tobill']['checked']) || !empty($arrayfields['t.billed']['checked'])) { $sql .= " , SUM(tt.task_duration * ".$db->ifsql("invoice_id IS NULL", "1", "0").") as tobill, SUM(tt.task_duration * ".$db->ifsql("invoice_id IS NULL", "0", "1").") as billed"; } // 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 : ''); + 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(); @@ -283,69 +315,113 @@ $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; // We'll need this table joined to the select in order to filter by categ -if (!empty($search_categ)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_project as cs ON p.rowid = cs.fk_project"; // We'll need this table joined to the select in order to filter by categ +if (!empty($search_categ)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_project as cs ON p.rowid = cs.fk_project"; // We'll need this table joined to the select in order to filter by categ +} $sql .= ", ".MAIN_DB_PREFIX."projet_task as t"; -if (!empty($arrayfields['t.tobill']['checked']) || !empty($arrayfields['t.billed']['checked'])) -{ +if (!empty($arrayfields['t.tobill']['checked']) || !empty($arrayfields['t.billed']['checked'])) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_time as tt ON tt.fk_task = t.rowid"; } -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($search_project_user > 0) $sql .= ", ".MAIN_DB_PREFIX."element_contact as ecp"; -if ($search_task_user > 0) $sql .= ", ".MAIN_DB_PREFIX."element_contact as ect"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if ($search_project_user > 0) { + $sql .= ", ".MAIN_DB_PREFIX."element_contact as ecp"; +} +if ($search_task_user > 0) { + $sql .= ", ".MAIN_DB_PREFIX."element_contact as ect"; +} $sql .= " WHERE t.fk_projet = p.rowid"; $sql .= " AND p.entity IN (".getEntity('project').')'; -if (!$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".($projectsListId ? $projectsListId : '0').")"; // public and assigned to projects, or restricted to company for external users -if (is_object($projectstatic) && $projectstatic->id > 0) $sql .= " AND p.rowid = ".$projectstatic->id; +if (!$user->rights->projet->all->lire) { + $sql .= " AND p.rowid IN (".($projectsListId ? $projectsListId : '0').")"; // public and assigned to projects, or restricted to company for external users +} +if (is_object($projectstatic) && $projectstatic->id > 0) { + $sql .= " AND p.rowid = ".$projectstatic->id; +} // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser -if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; -if ($search_categ > 0) $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ); -if ($search_categ == -2) $sql .= " AND cs.fk_categorie IS NULL"; -if ($search_project_ref) $sql .= natural_search('p.ref', $search_project_ref); -if ($search_project_title) $sql .= natural_search('p.title', $search_project_title); -if ($search_task_ref) $sql .= natural_search('t.ref', $search_task_ref); -if ($search_task_label) $sql .= natural_search('t.label', $search_task_label); -if ($search_task_description) $sql .= natural_search('t.description', $search_task_description); -if ($search_task_ref_parent) $sql .= ' AND t.fk_task_parent IN (SELECT ipt.rowid FROM '.MAIN_DB_PREFIX.'projet_task as ipt WHERE '.natural_search('ipt.ref', $search_task_ref_parent, 0, 1).')'; -if ($search_task_progress) $sql .= natural_search('t.progress', $search_task_progress, 1); -if ($search_societe) $sql .= natural_search('s.nom', $search_societe); +if ($socid) { + $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; +} +if ($search_categ > 0) { + $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ); +} +if ($search_categ == -2) { + $sql .= " AND cs.fk_categorie IS NULL"; +} +if ($search_project_ref) { + $sql .= natural_search('p.ref', $search_project_ref); +} +if ($search_project_title) { + $sql .= natural_search('p.title', $search_project_title); +} +if ($search_task_ref) { + $sql .= natural_search('t.ref', $search_task_ref); +} +if ($search_task_label) { + $sql .= natural_search('t.label', $search_task_label); +} +if ($search_task_description) { + $sql .= natural_search('t.description', $search_task_description); +} +if ($search_task_ref_parent) { + $sql .= ' AND t.fk_task_parent IN (SELECT ipt.rowid FROM '.MAIN_DB_PREFIX.'projet_task as ipt WHERE '.natural_search('ipt.ref', $search_task_ref_parent, 0, 1).')'; +} +if ($search_task_progress) { + $sql .= natural_search('t.progress', $search_task_progress, 1); +} +if ($search_societe) { + $sql .= natural_search('s.nom', $search_societe); +} $sql .= dolSqlDateFilter('t.dateo', $search_sday, $search_smonth, $search_syear); $sql .= dolSqlDateFilter('t.datee', $search_eday, $search_emonth, $search_eyear); -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); -if ($search_projectstatus >= 0) -{ - if ($search_projectstatus == 99) $sql .= " AND p.fk_statut <> 2"; - else $sql .= " AND p.fk_statut = ".$db->escape($search_projectstatus); +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} +if ($search_projectstatus >= 0) { + if ($search_projectstatus == 99) { + $sql .= " AND p.fk_statut <> 2"; + } else { + $sql .= " AND p.fk_statut = ".$db->escape($search_projectstatus); + } +} +if ($search_public != '') { + $sql .= " AND p.public = ".$db->escape($search_public); +} +if ($search_project_user > 0) { + $sql .= " AND ecp.fk_c_type_contact IN (".join(',', array_keys($listofprojectcontacttype)).") AND ecp.element_id = p.rowid AND ecp.fk_socpeople = ".$search_project_user; +} +if ($search_task_user > 0) { + $sql .= " AND ect.fk_c_type_contact IN (".join(',', array_keys($listoftaskcontacttype)).") AND ect.element_id = t.rowid AND ect.fk_socpeople = ".$search_task_user; } -if ($search_public != '') $sql .= " AND p.public = ".$db->escape($search_public); -if ($search_project_user > 0) $sql .= " AND ecp.fk_c_type_contact IN (".join(',', array_keys($listofprojectcontacttype)).") AND ecp.element_id = p.rowid AND ecp.fk_socpeople = ".$search_project_user; -if ($search_task_user > 0) $sql .= " AND ect.fk_c_type_contact IN (".join(',', array_keys($listoftaskcontacttype)).") AND ect.element_id = t.rowid AND ect.fk_socpeople = ".$search_task_user; // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; -if (!empty($arrayfields['t.tobill']['checked']) || !empty($arrayfields['t.billed']['checked'])) -{ +if (!empty($arrayfields['t.tobill']['checked']) || !empty($arrayfields['t.billed']['checked'])) { $sql .= " GROUP BY p.rowid, p.ref, p.title, p.fk_statut, p.datee, p.fk_opp_status, p.public, p.fk_user_creat,"; $sql .= " s.nom, s.rowid,"; $sql .= " t.datec, t.dateo, t.datee, t.tms,"; $sql .= " t.rowid, t.ref, t.label, t.planned_workload, t.duration_effective, t.progress, t.fk_statut"; - if ($search_categ) $sql .= ", cs.fk_categorie, cs.fk_project"; + if ($search_categ) { + $sql .= ", cs.fk_categorie, cs.fk_project"; + } // 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 : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key : ''); + } } } $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -356,8 +432,7 @@ $sql .= $db->plimit($limit + 1, $offset); dol_syslog("list allowed project", LOG_DEBUG); $resql = $db->query($sql); -if (!$resql) -{ +if (!$resql) { dol_print_error($db); exit; } @@ -366,8 +441,7 @@ $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->id; header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withproject=1'); @@ -378,30 +452,78 @@ $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos"; llxHeader("", $title, $help_url); $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_sday) $param .= '&search_sday='.urlencode($search_sday); -if ($search_smonth) $param .= '&search_smonth='.urlencode($search_smonth); -if ($search_syear) $param .= '&search_syear='.urlencode($search_syear); -if ($search_eday) $param .= '&search_eday='.urlencode($search_eday); -if ($search_emonth) $param .= '&search_emonth='.urlencode($search_emonth); -if ($search_eyear) $param .= '&search_eyear='.urlencode($search_eyear); -if ($socid) $param .= '&socid='.urlencode($socid); -if ($search_all != '') $param .= '&search_all='.urlencode($search_all); -if ($search_project_ref != '') $param .= '&search_project_ref='.urlencode($search_project_ref); -if ($search_project_title != '') $param .= '&search_project_title='.urlencode($search_project_title); -if ($search_task_ref != '') $param .= '&search_task_ref='.urlencode($search_ref); -if ($search_task_label != '') $param .= '&search_task_label='.urlencode($search_label); -if ($search_task_description != '') $param .= '&search_task_description='.urlencode($search_description); -if ($search_task_ref_parent != '') $param .= '&search_task_ref_parent='.urlencode($search_task_ref_parent); -if ($search_task_progress != '') $param .= '&search_task_progress='.urlencode($search_task_progress); -if ($search_societe != '') $param .= '&search_societe='.urlencode($search_societe); -if ($search_projectstatus != '') $param .= '&search_projectstatus='.urlencode($search_projectstatus); -if ((is_numeric($search_opp_status) && $search_opp_status >= 0) || in_array($search_opp_status, array('all', 'none'))) $param .= '&search_opp_status='.urlencode($search_opp_status); -if ($search_public != '') $param .= '&search_public='.urlencode($search_public); -if ($search_project_user != '') $param .= '&search_project_user='.urlencode($search_project_user); -if ($search_task_user > 0) $param .= '&search_task_user='.urlencode($search_task_user); -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 ($search_sday) { + $param .= '&search_sday='.urlencode($search_sday); +} +if ($search_smonth) { + $param .= '&search_smonth='.urlencode($search_smonth); +} +if ($search_syear) { + $param .= '&search_syear='.urlencode($search_syear); +} +if ($search_eday) { + $param .= '&search_eday='.urlencode($search_eday); +} +if ($search_emonth) { + $param .= '&search_emonth='.urlencode($search_emonth); +} +if ($search_eyear) { + $param .= '&search_eyear='.urlencode($search_eyear); +} +if ($socid) { + $param .= '&socid='.urlencode($socid); +} +if ($search_all != '') { + $param .= '&search_all='.urlencode($search_all); +} +if ($search_project_ref != '') { + $param .= '&search_project_ref='.urlencode($search_project_ref); +} +if ($search_project_title != '') { + $param .= '&search_project_title='.urlencode($search_project_title); +} +if ($search_task_ref != '') { + $param .= '&search_task_ref='.urlencode($search_ref); +} +if ($search_task_label != '') { + $param .= '&search_task_label='.urlencode($search_label); +} +if ($search_task_description != '') { + $param .= '&search_task_description='.urlencode($search_description); +} +if ($search_task_ref_parent != '') { + $param .= '&search_task_ref_parent='.urlencode($search_task_ref_parent); +} +if ($search_task_progress != '') { + $param .= '&search_task_progress='.urlencode($search_task_progress); +} +if ($search_societe != '') { + $param .= '&search_societe='.urlencode($search_societe); +} +if ($search_projectstatus != '') { + $param .= '&search_projectstatus='.urlencode($search_projectstatus); +} +if ((is_numeric($search_opp_status) && $search_opp_status >= 0) || in_array($search_opp_status, array('all', 'none'))) { + $param .= '&search_opp_status='.urlencode($search_opp_status); +} +if ($search_public != '') { + $param .= '&search_public='.urlencode($search_public); +} +if ($search_project_user != '') { + $param .= '&search_project_user='.urlencode($search_project_user); +} +if ($search_task_user > 0) { + $param .= '&search_task_user='.urlencode($search_task_user); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -411,14 +533,20 @@ $arrayofmassactions = array( // 'builddoc'=>$langs->trans("PDFMerge"), ); //if($user->rights->societe->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); -if ($user->rights->societe->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($user->rights->societe->supprimer) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $newcardbutton = dolGetButtonTitle($langs->trans('NewTask'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/projet/tasks.php?action=create', '', $user->rights->projet->creer); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; @@ -429,10 +557,14 @@ print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; // Show description of content $texthelp = ''; -if ($search_task_user == $user->id) $texthelp .= $langs->trans("MyTasksDesc"); -else { - if ($user->rights->projet->all->lire && !$socid) $texthelp .= $langs->trans("TasksOnProjectsDesc"); - else $texthelp .= $langs->trans("TasksOnProjectsPublicDesc"); +if ($search_task_user == $user->id) { + $texthelp .= $langs->trans("MyTasksDesc"); +} else { + if ($user->rights->projet->all->lire && !$socid) { + $texthelp .= $langs->trans("TasksOnProjectsDesc"); + } else { + $texthelp .= $langs->trans("TasksOnProjectsPublicDesc"); + } } print_barre_liste($form->textwithpicto($title, $texthelp), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'projecttask', 0, $newcardbutton, '', $limit, 0, 0, 1); @@ -443,17 +575,17 @@ $objecttmp = new Task($db); $trackid = 'tas'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } $morehtmlfilter = ''; // Filter on categories -if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) -{ +if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('ProjectCategories').': '; @@ -465,7 +597,9 @@ if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('ProjectsWithThisUserAsContact').' '; $includeonly = ''; -if (empty($user->rights->user->user->lire)) $includeonly = array($user->id); +if (empty($user->rights->user->user->lire)) { + $includeonly = array($user->id); +} $moreforfilter .= $form->select_dolusers($search_project_user ? $search_project_user : '', 'search_project_user', 1, '', 0, $includeonly, '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter .= '</div>'; @@ -473,12 +607,13 @@ $moreforfilter .= '</div>'; $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('TasksWithThisUserAsContact').': '; $includeonly = ''; -if (empty($user->rights->user->user->lire)) $includeonly = array($user->id); +if (empty($user->rights->user->user->lire)) { + $includeonly = array($user->id); +} $moreforfilter .= $form->select_dolusers($search_task_user, 'search_task_user', 1, '', 0, $includeonly, '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter .= '</div>'; -if (!empty($moreforfilter)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; $parameters = array(); @@ -487,109 +622,116 @@ if (!empty($moreforfilter)) print '</div>'; } -if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +} print '<div class="div-table-responsive">'; print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'" id="tablelines3">'."\n"; print '<tr class="liste_titre_filter">'; -if (!empty($arrayfields['t.fk_task_parent']['checked'])) -{ +if (!empty($arrayfields['t.fk_task_parent']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_task_ref_parent" value="'.dol_escape_htmltag($search_task_ref_parent).'" size="4">'; print '</td>'; } -if (!empty($arrayfields['t.ref']['checked'])) -{ +if (!empty($arrayfields['t.ref']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_task_ref" value="'.dol_escape_htmltag($search_task_ref).'" size="4">'; print '</td>'; } -if (!empty($arrayfields['t.label']['checked'])) -{ +if (!empty($arrayfields['t.label']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'" size="8">'; print '</td>'; } // Task Description -if (!empty($arrayfields['t.description']['checked'])) -{ +if (!empty($arrayfields['t.description']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_task_description" value="'.dol_escape_htmltag($search_task_description).'" size="8">'; print '</td>'; } // Start date -if (!empty($arrayfields['t.dateo']['checked'])) -{ +if (!empty($arrayfields['t.dateo']['checked'])) { print '<td class="liste_titre center minwidth150">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_sday" value="'.$search_sday.'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat" type="text" size="1" maxlength="2" name="search_sday" value="'.$search_sday.'">'; + } print '<input class="flat" type="text" size="1" maxlength="2" name="search_smonth" value="'.$search_smonth.'">'; $formother->select_year($search_syear ? $search_syear : -1, 'search_syear', 1, 20, 5); print '</td>'; } // End date -if (!empty($arrayfields['t.datee']['checked'])) -{ +if (!empty($arrayfields['t.datee']['checked'])) { print '<td class="liste_titre center minwidth150">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_eday" value="'.$search_eday.'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat" type="text" size="1" maxlength="2" name="search_eday" value="'.$search_eday.'">'; + } print '<input class="flat" type="text" size="1" maxlength="2" name="search_emonth" value="'.$search_emonth.'">'; $formother->select_year($search_eyear ? $search_eyear : -1, 'search_eyear', 1, 20, 5); print '</td>'; } -if (!empty($arrayfields['p.ref']['checked'])) -{ +if (!empty($arrayfields['p.ref']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_project_ref" value="'.$search_project_ref.'" size="4">'; print '</td>'; } -if (!empty($arrayfields['p.title']['checked'])) -{ +if (!empty($arrayfields['p.title']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_project_title" value="'.$search_project_title.'" size="6">'; print '</td>'; } -if (!empty($arrayfields['s.nom']['checked'])) -{ +if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_societe" value="'.dol_escape_htmltag($search_societe).'" size="4">'; print '</td>'; } -if (!empty($arrayfields['p.fk_statut']['checked'])) -{ +if (!empty($arrayfields['p.fk_statut']['checked'])) { print '<td class="liste_titre center">'; $arrayofstatus = array(); - foreach ($projectstatic->statuts_short as $key => $val) $arrayofstatus[$key] = $langs->trans($val); + foreach ($projectstatic->statuts_short as $key => $val) { + $arrayofstatus[$key] = $langs->trans($val); + } $arrayofstatus['99'] = $langs->trans("NotClosed").' ('.$langs->trans('Draft').'+'.$langs->trans('Opened').')'; print $form->selectarray('search_projectstatus', $arrayofstatus, $search_projectstatus, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100'); print '</td>'; } -if (!empty($arrayfields['t.planned_workload']['checked'])) print '<td class="liste_titre"></td>'; -if (!empty($arrayfields['t.duration_effective']['checked'])) print '<td class="liste_titre"></td>'; -if (!empty($arrayfields['t.progress_calculated']['checked'])) print '<td class="liste_titre"></td>'; -if (!empty($arrayfields['t.progress']['checked'])) -{ +if (!empty($arrayfields['t.planned_workload']['checked'])) { + print '<td class="liste_titre"></td>'; +} +if (!empty($arrayfields['t.duration_effective']['checked'])) { + print '<td class="liste_titre"></td>'; +} +if (!empty($arrayfields['t.progress_calculated']['checked'])) { + print '<td class="liste_titre"></td>'; +} +if (!empty($arrayfields['t.progress']['checked'])) { print '<td class="liste_titre center">'; print '<input type="text" class="flat" name="search_task_progress" value="'.$search_task_progress.'" size="4">'; print '</td>'; } -if (!empty($arrayfields['t.progress_summary']['checked'])) print '<td class="liste_titre"></td>'; -if (!empty($arrayfields['t.tobill']['checked'])) print '<td class="liste_titre"></td>'; -if (!empty($arrayfields['t.billed']['checked'])) print '<td class="liste_titre"></td>'; +if (!empty($arrayfields['t.progress_summary']['checked'])) { + print '<td class="liste_titre"></td>'; +} +if (!empty($arrayfields['t.tobill']['checked'])) { + print '<td class="liste_titre"></td>'; +} +if (!empty($arrayfields['t.billed']['checked'])) { + print '<td class="liste_titre"></td>'; +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (!empty($arrayfields['t.datec']['checked'])) -{ +if (!empty($arrayfields['t.datec']['checked'])) { // Date creation print '<td class="liste_titre">'; print '</td>'; } -if (!empty($arrayfields['t.tms']['checked'])) -{ +if (!empty($arrayfields['t.tms']['checked'])) { // Date modification print '<td class="liste_titre">'; print '</td>'; @@ -602,44 +744,85 @@ print '</td>'; print "</tr>\n"; print '<tr class="liste_titre">'; -if (!empty($arrayfields['t.fk_task_parent']['checked'])) print_liste_field_titre($arrayfields['t.fk_task_parent']['label'], $_SERVER["PHP_SELF"], "t.fk_task_parent", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['t.ref']['checked'])) print_liste_field_titre($arrayfields['t.ref']['label'], $_SERVER["PHP_SELF"], "t.ref", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['t.label']['checked'])) print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER["PHP_SELF"], "t.label", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['t.description']['checked'])) print_liste_field_titre($arrayfields['t.description']['label'], $_SERVER["PHP_SELF"], "t.description", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['t.dateo']['checked'])) print_liste_field_titre($arrayfields['t.dateo']['label'], $_SERVER["PHP_SELF"], "t.dateo", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['t.datee']['checked'])) print_liste_field_titre($arrayfields['t.datee']['label'], $_SERVER["PHP_SELF"], "t.datee", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], "p.ref", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['p.title']['checked'])) print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER["PHP_SELF"], "p.title", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['p.fk_statut']['checked'])) print_liste_field_titre($arrayfields['p.fk_statut']['label'], $_SERVER["PHP_SELF"], "p.fk_statut", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['t.planned_workload']['checked'])) print_liste_field_titre($arrayfields['t.planned_workload']['label'], $_SERVER["PHP_SELF"], "t.planned_workload", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['t.duration_effective']['checked'])) print_liste_field_titre($arrayfields['t.duration_effective']['label'], $_SERVER["PHP_SELF"], "t.duration_effective", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['t.progress_calculated']['checked'])) print_liste_field_titre($arrayfields['t.progress_calculated']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', '', '', 'center '); -if (!empty($arrayfields['t.progress']['checked'])) print_liste_field_titre($arrayfields['t.progress']['label'], $_SERVER["PHP_SELF"], "t.progress", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['t.progress_summary']['checked'])) print_liste_field_titre($arrayfields['t.progress_summary']['label'], $_SERVER["PHP_SELF"], "t.progress", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['t.tobill']['checked'])) print_liste_field_titre($arrayfields['t.tobill']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['t.billed']['checked'])) print_liste_field_titre($arrayfields['t.billed']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['t.fk_task_parent']['checked'])) { + print_liste_field_titre($arrayfields['t.fk_task_parent']['label'], $_SERVER["PHP_SELF"], "t.fk_task_parent", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['t.ref']['checked'])) { + print_liste_field_titre($arrayfields['t.ref']['label'], $_SERVER["PHP_SELF"], "t.ref", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['t.label']['checked'])) { + print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER["PHP_SELF"], "t.label", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['t.description']['checked'])) { + print_liste_field_titre($arrayfields['t.description']['label'], $_SERVER["PHP_SELF"], "t.description", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['t.dateo']['checked'])) { + print_liste_field_titre($arrayfields['t.dateo']['label'], $_SERVER["PHP_SELF"], "t.dateo", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['t.datee']['checked'])) { + print_liste_field_titre($arrayfields['t.datee']['label'], $_SERVER["PHP_SELF"], "t.datee", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['p.ref']['checked'])) { + print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], "p.ref", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['p.title']['checked'])) { + print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER["PHP_SELF"], "p.title", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['p.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['p.fk_statut']['label'], $_SERVER["PHP_SELF"], "p.fk_statut", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['t.planned_workload']['checked'])) { + print_liste_field_titre($arrayfields['t.planned_workload']['label'], $_SERVER["PHP_SELF"], "t.planned_workload", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['t.duration_effective']['checked'])) { + print_liste_field_titre($arrayfields['t.duration_effective']['label'], $_SERVER["PHP_SELF"], "t.duration_effective", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['t.progress_calculated']['checked'])) { + print_liste_field_titre($arrayfields['t.progress_calculated']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', '', '', 'center '); +} +if (!empty($arrayfields['t.progress']['checked'])) { + print_liste_field_titre($arrayfields['t.progress']['label'], $_SERVER["PHP_SELF"], "t.progress", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['t.progress_summary']['checked'])) { + print_liste_field_titre($arrayfields['t.progress_summary']['label'], $_SERVER["PHP_SELF"], "t.progress", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['t.tobill']['checked'])) { + print_liste_field_titre($arrayfields['t.tobill']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['t.billed']['checked'])) { + print_liste_field_titre($arrayfields['t.billed']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'center '); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $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['t.datec']['checked'])) print_liste_field_titre($arrayfields['t.datec']['label'], $_SERVER["PHP_SELF"], "t.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['t.tms']['checked'])) print_liste_field_titre($arrayfields['t.tms']['label'], $_SERVER["PHP_SELF"], "t.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +if (!empty($arrayfields['t.datec']['checked'])) { + print_liste_field_titre($arrayfields['t.datec']['label'], $_SERVER["PHP_SELF"], "t.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['t.tms']['checked'])) { + print_liste_field_titre($arrayfields['t.tms']['label'], $_SERVER["PHP_SELF"], "t.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; $plannedworkloadoutputformat = 'allhourmin'; $timespentoutputformat = 'allhourmin'; -if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; -if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT; +if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) { + $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; +} +if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) { + $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT; +} $i = 0; $totalarray = array(); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $object->id = $obj->id; @@ -663,8 +846,7 @@ while ($i < min($num, $limit)) $projectstatic->datee = $db->jdate($obj->projectdatee); $userAccess = $projectstatic->restrictedProjectArea($user); // why this ? - if ($userAccess >= 0) - { + if ($userAccess >= 0) { print '<tr data-rowid="'.$object->id.'" class="oddeven">'; // Ref Parent @@ -677,77 +859,89 @@ while ($i < min($num, $limit)) setEventMessage($object_parent->error, 'errors'); } else { print $object_parent->getNomUrl(1, 'withproject'); - if ($object_parent->hasDelay()) + if ($object_parent->hasDelay()) { print img_warning("Late"); + } } } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Ref - if (!empty($arrayfields['t.ref']['checked'])) - { + if (!empty($arrayfields['t.ref']['checked'])) { print '<td class="nowraponall">'; print $object->getNomUrl(1, 'withproject'); - if ($object->hasDelay()) print img_warning("Late"); + if ($object->hasDelay()) { + print img_warning("Late"); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Label - if (!empty($arrayfields['t.label']['checked'])) - { + if (!empty($arrayfields['t.label']['checked'])) { print '<td>'; print $object->label; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Description - if (!empty($arrayfields['t.description']['checked'])) - { + if (!empty($arrayfields['t.description']['checked'])) { print '<td>'; print $object->description; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date start - if (!empty($arrayfields['t.dateo']['checked'])) - { + if (!empty($arrayfields['t.dateo']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_start), 'day'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date end - if (!empty($arrayfields['t.datee']['checked'])) - { + if (!empty($arrayfields['t.datee']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_end), 'day'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Project ref - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print '<td class="nowraponall tdoverflowmax150">'; print $projectstatic->getNomUrl(1, 'task'); - if ($projectstatic->hasDelay()) print img_warning("Late"); + if ($projectstatic->hasDelay()) { + print img_warning("Late"); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Project title - if (!empty($arrayfields['p.title']['checked'])) - { + if (!empty($arrayfields['p.title']['checked'])) { print '<td>'; print dol_trunc($obj->projecttitle, 80); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Third party - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td>'; - if ($obj->socid) - { + if ($obj->socid) { $socstatic->id = $obj->socid; $socstatic->name = $obj->name; print $socstatic->getNomUrl(1); @@ -755,100 +949,131 @@ while ($i < min($num, $limit)) print '&nbsp;'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Project status - if (!empty($arrayfields['p.fk_statut']['checked'])) - { + if (!empty($arrayfields['p.fk_statut']['checked'])) { print '<td class="center">'; print $projectstatic->getLibStatut(1); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Planned workload - if (!empty($arrayfields['t.planned_workload']['checked'])) - { + if (!empty($arrayfields['t.planned_workload']['checked'])) { print '<td class="center">'; $fullhour = convertSecondToTime($obj->planned_workload, $plannedworkloadoutputformat); $workingdelay = convertSecondToTime($obj->planned_workload, 'all', 86400, 7); // TODO Replace 86400 and 7 to take account working hours per day and working day per weeks - if ($obj->planned_workload != '') - { + if ($obj->planned_workload != '') { print $fullhour; // TODO Add delay taking account of working hours per day and working day per week //if ($workingdelay != $fullhour) print '<br>('.$workingdelay.')'; } //else print '--:--'; print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.planned_workload'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.planned_workload'; + } $totalarray['val']['t.planned_workload'] += $obj->planned_workload; - if (!$i) $totalarray['totalplannedworkloadfield'] = $totalarray['nbfield']; + if (!$i) { + $totalarray['totalplannedworkloadfield'] = $totalarray['nbfield']; + } $totalarray['totalplannedworkload'] += $obj->planned_workload; } // Time spent - if (!empty($arrayfields['t.duration_effective']['checked'])) - { + if (!empty($arrayfields['t.duration_effective']['checked'])) { $showlineingray = 0; $showproject = 1; print '<td class="center">'; - if ($showlineingray) print '<i>'; - else print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$object->id.($showproject ? '' : '&withproject=1').'">'; - if ($obj->duration_effective) print convertSecondToTime($obj->duration_effective, $timespentoutputformat); - else print '--:--'; - if ($showlineingray) print '</i>'; - else print '</a>'; + if ($showlineingray) { + print '<i>'; + } else { + print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$object->id.($showproject ? '' : '&withproject=1').'">'; + } + if ($obj->duration_effective) { + print convertSecondToTime($obj->duration_effective, $timespentoutputformat); + } else { + print '--:--'; + } + if ($showlineingray) { + print '</i>'; + } else { + print '</a>'; + } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.duration_effective'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.duration_effective'; + } $totalarray['val']['t.duration_effective'] += $obj->duration_effective; - if (!$i) $totalarray['totaldurationeffectivefield'] = $totalarray['nbfield']; + if (!$i) { + $totalarray['totaldurationeffectivefield'] = $totalarray['nbfield']; + } $totalarray['totaldurationeffective'] += $obj->duration_effective; } // Calculated progress - if (!empty($arrayfields['t.progress_calculated']['checked'])) - { + if (!empty($arrayfields['t.progress_calculated']['checked'])) { print '<td class="center">'; - if ($obj->planned_workload || $obj->duration_effective) - { - if ($obj->planned_workload) print round(100 * $obj->duration_effective / $obj->planned_workload, 2).' %'; - else print $form->textwithpicto('', $langs->trans('WorkloadNotDefined'), 1, 'help'); + if ($obj->planned_workload || $obj->duration_effective) { + if ($obj->planned_workload) { + print round(100 * $obj->duration_effective / $obj->planned_workload, 2).' %'; + } else { + print $form->textwithpicto('', $langs->trans('WorkloadNotDefined'), 1, 'help'); + } } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['totalprogress_calculatedfield'] = $totalarray['nbfield']; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['totalprogress_calculatedfield'] = $totalarray['nbfield']; + } } // Declared progress - if (!empty($arrayfields['t.progress']['checked'])) - { + if (!empty($arrayfields['t.progress']['checked'])) { print '<td class="center">'; - if ($obj->progress != '') - { + if ($obj->progress != '') { print getTaskProgressBadge($object); } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.progress'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.progress'; + } $totalarray['val']['t.progress'] += ($obj->planned_workload * $obj->progress / 100); - if (!$i) $totalarray['totalprogress_declaredfield'] = $totalarray['nbfield']; + if (!$i) { + $totalarray['totalprogress_declaredfield'] = $totalarray['nbfield']; + } $totalarray['totaldurationdeclared'] += $obj->planned_workload * $obj->progress / 100; } // Progress summary - if (!empty($arrayfields['t.progress_summary']['checked'])) - { + if (!empty($arrayfields['t.progress_summary']['checked'])) { print '<td class="center">'; if ($obj->progress != '' && $obj->duration_effective) { print getTaskProgressView($object, false, false); } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['totalprogress_summary'] = $totalarray['nbfield']; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['totalprogress_summary'] = $totalarray['nbfield']; + } } // Time not billed - if (!empty($arrayfields['t.tobill']['checked'])) - { + if (!empty($arrayfields['t.tobill']['checked'])) { print '<td class="center">'; - if ($obj->usage_bill_time) - { + if ($obj->usage_bill_time) { print convertSecondToTime($obj->tobill, 'allhourmin'); $totalarray['val']['t.tobill'] += $obj->tobill; $totalarray['totaltobill'] += $obj->tobill; @@ -856,16 +1081,20 @@ while ($i < min($num, $limit)) print '<span class="opacitymedium">'.$langs->trans("NA").'</span>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.tobill'; - if (!$i) $totalarray['totaltobillfield'] = $totalarray['nbfield']; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.tobill'; + } + if (!$i) { + $totalarray['totaltobillfield'] = $totalarray['nbfield']; + } } // Time billed - if (!empty($arrayfields['t.billed']['checked'])) - { + if (!empty($arrayfields['t.billed']['checked'])) { print '<td class="center">'; - if ($obj->usage_bill_time) - { + if ($obj->usage_bill_time) { print convertSecondToTime($obj->billed, 'allhourmin'); $totalarray['val']['t.billed'] += $obj->billed; $totalarray['totalbilled'] += $obj->billed; @@ -873,9 +1102,15 @@ while ($i < min($num, $limit)) print '<span class="opacitymedium">'.$langs->trans("NA").'</span>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.billed'; - if (!$i) $totalarray['totalbilledfield'] = $totalarray['nbfield']; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.billed'; + } + if (!$i) { + $totalarray['totalbilledfield'] = $totalarray['nbfield']; + } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; @@ -884,37 +1119,42 @@ while ($i < min($num, $limit)) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['t.datec']['checked'])) - { + if (!empty($arrayfields['t.datec']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['t.tms']['checked'])) - { + if (!empty($arrayfields['t.tms']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status /*if (! empty($arrayfields['p.fk_statut']['checked'])) { - $projectstatic->statut = $obj->fk_statut; - print '<td class="right">'.$projectstatic->getLibStatut(5).'</td>'; + $projectstatic->statut = $obj->fk_statut; + print '<td class="right">'.$projectstatic->getLibStatut(5).'</td>'; }*/ // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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->id, $arrayofselected)) $selected = 1; + if (in_array($obj->id, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$obj->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; } @@ -923,24 +1163,32 @@ while ($i < min($num, $limit)) } // Show total line if (isset($totalarray['totaldurationeffectivefield']) || isset($totalarray['totalplannedworkloadfield']) || isset($totalarray['totalprogress_calculatedfield']) - || isset($totalarray['totaltobill']) || isset($totalarray['totalbilled'])) -{ + || isset($totalarray['totaltobill']) || isset($totalarray['totalbilled'])) { print '<tr class="liste_total">'; $i = 0; - while ($i < $totalarray['nbfield']) - { + while ($i < $totalarray['nbfield']) { $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print '<td class="left">'.$langs->trans("Total").'</td>'; - else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; - } elseif ($totalarray['totalplannedworkloadfield'] == $i) print '<td class="center">'.convertSecondToTime($totalarray['totalplannedworkload'], $plannedworkloadoutputformat).'</td>'; - elseif ($totalarray['totaldurationeffectivefield'] == $i) print '<td class="center">'.convertSecondToTime($totalarray['totaldurationeffective'], $timespentoutputformat).'</td>'; - elseif ($totalarray['totalprogress_calculatedfield'] == $i) print '<td class="center">'.($totalarray['totalplannedworkload'] > 0 ? round(100 * $totalarray['totaldurationeffective'] / $totalarray['totalplannedworkload'], 2).' %' : '').'</td>'; - elseif ($totalarray['totalprogress_declaredfield'] == $i) print '<td class="center">'.($totalarray['totalplannedworkload'] > 0 ? round(100 * $totalarray['totaldurationdeclared'] / $totalarray['totalplannedworkload'], 2).' %' : '').'</td>'; - elseif ($totalarray['totaltobillfield'] == $i) print '<td class="center">'.convertSecondToTime($totalarray['totaltobill'], $plannedworkloadoutputformat).'</td>'; - elseif ($totalarray['totalbilledfield'] == $i) print '<td class="center">'.convertSecondToTime($totalarray['totalbilled'], $plannedworkloadoutputformat).'</td>'; - else print '<td></td>'; + if ($i == 1) { + if ($num < $limit && empty($offset)) { + print '<td class="left">'.$langs->trans("Total").'</td>'; + } else { + print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + } + } elseif ($totalarray['totalplannedworkloadfield'] == $i) { + print '<td class="center">'.convertSecondToTime($totalarray['totalplannedworkload'], $plannedworkloadoutputformat).'</td>'; + } elseif ($totalarray['totaldurationeffectivefield'] == $i) { + print '<td class="center">'.convertSecondToTime($totalarray['totaldurationeffective'], $timespentoutputformat).'</td>'; + } elseif ($totalarray['totalprogress_calculatedfield'] == $i) { + print '<td class="center">'.($totalarray['totalplannedworkload'] > 0 ? round(100 * $totalarray['totaldurationeffective'] / $totalarray['totalplannedworkload'], 2).' %' : '').'</td>'; + } elseif ($totalarray['totalprogress_declaredfield'] == $i) { + print '<td class="center">'.($totalarray['totalplannedworkload'] > 0 ? round(100 * $totalarray['totaldurationdeclared'] / $totalarray['totalplannedworkload'], 2).' %' : '').'</td>'; + } elseif ($totalarray['totaltobillfield'] == $i) { + print '<td class="center">'.convertSecondToTime($totalarray['totaltobill'], $plannedworkloadoutputformat).'</td>'; + } elseif ($totalarray['totalbilledfield'] == $i) { + print '<td class="center">'.convertSecondToTime($totalarray['totalbilled'], $plannedworkloadoutputformat).'</td>'; + } else { + print '<td></td>'; + } } print '</tr>'; } diff --git a/htdocs/projet/tasks/note.php b/htdocs/projet/tasks/note.php index af5709c7322..e23b5e3d70b 100644 --- a/htdocs/projet/tasks/note.php +++ b/htdocs/projet/tasks/note.php @@ -41,20 +41,26 @@ $project_ref = GETPOST('project_ref', 'alpha'); // Security check $socid = 0; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. -if (!$user->rights->projet->lire) accessforbidden(); +if (!$user->rights->projet->lire) { + accessforbidden(); +} //$result = restrictedArea($user, 'projet', $id, '', 'task'); // TODO ameliorer la verification $object = new Task($db); $projectstatic = new Project($db); -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref) > 0) - { - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); + } $projectstatic->fetch($object->fk_project); - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) $projectstatic->fetchComments(); - if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) { + $projectstatic->fetchComments(); + } + if (!empty($projectstatic->socid)) { + $projectstatic->fetch_thirdparty(); + } $object->project = clone $projectstatic; } else { @@ -64,13 +70,10 @@ if ($id > 0 || !empty($ref)) // Retrieve First Task ID of Project if withprojet is on to allow project prev next to work -if (!empty($project_ref) && !empty($withproject)) -{ - if ($projectstatic->fetch(0, $project_ref) > 0) - { +if (!empty($project_ref) && !empty($withproject)) { + if ($projectstatic->fetch(0, $project_ref) > 0) { $tasksarray = $object->getTasksArray(0, 0, $projectstatic->id, $socid, 0); - if (count($tasksarray) > 0) - { + if (count($tasksarray) > 0) { $id = $tasksarray[0]->id; $object->fetch($id); } else { @@ -100,12 +103,10 @@ $userstatic = new User($db); $now = dol_now(); -if ($object->id > 0) -{ +if ($object->id > 0) { $userWrite = $projectstatic->restrictedProjectArea($user, 'write'); - if (!empty($withproject)) - { + if (!empty($withproject)) { // Tabs for project $tab = 'tasks'; $head = project_prepare_head($projectstatic); @@ -120,15 +121,13 @@ if ($object->id > 0) // Title $morehtmlref .= $projectstatic->title; // Thirdparty - if ($projectstatic->thirdparty->id > 0) - { + if ($projectstatic->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0); $projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -146,22 +145,19 @@ if ($object->id > 0) print $langs->trans("Usage"); print '</td>'; print '<td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } - if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); @@ -171,8 +167,11 @@ if ($object->id > 0) // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; - if ($projectstatic->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); + if ($projectstatic->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } print '</td></tr>'; // Date start - end @@ -182,12 +181,16 @@ if ($object->id > 0) $end = dol_print_date($projectstatic->date_end, 'day'); print ' - '; print ($end ? $end : '?'); - if ($projectstatic->hasDelay()) print img_warning("Late"); + if ($projectstatic->hasDelay()) { + print img_warning("Late"); + } print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; - if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + if (strcmp($projectstatic->budget_amount, '')) { + print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + } print '</td></tr>'; // Other attributes @@ -235,17 +238,17 @@ if ($object->id > 0) $param = (GETPOST('withproject') ? '&withproject=1' : ''); $linkback = GETPOST('withproject') ? '<a href="'.DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.'">'.$langs->trans("BackToList").'</a>' : ''; - if (!GETPOST('withproject') || empty($projectstatic->id)) - { + if (!GETPOST('withproject') || empty($projectstatic->id)) { $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1); $object->next_prev_filter = " fk_projet in (".$projectsListId.")"; - } else $object->next_prev_filter = " fk_projet = ".$projectstatic->id; + } else { + $object->next_prev_filter = " fk_projet = ".$projectstatic->id; + } $morehtmlref = ''; // Project - if (empty($withproject)) - { + if (empty($withproject)) { $morehtmlref .= '<div class="refidno">'; $morehtmlref .= $langs->trans("Project").': '; $morehtmlref .= $projectstatic->getNomUrl(1); diff --git a/htdocs/projet/tasks/stats/index.php b/htdocs/projet/tasks/stats/index.php index 571560518ab..531b9eb7b3a 100644 --- a/htdocs/projet/tasks/stats/index.php +++ b/htdocs/projet/tasks/stats/index.php @@ -28,8 +28,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/taskstats.class.php'; // Security check -if (!$user->rights->projet->lire) +if (!$user->rights->projet->lire) { accessforbidden(); +} $WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); @@ -38,8 +39,7 @@ $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); $userid = GETPOST('userid', 'int'); $socid = GETPOST('socid', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -65,7 +65,7 @@ $includeuserlist = array(); llxHeader('', $langs->trans('Tasks')); $title = $langs->trans("TasksStatistics"); -$dir = $conf->projet->dir_output.'/temp'; +$dir = $conf->project->dir_output.'/temp'; print load_fiche_titre($title, '', 'projecttask'); @@ -73,9 +73,15 @@ dol_mkdir($dir); $stats_tasks = new TaskStats($db); -if (!empty($userid) && $userid != -1) $stats_tasks->userid = $userid; -if (!empty($socid) && $socid != -1) $stats_tasks->socid = $socid; -if (!empty($year)) $stats_tasks->year = $year; +if (!empty($userid) && $userid != -1) { + $stats_tasks->userid = $userid; +} +if (!empty($socid) && $socid != -1) { + $stats_tasks->socid = $socid; +} +if (!empty($year)) { + $stats_tasks->year = $year; +} @@ -89,12 +95,10 @@ $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=taskstats&amp;file=tasknbpr $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -116,22 +120,26 @@ if (!$mesg) $stats_tasks->year = 0; $data_all_year = $stats_tasks->getAllByYear(); -if (!empty($year)) $stats_tasks->year = $year; +if (!empty($year)) { + $stats_tasks->year = $year; +} $arrayyears = array(); foreach ($data_all_year as $val) { $arrayyears[$val['year']] = $val['year']; } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; $head = array(); -$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/stats/index.php?mode='.$mode; +$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/stats/index.php'; $head[$h][1] = $langs->trans("ByMonthYear"); $head[$h][2] = 'byyear'; $h++; -complete_head_from_modules($conf, $langs, null, $head, $h, $type); +complete_head_from_modules($conf, $langs, null, $head, $h, 'project_tasks_stats'); print dol_get_fiche_head($head, 'byyear', $langs->trans("Statistics"), -1, ''); @@ -154,8 +162,12 @@ print $form->select_dolusers($userid, 'userid', 1, array(),0,$includeuserlist); print '</td></tr>';*/ // Year print '<tr><td>'.$langs->trans("Year").'</td><td>'; -if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; -if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} +if (!in_array($nowyear, $arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print '</td></tr>'; @@ -173,21 +185,19 @@ print '<td class="right">'.$langs->trans("NbOfTasks").'</td>'; print '</tr>'; $oldyear = 0; -foreach ($data_all_year as $val) -{ +foreach ($data_all_year as $val) { $year = $val['year']; - while ($year && $oldyear > $year + 1) - { // If we have empty year + while ($year && $oldyear > $year + 1) { // If we have empty year $oldyear--; print '<tr class="oddeven" height="24">'; - print '<td><a href="'.$_SERVER["PHP_SELF"].'?year='.$oldyear.'&amp;mode='.$mode.($socid > 0 ? '&socid='.$socid : '').($userid > 0 ? '&userid='.$userid : '').'">'.$oldyear.'</a></td>'; + print '<td><a href="'.$_SERVER["PHP_SELF"].'?year='.$oldyear.($socid > 0 ? '&socid='.$socid : '').($userid > 0 ? '&userid='.$userid : '').'">'.$oldyear.'</a></td>'; print '<td class="right">0</td>'; print '</tr>'; } print '<tr class="oddeven" height="24">'; - print '<td><a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'&amp;mode='.$mode.($socid > 0 ? '&socid='.$socid : '').($userid > 0 ? '&userid='.$userid : '').'">'.$year.'</a></td>'; + print '<td><a href="'.$_SERVER["PHP_SELF"].'?year='.$year.($socid > 0 ? '&socid='.$socid : '').($userid > 0 ? '&userid='.$userid : '').'">'.$year.'</a></td>'; print '<td class="right">'.$val['nb'].'</td>'; print '</tr>'; $oldyear = $year; @@ -198,8 +208,10 @@ print '</div>'; print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; -$stringtoshow .= '<table class="border centpercent"><tr class="pair nohover"><td class="center">'; -if ($mesg) { print $mesg; } else { +$stringtoshow = '<table class="border centpercent"><tr class="pair nohover"><td class="center">'; +if ($mesg) { + print $mesg; +} else { $stringtoshow .= $px1->show(); $stringtoshow .= "<br>\n"; } diff --git a/htdocs/projet/tasks/task.php b/htdocs/projet/tasks/task.php index cd10b43f0c0..77b015d5819 100644 --- a/htdocs/projet/tasks/task.php +++ b/htdocs/projet/tasks/task.php @@ -49,7 +49,9 @@ $planned_workload = ((GETPOST('planned_workloadhour', 'int') != '' || GETPOST('p // Security check $socid = 0; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. -if (!$user->rights->projet->lire) accessforbidden(); +if (!$user->rights->projet->lire) { + accessforbidden(); +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('projecttaskcard', 'globalcard')); @@ -63,34 +65,34 @@ $extrafields->fetch_name_optionals_label($object->table_element); $parameters = array('id'=>$id); $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'); +} /* * Actions */ -if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer) -{ +if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer) { $error = 0; - if (empty($taskref)) - { + if (empty($taskref)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); } - if (empty($_POST["label"])) - { + if (empty($_POST["label"])) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); } - if (!$error) - { + if (!$error) { $object->fetch($id, $ref); $object->oldcopy = clone $object; $tmparray = explode('_', $_POST['task_parent']); $task_parent = $tmparray[1]; - if (empty($task_parent)) $task_parent = 0; // If task_parent is '' + if (empty($task_parent)) { + $task_parent = 0; // If task_parent is '' + } $object->ref = $taskref ? $taskref : GETPOST("ref", 'alpha', 2); $object->label = GETPOST("label", "alphanohtml"); @@ -103,13 +105,13 @@ if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { $result = $object->update($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } } @@ -118,15 +120,12 @@ if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer) } } -if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->projet->supprimer) -{ - if ($object->fetch($id, $ref) >= 0) - { +if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->projet->supprimer) { + if ($object->fetch($id, $ref) >= 0) { $result = $projectstatic->fetch($object->fk_project); $projectstatic->fetch_thirdparty(); - if ($object->delete($user) > 0) - { + if ($object->delete($user) > 0) { header('Location: '.DOL_URL_ROOT.'/projet/tasks.php?restore_lastsearch_values=1&id='.$projectstatic->id.($withproject ? '&withproject=1' : '')); exit; } else { @@ -137,13 +136,10 @@ if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->projet->s } // Retrieve First Task ID of Project if withprojet is on to allow project prev next to work -if (!empty($project_ref) && !empty($withproject)) -{ - if ($projectstatic->fetch('', $project_ref) > 0) - { +if (!empty($project_ref) && !empty($withproject)) { + if ($projectstatic->fetch('', $project_ref) > 0) { $tasksarray = $object->getTasksArray(0, 0, $projectstatic->id, $socid, 0); - if (count($tasksarray) > 0) - { + if (count($tasksarray) > 0) { $id = $tasksarray[0]->id; } else { header("Location: ".DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.(empty($mode) ? '' : '&mode='.$mode)); @@ -152,41 +148,41 @@ if (!empty($project_ref) && !empty($withproject)) } // Build doc -if ($action == 'builddoc' && $user->rights->projet->creer) -{ +if ($action == 'builddoc' && $user->rights->projet->creer) { $object->fetch($id, $ref); // Save last template used to generate document - if (GETPOST('model')) $object->setDocModel($user, GETPOST('model', 'alpha')); + if (GETPOST('model')) { + $object->setDocModel($user, GETPOST('model', 'alpha')); + } $outputlangs = $langs; - if (GETPOST('lang_id', 'aZ09')) - { + if (GETPOST('lang_id', 'aZ09')) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang(GETPOST('lang_id', 'aZ09')); } $result = $object->generateDocument($object->model_pdf, $outputlangs); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = ''; } } // Delete file in doc form -if ($action == 'remove_file' && $user->rights->projet->creer) -{ +if ($action == 'remove_file' && $user->rights->projet->creer) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if ($object->fetch($id, $ref) >= 0) - { + if ($object->fetch($id, $ref) >= 0) { $langs->load("other"); $upload_dir = $conf->projet->dir_output; $file = $upload_dir.'/'.dol_sanitizeFileName(GETPOST('file')); $ret = dol_delete_file($file); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors'); + if ($ret) { + setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors'); + } } } @@ -201,23 +197,26 @@ $form = new Form($db); $formother = new FormOther($db); $formfile = new FormFile($db); -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref) > 0) - { +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { $res = $object->fetch_optionals(); - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); + } $result = $projectstatic->fetch($object->fk_project); - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) $projectstatic->fetchComments(); - if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) { + $projectstatic->fetchComments(); + } + if (!empty($projectstatic->socid)) { + $projectstatic->fetch_thirdparty(); + } $object->project = clone $projectstatic; //$userWrite = $projectstatic->restrictedProjectArea($user, 'write'); - if (!empty($withproject)) - { + if (!empty($withproject)) { // Tabs for project $tab = 'tasks'; $head = project_prepare_head($projectstatic); @@ -233,15 +232,13 @@ if ($id > 0 || !empty($ref)) // Title $morehtmlref .= $projectstatic->title; // Thirdparty - if ($projectstatic->thirdparty->id > 0) - { + if ($projectstatic->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0); $projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -259,22 +256,19 @@ if ($id > 0 || !empty($ref)) print $langs->trans("Usage"); print '</td>'; print '<td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } - if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); @@ -284,8 +278,11 @@ if ($id > 0 || !empty($ref)) // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; - if ($projectstatic->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); + if ($projectstatic->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } print '</td></tr>'; // Date start - end @@ -295,12 +292,16 @@ if ($id > 0 || !empty($ref)) $end = dol_print_date($projectstatic->date_end, 'day'); print ' - '; print ($end ? $end : '?'); - if ($projectstatic->hasDelay()) print img_warning("Late"); + if ($projectstatic->hasDelay()) { + print img_warning("Late"); + } print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; - if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + if (strcmp($projectstatic->budget_amount, '')) { + print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + } print '</td></tr>'; // Other attributes @@ -372,8 +373,7 @@ if ($id > 0 || !empty($ref)) $head = task_prepare_head($object); - if ($action == 'edit' && $user->rights->projet->creer) - { + if ($action == 'edit' && $user->rights->projet->creer) { print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; @@ -393,16 +393,18 @@ if ($id > 0 || !empty($ref)) print '<td><input class="minwidth500" name="label" value="'.$object->label.'"></td></tr>'; // Project - if (empty($withproject)) - { + if (empty($withproject)) { print '<tr><td>'.$langs->trans("Project").'</td><td colspan="3">'; print $projectstatic->getNomUrl(1); print '</td></tr>'; // Third party print '<td>'.$langs->trans("ThirdParty").'</td><td colspan="3">'; - if ($projectstatic->societe->id) print $projectstatic->societe->getNomUrl(1); - else print '&nbsp;'; + if ($projectstatic->societe->id) { + print $projectstatic->societe->getNomUrl(1); + } else { + print '&nbsp;'; + } print '</td></tr>'; } @@ -441,8 +443,7 @@ if ($id > 0 || !empty($ref)) $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } @@ -465,22 +466,21 @@ if ($id > 0 || !empty($ref)) print dol_get_fiche_head($head, 'task_task', $langs->trans("Task"), -1, 'projecttask', 0, '', 'reposition'); - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$_GET["id"].'&withproject='.$withproject, $langs->trans("DeleteATask"), $langs->trans("ConfirmDeleteATask"), "confirm_delete"); } - if (!GETPOST('withproject') || empty($projectstatic->id)) - { + if (!GETPOST('withproject') || empty($projectstatic->id)) { $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1); $object->next_prev_filter = " fk_projet in (".$projectsListId.")"; - } else $object->next_prev_filter = " fk_projet = ".$projectstatic->id; + } else { + $object->next_prev_filter = " fk_projet = ".$projectstatic->id; + } $morehtmlref = ''; // Project - if (empty($withproject)) - { + if (empty($withproject)) { $morehtmlref .= '<div class="refidno">'; $morehtmlref .= $langs->trans("Project").': '; $morehtmlref .= $projectstatic->getNomUrl(1); @@ -504,8 +504,7 @@ if ($id > 0 || !empty($ref)) // Task parent print '<tr><td>'.$langs->trans("ChildOfTask").'</td><td>'; - if ($object->fk_task_parent > 0) - { + if ($object->fk_task_parent > 0) { $tasktmp = new Task($db); $tasktmp->fetch($object->fk_task_parent); print $tasktmp->getNomUrl(1); @@ -519,13 +518,14 @@ if ($id > 0 || !empty($ref)) $end = dol_print_date($object->date_end, 'dayhour'); print ' - '; print ($end ? $end : '?'); - if ($object->hasDelay()) print img_warning("Late"); + if ($object->hasDelay()) { + print img_warning("Late"); + } print '</td></tr>'; // Planned workload print '<tr><td>'.$langs->trans("PlannedWorkload").'</td><td colspan="3">'; - if ($object->planned_workload != '') - { + if ($object->planned_workload != '') { print convertSecondToTime($object->planned_workload, 'allhourmin'); } print '</td></tr>'; @@ -545,20 +545,23 @@ if ($id > 0 || !empty($ref)) // Progress declared print '<tr><td class="titlefield">'.$langs->trans("ProgressDeclared").'</td><td colspan="3">'; - if ($object->progress != '') - { + if ($object->progress != '') { print $object->progress.' %'; } print '</td></tr>'; // Progress calculated print '<tr><td>'.$langs->trans("ProgressCalculated").'</td><td colspan="3">'; - if ($object->planned_workload != '') - { + if ($object->planned_workload != '') { $tmparray = $object->getSummaryOfTimeSpent(); - if ($tmparray['total_duration'] > 0 && !empty($object->planned_workload)) print round($tmparray['total_duration'] / $object->planned_workload * 100, 2).' %'; - else print '0 %'; - } else print '<span class="opacitymedium">'.$langs->trans("WorkloadNotDefined").'</span>'; + if ($tmparray['total_duration'] > 0 && !empty($object->planned_workload)) { + print round($tmparray['total_duration'] / $object->planned_workload * 100, 2).' %'; + } else { + print '0 %'; + } + } else { + print '<span class="opacitymedium">'.$langs->trans("WorkloadNotDefined").'</span>'; + } print '</td></tr>'; // Other attributes @@ -578,32 +581,27 @@ if ($id > 0 || !empty($ref)) } - if ($action != 'edit') - { + if ($action != 'edit') { /* * Actions - */ + */ print '<div class="tabsAction">'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { // Modify - if ($user->rights->projet->creer) - { + if ($user->rights->projet->creer) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=edit&amp;withproject='.$withproject.'">'.$langs->trans('Modify').'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans('Modify').'</a>'; } // Delete - if ($user->rights->projet->supprimer) - { - if (!$object->hasChildren() && !$object->hasTimeSpent()) - { + if ($user->rights->projet->supprimer) { + if (!$object->hasChildren() && !$object->hasTimeSpent()) { print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'&amp;withproject='.$withproject.'">'.$langs->trans('Delete').'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("TaskHasChild").'">'.$langs->trans('Delete').'</a>'; @@ -619,7 +617,7 @@ if ($id > 0 || !empty($ref)) print '<a name="builddoc"></a>'; // ancre /* - * Documents generes + * Generated documents */ $filename = dol_sanitizeFileName($projectstatic->ref)."/".dol_sanitizeFileName($object->ref); $filedir = $conf->projet->dir_output."/".dol_sanitizeFileName($projectstatic->ref)."/".dol_sanitizeFileName($object->ref); diff --git a/htdocs/projet/tasks/time.php b/htdocs/projet/tasks/time.php index 5cca624d11f..0beacab18a0 100644 --- a/htdocs/projet/tasks/time.php +++ b/htdocs/projet/tasks/time.php @@ -37,7 +37,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; // Load translation files required by the page -$langs->loadLangs(array('projects', 'bills', 'orders')); +$langsLoad=array('projects', 'bills', 'orders'); +if (!empty($conf->eventorganization->enabled)) { + $langsLoad[]='eventorganization'; +} + +$langs->loadLangs($langsLoad); $action = GETPOST('action', 'alpha'); $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) @@ -71,18 +76,26 @@ $search_valuebilled = GETPOST('search_valuebilled', 'int'); // Security check $socid = 0; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. -if (!$user->rights->projet->lire) accessforbidden(); +if (!$user->rights->projet->lire) { + accessforbidden(); +} $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 = 't.task_date,t.task_datehour,t.rowid'; -if (!$sortorder) $sortorder = 'DESC,DESC,DESC'; +if (!$sortfield) { + $sortfield = 't.task_date,t.task_datehour,t.rowid'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC,DESC'; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context //$object = new TaskTime($db); @@ -99,18 +112,23 @@ $extrafields->fetch_name_optionals_label($object->table_element); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_generateinvoice') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_generateinvoice') { + $massaction = ''; +} $parameters = array('socid'=>$socid, 'projectid'=>$projectid); $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'); +} include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_day = ''; $search_month = ''; $search_year = ''; @@ -131,32 +149,26 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $action = ''; } -if ($action == 'addtimespent' && $user->rights->projet->lire) -{ +if ($action == 'addtimespent' && $user->rights->projet->lire) { $error = 0; $timespent_durationhour = GETPOST('timespent_durationhour', 'int'); $timespent_durationmin = GETPOST('timespent_durationmin', 'int'); - if (empty($timespent_durationhour) && empty($timespent_durationmin)) - { + if (empty($timespent_durationhour) && empty($timespent_durationmin)) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Duration")), null, 'errors'); $error++; } - if (empty($_POST["userid"])) - { + if (empty($_POST["userid"])) { $langs->load("errors"); setEventMessages($langs->trans('ErrorUserNotAssignedToTask'), null, 'errors'); $error++; } - if (!$error) - { - if ($id || $ref) - { + if (!$error) { + if ($id || $ref) { $object->fetch($id, $ref); } else { - if (!GETPOST('taskid', 'int') || GETPOST('taskid', 'int') < 0) - { + if (!GETPOST('taskid', 'int') || GETPOST('taskid', 'int') < 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), null, 'errors'); $action = 'createtime'; $error++; @@ -165,22 +177,21 @@ if ($action == 'addtimespent' && $user->rights->projet->lire) } } - if (!$error) - { + if (!$error) { $object->fetch_projet(); - if (empty($object->project->statut)) - { + if (empty($object->project->statut)) { setEventMessages($langs->trans("ProjectMustBeValidatedFirst"), null, 'errors'); $action = 'createtime'; $error++; } else { $object->timespent_note = $_POST["timespent_note"]; - if (GETPOST('progress', 'int') > 0) $object->progress = GETPOST('progress', 'int'); // If progress is -1 (not defined), we do not change value + if (GETPOST('progress', 'int') > 0) { + $object->progress = GETPOST('progress', 'int'); // If progress is -1 (not defined), we do not change value + } $object->timespent_duration = $_POST["timespent_durationhour"] * 60 * 60; // We store duration in seconds $object->timespent_duration += ($_POST["timespent_durationmin"] ? $_POST["timespent_durationmin"] : 0) * 60; // We store duration in seconds - if (GETPOST("timehour") != '' && GETPOST("timehour") >= 0) // If hour was entered - { + if (GETPOST("timehour") != '' && GETPOST("timehour") >= 0) { // If hour was entered $object->timespent_date = dol_mktime(GETPOST("timehour"), GETPOST("timemin"), 0, GETPOST("timemonth"), GETPOST("timeday"), GETPOST("timeyear")); $object->timespent_withhour = 1; } else { @@ -188,8 +199,7 @@ if ($action == 'addtimespent' && $user->rights->projet->lire) } $object->timespent_fk_user = $_POST["userid"]; $result = $object->addTimeSpent($user); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans($object->error), null, 'errors'); @@ -198,25 +208,24 @@ if ($action == 'addtimespent' && $user->rights->projet->lire) } } } else { - if (empty($id)) $action = 'createtime'; - else $action = 'createtime'; + if (empty($id)) { + $action = 'createtime'; + } else { + $action = 'createtime'; + } } } -if (($action == 'updateline' || $action == 'updatesplitline') && !$cancel && $user->rights->projet->lire) -{ +if (($action == 'updateline' || $action == 'updatesplitline') && !$cancel && $user->rights->projet->lire) { $error = 0; - if (!GETPOST("new_durationhour") && !GETPOST("new_durationmin")) - { + if (!GETPOST("new_durationhour") && !GETPOST("new_durationmin")) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Duration")), null, 'errors'); $error++; } - if (!$error) - { - if (GETPOST('taskid', 'int') != $id) // GETPOST('taskid') is id of new task - { + if (!$error) { + if (GETPOST('taskid', 'int') != $id) { // GETPOST('taskid') is id of new task $id = GETPOST('taskid', 'int'); $object->fetchTimeSpent(GETPOST('lineid', 'int')); @@ -228,8 +237,7 @@ if (($action == 'updateline' || $action == 'updatesplitline') && !$cancel && $us $object->timespent_old_duration = $_POST["old_duration"]; $object->timespent_duration = $_POST["new_durationhour"] * 60 * 60; // We store duration in seconds $object->timespent_duration += ($_POST["new_durationmin"] ? $_POST["new_durationmin"] : 0) * 60; // We store duration in seconds - if (GETPOST("timelinehour") != '' && GETPOST("timelinehour") >= 0) // If hour was entered - { + if (GETPOST("timelinehour") != '' && GETPOST("timelinehour") >= 0) { // If hour was entered $object->timespent_date = dol_mktime(GETPOST("timelinehour"), GETPOST("timelinemin"), 0, GETPOST("timelinemonth"), GETPOST("timelineday"), GETPOST("timelineyear")); $object->timespent_withhour = 1; } else { @@ -237,8 +245,7 @@ if (($action == 'updateline' || $action == 'updatesplitline') && !$cancel && $us } $object->timespent_fk_user = $_POST["userid_line"]; $result = $object->addTimeSpent($user); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans($object->error), null, 'errors'); @@ -253,8 +260,7 @@ if (($action == 'updateline' || $action == 'updatesplitline') && !$cancel && $us $object->timespent_old_duration = $_POST["old_duration"]; $object->timespent_duration = $_POST["new_durationhour"] * 60 * 60; // We store duration in seconds $object->timespent_duration += ($_POST["new_durationmin"] ? $_POST["new_durationmin"] : 0) * 60; // We store duration in seconds - if (GETPOST("timelinehour") != '' && GETPOST("timelinehour") >= 0) // If hour was entered - { + if (GETPOST("timelinehour") != '' && GETPOST("timelinehour") >= 0) { // If hour was entered $object->timespent_date = dol_mktime(GETPOST("timelinehour"), GETPOST("timelinemin"), 0, GETPOST("timelinemonth"), GETPOST("timelineday"), GETPOST("timelineyear")); $object->timespent_withhour = 1; } else { @@ -263,8 +269,7 @@ if (($action == 'updateline' || $action == 'updatesplitline') && !$cancel && $us $object->timespent_fk_user = $_POST["userid_line"]; $result = $object->updateTimeSpent($user); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans($object->error), null, 'errors'); @@ -276,14 +281,12 @@ if (($action == 'updateline' || $action == 'updatesplitline') && !$cancel && $us } } -if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->projet->lire) -{ +if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->projet->lire) { $object->fetchTimeSpent(GETPOST('lineid', 'int')); // TODO Check that ($task_time->fk_user == $user->id || in_array($task_time->fk_user, $childids)) $result = $object->delTimeSpent($user); - if ($result < 0) - { + if ($result < 0) { $langs->load("errors"); setEventMessages($langs->trans($object->error), null, 'errors'); $error++; @@ -294,13 +297,10 @@ if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->projet->l } // Retrieve First Task ID of Project if withprojet is on to allow project prev next to work -if (!empty($project_ref) && !empty($withproject)) -{ - if ($projectstatic->fetch(0, $project_ref) > 0) - { +if (!empty($project_ref) && !empty($withproject)) { + if ($projectstatic->fetch(0, $project_ref) > 0) { $tasksarray = $object->getTasksArray(0, 0, $projectstatic->id, $socid, 0); - if (count($tasksarray) > 0) - { + if (count($tasksarray) > 0) { $id = $tasksarray[0]->id; } else { header("Location: ".DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.($withproject ? '&withproject=1' : '').(empty($mode) ? '' : '&mode='.$mode)); @@ -311,27 +311,27 @@ if (!empty($project_ref) && !empty($withproject)) // To show all time lines for project $projectidforalltimes = 0; -if (GETPOST('projectid', 'int') > 0) -{ +if (GETPOST('projectid', 'int') > 0) { $projectidforalltimes = GETPOST('projectid', 'int'); $result = $projectstatic->fetch($projectidforalltimes); - if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); + if (!empty($projectstatic->socid)) { + $projectstatic->fetch_thirdparty(); + } $res = $projectstatic->fetch_optionals(); -} elseif (GETPOST('project_ref', 'alpha')) -{ +} elseif (GETPOST('project_ref', 'alpha')) { $projectstatic->fetch(0, GETPOST('project_ref', 'alpha')); $projectidforalltimes = $projectstatic->id; $withproject = 1; -} elseif ($id > 0) -{ +} elseif ($id > 0) { $object->fetch($id); $result = $projectstatic->fetch($object->fk_project); } -if ($action == 'confirm_generateinvoice') -{ - if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); +if ($action == 'confirm_generateinvoice') { + if (!empty($projectstatic->socid)) { + $projectstatic->fetch_thirdparty(); + } if (!($projectstatic->thirdparty->id > 0)) { setEventMessages($langs->trans("ThirdPartyRequiredToGenerateInvoice"), null, 'errors'); @@ -351,21 +351,26 @@ if ($action == 'confirm_generateinvoice') $invoiceToUse = GETPOST('invoiceid', 'int'); $prodDurationHours = 1.0; - if ($idprod > 0) - { + if ($idprod > 0) { $tmpproduct->fetch($idprod); - if ($tmpproduct->duration_unit == 'i') + if ($tmpproduct->duration_unit == 'i') { $prodDurationHours = 1. / 60; - if ($tmpproduct->duration_unit == 'h') + } + if ($tmpproduct->duration_unit == 'h') { $prodDurationHours = 1.; - if ($tmpproduct->duration_unit == 'd') + } + if ($tmpproduct->duration_unit == 'd') { $prodDurationHours = 24.; - if ($tmpproduct->duration_unit == 'w') + } + if ($tmpproduct->duration_unit == 'w') { $prodDurationHours = 24. * 7; - if ($tmpproduct->duration_unit == 'm') + } + if ($tmpproduct->duration_unit == 'm') { $prodDurationHours = 24. * 30; - if ($tmpproduct->duration_unit == 'y') + } + if ($tmpproduct->duration_unit == 'y') { $prodDurationHours = 24. * 365; + } $prodDurationHours *= $tmpproduct->duration_value; $dataforprice = $tmpproduct->getSellPrice($mysoc, $projectstatic->thirdparty, 0); @@ -389,27 +394,23 @@ if ($action == 'confirm_generateinvoice') $tmpinvoice->fetch($invoiceToUse); } else { $result = $tmpinvoice->create($user); - if ($result <= 0) - { + if ($result <= 0) { $error++; setEventMessages($tmpinvoice->error, $tmpinvoice->errors, 'errors'); } } - if (!$error) - { + if (!$error) { if ($generateinvoicemode == 'onelineperuser') { $arrayoftasks = array(); - foreach ($toselect as $key => $value) - { + foreach ($toselect as $key => $value) { // Get userid, timepent $object->fetchTimeSpent($value); $arrayoftasks[$object->timespent_fk_user]['timespent'] += $object->timespent_duration; $arrayoftasks[$object->timespent_fk_user]['totalvaluetodivideby3600'] += ($object->timespent_duration * $object->timespent_thm); } - foreach ($arrayoftasks as $userid => $value) - { + foreach ($arrayoftasks as $userid => $value) { $fuser->fetch($userid); //$pu_ht = $value['timespent'] * $fuser->thm; $username = $fuser->getFullName($langs); @@ -419,8 +420,7 @@ if ($action == 'confirm_generateinvoice') $qtyhourtext = convertSecondToTime($value['timespent'], 'all', $conf->global->MAIN_DURATION_OF_WORKDAY); // If no unit price known - if (empty($pu_ht)) - { + if (empty($pu_ht)) { $pu_ht = price2num($value['totalvaluetodivideby3600'] / 3600, 'MU'); } @@ -431,8 +431,7 @@ if ($action == 'confirm_generateinvoice') $sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time SET invoice_line_id = '.$lineid.', invoice_id = '.$tmpinvoice->id; $sql .= ' WHERE rowid in ('.join(',', $toselect).') AND fk_user = '.$userid; $result = $db->query($sql); - if (!$result) - { + if (!$result) { $error++; setEventMessages($db->lasterror(), null, 'errors'); break; @@ -440,8 +439,7 @@ if ($action == 'confirm_generateinvoice') } } elseif ($generateinvoicemode == 'onelineperperiod') { $arrayoftasks = array(); - foreach ($toselect as $key => $value) - { + foreach ($toselect as $key => $value) { // Get userid, timepent $object->fetchTimeSpent($value); $arrayoftasks[$object->timespent_id]['timespent'] = $object->timespent_duration; @@ -450,8 +448,7 @@ if ($action == 'confirm_generateinvoice') $arrayoftasks[$object->timespent_id]['user'] = $object->timespent_fk_user; } - foreach ($arrayoftasks as $timespent_id => $value) - { + foreach ($arrayoftasks as $timespent_id => $value) { $userid = $value['user']; $fuser->fetch($userid); //$pu_ht = $value['timespent'] * $fuser->thm; @@ -462,8 +459,7 @@ if ($action == 'confirm_generateinvoice') $qtyhourtext = convertSecondToTime($value['timespent'], 'all', $conf->global->MAIN_DURATION_OF_WORKDAY); // If no unit price known - if (empty($pu_ht)) - { + if (empty($pu_ht)) { $pu_ht = price2num($value['totalvaluetodivideby3600'] / 3600, 'MU'); } @@ -474,8 +470,7 @@ if ($action == 'confirm_generateinvoice') $sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time SET invoice_line_id = '.$lineid.', invoice_id = '.$tmpinvoice->id; $sql .= ' WHERE rowid in ('.join(',', $toselect).') AND fk_user = '.$userid; $result = $db->query($sql); - if (!$result) - { + if (!$result) { $error++; setEventMessages($db->lasterror(), null, 'errors'); break; @@ -483,8 +478,7 @@ if ($action == 'confirm_generateinvoice') } } elseif ($generateinvoicemode == 'onelinepertask') { $arrayoftasks = array(); - foreach ($toselect as $key => $value) - { + foreach ($toselect as $key => $value) { // Get userid, timepent $object->fetchTimeSpent($value); // $object->id is the task id @@ -492,8 +486,7 @@ if ($action == 'confirm_generateinvoice') $arrayoftasks[$object->id]['totalvaluetodivideby3600'] += $object->timespent_duration * $object->timespent_thm; } - foreach ($arrayoftasks as $task_id => $value) - { + foreach ($arrayoftasks as $task_id => $value) { $ftask = new Task($db); $ftask->fetch($task_id); // Define qty per hour @@ -501,8 +494,7 @@ if ($action == 'confirm_generateinvoice') $qtyhourtext = convertSecondToTime($value['timespent'], 'all', $conf->global->MAIN_DURATION_OF_WORKDAY); // If no unit price known - if (empty($pu_ht)) - { + if (empty($pu_ht)) { $pu_ht = price2num($value['totalvaluetodivideby3600'] / 3600, 'MU'); } @@ -514,8 +506,7 @@ if ($action == 'confirm_generateinvoice') $sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time SET invoice_line_id = '.$lineid.', invoice_id = '.$tmpinvoice->id; $sql .= ' WHERE rowid in ('.join(',', $toselect).')'; $result = $db->query($sql); - if (!$result) - { + if (!$result) { $error++; setEventMessages($db->lasterror(), null, 'errors'); break; @@ -524,8 +515,7 @@ if ($action == 'confirm_generateinvoice') } } - if (!$error) - { + if (!$error) { $urltoinvoice = $tmpinvoice->getNomUrl(0); setEventMessages($langs->trans("InvoiceGeneratedFromTimeSpent", $urltoinvoice), null, 'mesgs'); //var_dump($tmpinvoice); @@ -551,22 +541,27 @@ $formother = new FormOther($db); $formproject = new FormProjets($db); $userstatic = new User($db); -if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) -{ +if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) { /* * Fiche projet en mode visu */ - if ($projectidforalltimes > 0) - { + if ($projectidforalltimes > 0) { $result = $projectstatic->fetch($projectidforalltimes); - if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); + if (!empty($projectstatic->socid)) { + $projectstatic->fetch_thirdparty(); + } $res = $projectstatic->fetch_optionals(); - } elseif ($object->fetch($id, $ref) >= 0) - { - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); + } elseif ($object->fetch($id, $ref) >= 0) { + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) { + $object->fetchComments(); + } $result = $projectstatic->fetch($object->fk_project); - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) $projectstatic->fetchComments(); - if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) { + $projectstatic->fetchComments(); + } + if (!empty($projectstatic->socid)) { + $projectstatic->fetch_thirdparty(); + } $res = $projectstatic->fetch_optionals(); $object->project = clone $projectstatic; @@ -575,13 +570,14 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $userRead = $projectstatic->restrictedProjectArea($user, 'read'); $linktocreatetime = ''; - if ($projectstatic->id > 0) - { - if ($withproject) - { + if ($projectstatic->id > 0) { + if ($withproject) { // Tabs for project - if (empty($id) || $tab == 'timespent') $tab = 'timespent'; - else $tab = 'tasks'; + if (empty($id) || $tab == 'timespent') { + $tab = 'timespent'; + } else { + $tab = 'tasks'; + } $head = project_prepare_head($projectstatic); print dol_get_fiche_head($head, $tab, $langs->trans("Project"), -1, ($projectstatic->public ? 'projectpub' : 'project')); @@ -596,15 +592,13 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Title $morehtmlref .= $projectstatic->title; // Thirdparty - if ($projectstatic->thirdparty->id > 0) - { + if ($projectstatic->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0); $projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -622,33 +616,38 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print $langs->trans("Usage"); print '</td>'; print '<td>'; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '<br>'; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '<br>'; } - if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); print '<br>'; } + if (!empty($conf->eventorganization->enabled)) { + print '<input type="checkbox" disabled name="usage_organize_event"'.(GETPOSTISSET('usage_organize_event') ? (GETPOST('usage_organize_event', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_organize_event ? ' checked="checked"' : '')).'"> '; + $htmltext = $langs->trans("EventOrganizationDescriptionLong"); + print $form->textwithpicto($langs->trans("ManageOrganizeEvent"), $htmltext); + } print '</td></tr>'; // Visibility print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>'; - if ($projectstatic->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); + if ($projectstatic->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } print '</td></tr>'; // Date start - end @@ -658,12 +657,16 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $end = dol_print_date($projectstatic->date_end, 'day'); print ' - '; print ($end ? $end : '?'); - if ($projectstatic->hasDelay()) print img_warning("Late"); + if ($projectstatic->hasDelay()) { + print img_warning("Late"); + } print '</td></tr>'; // Budget print '<tr><td>'.$langs->trans("Budget").'</td><td>'; - if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + if (strcmp($projectstatic->budget_amount, '')) { + print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + } print '</td></tr>'; // Other attributes @@ -708,14 +711,11 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $linktocreatetimeBtnStatus = 0; $linktocreatetimeUrl = ''; $linktocreatetimeHelpText = ''; - if ($user->rights->projet->all->lire || $user->rights->projet->lire) // To enter time, read permission is enough - { - if ($projectstatic->public || $userRead > 0) - { + if ($user->rights->projet->all->lire || $user->rights->projet->lire) { // To enter time, read permission is enough + if ($projectstatic->public || $userRead > 0) { $linktocreatetimeBtnStatus = 1; - if (!empty($projectidforalltimes)) // We are on tab 'Time Spent' of project - { + if (!empty($projectidforalltimes)) { // We are on tab 'Time Spent' of project $backtourl = $_SERVER['PHP_SELF'].'?projectid='.$projectstatic->id.($withproject ? '&withproject=1' : ''); $linktocreatetimeUrl = $_SERVER['PHP_SELF'].'?'.($withproject ? 'withproject=1' : '').'&projectid='.$projectstatic->id.'&action=createtime'.$param.'&backtopage='.urlencode($backtourl); } else // We are on tab 'Time Spent' of task @@ -733,42 +733,41 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } $massactionbutton = ''; - if ($projectstatic->usage_bill_time) - { + if ($projectstatic->usage_bill_time) { $arrayofmassactions = array( 'generateinvoice'=>$langs->trans("GenerateBill"), //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->projet->creer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete', 'generateinvoice'))) $arrayofmassactions = array(); + if (in_array($massaction, array('presend', 'predelete', 'generateinvoice'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); } // Show section with information of task. If id of task is not defined and project id defined, then $projectidforalltimes is not empty. - if (empty($projectidforalltimes)) - { + if (empty($projectidforalltimes)) { $head = task_prepare_head($object); print dol_get_fiche_head($head, 'task_time', $langs->trans("Task"), -1, 'projecttask', 0, '', 'reposition'); - if ($action == 'deleteline') - { + if ($action == 'deleteline') { print $form->formconfirm($_SERVER["PHP_SELF"]."?".($object->id > 0 ? "id=".$object->id : 'projectid='.$projectstatic->id).'&lineid='.GETPOST("lineid", 'int').($withproject ? '&withproject=1' : ''), $langs->trans("DeleteATimeSpent"), $langs->trans("ConfirmDeleteATimeSpent"), "confirm_delete", '', '', 1); } $param = ($withproject ? '&withproject=1' : ''); $linkback = $withproject ? '<a href="'.DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.'">'.$langs->trans("BackToList").'</a>' : ''; - if (!GETPOST('withproject') || empty($projectstatic->id)) - { + if (!GETPOST('withproject') || empty($projectstatic->id)) { $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1); $object->next_prev_filter = " fk_projet in (".$projectsListId.")"; - } else $object->next_prev_filter = " fk_projet = ".$projectstatic->id; + } else { + $object->next_prev_filter = " fk_projet = ".$projectstatic->id; + } $morehtmlref = ''; // Project - if (empty($withproject)) - { + if (empty($withproject)) { $morehtmlref .= '<div class="refidno">'; $morehtmlref .= $langs->trans("Project").': '; $morehtmlref .= $projectstatic->getNomUrl(1); @@ -797,13 +796,14 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $end = dol_print_date($object->date_end, 'dayhour'); print ' - '; print ($end ? $end : '?'); - if ($object->hasDelay()) print img_warning("Late"); + if ($object->hasDelay()) { + print img_warning("Late"); + } print '</td></tr>'; // Planned workload print '<tr><td>'.$langs->trans("PlannedWorkload").'</td><td>'; - if ($object->planned_workload) - { + if ($object->planned_workload) { print convertSecondToTime($object->planned_workload, 'allhourmin'); } print '</td></tr>'; @@ -823,12 +823,16 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Progress calculated print '<tr><td>'.$langs->trans("ProgressCalculated").'</td><td>'; - if ($object->planned_workload) - { + if ($object->planned_workload) { $tmparray = $object->getSummaryOfTimeSpent(); - if ($tmparray['total_duration'] > 0) print round($tmparray['total_duration'] / $object->planned_workload * 100, 2).' %'; - else print '0 %'; - } else print '<span class="opacitymedium">'.$langs->trans("WorkloadNotDefined").'</span>'; + if ($tmparray['total_duration'] > 0) { + print round($tmparray['total_duration'] / $object->planned_workload * 100, 2).' %'; + } else { + print '0 %'; + } + } else { + print '<span class="opacitymedium">'.$langs->trans("WorkloadNotDefined").'</span>'; + } print '</td>'; print '</tr>'; @@ -845,10 +849,8 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } - if ($projectstatic->id > 0) - { - if ($action == 'deleteline' && !empty($projectidforalltimes)) - { + if ($projectstatic->id > 0) { + if ($action == 'deleteline' && !empty($projectidforalltimes)) { print $form->formconfirm($_SERVER["PHP_SELF"]."?".($object->id > 0 ? "id=".$object->id : 'projectid='.$projectstatic->id).'&lineid='.GETPOST('lineid', 'int').($withproject ? '&withproject=1' : ''), $langs->trans("DeleteATimeSpent"), $langs->trans("ConfirmDeleteATimeSpent"), "confirm_delete", '', '', 1); } @@ -858,8 +860,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Definition of fields for list $arrayfields = array(); $arrayfields['t.task_date'] = array('label'=>$langs->trans("Date"), 'checked'=>1); - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task $arrayfields['t.task_ref'] = array('label'=>$langs->trans("RefTask"), 'checked'=>1); $arrayfields['t.task_label'] = array('label'=>$langs->trans("LabelTask"), 'checked'=>1); } @@ -874,33 +875,67 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $arrayfields = dol_sort_array($arrayfields, 'position'); $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_month > 0) $param .= '&search_month='.urlencode($search_month); - if ($search_year > 0) $param .= '&search_year='.urlencode($search_year); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_task_ref != '') $param .= '&search_task_ref='.urlencode($search_task_ref); - if ($search_task_label != '') $param .= '&search_task_label='.urlencode($search_task_label); - if ($search_note != '') $param .= '&search_note='.urlencode($search_note); - if ($search_duration != '') $param .= '&amp;search_field2='.urlencode($search_duration); - 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 ($search_month > 0) { + $param .= '&search_month='.urlencode($search_month); + } + if ($search_year > 0) { + $param .= '&search_year='.urlencode($search_year); + } + if ($search_user > 0) { + $param .= '&search_user='.urlencode($search_user); + } + if ($search_task_ref != '') { + $param .= '&search_task_ref='.urlencode($search_task_ref); + } + if ($search_task_label != '') { + $param .= '&search_task_label='.urlencode($search_task_label); + } + if ($search_note != '') { + $param .= '&search_note='.urlencode($search_note); + } + if ($search_duration != '') { + $param .= '&amp;search_field2='.urlencode($search_duration); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } /* // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; */ - if ($id) $param .= '&id='.urlencode($id); - if ($projectid) $param .= '&projectid='.urlencode($projectid); - if ($withproject) $param .= '&withproject='.urlencode($withproject); + if ($id) { + $param .= '&id='.urlencode($id); + } + if ($projectid) { + $param .= '&projectid='.urlencode($projectid); + } + if ($withproject) { + $param .= '&withproject='.urlencode($withproject); + } print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; - if ($action == 'editline') print '<input type="hidden" name="action" value="updateline">'; - elseif ($action == 'splitline') print '<input type="hidden" name="action" value="updatesplitline">'; - elseif ($action == 'createtime' && $user->rights->projet->lire) print '<input type="hidden" name="action" value="addtimespent">'; - elseif ($massaction == 'generateinvoice' && $user->rights->facture->lire) print '<input type="hidden" name="action" value="confirm_generateinvoice">'; - else print '<input type="hidden" name="action" value="list">'; + if ($action == 'editline') { + print '<input type="hidden" name="action" value="updateline">'; + } elseif ($action == 'splitline') { + print '<input type="hidden" name="action" value="updatesplitline">'; + } elseif ($action == 'createtime' && $user->rights->projet->lire) { + print '<input type="hidden" name="action" value="addtimespent">'; + } elseif ($massaction == 'generateinvoice' && $user->rights->facture->lire) { + print '<input type="hidden" name="action" value="confirm_generateinvoice">'; + } else { + print '<input type="hidden" name="action" value="list">'; + } print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; @@ -910,8 +945,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print '<input type="hidden" name="tab" value="'.$tab.'">'; // Form to convert time spent into invoice - if ($massaction == 'generateinvoice') - { + if ($massaction == 'generateinvoice') { print '<input type="hidden" name="massaction" value="confirm_createbills">'; if ($projectstatic->thirdparty->id > 0) { @@ -939,8 +973,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print '</td>'; print '</tr>'; - if ($conf->service->enabled) - { + if ($conf->service->enabled) { print '<tr>'; print '<td>'; print $langs->trans('ServiceToUseOnLines'); @@ -998,39 +1031,50 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as inv ON inv.rowid = il.fk_facture,"; $sql .= " ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."user as u"; $sql .= " WHERE t.fk_user = u.rowid AND t.fk_task = pt.rowid"; - if (empty($projectidforalltimes)) $sql .= " AND t.fk_task =".$object->id; - else $sql .= " AND pt.fk_projet IN (".$projectidforalltimes.")"; - if ($search_note) $sql .= natural_search('t.note', $search_note); - if ($search_task_ref) $sql .= natural_search('pt.ref', $search_task_ref); - if ($search_task_label) $sql .= natural_search('pt.label', $search_task_label); - if ($search_user > 0) $sql .= natural_search('t.fk_user', $search_user); - if ($search_valuebilled == '1') $sql .= ' AND t.invoice_id > 0'; - if ($search_valuebilled == '0') $sql .= ' AND (t.invoice_id = 0 OR t.invoice_id IS NULL)'; + if (empty($projectidforalltimes)) { + $sql .= " AND t.fk_task =".$object->id; + } else { + $sql .= " AND pt.fk_projet IN (".$projectidforalltimes.")"; + } + if ($search_note) { + $sql .= natural_search('t.note', $search_note); + } + if ($search_task_ref) { + $sql .= natural_search('pt.ref', $search_task_ref); + } + if ($search_task_label) { + $sql .= natural_search('pt.label', $search_task_label); + } + if ($search_user > 0) { + $sql .= natural_search('t.fk_user', $search_user); + } + if ($search_valuebilled == '1') { + $sql .= ' AND t.invoice_id > 0'; + } + if ($search_valuebilled == '0') { + $sql .= ' AND (t.invoice_id = 0 OR t.invoice_id IS NULL)'; + } $sql .= dolSqlDateFilter('t.task_datehour', $search_day, $search_month, $search_year); $sql .= $db->order($sortfield, $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; } @@ -1038,10 +1082,8 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $num = $db->num_rows($resql); } - if ($num >= 0) - { - if (!empty($projectidforalltimes)) - { + if ($num >= 0) { + if (!empty($projectidforalltimes)) { print '<!-- List of time spent for project -->'."\n"; $title = $langs->trans("ListTaskTimeUserProject"); @@ -1056,8 +1098,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } $i = 0; - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_object($resql); $tasks[$i] = $row; $i++; @@ -1070,23 +1111,25 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) /* * Form to add a new line of time spent */ - if ($action == 'createtime' && $user->rights->projet->lire) - { + if ($action == 'createtime' && $user->rights->projet->lire) { print '<!-- table to add time spent -->'."\n"; - if (!empty($id)) print '<input type="hidden" name="taskid" value="'.$id.'">'; + if (!empty($id)) { + print '<input type="hidden" name="taskid" value="'.$id.'">'; + } print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '<table class="noborder nohover centpercent">'; print '<tr class="liste_titre">'; print '<td>'.$langs->trans("Date").'</td>'; - if (empty($id)) print '<td>'.$langs->trans("Task").'</td>'; + if (empty($id)) { + print '<td>'.$langs->trans("Task").'</td>'; + } print '<td>'.$langs->trans("By").'</td>'; print '<td>'.$langs->trans("Note").'</td>'; print '<td>'.$langs->trans("NewTimeSpent").'</td>'; print '<td>'.$langs->trans("ProgressDeclared").'</td>'; - if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<td></td>'; } print '<td></td>'; @@ -1103,8 +1146,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Task $nboftasks = 0; - if (empty($id)) - { + if (empty($id)) { print '<td class="maxwidthonsmartphone">'; $nboftasks = $formproject->selectTasks(-1, GETPOST('taskid', 'int'), 'taskid', 0, 0, 1, 1, 0, 0, 'maxwidth300', $projectstatic->id, ''); print '</td>'; @@ -1113,13 +1155,17 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Contributor print '<td class="maxwidthonsmartphone nowraponall">'; $contactsofproject = $projectstatic->getListContactId('internal'); - if (count($contactsofproject) > 0) - { + if (count($contactsofproject) > 0) { print img_object('', 'user', 'class="hideonsmartphone"'); - if (in_array($user->id, $contactsofproject)) $userid = $user->id; - else $userid = $contactsofproject[0]; + if (in_array($user->id, $contactsofproject)) { + $userid = $user->id; + } else { + $userid = $contactsofproject[0]; + } - if ($projectstatic->public) $contactsofproject = array(); + if ($projectstatic->public) { + $contactsofproject = array(); + } print $form->select_dolusers((GETPOST('userid', 'int') ? GETPOST('userid', 'int') : $userid), 'userid', 0, '', 0, '', $contactsofproject, 0, 0, 0, '', 0, $langs->trans("ResourceNotAssignedToProject"), 'maxwidth250'); } else { if ($nboftasks) { @@ -1136,8 +1182,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Duration - Time spent print '<td>'; $durationtouse = ($_POST['timespent_duration'] ? $_POST['timespent_duration'] : ''); - if (GETPOSTISSET('timespent_durationhour') || GETPOSTISSET('timespent_durationmin')) - { + if (GETPOSTISSET('timespent_durationhour') || GETPOSTISSET('timespent_durationmin')) { $durationtouse = (GETPOST('timespent_durationhour') * 3600 + GETPOST('timespent_durationmin') * 60); } print $form->select_duration('timespent_duration', $durationtouse, 0, 'text'); @@ -1149,8 +1194,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print '</td>'; // Invoiced - if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) { print '<td>'; print '</td>'; } @@ -1170,11 +1214,13 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $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)) - { + if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -1190,29 +1236,43 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Fields title search print '<tr class="liste_titre_filter">'; // Date - if (!empty($arrayfields['t.task_date']['checked'])) - { + if (!empty($arrayfields['t.task_date']['checked'])) { print '<td class="liste_titre">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_day" value="'.$search_day.'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_day" value="'.$search_day.'">'; + } print '<input class="flat valignmiddle" type="text" size="1" maxlength="2" name="search_month" value="'.$search_month.'">'; $formother->select_year($search_year, 'search_year', 1, 20, 5); print '</td>'; } - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { - if (!empty($arrayfields['t.task_ref']['checked'])) print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="search_task_ref" value="'.dol_escape_htmltag($search_task_ref).'"></td>'; - if (!empty($arrayfields['t.task_label']['checked'])) print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'"></td>'; + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task + if (!empty($arrayfields['t.task_ref']['checked'])) { + print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="search_task_ref" value="'.dol_escape_htmltag($search_task_ref).'"></td>'; + } + if (!empty($arrayfields['t.task_label']['checked'])) { + print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'"></td>'; + } } // Author - if (!empty($arrayfields['author']['checked'])) print '<td class="liste_titre">'.$form->select_dolusers(($search_user > 0 ? $search_user : -1), 'search_user', 1, null, 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth250').'</td>'; + if (!empty($arrayfields['author']['checked'])) { + print '<td class="liste_titre">'.$form->select_dolusers(($search_user > 0 ? $search_user : -1), 'search_user', 1, null, 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth250').'</td>'; + } // Note - if (!empty($arrayfields['t.note']['checked'])) print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="search_note" value="'.dol_escape_htmltag($search_note).'"></td>'; + if (!empty($arrayfields['t.note']['checked'])) { + print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="search_note" value="'.dol_escape_htmltag($search_note).'"></td>'; + } // Duration - if (!empty($arrayfields['t.task_duration']['checked'])) print '<td class="liste_titre right"></td>'; + if (!empty($arrayfields['t.task_duration']['checked'])) { + print '<td class="liste_titre right"></td>'; + } // Value in main currency - if (!empty($arrayfields['value']['checked'])) print '<td class="liste_titre"></td>'; + if (!empty($arrayfields['value']['checked'])) { + print '<td class="liste_titre"></td>'; + } // Value billed - if (!empty($arrayfields['valuebilled']['checked'])) print '<td class="liste_titre center">'.$form->selectyesno('search_valuebilled', $search_valuebilled, 1, false, 1).'</td>'; + if (!empty($arrayfields['valuebilled']['checked'])) { + print '<td class="liste_titre center">'.$form->selectyesno('search_valuebilled', $search_valuebilled, 1, false, 1).'</td>'; + } /* // Extra fields @@ -1230,17 +1290,32 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print '</tr>'."\n"; print '<tr class="liste_titre">'; - if (!empty($arrayfields['t.task_date']['checked'])) print_liste_field_titre($arrayfields['t.task_date']['label'], $_SERVER['PHP_SELF'], 't.task_date,t.task_datehour,t.rowid', '', $param, '', $sortfield, $sortorder); - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { - if (!empty($arrayfields['t.task_ref']['checked'])) print_liste_field_titre($arrayfields['t.task_ref']['label'], $_SERVER['PHP_SELF'], 'pt.ref', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['t.task_label']['checked'])) print_liste_field_titre($arrayfields['t.task_label']['label'], $_SERVER['PHP_SELF'], 'pt.label', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['t.task_date']['checked'])) { + print_liste_field_titre($arrayfields['t.task_date']['label'], $_SERVER['PHP_SELF'], 't.task_date,t.task_datehour,t.rowid', '', $param, '', $sortfield, $sortorder); + } + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task + if (!empty($arrayfields['t.task_ref']['checked'])) { + print_liste_field_titre($arrayfields['t.task_ref']['label'], $_SERVER['PHP_SELF'], 'pt.ref', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['t.task_label']['checked'])) { + print_liste_field_titre($arrayfields['t.task_label']['label'], $_SERVER['PHP_SELF'], 'pt.label', '', $param, '', $sortfield, $sortorder); + } + } + if (!empty($arrayfields['author']['checked'])) { + print_liste_field_titre($arrayfields['author']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['t.note']['checked'])) { + print_liste_field_titre($arrayfields['t.note']['label'], $_SERVER['PHP_SELF'], 't.note', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['t.task_duration']['checked'])) { + print_liste_field_titre($arrayfields['t.task_duration']['label'], $_SERVER['PHP_SELF'], 't.task_duration', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['value']['checked'])) { + print_liste_field_titre($arrayfields['value']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['valuebilled']['checked'])) { + print_liste_field_titre($arrayfields['valuebilled']['label'], $_SERVER['PHP_SELF'], 'il.total_ht', '', $param, '', $sortfield, $sortorder, 'center '); } - if (!empty($arrayfields['author']['checked'])) print_liste_field_titre($arrayfields['author']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['t.note']['checked'])) print_liste_field_titre($arrayfields['t.note']['label'], $_SERVER['PHP_SELF'], 't.note', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['t.task_duration']['checked'])) print_liste_field_titre($arrayfields['t.task_duration']['label'], $_SERVER['PHP_SELF'], 't.task_duration', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['value']['checked'])) print_liste_field_titre($arrayfields['value']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['valuebilled']['checked'])) print_liste_field_titre($arrayfields['valuebilled']['label'], $_SERVER['PHP_SELF'], 'il.total_ht', '', $param, '', $sortfield, $sortorder, 'center '); /* // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; @@ -1262,9 +1337,10 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $total = 0; $totalvalue = 0; $totalarray = array(); - foreach ($tasks as $task_time) - { - if ($i >= $limit) break; + foreach ($tasks as $task_time) { + if ($i >= $limit) { + break; + } print '<tr class="oddeven">'; @@ -1272,30 +1348,28 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $date2 = $db->jdate($task_time->task_datehour); // Date - if (!empty($arrayfields['t.task_date']['checked'])) - { + if (!empty($arrayfields['t.task_date']['checked'])) { print '<td class="nowrap">'; - if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) - { - if (empty($task_time->task_date_withhour)) - { + if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) { + if (empty($task_time->task_date_withhour)) { print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 3, 3, 2, "timespent_date", 1, 0); - } else print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 1, 1, 2, "timespent_date", 1, 0); + } else { + print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 1, 1, 2, "timespent_date", 1, 0); + } } else { print dol_print_date(($date2 ? $date2 : $date1), ($task_time->task_date_withhour ? 'dayhour' : 'day')); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Task ref - if (!empty($arrayfields['t.task_ref']['checked'])) - { - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { + if (!empty($arrayfields['t.task_ref']['checked'])) { + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task print '<td class="nowrap">'; - if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) - { + if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) { $formproject->selectTasks(-1, GETPOST('taskid', 'int') ?GETPOST('taskid', 'int') : $task_time->fk_task, 'taskid', 0, 0, 1, 1, 0, 0, 'maxwidth300', $projectstatic->id, ''); } else { $tasktmp->id = $task_time->fk_task; @@ -1304,31 +1378,33 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print $tasktmp->getNomUrl(1, 'withproject', 'time'); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } } else { print '<input type="hidden" name="taskid" value="'.$id.'">'; } // Task label - if (!empty($arrayfields['t.task_label']['checked'])) - { - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { + if (!empty($arrayfields['t.task_label']['checked'])) { + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task print '<td class="nowrap">'; print $task_time->label; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } } // By User - if (!empty($arrayfields['author']['checked'])) - { + if (!empty($arrayfields['author']['checked'])) { print '<td class="nowrap">'; - if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) - { - if (empty($object->id)) $object->fetch($id); + if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) { + if (empty($object->id)) { + $object->fetch($id); + } $contactsoftask = $object->getListContactId('internal'); if (!in_array($task_time->fk_user, $contactsoftask)) { $contactsoftask[] = $task_time->fk_user; @@ -1348,72 +1424,77 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print $userstatic->getNomUrl(-1); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Note - if (!empty($arrayfields['t.note']['checked'])) - { + if (!empty($arrayfields['t.note']['checked'])) { print '<td class="left">'; - if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) - { + if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) { print '<textarea name="timespent_note_line" width="95%" rows="'.ROWS_2.'">'.$task_time->note.'</textarea>'; } else { print dol_nl2br($task_time->note); } print '</td>'; - if (!$i) $totalarray['nbfield']++; - } elseif ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) - { + if (!$i) { + $totalarray['nbfield']++; + } + } elseif ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) { print '<input type="hidden" name="timespent_note_line" value="'.$task_time->note.'">'; } // Time spent - if (!empty($arrayfields['t.task_duration']['checked'])) - { + if (!empty($arrayfields['t.task_duration']['checked'])) { print '<td class="right">'; - if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) - { + if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) { print '<input type="hidden" name="old_duration" value="'.$task_time->task_duration.'">'; print $form->select_duration('new_duration', $task_time->task_duration, 0, 'text'); } else { print convertSecondToTime($task_time->task_duration, 'allhourmin'); } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.task_duration'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.task_duration'; + } $totalarray['val']['t.task_duration'] += $task_time->task_duration; - if (!$i) $totalarray['totaldurationfield'] = $totalarray['nbfield']; + if (!$i) { + $totalarray['totaldurationfield'] = $totalarray['nbfield']; + } $totalarray['totalduration'] += $task_time->task_duration; } // Value spent - if (!empty($arrayfields['value']['checked'])) - { + if (!empty($arrayfields['value']['checked'])) { print '<td class="nowraponall right">'; $value = price2num($task_time->thm * $task_time->task_duration / 3600, 'MT', 1); print price($value, 1, $langs, 1, -1, -1, $conf->currency); print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'value'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'value'; + } $totalarray['val']['value'] += $value; - if (!$i) $totalarray['totalvaluefield'] = $totalarray['nbfield']; + if (!$i) { + $totalarray['totalvaluefield'] = $totalarray['nbfield']; + } $totalarray['totalvalue'] += $value; } // Invoiced - if (!empty($arrayfields['valuebilled']['checked'])) - { + if (!empty($arrayfields['valuebilled']['checked'])) { print '<td class="center">'; // invoice_id and invoice_line_id - if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { - if ($projectstatic->usage_bill_time) - { - if ($task_time->invoice_id) - { + if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) { + if ($projectstatic->usage_bill_time) { + if ($task_time->invoice_id) { $result = $tmpinvoice->fetch($task_time->invoice_id); - if ($result > 0) - { + if ($result > 0) { print $tmpinvoice->getNomUrl(1); } } else { @@ -1424,7 +1505,9 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } /* @@ -1439,18 +1522,14 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Action column print '<td class="center nowraponall">'; - if (($action == 'editline' || $action == 'splitline') && $_GET['lineid'] == $task_time->rowid) - { + if (($action == 'editline' || $action == 'splitline') && $_GET['lineid'] == $task_time->rowid) { print '<input type="hidden" name="lineid" value="'.$_GET['lineid'].'">'; print '<input type="submit" class="button buttongen margintoponlyshort marginbottomonlyshort button-save" name="save" value="'.$langs->trans("Save").'">'; print '<br>'; print '<input type="submit" class="button buttongen margintoponlyshort marginbottomonlyshort button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; - } elseif ($user->rights->projet->lire || $user->rights->projet->all->creer) // Read project and enter time consumed on assigned tasks - { - if ($task_time->fk_user == $user->id || in_array($task_time->fk_user, $childids) || $user->rights->projet->all->creer) - { - if ($conf->MAIN_FEATURES_LEVEL >= 2) - { + } elseif ($user->rights->projet->lire || $user->rights->projet->all->creer) { // Read project and enter time consumed on assigned tasks + if ($task_time->fk_user == $user->id || in_array($task_time->fk_user, $childids) || $user->rights->projet->all->creer) { + if ($conf->MAIN_FEATURES_LEVEL >= 2) { print '&nbsp;'; print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$task_time->fk_task.'&amp;action=splitline&amp;lineid='.$task_time->rowid.$param.((empty($id) || $tab == 'timespent') ? '&tab=timespent' : '').'">'; print img_split(); @@ -1467,37 +1546,38 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print img_delete('default', 'class="pictodelete paddingleft"'); print '</a>'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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($task_time->rowid, $arrayofselected)) $selected = 1; + if (in_array($task_time->rowid, $arrayofselected)) { + $selected = 1; + } print '&nbsp;'; print '<input id="cb'.$task_time->rowid.'" class="flat checkforselect marginleftonly" type="checkbox" name="toselect[]" value="'.$task_time->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } } } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; // Add line to split - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) { print '<tr class="oddeven">'; // Date - if (!empty($arrayfields['t.task_date']['checked'])) - { + if (!empty($arrayfields['t.task_date']['checked'])) { print '<td class="nowrap">'; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - if (empty($task_time->task_date_withhour)) - { + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) { + if (empty($task_time->task_date_withhour)) { print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 3, 3, 2, "timespent_date", 1, 0); - } else print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 1, 1, 2, "timespent_date", 1, 0); + } else { + print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 1, 1, 2, "timespent_date", 1, 0); + } } else { print dol_print_date(($date2 ? $date2 : $date1), ($task_time->task_date_withhour ? 'dayhour' : 'day')); } @@ -1505,10 +1585,8 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // Task ref - if (!empty($arrayfields['t.task_ref']['checked'])) - { - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { + if (!empty($arrayfields['t.task_ref']['checked'])) { + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task print '<td class="nowrap">'; $tasktmp->id = $task_time->fk_task; $tasktmp->ref = $task_time->ref; @@ -1519,10 +1597,8 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // Task label - if (!empty($arrayfields['t.task_label']['checked'])) - { - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { + if (!empty($arrayfields['t.task_label']['checked'])) { + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task print '<td>'; print $task_time->label; print '</td>'; @@ -1530,12 +1606,12 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // User - if (!empty($arrayfields['author']['checked'])) - { + if (!empty($arrayfields['author']['checked'])) { print '<td>'; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - if (empty($object->id)) $object->fetch($id); + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) { + if (empty($object->id)) { + $object->fetch($id); + } $contactsoftask = $object->getListContactId('internal'); if (!in_array($task_time->fk_user, $contactsoftask)) { $contactsoftask[] = $task_time->fk_user; @@ -1558,27 +1634,22 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // Note - if (!empty($arrayfields['t.note']['checked'])) - { + if (!empty($arrayfields['t.note']['checked'])) { print '<td class="left">'; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) { print '<textarea name="timespent_note_line" width="95%" rows="'.ROWS_2.'">'.$task_time->note.'</textarea>'; } else { print dol_nl2br($task_time->note); } print '</td>'; - } elseif ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { + } elseif ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) { print '<input type="hidden" name="timespent_note_line" value="'.$task_time->note.'">'; } // Time spent - if (!empty($arrayfields['t.task_duration']['checked'])) - { + if (!empty($arrayfields['t.task_duration']['checked'])) { print '<td class="right">'; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) { print '<input type="hidden" name="old_duration" value="'.$task_time->task_duration.'">'; print $form->select_duration('new_duration', $task_time->task_duration, 0, 'text'); } else { @@ -1588,8 +1659,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // Value spent - if (!empty($arrayfields['value']['checked'])) - { + if (!empty($arrayfields['value']['checked'])) { print '<td class="right">'; $value = price2num($task_time->thm * $task_time->task_duration / 3600, 'MT', 1); print price($value, 1, $langs, 1, -1, -1, $conf->currency); @@ -1597,11 +1667,12 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // Value billed - if (!empty($arrayfields['valuebilled']['checked'])) - { + if (!empty($arrayfields['valuebilled']['checked'])) { print '<td class="right">'; $valuebilled = price2num($task_time->total_ht, '', 1); - if (isset($task_time->total_ht)) print price($valuebilled, 1, $langs, 1, -1, -1, $conf->currency); + if (isset($task_time->total_ht)) { + print price($valuebilled, 1, $langs, 1, -1, -1, $conf->currency); + } print '</td>'; } @@ -1627,15 +1698,14 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print '<tr class="oddeven">'; // Date - if (!empty($arrayfields['t.task_date']['checked'])) - { + if (!empty($arrayfields['t.task_date']['checked'])) { print '<td class="nowrap">'; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - if (empty($task_time->task_date_withhour)) - { + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) { + if (empty($task_time->task_date_withhour)) { print $form->selectDate(($date2 ? $date2 : $date1), 'timeline_2', 3, 3, 2, "timespent_date", 1, 0); - } else print $form->selectDate(($date2 ? $date2 : $date1), 'timeline_2', 1, 1, 2, "timespent_date", 1, 0); + } else { + print $form->selectDate(($date2 ? $date2 : $date1), 'timeline_2', 1, 1, 2, "timespent_date", 1, 0); + } } else { print dol_print_date(($date2 ? $date2 : $date1), ($task_time->task_date_withhour ? 'dayhour' : 'day')); } @@ -1643,10 +1713,8 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // Task ref - if (!empty($arrayfields['t.task_ref']['checked'])) - { - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { + if (!empty($arrayfields['t.task_ref']['checked'])) { + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task print '<td class="nowrap">'; $tasktmp->id = $task_time->fk_task; $tasktmp->ref = $task_time->ref; @@ -1657,10 +1725,8 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // Task label - if (!empty($arrayfields['t.task_label']['checked'])) - { - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { + if (!empty($arrayfields['t.task_label']['checked'])) { + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task print '<td class="nowrap">'; print $task_time->label; print '</td>'; @@ -1668,12 +1734,12 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // User - if (!empty($arrayfields['author']['checked'])) - { + if (!empty($arrayfields['author']['checked'])) { print '<td>'; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - if (empty($object->id)) $object->fetch($id); + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) { + if (empty($object->id)) { + $object->fetch($id); + } $contactsoftask = $object->getListContactId('internal'); if (!in_array($task_time->fk_user, $contactsoftask)) { $contactsoftask[] = $task_time->fk_user; @@ -1696,27 +1762,22 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // Note - if (!empty($arrayfields['t.note']['checked'])) - { + if (!empty($arrayfields['t.note']['checked'])) { print '<td class="left">'; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) { print '<textarea name="timespent_note_line_2" width="95%" rows="'.ROWS_2.'">'.$task_time->note.'</textarea>'; } else { print dol_nl2br($task_time->note); } print '</td>'; - } elseif ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { + } elseif ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) { print '<input type="hidden" name="timespent_note_line_2" value="'.$task_time->note.'">'; } // Time spent - if (!empty($arrayfields['t.task_duration']['checked'])) - { + if (!empty($arrayfields['t.task_duration']['checked'])) { print '<td class="right">'; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) { print '<input type="hidden" name="old_duration_2" value="0">'; print $form->select_duration('new_duration_2', 0, 0, 'text'); } else { @@ -1726,8 +1787,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // Value spent - if (!empty($arrayfields['value']['checked'])) - { + if (!empty($arrayfields['value']['checked'])) { print '<td class="right">'; $value = 0; print price($value, 1, $langs, 1, -1, -1, $conf->currency); @@ -1735,11 +1795,12 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // Value billed - if (!empty($arrayfields['valuebilled']['checked'])) - { + if (!empty($arrayfields['valuebilled']['checked'])) { print '<td class="right">'; $valuebilled = price2num($task_time->total_ht, '', 1); - if (isset($task_time->total_ht)) print price($valuebilled, 1, $langs, 1, -1, -1, $conf->currency); + if (isset($task_time->total_ht)) { + print price($valuebilled, 1, $langs, 1, -1, -1, $conf->currency); + } print '</td>'; } @@ -1765,31 +1826,35 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Show total line //include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; - if (isset($totalarray['totaldurationfield']) || isset($totalarray['totalvaluefield'])) - { + if (isset($totalarray['totaldurationfield']) || isset($totalarray['totalvaluefield'])) { print '<tr class="liste_total">'; $i = 0; - while ($i < $totalarray['nbfield']) - { + while ($i < $totalarray['nbfield']) { $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print '<td class="left">'.$langs->trans("Total").'</td>'; - else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; - } elseif ($totalarray['totaldurationfield'] == $i) print '<td class="right">'.convertSecondToTime($totalarray['totalduration'], 'allhourmin').'</td>'; - elseif ($totalarray['totalvaluefield'] == $i) print '<td class="right">'.price($totalarray['totalvalue']).'</td>'; - //elseif ($totalarray['totalvaluebilledfield'] == $i) print '<td class="center">'.price($totalarray['totalvaluebilled']).'</td>'; - else print '<td></td>'; + if ($i == 1) { + if ($num < $limit && empty($offset)) { + print '<td class="left">'.$langs->trans("Total").'</td>'; + } else { + print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; + } + } elseif ($totalarray['totaldurationfield'] == $i) { + print '<td class="right">'.convertSecondToTime($totalarray['totalduration'], 'allhourmin').'</td>'; + } elseif ($totalarray['totalvaluefield'] == $i) { + print '<td class="right">'.price($totalarray['totalvalue']).'</td>'; + //} elseif ($totalarray['totalvaluebilledfield'] == $i) { print '<td class="center">'.price($totalarray['totalvaluebilled']).'</td>'; + } else { + print '<td></td>'; + } } print '</tr>'; } - if (!count($tasks)) - { + if (!count($tasks)) { $totalnboffields = 1; - foreach ($arrayfields as $value) - { - if ($value['checked']) $totalnboffields++; + foreach ($arrayfields as $value) { + if ($value['checked']) { + $totalnboffields++; + } } print '<tr class="oddeven"><td colspan="'.$totalnboffields.'">'; print '<span class="opacitymedium">'.$langs->trans("None").'</span>'; diff --git a/htdocs/public/agenda/agendaexport.php b/htdocs/public/agenda/agendaexport.php index 395bfd8915a..d1441a4a98c 100644 --- a/htdocs/public/agenda/agendaexport.php +++ b/htdocs/public/agenda/agendaexport.php @@ -28,13 +28,27 @@ * &id=..., &idfrom=..., &idto=... */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no menu to show -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); // If there is no menu to show +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} // It's a wrapper, so empty header @@ -61,39 +75,69 @@ function llxFooterVierge() // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; // Security check -if (empty($conf->agenda->enabled)) accessforbidden('', 0, 0, 1); +if (empty($conf->agenda->enabled)) { + accessforbidden('', 0, 0, 1); +} // Not older than -if (!isset($conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY)) $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY = 100; // default limit +if (!isset($conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY)) { + $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY = 100; // default limit +} // Define format, type and filter $format = 'ical'; $type = 'event'; -if (GETPOST("format", 'alpha')) $format = GETPOST("format", 'apha'); -if (GETPOST("type", 'apha')) $type = GETPOST("type", 'alpha'); +if (GETPOST("format", 'alpha')) { + $format = GETPOST("format", 'apha'); +} +if (GETPOST("type", 'apha')) { + $type = GETPOST("type", 'alpha'); +} $filters = array(); -if (GETPOST("year", 'int')) $filters['year'] = GETPOST("year", 'int'); -if (GETPOST("id", 'int')) $filters['id'] = GETPOST("id", 'int'); -if (GETPOST("idfrom", 'int')) $filters['idfrom'] = GETPOST("idfrom", 'int'); -if (GETPOST("idto", 'int')) $filters['idto'] = GETPOST("idto", 'int'); -if (GETPOST("project", 'apha')) $filters['project'] = GETPOST("project", 'apha'); -if (GETPOST("logina", 'apha')) $filters['logina'] = GETPOST("logina", 'apha'); -if (GETPOST("logint", 'apha')) $filters['logint'] = GETPOST("logint", 'apha'); -if (GETPOST("notactiontype", 'apha')) $filters['notactiontype'] = GETPOST("notactiontype", 'apha'); -if (GETPOST("actiontype", 'apha')) $filters['actiontype'] = GETPOST("actiontype", 'apha'); -if (GETPOST("notolderthan", 'int')) $filters['notolderthan'] = GETPOST("notolderthan", "int"); -else $filters['notolderthan'] = $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY; +if (GETPOST("year", 'int')) { + $filters['year'] = GETPOST("year", 'int'); +} +if (GETPOST("id", 'int')) { + $filters['id'] = GETPOST("id", 'int'); +} +if (GETPOST("idfrom", 'int')) { + $filters['idfrom'] = GETPOST("idfrom", 'int'); +} +if (GETPOST("idto", 'int')) { + $filters['idto'] = GETPOST("idto", 'int'); +} +if (GETPOST("project", 'apha')) { + $filters['project'] = GETPOST("project", 'apha'); +} +if (GETPOST("logina", 'apha')) { + $filters['logina'] = GETPOST("logina", 'apha'); +} +if (GETPOST("logint", 'apha')) { + $filters['logint'] = GETPOST("logint", 'apha'); +} +if (GETPOST("notactiontype", 'apha')) { + $filters['notactiontype'] = GETPOST("notactiontype", 'apha'); +} +if (GETPOST("actiontype", 'apha')) { + $filters['actiontype'] = GETPOST("actiontype", 'apha'); +} +if (GETPOST("notolderthan", 'int')) { + $filters['notolderthan'] = GETPOST("notolderthan", "int"); +} else { + $filters['notolderthan'] = $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY; +} // Check config -if (empty($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY)) -{ +if (empty($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY)) { $user->getrights(); llxHeaderVierge(); @@ -131,25 +175,45 @@ if ($reshook < 0) { $shortfilename = 'dolibarrcalendar'; $filename = $shortfilename; // Complete long filename -foreach ($filters as $key => $value) -{ +foreach ($filters as $key => $value) { //if ($key == 'notolderthan') $filename.='-notolderthan'.$value; This filter key is already added before and does not need to be in filename - if ($key == 'year') $filename .= '-year'.$value; - if ($key == 'id') $filename .= '-id'.$value; - if ($key == 'idfrom') $filename .= '-idfrom'.$value; - if ($key == 'idto') $filename .= '-idto'.$value; - if ($key == 'project') $filename .= '-project'.$value; - if ($key == 'logina') $filename .= '-logina'.$value; // Author - if ($key == 'logint') $filename .= '-logint'.$value; // Assigned to - if ($key == 'notactiontype') $filename .= '-notactiontype'.$value; + if ($key == 'year') { + $filename .= '-year'.$value; + } + if ($key == 'id') { + $filename .= '-id'.$value; + } + if ($key == 'idfrom') { + $filename .= '-idfrom'.$value; + } + if ($key == 'idto') { + $filename .= '-idto'.$value; + } + if ($key == 'project') { + $filename .= '-project'.$value; + } + if ($key == 'logina') { + $filename .= '-logina'.$value; // Author + } + if ($key == 'logint') { + $filename .= '-logint'.$value; // Assigned to + } + if ($key == 'notactiontype') { + $filename .= '-notactiontype'.$value; + } } // Add extension -if ($format == 'vcal') { $shortfilename .= '.vcs'; $filename .= '.vcs'; } -if ($format == 'ical') { $shortfilename .= '.ics'; $filename .= '.ics'; } -if ($format == 'rss') { $shortfilename .= '.rss'; $filename .= '.rss'; } +if ($format == 'vcal') { + $shortfilename .= '.vcs'; $filename .= '.vcs'; +} +if ($format == 'ical') { + $shortfilename .= '.ics'; $filename .= '.ics'; +} +if ($format == 'rss') { + $shortfilename .= '.rss'; $filename .= '.rss'; +} -if ($shortfilename == 'dolibarrcalendar') -{ +if ($shortfilename == 'dolibarrcalendar') { $langs->load("main"); $langs->load("errors"); llxHeaderVierge(); @@ -161,34 +225,47 @@ if ($shortfilename == 'dolibarrcalendar') $agenda = new ActionComm($db); $cachedelay = 0; -if (!empty($conf->global->MAIN_AGENDA_EXPORT_CACHE)) $cachedelay = $conf->global->MAIN_AGENDA_EXPORT_CACHE; +if (!empty($conf->global->MAIN_AGENDA_EXPORT_CACHE)) { + $cachedelay = $conf->global->MAIN_AGENDA_EXPORT_CACHE; +} $exportholidays = GETPOST('includeholidays', 'int'); // Build file -if ($format == 'ical' || $format == 'vcal') -{ +if ($format == 'ical' || $format == 'vcal') { $result = $agenda->build_exportfile($format, $type, $cachedelay, $filename, $filters, $exportholidays); - if ($result >= 0) - { + if ($result >= 0) { $attachment = true; - if (isset($_GET["attachment"])) $attachment = $_GET["attachment"]; + if (isset($_GET["attachment"])) { + $attachment = $_GET["attachment"]; + } //$attachment = false; $contenttype = 'text/calendar'; - if (isset($_GET["contenttype"])) $contenttype = $_GET["contenttype"]; + if (isset($_GET["contenttype"])) { + $contenttype = $_GET["contenttype"]; + } //$contenttype='text/plain'; $outputencoding = 'UTF-8'; - if ($contenttype) header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : '')); - if ($attachment) header('Content-Disposition: attachment; filename="'.$shortfilename.'"'); + if ($contenttype) { + header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : '')); + } + if ($attachment) { + header('Content-Disposition: attachment; filename="'.$shortfilename.'"'); + } - if ($cachedelay) header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate'); - else header('Cache-Control: private, must-revalidate'); + if ($cachedelay) { + header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate'); + } else { + header('Cache-Control: private, must-revalidate'); + } // Clean parameters $outputfile = $conf->agenda->dir_temp.'/'.$filename; $result = readfile($outputfile); - if (!$result) print 'File '.$outputfile.' was empty.'; + if (!$result) { + print 'File '.$outputfile.' was empty.'; + } //header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename)); exit; @@ -199,32 +276,43 @@ if ($format == 'ical' || $format == 'vcal') } } -if ($format == 'rss') -{ +if ($format == 'rss') { $result = $agenda->build_exportfile($format, $type, $cachedelay, $filename, $filters, $exportholidays); - if ($result >= 0) - { + if ($result >= 0) { $attachment = false; - if (isset($_GET["attachment"])) $attachment = $_GET["attachment"]; + if (isset($_GET["attachment"])) { + $attachment = $_GET["attachment"]; + } //$attachment = false; $contenttype = 'application/rss+xml'; - if (isset($_GET["contenttype"])) $contenttype = $_GET["contenttype"]; + if (isset($_GET["contenttype"])) { + $contenttype = $_GET["contenttype"]; + } //$contenttype='text/plain'; $outputencoding = 'UTF-8'; - if ($contenttype) header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : '')); - if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"'); + if ($contenttype) { + header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : '')); + } + if ($attachment) { + header('Content-Disposition: attachment; filename="'.$filename.'"'); + } // Ajout directives pour resoudre bug IE //header('Cache-Control: Public, must-revalidate'); //header('Pragma: public'); - if ($cachedelay) header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate'); - else header('Cache-Control: private, must-revalidate'); + if ($cachedelay) { + header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate'); + } else { + header('Cache-Control: private, must-revalidate'); + } // Clean parameters $outputfile = $conf->agenda->dir_temp.'/'.$filename; $result = readfile($outputfile); - if (!$result) print 'File '.$outputfile.' was empty.'; + if (!$result) { + print 'File '.$outputfile.' was empty.'; + } // header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename)); exit; diff --git a/htdocs/public/cron/cron_run_jobs.php b/htdocs/public/cron/cron_run_jobs_by_url.php similarity index 85% rename from htdocs/public/cron/cron_run_jobs.php rename to htdocs/public/cron/cron_run_jobs_by_url.php index cd5f1e3be51..aaf7e38cac8 100644 --- a/htdocs/public/cron/cron_run_jobs.php +++ b/htdocs/public/cron/cron_run_jobs_by_url.php @@ -23,21 +23,34 @@ * \ingroup cron * \brief Execute pendings jobs */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOLOGIN')) define('NOLOGIN', '1'); -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', '1'); +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} // Error if CLI mode -if (php_sapi_name() == "cli") -{ +if (php_sapi_name() == "cli") { echo "Error: This page can't be used as a CLI script. For the CLI version of script, launch cron_run_job.php available into scripts/cron/ directory.\n"; exit(-1); } @@ -66,39 +79,36 @@ $now = dol_now(); // Check the key, avoid that a stranger starts cron $key = GETPOST('securitykey', 'alpha'); -if (empty($key)) -{ +if (empty($key)) { echo 'Securitykey is required. Check setup of cron jobs module.'; exit; } -if ($key != $conf->global->CRON_KEY) -{ +if ($key != $conf->global->CRON_KEY) { echo 'Securitykey is wrong.'; exit; } // Check the key, avoid that a stranger starts cron $userlogin = GETPOST('userlogin', 'alpha'); -if (empty($userlogin)) -{ +if (empty($userlogin)) { echo 'Userlogin is required.'; exit; } require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; $user = new User($db); $result = $user->fetch('', $userlogin); -if ($result < 0) -{ +if ($result < 0) { echo "User Error:".$user->error; dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR); exit; } else { - if (empty($user->id)) - { + if (empty($user->id)) { echo " User login:".$userlogin." do not exists"; dol_syslog(" User login:".$userlogin." do not exists", LOG_ERR); exit; } } +$user->getrights(); + $id = GETPOST('id', 'alpha'); // We accept non numeric id. We will filter later. @@ -107,8 +117,7 @@ $object = new Cronjob($db); $filter = array(); if (!empty($id)) { - if (!is_numeric($id)) - { + if (!is_numeric($id)) { echo "Error: Bad value for parameter job id"; dol_syslog("cron_run_jobs.php Bad value for parameter job id", LOG_WARNING); exit; @@ -117,17 +126,17 @@ if (!empty($id)) { } $result = $object->fetch_all('ASC,ASC,ASC', 't.priority,t.entity,t.rowid', 0, 0, 1, $filter, 0); -if ($result < 0) -{ +if ($result < 0) { echo "Error: ".$object->error; dol_syslog("cron_run_jobs.php fetch Error".$object->error, LOG_ERR); exit; } $qualifiedjobs = array(); -foreach ($object->lines as $val) -{ - if (!verifCond($val->test)) continue; +foreach ($object->lines as $val) { + if (!verifCond($val->test)) { + continue; + } $qualifiedjobs[] = $val; } @@ -138,19 +147,16 @@ $nbofjobs = count($qualifiedjobs); $nbofjobslaunchedok = 0; $nbofjobslaunchedko = 0; -if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) -{ +if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) { $savconf = dol_clone($conf); // Loop over job - foreach ($qualifiedjobs as $line) - { + foreach ($qualifiedjobs as $line) { dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG); echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label; // Force reload of setup for the current entity - if ($line->entity != $conf->entity) - { + if ($line->entity != $conf->entity) { dol_syslog("cron_run_jobs.php we work on another entity so we reload user and conf", LOG_DEBUG); echo " -> we change entity so we reload user and conf"; @@ -158,17 +164,14 @@ if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) $conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings // Force recheck that user is ok for the entity to process and reload permission for entity - if ($conf->entity != $user->entity && $user->entity != 0) - { + if ($conf->entity != $user->entity && $user->entity != 0) { $result = $user->fetch('', $userlogin, '', 0, $conf->entity); - if ($result < 0) - { + if ($result < 0) { echo "\nUser Error: ".$user->error."\n"; dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR); exit(-1); } else { - if ($result == 0) - { + if ($result == 0) { echo "\nUser login: ".$userlogin." does not exists for entity ".$conf->entity."\n"; dol_syslog("User login:".$userlogin." does not exists", LOG_ERR); exit(-1); @@ -179,16 +182,14 @@ if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) } //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database - if (($line->datenextrun < $now) && (empty($line->datestart) || $line->datestart <= $now) && (empty($line->dateend) || $line->dateend >= $now)) - { + if (($line->datenextrun < $now) && (empty($line->datestart) || $line->datestart <= $now) && (empty($line->dateend) || $line->dateend >= $now)) { echo " - qualified"; dol_syslog("cron_run_jobs.php line->datenextrun:".dol_print_date($line->datenextrun, 'dayhourrfc')." line->datestart:".dol_print_date($line->datestart, 'dayhourrfc')." line->dateend:".dol_print_date($line->dateend, 'dayhourrfc')." now:".dol_print_date($now, 'dayhourrfc')); $cronjob = new Cronjob($db); $result = $cronjob->fetch($line->id); - if ($result < 0) - { + if ($result < 0) { echo "Error cronjobid: ".$line->id." cronjob->fetch: ".$cronjob->error."\n"; echo "Failed to fetch job ".$line->id."\n"; dol_syslog("cron_run_jobs.php::fetch Error".$cronjob->error, LOG_ERR); @@ -196,8 +197,7 @@ if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) } // Execute job $result = $cronjob->run_jobs($userlogin); - if ($result < 0) - { + if ($result < 0) { echo "Error cronjobid: ".$line->id." cronjob->run_job: ".$cronjob->error."\n"; echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n"; echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n"; @@ -211,8 +211,7 @@ if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) // We re-program the next execution and stores the last execution time for this job $result = $cronjob->reprogram_jobs($userlogin, $now); - if ($result < 0) - { + if ($result < 0) { echo "Error cronjobid: ".$line->id." cronjob->reprogram_job: ".$cronjob->error."\n"; echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n"; dol_syslog("cron_run_jobs.php::reprogram_jobs Error".$cronjob->error, LOG_ERR); diff --git a/htdocs/public/demo/index.php b/htdocs/public/demo/index.php index dbfeeebbf58..e39a332d3fb 100644 --- a/htdocs/public/demo/index.php +++ b/htdocs/public/demo/index.php @@ -24,10 +24,18 @@ * \brief Entry page to access demo */ -if (!defined('NOLOGIN')) define('NOLOGIN', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', 1); -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (!defined('NOLOGIN')) { + define('NOLOGIN', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', 1); +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} require '../../main.inc.php'; require_once '../../core/lib/functions2.lib.php'; @@ -42,7 +50,9 @@ $conf->dol_use_jmobile = GETPOST('dol_use_jmobile', 'int'); // Security check global $dolibarr_main_demo; -if (empty($dolibarr_main_demo)) accessforbidden('Parameter dolibarr_main_demo must be defined in conf file with value "default login,default pass" to enable the demo entry page', 0, 0, 1); +if (empty($dolibarr_main_demo)) { + accessforbidden('Parameter dolibarr_main_demo must be defined in conf file with value "default login,default pass" to enable the demo entry page', 0, 0, 1); +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $res = $hookmanager->initHooks(array('demo')); @@ -66,8 +76,7 @@ $parameters = array(); $object = new stdClass(); $reshook = $hookmanager->executeHooks('addDemoProfile', $parameters, $object, $tmpaction); // Note that $action and $object may have been modified by some hooks $error = $hookmanager->error; $errors = $hookmanager->errors; -if (empty($reshook)) -{ +if (empty($reshook)) { $demoprofiles = array( array('default'=>'1', 'key'=>'profdemoservonly', 'label'=>'DemoCompanyServiceOnly', 'disablemodules'=>'adherent,barcode,bom,cashdesk,don,expedition,externalsite,ftp,incoterm,mailmanspip,margin,mrp,prelevement,product,productbatch,stock,takepos', @@ -131,27 +140,21 @@ $dirmod = array(); $i = 0; // is a sequencer of modules found $j = 0; // j is module number. Automatically affected if module number not defined. -foreach ($modulesdir as $dir) -{ +foreach ($modulesdir as $dir) { // Charge tableaux modules, nom, numero, orders depuis repertoire dir $handle = @opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { //print "$i ".$file."\n<br>"; - if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') - { + if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') { $modName = substr($file, 0, dol_strlen($file) - 10); - if ($modName) - { + if ($modName) { try { include_once $dir.$file; $objMod = new $modName($db); - if ($objMod->numero > 0) - { + if ($objMod->numero > 0) { $j = $objMod->numero; } else { $j = 1000 + $i; @@ -161,11 +164,14 @@ foreach ($modulesdir as $dir) // We discard modules according to features level (PS: if module is activated we always show it) $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod))); - if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && empty($conf->global->$const_name)) $modulequalified = 0; - if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && empty($conf->global->$const_name)) $modulequalified = 0; + if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && empty($conf->global->$const_name)) { + $modulequalified = 0; + } + if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && empty($conf->global->$const_name)) { + $modulequalified = 0; + } - if ($modulequalified) - { + if ($modulequalified) { $modules[$i] = $objMod; $filename[$i] = $modName; $orders[$i] = $objMod->family."_".$j; // Tri par famille puis numero module @@ -174,8 +180,7 @@ foreach ($modulesdir as $dir) $j++; $i++; } - } catch (Exception $e) - { + } catch (Exception $e) { dol_syslog("Failed to load ".$dir.$file." ".$e->getMessage(), LOG_ERR); } } @@ -192,37 +197,34 @@ asort($orders); * Actions */ -if (GETPOST('action', 'aZ09') == 'gotodemo') // Action run when we click on "Start" after selection modules -{ +if (GETPOST('action', 'aZ09') == 'gotodemo') { // Action run when we click on "Start" after selection modules //print 'ee'.GETPOST("demochoice"); $disablestring = ''; // If we disable modules using a profile choice - if (GETPOST("demochoice")) - { - foreach ($demoprofiles as $profilearray) - { - if ($profilearray['key'] == GETPOST("demochoice")) - { + if (GETPOST("demochoice")) { + foreach ($demoprofiles as $profilearray) { + if ($profilearray['key'] == GETPOST("demochoice")) { $disablestring = $profilearray['disablemodules']; break; } } } // If we disable modules using personalized list - foreach ($modules as $val) - { + foreach ($modules as $val) { $modulekeyname = strtolower($val->name); - if (empty($_POST[$modulekeyname]) && empty($val->always_enabled) && !in_array($modulekeyname, $alwayscheckedmodules)) - { + if (empty($_POST[$modulekeyname]) && empty($val->always_enabled) && !in_array($modulekeyname, $alwayscheckedmodules)) { $disablestring .= $modulekeyname.','; - if ($modulekeyname == 'propale') $disablestring .= 'propal,'; + if ($modulekeyname == 'propale') { + $disablestring .= 'propal,'; + } } } // Do redirect to login page - if ($disablestring) - { - if (GETPOST('urlfrom')) $url .= (preg_match('/\?/', $url) ? '&amp;' : '?').'urlfrom='.urlencode(GETPOST('urlfrom', 'alpha')); + if ($disablestring) { + if (GETPOST('urlfrom')) { + $url .= (preg_match('/\?/', $url) ? '&amp;' : '?').'urlfrom='.urlencode(GETPOST('urlfrom', 'alpha')); + } $url .= (preg_match('/\?/', $url) ? '&amp;' : '?').'disablemodules='.$disablestring; //var_dump($url);exit; header("Location: ".$url); @@ -288,12 +290,12 @@ print '<div class="clearboth"></div>'; print '<div class="demobanbox">'; $i = 0; -foreach ($demoprofiles as $profilearray) -{ - if ($profilearray['default'] >= 0) - { +foreach ($demoprofiles as $profilearray) { + if ($profilearray['default'] >= 0) { //print $profilearray['lang']; - if (!empty($profilearray['lang'])) $langs->load($profilearray['lang']); + if (!empty($profilearray['lang'])) { + $langs->load($profilearray['lang']); + } $url = $_SERVER["PHP_SELF"].'?action=gotodemo'; $urlwithmod = $url.'&amp;demochoice='.$profilearray['key']; @@ -303,18 +305,15 @@ foreach ($demoprofiles as $profilearray) $urlfrom = preg_replace('/^'.preg_quote(DOL_URL_ROOT, '/').'/i', '', $_SERVER["PHP_SELF"]); //print $urlfrom; - if (!empty($profilearray['url'])) - { + if (!empty($profilearray['url'])) { $urlwithmod = $profilearray['url']; $urlwithmod = $urlwithmod.(preg_match('/\?/', $urlwithmod) ? '&amp;' : '?').'urlfrom='.urlencode($urlfrom); - if (!empty($profilearray['disablemodules'])) - { + if (!empty($profilearray['disablemodules'])) { $urlwithmod = $urlwithmod.(preg_match('/\?/', $urlwithmod) ? '&amp;' : '?').'disablemodules='.$profilearray['disablemodules']; } } - if (empty($profilearray['url'])) - { + if (empty($profilearray['url'])) { print '<div class="clearboth"></div>'; } @@ -350,8 +349,7 @@ foreach ($demoprofiles as $profilearray) // Modules (a profile you must choose modules) - if (empty($profilearray['url'])) - { + if (empty($profilearray['url'])) { print '<div id="tr1'.$profilearray['key'].'" class="moduleline hidden" style="margin-left: 8px; margin-right: 8px; text-align: justify; font-size:14px; line-height: 130%; padding-bottom: 8px">'; print $langs->trans("ThisIsListOfModules").'<br><br>'; @@ -362,20 +360,26 @@ foreach ($demoprofiles as $profilearray) $j = 0; $nbcolsmod = empty($conf->dol_optimize_smallscreen) ? 4 : 3; //var_dump($modules); - foreach ($orders as $index => $key) // Loop on qualified (enabled) modules - { + foreach ($orders as $index => $key) { // Loop on qualified (enabled) modules //print $index.' '.$key; $val = $modules[$index]; $modulekeyname = strtolower($val->name); $modulequalified = 1; - if (!empty($val->always_enabled) || in_array($modulekeyname, $alwayshiddenuncheckedmodules)) $modulequalified = 0; - if ($val->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && !$conf->global->$const_name) $modulequalified = 0; - if ($val->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && !$conf->global->$const_name) $modulequalified = 0; - if (!$modulequalified) continue; + if (!empty($val->always_enabled) || in_array($modulekeyname, $alwayshiddenuncheckedmodules)) { + $modulequalified = 0; + } + if ($val->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && !$conf->global->$const_name) { + $modulequalified = 0; + } + if ($val->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && !$conf->global->$const_name) { + $modulequalified = 0; + } + if (!$modulequalified) { + continue; + } - if (in_array($modulekeyname, $alwayshiddencheckedmodules)) - { + if (in_array($modulekeyname, $alwayshiddencheckedmodules)) { print "\n".'<!-- Module '.$modulekeyname.' hidden and always checked -->'; print '<input type="hidden" name="'.$modulekeyname.'" value="1">'; } else { @@ -384,8 +388,12 @@ foreach ($demoprofiles as $profilearray) print '<!-- id='.$val->numero.' -->'; print '<div class="nowrap">'; print '<input type="checkbox" class="checkbox" id="id'.$modulekeyname.'" name="'.$modulekeyname.'" value="1" title="'.dol_escape_htmltag($val->getName()).'"'; - if (in_array($modulekeyname, $alwaysuncheckedmodules)) print ' disabled'; - if (!in_array($modulekeyname, $alwaysuncheckedmodules) && (!in_array($modulekeyname, $listofdisabledmodules) || in_array($modulekeyname, $alwayscheckedmodules))) print ' checked'; + if (in_array($modulekeyname, $alwaysuncheckedmodules)) { + print ' disabled'; + } + if (!in_array($modulekeyname, $alwaysuncheckedmodules) && (!in_array($modulekeyname, $listofdisabledmodules) || in_array($modulekeyname, $alwayscheckedmodules))) { + print ' checked'; + } print '> <label for="id'.$modulekeyname.'" class="inline-block demomaxoveflow" title="'.dol_escape_htmltag($val->getName()).'">'.$val->getName().'</label><br>'; print '</div>'; //if ($modulo == ($nbcolsmod - 1)) print '</tr>'; @@ -414,10 +422,8 @@ print '</div>'; // TODO Replace this with a hook // Google Adsense (need Google module) -if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && !empty($conf->global->MAIN_GOOGLE_AD_SLOT)) -{ - if (empty($conf->dol_use_jmobile)) - { +if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && !empty($conf->global->MAIN_GOOGLE_AD_SLOT)) { + if (empty($conf->dol_use_jmobile)) { print '<div align="center">'."\n"; print '<script><!--'."\n"; print 'google_ad_client = "'.$conf->global->MAIN_GOOGLE_AD_CLIENT.'";'."\n"; diff --git a/htdocs/public/donations/donateurs_code.php b/htdocs/public/donations/donateurs_code.php index 70b55981816..87db3ee4133 100644 --- a/htdocs/public/donations/donateurs_code.php +++ b/htdocs/public/donations/donateurs_code.php @@ -22,10 +22,18 @@ * \brief Page to list donators */ -if (!defined('NOLOGIN')) define('NOLOGIN', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (!defined('NOLOGIN')) { + define('NOLOGIN', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} // C'est un wrapper, donc header vierge /** @@ -51,7 +59,9 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; // Security check -if (empty($conf->don->enabled)) accessforbidden('', 0, 0, 1); +if (empty($conf->don->enabled)) { + accessforbidden('', 0, 0, 1); +} $langs->load("donations"); @@ -68,11 +78,9 @@ $sql .= " FROM ".MAIN_DB_PREFIX."don as d"; $sql .= " WHERE d.fk_statut in (2, 3) ORDER BY d.datedon DESC"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { print "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"4\">"; print '<tr>'; @@ -81,13 +89,11 @@ if ($resql) print '<td class="right">'.$langs->trans("Amount").'</td>'; print "</tr>\n"; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); print '<tr class="oddeven">'; - if ($objp->public) - { + if ($objp->public) { print "<td>".dolGetFirstLastname($objp->firstname, $objp->lastname)." ".dol_escape_htmltag($objp->societe)."</td>\n"; } else { print "<td>".$langs->trans("Anonymous")."</td>\n"; diff --git a/htdocs/public/emailing/mailing-read.php b/htdocs/public/emailing/mailing-read.php index ccbf8f5c1d3..454201203cc 100644 --- a/htdocs/public/emailing/mailing-read.php +++ b/htdocs/public/emailing/mailing-read.php @@ -25,13 +25,30 @@ * \brief Script use to update mail status if destinaries read it (if images during mail read are display) */ -if (!defined('NOLOGIN')) define('NOLOGIN', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); -if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (!defined('NOLOGIN')) { + define('NOLOGIN', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} +if (!defined('NOREQUIRETRAN')) { + define('NOREQUIRETRAN', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined("NOSESSION")) { + define("NOSESSION", '1'); +} /** * Header empty @@ -53,6 +70,8 @@ function llxFooter() require '../../main.inc.php'; +$mtid = GETPOST('mtid'); +$email = GETPOST('email'); $tag = GETPOST('tag'); $securitykey = GETPOST('securitykey'); @@ -63,31 +82,61 @@ $securitykey = GETPOST('securitykey'); dol_syslog("public/emailing/mailing-read.php : tag=".$tag." securitykey=".$securitykey, LOG_DEBUG); -if ($securitykey != $conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY) -{ +if ($securitykey != $conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY) { print 'Bad security key value.'; exit; } -if (!empty($tag)) -{ - $statut = '2'; - $sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles SET statut=".$statut." WHERE tag='".$db->escape($tag)."'"; - dol_syslog("public/emailing/mailing-read.php : Mail read : ".$sql, LOG_DEBUG); +if (!empty($tag)) { + dol_syslog("public/emailing/mailing-read.php : Update status of email target and thirdparty for tag ".$tag, LOG_DEBUG); + + $sql = "SELECT mc.rowid, mc.email, mc.statut, mc.source_type, mc.source_id, m.entity"; + $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m"; + $sql .= " WHERE mc.fk_mailing = m.rowid AND mc.tag='".$db->escape($tag)."'"; $resql = $db->query($sql); + if (!$resql) dol_print_error($db); + + $obj = $db->fetch_object($resql); + + if (empty($obj)) { + print 'Email target not valid. Operation canceled.'; + exit; + } + if (empty($obj->email)) { + print 'Email target not valid. Operation canceled.'; + exit; + } + if ($obj->statut == 2 || $obj->statut == 3) { + print 'Email target already set to read or unsubscribe. Operation canceled.'; + exit; + } + // TODO Test that mtid and email match also with the one found from $tag + /* + if ($obj->email != $email) + { + print 'Email does not match tagnot found. No need to unsubscribe.'; + exit; + } + */ + + //Update status of target + $statut = '2'; + $sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles SET statut=".$statut." WHERE rowid = ".((int) $obj->rowid); + $resql = $db->query($sql); + if (!$resql) dol_print_error($db); //Update status communication of thirdparty prospect - $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=3 WHERE fk_stcomm != -1 AND rowid IN (SELECT source_id FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE tag='".$db->escape($tag)."' AND source_type='thirdparty' AND source_id is not null)"; - dol_syslog("public/emailing/mailing-read.php : Mail read thirdparty : ".$sql, LOG_DEBUG); - - $resql = $db->query($sql); + if ($obj->source_id > 0 && $obj->source_type == 'thirdparty' && $obj->entity) { + $sql = "UPDATE ".MAIN_DB_PREFIX.'societe SET fk_stcomm = 3 WHERE fk_stcomm <> -1 AND entity = '.$obj->entity.' AND rowid = '.$obj->source_id; + $resql = $db->query($sql); + } //Update status communication of contact prospect - $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=3 WHERE fk_stcomm != -1 AND rowid IN (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."socpeople AS sc INNER JOIN ".MAIN_DB_PREFIX."mailing_cibles AS mc ON mc.tag = '".$db->escape($tag)."' AND mc.source_type = 'contact' AND mc.source_id = sc.rowid)"; - dol_syslog("public/emailing/mailing-read.php : Mail read contact : ".$sql, LOG_DEBUG); - - $resql = $db->query($sql); + if ($obj->source_id > 0 && $obj->source_type == 'contact' && $obj->entity) { + $sql = "UPDATE ".MAIN_DB_PREFIX.'societe SET fk_stcomm = 3 WHERE fk_stcomm <> -1 AND entity = '.$obj->entity.' AND rowid IN (SELECT sc.fk_soc FROM '.MAIN_DB_PREFIX.'socpeople AS sc WHERE sc.rowid = '.$obj->source_id.')'; + $resql = $db->query($sql); + } } $db->close(); diff --git a/htdocs/public/emailing/mailing-unsubscribe.php b/htdocs/public/emailing/mailing-unsubscribe.php index 0d62545cf57..9c39dafa18d 100644 --- a/htdocs/public/emailing/mailing-unsubscribe.php +++ b/htdocs/public/emailing/mailing-unsubscribe.php @@ -27,11 +27,24 @@ * https://myserver/public/emailing/mailing-unsubscribe.php?unsuscrib=1&securitykey=securitykey&tag=abcdefghijklmn */ -if (!defined('NOLOGIN')) define('NOLOGIN', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (!defined('NOLOGIN')) { + define('NOLOGIN', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined("NOSESSION")) { + define("NOSESSION", '1'); +} /** * Header empty @@ -58,6 +71,8 @@ global $user, $conf, $langs; $langs->loadLangs(array("main", "mails")); +$mtid = GETPOST('mtid'); +$email = GETPOST('email'); $tag = GETPOST('tag'); $unsuscrib = GETPOST('unsuscrib'); $securitykey = GETPOST('securitykey'); @@ -69,38 +84,55 @@ $securitykey = GETPOST('securitykey'); dol_syslog("public/emailing/mailing-read.php : tag=".$tag." securitykey=".$securitykey, LOG_DEBUG); -if ($securitykey != $conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY) -{ +if ($securitykey != $conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY) { print 'Bad security key value.'; exit; } -if (!empty($tag) && ($unsuscrib == '1')) -{ +if (!empty($tag) && ($unsuscrib == '1')) { dol_syslog("public/emailing/mailing-unsubscribe.php : Launch unsubscribe requests", LOG_DEBUG); - $sql = "SELECT mc.email, m.entity"; + $sql = "SELECT mc.rowid, mc.email, mc.statut, m.entity"; $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m"; $sql .= " WHERE mc.fk_mailing = m.rowid AND mc.tag='".$db->escape($tag)."'"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $obj = $db->fetch_object($resql); - if (empty($obj->email)) - { - print 'Email not found. No need to unsubscribe.'; + if (empty($obj)) { + print 'Email target not valid. Operation canceled.'; exit; } + if (empty($obj->email)) { + print 'Email target not valid. Operation canceled.'; + exit; + } + if ($obj->statut == 3) { + print 'Email target already set to unsubscribe. Operation canceled.'; + exit; + } + // TODO Test that mtid and email match also with the one found from $tag + /* + if ($obj->email != $email) + { + print 'Email does not match tagnot found. No need to unsubscribe.'; + exit; + } + */ // Update status of mail in recipient mailing list table $statut = '3'; $sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles SET statut=".$statut." WHERE tag='".$db->escape($tag)."'"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } /* // Update status communication of thirdparty prospect (old usage) @@ -109,7 +141,7 @@ if (!empty($tag) && ($unsuscrib == '1')) $resql=$db->query($sql); if (! $resql) dol_print_error($db); - // Update status communication of contact prospect (old usage) + // Update status communication of contact prospect (old usage) $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET no_email=1 WHERE rowid IN (SELECT source_id FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE tag = '".$db->escape($tag)."' AND source_type='contact' AND source_id is not null)"; $resql=$db->query($sql); @@ -117,7 +149,7 @@ if (!empty($tag) && ($unsuscrib == '1')) */ // Update status communication of email (new usage) - $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe (date_creat, entity, email) VALUES ('".$db->idate(dol_now())."', ".$db->escape($obj->entity).", '".$db->escape($obj->email)."')"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe (date_creat, entity, email, unsubscribegroup, ip) VALUES ('".$db->idate(dol_now())."', ".$db->escape($obj->entity).", '".$db->escape($obj->email)."', '', '".$db->escape(getUserRemoteIP())."')"; $resql = $db->query($sql); //if (! $resql) dol_print_error($db); No test on errors, may fail if already unsubscribed diff --git a/htdocs/public/error-401.php b/htdocs/public/error-401.php index 87da7c347e3..bae712ec095 100644 --- a/htdocs/public/error-401.php +++ b/htdocs/public/error-401.php @@ -1,32 +1,32 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> - <title>Dolibarr 401 error page</title> + <title>Dolibarr 401 error page</title> </head> <body> - <div> + <div> - <!-- <div data-role="header" data-theme="b"> - <h1>Introduction</h1> - <a href="../../" data-icon="home" data-iconpos="notext" data-direction="reverse" class="ui-btn-right jqm-home">Home</a> - </div> - --> - <div> + <!-- <div data-role="header" data-theme="b"> + <h1>Introduction</h1> + <a href="../../" data-icon="home" data-iconpos="notext" data-direction="reverse" class="ui-btn-right jqm-home">Home</a> + </div> + --> + <div> - <h1>Error</h1> + <h1>Error</h1> - <br> - Sorry. You are not allowed to access this resource. + <br> + Sorry. You are not allowed to access this resource. - <br> - <?php print isset($_SERVER["HTTP_REFERER"]) ? 'You come from '.htmlentities($_SERVER["HTTP_REFERER"]).'.' : ''; ?> + <br> + <?php print isset($_SERVER["HTTP_REFERER"]) ? 'You come from '.htmlentities($_SERVER["HTTP_REFERER"]).'.' : ''; ?> - <hr> + <hr> - </div> - </div> + </div> + </div> </body> </html> diff --git a/htdocs/public/error-404.php b/htdocs/public/error-404.php index baaa26cd833..680b9e4a77c 100644 --- a/htdocs/public/error-404.php +++ b/htdocs/public/error-404.php @@ -1,32 +1,32 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> - <title>Dolibarr 404 error page</title> + <title>Dolibarr 404 error page</title> </head> <body> - <div> + <div> - <!-- <div data-role="header" data-theme="b"> - <h1>Introduction</h1> - <a href="../../" data-icon="home" data-iconpos="notext" data-direction="reverse" class="ui-btn-right jqm-home">Home</a> - </div> - --> - <div> + <!-- <div data-role="header" data-theme="b"> + <h1>Introduction</h1> + <a href="../../" data-icon="home" data-iconpos="notext" data-direction="reverse" class="ui-btn-right jqm-home">Home</a> + </div> + --> + <div> - <h2>Error</h2> + <h2>Error</h2> - <br> - You requested a website or a page that does not exists. + <br> + You requested a website or a page that does not exists. - <br> - <?php print isset($_SERVER["HTTP_REFERER"]) ? 'You come from '.htmlentities($_SERVER["HTTP_REFERER"]).'.' : ''; ?> + <br> + <?php print isset($_SERVER["HTTP_REFERER"]) ? 'You come from '.htmlentities($_SERVER["HTTP_REFERER"]).'.' : ''; ?> - <hr> + <hr> - </div> - </div> + </div> + </div> </body> </html> diff --git a/htdocs/public/members/new.php b/htdocs/public/members/new.php index 1946125dbc2..be1a574e3fe 100644 --- a/htdocs/public/members/new.php +++ b/htdocs/public/members/new.php @@ -37,17 +37,29 @@ * MEMBER_NEWFORM_FORCECOUNTRYCODE Force country */ -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php // TODO This should be useless. Because entity must be retrieve from object ref and not from url. $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -67,7 +79,9 @@ $action = GETPOST('action', 'aZ09'); $langs->loadLangs(array("main", "members", "companies", "install", "other")); // Security check -if (empty($conf->adherent->enabled)) accessforbidden('', 0, 0, 1); +if (empty($conf->adherent->enabled)) { + accessforbidden('', 0, 0, 1); +} if (empty($conf->global->MEMBER_ENABLE_PUBLIC)) { print $langs->trans("Auto subscription form for public visitors has not been enabled"); @@ -200,11 +214,11 @@ if (empty($reshook) && $action == 'add') { $error++; $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('Nature'))."<br>\n"; } - if (empty($_POST["lastname"])) { + if (!GETPOST("lastname")) { $error++; $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Lastname"))."<br>\n"; } - if (empty($_POST["firstname"])) { + if (GETPOST("firstname")) { $error++; $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Firstname"))."<br>\n"; } @@ -213,8 +227,8 @@ if (empty($reshook) && $action == 'add') { $langs->load("errors"); $errmsg .= $langs->trans("ErrorBadEMail", GETPOST("email"))."<br>\n"; } - $birthday = dol_mktime($_POST["birthhour"], $_POST["birthmin"], $_POST["birthsec"], $_POST["birthmonth"], $_POST["birthday"], $_POST["birthyear"]); - if ($_POST["birthmonth"] && empty($birthday)) { + $birthday = dol_mktime(GETPOST("birthhour", 'int'), GETPOST("birthmin", 'int'), GETPOST("birthsec", 'int'), GETPOST("birthmonth", 'int'), GETPOST("birthday", 'int'), GETPOST("birthyear", 'int')); + if (GETPOSTISSET("birthmonth") && empty($birthday)) { $error++; $langs->load("errors"); $errmsg .= $langs->trans("ErrorBadDateFormat")."<br>\n"; @@ -226,40 +240,45 @@ if (empty($reshook) && $action == 'add') { } } - if (isset($public)) $public = 1; - else $public = 0; + if (GETPOSTISSET('public')) { + $public = 1; + } else { + $public = 0; + } if (!$error) { // email a peu pres correct et le login n'existe pas $adh = new Adherent($db); $adh->statut = -1; $adh->public = $public; - $adh->firstname = $_POST["firstname"]; - $adh->lastname = $_POST["lastname"]; - $adh->gender = $_POST["gender"]; - $adh->civility_id = $_POST["civility_id"]; - $adh->societe = $_POST["societe"]; - $adh->address = $_POST["address"]; - $adh->zip = $_POST["zipcode"]; - $adh->town = $_POST["town"]; - $adh->email = $_POST["email"]; + $adh->firstname = GETPOST("firstname"); + $adh->lastname = GETPOST("lastname"); + $adh->gender = GETPOST("gender"); + $adh->civility_id = GETPOST("civility_id"); + $adh->societe = GETPOST("societe"); + $adh->address = GETPOST("address"); + $adh->zip = GETPOST("zipcode"); + $adh->town = GETPOST("town"); + $adh->email = GETPOST("email"); if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { - $adh->login = $_POST["login"]; - $adh->pass = $_POST["pass1"]; + $adh->login = GETPOST("login"); + $adh->pass = GETPOST("pass1"); } - $adh->photo = $_POST["photo"]; - $adh->country_id = $_POST["country_id"]; - $adh->state_id = $_POST["state_id"]; - $adh->typeid = $_POST["type"]; - $adh->note_private = $_POST["note_private"]; - $adh->morphy = $_POST["morphy"]; + $adh->photo = GETPOST("photo"); + $adh->country_id = GETPOST("country_id", 'int'); + $adh->state_id = GETPOST("state_id", 'int'); + $adh->typeid = GETPOST("type", 'int'); + $adh->note_private = GETPOST("note_private"); + $adh->morphy = GETPOST("morphy"); $adh->birth = $birthday; // Fill array 'array_options' with data from add form $extrafields->fetch_name_optionals_label($adh->table_element); $ret = $extrafields->setOptionalsFromPost(null, $adh); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } $result = $adh->create($user); if ($result > 0) { @@ -285,7 +304,9 @@ if (empty($reshook) && $action == 'add') { $arraydefaultmessage = null; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_AUTOREGISTER; - 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; @@ -303,9 +324,9 @@ if (empty($reshook) && $action == 'add') { $result = $object->send_an_email($texttosend, $subjecttosend, array(), array(), array(), "", "", 0, -1, '', $moreinheader); } /*if ($result < 0) { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - }*/ + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + }*/ } // Send email to the foundation to say a new member subscribed with autosubscribe form @@ -316,8 +337,12 @@ if (empty($reshook) && $action == 'add') { if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { $appli = $conf->global->MAIN_APPLICATION_TITLE; if (preg_match('/\d\.\d/', $appli)) { - if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core - } else $appli .= " ".DOL_VERSION; + if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) { + $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core + } + } else { + $appli .= " ".DOL_VERSION; + } } else { $appli .= " ".DOL_VERSION; } @@ -355,8 +380,12 @@ if (empty($reshook) && $action == 'add') { if (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE) && $conf->global->MEMBER_NEWFORM_PAYONLINE != '-1') { if ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'all') { $urlback = DOL_MAIN_URL_ROOT.'/public/payment/newpayment.php?from=membernewform&source=membersubscription&ref='.urlencode($adh->ref); - if (price2num(GETPOST('amount', 'alpha'))) $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha')); - if (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email')); + if (price2num(GETPOST('amount', 'alpha'))) { + $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha')); + } + if (GETPOST('email')) { + $urlback .= '&email='.urlencode(GETPOST('email')); + } if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2)); @@ -366,8 +395,12 @@ if (empty($reshook) && $action == 'add') { } } elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paybox') { $urlback = DOL_MAIN_URL_ROOT.'/public/paybox/newpayment.php?from=membernewform&source=membersubscription&ref='.urlencode($adh->ref); - if (price2num(GETPOST('amount', 'alpha'))) $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha')); - if (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email')); + if (price2num(GETPOST('amount', 'alpha'))) { + $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha')); + } + if (GETPOST('email')) { + $urlback .= '&email='.urlencode(GETPOST('email')); + } if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2)); @@ -377,8 +410,12 @@ if (empty($reshook) && $action == 'add') { } } elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paypal') { $urlback = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?from=membernewform&source=membersubscription&ref='.urlencode($adh->ref); - if (price2num(GETPOST('amount', 'alpha'))) $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha')); - if (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email')); + if (price2num(GETPOST('amount', 'alpha'))) { + $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha')); + } + if (GETPOST('email')) { + $urlback .= '&email='.urlencode(GETPOST('email')); + } if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2)); @@ -388,8 +425,12 @@ if (empty($reshook) && $action == 'add') { } } elseif ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'stripe') { $urlback = DOL_MAIN_URL_ROOT.'/public/stripe/newpayment.php?from=membernewform&source=membersubscription&ref='.$adh->ref; - if (price2num(GETPOST('amount', 'alpha'))) $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha')); - if (GETPOST('email')) $urlback .= '&email='.urlencode(GETPOST('email')); + if (price2num(GETPOST('amount', 'alpha'))) { + $urlback .= '&amount='.price2num(GETPOST('amount', 'alpha')); + } + if (GETPOST('email')) { + $urlback .= '&email='.urlencode(GETPOST('email')); + } if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $urlback .= '&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$adh->ref, 2)); @@ -403,7 +444,9 @@ if (empty($reshook) && $action == 'add') { } } - if (!empty($entity)) $urlback .= '&entity='.$entity; + if (!empty($entity)) { + $urlback .= '&entity='.$entity; + } dol_syslog("member ".$adh->ref." was created, we redirect to ".$urlback); } else { $error++; @@ -572,7 +615,9 @@ if (!$country_id && !empty($conf->geoipmaxmind->enabled)) { if ($country_code) { $new_country_id = getCountry($country_code, 3, $db, $langs); //print 'xxx'.$country_code.' - '.$new_country_id; - if ($new_country_id) $country_id = $new_country_id; + if ($new_country_id) { + $country_id = $new_country_id; + } } } $country_code = getCountry($country_id, 2, $db, $langs); @@ -581,8 +626,11 @@ print '</td></tr>'; // State if (empty($conf->global->SOCIETE_DISABLE_STATE)) { print '<tr><td>'.$langs->trans('State').'</td><td>'; - if ($country_code) print $formcompany->select_state(GETPOST("state_id"), $country_code); - else print ''; + if ($country_code) { + print $formcompany->select_state(GETPOST("state_id"), $country_code); + } else { + print ''; + } print '</td></tr>'; } // EMail @@ -602,7 +650,7 @@ print '<tr><td>'.$langs->trans("URLPhoto").'</td><td><input type="text" name="ph // Public print '<tr><td>'.$langs->trans("Public").'</td><td><input type="checkbox" name="public"></td></tr>'."\n"; // Other attributes -$tpl_context = 'public'; //BUG #11554 : define templae context to public +$tpl_context = 'public'; // define templae context to public include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; // Comments print '<tr>'; diff --git a/htdocs/public/members/public_card.php b/htdocs/public/members/public_card.php index 18f918c26e2..4950db468f1 100644 --- a/htdocs/public/members/public_card.php +++ b/htdocs/public/members/public_card.php @@ -25,16 +25,26 @@ * \brief File to show a public card of a member */ -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php // TODO This should be useless. Because entity must be retrieve from object ref and not from url. $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; @@ -42,7 +52,9 @@ require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Security check -if (empty($conf->adherent->enabled)) accessforbidden('', 0, 0, 1); +if (empty($conf->adherent->enabled)) { + accessforbidden('', 0, 0, 1); +} $langs->loadLangs(array("main", "members", "companies", "other")); @@ -66,24 +78,27 @@ $extrafields = new ExtraFields($db); */ $morehead = ''; -if (!empty($conf->global->MEMBER_PUBLIC_CSS)) $morehead = '<link rel="stylesheet" type="text/css" href="'.$conf->global->MEMBER_PUBLIC_CSS.'">'; -else $morehead = '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/eldy/style.css.php">'; +if (!empty($conf->global->MEMBER_PUBLIC_CSS)) { + $morehead = '<link rel="stylesheet" type="text/css" href="'.$conf->global->MEMBER_PUBLIC_CSS.'">'; +} else { + $morehead = '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/eldy/style.css.php">'; +} llxHeaderVierge($langs->trans("MemberCard"), $morehead); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -if ($id > 0) -{ +if ($id > 0) { $res = $object->fetch($id); - if ($res < 0) { dol_print_error($db, $object->error); exit; } + if ($res < 0) { + dol_print_error($db, $object->error); exit; + } $res = $object->fetch_optionals(); print load_fiche_titre($langs->trans("MemberCard"), '', ''); - if (empty($object->public)) - { + if (empty($object->public)) { print $langs->trans("ErrorThisMemberIsNotPublic"); } else { print '<table class="public_border" cellspacing="0" width="100%" cellpadding="3">'; @@ -100,8 +115,7 @@ if ($id > 0) print '<tr><td>'.$langs->trans("EMail").'</td><td class="valeur">'.$object->email.'&nbsp;</td></tr>'; print '<tr><td>'.$langs->trans("Birthday").'</td><td class="valeur">'.dol_print_date($object->birth, 'day').'</td></tr>'; - if (isset($object->photo) && $object->photo != '') - { + if (isset($object->photo) && $object->photo != '') { $form = new Form($db); print '<tr><td>URL Photo</td><td class="valeur">'; print $form->showphoto('memberphoto', $object, 64); @@ -139,7 +153,9 @@ function llxHeaderVierge($title, $head = "") print "<html>\n"; print "<head>\n"; print "<title>".$title."</title>\n"; - if ($head) print $head."\n"; + if ($head) { + print $head."\n"; + } print "</head>\n"; print '<body class="public_body">'."\n"; } diff --git a/htdocs/public/members/public_list.php b/htdocs/public/members/public_list.php index d81529d1eaf..e6c6e040a97 100644 --- a/htdocs/public/members/public_list.php +++ b/htdocs/public/members/public_list.php @@ -24,21 +24,33 @@ * \brief File sample to list members */ -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php // TODO This should be useless. Because entity must be retrieve from object ref and not from url. $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} require '../../main.inc.php'; // Security check -if (empty($conf->adherent->enabled)) accessforbidden('', 0, 0, 1); +if (empty($conf->adherent->enabled)) { + accessforbidden('', 0, 0, 1); +} $langs->loadLangs(array("main", "members", "companies", "other")); @@ -59,7 +71,9 @@ function llxHeaderVierge($title, $head = "") print "<html>\n"; print "<head>\n"; print "<title>".$title."</title>\n"; - if ($head) print $head."\n"; + if ($head) { + print $head."\n"; + } print "</head>\n"; print '<body class="public_body">'."\n"; } @@ -82,7 +96,9 @@ $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $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; @@ -90,8 +106,12 @@ $pagenext = $page + 1; $filter = GETPOST('filter'); $statut = GETPOST('statut'); -if (!$sortorder) { $sortorder = "ASC"; } -if (!$sortfield) { $sortfield = "lastname"; } +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "lastname"; +} /* @@ -101,8 +121,11 @@ if (!$sortfield) { $sortfield = "lastname"; } $form = new Form($db); $morehead = ''; -if (!empty($conf->global->MEMBER_PUBLIC_CSS)) $morehead = '<link rel="stylesheet" type="text/css" href="'.$conf->global->MEMBER_PUBLIC_CSS.'">'; -else $morehead = '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/eldy/style.css.php">'; +if (!empty($conf->global->MEMBER_PUBLIC_CSS)) { + $morehead = '<link rel="stylesheet" type="text/css" href="'.$conf->global->MEMBER_PUBLIC_CSS.'">'; +} else { + $morehead = '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/eldy/style.css.php">'; +} llxHeaderVierge($langs->trans("ListOfValidatedPublicMembers"), $morehead); @@ -119,8 +142,7 @@ $sql .= $db->plimit($conf->liste_limit + 1, $offset); //$sql .= " ORDER BY $sortfield $sortorder " . $db->plimit($conf->liste_limit, $offset); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; @@ -138,8 +160,7 @@ if ($result) print_liste_field_titre("Photo", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'public_'); print "</tr>\n"; - while ($i < $num && $i < $conf->liste_limit) - { + while ($i < $num && $i < $conf->liste_limit) { $objp = $db->fetch_object($result); print '<tr class="oddeven">'; @@ -148,8 +169,7 @@ if ($result) print '<td>'.$objp->email.'</td>'."\n"; print '<td>'.$objp->zip.'</td>'."\n"; print '<td>'.$objp->town.'</td>'."\n"; - if (isset($objp->photo) && $objp->photo != '') - { + if (isset($objp->photo) && $objp->photo != '') { print '<td>'; print $form->showphoto('memberphoto', $objp, 64); print '</td>'."\n"; diff --git a/htdocs/public/notice.php b/htdocs/public/notice.php index 59b8e3a70cb..f85c628e1eb 100644 --- a/htdocs/public/notice.php +++ b/htdocs/public/notice.php @@ -24,11 +24,21 @@ * /public/notice.php?transphrase=url_encoded_sentence_to_show */ -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOSESSION')) define('NOSESSION', '1'); -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} require '../main.inc.php'; @@ -37,13 +47,15 @@ require '../main.inc.php'; * View */ -if (!GETPOST('transkey', 'alphanohtml') && !GETPOST('transphrase', 'alphanohtml')) -{ +if (!GETPOST('transkey', 'alphanohtml') && !GETPOST('transphrase', 'alphanohtml')) { print 'Sorry, it seems your internet connexion is off.<br>'; print 'You need to be connected to network to use this software.<br>'; } else { $langs->loadLangs(array("error", "other")); - if (GETPOST('transphrase', 'alphanohtml')) print dol_escape_htmltag(GETPOST('transphrase', 'alphanohtml')); - elseif (GETPOST('transkey', 'alphanohtml')) print dol_escape_htmltag($langs->trans(GETPOST('transkey', 'alphanohtml'))); + if (GETPOST('transphrase', 'alphanohtml')) { + print dol_escape_htmltag(GETPOST('transphrase', 'alphanohtml')); + } elseif (GETPOST('transkey', 'alphanohtml')) { + print dol_escape_htmltag($langs->trans(GETPOST('transkey', 'alphanohtml'))); + } } diff --git a/htdocs/public/onlinesign/newonlinesign.php b/htdocs/public/onlinesign/newonlinesign.php index 56690f78a42..a4a2de27beb 100644 --- a/htdocs/public/onlinesign/newonlinesign.php +++ b/htdocs/public/onlinesign/newonlinesign.php @@ -23,16 +23,26 @@ * \brief File to offer a way to make an online signature for a particular Dolibarr entity */ -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php // TODO This should be useless. Because entity must be retrieve from object ref and not from url. $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -60,12 +70,12 @@ $suffix = GETPOST("suffix", 'aZ09'); $source = GETPOST("source", 'alpha'); $ref = $REF = GETPOST("ref", 'alpha'); -if (empty($source)) $source = 'proposal'; +if (empty($source)) { + $source = 'proposal'; +} -if (!$action) -{ - if ($source && !$ref) - { +if (!$action) { + if ($source && !$ref) { print $langs->trans('ErrorBadParameters')." - ref missing"; exit; } @@ -81,23 +91,19 @@ $urlwithroot = DOL_MAIN_URL_ROOT; // This is to use same domain name than curren // Complete urls for post treatment $SECUREKEY = GETPOST("securekey"); // Secure key -if (!empty($source)) -{ +if (!empty($source)) { $urlok .= 'source='.urlencode($source).'&'; $urlko .= 'source='.urlencode($source).'&'; } -if (!empty($REF)) -{ +if (!empty($REF)) { $urlok .= 'ref='.urlencode($REF).'&'; $urlko .= 'ref='.urlencode($REF).'&'; } -if (!empty($SECUREKEY)) -{ +if (!empty($SECUREKEY)) { $urlok .= 'securekey='.urlencode($SECUREKEY).'&'; $urlko .= 'securekey='.urlencode($SECUREKEY).'&'; } -if (!empty($entity)) -{ +if (!empty($entity)) { $urlok .= 'entity='.urlencode($entity).'&'; $urlko .= 'entity='.urlencode($entity).'&'; } @@ -112,8 +118,7 @@ $creditor = $mysoc->name; */ -if ($action == 'dosign') -{ +if ($action == 'dosign') { // TODO } @@ -123,7 +128,9 @@ if ($action == 'dosign') */ $head = ''; -if (!empty($conf->global->MAIN_SIGN_CSS_URL)) $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->MAIN_SIGN_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n"; +if (!empty($conf->global->MAIN_SIGN_CSS_URL)) { + $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->MAIN_SIGN_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n"; +} $conf->dol_hide_topmenu = 1; $conf->dol_hide_leftmenu = 1; @@ -132,8 +139,7 @@ $replacemainarea = (empty($conf->dol_hide_leftmenu) ? '<div>' : '').'<div>'; llxHeader($head, $langs->trans("OnlineSignature"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea, 1); // Check link validity for param 'source' -if (!empty($source) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) -{ +if (!empty($source) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) { $langs->load("errors"); dol_print_error_email('BADREFINONLINESIGNFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref)); // End of page @@ -161,24 +167,24 @@ print '<table id="dolpaymenttable" summary="Payment form" class="center">'."\n"; $logosmall = $mysoc->logo_small; $logo = $mysoc->logo; $paramlogo = 'ONLINE_SIGN_LOGO_'.$suffix; -if (!empty($conf->global->$paramlogo)) $logosmall = $conf->global->$paramlogo; -elseif (!empty($conf->global->ONLINE_SIGN_LOGO)) $logosmall = $conf->global->ONLINE_SIGN_LOGO; +if (!empty($conf->global->$paramlogo)) { + $logosmall = $conf->global->$paramlogo; +} elseif (!empty($conf->global->ONLINE_SIGN_LOGO)) { + $logosmall = $conf->global->ONLINE_SIGN_LOGO; +} //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n"; // Define urllogo $urllogo = ''; $urllogofull = ''; -if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) -{ +if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); -} elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) -{ +} elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); } // Output html code for logo -if ($urllogo) -{ +if ($urllogo) { print '<div class="backgreypublicpayment">'; print '<div class="logopublicpayment">'; print '<img id="dolpaymentlogo" src="'.$urllogo.'"'; @@ -192,16 +198,17 @@ if ($urllogo) // Output introduction text $text = ''; -if (!empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT)) -{ +if (!empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT)) { $langs->load("members"); $reg = array(); - if (preg_match('/^\((.*)\)$/', $conf->global->ONLINE_SIGN_NEWFORM_TEXT, $reg)) $text .= $langs->trans($reg[1])."<br>\n"; - else $text .= $conf->global->ONLINE_SIGN_NEWFORM_TEXT."<br>\n"; + if (preg_match('/^\((.*)\)$/', $conf->global->ONLINE_SIGN_NEWFORM_TEXT, $reg)) { + $text .= $langs->trans($reg[1])."<br>\n"; + } else { + $text .= $conf->global->ONLINE_SIGN_NEWFORM_TEXT."<br>\n"; + } $text = '<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n"; } -if (empty($text)) -{ +if (empty($text)) { $text .= '<tr><td class="textpublicpayment"><br><strong>'.$langs->trans("WelcomeOnOnlineSignaturePage", $mysoc->name).'</strong></td></tr>'."\n"; $text .= '<tr><td class="textpublicpayment">'.$langs->trans("ThisScreenAllowsYouToSignDocFrom", $creditor).'<br><br></td></tr>'."\n"; } @@ -217,8 +224,7 @@ $error = 0; $var = false; // Payment on customer order -if ($source == 'proposal') -{ +if ($source == 'proposal') { $found = true; $langs->load("proposal"); @@ -226,8 +232,7 @@ if ($source == 'proposal') $proposal = new Propal($db); $result = $proposal->fetch('', $ref); - if ($result <= 0) - { + if ($result <= 0) { $mesg = $proposal->error; $error++; } else { @@ -258,9 +263,13 @@ if ($source == 'proposal') -if (!$found && !$mesg) $mesg = $langs->transnoentitiesnoconv("ErrorBadParameters"); +if (!$found && !$mesg) { + $mesg = $langs->transnoentitiesnoconv("ErrorBadParameters"); +} -if ($mesg) print '<tr><td align="center" colspan="2"><br><div class="warning">'.dol_escape_htmltag($mesg).'</div></td></tr>'."\n"; +if ($mesg) { + print '<tr><td align="center" colspan="2"><br><div class="warning">'.dol_escape_htmltag($mesg).'</div></td></tr>'."\n"; +} print '</table>'."\n"; print "\n"; diff --git a/htdocs/public/opensurvey/studs.php b/htdocs/public/opensurvey/studs.php index 3f19fb68b7e..90dab0379ff 100644 --- a/htdocs/public/opensurvey/studs.php +++ b/htdocs/public/opensurvey/studs.php @@ -22,10 +22,18 @@ * \brief Page to list surveys */ -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; @@ -37,8 +45,7 @@ require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; // Init vars $action = GETPOST('action', 'aZ09'); $numsondage = ''; -if (GETPOST('sondage')) -{ +if (GETPOST('sondage')) { $numsondage = GETPOST('sondage', 'alpha'); } @@ -51,7 +58,9 @@ $nblines = $object->fetch_lines(); $canbemodified = ((empty($object->date_fin) || $object->date_fin > dol_now()) && $object->status != Opensurveysondage::STATUS_CLOSED); // Security check -if (empty($conf->opensurvey->enabled)) accessforbidden('', 0, 0, 1); +if (empty($conf->opensurvey->enabled)) { + accessforbidden('', 0, 0, 1); +} /* @@ -63,51 +72,49 @@ $nbcolonnes = substr_count($object->sujet, ',') + 1; $listofvoters = explode(',', $_SESSION["savevoter"]); // Add comment -if (GETPOST('ajoutcomment', 'alpha')) -{ - if (!$canbemodified) accessforbidden('', 0, 0, 1); +if (GETPOST('ajoutcomment', 'alpha')) { + if (!$canbemodified) { + accessforbidden('', 0, 0, 1); + } $error = 0; $comment = GETPOST("comment", 'restricthtml'); $comment_user = GETPOST('commentuser', 'nohtml'); - if (!$comment) - { + if (!$comment) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors'); } - if (!$comment_user) - { + if (!$comment_user) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Name")), null, 'errors'); } - if (!in_array($comment_user, $listofvoters)) - { + if (!in_array($comment_user, $listofvoters)) { setEventMessages($langs->trans("UserMustBeSameThanUserUsedToVote"), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $resql = $object->addComment($comment, $comment_user); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } } } // Add vote -if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // boutonp for chrome, boutonp_x for firefox -{ - if (!$canbemodified) accessforbidden('', 0, 0, 1); +if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) { // boutonp for chrome, boutonp_x for firefox + if (!$canbemodified) { + accessforbidden('', 0, 0, 1); + } //Si le nom est bien entré - if (GETPOST('nom', 'nohtml')) - { + if (GETPOST('nom', 'nohtml')) { $nouveauchoix = ''; - for ($i = 0; $i < $nbcolonnes; $i++) - { + for ($i = 0; $i < $nbcolonnes; $i++) { if (GETPOSTISSET("choix$i") && GETPOST("choix$i") == '1') { $nouveauchoix .= "1"; } elseif (GETPOSTISSET("choix$i") && GETPOST("choix$i") == '2') { @@ -124,11 +131,12 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout $sql .= ' FROM '.MAIN_DB_PREFIX.'opensurvey_user_studs'; $sql .= " WHERE id_sondage='".$db->escape($numsondage)."' AND nom = '".$db->escape($nom)."' ORDER BY id_users"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $num_rows = $db->num_rows($resql); - if ($num_rows > 0) - { + if ($num_rows > 0) { setEventMessages($langs->trans("VoteNameAlreadyExists"), null, 'errors'); $error++; } else { @@ -136,14 +144,12 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout $sql .= " VALUES ('".$db->escape($nom)."', '".$db->escape($numsondage)."','".$db->escape($nouveauchoix)."')"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { // Add voter to session $_SESSION["savevoter"] = $nom.','.(empty($_SESSION["savevoter"]) ? '' : $_SESSION["savevoter"]); // Save voter $listofvoters = explode(',', $_SESSION["savevoter"]); - if ($object->mailsonde) - { + if ($object->mailsonde) { if ($object->fk_user_creat) { $userstatic = new User($db); $userstatic->fetch($object->fk_user_creat); @@ -166,7 +172,9 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout $result = $cmailfile->sendfile(); } } - } else dol_print_error($db); + } else { + dol_print_error($db); + } } } else { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Name")), null, 'errors'); @@ -178,28 +186,23 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout $testmodifier = false; $testligneamodifier = false; $ligneamodifier = -1; -for ($i = 0; $i < $nblines; $i++) -{ - if (GETPOSTISSET('modifierligne'.$i)) - { +for ($i = 0; $i < $nblines; $i++) { + if (GETPOSTISSET('modifierligne'.$i)) { $ligneamodifier = $i; $testligneamodifier = true; } //test to see if a line is to be modified - if (GETPOSTISSET('validermodifier'.$i)) - { + if (GETPOSTISSET('validermodifier'.$i)) { $modifier = $i; $testmodifier = true; } } -if ($testmodifier) -{ +if ($testmodifier) { //var_dump($_POST);exit; $nouveauchoix = ''; - for ($i = 0; $i < $nbcolonnes; $i++) - { + for ($i = 0; $i < $nbcolonnes; $i++) { //var_dump($_POST["choix$i"]); if (GETPOSTISSET("choix".$i) && GETPOST("choix".$i) == '1') { $nouveauchoix .= "1"; @@ -210,7 +213,9 @@ if ($testmodifier) } } - if (!$canbemodified) accessforbidden('', 0, 0, 1); + if (!$canbemodified) { + accessforbidden('', 0, 0, 1); + } $idtomodify = $_POST["idtomodify".$modifier]; $sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_user_studs"; @@ -218,14 +223,17 @@ if ($testmodifier) $sql .= " WHERE id_users = '".$db->escape($idtomodify)."'"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } } // Delete comment $idcomment = GETPOST('deletecomment', 'int'); -if ($idcomment) -{ - if (!$canbemodified) accessforbidden('', 0, 0, 1); +if ($idcomment) { + if (!$canbemodified) { + accessforbidden('', 0, 0, 1); + } $resql = $object->deleteComment($idcomment); } @@ -243,8 +251,7 @@ $arrayofcss = array('/opensurvey/css/style.css'); llxHeaderSurvey($object->title, "", 0, 0, $arrayofjs, $arrayofcss, $numsondage); -if (empty($object->ref)) // For survey, id is a hex string -{ +if (empty($object->ref)) { // For survey, id is a hex string $langs->load("errors"); print $langs->trans("ErrorRecordNotFound"); @@ -257,8 +264,7 @@ if (empty($object->ref)) // For survey, id is a hex string // Define format of choices $toutsujet = explode(",", $object->sujet); $listofanswers = array(); -foreach ($toutsujet as $value) -{ +foreach ($toutsujet as $value) { $tmp = explode('@', $value); $listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox')); } @@ -276,8 +282,7 @@ $titre = str_replace("\\", "", $object->title); print '<strong>'.dol_htmlentities($titre).'</strong><br><br>'."\n"; // show description of survey -if ($object->description) -{ +if ($object->description) { print dol_htmlentitiesbr($object->description); print '<br>'."\n"; } @@ -300,8 +305,7 @@ print '<br><br>'."\n"; print '<table class="resultats">'."\n"; // Show choice titles -if ($object->format == "D") -{ +if ($object->format == "D") { //display of survey topics print '<tr>'."\n"; print '<td></td>'."\n"; @@ -309,8 +313,7 @@ if ($object->format == "D") //display of years $colspan = 1; $nbofsujet = count($toutsujet); - for ($i = 0; $i < $nbofsujet; $i++) - { + for ($i = 0; $i < $nbofsujet; $i++) { if (isset($toutsujet[$i + 1]) && date('Y', intval($toutsujet[$i])) == date('Y', intval($toutsujet[$i + 1]))) { $colspan++; } else { @@ -386,8 +389,7 @@ if ($object->format == "D") print '<tr>'."\n"; print '<td></td>'."\n"; - for ($i = 0; isset($toutsujet[$i]); $i++) - { + for ($i = 0; isset($toutsujet[$i]); $i++) { $tmp = explode('@', $toutsujet[$i]); print '<td class="sujet">'.dol_escape_htmltag($tmp[0]).'</td>'."\n"; } @@ -404,14 +406,12 @@ $sql = "SELECT id_users, nom as name, id_sondage, reponses"; $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $resql = $db->query($sql); -if (!$resql) -{ +if (!$resql) { dol_print_error($db); exit; } $num = $db->num_rows($resql); -while ($compteur < $num) -{ +while ($compteur < $num) { $obj = $db->fetch_object($resql); $ensemblereponses = $obj->reponses; @@ -430,121 +430,167 @@ while ($compteur < $num) print '<td class="nom">'.dol_htmlentities($obj->name).'</td>'."\n"; // si la ligne n'est pas a changer, on affiche les données - if (!$testligneamodifier) - { - for ($i = 0; $i < $nbcolonnes; $i++) - { + if (!$testligneamodifier) { + for ($i = 0; $i < $nbcolonnes; $i++) { $car = substr($ensemblereponses, $i, 1); //print 'xx'.$i."-".$car.'-'.$listofanswers[$i]['format'].'zz'; - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) - { - if (((string) $car) == "1") print '<td class="ok">OK</td>'."\n"; - else print '<td class="non">KO</td>'."\n"; + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { + if (((string) $car) == "1") { + print '<td class="ok">OK</td>'."\n"; + } else { + print '<td class="non">KO</td>'."\n"; + } // Total - if (!isset($sumfor[$i])) $sumfor[$i] = 0; - if (((string) $car) == "1") $sumfor[$i]++; + if (!isset($sumfor[$i])) { + $sumfor[$i] = 0; + } + if (((string) $car) == "1") { + $sumfor[$i]++; + } } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') - { - if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("Yes").'</td>'."\n"; - elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("No").'</td>'."\n"; - else print '<td class="vide">&nbsp;</td>'."\n"; + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { + if (((string) $car) == "1") { + print '<td class="ok">'.$langs->trans("Yes").'</td>'."\n"; + } elseif (((string) $car) == "0") { + print '<td class="non">'.$langs->trans("No").'</td>'."\n"; + } else { + print '<td class="vide">&nbsp;</td>'."\n"; + } // Total - if (!isset($sumfor[$i])) $sumfor[$i] = 0; - if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; - if (((string) $car) == "1") $sumfor[$i]++; - if (((string) $car) == "0") $sumagainst[$i]++; + if (!isset($sumfor[$i])) { + $sumfor[$i] = 0; + } + if (!isset($sumagainst[$i])) { + $sumagainst[$i] = 0; + } + if (((string) $car) == "1") { + $sumfor[$i]++; + } + if (((string) $car) == "0") { + $sumagainst[$i]++; + } } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') - { - if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; - elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; - else print '<td class="vide">&nbsp;</td>'."\n"; + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { + if (((string) $car) == "1") { + print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; + } elseif (((string) $car) == "0") { + print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; + } else { + print '<td class="vide">&nbsp;</td>'."\n"; + } // Total - if (!isset($sumfor[$i])) $sumfor[$i] = 0; - if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; - if (((string) $car) == "1") $sumfor[$i]++; - if (((string) $car) == "0") $sumagainst[$i]++; + if (!isset($sumfor[$i])) { + $sumfor[$i] = 0; + } + if (!isset($sumagainst[$i])) { + $sumagainst[$i] = 0; + } + if (((string) $car) == "1") { + $sumfor[$i]++; + } + if (((string) $car) == "0") { + $sumagainst[$i]++; + } } } } else { //sinon on remplace les choix de l'utilisateur par une ligne de checkbox pour recuperer de nouvelles valeurs - if ($compteur == $ligneamodifier) - { - for ($i = 0; $i < $nbcolonnes; $i++) - { + if ($compteur == $ligneamodifier) { + for ($i = 0; $i < $nbcolonnes; $i++) { $car = substr($ensemblereponses, $i, 1); print '<td class="vide">'; - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) - { + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { print '<input type="checkbox" name="choix'.$i.'" value="1" '; - if ($car == '1') print 'checked'; + if ($car == '1') { + print 'checked'; + } print '>'; } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') - { + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes")); print $form->selectarray("choix".$i, $arraychoice, $car); } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') - { + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For")); print $form->selectarray("choix".$i, $arraychoice, $car); } print '</td>'."\n"; } } else { - for ($i = 0; $i < $nbcolonnes; $i++) - { + for ($i = 0; $i < $nbcolonnes; $i++) { $car = substr($ensemblereponses, $i, 1); - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) - { - if (((string) $car) == "1") print '<td class="ok">OK</td>'."\n"; - else print '<td class="non">KO</td>'."\n"; + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { + if (((string) $car) == "1") { + print '<td class="ok">OK</td>'."\n"; + } else { + print '<td class="non">KO</td>'."\n"; + } // Total - if (!isset($sumfor[$i])) $sumfor[$i] = 0; - if (((string) $car) == "1") $sumfor[$i]++; + if (!isset($sumfor[$i])) { + $sumfor[$i] = 0; + } + if (((string) $car) == "1") { + $sumfor[$i]++; + } } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') - { - if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; - elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; - else print '<td class="vide">&nbsp;</td>'."\n"; + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { + if (((string) $car) == "1") { + print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; + } elseif (((string) $car) == "0") { + print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; + } else { + print '<td class="vide">&nbsp;</td>'."\n"; + } // Total - if (!isset($sumfor[$i])) $sumfor[$i] = 0; - if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; - if (((string) $car) == "1") $sumfor[$i]++; - if (((string) $car) == "0") $sumagainst[$i]++; + if (!isset($sumfor[$i])) { + $sumfor[$i] = 0; + } + if (!isset($sumagainst[$i])) { + $sumagainst[$i] = 0; + } + if (((string) $car) == "1") { + $sumfor[$i]++; + } + if (((string) $car) == "0") { + $sumagainst[$i]++; + } } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') - { - if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; - elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; - else print '<td class="vide">&nbsp;</td>'."\n"; + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { + if (((string) $car) == "1") { + print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; + } elseif (((string) $car) == "0") { + print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; + } else { + print '<td class="vide">&nbsp;</td>'."\n"; + } // Total - if (!isset($sumfor[$i])) $sumfor[$i] = 0; - if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; - if (((string) $car) == "1") $sumfor[$i]++; - if (((string) $car) == "0") $sumagainst[$i]++; + if (!isset($sumfor[$i])) { + $sumfor[$i] = 0; + } + if (!isset($sumagainst[$i])) { + $sumagainst[$i] = 0; + } + if (((string) $car) == "1") { + $sumfor[$i]++; + } + if (((string) $car) == "0") { + $sumagainst[$i]++; + } } } } } // Button edit at end of line - if ($compteur != $ligneamodifier && $mod_ok) - { + if ($compteur != $ligneamodifier && $mod_ok) { print '<td class="casevide"><input type="submit" class="button smallpaddingimp" name="modifierligne'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Edit")).'"></td>'."\n"; } //demande de confirmation pour modification de ligne - for ($i = 0; $i < $nblines; $i++) - { - if (GETPOSTISSET("modifierligne".$i)) - { - if ($compteur == $i) - { + for ($i = 0; $i < $nblines; $i++) { + if (GETPOSTISSET("modifierligne".$i)) { + if ($compteur == $i) { print '<td class="casevide">'; print '<input type="hidden" name="idtomodify'.$compteur.'" value="'.$obj->id_users.'">'; print '<input type="submit" class="button button-save" name="validermodifier'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Save")).'">'; @@ -558,12 +604,10 @@ while ($compteur < $num) } // Add line to add new record -if ($ligneamodifier < 0 && (!isset($_SESSION['nom']))) -{ +if ($ligneamodifier < 0 && (!isset($_SESSION['nom']))) { print '<tr>'."\n"; print '<td class="nom">'."\n"; - if (isset($_SESSION['nom'])) - { + if (isset($_SESSION['nom'])) { print '<input type=hidden name="nom" value="'.$_SESSION['nom'].'">'.$_SESSION['nom']."\n"; } else { print '<input type="text" name="nom" placeholder="'.dol_escape_htmltag($langs->trans("Name")).'" maxlength="64" size="24">'."\n"; @@ -571,24 +615,20 @@ if ($ligneamodifier < 0 && (!isset($_SESSION['nom']))) print '</td>'."\n"; // affichage des cases de formulaire checkbox pour un nouveau choix - for ($i = 0; $i < $nbcolonnes; $i++) - { + for ($i = 0; $i < $nbcolonnes; $i++) { print '<td class="vide">'; - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) - { + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { print '<input type="checkbox" name="choix'.$i.'" value="1"'; if (GETPOSTISSET('choix'.$i) && GETPOST('choix'.$i) == '1') { print ' checked'; } print '>'; } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') - { + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes")); print $form->selectarray("choix".$i, $arraychoice, GETPOST('choix'.$i)); } - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') - { + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For")); print $form->selectarray("choix".$i, $arraychoice, GETPOST('choix'.$i)); } @@ -602,18 +642,15 @@ if ($ligneamodifier < 0 && (!isset($_SESSION['nom']))) // Select value of best choice (for checkbox columns only) $nbofcheckbox = 0; -for ($i = 0; $i < $nbcolonnes; $i++) -{ - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) - $nbofcheckbox++; - if (isset($sumfor[$i])) - { - if ($i == 0) - { +for ($i = 0; $i < $nbcolonnes; $i++) { + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { + $nbofcheckbox++; + } + if (isset($sumfor[$i])) { + if ($i == 0) { $meilleurecolonne = $sumfor[$i]; } - if (!isset($meilleurecolonne) || $sumfor[$i] > $meilleurecolonne) - { + if (!isset($meilleurecolonne) || $sumfor[$i] > $meilleurecolonne) { $meilleurecolonne = $sumfor[$i]; } } @@ -623,30 +660,36 @@ if ($object->allow_spy) { // Show line total print '<tr>'."\n"; print '<td class="center">'.$langs->trans("Total").'</td>'."\n"; - for ($i = 0; $i < $nbcolonnes; $i++) - { + for ($i = 0; $i < $nbcolonnes; $i++) { $showsumfor = isset($sumfor[$i]) ? $sumfor[$i] : ''; $showsumagainst = isset($sumagainst[$i]) ? $sumagainst[$i] : ''; - if (empty($showsumfor)) $showsumfor = 0; - if (empty($showsumagainst)) $showsumagainst = 0; + if (empty($showsumfor)) { + $showsumfor = 0; + } + if (empty($showsumagainst)) { + $showsumagainst = 0; + } print '<td>'; - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) print $showsumfor; - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') print $langs->trans("Yes").': '.$showsumfor.'<br>'.$langs->trans("No").': '.$showsumagainst; - if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') print $langs->trans("For").': '.$showsumfor.'<br>'.$langs->trans("Against").': '.$showsumagainst; + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { + print $showsumfor; + } + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { + print $langs->trans("Yes").': '.$showsumfor.'<br>'.$langs->trans("No").': '.$showsumagainst; + } + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { + print $langs->trans("For").': '.$showsumfor.'<br>'.$langs->trans("Against").': '.$showsumagainst; + } print '</td>'."\n"; } print '</tr>'; // Show picto winner - if ($nbofcheckbox >= 2) - { + if ($nbofcheckbox >= 2) { print '<tr>'."\n"; print '<td class="somme"></td>'."\n"; - for ($i = 0; $i < $nbcolonnes; $i++) - { + for ($i = 0; $i < $nbcolonnes; $i++) { //print 'xx'.(! empty($listofanswers[$i]['format'])).'-'.$sumfor[$i].'-'.$meilleurecolonne; - if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst')) && isset($sumfor[$i]) && isset($meilleurecolonne) && $sumfor[$i] == $meilleurecolonne) - { + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst')) && isset($sumfor[$i]) && isset($meilleurecolonne) && $sumfor[$i] == $meilleurecolonne) { print '<td class="somme"><img src="'.dol_buildpath('/opensurvey/img/medaille.png', 1).'"></td>'."\n"; } else { print '<td class="somme"></td>'."\n"; @@ -691,8 +734,7 @@ if ($object->allow_spy) { // Show best choice - if ($nbofcheckbox >= 2) - { + if ($nbofcheckbox >= 2) { $vote_str = $langs->trans('votes'); print '<p class="affichageresultats">'."\n"; @@ -712,8 +754,7 @@ print '<br>'; // Comment list $comments = $object->getComments(); -if ($comments) -{ +if ($comments) { print '<br><u><span class="bold opacitymedium">'.$langs->trans("CommentsOfVoters").':</span></u><br>'."\n"; foreach ($comments as $obj) { @@ -721,7 +762,9 @@ if ($comments) //$mod_ok = (in_array($obj->name, $listofvoters)); print '<div class="comment"><span class="usercomment">'; - if (in_array($obj->usercomment, $listofvoters)) print '<a href="'.$_SERVER["PHP_SELF"].'?deletecomment='.$obj->id_comment.'&sondage='.$numsondage.'"> '.img_picto('', 'delete.png', '', false, 0, 0, '', 'nomarginleft').'</a> '; + if (in_array($obj->usercomment, $listofvoters)) { + print '<a href="'.$_SERVER["PHP_SELF"].'?deletecomment='.$obj->id_comment.'&sondage='.$numsondage.'"> '.img_picto('', 'delete.png', '', false, 0, 0, '', 'nomarginleft').'</a> '; + } //else print img_picto('', 'ellipsis-h', '', false, 0, 0, '', 'nomarginleft').' '; print dol_htmlentities($obj->usercomment).':</span> <span class="comment">'.dol_nl2br(dol_htmlentities($obj->comment))."</span></div>"; } diff --git a/htdocs/public/payment/newpayment.php b/htdocs/public/payment/newpayment.php index 8672fa1c2bf..dc5d99a43eb 100644 --- a/htdocs/public/payment/newpayment.php +++ b/htdocs/public/payment/newpayment.php @@ -34,15 +34,25 @@ * \brief File to offer a way to make a payment for a particular Dolibarr object */ -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} // For MultiCompany module. // Do not use GETPOST here, function is not defined and get of entity must be done before including main.inc.php $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : (!empty($_GET['e']) ? (int) $_GET['e'] : (!empty($_POST['e']) ? (int) $_POST['e'] : 1)))); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -72,25 +82,24 @@ $action = GETPOST('action', 'aZ09'); $suffix = GETPOST("suffix", 'aZ09'); $amount = price2num(GETPOST("amount", 'alpha')); -if (!GETPOST("currency", 'alpha')) $currency = $conf->currency; -else $currency = GETPOST("currency", 'aZ09'); +if (!GETPOST("currency", 'alpha')) { + $currency = $conf->currency; +} else { + $currency = GETPOST("currency", 'aZ09'); +} $source = GETPOST("s", 'aZ09') ?GETPOST("s", 'aZ09') : GETPOST("source", 'aZ09'); $download = GETPOST('d', 'int') ?GETPOST('d', 'int') : GETPOST('download', 'int'); -if (!$action) -{ - if (!GETPOST("amount", 'alpha') && !$source) - { +if (!$action) { + if (!GETPOST("amount", 'alpha') && !$source) { print $langs->trans('ErrorBadParameters')." - amount or source"; exit; } - if (is_numeric($amount) && !GETPOST("tag", 'alpha') && !$source) - { + if (is_numeric($amount) && !GETPOST("tag", 'alpha') && !$source) { print $langs->trans('ErrorBadParameters')." - tag or source"; exit; } - if ($source && !GETPOST("ref", 'alpha')) - { + if ($source && !GETPOST("ref", 'alpha')) { print $langs->trans('ErrorBadParameters')." - ref"; exit; } @@ -101,10 +110,8 @@ $paymentmethod = GETPOST('paymentmethod', 'alphanohtml') ?GETPOST('paymentmethod $validpaymentmethod = array(); // Detect $paymentmethod -foreach ($_POST as $key => $val) -{ - if (preg_match('/^dopayment_(.*)$/', $key, $reg)) - { +foreach ($_POST as $key => $val) { + if (preg_match('/^dopayment_(.*)$/', $key, $reg)) { $paymentmethod = $reg[1]; break; } @@ -124,40 +131,35 @@ $ref = $REF = GETPOST('ref', 'alpha'); $TAG = GETPOST("tag", 'alpha'); $FULLTAG = GETPOST("fulltag", 'alpha'); // fulltag is tag with more informations $SECUREKEY = GETPOST("securekey"); // Secure key -if ($paymentmethod && !preg_match('/'.preg_quote('PM='.$paymentmethod, '/').'/', $FULLTAG)) $FULLTAG .= ($FULLTAG ? '.' : '').'PM='.$paymentmethod; +if ($paymentmethod && !preg_match('/'.preg_quote('PM='.$paymentmethod, '/').'/', $FULLTAG)) { + $FULLTAG .= ($FULLTAG ? '.' : '').'PM='.$paymentmethod; +} -if (!empty($suffix)) -{ +if (!empty($suffix)) { $urlok .= 'suffix='.urlencode($suffix).'&'; $urlko .= 'suffix='.urlencode($suffix).'&'; } -if ($source) -{ +if ($source) { $urlok .= 's='.urlencode($source).'&'; $urlko .= 's='.urlencode($source).'&'; } -if (!empty($REF)) -{ +if (!empty($REF)) { $urlok .= 'ref='.urlencode($REF).'&'; $urlko .= 'ref='.urlencode($REF).'&'; } -if (!empty($TAG)) -{ +if (!empty($TAG)) { $urlok .= 'tag='.urlencode($TAG).'&'; $urlko .= 'tag='.urlencode($TAG).'&'; } -if (!empty($FULLTAG)) -{ +if (!empty($FULLTAG)) { $urlok .= 'fulltag='.urlencode($FULLTAG).'&'; $urlko .= 'fulltag='.urlencode($FULLTAG).'&'; } -if (!empty($SECUREKEY)) -{ +if (!empty($SECUREKEY)) { $urlok .= 'securekey='.urlencode($SECUREKEY).'&'; $urlko .= 'securekey='.urlencode($SECUREKEY).'&'; } -if (!empty($entity)) -{ +if (!empty($entity)) { $urlok .= 'e='.urlencode($entity).'&'; $urlko .= 'e='.urlencode($entity).'&'; } @@ -168,38 +170,36 @@ $urlko = preg_replace('/&$/', '', $urlko); // Remove last & // Make special controls -if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled)) -{ +if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled)) { require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php'; require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php'; // Check parameters $PAYPAL_API_OK = ""; - if ($urlok) $PAYPAL_API_OK = $urlok; + if ($urlok) { + $PAYPAL_API_OK = $urlok; + } $PAYPAL_API_KO = ""; - if ($urlko) $PAYPAL_API_KO = $urlko; - if (empty($PAYPAL_API_USER)) - { + if ($urlko) { + $PAYPAL_API_KO = $urlko; + } + if (empty($PAYPAL_API_USER)) { dol_print_error('', "Paypal setup param PAYPAL_API_USER not defined"); return -1; } - if (empty($PAYPAL_API_PASSWORD)) - { + if (empty($PAYPAL_API_PASSWORD)) { dol_print_error('', "Paypal setup param PAYPAL_API_PASSWORD not defined"); return -1; } - if (empty($PAYPAL_API_SIGNATURE)) - { + if (empty($PAYPAL_API_SIGNATURE)) { dol_print_error('', "Paypal setup param PAYPAL_API_SIGNATURE not defined"); return -1; } } -if ((empty($paymentmethod) || $paymentmethod == 'paybox') && !empty($conf->paybox->enabled)) -{ +if ((empty($paymentmethod) || $paymentmethod == 'paybox') && !empty($conf->paybox->enabled)) { // No specific test for the moment } -if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled)) -{ +if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled)) { require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; // This include also /stripe/lib/stripe.lib.php, /includes/stripe/stripe-php/init.php, ... } @@ -215,36 +215,36 @@ $reshook = $hookmanager->executeHooks('doValidatePayment', $parameters, $object, // Check security token $valid = true; -if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) -{ - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { - if ($source && $REF) $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$source.$REF, 2); // Use the source in the hash to avoid duplicates if the references are identical - else $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); +if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + if ($source && $REF) { + $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$source.$REF, 2); // Use the source in the hash to avoid duplicates if the references are identical + } else { + $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + } } else { $token = $conf->global->PAYMENT_SECURITY_TOKEN; } - if ($SECUREKEY != $token) - { - if (empty($conf->global->PAYMENT_SECURITY_ACCEPT_ANY_TOKEN)) $valid = false; // PAYMENT_SECURITY_ACCEPT_ANY_TOKEN is for backward compatibility - else dol_syslog("Warning: PAYMENT_SECURITY_ACCEPT_ANY_TOKEN is on", LOG_WARNING); + if ($SECUREKEY != $token) { + if (empty($conf->global->PAYMENT_SECURITY_ACCEPT_ANY_TOKEN)) { + $valid = false; // PAYMENT_SECURITY_ACCEPT_ANY_TOKEN is for backward compatibility + } else { + dol_syslog("Warning: PAYMENT_SECURITY_ACCEPT_ANY_TOKEN is on", LOG_WARNING); + } } - if (!$valid) - { + if (!$valid) { print '<div class="error">Bad value for key.</div>'; //print 'SECUREKEY='.$SECUREKEY.' token='.$token.' valid='.$valid; exit; } } -if (!empty($paymentmethod) && empty($validpaymentmethod[$paymentmethod])) -{ +if (!empty($paymentmethod) && empty($validpaymentmethod[$paymentmethod])) { print 'Payment module for payment method '.$paymentmethod.' is not active'; exit; } -if (empty($validpaymentmethod)) -{ +if (empty($validpaymentmethod)) { print 'No active payment module (Paypal, Stripe, Paybox, ...)'; exit; } @@ -253,8 +253,11 @@ if (empty($validpaymentmethod)) $creditor = $mysoc->name; $paramcreditor = 'ONLINE_PAYMENT_CREDITOR'; $paramcreditorlong = 'ONLINE_PAYMENT_CREDITOR_'.$suffix; -if (!empty($conf->global->$paramcreditorlong)) $creditor = $conf->global->$paramcreditorlong; -elseif (!empty($conf->global->$paramcreditor)) $creditor = $conf->global->$paramcreditor; +if (!empty($conf->global->$paramcreditorlong)) { + $creditor = $conf->global->$paramcreditorlong; +} elseif (!empty($conf->global->$paramcreditor)) { + $creditor = $conf->global->$paramcreditor; +} @@ -263,10 +266,8 @@ elseif (!empty($conf->global->$paramcreditor)) $creditor = $conf->global->$param */ // Action dopayment is called after clicking/choosing the payment mode -if ($action == 'dopayment') -{ - if ($paymentmethod == 'paypal') - { +if ($action == 'dopayment') { + if ($paymentmethod == 'paypal') { $PAYPAL_API_PRICE = price2num(GETPOST("newamount", 'alpha'), 'MT'); $PAYPAL_PAYMENT_TYPE = 'Sale'; @@ -285,33 +286,30 @@ if ($action == 'dopayment') $thirdparty_id = GETPOST('thirdparty_id', 'int'); // Special case for Paypal-Indonesia - if ($shipToCountryCode == 'ID' && !preg_match('/\-/', $shipToState)) - { + if ($shipToCountryCode == 'ID' && !preg_match('/\-/', $shipToState)) { $shipToState = 'ID-'.$shipToState; } $mesg = ''; - if (empty($PAYPAL_API_PRICE) || !is_numeric($PAYPAL_API_PRICE)) - { + if (empty($PAYPAL_API_PRICE) || !is_numeric($PAYPAL_API_PRICE)) { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")); $action = ''; - } - //elseif (empty($EMAIL)) $mesg=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("YourEMail")); - //elseif (! isValidEMail($EMAIL)) $mesg=$langs->trans("ErrorBadEMail",$EMAIL); - elseif (!$origfulltag) - { + // } elseif (empty($EMAIL)) { $mesg=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("YourEMail")); + // } elseif (! isValidEMail($EMAIL)) { $mesg=$langs->trans("ErrorBadEMail",$EMAIL); + } elseif (!$origfulltag) { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PaymentCode")); $action = ''; } //var_dump($_POST); - if (empty($mesg)) - { + if (empty($mesg)) { dol_syslog("newpayment.php call paypal api and do redirect", LOG_DEBUG); // Other $PAYPAL_API_DEVISE = "USD"; - if (!empty($currency)) $PAYPAL_API_DEVISE = $currency; + if (!empty($currency)) { + $PAYPAL_API_DEVISE = $currency; + } // Show var initialized by include fo paypal lib at begin of this file dol_syslog("Submit Paypal form", LOG_DEBUG); @@ -345,8 +343,7 @@ if ($action == 'dopayment') } } - if ($paymentmethod == 'paybox') - { + if ($paymentmethod == 'paybox') { $PRICE = price2num(GETPOST("newamount"), 'MT'); $email = $conf->global->ONLINE_PAYMENT_SENDEMAIL; $thirdparty_id = GETPOST('thirdparty_id', 'int'); @@ -358,15 +355,21 @@ if ($action == 'dopayment') $urlko = preg_replace('/securekey=[^&]+/', '', $urlko); $mesg = ''; - if (empty($PRICE) || !is_numeric($PRICE)) $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")); - elseif (empty($email)) $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("YourEMail")); - elseif (!isValidEMail($email)) $mesg = $langs->trans("ErrorBadEMail", $email); - elseif (!$origfulltag) $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PaymentCode")); - elseif (dol_strlen($urlok) > 150) $mesg = 'Error urlok too long '.$urlok.'( Paybox requires 150, found '.strlen($urlok).')'; - elseif (dol_strlen($urlko) > 150) $mesg = 'Error urlko too long '.$urlko.'( Paybox requires 150, found '.strlen($urlok).')'; + if (empty($PRICE) || !is_numeric($PRICE)) { + $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")); + } elseif (empty($email)) { + $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("YourEMail")); + } elseif (!isValidEMail($email)) { + $mesg = $langs->trans("ErrorBadEMail", $email); + } elseif (!$origfulltag) { + $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PaymentCode")); + } elseif (dol_strlen($urlok) > 150) { + $mesg = 'Error urlok too long '.$urlok.'( Paybox requires 150, found '.strlen($urlok).')'; + } elseif (dol_strlen($urlko) > 150) { + $mesg = 'Error urlko too long '.$urlko.'( Paybox requires 150, found '.strlen($urlok).')'; + } - if (empty($mesg)) - { + if (empty($mesg)) { dol_syslog("newpayment.php call paybox api and do redirect", LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/paybox/lib/paybox.lib.php'; @@ -377,10 +380,10 @@ if ($action == 'dopayment') } } - if ($paymentmethod == 'stripe') - { - if (GETPOST('newamount', 'alpha')) $amount = price2num(GETPOST('newamount', 'alpha'), 'MT'); - else { + if ($paymentmethod == 'stripe') { + if (GETPOST('newamount', 'alpha')) { + $amount = price2num(GETPOST('newamount', 'alpha'), 'MT'); + } else { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors'); $action = ''; } @@ -391,14 +394,15 @@ if ($action == 'dopayment') // Called when choosing Stripe mode. // When using the Charge API architecture, this code is called after clicking the 'dopayment' with the Charge API architecture. // When using the PaymentIntent API architecture, the Stripe customer is already created when creating PaymentIntent when showing payment page and the payment is already ok. -if ($action == 'charge' && !empty($conf->stripe->enabled)) -{ +if ($action == 'charge' && !empty($conf->stripe->enabled)) { $amountstripe = $amount; // Correct the amount according to unit of currency // See https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); - if (!in_array($currency, $arrayzerounitcurrency)) $amountstripe = $amountstripe * 100; + if (!in_array($currency, $arrayzerounitcurrency)) { + $amountstripe = $amountstripe * 100; + } dol_syslog("--- newpayment.php Execute action = ".$action, LOG_DEBUG, 0, '_stripe'); dol_syslog("POST keys : ".join(',', array_keys($_POST)), LOG_DEBUG, 0, '_stripe'); @@ -408,8 +412,8 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) $email = GETPOST("email", 'alpha'); $thirdparty_id = GETPOST('thirdparty_id', 'int'); // Note that for payment following online registration for members, this is empty because thirdparty is created once payment is confirmed by paymentok.php $dol_type = (GETPOST('s', 'alpha') ? GETPOST('s', 'alpha') : GETPOST('source', 'alpha')); - $dol_id = GETPOST('dol_id', 'int'); - $vatnumber = GETPOST('vatnumber', 'alpha'); + $dol_id = GETPOST('dol_id', 'int'); + $vatnumber = GETPOST('vatnumber', 'alpha'); $savesource = GETPOSTISSET('savesource') ?GETPOST('savesource', 'int') : 1; dol_syslog("POST stripeToken = ".$stripeToken, LOG_DEBUG, 0, '_stripe'); @@ -421,8 +425,7 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) $errormessage = ''; // When using the old Charge API architecture - if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { + if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { try { $metadata = array( 'dol_version' => DOL_VERSION, @@ -432,16 +435,16 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) 'ipaddress'=> getUserRemoteIP() ); - if (!empty($thirdparty_id)) $metadata["dol_thirdparty_id"] = $thirdparty_id; + if (!empty($thirdparty_id)) { + $metadata["dol_thirdparty_id"] = $thirdparty_id; + } - if ($thirdparty_id > 0) - { + if ($thirdparty_id > 0) { dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_stripe'); $service = 'StripeTest'; $servicestatus = 0; - if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int')) - { + if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int')) { $service = 'StripeLive'; $servicestatus = 1; } @@ -454,8 +457,7 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) $stripe = new Stripe($db); $stripeacc = $stripe->getStripeAccount($service); $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1); - if (empty($customer)) - { + if (empty($customer)) { $error++; dol_syslog('Failed to get/create stripe customer for thirdparty id = '.$thirdparty_id.' and servicestatus = '.$servicestatus.': '.$stripe->error, LOG_ERR, 0, '_stripe'); setEventMessages('Failed to get/create stripe customer for thirdparty id = '.$thirdparty_id.' and servicestatus = '.$servicestatus.': '.$stripe->error, null, 'errors'); @@ -463,24 +465,28 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) } // Create Stripe card from Token - if (!$error) - { + if (!$error) { if ($savesource) { $card = $customer->sources->create(array("source" => $stripeToken, "metadata" => $metadata)); } else { $card = $stripeToken; } - if (empty($card)) - { + if (empty($card)) { $error++; dol_syslog('Failed to create card record', LOG_WARNING, 0, '_stripe'); setEventMessages('Failed to create card record', null, 'errors'); $action = ''; } else { - if (!empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG; - if (!empty($dol_id)) $metadata["dol_id"] = $dol_id; - if (!empty($dol_type)) $metadata["dol_type"] = $dol_type; + if (!empty($FULLTAG)) { + $metadata["FULLTAG"] = $FULLTAG; + } + if (!empty($dol_id)) { + $metadata["dol_id"] = $dol_id; + } + if (!empty($dol_type)) { + $metadata["dol_type"] = $dol_type; + } dol_syslog("Create charge on card ".$card->id, LOG_DEBUG, 0, '_stripe'); $charge = \Stripe\Charge::create(array( @@ -494,8 +500,7 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) 'statement_descriptor_suffix' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) ), array("idempotency_key" => "$FULLTAG", "stripe_account" => "$stripeacc")); // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) - if (empty($charge)) - { + if (empty($charge)) { $error++; dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe'); setEventMessages('Failed to charge card', null, 'errors'); @@ -507,13 +512,13 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) $vatcleaned = $vatnumber ? $vatnumber : null; /*$taxinfo = array('type'=>'vat'); - if ($vatcleaned) - { - $taxinfo["tax_id"] = $vatcleaned; - } - // We force data to "null" if not defined as expected by Stripe - if (empty($vatcleaned)) $taxinfo=null; - */ + if ($vatcleaned) + { + $taxinfo["tax_id"] = $vatcleaned; + } + // We force data to "null" if not defined as expected by Stripe + if (empty($vatcleaned)) $taxinfo=null; + */ dol_syslog("Create anonymous customer card profile", LOG_DEBUG, 0, '_stripe'); @@ -527,22 +532,28 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) // Create the VAT record in Stripe /* We don't know country of customer, so we can't create tax - if (! empty($conf->global->STRIPE_SAVE_TAX_IDS)) // We setup to save Tax info on Stripe side. Warning: This may result in error when saving customer - { - if (! empty($vatcleaned)) - { - $isineec=isInEEC($object); - if ($object->country_code && $isineec) - { - //$taxids = $customer->allTaxIds($customer->id); - $customer->createTaxId($customer->id, array('type'=>'eu_vat', 'value'=>$vatcleaned)); - } - } - }*/ + if (! empty($conf->global->STRIPE_SAVE_TAX_IDS)) // We setup to save Tax info on Stripe side. Warning: This may result in error when saving customer + { + if (! empty($vatcleaned)) + { + $isineec=isInEEC($object); + if ($object->country_code && $isineec) + { + //$taxids = $customer->allTaxIds($customer->id); + $customer->createTaxId($customer->id, array('type'=>'eu_vat', 'value'=>$vatcleaned)); + } + } + }*/ - if (!empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG; - if (!empty($dol_id)) $metadata["dol_id"] = $dol_id; - if (!empty($dol_type)) $metadata["dol_type"] = $dol_type; + if (!empty($FULLTAG)) { + $metadata["FULLTAG"] = $FULLTAG; + } + if (!empty($dol_id)) { + $metadata["dol_id"] = $dol_id; + } + if (!empty($dol_type)) { + $metadata["dol_type"] = $dol_type; + } // The customer was just created with a source, so we can make a charge // with no card defined, the source just used for customer creation will be used. @@ -557,8 +568,7 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) 'statement_descriptor' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) ), array("idempotency_key" => "$FULLTAG", "stripe_account" => "$stripeacc")); // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) - if (empty($charge)) - { + if (empty($charge)) { $error++; dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe'); setEventMessages('Failed to charge card', null, 'errors'); @@ -630,12 +640,10 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) } // When using the PaymentIntent API architecture - if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { $service = 'StripeTest'; $servicestatus = 0; - if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int')) - { + if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int')) { $service = 'StripeLive'; $servicestatus = 1; } @@ -657,8 +665,7 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) } else { $paymentintent = \Stripe\PaymentIntent::retrieve($paymentintent_id, array("stripe_account" => $stripeacc)); } - } catch (Exception $e) - { + } catch (Exception $e) { $error++; $errormessage = "CantRetrievePaymentIntent ".$e->getMessage(); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); @@ -666,8 +673,7 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) $action = ''; } - if ($paymentintent->status != 'succeeded') - { + if ($paymentintent->status != 'succeeded') { $error++; $errormessage = "StatusOfRetrievedIntent is not succeeded: ".$paymentintent->status; dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); @@ -698,8 +704,7 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) dol_syslog("error=".$error." errormessage=".$errormessage, LOG_DEBUG, 0, '_stripe'); dol_syslog("Now call the redirect to paymentok or paymentko, URL = ".($error ? $urlko : $urlok), LOG_DEBUG, 0, '_stripe'); - if ($error) - { + if ($error) { header("Location: ".$urlko); exit; } else { @@ -714,7 +719,9 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) */ $head = ''; -if (!empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->ONLINE_PAYMENT_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n"; +if (!empty($conf->global->ONLINE_PAYMENT_CSS_URL)) { + $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->ONLINE_PAYMENT_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n"; +} $conf->dol_hide_topmenu = 1; $conf->dol_hide_leftmenu = 1; @@ -723,8 +730,7 @@ $replacemainarea = (empty($conf->dol_hide_leftmenu) ? '<div>' : '').'<div>'; llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea); // Check link validity -if ($source && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) -{ +if ($source && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) { $langs->load("errors"); dol_print_error_email('BADREFINPAYMENTFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref)); // End of page @@ -735,12 +741,10 @@ if ($source && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_r // Show sandbox warning -if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled) && (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'int'))) // We can force sand box with param 'forcesandbox' -{ +if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled) && (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'int'))) { // We can force sand box with param 'forcesandbox' dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Paypal'), '', 'warning'); } -if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'int'))) -{ +if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'int'))) { dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning'); } @@ -763,25 +767,25 @@ print "\n"; $logosmall = $mysoc->logo_small; $logo = $mysoc->logo; $paramlogo = 'ONLINE_PAYMENT_LOGO_'.$suffix; -if (!empty($conf->global->$paramlogo)) $logosmall = $conf->global->$paramlogo; -elseif (!empty($conf->global->ONLINE_PAYMENT_LOGO)) $logosmall = $conf->global->ONLINE_PAYMENT_LOGO; +if (!empty($conf->global->$paramlogo)) { + $logosmall = $conf->global->$paramlogo; +} elseif (!empty($conf->global->ONLINE_PAYMENT_LOGO)) { + $logosmall = $conf->global->ONLINE_PAYMENT_LOGO; +} //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n"; // Define urllogo $urllogo = ''; $urllogofull = ''; -if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) -{ +if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); -} elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) -{ +} elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); } // Output html code for logo -if ($urllogo) -{ +if ($urllogo) { print '<div class="backgreypublicpayment">'; print '<div class="logopublicpayment">'; print '<img id="dolpaymentlogo" src="'.$urllogo.'"'; @@ -799,17 +803,14 @@ if ($urllogo) print '<!-- Form to send a payment -->'."\n"; print '<!-- creditor = '.$creditor.' -->'."\n"; // Additionnal information for each payment system -if (!empty($conf->paypal->enabled)) -{ +if (!empty($conf->paypal->enabled)) { print '<!-- PAYPAL_API_SANDBOX = '.$conf->global->PAYPAL_API_SANDBOX.' -->'."\n"; print '<!-- PAYPAL_API_INTEGRAL_OR_PAYPALONLY = '.$conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY.' -->'."\n"; } -if (!empty($conf->paybox->enabled)) -{ +if (!empty($conf->paybox->enabled)) { print '<!-- PAYBOX_CGI_URL = '.$conf->global->PAYBOX_CGI_URL_V2.' -->'."\n"; } -if (!empty($conf->stripe->enabled)) -{ +if (!empty($conf->stripe->enabled)) { print '<!-- STRIPE_LIVE = '.$conf->global->STRIPE_LIVE.' -->'."\n"; } print '<!-- urlok = '.$urlok.' -->'."\n"; @@ -820,15 +821,16 @@ print '<table id="dolpaymenttable" summary="Payment form" class="center">'."\n"; // Output introduction text $text = ''; -if (!empty($conf->global->PAYMENT_NEWFORM_TEXT)) -{ +if (!empty($conf->global->PAYMENT_NEWFORM_TEXT)) { $langs->load("members"); - if (preg_match('/^\((.*)\)$/', $conf->global->PAYMENT_NEWFORM_TEXT, $reg)) $text .= $langs->trans($reg[1])."<br>\n"; - else $text .= $conf->global->PAYMENT_NEWFORM_TEXT."<br>\n"; + if (preg_match('/^\((.*)\)$/', $conf->global->PAYMENT_NEWFORM_TEXT, $reg)) { + $text .= $langs->trans($reg[1])."<br>\n"; + } else { + $text .= $conf->global->PAYMENT_NEWFORM_TEXT."<br>\n"; + } $text = '<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n"; } -if (empty($text)) -{ +if (empty($text)) { $text .= '<tr><td class="textpublicpayment"><br><strong>'.$langs->trans("WelcomeOnPaymentPage").'</strong></td></tr>'."\n"; $text .= '<tr><td class="textpublicpayment">'.$langs->trans("ThisScreenAllowsYouToPay", $creditor).'<br><br></td></tr>'."\n"; } @@ -847,8 +849,7 @@ $object = null; // Free payment -if (!$source) -{ +if (!$source) { $found = true; $tag = GETPOST("tag", 'alpha'); if (GETPOST('fulltag', 'alpha')) { @@ -865,11 +866,12 @@ if (!$source) // Amount print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Amount"); - if (empty($amount)) print ' ('.$langs->trans("ToComplete").')'; + if (empty($amount)) { + print ' ('.$langs->trans("ToComplete").')'; + } print '</td><td class="CTableRow'.($var ? '1' : '2').'">'; - if (empty($amount) || !is_numeric($amount)) - { - print '<input type="hidden" name="amount" value="'.GETPOST("amount", 'int').'">'; + if (empty($amount) || !is_numeric($amount)) { + print '<input type="hidden" name="amount" value="'.price2num(GETPOST("amount", 'alpha'), 'MT').'">'; print '<input class="flat maxwidth75" type="text" name="newamount" value="'.price2num(GETPOST("newamount", "alpha"), 'MT').'">'; } else { print '<b>'.price($amount).'</b>'; @@ -894,8 +896,7 @@ if (!$source) // Payment on customer order -if ($source == 'order') -{ +if ($source == 'order') { $found = true; $langs->load("orders"); @@ -903,8 +904,7 @@ if ($source == 'order') $order = new Commande($db); $result = $order->fetch('', $ref); - if ($result <= 0) - { + if ($result <= 0) { $mesg = $order->error; $error++; } else { @@ -912,10 +912,11 @@ if ($source == 'order') } $object = $order; - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { + if ($action != 'dopayment') { // Do not change amount if we just click on first dopayment $amount = $order->total_ttc; - if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int'); + if (GETPOST("amount", 'alpha')) { + $amount = GETPOST("amount", 'alpha'); + } $amount = price2num($amount); } @@ -923,7 +924,9 @@ if ($source == 'order') $fulltag = GETPOST('fulltag', 'alpha'); } else { $fulltag = 'ORD='.$order->id.'.CUS='.$order->thirdparty->id; - if (!empty($TAG)) { $tag = $TAG; $fulltag .= '.TAG='.$TAG; } + if (!empty($TAG)) { + $tag = $TAG; $fulltag .= '.TAG='.$TAG; + } } $fulltag = dol_string_unaccent($fulltag); @@ -940,15 +943,16 @@ if ($source == 'order') // Object $text = '<b>'.$langs->trans("PaymentOrderRef", $order->ref).'</b>'; - if (GETPOST('desc', 'alpha')) $text = '<b>'.$langs->trans(GETPOST('desc', 'alpha')).'</b>'; + if (GETPOST('desc', 'alpha')) { + $text = '<b>'.$langs->trans(GETPOST('desc', 'alpha')).'</b>'; + } print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Designation"); print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.$text; print '<input type="hidden" name="s" value="'.dol_escape_htmltag($source).'">'; print '<input type="hidden" name="ref" value="'.dol_escape_htmltag($order->ref).'">'; - print '<input type="hidden" name="dol_id" value="'.dol_escape_htmltag($order->id).'">'; + print '<input type="hidden" name="dol_id" value="'.dol_escape_htmltag($order->id).'">'; $directdownloadlink = $order->getLastMainDocLink('commande'); - if ($directdownloadlink) - { + if ($directdownloadlink) { print '<br><a href="'.$directdownloadlink.'" rel="nofollow noopener">'; print img_mime($order->last_main_doc, ''); print $langs->trans("DownloadDocument").'</a>'; @@ -957,11 +961,12 @@ if ($source == 'order') // Amount print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Amount"); - if (empty($amount)) print ' ('.$langs->trans("ToComplete").')'; + if (empty($amount)) { + print ' ('.$langs->trans("ToComplete").')'; + } print '</td><td class="CTableRow'.($var ? '1' : '2').'">'; - if (empty($amount) || !is_numeric($amount)) - { - print '<input type="hidden" name="amount" value="'.GETPOST("amount", 'int').'">'; + if (empty($amount) || !is_numeric($amount)) { + print '<input type="hidden" name="amount" value="'.price2num(GETPOST("amount", 'alpha'), 'MT').'">'; print '<input class="flat maxwidth75" type="text" name="newamount" value="'.price2num(GETPOST("newamount", "alpha"), 'MT').'">'; } else { print '<b>'.price($amount).'</b>'; @@ -989,8 +994,7 @@ if ($source == 'order') $shipToZip = $order->thirdparty->zip; $shipToStreet2 = ''; $phoneNum = $order->thirdparty->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) { print '<input type="hidden" name="shipToName" value="'.dol_escape_htmltag($shipToName).'">'."\n"; print '<input type="hidden" name="shipToStreet" value="'.dol_escape_htmltag($shipToStreet).'">'."\n"; print '<input type="hidden" name="shipToCity" value="'.dol_escape_htmltag($shipToCity).'">'."\n"; @@ -1002,18 +1006,21 @@ if ($source == 'order') } else { print '<!-- Shipping address not complete, so we don t use it -->'."\n"; } - if (is_object($order->thirdparty)) print '<input type="hidden" name="thirdparty_id" value="'.$order->thirdparty->id.'">'."\n"; + if (is_object($order->thirdparty)) { + print '<input type="hidden" name="thirdparty_id" value="'.$order->thirdparty->id.'">'."\n"; + } print '<input type="hidden" name="email" value="'.$order->thirdparty->email.'">'."\n"; print '<input type="hidden" name="vatnumber" value="'.dol_escape_htmltag($order->thirdparty->tva_intra).'">'."\n"; $labeldesc = $langs->trans("Order").' '.$order->ref; - if (GETPOST('desc', 'alpha')) $labeldesc = GETPOST('desc', 'alpha'); + if (GETPOST('desc', 'alpha')) { + $labeldesc = GETPOST('desc', 'alpha'); + } print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; } // Payment on customer invoice -if ($source == 'invoice') -{ +if ($source == 'invoice') { $found = true; $langs->load("bills"); @@ -1021,8 +1028,7 @@ if ($source == 'invoice') $invoice = new Facture($db); $result = $invoice->fetch('', $ref); - if ($result <= 0) - { + if ($result <= 0) { $mesg = $invoice->error; $error++; } else { @@ -1030,10 +1036,11 @@ if ($source == 'invoice') } $object = $invoice; - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { + if ($action != 'dopayment') { // Do not change amount if we just click on first dopayment $amount = price2num($invoice->total_ttc - ($invoice->getSommePaiement() + $invoice->getSumCreditNotesUsed() + $invoice->getSumDepositsUsed())); - if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int'); + if (GETPOST("amount", 'alpha')) { + $amount = GETPOST("amount", 'alpha'); + } $amount = price2num($amount); } @@ -1041,7 +1048,9 @@ if ($source == 'invoice') $fulltag = GETPOST('fulltag', 'alpha'); } else { $fulltag = 'INV='.$invoice->id.'.CUS='.$invoice->thirdparty->id; - if (!empty($TAG)) { $tag = $TAG; $fulltag .= '.TAG='.$TAG; } + if (!empty($TAG)) { + $tag = $TAG; $fulltag .= '.TAG='.$TAG; + } } $fulltag = dol_string_unaccent($fulltag); @@ -1058,15 +1067,16 @@ if ($source == 'invoice') // Object $text = '<b>'.$langs->trans("PaymentInvoiceRef", $invoice->ref).'</b>'; - if (GETPOST('desc', 'alpha')) $text = '<b>'.$langs->trans(GETPOST('desc', 'alpha')).'</b>'; + if (GETPOST('desc', 'alpha')) { + $text = '<b>'.$langs->trans(GETPOST('desc', 'alpha')).'</b>'; + } print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Designation"); print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.$text; print '<input type="hidden" name="s" value="'.dol_escape_htmltag($source).'">'; print '<input type="hidden" name="ref" value="'.dol_escape_htmltag($invoice->ref).'">'; - print '<input type="hidden" name="dol_id" value="'.dol_escape_htmltag($invoice->id).'">'; + print '<input type="hidden" name="dol_id" value="'.dol_escape_htmltag($invoice->id).'">'; $directdownloadlink = $invoice->getLastMainDocLink('facture'); - if ($directdownloadlink) - { + if ($directdownloadlink) { print '<br><a href="'.$directdownloadlink.'">'; print img_mime($invoice->last_main_doc, ''); print $langs->trans("DownloadDocument").'</a>'; @@ -1075,14 +1085,15 @@ if ($source == 'invoice') // Amount print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("PaymentAmount"); - if (empty($amount) && empty($object->paye)) print ' ('.$langs->trans("ToComplete").')'; + if (empty($amount) && empty($object->paye)) { + print ' ('.$langs->trans("ToComplete").')'; + } print '</td><td class="CTableRow'.($var ? '1' : '2').'">'; if ($object->type == $object::TYPE_CREDIT_NOTE) { print '<b>'.$langs->trans("CreditNote").'</b>'; } elseif (empty($object->paye)) { - if (empty($amount) || !is_numeric($amount)) - { - print '<input type="hidden" name="amount" value="'.GETPOST("amount", 'int').'">'; + if (empty($amount) || !is_numeric($amount)) { + print '<input type="hidden" name="amount" value="'.price2num(GETPOST("amount", 'alpha'), 'MT').'">'; print '<input class="flat maxwidth75" type="text" name="newamount" value="'.price2num(GETPOST("newamount", "alpha"), 'MT').'">'; } else { print '<b>'.price($amount).'</b>'; @@ -1114,8 +1125,7 @@ if ($source == 'invoice') $shipToZip = $invoice->thirdparty->zip; $shipToStreet2 = ''; $phoneNum = $invoice->thirdparty->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) { print '<input type="hidden" name="shipToName" value="'.$shipToName.'">'."\n"; print '<input type="hidden" name="shipToStreet" value="'.$shipToStreet.'">'."\n"; print '<input type="hidden" name="shipToCity" value="'.$shipToCity.'">'."\n"; @@ -1127,17 +1137,20 @@ if ($source == 'invoice') } else { print '<!-- Shipping address not complete, so we don t use it -->'."\n"; } - if (is_object($invoice->thirdparty)) print '<input type="hidden" name="thirdparty_id" value="'.$invoice->thirdparty->id.'">'."\n"; + if (is_object($invoice->thirdparty)) { + print '<input type="hidden" name="thirdparty_id" value="'.$invoice->thirdparty->id.'">'."\n"; + } print '<input type="hidden" name="email" value="'.$invoice->thirdparty->email.'">'."\n"; print '<input type="hidden" name="vatnumber" value="'.$invoice->thirdparty->tva_intra.'">'."\n"; $labeldesc = $langs->trans("Invoice").' '.$invoice->ref; - if (GETPOST('desc', 'alpha')) $labeldesc = GETPOST('desc', 'alpha'); + if (GETPOST('desc', 'alpha')) { + $labeldesc = GETPOST('desc', 'alpha'); + } print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; } // Payment on contract line -if ($source == 'contractline') -{ +if ($source == 'contractline') { $found = true; $langs->load("contracts"); @@ -1147,16 +1160,13 @@ if ($source == 'contractline') $contractline = new ContratLigne($db); $result = $contractline->fetch('', $ref); - if ($result <= 0) - { + if ($result <= 0) { $mesg = $contractline->error; $error++; } else { - if ($contractline->fk_contrat > 0) - { + if ($contractline->fk_contrat > 0) { $result = $contract->fetch($contractline->fk_contrat); - if ($result > 0) - { + if ($result > 0) { $result = $contract->fetch_thirdparty($contract->socid); } else { $mesg = $contract->error; @@ -1169,18 +1179,15 @@ if ($source == 'contractline') } $object = $contractline; - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { + if ($action != 'dopayment') { // Do not change amount if we just click on first dopayment $amount = $contractline->total_ttc; - if ($contractline->fk_product && !empty($conf->global->PAYMENT_USE_NEW_PRICE_FOR_CONTRACTLINES)) - { + if ($contractline->fk_product && !empty($conf->global->PAYMENT_USE_NEW_PRICE_FOR_CONTRACTLINES)) { $product = new Product($db); $result = $product->fetch($contractline->fk_product); // We define price for product (TODO Put this in a method in product class) - if (!empty($conf->global->PRODUIT_MULTIPRICES)) - { + if (!empty($conf->global->PRODUIT_MULTIPRICES)) { $pu_ht = $product->multiprices[$contract->thirdparty->price_level]; $pu_ttc = $product->multiprices_ttc[$contract->thirdparty->price_level]; $price_base_type = $product->multiprices_base_type[$contract->thirdparty->price_level]; @@ -1191,14 +1198,15 @@ if ($source == 'contractline') } $amount = $pu_ttc; - if (empty($amount)) - { + if (empty($amount)) { dol_print_error('', 'ErrorNoPriceDefinedForThisProduct'); exit; } } - if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int'); + if (GETPOST("amount", 'alpha')) { + $amount = GETPOST("amount", 'alpha'); + } $amount = price2num($amount); } @@ -1206,12 +1214,16 @@ if ($source == 'contractline') $fulltag = GETPOST('fulltag', 'alpha'); } else { $fulltag = 'COL='.$contractline->id.'.CON='.$contract->id.'.CUS='.$contract->thirdparty->id.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M%S'); - if (!empty($TAG)) { $tag = $TAG; $fulltag .= '.TAG='.$TAG; } + if (!empty($TAG)) { + $tag = $TAG; $fulltag .= '.TAG='.$TAG; + } } $fulltag = dol_string_unaccent($fulltag); $qty = 1; - if (GETPOST('qty')) $qty = GETPOST('qty'); + if (GETPOST('qty')) { + $qty = GETPOST('qty'); + } // Creditor print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Creditor"); @@ -1226,29 +1238,30 @@ if ($source == 'contractline') // Object $text = '<b>'.$langs->trans("PaymentRenewContractId", $contract->ref, $contractline->ref).'</b>'; - if ($contractline->fk_product) - { + if ($contractline->fk_product) { $contractline->fetch_product(); $text .= '<br>'.$contractline->product->ref.($contractline->product->label ? ' - '.$contractline->product->label : ''); } - if ($contractline->description) $text .= '<br>'.dol_htmlentitiesbr($contractline->description); + if ($contractline->description) { + $text .= '<br>'.dol_htmlentitiesbr($contractline->description); + } //if ($contractline->date_fin_validite) { // $text.='<br>'.$langs->trans("DateEndPlanned").': '; // $text.=dol_print_date($contractline->date_fin_validite); //} - if ($contractline->date_fin_validite) - { + if ($contractline->date_fin_validite) { $text .= '<br>'.$langs->trans("ExpiredSince").': '.dol_print_date($contractline->date_fin_validite); } - if (GETPOST('desc', 'alpha')) $text = '<b>'.$langs->trans(GETPOST('desc', 'alpha')).'</b>'; + if (GETPOST('desc', 'alpha')) { + $text = '<b>'.$langs->trans(GETPOST('desc', 'alpha')).'</b>'; + } print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Designation"); print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.$text; print '<input type="hidden" name="source" value="'.dol_escape_htmltag($source).'">'; print '<input type="hidden" name="ref" value="'.dol_escape_htmltag($contractline->ref).'">'; print '<input type="hidden" name="dol_id" value="'.dol_escape_htmltag($contractline->id).'">'; $directdownloadlink = $contract->getLastMainDocLink('contract'); - if ($directdownloadlink) - { + if ($directdownloadlink) { print '<br><a href="'.$directdownloadlink.'">'; print img_mime($contract->last_main_doc, ''); print $langs->trans("DownloadDocument").'</a>'; @@ -1259,15 +1272,12 @@ if ($source == 'contractline') $label = $langs->trans("Quantity"); $qty = 1; $duration = ''; - if ($contractline->fk_product) - { - if ($contractline->product->isService() && $contractline->product->duration_value > 0) - { + if ($contractline->fk_product) { + if ($contractline->product->isService() && $contractline->product->duration_value > 0) { $label = $langs->trans("Duration"); // TODO Put this in a global method - if ($contractline->product->duration_value > 1) - { + if ($contractline->product->duration_value > 1) { $dur = array("h"=>$langs->trans("Hours"), "d"=>$langs->trans("DurationDays"), "w"=>$langs->trans("DurationWeeks"), "m"=>$langs->trans("DurationMonths"), "y"=>$langs->trans("DurationYears")); } else { $dur = array("h"=>$langs->trans("Hour"), "d"=>$langs->trans("DurationDay"), "w"=>$langs->trans("DurationWeek"), "m"=>$langs->trans("DurationMonth"), "y"=>$langs->trans("DurationYear")); @@ -1282,11 +1292,12 @@ if ($source == 'contractline') // Amount print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Amount"); - if (empty($amount)) print ' ('.$langs->trans("ToComplete").')'; + if (empty($amount)) { + print ' ('.$langs->trans("ToComplete").')'; + } print '</td><td class="CTableRow'.($var ? '1' : '2').'">'; - if (empty($amount) || !is_numeric($amount)) - { - print '<input type="hidden" name="amount" value="'.GETPOST("amount", 'int').'">'; + if (empty($amount) || !is_numeric($amount)) { + print '<input type="hidden" name="amount" value="'.price2num(GETPOST("amount", 'alpha'), 'MT').'">'; print '<input class="flat maxwidth75" type="text" name="newamount" value="'.price2num(GETPOST("newamount", "alpha"), 'MT').'">'; } else { print '<b>'.price($amount).'</b>'; @@ -1314,8 +1325,7 @@ if ($source == 'contractline') $shipToZip = $contract->thirdparty->zip; $shipToStreet2 = ''; $phoneNum = $contract->thirdparty->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) { print '<input type="hidden" name="shipToName" value="'.$shipToName.'">'."\n"; print '<input type="hidden" name="shipToStreet" value="'.$shipToStreet.'">'."\n"; print '<input type="hidden" name="shipToCity" value="'.$shipToCity.'">'."\n"; @@ -1327,17 +1337,20 @@ if ($source == 'contractline') } else { print '<!-- Shipping address not complete, so we don t use it -->'."\n"; } - if (is_object($contract->thirdparty)) print '<input type="hidden" name="thirdparty_id" value="'.$contract->thirdparty->id.'">'."\n"; + if (is_object($contract->thirdparty)) { + print '<input type="hidden" name="thirdparty_id" value="'.$contract->thirdparty->id.'">'."\n"; + } print '<input type="hidden" name="email" value="'.$contract->thirdparty->email.'">'."\n"; print '<input type="hidden" name="vatnumber" value="'.$contract->thirdparty->tva_intra.'">'."\n"; $labeldesc = $langs->trans("Contract").' '.$contract->ref; - if (GETPOST('desc', 'alpha')) $labeldesc = GETPOST('desc', 'alpha'); + if (GETPOST('desc', 'alpha')) { + $labeldesc = GETPOST('desc', 'alpha'); + } print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; } // Payment on member subscription -if ($source == 'membersubscription') -{ +if ($source == 'membersubscription') { $found = true; $langs->load("members"); @@ -1346,8 +1359,7 @@ if ($source == 'membersubscription') $member = new Adherent($db); $result = $member->fetch('', $ref); - if ($result <= 0) - { + if ($result <= 0) { $mesg = $member->error; $error++; } else { @@ -1356,18 +1368,21 @@ if ($source == 'membersubscription') } $object = $member; - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { + if ($action != 'dopayment') { // Do not change amount if we just click on first dopayment $amount = $subscription->total_ttc; - if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int'); - $amount = price2num($amount); + if (GETPOST("amount", 'alpha')) { + $amount = GETPOST("amount", 'alpha'); + } + $amount = price2num($amount, 'MT'); } if (GETPOST('fulltag', 'alpha')) { $fulltag = GETPOST('fulltag', 'alpha'); } else { $fulltag = 'MEM='.$member->id.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M%S'); - if (!empty($TAG)) { $tag = $TAG; $fulltag .= '.TAG='.$TAG; } + if (!empty($TAG)) { + $tag = $TAG; $fulltag .= '.TAG='.$TAG; + } } $fulltag = dol_string_unaccent($fulltag); @@ -1380,14 +1395,19 @@ if ($source == 'membersubscription') // Debitor print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Member"); print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'; - if ($member->morphy == 'mor' && !empty($member->societe)) print $member->societe; - else print $member->getFullName($langs); + if ($member->morphy == 'mor' && !empty($member->societe)) { + print $member->societe; + } else { + print $member->getFullName($langs); + } print '</b>'; print '</td></tr>'."\n"; // Object $text = '<b>'.$langs->trans("PaymentSubscription").'</b>'; - if (GETPOST('desc', 'alpha')) $text = '<b>'.$langs->trans(GETPOST('desc', 'alpha')).'</b>'; + if (GETPOST('desc', 'alpha')) { + $text = '<b>'.$langs->trans(GETPOST('desc', 'alpha')).'</b>'; + } print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Designation"); print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.$text; print '<input type="hidden" name="source" value="'.dol_escape_htmltag($source).'">'; @@ -1400,8 +1420,7 @@ if ($source == 'membersubscription') print '</td></tr>'."\n"; } - if ($member->last_subscription_date || $member->last_subscription_amount) - { + if ($member->last_subscription_date || $member->last_subscription_amount) { // Last subscription date print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("LastSubscriptionDate"); @@ -1414,25 +1433,30 @@ if ($source == 'membersubscription') print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.price($member->last_subscription_amount); print '</td></tr>'."\n"; - if (empty($amount) && !GETPOST('newamount', 'alpha')) $_GET['newamount'] = $member->last_subscription_amount; + if (empty($amount) && !GETPOST('newamount', 'alpha')) { + $_GET['newamount'] = $member->last_subscription_amount; + } } // Amount print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Amount"); - if (empty($amount)) - { - if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) print ' ('.$langs->trans("ToComplete"); - if (!empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) print ' - <a href="'.$conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO.'" rel="external" target="_blank">'.$langs->trans("SeeHere").'</a>'; - if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) print ')'; + if (empty($amount)) { + if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { + print ' ('.$langs->trans("ToComplete"); + } + if (!empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) { + print ' - <a href="'.$conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO.'" rel="external" target="_blank">'.$langs->trans("SeeHere").'</a>'; + } + if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { + print ')'; + } } print '</td><td class="CTableRow'.($var ? '1' : '2').'">'; $valtoshow = ''; - if (empty($amount) || !is_numeric($amount)) - { + if (empty($amount) || !is_numeric($amount)) { $valtoshow = price2num(GETPOST("newamount", 'alpha'), 'MT'); // force default subscription amount to value defined into constant... - if (empty($valtoshow)) - { + if (empty($valtoshow)) { if (!empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { $valtoshow = $conf->global->MEMBER_NEWFORM_AMOUNT; @@ -1444,15 +1468,24 @@ if ($source == 'membersubscription') } } } - if (empty($amount) || !is_numeric($amount)) - { + if (empty($amount) || !is_numeric($amount)) { //$valtoshow=price2num(GETPOST("newamount",'alpha'),'MT'); - if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); - print '<input type="hidden" name="amount" value="'.GETPOST("amount", 'int').'">'; - print '<input class="flat maxwidth75" type="text" name="newamount" value="'.$valtoshow.'">'; + if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) { + $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); + } + print '<input type="hidden" name="amount" value="'.price2num(GETPOST("amount", 'alpha'), 'MT').'">'; + if (empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { + print '<input class="flat maxwidth75" type="text" name="newamountbis" value="'.$valtoshow.'" disabled>'; + print '<input type="hidden" name="newamount" value="'.$valtoshow.'">'; + } else { + print '<input class="flat maxwidth75" type="text" name="newamount" value="'.$valtoshow.'">'; + } } else { $valtoshow = $amount; - if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); + if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) { + $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); + $amount = $valtoshow; + } print '<b>'.price($valtoshow).'</b>'; print '<input type="hidden" name="amount" value="'.$valtoshow.'">'; print '<input type="hidden" name="newamount" value="'.$valtoshow.'">'; @@ -1478,8 +1511,7 @@ if ($source == 'membersubscription') $shipToZip = $member->zip; $shipToStreet2 = ''; $phoneNum = $member->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) { print '<!-- Shipping address information -->'; print '<input type="hidden" name="shipToName" value="'.$shipToName.'">'."\n"; print '<input type="hidden" name="shipToStreet" value="'.$shipToStreet.'">'."\n"; @@ -1492,16 +1524,19 @@ if ($source == 'membersubscription') } else { print '<!-- Shipping address not complete, so we don t use it -->'."\n"; } - if (is_object($member->thirdparty)) print '<input type="hidden" name="thirdparty_id" value="'.$member->thirdparty->id.'">'."\n"; + if (is_object($member->thirdparty)) { + print '<input type="hidden" name="thirdparty_id" value="'.$member->thirdparty->id.'">'."\n"; + } print '<input type="hidden" name="email" value="'.$member->email.'">'."\n"; $labeldesc = $langs->trans("PaymentSubscription"); - if (GETPOST('desc', 'alpha')) $labeldesc = GETPOST('desc', 'alpha'); + if (GETPOST('desc', 'alpha')) { + $labeldesc = GETPOST('desc', 'alpha'); + } print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; } // Payment on donation -if ($source == 'donation') -{ +if ($source == 'donation') { $found = true; $langs->load("don"); @@ -1509,8 +1544,7 @@ if ($source == 'donation') $don = new Don($db); $result = $don->fetch($ref); - if ($result <= 0) - { + if ($result <= 0) { $mesg = $don->error; $error++; } else { @@ -1518,10 +1552,11 @@ if ($source == 'donation') } $object = $don; - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { + if ($action != 'dopayment') { // Do not change amount if we just click on first dopayment $amount = $subscription->total_ttc; - if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int'); + if (GETPOST("amount", 'alpha')) { + $amount = GETPOST("amount", 'alpha'); + } $amount = price2num($amount); } @@ -1529,7 +1564,9 @@ if ($source == 'donation') $fulltag = GETPOST('fulltag', 'alpha'); } else { $fulltag = 'DON='.$don->ref.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M%S'); - if (!empty($TAG)) { $tag = $TAG; $fulltag .= '.TAG='.$TAG; } + if (!empty($TAG)) { + $tag = $TAG; $fulltag .= '.TAG='.$TAG; + } } $fulltag = dol_string_unaccent($fulltag); @@ -1542,14 +1579,19 @@ if ($source == 'donation') // Debitor print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("ThirdParty"); print '</td><td class="CTableRow'.($var ? '1' : '2').'"><b>'; - if ($don->morphy == 'mor' && !empty($don->societe)) print $don->societe; - else print $don->getFullName($langs); + if ($don->morphy == 'mor' && !empty($don->societe)) { + print $don->societe; + } else { + print $don->getFullName($langs); + } print '</b>'; print '</td></tr>'."\n"; // Object $text = '<b>'.$langs->trans("PaymentDonation").'</b>'; - if (GETPOST('desc', 'alpha')) $text = '<b>'.$langs->trans(GETPOST('desc', 'alpha')).'</b>'; + if (GETPOST('desc', 'alpha')) { + $text = '<b>'.$langs->trans(GETPOST('desc', 'alpha')).'</b>'; + } print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Designation"); print '</td><td class="CTableRow'.($var ? '1' : '2').'">'.$text; print '<input type="hidden" name="source" value="'.dol_escape_htmltag($source).'">'; @@ -1558,20 +1600,23 @@ if ($source == 'donation') // Amount print '<tr class="CTableRow'.($var ? '1' : '2').'"><td class="CTableRow'.($var ? '1' : '2').'">'.$langs->trans("Amount"); - if (empty($amount)) - { - if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) print ' ('.$langs->trans("ToComplete"); - if (!empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) print ' - <a href="'.$conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO.'" rel="external" target="_blank">'.$langs->trans("SeeHere").'</a>'; - if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) print ')'; + if (empty($amount)) { + if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { + print ' ('.$langs->trans("ToComplete"); + } + if (!empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) { + print ' - <a href="'.$conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO.'" rel="external" target="_blank">'.$langs->trans("SeeHere").'</a>'; + } + if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { + print ')'; + } } print '</td><td class="CTableRow'.($var ? '1' : '2').'">'; $valtoshow = ''; - if (empty($amount) || !is_numeric($amount)) - { + if (empty($amount) || !is_numeric($amount)) { $valtoshow = price2num(GETPOST("newamount", 'alpha'), 'MT'); // force default subscription amount to value defined into constant... - if (empty($valtoshow)) - { + if (empty($valtoshow)) { if (!empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { $valtoshow = $conf->global->MEMBER_NEWFORM_AMOUNT; @@ -1583,15 +1628,19 @@ if ($source == 'donation') } } } - if (empty($amount) || !is_numeric($amount)) - { + if (empty($amount) || !is_numeric($amount)) { //$valtoshow=price2num(GETPOST("newamount",'alpha'),'MT'); - if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); - print '<input type="hidden" name="amount" value="'.GETPOST("amount", 'int').'">'; + if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) { + $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); + } + print '<input type="hidden" name="amount" value="'.price2num(GETPOST("amount", 'alpha'), 'MT').'">'; print '<input class="flat maxwidth75" type="text" name="newamount" value="'.$valtoshow.'">'; } else { $valtoshow = $amount; - if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); + if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) { + $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); + $amount = $valtoshow; + } print '<b>'.price($valtoshow).'</b>'; print '<input type="hidden" name="amount" value="'.$valtoshow.'">'; print '<input type="hidden" name="newamount" value="'.$valtoshow.'">'; @@ -1617,8 +1666,7 @@ if ($source == 'donation') $shipToZip = $don->zip; $shipToStreet2 = ''; $phoneNum = $don->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) { print '<!-- Shipping address information -->'; print '<input type="hidden" name="shipToName" value="'.$shipToName.'">'."\n"; print '<input type="hidden" name="shipToStreet" value="'.$shipToStreet.'">'."\n"; @@ -1631,46 +1679,48 @@ if ($source == 'donation') } else { print '<!-- Shipping address not complete, so we don t use it -->'."\n"; } - if (is_object($don->thirdparty)) print '<input type="hidden" name="thirdparty_id" value="'.$don->thirdparty->id.'">'."\n"; + if (is_object($don->thirdparty)) { + print '<input type="hidden" name="thirdparty_id" value="'.$don->thirdparty->id.'">'."\n"; + } print '<input type="hidden" name="email" value="'.$don->email.'">'."\n"; $labeldesc = $langs->trans("PaymentSubscription"); - if (GETPOST('desc', 'alpha')) $labeldesc = GETPOST('desc', 'alpha'); + if (GETPOST('desc', 'alpha')) { + $labeldesc = GETPOST('desc', 'alpha'); + } print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; } -if (!$found && !$mesg) $mesg = $langs->trans("ErrorBadParameters"); +if (!$found && !$mesg) { + $mesg = $langs->trans("ErrorBadParameters"); +} -if ($mesg) print '<tr><td align="center" colspan="2"><br><div class="warning">'.dol_escape_htmltag($mesg).'</div></td></tr>'."\n"; +if ($mesg) { + print '<tr><td align="center" colspan="2"><br><div class="warning">'.dol_escape_htmltag($mesg).'</div></td></tr>'."\n"; +} print '</table>'."\n"; print "\n"; // Show all payment mode buttons (Stripe, Paypal, ...) -if ($action != 'dopayment') -{ - if ($found && !$error) // We are in a management option and no error - { +if ($action != 'dopayment') { + if ($found && !$error) { // We are in a management option and no error // Check status of the object (Invoice) to verify if it is paid by external payment modules (ie Payzen, ...) $parameters = [ 'source' => $source, 'object' => $object ]; $reshook = $hookmanager->executeHooks('doCheckStatus', $parameters, $object, $action); - if ($source == 'order' && $object->billed) - { + if ($source == 'order' && $object->billed) { print '<br><br><span class="amountpaymentcomplete size15x">'.$langs->trans("OrderBilled").'</span>'; - } elseif ($source == 'invoice' && $object->paye) - { + } elseif ($source == 'invoice' && $object->paye) { print '<br><br><span class="amountpaymentcomplete size15x">'.$langs->trans("InvoicePaid").'</span>'; - } elseif ($source == 'donation' && $object->paid) - { + } elseif ($source == 'donation' && $object->paid) { print '<br><br><span class="amountpaymentcomplete size15x">'.$langs->trans("DonationPaid").'</span>'; } else { // Membership can be paid and we still allow to make renewal - if ($source == 'membersubscription' && $object->datefin > dol_now()) - { + if ($source == 'membersubscription' && $object->datefin > dol_now()) { $langs->load("members"); print '<br><span class="amountpaymentcomplete size15x">'.$langs->trans("MembershipPaid", dol_print_date($object->datefin, 'day')).'</span><br>'; print '<div class="opacitymedium margintoponly">'.$langs->trans("PaymentWillBeRecordedForNextPeriod").'</div>'; @@ -1683,8 +1733,7 @@ if ($action != 'dopayment') 'paymentmethod' => $paymentmethod ]; $reshook = $hookmanager->executeHooks('doAddButton', $parameters, $object, $action); - if ((empty($paymentmethod) || $paymentmethod == 'paybox') && !empty($conf->paybox->enabled)) - { + if ((empty($paymentmethod) || $paymentmethod == 'paybox') && !empty($conf->paybox->enabled)) { print '<div class="button buttonpayment" id="div_dopayment_paybox"><span class="fa fa-credit-card"></span> <input class="" type="submit" id="dopayment_paybox" name="dopayment_paybox" value="'.$langs->trans("PayBoxDoPayment").'">'; print '<br>'; print '<span class="buttonpaymentsmall">'.$langs->trans("CreditOrDebitCard").'</span>'; @@ -1703,8 +1752,7 @@ if ($action != 'dopayment') '; } - if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled)) - { + if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled)) { print '<div class="button buttonpayment" id="div_dopayment_stripe"><span class="fa fa-credit-card"></span> <input class="" type="submit" id="dopayment_stripe" name="dopayment_stripe" value="'.$langs->trans("StripeDoPayment").'">'; print '<input type="hidden" name="noidempotency" value="'.GETPOST('noidempotency', 'int').'">'; print '<br>'; @@ -1725,23 +1773,22 @@ if ($action != 'dopayment') '; } - if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled)) - { - if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY = 'integral'; + if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled)) { + if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) { + $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY = 'integral'; + } print '<div class="button buttonpayment" id="div_dopayment_paypal">'; if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY != 'integral') { print '<div style="line-height: 1em">&nbsp;</div>'; } print '<span class="fa fa-paypal"></span> <input class="" type="submit" id="dopayment_paypal" name="dopayment_paypal" value="'.$langs->trans("PaypalDoPayment").'">'; - if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') - { + if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') { print '<br>'; print '<span class="buttonpaymentsmall">'.$langs->trans("CreditOrDebitCard").'</span><span class="buttonpaymentsmall"> - </span>'; print '<span class="buttonpaymentsmall">'.$langs->trans("PayPalBalance").'</span>'; } - if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') - { + if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') { //print '<br>'; //print '<span class="buttonpaymentsmall">'.$langs->trans("PayPalBalance").'"></span>'; } @@ -1779,11 +1826,9 @@ print '<br>'; // Add more content on page for some services -if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment mode -{ +if (preg_match('/^dopayment/', $action)) { // If we choosed/click on the payment mode // Stripe - if (GETPOST('dopayment_stripe', 'alpha')) - { + if (GETPOST('dopayment_stripe', 'alpha')) { // Personalized checkout print '<style> /** @@ -1834,14 +1879,12 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment print '<input type="hidden" name="email" value="'.GETPOST('email', 'alpha').'" />'; print '<input type="hidden" name="thirdparty_id" value="'.GETPOST('thirdparty_id', 'int').'" />'; - if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION) || !empty($conf->global->STRIPE_USE_NEW_CHECKOUT)) // Use a SCA ready method - { + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION) || !empty($conf->global->STRIPE_USE_NEW_CHECKOUT)) { // Use a SCA ready method require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; $service = 'StripeLive'; $servicestatus = 1; - if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha')) - { + if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha')) { $service = 'StripeTest'; $servicestatus = 0; } @@ -1849,15 +1892,18 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment $stripe = new Stripe($db); $stripeacc = $stripe->getStripeAccount($service); $stripecu = null; - if (is_object($object) && is_object($object->thirdparty)) $stripecu = $stripe->customerStripe($object->thirdparty, $stripeacc, $servicestatus, 1); + if (is_object($object) && is_object($object->thirdparty)) { + $stripecu = $stripe->customerStripe($object->thirdparty, $stripeacc, $servicestatus, 1); + } - if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { $noidempotency_key = (GETPOSTISSET('noidempotency') ? GETPOST('noidempotency', 'int') : 0); // By default noidempotency is unset, so we must use a different tag/ref for each payment. If set, we can pay several times the same tag/ref. $paymentintent = $stripe->getPaymentIntent($amount, $currency, $tag, 'Stripe payment: '.$fulltag.(is_object($object) ? ' ref='.$object->ref : ''), $object, $stripecu, $stripeacc, $servicestatus, 0, 'automatic', false, null, 0, $noidempotency_key); // The paymentintnent has status 'requires_payment_method' (even if paymentintent was already paid) //var_dump($paymentintent); - if ($stripe->error) setEventMessages($stripe->error, null, 'errors'); + if ($stripe->error) { + setEventMessages($stripe->error, null, 'errors'); + } } } @@ -1867,16 +1913,14 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment <table id="dolpaymenttable" summary="Payment form" class="center"> <tbody><tr><td class="textpublicpayment">'; - if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { print '<div id="payment-request-button"><!-- A Stripe Element will be inserted here. --></div>'; } print '<div class="form-row left">'; print '<label for="card-element">'.$langs->trans("CreditOrDebitCard").'</label>'; - if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { print '<br><input id="cardholder-name" class="marginbottomonly" name="cardholder-name" value="" type="text" placeholder="'.$langs->trans("CardOwner").'" autocomplete="off" autofocus required>'; } @@ -1896,10 +1940,8 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment print '</table>'; //} - if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { - if (empty($paymentintent)) - { + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { + if (empty($paymentintent)) { print '<center>'.$langs->trans("Error").'</center>'; } else { print '<input type="hidden" name="paymentintent_id" value="'.$paymentintent->id.'">'; @@ -1911,8 +1953,7 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment // JS Code for Stripe - if (empty($stripearrayofkeys['publishable_key'])) - { + if (empty($stripearrayofkeys['publishable_key'])) { $langs->load("errors"); print info_admin($langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Stripe")), 0, 0, 'error'); } else { @@ -1923,19 +1964,19 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment // Code to ask the credit card. This use the default "API version". No way to force API version when using JS code. print '<script type="text/javascript" language="javascript">'."\n"; - if (!empty($conf->global->STRIPE_USE_NEW_CHECKOUT)) - { + if (!empty($conf->global->STRIPE_USE_NEW_CHECKOUT)) { $amountstripe = $amount; // Correct the amount according to unit of currency // See https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); - if (!in_array($currency, $arrayzerounitcurrency)) $amountstripe = $amountstripe * 100; + if (!in_array($currency, $arrayzerounitcurrency)) { + $amountstripe = $amountstripe * 100; + } $ipaddress = getUserRemoteIP(); $metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress); - if (is_object($object)) - { + if (is_object($object)) { $metadata['dol_type'] = $object->element; $metadata['dol_id'] = $object->id; @@ -1947,7 +1988,9 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment 'description'=>'Stripe payment: '.$FULLTAG.($ref ? ' ref='.$ref : ''), "metadata" => $metadata ); - if ($TAG) $arrayforpaymentintent["statement_descriptor"] = dol_trunc($TAG, 10, 'right', 'UTF-8', 1); // 22 chars that appears on bank receipt (company + description) + if ($TAG) { + $arrayforpaymentintent["statement_descriptor"] = dol_trunc($TAG, 10, 'right', 'UTF-8', 1); // 22 chars that appears on bank receipt (company + description) + } $arrayforcheckout = array( 'payment_method_types' => array('card'), @@ -1964,8 +2007,11 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment 'cancel_url' => $urlko, 'payment_intent_data' => $arrayforpaymentintent ); - if ($stripecu) $arrayforcheckout['customer'] = $stripecu; - elseif (GETPOST('email', 'alpha') && isValidEmail(GETPOST('email', 'alpha'))) $arrayforcheckout['customer_email'] = GETPOST('email', 'alpha'); + if ($stripecu) { + $arrayforcheckout['customer'] = $stripecu; + } elseif (GETPOST('email', 'alpha') && isValidEmail(GETPOST('email', 'alpha'))) { + $arrayforcheckout['customer_email'] = GETPOST('email', 'alpha'); + } $sessionstripe = \Stripe\Checkout\Session::create($arrayforcheckout); $remoteip = getUserRemoteIP(); @@ -1977,39 +2023,38 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment $_SESSION['ipaddress'] = ($remoteip ? $remoteip : 'unknown'); // Payer ip $_SESSION['payerID'] = is_object($stripecu) ? $stripecu->id : ''; $_SESSION['TRANSACTIONID'] = $sessionstripe->id; - } catch (Exception $e) - { + } catch (Exception $e) { print $e->getMessage(); } ?> - // Code for payment with option STRIPE_USE_NEW_CHECKOUT set + // Code for payment with option STRIPE_USE_NEW_CHECKOUT set - // Create a Stripe client. - var stripe = Stripe('<?php echo $stripearrayofkeys['publishable_key']; // Defined into config.php ?>'); + // Create a Stripe client. + var stripe = Stripe('<?php echo $stripearrayofkeys['publishable_key']; // Defined into config.php ?>'); - // Create an instance of Elements - var elements = stripe.elements(); + // Create an instance of Elements + var elements = stripe.elements(); - // Custom styling can be passed to options when creating an Element. - // (Note that this demo uses a wider set of styles than the guide below.) - var style = { - base: { - color: '#32325d', - lineHeight: '24px', - fontFamily: '"Helvetica Neue", Helvetica, sans-serif', - fontSmoothing: 'antialiased', - fontSize: '16px', - '::placeholder': { - color: '#aab7c4' - } - }, - invalid: { - color: '#fa755a', - iconColor: '#fa755a' - } - }; + // Custom styling can be passed to options when creating an Element. + // (Note that this demo uses a wider set of styles than the guide below.) + var style = { + base: { + color: '#32325d', + lineHeight: '24px', + fontFamily: '"Helvetica Neue", Helvetica, sans-serif', + fontSmoothing: 'antialiased', + fontSize: '16px', + '::placeholder': { + color: '#aab7c4' + } + }, + invalid: { + color: '#fa755a', + iconColor: '#fa755a' + } + }; - var cardElement = elements.create('card', {style: style}); + var cardElement = elements.create('card', {style: style}); // Comment this to avoid the redirect stripe.redirectToCheckout({ @@ -2024,248 +2069,261 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment }); - <?php - } elseif (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { + <?php + } elseif (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { ?> - // Code for payment with option STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION set + // Code for payment with option STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION set - // Create a Stripe client. - var stripe = Stripe('<?php echo $stripearrayofkeys['publishable_key']; // Defined into config.php ?>'); + // Create a Stripe client. + var stripe = Stripe('<?php echo $stripearrayofkeys['publishable_key']; // Defined into config.php ?>'); - // Create an instance of Elements - var elements = stripe.elements(); + // Create an instance of Elements + var elements = stripe.elements(); - // Custom styling can be passed to options when creating an Element. - // (Note that this demo uses a wider set of styles than the guide below.) - var style = { - base: { - color: '#32325d', - lineHeight: '24px', - fontFamily: '"Helvetica Neue", Helvetica, sans-serif', - fontSmoothing: 'antialiased', - fontSize: '16px', - '::placeholder': { - color: '#aab7c4' - } - }, - invalid: { - color: '#fa755a', - iconColor: '#fa755a' - } - }; + // Custom styling can be passed to options when creating an Element. + // (Note that this demo uses a wider set of styles than the guide below.) + var style = { + base: { + color: '#32325d', + lineHeight: '24px', + fontFamily: '"Helvetica Neue", Helvetica, sans-serif', + fontSmoothing: 'antialiased', + fontSize: '16px', + '::placeholder': { + color: '#aab7c4' + } + }, + invalid: { + color: '#fa755a', + iconColor: '#fa755a' + } + }; - var cardElement = elements.create('card', {style: style}); + var cardElement = elements.create('card', {style: style}); - // Add an instance of the card Element into the `card-element` <div> - cardElement.mount('#card-element'); + // Add an instance of the card Element into the `card-element` <div> + cardElement.mount('#card-element'); - // Handle real-time validation errors from the card Element. - cardElement.addEventListener('change', function(event) { - var displayError = document.getElementById('card-errors'); - if (event.error) { - console.log("Show event error (like 'Incorrect card number', ...)"); - displayError.textContent = event.error.message; - } else { - console.log("Reset error message"); - displayError.textContent = ''; - } - }); + // Handle real-time validation errors from the card Element. + cardElement.addEventListener('change', function(event) { + var displayError = document.getElementById('card-errors'); + if (event.error) { + console.log("Show event error (like 'Incorrect card number', ...)"); + displayError.textContent = event.error.message; + } else { + console.log("Reset error message"); + displayError.textContent = ''; + } + }); - // Handle form submission - var cardholderName = document.getElementById('cardholder-name'); - var cardButton = document.getElementById('buttontopay'); - var clientSecret = cardButton.dataset.secret; + // Handle form submission + var cardholderName = document.getElementById('cardholder-name'); + var cardButton = document.getElementById('buttontopay'); + var clientSecret = cardButton.dataset.secret; - cardButton.addEventListener('click', function(event) { - console.log("We click on buttontopay"); - event.preventDefault(); + cardButton.addEventListener('click', function(event) { + console.log("We click on buttontopay"); + event.preventDefault(); - if (cardholderName.value == '') - { - console.log("Field Card holder is empty"); - var displayError = document.getElementById('card-errors'); - displayError.textContent = '<?php print dol_escape_js($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardOwner"))); ?>'; - } - else - { - stripe.handleCardPayment( - clientSecret, cardElement, { - payment_method_data: { - billing_details: { - name: cardholderName.value - <?php if (GETPOST('email', 'alpha') || (is_object($object) && is_object($object->thirdparty) && !empty($object->thirdparty->email))) { ?>, email: '<?php echo dol_escape_js(GETPOST('email', 'alpha') ? GETPOST('email', 'alpha') : $object->thirdparty->email); ?>'<?php } ?> - <?php if (is_object($object) && is_object($object->thirdparty) && !empty($object->thirdparty->phone)) { ?>, phone: '<?php echo dol_escape_js($object->thirdparty->phone); ?>'<?php } ?> - <?php if (is_object($object) && is_object($object->thirdparty)) { ?>, address: { - city: '<?php echo dol_escape_js($object->thirdparty->town); ?>', - <?php if ($object->thirdparty->country_code) { ?>country: '<?php echo dol_escape_js($object->thirdparty->country_code); ?>',<?php } ?> - line1: '<?php echo dol_escape_js(preg_replace('/\s\s+/', ' ', $object->thirdparty->address)); ?>', - postal_code: '<?php echo dol_escape_js($object->thirdparty->zip); ?>' - } - <?php } ?> - } - }, - save_payment_method: <?php if ($stripecu) { print 'true'; } else { print 'false'; } ?> /* true when a customer was provided when creating payment intent. true ask to save the card */ - } - ).then(function(result) { - console.log(result); - if (result.error) { - console.log("Error on result of handleCardPayment"); - jQuery('#buttontopay').show(); - jQuery('#hourglasstopay').hide(); - // Inform the user if there was an error - var errorElement = document.getElementById('card-errors'); - errorElement.textContent = result.error.message; - } else { - // The payment has succeeded. Display a success message. - console.log("No error on result of handleCardPayment, so we submit the form"); - // Submit the form - jQuery('#buttontopay').hide(); - jQuery('#hourglasstopay').show(); - // Send form (action=charge that will do nothing) - jQuery('#payment-form').submit(); - } - }); - } - }); - - <?php - } else // Old method (not SCA ready) - { - ?> - // Old code for payment with option STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION off and STRIPE_USE_NEW_CHECKOUT off - - // Create a Stripe client. - var stripe = Stripe('<?php echo $stripearrayofkeys['publishable_key']; // Defined into config.php ?>'); - - // Create an instance of Elements - var elements = stripe.elements(); - - // Custom styling can be passed to options when creating an Element. - // (Note that this demo uses a wider set of styles than the guide below.) - var style = { - base: { - color: '#32325d', - lineHeight: '24px', - fontFamily: '"Helvetica Neue", Helvetica, sans-serif', - fontSmoothing: 'antialiased', - fontSize: '16px', - '::placeholder': { - color: '#aab7c4' - } - }, - invalid: { - color: '#fa755a', - iconColor: '#fa755a' - } - }; - - // Create an instance of the card Element - var card = elements.create('card', {style: style}); - - // Add an instance of the card Element into the `card-element` <div> - card.mount('#card-element'); - - // Handle real-time validation errors from the card Element. - card.addEventListener('change', function(event) { - var displayError = document.getElementById('card-errors'); - if (event.error) { - displayError.textContent = event.error.message; - } else { - displayError.textContent = ''; - } - }); - - // Handle form submission - var form = document.getElementById('payment-form'); - console.log(form); - form.addEventListener('submit', function(event) { - event.preventDefault(); - <?php - if (empty($conf->global->STRIPE_USE_3DSECURE)) // Ask credit card directly, no 3DS test + if (cardholderName.value == '') { + console.log("Field Card holder is empty"); + var displayError = document.getElementById('card-errors'); + displayError.textContent = '<?php print dol_escape_js($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardOwner"))); ?>'; + } + else + { + /* Disable button to pay and show hourglass cursor */ + jQuery('#hourglasstopay').show(); + jQuery('#buttontopay').hide(); + + stripe.handleCardPayment( + clientSecret, cardElement, { + payment_method_data: { + billing_details: { + name: cardholderName.value + <?php if (GETPOST('email', 'alpha') || (is_object($object) && is_object($object->thirdparty) && !empty($object->thirdparty->email))) { + ?>, email: '<?php echo dol_escape_js(GETPOST('email', 'alpha') ? GETPOST('email', 'alpha') : $object->thirdparty->email); ?>'<?php + } ?> + <?php if (is_object($object) && is_object($object->thirdparty) && !empty($object->thirdparty->phone)) { + ?>, phone: '<?php echo dol_escape_js($object->thirdparty->phone); ?>'<?php + } ?> + <?php if (is_object($object) && is_object($object->thirdparty)) { + ?>, address: { + city: '<?php echo dol_escape_js($object->thirdparty->town); ?>', + <?php if ($object->thirdparty->country_code) { + ?>country: '<?php echo dol_escape_js($object->thirdparty->country_code); ?>',<?php + } ?> + line1: '<?php echo dol_escape_js(preg_replace('/\s\s+/', ' ', $object->thirdparty->address)); ?>', + postal_code: '<?php echo dol_escape_js($object->thirdparty->zip); ?>' + } + <?php } ?> + } + }, + save_payment_method:<?php if ($stripecu) { + print 'true'; + } else { + print 'false'; + } ?> /* true when a customer was provided when creating payment intent. true ask to save the card */ + } + ).then(function(result) { + console.log(result); + if (result.error) { + console.log("Error on result of handleCardPayment"); + jQuery('#buttontopay').show(); + jQuery('#hourglasstopay').hide(); + // Inform the user if there was an error + var errorElement = document.getElementById('card-errors'); + errorElement.textContent = result.error.message; + } else { + // The payment has succeeded. Display a success message. + console.log("No error on result of handleCardPayment, so we submit the form"); + // Submit the form + jQuery('#buttontopay').hide(); + jQuery('#hourglasstopay').show(); + // Send form (action=charge that will do nothing) + jQuery('#payment-form').submit(); + } + }); + } + }); + + <?php + } else { + // Old method (not SCA ready) + ?> + // Old code for payment with option STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION off and STRIPE_USE_NEW_CHECKOUT off + + // Create a Stripe client. + var stripe = Stripe('<?php echo $stripearrayofkeys['publishable_key']; // Defined into config.php ?>'); + + // Create an instance of Elements + var elements = stripe.elements(); + + // Custom styling can be passed to options when creating an Element. + // (Note that this demo uses a wider set of styles than the guide below.) + var style = { + base: { + color: '#32325d', + lineHeight: '24px', + fontFamily: '"Helvetica Neue", Helvetica, sans-serif', + fontSmoothing: 'antialiased', + fontSize: '16px', + '::placeholder': { + color: '#aab7c4' + } + }, + invalid: { + color: '#fa755a', + iconColor: '#fa755a' + } + }; + + // Create an instance of the card Element + var card = elements.create('card', {style: style}); + + // Add an instance of the card Element into the `card-element` <div> + card.mount('#card-element'); + + // Handle real-time validation errors from the card Element. + card.addEventListener('change', function(event) { + var displayError = document.getElementById('card-errors'); + if (event.error) { + displayError.textContent = event.error.message; + } else { + displayError.textContent = ''; + } + }); + + // Handle form submission + var form = document.getElementById('payment-form'); + console.log(form); + form.addEventListener('submit', function(event) { + event.preventDefault(); + <?php + if (empty($conf->global->STRIPE_USE_3DSECURE)) { // Ask credit card directly, no 3DS test ?> - /* Use token */ - stripe.createToken(card).then(function(result) { - if (result.error) { - // Inform the user if there was an error - var errorElement = document.getElementById('card-errors'); - errorElement.textContent = result.error.message; - } else { - // Send the token to your server - stripeTokenHandler(result.token); - } - }); - <?php + /* Use token */ + stripe.createToken(card).then(function(result) { + if (result.error) { + // Inform the user if there was an error + var errorElement = document.getElementById('card-errors'); + errorElement.textContent = result.error.message; + } else { + // Send the token to your server + stripeTokenHandler(result.token); + } + }); + <?php } else // Ask credit card with 3DS test { ?> - /* Use 3DS source */ - stripe.createSource(card).then(function(result) { - if (result.error) { - // Inform the user if there was an error - var errorElement = document.getElementById('card-errors'); - errorElement.textContent = result.error.message; - } else { - // Send the source to your server - stripeSourceHandler(result.source); - } - }); - <?php + /* Use 3DS source */ + stripe.createSource(card).then(function(result) { + if (result.error) { + // Inform the user if there was an error + var errorElement = document.getElementById('card-errors'); + errorElement.textContent = result.error.message; + } else { + // Send the source to your server + stripeSourceHandler(result.source); + } + }); + <?php } ?> - }); + }); - /* Insert the Token into the form so it gets submitted to the server */ - function stripeTokenHandler(token) { - // Insert the token ID into the form so it gets submitted to the server - var form = document.getElementById('payment-form'); + /* Insert the Token into the form so it gets submitted to the server */ + function stripeTokenHandler(token) { + // Insert the token ID into the form so it gets submitted to the server + var form = document.getElementById('payment-form'); - var hiddenInput = document.createElement('input'); - hiddenInput.setAttribute('type', 'hidden'); - hiddenInput.setAttribute('name', 'stripeToken'); - hiddenInput.setAttribute('value', token.id); - form.appendChild(hiddenInput); + var hiddenInput = document.createElement('input'); + hiddenInput.setAttribute('type', 'hidden'); + hiddenInput.setAttribute('name', 'stripeToken'); + hiddenInput.setAttribute('value', token.id); + form.appendChild(hiddenInput); var hiddenInput2 = document.createElement('input'); hiddenInput2.setAttribute('type', 'hidden'); hiddenInput2.setAttribute('name', 'token'); - hiddenInput2.setAttribute('value', '<?php echo newToken(); ?>'); + hiddenInput2.setAttribute('value', '<?php echo newToken(); ?>'); form.appendChild(hiddenInput2); - // Submit the form - jQuery('#buttontopay').hide(); - jQuery('#hourglasstopay').show(); - console.log("submit token"); - form.submit(); - } + // Submit the form + jQuery('#buttontopay').hide(); + jQuery('#hourglasstopay').show(); + console.log("submit token"); + form.submit(); + } - /* Insert the Source into the form so it gets submitted to the server */ - function stripeSourceHandler(source) { - // Insert the source ID into the form so it gets submitted to the server - var form = document.getElementById('payment-form'); + /* Insert the Source into the form so it gets submitted to the server */ + function stripeSourceHandler(source) { + // Insert the source ID into the form so it gets submitted to the server + var form = document.getElementById('payment-form'); - var hiddenInput = document.createElement('input'); - hiddenInput.setAttribute('type', 'hidden'); - hiddenInput.setAttribute('name', 'stripeSource'); - hiddenInput.setAttribute('value', source.id); - form.appendChild(hiddenInput); + var hiddenInput = document.createElement('input'); + hiddenInput.setAttribute('type', 'hidden'); + hiddenInput.setAttribute('name', 'stripeSource'); + hiddenInput.setAttribute('value', source.id); + form.appendChild(hiddenInput); var hiddenInput2 = document.createElement('input'); hiddenInput2.setAttribute('type', 'hidden'); hiddenInput2.setAttribute('name', 'token'); - hiddenInput2.setAttribute('value', '<?php echo newToken(); ?>'); + hiddenInput2.setAttribute('value', '<?php echo newToken(); ?>'); form.appendChild(hiddenInput2); - // Submit the form - jQuery('#buttontopay').hide(); - jQuery('#hourglasstopay').show(); - console.log("submit source"); - form.submit(); - } + // Submit the form + jQuery('#buttontopay').hide(); + jQuery('#hourglasstopay').show(); + console.log("submit source"); + form.submit(); + } - <?php + <?php } print '</script>'; diff --git a/htdocs/public/payment/paymentko.php b/htdocs/public/payment/paymentko.php index b99c4a39392..6b4b28f66fe 100644 --- a/htdocs/public/payment/paymentko.php +++ b/htdocs/public/payment/paymentko.php @@ -25,45 +25,57 @@ * This token can be used to get more informations. */ -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} // For MultiCompany module. // Do not use GETPOST here, function is not defined and this test must be done before including main.inc.php // TODO This should be useless. Because entity must be retrieve from object ref and not from url. $entity = (!empty($_GET['e']) ? (int) $_GET['e'] : (!empty($_POST['e']) ? (int) $_POST['e'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; -if (!empty($conf->paypal->enabled)) -{ +if (!empty($conf->paypal->enabled)) { require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php'; require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php'; } $langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paybox", "paypal", "stripe")); -if (!empty($conf->paypal->enabled)) -{ +if (!empty($conf->paypal->enabled)) { $PAYPALTOKEN = GETPOST('TOKEN'); - if (empty($PAYPALTOKEN)) $PAYPALTOKEN = GETPOST('token'); + if (empty($PAYPALTOKEN)) { + $PAYPALTOKEN = GETPOST('token'); + } $PAYPALPAYERID = GETPOST('PAYERID'); - if (empty($PAYPALPAYERID)) $PAYPALPAYERID = GETPOST('PayerID'); + if (empty($PAYPALPAYERID)) { + $PAYPALPAYERID = GETPOST('PayerID'); + } } -if (!empty($conf->paybox->enabled)) -{ +if (!empty($conf->paybox->enabled)) { } -if (!empty($conf->stripe->enabled)) -{ +if (!empty($conf->stripe->enabled)) { } $FULLTAG = GETPOST('FULLTAG'); -if (empty($FULLTAG)) $FULLTAG = GETPOST('fulltag'); +if (empty($FULLTAG)) { + $FULLTAG = GETPOST('fulltag'); +} $suffix = GETPOST("suffix", 'aZ09'); @@ -71,12 +83,10 @@ $suffix = GETPOST("suffix", 'aZ09'); // Detect $paymentmethod $paymentmethod = ''; $reg = array(); -if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) -{ +if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) { $paymentmethod = $reg[1]; } -if (empty($paymentmethod)) -{ +if (empty($paymentmethod)) { dol_print_error(null, 'The back url does not contains a parameter fulltag that should help us to find the payment method used'); exit; } else { @@ -85,13 +95,21 @@ if (empty($paymentmethod)) $validpaymentmethod = array(); -if (!empty($conf->paypal->enabled)) $validpaymentmethod['paypal'] = 'paypal'; -if (!empty($conf->paybox->enabled)) $validpaymentmethod['paybox'] = 'paybox'; -if (!empty($conf->stripe->enabled)) $validpaymentmethod['stripe'] = 'stripe'; +if (!empty($conf->paypal->enabled)) { + $validpaymentmethod['paypal'] = 'paypal'; +} +if (!empty($conf->paybox->enabled)) { + $validpaymentmethod['paybox'] = 'paybox'; +} +if (!empty($conf->stripe->enabled)) { + $validpaymentmethod['stripe'] = 'stripe'; +} // Security check -if (empty($validpaymentmethod)) accessforbidden('', 0, 0, 1); +if (empty($validpaymentmethod)) { + accessforbidden('', 0, 0, 1); +} $object = new stdClass(); // For triggers @@ -111,12 +129,13 @@ $object = new stdClass(); // For triggers dol_syslog("Callback url when an online payment is refused or canceled. query_string=".(empty($_SERVER["QUERY_STRING"]) ? '' : $_SERVER["QUERY_STRING"])." script_uri=".(empty($_SERVER["SCRIPT_URI"]) ? '' : $_SERVER["SCRIPT_URI"]), LOG_DEBUG, 0, '_payment'); $tracepost = ""; -foreach ($_POST as $k => $v) $tracepost .= "{$k} - {$v}\n"; +foreach ($_POST as $k => $v) { + $tracepost .= "{$k} - {$v}\n"; +} dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_payment'); -if (!empty($_SESSION['ipaddress'])) // To avoid to make action twice -{ +if (!empty($_SESSION['ipaddress'])) { // To avoid to make action twice // Get on url call $fulltag = $FULLTAG; $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN; @@ -132,20 +151,20 @@ if (!empty($_SESSION['ipaddress'])) // To avoid to make action twice if (is_object($object) && method_exists($object, 'call_trigger')) { // Call trigger $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_KO', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } // Send an email $sendemail = ''; - if (!empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) - { + if (!empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) { $sendemail = $conf->global->ONLINE_PAYMENT_SENDEMAIL; } // Send warning of error to administrator - if ($sendemail) - { + if ($sendemail) { $companylangs = new Translate('', $conf); $companylangs->setDefaultLang($mysoc->default_lang); $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox')); @@ -155,14 +174,18 @@ if (!empty($_SESSION['ipaddress'])) // To avoid to make action twice // Define link to login card $appli = constant('DOL_APPLICATION_TITLE'); - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) - { + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { $appli = $conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core - } else $appli .= " ".DOL_VERSION; - } else $appli .= " ".DOL_VERSION; + if (preg_match('/\d\.\d/', $appli)) { + if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) { + $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core + } + } else { + $appli .= " ".DOL_VERSION; + } + } else { + $appli .= " ".DOL_VERSION; + } $urlback = $_SERVER["REQUEST_URI"]; $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("NewOnlinePaymentFailed"); @@ -183,8 +206,7 @@ if (!empty($_SESSION['ipaddress'])) // To avoid to make action twice $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml); $result = $mailfile->sendfile(); - if ($result) - { + if ($result) { dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment'); } else { dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment'); @@ -195,7 +217,9 @@ if (!empty($_SESSION['ipaddress'])) // To avoid to make action twice } $head = ''; -if (!empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->ONLINE_PAYMENT_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n"; +if (!empty($conf->global->ONLINE_PAYMENT_CSS_URL)) { + $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->ONLINE_PAYMENT_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n"; +} $conf->dol_hide_topmenu = 1; $conf->dol_hide_leftmenu = 1; @@ -213,25 +237,25 @@ print '<div id="dolpaymentdiv" align="center">'."\n"; $logosmall = $mysoc->logo_small; $logo = $mysoc->logo; $paramlogo = 'ONLINE_PAYMENT_LOGO_'.$suffix; -if (!empty($conf->global->$paramlogo)) $logosmall = $conf->global->$paramlogo; -elseif (!empty($conf->global->ONLINE_PAYMENT_LOGO)) $logosmall = $conf->global->ONLINE_PAYMENT_LOGO; +if (!empty($conf->global->$paramlogo)) { + $logosmall = $conf->global->$paramlogo; +} elseif (!empty($conf->global->ONLINE_PAYMENT_LOGO)) { + $logosmall = $conf->global->ONLINE_PAYMENT_LOGO; +} //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n"; // Define urllogo $urllogo = ''; $urllogofull = ''; -if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) -{ +if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); -} elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) -{ +} elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); } // Output html code for logo -if ($urllogo) -{ +if ($urllogo) { print '<div class="backgreypublicpayment">'; print '<div class="logopublicpayment">'; print '<img id="dolpaymentlogo" src="'.$urllogo.'"'; @@ -250,14 +274,15 @@ print '<br><br>'; print $langs->trans("YourPaymentHasNotBeenRecorded")."<br><br>"; $key = 'ONLINE_PAYMENT_MESSAGE_KO'; -if (!empty($conf->global->$key)) print $conf->global->$key; +if (!empty($conf->global->$key)) { + print $conf->global->$key; +} $type = GETPOST('s', 'alpha'); $ref = GETPOST('ref', 'alphanohtml'); $tag = GETPOST('tag', 'alpha'); require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; -if ($type || $tag) -{ +if ($type || $tag) { $urlsubscription = getOnlinePaymentUrl(0, ($type ? $type : 'free'), $ref, $FinalPaymentAmt, $tag); print $langs->trans("ClickHereToTryAgain", $urlsubscription); diff --git a/htdocs/public/payment/paymentok.php b/htdocs/public/payment/paymentok.php index f4b9f0feb5b..99a97e0c321 100644 --- a/htdocs/public/payment/paymentok.php +++ b/htdocs/public/payment/paymentok.php @@ -25,23 +25,32 @@ * This token can be used to get more informations. */ -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php // TODO This should be useless. Because entity must be retrieve from object ref and not from url. $entity = (!empty($_GET['e']) ? (int) $_GET['e'] : (!empty($_POST['e']) ? (int) $_POST['e'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; -if (!empty($conf->paypal->enabled)) -{ +if (!empty($conf->paypal->enabled)) { require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php'; require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php'; } @@ -49,29 +58,46 @@ if (!empty($conf->paypal->enabled)) $langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paybox", "paypal")); // Clean parameters -if (!empty($conf->paypal->enabled)) -{ +if (!empty($conf->paypal->enabled)) { $PAYPAL_API_USER = ""; - if (!empty($conf->global->PAYPAL_API_USER)) $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER; + if (!empty($conf->global->PAYPAL_API_USER)) { + $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER; + } $PAYPAL_API_PASSWORD = ""; - if (!empty($conf->global->PAYPAL_API_PASSWORD)) $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD; + if (!empty($conf->global->PAYPAL_API_PASSWORD)) { + $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD; + } $PAYPAL_API_SIGNATURE = ""; - if (!empty($conf->global->PAYPAL_API_SIGNATURE)) $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE; + if (!empty($conf->global->PAYPAL_API_SIGNATURE)) { + $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE; + } $PAYPAL_API_SANDBOX = ""; - if (!empty($conf->global->PAYPAL_API_SANDBOX)) $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX; + if (!empty($conf->global->PAYPAL_API_SANDBOX)) { + $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX; + } $PAYPAL_API_OK = ""; - if ($urlok) $PAYPAL_API_OK = $urlok; + if ($urlok) { + $PAYPAL_API_OK = $urlok; + } $PAYPAL_API_KO = ""; - if ($urlko) $PAYPAL_API_KO = $urlko; + if ($urlko) { + $PAYPAL_API_KO = $urlko; + } $PAYPALTOKEN = GETPOST('TOKEN'); - if (empty($PAYPALTOKEN)) $PAYPALTOKEN = GETPOST('token'); + if (empty($PAYPALTOKEN)) { + $PAYPALTOKEN = GETPOST('token'); + } $PAYPALPAYERID = GETPOST('PAYERID'); - if (empty($PAYPALPAYERID)) $PAYPALPAYERID = GETPOST('PayerID'); + if (empty($PAYPALPAYERID)) { + $PAYPALPAYERID = GETPOST('PayerID'); + } } $FULLTAG = GETPOST('FULLTAG'); -if (empty($FULLTAG)) $FULLTAG = GETPOST('fulltag'); +if (empty($FULLTAG)) { + $FULLTAG = GETPOST('fulltag'); +} $source = GETPOST('s', 'alpha') ?GETPOST('s', 'alpha') : GETPOST('source', 'alpha'); $ref = GETPOST('ref'); @@ -81,12 +107,10 @@ $suffix = GETPOST("suffix", 'aZ09'); // Detect $paymentmethod $paymentmethod = ''; $reg = array(); -if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) -{ +if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) { $paymentmethod = $reg[1]; } -if (empty($paymentmethod)) -{ +if (empty($paymentmethod)) { dol_print_error(null, 'The back url does not contains a parameter fulltag that should help us to find the payment method used'); exit; } @@ -95,12 +119,20 @@ dol_syslog("***** paymentok.php is called paymentmethod=".$paymentmethod." FULLT $validpaymentmethod = array(); -if (!empty($conf->paypal->enabled)) $validpaymentmethod['paypal'] = 'paypal'; -if (!empty($conf->paybox->enabled)) $validpaymentmethod['paybox'] = 'paybox'; -if (!empty($conf->stripe->enabled)) $validpaymentmethod['stripe'] = 'stripe'; +if (!empty($conf->paypal->enabled)) { + $validpaymentmethod['paypal'] = 'paypal'; +} +if (!empty($conf->paybox->enabled)) { + $validpaymentmethod['paybox'] = 'paybox'; +} +if (!empty($conf->stripe->enabled)) { + $validpaymentmethod['stripe'] = 'stripe'; +} // Security check -if (empty($validpaymentmethod)) accessforbidden('', 0, 0, 1); +if (empty($validpaymentmethod)) { + accessforbidden('', 0, 0, 1); +} $ispaymentok = false; @@ -130,11 +162,15 @@ $now = dol_now(); dol_syslog("Callback url when a payment was done. query_string=".(dol_escape_htmltag($_SERVER["QUERY_STRING"]) ?dol_escape_htmltag($_SERVER["QUERY_STRING"]) : '')." script_uri=".(dol_escape_htmltag($_SERVER["SCRIPT_URI"]) ?dol_escape_htmltag($_SERVER["SCRIPT_URI"]) : ''), LOG_DEBUG, 0, '_payment'); $tracepost = ""; -foreach ($_POST as $k => $v) $tracepost .= "{$k} - {$v}\n"; +foreach ($_POST as $k => $v) { + $tracepost .= "{$k} - {$v}\n"; +} dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_payment'); $head = ''; -if (!empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->ONLINE_PAYMENT_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n"; +if (!empty($conf->global->ONLINE_PAYMENT_CSS_URL)) { + $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->ONLINE_PAYMENT_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n"; +} $conf->dol_hide_topmenu = 1; $conf->dol_hide_leftmenu = 1; @@ -153,25 +189,25 @@ print '<div id="dolpaymentdiv" class="center">'."\n"; $logosmall = $mysoc->logo_small; $logo = $mysoc->logo; $paramlogo = 'ONLINE_PAYMENT_LOGO_'.$suffix; -if (!empty($conf->global->$paramlogo)) $logosmall = $conf->global->$paramlogo; -elseif (!empty($conf->global->ONLINE_PAYMENT_LOGO)) $logosmall = $conf->global->ONLINE_PAYMENT_LOGO; +if (!empty($conf->global->$paramlogo)) { + $logosmall = $conf->global->$paramlogo; +} elseif (!empty($conf->global->ONLINE_PAYMENT_LOGO)) { + $logosmall = $conf->global->ONLINE_PAYMENT_LOGO; +} //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n"; // Define urllogo $urllogo = ''; $urllogofull = ''; -if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) -{ +if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); -} elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) -{ +} elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); } // Output html code for logo -if ($urllogo) -{ +if ($urllogo) { print '<div class="backgreypublicpayment">'; print '<div class="logopublicpayment">'; print '<img id="dolpaymentlogo" src="'.$urllogo.'"'; @@ -187,12 +223,9 @@ if ($urllogo) print '<br><br><br>'; -if (!empty($conf->paypal->enabled)) -{ - if ($paymentmethod == 'paypal') // We call this page only if payment is ok on payment system - { - if ($PAYPALTOKEN) - { +if (!empty($conf->paypal->enabled)) { + if ($paymentmethod == 'paypal') { // We call this page only if payment is ok on payment system + if ($PAYPALTOKEN) { // Get on url call $onlinetoken = $PAYPALTOKEN; $fulltag = $FULLTAG; @@ -207,15 +240,13 @@ if (!empty($conf->paypal->enabled)) dol_syslog("Call paymentok with token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment'); // Validate record - if (!empty($paymentType)) - { + if (!empty($paymentType)) { dol_syslog("We call GetExpressCheckoutDetails", LOG_DEBUG, 0, '_payment'); $resArray = getDetails($onlinetoken); //var_dump($resarray); $ack = strtoupper($resArray["ACK"]); - if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") - { + if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") { // Nothing to do dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment'); } else { @@ -227,8 +258,7 @@ if (!empty($conf->paypal->enabled)) //var_dump($resarray); $ack = strtoupper($resArray2["ACK"]); - if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") - { + if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") { dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment'); $object->source = $source; @@ -263,22 +293,32 @@ if (!empty($conf->paypal->enabled)) } } -if (!empty($conf->paybox->enabled)) -{ - if ($paymentmethod == 'paybox') $ispaymentok = true; // We call this page only if payment is ok on payment system +if (!empty($conf->paybox->enabled)) { + if ($paymentmethod == 'paybox') { + $ispaymentok = true; // We call this page only if payment is ok on payment system + } } -if (!empty($conf->stripe->enabled)) -{ - if ($paymentmethod == 'stripe') $ispaymentok = true; // We call this page only if payment is ok on payment system +if (!empty($conf->stripe->enabled)) { + if ($paymentmethod == 'stripe') { + $ispaymentok = true; // We call this page only if payment is ok on payment system + } } // If data not provided from back url, search them into the session env -if (empty($ipaddress)) $ipaddress = $_SESSION['ipaddress']; -if (empty($TRANSACTIONID)) $TRANSACTIONID = $_SESSION['TRANSACTIONID']; -if (empty($FinalPaymentAmt)) $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; -if (empty($paymentType)) $paymentType = $_SESSION["paymentType"]; +if (empty($ipaddress)) { + $ipaddress = $_SESSION['ipaddress']; +} +if (empty($TRANSACTIONID)) { + $TRANSACTIONID = $_SESSION['TRANSACTIONID']; +} +if (empty($FinalPaymentAmt)) { + $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; +} +if (empty($paymentType)) { + $paymentType = $_SESSION["paymentType"]; +} $fulltag = $FULLTAG; $tmptag = dolExplodeIntoArray($fulltag, '.', '='); @@ -290,18 +330,22 @@ dol_syslog("ispaymentok=".$ispaymentok." tmptag=".var_export($tmptag, true), LOG // Make complementary actions $ispostactionok = 0; $postactionmessages = array(); -if ($ispaymentok) -{ +if ($ispaymentok) { // Set permission for the anonymous user - if (empty($user->rights->societe)) $user->rights->societe = new stdClass(); - if (empty($user->rights->facture)) $user->rights->facture = new stdClass(); - if (empty($user->rights->adherent)) { $user->rights->adherent = new stdClass(); $user->rights->adherent->cotisation = new stdClass(); } + if (empty($user->rights->societe)) { + $user->rights->societe = new stdClass(); + } + if (empty($user->rights->facture)) { + $user->rights->facture = new stdClass(); + } + if (empty($user->rights->adherent)) { + $user->rights->adherent = new stdClass(); $user->rights->adherent->cotisation = new stdClass(); + } $user->rights->societe->creer = 1; $user->rights->facture->creer = 1; $user->rights->adherent->cotisation->creer = 1; - if (array_key_exists('MEM', $tmptag) && $tmptag['MEM'] > 0) - { + if (array_key_exists('MEM', $tmptag) && $tmptag['MEM'] > 0) { // Validate member // Create subscription // Create complementary actions (this include creation of thirdparty) @@ -322,16 +366,22 @@ if ($ispaymentok) dol_syslog("We have to process member with id=".$tmptag['MEM']." result1=".$result1." result2=".$result2, LOG_DEBUG, 0, '_payment'); - if ($result1 > 0 && $result2 > 0) - { + if ($result1 > 0 && $result2 > 0) { $paymentTypeId = 0; - if ($paymentmethod == 'paybox') $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS; - if ($paymentmethod == 'paypal') $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS; - if ($paymentmethod == 'stripe') $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS; - if (empty($paymentTypeId)) - { + if ($paymentmethod == 'paybox') { + $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS; + } + if ($paymentmethod == 'paypal') { + $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS; + } + if ($paymentmethod == 'stripe') { + $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS; + } + if (empty($paymentTypeId)) { $paymentType = $_SESSION["paymentType"]; - if (empty($paymentType)) $paymentType = 'CB'; + if (empty($paymentType)) { + $paymentType = 'CB'; + } $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1); } @@ -340,11 +390,9 @@ if ($ispaymentok) dol_syslog("FinalPaymentAmt=".$FinalPaymentAmt." paymentTypeId=".$paymentTypeId, LOG_DEBUG, 0, '_payment'); // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time) - if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) - { + if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) { $result = $object->validate($user); - if ($result < 0 || empty($object->datevalid)) - { + if ($result < 0 || empty($object->datevalid)) { $error++; $errmsg = $object->error; $postactionmessages[] = $errmsg; @@ -355,13 +403,14 @@ if ($ispaymentok) // Subscription informations $datesubscription = $object->datevalid; - if ($object->datefin > 0) - { + if ($object->datefin > 0) { $datesubscription = dol_time_plus_duree($object->datefin, 1, 'd'); } $datesubend = null; - if ($datesubscription && $defaultdelay && $defaultdelayunit) $datesubend = dol_time_plus_duree(dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit), -1, 'd'); + if ($datesubscription && $defaultdelay && $defaultdelayunit) { + $datesubend = dol_time_plus_duree(dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit), -1, 'd'); + } $paymentdate = $now; $amount = $FinalPaymentAmt; @@ -369,11 +418,16 @@ if ($ispaymentok) // Payment informations $accountid = 0; - if ($paymentmethod == 'paybox') $accountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS; - if ($paymentmethod == 'paypal') $accountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS; - if ($paymentmethod == 'stripe') $accountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS; - if ($accountid < 0) - { + if ($paymentmethod == 'paybox') { + $accountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS; + } + if ($paymentmethod == 'paypal') { + $accountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS; + } + if ($paymentmethod == 'stripe') { + $accountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS; + } + if ($accountid < 0) { $error++; $errmsg = 'Setup of bank account to use for payment is not correctly done for payment method '.$paymentmethod; $postactionmessages[] = $errmsg; @@ -387,23 +441,27 @@ if ($ispaymentok) $emetteur_banque = ''; // Define default choice for complementary actions $option = ''; - 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)) $option = 'bankviainvoice'; - elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && !empty($conf->banque->enabled)) $option = 'bankdirect'; - 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)) $option = 'invoiceonly'; - if (empty($option)) $option = 'none'; + 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)) { + $option = 'bankviainvoice'; + } elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && !empty($conf->banque->enabled)) { + $option = 'bankdirect'; + } 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)) { + $option = 'invoiceonly'; + } + if (empty($option)) { + $option = 'none'; + } $sendalsoemail = 1; // Record the subscription then complementary actions $db->begin(); // Create subscription - if (!$error) - { + if (!$error) { dol_syslog("Call ->subscription to create subscription", LOG_DEBUG, 0, '_payment'); $crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend); - if ($crowid <= 0) - { + if ($crowid <= 0) { $error++; $errmsg = $object->error; $postactionmessages[] = $errmsg; @@ -414,15 +472,13 @@ if ($ispaymentok) } } - if (!$error) - { + if (!$error) { dol_syslog("Call ->subscriptionComplementaryActions option=".$option, LOG_DEBUG, 0, '_payment'); $autocreatethirdparty = 1; // will create thirdparty if member not yet linked to a thirdparty $result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque, $autocreatethirdparty); - if ($result < 0) - { + if ($result < 0) { dol_syslog("Error ".$object->error." ".join(',', $object->errors), LOG_DEBUG, 0, '_payment'); $error++; @@ -430,18 +486,15 @@ if ($ispaymentok) $postactionmessages = array_merge($postactionmessages, $object->errors); $ispostactionok = -1; } else { - if ($option == 'bankviainvoice') - { + if ($option == 'bankviainvoice') { $postactionmessages[] = 'Invoice, payment and bank record created'; dol_syslog("Invoice, payment and bank record created", LOG_DEBUG, 0, '_payment'); } - if ($option == 'bankdirect') - { + if ($option == 'bankdirect') { $postactionmessages[] = 'Bank record created'; dol_syslog("Bank record created", LOG_DEBUG, 0, '_payment'); } - if ($option == 'invoiceonly') - { + if ($option == 'invoiceonly') { $postactionmessages[] = 'Invoice recorded'; dol_syslog("Invoice recorded", LOG_DEBUG, 0, '_payment'); } @@ -451,18 +504,15 @@ if ($ispaymentok) } } - if (!$error) - { - if ($paymentmethod == 'stripe' && $autocreatethirdparty && $option == 'bankviainvoice') - { + if (!$error) { + if ($paymentmethod == 'stripe' && $autocreatethirdparty && $option == 'bankviainvoice') { $thirdparty_id = $object->fk_soc; dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_payment'); $service = 'StripeTest'; $servicestatus = 0; - if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) - { + if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) { $service = 'StripeLive'; $servicestatus = 1; } @@ -477,8 +527,7 @@ if ($ispaymentok) $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 0); - if (!$customer && $TRANSACTIONID) // Not linked to a stripe customer, we make the link - { + if (!$customer && $TRANSACTIONID) { // Not linked to a stripe customer, we make the link dol_syslog("No stripe profile found, so we add it for TRANSACTIONID = ".$TRANSACTIONID, LOG_DEBUG, 0, '_payment'); try { @@ -541,13 +590,11 @@ if ($ispaymentok) } // Send email to member - if (!$error) - { + if (!$error) { dol_syslog("Send email to customer to ".$object->email." if we have to (sendalsoemail = ".$sendalsoemail.")", LOG_DEBUG, 0, '_payment'); // Send confirmation Email - if ($object->email && $sendalsoemail) - { + if ($object->email && $sendalsoemail) { $subject = ''; $msg = ''; @@ -563,10 +610,11 @@ if ($ispaymentok) $arraydefaultmessage = null; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION; - 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) - { + if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { $subject = $arraydefaultmessage->topic; $msg = $arraydefaultmessage->content; } @@ -581,8 +629,7 @@ if ($ispaymentok) $listofpaths = array(); $listofnames = array(); $listofmimes = array(); - if (is_object($object->invoice)) - { + if (is_object($object->invoice)) { $invoicediroutput = $conf->facture->dir_output; $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+'); $file = $fileparams['fullname']; @@ -596,14 +643,16 @@ if ($ispaymentok) $result = $object->send_an_email($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, "", $moreinheader); - if ($result < 0) - { + if ($result < 0) { $errmsg = $object->error; $postactionmessages[] = $errmsg; $ispostactionok = -1; } else { - if ($file) $postactionmessages[] = 'Email sent to member (with invoice document attached)'; - else $postactionmessages[] = 'Email sent to member (without any attached document)'; + if ($file) { + $postactionmessages[] = 'Email sent to member (with invoice document attached)'; + } else { + $postactionmessages[] = 'Email sent to member (without any attached document)'; + } // TODO Add actioncomm event } @@ -617,40 +666,43 @@ if ($ispaymentok) $postactionmessages[] = 'Member '.$tmptag['MEM'].' for subscription paid was not found'; $ispostactionok = -1; } - } elseif (array_key_exists('INV', $tmptag) && $tmptag['INV'] > 0) - { + } elseif (array_key_exists('INV', $tmptag) && $tmptag['INV'] > 0) { // Record payment include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $object = new Facture($db); $result = $object->fetch($tmptag['INV']); - if ($result) - { + if ($result) { $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; $paymentTypeId = 0; - if ($paymentmethod == 'paybox') $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS; - if ($paymentmethod == 'paypal') $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS; - if ($paymentmethod == 'stripe') $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS; - if (empty($paymentTypeId)) - { + if ($paymentmethod == 'paybox') { + $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS; + } + if ($paymentmethod == 'paypal') { + $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS; + } + if ($paymentmethod == 'stripe') { + $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS; + } + if (empty($paymentTypeId)) { $paymentType = $_SESSION["paymentType"]; - if (empty($paymentType)) $paymentType = 'CB'; + if (empty($paymentType)) { + $paymentType = 'CB'; + } $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1); } $currencyCodeType = $_SESSION['currencyCodeType']; // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time) - if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) - { + if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) { $db->begin(); // Creation of payment line include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; $paiement = new Paiement($db); $paiement->datepaye = $now; - if ($currencyCodeType == $conf->currency) - { + if ($currencyCodeType == $conf->currency) { $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id } else { $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching @@ -665,11 +717,9 @@ if ($ispaymentok) $paiement->ext_payment_id = $TRANSACTIONID; $paiement->ext_payment_site = $service; - if (!$error) - { + if (!$error) { $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents - if ($paiement_id < 0) - { + if ($paiement_id < 0) { $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors); $ispostactionok = -1; $error++; @@ -679,20 +729,23 @@ if ($ispaymentok) } } - if (!$error && !empty($conf->banque->enabled)) - { + if (!$error && !empty($conf->banque->enabled)) { $bankaccountid = 0; - if ($paymentmethod == 'paybox') $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS; - elseif ($paymentmethod == 'paypal') $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS; - elseif ($paymentmethod == 'stripe') $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS; + if ($paymentmethod == 'paybox') { + $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS; + } elseif ($paymentmethod == 'paypal') { + $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS; + } elseif ($paymentmethod == 'stripe') { + $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS; + } - if ($bankaccountid > 0) - { + if ($bankaccountid > 0) { $label = '(CustomerInvoicePayment)'; - if ($object->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note + if ($object->type == Facture::TYPE_CREDIT_NOTE) { + $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note + } $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', ''); - if ($result < 0) - { + if ($result < 0) { $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors); $ispostactionok = -1; $error++; @@ -707,8 +760,7 @@ if ($ispaymentok) } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -726,8 +778,7 @@ if ($ispaymentok) } } -if ($ispaymentok) -{ +if ($ispaymentok) { // Get on url call $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN; $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID; @@ -739,26 +790,33 @@ if ($ispaymentok) if (is_object($object) && method_exists($object, 'call_trigger')) { // Call trigger $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } print $langs->trans("YourPaymentHasBeenRecorded")."<br>\n"; - if ($TRANSACTIONID) print $langs->trans("ThisIsTransactionId", $TRANSACTIONID)."<br><br>\n"; + if ($TRANSACTIONID) { + print $langs->trans("ThisIsTransactionId", $TRANSACTIONID)."<br><br>\n"; + } $key = 'ONLINE_PAYMENT_MESSAGE_OK'; - if (!empty($conf->global->$key)) print $conf->global->$key; + if (!empty($conf->global->$key)) { + print $conf->global->$key; + } $sendemail = ''; - if (!empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) $sendemail = $conf->global->ONLINE_PAYMENT_SENDEMAIL; + if (!empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) { + $sendemail = $conf->global->ONLINE_PAYMENT_SENDEMAIL; + } $tmptag = dolExplodeIntoArray($fulltag, '.', '='); dol_syslog("Send email to admins if we have to (sendemail = ".$sendemail.")", LOG_DEBUG, 0, '_payment'); // Send an email to admins - if ($sendemail) - { + if ($sendemail) { $companylangs = new Translate('', $conf); $companylangs->setDefaultLang($mysoc->default_lang); $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox')); @@ -772,26 +830,28 @@ if ($ispaymentok) // Define link to login card $appli = constant('DOL_APPLICATION_TITLE'); - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) - { + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { $appli = $conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core - } else $appli .= " ".DOL_VERSION; - } else $appli .= " ".DOL_VERSION; + if (preg_match('/\d\.\d/', $appli)) { + if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) { + $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core + } + } else { + $appli .= " ".DOL_VERSION; + } + } else { + $appli .= " ".DOL_VERSION; + } $urlback = $_SERVER["REQUEST_URI"]; $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived"); $content = ""; - if (array_key_exists('MEM', $tmptag)) - { + if (array_key_exists('MEM', $tmptag)) { $url = $urlwithroot."/adherents/subscription.php?rowid=".$tmptag['MEM']; $content .= '<strong>'.$companylangs->trans("PaymentSubscription")."</strong><br><br>\n"; $content .= $companylangs->trans("MemberId").': <strong>'.$tmptag['MEM']."</strong><br>\n"; $content .= $companylangs->trans("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n"; - } elseif (array_key_exists('INV', $tmptag)) - { + } elseif (array_key_exists('INV', $tmptag)) { $url = $urlwithroot."/compta/facture/card.php?id=".$tmptag['INV']; $content .= '<strong>'.$companylangs->trans("Payment")."</strong><br><br>\n"; $content .= $companylangs->trans("InvoiceId").': <strong>'.$tmptag['INV']."</strong><br>\n"; @@ -801,24 +861,20 @@ if ($ispaymentok) $content .= $companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived")."<br>\n"; } $content .= $companylangs->transnoentities("PostActionAfterPayment").' : '; - if ($ispostactionok > 0) - { + if ($ispostactionok > 0) { //$topic.=' ('.$companylangs->transnoentitiesnoconv("Status").' '.$companylangs->transnoentitiesnoconv("OK").')'; $content .= '<font color="green">'.$companylangs->transnoentitiesnoconv("OK").'</font>'; - } elseif ($ispostactionok == 0) - { + } elseif ($ispostactionok == 0) { $content .= $companylangs->transnoentitiesnoconv("None"); } else { $topic .= ($ispostactionok ? '' : ' ('.$companylangs->trans("WarningPostActionErrorAfterPayment").')'); $content .= '<font color="red">'.$companylangs->transnoentitiesnoconv("Error").'</font>'; } $content .= '<br>'."\n"; - foreach ($postactionmessages as $postactionmessage) - { + foreach ($postactionmessages as $postactionmessage) { $content .= ' * '.$postactionmessage.'<br>'."\n"; } - if ($ispostactionok < 0) - { + if ($ispostactionok < 0) { $content .= $langs->transnoentities("ARollbackWasPerformedOnPostActions"); } $content .= '<br>'."\n"; @@ -831,10 +887,18 @@ if ($ispaymentok) $content .= "<br>\n"; $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n"; - if (!empty($ErrorCode)) $content .= "ErrorCode = ".$ErrorCode."<br>\n"; - if (!empty($ErrorShortMsg)) $content .= "ErrorShortMsg = ".$ErrorShortMsg."<br>\n"; - if (!empty($ErrorLongMsg)) $content .= "ErrorLongMsg = ".$ErrorLongMsg."<br>\n"; - if (!empty($ErrorSeverityCode)) $content .= "ErrorSeverityCode = ".$ErrorSeverityCode."<br>\n"; + if (!empty($ErrorCode)) { + $content .= "ErrorCode = ".$ErrorCode."<br>\n"; + } + if (!empty($ErrorShortMsg)) { + $content .= "ErrorShortMsg = ".$ErrorShortMsg."<br>\n"; + } + if (!empty($ErrorLongMsg)) { + $content .= "ErrorLongMsg = ".$ErrorLongMsg."<br>\n"; + } + if (!empty($ErrorSeverityCode)) { + $content .= "ErrorSeverityCode = ".$ErrorSeverityCode."<br>\n"; + } $ishtml = dol_textishtml($content); // May contain urls @@ -842,8 +906,7 @@ if ($ispaymentok) $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml); $result = $mailfile->sendfile(); - if ($result) - { + if ($result) { dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment'); //dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0); } else { @@ -863,7 +926,9 @@ if ($ispaymentok) if (is_object($object) && method_exists($object, 'call_trigger')) { // Call trigger $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_KO', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -873,18 +938,25 @@ if ($ispaymentok) print $langs->trans('ErrorCode').": ".$ErrorCode."<br>\n"; print $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."<br>\n"; - if ($mysoc->email) print "\nPlease, send a screenshot of this page to ".$mysoc->email."<br>\n"; + if ($mysoc->email) { + print "\nPlease, send a screenshot of this page to ".$mysoc->email."<br>\n"; + } $sendemail = ''; - if (!empty($conf->global->PAYMENTONLINE_SENDEMAIL)) $sendemail = $conf->global->PAYMENTONLINE_SENDEMAIL; + if (!empty($conf->global->PAYMENTONLINE_SENDEMAIL)) { + $sendemail = $conf->global->PAYMENTONLINE_SENDEMAIL; + } // TODO Remove local option to keep only the generic one ? - if ($paymentmethod == 'paypal' && !empty($conf->global->PAYPAL_PAYONLINE_SENDEMAIL)) $sendemail = $conf->global->PAYPAL_PAYONLINE_SENDEMAIL; - elseif ($paymentmethod == 'paybox' && !empty($conf->global->PAYBOX_PAYONLINE_SENDEMAIL)) $sendemail = $conf->global->PAYBOX_PAYONLINE_SENDEMAIL; - elseif ($paymentmethod == 'stripe' && !empty($conf->global->STRIPE_PAYONLINE_SENDEMAIL)) $sendemail = $conf->global->STRIPE_PAYONLINE_SENDEMAIL; + if ($paymentmethod == 'paypal' && !empty($conf->global->PAYPAL_PAYONLINE_SENDEMAIL)) { + $sendemail = $conf->global->PAYPAL_PAYONLINE_SENDEMAIL; + } elseif ($paymentmethod == 'paybox' && !empty($conf->global->PAYBOX_PAYONLINE_SENDEMAIL)) { + $sendemail = $conf->global->PAYBOX_PAYONLINE_SENDEMAIL; + } elseif ($paymentmethod == 'stripe' && !empty($conf->global->STRIPE_PAYONLINE_SENDEMAIL)) { + $sendemail = $conf->global->STRIPE_PAYONLINE_SENDEMAIL; + } // Send warning of error to administrator - if ($sendemail) - { + if ($sendemail) { $companylangs = new Translate('', $conf); $companylangs->setDefaultLang($mysoc->default_lang); $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox')); @@ -898,14 +970,18 @@ if ($ispaymentok) // Define link to login card $appli = constant('DOL_APPLICATION_TITLE'); - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) - { + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { $appli = $conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core - } else $appli .= " ".DOL_VERSION; - } else $appli .= " ".DOL_VERSION; + if (preg_match('/\d\.\d/', $appli)) { + if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) { + $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core + } + } else { + $appli .= " ".DOL_VERSION; + } + } else { + $appli .= " ".DOL_VERSION; + } $urlback = $_SERVER["REQUEST_URI"]; $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("ValidationOfPaymentFailed"); @@ -926,8 +1002,7 @@ if ($ispaymentok) $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml); $result = $mailfile->sendfile(); - if ($result) - { + if ($result) { dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment'); } else { dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment'); diff --git a/htdocs/public/project/new.php b/htdocs/public/project/new.php new file mode 100644 index 00000000000..51b8dbf9aa1 --- /dev/null +++ b/htdocs/public/project/new.php @@ -0,0 +1,486 @@ +<?php +/* Copyright (C) 2001-2002 Rodolphe Quiedeville <rodolphe@quiedeville.org> + * Copyright (C) 2001-2002 Jean-Louis Bergamo <jlb@j1b.org> + * Copyright (C) 2006-2013 Laurent Destailleur <eldy@users.sourceforge.net> + * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com> + * Copyright (C) 2012 J. Fernando Lagrange <fernando@demo-tic.org> + * Copyright (C) 2018-2019 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2018 Alexandre Spangaro <aspangaro@open-dsi.fr> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * 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 <https://www.gnu.org/licenses/>. + */ + +/** + * \file htdocs/public/lead/new.php + * \ingroup project + * \brief Example of form to add a new lead + */ + +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} + +// For MultiCompany module. +// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php +// TODO This should be useless. Because entity must be retrieve from object ref and not from url. +$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; + +// Init vars +$errmsg = ''; +$num = 0; +$error = 0; +$backtopage = GETPOST('backtopage', 'alpha'); +$action = GETPOST('action', 'aZ09'); + +// Load translation files +$langs->loadLangs(array("main", "members", "companies", "install", "other")); + +// Security check +if (empty($conf->projet->enabled)) { + accessforbidden('', 0, 0, 1); +} + +if (empty($conf->global->PROJECT_ENABLE_PUBLIC)) { + print $langs->trans("Form for public lead registration has not been enabled"); + exit; +} + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('publicnewleadcard', 'globalcard')); + +$extrafields = new ExtraFields($db); + +$object = new Project($db); + +$user->loadDefaultValues(); + + +/** + * Show header for new member + * + * @param string $title Title + * @param string $head Head array + * @param int $disablejs More content into html header + * @param int $disablehead More content into html header + * @param array $arrayofjs Array of complementary js files + * @param array $arrayofcss Array of complementary css files + * @return void + */ +function llxHeaderVierge($title, $head = "", $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '') +{ + global $user, $conf, $langs, $mysoc; + + top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); // Show html headers + + print '<body id="mainbody" class="publicnewmemberform">'; + + // Define urllogo + $urllogo = DOL_URL_ROOT.'/theme/common/login_logo.png'; + + if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) { + $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small); + } elseif (!empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) { + $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/'.$mysoc->logo); + } elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) { + $urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.svg'; + } + + print '<div class="center">'; + // Output html code for logo + if ($urllogo) { + print '<div class="backgreypublicpayment">'; + print '<div class="logopublicpayment">'; + print '<img id="dolpaymentlogo" src="'.$urllogo.'"'; + print '>'; + print '</div>'; + if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { + print '<div class="poweredbypublicpayment opacitymedium right"><a class="poweredbyhref" href="https://www.dolibarr.org?utm_medium=website&utm_source=poweredby" target="dolibarr" rel="noopener">'.$langs->trans("PoweredBy").'<br><img class="poweredbyimg" src="'.DOL_URL_ROOT.'/theme/dolibarr_logo.svg" width="80px"></a></div>'; + } + print '</div>'; + } + print '</div>'; + + print '<div class="divmainbodylarge">'; +} + +/** + * Show footer for new member + * + * @return void + */ +function llxFooterVierge() +{ + print '</div>'; + + printCommonFooter('public'); + + print "</body>\n"; + print "</html>\n"; +} + + +$arrayofdata = array(); +if (GETPOST('action') == 'addlead') { + // When a json request is sent + $entityBody = file_get_contents('php://input'); + + if ($entityBody) { + $arrayofdata = json_decode($entityBody, true); + } + + print 'Date received and lead created'; + + $db->close(); + exit; +} + + + +/* + * Actions + */ + +$parameters = array(); +// Note that $action and $object may have been modified by some hooks +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} + +// Action called when page is submitted +if (empty($reshook) && $action == 'add') { + $error = 0; + $urlback = ''; + + $db->begin(); + + // test if lead already exists + /* + if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { + if (!GETPOST('login')) { + $error++; + $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"))."<br>\n"; + } + $sql = "SELECT login FROM ".MAIN_DB_PREFIX."adherent WHERE login='".$db->escape(GETPOST('login'))."'"; + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + } + if ($num != 0) { + $error++; + $langs->load("errors"); + $errmsg .= $langs->trans("ErrorLoginAlreadyExists")."<br>\n"; + } + if (!GETPOSTISSET("pass1") || !GETPOSTISSET("pass2") || GETPOST("pass1", 'none') == '' || GETPOST("pass2", 'none') == '' || GETPOST("pass1", 'none') != GETPOST("pass2", 'none')) { + $error++; + $langs->load("errors"); + $errmsg .= $langs->trans("ErrorPasswordsMustMatch")."<br>\n"; + } + if (!GETPOST("email")) { + $error++; + $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("EMail"))."<br>\n"; + } + } + */ + if (GETPOST('type') <= 0) { + $error++; + $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type"))."<br>\n"; + } + if (!in_array(GETPOST('morphy'), array('mor', 'phy'))) { + $error++; + $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('Nature'))."<br>\n"; + } + if (empty($_POST["lastname"])) { + $error++; + $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Lastname"))."<br>\n"; + } + if (empty($_POST["firstname"])) { + $error++; + $errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Firstname"))."<br>\n"; + } + if (GETPOST("email") && !isValidEmail(GETPOST("email"))) { + $error++; + $langs->load("errors"); + $errmsg .= $langs->trans("ErrorBadEMail", GETPOST("email"))."<br>\n"; + } + + if (!$error) { + // email a peu pres correct et le login n'existe pas + $proj = new Project($db); + $proj->statut = -1; + $proj->email = GETPOST("email"); + $proj->note_private = GETPOST("note_private"); + + + // Fill array 'array_options' with data from add form + $extrafields->fetch_name_optionals_label($proj->table_element); + $ret = $extrafields->setOptionalsFromPost(null, $proj); + if ($ret < 0) { + $error++; + } + + $result = $proj->create($user); + if ($result > 0) { + require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; + $object = $proj; + + if ($object->email) { + $subject = ''; + $msg = ''; + + // Send subscription email + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + // Set output language + $outputlangs = new Translate('', $conf); + $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang); + // Load traductions files required by page + $outputlangs->loadLangs(array("main", "members")); + // Get email content from template + $arraydefaultmessage = null; + $labeltouse = $conf->global->PROJECT_EMAIL_TEMPLATE_AUTOLEAD; + + if (!empty($labeltouse)) { + $arraydefaultmessage = $formmail->getEMailTemplate($db, 'project', $user, $outputlangs, 0, 1, $labeltouse); + } + + if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { + $subject = $arraydefaultmessage->topic; + $msg = $arraydefaultmessage->content; + } + + $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object); + complete_substitutions_array($substitutionarray, $outputlangs, $object); + $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs); + $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnValid()), $substitutionarray, $outputlangs); + + if ($subjecttosend && $texttosend) { + $moreinheader = 'X-Dolibarr-Info: send_an_email by public/lead/new.php'."\r\n"; + + $result = $object->send_an_email($texttosend, $subjecttosend, array(), array(), array(), "", "", 0, -1, '', $moreinheader); + } + /*if ($result < 0) { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + }*/ + } + + if (!empty($backtopage)) { + $urlback = $backtopage; + } elseif (!empty($conf->global->PROJECT_URL_REDIRECT_LEAD)) { + $urlback = $conf->global->PROJECT_URL_REDIRECT_LEAD; + // TODO Make replacement of __AMOUNT__, etc... + } else { + $urlback = $_SERVER["PHP_SELF"]."?action=added"; + } + + if (!empty($entity)) { + $urlback .= '&entity='.$entity; + } + dol_syslog("project lead ".$proj->ref." was created, we redirect to ".$urlback); + } else { + $error++; + $errmsg .= join('<br>', $proj->errors); + } + } + + if (!$error) { + $db->commit(); + + Header("Location: ".$urlback); + exit; + } else { + $db->rollback(); + } +} + +// Create lead from $arrayofdata +if (empty($reshook) && !empty($arrayofdata)) { + // TODO + dol_syslog(var_export($arrayofdata, true)); + // ... +} + +// Action called after a submitted was send and member created successfully +// If MEMBER_URL_REDIRECT_SUBSCRIPTION is set to url we never go here because a redirect was done to this url. +// backtopage parameter with an url was set on member submit page, we never go here because a redirect was done to this url. +if (empty($reshook) && $action == 'added') { + llxHeaderVierge($langs->trans("NewMemberForm")); + + // Si on a pas ete redirige + print '<br>'; + print '<div class="center">'; + print $langs->trans("NewMemberbyWeb"); + print '</div>'; + + llxFooterVierge(); + exit; +} + + + +/* + * View + */ + +$form = new Form($db); +$formcompany = new FormCompany($db); +$extrafields->fetch_name_optionals_label('project'); // fetch optionals attributes and labels + + +llxHeaderVierge($langs->trans("NewContact")); + + +print load_fiche_titre($langs->trans("NewContact"), '', '', 0, 0, 'center'); + + +print '<div align="center">'; +print '<div id="divsubscribe">'; + +print '<div class="center subscriptionformhelptext justify">'; +if (!empty($conf->global->PROJECT_NEWFORM_TEXT)) { + print $langs->trans($conf->global->PROJECT_NEWFORM_TEXT)."<br>\n"; +} else { + print $langs->trans("NewLeadDesc", $conf->global->MAIN_INFO_SOCIETE_MAIL)."<br>\n"; +} +print '</div>'; + +dol_htmloutput_errors($errmsg); + +// Print form +print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="newlead">'."\n"; +print '<input type="hidden" name="token" value="'.newToken().'" / >'; +print '<input type="hidden" name="entity" value="'.$entity.'" />'; +print '<input type="hidden" name="action" value="add" />'; + +print '<br>'; + +print '<br><span class="opacitymedium">'.$langs->trans("FieldsWithAreMandatory", '*').'</span><br>'; +//print $langs->trans("FieldsWithIsForPublic",'**').'<br>'; + +print dol_get_fiche_head(''); + +print '<script type="text/javascript"> +jQuery(document).ready(function () { + jQuery(document).ready(function () { + jQuery("#selectcountry_id").change(function() { + document.newlead.action.value="create"; + document.newlead.submit(); + }); + }); +}); +</script>'; + + +print '<table class="border" summary="form to subscribe" id="tablesubscribe">'."\n"; + +// Lastname +print '<tr><td>'.$langs->trans("Lastname").' <FONT COLOR="red">*</FONT></td><td><input type="text" name="lastname" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('lastname')).'"></td></tr>'."\n"; +// Firstname +print '<tr><td>'.$langs->trans("Firstname").' <FONT COLOR="red">*</FONT></td><td><input type="text" name="firstname" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('firstname')).'"></td></tr>'."\n"; +// Company +print '<tr id="trcompany" class="trcompany"><td>'.$langs->trans("Company").'</td><td><input type="text" name="societe" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('societe')).'"></td></tr>'."\n"; +// Address +print '<tr><td>'.$langs->trans("Address").'</td><td>'."\n"; +print '<textarea name="address" id="address" wrap="soft" class="quatrevingtpercent" rows="'.ROWS_3.'">'.dol_escape_htmltag(GETPOST('address', 'restricthtml'), 0, 1).'</textarea></td></tr>'."\n"; +// Zip / Town +print '<tr><td>'.$langs->trans('Zip').' / '.$langs->trans('Town').'</td><td>'; +print $formcompany->select_ziptown(GETPOST('zipcode'), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6, 1); +print ' / '; +print $formcompany->select_ziptown(GETPOST('town'), 'town', array('zipcode', 'selectcountry_id', 'state_id'), 0, 1); +print '</td></tr>'; +// Country +print '<tr><td>'.$langs->trans('Country').'</td><td>'; +$country_id = GETPOST('country_id'); +if (!$country_id && !empty($conf->global->PROJECT_NEWFORM_FORCECOUNTRYCODE)) { + $country_id = getCountry($conf->global->PROJECT_NEWFORM_FORCECOUNTRYCODE, 2, $db, $langs); +} +if (!$country_id && !empty($conf->geoipmaxmind->enabled)) { + $country_code = dol_user_country(); + //print $country_code; + if ($country_code) { + $new_country_id = getCountry($country_code, 3, $db, $langs); + //print 'xxx'.$country_code.' - '.$new_country_id; + if ($new_country_id) { + $country_id = $new_country_id; + } + } +} +$country_code = getCountry($country_id, 2, $db, $langs); +print $form->select_country($country_id, 'country_id'); +print '</td></tr>'; +// State +if (empty($conf->global->SOCIETE_DISABLE_STATE)) { + print '<tr><td>'.$langs->trans('State').'</td><td>'; + if ($country_code) { + print $formcompany->select_state(GETPOST("state_id"), $country_code); + } else { + print ''; + } + print '</td></tr>'; +} +// EMail +print '<tr><td>'.$langs->trans("Email").' <FONT COLOR="red">*</FONT></td><td><input type="text" name="email" maxlength="255" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('email')).'"></td></tr>'."\n"; +// Other attributes +$tpl_context = 'public'; // define template context to public +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; +// Comments +print '<tr>'; +print '<td class="tdtop">'.$langs->trans("Comments").'</td>'; +print '<td class="tdtop"><textarea name="note_private" id="note_private" wrap="soft" class="quatrevingtpercent" rows="'.ROWS_3.'">'.dol_escape_htmltag(GETPOST('note_private', 'restricthtml'), 0, 1).'</textarea></td>'; +print '</tr>'."\n"; + +print "</table>\n"; + +print dol_get_fiche_end(); + +// Save +print '<div class="center">'; +print '<input type="submit" value="'.$langs->trans("Submit").'" id="submitsave" class="button">'; +if (!empty($backtopage)) { + print ' &nbsp; &nbsp; <input type="submit" value="'.$langs->trans("Cancel").'" id="submitcancel" class="button button-cancel">'; +} +print '</div>'; + + +print "</form>\n"; +print "<br>"; +print '</div></div>'; + + +llxFooterVierge(); + +$db->close(); diff --git a/htdocs/public/recruitment/index.php b/htdocs/public/recruitment/index.php index 204d3bf3140..c7381059a39 100644 --- a/htdocs/public/recruitment/index.php +++ b/htdocs/public/recruitment/index.php @@ -32,8 +32,12 @@ if (!defined('NOREQUIREMENU')) { if (!defined("NOLOGIN")) { define("NOLOGIN", '1'); } -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} // If this page is public (can be called outside logged session) require '../../main.inc.php'; @@ -206,7 +210,9 @@ if ($display_ticket_list) { $limit = $conf->liste_limit; $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; @@ -237,8 +243,9 @@ if ($display_ticket_list) { $sql .= " type.label as type_label, category.label as category_label, severity.label as severity_label"; // Add fields for extrafields if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } $sql .= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as t"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid=t.fk_soc"; @@ -360,8 +367,7 @@ if ($display_ticket_list) { print_liste_field_titre($selectedfields, $url_page_current, "", '', '', 'align="right"', $sortfield, $sortorder, 'center maxwidthsearch '); print '</tr>'; - while ($obj = $db->fetch_object($resql)) - { + while ($obj = $db->fetch_object($resql)) { print '<tr class="oddeven">'; // Date ticket diff --git a/htdocs/public/recruitment/view.php b/htdocs/public/recruitment/view.php index b8858b921e9..27aaa0fd0f4 100644 --- a/htdocs/public/recruitment/view.php +++ b/htdocs/public/recruitment/view.php @@ -21,10 +21,18 @@ * \brief Public file to show on job */ -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/recruitment/class/recruitmentjobposition.class.php'; @@ -52,10 +60,8 @@ if (isset($_SESSION['email_customer'])) { $object = new RecruitmentJobPosition($db); -if (!$action) -{ - if (!$ref) - { +if (!$action) { + if (!$ref) { print $langs->trans('ErrorBadParameters')." - ref missing"; exit; } else { @@ -73,10 +79,8 @@ $urlwithroot = DOL_MAIN_URL_ROOT; // This is to use same domain name than curren * Actions */ -if ($cancel) -{ - if (!empty($backtopage)) - { +if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -125,8 +129,7 @@ if ($action == "view" || $action == "presend" || $action == "close" || $action = if ($error || $errors) { setEventMessages($object->error, $object->errors, 'errors'); - if ($action == "add_message") - { + if ($action == "add_message") { $action = 'presend'; } else { $action = ''; @@ -150,7 +153,9 @@ include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; */ $head = ''; -if (!empty($conf->global->MAIN_RECRUITMENT_CSS_URL)) $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->MAIN_RECRUITMENT_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n"; +if (!empty($conf->global->MAIN_RECRUITMENT_CSS_URL)) { + $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->MAIN_RECRUITMENT_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n"; +} $conf->dol_hide_topmenu = 1; $conf->dol_hide_leftmenu = 1; @@ -188,24 +193,24 @@ print '<table id="dolpaymenttable" summary="Payment form" class="center">'."\n"; $logosmall = $mysoc->logo_small; $logo = $mysoc->logo; $paramlogo = 'ONLINE_RECRUITMENT_LOGO_'.$suffix; -if (!empty($conf->global->$paramlogo)) $logosmall = $conf->global->$paramlogo; -elseif (!empty($conf->global->ONLINE_RECRUITMENT_LOGO)) $logosmall = $conf->global->ONLINE_RECRUITMENT_LOGO_; +if (!empty($conf->global->$paramlogo)) { + $logosmall = $conf->global->$paramlogo; +} elseif (!empty($conf->global->ONLINE_RECRUITMENT_LOGO)) { + $logosmall = $conf->global->ONLINE_RECRUITMENT_LOGO_; +} //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n"; // Define urllogo $urllogo = ''; $urllogofull = ''; -if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) -{ +if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); -} elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) -{ +} elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); } // Output html code for logo -if ($urllogo) -{ +if ($urllogo) { print '<div class="backgreypublicpayment">'; print '<div class="logopublicpayment">'; print '<img id="dolpaymentlogo" src="'.$urllogo.'"'; @@ -219,15 +224,16 @@ if ($urllogo) // Output introduction text $text = ''; -if (!empty($conf->global->RECRUITMENT_NEWFORM_TEXT)) -{ +if (!empty($conf->global->RECRUITMENT_NEWFORM_TEXT)) { $langs->load("recruitment"); - if (preg_match('/^\((.*)\)$/', $conf->global->RECRUITMENT_NEWFORM_TEXT, $reg)) $text .= $langs->trans($reg[1])."<br>\n"; - else $text .= $conf->global->RECRUITMENT_NEWFORM_TEXT."<br>\n"; + if (preg_match('/^\((.*)\)$/', $conf->global->RECRUITMENT_NEWFORM_TEXT, $reg)) { + $text .= $langs->trans($reg[1])."<br>\n"; + } else { + $text .= $conf->global->RECRUITMENT_NEWFORM_TEXT."<br>\n"; + } $text = '<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n"; } -if (empty($text)) -{ +if (empty($text)) { $text .= '<tr><td class="textpublicpayment"><br>'.$langs->trans("JobOfferToBeFilled", $mysoc->name); $text .= ' &nbsp; - &nbsp; <strong>'.$mysoc->name.'</strong>'; $text .= ' &nbsp; - &nbsp; <span class="fa fa-calendar secondary"></span> '.dol_print_date($object->date_creation); @@ -304,10 +310,8 @@ print '</div>'."\n"; print "\n"; -if ($action != 'dosubmit') -{ - if ($found && !$error) // We are in a management option and no error - { +if ($action != 'dosubmit') { + if ($found && !$error) { // We are in a management option and no error } else { dol_print_error_email('ERRORNEWONLINESIGN'); } diff --git a/htdocs/public/stripe/confirm_payment.php b/htdocs/public/stripe/confirm_payment.php index 5db7b49cc80..b0f8f8213a0 100644 --- a/htdocs/public/stripe/confirm_payment.php +++ b/htdocs/public/stripe/confirm_payment.php @@ -17,13 +17,23 @@ // TODO Do we really need this page. We alread have a ipn.php page ! -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; @@ -39,14 +49,14 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; require_once DOL_DOCUMENT_ROOT.'/includes/stripe/stripe-php/init.php'; require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; -if (empty($conf->stripe->enabled)) accessforbidden('', 0, 0, 1); +if (empty($conf->stripe->enabled)) { + accessforbidden('', 0, 0, 1); +} // You can find your endpoint's secret in your webhook settings -if (isset($_GET['connect'])) -{ - if (isset($_GET['test'])) - { +if (isset($_GET['connect'])) { + if (isset($_GET['test'])) { $endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_CONNECT_KEY; $service = 'StripeTest'; $servicestatus = 0; @@ -56,8 +66,7 @@ if (isset($_GET['connect'])) $servicestatus = 1; } } else { - if (isset($_GET['test'])) - { + if (isset($_GET['test'])) { $endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_KEY; $service = 'StripeTest'; $servicestatus = 0; @@ -86,7 +95,9 @@ $stripe = new Stripe($db); // Subject $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; -if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $societeName = $conf->global->MAIN_APPLICATION_TITLE; +} dol_syslog("Stripe confirm_payment was called"); @@ -115,7 +126,7 @@ try { if (isset($json_obj->payment_intent_id)) { $intent = \Stripe\PaymentIntent::retrieve( $json_obj->payment_intent_id - ); + ); $intent->confirm(); } generatePaymentResponse($intent); diff --git a/htdocs/public/stripe/ipn.php b/htdocs/public/stripe/ipn.php index 0b5f14c9217..d39f48f2dfe 100644 --- a/htdocs/public/stripe/ipn.php +++ b/htdocs/public/stripe/ipn.php @@ -16,13 +16,23 @@ * along with this program. If not, see <https://www.gnu.org/licenses/>. */ -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; @@ -39,14 +49,14 @@ require_once DOL_DOCUMENT_ROOT.'/includes/stripe/stripe-php/init.php'; require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; -if (empty($conf->stripe->enabled)) accessforbidden('', 0, 0, 1); +if (empty($conf->stripe->enabled)) { + accessforbidden('', 0, 0, 1); +} // You can find your endpoint's secret in your webhook settings -if (isset($_GET['connect'])) -{ - if (isset($_GET['test'])) - { +if (isset($_GET['connect'])) { + if (isset($_GET['test'])) { $endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_CONNECT_KEY; $service = 'StripeTest'; $servicestatus = 0; @@ -56,8 +66,7 @@ if (isset($_GET['connect'])) $servicestatus = 1; } } else { - if (isset($_GET['test'])) - { + if (isset($_GET['test'])) { $endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_KEY; $service = 'StripeTest'; $servicestatus = 0; @@ -68,8 +77,7 @@ if (isset($_GET['connect'])) } } -if (empty($endpoint_secret)) -{ +if (empty($endpoint_secret)) { print 'Error: Setup of module Stripe not complete for mode '.$service.'. The WEBHOOK_KEY is not defined.'; http_response_code(400); // PHP 5.4 or greater exit(); @@ -107,18 +115,15 @@ $user = new User($db); $user->fetch($conf->global->STRIPE_USER_ACCOUNT_FOR_ACTIONS); $user->getrights(); -if (!empty($conf->multicompany->enabled) && !empty($conf->stripeconnect->enabled) && is_object($mc)) -{ +if (!empty($conf->multicompany->enabled) && !empty($conf->stripeconnect->enabled) && is_object($mc)) { $sql = "SELECT entity"; $sql .= " FROM ".MAIN_DB_PREFIX."oauth_token"; $sql .= " WHERE service = '".$db->escape($service)."' and tokenstring LIKE '%".$db->escape($event->account)."%'"; dol_syslog(get_class($db)."::fetch", LOG_DEBUG); $result = $db->query($sql); - if ($result) - { - if ($db->num_rows($result)) - { + if ($result) { + if ($db->num_rows($result)) { $obj = $db->fetch_object($result); $key = $obj->entity; } else { @@ -135,7 +140,9 @@ $stripe = new Stripe($db); // Subject $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; -if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $societeName = $conf->global->MAIN_APPLICATION_TITLE; +} dol_syslog("***** Stripe IPN was called with event->type = ".$event->type); @@ -146,8 +153,7 @@ if ($event->type == 'payout.created') { $result = dolibarr_set_const($db, $service."_NEXTPAYOUT", date('Y-m-d H:i:s', $event->data->object->arrival_date), 'chaine', 0, '', $conf->entity); - if ($result > 0) - { + if ($result > 0) { $subject = $societeName.' - [NOTIFICATION] Stripe payout scheduled'; if (!empty($user->email)) { $sendto = dolGetFirstLastname($user->firstname, $user->lastname)." <".$user->email.">"; @@ -189,8 +195,7 @@ if ($event->type == 'payout.created') { global $conf; $error = 0; $result = dolibarr_set_const($db, $service."_NEXTPAYOUT", null, 'chaine', 0, '', $conf->entity); - if ($result) - { + if ($result) { $langs->load("errors"); $dateo = dol_now(); @@ -205,8 +210,7 @@ if ($event->type == 'payout.created') { $accountto = new Account($db); $accountto->fetch($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS); - if (($accountto->id != $accountfrom->id) && empty($error)) - { + if (($accountto->id != $accountfrom->id) && empty($error)) { $bank_line_id_from = 0; $bank_line_id_to = 0; $result = 0; @@ -215,15 +219,31 @@ if ($event->type == 'payout.created') { $typefrom = 'PRE'; $typeto = 'VIR'; - if (!$error) $bank_line_id_from = $accountfrom->addline($dateo, $typefrom, $label, -1 * price2num($amount), '', '', $user); - if (!($bank_line_id_from > 0)) $error++; - if (!$error) $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amount), '', '', $user); - if (!($bank_line_id_to > 0)) $error++; + if (!$error) { + $bank_line_id_from = $accountfrom->addline($dateo, $typefrom, $label, -1 * price2num($amount), '', '', $user); + } + if (!($bank_line_id_from > 0)) { + $error++; + } + if (!$error) { + $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amount), '', '', $user); + } + if (!($bank_line_id_to > 0)) { + $error++; + } - if (!$error) $result = $accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, DOL_URL_ROOT.'/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert'); - if (!($result > 0)) $error++; - if (!$error) $result = $accountto->add_url_line($bank_line_id_to, $bank_line_id_from, DOL_URL_ROOT.'/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert'); - if (!($result > 0)) $error++; + if (!$error) { + $result = $accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, DOL_URL_ROOT.'/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert'); + } + if (!($result > 0)) { + $error++; + } + if (!$error) { + $result = $accountto->add_url_line($bank_line_id_to, $bank_line_id_from, DOL_URL_ROOT.'/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert'); + } + if (!($result > 0)) { + $error++; + } } $subject = $societeName.' - [NOTIFICATION] Stripe payout done'; @@ -252,7 +272,7 @@ if ($event->type == 'payout.created') { '', 0, -1 - ); + ); $ret = $mailfile->sendfile(); @@ -279,8 +299,7 @@ if ($event->type == 'payout.created') { // TODO: Redirect to paymentok.php } elseif ($event->type == 'payment_intent.payment_failed') { // TODO: Redirect to paymentko.php -} elseif ($event->type == 'checkout.session.completed') // Called when making payment with new Checkout method ($conf->global->STRIPE_USE_NEW_CHECKOUT is on). -{ +} elseif ($event->type == 'checkout.session.completed') { // Called when making payment with new Checkout method ($conf->global->STRIPE_USE_NEW_CHECKOUT is on). // TODO: create fees // TODO: Redirect to paymentok.php } elseif ($event->type == 'payment_method.attached') { @@ -291,8 +310,7 @@ if ($event->type == 'payout.created') { $companypaymentmode = new CompanyPaymentMode($db); $idthirdparty = $societeaccount->getThirdPartyID($db->escape($event->data->object->customer), 'stripe', $servicestatus); - if ($idthirdparty > 0) // If the payment mode is on an external customer that is known in societeaccount, we can create the payment mode - { + if ($idthirdparty > 0) { // If the payment mode is on an external customer that is known in societeaccount, we can create the payment mode $companypaymentmode->stripe_card_ref = $db->escape($event->data->object->id); $companypaymentmode->fk_soc = $idthirdparty; $companypaymentmode->bank = null; @@ -311,16 +329,13 @@ if ($event->type == 'payout.created') { $companypaymentmode->status = $servicestatus; $db->begin(); - if (!$error) - { + if (!$error) { $result = $companypaymentmode->create($user); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -345,16 +360,13 @@ if ($event->type == 'payout.created') { $companypaymentmode->status = $servicestatus; $db->begin(); - if (!$error) - { + if (!$error) { $result = $companypaymentmode->update($user); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); diff --git a/htdocs/theme/eldy/doc/badges.php b/htdocs/public/test/badges.php similarity index 90% rename from htdocs/theme/eldy/doc/badges.php rename to htdocs/public/test/badges.php index 52a422a053c..fd0add00af1 100644 --- a/htdocs/theme/eldy/doc/badges.php +++ b/htdocs/public/test/badges.php @@ -1,39 +1,55 @@ <?php - -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); -if (!defined('NOLOGIN')) define('NOLOGIN', 1); // File must be accessed by logon page so without login -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', 1); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', 1); // File must be accessed by logon page so without login +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', 1); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} session_cache_limiter('public'); -require_once '../../../main.inc.php'; +require_once '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; +if ($dolibarr_main_prod) { + accessforbidden(); +} + ?> <!doctype html> <html lang="en"> <head> - <meta charset="utf-8"> + <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="Documentation and examples for theme."> - - <link href="../style.css.php" rel="stylesheet"> - <link href="doc.css" rel="stylesheet"> + <link href="<?php echo DOL_URL_ROOT ?>/theme/eldy/style.css.php" rel="stylesheet"> </head> - <body class="docpage" > - - <main role="main" > - <h1 class="bd-title" id="content">Badges</h1> - <p class="bd-lead">Documentation and examples for badges, our small count and labeling component.</p> + <body class="docpage" style="padding: 20px;"> - <h2 id="example">Example</h2> + <main role="main" > + <h1 class="bd-title" id="content">Badges</h1> + <p class="bd-lead">Documentation and examples for badges, our small count and labeling component.</p> + + <h2 id="example">Example</h2> <p>Badges scale to match the size of the immediate parent element by using relative font sizing and em units.</p> - + <div class="bd-example"> <h1>Example heading <span class="badge badge-secondary">New</span></h1> <h2>Example heading <span class="badge badge-secondary">New</span></h2> @@ -42,39 +58,39 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; <h5>Example heading <span class="badge badge-secondary">New</span></h5> <h6>Example heading <span class="badge badge-secondary">New</span></h6> </div> - + <figure class="highlight"> - <pre> - + <pre> + &lt;h1&gt;Example heading &lt;span class=&quot;badge badge-secondary&quot;&gt;New&lt;/span&gt;&lt;/h1&gt; &lt;h2&gt;Example heading &lt;span class=&quot;badge badge-secondary&quot;&gt;New&lt;/span&gt;&lt;/h2&gt; &lt;h3&gt;Example heading &lt;span class=&quot;badge badge-secondary&quot;&gt;New&lt;/span&gt;&lt;/h3&gt; &lt;h4&gt;Example heading &lt;span class=&quot;badge badge-secondary&quot;&gt;New&lt;/span&gt;&lt;/h4&gt; &lt;h5&gt;Example heading &lt;span class=&quot;badge badge-secondary&quot;&gt;New&lt;/span&gt;&lt;/h5&gt; &lt;h6&gt;Example heading &lt;span class=&quot;badge badge-secondary&quot;&gt;New&lt;/span&gt;&lt;/h6&gt; - - </pre> + + </pre> </figure> - + <p>Badges can be used as part of links or buttons to provide a counter.</p> - + <div class="bd-example"> <button type="button" class="button"> Notifications <span class="badge badge-primary">4</span> </button> </div> - + <figure class="highlight"><pre> &lt;button type=&quot;button&quot; class=&quot;button&quot;&gt; Notifications &lt;span class=&quot;badge badge-primary&quot;&gt;4&lt;/span&gt; &lt;/button&gt; </pre></figure> - - <div class="warning"> + + <div class="warning"> <p>Note that depending on how they are used, badges may be confusing for users of screen readers and similar assistive technologies. While the styling of badges provides a visual cue as to their purpose, these users will simply be presented with the content of the badge. Depending on the specific situation, these badges may seem like random additional words or numbers at the end of a sentence, link, or button.</p> - + <p>Unless the context is clear (as with the “Notifications” example, where it is understood that the “4” is the number of notifications), consider including additional context with a visually hidden piece of additional text.</p> - + <p><strong>Remember to use aria-label attribute for accessibility in Dolibarr. Don't forget to use aria-hidden on icons included in badges</strong></p> </div> @@ -84,26 +100,26 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; <span class="sr-only">unread messages</span> </button> </div> - + <figure class="highlight"> - <pre> - - + <pre> + + &lt;button type=&quot;button&quot; class=&quot;btn btn-primary&quot;&gt; Profile &lt;span class=&quot;badge badge-light&quot; aria-label=&quot;9 unread messages&quot; &gt;9&lt;/span&gt; &lt;span class=&quot;sr-only&quot;&gt;unread messages&lt;/span&gt; &lt;/button&gt; - - - </pre> + + + </pre> </figure> - + <h2 id="contextual-variations">Contextual variations</h2> - + <p>Add any of the below mentioned modifier classes to change the appearance of a badge.</p> - + <div class="bd-example"> - + <span class="badge badge-primary">Primary</span> <span class="badge badge-secondary">Secondary</span> <span class="badge badge-success">Success</span> @@ -113,10 +129,10 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; <span class="badge badge-light">Light</span> <span class="badge badge-dark">Dark</span> </div> - + <figure class="highlight"> - <pre> - + <pre> + &lt;span class=&quot;badge badge-primary&quot;&gt;Primary&lt;/span&gt; &lt;span class=&quot;badge badge-secondary&quot;&gt;Secondary&lt;/span&gt; &lt;span class=&quot;badge badge-success&quot;&gt;Success&lt;/span&gt; @@ -125,41 +141,41 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; &lt;span class=&quot;badge badge-info&quot;&gt;Info&lt;/span&gt; &lt;span class=&quot;badge badge-light&quot;&gt;Light&lt;/span&gt; &lt;span class=&quot;badge badge-dark&quot;&gt;Dark&lt;/span&gt; - - </pre> + + </pre> </figure> - + <div class="warning"> <h5 id="conveying-meaning-to-assistive-technologies">Conveying meaning to assistive technologies</h5> - + <p>Using color to add meaning only provides a visual indication, which will not be conveyed to users of assistive technologies – such as screen readers. Ensure that information denoted by the color is either obvious from the content itself (e.g. the visible text), or is included through alternative means, such as additional text hidden with the .sr-only class.</p> </div> - - + + <h2 id="contextual-variations">Default status</h2> - + <p>Add any of the below mentioned modifier classes to change the appearance of a badge to be linked to a default status.</p> - + <div class="bd-example"> - <?php for ($i = 0; $i <= 9; $i++): ?> + <?php for ($i = 0; $i <= 9; $i++) : ?> <span class="badge badge-status<?php print $i; ?>" >status-<?php print $i; ?></span> <?php endfor; ?> </div> <figure class="highlight"><pre><pre> -<?php for ($i = 0; $i <= 9; $i++): ?> +<?php for ($i = 0; $i <= 9; $i++) : ?> &lt;span class="badge badge-status<?php print $i; ?>" &gt;status<?php print $i; ?>&lt;/span&gt; <?php endfor; ?> </pre></figure> - - + + <h2 id="pill-badges">Pill badges</h2> - + <p>Use the .badge-pill modifier class to make badges more rounded (with a larger border-radius and additional horizontal padding).</p> - + <div class="bd-example"> - + <span class="badge badge-pill badge-primary">Primary</span> <span class="badge badge-pill badge-secondary">Secondary</span> <span class="badge badge-pill badge-success">Success</span> @@ -168,16 +184,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; <span class="badge badge-pill badge-info">Info</span> <span class="badge badge-pill badge-light">Light</span> <span class="badge badge-pill badge-dark">Dark</span> - - <?php for ($i = 0; $i <= 9; $i++): ?> + + <?php for ($i = 0; $i <= 9; $i++) : ?> <span class="badge badge-pill badge-status<?php print $i; ?>" >status<?php print $i; ?></span> <?php endfor; ?> - + </div> - + <figure class="highlight"> <pre> - + &lt;span class=&quot;badge badge-pill badge-primary&quot;&gt;Primary&lt;/span&gt; &lt;span class=&quot;badge badge-pill badge-secondary&quot;&gt;Secondary&lt;/span&gt; &lt;span class=&quot;badge badge-pill badge-success&quot;&gt;Success&lt;/span&gt; @@ -186,19 +202,19 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; &lt;span class=&quot;badge badge-pill badge-info&quot;&gt;Info&lt;/span&gt; &lt;span class=&quot;badge badge-pill badge-light&quot;&gt;Light&lt;/span&gt; &lt;span class=&quot;badge badge-pill badge-dark&quot;&gt;Dark&lt;/span&gt; -<?php for ($i = 0; $i <= 9; $i++): ?> +<?php for ($i = 0; $i <= 9; $i++) : ?> &lt;span class="badge badge-pill badge-status<?php print $i; ?>" &gt;status<?php print $i; ?>&lt;/span&gt; <?php endfor; ?> </pre></figure> - - - + + + <h2 id="dot-badges">Dot badges</h2> - + <p>.dot-pill modifier class to make badges circle.</p> - + <div class="bd-example"> - + <span class="badge badge-dot badge-primary"></span> <span class="badge badge-dot badge-secondary"></span> <span class="badge badge-dot badge-success"></span> @@ -207,16 +223,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; <span class="badge badge-dot badge-info"></span> <span class="badge badge-dot badge-light"></span> <span class="badge badge-dot badge-dark"></span> - - <?php for ($i = 0; $i <= 9; $i++): ?> + + <?php for ($i = 0; $i <= 9; $i++) : ?> <span class="badge badge-dot badge-status<?php print $i; ?>" ></span> <?php endfor; ?> - + </div> - + <figure class="highlight"> <pre> - + &lt;span class=&quot;badge badge-dot badge-primary&quot;&gt;&lt;/span&gt; &lt;span class=&quot;badge badge-dot badge-secondary&quot;&gt;&lt;/span&gt; &lt;span class=&quot;badge badge-dot badge-success&quot;&gt;&lt;/span&gt; @@ -225,27 +241,27 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; &lt;span class=&quot;badge badge-dot badge-info&quot;&gt;&lt;/span&gt; &lt;span class=&quot;badge badge-dot badge-light&quot;&gt;&lt;/span&gt; &lt;span class=&quot;badge badge-dot badge-dark&quot;&gt;&lt;/span&gt; -<?php for ($i = 0; $i <= 9; $i++): ?> +<?php for ($i = 0; $i <= 9; $i++) : ?> &lt;span class="badge badge-dot badge-status<?php print $i; ?>" &gt;&lt;/span&gt; <?php endfor; ?> </pre></figure> - - -<div class="warning"> + + +<div class="warning"> <p>Note that depending on how they are used, badges may be confusing for users of screen readers and similar assistive technologies. While the styling of badges provides a visual cue as to their purpose, these users will simply be presented with the content of the badge. Depending on the specific situation, these badges may seem like random additional words or numbers at the end of a sentence, link, or button.</p> - + <p>Unless the context is clear (as with the “Notifications” example, where it is understood that the “4” is the number of notifications), consider including additional context with a visually hidden piece of additional text.</p> - + <p><strong>Remember to use aria-label attribute for accessibility in Dolibarr. Don't forget to use aria-hidden on icons included in badges</strong></p> -</div> - - +</div> + + <h2 id="links">Links</h2> - + <p>Using the contextual .badge-* classes on an &lt;a&gt; element quickly provide <em>actionable</em> badges with hover and focus states.</p> - + <div class="bd-example"> - + <a href="#" class="badge badge-primary">Primary</a> <a href="#" class="badge badge-secondary">Secondary</a> <a href="#" class="badge badge-success">Success</a> @@ -254,12 +270,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; <a href="#" class="badge badge-info">Info</a> <a href="#" class="badge badge-light">Light</a> <a href="#" class="badge badge-dark">Dark</a> - <?php for ($i = 0; $i <= 9; $i++): ?> + <?php for ($i = 0; $i <= 9; $i++) : ?> <a href="#" class="badge badge-status<?php print $i; ?>" >status<?php print $i; ?></a> <?php endfor; ?> - + </div> - + <figure class="highlight"><pre> &lt;a href=&quot;#&quot; class=&quot;badge badge-primary&quot;&gt;Primary&lt;/a&gt; &lt;a href=&quot;#&quot; class=&quot;badge badge-secondary&quot;&gt;Secondary&lt;/a&gt; @@ -269,7 +285,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; &lt;a href=&quot;#&quot; class=&quot;badge badge-info&quot;&gt;Info&lt;/a&gt; &lt;a href=&quot;#&quot; class=&quot;badge badge-light&quot;&gt;Light&lt;/a&gt; &lt;a href=&quot;#&quot; class=&quot;badge badge-dark&quot;&gt;Dark&lt;/a&gt; -<?php for ($i = 0; $i <= 9; $i++): ?> +<?php for ($i = 0; $i <= 9; $i++) : ?> &lt;a href=&quot;#&quot; class="badge badge-status<?php print $i; ?>" &gt;status<?php print $i; ?>&lt;/a&gt; <?php endfor; ?> </pre></figure> @@ -280,12 +296,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; <?php print dolGetBadge('your label for accessibility', 'your label <u>with</u> <em>html</em>', 'primary') ?> <?php print dolGetBadge('your label for accessibility', 'your label <u>with</u> <em>html</em>', 'danger', 'pill') ?> <?php print dolGetBadge('your label for accessibility', 'your label <u>with</u> <em>html</em>', 'warning', 'dot') ?> - + <figure class="highlight"><pre> &lt;?php print dolGetBadge('your label for accessibility', 'your label &lt;u&gt;with&lt;/u&gt; &lt;em&gt;html&lt;/em&gt;', 'danger', 'pill') ?&gt; &lt;?php print dolGetBadge('your label for accessibility', 'your label &lt;u&gt;with&lt;/u&gt; &lt;em&gt;html&lt;/em&gt;', 'warning', 'dot') ?&gt; </pre></figure> - + <h2 id="helper">Use status helper function</h2> <p>Using the dolGetStatus function provide in core/lib/functions.lib.php. This function is recommended for code uniformisation and easy maintain</p> <?php @@ -311,8 +327,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; <p><?php print dolGetStatus('your label for accessibility', 'your label', 'your label <u>with</u> <em>html</em>', 'status4', 6) ?></p> <?php $conf->global->MAIN_STATUS_USES_CSS = $saveGlobalConf; ?> - - + + <figure class="highlight"><pre> &lt;?php print dolGetStatus('your label for accessibility', 'your label', 'your label &lt;u&gt;with&lt;/u&gt; &lt;em&gt;html&lt;/em&gt;', 'status4') ?&gt; &lt;?php print dolGetStatus('your label for accessibility', 'your label', 'your label &lt;u&gt;with&lt;/u&gt; &lt;em&gt;html&lt;/em&gt;', 'status4',1) ?&gt; @@ -323,8 +339,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; &lt;?php print dolGetStatus('your label for accessibility', 'your label', 'your label &lt;u&gt;with&lt;/u&gt; &lt;em&gt;html&lt;/em&gt;', 'status4',6) ?&gt; </pre></figure> - - </main> - + + </main> + </body> </html> \ No newline at end of file diff --git a/htdocs/public/test/test_arrays.php b/htdocs/public/test/test_arrays.php index 95265831670..b2a87a75480 100644 --- a/htdocs/public/test/test_arrays.php +++ b/htdocs/public/test/test_arrays.php @@ -1,6 +1,27 @@ <?php //define("NOLOGIN",1); // This means this output page does not require to be logged. -define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +//if (!defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); +//if (!defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +//if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); +if (!defined('NOSTYLECHECK')) { + define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test +} +//if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +if (!defined("NOLOGIN")) { + define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) +} + require '../../main.inc.php'; @@ -18,8 +39,7 @@ $form = new Form($db); // HEADER //-------- -if (empty($usedolheader)) -{ +if (empty($usedolheader)) { header("Content-type: text/html; charset=UTF8"); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> @@ -64,7 +84,7 @@ if (empty($usedolheader)) '/includes/pdfmake/pdfmake.min.js', '/includes/pdfmake/vfs_fonts.js' ); - */ + */ llxHeader('', '', '', '', 0, 0, $arrayjs, $arraycss); } @@ -76,14 +96,14 @@ if (empty($usedolheader)) <h2> This page is a sample of page using tables. It is designed to make test with<br> +</h2> +<div class="wordbreak"> - css (add parameter &amp;theme=newtheme to test another theme or edit css of current theme)<br> -- jmobile (add parameter <a href="<?php echo $_SERVER["PHP_SELF"].'?dol_use_jmobile=4&dol_optimize_smallscreen=1'; ?>">dol_use_jmobile=4&amp;dol_optimize_smallscreen=1</a> and switch to small screen < 1000 to enable view with jmobile)<br> - jmobile (add parameter <a href="<?php echo $_SERVER["PHP_SELF"].'?dol_use_jmobile=1&dol_optimize_smallscreen=1'; ?>">dol_use_jmobile=1&amp;dol_optimize_smallscreen=1</a> and switch to small screen < 570 to enable with emulated jmobile)<br> - no javascript / usage for bind people (add parameter <a href="<?php echo $_SERVER["PHP_SELF"].'?nojs=1'; ?>">nojs=1</a> to force disable javascript)<br> - tablednd<br> -</h2> +</div> -<?php ?> <br><hr><br>Example 0a : Table with div+div+div containg a select that should be overflowed and truncated => Use this to align text or form<br> @@ -114,17 +134,16 @@ This page is a sample of page using tables. It is designed to make test with<br> <br><hr><br>Example 0c: Table with table+tr+td containg a select that should be overflowed and truncated => Use this to align text or form<br> <table class="centpercent"> - <tr> - <td class="tagtd maxwidthonsmartphone" style="overflow: hidden; white-space: nowrap;"> <!-- If you remove max-width, the jmobile overflow does not work --> + <tr> + <td class="tagtd maxwidthonsmartphone" style="overflow: hidden; white-space: nowrap;"> <!-- If you remove max-width, the jmobile overflow does not work --> <select name="hidedetails" class="centpercentonsmartphone"><option>aaaaaaaaaaaaaaafd sf sf gfd gfds fsd gfd fhfg hf dhfg hg fhfgdhfgdh gh gfdhdgf h gfdh dfhg dfgh dfgh fdgh gfd hfd hfd gs fgdf gaaaa</option><option>gdfs gdf g sdfg dfg fdsg dsfg dfs gdfs gds fgs gdfdf gd</option></select> - </td> - <td class="tagtd maxwidthonsmartphone" style="overflow: hidden; white-space: nowrap;"> <!-- If you remove max-width, the jmobile overflow does not work --> + </td> + <td class="tagtd maxwidthonsmartphone" style="overflow: hidden; white-space: nowrap;"> <!-- If you remove max-width, the jmobile overflow does not work --> <select name="hidedetails" class="centpercentonsmartphone"><option>aaaaaaaaaaaaaaafd sf sf gfd gfds fsd gfd fhfg hf dhfg hg fhfgdhfgdh gh gfdhdgf h gfdh dfhg dfgh dfgh fdgh gfd hfd hfd gs fgdf gaaaa</option><option>gdfs gdf g sdfg dfg fdsg dsfg dfs gdfs gds fgs gdfdf gd</option></select> - </td> - </tr> + </td> + </tr> </table> -<?php ?> @@ -134,16 +153,16 @@ This page is a sample of page using tables. It is designed to make test with<br> <script type="text/javascript" language="javascript"> /*jQuery(document).ready(function() { $(document).ready(function() { - var table = $('#tablelines3').DataTable( { - scrollY: "300px", - scrollX: true, - scrollCollapse: true, - paging: false, - fixedColumns: { - leftColumns: 1, - rightColumns: 1 - } - } ); + var table = $('#tablelines3').DataTable( { + scrollY: "300px", + scrollX: true, + scrollCollapse: true, + paging: false, + fixedColumns: { + leftColumns: 1, + rightColumns: 1 + } + } ); } ); });*/ </script> @@ -153,58 +172,77 @@ $(document).ready(function() { include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $productspecimen = new Product($db); $productspecimen->initAsSpecimen(); +$object = $productspecimen; $sortfield = 'aaa'; $sortorder = 'ASC'; $tasksarray = array(1, 2, 3); // To force having several lines $tagidfortablednd = 'tablelines3'; -if (!empty($conf->use_javascript_ajax)) include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; +if (!empty($conf->use_javascript_ajax)) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; +} $nav = ''; $nav .= '<form name="dateselect" action="'.$_SERVER["PHP_SELF"].'?action=show_peruser'.$param.'">'; -if ($actioncode || GETPOSTISSET('actioncode')) $nav .= '<input type="hidden" name="actioncode" value="'.$actioncode.'">'; -if ($status || GETPOSTISSET('status')) $nav .= '<input type="hidden" name="status" value="'.$status.'">'; -if ($filter) $nav .= '<input type="hidden" name="filter" value="'.$filter.'">'; -if ($filtert) $nav .= '<input type="hidden" name="filtert" value="'.$filtert.'">'; -if ($socid) $nav .= '<input type="hidden" name="socid" value="'.$socid.'">'; -if ($showbirthday) $nav .= '<input type="hidden" name="showbirthday" value="1">'; -if ($pid) $nav .= '<input type="hidden" name="projectid" value="'.$pid.'">'; -if ($type) $nav .= '<input type="hidden" name="type" value="'.$type.'">'; -if ($usergroup) $nav .= '<input type="hidden" name="usergroup" value="'.$usergroup.'">'; +if ($actioncode || GETPOSTISSET('actioncode')) { + $nav .= '<input type="hidden" name="actioncode" value="'.$actioncode.'">'; +} +if ($status || GETPOSTISSET('status')) { + $nav .= '<input type="hidden" name="status" value="'.$status.'">'; +} +if ($filter) { + $nav .= '<input type="hidden" name="filter" value="'.$filter.'">'; +} +if ($filtert) { + $nav .= '<input type="hidden" name="filtert" value="'.$filtert.'">'; +} +if ($socid) { + $nav .= '<input type="hidden" name="socid" value="'.$socid.'">'; +} +if ($showbirthday) { + $nav .= '<input type="hidden" name="showbirthday" value="1">'; +} +if ($pid) { + $nav .= '<input type="hidden" name="projectid" value="'.$pid.'">'; +} +if ($type) { + $nav .= '<input type="hidden" name="type" value="'.$type.'">'; +} +if ($usergroup) { + $nav .= '<input type="hidden" name="usergroup" value="'.$usergroup.'">'; +} $nav .= $form->selectDate($dateselect, 'dateselect', 0, 0, 1, '', 1, 0); $nav .= ' <input type="submit" name="submitdateselect" class="button" value="'.$langs->trans("Refresh").'">'; $nav .= '</form>'; $limit = 10; -print_barre_liste('Title of my list', 12, $_SERVER["PHP_SELF"], '', '', '', 'Text in middle', 20, 500, '', 0, $nav, '', $limit); - +print_barre_liste('Title of my list', 12, $_SERVER["PHP_SELF"], '', '', '', 'Text in middle', 20, 500, '', 0, $nav, '', $limit, 0, 0, 1); $moreforfilter .= '<div class="divsearchfield">'; -$moreforfilter .= $langs->trans('This is a select list for a filter A').': '; +$moreforfilter .= $langs->trans('This is a select list for a filter A (no combo forced)').': '; $cate_arbo = array('field1'=>'value1a into the select list A', 'field2'=>'value2a'); -$moreforfilter .= $form->selectarray('search_aaa', $cate_arbo, '', 1); // List without js combo +$moreforfilter .= $form->selectarray('search_aaa', $cate_arbo, '', 1, 0, 0, '', 0, 0, 0, '', 'maxwidth300', 0); // List with no js combo $moreforfilter .= '</div>'; $moreforfilter .= '<div class="divsearchfield">'; -$moreforfilter .= $langs->trans('This is a select list for a filter B').': '; +$moreforfilter .= $langs->trans('This is a select list for a filter B (auto combo)').': '; $cate_arbo = array('field1'=>'value1b into the select list B', 'field2'=>'value2b'); -$moreforfilter .= $form->selectarray('search_bbb', $cate_arbo, '', 1, 0, 0, '', 0, 0, 0, 0, '', 1); // List with js combo +$moreforfilter .= $form->selectarray('search_bbb', $cate_arbo, '', 1, 0, 0, '', 0, 0, 0, '', 'maxwidth300', -1); // List with js combo auto $moreforfilter .= '</div>'; $moreforfilter .= '<div class="divsearchfield">'; -$moreforfilter .= $langs->trans('This is a select list for a filter C').': '; +$moreforfilter .= $langs->trans('This is a select list for a filter C (combo forced)').': '; $cate_arbo = array('field1'=>'value1c into the select list C', 'field2'=>'value2c'); -$moreforfilter .= $form->selectarray('search_ccc', $cate_arbo, '', 1, 0, 0, '', 0, 0, 0, 0, '', 1); // List with js combo +$moreforfilter .= $form->selectarray('search_ccc', $cate_arbo, '', 1, 0, 0, '', 0, 0, 0, '', 'maxwidth300', 1); // List with js combo forced $moreforfilter .= '</div>'; $moreforfilter .= '<div class="divsearchfield">'; -$moreforfilter .= $langs->trans('This is a select list for a filter D').': '; +$moreforfilter .= $langs->trans('This is a select list for a filter D (combo forced)').': '; $cate_arbo = array('field1'=>'value1d into the select list D', 'field2'=>'value2d'); -$moreforfilter .= $form->selectarray('search_ddd', $cate_arbo, '', 1, 0, 0, '', 0, 0, 0, 0, '', 1); // List with js combo +$moreforfilter .= $form->selectarray('search_ddd', $cate_arbo, '', 1, 0, 0, '', 0, 0, 0, '', 'maxwidth300', 1); // List with js combo forced $moreforfilter .= '</div>'; -if (!empty($moreforfilter)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; $parameters = array(); @@ -219,14 +257,14 @@ if (!empty($moreforfilter)) <thead> <tr class="liste_titre"> <?php print getTitleFieldOfList($langs->trans('title1'), 0, $_SERVER["PHP_SELF"], 'aaa', '', '', 'align="left"', $sortfield, $sortorder); ?> -<?php print getTitleFieldOfList($langs->trans('title2'), 0, $_SERVER["PHP_SELF"], 'bbb', '', '', 'align="right"', $sortfield, $sortorder); ?> -<?php print getTitleFieldOfList($langs->trans('title3'), 0, $_SERVER["PHP_SELF"], 'ccc', '', '', 'align="center"', $sortfield, $sortorder); ?> +<?php print getTitleFieldOfList($langs->trans('title2'), 0, $_SERVER["PHP_SELF"], 'bbb', '', '', 'align="center"', $sortfield, $sortorder); ?> +<?php print getTitleFieldOfList($langs->trans('title3'), 0, $_SERVER["PHP_SELF"], 'ccc', '', '', 'align="right"', $sortfield, $sortorder); ?> </tr> </thead> <tbody> -<tr class="pair"><td><?php echo $productspecimen->getNomUrl(1); ?></td><td class="right">b1</td><td class="tdlineupdown left">c1</td></tr> -<tr class="impair nowrap"><td>a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2</td><td align="right">b2</td><td class="tdlineupdown left">c2</td></tr> -<tr class="pair"><td>a3</td><td class="right">b3</td><td class="tdlineupdown left">c3</td></tr> +<tr class="pair"><td><?php echo $productspecimen->getNomUrl(1); ?></td><td class="center">b1</td><td class="tdlineupdown right">c1</td></tr> +<tr class="impair nowrap"><td>a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2 a2</td><td align="center">b2</td><td class="tdlineupdown right">c2</td></tr> +<tr class="pair"><td>a3</td><td class="center">b3</td><td class="tdlineupdown right">c3</td></tr> </tbody> </table> @@ -237,22 +275,20 @@ if (!empty($moreforfilter)) <!-- <br><hr><br>Example 1b : Table using tags: table/thead/tbody/tr/th-td + dataTable => Use this for short result tables<br> - - <script type="text/javascript"> $(document).ready(function(){ - $('#idtableexample2').dataTable( { - <?php + $('#idtableexample2').dataTable( { + <?php if ($optioncss == 'print') { - print '\'dom\': \'lfrtip\','; + print '\'dom\': \'lfrtip\','; } else { print '\'dom\': \'Blfrtip\','; } ?> - "colReorder": true, + "colReorder": true, 'buttons': [ - 'colvis','copy', 'csv', 'excel', 'pdf', 'print' - ], + 'colvis','copy', 'csv', 'excel', 'pdf', 'print' + ], "sPaginationType": "full_numbers", "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "<?php echo $langs->trans('All'); ?>"]], "oLanguage": { @@ -276,13 +312,12 @@ $(document).ready(function(){ "bServerSide": true, "sAjaxSource": "../ajax.php", "aoColumnDefs": [ - { "bSortable": false, "aTargets": [ 2,3,4 ] } - ], + { "bSortable": false, "aTargets": [ 2,3,4 ] } + ], */ - }) + }) }); </script> - --> @@ -292,54 +327,55 @@ $(document).ready(function(){ <?php $tasksarray = array(1, 2, 3); // To force having several lines $tagidfortablednd = 'tablelines'; - if (!empty($conf->use_javascript_ajax)) include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; +if (!empty($conf->use_javascript_ajax)) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; +} ?> <div class="tagtable centpercent liste_titre_bydiv" id="tablelines"> - <div class="tagtr liste_titre"> - <div class="tagtd">Title A<input type="hidden" name="cartitem" value="3"></div> - <div class="tagtd">title B</div> - <div class="tagtd">title C</div> - <div class="tagtd">title D</div> - </div> - <div class="pair tagtr"> - <div class="tagtd">line4<input type="hidden" name="cartitem" value="3"></div> - <div class="tagtd">dfsdf</div> - <div class="tagtd"><input name="count" value="4"></div> - <div class="tagtd tdlineupdown">bbbb</div> - </div> - <div class="impair tagtr"> - <div class="tagtd">line5<input type="hidden" name="cartitemb" value="3"></div> - <div class="tagtd">dfsdf</div> - <div class="tagtd"><input name="countb" value="4"></div> - <div class="tagtd tdlineupdown">bbbb</div> - </div> - <div class="pair tagtr"> - <div class="tagtd">line6<input type="hidden" name="cartitem" value="3"></div> - <div class="tagtd">jghjgh</div> - <div class="tagtd">5</div> - <div class="tagtd tdlineupdown">lll</div> - </div> + <div class="tagtr liste_titre"> + <div class="tagtd">Title A<input type="hidden" name="cartitem" value="3"></div> + <div class="tagtd">title B</div> + <div class="tagtd">title C</div> + <div class="tagtd">title D</div> + </div> + <div class="pair tagtr"> + <div class="tagtd">line4<input type="hidden" name="cartitem" value="3"></div> + <div class="tagtd">dfsdf</div> + <div class="tagtd"><input name="count" value="4" class="maxwidth50"></div> + <div class="tagtd tdlineupdown">bbbb</div> + </div> + <div class="impair tagtr"> + <div class="tagtd">line5<input type="hidden" name="cartitemb" value="3"></div> + <div class="tagtd">dfsdf</div> + <div class="tagtd"><input name="countb" value="4" class="maxwidth50"></div> + <div class="tagtd tdlineupdown">bbbb</div> + </div> + <div class="pair tagtr"> + <div class="tagtd">line6<input type="hidden" name="cartitem" value="3"></div> + <div class="tagtd">jghjgh</div> + <div class="tagtd">5</div> + <div class="tagtd tdlineupdown">lll</div> + </div> <!-- Using form into div make Firefox crazy (page loading does not end) --> <!-- <form class="liste_titre" method="POST" action="1.php"> - <div>line1<input type="hidden" name="cartitem" value="1"></div> - <div><label><input type="checkbox" name="hidedetails" value="2"> A checkbox inside a cell</label></div> - <div><input name="count" value="4"></div> - <div><input type="submit" name="count2" class="button noshadow" value="aaa"></div> - </form> - <form class="impair" method="POST" action="2.php"> - <div>line2<input type="hidden" name="cartitem" value="2"></div> - <div><select name="hidedetails"><option>aaaaaaaaaaaaaaafd sf sf gfd gfd gs fgdf gaaaa</option><option>gdfs gdf g sdfg dfg fdsg dsfg dfs gdfs gds fgs gdfdf gd</option></select></div> - <div><input name="countb" value="4"></div> - <div class="tdlineupdown"><input type="submit" value="xxx" class="button"></div> - </form>--> + <div>line1<input type="hidden" name="cartitem" value="1"></div> + <div><label><input type="checkbox" name="hidedetails" value="2"> A checkbox inside a cell</label></div> + <div><input name="count" value="4"></div> + <div><input type="submit" name="count2" class="button noshadow" value="aaa"></div> + </form> + <form class="impair" method="POST" action="2.php"> + <div>line2<input type="hidden" name="cartitem" value="2"></div> + <div><select name="hidedetails"><option>aaaaaaaaaaaaaaafd sf sf gfd gfd gs fgdf gaaaa</option><option>gdfs gdf g sdfg dfg fdsg dsfg dfs gdfs gds fgs gdfdf gd</option></select></div> + <div><input name="countb" value="4"></div> + <div class="tdlineupdown"><input type="submit" value="xxx" class="button"></div> + </form>--> </div> <?php -if (!empty($usedolheader)) -{ +if (!empty($usedolheader)) { llxFooter(); } else { ?> </body> diff --git a/htdocs/public/test/test_csrf.php b/htdocs/public/test/test_csrf.php index 8c242cade64..1c23dc7070a 100644 --- a/htdocs/public/test/test_csrf.php +++ b/htdocs/public/test/test_csrf.php @@ -3,14 +3,16 @@ ?> -This is a form to test a CSRF.<br> +This is a form to test if a CSRF exists into a Dolibarr page.<br> <br> -Open this form into a Virtual server A.<br> -Change url to send request to into file to send request to virtual server B.<br> +- Change url to send request to into this file (server B, hard coded page)<br> +- Open this form into a virtual server A.<br> +- Send the request to the virtual server B by clicking submit.<br> +- Check that Anticsrf protection is triggered.<br> <br> <?php - $urltosendrequest = "http://localhostgit/dolibarr_dev/htdocs/user/group/card.php"; + $urltosendrequest = "http://127.0.0.1/dolibarr/htdocs/user/group/card.php"; print 'urltosendrequest = '.$urltosendrequest.'<br><br>'; ?> diff --git a/htdocs/public/test/test_forms.php b/htdocs/public/test/test_forms.php index bd74ecb0f13..d89e04e12a6 100644 --- a/htdocs/public/test/test_forms.php +++ b/htdocs/public/test/test_forms.php @@ -1,7 +1,9 @@ <?php //define("NOLOGIN",1); // This means this output page does not require to be logged. define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -define('REQUIRE_JQUERY_MULTISELECT', 'select2'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} require '../../main.inc.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; diff --git a/htdocs/public/test/test_sessionlock.php b/htdocs/public/test/test_sessionlock.php index b10d1e892ec..18a1ef73d08 100644 --- a/htdocs/public/test/test_sessionlock.php +++ b/htdocs/public/test/test_sessionlock.php @@ -1,37 +1,68 @@ <?php - -if (!defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); -if (!defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); -if (!defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library -if (!defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) +if (!defined('NOREQUIREUSER')) { + define('NOREQUIREUSER', '1'); +} +if (!defined('NOREQUIREDB')) { + define('NOREQUIREDB', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOREQUIRETRAN')) { + define('NOREQUIRETRAN', '1'); +} +if (!defined('NOSTYLECHECK')) { + define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +} +if (!defined("NOLOGIN")) { + define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) +} // If you don't need session management (can't be logged if no session used). You must also set // NOCSRFCHECK, NOTOKENRENEWAL, NOLOGIN // Disable module with GETPOST('disablemodules') won't work. Variable 'dol_...' will not be set. // $_SESSION are then simple vars if sessions are not active. -// TODO We can close session with session_write_close() as soon as we just need read access. -if (!defined("NOSESSION")) define("NOSESSION", '1'); +// TODO We can close session with session_write_close() as soon as we just need read access everywhere in code. +if (!defined("NOSESSION")) { + define("NOSESSION", '1'); +} -define('REQUIRE_JQUERY_MULTISELECT', 'select2'); - -print PHP_SESSION_DISABLED; -print PHP_SESSION_NONE; -print PHP_SESSION_ACTIVE; +print "Legend:<br>\n"; +print 'PHP_SESSION_DISABLED='.PHP_SESSION_DISABLED."<br>\n"; +print 'PHP_SESSION_NONE='.PHP_SESSION_NONE."<br>\n"; +print 'PHP_SESSION_ACTIVE='.PHP_SESSION_ACTIVE."<br>\n"; +print '<br>'; + +print 'session_status='.session_status().' (before main.inc.php)'; print '<br>'; -print session_status(); require '../../main.inc.php'; -print session_status(); + +/* No need for this. +if ($dolibarr_main_prod) { + accessforbidden(); +} +*/ + +print 'session_status='.session_status().' (after main.inc.php)'; print '<br>'; //print 'a'.$_SESSION['disablemodules'].'b'; -print 'This page is visible. It means you are not locked.'; +print "\n<br>This page is visible. It means you are not locked by another page called in same session."; //session_write_close(); diff --git a/htdocs/public/ticket/create_ticket.php b/htdocs/public/ticket/create_ticket.php index 1c81faca1ad..5b7ba4ecf22 100644 --- a/htdocs/public/ticket/create_ticket.php +++ b/htdocs/public/ticket/create_ticket.php @@ -22,14 +22,30 @@ * \brief Display public form to add new ticket */ -if (!defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOREQUIREUSER')) { + define('NOREQUIREUSER', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); // This means this output page does not require to be logged. +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} require '../../main.inc.php'; @@ -143,6 +159,17 @@ if (empty($reshook) && $action == 'create_ticket' && GETPOST('add', 'alpha')) { $action = ''; } + // Check Captcha code if is enabled + if (!empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA)) { + $sessionkey = 'dol_antispam_value'; + $ok = (array_key_exists($sessionkey, $_SESSION) === true && (strtolower($_SESSION[$sessionkey]) === strtolower(GETPOST('code', 'none')))); + if (!$ok) { + $error++; + array_push($object->errors, $langs->trans("ErrorBadValueForCode")); + $action = ''; + } + } + if (!$error) { $object->db->begin(); @@ -307,7 +334,9 @@ if (empty($reshook) && $action == 'create_ticket' && GETPOST('add', 'alpha')) { //setEventMessages($langs->trans('YourTicketSuccessfullySaved'), null, 'mesgs'); // Make a redirect to avoid to have ticket submitted twice if we make back - setEventMessages($langs->trans('MesgInfosPublicTicketCreatedWithTrackId', '<strong>'.$object->track_id.'</strong>', '<strong>'.$object->ref.'</strong>'), null, 'warnings'); + $messagetoshow = $langs->trans('MesgInfosPublicTicketCreatedWithTrackId', '{s1}', '{s2}'); + $messagetoshow = str_replace(array('{s1}', '{s2}'), array('<strong>'.$object->track_id.'</strong>', '<strong>'.$object->ref.'</strong>'), $messagetoshow); + setEventMessages($messagetoshow, null, 'warnings'); setEventMessages($langs->trans('PleaseRememberThisId'), null, 'warnings'); header("Location: index.php"); exit; diff --git a/htdocs/public/ticket/index.php b/htdocs/public/ticket/index.php index b3e8a5e237e..81d13832ca4 100644 --- a/htdocs/public/ticket/index.php +++ b/htdocs/public/ticket/index.php @@ -22,17 +22,29 @@ * \brief Public page to add and manage ticket */ -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined("NOLOGIN")) { + define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php // TODO This should be useless. Because entity must be retrieve from object ref and not from url. $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/ticket/class/actions_ticket.class.php'; @@ -57,8 +69,7 @@ $action = GETPOST('action', 'aZ09'); $form = new Form($db); $formticket = new FormTicket($db); -if (empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) -{ +if (empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) { print $langs->trans('TicketPublicInterfaceForbidden'); exit; } diff --git a/htdocs/public/ticket/list.php b/htdocs/public/ticket/list.php index 0f9542c986a..befeee00a7b 100644 --- a/htdocs/public/ticket/list.php +++ b/htdocs/public/ticket/list.php @@ -32,8 +32,12 @@ if (!defined('NOREQUIREMENU')) { if (!defined("NOLOGIN")) { define("NOLOGIN", '1'); } -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} // If this page is public (can be called outside logged session) require '../../main.inc.php'; @@ -174,8 +178,7 @@ llxHeaderTicket($langs->trans("Tickets"), "", 0, 0, $arrayofjs, $arrayofcss); print '<div class="ticketpublicarealist">'; -if ($action == "view_ticketlist") -{ +if ($action == "view_ticketlist") { print '<br>'; if ($display_ticket_list) { // Filters @@ -295,7 +298,9 @@ if ($action == "view_ticketlist") $limit = $conf->liste_limit; $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; @@ -326,8 +331,9 @@ if ($action == "view_ticketlist") $sql .= " type.label as type_label, category.label as category_label, severity.label as severity_label"; // Add fields for extrafields if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } $sql .= " FROM ".MAIN_DB_PREFIX."ticket as t"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_type as type ON type.code=t.type_code"; @@ -528,8 +534,7 @@ if ($action == "view_ticketlist") print_liste_field_titre($selectedfields, $url_page_current, "", '', '', 'align="right"', $sortfield, $sortorder, 'center maxwidthsearch '); print '</tr>'; - while ($obj = $db->fetch_object($resql)) - { + while ($obj = $db->fetch_object($resql)) { print '<tr class="oddeven">'; // Date ticket diff --git a/htdocs/public/ticket/view.php b/htdocs/public/ticket/view.php index 02c7c9e51d8..d556ca2935f 100644 --- a/htdocs/public/ticket/view.php +++ b/htdocs/public/ticket/view.php @@ -33,8 +33,12 @@ if (!defined('NOREQUIREMENU')) { if (!defined("NOLOGIN")) { define("NOLOGIN", '1'); } -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} // If this page is public (can be called outside logged session) require '../../main.inc.php'; @@ -69,10 +73,8 @@ $object = new ActionsTicket($db); * Actions */ -if ($cancel) -{ - if (!empty($backtopage)) - { +if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -104,13 +106,11 @@ if ($action == "view_ticket" || $action == "presend" || $action == "close" || $a if ($ret && $object->dao->id > 0) { // Check if emails provided is the one of author $emailofticket = CMailFile::getValidAddress($object->dao->origin_email, 2); - if ($emailofticket == $email) - { + if ($emailofticket == $email) { $display_ticket = true; $_SESSION['email_customer'] = $email; - } - // Check if emails provided is inside list of contacts - else { + } else { + // Check if emails provided is inside list of contacts $contacts = $object->dao->liste_contact(-1, 'external'); foreach ($contacts as $contact) { if ($contact['email'] == $email) { @@ -131,8 +131,7 @@ if ($action == "view_ticket" || $action == "presend" || $action == "close" || $a } } // Check if email is email of creator - if ($object->dao->fk_user_create > 0) - { + if ($object->dao->fk_user_create > 0) { $tmpuser = new User($db); $tmpuser->fetch($object->dao->fk_user_create); if ($email == $tmpuser->email) { @@ -141,8 +140,7 @@ if ($action == "view_ticket" || $action == "presend" || $action == "close" || $a } } // Check if email is email of creator - if ($object->dao->fk_user_assign > 0 && $object->dao->fk_user_assign != $object->dao->fk_user_create) - { + if ($object->dao->fk_user_assign > 0 && $object->dao->fk_user_assign != $object->dao->fk_user_create) { $tmpuser = new User($db); $tmpuser->fetch($object->dao->fk_user_assign); if ($email == $tmpuser->email) { @@ -157,8 +155,7 @@ if ($action == "view_ticket" || $action == "presend" || $action == "close" || $a } } - if (!$error && $action == 'confirm_public_close' && $display_ticket) - { + if (!$error && $action == 'confirm_public_close' && $display_ticket) { if ($object->dao->close($user)) { setEventMessages($langs->trans('TicketMarkedAsClosed'), null, 'mesgs'); @@ -171,24 +168,21 @@ if ($action == "view_ticket" || $action == "presend" || $action == "close" || $a } } - if (!$error && $action == "add_message" && $display_ticket && GETPOSTISSET('btn_add_message')) - { + if (!$error && $action == "add_message" && $display_ticket && GETPOSTISSET('btn_add_message')) { // TODO Add message... $ret = $object->dao->newMessage($user, $action, 0, 1); - if (!$error) - { + if (!$error) { $action = 'view_ticket'; } } if ($error || $errors) { setEventMessages($object->error, $object->errors, 'errors'); - if ($action == "add_message") - { + if ($action == "add_message") { $action = 'presend'; } else { $action = ''; @@ -228,8 +222,7 @@ llxHeaderTicket($langs->trans("Tickets"), "", 0, 0, $arrayofjs, $arrayofcss); print '<div class="ticketpublicarea">'; if ($action == "view_ticket" || $action == "presend" || $action == "close" || $action == "confirm_public_close") { - if ($display_ticket) - { + if ($display_ticket) { // Confirmation close if ($action == 'close') { print $form->formconfirm($_SERVER["PHP_SELF"]."?track_id=".$track_id, $langs->trans("CloseATicket"), $langs->trans("ConfirmCloseAticket"), "confirm_public_close", '', '', 1); diff --git a/htdocs/public/website/index.php b/htdocs/public/website/index.php index 4edd733b9e6..d72fedefa7e 100644 --- a/htdocs/public/website/index.php +++ b/htdocs/public/website/index.php @@ -30,14 +30,30 @@ * \brief Wrapper to output pages when website is powered by Dolibarr instead of a native web server */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal -if (!defined('NOLOGIN')) define("NOLOGIN", 1); -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); // Disables token renewal +} +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} /** * Header empty @@ -69,18 +85,15 @@ $accessallowed = 1; $type = ''; -if (empty($pageid)) -{ +if (empty($pageid)) { require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; require_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php'; $object = new Website($db); $object->fetch(0, $websitekey); - if (empty($object->id)) - { - if (empty($pageid)) - { + if (empty($object->id)) { + if (empty($pageid)) { // Return header 404 header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404); @@ -91,57 +104,52 @@ if (empty($pageid)) $objectpage = new WebsitePage($db); - if ($pageref) - { + if ($pageref) { $result = $objectpage->fetch(0, $object->id, $pageref); - if ($result > 0) - { + if ($result > 0) { $pageid = $objectpage->id; - } elseif ($result == 0) - { + } elseif ($result == 0) { // Page not found from ref=pageurl, we try using alternative alias $result = $objectpage->fetch(0, $object->id, null, $pageref); - if ($result > 0) - { + if ($result > 0) { $pageid = $objectpage->id; } } } else { - if ($object->fk_default_home > 0) - { + if ($object->fk_default_home > 0) { $result = $objectpage->fetch($object->fk_default_home); - if ($result > 0) - { + if ($result > 0) { $pageid = $objectpage->id; } } - if (empty($pageid)) - { + if (empty($pageid)) { $array = $objectpage->fetchAll($object->id); // TODO Can filter on container of type pages only ? - if (is_array($array) && count($array) > 0) - { + if (is_array($array) && count($array) > 0) { $firstrep = reset($array); $pageid = $firstrep->id; } } } } -if (empty($pageid)) -{ +if (empty($pageid)) { // Return header 404 header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404); $langs->load("website"); - if (!GETPOSTISSET('pageref')) print $langs->trans("PreviewOfSiteNotYetAvailable", $websitekey); + if (!GETPOSTISSET('pageref')) { + print $langs->trans("PreviewOfSiteNotYetAvailable", $websitekey); + } include DOL_DOCUMENT_ROOT.'/public/error-404.php'; exit; } $appli = constant('DOL_APPLICATION_TITLE'); -if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli = $conf->global->MAIN_APPLICATION_TITLE; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $appli = $conf->global->MAIN_APPLICATION_TITLE; +} @@ -155,8 +163,7 @@ if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli = $conf->global->MAIN_ // Security: Delete string ../ into $original_file global $dolibarr_main_data_root; -if ($pageid == 'css') // No more used ? -{ +if ($pageid == 'css') { // No more used ? header('Content-type: text/css'); // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. //if (empty($dolibarr_nocache)) header('Cache-Control: max-age=3600, public, must-revalidate'); @@ -172,16 +179,14 @@ $refname = basename(dirname($original_file)."/"); // Security: // Limite acces si droits non corrects -if (!$accessallowed) -{ +if (!$accessallowed) { accessforbidden(); } // Security: // On interdit les remontees de repertoire ainsi que les pipe dans // les noms de fichiers. -if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) -{ +if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) { dol_syslog("Refused to deliver file ".$original_file); $file = basename($original_file); // Do no show plain path of original_file in shown error message dol_print_error(0, $langs->trans("ErrorFileNameInvalid", $file)); @@ -197,8 +202,7 @@ dol_syslog("index.php include $original_file $filename content-type=$type"); $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset // This test if file exists should be useless. We keep it to find bug more easily -if (!file_exists($original_file_osencoded)) -{ +if (!file_exists($original_file_osencoded)) { // Return header 404 header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404); @@ -215,4 +219,6 @@ define('USEDOLIBARRSERVER', 1); print '<!-- Page content '.$original_file.' rendered with DOLIBARR SERVER : Html with CSS link and html header + Body that was saved into tpl dir -->'."\n"; include_once $original_file_osencoded; // Note: The pageXXX.tpl.php showed here contains a formatage with dolWebsiteOutput() at end of page. -if (is_object($db)) $db->close(); +if (is_object($db)) { + $db->close(); +} diff --git a/htdocs/public/website/styles.css.php b/htdocs/public/website/styles.css.php index 75257a8facc..a0002b5380b 100644 --- a/htdocs/public/website/styles.css.php +++ b/htdocs/public/website/styles.css.php @@ -21,14 +21,30 @@ * \brief Page to output style page. Called with <link rel="stylesheet" href="styles.css.php?websiteid=123" type="text/css" /> */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal -if (!defined('NOLOGIN')) define("NOLOGIN", 1); -if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); // Disables token renewal +} +if (!defined('NOLOGIN')) { + define("NOLOGIN", 1); +} +if (!defined('NOCSRFCHECK')) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} /** * Header empty @@ -65,18 +81,18 @@ $type = ''; */ $appli = constant('DOL_APPLICATION_TITLE'); -if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli = $conf->global->MAIN_APPLICATION_TITLE; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $appli = $conf->global->MAIN_APPLICATION_TITLE; +} //print 'Directory with '.$appli.' websites.<br>'; -if (empty($pageid)) -{ +if (empty($pageid)) { require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; require_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php'; $object = new Website($db); - if ($websiteid) - { + if ($websiteid) { $object->fetch($websiteid); $website = $object->ref; } else { @@ -85,21 +101,21 @@ if (empty($pageid)) $objectpage = new WebsitePage($db); /* Not required for CSS file - $array=$objectpage->fetchAll($object->id); + $array=$objectpage->fetchAll($object->id); - if (is_array($array) && count($array) > 0) - { - $firstrep=reset($array); - $pageid=$firstrep->id; - } - */ + if (is_array($array) && count($array) > 0) + { + $firstrep=reset($array); + $pageid=$firstrep->id; + } + */ } /* Not required for CSS file if (empty($pageid)) { - $langs->load("website"); - print $langs->trans("PreviewOfSiteNotYetAvailable"); - exit; + $langs->load("website"); + print $langs->trans("PreviewOfSiteNotYetAvailable"); + exit; } */ @@ -113,16 +129,14 @@ $refname = basename(dirname($original_file)."/"); // Security: // Limite acces si droits non corrects -if (!$accessallowed) -{ +if (!$accessallowed) { accessforbidden(); } // Security: // On interdit les remontees de repertoire ainsi que les pipe dans // les noms de fichiers. -if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) -{ +if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) { dol_syslog("Refused to deliver file ".$original_file); $file = basename($original_file); // Do no show plain path of original_file in shown error message dol_print_error(0, $langs->trans("ErrorFileNameInvalid", $file)); @@ -138,8 +152,7 @@ dol_syslog("styles.css.php include $original_file $filename content-type=$type") $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset // This test if file exists should be useless. We keep it to find bug more easily -if (!file_exists($original_file_osencoded)) -{ +if (!file_exists($original_file_osencoded)) { $langs->load("website"); print $langs->trans("RequestedPageHasNoContentYet", $pageid); //dol_print_error(0,$langs->trans("ErrorFileDoesNotExists",$original_file)); @@ -153,4 +166,6 @@ print '/* Page content '.$original_file.' : CSS content that was saved into tpl require_once $original_file_osencoded; -if (is_object($db)) $db->close(); +if (is_object($db)) { + $db->close(); +} diff --git a/htdocs/reception/card.php b/htdocs/reception/card.php index 41e8f60e634..83701e59e40 100644 --- a/htdocs/reception/card.php +++ b/htdocs/reception/card.php @@ -44,13 +44,19 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; -if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +} +if (!empty($conf->propal->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +} if (!empty($conf->fournisseur->enabled)) { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php'; } -if (!empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; +if (!empty($conf->productbatch->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; +} if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; @@ -58,28 +64,45 @@ if (!empty($conf->projet->enabled)) { $langs->loadLangs(array("receptions", "companies", "bills", 'deliveries', 'orders', 'stocks', 'other', 'propal', 'sendings')); -if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); -if (!empty($conf->productbatch->enabled)) $langs->load('productbatch'); +if (!empty($conf->incoterm->enabled)) { + $langs->load('incoterm'); +} +if (!empty($conf->productbatch->enabled)) { + $langs->load('productbatch'); +} $origin = GETPOST('origin', 'alpha') ?GETPOST('origin', 'alpha') : 'reception'; // Example: commande, propal $origin_id = GETPOST('id', 'int') ?GETPOST('id', 'int') : ''; $id = $origin_id; -if (empty($origin_id)) $origin_id = GETPOST('origin_id', 'int'); // Id of order or propal -if (empty($origin_id)) $origin_id = GETPOST('object_id', 'int'); // Id of order or propal -if (empty($origin_id)) $origin_id = GETPOST('originid', 'int'); // Id of order or propal +if (empty($origin_id)) { + $origin_id = GETPOST('origin_id', 'int'); // Id of order or propal +} +if (empty($origin_id)) { + $origin_id = GETPOST('object_id', 'int'); // Id of order or propal +} +if (empty($origin_id)) { + $origin_id = GETPOST('originid', 'int'); // Id of order or propal +} $ref = GETPOST('ref', 'alpha'); $line_id = GETPOST('lineid', 'int') ?GETPOST('lineid', 'int') : ''; // Security check $socid = ''; -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} -if ($origin == 'reception') $result = restrictedArea($user, $origin, $id); -else { +if ($origin == 'reception') { + $result = restrictedArea($user, $origin, $id); +} else { $result = restrictedArea($user, 'reception'); if ($origin == 'supplierorder') { - if (empty($user->rights->fournisseur->commande->lire) && empty($user->rights->fournisseur->commande->read)) accessforbidden(); - } elseif (empty($user->rights->{$origin}->lire) && empty($user->rights->{$origin}->read)) accessforbidden(); + if (empty($user->rights->fournisseur->commande->lire) && empty($user->rights->fournisseur->commande->read)) { + accessforbidden(); + } + } elseif (empty($user->rights->{$origin}->lire) && empty($user->rights->{$origin}->read)) { + accessforbidden(); + } } $action = GETPOST('action', 'alpha'); @@ -120,12 +143,12 @@ $date_delivery = dol_mktime(GETPOST('date_deliveryhour', 'int'), GETPOST('date_d $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 ($cancel) - { +if (empty($reshook)) { + if ($cancel) { $action = ''; $object->fetch($id); // show reception also after canceling modification } @@ -133,25 +156,25 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once // Reopen - if ($action == 'reopen' && $user->rights->reception->creer) - { + if ($action == 'reopen' && $user->rights->reception->creer) { $object->fetch($id); $result = $object->reOpen(); } // Confirm back to draft status - if ($action == 'modif' && $user->rights->reception->creer) - { + if ($action == 'modif' && $user->rights->reception->creer) { $result = $object->setDraft($user); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -164,13 +187,11 @@ if (empty($reshook)) } // Set incoterm - if ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { + if ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) { $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); } - if ($action == 'setref_supplier') - { + if ($action == 'setref_supplier') { $result = $object->fetch($id); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -186,32 +207,31 @@ if (empty($reshook)) } } - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('RECEPTION_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } // Create reception - if ($action == 'add' && $user->rights->reception->creer) - { + if ($action == 'add' && $user->rights->reception->creer) { $error = 0; $predef = ''; @@ -231,9 +251,11 @@ if (empty($reshook)) // On va boucler sur chaque ligne du document d'origine pour completer objet reception // avec info diverses + qte a livrer - if ($object->origin == "supplierorder") + if ($object->origin == "supplierorder") { $classname = 'CommandeFournisseur'; - else $classname = ucfirst($object->origin); + } else { + $classname = ucfirst($object->origin); + } $objectsrc = new $classname($db); $objectsrc->fetch($object->origin_id); @@ -258,18 +280,15 @@ if (empty($reshook)) $totalqty = 0; $num = 0; - foreach ($_POST as $key => $value) - { + foreach ($_POST as $key => $value) { // without batch module enabled - if (strpos($key, 'qtyasked') !== false) - { + if (strpos($key, 'qtyasked') !== false) { $num++; } } - for ($i = 1; $i <= $num; $i++) - { + for ($i = 1; $i <= $num; $i++) { $idl = "idl".$i; $sub_qty = array(); @@ -284,8 +303,9 @@ if (empty($reshook)) //var_dump(GETPOST($qty,'int')); var_dump($_POST); var_dump($batch);exit; //reception line for product with no batch management and no multiple stock location - if (GETPOST($qty, 'int') > 0) + if (GETPOST($qty, 'int') > 0) { $totalqty += GETPOST($qty, 'int'); + } // Extrafields @@ -293,14 +313,14 @@ if (empty($reshook)) } - if ($totalqty > 0) // There is at least one thing to ship - { + if ($totalqty > 0) { // There is at least one thing to ship //var_dump($_POST);exit; - for ($i = 1; $i <= $num; $i++) - { + for ($i = 1; $i <= $num; $i++) { $lineToTest = ''; foreach ($objectsrc->lines as $linesrc) { - if ($linesrc->id == GETPOST($idl, 'int')) $lineToTest = $linesrc; + if ($linesrc->id == GETPOST($idl, 'int')) { + $lineToTest = $linesrc; + } } $qty = "qtyl".$i; $comment = "comment".$i; @@ -310,18 +330,19 @@ if (empty($reshook)) $timeFormat = '%d/%m/%Y'; - if (GETPOST($qty, 'int') > 0 || (GETPOST($qty, 'int') == 0 && $conf->global->RECEPTION_GETS_ALL_ORDER_PRODUCTS)) - { + if (GETPOST($qty, 'int') > 0 || (GETPOST($qty, 'int') == 0 && $conf->global->RECEPTION_GETS_ALL_ORDER_PRODUCTS)) { $ent = "entl".$i; $idl = "idl".$i; $entrepot_id = is_numeric(GETPOST($ent, 'int')) ? GETPOST($ent, 'int') : GETPOST('entrepot_id', 'int'); - if ($entrepot_id < 0) + if ($entrepot_id < 0) { $entrepot_id = ''; - if (!($linesrc->fk_product > 0) && empty($conf->global->STOCK_SUPPORTS_SERVICES)) + } + if (!($linesrc->fk_product > 0) && empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $entrepot_id = 0; + } $eatby = GETPOST($eatby, 'alpha'); $sellby = GETPOST($sellby, 'alpha'); $eatbydate = str_replace('/', '-', $eatby); @@ -329,8 +350,7 @@ if (empty($reshook)) $ret = $object->addline($entrepot_id, GETPOST($idl, 'int'), GETPOST($qty, 'int'), $array_options[$i], GETPOST($comment, 'alpha'), strtotime($eatbydate), strtotime($sellbydate), GETPOST($batch, 'alpha')); - if ($ret < 0) - { + if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -340,13 +360,13 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; - if (!$error) - { + if ($ret < 0) { + $error++; + } + if (!$error) { $ret = $object->create($user); // This create reception (like Odoo picking) and line of receptions. Stock movement will when validating reception. - if ($ret <= 0) - { + if ($ret <= 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -356,8 +376,7 @@ if (empty($reshook)) $error++; } - if (!$error) - { + if (!$error) { $db->commit(); header("Location: card.php?id=".$object->id); exit; @@ -368,25 +387,26 @@ if (empty($reshook)) } } elseif ($action == 'confirm_valid' && $confirm == 'yes' && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->reception_advance->validate))) - ) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->reception_advance->validate))) + ) { $object->fetch_thirdparty(); $result = $object->valid($user); - if ($result < 0) - { + if ($result < 0) { $langs->load("errors"); setEventMessages($langs->trans($object->error), null, 'errors'); } else { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -395,71 +415,70 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } } - } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->reception->supprimer) - { + } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->reception->supprimer) { $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".DOL_URL_ROOT.'/reception/index.php'); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } - // TODO add alternative status - /*elseif ($action == 'reopen' && (! empty($user->rights->reception->creer) || ! empty($user->rights->reception->reception_advance->validate))) - { - $result = $object->setStatut(0); - if ($result < 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } - }*/ - elseif ($action == 'setdate_livraison' && $user->rights->reception->creer) - { + // TODO add alternative status + /*} elseif ($action == 'reopen' && (! empty($user->rights->reception->creer) || ! empty($user->rights->reception->reception_advance->validate))) { + $result = $object->setStatut(0); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + }*/ + } elseif ($action == 'setdate_livraison' && $user->rights->reception->creer) { //print "x ".$_POST['liv_month'].", ".$_POST['liv_day'].", ".$_POST['liv_year']; $datedelivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int')); $object->fetch($id); $result = $object->setDeliveryDate($user, $datedelivery); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Action update - elseif ($action == 'settracking_number' || $action == 'settracking_url' + } elseif ($action == 'settracking_number' || $action == 'settracking_url' || $action == 'settrueWeight' || $action == 'settrueWidth' || $action == 'settrueHeight' || $action == 'settrueDepth' - || $action == 'setshipping_method_id') - { + || $action == 'setshipping_method_id') { + // Action update $error = 0; - if ($action == 'settracking_number') $object->tracking_number = trim(GETPOST('tracking_number', 'alpha')); - if ($action == 'settracking_url') $object->tracking_url = trim(GETPOST('tracking_url', 'int')); + if ($action == 'settracking_number') { + $object->tracking_number = trim(GETPOST('tracking_number', 'alpha')); + } + if ($action == 'settracking_url') { + $object->tracking_url = trim(GETPOST('tracking_url', 'int')); + } if ($action == 'settrueWeight') { $object->trueWeight = trim(GETPOST('trueWeight', 'int')); $object->weight_units = GETPOST('weight_units', 'int'); } - if ($action == 'settrueWidth') $object->trueWidth = trim(GETPOST('trueWidth', 'int')); + if ($action == 'settrueWidth') { + $object->trueWidth = trim(GETPOST('trueWidth', 'int')); + } if ($action == 'settrueHeight') { $object->trueHeight = trim(GETPOST('trueHeight', 'int')); $object->size_units = GETPOST('size_units', 'int'); } - if ($action == 'settrueDepth') $object->trueDepth = trim(GETPOST('trueDepth', 'int')); - if ($action == 'setshipping_method_id') $object->shipping_method_id = trim(GETPOST('shipping_method_id', 'int')); + if ($action == 'settrueDepth') { + $object->trueDepth = trim(GETPOST('trueDepth', 'int')); + } + if ($action == 'setshipping_method_id') { + $object->shipping_method_id = trim(GETPOST('shipping_method_id', 'int')); + } - if (!$error) - { - if ($object->update($user) >= 0) - { + if (!$error) { + if ($object->update($user) >= 0) { header("Location: card.php?id=".$object->id); exit; } @@ -467,78 +486,70 @@ if (empty($reshook)) } $action = ""; - } - - // Build document - elseif ($action == 'builddoc') // En get ou en post - { + } elseif ($action == 'builddoc') { + // Build document + // En get ou en post // Save last template used to generate document - if (GETPOST('model')) $object->setDocModel($user, GETPOST('model', 'alpha')); + if (GETPOST('model')) { + $object->setDocModel($user, GETPOST('model', 'alpha')); + } // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $reception->thirdparty->default_lang; - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $reception->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = ''; } - } - - // Delete file in doc form - elseif ($action == 'remove_file') - { + } elseif ($action == 'remove_file') { + // Delete file in doc form require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $upload_dir = $conf->reception->dir_output; $file = $upload_dir.'/'.GETPOST('file'); $ret = dol_delete_file($file, 0, 0, 0, $object); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors'); - } elseif ($action == 'classifybilled') - { + if ($ret) { + setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors'); + } + } elseif ($action == 'classifybilled') { $object->fetch($id); $result = $object->setBilled(); if ($result >= 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit(); } - } elseif ($action == 'classifyclosed') - { + } elseif ($action == 'classifyclosed') { $object->fetch($id); $result = $object->setClosed(); if ($result >= 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit(); } - } - - /* - * delete a line - */ - elseif ($action == 'deleteline' && !empty($line_id)) - { + } elseif ($action == 'deleteline' && !empty($line_id)) { + // delete a line $object->fetch($id); $lines = $object->lines; $line = new CommandeFournisseurDispatch($db); $num_prod = count($lines); - for ($i = 0; $i < $num_prod; $i++) - { - if ($lines[$i]->id == $line_id) - { + for ($i = 0; $i < $num_prod; $i++) { + if ($lines[$i]->id == $line_id) { // delete single warehouse line $line->id = $line_id; - if (!$error && $line->delete($user) < 0) - { + if (!$error && $line->delete($user) < 0) { $error++; } } @@ -551,13 +562,8 @@ if (empty($reshook)) } else { setEventMessages($line->error, $line->errors, 'errors'); } - } - - /* - * Update a line - */ - elseif ($action == 'updateline' && $user->rights->reception->creer && GETPOST('save')) - { + } elseif ($action == 'updateline' && $user->rights->reception->creer && GETPOST('save')) { + // Update a line // Clean parameters $qty = 0; $entrepot_id = 0; @@ -565,10 +571,8 @@ if (empty($reshook)) $lines = $object->lines; $num_prod = count($lines); - for ($i = 0; $i < $num_prod; $i++) - { - if ($lines[$i]->id == $line_id) // we have found line to update - { + for ($i = 0; $i < $num_prod; $i++) { + if ($lines[$i]->id == $line_id) { // we have found line to update $line = new CommandeFournisseurDispatch($db); $line->fetch($line_id); // Extrafields Lines @@ -579,8 +583,7 @@ if (empty($reshook)) $line->fk_product = $lines[$i]->fk_product; - if ($lines[$i]->fk_product > 0) - { + if ($lines[$i]->fk_product > 0) { // single warehouse reception line $stockLocation = "entl".$line_id; $qty = "qtyl".$line_id; @@ -605,8 +608,7 @@ if (empty($reshook)) $line->sellby = strtotime($sellbydate); } - if ($line->update($user) < 0) - { + if ($line->update($user) < 0) { setEventMessages($line->error, $line->errors, 'errors'); $error++; } @@ -616,8 +618,7 @@ if (empty($reshook)) $line->id = $line_id; $line->qty = GETPOST($qty, 'int'); $line->fk_entrepot = 0; - if ($line->update($user) < 0) - { + if ($line->update($user) < 0) { setEventMessages($line->error, $line->errors, 'errors'); $error++; } @@ -633,10 +634,12 @@ if (empty($reshook)) // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -657,7 +660,9 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - if (empty($id)) $id = $facid; + if (empty($id)) { + $id = $facid; + } $triggersendname = 'RECEPTION_SENTBYMAIL'; $paramname = 'id'; $mode = 'emailfromreception'; @@ -675,14 +680,15 @@ llxHeader('', $langs->trans('Reception'), 'Reception'); $form = new Form($db); $formfile = new FormFile($db); $formproduct = new FormProduct($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $product_static = new Product($db); $reception_static = new Reception($db); $warehousestatic = new Entrepot($db); -if ($action == 'create2') -{ +if ($action == 'create2') { print load_fiche_titre($langs->trans("CreateReception"), '', 'dollyrevert'); print '<br>'.$langs->trans("ReceptionCreationIsDoneFromOrder"); @@ -690,31 +696,32 @@ if ($action == 'create2') } // Mode creation. -if ($action == 'create') -{ +if ($action == 'create') { $recept = new Reception($db); print load_fiche_titre($langs->trans("CreateReception")); - if (!$origin) - { + if (!$origin) { setEventMessages($langs->trans("ErrorBadParameters"), null, 'errors'); } - if ($origin) - { - if ($origin == 'supplierorder')$classname = 'CommandeFournisseur'; - else $classname = ucfirst($origin); + if ($origin) { + if ($origin == 'supplierorder') { + $classname = 'CommandeFournisseur'; + } else { + $classname = ucfirst($origin); + } $object = new $classname($db); - if ($object->fetch($origin_id)) // This include the fetch_lines - { + if ($object->fetch($origin_id)) { // This include the fetch_lines $soc = new Societe($db); $soc->fetch($object->socid); $author = new User($db); $author->fetch($object->user_author_id); - if (!empty($conf->stock->enabled)) $entrepot = new Entrepot($db); + if (!empty($conf->stock->enabled)) { + $entrepot = new Entrepot($db); + } print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -722,8 +729,7 @@ if ($action == 'create') print '<input type="hidden" name="origin" value="'.$origin.'">'; print '<input type="hidden" name="origin_id" value="'.$object->id.'">'; print '<input type="hidden" name="ref_int" value="'.$object->ref_int.'">'; - if (GETPOST('entrepot_id', 'int')) - { + if (GETPOST('entrepot_id', 'int')) { print '<input type="hidden" name="entrepot_id" value="'.GETPOST('entrepot_id', 'int').'">'; } @@ -733,12 +739,10 @@ if ($action == 'create') // Ref print '<tr><td class="titlefieldcreate fieldrequired">'; - if ($origin == 'supplierorder' && !empty($conf->fournisseur->enabled)) - { + if ($origin == 'supplierorder' && !empty($conf->fournisseur->enabled)) { print $langs->trans("RefOrder").'</td><td colspan="3"><a href="'.DOL_URL_ROOT.'/fourn/commande/card.php?id='.$object->id.'">'.img_object($langs->trans("ShowOrder"), 'order').' '.$object->ref; } - if ($origin == 'propal' && !empty($conf->propal->enabled)) - { + if ($origin == 'propal' && !empty($conf->propal->enabled)) { print $langs->trans("RefProposal").'</td><td colspan="3"><a href="'.DOL_URL_ROOT.'/comm/card.php?id='.$object->id.'">'.img_object($langs->trans("ShowProposal"), 'propal').' '.$object->ref; } print '</a></td>'; @@ -746,8 +750,11 @@ if ($action == 'create') // Ref client print '<tr><td>'; - if ($origin == 'supplier_order') print $langs->trans('SupplierOrder'); - else print $langs->trans('RefSupplier'); + if ($origin == 'supplier_order') { + print $langs->trans('SupplierOrder'); + } else { + print $langs->trans('RefSupplier'); + } print '</td><td colspan="3">'; print '<input type="text" name="ref_supplier" value="'.$object->ref_supplier.'" />'; print '</td>'; @@ -759,11 +766,14 @@ if ($action == 'create') print '</tr>'; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $projectid = GETPOST('projectid', 'int') ?GETPOST('projectid', 'int') : 0; - if (empty($projectid) && !empty($object->fk_project)) $projectid = $object->fk_project; - if ($origin == 'project') $projectid = ($originid ? $originid : 0); + if (empty($projectid) && !empty($object->fk_project)) { + $projectid = $object->fk_project; + } + if ($origin == 'project') { + $projectid = ($originid ? $originid : 0); + } $langs->load("projects"); print '<tr>'; @@ -790,8 +800,7 @@ if ($action == 'create') print "</td></tr>"; // Note Private - if ($object->note_private && !$user->socid) - { + if ($object->note_private && !$user->socid) { print '<tr><td>'.$langs->trans("NotePrivate").'</td>'; print '<td colspan="3">'; $doleditor = new DolEditor('note_private', $object->note_private, '', 60, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%'); @@ -824,7 +833,9 @@ if ($action == 'create') print '<td colspan="3">'; $recept->fetch_delivery_methods(); print $form->selectarray("shipping_method_id", $recept->meths, GETPOST('shipping_method_id', 'int'), 1, 0, 0, "", 1); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print "</td></tr>\n"; // Tracking number @@ -849,8 +860,7 @@ if ($action == 'create') } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '<tr>'; print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), $object->label_incoterms, 1).'</label></td>'; print '<td colspan="3" class="maxwidthonsmartphone">'; @@ -862,8 +872,7 @@ if ($action == 'create') include_once DOL_DOCUMENT_ROOT.'/core/modules/reception/modules_reception.php'; $list = ModelePdfReception::liste_modeles($db); - if (count($list) > 1) - { + if (count($list) > 1) { print "<tr><td>".$langs->trans("DefaultModel")."</td>"; print '<td colspan="3">'; print $form->selectarray('model', $list, $conf->global->RECEPTION_ADDON_PDF); @@ -878,11 +887,9 @@ if ($action == 'create') // Reception lines $numAsked = 0; $dispatchLines = array(); - foreach ($_POST as $key => $value) - { + foreach ($_POST as $key => $value) { // without batch module enabled - if (preg_match('/^product_([0-9]+)_([0-9]+)$/i', $key, $reg)) - { + if (preg_match('/^product_([0-9]+)_([0-9]+)$/i', $key, $reg)) { $numAsked++; // $numline=$reg[2] + 1; // line of product @@ -896,8 +903,7 @@ if ($action == 'create') } // with batch module enabled - if (preg_match('/^product_batch_([0-9]+)_([0-9]+)$/i', $key, $reg)) - { + if (preg_match('/^product_batch_([0-9]+)_([0-9]+)$/i', $key, $reg)) { $numAsked++; // eat-by date dispatch @@ -920,16 +926,14 @@ if ($action == 'create') jQuery(document).ready(function() { jQuery("#autofill").click(function() {'; $i = 1; - while ($i <= $numAsked) - { + while ($i <= $numAsked) { print 'jQuery("#qtyl'.$i.'").val(jQuery("#qtyasked'.$i.'").val() - jQuery("#qtydelivered'.$i.'").val());'."\n"; $i++; } print '}); jQuery("#autoreset").click(function() {'; $i = 1; - while ($i <= $numAsked) - { + while ($i <= $numAsked) { print 'jQuery("#qtyl'.$i.'").val(0);'."\n"; $i++; } @@ -944,25 +948,21 @@ if ($action == 'create') // Load receptions already done for same order $object->loadReceptions(); - if ($numAsked) - { + if ($numAsked) { print '<tr class="liste_titre">'; print '<td>'.$langs->trans("Description").'</td>'; print '<td class="center">'.$langs->trans("QtyOrdered").'</td>'; print '<td class="center">'.$langs->trans("QtyReceived").'</td>'; print '<td class="center">'.$langs->trans("QtyToReceive"); - if (empty($conf->productbatch->enabled)) - { + if (empty($conf->productbatch->enabled)) { print ' <br>(<a href="#" id="autofill">'.$langs->trans("Fill").'</a>'; print ' / <a href="#" id="autoreset">'.$langs->trans("Reset").'</a>)'; } print '</td>'; - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print '<td class="left">'.$langs->trans("Warehouse").' ('.$langs->trans("Stock").')</td>'; } - if (!empty($conf->productbatch->enabled)) - { + if (!empty($conf->productbatch->enabled)) { print '<td class="left">'.$langs->trans("batch_number").'</td>'; if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { print '<td class="left">'.$langs->trans("EatByDate").'</td>'; @@ -975,8 +975,7 @@ if ($action == 'create') } $indiceAsked = 1; - while ($indiceAsked <= $numAsked) - { + while ($indiceAsked <= $numAsked) { $product = new Product($db); foreach ($object->lines as $supplierLine) { if ($dispatchLines[$indiceAsked]['fk_commandefourndet'] == $supplierLine->id) { @@ -990,16 +989,19 @@ if ($action == 'create') $type = $line->product_type ? $line->product_type : $line->fk_product_type; // Try to enhance type detection using date_start and date_end for free lines where type // was not saved. - if (!empty($line->date_start)) $type = 1; - if (!empty($line->date_end)) $type = 1; + if (!empty($line->date_start)) { + $type = 1; + } + if (!empty($line->date_end)) { + $type = 1; + } print '<!-- line '.$line->rowid.' for product -->'."\n"; print '<tr class="oddeven">'."\n"; // Product label - if ($line->fk_product > 0) // If predefined product - { + if ($line->fk_product > 0) { // If predefined product $product->fetch($line->fk_product); $product->load_stock('warehouseopen'); // Load all $product->stock_warehouse[idwarehouse]->detail_batch //var_dump($product->stock_warehouse[1]); @@ -1022,16 +1024,18 @@ if ($action == 'create') print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end)); // Add description in form - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { print ($line->desc && $line->desc != $line->product_label) ? '<br>'.dol_htmlentitiesbr($line->desc) : ''; } print '</td>'; } else { print "<td>"; - if ($type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if ($type == 1) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($line->label)) { $text .= ' <strong>'.$line->label.'</strong>'; @@ -1063,8 +1067,7 @@ if ($action == 'create') print '</td>'; - if ($line->product_type == 1 && empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if ($line->product_type == 1 && empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $quantityToBeDelivered = 0; } else { $quantityToBeDelivered = $dispatchLines[$indiceAsked]['qty']; @@ -1073,8 +1076,7 @@ if ($action == 'create') $warehouseObject = null; - if (!empty($conf->stock->enabled)) // If warehouse was already selected or if product is not a predefined, we go into this part with no multiwarehouse selection - { + if (!empty($conf->stock->enabled)) { // If warehouse was already selected or if product is not a predefined, we go into this part with no multiwarehouse selection print '<!-- Case warehouse already known or product not a predefined product -->'; $stock = + $product->stock_warehouse[$dispatchLines[$indiceAsked]['ent']]->real; // Convert to number @@ -1082,26 +1084,26 @@ if ($action == 'create') // Quantity to send print '<td class="center">'; - if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - if (GETPOST('qtyl'.$indiceAsked, 'int')) $defaultqty = GETPOST('qtyl'.$indiceAsked, 'int'); + if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { + if (GETPOST('qtyl'.$indiceAsked, 'int')) { + $defaultqty = GETPOST('qtyl'.$indiceAsked, 'int'); + } print '<input name="idl'.$indiceAsked.'" type="hidden" value="'.$line->id.'">'; print '<input name="qtyl'.$indiceAsked.'" id="qtyl'.$indiceAsked.'" type="text" size="4" value="'.$deliverableQty.'">'; - } else print $langs->trans("NA"); + } else { + print $langs->trans("NA"); + } print '</td>'; // Stock - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print '<td class="left">'; - if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) // Type of product need stock change ? - { + if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { // Type of product need stock change ? // Show warehouse combo list $ent = "entl".$indiceAsked; $idl = "idl".$indiceAsked; $tmpentrepot_id = is_numeric(GETPOST($ent, 'int')) ?GETPOST($ent, 'int') : $warehouse_id; - if ($line->fk_product > 0) - { + if ($line->fk_product > 0) { print '<!-- Show warehouse selection -->'; print $formproduct->selectWarehouses($tmpentrepot_id, 'entl'.$indiceAsked, '', 0, 0, $line->fk_product, '', 1); } @@ -1111,10 +1113,8 @@ if ($action == 'create') print '</td>'; } - if (!empty($conf->productbatch->enabled)) - { - if (!empty($product->status_batch)) - { + if (!empty($conf->productbatch->enabled)) { + if (!empty($product->status_batch)) { print '<td><input name="batch'.$indiceAsked.'" value="'.$dispatchLines[$indiceAsked]['lot'].'"></td>'; if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { print '<td>'; @@ -1134,10 +1134,11 @@ if ($action == 'create') } //Display lines extrafields - if (is_array($extralabelslines) && count($extralabelslines) > 0) - { + if (is_array($extralabelslines) && count($extralabelslines) > 0) { $colspan = 5; - if ($conf->productbatch->enabled) $colspan += 3; + if ($conf->productbatch->enabled) { + $colspan += 3; + } $srcLine = new CommandeFournisseurLigne($db); $line = new CommandeFournisseurDispatch($db); @@ -1174,21 +1175,18 @@ if ($action == 'create') dol_print_error($db); } } -} elseif ($id || $ref) -/* *************************************************************************** */ -/* */ -/* Edit and view mode */ -/* */ -/* *************************************************************************** */ -{ +} elseif ($id || $ref) { + /* *************************************************************************** */ + /* */ + /* Edit and view mode */ + /* */ + /* *************************************************************************** */ $lines = $object->lines; $num_prod = count($lines); - if ($object->id > 0) - { - if (!empty($object->origin) && $object->origin_id > 0) - { + if ($object->id > 0) { + if (!empty($object->origin) && $object->origin_id > 0) { $object->origin = 'CommandeFournisseur'; $typeobject = $object->origin; $origin = $object->origin; @@ -1207,17 +1205,14 @@ if ($action == 'create') $formconfirm = ''; // Confirm deleteion - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('DeleteReception'), $langs->trans("ConfirmDeleteReception", $object->ref), 'confirm_delete', '', 0, 1); } // Confirmation validation - if ($action == 'valid') - { + if ($action == 'valid') { $objectref = substr($object->ref, 1, 4); - if ($objectref == 'PROV') - { + if ($objectref == 'PROV') { $numref = $object->getNextNumRef($soc); } else { $numref = $object->ref; @@ -1225,8 +1220,7 @@ if ($action == 'create') $text = $langs->trans("ConfirmValidateReception", $numref); - if (!empty($conf->notification->enabled)) - { + if (!empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; $notify = new Notify($db); $text .= '<br>'; @@ -1237,16 +1231,18 @@ if ($action == 'create') } // Confirm cancelation - if ($action == 'annuler') - { + if ($action == 'annuler') { $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('CancelReception'), $langs->trans("ConfirmCancelReception", $object->ref), 'confirm_cancel', '', 0, 1); } if (!$formconfirm) { $parameters = array('formConfirm' => $formconfirm); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } } // Print form confirm @@ -1260,18 +1256,15 @@ if ($action == 'create') $totalVolume = $tmparray['volume']; - if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) - { + if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) { $objectsrc = new Commande($db); $objectsrc->fetch($object->$typeobject->id); } - if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) - { + if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) { $objectsrc = new Propal($db); $objectsrc->fetch($object->$typeobject->id); } - if ($typeobject == 'CommandeFournisseur' && $object->$typeobject->id && !empty($conf->fournisseur->enabled)) - { + if ($typeobject == 'CommandeFournisseur' && $object->$typeobject->id && !empty($conf->fournisseur->enabled)) { $objectsrc = new CommandeFournisseur($db); $objectsrc->fetch($object->$typeobject->id); } @@ -1286,8 +1279,7 @@ if ($action == 'create') // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; if (0) { // Do not change on reception @@ -1333,8 +1325,7 @@ if ($action == 'create') print '<table class="border centpercent">'; // Linked documents - if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) - { + if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) { print '<tr><td>'; print $langs->trans("RefOrder").'</td>'; print '<td colspan="3">'; @@ -1342,8 +1333,7 @@ if ($action == 'create') print "</td>\n"; print '</tr>'; } - if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) - { + if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) { print '<tr><td>'; print $langs->trans("RefProposal").'</td>'; print '<td colspan="3">'; @@ -1351,8 +1341,7 @@ if ($action == 'create') print "</td>\n"; print '</tr>'; } - if ($typeobject == 'CommandeFournisseur' && $object->$typeobject->id && !empty($conf->propal->enabled)) - { + if ($typeobject == 'CommandeFournisseur' && $object->$typeobject->id && !empty($conf->propal->enabled)) { print '<tr><td>'; print $langs->trans("SupplierOrder").'</td>'; print '<td colspan="3">'; @@ -1372,11 +1361,12 @@ if ($action == 'create') print $langs->trans('DateDeliveryPlanned'); print '</td>'; - if ($action != 'editdate_livraison') print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_livraison&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).'</a></td>'; + if ($action != 'editdate_livraison') { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_livraison&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td colspan="2">'; - if ($action == 'editdate_livraison') - { + if ($action == 'editdate_livraison') { print '<form name="setdate_livraison" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="setdate_livraison">'; @@ -1394,8 +1384,7 @@ if ($action == 'create') print $form->editfieldkey("Weight", 'trueWeight', $object->trueWeight, $object, $user->rights->reception->creer); print '</td><td colspan="3">'; - if ($action == 'edittrueWeight') - { + if ($action == 'edittrueWeight') { print '<form name="settrueweight" action="'.$_SERVER["PHP_SELF"].'" method="post">'; print '<input name="action" value="settrueWeight" type="hidden">'; print '<input name="id" value="'.$object->id.'" type="hidden">'; @@ -1411,11 +1400,14 @@ if ($action == 'create') } // Calculated - if ($totalWeight > 0) - { - if (!empty($object->trueWeight)) print ' ('.$langs->trans("SumOfProductWeights").': '; + if ($totalWeight > 0) { + if (!empty($object->trueWeight)) { + print ' ('.$langs->trans("SumOfProductWeights").': '; + } print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND) ? $conf->global->MAIN_WEIGHT_DEFAULT_ROUND : -1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? $conf->global->MAIN_WEIGHT_DEFAULT_UNIT : 'no'); - if (!empty($object->trueWeight)) print ')'; + if (!empty($object->trueWeight)) { + print ')'; + } } print '</td></tr>'; @@ -1427,8 +1419,7 @@ if ($action == 'create') // Height print '<tr><td>'.$form->editfieldkey("Height", 'trueHeight', $object->trueHeight, $object, $user->rights->reception->creer).'</td><td colspan="3">'; - if ($action == 'edittrueHeight') - { + if ($action == 'edittrueHeight') { print '<form name="settrueHeight" action="'.$_SERVER["PHP_SELF"].'" method="post">'; print '<input name="action" value="settrueHeight" type="hidden">'; print '<input name="id" value="'.$object->id.'" type="hidden">'; @@ -1458,25 +1449,27 @@ if ($action == 'create') print '<td colspan="3">'; $calculatedVolume = 0; $volumeUnit = 0; - if ($object->trueWidth && $object->trueHeight && $object->trueDepth) - { + if ($object->trueWidth && $object->trueHeight && $object->trueDepth) { $calculatedVolume = ($object->trueWidth * $object->trueHeight * $object->trueDepth); $volumeUnit = $object->size_units * 3; } // If reception volume not defined we use sum of products - if ($calculatedVolume > 0) - { - if ($volumeUnit < 50) - { + if ($calculatedVolume > 0) { + if ($volumeUnit < 50) { print showDimensionInBestUnit($calculatedVolume, $volumeUnit, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND) ? $conf->global->MAIN_VOLUME_DEFAULT_ROUND : -1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT) ? $conf->global->MAIN_VOLUME_DEFAULT_UNIT : 'no'); - } else print $calculatedVolume.' '.measuringUnitString(0, "volume", $volumeUnit); + } else { + print $calculatedVolume.' '.measuringUnitString(0, "volume", $volumeUnit); + } } - if ($totalVolume > 0) - { - if ($calculatedVolume) print ' ('.$langs->trans("SumOfProductVolumes").': '; + if ($totalVolume > 0) { + if ($calculatedVolume) { + print ' ('.$langs->trans("SumOfProductVolumes").': '; + } print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND) ? $conf->global->MAIN_VOLUME_DEFAULT_ROUND : -1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT) ? $conf->global->MAIN_VOLUME_DEFAULT_UNIT : 'no'); //if (empty($calculatedVolume)) print ' ('.$langs->trans("Calculated").')'; - if ($calculatedVolume) print ')'; + if ($calculatedVolume) { + print ')'; + } } print "</td>\n"; print '</tr>'; @@ -1501,22 +1494,24 @@ if ($action == 'create') print $langs->trans('ReceptionMethod'); print '</td>'; - if ($action != 'editshipping_method_id') print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editshipping_method_id&amp;id='.$object->id.'">'.img_edit($langs->trans('SetReceptionMethod'), 1).'</a></td>'; + if ($action != 'editshipping_method_id') { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editshipping_method_id&amp;id='.$object->id.'">'.img_edit($langs->trans('SetReceptionMethod'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td colspan="2">'; - if ($action == 'editshipping_method_id') - { + if ($action == 'editshipping_method_id') { print '<form name="setshipping_method_id" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="setshipping_method_id">'; $object->fetch_delivery_methods(); print $form->selectarray("shipping_method_id", $object->meths, $object->shipping_method_id, 1, 0, 0, "", 1); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">'; print '</form>'; } else { - if ($object->shipping_method_id > 0) - { + if ($object->shipping_method_id > 0) { // Get code using getLabelFromKey $code = $langs->getLabelFromKey($db, $object->shipping_method_id, 'c_shipment_mode', 'rowid', 'code'); print $langs->trans("SendingMethod".strtoupper($code)); @@ -1532,19 +1527,20 @@ if ($action == 'create') print '</td></tr>'; // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '<tr><td>'; print '<table width="100%" class="nobordernopadding"><tr><td>'; print $langs->trans('IncotermLabel'); print '<td><td class="right">'; - if ($user->rights->reception->creer) print '<a class="editfielda" href="'.DOL_URL_ROOT.'/reception/card.php?id='.$object->id.'&action=editincoterm">'.img_edit().'</a>'; - else print '&nbsp;'; + if ($user->rights->reception->creer) { + print '<a class="editfielda" href="'.DOL_URL_ROOT.'/reception/card.php?id='.$object->id.'&action=editincoterm">'.img_edit().'</a>'; + } else { + print '&nbsp;'; + } print '</td></tr></table>'; print '</td>'; print '<td colspan="3">'; - if ($action != 'editincoterm') - { + if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1); } else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); @@ -1562,8 +1558,7 @@ if ($action == 'create') // Lines of products - if ($action == 'editline') - { + if ($action == 'editline') { print '<form name="updateline" id="updateline" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;lineid='.$line_id.'" method="POST"> <input type="hidden" name="token" value="' . newToken().'"> <input type="hidden" name="action" value="updateline"> @@ -1576,8 +1571,7 @@ if ($action == 'create') print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; // # - if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) - { + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { print '<td width="5" class="center">&nbsp;</td>'; } // Product/Service @@ -1586,53 +1580,48 @@ if ($action == 'create') print '<td>'.$langs->trans("Description").'</td>'; // Qty print '<td class="center">'.$langs->trans("QtyOrdered").'</td>'; - if ($origin && $origin_id > 0) - { + if ($origin && $origin_id > 0) { print '<td class="center">'.$langs->trans("QtyInOtherReceptions").'</td>'; } - if ($action == 'editline') - { + if ($action == 'editline') { $editColspan = 3; - if (empty($conf->stock->enabled)) $editColspan--; - if (empty($conf->productbatch->enabled)) $editColspan--; + if (empty($conf->stock->enabled)) { + $editColspan--; + } + if (empty($conf->productbatch->enabled)) { + $editColspan--; + } print '<td class="center" colspan="'.$editColspan.'">'; - if ($object->statut <= 1) - { + if ($object->statut <= 1) { print $langs->trans("QtyToReceive").' - '; } else { print $langs->trans("QtyReceived").' - '; } - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print $langs->trans("WarehouseSource").' - '; } - if (!empty($conf->productbatch->enabled)) - { + if (!empty($conf->productbatch->enabled)) { print $langs->trans("Batch"); } print '</td>'; } else { - if ($object->statut <= 1) - { + if ($object->statut <= 1) { print '<td class="center">'.$langs->trans("QtyToReceive").'</td>'; } else { print '<td class="center">'.$langs->trans("QtyReceived").'</td>'; } - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print '<td class="left">'.$langs->trans("WarehouseSource").'</td>'; } - if (!empty($conf->productbatch->enabled)) - { + if (!empty($conf->productbatch->enabled)) { print '<td class="left">'.$langs->trans("Batch").'</td>'; } } print '<td class="center">'.$langs->trans("CalculatedWeight").'</td>'; print '<td class="center">'.$langs->trans("CalculatedVolume").'</td>'; //print '<td class="center">'.$langs->trans("Size").'</td>'; - if ($object->statut == 0) - { + if ($object->statut == 0) { print '<td class="linecoledit"></td>'; print '<td class="linecoldelete" width="10"></td>'; } @@ -1640,15 +1629,17 @@ if ($action == 'create') $var = false; - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $object->fetch_thirdparty(); $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if (empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -1659,8 +1650,7 @@ if ($action == 'create') $origin = 'commande_fournisseur'; - if ($origin && $origin_id > 0) - { + if ($origin && $origin_id > 0) { $sql = "SELECT obj.rowid, obj.fk_product, obj.label, obj.description, obj.product_type as fk_product_type, obj.qty as qty_asked, obj.date_start, obj.date_end"; $sql .= ", ed.rowid as receptionline_id, ed.qty, ed.fk_reception as reception_id, ed.fk_entrepot"; $sql .= ", e.rowid as reception_id, e.ref as reception_ref, e.date_creation, e.date_valid, e.date_delivery, e.date_reception"; @@ -1682,16 +1672,13 @@ if ($action == 'create') dol_syslog("get list of reception lines", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { // $obj->rowid is rowid in $origin."det" table $alreadysent[$obj->rowid][$obj->receptionline_id] = array('reception_ref'=>$obj->reception_ref, 'reception_id'=>$obj->reception_id, 'warehouse'=>$obj->fk_entrepot, 'qty'=>$obj->qty, 'date_valid'=>$obj->date_valid, 'date_delivery'=>$obj->date_delivery); } @@ -1702,27 +1689,25 @@ if ($action == 'create') } // Loop on each product to send/sent - for ($i = 0; $i < $num_prod; $i++) - { + for ($i = 0; $i < $num_prod; $i++) { print '<!-- origin line id = '.$lines[$i]->origin_line_id.' -->'; // id of order line print '<tr class="oddeven">'; // # - if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) - { + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { print '<td class="center">'.($i + 1).'</td>'; } // Predefined product or service - if ($lines[$i]->fk_product > 0) - { + if ($lines[$i]->fk_product > 0) { // Define output language - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $prod = new Product($db); $prod->fetch($lines[$i]->fk_product); $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $lines[$i]->product->label; - } else $label = (!empty($lines[$i]->product->label) ? $lines[$i]->product->label : $lines[$i]->product->product_label); + } else { + $label = (!empty($lines[$i]->product->label) ? $lines[$i]->product->label : $lines[$i]->product->product_label); + } print '<td>'; @@ -1731,15 +1716,17 @@ if ($action == 'create') $description = (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($lines[$i]->product->description)); print $form->textwithtooltip($text, $description, 3, '', '', $i); print_date_range($lines[$i]->date_start, $lines[$i]->date_end); - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { print (!empty($lines[$i]->product->description) && $lines[$i]->description != $lines[$i]->product->description) ? '<br>'.dol_htmlentitiesbr($lines[$i]->description) : ''; } print "</td>\n"; } else { print "<td>"; - if ($lines[$i]->product_type == Product::TYPE_SERVICE) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if ($lines[$i]->product_type == Product::TYPE_SERVICE) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($lines[$i]->label)) { $text .= ' <strong>'.$lines[$i]->label.'</strong>'; @@ -1752,8 +1739,7 @@ if ($action == 'create') print "</td>\n"; } - if ($action == 'editline' && $lines[$i]->id == $line_id) - { + if ($action == 'editline' && $lines[$i]->id == $line_id) { print '<td><textarea name="comment'.$line_id.'" id="comment'.$line_id.'" /> '.$lines[$i]->comment.'</textarea></td>'; } else { print '<td style="white-space: pre-wrap;max-width: 200px;" >'.$lines[$i]->comment.'</td>'; @@ -1764,27 +1750,26 @@ if ($action == 'create') print '<td class="center">'.$lines[$i]->qty_asked.'</td>'; // Qty in other receptions (with reception and warehouse used) - if ($origin && $origin_id > 0) - { + if ($origin && $origin_id > 0) { print '<td class="center nowrap">'; - foreach ($alreadysent as $key => $val) - { - if ($lines[$i]->fk_commandefourndet == $key) - { + foreach ($alreadysent as $key => $val) { + if ($lines[$i]->fk_commandefourndet == $key) { $j = 0; - foreach ($val as $receptionline_id=> $receptionline_var) - { - if ($receptionline_var['reception_id'] == $lines[$i]->fk_reception) continue; // We want to show only "other receptions" + foreach ($val as $receptionline_id => $receptionline_var) { + if ($receptionline_var['reception_id'] == $lines[$i]->fk_reception) { + continue; // We want to show only "other receptions" + } $j++; - if ($j > 1) print '<br>'; + if ($j > 1) { + print '<br>'; + } $reception_static->fetch($receptionline_var['reception_id']); print $reception_static->getNomUrl(1); print ' - '.$receptionline_var['qty']; $htmltext = $langs->trans("DateValidation").' : '.(empty($receptionline_var['date_valid']) ? $langs->trans("Draft") : dol_print_date($receptionline_var['date_valid'], 'dayhour')); - if (!empty($conf->stock->enabled) && $receptionline_var['warehouse'] > 0) - { + if (!empty($conf->stock->enabled) && $receptionline_var['warehouse'] > 0) { $warehousestatic->fetch($receptionline_var['warehouse']); $htmltext .= '<br>'.$langs->trans("From").' : '.$warehousestatic->getNomUrl(1); } @@ -1795,14 +1780,11 @@ if ($action == 'create') } print '</td>'; - if ($action == 'editline' && $lines[$i]->id == $line_id) - { + if ($action == 'editline' && $lines[$i]->id == $line_id) { // edit mode print '<td colspan="'.$editColspan.'" class="center"><table class="nobordernopadding">'; - if (!empty($conf->stock->enabled)) - { - if ($lines[$i]->fk_product > 0) - { + if (!empty($conf->stock->enabled)) { + if ($lines[$i]->fk_product > 0) { print '<!-- case edit 1 -->'; print '<tr>'; // Qty to receive or received @@ -1810,8 +1792,7 @@ if ($action == 'create') // Warehouse source print '<td>'.$formproduct->selectWarehouses($lines[$i]->fk_entrepot, 'entl'.$line_id, '', 1, 0, $lines[$i]->fk_product, '', 1).'</td>'; // Batch number managment - if ($conf->productbatch->enabled && !empty($lines[$i]->product->status_batch)) - { + if ($conf->productbatch->enabled && !empty($lines[$i]->product->status_batch)) { print '<td> <input name="batch'.$line_id.'" id="batch'.$line_id.'" type="text" value="'.$lines[$i]->batch.'"> </br>'; if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { print $langs->trans('EatByDate').' : '; @@ -1842,12 +1823,10 @@ if ($action == 'create') print '<td class="center">'.$lines[$i]->qty.'</td>'; // Warehouse source - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print '<td class="left">'; - if ($lines[$i]->fk_entrepot > 0) - { + if ($lines[$i]->fk_entrepot > 0) { $entrepot = new Entrepot($db); $entrepot->fetch($lines[$i]->fk_entrepot); print $entrepot->getNomUrl(1); @@ -1857,15 +1836,12 @@ if ($action == 'create') } // Batch number managment - if (!empty($conf->productbatch->enabled)) - { - if (isset($lines[$i]->batch)) - { + if (!empty($conf->productbatch->enabled)) { + if (isset($lines[$i]->batch)) { print '<!-- Detail of lot -->'; print '<td>'; $detail = ''; - if ($lines[$i]->product->status_batch) - { + if ($lines[$i]->product->status_batch) { $detail .= $langs->trans("Batch").': '.$lines[$i]->batch; if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { $detail .= ' - '.$langs->trans("SellByDate").': '.dol_print_date($lines[$i]->sellby, "day"); @@ -1888,24 +1864,28 @@ if ($action == 'create') // Weight print '<td class="center">'; - if ($lines[$i]->fk_product_type == Product::TYPE_PRODUCT) print $lines[$i]->product->weight * $lines[$i]->qty.' '.measuringUnitString(0, "weight", $lines[$i]->product->weight_units); - else print '&nbsp;'; + if ($lines[$i]->fk_product_type == Product::TYPE_PRODUCT) { + print $lines[$i]->product->weight * $lines[$i]->qty.' '.measuringUnitString(0, "weight", $lines[$i]->product->weight_units); + } else { + print '&nbsp;'; + } print '</td>'; // Volume print '<td class="center">'; - if ($lines[$i]->fk_product_type == Product::TYPE_PRODUCT) print $lines[$i]->product->volume * $lines[$i]->qty.' '.measuringUnitString(0, "volume", $lines[$i]->product->volume_units); - else print '&nbsp;'; + if ($lines[$i]->fk_product_type == Product::TYPE_PRODUCT) { + print $lines[$i]->product->volume * $lines[$i]->qty.' '.measuringUnitString(0, "volume", $lines[$i]->product->volume_units); + } else { + print '&nbsp;'; + } print '</td>'; - if ($action == 'editline' && $lines[$i]->id == $line_id) - { + if ($action == 'editline' && $lines[$i]->id == $line_id) { print '<td class="center" colspan="2" valign="middle">'; print '<input type="submit" class="button button-save" id="savelinebutton marginbottomonly" name="save" value="'.$langs->trans("Save").'"><br>'; print '<input type="submit" class="button button-cancel" id="cancellinebutton" name="cancel" value="'.$langs->trans("Cancel").'"><br>'; - } elseif ($object->statut == Reception::STATUS_DRAFT) - { + } elseif ($object->statut == Reception::STATUS_DRAFT) { // edit-delete buttons print '<td class="linecoledit center">'; print '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=editline&amp;token='.newToken().'&amp;lineid='.$lines[$i]->id.'">'.img_edit().'</a>'; @@ -1915,8 +1895,7 @@ if ($action == 'create') print '</td>'; // Display lines extrafields - if (!empty($rowExtrafieldsStart)) - { + if (!empty($rowExtrafieldsStart)) { print $rowExtrafieldsStart; print $rowExtrafieldsView; print $rowEnd; @@ -1925,15 +1904,13 @@ if ($action == 'create') print "</tr>"; // Display lines extrafields - if (is_array($extralabelslines) && count($extralabelslines) > 0) - { + if (is_array($extralabelslines) && count($extralabelslines) > 0) { $colspan = empty($conf->productbatch->enabled) ? 8 : 9; $line = new CommandeFournisseurDispatch($db); $line->id = $lines[$i]->id; $line->fetch_optionals(); - if ($action == 'editline' && $lines[$i]->id == $line_id) - { + if ($action == 'editline' && $lines[$i]->id == $line_id) { print $line->showOptionals($extrafields, 'edit', array('colspan'=>$colspan), $indiceAsked); } else { print $line->showOptionals($extrafields, 'view', array('colspan'=>$colspan), $indiceAsked); @@ -1958,19 +1935,15 @@ if ($action == 'create') * Boutons actions */ - if (($user->socid == 0) && ($action != 'presend')) - { + if (($user->socid == 0) && ($action != 'presend')) { print '<div class="tabsAction">'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { - if ($object->statut == Reception::STATUS_DRAFT && $num_prod > 0) - { + if (empty($reshook)) { + if ($object->statut == Reception::STATUS_DRAFT && $num_prod > 0) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->reception_advance->validate))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->reception_advance->validate))) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid">'.$langs->trans("Validate").'</a>'; } else { print '<a class="butActionRefused" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans("Validate").'</a>'; @@ -1983,10 +1956,8 @@ if ($action == 'create') // TODO add alternative status // 0=draft, 1=validated, 2=billed, we miss a status "delivered" (only available on order) - if ($object->statut == Reception::STATUS_CLOSED && $user->rights->reception->creer) - { - if (!empty($conf->facture->enabled) && !empty($conf->global->WORKFLOW_BILL_ON_RECEPTION)) // Quand l'option est on, il faut avoir le bouton en plus et non en remplacement du Close ? - { + if ($object->statut == Reception::STATUS_CLOSED && $user->rights->reception->creer) { + if (!empty($conf->facture->enabled) && !empty($conf->global->WORKFLOW_BILL_ON_RECEPTION)) { // Quand l'option est on, il faut avoir le bouton en plus et non en remplacement du Close ? print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("ClassifyUnbilled").'</a>'; } else { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("ReOpen").'</a>'; @@ -1995,20 +1966,18 @@ if ($action == 'create') // Send if (empty($user->socid)) { - if ($object->statut > 0) - { - if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->reception->reception_advance->send) - { + if ($object->statut > 0) { + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->reception->reception_advance->send) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendByMail').'</a>'; - } else print '<a class="butActionRefused" href="#">'.$langs->trans('SendByMail').'</a>'; + } else { + print '<a class="butActionRefused" href="#">'.$langs->trans('SendByMail').'</a>'; + } } } // Create bill - if (!empty($conf->fournisseur->enabled) && ($object->statut == Reception::STATUS_VALIDATED || $object->statut == Reception::STATUS_CLOSED)) - { - if ($user->rights->fournisseur->facture->creer) - { + if (!empty($conf->fournisseur->enabled) && ($object->statut == Reception::STATUS_VALIDATED || $object->statut == Reception::STATUS_CLOSED)) { + if ($user->rights->fournisseur->facture->creer) { // TODO show button only if (! empty($conf->global->WORKFLOW_BILL_ON_RECEPTION)) // If we do that, we must also make this option official. print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("CreateBill").'</a>'; @@ -2017,14 +1986,11 @@ if ($action == 'create') // Close - if ($object->statut == Reception::STATUS_VALIDATED) - { - if ($user->rights->reception->creer && $object->statut > 0 && !$object->billed) - { + if ($object->statut == Reception::STATUS_VALIDATED) { + if ($user->rights->reception->creer && $object->statut > 0 && !$object->billed) { $label = "Close"; $paramaction = 'classifyclosed'; // = Transferred/Received // Label here should be "Close" or "ClassifyBilled" if we decided to make bill on receptions instead of orders - if (!empty($conf->fournisseur->enabled) && !empty($conf->global->WORKFLOW_BILL_ON_RECEPTION)) // Quand l'option est on, il faut avoir le bouton en plus et non en remplacement du Close ? - { + if (!empty($conf->fournisseur->enabled) && !empty($conf->global->WORKFLOW_BILL_ON_RECEPTION)) { // Quand l'option est on, il faut avoir le bouton en plus et non en remplacement du Close ? $label = "ClassifyBilled"; $paramaction = 'classifybilled'; } @@ -2032,8 +1998,7 @@ if ($action == 'create') } } - if ($user->rights->reception->supprimer) - { + if ($user->rights->reception->supprimer) { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans("Delete").'</a>'; } } @@ -2046,8 +2011,7 @@ if ($action == 'create') * Documents generated */ - if ($action != 'presend' && $action != 'editline') - { + if ($action != 'presend' && $action != 'editline') { print '<div class="fichecenter"><div class="fichehalfleft">'; $objectref = dol_sanitizeFileName($object->ref); diff --git a/htdocs/reception/class/reception.class.php b/htdocs/reception/class/reception.class.php index f53c2bc466d..a8a55c7faf2 100644 --- a/htdocs/reception/class/reception.class.php +++ b/htdocs/reception/class/reception.class.php @@ -35,8 +35,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php"; require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php'; -if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; -if (!empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +if (!empty($conf->propal->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +} +if (!empty($conf->commande->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +} /** @@ -156,8 +160,7 @@ class Reception extends CommonObject global $langs, $conf; $langs->load("receptions"); - if (!empty($conf->global->RECEPTION_ADDON_NUMBER)) - { + if (!empty($conf->global->RECEPTION_ADDON_NUMBER)) { $mybool = false; $file = $conf->global->RECEPTION_ADDON_NUMBER.".php"; @@ -173,8 +176,7 @@ class Reception extends CommonObject $mybool |= @include_once $dir.$file; } - if (!$mybool) - { + if (!$mybool) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -184,8 +186,7 @@ class Reception extends CommonObject $numref = ""; $numref = $obj->getNextValue($soc, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { dol_print_error($this->db, get_class($this)."::getNextNumRef ".$obj->error); @@ -216,9 +217,15 @@ class Reception extends CommonObject // Clean parameters $this->brouillon = 1; $this->tracking_number = dol_sanitizeFileName($this->tracking_number); - if (empty($this->fk_project)) $this->fk_project = 0; - if (empty($this->weight_units)) $this->weight_units = 0; - if (empty($this->size_units)) $this->size_units = 0; + if (empty($this->fk_project)) { + $this->fk_project = 0; + } + if (empty($this->weight_units)) { + $this->weight_units = 0; + } + if (empty($this->size_units)) { + $this->size_units = 0; + } $this->user = $user; @@ -276,8 +283,7 @@ class Reception extends CommonObject $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."reception"); $sql = "UPDATE ".MAIN_DB_PREFIX."reception"; @@ -285,51 +291,46 @@ class Reception extends CommonObject $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::create", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { // Insert of lines $num = count($this->lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $this->lines[$i]->fk_reception = $this->id; - if (!$this->lines[$i]->create($user) > 0) - { + if (!$this->lines[$i]->create($user) > 0) { $error++; } } - if (!$error && $this->id && $this->origin_id) - { + if (!$error && $this->id && $this->origin_id) { $ret = $this->add_object_linked(); - if (!$ret) - { + if (!$ret) { $error++; } } // Create extrafields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('RECEPTION_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -366,7 +367,9 @@ class Reception extends CommonObject global $conf; // Check parameters - if (empty($id) && empty($ref) && empty($ref_ext)) return -1; + if (empty($id) && empty($ref) && empty($ref_ext)) { + return -1; + } $sql = "SELECT e.rowid, e.ref, e.fk_soc as socid, e.date_creation, e.ref_supplier, e.ref_ext, e.fk_user_author, e.fk_statut"; $sql .= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height"; @@ -380,17 +383,23 @@ class Reception extends CommonObject $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = e.rowid AND el.targettype = '".$this->db->escape($this->element)."'"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON e.fk_incoterms = i.rowid'; $sql .= " WHERE e.entity IN (".getEntity('reception').")"; - if ($id) $sql .= " AND e.rowid=".$id; - if ($ref) $sql .= " AND e.ref='".$this->db->escape($ref)."'"; - if ($ref_ext) $sql .= " AND e.ref_ext='".$this->db->escape($ref_ext)."'"; - if ($notused) $sql .= " AND e.ref_int='".$this->db->escape($notused)."'"; + if ($id) { + $sql .= " AND e.rowid=".$id; + } + if ($ref) { + $sql .= " AND e.ref='".$this->db->escape($ref)."'"; + } + if ($ref_ext) { + $sql .= " AND e.ref_ext='".$this->db->escape($ref_ext)."'"; + } + if ($notused) { + $sql .= " AND e.ref_int='".$this->db->escape($notused)."'"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -437,7 +446,9 @@ class Reception extends CommonObject $this->db->free($result); - if ($this->statut == 0) $this->brouillon = 1; + if ($this->statut == 0) { + $this->brouillon = 1; + } $file = $conf->reception->dir_output."/".get_exdir($this->id, 2, 0, 0, $this, 'reception')."/".$this->id.".pdf"; $this->pdf_filename = $file; @@ -462,8 +473,7 @@ class Reception extends CommonObject * Lines */ $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { return -3; } @@ -495,15 +505,13 @@ class Reception extends CommonObject dol_syslog(get_class($this)."::valid"); // Protection - if ($this->statut) - { + if ($this->statut) { dol_syslog(get_class($this)."::valid no draft status", LOG_WARNING); return 0; } if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->reception_advance->validate)))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->reception_advance->validate)))) { $this->error = 'Permission denied'; dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); return -1; @@ -519,8 +527,7 @@ class Reception extends CommonObject // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $numref = $this->getNextNumRef($soc); } else { $numref = $this->ref; @@ -539,15 +546,13 @@ class Reception extends CommonObject $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::valid update reception", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->lasterror(); $error++; } // If stock increment is done on reception (recommanded choice) - if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)) - { + if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); @@ -564,24 +569,23 @@ class Reception extends CommonObject dol_syslog(get_class($this)."::valid select details", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $cpt = $this->db->num_rows($resql); - for ($i = 0; $i < $cpt; $i++) - { + for ($i = 0; $i < $cpt; $i++) { $obj = $this->db->fetch_object($resql); $qty = $obj->qty; - if ($qty <= 0) continue; + if ($qty <= 0) { + continue; + } dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid); //var_dump($this->lines[$i]); $mouvS = new MouvementStock($this->db); $mouvS->origin = &$this; - if (empty($obj->batch)) - { + if (empty($obj->batch)) { // line without batch detail // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record. @@ -616,48 +620,45 @@ class Reception extends CommonObject // Change status of order to "reception in process" $ret = $this->setStatut(4, $this->origin_id, 'commande_fournisseur'); - if (!$ret) - { + if (!$ret) { $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('RECEPTION_VALIDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'reception/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'reception/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($numref); $dirsource = $conf->reception->dir_output.'/'.$oldref; $dirdest = $conf->reception->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->reception->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -670,19 +671,16 @@ class Reception extends CommonObject } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $numref; $this->statut = 1; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::valid ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -722,12 +720,10 @@ class Reception extends CommonObject $supplierorderline = new CommandeFournisseurLigne($this->db); $supplierorderline->fetch($id); - if (!empty($conf->stock->enabled) && !empty($supplierorderline->fk_product)) - { + if (!empty($conf->stock->enabled) && !empty($supplierorderline->fk_product)) { $fk_product = $supplierorderline->fk_product; - if (!($entrepot_id > 0) && empty($conf->global->STOCK_WAREHOUSE_NOT_REQUIRED_FOR_RECEPTIONS)) - { + if (!($entrepot_id > 0) && empty($conf->global->STOCK_WAREHOUSE_NOT_REQUIRED_FOR_RECEPTIONS)) { $langs->load("errors"); $this->error = $langs->trans("ErrorWarehouseRequiredIntoReceptionLine"); return -1; @@ -736,8 +732,7 @@ class Reception extends CommonObject // extrafields $line->array_options = $supplierorderline->array_options; - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) - { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) { foreach ($array_options as $key => $value) { $line->array_options[$key] = $value; } @@ -773,24 +768,60 @@ class Reception extends CommonObject // Clean parameters - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->entity)) $this->entity = trim($this->entity); - if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier); - if (isset($this->socid)) $this->socid = trim($this->socid); - if (isset($this->fk_user_author)) $this->fk_user_author = trim($this->fk_user_author); - if (isset($this->fk_user_valid)) $this->fk_user_valid = trim($this->fk_user_valid); - if (isset($this->shipping_method_id)) $this->shipping_method_id = trim($this->shipping_method_id); - if (isset($this->tracking_number)) $this->tracking_number = trim($this->tracking_number); - if (isset($this->statut)) $this->statut = (int) $this->statut; - if (isset($this->trueDepth)) $this->trueDepth = trim($this->trueDepth); - if (isset($this->trueWidth)) $this->trueWidth = trim($this->trueWidth); - if (isset($this->trueHeight)) $this->trueHeight = trim($this->trueHeight); - if (isset($this->size_units)) $this->size_units = trim($this->size_units); - if (isset($this->weight_units)) $this->weight_units = trim($this->weight_units); - if (isset($this->trueWeight)) $this->weight = trim($this->trueWeight); - if (isset($this->note_private)) $this->note_private = trim($this->note_private); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf); + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->entity)) { + $this->entity = trim($this->entity); + } + if (isset($this->ref_supplier)) { + $this->ref_supplier = trim($this->ref_supplier); + } + if (isset($this->socid)) { + $this->socid = trim($this->socid); + } + if (isset($this->fk_user_author)) { + $this->fk_user_author = trim($this->fk_user_author); + } + if (isset($this->fk_user_valid)) { + $this->fk_user_valid = trim($this->fk_user_valid); + } + if (isset($this->shipping_method_id)) { + $this->shipping_method_id = trim($this->shipping_method_id); + } + if (isset($this->tracking_number)) { + $this->tracking_number = trim($this->tracking_number); + } + if (isset($this->statut)) { + $this->statut = (int) $this->statut; + } + if (isset($this->trueDepth)) { + $this->trueDepth = trim($this->trueDepth); + } + if (isset($this->trueWidth)) { + $this->trueWidth = trim($this->trueWidth); + } + if (isset($this->trueHeight)) { + $this->trueHeight = trim($this->trueHeight); + } + if (isset($this->size_units)) { + $this->size_units = trim($this->size_units); + } + if (isset($this->weight_units)) { + $this->weight_units = trim($this->weight_units); + } + if (isset($this->trueWeight)) { + $this->weight = trim($this->trueWeight); + } + if (isset($this->note_private)) { + $this->note_private = trim($this->note_private); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->model_pdf)) { + $this->model_pdf = trim($this->model_pdf); + } // Check parameters @@ -822,30 +853,30 @@ class Reception extends CommonObject $sql .= " model_pdf=".(isset($this->modelpdf) ? "'".$this->db->escape($this->modelpdf)."'" : "null").","; $sql .= " entity=".$conf->entity; - $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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('RECEPTION_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -875,8 +906,7 @@ class Reception extends CommonObject $this->db->begin(); // Stock control - if ($conf->stock->enabled && $conf->global->STOCK_CALCULATE_ON_RECEPTION && $this->statut > 0) - { + if ($conf->stock->enabled && $conf->global->STOCK_CALCULATE_ON_RECEPTION && $this->statut > 0) { require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php"; $langs->load("agenda"); @@ -890,11 +920,9 @@ class Reception extends CommonObject dol_syslog(get_class($this)."::delete select details", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $cpt = $this->db->num_rows($resql); - for ($i = 0; $i < $cpt; $i++) - { + for ($i = 0; $i < $cpt; $i++) { dol_syslog(get_class($this)."::delete movement index ".$i); $obj = $this->db->fetch_object($resql); @@ -909,8 +937,7 @@ class Reception extends CommonObject } } - if (!$error) - { + if (!$error) { $main = MAIN_DB_PREFIX.'commande_fournisseur_dispatch'; $ef = $main."_extrafields"; $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_reception = ".$this->id.")"; @@ -918,61 +945,53 @@ class Reception extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur_dispatch"; $sql .= " WHERE fk_reception = ".$this->id; - if ($this->db->query($sqlef) && $this->db->query($sql)) - { + if ($this->db->query($sqlef) && $this->db->query($sql)) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."reception"; $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { // Call trigger $result = $this->call_trigger('RECEPTION_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers - if (!empty($this->origin) && $this->origin_id > 0) - { + if (!empty($this->origin) && $this->origin_id > 0) { $this->fetch_origin(); $origin = $this->origin; - if ($this->$origin->statut == 4) // If order source of reception is "partially received" - { + if ($this->$origin->statut == 4) { // If order source of reception is "partially received" // Check if there is no more reception. If not, we can move back status of order to "validated" instead of "reception in progress" $this->$origin->loadReceptions(); //var_dump($this->$origin->receptions);exit; - if (count($this->$origin->receptions) <= 0) - { + if (count($this->$origin->receptions) <= 0) { $this->$origin->setStatut(3); // ordered } } } - if (!$error) - { + if (!$error) { $this->db->commit(); // We delete PDFs $ref = dol_sanitizeFileName($this->ref); - if (!empty($conf->reception->dir_output)) - { + if (!empty($conf->reception->dir_output)) { $dir = $conf->reception->dir_output.'/'.$ref; $file = $dir.'/'.$ref.'.pdf'; - if (file_exists($file)) - { - if (!dol_delete_file($file)) - { + if (file_exists($file)) { + if (!dol_delete_file($file)) { return 0; } } - if (file_exists($dir)) - { - if (!dol_delete_dir_recursive($dir)) - { + if (file_exists($dir)) { + if (!dol_delete_dir_recursive($dir)) { $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir); return 0; } @@ -1081,13 +1100,13 @@ class Reception extends CommonObject $url = DOL_URL_ROOT.'/reception/card.php?id='.$this->id; - if ($short) return $url; + if ($short) { + return $url; + } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("Reception"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -1099,8 +1118,12 @@ class Reception extends CommonObject $linkstart .= $linkclose.'>'; $linkend = '</a>'; - if ($withpicto) $result .= ($linkstart.img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend); - if ($withpicto && $withpicto != 2) $result .= ' '; + if ($withpicto) { + $result .= ($linkstart.img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } $result .= $linkstart.$this->ref.$linkend; return $result; } @@ -1133,8 +1156,12 @@ class Reception extends CommonObject $labelStatusShort = $langs->trans($this->statutshorts[$status]); $statusType = 'status'.$status; - if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; - if ($status == self::STATUS_CLOSED) $statusType = 'status6'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } + if ($status == self::STATUS_CLOSED) { + $statusType = 'status6'; + } return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); } @@ -1165,12 +1192,10 @@ class Reception extends CommonObject $sql .= $this->db->plimit(100); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -1206,8 +1231,7 @@ class Reception extends CommonObject $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new CommandeFournisseurDispatch($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; $line->libelle = $langs->trans("Description")." ".$xnbp; @@ -1230,16 +1254,14 @@ class Reception extends CommonObject public function setDeliveryDate($user, $delivery_date) { // phpcs:enable - if ($user->rights->reception->creer) - { + if ($user->rights->reception->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."reception"; $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null'); $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->date_delivery = $delivery_date; return 1; } else { @@ -1269,10 +1291,8 @@ class Reception extends CommonObject $sql .= " ORDER BY em.libelle ASC"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $label = $langs->trans('ReceptionMethod'.$obj->code); $this->meths[$obj->rowid] = ($label != 'ReceptionMethod'.$obj->code ? $label : $obj->libelle); } @@ -1296,7 +1316,9 @@ class Reception extends CommonObject $sql = "SELECT em.rowid, em.code, em.libelle, em.description, em.tracking, em.active"; $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em"; - if ($id != '') $sql .= " WHERE em.rowid=".$id; + if ($id != '') { + $sql .= " WHERE em.rowid=".$id; + } $resql = $this->db->query($sql); if ($resql) { @@ -1324,8 +1346,7 @@ class Reception extends CommonObject public function update_delivery_method($id = '') { // phpcs:enable - if ($id == '') - { + if ($id == '') { $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_shipment_mode (code, libelle, description, tracking)"; $sql .= " VALUES ('".$this->db->escape($this->update['code'])."','".$this->db->escape($this->update['libelle'])."','".$this->db->escape($this->update['description'])."','".$this->db->escape($this->update['tracking'])."')"; $resql = $this->db->query($sql); @@ -1338,7 +1359,9 @@ class Reception extends CommonObject $sql .= " WHERE rowid=".$id; $resql = $this->db->query($sql); } - if ($resql < 0) dol_print_error($this->db, ''); + if ($resql < 0) { + dol_print_error($this->db, ''); + } } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1384,24 +1407,20 @@ class Reception extends CommonObject */ public function getUrlTrackingStatus($value = '') { - if (!empty($this->shipping_method_id)) - { + if (!empty($this->shipping_method_id)) { $sql = "SELECT em.code, em.tracking"; $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em"; $sql .= " WHERE em.rowid = ".$this->shipping_method_id; $resql = $this->db->query($sql); - if ($resql) - { - if ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + if ($obj = $this->db->fetch_object($resql)) { $tracking = $obj->tracking; } } } - if (!empty($tracking) && !empty($value)) - { + if (!empty($tracking) && !empty($value)) { $url = str_replace('{TRACKID}', $value, $tracking); $this->tracking_url = sprintf('<a target="_blank" href="%s">'.($value ? $value : 'url').'</a>', $url, $url); } else { @@ -1426,31 +1445,26 @@ class Reception extends CommonObject $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0'; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Set order billed if 100% of order is received (qty in reception lines match qty in order lines) - if ($this->origin == 'order_supplier' && $this->origin_id > 0) - { + if ($this->origin == 'order_supplier' && $this->origin_id > 0) { $order = new CommandeFournisseur($this->db); $order->fetch($this->origin_id); $order->loadReceptions(self::STATUS_CLOSED); // Fill $order->receptions = array(orderlineid => qty) $receptions_match_order = 1; - foreach ($order->lines as $line) - { + foreach ($order->lines as $line) { $lineid = $line->id; $qty = $line->qty; - if (($line->product_type == 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) && $order->receptions[$lineid] < $qty) - { + if (($line->product_type == 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) && $order->receptions[$lineid] < $qty) { $receptions_match_order = 0; $text = 'Qty for order line id '.$lineid.' is '.$qty.'. However in the receptions with status Reception::STATUS_CLOSED='.self::STATUS_CLOSED.' we have qty = '.$order->receptions[$lineid].', so we can t close order'; dol_syslog($text); break; } } - if ($receptions_match_order) - { + if ($receptions_match_order) { dol_syslog("Qty for the ".count($order->lines)." lines of order have same value for receptions with status Reception::STATUS_CLOSED=".self::STATUS_CLOSED.', so we close order'); $order->Livraison($user, dol_now(), 'tot', 'Reception '.$this->ref); } @@ -1460,8 +1474,7 @@ class Reception extends CommonObject // If stock increment is done on closing - if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) - { + if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); @@ -1479,23 +1492,22 @@ class Reception extends CommonObject dol_syslog(get_class($this)."::valid select details", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $cpt = $this->db->num_rows($resql); - for ($i = 0; $i < $cpt; $i++) - { + for ($i = 0; $i < $cpt; $i++) { $obj = $this->db->fetch_object($resql); $qty = $obj->qty; - if ($qty <= 0) continue; + if ($qty <= 0) { + continue; + } dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid); $mouvS = new MouvementStock($this->db); $mouvS->origin = &$this; - if (empty($obj->batch)) - { + if (empty($obj->batch)) { // line without batch detail // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record @@ -1525,8 +1537,7 @@ class Reception extends CommonObject } // Call trigger - if (!$error) - { + if (!$error) { $result = $this->call_trigger('RECEPTION_CLOSED', $user); if ($result < 0) { $error++; @@ -1537,8 +1548,7 @@ class Reception extends CommonObject $error++; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1580,8 +1590,7 @@ class Reception extends CommonObject $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0'; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->statut = 2; $this->billed = 1; @@ -1621,14 +1630,12 @@ class Reception extends CommonObject $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0'; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->statut = 1; $this->billed = 0; // If stock increment is done on closing - if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) - { + if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $numref = $this->ref; $langs->load("agenda"); @@ -1645,16 +1652,16 @@ class Reception extends CommonObject dol_syslog(get_class($this)."::valid select details", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $cpt = $this->db->num_rows($resql); - for ($i = 0; $i < $cpt; $i++) - { + for ($i = 0; $i < $cpt; $i++) { $obj = $this->db->fetch_object($resql); $qty = $obj->qty; - if ($qty <= 0) continue; + if ($qty <= 0) { + continue; + } dol_syslog(get_class($this)."::reopen reception movement index ".$i." ed.rowid=".$obj->rowid); @@ -1662,8 +1669,7 @@ class Reception extends CommonObject $mouvS = new MouvementStock($this->db); $mouvS->origin = &$this; - if (empty($obj->batch)) - { + if (empty($obj->batch)) { // line without batch detail // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record @@ -1691,14 +1697,13 @@ class Reception extends CommonObject } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('RECEPTION_REOPEN', $user); if ($result < 0) { $error++; } - } + } if ($this->origin == 'order_supplier') { $commande = new CommandeFournisseur($this->db); @@ -1710,8 +1715,7 @@ class Reception extends CommonObject $this->errors[] = $this->db->lasterror(); } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1734,14 +1738,12 @@ class Reception extends CommonObject $error = 0; // Protection - if ($this->statut <= self::STATUS_DRAFT) - { + if ($this->statut <= self::STATUS_DRAFT) { return 0; } if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->reception_advance->validate)))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->reception_advance->validate)))) { $this->error = 'Permission denied'; return -1; } @@ -1753,11 +1755,9 @@ class Reception extends CommonObject $sql .= " WHERE rowid = ".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { // If stock increment is done on closing - if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)) - { + if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); @@ -1774,25 +1774,24 @@ class Reception extends CommonObject dol_syslog(get_class($this)."::valid select details", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $cpt = $this->db->num_rows($resql); - for ($i = 0; $i < $cpt; $i++) - { + for ($i = 0; $i < $cpt; $i++) { $obj = $this->db->fetch_object($resql); $qty = $obj->qty; - if ($qty <= 0) continue; + if ($qty <= 0) { + continue; + } dol_syslog(get_class($this)."::reopen reception movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid); //var_dump($this->lines[$i]); $mouvS = new MouvementStock($this->db); $mouvS->origin = &$this; - if (empty($obj->batch)) - { + if (empty($obj->batch)) { // line without batch detail // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record @@ -1824,32 +1823,27 @@ class Reception extends CommonObject if (!$error) { // Call trigger $result = $this->call_trigger('RECEPTION_UNVALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if ($this->origin == 'order_supplier') - { - if (!empty($this->origin) && $this->origin_id > 0) - { + if ($this->origin == 'order_supplier') { + if (!empty($this->origin) && $this->origin_id > 0) { $this->fetch_origin(); $origin = $this->origin; - if ($this->$origin->statut == 4) // If order source of reception is "partially received" - { + if ($this->$origin->statut == 4) { // If order source of reception is "partially received" // Check if there is no more reception validated. $this->$origin->fetchObjectLinked(); $setStatut = 1; - if (!empty($this->$origin->linkedObjects['reception'])) - { - foreach ($this->$origin->linkedObjects['reception'] as $rcption) - { - if ($rcption->statut > 0) - { + if (!empty($this->$origin->linkedObjects['reception'])) { + foreach ($this->$origin->linkedObjects['reception'] as $rcption) { + if ($rcption->statut > 0) { $setStatut = 0; break; } } //var_dump($this->$origin->receptions);exit; - if ($setStatut) - { + if ($setStatut) { $this->$origin->setStatut(3); // ordered } } @@ -1888,8 +1882,7 @@ class Reception extends CommonObject $langs->load("receptions"); - if (!dol_strlen($modele)) - { + if (!dol_strlen($modele)) { $modele = 'squille'; if ($this->model_pdf) { diff --git a/htdocs/reception/class/receptionstats.class.php b/htdocs/reception/class/receptionstats.class.php index 297f99e53b0..3e28d96bc49 100644 --- a/htdocs/reception/class/receptionstats.class.php +++ b/htdocs/reception/class/receptionstats.class.php @@ -70,12 +70,15 @@ class ReceptionStats extends Stats //$this->where.= " AND c.fk_soc = s.rowid AND c.entity = ".$conf->entity; $this->where .= " AND c.entity = ".$conf->entity; - if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($this->socid) - { + if (!$user->rights->societe->client->voir && !$this->socid) { + $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($this->socid) { $this->where .= " AND c.fk_soc = ".$this->socid; } - if ($this->userid > 0) $this->where .= ' AND c.fk_user_author = '.$this->userid; + if ($this->userid > 0) { + $this->where .= ' AND c.fk_user_author = '.$this->userid; + } } /** @@ -114,7 +117,9 @@ class ReceptionStats extends Stats $sql = "SELECT date_format(c.date_valid,'%Y') as dm, COUNT(*) as nb, SUM(c.".$this->field.")"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE ".$this->where; $sql .= " GROUP BY dm"; $sql .= $this->db->order('dm', 'DESC'); @@ -133,7 +138,9 @@ class ReceptionStats extends Stats $sql = "SELECT date_format(c.date_valid,'%Y') as year, COUNT(*) as nb, SUM(c.".$this->field.") as total, AVG(".$this->field.") as avg"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE ".$this->where; $sql .= " GROUP BY year"; $sql .= $this->db->order('year', 'DESC'); diff --git a/htdocs/reception/contact.php b/htdocs/reception/contact.php index ad8811a4e1f..f814bbbf64a 100644 --- a/htdocs/reception/contact.php +++ b/htdocs/reception/contact.php @@ -44,17 +44,17 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'reception', $id, ''); $object = new Reception($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch($id, $ref); $object->fetch_thirdparty(); - if (!empty($object->origin)) - { + if (!empty($object->origin)) { $origin = $object->origin; $object->fetch_origin(); @@ -62,8 +62,7 @@ if ($id > 0 || !empty($ref)) } // Linked documents - if ($origin == 'order_supplier' && $object->$typeobject->id && !empty($conf->fournisseur->enabled)) - { + if ($origin == 'order_supplier' && $object->$typeobject->id && !empty($conf->fournisseur->enabled)) { $objectsrc = new CommandeFournisseur($db); $objectsrc->fetch($object->$typeobject->id); } @@ -74,22 +73,18 @@ if ($id > 0 || !empty($ref)) * Actions */ -if ($action == 'addcontact' && $user->rights->reception->creer) -{ - if ($result > 0 && $id > 0) - { +if ($action == 'addcontact' && $user->rights->reception->creer) { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $objectsrc->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($objectsrc->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($objectsrc->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); $mesg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); } else { @@ -98,21 +93,14 @@ if ($action == 'addcontact' && $user->rights->reception->creer) } setEventMessages($mesg, $mesgs, 'errors'); } -} - -// bascule du statut d'un contact -elseif ($action == 'swapstatut' && $user->rights->reception->creer) -{ +} elseif ($action == 'swapstatut' && $user->rights->reception->creer) { + // bascule du statut d'un contact $result = $objectsrc->swapContactStatus(GETPOST('ligne')); -} - -// Efface un contact -elseif ($action == 'deletecontact' && $user->rights->reception->creer) -{ +} elseif ($action == 'deletecontact' && $user->rights->reception->creer) { + // Efface un contact $result = $objectsrc->delete_contact(GETPOST("lineid")); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -147,8 +135,7 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $langs->trans("OrderCard"); $head = reception_prepare_head($object); @@ -210,8 +197,7 @@ if ($id > 0 || !empty($ref)) print '<table class="border centpercent">'; // Linked documents - if ($origin == 'order_supplier' && $object->$typeobject->id && !empty($conf->fournisseur->enabled)) - { + if ($origin == 'order_supplier' && $object->$typeobject->id && !empty($conf->fournisseur->enabled)) { print '<tr><td class="titlefield">'; $objectsrc = new CommandeFournisseur($db); $objectsrc->fetch($object->$typeobject->id); @@ -221,8 +207,7 @@ if ($id > 0 || !empty($ref)) print "</td>\n"; print '</tr>'; } - if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) - { + if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) { print '<tr><td class="titlefield">'; $objectsrc = new Propal($db); $objectsrc->fetch($object->$typeobject->id); @@ -256,10 +241,11 @@ if ($id > 0 || !empty($ref)) // Contacts lines (modules that overwrite templates must declare this into descriptor) $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); - foreach ($dirtpls as $reldir) - { + foreach ($dirtpls as $reldir) { $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); - if ($res) break; + if ($res) { + break; + } } } diff --git a/htdocs/reception/index.php b/htdocs/reception/index.php index f707196b766..3aa6b8af754 100644 --- a/htdocs/reception/index.php +++ b/htdocs/reception/index.php @@ -53,8 +53,7 @@ print load_fiche_titre($langs->trans("ReceptionsArea"), '', 'dollyrevert'); print '<div class="fichecenter"><div class="fichethirdleft">'; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo print '<form method="post" action="list.php">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<div class="div-table-responsive-no-min">'; @@ -79,30 +78,28 @@ $sql .= " FROM ".MAIN_DB_PREFIX."reception as e"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON e.rowid = el.fk_target AND el.targettype = 'reception'"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseur as c ON el.fk_source = c.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = e.fk_soc"; -if (!$user->rights->societe->client->voir && !$socid) -{ +if (!$user->rights->societe->client->voir && !$socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON e.fk_soc = sc.fk_soc"; $sql .= $clause." sc.fk_user = ".$user->id; $clause = " AND "; } $sql .= $clause." e.fk_statut = 0"; $sql .= " AND e.entity IN (".getEntity('reception').")"; -if ($socid) $sql .= " AND c.fk_soc = ".$socid; +if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; +} $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="3">'.$langs->trans("ReceptionsToValidate").'</th></tr>'; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $reception->id = $obj->rowid; @@ -116,7 +113,9 @@ if ($resql) print '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$obj->socid.'">'.$obj->name.'</a>'; print '</td>'; print '<td>'; - if ($obj->commande_fournisseur_id) print '<a href="'.DOL_URL_ROOT.'/commande_fournisseur/card.php?id='.$obj->commande_fournisseur_id.'">'.$obj->commande_fournisseur_ref.'</a>'; + if ($obj->commande_fournisseur_id) { + print '<a href="'.DOL_URL_ROOT.'/commande_fournisseur/card.php?id='.$obj->commande_fournisseur_id.'">'.$obj->commande_fournisseur_ref.'</a>'; + } print '</td></tr>'; $i++; } @@ -144,27 +143,30 @@ $sql .= " FROM ".MAIN_DB_PREFIX."reception as e"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON e.rowid = el.fk_target AND el.targettype = 'reception' AND el.sourcetype IN ('order_supplier')"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseur as c ON el.fk_source = c.rowid AND el.sourcetype IN ('order_supplier') AND el.targettype = 'reception'"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = e.fk_soc"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON e.fk_soc = sc.fk_soc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON e.fk_soc = sc.fk_soc"; +} $sql .= " WHERE e.entity IN (".getEntity('reception').")"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND sc.fk_user = ".$user->id; +} $sql .= " AND e.fk_statut = 1"; -if ($socid) $sql .= " AND c.fk_soc = ".$socid; +if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; +} $sql .= " ORDER BY e.date_delivery DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="3">'.$langs->trans("LastReceptions", $num).'</th></tr>'; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $reception->id = $obj->rowid; @@ -176,19 +178,22 @@ if ($resql) print '</td>'; print '<td><a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$obj->socid.'">'.img_object($langs->trans("ShowCompany"), "company").' '.$obj->name.'</a></td>'; print '<td>'; - if ($obj->commande_fournisseur_id > 0) - { + if ($obj->commande_fournisseur_id > 0) { $orderstatic->id = $obj->commande_fournisseur_id; $orderstatic->ref = $obj->commande_fournisseur_ref; print $orderstatic->getNomUrl(1); - } else print '&nbsp;'; + } else { + print '&nbsp;'; + } print '</td></tr>'; $i++; } print "</table></div><br>"; } $db->free($resql); -} else dol_print_error($db); +} else { + dol_print_error($db); +} @@ -199,19 +204,23 @@ if ($resql) $sql = "SELECT c.rowid, c.ref, c.ref_supplier as ref_supplier, c.fk_statut as status, c.billed as billed, s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c,"; $sql .= " ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity('supplier_order').")"; $sql .= " AND c.fk_statut IN (".CommandeFournisseur::STATUS_ORDERSENT.", ".CommandeFournisseur::STATUS_RECEIVED_PARTIALLY.")"; -if ($socid > 0) $sql .= " AND c.fk_soc = ".$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($socid > 0) { + $sql .= " AND c.fk_soc = ".$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " ORDER BY c.rowid ASC"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $langs->load("orders"); $i = 0; @@ -219,8 +228,7 @@ if ($resql) print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="3">'.$langs->trans("SuppliersOrdersToProcess").' <span class="badge">'.$num.'</span></th></tr>'; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $orderstatic->id = $obj->rowid; diff --git a/htdocs/reception/list.php b/htdocs/reception/list.php index cb9bc100f79..661c14c9d01 100644 --- a/htdocs/reception/list.php +++ b/htdocs/reception/list.php @@ -42,7 +42,9 @@ $toselect = GETPOST('toselect', 'array'); // Security check $receptionid = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'reception', $receptionid, ''); $diroutputmassaction = $conf->reception->dir_output.'/temp/massgeneration/'.$user->id; @@ -64,9 +66,15 @@ $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 (!$sortfield) $sortfield = "e.ref"; -if (!$sortorder) $sortorder = "DESC"; -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (!$sortfield) { + $sortfield = "e.ref"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -92,7 +100,9 @@ $fieldstosearchall = array( 's.nom'=>"ThirdParty", 'e.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["e.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["e.note_private"] = "NotePrivate"; +} $checkedtypetiers = 0; $arrayfields = array( @@ -117,23 +127,30 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); +$error = 0; + /* * Actions */ -if (GETPOST('cancel')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction') && $massaction != 'confirm_createbills') { $massaction = ''; } +if (GETPOST('cancel')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction') && $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'); +} include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_ref_supplier = ''; $search_ref_rcp = ''; $search_ref_liv = ''; @@ -148,8 +165,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_array_options = array(); } -if (empty($reshook)) -{ +if (empty($reshook)) { if ($massaction == 'confirm_createbills') { $receptions = GETPOST('toselect', 'array'); $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); @@ -162,8 +178,7 @@ if (empty($reshook)) $db->begin(); $errors = array(); - foreach ($receptions as $id_reception) - { + foreach ($receptions as $id_reception) { $rcp = new Reception($db); // On ne facture que les réceptions validées if ($rcp->fetch($id_reception) <= 0 || $rcp->statut != 1) { @@ -175,16 +190,19 @@ if (empty($reshook)) $object = new FactureFournisseur($db); if (!empty($createbills_onebythird) && !empty($TFactThird[$rcp->socid])) { $object = $TFactThird[$rcp->socid]; // If option "one bill per third" is set, we use already created reception. - if (empty($object->rowid) && $object->id != null)$object->rowid = $object->id; - if (!empty($object->rowid))$object->fetchObjectLinked(); + if (empty($object->rowid) && $object->id != null) { + $object->rowid = $object->id; + } + if (!empty($object->rowid)) { + $object->fetchObjectLinked(); + } $rcp->fetchObjectLinked(); - if (count($rcp->linkedObjectsIds['reception']) > 0) - { - foreach ($rcp->linkedObjectsIds['reception'] as $key => $value) - { - if (empty($object->linkedObjectsIds['reception']) || !in_array($value, $object->linkedObjectsIds['reception']))//Dont try to link if already linked + if (count($rcp->linkedObjectsIds['reception']) > 0) { + foreach ($rcp->linkedObjectsIds['reception'] as $key => $value) { + if (empty($object->linkedObjectsIds['reception']) || !in_array($value, $object->linkedObjectsIds['reception'])) { //Dont try to link if already linked $object->add_object_linked('reception', $value); // add supplier order linked object + } } } } else { @@ -200,8 +218,7 @@ if (empty($reshook)) $object->ref_supplier = $rcp->ref_supplier; $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - if (empty($datefacture)) - { + if (empty($datefacture)) { $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); } @@ -210,10 +227,8 @@ if (empty($reshook)) $object->origin_id = $id_reception; $rcp->fetchObjectLinked(); - if (count($rcp->linkedObjectsIds['reception']) > 0) - { - foreach ($rcp->linkedObjectsIds['reception'] as $key => $value) - { + if (count($rcp->linkedObjectsIds['reception']) > 0) { + foreach ($rcp->linkedObjectsIds['reception'] as $key => $value) { $object->linked_objects['reception'] = $value; } } @@ -229,23 +244,19 @@ if (empty($reshook)) } } - if ($object->id > 0) - { + if ($object->id > 0) { if (!empty($createbills_onebythird) && !empty($TFactThird[$rcp->socid])) { //cause function create already add object linked for facturefournisseur $res = $object->add_object_linked($object->origin, $id_reception); - if ($res == 0) - { + if ($res == 0) { $errors[] = $object->error; $error++; } } - if (!$error) - { + if (!$error) { $lines = $rcp->lines; - if (empty($lines) && method_exists($rcp, 'fetch_lines')) - { + if (empty($lines) && method_exists($rcp, 'fetch_lines')) { $rcp->fetch_lines(); $lines = $rcp->lines; } @@ -253,11 +264,9 @@ if (empty($reshook)) $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); - if ($lines[$i]->subprice < 0) - { + if ($lines[$i]->subprice < 0) { // Negative line, we create a discount line $discount = new DiscountAbsolute($db); $discount->fk_soc = $object->socid; @@ -268,8 +277,7 @@ if (empty($reshook)) $discount->fk_user = $user->id; $discount->description = $desc; $discountid = $discount->create($user); - if ($discountid > 0) - { + if ($discountid > 0) { $result = $object->insert_discount($discountid); //$result=$discount->link_to_invoice($lineid,$id); } else { @@ -282,17 +290,28 @@ if (empty($reshook)) $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); // Date start $date_start = false; - if ($lines[$i]->date_debut_prevue) $date_start = $lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) $date_start = $lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) $date_start = $lines[$i]->date_start; + if ($lines[$i]->date_debut_prevue) { + $date_start = $lines[$i]->date_debut_prevue; + } + if ($lines[$i]->date_debut_reel) { + $date_start = $lines[$i]->date_debut_reel; + } + if ($lines[$i]->date_start) { + $date_start = $lines[$i]->date_start; + } //Date end $date_end = false; - if ($lines[$i]->date_fin_prevue) $date_end = $lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) $date_end = $lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) $date_end = $lines[$i]->date_end; + if ($lines[$i]->date_fin_prevue) { + $date_end = $lines[$i]->date_fin_prevue; + } + if ($lines[$i]->date_fin_reel) { + $date_end = $lines[$i]->date_fin_reel; + } + if ($lines[$i]->date_end) { + $date_end = $lines[$i]->date_end; + } // Reset fk_parent_line for no child products and special product - if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) - { + if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) { $fk_parent_line = 0; } $result = $object->addline( @@ -321,8 +340,7 @@ if (empty($reshook)) $rcp->add_object_linked('facture_fourn_det', $result); - if ($result > 0) - { + if ($result > 0) { $lineid = $result; } else { $lineid = 0; @@ -330,8 +348,7 @@ if (empty($reshook)) break; } // Defined the new fk_parent_line - if ($result > 0 && $lines[$i]->product_type == 9) - { + if ($result > 0 && $lines[$i]->product_type == 9) { $fk_parent_line = $result; } } @@ -341,22 +358,22 @@ if (empty($reshook)) //$rcp->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module. - if (!empty($createbills_onebythird) && empty($TFactThird[$rcp->socid])) $TFactThird[$rcp->socid] = $object; - else $TFact[$object->id] = $object; + if (!empty($createbills_onebythird) && empty($TFactThird[$rcp->socid])) { + $TFactThird[$rcp->socid] = $object; + } else { + $TFact[$object->id] = $object; + } } // Build doc with all invoices $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; $toselect = array(); - if (!$error && $validate_invoices) - { + if (!$error && $validate_invoices) { $massaction = $action = 'builddoc'; - foreach ($TAllFact as &$object) - { + foreach ($TAllFact as &$object) { $result = $object->validate($user); - if ($result <= 0) - { + if ($result <= 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); break; @@ -374,8 +391,7 @@ if (empty($reshook)) $massaction = $action = 'confirm_createbills'; } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessage($langs->trans('BillCreated', $nb_bills_created)); } else { @@ -411,60 +427,85 @@ $sql .= " state.code_departement as state_code, state.nom as state_name,"; $sql .= ' e.date_creation as date_creation, e.tms as date_update'; // 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 : ''); + 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 $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."reception as e"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (e.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (e.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = e.fk_soc"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as ee ON e.rowid = ee.fk_source AND ee.sourcetype = 'reception' AND ee.targettype = 'delivery'"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."delivery as l ON l.rowid = ee.fk_target"; -if (!$user->rights->societe->client->voir && !$socid) // Internal user with no permission to see all -{ +if (!$user->rights->societe->client->voir && !$socid) { // Internal user with no permission to see all $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } $sql .= " WHERE e.entity IN (".getEntity('reception').")"; -if (!$user->rights->societe->client->voir && !$socid) // Internal user with no permission to see all -{ +if (!$user->rights->societe->client->voir && !$socid) { // Internal user with no permission to see all $sql .= " AND e.fk_soc = sc.fk_soc"; $sql .= " AND sc.fk_user = ".$user->id; } -if ($socid) -{ +if ($socid) { $sql .= " AND e.fk_soc = ".$socid; } if ($search_status <> '' && $search_status >= 0) { $sql .= " AND e.fk_statut = ".$search_status; } -if ($search_billed != '' && $search_billed >= 0) $sql .= ' AND e.billed = '.$search_billed; -if ($search_town) $sql .= natural_search('s.town', $search_town); -if ($search_zip) $sql .= natural_search("s.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_country) $sql .= " AND s.fk_pays IN (".$search_country.')'; -if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; -if ($search_ref_rcp) $sql .= natural_search('e.ref', $search_ref_rcp); -if ($search_ref_liv) $sql .= natural_search('l.ref', $search_ref_liv); -if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_ref_supplier) $sql .= natural_search('e.ref_supplier', $search_ref_supplier); -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); +if ($search_billed != '' && $search_billed >= 0) { + $sql .= ' AND e.billed = '.$search_billed; +} +if ($search_town) { + $sql .= natural_search('s.town', $search_town); +} +if ($search_zip) { + $sql .= natural_search("s.zip", $search_zip); +} +if ($search_state) { + $sql .= natural_search("state.nom", $search_state); +} +if ($search_country) { + $sql .= " AND s.fk_pays IN (".$search_country.')'; +} +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; +} +if ($search_ref_rcp) { + $sql .= natural_search('e.ref', $search_ref_rcp); +} +if ($search_ref_liv) { + $sql .= natural_search('l.ref', $search_ref_liv); +} +if ($search_company) { + $sql .= natural_search('s.nom', $search_company); +} +if ($search_ref_supplier) { + $sql .= natural_search('e.ref_supplier', $search_ref_supplier); +} +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} // Add where from extra fields -foreach ($search_array_options as $key => $val) -{ +foreach ($search_array_options as $key => $val) { $crit = $val; $tmpkey = preg_replace('/search_options_/', '', $key); $typ = $extrafields->attributes[$object->table_element]['type'][$tmpkey]; $mode = 0; - if (in_array($typ, array('int', 'double', 'real'))) $mode = 1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode = 2; // Search on a foreign key int - if ($crit != '' && (!in_array($typ, array('select', 'sellist')) || $crit != '0')) - { + if (in_array($typ, array('int', 'double', 'real'))) { + $mode = 1; // Search on a numeric + } + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') { + $mode = 2; // Search on a foreign key int + } + if ($crit != '' && (!in_array($typ, array('select', 'sellist')) || $crit != '0')) { $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); } } @@ -474,8 +515,7 @@ $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // No $sql .= $hookmanager->resPrint; $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); } @@ -485,444 +525,525 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ - $num = $db->num_rows($resql); +if (!$resql) { + dol_print_error($db); + exit; +} - $reception = new Reception($db); +$num = $db->num_rows($resql); - $arrayofselected = is_array($toselect) ? $toselect : array(); +$reception = new Reception($db); - $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 .= "&amp;sall=".urlencode($sall); - if ($search_ref_rcp) $param .= "&amp;search_ref_rcp=".urlencode($search_ref_rcp); - if ($search_ref_liv) $param .= "&amp;search_ref_liv=".urlencode($search_ref_liv); - if ($search_company) $param .= "&amp;search_company=".urlencode($search_company); - if ($optioncss != '') $param .= '&amp;optioncss='.urlencode($optioncss); - if ($search_billed != '' && $search_billed >= 0) $param .= "&amp;search_billed=".urlencode($search_billed); - if ($search_town) $param .= "&amp;search_town=".urlencode($search_town); - if ($search_zip) $param .= "&amp;search_zip=".urlencode($search_zip); - if ($search_state) $param .= "&amp;search_state=".urlencode($search_state); - if ($search_status != '') $param .= "&amp;search_status=".urlencode($search_status); - if ($search_country) $param .= "&amp;search_country=".urlencode($search_country); - if ($search_type_thirdparty) $param .= "&amp;search_type_thirdparty=".urlencode($search_type_thirdparty); - if ($search_ref_supplier) $param .= "&amp;search_ref_supplier=".urlencode($search_ref_supplier); - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit = $val; - $tmpkey = preg_replace('/search_options_/', '', $key); - if ($val != '') $param .= '&search_options_'.$tmpkey.'='.urlencode($val); +$arrayofselected = is_array($toselect) ? $toselect : array(); + +$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 .= "&amp;sall=".urlencode($sall); +} +if ($search_ref_rcp) { + $param .= "&amp;search_ref_rcp=".urlencode($search_ref_rcp); +} +if ($search_ref_liv) { + $param .= "&amp;search_ref_liv=".urlencode($search_ref_liv); +} +if ($search_company) { + $param .= "&amp;search_company=".urlencode($search_company); +} +if ($optioncss != '') { + $param .= '&amp;optioncss='.urlencode($optioncss); +} +if ($search_billed != '' && $search_billed >= 0) { + $param .= "&amp;search_billed=".urlencode($search_billed); +} +if ($search_town) { + $param .= "&amp;search_town=".urlencode($search_town); +} +if ($search_zip) { + $param .= "&amp;search_zip=".urlencode($search_zip); +} +if ($search_state) { + $param .= "&amp;search_state=".urlencode($search_state); +} +if ($search_status != '') { + $param .= "&amp;search_status=".urlencode($search_status); +} +if ($search_country) { + $param .= "&amp;search_country=".urlencode($search_country); +} +if ($search_type_thirdparty) { + $param .= "&amp;search_type_thirdparty=".urlencode($search_type_thirdparty); +} +if ($search_ref_supplier) { + $param .= "&amp;search_ref_supplier=".urlencode($search_ref_supplier); +} +// Add $param from extra fields +foreach ($search_array_options as $key => $val) { + $crit = $val; + $tmpkey = preg_replace('/search_options_/', '', $key); + if ($val != '') { + $param .= '&search_options_'.$tmpkey.'='.urlencode($val); } +} - $arrayofmassactions = array( +$arrayofmassactions = array( // 'presend'=>$langs->trans("SendByMail"), - ); +); - if ($user->rights->fournisseur->facture->creer)$arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisSupplier"); - if ($massaction == 'createbills') $arrayofmassactions = array(); - $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - //$massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); +if ($user->rights->fournisseur->facture->creer) { + $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisSupplier"); +} +if ($massaction == 'createbills') { + $arrayofmassactions = array(); +} +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); +//$massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); - $i = 0; - print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; - print '<input type="hidden" name="token" value="'.newToken().'">'; - print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; - print '<input type="hidden" name="action" value="list">'; - print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; - print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; +$i = 0; +print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'."\n"; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} +print '<input type="hidden" name="token" value="'.newToken().'">'; +print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; +print '<input type="hidden" name="action" value="list">'; +print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; +print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; - print_barre_liste($langs->trans('ListOfReceptions'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'dollyrevert', 0, '', '', $limit, 0, 0, 1); +print_barre_liste($langs->trans('ListOfReceptions'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'dollyrevert', 0, '', '', $limit, 0, 0, 1); +if ($massaction == 'createbills') { + //var_dump($_REQUEST); + print '<input type="hidden" name="massaction" value="confirm_createbills">'; - if ($massaction == 'createbills') - { - //var_dump($_REQUEST); - print '<input type="hidden" name="massaction" value="confirm_createbills">'; - - print '<table class="noborder" width="100%" >'; - print '<tr>'; - print '<td class="titlefieldmiddle">'; - print $langs->trans('DateInvoice'); - print '</td>'; - print '<td>'; - print $form->selectDate('', '', '', '', '', '', 1, 1); - print '</td>'; - print '</tr>'; - print '<tr>'; - print '<td>'; - print $langs->trans('CreateOneBillByThird'); - print '</td>'; - print '<td>'; - print $form->selectyesno('createbills_onebythird', '', 1); - print '</td>'; - print '</tr>'; - print '<tr>'; - print '<td>'; - print $langs->trans('ValidateInvoices'); - print '</td>'; - print '<td>'; - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) - { - print $form->selectyesno('validate_invoices', 0, 1, 1); - print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')'; - } else { - print $form->selectyesno('validate_invoices', 0, 1); - } - print '</td>'; - print '</tr>'; - print '</table>'; - - print '<br>'; - print '<div class="center">'; - print '<input type="submit" class="button" id="createbills" name="createbills" value="'.$langs->trans('CreateInvoiceForThisSupplier').'"> '; - print '<input type="submit" class="button button-cancel" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; - print '</div>'; - print '<br>'; + print '<table class="noborder" width="100%" >'; + print '<tr>'; + print '<td class="titlefieldmiddle">'; + print $langs->trans('DateInvoice'); + print '</td>'; + print '<td>'; + print $form->selectDate('', '', '', '', '', '', 1, 1); + print '</td>'; + print '</tr>'; + print '<tr>'; + print '<td>'; + print $langs->trans('CreateOneBillByThird'); + print '</td>'; + print '<td>'; + print $form->selectyesno('createbills_onebythird', '', 1); + print '</td>'; + print '</tr>'; + print '<tr>'; + print '<td>'; + print $langs->trans('ValidateInvoices'); + print '</td>'; + print '<td>'; + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) { + print $form->selectyesno('validate_invoices', 0, 1, 1); + print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')'; + } else { + print $form->selectyesno('validate_invoices', 0, 1); } + print '</td>'; + print '</tr>'; + print '</table>'; - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); - print $langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall); + print '<br>'; + print '<div class="center">'; + print '<input type="submit" class="button" id="createbills" name="createbills" value="'.$langs->trans('CreateInvoiceForThisSupplier').'"> '; + print '<input type="submit" class="button button-cancel" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; + print '</div>'; + print '<br>'; +} + +if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); } + print $langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall); +} - $moreforfilter = ''; - if (!empty($moreforfilter)) - { - print '<div class="liste_titre liste_titre_bydiv centpercent">'; - print $moreforfilter; - $parameters = array('type'=>$type); - $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - print '</div>'; - } +$moreforfilter = ''; +if (!empty($moreforfilter)) { + print '<div class="liste_titre liste_titre_bydiv centpercent">'; + print $moreforfilter; + $parameters = array('type'=>$type); + $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + print '</div>'; +} - $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= $form->showCheckAddButtons('checkforselect', 1); - print '<div class="div-table-responsive">'; - print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; +print '<div class="div-table-responsive">'; +print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; + +// Fields title search +// -------------------------------------------------------------------- +print '<tr class="liste_titre_filter">'; +// Ref +if (!empty($arrayfields['e.ref']['checked'])) { + print '<td class="liste_titre">'; + print '<input class="flat" size="6" type="text" name="search_ref_rcp" value="'.$search_ref_rcp.'">'; + print '</td>'; +} +// Ref customer +if (!empty($arrayfields['e.ref_supplier']['checked'])) { + print '<td class="liste_titre">'; + print '<input class="flat" size="6" type="text" name="search_ref_supplier" value="'.$search_ref_supplier.'">'; + print '</td>'; +} +// Thirdparty +if (!empty($arrayfields['s.nom']['checked'])) { + print '<td class="liste_titre left">'; + print '<input class="flat" type="text" size="8" name="search_company" value="'.dol_escape_htmltag($search_company).'">'; + print '</td>'; +} +// Town +if (!empty($arrayfields['s.town']['checked'])) { + print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>'; +} +// Zip +if (!empty($arrayfields['s.zip']['checked'])) { + print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_zip" value="'.$search_zip.'"></td>'; +} +// State +if (!empty($arrayfields['state.nom']['checked'])) { + print '<td class="liste_titre">'; + print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; + print '</td>'; +} +// Country +if (!empty($arrayfields['country.code_iso']['checked'])) { + print '<td class="liste_titre center">'; + print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); + print '</td>'; +} +// Company type +if (!empty($arrayfields['typent.code']['checked'])) { + print '<td class="liste_titre maxwidthonsmartphone center">'; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); + print '</td>'; +} +// Date delivery planned +if (!empty($arrayfields['e.date_delivery']['checked'])) { + print '<td class="liste_titre">&nbsp;</td>'; +} +if (!empty($arrayfields['l.ref']['checked'])) { + // Delivery ref + print '<td class="liste_titre">'; + print '<input class="flat" size="10" type="text" name="search_ref_liv" value="'.$search_ref_liv.'"'; + print '</td>'; +} +if (!empty($arrayfields['l.date_delivery']['checked'])) { + // Date received + print '<td class="liste_titre">&nbsp;</td>'; +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + +// Fields from hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Date creation +if (!empty($arrayfields['e.datec']['checked'])) { + print '<td class="liste_titre">'; + print '</td>'; +} +// Date modification +if (!empty($arrayfields['e.tms']['checked'])) { + print '<td class="liste_titre">'; + print '</td>'; +} +// Status +if (!empty($arrayfields['e.fk_statut']['checked'])) { + print '<td class="liste_titre maxwidthonsmartphone right">'; + print $form->selectarray('search_status', array('0'=>$langs->trans('StatusReceptionDraftShort'), '1'=>$langs->trans('StatusReceptionValidatedShort'), '2'=>$langs->trans('StatusReceptionProcessedShort')), $search_status, 1); + print '</td>'; +} +// Status billed +if (!empty($arrayfields['e.billed']['checked'])) { + print '<td class="liste_titre maxwidthonsmartphone center">'; + print $form->selectyesno('search_billed', $search_billed, 1, 0, 1); + print '</td>'; +} +// Action column +print '<td class="liste_titre middle">'; +$searchpicto = $form->showFilterAndCheckAddButtons(0); +print $searchpicto; +print '</td>'; +print "</tr>\n"; + +print '<tr class="liste_titre">'; +if (!empty($arrayfields['e.ref']['checked'])) { + print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['e.ref_supplier']['checked'])) { + print_liste_field_titre($arrayfields['e.ref_supplier']['label'], $_SERVER["PHP_SELF"], "e.ref_supplier", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder, 'left '); +} +if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['e.date_delivery']['checked'])) { + print_liste_field_titre($arrayfields['e.date_delivery']['label'], $_SERVER["PHP_SELF"], "e.date_delivery", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['l.ref']['checked'])) { + print_liste_field_titre($arrayfields['l.ref']['label'], $_SERVER["PHP_SELF"], "l.ref", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['l.date_delivery']['checked'])) { + print_liste_field_titre($arrayfields['l.date_delivery']['label'], $_SERVER["PHP_SELF"], "l.date_delivery", "", $param, '', $sortfield, $sortorder, 'center '); +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; +// Hook fields +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (!empty($arrayfields['e.datec']['checked'])) { + print_liste_field_titre($arrayfields['e.datec']['label'], $_SERVER["PHP_SELF"], "e.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['e.tms']['checked'])) { + print_liste_field_titre($arrayfields['e.tms']['label'], $_SERVER["PHP_SELF"], "e.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['e.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['e.fk_statut']['label'], $_SERVER["PHP_SELF"], "e.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['e.billed']['checked'])) { + print_liste_field_titre($arrayfields['e.billed']['label'], $_SERVER["PHP_SELF"], "e.billed", "", $param, '', $sortfield, $sortorder, 'center '); +} +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); +print "</tr>\n"; + +$i = 0; +$totalarray = array(); +while ($i < min($num, $limit)) { + $obj = $db->fetch_object($resql); + + $reception->id = $obj->rowid; + $reception->ref = $obj->ref; + + $companystatic->id = $obj->socid; + $companystatic->ref = $obj->name; + $companystatic->name = $obj->name; + + + print '<tr class="oddeven">'; - // Fields title search - // -------------------------------------------------------------------- - print '<tr class="liste_titre_filter">'; // Ref - if (!empty($arrayfields['e.ref']['checked'])) - { - print '<td class="liste_titre">'; - print '<input class="flat" size="6" type="text" name="search_ref_rcp" value="'.$search_ref_rcp.'">'; - print '</td>'; + if (!empty($arrayfields['e.ref']['checked'])) { + print "<td>"; + print $reception->getNomUrl(1); + $filename = dol_sanitizeFileName($reception->ref); + $filedir = $conf->reception->dir_output.'/'.dol_sanitizeFileName($reception->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$reception->id; + print $formfile->getDocumentsLink($reception->element, $filename, $filedir); + print "</td>\n"; + + if (!$i) { + $totalarray['nbfield']++; + } } + // Ref customer - if (!empty($arrayfields['e.ref_supplier']['checked'])) - { - print '<td class="liste_titre">'; - print '<input class="flat" size="6" type="text" name="search_ref_supplier" value="'.$search_ref_supplier.'">'; - print '</td>'; + if (!empty($arrayfields['e.ref_supplier']['checked'])) { + print "<td>"; + print $obj->ref_supplier; + print "</td>\n"; + if (!$i) { + $totalarray['nbfield']++; + } } - // Thirdparty - if (!empty($arrayfields['s.nom']['checked'])) - { - print '<td class="liste_titre left">'; - print '<input class="flat" type="text" size="8" name="search_company" value="'.dol_escape_htmltag($search_company).'">'; + + // Third party + if (!empty($arrayfields['s.nom']['checked'])) { + print '<td>'; + print $companystatic->getNomUrl(1); print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>'; - // Zip - if (!empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_zip" value="'.$search_zip.'"></td>'; - // State - if (!empty($arrayfields['state.nom']['checked'])) - { - print '<td class="liste_titre">'; - print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; + if (!empty($arrayfields['s.town']['checked'])) { + print '<td class="nocellnopadd">'; + print $obj->town; print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } + } + // Zip + if (!empty($arrayfields['s.zip']['checked'])) { + print '<td class="nocellnopadd">'; + print $obj->zip; + print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } + } + // State + if (!empty($arrayfields['state.nom']['checked'])) { + print "<td>".$obj->state_name."</td>\n"; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { - print '<td class="liste_titre center">'; - print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); + if (!empty($arrayfields['country.code_iso']['checked'])) { + print '<td class="center">'; + $tmparray = getCountry($obj->fk_pays, 'all'); + print $tmparray['label']; print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } } - // Company type - if (!empty($arrayfields['typent.code']['checked'])) - { - print '<td class="liste_titre maxwidthonsmartphone center">'; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); + // Type ent + if (!empty($arrayfields['typent.code']['checked'])) { + print '<td class="center">'; + if (count($typenArray) == 0) { + $typenArray = $formcompany->typent_array(1); + } + print $typenArray[$obj->typent_code]; print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } } - // Date delivery planned - if (!empty($arrayfields['e.date_delivery']['checked'])) - { - print '<td class="liste_titre">&nbsp;</td>'; + + // Date delivery planed + if (!empty($arrayfields['e.date_delivery']['checked'])) { + print '<td class="center">'; + print dol_print_date($db->jdate($obj->delivery_date), "day"); + /*$now = time(); + if ( ($now - $db->jdate($obj->date_reception)) > $conf->warnings->lim && $obj->statutid == 1 ) + { + }*/ + print "</td>\n"; } - if (!empty($arrayfields['l.ref']['checked'])) - { - // Delivery ref - print '<td class="liste_titre">'; - print '<input class="flat" size="10" type="text" name="search_ref_liv" value="'.$search_ref_liv.'"'; - print '</td>'; - } - if (!empty($arrayfields['l.date_delivery']['checked'])) - { - // Date received - print '<td class="liste_titre">&nbsp;</td>'; + + if (!empty($arrayfields['l.ref']['checked']) || !empty($arrayfields['l.date_delivery']['checked'])) { + $reception->fetchObjectLinked($reception->id, $reception->element); + $receiving = ''; + if (count($reception->linkedObjects['delivery']) > 0) { + $receiving = reset($reception->linkedObjects['delivery']); + } + + if (!empty($arrayfields['l.ref']['checked'])) { + // Ref + print '<td>'; + print !empty($receiving) ? $receiving->getNomUrl($db) : ''; + print '</td>'; + } + + if (!empty($arrayfields['l.date_delivery']['checked'])) { + // Date received + print '<td class="center">'; + print dol_print_date($db->jdate($obj->date_reception), "day"); + print '</td>'."\n"; + } } + // Extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters = array('arrayfields'=>$arrayfields); - $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['e.datec']['checked'])) - { - print '<td class="liste_titre">'; + if (!empty($arrayfields['e.datec']['checked'])) { + print '<td class="center nowrap">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['e.tms']['checked'])) - { - print '<td class="liste_titre">'; + if (!empty($arrayfields['e.tms']['checked'])) { + print '<td class="center nowrap">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour'); print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['e.fk_statut']['checked'])) - { - print '<td class="liste_titre maxwidthonsmartphone right">'; - print $form->selectarray('search_status', array('0'=>$langs->trans('StatusReceptionDraftShort'), '1'=>$langs->trans('StatusReceptionValidatedShort'), '2'=>$langs->trans('StatusReceptionProcessedShort')), $search_status, 1); - print '</td>'; + if (!empty($arrayfields['e.fk_statut']['checked'])) { + print '<td class="right nowrap">'.$reception->LibStatut($obj->fk_statut, 5).'</td>'; + if (!$i) { + $totalarray['nbfield']++; + } } - // Status billed - if (!empty($arrayfields['e.billed']['checked'])) - { - print '<td class="liste_titre maxwidthonsmartphone center">'; - print $form->selectyesno('search_billed', $search_billed, 1, 0, 1); - print '</td>'; + // Billed + if (!empty($arrayfields['e.billed']['checked'])) { + print '<td class="center">'.yn($obj->billed).'</td>'; + if (!$i) { + $totalarray['nbfield']++; + } } + // Action column - print '<td class="liste_titre middle">'; - $searchpicto = $form->showFilterAndCheckAddButtons(0); - print $searchpicto; + print '<td class="center">'; + 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; + } + print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; + } print '</td>'; - print "</tr>\n"; - - print '<tr class="liste_titre">'; - if (!empty($arrayfields['e.ref']['checked'])) print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['e.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['e.ref_supplier']['label'], $_SERVER["PHP_SELF"], "e.ref_supplier", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder, 'left '); - if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['e.date_delivery']['checked'])) print_liste_field_titre($arrayfields['e.date_delivery']['label'], $_SERVER["PHP_SELF"], "e.date_delivery", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['l.ref']['checked'])) print_liste_field_titre($arrayfields['l.ref']['label'], $_SERVER["PHP_SELF"], "l.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['l.date_delivery']['checked'])) print_liste_field_titre($arrayfields['l.date_delivery']['label'], $_SERVER["PHP_SELF"], "l.date_delivery", "", $param, '', $sortfield, $sortorder, 'center '); - // Extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; - // Hook fields - $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); - $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (!empty($arrayfields['e.datec']['checked'])) print_liste_field_titre($arrayfields['e.datec']['label'], $_SERVER["PHP_SELF"], "e.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['e.tms']['checked'])) print_liste_field_titre($arrayfields['e.tms']['label'], $_SERVER["PHP_SELF"], "e.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['e.fk_statut']['checked'])) print_liste_field_titre($arrayfields['e.fk_statut']['label'], $_SERVER["PHP_SELF"], "e.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['e.billed']['checked'])) print_liste_field_titre($arrayfields['e.billed']['label'], $_SERVER["PHP_SELF"], "e.billed", "", $param, '', $sortfield, $sortorder, 'center '); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); - print "</tr>\n"; - - $i = 0; - $totalarray = array(); - while ($i < min($num, $limit)) - { - $obj = $db->fetch_object($resql); - - $reception->id = $obj->rowid; - $reception->ref = $obj->ref; - - $companystatic->id = $obj->socid; - $companystatic->ref = $obj->name; - $companystatic->name = $obj->name; - - - print '<tr class="oddeven">'; - - // Ref - if (!empty($arrayfields['e.ref']['checked'])) - { - print "<td>"; - print $reception->getNomUrl(1); - $filename = dol_sanitizeFileName($reception->ref); - $filedir = $conf->reception->dir_output.'/'.dol_sanitizeFileName($reception->ref); - $urlsource = $_SERVER['PHP_SELF'].'?id='.$reception->id; - print $formfile->getDocumentsLink($reception->element, $filename, $filedir); - print "</td>\n"; - - if (!$i) $totalarray['nbfield']++; - } - - // Ref customer - if (!empty($arrayfields['e.ref_supplier']['checked'])) - { - print "<td>"; - print $obj->ref_supplier; - print "</td>\n"; - if (!$i) $totalarray['nbfield']++; - } - - // Third party - if (!empty($arrayfields['s.nom']['checked'])) - { - print '<td>'; - print $companystatic->getNomUrl(1); - print '</td>'; - if (!$i) $totalarray['nbfield']++; - } - // Town - if (!empty($arrayfields['s.town']['checked'])) - { - print '<td class="nocellnopadd">'; - print $obj->town; - print '</td>'; - if (!$i) $totalarray['nbfield']++; - } - // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { - print '<td class="nocellnopadd">'; - print $obj->zip; - print '</td>'; - if (!$i) $totalarray['nbfield']++; - } - // State - if (!empty($arrayfields['state.nom']['checked'])) - { - print "<td>".$obj->state_name."</td>\n"; - if (!$i) $totalarray['nbfield']++; - } - // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { - print '<td class="center">'; - $tmparray = getCountry($obj->fk_pays, 'all'); - print $tmparray['label']; - print '</td>'; - if (!$i) $totalarray['nbfield']++; - } - // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { - print '<td class="center">'; - if (count($typenArray) == 0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print '</td>'; - if (!$i) $totalarray['nbfield']++; - } - - // Date delivery planed - if (!empty($arrayfields['e.date_delivery']['checked'])) - { - print '<td class="center">'; - print dol_print_date($db->jdate($obj->delivery_date), "day"); - /*$now = time(); - if ( ($now - $db->jdate($obj->date_reception)) > $conf->warnings->lim && $obj->statutid == 1 ) - { - }*/ - print "</td>\n"; - } - - if (!empty($arrayfields['l.ref']['checked']) || !empty($arrayfields['l.date_delivery']['checked'])) - { - $reception->fetchObjectLinked($reception->id, $reception->element); - $receiving = ''; - if (count($reception->linkedObjects['delivery']) > 0) $receiving = reset($reception->linkedObjects['delivery']); - - if (!empty($arrayfields['l.ref']['checked'])) - { - // Ref - print '<td>'; - print !empty($receiving) ? $receiving->getNomUrl($db) : ''; - print '</td>'; - } - - if (!empty($arrayfields['l.date_delivery']['checked'])) - { - // Date received - print '<td class="center">'; - print dol_print_date($db->jdate($obj->date_reception), "day"); - print '</td>'."\n"; - } - } - - // Extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - - // Fields from hook - $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); - $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (!empty($arrayfields['e.datec']['checked'])) - { - print '<td class="center nowrap">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print '</td>'; - if (!$i) $totalarray['nbfield']++; - } - // Date modification - if (!empty($arrayfields['e.tms']['checked'])) - { - print '<td class="center nowrap">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print '</td>'; - if (!$i) $totalarray['nbfield']++; - } - // Status - if (!empty($arrayfields['e.fk_statut']['checked'])) - { - print '<td class="right nowrap">'.$reception->LibStatut($obj->fk_statut, 5).'</td>'; - if (!$i) $totalarray['nbfield']++; - } - // Billed - if (!empty($arrayfields['e.billed']['checked'])) - { - print '<td class="center">'.yn($obj->billed).'</td>'; - if (!$i) $totalarray['nbfield']++; - } - - // Action column - print '<td class="center">'; - 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; - print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; - } - print '</td>'; - if (!$i) $totalarray['nbfield']++; - - print "</tr>\n"; - - $i++; + if (!$i) { + $totalarray['nbfield']++; } - print "</table>"; - print "</div>"; - print '</form>'; - $db->free($resql); -} else { - dol_print_error($db); + print "</tr>\n"; + + $i++; } +// If no record found +if ($num == 0) { + $colspan = 1; + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } + print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; +} + +print "</table>"; +print "</div>"; +print '</form>'; +$db->free($resql); + llxFooter(); $db->close(); diff --git a/htdocs/reception/note.php b/htdocs/reception/note.php index b57f3ea2efb..b1588a07b14 100644 --- a/htdocs/reception/note.php +++ b/htdocs/reception/note.php @@ -48,30 +48,28 @@ $action = GETPOST('action', 'aZ09'); // Security check $socid = ''; -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, $origin, $origin_id); $object = new Reception($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch($id, $ref); $object->fetch_thirdparty(); - if (!empty($object->origin)) - { + if (!empty($object->origin)) { $typeobject = $object->origin; $origin = $object->origin; $object->fetch_origin(); } // Linked documents - if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) - { + if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) { $objectsrc = new Commande($db); $objectsrc->fetch($object->$typeobject->id); } - if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) - { + if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) { $objectsrc = new Propal($db); $objectsrc->fetch($object->$typeobject->id); } @@ -95,8 +93,7 @@ llxHeader('', 'Reception'); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $head = reception_prepare_head($object); print dol_get_fiche_head($head, 'note', $langs->trans("Reception"), -1, 'dollyrevert'); diff --git a/htdocs/reception/stats/index.php b/htdocs/reception/stats/index.php index bf839b16154..0b118c5d733 100644 --- a/htdocs/reception/stats/index.php +++ b/htdocs/reception/stats/index.php @@ -35,8 +35,7 @@ $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); $userid = GETPOST('userid', 'int'); $socid = GETPOST('socid', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -74,8 +73,7 @@ $data = $stats->getNbByMonthWithPrevYear($endyear, $startyear); // $data = array(array('Lib',val1,val2,val3),...) -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filenamenb = $dir.'/receptionsnbinyear-'.$user->id.'-'.$year.'.png'; } else { $filenamenb = $dir.'/receptionsnbinyear-'.$year.'.png'; @@ -83,12 +81,10 @@ if (!$user->rights->societe->client->voir || $user->socid) $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -114,36 +110,36 @@ $data = $stats->getAmountByMonthWithPrevYear($endyear,$startyear); if (!$user->rights->societe->client->voir || $user->socid) { - $filenameamount = $dir.'/receptionsamountinyear-'.$user->id.'-'.$year.'.png'; + $filenameamount = $dir.'/receptionsamountinyear-'.$user->id.'-'.$year.'.png'; } else { - $filenameamount = $dir.'/receptionsamountinyear-'.$year.'.png'; + $filenameamount = $dir.'/receptionsamountinyear-'.$year.'.png'; } $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); if (! $mesg) { - $px2->SetData($data); - $i=$startyear;$legend=array(); - while ($i <= $endyear) - { - $legend[]=$i; - $i++; - } - $px2->SetLegend($legend); - $px2->SetMaxValue($px2->GetCeilMaxValue()); - $px2->SetMinValue(min(0,$px2->GetFloorMinValue())); - $px2->SetWidth($WIDTH); - $px2->SetHeight($HEIGHT); - $px2->SetYLabel($langs->trans("AmountOfReceptions")); - $px2->SetShading(3); - $px2->SetHorizTickIncrement(1); - $px2->mode='depth'; - $px2->SetTitle($langs->trans("AmountOfReceptionsByMonthHT")); + $px2->SetData($data); + $i=$startyear;$legend=array(); + while ($i <= $endyear) + { + $legend[]=$i; + $i++; + } + $px2->SetLegend($legend); + $px2->SetMaxValue($px2->GetCeilMaxValue()); + $px2->SetMinValue(min(0,$px2->GetFloorMinValue())); + $px2->SetWidth($WIDTH); + $px2->SetHeight($HEIGHT); + $px2->SetYLabel($langs->trans("AmountOfReceptions")); + $px2->SetShading(3); + $px2->SetHorizTickIncrement(1); + $px2->mode='depth'; + $px2->SetTitle($langs->trans("AmountOfReceptionsByMonthHT")); - $px2->draw($filenameamount,$fileurlamount); + $px2->draw($filenameamount,$fileurlamount); } */ @@ -152,36 +148,36 @@ $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); if (!$user->rights->societe->client->voir || $user->socid) { - $filename_avg = $dir.'/receptionsaverage-'.$user->id.'-'.$year.'.png'; + $filename_avg = $dir.'/receptionsaverage-'.$user->id.'-'.$year.'.png'; } else { - $filename_avg = $dir.'/receptionsaverage-'.$year.'.png'; + $filename_avg = $dir.'/receptionsaverage-'.$year.'.png'; } $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); if (! $mesg) { - $px3->SetData($data); - $i=$startyear;$legend=array(); - while ($i <= $endyear) - { - $legend[]=$i; - $i++; - } - $px3->SetLegend($legend); - $px3->SetYLabel($langs->trans("AmountAverage")); - $px3->SetMaxValue($px3->GetCeilMaxValue()); - $px3->SetMinValue($px3->GetFloorMinValue()); - $px3->SetWidth($WIDTH); - $px3->SetHeight($HEIGHT); - $px3->SetShading(3); - $px3->SetHorizTickIncrement(1); - $px3->mode='depth'; - $px3->SetTitle($langs->trans("AmountAverage")); + $px3->SetData($data); + $i=$startyear;$legend=array(); + while ($i <= $endyear) + { + $legend[]=$i; + $i++; + } + $px3->SetLegend($legend); + $px3->SetYLabel($langs->trans("AmountAverage")); + $px3->SetMaxValue($px3->GetCeilMaxValue()); + $px3->SetMinValue($px3->GetFloorMinValue()); + $px3->SetWidth($WIDTH); + $px3->SetHeight($HEIGHT); + $px3->SetShading(3); + $px3->SetHorizTickIncrement(1); + $px3->mode='depth'; + $px3->SetTitle($langs->trans("AmountAverage")); - $px3->draw($filename_avg,$fileurl_avg); + $px3->draw($filename_avg,$fileurl_avg); } */ @@ -194,7 +190,9 @@ foreach ($data as $val) { $arrayyears[$val['year']] = $val['year']; } } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; $head = array(); @@ -231,8 +229,12 @@ print '<div class="fichecenter"><div class="fichethirdleft">'; print '</td></tr>'; // Year print '<tr><td class="left">'.$langs->trans("Year").'</td><td class="left">'; - if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; - if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} +if (!in_array($nowyear, $arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print '</td></tr>'; @@ -251,11 +253,9 @@ print '<td class="center">'.$langs->trans("AmountAverage").'</td>';*/ print '</tr>'; $oldyear = 0; -foreach ($data as $val) -{ +foreach ($data as $val) { $year = $val['year']; - while (!empty($year) && $oldyear > $year + 1) - { // If we have empty year + while (!empty($year) && $oldyear > $year + 1) { // If we have empty year $oldyear--; @@ -270,8 +270,11 @@ foreach ($data as $val) print '<tr class="oddeven" height="24">'; print '<td class="center">'; - if ($year) print '<a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'">'.$year.'</a>'; - else print $langs->trans("ValidationDateNotDefinedEvenIfReceptionValidated"); + if ($year) { + print '<a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'">'.$year.'</a>'; + } else { + print $langs->trans("ValidationDateNotDefinedEvenIfReceptionValidated"); + } print '</td>'; print '<td class="right">'.$val['nb'].'</td>'; /*print '<td class="right">'.price(price2num($val['total'],'MT'),1).'</td>'; @@ -288,12 +291,14 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; // Show graphs print '<table class="border centpercent"><tr valign="top"><td class="center">'; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); print "<br>\n"; /*print $px2->show(); - print "<br>\n"; - print $px3->show();*/ + print "<br>\n"; + print $px3->show();*/ } print '</td></tr></table>'; @@ -320,17 +325,17 @@ $sql.= " GROUP BY dm DESC"; $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $row = $db->fetch_row($resql); - $nbproduct = $row[0]; - $year = $row[1]; - print "<tr>"; - print '<td class="center"><a href="month.php?year='.$year.'">'.$year.'</a></td><td class="center">'.$nbproduct.'</td></tr>'; - $i++; - } + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $row = $db->fetch_row($resql); + $nbproduct = $row[0]; + $year = $row[1]; + print "<tr>"; + print '<td class="center"><a href="month.php?year='.$year.'">'.$year.'</a></td><td class="center">'.$nbproduct.'</td></tr>'; + $i++; + } } $db->free($resql); diff --git a/htdocs/reception/stats/month.php b/htdocs/reception/stats/month.php index f974b4edcff..25c6b16e116 100644 --- a/htdocs/reception/stats/month.php +++ b/htdocs/reception/stats/month.php @@ -53,8 +53,7 @@ $fileurl = DOL_URL_ROOT.'/viewimage.php?modulepart=receptionstats&file=reception $px = new DolGraph(); $mesg = $px->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px->SetData($data); $px->SetMaxValue($px->GetCeilMaxValue()); $px->SetWidth($WIDTH); diff --git a/htdocs/reception/tpl/linkedobjectblock.tpl.php b/htdocs/reception/tpl/linkedobjectblock.tpl.php index 014dbff00a0..39a5a24347d 100644 --- a/htdocs/reception/tpl/linkedobjectblock.tpl.php +++ b/htdocs/reception/tpl/linkedobjectblock.tpl.php @@ -18,8 +18,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -42,52 +41,54 @@ $langs->load("receptions"); $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1); $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - <tr class="<?php echo $trclass; ?>"> - <td class="linkedcol-element"><?php echo $langs->trans("Reception"); ?> - <?php if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) print '<a class="objectlinked_importbtn" href="'.$objectlink->getNomUrl(0, '', 0, 1).'&amp;action=selectlines" data-element="'.$objectlink->element.'" data-id="'.$objectlink->id.'" > <i class="fa fa-indent"></i> </a'; ?> - </td> - <td class="linkedcol-name nowraponall" ><?php echo $objectlink->getNomUrl(1); ?></td> - <td class="linkedcol-ref center"></td> - <td class="linkedcol-date center"><?php echo dol_print_date($objectlink->date_delivery, 'day'); ?></td> - <td class="linkedcol-amount right"><?php + <tr class="<?php echo $trclass; ?>"> + <td class="linkedcol-element"><?php echo $langs->trans("Reception"); ?> + <?php if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) { + print '<a class="objectlinked_importbtn" href="'.$objectlink->getNomUrl(0, '', 0, 1).'&amp;action=selectlines" data-element="'.$objectlink->element.'" data-id="'.$objectlink->id.'" > <i class="fa fa-indent"></i> </a'; + } ?> + </td> + <td class="linkedcol-name nowraponall" ><?php echo $objectlink->getNomUrl(1); ?></td> + <td class="linkedcol-ref center"></td> + <td class="linkedcol-date center"><?php echo dol_print_date($objectlink->date_delivery, 'day'); ?></td> + <td class="linkedcol-amount right"><?php if ($user->rights->reception->lire) { $total = $total + $objectlink->total_ht; echo price($objectlink->total_ht); } ?></td> - <td class="linkedcol-statut right"><?php echo $objectlink->getLibStatut(3); ?></td> - <td class="linkedcol-action right"> - <?php + <td class="linkedcol-statut right"><?php echo $objectlink->getLibStatut(3); ?></td> + <td class="linkedcol-action right"> + <?php // For now, receptions must stay linked to order, so link is not deletable if ($object->element != 'order_supplier') { ?> - <a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a> - <?php + <a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a> + <?php } ?> - </td> - </tr> - <?php + </td> + </tr> + <?php } -if (count($linkedObjectBlock) > 1) -{ +if (count($linkedObjectBlock) > 1) { ?> - <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> - <td><?php echo $langs->trans("Total"); ?></td> - <td></td> - <td class="center"></td> - <td class="center"></td> - <td class="right"><?php echo price($total); ?></td> - <td class="right"></td> - <td class="right"></td> - </tr> - <?php + <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> + <td><?php echo $langs->trans("Total"); ?></td> + <td></td> + <td class="center"></td> + <td class="center"></td> + <td class="right"><?php echo price($total); ?></td> + <td class="right"></td> + <td class="right"></td> + </tr> + <?php } ?> diff --git a/htdocs/recruitment/admin/candidature_extrafields.php b/htdocs/recruitment/admin/candidature_extrafields.php index 1d9e567da9d..984d92ce913 100644 --- a/htdocs/recruitment/admin/candidature_extrafields.php +++ b/htdocs/recruitment/admin/candidature_extrafields.php @@ -34,13 +34,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 = 'recruitment_recruitmentcandidature'; -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -73,8 +77,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -84,8 +87,7 @@ if ($action != 'create' && $action != 'edit') /* * Creation of an optional field */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -95,8 +97,7 @@ if ($action == 'create') /* * Edition of an optional field */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/recruitment/admin/index.html b/htdocs/recruitment/admin/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/recruitment/admin/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/recruitment/admin/jobposition_extrafields.php b/htdocs/recruitment/admin/jobposition_extrafields.php index af7a7c316a7..7df03c0c543 100644 --- a/htdocs/recruitment/admin/jobposition_extrafields.php +++ b/htdocs/recruitment/admin/jobposition_extrafields.php @@ -34,13 +34,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 = 'recruitment_recruitmentjobposition'; -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -73,8 +77,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -84,8 +87,7 @@ if ($action != 'create' && $action != 'edit') /* * Creation of an optional field */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -95,8 +97,7 @@ if ($action == 'create') /* * Edition of an optional field */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/recruitment/admin/public_interface.php b/htdocs/recruitment/admin/public_interface.php index 31925608811..7b2d72cb835 100644 --- a/htdocs/recruitment/admin/public_interface.php +++ b/htdocs/recruitment/admin/public_interface.php @@ -33,7 +33,9 @@ $langs->loadLangs(array("admin", "recruitment")); $action = GETPOST('action', 'aZ09'); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $error = 0; @@ -43,8 +45,11 @@ $error = 0; */ if ($action == 'setRECRUITMENT_ENABLE_PUBLIC_INTERFACE') { - if (GETPOST('value')) dolibarr_set_const($db, 'RECRUITMENT_ENABLE_PUBLIC_INTERFACE', 1, 'chaine', 0, '', $conf->entity); - else dolibarr_set_const($db, 'RECRUITMENT_ENABLE_PUBLIC_INTERFACE', 0, 'chaine', 0, '', $conf->entity); + if (GETPOST('value')) { + dolibarr_set_const($db, 'RECRUITMENT_ENABLE_PUBLIC_INTERFACE', 1, 'chaine', 0, '', $conf->entity); + } else { + dolibarr_set_const($db, 'RECRUITMENT_ENABLE_PUBLIC_INTERFACE', 0, 'chaine', 0, '', $conf->entity); + } } if ($action == 'update') { @@ -52,9 +57,11 @@ if ($action == 'update') { $res = dolibarr_set_const($db, "RECRUITMENT_ENABLE_PUBLIC_INTERFACE", $public, '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'); diff --git a/htdocs/recruitment/admin/setup.php b/htdocs/recruitment/admin/setup.php index 1c2d76ffd40..6da39445f7f 100644 --- a/htdocs/recruitment/admin/setup.php +++ b/htdocs/recruitment/admin/setup.php @@ -25,16 +25,30 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} global $langs, $user; @@ -47,7 +61,9 @@ require_once DOL_DOCUMENT_ROOT."/recruitment/class/recruitmentjobposition.class. $langs->loadLangs(array("admin", "recruitment")); // Access control -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Parameters $action = GETPOST('action', 'aZ09'); @@ -71,28 +87,28 @@ $setupnotempty = 0; * Actions */ -if ((float) DOL_VERSION >= 6) -{ +if ((float) DOL_VERSION >= 6) { include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; } -if ($action == 'updateMask') -{ +if ($action == 'updateMask') { $maskconstorder = GETPOST('maskconstorder', 'alpha'); $maskorder = GETPOST('maskorder', 'alpha'); - if ($maskconstorder) $res = dolibarr_set_const($db, $maskconstorder, $maskorder, 'chaine', 0, '', $conf->entity); + if ($maskconstorder) { + $res = dolibarr_set_const($db, $maskconstorder, $maskorder, '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'); } -} elseif ($action == 'specimen') -{ +} elseif ($action == 'specimen') { $modele = GETPOST('module', 'alpha'); $tmpobjectkey = GETPOST('object'); @@ -102,25 +118,21 @@ if ($action == 'updateMask') // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/mymodule/doc/pdf_".$modele."_".strtolower($tmpobjectkey).".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db); - if ($module->write_file($tmpobject, $langs) > 0) - { + if ($module->write_file($tmpobject, $langs) > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=".strtolower($tmpobjectkey)."&file=SPECIMEN.pdf"); return; } else { @@ -131,10 +143,8 @@ if ($action == 'updateMask') setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); } -} - -// Activate a model -elseif ($action == 'set') { +} elseif ($action == 'set') { + // Activate a model $ret = addDocumentModel($value, $type, $label, $scandir); } elseif ($action == 'del') { $ret = delDocumentModel($value, $type); @@ -142,12 +152,12 @@ elseif ($action == 'set') { $tmpobjectkey = GETPOST('object'); if (!empty($tmpobjectkey)) { $constforval = 'RECRUITMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; - if ($conf->global->$constforval == "$value") dolibarr_del_const($db, $constforval, $conf->entity); + if ($conf->global->$constforval == "$value") { + dolibarr_del_const($db, $constforval, $conf->entity); + } } } -} - -elseif ($action == 'setmod') { +} elseif ($action == 'setmod') { // TODO Check if numbering module chosen can be activated by calling method canBeActivated $tmpobjectkey = GETPOST('object'); if (!empty($tmpobjectkey)) { @@ -155,10 +165,8 @@ elseif ($action == 'setmod') { dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity); } -} - -// Set default model -elseif ($action == 'setdoc') { +} elseif ($action == 'setdoc') { + // Set default model $tmpobjectkey = GETPOST('object'); if (!empty($tmpobjectkey)) { $constforval = 'RECRUITMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; @@ -208,8 +216,7 @@ print dol_get_fiche_head($head, 'settings', '', -1, ''); //echo '<span class="opacitymedium">'.$langs->trans("RecruitmentSetupPage").'</span><br><br>'; -if ($action == 'edit') -{ +if ($action == 'edit') { print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; @@ -217,8 +224,7 @@ if ($action == 'edit') print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>'; - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { print '<tr class="oddeven"><td>'; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); @@ -233,13 +239,11 @@ if ($action == 'edit') print '</form>'; print '<br>'; } else { - if (!empty($arrayofparameters)) - { + if (!empty($arrayofparameters)) { print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>'; - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { $setupnotempty++; print '<tr class="oddeven"><td>'; @@ -282,30 +286,28 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { clearstatcache(); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/".$moduledir); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php') - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php') { $file = substr($file, 0, dol_strlen($file) - 4); require_once $dir.'/'.$file.'.php'; $module = new $file($db); // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } - if ($module->isEnabled()) - { + if ($module->isEnabled()) { dol_include_once('/'.$moduledir.'/class/'.strtolower($myTmpObjectKey).'.class.php'); print '<tr class="oddeven"><td>'.$module->name."</td><td>\n"; @@ -318,14 +320,16 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '<div class="error">'.$langs->trans($tmp).'</div>'; - } elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); - else print $tmp; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; + } print '</td>'."\n"; print '<td class="center">'; $constforvar = 'RECRUITMENT_'.strtoupper($myTmpObjectKey).'_ADDON'; - if ($conf->global->$constforvar == $file) - { + if ($conf->global->$constforvar == $file) { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print '<a href="'.$_SERVER["PHP_SELF"].'?action=setmod&token='.newToken().'&object='.strtolower($myTmpObjectKey).'&value='.urlencode($file).'">'; @@ -345,8 +349,9 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { $nextval = $langs->trans($nextval); + } $htmltooltip .= $nextval.'<br>'; } else { $htmltooltip .= $langs->trans($module->error).'<br>'; @@ -387,8 +392,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -410,31 +414,23 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { clearstatcache(); - foreach ($dirmodels as $reldir) - { - foreach (array('', '/doc') as $valdir) - { + foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { $realpath = $reldir."core/modules/".$moduledir.$valdir; $dir = dol_buildpath($realpath); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -442,21 +438,26 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { $module = new $classname($db); $modulequalified = 1; - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print '<tr class="oddeven"><td width="100">'; print (empty($module->name) ? $name : $module->name); print "</td><td>\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print '</td>'; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print '<td class="center">'."\n"; print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&amp;token='.newToken().'&amp;value='.$name.'">'; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -483,8 +484,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } $htmltooltip .= '<br>'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; @@ -499,8 +499,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { // Preview print '<td class="center">'; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'&object='.$myTmpObjectKey.'">'.img_object($langs->trans("Preview"), 'generic').'</a>'; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); diff --git a/htdocs/recruitment/admin/setup_candidatures.php b/htdocs/recruitment/admin/setup_candidatures.php index 9bc3cd96d5a..2bcddf58964 100644 --- a/htdocs/recruitment/admin/setup_candidatures.php +++ b/htdocs/recruitment/admin/setup_candidatures.php @@ -25,16 +25,30 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} global $langs, $user; @@ -47,7 +61,9 @@ require_once DOL_DOCUMENT_ROOT."/recruitment/class/recruitmentjobposition.class. $langs->loadLangs(array("admin", "recruitment")); // Access control -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Parameters $action = GETPOST('action', 'aZ09'); @@ -71,28 +87,28 @@ $setupnotempty = 0; * Actions */ -if ((float) DOL_VERSION >= 6) -{ +if ((float) DOL_VERSION >= 6) { include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; } -if ($action == 'updateMask') -{ +if ($action == 'updateMask') { $maskconstorder = GETPOST('maskconstorder', 'alpha'); $maskorder = GETPOST('maskorder', 'alpha'); - if ($maskconstorder) $res = dolibarr_set_const($db, $maskconstorder, $maskorder, 'chaine', 0, '', $conf->entity); + if ($maskconstorder) { + $res = dolibarr_set_const($db, $maskconstorder, $maskorder, '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'); } -} elseif ($action == 'specimen') -{ +} elseif ($action == 'specimen') { $modele = GETPOST('module', 'alpha'); $tmpobjectkey = GETPOST('object'); @@ -102,25 +118,21 @@ if ($action == 'updateMask') // Search template files $file = ''; $classname = ''; $filefound = 0; $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $file = dol_buildpath($reldir."core/modules/mymodule/doc/pdf_".$modele."_".strtolower($tmpobjectkey).".modules.php", 0); - if (file_exists($file)) - { + if (file_exists($file)) { $filefound = 1; $classname = "pdf_".$modele; break; } } - if ($filefound) - { + if ($filefound) { require_once $file; $module = new $classname($db); - if ($module->write_file($tmpobject, $langs) > 0) - { + if ($module->write_file($tmpobject, $langs) > 0) { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=".strtolower($tmpobjectkey)."&file=SPECIMEN.pdf"); return; } else { @@ -131,10 +143,8 @@ if ($action == 'updateMask') setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); } -} - -// Activate a model -elseif ($action == 'set') { +} elseif ($action == 'set') { + // Activate a model $ret = addDocumentModel($value, $type, $label, $scandir); } elseif ($action == 'del') { $tmpobjectkey = GETPOST('object'); @@ -142,11 +152,11 @@ elseif ($action == 'set') { $ret = delDocumentModel($value, $type); if ($ret > 0) { $constforval = 'RECRUITMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; - if ($conf->global->$constforval == "$value") dolibarr_del_const($db, $constforval, $conf->entity); + if ($conf->global->$constforval == "$value") { + dolibarr_del_const($db, $constforval, $conf->entity); + } } -} - -elseif ($action == 'setmod') { +} elseif ($action == 'setmod') { // TODO Check if numbering module chosen can be activated by calling method canBeActivated $tmpobjectkey = GETPOST('object'); if (!empty($tmpobjectkey)) { @@ -154,10 +164,8 @@ elseif ($action == 'setmod') { dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity); } -} - -// Set default model -elseif ($action == 'setdoc') { +} elseif ($action == 'setdoc') { + // Set default model $tmpobjectkey = GETPOST('object'); $constforval = 'RECRUITMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; if (dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity)) { @@ -205,8 +213,7 @@ print dol_get_fiche_head($head, 'settings_candidatures', '', -1, ''); //echo '<span class="opacitymedium">'.$langs->trans("RecruitmentSetupPage").'</span><br><br>'; -if ($action == 'edit') -{ +if ($action == 'edit') { print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; @@ -214,8 +221,7 @@ if ($action == 'edit') print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>'; - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { print '<tr class="oddeven"><td>'; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); @@ -230,13 +236,11 @@ if ($action == 'edit') print '</form>'; print '<br>'; } else { - if (!empty($arrayofparameters)) - { + if (!empty($arrayofparameters)) { print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>'; - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { $setupnotempty++; print '<tr class="oddeven"><td>'; @@ -279,19 +283,14 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { clearstatcache(); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/".$moduledir); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php') - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php') { $file = substr($file, 0, dol_strlen($file) - 4); require_once $dir.'/'.$file.'.php'; @@ -299,11 +298,14 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { $module = new $file($db); // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } - if ($module->isEnabled()) - { + if ($module->isEnabled()) { dol_include_once('/'.$moduledir.'/class/'.strtolower($myTmpObjectKey).'.class.php'); print '<tr class="oddeven"><td>'.$module->name."</td><td>\n"; @@ -316,14 +318,16 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '<div class="error">'.$langs->trans($tmp).'</div>'; - } elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); - else print $tmp; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; + } print '</td>'."\n"; print '<td class="center">'; $constforvar = 'RECRUITMENT_'.strtoupper($myTmpObjectKey).'_ADDON'; - if ($conf->global->$constforvar == $file) - { + if ($conf->global->$constforvar == $file) { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print '<a href="'.$_SERVER["PHP_SELF"].'?action=setmod&token='.newToken().'&object='.strtolower($myTmpObjectKey).'&value='.urlencode($file).'">'; @@ -343,8 +347,9 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { $nextval = $langs->trans($nextval); + } $htmltooltip .= $nextval.'<br>'; } else { $htmltooltip .= $langs->trans($module->error).'<br>'; @@ -382,12 +387,10 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { $sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -409,31 +412,23 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { clearstatcache(); - foreach ($dirmodels as $reldir) - { - foreach (array('', '/doc') as $valdir) - { + foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { $realpath = $reldir."core/modules/".$moduledir.$valdir; $dir = dol_buildpath($realpath); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach ($filelist as $file) - { - if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) - { - if (file_exists($dir.'/'.$file)) - { + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); @@ -441,21 +436,26 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { $module = new $classname($db); $modulequalified = 1; - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $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; + } - if ($modulequalified) - { + if ($modulequalified) { print '<tr class="oddeven"><td width="100">'; print (empty($module->name) ? $name : $module->name); print "</td><td>\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print '</td>'; // Active - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print '<td class="center">'."\n"; print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&amp;token='.newToken().'&amp;value='.$name.'">'; print img_picto($langs->trans("Enabled"), 'switch_on'); @@ -482,8 +482,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } $htmltooltip .= '<br>'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; @@ -498,8 +497,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { // Preview print '<td class="center">'; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'&object='.$myTmpObjectKey.'">'.img_object($langs->trans("Preview"), 'generic').'</a>'; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); diff --git a/htdocs/recruitment/class/index.html b/htdocs/recruitment/class/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/recruitment/class/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/recruitment/class/recruitmentcandidature.class.php b/htdocs/recruitment/class/recruitmentcandidature.class.php index 9e99cbc29fb..99ac555ba8e 100644 --- a/htdocs/recruitment/class/recruitmentcandidature.class.php +++ b/htdocs/recruitment/class/recruitmentcandidature.class.php @@ -164,8 +164,12 @@ class RecruitmentCandidature extends CommonObject $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } // Example to show how to set values of fields definition dynamically /*if ($user->rights->recruitment->recruitmentcandidature->read) { @@ -174,23 +178,17 @@ class RecruitmentCandidature extends CommonObject }*/ // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } // Translate some data of arrayofkeyval - if (is_object($langs)) - { - foreach ($this->fields as $key => $val) - { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } @@ -230,7 +228,9 @@ class RecruitmentCandidature extends CommonObject // Load source object $result = $object->fetchCommon($fromid); - if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); + if ($result > 0 && !empty($object->table_element_line)) { + $object->fetchLines(); + } // get lines so they will be clone //foreach($this->lines as $line) @@ -242,22 +242,29 @@ class RecruitmentCandidature extends CommonObject unset($object->import_key); // Clear fields - if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; - if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; - if (property_exists($object, 'status')) { $object->status = self::STATUS_DRAFT; } - if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); } - if (property_exists($object, 'date_modification')) { $object->date_modification = null; } + if (property_exists($object, 'ref')) { + $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; + } + if (property_exists($object, 'label')) { + $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; + } + if (property_exists($object, 'status')) { + $object->status = self::STATUS_DRAFT; + } + if (property_exists($object, 'date_creation')) { + $object->date_creation = dol_now(); + } + if (property_exists($object, 'date_modification')) { + $object->date_modification = null; + } // ... // Clear extrafields that are unique - if (is_array($object->array_options) && count($object->array_options) > 0) - { + if (is_array($object->array_options) && count($object->array_options) > 0) { $extrafields->fetch_name_optionals_label($this->table_element); - foreach ($object->array_options as $key => $option) - { + foreach ($object->array_options as $key => $option) { $shortkey = preg_replace('/options_/', '', $key); - if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) - { + if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) { //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; unset($object->array_options[$key]); } @@ -273,22 +280,19 @@ class RecruitmentCandidature extends CommonObject $this->errors = $object->errors; } - if (!$error) - { + if (!$error) { // copy internal contacts - if ($this->copy_linked_contact($object, 'internal') < 0) - { + if ($this->copy_linked_contact($object, 'internal') < 0) { $error++; } } - if (!$error) - { + if (!$error) { // copy external contacts if same company - if (property_exists($this, 'socid') && $this->socid == $object->socid) - { - if ($this->copy_linked_contact($object, 'external') < 0) + if (property_exists($this, 'socid') && $this->socid == $object->socid) { + if ($this->copy_linked_contact($object, 'external') < 0) { $error++; + } } } @@ -315,9 +319,13 @@ class RecruitmentCandidature extends CommonObject public function fetch($id, $ref = null, $email_msgid = '') { $morewhere = ''; - if ($email_msgid) $morewhere = " AND email_msgid = '".$this->db->escape($email_msgid)."'"; + if ($email_msgid) { + $morewhere = " AND email_msgid = '".$this->db->escape($email_msgid)."'"; + } $result = $this->fetchCommon($id, $ref, $morewhere); - if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); + if ($result > 0 && !empty($this->table_element_line)) { + $this->fetchLines(); + } return $result; } @@ -357,8 +365,11 @@ class RecruitmentCandidature extends CommonObject $sql = 'SELECT '; $sql .= $this->getFieldList(); $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; - else $sql .= ' WHERE 1 = 1'; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { + $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; + } else { + $sql .= ' WHERE 1 = 1'; + } // Manage filter $sqlwhere = array(); if (count($filter) > 0) { @@ -391,8 +402,7 @@ class RecruitmentCandidature extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < ($limit ? min($limit, $num) : $num)) - { + while ($i < ($limit ? min($limit, $num) : $num)) { $obj = $this->db->fetch_object($resql); $record = new self($this->db); @@ -448,8 +458,7 @@ class RecruitmentCandidature extends CommonObject */ public function deleteLine(User $user, $idline, $notrigger = false) { - if ($this->status < 0) - { + if ($this->status < 0) { $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; return -2; } @@ -474,8 +483,7 @@ class RecruitmentCandidature extends CommonObject $error = 0; // Protection - if ($this->status == self::STATUS_VALIDATED) - { + if ($this->status == self::STATUS_VALIDATED) { dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); return 0; } @@ -493,8 +501,7 @@ class RecruitmentCandidature extends CommonObject $this->db->begin(); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef(); } else { $num = $this->ref; @@ -506,57 +513,58 @@ class RecruitmentCandidature extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql .= " SET ref = '".$this->db->escape($num)."',"; $sql .= " status = ".self::STATUS_VALIDATED; - if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."',"; - if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".$user->id; + if (!empty($this->fields['date_validation'])) { + $sql .= ", date_validation = '".$this->db->idate($now)."',"; + } + if (!empty($this->fields['fk_user_valid'])) { + $sql .= ", fk_user_valid = ".$user->id; + } $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::validate()", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $this->error = $this->db->lasterror(); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('RECRUITMENTCANDIDATURE_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'recruitmentcandidature/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'recruitmentcandidature/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->recruitment->dir_output.'/recruitmentcandidature/'.$oldref; $dirdest = $conf->recruitment->dir_output.'/recruitmentcandidature/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->recruitment->dir_output.'/recruitmentcandidature/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -569,14 +577,12 @@ class RecruitmentCandidature extends CommonObject } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $num; $this->status = self::STATUS_VALIDATED; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -596,8 +602,7 @@ class RecruitmentCandidature extends CommonObject public function setDraft($user, $notrigger = 0) { // Protection - if ($this->status <= self::STATUS_DRAFT) - { + if ($this->status <= self::STATUS_DRAFT) { return 0; } @@ -621,8 +626,7 @@ class RecruitmentCandidature extends CommonObject public function cancel($user, $notrigger = 0) { // Protection - if ($this->status != self::STATUS_VALIDATED) - { + if ($this->status != self::STATUS_VALIDATED) { return 0; } @@ -646,8 +650,7 @@ class RecruitmentCandidature extends CommonObject public function reopen($user, $notrigger = 0) { // Protection - if ($this->status != self::STATUS_REFUSED && $this->status != self::STATUS_CANCELED && $this->status != self::STATUS_CONTRACT_REFUSED) - { + if ($this->status != self::STATUS_REFUSED && $this->status != self::STATUS_CANCELED && $this->status != self::STATUS_CONTRACT_REFUSED) { return 0; } @@ -675,7 +678,9 @@ class RecruitmentCandidature extends CommonObject { global $conf, $langs, $hookmanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -690,25 +695,28 @@ class RecruitmentCandidature extends CommonObject $url = dol_buildpath('/recruitment/recruitmentcandidature_card.php', 1).'?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowRecruitmentCandidature"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = '<a href="'.$url.'"'; $linkstart .= $linkclose.'>'; @@ -717,7 +725,9 @@ class RecruitmentCandidature extends CommonObject $result .= $linkstart; if (empty($this->showphoto_on_popup)) { - 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) { + $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); + } } else { if ($withpicto) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -743,7 +753,9 @@ class RecruitmentCandidature extends CommonObject } } - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -752,8 +764,11 @@ class RecruitmentCandidature extends CommonObject $hookmanager->initHooks(array('recruitmentcandidaturedao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -780,8 +795,7 @@ class RecruitmentCandidature extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("recruitment@recruitment"); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); @@ -802,7 +816,9 @@ class RecruitmentCandidature extends CommonObject $statusType = 'status'.$status; //if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; - if ($status == self::STATUS_CANCELED) $statusType = 'status6'; + if ($status == self::STATUS_CANCELED) { + $statusType = 'status6'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -818,30 +834,25 @@ class RecruitmentCandidature 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; @@ -881,8 +892,7 @@ class RecruitmentCandidature extends CommonObject $objectline = new RecruitmentCandidatureLine($this->db); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_recruitmentcandidature = '.$this->id)); - if (is_numeric($result)) - { + if (is_numeric($result)) { $this->error = $this->error; $this->errors = $this->errors; return $result; @@ -906,8 +916,7 @@ class RecruitmentCandidature extends CommonObject $conf->global->RECRUITMENT_RECRUITMENTCANDIDATURE_ADDON = 'mod_recruitmentcandidature_standard'; } - if (!empty($conf->global->RECRUITMENT_RECRUITMENTCANDIDATURE_ADDON)) - { + if (!empty($conf->global->RECRUITMENT_RECRUITMENTCANDIDATURE_ADDON)) { $mybool = false; $file = $conf->global->RECRUITMENT_RECRUITMENTCANDIDATURE_ADDON.".php"; @@ -915,16 +924,14 @@ class RecruitmentCandidature extends CommonObject // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/recruitment/"); // Load file with numbering class (if found) $mybool |= @include_once $dir.$file; } - if ($mybool === false) - { + if ($mybool === false) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -933,8 +940,7 @@ class RecruitmentCandidature extends CommonObject $obj = new $classname(); $numref = $obj->getNextValue($this); - if ($numref != '' && $numref != '-1') - { + if ($numref != '' && $numref != '-1') { return $numref; } else { $this->error = $obj->error; @@ -972,8 +978,7 @@ class RecruitmentCandidature extends CommonObject $langs->load("recruitment@recruitment"); if (!dol_strlen($modele)) { - if (!empty($conf->global->RECRUITMENTCANDIDATURE_ADDON_PDF)) - { + if (!empty($conf->global->RECRUITMENTCANDIDATURE_ADDON_PDF)) { $modele = $conf->global->RECRUITMENTCANDIDATURE_ADDON_PDF; } else { $modele = ''; // No default value. For job application, we allow to disable all PDF generation diff --git a/htdocs/recruitment/class/recruitmentjobposition.class.php b/htdocs/recruitment/class/recruitmentjobposition.class.php index 6861717d825..d82e2265e7e 100644 --- a/htdocs/recruitment/class/recruitmentjobposition.class.php +++ b/htdocs/recruitment/class/recruitmentjobposition.class.php @@ -179,8 +179,12 @@ class RecruitmentJobPosition extends CommonObject $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } // Example to show how to set values of fields definition dynamically /*if ($user->rights->recruitment->recruitmentjobposition->read) { @@ -189,23 +193,17 @@ class RecruitmentJobPosition extends CommonObject }*/ // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } // Translate some data of arrayofkeyval - if (is_object($langs)) - { - foreach ($this->fields as $key => $val) - { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } @@ -245,7 +243,9 @@ class RecruitmentJobPosition extends CommonObject // Load source object $result = $object->fetchCommon($fromid); - if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); + if ($result > 0 && !empty($object->table_element_line)) { + $object->fetchLines(); + } // get lines so they will be clone //foreach($this->lines as $line) @@ -257,21 +257,28 @@ class RecruitmentJobPosition extends CommonObject unset($object->import_key); // Clear fields - if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; - if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; - if (property_exists($object, 'status')) { $object->status = self::STATUS_DRAFT; } - if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); } - if (property_exists($object, 'date_modification')) { $object->date_modification = null; } + if (property_exists($object, 'ref')) { + $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; + } + if (property_exists($object, 'label')) { + $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; + } + if (property_exists($object, 'status')) { + $object->status = self::STATUS_DRAFT; + } + if (property_exists($object, 'date_creation')) { + $object->date_creation = dol_now(); + } + if (property_exists($object, 'date_modification')) { + $object->date_modification = null; + } // ... // Clear extrafields that are unique - if (is_array($object->array_options) && count($object->array_options) > 0) - { + if (is_array($object->array_options) && count($object->array_options) > 0) { $extrafields->fetch_name_optionals_label($this->table_element); - foreach ($object->array_options as $key => $option) - { + foreach ($object->array_options as $key => $option) { $shortkey = preg_replace('/options_/', '', $key); - if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) - { + if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) { //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; unset($object->array_options[$key]); } @@ -287,22 +294,19 @@ class RecruitmentJobPosition extends CommonObject $this->errors = $object->errors; } - if (!$error) - { + if (!$error) { // copy internal contacts - if ($this->copy_linked_contact($object, 'internal') < 0) - { + if ($this->copy_linked_contact($object, 'internal') < 0) { $error++; } } - if (!$error) - { + if (!$error) { // copy external contacts if same company - if (property_exists($this, 'socid') && $this->socid == $object->socid) - { - if ($this->copy_linked_contact($object, 'external') < 0) + if (property_exists($this, 'socid') && $this->socid == $object->socid) { + if ($this->copy_linked_contact($object, 'external') < 0) { $error++; + } } } @@ -328,7 +332,9 @@ class RecruitmentJobPosition extends CommonObject public function fetch($id, $ref = null) { $result = $this->fetchCommon($id, $ref); - if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); + if ($result > 0 && !empty($this->table_element_line)) { + $this->fetchLines(); + } return $result; } @@ -368,8 +374,11 @@ class RecruitmentJobPosition extends CommonObject $sql = 'SELECT '; $sql .= $this->getFieldList(); $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; - else $sql .= ' WHERE 1 = 1'; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { + $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; + } else { + $sql .= ' WHERE 1 = 1'; + } // Manage filter $sqlwhere = array(); if (count($filter) > 0) { @@ -402,8 +411,7 @@ class RecruitmentJobPosition extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < ($limit ? min($limit, $num) : $num)) - { + while ($i < ($limit ? min($limit, $num) : $num)) { $obj = $this->db->fetch_object($resql); $record = new self($this->db); @@ -459,8 +467,7 @@ class RecruitmentJobPosition extends CommonObject */ public function deleteLine(User $user, $idline, $notrigger = false) { - if ($this->status < 0) - { + if ($this->status < 0) { $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; return -2; } @@ -485,8 +492,7 @@ class RecruitmentJobPosition extends CommonObject $error = 0; // Protection - if ($this->status == self::STATUS_VALIDATED) - { + if ($this->status == self::STATUS_VALIDATED) { dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); return 0; } @@ -504,8 +510,7 @@ class RecruitmentJobPosition extends CommonObject $this->db->begin(); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef(); } else { $num = $this->ref; @@ -517,57 +522,58 @@ class RecruitmentJobPosition extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql .= " SET ref = '".$this->db->escape($num)."',"; $sql .= " status = ".self::STATUS_VALIDATED; - if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."',"; - if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".$user->id; + if (!empty($this->fields['date_validation'])) { + $sql .= ", date_validation = '".$this->db->idate($now)."',"; + } + if (!empty($this->fields['fk_user_valid'])) { + $sql .= ", fk_user_valid = ".$user->id; + } $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::validate()", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $this->error = $this->db->lasterror(); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('RECRUITMENTJOBPOSITION_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'recruitmentjobposition/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'recruitmentjobposition/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->recruitment->dir_output.'/recruitmentjobposition/'.$oldref; $dirdest = $conf->recruitment->dir_output.'/recruitmentjobposition/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->recruitment->dir_output.'/recruitmentjobposition/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -580,14 +586,12 @@ class RecruitmentJobPosition extends CommonObject } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $num; $this->status = self::STATUS_VALIDATED; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -607,8 +611,7 @@ class RecruitmentJobPosition extends CommonObject public function setDraft($user, $notrigger = 0) { // Protection - if ($this->status <= self::STATUS_DRAFT) - { + if ($this->status <= self::STATUS_DRAFT) { return 0; } @@ -632,8 +635,7 @@ class RecruitmentJobPosition extends CommonObject public function cancel($user, $notrigger = 0) { // Protection - if ($this->status != self::STATUS_VALIDATED) - { + if ($this->status != self::STATUS_VALIDATED) { return 0; } @@ -673,30 +675,25 @@ class RecruitmentJobPosition extends CommonObject $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $modelpdf = $this->model_pdf; $triggerName = 'RECRUITMENTJOB_CLOSE_REFUSED'; - if ($status == self::STATUS_RECRUITED) - { + if ($status == self::STATUS_RECRUITED) { $triggerName = 'RECRUITMENTJOB_CLOSE_RECRUITED'; $modelpdf = $this->model_pdf; - if ($result < 0) - { + if ($result < 0) { $this->error = $this->db->lasterror(); $this->db->rollback(); return -2; } } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); @@ -705,24 +702,23 @@ class RecruitmentJobPosition extends CommonObject $this->generateDocument($modelpdf, $outputlangs); } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->status = $status; $this->date_cloture = $now; $this->note_private = $newprivatenote; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger($triggerName, $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -750,8 +746,7 @@ class RecruitmentJobPosition extends CommonObject public function reopen($user, $notrigger = 0) { // Protection - if ($this->status != self::STATUS_CANCELED) - { + if ($this->status != self::STATUS_CANCELED) { return 0; } @@ -779,7 +774,9 @@ class RecruitmentJobPosition extends CommonObject { global $conf, $langs, $hookmanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -793,25 +790,28 @@ class RecruitmentJobPosition extends CommonObject $url = dol_buildpath('/recruitment/recruitmentjobposition_card.php', 1).'?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowRecruitmentJobPosition"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = '<a href="'.$url.'"'; $linkstart .= $linkclose.'>'; @@ -820,7 +820,9 @@ class RecruitmentJobPosition extends CommonObject $result .= $linkstart; if (empty($this->showphoto_on_popup)) { - 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) { + $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); + } } else { if ($withpicto) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -846,7 +848,9 @@ class RecruitmentJobPosition extends CommonObject } } - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -855,8 +859,11 @@ class RecruitmentJobPosition extends CommonObject $hookmanager->initHooks(array('recruitmentjobpositiondao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -883,8 +890,7 @@ class RecruitmentJobPosition extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("recruitment"); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); @@ -898,9 +904,15 @@ class RecruitmentJobPosition extends CommonObject } $statusType = 'status'.$status; - if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; - if ($status == self::STATUS_RECRUITED) $statusType = 'status6'; - if ($status == self::STATUS_CANCELED) $statusType = 'status9'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } + if ($status == self::STATUS_RECRUITED) { + $statusType = 'status6'; + } + if ($status == self::STATUS_CANCELED) { + $statusType = 'status9'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -916,30 +928,25 @@ class RecruitmentJobPosition 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; @@ -993,8 +1000,7 @@ class RecruitmentJobPosition extends CommonObject $conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON = 'mod_recruitmentjobposition_standard'; } - if (!empty($conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON)) - { + if (!empty($conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON)) { $mybool = false; $file = $conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON.".php"; @@ -1002,16 +1008,14 @@ class RecruitmentJobPosition extends CommonObject // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/recruitment/"); // Load file with numbering class (if found) $mybool |= @include_once $dir.$file; } - if ($mybool === false) - { + if ($mybool === false) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -1020,8 +1024,7 @@ class RecruitmentJobPosition extends CommonObject $obj = new $classname(); $numref = $obj->getNextValue($this); - if ($numref != '' && $numref != '-1') - { + if ($numref != '' && $numref != '-1') { return $numref; } else { $this->error = $obj->error; diff --git a/htdocs/recruitment/core/modules/recruitment/doc/doc_generic_recruitmentjobposition_odt.modules.php b/htdocs/recruitment/core/modules/recruitment/doc/doc_generic_recruitmentjobposition_odt.modules.php index 0a8fb1bab0f..054443a5be5 100644 --- a/htdocs/recruitment/core/modules/recruitment/doc/doc_generic_recruitmentjobposition_odt.modules.php +++ b/htdocs/recruitment/core/modules/recruitment/doc/doc_generic_recruitmentjobposition_odt.modules.php @@ -98,7 +98,9 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi // Recupere emetteur $this->emetteur = $mysoc; - if (!$this->emetteur->country_code) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined + if (!$this->emetteur->country_code) { + $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined + } } @@ -129,8 +131,7 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi $texttitle = $langs->trans("ListOfDirectories"); $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON_PDF_ODT_PATH))); $listoffiles = array(); - foreach ($listofdir as $key=>$tmpdir) - { + foreach ($listofdir as $key => $tmpdir) { $tmpdir = trim($tmpdir); $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); if (!$tmpdir) { @@ -140,7 +141,9 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0); } else { $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)'); - if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); + if (count($tmpfiles)) { + $listoffiles = array_merge($listoffiles, $tmpfiles); + } } } $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT"); @@ -159,8 +162,7 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi // Scan directories $nbofiles = count($listoffiles); - if (!empty($conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON_PDF_ODT_PATH)) - { + if (!empty($conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON_PDF_ODT_PATH)) { $texte .= $langs->trans("NumberOfModelFilesFound").': <b>'; //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':''; $texte .= count($listoffiles); @@ -168,11 +170,9 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi $texte .= '</b>'; } - if ($nbofiles) - { + if ($nbofiles) { $texte .= '<div id="div_'.get_class($this).'" class="hidden">'; - foreach ($listoffiles as $file) - { + foreach ($listoffiles as $file) { $texte .= $file['name'].'<br>'; } $texte .= '</div>'; @@ -208,37 +208,34 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi // phpcs:enable global $user, $langs, $conf, $mysoc, $hookmanager; - if (empty($srctemplatepath)) - { + if (empty($srctemplatepath)) { dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); return -1; } // Add odtgeneration hook - if (!is_object($hookmanager)) - { + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('odtgeneration')); global $action; - if (!is_object($outputlangs)) $outputlangs = $langs; + if (!is_object($outputlangs)) { + $outputlangs = $langs; + } $sav_charset_output = $outputlangs->charset_output; $outputlangs->charset_output = 'UTF-8'; $outputlangs->loadLangs(array("main", "dict", "companies", "bills")); - if ($conf->commande->dir_output) - { + if ($conf->commande->dir_output) { // If $object is id instead of object - if (!is_object($object)) - { + if (!is_object($object)) { $id = $object; $object = new Commande($this->db); $result = $object->fetch($id); - if ($result < 0) - { + if ($result < 0) { dol_print_error($this->db, $object->error); return -1; } @@ -246,20 +243,19 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi $dir = $conf->commande->multidir_output[isset($object->entity) ? $object->entity : 1]; $objectref = dol_sanitizeFileName($object->ref); - if (!preg_match('/specimen/i', $objectref)) $dir .= "/".$objectref; + if (!preg_match('/specimen/i', $objectref)) { + $dir .= "/".$objectref; + } $file = $dir."/".$objectref.".odt"; - if (!file_exists($dir)) - { - if (dol_mkdir($dir) < 0) - { + if (!file_exists($dir)) { + if (dol_mkdir($dir) < 0) { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } - if (file_exists($dir)) - { + if (file_exists($dir)) { //print "srctemplatepath=".$srctemplatepath; // Src filename $newfile = basename($srctemplatepath); $newfiletmp = preg_replace('/\.od(t|s)/i', '', $newfile); @@ -269,10 +265,11 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt'; // Get extension (ods or odt) $newfileformat = substr($newfile, strrpos($newfile, '.') + 1); - if (!empty($conf->global->MAIN_DOC_USE_TIMING)) - { + if (!empty($conf->global->MAIN_DOC_USE_TIMING)) { $format = $conf->global->MAIN_DOC_USE_TIMING; - if ($format == '1') $format = '%Y%m%d%H%M%S'; + if ($format == '1') { + $format = '%Y%m%d%H%M%S'; + } $filename = $newfiletmp.'-'.dol_print_date(dol_now(), $format).'.'.$newfileformat; } else { $filename = $newfiletmp.'.'.$newfileformat; @@ -289,16 +286,14 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi // If CUSTOMER contact defined on order, we use it $usecontact = false; $arrayidcontact = $object->getIdContact('external', 'CUSTOMER'); - if (count($arrayidcontact) > 0) - { + if (count($arrayidcontact) > 0) { $usecontact = true; $result = $object->fetch_contact($arrayidcontact[0]); } // Recipient name $contactobject = null; - if (!empty($usecontact)) - { + if (!empty($usecontact)) { if ($usecontact && ($object->contact->fk_soc != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)))) { $socobject = $object->contact; } else { @@ -326,8 +321,7 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi // Line of free text $newfreetext = ''; $paramfreetext = 'ORDER_FREE_TEXT'; - if (!empty($conf->global->$paramfreetext)) - { + if (!empty($conf->global->$paramfreetext)) { $newfreetext = make_substitutions($conf->global->$paramfreetext, $substitutionarray); } @@ -343,8 +337,7 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi 'DELIMITER_RIGHT' => '}' ) ); - } catch (Exception $e) - { + } catch (Exception $e) { $this->error = $e->getMessage(); dol_syslog($e->getMessage(), LOG_INFO); return -1; @@ -359,8 +352,7 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi // Make substitutions into odt of freetext try { $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8'); - } catch (OdfException $e) - { + } catch (OdfException $e) { dol_syslog($e->getMessage(), LOG_INFO); } @@ -374,7 +366,9 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi $array_other = $this->get_substitutionarray_other($outputlangs); // retrieve contact information for use in object as contact_xxx tags $array_thirdparty_contact = array(); - if ($usecontact && is_object($contactobject)) $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact'); + if ($usecontact && is_object($contactobject)) { + $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact'); + } $tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_thirdparty_contact); complete_substitutions_array($tmparray, $outputlangs, $object); @@ -383,19 +377,20 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray); $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - foreach ($tmparray as $key=>$value) - { + foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { // Image - if (file_exists($value)) $odfHandler->setImage($key, $value); - else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); + if (file_exists($value)) { + $odfHandler->setImage($key, $value); + } else { + $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); + } } else { // Text $odfHandler->setVars($key, $value, true, 'UTF-8'); } - } catch (OdfException $e) - { + } catch (OdfException $e) { dol_syslog($e->getMessage(), LOG_INFO); } } @@ -404,32 +399,26 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi $foundtagforlines = 1; try { $listlines = $odfHandler->setSegment('lines'); - } catch (OdfException $e) - { + } catch (OdfException $e) { // We may arrive here if tags for lines not present into template $foundtagforlines = 0; dol_syslog($e->getMessage(), LOG_INFO); } - if ($foundtagforlines) - { + if ($foundtagforlines) { $linenumber = 0; - foreach ($object->lines as $line) - { + foreach ($object->lines as $line) { $linenumber++; $tmparray = $this->get_substitutionarray_lines($line, $outputlangs, $linenumber); complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines"); // Call the ODTSubstitutionLine hook $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray, 'line'=>$line); $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - foreach ($tmparray as $key => $val) - { + foreach ($tmparray as $key => $val) { try { $listlines->setVars($key, $val, true, 'UTF-8'); - } catch (OdfException $e) - { + } catch (OdfException $e) { dol_syslog($e->getMessage(), LOG_INFO); - } catch (SegmentException $e) - { + } catch (SegmentException $e) { dol_syslog($e->getMessage(), LOG_INFO); } } @@ -437,8 +426,7 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi } $odfHandler->mergeSegment($listlines); } - } catch (OdfException $e) - { + } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); return -1; @@ -446,12 +434,10 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi // Replace labels translated $tmparray = $outputlangs->get_translations_for_substitutions(); - foreach ($tmparray as $key=>$value) - { + foreach ($tmparray as $key => $value) { try { $odfHandler->setVars($key, $value, true, 'UTF-8'); - } catch (OdfException $e) - { + } catch (OdfException $e) { dol_syslog($e->getMessage(), LOG_INFO); } } @@ -483,8 +469,9 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray); $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); + } $odfHandler = null; // Destroy object diff --git a/htdocs/recruitment/core/modules/recruitment/doc/index.html b/htdocs/recruitment/core/modules/recruitment/doc/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/recruitment/core/modules/recruitment/doc/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/recruitment/core/modules/recruitment/doc/pdf_standard_recruitmentjobposition.modules.php b/htdocs/recruitment/core/modules/recruitment/doc/pdf_standard_recruitmentjobposition.modules.php index 918fc9f727d..21ff7c2a7ba 100644 --- a/htdocs/recruitment/core/modules/recruitment/doc/pdf_standard_recruitmentjobposition.modules.php +++ b/htdocs/recruitment/core/modules/recruitment/doc/pdf_standard_recruitmentjobposition.modules.php @@ -174,7 +174,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio // Get source company $this->emetteur = $mysoc; - if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined + if (empty($this->emetteur->country_code)) { + $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined + } // Define position of columns $this->posxdesc = $this->marge_gauche + 1; // used for notes ans other stuff @@ -212,9 +214,13 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio dol_syslog("write_file outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); - if (!is_object($outputlangs)) $outputlangs = $langs; + if (!is_object($outputlangs)) { + $outputlangs = $langs; + } // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; + if (!empty($conf->global->MAIN_USE_FPDF)) { + $outputlangs->charset_output = 'ISO-8859-1'; + } // Load translation files required by the page $outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies")); @@ -237,67 +243,65 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $realpatharray = array(); $this->atleastonephoto = false; /* - if (!empty($conf->global->MAIN_GENERATE_MYOBJECT_WITH_PICTURE)) - { - $objphoto = new Product($this->db); + if (!empty($conf->global->MAIN_GENERATE_MYOBJECT_WITH_PICTURE)) + { + $objphoto = new Product($this->db); - for ($i = 0; $i < $nblines; $i++) - { - if (empty($object->lines[$i]->fk_product)) continue; + for ($i = 0; $i < $nblines; $i++) + { + if (empty($object->lines[$i]->fk_product)) continue; - $objphoto->fetch($object->lines[$i]->fk_product); - //var_dump($objphoto->ref);exit; - if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) - { - $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; - $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; - } else { - $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; // default - $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; // alternative - } + $objphoto->fetch($object->lines[$i]->fk_product); + //var_dump($objphoto->ref);exit; + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) + { + $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; + $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; + } else { + $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; // default + $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; // alternative + } - $arephoto = false; - foreach ($pdir as $midir) - { - if (!$arephoto) - { - $dir = $conf->product->dir_output.'/'.$midir; + $arephoto = false; + foreach ($pdir as $midir) + { + if (!$arephoto) + { + $dir = $conf->product->dir_output.'/'.$midir; - foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) - { - if (empty($conf->global->CAT_HIGH_QUALITY_IMAGES)) // If CAT_HIGH_QUALITY_IMAGES not defined, we use thumb if defined and then original photo - { - if ($obj['photo_vignette']) - { - $filename = $obj['photo_vignette']; - } else { - $filename = $obj['photo']; - } - } else { - $filename = $obj['photo']; - } + foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) + { + if (empty($conf->global->CAT_HIGH_QUALITY_IMAGES)) // If CAT_HIGH_QUALITY_IMAGES not defined, we use thumb if defined and then original photo + { + if ($obj['photo_vignette']) + { + $filename = $obj['photo_vignette']; + } else { + $filename = $obj['photo']; + } + } else { + $filename = $obj['photo']; + } - $realpath = $dir.$filename; - $arephoto = true; - $this->atleastonephoto = true; - } - } - } + $realpath = $dir.$filename; + $arephoto = true; + $this->atleastonephoto = true; + } + } + } - if ($realpath && $arephoto) $realpatharray[$i] = $realpath; - } - } + if ($realpath && $arephoto) $realpatharray[$i] = $realpath; + } + } */ //if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; - if ($conf->recruitment->dir_output.'/recruitmentjobposition') - { + if ($conf->recruitment->dir_output.'/recruitmentjobposition') { $object->fetch_thirdparty(); // Definition of $dir and $file - if ($object->specimen) - { + if ($object->specimen) { $dir = $conf->recruitment->dir_output.'/recruitmentjobposition'; $file = $dir."/SPECIMEN.pdf"; } else { @@ -305,20 +309,16 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $dir = $conf->recruitment->dir_output.'/recruitmentjobposition/'.$objectref; $file = $dir."/".$objectref.".pdf"; } - if (!file_exists($dir)) - { - if (dol_mkdir($dir) < 0) - { + if (!file_exists($dir)) { + if (dol_mkdir($dir) < 0) { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return 0; } } - if (file_exists($dir)) - { + if (file_exists($dir)) { // Add pdfgeneration hook - if (!is_object($hookmanager)) - { + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; $hookmanager = new HookManager($this->db); } @@ -339,16 +339,14 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page $heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin) - if (class_exists('TCPDF')) - { + if (class_exists('TCPDF')) { $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); } $pdf->SetFont(pdf_getPDFFont($outputlangs)); // Set path to the background PDF File - if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) - { + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) { $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); $tplidx = $pdf->importPage(1); } @@ -362,7 +360,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $pdf->SetCreator("Dolibarr ".DOL_VERSION); $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$object->label." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); - if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) { + $pdf->SetCompression(false); + } // Set certificate $cert = empty($user->conf->CERTIFICATE_CRT) ? '' : $user->conf->CERTIFICATE_CRT; @@ -385,7 +385,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio // New page $pdf->AddPage(); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } $pagenb++; $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs, $outputlangsbis); @@ -397,7 +399,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); $tab_height = 130 - $top_shift; $tab_height_newpage = 150; - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $tab_height_newpage -= $top_shift; + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { + $tab_height_newpage -= $top_shift; + } $nexY = $tab_top - 1; @@ -405,14 +409,12 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $notetoshow = empty($object->note_public) ? '' : $object->note_public; // Extrafields in note $extranote = $this->getExtrafieldsInHtml($object, $outputlangs); - if (!empty($extranote)) - { + if (!empty($extranote)) { $notetoshow = dol_concatdesc($notetoshow, $extranote); } $pagenb = $pdf->getPage(); - if ($notetoshow) - { + if ($notetoshow) { $tab_top -= 2; $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite; @@ -431,16 +433,19 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $pageposafternote = $pdf->getPage(); $posyafter = $pdf->GetY(); - if ($pageposafternote > $pageposbeforenote) - { + if ($pageposafternote > $pageposbeforenote) { $pdf->rollbackTransaction(true); // prepare pages to receive notes while ($pagenb < $pageposafternote) { $pdf->AddPage(); $pagenb++; - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { + $this->_pagehead($pdf, $object, 0, $outputlangs); + } // $this->_pagefoot($pdf,$object,$outputlangs,1); $pdf->setTopMargin($tab_top_newpage); // The only function to edit the bottom margin of current page to set it. @@ -456,8 +461,7 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $posyafter = $pdf->GetY(); - if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) // There is no space left for total+free text - { + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) { // There is no space left for total+free text $pdf->AddPage('', '', true); $pagenb++; $pageposafternote++; @@ -494,8 +498,12 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio // apply note frame to last page $pdf->setPage($pageposafternote); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { + $this->_pagehead($pdf, $object, 0, $outputlangs); + } $height_note = $posyafter - $tab_top_newpage; $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); } else // No pagebreak @@ -505,15 +513,18 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $height_note = $posyafter - $tab_top; $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); - if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) - { + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) { // not enough space, need to add page $pdf->AddPage('', '', true); $pagenb++; $pageposafternote++; $pdf->setPage($pageposafternote); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { + $this->_pagehead($pdf, $object, 0, $outputlangs); + } $posyafter = $tab_top_newpage; } @@ -538,15 +549,16 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio // Loop on each lines $pageposbeforeprintlines = $pdf->getPage(); $pagenb = $pageposbeforeprintlines; - for ($i = 0; $i < $nblines; $i++) - { + for ($i = 0; $i < $nblines; $i++) { $curY = $nexY; $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); // Define size of image if we need it $imglinesize = array(); - if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); + if (!empty($realpatharray[$i])) { + $imglinesize = pdf_getSizeForImage($realpatharray[$i]); + } $pdf->setTopMargin($tab_top_newpage); $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. @@ -555,25 +567,26 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $showpricebeforepagebreak = 1; $posYAfterImage = 0; - if ($this->getColumnStatus('photo')) - { + if ($this->getColumnStatus('photo')) { // We start with Photo of product line - if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page - { + if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // If photo too high, we moved completely on new page $pdf->AddPage('', '', true); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } $pdf->setPage($pageposbefore + 1); $curY = $tab_top_newpage; // Allows data in the first page if description is long enough to break in multiples pages - if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) { $showpricebeforepagebreak = 1; - else $showpricebeforepagebreak = 0; + } else { + $showpricebeforepagebreak = 0; + } } - if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) - { + if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) { $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi // $pdf->Image does not increase value return by getY, so we save it manually $posYAfterImage = $curY + $imglinesize['height']; @@ -581,15 +594,13 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio } // Description of product line - if ($this->getColumnStatus('desc')) - { + if ($this->getColumnStatus('desc')) { $pdf->startTransaction(); $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); $pageposafter = $pdf->getPage(); - if ($pageposafter > $pageposbefore) // There is a pagebreak - { + if ($pageposafter > $pageposbefore) { // There is a pagebreak $pdf->rollbackTransaction(true); $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. @@ -598,20 +609,22 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $pageposafter = $pdf->getPage(); $posyafter = $pdf->GetY(); //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; - if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text - { - if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page - { + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // There is no space left for total+free text + if ($i == ($nblines - 1)) { // No more lines, and no space left to show total, so we create a new page $pdf->AddPage('', '', true); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } $pdf->setPage($pageposafter + 1); } } else { // We found a page break // Allows data in the first page if description is long enough to break in multiples pages - if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) { $showpricebeforepagebreak = 1; - else $showpricebeforepagebreak = 0; + } else { + $showpricebeforepagebreak = 0; + } } } else // No pagebreak { @@ -659,7 +672,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $pagenb++; $pdf->setPage($pagenb); $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { + $this->_pagehead($pdf, $object, 0, $outputlangs); + } } if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { @@ -671,15 +686,18 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $this->_pagefoot($pdf, $object, $outputlangs, 1); // New page $pdf->AddPage(); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) { + $pdf->useTemplate($tplidx); + } $pagenb++; - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { + $this->_pagehead($pdf, $object, 0, $outputlangs); + } } } // Show square - if ($pagenb == $pageposbeforeprintlines) - { + if ($pagenb == $pageposbeforeprintlines) { $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code, $outputlangsbis); $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } else { @@ -695,15 +713,17 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio // Display payment area /* - if (($deja_regle || $amount_credit_notes_included || $amount_deposits_included) && empty($conf->global->INVOICE_NO_PAYMENT_DETAILS)) - { - $posy = $this->drawPaymentsTable($pdf, $object, $posy, $outputlangs); - } - */ + if (($deja_regle || $amount_credit_notes_included || $amount_deposits_included) && empty($conf->global->INVOICE_NO_PAYMENT_DETAILS)) + { + $posy = $this->drawPaymentsTable($pdf, $object, $posy, $outputlangs); + } + */ // Pagefoot $this->_pagefoot($pdf, $object, $outputlangs); - if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages(); + if (method_exists($pdf, 'AliasNbPages')) { + $pdf->AliasNbPages(); + } $pdf->Close(); @@ -714,14 +734,14 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) - { + if ($reshook < 0) { $this->error = $hookmanager->error; $this->errors = $hookmanager->errors; } - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); + } $this->result = array('fullpath'=>$file); @@ -771,7 +791,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio // Force to disable hidetop and hidebottom $hidebottom = 0; - if ($hidetop) $hidetop = -1; + if ($hidetop) { + $hidetop = -1; + } $currency = !empty($currency) ? $currency : $conf->currency; $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -780,8 +802,7 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - if (empty($hidetop)) - { + if (empty($hidetop)) { //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230'; if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) { $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); @@ -825,8 +846,7 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio pdf_pagehead($pdf, $outputlangs, $this->page_hauteur); // Show Draft Watermark - if ($object->statut == $object::STATUS_DRAFT && (!empty($conf->global->FACTURE_DRAFT_WATERMARK))) - { + if ($object->statut == $object::STATUS_DRAFT && (!empty($conf->global->FACTURE_DRAFT_WATERMARK))) { pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->FACTURE_DRAFT_WATERMARK); } @@ -841,20 +861,18 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $pdf->SetXY($this->marge_gauche, $posy); // Logo - if (empty($conf->global->PDF_DISABLE_MYCOMPANY_LOGO)) - { - if ($this->emetteur->logo) - { + if (empty($conf->global->PDF_DISABLE_MYCOMPANY_LOGO)) { + if ($this->emetteur->logo) { $logodir = $conf->mycompany->dir_output; - if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; - if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) - { + if (!empty($conf->mycompany->multidir_output[$object->entity])) { + $logodir = $conf->mycompany->multidir_output[$object->entity]; + } + if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) { $logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small; } else { $logo = $logodir.'/logos/'.$this->emetteur->logo; } - if (is_readable($logo)) - { + if (is_readable($logo)) { $height = pdf_getHeightForLogo($logo); $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { @@ -885,8 +903,7 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $textref = $outputlangs->transnoentities("Ref")." : ".$outputlangs->convToOutputCharset($object->ref); - if ($object->statut == $object::STATUS_DRAFT) - { + if ($object->statut == $object::STATUS_DRAFT) { $pdf->SetTextColor(128, 0, 0); $textref .= ' - '.$outputlangs->transnoentities("NotValidated"); } @@ -895,19 +912,16 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $posy += 1; $pdf->SetFont('', '', $default_font_size - 2); - if ($object->ref_client) - { + if ($object->ref_client) { $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("RefCustomer")." : ".$outputlangs->convToOutputCharset($object->ref_client), '', 'R'); } - if (!empty($conf->global->PDF_SHOW_PROJECT_TITLE)) - { + if (!empty($conf->global->PDF_SHOW_PROJECT_TITLE)) { $object->fetch_projet(); - if (!empty($object->project->ref)) - { + if (!empty($object->project->ref)) { $posy += 3; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); @@ -915,11 +929,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio } } - if (!empty($conf->global->PDF_SHOW_PROJECT)) - { + if (!empty($conf->global->PDF_SHOW_PROJECT)) { $object->fetch_projet(); - if (!empty($object->project->ref)) - { + if (!empty($object->project->ref)) { $posy += 3; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); @@ -937,8 +949,7 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio } $pdf->MultiCell($w, 3, $title." : ".dol_print_date($object->date_creation, "day", false, $outputlangs), '', 'R'); - if ($object->thirdparty->code_client) - { + if ($object->thirdparty->code_client) { $posy += 3; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); @@ -951,13 +962,11 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio // Show list of linked objects $current_y = $pdf->getY(); $posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, $w, 3, 'R', $default_font_size); - if ($current_y < $pdf->getY()) - { + if ($current_y < $pdf->getY()) { $top_shift = $pdf->getY() - $current_y; } - if ($showaddress) - { + if ($showaddress) { // Sender properties $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); @@ -965,7 +974,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; $posy += $top_shift; $posx = $this->marge_gauche; - if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) { + $posx = $this->page_largeur - $this->marge_droite - 80; + } $hautcadre = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40; $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82; @@ -995,8 +1006,7 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio // If BILLING contact defined on invoice, we use it $usecontact = false; $arrayidcontact = $object->getIdContact('external', 'BILLING'); - if (count($arrayidcontact) > 0) - { + if (count($arrayidcontact) > 0) { $usecontact = true; $result = $object->fetch_contact($arrayidcontact[0]); } @@ -1091,162 +1101,162 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio ); /* - * For exemple - $this->cols['theColKey'] = array( - 'rank' => $rank, // int : use for ordering columns - 'width' => 20, // the column width in mm - 'title' => array( - 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label - 'label' => ' ', // the final label : used fore final generated text - 'align' => 'L', // text alignement : R,C,L - 'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - 'content' => array( - 'align' => 'L', // text alignement : R,C,L - 'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - ); - */ + * For exemple + $this->cols['theColKey'] = array( + 'rank' => $rank, // int : use for ordering columns + 'width' => 20, // the column width in mm + 'title' => array( + 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label + 'label' => ' ', // the final label : used fore final generated text + 'align' => 'L', // text alignement : R,C,L + 'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + 'content' => array( + 'align' => 'L', // text alignement : R,C,L + 'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + ); + */ $rank = 0; // do not use negative rank /* - $this->cols['desc'] = array( - 'rank' => $rank, - 'width' => false, // only for desc - 'status' => true, - 'title' => array( - 'textkey' => 'Designation', // use lang key is usefull in somme case with module - 'align' => 'L', - // 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label - // 'label' => ' ', // the final label - 'padding' => array(0.5, 0.5, 0.5, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - 'content' => array( - 'align' => 'L', - 'padding' => array(1, 0.5, 1, 1.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - ); + $this->cols['desc'] = array( + 'rank' => $rank, + 'width' => false, // only for desc + 'status' => true, + 'title' => array( + 'textkey' => 'Designation', // use lang key is usefull in somme case with module + 'align' => 'L', + // 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label + // 'label' => ' ', // the final label + 'padding' => array(0.5, 0.5, 0.5, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + 'content' => array( + 'align' => 'L', + 'padding' => array(1, 0.5, 1, 1.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + ); - // PHOTO - $rank = $rank + 10; - $this->cols['photo'] = array( - 'rank' => $rank, - 'width' => (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH), // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'Photo', - 'label' => ' ' - ), - 'content' => array( - 'padding' => array(0, 0, 0, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - 'border-left' => false, // remove left line separator - ); + // PHOTO + $rank = $rank + 10; + $this->cols['photo'] = array( + 'rank' => $rank, + 'width' => (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH), // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'Photo', + 'label' => ' ' + ), + 'content' => array( + 'padding' => array(0, 0, 0, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + 'border-left' => false, // remove left line separator + ); - if (!empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE) && !empty($this->atleastonephoto)) - { - $this->cols['photo']['status'] = true; - } + if (!empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE) && !empty($this->atleastonephoto)) + { + $this->cols['photo']['status'] = true; + } - $rank = $rank + 10; - $this->cols['vat'] = array( - 'rank' => $rank, - 'status' => false, - 'width' => 16, // in mm - 'title' => array( - 'textkey' => 'VAT' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 10; + $this->cols['vat'] = array( + 'rank' => $rank, + 'status' => false, + 'width' => 16, // in mm + 'title' => array( + 'textkey' => 'VAT' + ), + 'border-left' => true, // add left line separator + ); - if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) - { - $this->cols['vat']['status'] = true; - } + if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) + { + $this->cols['vat']['status'] = true; + } - $rank = $rank + 10; - $this->cols['subprice'] = array( - 'rank' => $rank, - 'width' => 19, // in mm - 'status' => true, - 'title' => array( - 'textkey' => 'PriceUHT' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 10; + $this->cols['subprice'] = array( + 'rank' => $rank, + 'width' => 19, // in mm + 'status' => true, + 'title' => array( + 'textkey' => 'PriceUHT' + ), + 'border-left' => true, // add left line separator + ); - $rank = $rank + 10; - $this->cols['qty'] = array( - 'rank' => $rank, - 'width' => 16, // in mm - 'status' => true, - 'title' => array( - 'textkey' => 'Qty' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 10; + $this->cols['qty'] = array( + 'rank' => $rank, + 'width' => 16, // in mm + 'status' => true, + 'title' => array( + 'textkey' => 'Qty' + ), + 'border-left' => true, // add left line separator + ); - $rank = $rank + 10; - $this->cols['progress'] = array( - 'rank' => $rank, - 'width' => 19, // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'Progress' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 10; + $this->cols['progress'] = array( + 'rank' => $rank, + 'width' => 19, // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'Progress' + ), + 'border-left' => true, // add left line separator + ); - if ($this->situationinvoice) - { - $this->cols['progress']['status'] = true; - } + if ($this->situationinvoice) + { + $this->cols['progress']['status'] = true; + } - $rank = $rank + 10; - $this->cols['unit'] = array( - 'rank' => $rank, - 'width' => 11, // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'Unit' - ), - 'border-left' => true, // add left line separator - ); - if (!empty($conf->global->PRODUCT_USE_UNITS)) { - $this->cols['unit']['status'] = true; - } + $rank = $rank + 10; + $this->cols['unit'] = array( + 'rank' => $rank, + 'width' => 11, // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'Unit' + ), + 'border-left' => true, // add left line separator + ); + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $this->cols['unit']['status'] = true; + } - $rank = $rank + 10; - $this->cols['discount'] = array( - 'rank' => $rank, - 'width' => 13, // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'ReductionShort' - ), - 'border-left' => true, // add left line separator - ); - if ($this->atleastonediscount) { - $this->cols['discount']['status'] = true; - } + $rank = $rank + 10; + $this->cols['discount'] = array( + 'rank' => $rank, + 'width' => 13, // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'ReductionShort' + ), + 'border-left' => true, // add left line separator + ); + if ($this->atleastonediscount) { + $this->cols['discount']['status'] = true; + } - $rank = $rank + 1000; // add a big offset to be sure is the last col because default extrafield rank is 100 - $this->cols['totalexcltax'] = array( - 'rank' => $rank, - 'width' => 26, // in mm - 'status' => true, - 'title' => array( - 'textkey' => 'TotalHT' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 1000; // add a big offset to be sure is the last col because default extrafield rank is 100 + $this->cols['totalexcltax'] = array( + 'rank' => $rank, + 'width' => 26, // in mm + 'status' => true, + 'title' => array( + 'textkey' => 'TotalHT' + ), + 'border-left' => true, // add left line separator + ); - // Add extrafields cols - if (!empty($object->lines)) { - $line = reset($object->lines); - $this->defineColumnExtrafield($line, $outputlangs, $hidedetails); - } + // Add extrafields cols + if (!empty($object->lines)) { + $line = reset($object->lines); + $this->defineColumnExtrafield($line, $outputlangs, $hidedetails); + } */ $parameters = array( @@ -1258,11 +1268,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio ); $reshook = $hookmanager->executeHooks('defineColumnField', $parameters, $this); // Note that $object may have been modified by hook - if ($reshook < 0) - { + if ($reshook < 0) { setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - } elseif (empty($reshook)) - { + } elseif (empty($reshook)) { $this->cols = array_replace($this->cols, $hookmanager->resArray); // array_replace is used to preserve keys } else { $this->cols = $hookmanager->resArray; diff --git a/htdocs/recruitment/core/modules/recruitment/index.html b/htdocs/recruitment/core/modules/recruitment/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/recruitment/core/modules/recruitment/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/recruitment/core/modules/recruitment/mod_recruitmentcandidature_standard.php b/htdocs/recruitment/core/modules/recruitment/mod_recruitmentcandidature_standard.php index 61e04b9000e..192d1d4c526 100644 --- a/htdocs/recruitment/core/modules/recruitment/mod_recruitmentcandidature_standard.php +++ b/htdocs/recruitment/core/modules/recruitment/mod_recruitmentcandidature_standard.php @@ -96,13 +96,13 @@ class mod_recruitmentcandidature_standard extends ModeleNumRefRecruitmentCandida } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $row = $db->fetch_row($resql); - if ($row) { $coyymm = substr($row[0], 0, 6); $max = $row[0]; } + if ($row) { + $coyymm = substr($row[0], 0, 6); $max = $row[0]; + } } - if ($coyymm && !preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) - { + if ($coyymm && !preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) { $langs->load("errors"); $this->error = $langs->trans('ErrorNumRefModel', $max); return false; @@ -133,11 +133,13 @@ class mod_recruitmentcandidature_standard extends ModeleNumRefRecruitmentCandida } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $max = intval($obj->max); - else $max = 0; + if ($obj) { + $max = intval($obj->max); + } else { + $max = 0; + } } else { dol_syslog("mod_recruitmentcandidature_standard::getNextValue", LOG_DEBUG); return -1; @@ -147,8 +149,11 @@ class mod_recruitmentcandidature_standard extends ModeleNumRefRecruitmentCandida $date = $object->date_creation; $yymm = strftime("%y%m", $date); - if ($max >= (pow(10, 4) - 1)) $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is - else $num = sprintf("%04s", $max + 1); + if ($max >= (pow(10, 4) - 1)) { + $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is + } else { + $num = sprintf("%04s", $max + 1); + } dol_syslog("mod_recruitmentcandidature_standard::getNextValue return ".$this->prefix.$yymm."-".$num); return $this->prefix.$yymm."-".$num; diff --git a/htdocs/recruitment/core/modules/recruitment/mod_recruitmentjobposition_advanced.php b/htdocs/recruitment/core/modules/recruitment/mod_recruitmentjobposition_advanced.php index a86337b288a..311eb7e1b36 100644 --- a/htdocs/recruitment/core/modules/recruitment/mod_recruitmentjobposition_advanced.php +++ b/htdocs/recruitment/core/modules/recruitment/mod_recruitmentjobposition_advanced.php @@ -113,8 +113,7 @@ class mod_recruitmentjobposition_advanced extends ModeleNumRefRecruitmentJobPosi /*$mysoc->code_client = $old_code_client; $mysoc->typent_code = $old_code_type;*/ - if (!$numExample) - { + if (!$numExample) { $numExample = $langs->trans('NotConfigured'); } return $numExample; @@ -135,8 +134,7 @@ class mod_recruitmentjobposition_advanced extends ModeleNumRefRecruitmentJobPosi // We get cursor rule $mask = $conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADVANCED_MASK; - if (!$mask) - { + if (!$mask) { $this->error = 'NotConfigured'; return 0; } diff --git a/htdocs/recruitment/core/modules/recruitment/mod_recruitmentjobposition_standard.php b/htdocs/recruitment/core/modules/recruitment/mod_recruitmentjobposition_standard.php index 4b3aba946bb..b2b413ee508 100644 --- a/htdocs/recruitment/core/modules/recruitment/mod_recruitmentjobposition_standard.php +++ b/htdocs/recruitment/core/modules/recruitment/mod_recruitmentjobposition_standard.php @@ -96,13 +96,13 @@ class mod_recruitmentjobposition_standard extends ModeleNumRefRecruitmentJobPosi } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $row = $db->fetch_row($resql); - if ($row) { $coyymm = substr($row[0], 0, 6); $max = $row[0]; } + if ($row) { + $coyymm = substr($row[0], 0, 6); $max = $row[0]; + } } - if ($coyymm && !preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) - { + if ($coyymm && !preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) { $langs->load("errors"); $this->error = $langs->trans('ErrorNumRefModel', $max); return false; @@ -133,11 +133,13 @@ class mod_recruitmentjobposition_standard extends ModeleNumRefRecruitmentJobPosi } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $max = intval($obj->max); - else $max = 0; + if ($obj) { + $max = intval($obj->max); + } else { + $max = 0; + } } else { dol_syslog("mod_recruitmentjobposition_standard::getNextValue", LOG_DEBUG); return -1; @@ -147,8 +149,11 @@ class mod_recruitmentjobposition_standard extends ModeleNumRefRecruitmentJobPosi $date = $object->date_creation; $yymm = strftime("%y%m", $date); - if ($max >= (pow(10, 4) - 1)) $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is - else $num = sprintf("%04s", $max + 1); + if ($max >= (pow(10, 4) - 1)) { + $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is + } else { + $num = sprintf("%04s", $max + 1); + } dol_syslog("mod_recruitmentjobposition_standard::getNextValue return ".$this->prefix.$yymm."-".$num); return $this->prefix.$yymm."-".$num; diff --git a/htdocs/recruitment/core/modules/recruitment/modules_recruitmentcandidature.php b/htdocs/recruitment/core/modules/recruitment/modules_recruitmentcandidature.php index a4ec3ac75b6..84bfd30401c 100644 --- a/htdocs/recruitment/core/modules/recruitment/modules_recruitmentcandidature.php +++ b/htdocs/recruitment/core/modules/recruitment/modules_recruitmentcandidature.php @@ -141,10 +141,18 @@ abstract class ModeleNumRefRecruitmentCandidature global $langs; $langs->load("admin"); - if ($this->version == 'development') return $langs->trans("VersionDevelopment"); - if ($this->version == 'experimental') return $langs->trans("VersionExperimental"); - if ($this->version == 'dolibarr') return DOL_VERSION; - if ($this->version) return $this->version; + if ($this->version == 'development') { + return $langs->trans("VersionDevelopment"); + } + if ($this->version == 'experimental') { + return $langs->trans("VersionExperimental"); + } + if ($this->version == 'dolibarr') { + return DOL_VERSION; + } + if ($this->version) { + return $this->version; + } return $langs->trans("NotAvailable"); } } diff --git a/htdocs/recruitment/core/modules/recruitment/modules_recruitmentjobposition.php b/htdocs/recruitment/core/modules/recruitment/modules_recruitmentjobposition.php index 482964764ef..dd9aa49ab10 100644 --- a/htdocs/recruitment/core/modules/recruitment/modules_recruitmentjobposition.php +++ b/htdocs/recruitment/core/modules/recruitment/modules_recruitmentjobposition.php @@ -141,10 +141,18 @@ abstract class ModeleNumRefRecruitmentJobPosition global $langs; $langs->load("admin"); - if ($this->version == 'development') return $langs->trans("VersionDevelopment"); - if ($this->version == 'experimental') return $langs->trans("VersionExperimental"); - if ($this->version == 'dolibarr') return DOL_VERSION; - if ($this->version) return $this->version; + if ($this->version == 'development') { + return $langs->trans("VersionDevelopment"); + } + if ($this->version == 'experimental') { + return $langs->trans("VersionExperimental"); + } + if ($this->version == 'dolibarr') { + return DOL_VERSION; + } + if ($this->version) { + return $this->version; + } return $langs->trans("NotAvailable"); } } diff --git a/htdocs/recruitment/index.html b/htdocs/recruitment/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/recruitment/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/recruitment/lib/index.html b/htdocs/recruitment/lib/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/recruitment/lib/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/recruitment/lib/recruitment_recruitmentcandidature.lib.php b/htdocs/recruitment/lib/recruitment_recruitmentcandidature.lib.php index 661f5ccc984..759e627bf59 100644 --- a/htdocs/recruitment/lib/recruitment_recruitmentcandidature.lib.php +++ b/htdocs/recruitment/lib/recruitment_recruitmentcandidature.lib.php @@ -48,14 +48,19 @@ function recruitmentCandidaturePrepareHead($object) $h++; } - if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) - { + if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = dol_buildpath('/recruitment/recruitmentcandidature_note.php', 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>'; + if ($nbNote > 0) { + $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>'; + } $head[$h][2] = 'note'; $h++; } @@ -67,7 +72,9 @@ function recruitmentCandidaturePrepareHead($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = dol_buildpath("/recruitment/recruitmentcandidature_document.php", 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; + } $head[$h][2] = 'document'; $h++; diff --git a/htdocs/recruitment/lib/recruitment_recruitmentjobposition.lib.php b/htdocs/recruitment/lib/recruitment_recruitmentjobposition.lib.php index dbf4ef5040c..2be1fea7756 100644 --- a/htdocs/recruitment/lib/recruitment_recruitmentjobposition.lib.php +++ b/htdocs/recruitment/lib/recruitment_recruitmentjobposition.lib.php @@ -48,14 +48,19 @@ function recruitmentjobpositionPrepareHead($object) $h++; } - if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) - { + if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = dol_buildpath('/recruitment/recruitmentjobposition_note.php', 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>'; + if ($nbNote > 0) { + $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>'; + } $head[$h][2] = 'note'; $h++; } @@ -67,7 +72,9 @@ function recruitmentjobpositionPrepareHead($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = dol_buildpath("/recruitment/recruitmentjobposition_document.php", 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; + } $head[$h][2] = 'document'; $h++; @@ -113,7 +120,9 @@ function getPublicJobPositionUrl($mode, $ref = '', $localorexternal = 0) //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current $urltouse = DOL_MAIN_URL_ROOT; - if ($localorexternal) $urltouse = $urlwithroot; + if ($localorexternal) { + $urltouse = $urlwithroot; + } $out = $urltouse.'/public/recruitment/view.php?ref='.($mode ? '<font color="#666666">' : '').$ref.($mode ? '</font>' : ''); /*if (!empty($conf->global->RECRUITMENT_SECURITY_TOKEN)) @@ -123,7 +132,9 @@ function getPublicJobPositionUrl($mode, $ref = '', $localorexternal = 0) }*/ // For multicompany - if (!empty($out) && !empty($conf->multicompany->enabled)) $out .= "&entity=".$conf->entity; // Check the entity because we may have the same reference in several entities + if (!empty($out) && !empty($conf->multicompany->enabled)) { + $out .= "&entity=".$conf->entity; // Check the entity because we may have the same reference in several entities + } return $out; } diff --git a/htdocs/recruitment/recruitmentcandidature_agenda.php b/htdocs/recruitment/recruitmentcandidature_agenda.php index c125a14c647..2930b3889c6 100644 --- a/htdocs/recruitment/recruitmentcandidature_agenda.php +++ b/htdocs/recruitment/recruitmentcandidature_agenda.php @@ -25,17 +25,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -56,7 +72,9 @@ $backtopage = GETPOST('backtopage', 'alpha'); 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)); } @@ -66,12 +84,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 (!$sortfield) $sortfield = 'a.datep,a.id'; -if (!$sortorder) $sortorder = 'DESC,DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC'; +} // Initialize technical objects $object = new RecruitmentCandidature($db); @@ -83,7 +107,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->recruitment->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->recruitment->multidir_output[$object->entity]."/".$object->id; +} // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); @@ -99,20 +125,19 @@ $permissiontoadd = $user->rights->recruitment->recruitmentjobposition->write; // $parameters = array('id'=>$id); $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 (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // 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 $actioncode = ''; $search_agenda_label = ''; } @@ -126,14 +151,15 @@ if (empty($reshook)) $form = new Form($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $title = $langs->trans("Agenda"); //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; $help_url = ''; llxHeader('', $title, $help_url); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = recruitmentCandidaturePrepareHead($object); @@ -206,10 +232,11 @@ if ($object->id > 0) $out = '&origin='.$object->element.'@recruitment&originid='.$object->id; $permok = $user->rights->agenda->myactions->create; - if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) - { + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { //$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'; - if (get_class($objthirdparty) == 'Societe') $out .= '&amp;socid='.$objthirdparty->id; + if (get_class($objthirdparty) == 'Societe') { + $out .= '&amp;socid='.$objthirdparty->id; + } $out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1'; //$out.=$langs->trans("AddAnAction").' '; //$out.=img_picto($langs->trans("AddAnAction"),'filenew'); @@ -219,10 +246,8 @@ if ($object->id > 0) print '<div class="tabsAction">'; - if (!empty($conf->agenda->enabled)) - { - if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) - { + if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'">'.$langs->trans("AddAction").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>'; @@ -231,11 +256,14 @@ if ($object->id > 0) print '</div>'; - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $param = '&id='.$object->id.'&socid='.$socid; - 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); + } //print load_fiche_titre($langs->trans("ActionsOnRecruitmentJobPosition"), '', ''); diff --git a/htdocs/recruitment/recruitmentcandidature_card.php b/htdocs/recruitment/recruitmentcandidature_card.php index 0a0cf4c061d..653b38c90b3 100644 --- a/htdocs/recruitment/recruitmentcandidature_card.php +++ b/htdocs/recruitment/recruitmentcandidature_card.php @@ -44,17 +44,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; @@ -92,12 +108,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. @@ -125,18 +144,22 @@ $upload_dir = $conf->recruitment->multidir_output[isset($object->entity) ? $obje $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 (empty($reshook)) { $error = 0; $backurlforlist = dol_buildpath('/recruitment/recruitmentcandidature_list.php', 1); if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = dol_buildpath('/recruitment/recruitmentcandidature_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('/recruitment/recruitmentcandidature_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + } } } $triggermodname = 'RECRUITMENTCANDIDATURE_MODIFY'; // Name of trigger action code to execute when we modify record @@ -156,8 +179,7 @@ if (empty($reshook)) // Action to build doc include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - if ($action == 'classin' && $permissiontoadd) - { + if ($action == 'classin' && $permissiontoadd) { $object->setProject(GETPOST('projectid', 'int')); } if ($action == 'confirm_decline' && $confirm == 'yes' && $permissiontoadd) { @@ -173,8 +195,7 @@ if (empty($reshook)) $action = 'makeofferordecline'; } else { // prevent browser refresh from closing proposal several times - if ($object->status == $object::STATUS_VALIDATED) - { + if ($object->status == $object::STATUS_VALIDATED) { $db->begin(); if (GETPOST('status', 'int') == $object::STATUS_REFUSED) { @@ -189,8 +210,7 @@ if (empty($reshook)) } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -205,8 +225,7 @@ if (empty($reshook)) $action = 'makeofferordecline'; } else { // prevent browser refresh from closing proposal several times - if ($object->status == $object::STATUS_CONTRACT_PROPOSED) - { + if ($object->status == $object::STATUS_CONTRACT_PROPOSED) { $db->begin(); if (GETPOST('status', 'int') == $object::STATUS_CONTRACT_REFUSED) { @@ -221,8 +240,7 @@ if (empty($reshook)) } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -306,15 +324,18 @@ jQuery(document).ready(function() { // Part to create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("RecruitmentCandidature")), '', 'object_'.$object->picto); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } print dol_get_fiche_head(array(), ''); @@ -345,16 +366,19 @@ if ($action == 'create') } // Part to edit record -if (($id || $ref) && $action == 'edit') -{ +if (($id || $ref) && $action == 'edit') { print load_fiche_titre($langs->trans("RecruitmentCandidature"), '', 'object_'.$object->picto); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } print dol_get_fiche_head(); @@ -378,8 +402,7 @@ if (($id || $ref) && $action == 'edit') } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_optionals(); $head = recruitmentcandidaturePrepareHead($object); @@ -402,8 +425,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneAsk', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } - if ($action == 'makeofferordecline') - { + if ($action == 'makeofferordecline') { $langs->load("propal"); //Form to close proposal (signed or not) @@ -417,8 +439,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('SetAcceptedRefused'), $text, 'confirm_makeofferordecline', $formquestion, '', 1, 250); } - if ($action == 'closeas') - { + if ($action == 'closeas') { $langs->load("propal"); //Form to close proposal (signed or not) @@ -440,7 +461,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea 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( @@ -453,8 +476,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -534,8 +560,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea * Lines */ - if (!empty($object->table_element_line)) - { + if (!empty($object->table_element_line)) { // Show object lines $result = $object->getLinesArray(); @@ -551,21 +576,17 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } print '<div class="div-table-responsive-no-min">'; - if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) - { + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { print '<table id="tablelines" class="noborder noshadow" width="100%">'; } - if (!empty($object->lines)) - { + if (!empty($object->lines)) { $object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1); } // Form to add new line - if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') - { - if ($action != 'editline') - { + if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') { + if ($action != 'editline') { // Add products/services form $object->formAddObjectLine(1, $mysoc, $soc); @@ -574,8 +595,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } - if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) - { + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { print '</table>'; } print '</div>'; @@ -590,39 +610,34 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<div class="tabsAction">'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Send if (empty($user->socid)) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init&sendto='.urlencode($object->email).'#formmailbeforetitle">'.$langs->trans('SendMail').'</a>'."\n"; } // Back to draft - if ($object->status == $object::STATUS_VALIDATED) - { - if ($permissiontoadd) - { + if ($object->status == $object::STATUS_VALIDATED) { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes">'.$langs->trans("SetToDraft").'</a>'; } } // Modify - if ($permissiontoadd) - { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit">'.$langs->trans("Modify").'</a>'."\n"; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n"; } // Validate - if ($object->status == $object::STATUS_DRAFT) - { - if ($permissiontoadd) - { - if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) - { + if ($object->status == $object::STATUS_DRAFT) { + if ($permissiontoadd) { + if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes">'.$langs->trans("Validate").'</a>'; } else { $langs->load("errors"); @@ -632,32 +647,26 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Make offer - Refuse - Decline - if ($object->status >= $object::STATUS_VALIDATED && $object->status < $object::STATUS_CONTRACT_PROPOSED) - { - if ($permissiontoadd) - { + if ($object->status >= $object::STATUS_VALIDATED && $object->status < $object::STATUS_CONTRACT_PROPOSED) { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=makeofferordecline">'.$langs->trans("MakeOffer").' / '.$langs->trans("Decline").'</a>'; } } // Contract refused / accepted - if ($object->status == $object::STATUS_CONTRACT_PROPOSED) - { - if ($permissiontoadd) - { + if ($object->status == $object::STATUS_CONTRACT_PROPOSED) { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=closeas">'.$langs->trans("Accept").' / '.$langs->trans("Decline").'</a>'; } } // Clone - if ($permissiontoadd) - { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->socid.'&action=clone&object=recruitmentcandidature">'.$langs->trans("ToClone").'</a>'."\n"; } // Button to convert into a user - if ($object->status == $object::STATUS_CONTRACT_SIGNED) - { + if ($object->status == $object::STATUS_CONTRACT_SIGNED) { if ($user->rights->user->user->creer) { // TODO Check if a user already exists $useralreadyexists = 0; @@ -672,21 +681,16 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Cancel - if ($permissiontoadd) - { - if ($object->status == $object::STATUS_VALIDATED) - { + if ($permissiontoadd) { + if ($object->status == $object::STATUS_VALIDATED) { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=close">'.$langs->trans("Cancel").'</a>'."\n"; - } - elseif ($object->status == $object::STATUS_REFUSED || $object->status == $object::STATUS_CANCELED || $object->status == $object::STATUS_CONTRACT_REFUSED) - { + } elseif ($object->status == $object::STATUS_REFUSED || $object->status == $object::STATUS_CANCELED || $object->status == $object::STATUS_CONTRACT_REFUSED) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes&token='.newToken().'">'.$langs->trans("Re-Open").'</a>'."\n"; } } // Delete (need delete permission, or if draft, just need create/modify permission) - if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) - { + if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n"; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n"; @@ -701,8 +705,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre @@ -741,7 +744,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } //Select mail models is same action as presend - if (GETPOST('modelselected')) $action = 'presend'; + if (GETPOST('modelselected')) { + $action = 'presend'; + } // Presend form $modelmail = 'recruitmentcandidature_send'; diff --git a/htdocs/recruitment/recruitmentcandidature_document.php b/htdocs/recruitment/recruitmentcandidature_document.php index 1c801f27fd4..ee79a4c59a5 100644 --- a/htdocs/recruitment/recruitmentcandidature_document.php +++ b/htdocs/recruitment/recruitmentcandidature_document.php @@ -25,17 +25,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -58,12 +74,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 = $liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} //if (! $sortfield) $sortfield="position_name"; // Initialize technical objects @@ -77,7 +99,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->recruitment->multidir_output[$object->entity ? $object->entity : $conf->entity]."/recruitmentcandidature/".get_exdir(0, 0, 0, 1, $object); +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->recruitment->multidir_output[$object->entity ? $object->entity : $conf->entity]."/recruitmentcandidature/".get_exdir(0, 0, 0, 1, $object); +} // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); @@ -92,7 +116,7 @@ $permissiontoadd = $user->rights->recruitment->recruitmentjobposition->write; // * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -106,8 +130,7 @@ $help_url = ''; //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($object->id) -{ +if ($object->id) { /* * Show tabs */ @@ -119,8 +142,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/recruitment/recruitmentcandidature_list.php b/htdocs/recruitment/recruitmentcandidature_list.php index 70d3bc3be4d..05f007fcb1a 100644 --- a/htdocs/recruitment/recruitmentcandidature_list.php +++ b/htdocs/recruitment/recruitmentcandidature_list.php @@ -44,17 +44,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; @@ -86,7 +102,9 @@ $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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -104,28 +122,33 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Initialize array of search criterias $search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of fields for list $arrayfields = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field if (!empty($val['visible'])) { $visible = dol_eval($val['visible'], 1); @@ -138,10 +161,8 @@ foreach ($object->fields as $key => $val) } } // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], @@ -160,10 +181,11 @@ $permissiontoadd = $user->rights->recruitment->recruitmentjobposition->write; $permissiontodelete = $user->rights->recruitment->recruitmentjobposition->delete; // Security check -if (empty($conf->recruitment->enabled)) accessforbidden('Module not enabled'); +if (empty($conf->recruitment->enabled)) { + accessforbidden('Module not enabled'); +} $socid = 0; -if ($user->socid > 0) // Protection if external user -{ +if ($user->socid > 0) { // Protection if external user //$socid = $user->socid; accessforbidden(); } @@ -176,31 +198,33 @@ if ($user->socid > 0) // Protection if external user * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($object->fields as $key => $val) - { + 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 + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $toselect = ''; $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -229,13 +253,14 @@ $title = $langs->trans('ListOfCandidatures'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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.', ' : ''); + 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(); @@ -243,20 +268,32 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -else $sql .= " WHERE 1 = 1"; -foreach ($search as $key => $val) -{ - if ($key == 'status' && $search[$key] == -1) continue; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); if (strpos($object->fields[$key]['type'], 'integer:') === 0) { - if ($search[$key] == '-1') $search[$key] = ''; + if ($search[$key] == '-1') { + $search[$key] = ''; + } $mode_search = 2; } - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -286,26 +323,24 @@ $sql .= $db->order($sortfield, $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 || empty($limit))) -{ +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -314,8 +349,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".dol_buildpath('/recruitment/recruitmentcandidature_card.php', 1).'?id='.$id); @@ -346,14 +380,24 @@ jQuery(document).ready(function() { $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ - if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); - else $param .= '&search_'.$key.'='.urlencode($search[$key]); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +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'; @@ -364,12 +408,18 @@ $arrayofmassactions = array( //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); -if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($permissiontodelete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -389,9 +439,10 @@ $objecttmp = new RecruitmentCandidature($db); $trackid = 'xxxx'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } @@ -402,11 +453,13 @@ $moreforfilter.= '</div>';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -423,20 +476,26 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit // Fields title search // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - elseif (strpos($val['type'], 'integer:') === 0) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { + print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } print '</td>'; } } @@ -458,15 +517,18 @@ print '</tr>'."\n"; // Fields title label // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -483,11 +545,11 @@ print '</tr>'."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -496,38 +558,51 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->setVarsFromFetchObj($obj); // Show here line of result print '<tr class="oddeven">'; - foreach ($object->fields as $key => $val) - { + foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>'; - if ($key == 'status') print $object->getLibStatut(5); - else print $object->showOutputField($val, $key, $object->$key, ''); + if ($key == 'status') { + print $object->getLibStatut(5); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $object->$key; } } @@ -540,14 +615,17 @@ while ($i < ($limit ? min($num, $limit) : $num)) print $hookmanager->resPrint; // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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($object->id, $arrayofselected)) $selected = 1; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'."\n"; @@ -558,10 +636,13 @@ while ($i < ($limit ? min($num, $limit) : $num)) include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } @@ -577,10 +658,11 @@ print '</div>'."\n"; print '</form>'."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/recruitment/recruitmentcandidature_note.php b/htdocs/recruitment/recruitmentcandidature_note.php index c0673b35c52..9dbe3909f2c 100644 --- a/htdocs/recruitment/recruitmentcandidature_note.php +++ b/htdocs/recruitment/recruitmentcandidature_note.php @@ -25,17 +25,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} dol_include_once('/recruitment/class/recruitmentcandidature.class.php'); dol_include_once('/recruitment/lib/recruitment_recruitmentcandidature.lib.php'); @@ -65,7 +81,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->recruitment->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->recruitment->multidir_output[$object->entity]."/".$object->id; +} $permissionnote = $user->rights->recruitment->recruitmentjobposition->write; // Used by the include of actions_setnotes.inc.php $permissiontoadd = $user->rights->recruitment->recruitmentjobposition->write; // Used by the include of actions_addupdatedelete.inc.php @@ -89,8 +107,7 @@ $form = new Form($db); $help_url = ''; llxHeader('', $langs->trans('RecruitmentCandidature'), $help_url); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = recruitmentCandidaturePrepareHead($object); diff --git a/htdocs/recruitment/recruitmentindex.php b/htdocs/recruitment/recruitmentindex.php index a8649abbd21..844cd8a221a 100644 --- a/htdocs/recruitment/recruitmentindex.php +++ b/htdocs/recruitment/recruitmentindex.php @@ -38,8 +38,7 @@ $action = GETPOST('action', 'aZ09'); // Security check //if (! $user->rights->recruitment->myobject->read) accessforbidden(); $socid = GETPOST('socid', 'int'); -if (isset($user->socid) && $user->socid > 0) -{ +if (isset($user->socid) && $user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -75,16 +74,14 @@ print '<div class="fichecenter"><div class="fichethirdleft">'; * Statistics */ -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { $sql = "SELECT COUNT(t.rowid) as nb, status"; $sql .= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as t"; $sql .= " GROUP BY t.status"; $sql .= " ORDER BY t.status ASC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -95,11 +92,9 @@ if ($conf->use_javascript_ajax) include_once DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $vals[$obj->status] = $obj->nb; $totalnb += $obj->nb; @@ -112,24 +107,29 @@ if ($conf->use_javascript_ajax) print '<table class="noborder nohover centpercent">'; print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("JobPositions").'</th></tr>'."\n"; $listofstatus = array(0, 1, 3, 9); - foreach ($listofstatus as $status) - { + foreach ($listofstatus as $status) { $dataseries[] = array(dol_html_entity_decode($staticrecruitmentjobposition->LibStatut($status, 1), ENT_QUOTES | ENT_HTML5), (isset($vals[$status]) ? (int) $vals[$status] : 0)); - if ($status == RecruitmentJobPosition::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; - if ($status == RecruitmentJobPosition::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus4; - if ($status == RecruitmentJobPosition::STATUS_RECRUITED) $colorseries[$status] = $badgeStatus6; - if ($status == RecruitmentJobPosition::STATUS_CANCELED) $colorseries[$status] = $badgeStatus9; + if ($status == RecruitmentJobPosition::STATUS_DRAFT) { + $colorseries[$status] = '-'.$badgeStatus0; + } + if ($status == RecruitmentJobPosition::STATUS_VALIDATED) { + $colorseries[$status] = $badgeStatus4; + } + if ($status == RecruitmentJobPosition::STATUS_RECRUITED) { + $colorseries[$status] = $badgeStatus6; + } + if ($status == RecruitmentJobPosition::STATUS_CANCELED) { + $colorseries[$status] = $badgeStatus9; + } - if (empty($conf->use_javascript_ajax)) - { + if (empty($conf->use_javascript_ajax)) { print '<tr class="oddeven">'; print '<td>'.$staticrecruitmentjobposition->LibStatut($status, 0).'</td>'; print '<td class="right"><a href="list.php?statut='.$status.'">'.(isset($vals[$status]) ? $vals[$status] : 0).'</a></td>'; print "</tr>\n"; } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<tr><td class="center" colspan="2">'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -159,8 +159,7 @@ if ($conf->use_javascript_ajax) $sql .= " ORDER BY t.status ASC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -171,11 +170,9 @@ if ($conf->use_javascript_ajax) include_once DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $vals[$obj->status] = $obj->nb; $totalnb += $obj->nb; @@ -188,26 +185,35 @@ if ($conf->use_javascript_ajax) print '<table class="noborder nohover centpercent">'; print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("Candidatures").'</th></tr>'."\n"; $listofstatus = array(0, 1, 3, 5, 8, 9); - foreach ($listofstatus as $status) - { + foreach ($listofstatus as $status) { $dataseries[] = array(dol_html_entity_decode($staticrecruitmentcandidature->LibStatut($status, 1), ENT_QUOTES | ENT_HTML5), (isset($vals[$status]) ? (int) $vals[$status] : 0)); - if ($status == RecruitmentCandidature::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; - if ($status == RecruitmentCandidature::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus1; - if ($status == RecruitmentCandidature::STATUS_CONTRACT_PROPOSED) $colorseries[$status] = $badgeStatus4; - if ($status == RecruitmentCandidature::STATUS_CONTRACT_SIGNED) $colorseries[$status] = $badgeStatus5; - if ($status == RecruitmentCandidature::STATUS_REFUSED) $colorseries[$status] = $badgeStatus9; - if ($status == RecruitmentCandidature::STATUS_CANCELED) $colorseries[$status] = $badgeStatus9; + if ($status == RecruitmentCandidature::STATUS_DRAFT) { + $colorseries[$status] = '-'.$badgeStatus0; + } + if ($status == RecruitmentCandidature::STATUS_VALIDATED) { + $colorseries[$status] = $badgeStatus1; + } + if ($status == RecruitmentCandidature::STATUS_CONTRACT_PROPOSED) { + $colorseries[$status] = $badgeStatus4; + } + if ($status == RecruitmentCandidature::STATUS_CONTRACT_SIGNED) { + $colorseries[$status] = $badgeStatus5; + } + if ($status == RecruitmentCandidature::STATUS_REFUSED) { + $colorseries[$status] = $badgeStatus9; + } + if ($status == RecruitmentCandidature::STATUS_CANCELED) { + $colorseries[$status] = $badgeStatus9; + } - if (empty($conf->use_javascript_ajax)) - { + if (empty($conf->use_javascript_ajax)) { print '<tr class="oddeven">'; print '<td>'.$staticrecruitmentcandidature->LibStatut($status, 0).'</td>'; print '<td class="right"><a href="list.php?statut='.$status.'">'.(isset($vals[$status]) ? $vals[$status] : 0).'</a></td>'; print "</tr>\n"; } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<tr><td class="center" colspan="2">'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -321,22 +327,26 @@ $NBMAX = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; $max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; // Last modified job position -if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read) -{ +if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read) { $sql = "SELECT s.rowid, s.ref, s.label, s.date_creation, s.tms, s.status, COUNT(rc.rowid) as nbapplications"; $sql .= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as s"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature as rc ON rc.fk_recruitmentjobposition = s.rowid"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE s.entity IN (".getEntity($staticrecruitmentjobposition->element).")"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.fk_soc = $socid"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.fk_soc = $socid"; + } $sql .= " GROUP BY s.rowid, s.ref, s.label, s.date_creation, s.tms, s.status"; $sql .= " ORDER BY s.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -351,10 +361,8 @@ if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitme print '</th>'; print '<th class="right" colspan="2"><a href="'.DOL_URL_ROOT.'/recruitment/recruitmentjobposition_list.php?sortfield=t.tms&sortorder=DESC">'.$langs->trans("FullList").'</th>'; print '</tr>'; - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $objp = $db->fetch_object($resql); $staticrecruitmentjobposition->id = $objp->rowid; $staticrecruitmentjobposition->ref = $objp->ref; @@ -390,21 +398,25 @@ if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitme } // Last modified job position -if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read) -{ +if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read) { $sql = "SELECT rc.rowid, rc.ref, rc.email, rc.lastname, rc.firstname, rc.date_creation, rc.tms, rc.status"; $sql .= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature as rc"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as s ON rc.fk_recruitmentjobposition = s.rowid"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE rc.entity IN (".getEntity($staticrecruitmentjobposition->element).")"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.fk_soc = $socid"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.fk_soc = $socid"; + } $sql .= " ORDER BY rc.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -416,10 +428,8 @@ if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitme print '</th>'; print '<th class="right" colspan="2"><a href="'.DOL_URL_ROOT.'/recruitment/recruitmentcandidature_list.php?sortfield=t.tms&sortorder=DESC">'.$langs->trans("FullList").'</th>'; print '</tr>'; - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $objp = $db->fetch_object($resql); $staticrecruitmentcandidature->id = $objp->rowid; $staticrecruitmentcandidature->ref = $objp->ref; diff --git a/htdocs/recruitment/recruitmentjobposition_agenda.php b/htdocs/recruitment/recruitmentjobposition_agenda.php index 97ea279e8ae..388d4e8eadc 100644 --- a/htdocs/recruitment/recruitmentjobposition_agenda.php +++ b/htdocs/recruitment/recruitmentjobposition_agenda.php @@ -25,17 +25,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -56,7 +72,9 @@ $backtopage = GETPOST('backtopage', 'alpha'); 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)); } @@ -66,12 +84,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 (!$sortfield) $sortfield = 'a.datep,a.id'; -if (!$sortorder) $sortorder = 'DESC,DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC'; +} // Initialize technical objects $object = new RecruitmentJobPosition($db); @@ -83,7 +107,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->recruitment->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->recruitment->multidir_output[$object->entity]."/".$object->id; +} // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); @@ -99,20 +125,19 @@ $permissiontoadd = $user->rights->recruitment->recruitmentjobposition->write; // $parameters = array('id'=>$id); $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 (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // 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 $actioncode = ''; $search_agenda_label = ''; } @@ -126,14 +151,15 @@ if (empty($reshook)) $form = new Form($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $title = $langs->trans("Agenda"); //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; $help_url = ''; llxHeader('', $title, $help_url); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = recruitmentjobpositionPrepareHead($object); @@ -152,15 +178,14 @@ if ($object->id > 0) $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); */ // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= $langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') + if ($permissiontoadd) { + if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; - $morehtmlref .= ' : '; + $morehtmlref .= ' : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; @@ -206,10 +231,11 @@ if ($object->id > 0) $out = '&origin='.$object->element.'@recruitment&originid='.$object->id; $permok = $user->rights->agenda->myactions->create; - if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) - { + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { //$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'; - if (get_class($objthirdparty) == 'Societe') $out .= '&amp;socid='.$objthirdparty->id; + if (get_class($objthirdparty) == 'Societe') { + $out .= '&amp;socid='.$objthirdparty->id; + } $out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1'; //$out.=$langs->trans("AddAnAction").' '; //$out.=img_picto($langs->trans("AddAnAction"),'filenew'); @@ -219,10 +245,8 @@ if ($object->id > 0) print '<div class="tabsAction">'; - if (!empty($conf->agenda->enabled)) - { - if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) - { + if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'">'.$langs->trans("AddAction").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>'; @@ -231,11 +255,14 @@ if ($object->id > 0) print '</div>'; - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $param = '&id='.$object->id.'&socid='.$socid; - 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); + } //print load_fiche_titre($langs->trans("ActionsOnRecruitmentJobPosition"), '', ''); diff --git a/htdocs/recruitment/recruitmentjobposition_applications.php b/htdocs/recruitment/recruitmentjobposition_applications.php index ef151beb8d5..c126c594c3a 100644 --- a/htdocs/recruitment/recruitmentjobposition_applications.php +++ b/htdocs/recruitment/recruitmentjobposition_applications.php @@ -44,17 +44,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; @@ -91,12 +107,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. @@ -124,18 +143,22 @@ $upload_dir = $conf->recruitment->multidir_output[isset($object->entity) ? $obje $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 (empty($reshook)) { $error = 0; $backurlforlist = dol_buildpath('/recruitment/recruitmentjobposition_list.php', 1); if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = dol_buildpath('/recruitment/recruitmentjobposition_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('/recruitment/recruitmentjobposition_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + } } } $triggermodname = 'RECRUITMENT_RECRUITMENTJOBPOSITION_MODIFY'; // Name of trigger action code to execute when we modify record @@ -155,12 +178,10 @@ if (empty($reshook)) // Action to build doc include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - if ($action == 'set_thirdparty' && $permissiontoadd) - { + if ($action == 'set_thirdparty' && $permissiontoadd) { $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'RECRUITMENTJOBPOSITION_MODIFY'); } - if ($action == 'classin' && $permissiontoadd) - { + if ($action == 'classin' && $permissiontoadd) { $object->setProject(GETPOST('projectid', 'int')); } @@ -189,18 +210,23 @@ $help_url = ''; llxHeader('', $title, $help_url); // Part to create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewPositionToBeFilled"), '', 'object_'.$object->picto); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } // Set some default values - if (!GETPOSTISSET('fk_user_recruiter')) $_POST['fk_user_recruiter'] = $user->id; + if (!GETPOSTISSET('fk_user_recruiter')) { + $_POST['fk_user_recruiter'] = $user->id; + } print dol_get_fiche_head(array(), ''); @@ -228,16 +254,19 @@ if ($action == 'create') } // Part to edit record -if (($id || $ref) && $action == 'edit') -{ +if (($id || $ref) && $action == 'edit') { print load_fiche_titre($langs->trans("PositionToBeFilled"), '', 'object_'.$object->picto); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } print dol_get_fiche_head(); @@ -261,8 +290,7 @@ if (($id || $ref) && $action == 'edit') } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_optionals(); $head = recruitmentjobpositionPrepareHead($object); @@ -271,13 +299,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $formconfirm = ''; // Confirmation to delete - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteRecruitmentJobPosition'), $langs->trans('ConfirmDeleteObject'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line - if ($action == 'deleteline') - { + if ($action == 'deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); } // Clone confirmation @@ -288,8 +314,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Confirmation of action xxxx - if ($action == 'xxx') - { + if ($action == 'xxx') { $formquestion = array(); /* $forcecombo=0; @@ -307,8 +332,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -327,13 +355,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); */ // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= $langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a>'; + if ($permissiontoadd) { + if ($action != 'classify') { + $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a>'; + } $morehtmlref .= ' : '; if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); @@ -389,8 +417,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea * Lines */ - if (!empty($object->table_element_line)) - { + if (!empty($object->table_element_line)) { // Show object lines $result = $object->getLinesArray(); @@ -406,21 +433,17 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } print '<div class="div-table-responsive-no-min">'; - if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) - { + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { print '<table id="tablelines" class="noborder noshadow" width="100%">'; } - if (!empty($object->lines)) - { + if (!empty($object->lines)) { $object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1); } // Form to add new line - if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') - { - if ($action != 'editline') - { + if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') { + if ($action != 'editline') { // Add products/services form $object->formAddObjectLine(1, $mysoc, $soc); @@ -429,8 +452,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } - if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) - { + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { print '</table>'; } print '</div>'; diff --git a/htdocs/recruitment/recruitmentjobposition_card.php b/htdocs/recruitment/recruitmentjobposition_card.php index 78736eed3ae..26d1578b24c 100644 --- a/htdocs/recruitment/recruitmentjobposition_card.php +++ b/htdocs/recruitment/recruitmentjobposition_card.php @@ -44,17 +44,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; @@ -91,12 +107,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. @@ -126,18 +145,22 @@ $usercanclose = $permissiontoadd; $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 (empty($reshook)) { $error = 0; $backurlforlist = dol_buildpath('/recruitment/recruitmentjobposition_list.php', 1); if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = dol_buildpath('/recruitment/recruitmentjobposition_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('/recruitment/recruitmentjobposition_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + } } } $triggermodname = 'RECRUITMENT_RECRUITMENTJOBPOSITION_MODIFY'; // Name of trigger action code to execute when we modify record @@ -157,12 +180,10 @@ if (empty($reshook)) // Action to build doc include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - if ($action == 'set_thirdparty' && $permissiontoadd) - { + if ($action == 'set_thirdparty' && $permissiontoadd) { $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'RECRUITMENTJOBPOSITION_MODIFY'); } - if ($action == 'classin' && $permissiontoadd) - { + if ($action == 'classin' && $permissiontoadd) { $object->setProject(GETPOST('projectid', 'int')); } if ($action == 'confirm_closeas' && $usercanclose && !GETPOST('cancel', 'alpha')) { @@ -171,19 +192,16 @@ if (empty($reshook)) $action = 'closeas'; } else { // prevent browser refresh from closing proposal several times - if ($object->status == $object::STATUS_VALIDATED) - { + if ($object->status == $object::STATUS_VALIDATED) { $db->begin(); $result = $object->cloture($user, GETPOST('status', 'int'), GETPOST('note_private', 'restricthtml')); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -217,18 +235,23 @@ $help_url = ''; llxHeader('', $title, $help_url); // Part to create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewPositionToBeFilled"), '', 'object_'.$object->picto); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } // Set some default values - if (!GETPOSTISSET('fk_user_recruiter')) $_POST['fk_user_recruiter'] = $user->id; + if (!GETPOSTISSET('fk_user_recruiter')) { + $_POST['fk_user_recruiter'] = $user->id; + } print dol_get_fiche_head(array(), ''); @@ -256,16 +279,19 @@ if ($action == 'create') } // Part to edit record -if (($id || $ref) && $action == 'edit') -{ +if (($id || $ref) && $action == 'edit') { print load_fiche_titre($langs->trans("PositionToBeFilled"), '', 'object_'.$object->picto); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } print dol_get_fiche_head(); @@ -289,8 +315,7 @@ if (($id || $ref) && $action == 'edit') } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_optionals(); $head = recruitmentjobpositionPrepareHead($object); @@ -299,13 +324,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $formconfirm = ''; // Confirmation to delete - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteRecruitmentJobPosition'), $langs->trans('ConfirmDeleteObject'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line - if ($action == 'deleteline') - { + if ($action == 'deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); } // Clone confirmation @@ -314,8 +337,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $formquestion = array(); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneAsk', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } - if ($action == 'closeas') - { + if ($action == 'closeas') { //Form to close proposal (signed or not) $formquestion = array( array('type' => 'select', 'name' => 'status', 'label' => '<span class="fieldrequired">'.$langs->trans("CloseAs").'</span>', 'values' => array(3=>$object->LibStatut($object::STATUS_RECRUITED), 9=>$object->LibStatut($object::STATUS_CANCELED))), @@ -337,8 +359,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -357,13 +382,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); */ // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= $langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a>'; + if ($permissiontoadd) { + if ($action != 'classify') { + $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a>'; + } $morehtmlref .= ' : '; if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); @@ -419,8 +444,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea * Lines */ - if (!empty($object->table_element_line)) - { + if (!empty($object->table_element_line)) { // Show object lines $result = $object->getLinesArray(); @@ -436,21 +460,17 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } print '<div class="div-table-responsive-no-min">'; - if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) - { + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { print '<table id="tablelines" class="noborder noshadow" width="100%">'; } - if (!empty($object->lines)) - { + if (!empty($object->lines)) { $object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1); } // Form to add new line - if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') - { - if ($action != 'editline') - { + if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') { + if ($action != 'editline') { // Add products/services form $object->formAddObjectLine(1, $mysoc, $soc); @@ -459,8 +479,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } - if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) - { + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { print '</table>'; } print '</div>'; @@ -475,10 +494,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<div class="tabsAction">'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Send if (empty($user->socid)) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>'."\n"; @@ -486,8 +506,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Back to draft if ($object->status == $object::STATUS_VALIDATED) { - if ($permissiontoadd) - { + if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes">'.$langs->trans("SetToDraft").'</a>'; } } @@ -502,8 +521,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Validate if ($object->status == $object::STATUS_DRAFT) { if ($permissiontoadd) { - if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) - { + if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes">'.$langs->trans("Validate").'</a>'; } else { $langs->load("errors"); @@ -535,8 +553,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=enable">'.$langs->trans("Enable").'</a>'."\n"; } }*/ - if ($permissiontoadd) - { + if ($permissiontoadd) { if ($object->status == $object::STATUS_CANCELED) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes">'.$langs->trans("Re-Open").'</a>'."\n"; } @@ -558,8 +575,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre @@ -581,8 +597,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); // Show link to public job page - if ($object->status != RecruitmentJobPosition::STATUS_DRAFT) - { + if ($object->status != RecruitmentJobPosition::STATUS_DRAFT) { print '<br><!-- Link to go on public job page -->'."\n"; // Load translation files required by the page $langs->loadLangs(array('recruitment')); @@ -614,7 +629,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } //Select mail models is same action as presend - if (GETPOST('modelselected')) $action = 'presend'; + if (GETPOST('modelselected')) { + $action = 'presend'; + } // Presend form $modelmail = 'recruitmentjobposition'; diff --git a/htdocs/recruitment/recruitmentjobposition_document.php b/htdocs/recruitment/recruitmentjobposition_document.php index 3005b4cc1be..9a3339b5130 100644 --- a/htdocs/recruitment/recruitmentjobposition_document.php +++ b/htdocs/recruitment/recruitmentjobposition_document.php @@ -25,17 +25,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -58,12 +74,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 = $liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} //if (! $sortfield) $sortfield="position_name"; // Initialize technical objects @@ -77,7 +99,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->recruitment->multidir_output[$object->entity ? $object->entity : $conf->entity]."/recruitmentjobposition/".get_exdir(0, 0, 0, 1, $object); +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->recruitment->multidir_output[$object->entity ? $object->entity : $conf->entity]."/recruitmentjobposition/".get_exdir(0, 0, 0, 1, $object); +} // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); @@ -92,7 +116,7 @@ $permissiontoadd = $user->rights->recruitment->recruitmentjobposition->write; // * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -106,8 +130,7 @@ $help_url = ''; //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($object->id) -{ +if ($object->id) { /* * Show tabs */ @@ -119,8 +142,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -137,15 +159,14 @@ if ($object->id) $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); */ // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= $langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') + if ($permissiontoadd) { + if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; - $morehtmlref .= ' : '; + $morehtmlref .= ' : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; diff --git a/htdocs/recruitment/recruitmentjobposition_list.php b/htdocs/recruitment/recruitmentjobposition_list.php index 1891d9ce822..d497fa3d998 100644 --- a/htdocs/recruitment/recruitmentjobposition_list.php +++ b/htdocs/recruitment/recruitmentjobposition_list.php @@ -44,17 +44,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; @@ -86,7 +102,9 @@ $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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -104,28 +122,33 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Initialize array of search criterias $search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of fields for list $arrayfields = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field if (!empty($val['visible'])) { $visible = dol_eval($val['visible'], 1); @@ -138,10 +161,8 @@ foreach ($object->fields as $key => $val) } } // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], @@ -161,10 +182,11 @@ $permissiontoadd = $user->rights->recruitment->recruitmentjobposition->write; $permissiontodelete = $user->rights->recruitment->recruitmentjobposition->delete; // Security check -if (empty($conf->recruitment->enabled)) accessforbidden('Module not enabled'); +if (empty($conf->recruitment->enabled)) { + accessforbidden('Module not enabled'); +} $socid = 0; -if ($user->socid > 0) // Protection if external user -{ +if ($user->socid > 0) { // Protection if external user //$socid = $user->socid; accessforbidden(); } @@ -177,31 +199,33 @@ if ($user->socid > 0) // Protection if external user * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($object->fields as $key => $val) - { + 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 + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $toselect = ''; $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -230,13 +254,14 @@ $title = $langs->trans('ListOfPositionsToBeFilled'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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.', ' : ''); + 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(); @@ -246,20 +271,32 @@ $sql = preg_replace('/,\s*$/', '', $sql); $sql .= ", COUNT(rc.rowid) as nbapplications"; $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature as rc ON rc.fk_recruitmentjobposition = t.rowid"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -else $sql .= " WHERE 1 = 1"; -foreach ($search as $key => $val) -{ - if ($key == 'status' && $search[$key] == -1) continue; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); if (strpos($object->fields[$key]['type'], 'integer:') === 0) { - if ($search[$key] == '-1') $search[$key] = ''; + if ($search[$key] == '-1') { + $search[$key] = ''; + } $mode_search = 2; } - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -270,13 +307,14 @@ $sql .= $hookmanager->resPrint; /* If a group by is required */ $sql .= " GROUP BY "; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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.', ' : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : ''); + } } // Add where from hooks $parameters = array(); @@ -288,26 +326,24 @@ $sql .= $db->order($sortfield, $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 || empty($limit))) -{ +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -316,8 +352,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".dol_buildpath('/recruitment/recruitmentjobposition_card.php', 1).'?id='.$id); @@ -348,14 +383,24 @@ jQuery(document).ready(function() { $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ - if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); - else $param .= '&search_'.$key.'='.urlencode($search[$key]); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +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'; @@ -366,12 +411,18 @@ $arrayofmassactions = array( //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); -if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($permissiontodelete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -391,9 +442,10 @@ $objecttmp = new RecruitmentJobPosition($db); $trackid = 'recruitmentjobposition'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } @@ -404,11 +456,13 @@ $moreforfilter.= '</div>';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -425,20 +479,26 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit // Fields title search // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - elseif (strpos($val['type'], 'integer:') === 0) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { + print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } print '</td>'; } } @@ -448,8 +508,7 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (!empty($arrayfields['nbapplications']['checked'])) -{ +if (!empty($arrayfields['nbapplications']['checked'])) { print '<td class="liste_titre"></td>'; } // Action column @@ -463,15 +522,18 @@ print '</tr>'."\n"; // Fields title label // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -481,8 +543,7 @@ 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, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (!empty($arrayfields['nbapplications']['checked'])) -{ +if (!empty($arrayfields['nbapplications']['checked'])) { print '<td class="liste_titre">'.$langs->trans("Applications").'</td>'; } // Action column @@ -492,11 +553,11 @@ print '</tr>'."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -505,38 +566,51 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->setVarsFromFetchObj($obj); // Show here line of result print '<tr class="oddeven">'; - foreach ($object->fields as $key => $val) - { + foreach ($object->fields as $key => $val) { $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') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>'; - if ($key == 'status') print $object->getLibStatut(5); - else print $object->showOutputField($val, $key, $object->$key, ''); + if ($key == 'status') { + print $object->getLibStatut(5); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $object->$key; } } @@ -547,20 +621,22 @@ while ($i < ($limit ? min($num, $limit) : $num)) $parameters = array('arrayfields'=>$arrayfields, 'object'=>$object, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (!empty($arrayfields['nbapplications']['checked'])) - { + if (!empty($arrayfields['nbapplications']['checked'])) { print '<td class="right">'.$obj->nbapplications.'</td>'; } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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($object->id, $arrayofselected)) $selected = 1; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'."\n"; @@ -571,10 +647,13 @@ while ($i < ($limit ? min($num, $limit) : $num)) include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } @@ -590,10 +669,11 @@ print '</div>'."\n"; print '</form>'."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/recruitment/recruitmentjobposition_note.php b/htdocs/recruitment/recruitmentjobposition_note.php index 2fe2f5a3257..9dcb5ad9d7d 100644 --- a/htdocs/recruitment/recruitmentjobposition_note.php +++ b/htdocs/recruitment/recruitmentjobposition_note.php @@ -25,17 +25,33 @@ // Load Dolibarr environment $res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} // Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} dol_include_once('/recruitment/class/recruitmentjobposition.class.php'); dol_include_once('/recruitment/lib/recruitment_recruitmentjobposition.lib.php'); @@ -65,7 +81,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->recruitment->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->recruitment->multidir_output[$object->entity]."/".$object->id; +} $permissionnote = $user->rights->recruitment->recruitmentjobposition->write; // Used by the include of actions_setnotes.inc.php $permissiontoadd = $user->rights->recruitment->recruitmentjobposition->write; // Used by the include of actions_addupdatedelete.inc.php @@ -89,8 +107,7 @@ $form = new Form($db); $help_url = ''; llxHeader('', $langs->trans('RecruitmentJobPosition'), $help_url); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = recruitmentjobpositionPrepareHead($object); @@ -110,15 +127,14 @@ if ($id > 0 || !empty($ref)) $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); */ // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= $langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') + if ($permissiontoadd) { + if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; - $morehtmlref .= ' : '; + $morehtmlref .= ' : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; diff --git a/htdocs/resource/agenda.php b/htdocs/resource/agenda.php index 903a9653056..6f9cfa8ce34 100644 --- a/htdocs/resource/agenda.php +++ b/htdocs/resource/agenda.php @@ -44,10 +44,11 @@ $action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); -if (GETPOST('actioncode', 'array')) -{ +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)); } @@ -57,12 +58,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 (!$sortfield) $sortfield = 'a.datep,a.id'; -if (!$sortorder) $sortorder = 'DESC,DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC'; +} $object = new DolResource($db); $object->fetch($id, $ref); @@ -73,8 +80,7 @@ $extrafields = new ExtraFields($db); $hookmanager->initHooks(array('agendaresource')); // Security check -if (!$user->rights->resource->read) -{ +if (!$user->rights->resource->read) { accessforbidden(); } @@ -85,20 +91,19 @@ if (!$user->rights->resource->read) $parameters = array('id'=>$id); $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 (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // 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 $actioncode = ''; $search_agenda_label = ''; } @@ -113,8 +118,7 @@ if (empty($reshook)) $contactstatic = new Contact($db); $form = new Form($db); -if ($object->id > 0) -{ +if ($object->id > 0) { require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; @@ -122,10 +126,14 @@ if ($object->id > 0) $picto = 'resource'; $title = $langs->trans("Agenda"); - if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/productnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref." - ".$title; + if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/productnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->ref." - ".$title; + } llxHeader('', $title); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $type = $langs->trans('ResourceSingular'); $head = resource_prepare_head($object); @@ -139,7 +147,9 @@ if ($object->id > 0) $morehtmlref .= '</div>'; $shownav = 1; - if ($user->socid && !in_array('resource', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('resource', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -150,11 +160,14 @@ if ($object->id > 0) print dol_get_fiche_end(); - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $param = '&id='.$object->id.'&socid='.$socid; - 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); + } print_barre_liste($langs->trans("ActionsOnResource"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $morehtmlcenter, '', 0, 1, 1); diff --git a/htdocs/resource/card.php b/htdocs/resource/card.php index 13789173094..1b4c71b158b 100644 --- a/htdocs/resource/card.php +++ b/htdocs/resource/card.php @@ -44,13 +44,11 @@ $fk_code_type_resource = GETPOST('fk_code_type_resource', 'alpha'); $country_id = GETPOST('country_id', 'int'); // Protection if external user -if ($user->socid > 0) -{ +if ($user->socid > 0) { accessforbidden(); } -if (!$user->rights->resource->read) -{ +if (!$user->rights->resource->read) { accessforbidden(); } @@ -70,33 +68,28 @@ $extrafields->fetch_name_optionals_label($object->table_element); $hookmanager->initHooks(array('resource', 'resource_card', 'globalcard')); $parameters = array('resource_id'=>$id); $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) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } - if ($action == 'add') - { + if ($action == 'add') { header("Location: ".DOL_URL_ROOT.'/resource/list.php'); exit; } $action = ''; } - if ($action == 'add' && $user->rights->resource->write) - { - if (!$cancel) - { + if ($action == 'add' && $user->rights->resource->write) { + if (!$cancel) { $error = ''; - if (empty($ref)) - { + if (empty($ref)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); $action = 'create'; } else { @@ -107,11 +100,12 @@ 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++; + } $result = $object->create($user); - if ($result > 0) - { + if ($result > 0) { // Creation OK setEventMessages($langs->trans('ResourceCreatedWithSuccess'), null, 'mesgs'); Header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); @@ -128,21 +122,17 @@ if (empty($reshook)) } } - if ($action == 'update' && !$cancel && $user->rights->resource->write) - { + if ($action == 'update' && !$cancel && $user->rights->resource->write) { $error = 0; - if (empty($ref)) - { + if (empty($ref)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $res = $object->fetch($id); - if ($res > 0) - { + if ($res > 0) { $object->ref = $ref; $object->description = $description; $object->fk_code_type_resource = $fk_code_type_resource; @@ -155,8 +145,7 @@ if (empty($reshook)) } $result = $object->update($user); - if ($result > 0) - { + if ($result > 0) { Header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -169,21 +158,17 @@ if (empty($reshook)) } } - if ($error) - { + if ($error) { $action = 'edit'; } } - if ($action == 'confirm_delete_resource' && $user->rights->resource->delete && $confirm === 'yes') - { + if ($action == 'confirm_delete_resource' && $user->rights->resource->delete && $confirm === 'yes') { $res = $object->fetch($id); - if ($res > 0) - { + if ($res > 0) { $result = $object->delete($id); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans('RessourceSuccessfullyDeleted'), null, 'mesgs'); Header('Location: '.DOL_URL_ROOT.'/resource/list.php'); exit; @@ -207,10 +192,8 @@ llxHeader('', $title, ''); $form = new Form($db); $formresource = new FormResource($db); -if ($action == 'create' || $object->fetch($id, $ref) > 0) -{ - if ($action == 'create') - { +if ($action == 'create' || $object->fetch($id, $ref) > 0) { + if ($action == 'create') { print load_fiche_titre($title, '', 'object_resource'); print dol_get_fiche_head(''); } else { @@ -218,9 +201,10 @@ if ($action == 'create' || $object->fetch($id, $ref) > 0) print dol_get_fiche_head($head, 'resource', $title, -1, 'resource'); } - if ($action == 'create' || $action == 'edit') - { - if (!$user->rights->resource->write) accessforbidden('', 0, 1); + if ($action == 'create' || $action == 'edit') { + if (!$user->rights->resource->write) { + accessforbidden('', 0, 1); + } // Create/Edit object @@ -251,15 +235,16 @@ if ($action == 'create' || $object->fetch($id, $ref) > 0) // Origin country print '<tr><td>'.$langs->trans("CountryOrigin").'</td><td>'; print $form->select_country($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 '</td></tr>'; // Other attributes $parameters = array('objectsrc' => $objectsrc); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } @@ -279,8 +264,7 @@ if ($action == 'create' || $object->fetch($id, $ref) > 0) $formconfirm = ''; // Confirm deleting resource line - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm("card.php?&id=".$object->id, $langs->trans("DeleteResource"), $langs->trans("ConfirmDeleteResource"), "confirm_delete_resource", '', '', 1); } @@ -352,23 +336,18 @@ if ($action == 'create' || $object->fetch($id, $ref) > 0) $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { - if ($action != "create" && $action != "edit") - { + if (empty($reshook)) { + if ($action != "create" && $action != "edit") { // Edit resource - if ($user->rights->resource->write) - { + if ($user->rights->resource->write) { print '<div class="inline-block divButAction">'; print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$id.'&amp;action=edit" class="butAction">'.$langs->trans('Modify').'</a>'; print '</div>'; } } - if ($action != "delete" && $action != "create" && $action != "edit") - { + if ($action != "delete" && $action != "create" && $action != "edit") { // Delete resource - if ($user->rights->resource->delete) - { + if ($user->rights->resource->delete) { print '<div class="inline-block divButAction">'; print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$id.'&amp;action=delete&amp;token='.newToken().'" class="butActionDelete">'.$langs->trans('Delete').'</a>'; print '</div>'; diff --git a/htdocs/resource/class/dolresource.class.php b/htdocs/resource/class/dolresource.class.php index ef4252f41df..5ab07cdd536 100644 --- a/htdocs/resource/class/dolresource.class.php +++ b/htdocs/resource/class/dolresource.class.php @@ -61,6 +61,9 @@ class Dolresource extends CommonObject public $cache_code_type_resource = array(); + /** + * @var Dolresource Clone of object before changing it + */ public $oldcopy; /** @@ -87,12 +90,24 @@ class Dolresource extends CommonObject // Clean parameters - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->description)) $this->description = trim($this->description); - if (!is_numeric($this->country_id)) $this->country_id = 0; - if (isset($this->fk_code_type_resource)) $this->fk_code_type_resource = trim($this->fk_code_type_resource); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->note_private)) $this->note_private = trim($this->note_private); + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->description)) { + $this->description = trim($this->description); + } + if (!is_numeric($this->country_id)) { + $this->country_id = 0; + } + if (isset($this->fk_code_type_resource)) { + $this->fk_code_type_resource = trim($this->fk_code_type_resource); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->note_private)) { + $this->note_private = trim($this->note_private); + } // Insert request @@ -122,39 +137,34 @@ class Dolresource extends CommonObject $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); } - if (!$error) - { + if (!$error) { $action = 'create'; // Actions on extra fields - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } + if (!$error) { + $result = $this->insertExtraFields(); + if ($result < 0) { + $error++; + } } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('RESOURCE_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -189,15 +199,16 @@ class Dolresource extends CommonObject $sql .= " ty.label as type_label"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_resource as ty ON ty.code=t.fk_code_type_resource"; - if ($id) $sql .= " WHERE t.rowid = ".$this->db->escape($id); - else $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'"; + if ($id) { + $sql .= " WHERE t.rowid = ".$this->db->escape($id); + } else { + $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -238,13 +249,20 @@ class Dolresource extends CommonObject $error = 0; // Clean parameters - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->fk_code_type_resource)) $this->fk_code_type_resource = trim($this->fk_code_type_resource); - if (isset($this->description)) $this->description = trim($this->description); - if (!is_numeric($this->country_id)) $this->country_id = 0; + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->fk_code_type_resource)) { + $this->fk_code_type_resource = trim($this->fk_code_type_resource); + } + if (isset($this->description)) { + $this->description = trim($this->description); + } + if (!is_numeric($this->country_id)) { + $this->country_id = 0; + } - if (empty($this->oldcopy)) - { + if (empty($this->oldcopy)) { $org = new self($this->db); $org->fetch($this->id); $this->oldcopy = $org; @@ -257,37 +275,35 @@ class Dolresource extends CommonObject $sql .= " fk_country=".($this->country_id > 0 ? $this->country_id : "null").","; $sql .= " fk_code_type_resource=".(isset($this->fk_code_type_resource) ? "'".$this->db->escape($this->fk_code_type_resource)."'" : "null").","; $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : '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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('RESOURCE_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } } - if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) - { + if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) { // We remove directory - if (!empty($conf->resource->dir_output)) - { + if (!empty($conf->resource->dir_output)) { $olddir = $conf->resource->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref); $newdir = $conf->resource->dir_output."/".dol_sanitizeFileName($this->ref); - if (file_exists($olddir)) - { + if (file_exists($olddir)) { $res = @rename($olddir, $newdir); - if (!$res) - { + if (!$res) { $langs->load("errors"); $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir); $error++; @@ -296,26 +312,21 @@ class Dolresource extends CommonObject } } - if (!$error) - { + if (!$error) { $action = 'update'; // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -340,7 +351,7 @@ class Dolresource extends CommonObject global $langs; $sql = "SELECT"; $sql .= " t.rowid,"; - $sql .= " t.resource_id,"; + $sql .= " t.resource_id,"; $sql .= " t.resource_type,"; $sql .= " t.element_id,"; $sql .= " t.element_type,"; @@ -353,10 +364,8 @@ class Dolresource extends CommonObject dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -404,14 +413,12 @@ class Dolresource extends CommonObject $sql .= " WHERE rowid =".$rowid; dol_syslog(get_class($this), LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources"; $sql .= " WHERE element_type='resource' AND resource_id =".$this->db->escape($rowid); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->lasterror(); $error++; } @@ -423,33 +430,29 @@ class Dolresource extends CommonObject // Removed extrafields if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR); } } - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('RESOURCE_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { // We remove directory $ref = dol_sanitizeFileName($this->ref); - if (!empty($conf->resource->dir_output)) - { + if (!empty($conf->resource->dir_output)) { $dir = $conf->resource->dir_output."/".dol_sanitizeFileName($this->ref); - if (file_exists($dir)) - { + if (file_exists($dir)) { $res = @dol_delete_dir_recursive($dir); - if (!$res) - { + if (!$res) { $this->errors[] = 'ErrorFailToDeleteDir'; $error++; } @@ -457,8 +460,7 @@ class Dolresource extends CommonObject } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -491,11 +493,15 @@ class Dolresource extends CommonObject $sql .= " t.entity,"; $sql .= " t.ref,"; $sql .= " t.description,"; + $sql .= " t.fk_country,"; $sql .= " t.fk_code_type_resource,"; $sql .= " t.tms,"; // Add fields from extrafields - if (!empty($extrafields->attributes[$this->table_element]['label'])) - foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$this->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); + if (!empty($extrafields->attributes[$this->table_element]['label'])) { + foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$this->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); + } + } $sql .= " ty.label as type_label"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_resource as ty ON ty.code=t.fk_code_type_resource"; @@ -515,23 +521,21 @@ class Dolresource extends CommonObject } $sql .= $this->db->order($sortfield, $sortorder); $this->num_all = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $this->db->query($sql); $this->num_all = $this->db->num_rows($result); } - if ($limit) $sql .= $this->db->plimit($limit, $offset); + if ($limit) { + $sql .= $this->db->plimit($limit, $offset); + } dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); $this->lines = array(); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($num) { + while ($obj = $this->db->fetch_object($resql)) { $line = new Dolresource($this->db); $line->id = $obj->rowid; $line->ref = $obj->ref; @@ -569,10 +573,10 @@ class Dolresource extends CommonObject public function fetch_all_resources($sortorder, $sortfield, $limit, $offset, $filter = '') { // phpcs:enable - global $conf; - $sql = "SELECT "; - $sql .= " t.rowid,"; - $sql .= " t.resource_id,"; + global $conf; + $sql = "SELECT "; + $sql .= " t.rowid,"; + $sql .= " t.resource_id,"; $sql .= " t.resource_type,"; $sql .= " t.element_id,"; $sql .= " t.element_type,"; @@ -580,54 +584,55 @@ class Dolresource extends CommonObject $sql .= " t.mandatory,"; $sql .= " t.fk_user_create,"; $sql .= " t.tms"; - $sql .= ' FROM '.MAIN_DB_PREFIX.'element_resources as t '; - $sql .= " WHERE t.entity IN (".getEntity('resource').")"; + $sql .= ' FROM '.MAIN_DB_PREFIX.'element_resources as t '; + $sql .= " WHERE t.entity IN (".getEntity('resource').")"; - //Manage filter - if (!empty($filter)) { - foreach ($filter as $key => $value) { - if (strpos($key, 'date')) { - $sql .= ' AND '.$key.' = \''.$this->db->idate($value).'\''; - } else { - $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\''; - } - } - } + //Manage filter + if (!empty($filter)) { + foreach ($filter as $key => $value) { + if (strpos($key, 'date')) { + $sql .= ' AND '.$key.' = \''.$this->db->idate($value).'\''; + } else { + $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\''; + } + } + } $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) $sql .= $this->db->plimit($limit + 1, $offset); - dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); + if ($limit) { + $sql .= $this->db->plimit($limit + 1, $offset); + } + dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - if ($num) - { - while ($obj = $this->db->fetch_object($resql)) - { - $line = new Dolresource($this->db); - $line->id = $obj->rowid; - $line->resource_id = $obj->resource_id; - $line->resource_type = $obj->resource_type; - $line->element_id = $obj->element_id; - $line->element_type = $obj->element_type; - $line->busy = $obj->busy; - $line->mandatory = $obj->mandatory; - $line->fk_user_create = $obj->fk_user_create; + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + if ($num) { + while ($obj = $this->db->fetch_object($resql)) { + $line = new Dolresource($this->db); + $line->id = $obj->rowid; + $line->resource_id = $obj->resource_id; + $line->resource_type = $obj->resource_type; + $line->element_id = $obj->element_id; + $line->element_type = $obj->element_type; + $line->busy = $obj->busy; + $line->mandatory = $obj->mandatory; + $line->fk_user_create = $obj->fk_user_create; - if ($obj->resource_id && $obj->resource_type) + if ($obj->resource_id && $obj->resource_type) { $line->objresource = fetchObjectByElement($obj->resource_id, $obj->resource_type); - if ($obj->element_id && $obj->element_type) + } + if ($obj->element_id && $obj->element_type) { $line->objelement = fetchObjectByElement($obj->element_id, $obj->element_type); + } $this->lines[] = $line; - } - $this->db->free($resql); - } - return $num; - } else { - $this->error = $this->db->lasterror(); - return -1; - } + } + $this->db->free($resql); + } + return $num; + } else { + $this->error = $this->db->lasterror(); + return -1; + } } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -646,8 +651,12 @@ class Dolresource extends CommonObject // phpcs:enable global $conf; - if (!$sortorder) $sortorder = "ASC"; - if (!$sortfield) $sortfield = "t.rowid"; + if (!$sortorder) { + $sortorder = "ASC"; + } + if (!$sortfield) { + $sortfield = "t.rowid"; + } $sql = "SELECT "; $sql .= " t.rowid,"; @@ -673,18 +682,17 @@ class Dolresource extends CommonObject } } $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) $sql .= $this->db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $this->db->plimit($limit + 1, $offset); + } dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num) - { + if ($num) { $this->lines = array(); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $line = new Dolresource($this->db); $line->id = $obj->rowid; $line->resource_id = $obj->resource_id; @@ -720,8 +728,7 @@ class Dolresource extends CommonObject // phpcs:enable global $conf; - if (!empty($conf->modules_parts['resources'])) - { + if (!empty($conf->modules_parts['resources'])) { $this->available_resources = (array) $conf->modules_parts['resources']; return count($this->available_resources); @@ -744,12 +751,24 @@ class Dolresource extends CommonObject $error = 0; // Clean parameters - if (isset($this->resource_id)) $this->resource_id = trim($this->resource_id); - if (isset($this->resource_type)) $this->resource_type = trim($this->resource_type); - if (isset($this->element_id)) $this->element_id = trim($this->element_id); - if (isset($this->element_type)) $this->element_type = trim($this->element_type); - if (isset($this->busy)) $this->busy = trim($this->busy); - if (isset($this->mandatory)) $this->mandatory = trim($this->mandatory); + if (isset($this->resource_id)) { + $this->resource_id = trim($this->resource_id); + } + if (isset($this->resource_type)) { + $this->resource_type = trim($this->resource_type); + } + if (isset($this->element_id)) { + $this->element_id = trim($this->element_id); + } + if (isset($this->element_type)) { + $this->element_type = trim($this->element_type); + } + if (isset($this->busy)) { + $this->busy = trim($this->busy); + } + if (isset($this->mandatory)) { + $this->mandatory = trim($this->mandatory); + } // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."element_resources SET"; @@ -761,30 +780,30 @@ class Dolresource extends CommonObject $sql .= " mandatory=".(isset($this->mandatory) ? $this->mandatory : "null").","; $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : '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(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('RESOURCE_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -813,20 +832,19 @@ class Dolresource extends CommonObject $sql = 'SELECT rowid, resource_id, resource_type, busy, mandatory'; $sql .= ' FROM '.MAIN_DB_PREFIX.'element_resources'; $sql .= " WHERE element_id=".$element_id." AND element_type='".$this->db->escape($element)."'"; - if ($resource_type) + if ($resource_type) { $sql .= " AND resource_type LIKE '%".$this->db->escape($resource_type)."%'"; + } $sql .= ' ORDER BY resource_type'; dol_syslog(get_class($this)."::getElementResources", LOG_DEBUG); $resources = array(); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $resources[$i] = array( @@ -873,7 +891,9 @@ class Dolresource extends CommonObject // phpcs:enable global $langs; - if (is_array($this->cache_code_type_resource) && count($this->cache_code_type_resource)) return 0; // Cache deja charge + if (is_array($this->cache_code_type_resource) && count($this->cache_code_type_resource)) { + return 0; // Cache deja charge + } $sql = "SELECT rowid, code, label, active"; $sql .= " FROM ".MAIN_DB_PREFIX."c_type_resource"; @@ -881,12 +901,10 @@ class Dolresource extends CommonObject $sql .= " ORDER BY rowid"; dol_syslog(get_class($this)."::load_cache_code_type_resource", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut $label = ($langs->trans("ResourceTypeShort".$obj->code) != ("ResourceTypeShort".$obj->code) ? $langs->trans("ResourceTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : '')); @@ -922,43 +940,50 @@ class Dolresource extends CommonObject $label .= '<br>'; $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref; /*if (isset($this->status)) { - $label.= '<br><b>' . $langs->trans("Status").":</b> ".$this->getLibStatut(5); - }*/ + $label.= '<br><b>' . $langs->trans("Status").":</b> ".$this->getLibStatut(5); + }*/ if (isset($this->type_label)) { $label .= '<br><b>'.$langs->trans("ResourceType").":</b> ".$this->type_label; } $url = DOL_URL_ROOT.'/resource/card.php?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowMyObject"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = '<a href="'.$url.$get_params.'"'; $linkstart .= $linkclose.'>'; $linkend = '</a>'; /*$linkstart = '<a href="'.dol_buildpath('/resource/card.php', 1).'?id='.$this->id.$get_params.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; - $linkend = '</a>';*/ + $linkend = '</a>';*/ $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; return $result; diff --git a/htdocs/resource/class/html.formresource.class.php b/htdocs/resource/class/html.formresource.class.php index 30d7a13a194..a8b17665fa1 100644 --- a/htdocs/resource/class/html.formresource.class.php +++ b/htdocs/resource/class/html.formresource.class.php @@ -90,18 +90,17 @@ class FormResource $resources_used = $resourcestat->fetch_all('ASC', 't.rowid', $limit, 0, $filter); - if (!is_array($selected)) $selected = array($selected); + if (!is_array($selected)) { + $selected = array($selected); + } - if ($outputmode != 2) - { + if ($outputmode != 2) { $out = '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">'; $out .= '<input type="hidden" name="token" value="'.newToken().'">'; } - if ($resourcestat) - { - if (!empty($conf->use_javascript_ajax) && !empty($conf->global->RESOURCE_USE_SEARCH_TO_SELECT) && !$forcecombo) - { + if ($resourcestat) { + if (!empty($conf->use_javascript_ajax) && !empty($conf->global->RESOURCE_USE_SEARCH_TO_SELECT) && !$forcecombo) { //$minLength = (is_numeric($conf->global->RESOURCE_USE_SEARCH_TO_SELECT)?$conf->global->RESOURCE_USE_SEARCH_TO_SELECT:2); $out .= ajax_combobox($htmlname, $event, $conf->global->RESOURCE_USE_SEARCH_TO_SELECT); } else { @@ -110,24 +109,27 @@ class FormResource // Construct $out and $outarray $out .= '<select id="'.$htmlname.'" class="flat minwidth100'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n"; - if ($showempty) $out .= '<option value="-1">&nbsp;</option>'."\n"; + if ($showempty) { + $out .= '<option value="-1">&nbsp;</option>'."\n"; + } $num = 0; - if (is_array($resourcestat->lines)) $num = count($resourcestat->lines); + if (is_array($resourcestat->lines)) { + $num = count($resourcestat->lines); + } //var_dump($resourcestat->lines); $i = 0; - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $resourceclass = ucfirst($resourcestat->lines[$i]->element); $label = $resourcestat->lines[$i]->ref ? $resourcestat->lines[$i]->ref : ''.$resourcestat->lines[$i]->label; - if ($resourceclass != 'Dolresource') $label .= ' ('.$langs->trans($resourceclass).')'; + if ($resourceclass != 'Dolresource') { + $label .= ' ('.$langs->trans($resourceclass).')'; + } - if ((is_object($selected[0]) && $selected[0]->id == $resourcestat->lines[$i]->id) || (!is_object($selected[0]) && in_array($resourcestat->lines[$i]->id, $selected))) - { + if ((is_object($selected[0]) && $selected[0]->id == $resourcestat->lines[$i]->id) || (!is_object($selected[0]) && in_array($resourcestat->lines[$i]->id, $selected))) { $out .= '<option value="'.$resourcestat->lines[$i]->id.'" selected>'.$label.'</option>'; } else { $out .= '<option value="'.$resourcestat->lines[$i]->id.'">'.$label.'</option>'; @@ -136,13 +138,14 @@ class FormResource array_push($outarray, array('key'=>$resourcestat->lines[$i]->id, 'value'=>$resourcestat->lines[$i]->label, 'label'=>$resourcestat->lines[$i]->label)); $i++; - if (($i % 10) == 0) $out .= "\n"; + if (($i % 10) == 0) { + $out .= "\n"; + } } } $out .= '</select>'."\n"; - if ($outputmode != 2) - { + if ($outputmode != 2) { $out .= '<input type="submit" class="button" value="'.$langs->trans("Search").'"> &nbsp; &nbsp; '; $out .= '</form>'; @@ -151,7 +154,9 @@ class FormResource dol_print_error($this->db); } - if ($outputmode && $outputmode != 2) return $outarray; + if ($outputmode && $outputmode != 2) { + return $outarray; + } return $out; } @@ -179,35 +184,54 @@ class FormResource $filterarray = array(); - if ($filtertype != '' && $filtertype != '-1') $filterarray = explode(',', $filtertype); + if ($filtertype != '' && $filtertype != '-1') { + $filterarray = explode(',', $filtertype); + } $resourcestat->load_cache_code_type_resource(); print '<select id="select'.$htmlname.'" class="flat maxwidthonsmartphone select_'.$htmlname.'" name="'.$htmlname.'">'; - if ($empty) print '<option value="">&nbsp;</option>'; - if (is_array($resourcestat->cache_code_type_resource) && count($resourcestat->cache_code_type_resource)) - { - foreach ($resourcestat->cache_code_type_resource as $id => $arraytypes) - { + if ($empty) { + print '<option value="">&nbsp;</option>'; + } + if (is_array($resourcestat->cache_code_type_resource) && count($resourcestat->cache_code_type_resource)) { + foreach ($resourcestat->cache_code_type_resource as $id => $arraytypes) { // We discard empty line if showempty is on because an empty line has already been output. - if ($empty && empty($arraytypes['code'])) continue; + if ($empty && empty($arraytypes['code'])) { + continue; + } - if ($format == 0) print '<option value="'.$id.'"'; - elseif ($format == 1) print '<option value="'.$arraytypes['code'].'"'; - elseif ($format == 2) print '<option value="'.$arraytypes['code'].'"'; - elseif ($format == 3) print '<option value="'.$id.'"'; + if ($format == 0) { + print '<option value="'.$id.'"'; + } elseif ($format == 1) { + print '<option value="'.$arraytypes['code'].'"'; + } elseif ($format == 2) { + print '<option value="'.$arraytypes['code'].'"'; + } elseif ($format == 3) { + print '<option value="'.$id.'"'; + } // Si selected est text, on compare avec code, sinon avec id - if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected'; - elseif ($selected == $id) print ' selected'; + if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) { + print ' selected'; + } elseif ($selected == $id) { + print ' selected'; + } print '>'; - if ($format == 0) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']); - elseif ($format == 1) $value = $arraytypes['code']; - elseif ($format == 2) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']); - elseif ($format == 3) $value = $arraytypes['code']; + if ($format == 0) { + $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']); + } elseif ($format == 1) { + $value = $arraytypes['code']; + } elseif ($format == 2) { + $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']); + } elseif ($format == 3) { + $value = $arraytypes['code']; + } print $value ? $value : '&nbsp;'; print '</option>'; } } print '</select>'; - if ($user->admin && !$noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin && !$noadmininfo) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } } } diff --git a/htdocs/resource/contact.php b/htdocs/resource/contact.php index 0330579f06c..811bb476430 100644 --- a/htdocs/resource/contact.php +++ b/htdocs/resource/contact.php @@ -39,7 +39,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'resource', $id, 'resource'); $object = new DolResource($db); @@ -50,17 +52,14 @@ $result = $object->fetch($id, $ref); * Add a new contact */ -if ($action == 'addcontact' && $user->rights->resource->write) -{ - if ($result > 0 && $id > 0) - { +if ($action == 'addcontact' && $user->rights->resource->write) { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -73,21 +72,14 @@ if ($action == 'addcontact' && $user->rights->resource->write) setEventMessages($mesg, null, 'errors'); } -} - -// Toggle the status of a contact -elseif ($action == 'swapstatut' && $user->rights->resource->write) -{ +} elseif ($action == 'swapstatut' && $user->rights->resource->write) { + // Toggle the status of a contact $result = $object->swapContactStatus(GETPOST('ligne', 'int')); -} - -// Erase a contact -elseif ($action == 'deletecontact' && $user->rights->resource->write) -{ +} elseif ($action == 'deletecontact' && $user->rights->resource->write) { + // Erase a contact $result = $object->delete_contact(GETPOST('lineid', 'int')); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -109,8 +101,7 @@ llxHeader('', $langs->trans("Resource")); // Mode vue et edition -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $soc = new Societe($db); $soc->fetch($object->socid); @@ -152,8 +143,12 @@ if ($id > 0 || !empty($ref)) print '<br>'; - if (!empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_USER)) $hideaddcontactforuser = 1; - if (!empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_THIPARTY)) $hideaddcontactforthirdparty = 1; + if (!empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_USER)) { + $hideaddcontactforuser = 1; + } + if (!empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_THIPARTY)) { + $hideaddcontactforthirdparty = 1; + } $permission = 1; // Contacts lines diff --git a/htdocs/resource/document.php b/htdocs/resource/document.php index 0019d6b99ed..fb291a5a4a7 100644 --- a/htdocs/resource/document.php +++ b/htdocs/resource/document.php @@ -44,7 +44,9 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'resource', $id, 'resource'); @@ -53,12 +55,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) { $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"; +} $object = new DolResource($db); @@ -72,7 +80,7 @@ $modulepart = 'resource'; * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -83,8 +91,7 @@ $form = new Form($db); llxHeader('', $langs->trans("Resource")); -if ($object->id > 0) -{ +if ($object->id > 0) { $object->fetch_thirdparty(); $head = resource_prepare_head($object); @@ -95,8 +102,7 @@ if ($object->id > 0) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/resource/element_resource.php b/htdocs/resource/element_resource.php index 7da223dd02b..c16018a30c1 100644 --- a/htdocs/resource/element_resource.php +++ b/htdocs/resource/element_resource.php @@ -45,8 +45,9 @@ $sortfield = GETPOST('sortfield','alpha'); $page = GETPOST('page','int'); */ -if (!$user->rights->resource->read) +if (!$user->rights->resource->read) { accessforbidden(); +} $object = new Dolresource($db); @@ -69,8 +70,7 @@ $cancel = GETPOST('cancel', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); $socid = GETPOST('socid', 'int'); -if ($socid > 0) // Special for thirdparty -{ +if ($socid > 0) { // Special for thirdparty $element_id = $socid; $element = 'societe'; } @@ -83,17 +83,16 @@ if ($socid > 0) // Special for thirdparty $parameters = array('resource_id' => $resource_id); $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 (empty($reshook)) { $error = 0; - if ($action == 'add_element_resource' && !$cancel) - { + if ($action == 'add_element_resource' && !$cancel) { $res = 0; - if (!($resource_id > 0)) - { + if (!($resource_id > 0)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Resource")), null, 'errors'); $action = ''; @@ -162,23 +161,19 @@ if (empty($reshook)) } } - if (!$error && $res > 0) - { + if (!$error && $res > 0) { setEventMessages($langs->trans('ResourceLinkedWithSuccess'), null, 'mesgs'); header("Location: ".$_SERVER['PHP_SELF'].'?element='.$element.'&element_id='.$objstat->id); exit; - } elseif ($objstat) - { + } elseif ($objstat) { setEventMessages($objstat->error, $objstat->errors, 'errors'); } } // Update ressource - if ($action == 'update_linked_resource' && $user->rights->resource->write && !GETPOST('cancel', 'alpha')) - { + if ($action == 'update_linked_resource' && $user->rights->resource->write && !GETPOST('cancel', 'alpha')) { $res = $object->fetch_element_resource($lineid); - if ($res) - { + if ($res) { $object->busy = $busy; $object->mandatory = $mandatory; @@ -239,7 +234,9 @@ if (empty($reshook)) if (!$error) { $result = $object->update_element_resource($user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } if ($error) { @@ -253,12 +250,10 @@ if (empty($reshook)) } // Delete a resource linked to an element - if ($action == 'confirm_delete_linked_resource' && $user->rights->resource->delete && $confirm === 'yes') - { + if ($action == 'confirm_delete_linked_resource' && $user->rights->resource->delete && $confirm === 'yes') { $result = $object->delete_resource($lineid, $element); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans('RessourceLineSuccessfullyDeleted'), null, 'mesgs'); header("Location: ".$_SERVER['PHP_SELF']."?element=".$element."&element_id=".$element_id); exit; @@ -270,7 +265,9 @@ if (empty($reshook)) $parameters = array('resource_id'=>$resource_id); $reshook = $hookmanager->executeHooks('getElementResources', $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'); +} @@ -294,20 +291,17 @@ if (!$ret) { print '<div class="warning">'.$langs->trans('NoResourceInDatabase').'</div>'; } else { // Confirmation suppression resource line - if ($action == 'delete_resource') - { + if ($action == 'delete_resource') { print $form->formconfirm("element_resource.php?element=".$element."&element_id=".$element_id."&id=".$id."&lineid=".$lineid, $langs->trans("DeleteResource"), $langs->trans("ConfirmDeleteResourceElement"), "confirm_delete_linked_resource", '', '', 1); } // Specific to agenda module - if (($element_id || $element_ref) && $element == 'action') - { + if (($element_id || $element_ref) && $element == 'action') { require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; $act = fetchObjectByElement($element_id, $element, $element_ref); - if (is_object($act)) - { + if (is_object($act)) { $head = actions_prepare_head($act); print dol_get_fiche_head($head, 'resources', $langs->trans("Action"), -1, 'action'); @@ -332,8 +326,7 @@ if (!$ret) { // Thirdparty //$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); //$morehtmlref.='<br>'.$langs->trans('Project') . ' '; $morehtmlref .= $langs->trans('Project').': '; @@ -343,7 +336,9 @@ if (!$ret) { $morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$act->fk_project.'" title="'.$langs->trans('ShowProject').'">'; $morehtmlref .= $proj->ref; $morehtmlref .= '</a>'; - if ($proj->title) $morehtmlref .= ' - '.$proj->title; + if ($proj->title) { + $morehtmlref .= ' - '.$proj->title; + } } else { $morehtmlref .= ''; } @@ -359,8 +354,7 @@ if (!$ret) { print '<table class="border tableforfield" width="100%">'; // Type - if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) - { + if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { print '<tr><td class="titlefield">'.$langs->trans("Type").'</td><td colspan="3">'.$act->type.'</td></tr>'; } @@ -369,44 +363,53 @@ if (!$ret) { // Date start print '<tr><td>'.$langs->trans("DateActionStart").'</td><td colspan="3">'; - if (!$act->fulldayevent) print dol_print_date($act->datep, 'dayhour'); - else print dol_print_date($act->datep, 'day'); - if ($act->percentage == 0 && $act->datep && $act->datep < ($now - $delay_warning)) print img_warning($langs->trans("Late")); + if (!$act->fulldayevent) { + print dol_print_date($act->datep, 'dayhour'); + } else { + print dol_print_date($act->datep, 'day'); + } + if ($act->percentage == 0 && $act->datep && $act->datep < ($now - $delay_warning)) { + print img_warning($langs->trans("Late")); + } print '</td>'; print '</tr>'; // Date end print '<tr><td>'.$langs->trans("DateActionEnd").'</td><td colspan="3">'; - if (!$act->fulldayevent) print dol_print_date($act->datef, 'dayhour'); - else print dol_print_date($act->datef, 'day'); - if ($act->percentage > 0 && $act->percentage < 100 && $act->datef && $act->datef < ($now - $delay_warning)) print img_warning($langs->trans("Late")); + if (!$act->fulldayevent) { + print dol_print_date($act->datef, 'dayhour'); + } else { + print dol_print_date($act->datef, 'day'); + } + if ($act->percentage > 0 && $act->percentage < 100 && $act->datef && $act->datef < ($now - $delay_warning)) { + print img_warning($langs->trans("Late")); + } print '</td></tr>'; // Location - if (empty($conf->global->AGENDA_DISABLE_LOCATION)) - { + if (empty($conf->global->AGENDA_DISABLE_LOCATION)) { print '<tr><td>'.$langs->trans("Location").'</td><td colspan="3">'.$act->location.'</td></tr>'; } // Assigned to print '<tr><td class="nowrap">'.$langs->trans("ActionAffectedTo").'</td><td colspan="3">'; $listofuserid = array(); - if (empty($donotclearsession)) - { - if ($act->userownerid > 0) $listofuserid[$act->userownerid] = array('id'=>$act->userownerid, 'transparency'=>$act->transparency); // Owner first - if (!empty($act->userassigned)) // Now concat assigned users - { + if (empty($donotclearsession)) { + if ($act->userownerid > 0) { + $listofuserid[$act->userownerid] = array('id'=>$act->userownerid, 'transparency'=>$act->transparency); // Owner first + } + if (!empty($act->userassigned)) { // Now concat assigned users // Restore array with key with same value than param 'id' $tmplist1 = $act->userassigned; $tmplist2 = array(); - foreach ($tmplist1 as $key => $val) - { - if ($val['id'] && $val['id'] != $act->userownerid) $listofuserid[$val['id']] = $val; + foreach ($tmplist1 as $key => $val) { + if ($val['id'] && $val['id'] != $act->userownerid) { + $listofuserid[$val['id']] = $val; + } } } $_SESSION['assignedtouser'] = json_encode($listofuserid); } else { - if (!empty($_SESSION['assignedtouser'])) - { + if (!empty($_SESSION['assignedtouser'])) { $listofuserid = json_decode($_SESSION['assignedtouser'], true); } } @@ -432,8 +435,7 @@ if (!$ret) { } // Specific to thirdparty module - if (($element_id || $element_ref) && $element == 'societe') - { + if (($element_id || $element_ref) && $element == 'societe') { $socstatic = fetchObjectByElement($element_id, $element, $element_ref); if (is_object($socstatic)) { $savobject = $object; @@ -467,16 +469,14 @@ if (!$ret) { } // Specific to fichinter module - if (($element_id || $element_ref) && $element == 'fichinter') - { + if (($element_id || $element_ref) && $element == 'fichinter') { require_once DOL_DOCUMENT_ROOT.'/core/lib/fichinter.lib.php'; $fichinter = new Fichinter($db); $fichinter->fetch($element_id, $element_ref); $fichinter->fetch_thirdparty(); - if (is_object($fichinter)) - { + if (is_object($fichinter)) { $head = fichinter_prepare_head($fichinter); print dol_get_fiche_head($head, 'resource', $langs->trans("InterventionCard"), -1, 'intervention'); @@ -491,15 +491,14 @@ if (!$ret) { // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$fichinter->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->commande->creer) - { - if ($action != 'classify') + if ($user->rights->commande->creer) { + if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $fichinter->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $fichinter->id, $fichinter->socid, $fichinter->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$fichinter->id.'">'; @@ -532,15 +531,13 @@ if (!$ret) { } // Specific to product/service module - if (($element_id || $element_ref) && ($element == 'product' || $element == 'service')) - { + if (($element_id || $element_ref) && ($element == 'product' || $element == 'service')) { require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; $product = new Product($db); $product->fetch($element_id, $element_ref); - if (is_object($product)) - { + if (is_object($product)) { $head = product_prepare_head($product); $titre = $langs->trans("CardProduct".$product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); @@ -548,7 +545,9 @@ if (!$ret) { print dol_get_fiche_head($head, 'resources', $titre, -1, $picto); $shownav = 1; - if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) { + $shownav = 0; + } dol_banner_tab($product, 'ref', '', $shownav, 'ref', 'ref', '', '&element='.$element); print dol_get_fiche_end(); @@ -559,7 +558,9 @@ if (!$ret) { // hook for other elements linked $parameters = array('element'=>$element, 'element_id'=>$element_id, 'element_ref'=>$element_ref); $reshook = $hookmanager->executeHooks('printElementTab', $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'); + } //print load_fiche_titre($langs->trans('ResourcesLinkedToElement'),'',''); @@ -567,18 +568,17 @@ if (!$ret) { // Show list of resource links - foreach ($object->available_resources as $modresources => $resources) - { + foreach ($object->available_resources as $modresources => $resources) { $resources = (array) $resources; // To be sure $resources is an array - foreach ($resources as $resource_obj) - { + foreach ($resources as $resource_obj) { $element_prop = getElementProperties($resource_obj); //print '/'.$modresources.'/class/'.$resource_obj.'.class.php<br>'; $path = ''; - if (strpos($resource_obj, '@')) + if (strpos($resource_obj, '@')) { $path .= '/'.$element_prop['module']; + } $linked_resources = $object->getElementResources($element, $element_id, $resource_obj); @@ -586,10 +586,8 @@ if (!$ret) { $defaulttpldir = '/core/tpl'; $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir), array($path.$defaulttpldir)); - foreach ($dirtpls as $module => $reldir) - { - if (file_exists(dol_buildpath($reldir.'/resource_'.$element_prop['element'].'_add.tpl.php'))) - { + foreach ($dirtpls as $module => $reldir) { + if (file_exists(dol_buildpath($reldir.'/resource_'.$element_prop['element'].'_add.tpl.php'))) { $tpl = dol_buildpath($reldir.'/resource_'.$element_prop['element'].'_add.tpl.php'); } else { $tpl = DOL_DOCUMENT_ROOT.$reldir.'/resource_add.tpl.php'; @@ -599,15 +597,14 @@ if (!$ret) { } else { $res = include $tpl; // for debug } - if ($res) break; + if ($res) { + break; + } } - if ($mode != 'add' || $resource_obj != $resource_type) - { - foreach ($dirtpls as $module => $reldir) - { - if (file_exists(dol_buildpath($reldir.'/resource_'.$element_prop['element'].'_view.tpl.php'))) - { + if ($mode != 'add' || $resource_obj != $resource_type) { + foreach ($dirtpls as $module => $reldir) { + if (file_exists(dol_buildpath($reldir.'/resource_'.$element_prop['element'].'_view.tpl.php'))) { $tpl = dol_buildpath($reldir.'/resource_'.$element_prop['element'].'_view.tpl.php'); } else { $tpl = DOL_DOCUMENT_ROOT.$reldir.'/resource_view.tpl.php'; @@ -617,7 +614,9 @@ if (!$ret) { } else { $res = include $tpl; // for debug } - if ($res) break; + if ($res) { + break; + } } } } diff --git a/htdocs/resource/list.php b/htdocs/resource/list.php index c1b67edaa0e..356df3a746e 100644 --- a/htdocs/resource/list.php +++ b/htdocs/resource/list.php @@ -1,7 +1,7 @@ <?php /* Copyright (C) 2013-2014 Jean-François Ferry <jfefe@aternatik.fr> * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com> - * Copyright (C) 2018-2019 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -40,6 +40,7 @@ $resource_id = GETPOST('resource_id', 'int'); $sortorder = GETPOST('sortorder', 'alpha'); $sortfield = GETPOST('sortfield', 'aZ09comma'); +$optioncss = GETPOST('optioncss', 'alpha'); // Initialize context for list $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'resourcelist'; @@ -51,7 +52,9 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); -if (!is_array($search_array_options)) $search_array_options = array(); +if (!is_array($search_array_options)) { + $search_array_options = array(); +} $search_ref = GETPOST("search_ref", 'alpha'); $search_type = GETPOST("search_type", 'alpha'); @@ -62,8 +65,12 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $filter = array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&amp;contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&amp;limit='.urlencode($limit); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&amp;contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&amp;limit='.urlencode($limit); +} if ($search_ref != '') { $param .= '&search_ref='.urlencode($search_ref); @@ -75,8 +82,7 @@ if ($search_type != '') { } // Add $param from extra fields -foreach ($search_array_options as $key => $val) -{ +foreach ($search_array_options as $key => $val) { $crit = $val; $tmpkey = preg_replace('/search_options_/', '', $key); $typ = $extrafields->attributes[$object->table_element]['type'][$tmpkey]; @@ -84,25 +90,38 @@ foreach ($search_array_options as $key => $val) $param .= '&search_options_'.$tmpkey.'='.urlencode($val); } $mode_search = 0; - if (in_array($typ, array('int', 'double', 'real'))) $mode_search = 1; // Search on a numeric - if (in_array($typ, array('sellist', 'link')) && $crit != '0' && $crit != '-1') $mode_search = 2; // Search on a foreign key int - if ($crit != '' && (!in_array($typ, array('select', 'sellist')) || $crit != '0') && (!in_array($typ, array('link')) || $crit != '-1')) - { + if (in_array($typ, array('int', 'double', 'real'))) { + $mode_search = 1; // Search on a numeric + } + if (in_array($typ, array('sellist', 'link')) && $crit != '0' && $crit != '-1') { + $mode_search = 2; // Search on a foreign key int + } + if ($crit != '' && (!in_array($typ, array('select', 'sellist')) || $crit != '0') && (!in_array($typ, array('link')) || $crit != '-1')) { $filter['ef.'.$tmpkey] = natural_search('ef.'.$tmpkey, $crit, $mode_search); } } -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} $hookmanager->initHooks(array('resourcelist')); -if (empty($sortorder)) $sortorder = "ASC"; -if (empty($sortfield)) $sortfield = "t.ref"; -if (empty($arch)) $arch = 0; +if (empty($sortorder)) { + $sortorder = "ASC"; +} +if (empty($sortfield)) { + $sortfield = "t.ref"; +} +if (empty($arch)) { + $arch = 0; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $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; @@ -130,8 +149,7 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $search_ref = ""; $search_type = ""; $search_array_options = array(); @@ -145,7 +163,9 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $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'); +} /* @@ -158,8 +178,7 @@ $pagetitle = $langs->trans('ResourcePageIndex'); llxHeader('', $pagetitle, ''); // Confirmation suppression resource line -if ($action == 'delete_resource') -{ +if ($action == 'delete_resource') { print $form->formconfirm($_SERVER['PHP_SELF']."?element=".$element."&element_id=".$element_id."&lineid=".$lineid, $langs->trans("DeleteResource"), $langs->trans("ConfirmDeleteResourceElement"), "confirm_delete_resource", '', '', 1); } @@ -167,7 +186,9 @@ $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -175,8 +196,7 @@ print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $ret = $object->fetch_all('', '', 0, 0, $filter); if ($ret == -1) { dol_print_error($db, $object->error); @@ -193,8 +213,7 @@ if ($ret == -1) { exit; } else { $newcardbutton = ''; - if ($user->rights->resource->write) - { + if ($user->rights->resource->write) { $newcardbutton .= dolGetButtonTitle($langs->trans('MenuResourceAdd'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/resource/card.php?action=create'); } @@ -207,14 +226,12 @@ print '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; print '<tr class="liste_titre_filter">'; -if (!empty($arrayfields['t.ref']['checked'])) -{ +if (!empty($arrayfields['t.ref']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_ref" value="'.$search_ref.'" size="6">'; print '</td>'; } -if (!empty($arrayfields['ty.label']['checked'])) -{ +if (!empty($arrayfields['ty.label']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_type" value="'.$search_type.'" size="6">'; print '</td>'; @@ -229,34 +246,38 @@ print '</td>'; print "</tr>\n"; print '<tr class="liste_titre">'; -if (!empty($arrayfields['t.ref']['checked'])) print_liste_field_titre($arrayfields['t.ref']['label'], $_SERVER["PHP_SELF"], "t.ref", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['ty.label']['checked'])) print_liste_field_titre($arrayfields['ty.label']['label'], $_SERVER["PHP_SELF"], "ty.label", "", $param, "", $sortfield, $sortorder); +if (!empty($arrayfields['t.ref']['checked'])) { + print_liste_field_titre($arrayfields['t.ref']['label'], $_SERVER["PHP_SELF"], "t.ref", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['ty.label']['checked'])) { + print_liste_field_titre($arrayfields['ty.label']['label'], $_SERVER["PHP_SELF"], "ty.label", "", $param, "", $sortfield, $sortorder); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; -if ($ret) -{ - foreach ($object->lines as $resource) - { +if ($ret) { + foreach ($object->lines as $resource) { print '<tr class="oddeven">'; - if (!empty($arrayfields['t.ref']['checked'])) - { + if (!empty($arrayfields['t.ref']['checked'])) { print '<td>'; print $resource->getNomUrl(5); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['ty.label']['checked'])) - { + if (!empty($arrayfields['ty.label']['checked'])) { print '<td>'; print $resource->type_label; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields $obj = (Object) $resource->array_options; @@ -271,13 +292,19 @@ if ($ret) print img_delete('', 'class="marginleftonly"'); print '</a>'; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'; } } else { $colspan = 1; - foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } diff --git a/htdocs/resource/note.php b/htdocs/resource/note.php index 385fb9f190a..07819b1d0b4 100644 --- a/htdocs/resource/note.php +++ b/htdocs/resource/note.php @@ -37,7 +37,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'resource', $id, 'resource'); $object = new DolResource($db); @@ -61,8 +63,7 @@ llxHeader(); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $head = resource_prepare_head($object); print dol_get_fiche_head($head, 'note', $langs->trans('ResourceSingular'), -1, 'resource'); diff --git a/htdocs/salaries/admin/salaries.php b/htdocs/salaries/admin/salaries.php index 2b429dc79ec..dc0cc5b14a0 100644 --- a/htdocs/salaries/admin/salaries.php +++ b/htdocs/salaries/admin/salaries.php @@ -27,14 +27,17 @@ require '../../main.inc.php'; // Class require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/salaries.lib.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('admin', 'salaries')); // Security check -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); @@ -47,8 +50,7 @@ $list = array( * Actions */ -if ($action == 'update') -{ +if ($action == 'update') { $error = 0; foreach ($list as $constname) { @@ -59,14 +61,21 @@ if ($action == 'update') } } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); } } +$reg = array(); +if (preg_match('/^(set|del)_?([A-Z_]+)$/', $action, $reg)) { + // Set boolean (on/off) constants + if (!dolibarr_set_const($db, $reg[2], ($reg[1] === 'set' ? '1' : '0'), 'chaine', 0, '', $conf->entity) > 0) { + dol_print_error($db); + } +} + /* * View */ @@ -74,7 +83,9 @@ if ($action == 'update') llxHeader('', $langs->trans('SalariesSetup')); $form = new Form($db); -if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); +if (!empty($conf->accounting->enabled)) { + $formaccounting = new FormAccounting($db); +} $linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>'; print load_fiche_titre($langs->trans('SalariesSetup'), $linkback, 'title_setup'); @@ -99,8 +110,7 @@ print '<td>'.$langs->trans("Parameters").'</td>'; print '<td width="60">'.$langs->trans("Value")."</td>\n"; print "</tr>\n"; -foreach ($list as $key) -{ +foreach ($list as $key) { print '<tr class="oddeven value">'; // Param @@ -109,8 +119,7 @@ foreach ($list as $key) // Value print '<td>'; - if (!empty($conf->accounting->enabled)) - { + if (!empty($conf->accounting->enabled)) { print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); } else { print '<input type="text" size="20" id="'.$key.'" name="'.$key.'" value="'.$conf->global->$key.'">'; @@ -126,7 +135,21 @@ print "</table>\n"; print '<div class="center"><input type="submit" class="button" value="'.$langs->trans('Modify').'" name="button"></div>'; -print '</form>'; +print '</form><br>'; + +echo '<div>'; +echo '<table class="noborder centpercent">'; +echo '<thead>'; +echo '<tr class="liste_titre"><th>' . $langs->trans('Parameter') . '</th><th>' . $langs->trans('Value') . '</th></tr>'; +echo '</thead>'; +echo '<tbody>'; + +$key = 'CREATE_NEW_SALARY_WITHOUT_AUTO_PAYMENT'; +echo '<tr><td>', $langs->trans($key), '</td><td>', ajax_constantonoff($key), '</td></tr>'; + +echo '</tbody>'; +echo '</table>'; +echo '</div>'; // End of page llxFooter(); diff --git a/htdocs/salaries/admin/salaries_extrafields.php b/htdocs/salaries/admin/salaries_extrafields.php index 62073f8177b..59074e582d2 100644 --- a/htdocs/salaries/admin/salaries_extrafields.php +++ b/htdocs/salaries/admin/salaries_extrafields.php @@ -36,13 +36,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 = 'payment_salary'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -77,8 +81,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"]."?action=create\">".$langs->trans("NewAttribute").'</a></div>'; print "</div>"; @@ -91,8 +94,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<div name="topofform"></div><br>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -104,8 +106,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print '<div name="topofform"></div><br>'; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/salaries/card.php b/htdocs/salaries/card.php old mode 100644 new mode 100755 index 2fc71bec099..775221caeb2 --- a/htdocs/salaries/card.php +++ b/htdocs/salaries/card.php @@ -3,7 +3,8 @@ * Copyright (C) 2014-2020 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr> * Copyright (C) 2015 Charlie BENKE <charlie@patas-monkey.com> - * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -24,40 +25,52 @@ * \ingroup salaries * \brief Page of salaries payments */ - require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php'; require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/salaries.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (!empty($conf->projet->enabled)) -{ +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } // Load translation files required by the page -$langs->loadLangs(array("compta", "banks", "bills", "users", "salaries", "hrm")); -if (!empty($conf->projet->enabled)) $langs->load("projects"); +$langs->loadLangs(array("compta", "banks", "bills", "users", "salaries", "hrm", "trips")); +if (!empty($conf->projet->enabled)) { + $langs->load("projects"); +} -$id = GETPOST("id", 'int'); +$id = GETPOSTINT('id'); $action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09'); $accountid = GETPOST('accountid', 'int') > 0 ? GETPOST('accountid', 'int') : 0; $projectid = (GETPOST('projectid', 'int') ? GETPOST('projectid', 'int') : GETPOST('fk_project', 'int')); +$confirm = GETPOST('confirm'); +if (GETPOSTISSET('auto_create_paiement') || $action === 'add') { + $auto_create_paiement = GETPOST("auto_create_paiement", "int"); +} else { + $auto_create_paiement = empty($conf->global->CREATE_NEW_SALARY_WITHOUT_AUTO_PAYMENT); +} $datep = dol_mktime(12, 0, 0, GETPOST("datepmonth", 'int'), GETPOST("datepday", 'int'), GETPOST("datepyear", 'int')); $datev = dol_mktime(12, 0, 0, GETPOST("datevmonth", 'int'), GETPOST("datevday", 'int'), GETPOST("datevyear", 'int')); $datesp = dol_mktime(12, 0, 0, GETPOST("datespmonth", 'int'), GETPOST("datespday", 'int'), GETPOST("datespyear", 'int')); $dateep = dol_mktime(12, 0, 0, GETPOST("dateepmonth", 'int'), GETPOST("dateepday", 'int'), GETPOST("dateepyear", 'int')); +$label = GETPOST('label', 'alphanohtml'); +$fk_user = GETPOSTINT('userid'); // Security check -$socid = GETPOST("socid", "int"); -if ($user->socid) $socid = $user->socid; +$socid = GETPOSTINT('socid'); +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'salaries', '', '', ''); -$object = new PaymentSalary($db); +$object = new Salary($db); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels @@ -71,38 +84,89 @@ $hookmanager->initHooks(array('salarycard', 'globalcard')); * Actions */ -if ($cancel) -{ +if ($cancel) { header("Location: list.php"); exit; } // Link to a project -if ($action == 'classin' && $user->rights->banque->modifier) -{ +if ($action == 'classin' && $user->rights->banque->modifier) { $object->fetch($id); $object->setProject($projectid); } -if ($action == 'add' && empty($cancel)) -{ +// set label +if ($action == 'setlabel' && $user->rights->salaries->write) { + $object->fetch($id); + $object->label = $label; + $object->update($user); +} + +// Classify paid +if ($action == 'confirm_paid' && $user->rights->salaries->write && $confirm == 'yes') { + $object->fetch($id); + $result = $object->set_paid($user); +} + +if ($action == 'setfk_user' && $user->rights->salaries->write) { + $result = $object->fetch($id); + if ($result > 0) { + $object->fk_user = $fk_user; + $object->update($user); + } else { + dol_print_error($db); + exit; + } +} + +if ($action == 'reopen' && $user->rights->salaries->write) { + $result = $object->fetch($id); + if ($object->paye) { + $result = $object->set_unpaid($user); + if ($result > 0) { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); + exit(); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } +} + +// payment mode +if ($action == 'setmode' && $user->rights->salaries->write) { + $object->fetch($id); + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); + if ($result < 0) + setEventMessages($object->error, $object->errors, 'errors'); +} + +// bank account +if ($action == 'setbankaccount' && $user->rights->salaries->write) { + $object->fetch($id); + $result = $object->setBankAccount(GETPOST('fk_account', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } +} + +if ($action == 'add' && empty($cancel)) { $error = 0; if (empty($datev)) $datev = $datep; - $type_payment = dol_getIdFromCode($db, GETPOST("paymenttype", 'alpha'), 'c_paiement', 'code', 'id', 1); + $type_payment = GETPOST("paymenttype", 'alpha'); + $amount = price2num(GETPOST("amount", 'alpha'), 'MT', 2); $object->accountid = GETPOST("accountid", 'int') > 0 ? GETPOST("accountid", "int") : 0; $object->fk_user = GETPOST("fk_user", 'int') > 0 ? GETPOST("fk_user", "int") : 0; $object->datev = $datev; $object->datep = $datep; - $object->amount = price2num(GETPOST("amount", 'alpha')); + $object->amount = $amount; $object->label = GETPOST("label", 'alphanohtml'); $object->datesp = $datesp; $object->dateep = $dateep; $object->note = GETPOST("note", 'restricthtml'); $object->type_payment = ($type_payment > 0 ? $type_payment : 0); - $object->num_payment = GETPOST("num_payment", 'alphanohtml'); $object->fk_user_author = $user->id; $object->fk_project = $projectid; @@ -113,95 +177,175 @@ if ($action == 'add' && empty($cancel)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (empty($datep) || empty($datev) || empty($datesp) || empty($dateep)) - { + if (!empty($auto_create_paiement) && empty($datep)) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DATE_PAIEMENT")), null, 'errors'); + $error++; + } + if (empty($datesp) || empty($dateep)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); $error++; } - if (empty($object->fk_user) || $object->fk_user < 0) - { + if (empty($object->fk_user) || $object->fk_user < 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Employee")), null, 'errors'); $error++; } - if (empty($type_payment) || $type_payment < 0) - { + if (!empty($auto_create_paiement) && (empty($type_payment) || $type_payment < 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PaymentMode")), null, 'errors'); $error++; } - if (empty($object->amount)) - { + if (empty($object->amount)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors'); $error++; } - if (!empty($conf->banque->enabled) && !$object->accountid > 0) - { + if (!empty($conf->banque->enabled) && !empty($auto_create_paiement) && !$object->accountid > 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankAccount")), null, 'errors'); $error++; } - if (!$error) - { - $db->begin(); - + if (!$error) { $ret = $object->create($user); - if ($ret > 0) - { - $db->commit(); + if ($ret < 0) $error++; + if (!empty($auto_create_paiement) && !$error) { + $db->begin(); + // Create a line of payments + $paiement = new PaymentSalary($db); + $paiement->chid = $object->id; + $paiement->datepaye = $datep; + $paiement->datev = $datev; + $paiement->amounts = array($object->id=>$amount); // Tableau de montant + $paiement->paiementtype = $type_payment; + $paiement->num_payment = GETPOST("num_payment", 'alphanohtml'); + $paiement->note = GETPOST("note", 'none'); + if (!$error) { + $paymentid = $paiement->create($user, (int) GETPOST('closepaidsalary')); + if ($paymentid < 0) { + $error++; + setEventMessages($paiement->error, null, 'errors'); + $action = 'create'; + } + } + + if (!$error) { + $result = $paiement->addPaymentToBank($user, 'payment_salary', '(SalaryPayment)', GETPOST('accountid', 'int'), '', ''); + if (!($result > 0)) { + $error++; + setEventMessages($paiement->error, null, 'errors'); + } + } + + if (!$error) { + $db->commit(); + } else { + $db->rollback(); + } + } + + if (empty($error)) { if (GETPOST('saveandnew', 'alpha')) { setEventMessages($langs->trans("RecordSaved"), '', 'mesgs'); - header("Location: card.php?action=create&fk_project=".urlencode($projectid)."&accountid=".urlencode($accountid).'&paymenttype='.urlencode(GETPOST('paymenttype', 'az09')).'&datepday='.GETPOST("datepday", 'int').'&datepmonth='.GETPOST("datepmonth", 'int').'&datepyear='.GETPOST("datepyear", 'int')); + header("Location: card.php?action=create&fk_project=" . urlencode($projectid) . "&accountid=" . urlencode($accountid) . '&paymenttype=' . urlencode(GETPOST('paymenttype', 'az09')) . '&datepday=' . GETPOST("datepday", 'int') . '&datepmonth=' . GETPOST("datepmonth", 'int') . '&datepyear=' . GETPOST("datepyear", 'int')); exit; } else { - header("Location: list.php"); + header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $object->id); exit; } - } else { - $db->rollback(); - setEventMessages($object->error, $object->errors, 'errors'); - $action = "create"; } } $action = 'create'; } -if ($action == 'delete') -{ +if ($action == 'confirm_delete') { $result = $object->fetch($id); + $totalpaye = $object->getSommePaiement(); - if ($object->rappro == 0) - { + if (empty($totalpaye)) { $db->begin(); $ret = $object->delete($user); - if ($ret > 0) - { - if ($object->fk_bank) - { - $accountline = new AccountLine($db); - $result = $accountline->fetch($object->fk_bank); - if ($result > 0) $result = $accountline->delete($user); // $result may be 0 if not found (when bank entry was deleted manually and fk_bank point to nothing) - } - - if ($result >= 0) - { - $db->commit(); - header("Location: ".DOL_URL_ROOT.'/salaries/list.php'); - exit; - } else { - $object->error = $accountline->error; - $db->rollback(); - setEventMessages($object->error, $object->errors, 'errors'); - } + if ($ret > 0) { + $db->commit(); + header("Location: ".DOL_URL_ROOT.'/salaries/list.php'); + exit; } else { $db->rollback(); setEventMessages($object->error, $object->errors, 'errors'); } } else { - setEventMessages('Error try do delete a line linked to a conciliated bank transaction', null, 'errors'); + setEventMessages($langs->trans('DisabledBecausePayments'), null, 'errors'); + } +} + + +if ($action == 'update' && !$_POST["cancel"] && $user->rights->salaries->write) { + $amount = price2num(GETPOST('amount'), 'MT', 2); + + if (empty($amount)) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")), null, 'errors'); + $action = 'edit'; + } elseif (!is_numeric($amount)) { + setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentities("Amount")), null, 'errors'); + $action = 'create'; + } else { + $result = $object->fetch($id); + + $object->amount = price2num($amount); + $object->datesp = price2num($datesp); + $object->dateep = price2num($dateep); + + $result = $object->update($user); + if ($result <= 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } +} + +if ($action == 'confirm_clone' && $confirm != 'yes') { $action = ''; } + +if ($action == 'confirm_clone' && $confirm == 'yes' && ($user->rights->salaries->write)) { + $db->begin(); + + $originalId = $id; + + $object->fetch($id); + + if ($object->id > 0) { + $object->paye = 0; + $object->id = $object->ref = null; + + if (GETPOST('clone_label', 'alphanohtml')) { + $object->label = GETPOST('clone_label', 'alphanohtml'); + } else { + $object->label = $langs->trans("CopyOf").' '.$object->label; + } + + $newdatestart = dol_mktime(0, 0, 0, GETPOST('clone_date_startmonth', 'int'), GETPOST('clone_date_startday', 'int'), GETPOST('clone_date_startyear', 'int')); + $newdateend = dol_mktime(0, 0, 0, GETPOST('clone_date_endmonth', 'int'), GETPOST('clone_date_endday', 'int'), GETPOST('clone_date_endyear', 'int')); + + if ($newdatestart) $object->datesp = $newdatestart; + if ($newdateend) $object->dateep = $newdateend; + + $id = $object->create($user); + if ($id > 0) { + $db->commit(); + $db->close(); + + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + $id = $originalId; + $db->rollback(); + + setEventMessages($object->error, $object->errors, 'errors'); + } + } else { + $db->rollback(); + dol_print_error($db, $object->error); } } @@ -210,30 +354,26 @@ if ($action == 'delete') * View */ -llxHeader("", $langs->trans("SalaryPayment")); +llxHeader("", $langs->trans("Salary")); $form = new Form($db); if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); -if ($id) -{ - $object = new PaymentSalary($db); +if ($id) { + $object = new Salary($db); $result = $object->fetch($id); - if ($result <= 0) - { + if ($result <= 0) { dol_print_error($db); exit; } } // Create -if ($action == 'create') -{ +if ($action == 'create') { $year_current = strftime("%Y", dol_now()); $pastmonth = strftime("%m", dol_now()) - 1; $pastmonthyear = $year_current; - if ($pastmonth == 0) - { + if ($pastmonth == 0) { $pastmonth = 12; $pastmonthyear--; } @@ -247,8 +387,7 @@ if ($action == 'create') $datesp = dol_mktime(0, 0, 0, $datespmonth, $datespday, $datespyear); $dateep = dol_mktime(23, 59, 59, $dateepmonth, $dateepday, $dateepyear); - if (empty($datesp) || empty($dateep)) // We define date_start and date_end - { + if (empty($datesp) || empty($dateep)) { // We define date_start and date_end $datesp = dol_get_first_day($pastmonthyear, $pastmonth, false); $dateep = dol_get_last_day($pastmonthyear, $pastmonth, false); } @@ -256,35 +395,53 @@ if ($action == 'create') print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; - print load_fiche_titre($langs->trans("NewSalaryPayment"), '', 'salary'); + print load_fiche_titre($langs->trans("NewSalary"), '', 'salary'); + + if (!empty($conf->use_javascript_ajax)) { + print "\n".'<script type="text/javascript" language="javascript">'; + print /** @lang JavaScript */' + $(document).ready(function () { + let onAutoCreatePaiementChange = function () { + if($("#auto_create_paiement").is(":checked")) { + $("#label_fk_account").find("span").addClass("fieldrequired"); + $("#label_type_payment").find("span").addClass("fieldrequired"); + $(".hide_if_no_auto_create_payment").show(); + } else { + $("#label_fk_account").find("span").removeClass("fieldrequired"); + $("#label_type_payment").find("span").removeClass("fieldrequired"); + $(".hide_if_no_auto_create_payment").hide(); + } + }; + $("#radiopayment").click(function() { + $("#label").val($(this).data("label")); + }); + $("#radiorefund").click(function() { + $("#label").val($(this).data("label")); + }); + $("#auto_create_paiement").click(function () { + onAutoCreatePaiementChange(); + }); + onAutoCreatePaiementChange(); + }); + '; + print '</script>'."\n"; + } print dol_get_fiche_head('', ''); print '<table class="border centpercent">'; - // Date payment - print '<tr><td>'; - print $form->editfieldkey('DatePayment', 'datep', '', $object, 0, 'string', '', 1).'</td><td>'; - print $form->selectDate((empty($datep) ? '' : $datep), "datep", 0, 0, 0, 'add', 1, 1); - print '</td></tr>'; - - // Date value for bank - print '<tr><td>'; - print $form->editfieldkey('DateValue', 'datev', '', $object, 0).'</td><td>'; - print $form->selectDate((empty($datev) ?-1 : $datev), "datev", '', '', '', 'add', 1, 1); - print '</td></tr>'; - // Employee - print '<tr><td>'; + print '<tr><td class="titlefieldcreate">'; print $form->editfieldkey('Employee', 'fk_user', '', $object, 0, 'string', '', 1).'</td><td>'; $noactive = 0; // We keep active and unactive users - print $form->select_dolusers(GETPOST('fk_user', 'int'), 'fk_user', 1, '', 0, '', '', 0, 0, 0, 'AND employee=1', 0, '', 'maxwidth300', $noactive); + print img_picto('', 'user', 'class="paddingrighonly"').$form->select_dolusers(GETPOST('fk_user', 'int'), 'fk_user', 1, '', 0, '', '', 0, 0, 0, 'AND employee=1', 0, '', 'maxwidth300', $noactive); print '</td></tr>'; // Label print '<tr><td>'; print $form->editfieldkey('Label', 'label', '', $object, 0, 'string', '', 1).'</td><td>'; - print '<input name="label" id="label" class="minwidth300" value="'.(GETPOST("label") ?GETPOST("label") : $langs->trans("SalaryPayment")).'">'; + print '<input name="label" id="label" class="minwidth300" value="'.(GETPOST("label") ?GETPOST("label") : $langs->trans("Salary")).'">'; print '</td></tr>'; // Date start period @@ -302,50 +459,76 @@ if ($action == 'create') // Amount print '<tr><td>'; print $form->editfieldkey('Amount', 'amount', '', $object, 0, 'string', '', 1).'</td><td>'; - print '<input name="amount" id="amount" class="minwidth100" value="'.GETPOST("amount").'">'; + print '<input name="amount" id="amount" class="minwidth75 maxwidth100" value="'.GETPOST("amount").'">'; print '</td></tr>'; + // Project + if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); + + print '<tr><td>'.$langs->trans("Project").'</td><td>'; + $formproject->select_projects(-1, $projectid, 'fk_project', 0, 0, 1, 1); + print '</td></tr>'; + } + + // Comments + print '<tr>'; + print '<td class="tdtop">'.$langs->trans("Comments").'</td>'; + print '<td class="tdtop"><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_3.'">'.GETPOST('note', 'restricthtml').'</textarea></td>'; + print '</tr>'; + + print '<tr><td colspan="2"><hr></td></tr>'; + + // Auto create payment + print '<tr><td>'.$langs->trans('AutomaticCreationPayment').'</td>'; + print '<td><input id="auto_create_paiement" name="auto_create_paiement" type="checkbox" ' . (empty($auto_create_paiement) ? '' : 'checked="checked"') . ' value="1"></td></tr>'."\n"; // Date payment + // Bank - if (!empty($conf->banque->enabled)) - { - print '<tr><td>'; + if (!empty($conf->banque->enabled)) { + print '<tr><td id="label_fk_account">'; print $form->editfieldkey('BankAccount', 'selectaccountid', '', $object, 0, 'string', '', 1).'</td><td>'; + print img_picto('', 'bank_account', 'class="paddingrighonly"'); $form->select_comptes($accountid, "accountid", 0, '', 1); // Affiche liste des comptes courant print '</td></tr>'; } // Type payment - print '<tr><td>'; + print '<tr><td id="label_type_payment">'; print $form->editfieldkey('PaymentMode', 'selectpaymenttype', '', $object, 0, 'string', '', 1).'</td><td>'; - $form->select_types_paiements(GETPOST("paymenttype", 'aZ09'), "paymenttype", '', 2); + $form->select_types_paiements(GETPOST("paymenttype", 'aZ09'), "paymenttype", ''); + print '</td></tr>'; + + // Date payment + print '<tr class="hide_if_no_auto_create_payment"><td>'; + print $form->editfieldkey('DatePayment', 'datep', '', $object, 0, 'string', '', 1).'</td><td>'; + print $form->selectDate((empty($datep) ? '' : $datep), "datep", 0, 0, 0, 'add', 1, 1); + print '</td></tr>'; + + // Date value for bank + print '<tr class="hide_if_no_auto_create_payment"><td>'; + print $form->editfieldkey('DateValue', 'datev', '', $object, 0).'</td><td>'; + print $form->selectDate((empty($datev) ?-1 : $datev), "datev", '', '', '', 'add', 1, 1); print '</td></tr>'; // Number - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { // Number - print '<tr><td><label for="num_payment">'.$langs->trans('Numero'); + print '<tr class="hide_if_no_auto_create_payment"><td><label for="num_payment">'.$langs->trans('Numero'); print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>'; print '</label></td>'; print '<td><input name="num_payment" id="num_payment" type="text" value="'.GETPOST("num_payment").'"></td></tr>'."\n"; } - // Project - if (!empty($conf->projet->enabled)) - { - $formproject = new FormProjets($db); - - print '<tr><td>'.$langs->trans("Project").'</td><td>'; - $formproject->select_projects(-1, $projectid, 'fk_project', 0, 0, 1, 1); - print '</td></tr>'; - } + // Bouton Save payment + print '<tr class="hide_if_no_auto_create_payment"><td>'; + print $langs->trans("ClosePaidSalaryAutomatically"); + print '</td><td><input type="checkbox" checked value="1" name="closepaidsalary"></td></tr>'; // Other attributes $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } @@ -371,27 +554,92 @@ if ($action == 'create') /* */ /* ************************************************************************** */ -if ($id) -{ +if ($id) { $head = salaries_prepare_head($object); + if ($action === 'clone') { + $formquestion = array( + array('type' => 'text', 'name' => 'clone_label', 'label' => $langs->trans("Label"), 'value' => $langs->trans("CopyOf").' '.$object->label), + ); + + //$formquestion[] = array('type' => 'date', 'name' => 'clone_date_ech', 'label' => $langs->trans("Date"), 'value' => -1); + $formquestion[] = array('type' => 'date', 'name' => 'clone_date_start', 'label' => $langs->trans("DateStart"), 'value' => -1); + $formquestion[] = array('type' => 'date', 'name' => 'clone_date_end', 'label' => $langs->trans("DateEnd"), 'value' => -1); + + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneSalary', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 240); + } + + if ($action == 'paid') { + $text = $langs->trans('ConfirmPaySalary'); + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans('PaySalary'), $text, "confirm_paid", '', '', 2); + } + + if ($action == 'delete') { + $text = $langs->trans('ConfirmDeleteSalary'); + print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('DeleteSalary'), $text, 'confirm_delete', '', '', 2); + } + + if ($action == 'edit') { + print "<form name=\"charge\" action=\"".$_SERVER["PHP_SELF"]."?id=$object->id&amp;action=update\" method=\"post\">"; + print '<input type="hidden" name="token" value="'.newToken().'">'; + } + print dol_get_fiche_head($head, 'card', $langs->trans("SalaryPayment"), -1, 'salary'); $linkback = '<a href="'.DOL_URL_ROOT.'/salaries/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>'; $morehtmlref = '<div class="refidno">'; - // Employee - $userstatic = new User($db); - $userstatic->fetch($object->fk_user); - $morehtmlref .= $langs->trans('Employee').' : '.$userstatic->getNomUrl(1); + // Label + if ($action != 'editlabel') { + $morehtmlref .= $form->editfieldkey("Label", 'label', $object->label, $object, $user->rights->salaries->write, 'string', '', 0, 1); + $morehtmlref .= $object->label; + } else { + $morehtmlref .= '<br>'.$langs->trans('Label').' :&nbsp;'; + $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref .= '<input type="hidden" name="action" value="setlabel">'; + $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref .= '<input type="text" name="label" value="'.$object->label.'"/>'; + $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref .= '</form>'; + } + + //Employee + if ($action != 'editfk_user') { + if ($object->getSommePaiement() > 0 && !empty($object->fk_user)) { + $userstatic = new User($db); + $result = $userstatic->fetch($object->fk_user); + if ($result > 0) { + $morehtmlref .= '<br>' .$langs->trans('Employee').' : '.$userstatic->getNomUrl(1); + } + } else { + $morehtmlref .= '<br>' . $form->editfieldkey("Employee", 'fk_user', $object->label, $object, $user->rights->salaries->write, 'string', '', 0, 1); + + if (!empty($object->fk_user)) { + $userstatic = new User($db); + $result = $userstatic->fetch($object->fk_user); + if ($result > 0) { + $morehtmlref .= $userstatic->getNomUrl(1); + } else { + dol_print_error($db); + exit(); + } + } + } + } else { + $morehtmlref .= '<br>'.$langs->trans('Employee').' :&nbsp;'; + $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref .= '<input type="hidden" name="action" value="setfk_user">'; + $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref .= $form->select_dolusers($object->fk_user, 'userid', 1); + $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref .= '</form>'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->salaries->write) - { + if ($user->rights->salaries->write) { if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; } @@ -400,7 +648,7 @@ if ($id) $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref .= '<input type="hidden" name="action" value="classin">'; $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; - $morehtmlref .= $formproject->select_projects(0, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= $formproject->select_projects(-1, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; $morehtmlref .= '</form>'; } else { @@ -418,52 +666,92 @@ if ($id) } } } + $morehtmlref .= '</div>'; + $totalpaye = $object->getSommePaiement(); + $object->totalpaye = $totalpaye; + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', ''); print '<div class="fichecenter">'; + print '<div class="fichehalfleft">'; print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent tableforfield">'; - // Label - print '<tr><td class="titlefield">'.$langs->trans("Label").'</td><td>'.$object->label.'</td></tr>'; + if ($action == 'edit') { + print '<tr><td>'.$langs->trans("DateStartPeriod")."</td><td>"; + print $form->selectDate($object->datesp, 'datesp', 0, 0, 0, 'datesp', 1); + print "</td></tr>"; + } else { + print "<tr>"; + print '<td>' . $langs->trans("DateStartPeriod") . '</td><td>'; + print dol_print_date($object->datesp, 'day'); + print '</td></tr>'; + } - print "<tr>"; - print '<td>'.$langs->trans("DateStartPeriod").'</td><td>'; - print dol_print_date($object->datesp, 'day'); - print '</td></tr>'; + if ($action == 'edit') { + print '<tr><td>'.$langs->trans("DateEndPeriod")."</td><td>"; + print $form->selectDate($object->dateep, 'dateep', 0, 0, 0, 'dateep', 1); + print "</td></tr>"; + } else { + print "<tr>"; + print '<td>' . $langs->trans("DateEndPeriod") . '</td><td>'; + print dol_print_date($object->dateep, 'day'); + print '</td></tr>'; + } - print '<tr><td>'.$langs->trans("DateEndPeriod").'</td><td>'; - print dol_print_date($object->dateep, 'day'); - print '</td></tr>'; - - print "<tr>"; + /*print "<tr>"; print '<td>'.$langs->trans("DatePayment").'</td><td>'; print dol_print_date($object->datep, 'day'); print '</td></tr>'; print '<tr><td>'.$langs->trans("DateValue").'</td><td>'; print dol_print_date($object->datev, 'day'); + print '</td></tr>';*/ + + if ($action == 'edit') { + print '<tr><td class="fieldrequired">' . $langs->trans("Amount") . '</td><td><input name="amount" size="10" value="' . price($object->amount) . '"></td></tr>'; + } else { + print '<tr><td>' . $langs->trans("Amount") . '</td><td>' . price($object->amount, 0, $outputlangs, 1, -1, -1, $conf->currency) . '</td></tr>'; + } + + // Mode of payment + print '<tr><td>'; + print '<table class="nobordernopadding" width="100%"><tr><td>'; + print $langs->trans('PaymentMode'); + print '</td>'; + if ($action != 'editmode') + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>'; + print '</tr></table>'; + print '</td><td>'; + + if ($action == 'editmode') { + $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->type_payment, 'mode_reglement_id'); + } else { + $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->type_payment, 'none'); + } print '</td></tr>'; - print '<tr><td>'.$langs->trans("Amount").'</td><td>'.price($object->amount, 0, $outputlangs, 1, -1, -1, $conf->currency).'</td></tr>'; - - if (!empty($conf->banque->enabled)) - { - if ($object->fk_account > 0) - { - $bankline = new AccountLine($db); - $bankline->fetch($object->fk_bank); - - print '<tr>'; - print '<td>'.$langs->trans('BankTransactionLine').'</td>'; - print '<td>'; - print $bankline->getNomUrl(1, 0, 'showall'); - print '</td>'; - print '</tr>'; + // Bank Account + if (!empty($conf->banque->enabled)) { + print '<tr><td class="nowrap">'; + print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">'; + print $langs->trans('BankAccount'); + print '<td>'; + if ($action != 'editbankaccount' && $user->rights->salaries->write) { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'</a></td>'; } + print '</tr></table>'; + print '</td><td>'; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print '</td>'; + print '</tr>'; } // Other attributes @@ -473,22 +761,167 @@ if ($id) print '</div>'; + print '<div class="fichehalfright">'; + print '<div class="ficheaddleft">'; + + $nbcols = 3; + if (!empty($conf->banque->enabled)) { + $nbcols++; + } + + /* + * Payments + */ + $sql = "SELECT p.rowid, p.num_payment as num_payment, p.datep as dp, p.amount,"; + $sql .= " c.code as type_code,c.libelle as paiement_type,"; + $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.currency_code as bacurrency_code, ba.fk_accountancy_journal'; + $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as p"; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.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 c ON p.fk_typepayment = c.id"; + $sql .= ", ".MAIN_DB_PREFIX."salary as salaire"; + $sql .= " WHERE p.fk_salary = ".$id; + $sql .= " AND p.fk_salary = salaire.rowid"; + $sql .= " AND salaire.entity IN (".getEntity('tax').")"; + $sql .= " ORDER BY dp DESC"; + + //print $sql; + $resql = $db->query($sql); + if ($resql) { + $totalpaye = 0; + + $num = $db->num_rows($resql); + $i = 0; $total = 0; + + print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '<table class="noborder paymenttable">'; + print '<tr class="liste_titre">'; + print '<td>'.$langs->trans("RefPayment").'</td>'; + print '<td>'.$langs->trans("Date").'</td>'; + print '<td>'.$langs->trans("Type").'</td>'; + if (!empty($conf->banque->enabled)) { + print '<td class="liste_titre right">'.$langs->trans('BankAccount').'</td>'; + } + print '<td class="right">'.$langs->trans("Amount").'</td>'; + print '</tr>'; + + if ($num > 0) { + $bankaccountstatic = new Account($db); + while ($i < $num) { + $objp = $db->fetch_object($resql); + + print '<tr class="oddeven"><td>'; + print '<a href="'.DOL_URL_ROOT.'/salaries/payment_salary/card.php?id='.$objp->rowid.'">'.img_object($langs->trans("Payment"), "payment").' '.$objp->rowid.'</a></td>'; + print '<td>'.dol_print_date($db->jdate($objp->dp), 'day')."</td>\n"; + $labeltype = $langs->trans("PaymentType".$objp->type_code) != ("PaymentType".$objp->type_code) ? $langs->trans("PaymentType".$objp->type_code) : $objp->paiement_type; + print "<td>".$labeltype.' '.$objp->num_payment."</td>\n"; + if (!empty($conf->banque->enabled)) { + $bankaccountstatic->id = $objp->baid; + $bankaccountstatic->ref = $objp->baref; + $bankaccountstatic->label = $objp->baref; + $bankaccountstatic->number = $objp->banumber; + $bankaccountstatic->currency_code = $objp->bacurrency_code; + + if (!empty($conf->accounting->enabled)) { + $bankaccountstatic->account_number = $objp->account_number; + + $accountingjournal = new AccountingJournal($db); + $accountingjournal->fetch($objp->fk_accountancy_journal); + $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1); + } + + print '<td class="right">'; + if ($bankaccountstatic->id) + print $bankaccountstatic->getNomUrl(1, 'transactions'); + print '</td>'; + } + print '<td class="right">'.price($objp->amount)."</td>\n"; + print "</tr>"; + $totalpaye += $objp->amount; + $i++; + } + } else { + print '<tr class="oddeven"><td><span class="opacitymedium">'.$langs->trans("None").'</span></td>'; + print '<td></td><td></td><td></td><td></td>'; + print '</tr>'; + } + + print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("AlreadyPaid")." :</td><td class=\"right\">".price($totalpaye)."</td></tr>\n"; + print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("AmountExpected")." :</td><td class=\"right\">".price($object->amount)."</td></tr>\n"; + + $resteapayer = $object->amount - $totalpaye; + $cssforamountpaymentcomplete = 'amountpaymentcomplete'; + + print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("RemainderToPay")." :</td>"; + print '<td class="right'.($resteapayer ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($resteapayer)."</td></tr>\n"; + + print "</table>"; + print '</div>'; + + $db->free($resql); + } else { + dol_print_error($db); + } + + print '</div>'; + print '</div>'; + print '</div>'; + + print '<div class="clearboth"></div>'; + + + if ($action == 'edit') { + print '<div align="center">'; + print '<input type="submit" class="button" name="save" value="'.$langs->trans("Save").'">'; + print ' &nbsp; '; + print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">'; + print '</div>'; + print "</form>\n"; + } + print dol_get_fiche_end(); - // Action buttons - + /* + * Action bar + */ print '<div class="tabsAction">'."\n"; - if ($object->rappro == 0) - { - if (!empty($user->rights->salaries->delete)) - { - print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=delete&token='.newToken().'">'.$langs->trans("Delete").'</a></div>'; - } else { - print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.(dol_escape_htmltag($langs->trans("NotAllowed"))).'">'.$langs->trans("Delete").'</a></div>'; + if ($action != 'edit') { + // Reopen + if ($object->paye && $user->rights->salaries->write) { + print "<div class=\"inline-block divButAction\"><a class=\"butAction\" href=\"".dol_buildpath("/salaries/card.php", 1)."?id=$object->id&amp;action=reopen\">".$langs->trans("ReOpen")."</a></div>"; + } + + // Edit + if ($object->paye == 0 && $user->rights->salaries->write) { + print "<div class=\"inline-block divButAction\"><a class=\"butAction\" href=\"".DOL_URL_ROOT."/salaries/card.php?id=$object->id&amp;action=edit\">".$langs->trans("Modify")."</a></div>"; + } + + // Emit payment + if ($object->paye == 0 && ((price2num($object->amount) < 0 && price2num($resteapayer, 'MT') < 0) || (price2num($object->amount) > 0 && price2num($resteapayer, 'MT') > 0)) && $user->rights->salaries->write) { + print "<div class=\"inline-block divButAction\"><a class=\"butAction\" href=\"".DOL_URL_ROOT."/salaries/paiement_salary.php?id=$object->id&amp;action=create\">".$langs->trans("DoPayment")."</a></div>"; + } + + // Classify 'paid' + if ($object->paye == 0 + && ( + (round($resteapayer) <= 0 && $object->amount > 0) + || (round($resteapayer) >= 0 && $object->amount < 0) + ) + && $user->rights->salaries->write) { + print "<div class=\"inline-block divButAction\"><a class=\"butAction\" href=\"".DOL_URL_ROOT."/salaries/card.php?id=$object->id&amp;action=paid\">".$langs->trans("ClassifyPaid")."</a></div>"; + } + + // Clone + if ($user->rights->salaries->write) { + print "<div class=\"inline-block divButAction\"><a class=\"butAction\" href=\"".dol_buildpath("/salaries/card.php", 1)."?id=$object->id&amp;action=clone\">".$langs->trans("ToClone")."</a></div>"; + } + + if (!empty($user->rights->salaries->delete) && empty($totalpaye)) { + print '<div class="inline-block divButAction"><a class="butActionDelete" href="card.php?id='.$object->id.'&action=delete">'.$langs->trans("Delete").'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.(dol_escape_htmltag($langs->trans("DisabledBecausePayments"))).'">'.$langs->trans("Delete").'</a></div>'; } - } else { - print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("LinkedToAConciliatedTransaction").'">'.$langs->trans("Delete").'</a></div>'; } print "</div>"; } diff --git a/htdocs/salaries/class/paymentsalary.class.php b/htdocs/salaries/class/paymentsalary.class.php index 59cf90e72e7..dc7e310d560 100644 --- a/htdocs/salaries/class/paymentsalary.class.php +++ b/htdocs/salaries/class/paymentsalary.class.php @@ -1,6 +1,7 @@ <?php /* Copyright (C) 2011-2019 Alexandre Spangaro <aspangaro@open-dsi.fr> * Copyright (C) 2014 Juanjo Menent <jmenent@2byte.es> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,15 +20,16 @@ /** * \file htdocs/salaries/class/paymentsalary.class.php * \ingroup salaries - * \brief Class for salaries module payment + * \brief File of class to manage payment of salaries */ // Put here all includes required by your class file require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php'; /** - * Class to manage salary payments + * Class to manage payments of salaries */ class PaymentSalary extends CommonObject { @@ -44,34 +46,41 @@ class PaymentSalary extends CommonObject /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ - public $picto = 'salary'; - - public $tms; - - /** - * @var int User ID - */ - public $fk_user; - - public $datep; - public $datev; - public $amount; + public $picto = 'payment'; /** * @var int ID */ - public $fk_project; + public $fk_salary; - public $type_payment; - public $num_payment; + public $datec = ''; + public $tms = ''; + public $datep = ''; /** - * @var string salary payments label + * @deprecated + * @see $amount */ - public $label; + public $total; - public $datesp; - public $dateep; + public $amount; // Total amount of payment + public $amounts = array(); // Array of amounts + + /** + * @var int ID + */ + public $fk_typepayment; + + /** + * @var string + * @deprecated + */ + public $num_paiement; + + /** + * @var string + */ + public $num_payment; /** * @var int ID @@ -89,10 +98,11 @@ class PaymentSalary extends CommonObject public $fk_user_modif; /** - * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + * @var array */ - public $fields = array(); - + public $fields = array( + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'), + ); /** * Constructor @@ -102,127 +112,141 @@ class PaymentSalary extends CommonObject public function __construct($db) { $this->db = $db; - $this->element = 'payment_salary'; - $this->table_element = 'payment_salary'; } /** - * Update database + * Create payment of salary into database. + * Use this->amounts to have list of lines for the payment * - * @param User $user User that modify - * @param int $notrigger 0=no, 1=yes (no update trigger) - * @return int <0 if KO, >0 if OK + * @param User $user User making payment + * @param int $closepaidcontrib 1=Also close payed contributions to paid, 0=Do nothing more + * @return int <0 if KO, id of payment if OK */ - public function update($user = null, $notrigger = 0) + public function create($user, $closepaidcontrib = 0) { global $conf, $langs; $error = 0; - // Clean parameters - $this->amount = trim($this->amount); - $this->label = trim($this->label); - $this->note = trim($this->note); + $now = dol_now(); - // Check parameters - if (empty($this->fk_user) || $this->fk_user < 0) { - $this->error = 'ErrorBadParameter'; + dol_syslog(get_class($this)."::create", LOG_DEBUG); + + // Validate parametres + if (!$this->datepaye) { + $this->error = 'ErrorBadValueForParameterCreatePaymentSalary'; return -1; } + // Clean parameters + if (isset($this->fk_salary)) $this->fk_salary = (int) $this->fk_salary; + if (isset($this->amount)) $this->amount = trim($this->amount); + if (isset($this->fk_typepayment)) $this->fk_typepayment = (int) $this->fk_typepayment; + if (isset($this->num_paiement)) $this->num_paiement = trim($this->num_paiement); // deprecated + if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); + if (isset($this->note)) $this->note = trim($this->note); + if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; + if (isset($this->fk_user_author)) $this->fk_user_author = (int) $this->fk_user_author; + if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + + $totalamount = 0; + foreach ($this->amounts as $key => $value) { // How payment is dispatch + $newvalue = price2num($value, 'MT'); + $this->amounts[$key] = $newvalue; + $totalamount += $newvalue; + } + $totalamount = price2num($totalamount); + + // Check parameters + if ($totalamount == 0) return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null + + $this->db->begin(); - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."payment_salary SET"; + if ($totalamount != 0) { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_salary (fk_salary, datec, datep, amount,"; + $sql .= " fk_typepayment, num_payment, note, fk_user_author, fk_bank)"; + $sql .= " VALUES ($this->chid, '".$this->db->idate($now)."',"; + $sql .= " '".$this->db->idate($this->datepaye)."',"; + $sql .= " ".$totalamount.","; + $sql .= " ".$this->paiementtype.", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note)."', ".$user->id.","; + $sql .= " 0)"; - $sql .= " tms='".$this->db->idate($this->tms)."',"; - $sql .= " fk_user=".$this->fk_user.","; - $sql .= " datep='".$this->db->idate($this->datep)."',"; - $sql .= " datev='".$this->db->idate($this->datev)."',"; - $sql .= " amount=".price2num($this->amount).","; - $sql .= " fk_projet=".((int) $this->fk_project).","; - $sql .= " fk_typepayment=".$this->fk_typepayment."',"; - $sql .= " num_payment='".$this->db->escape($this->num_payment)."',"; - $sql .= " label='".$this->db->escape($this->label)."',"; - $sql .= " datesp='".$this->db->idate($this->datesp)."',"; - $sql .= " dateep='".$this->db->idate($this->dateep)."',"; - $sql .= " note='".$this->db->escape($this->note)."',"; - $sql .= " fk_bank=".($this->fk_bank > 0 ? (int) $this->fk_bank : "null").","; - $sql .= " fk_user_author=".((int) $this->fk_user_author).","; - $sql .= " fk_user_modif=".($this->fk_user_modif > 0 ? (int) $this->fk_user_modif : 'null'); + $resql = $this->db->query($sql); + if ($resql) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_salary"); - $sql .= " WHERE rowid=".$this->id; + // Insere tableau des montants / factures + foreach ($this->amounts as $key => $amount) { + $contribid = $key; + if (is_numeric($amount) && $amount <> 0) { + $amount = price2num($amount); - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - - // Update extrafield - if (!$error) { - $result = $this->insertExtraFields(); - if ($result < 0) { + // If we want to closed payed invoices + if ($closepaidcontrib) { + $contrib = new Salary($this->db); + $contrib->fetch($contribid); + $paiement = $contrib->getSommePaiement(); + //$creditnotes=$contrib->getSumCreditNotesUsed(); + $creditnotes = 0; + //$deposits=$contrib->getSumDepositsUsed(); + $deposits = 0; + $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT'); + $remaintopay = price2num($contrib->amount - $paiement - $creditnotes - $deposits, 'MT'); + if ($remaintopay == 0) { + $result = $contrib->set_paid($user); + } else dol_syslog("Remain to pay for conrib ".$contribid." not null. We do nothing."); + } + } + } + } else { $error++; } } - if (!$notrigger) { - // Call trigger - $result = $this->call_trigger('PAYMENT_SALARY_MODIFY', $user); - if ($result < 0) { - $error++; - } - // End call triggers - } + $result = $this->call_trigger('PAYMENTSALARY_CREATE', $user); + if ($result < 0) $error++; - if (!$error) { + if ($totalamount != 0 && !$error) { + $this->amount = $totalamount; + $this->total = $totalamount; // deprecated $this->db->commit(); - return 1; + return $this->id; } else { + $this->error = $this->db->error(); $this->db->rollback(); return -1; } } - /** * Load object in memory from database * - * @param int $id id object - * @param User $user User that load + * @param int $id Id object * @return int <0 if KO, >0 if OK */ - public function fetch($id, $user = null) + public function fetch($id) { global $langs; - $sql = "SELECT"; - $sql .= " s.rowid,"; - - $sql .= " s.tms,"; - $sql .= " s.fk_user,"; - $sql .= " s.datep,"; - $sql .= " s.datev,"; - $sql .= " s.amount,"; - $sql .= " s.fk_projet as fk_project,"; - $sql .= " s.fk_typepayment,"; - $sql .= " s.num_payment,"; - $sql .= " s.label,"; - $sql .= " s.datesp,"; - $sql .= " s.dateep,"; - $sql .= " s.note,"; - $sql .= " s.fk_bank,"; - $sql .= " s.fk_user_author,"; - $sql .= " s.fk_user_modif,"; - $sql .= " b.fk_account,"; - $sql .= " b.fk_type,"; - $sql .= " b.rappro"; - - $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 .= " WHERE s.rowid = ".$id; + $sql .= " t.rowid,"; + $sql .= " t.fk_salary,"; + $sql .= " t.datec,"; + $sql .= " t.tms,"; + $sql .= " t.datep,"; + $sql .= " t.amount,"; + $sql .= " t.fk_typepayment,"; + $sql .= " t.num_payment as num_payment,"; + $sql .= " t.note,"; + $sql .= " t.fk_bank,"; + $sql .= " t.fk_user_author,"; + $sql .= " t.fk_user_modif,"; + $sql .= " pt.code as type_code, pt.libelle as type_label,"; + $sql .= ' b.fk_account'; + $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as t LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id"; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; + $sql .= " WHERE t.rowid = ".((int) $id); + // TODO link on entity of tax; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -230,30 +254,27 @@ class PaymentSalary extends CommonObject if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->ref = $obj->rowid; + $this->id = $obj->rowid; + $this->ref = $obj->rowid; + + $this->fk_salary = $obj->fk_salary; + $this->datec = $this->db->jdate($obj->datec); $this->tms = $this->db->jdate($obj->tms); - $this->fk_user = $obj->fk_user; $this->datep = $this->db->jdate($obj->datep); - $this->datev = $this->db->jdate($obj->datev); $this->amount = $obj->amount; - $this->fk_project = $obj->fk_project; - $this->type_payement = $obj->fk_typepayment; + $this->fk_typepayment = $obj->fk_typepayment; + $this->num_paiement = $obj->num_payment; $this->num_payment = $obj->num_payment; - $this->label = $obj->label; - $this->datesp = $this->db->jdate($obj->datesp); - $this->dateep = $this->db->jdate($obj->dateep); $this->note = $obj->note; $this->fk_bank = $obj->fk_bank; $this->fk_user_author = $obj->fk_user_author; $this->fk_user_modif = $obj->fk_user_modif; - $this->fk_account = $obj->fk_account; - $this->fk_type = $obj->fk_type; - $this->rappro = $obj->rappro; - // Retrieve all extrafield - // fetch optionals attributes and labels - $this->fetch_optionals(); + $this->type_code = $obj->type_code; + $this->type_label = $obj->type_label; + + $this->bank_account = $obj->fk_account; + $this->bank_line = $obj->fk_bank; } $this->db->free($resql); @@ -266,47 +287,162 @@ class PaymentSalary extends CommonObject /** - * Delete object in database + * Update database * - * @param User $user User that delete - * @return int <0 if KO, >0 if OK + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK */ - public function delete($user) + public function update($user = null, $notrigger = 0) { global $conf, $langs; - $error = 0; - // Call trigger - $result = $this->call_trigger('PAYMENT_SALARY_DELETE', $user); - if ($result < 0) { - return -1; + // Clean parameters + + if (isset($this->fk_salary)) $this->fk_salary = (int) $this->fk_salary; + if (isset($this->amount)) $this->amount = trim($this->amount); + if (isset($this->fk_typepayment)) $this->fk_typepayment = (int) $this->fk_typepayment; + if (isset($this->num_paiement)) $this->num_paiement = trim($this->num_paiement); // deprecated + if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); + if (isset($this->note)) $this->note = trim($this->note); + if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; + if (isset($this->fk_user_author)) $this->fk_user_author = (int) $this->fk_user_author; + if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + + // Check parameters + // Put here code to add control on parameters values + + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."payment_salary SET"; + $sql .= " fk_salary=".(isset($this->fk_salary) ? $this->fk_salary : "null").","; + $sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').","; + $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; + $sql .= " datep=".(dol_strlen($this->datep) != 0 ? "'".$this->db->idate($this->datep)."'" : 'null').","; + $sql .= " amount=".(isset($this->amount) ? $this->amount : "null").","; + $sql .= " fk_typepayment=".(isset($this->fk_typepayment) ? $this->fk_typepayment : "null").","; + $sql .= " num_payment=".(isset($this->num_payment) ? "'".$this->db->escape($this->num_payment)."'" : "null").","; + $sql .= " note=".(isset($this->note) ? "'".$this->db->escape($this->note)."'" : "null").","; + $sql .= " fk_bank=".(isset($this->fk_bank) ? $this->fk_bank : "null").","; + $sql .= " fk_user_author=".(isset($this->fk_user_author) ? $this->fk_user_author : "null").","; + $sql .= " fk_user_modif=".(isset($this->fk_user_modif) ? $this->fk_user_modif : "null").""; + $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(); } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; } - // End call triggers + } - // Delete donation - if (!$error) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_salary_extrafields"; - $sql .= " WHERE fk_object=".$this->id; - $resql = $this->db->query($sql); - if (!$resql) { - $this->errors[] = $this->db->lasterror(); + /** + * Delete object in database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + dol_syslog(get_class($this)."::delete"); + + $this->db->begin(); + + if ($this->bank_line > 0) { + $accline = new AccountLine($this->db); + $accline->fetch($this->bank_line); + $result = $accline->delete(); + if ($result < 0) { + $this->errors[] = $accline->error; $error++; } } - $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_salary"; - $sql .= " WHERE rowid=".$this->id; + if (!$error) { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_salary"; + $sql .= " WHERE rowid=".((int) $this->id); - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { - $this->error = "Error ".$this->db->lasterror(); - return -1; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } } - return 1; + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; + } + } + + + + /** + * Load an object from its id and create a new one in database + * + * @param User $user User making the clone + * @param int $fromid Id of object to clone + * @return int New id of clone + */ + public function createFromClone(User $user, $fromid) + { + $error = 0; + + $object = new PaymentSalary($this->db); + + $this->db->begin(); + + // Load source object + $object->fetch($fromid); + $object->id = 0; + $object->statut = 0; + + // Clear fields + // ... + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->create($user); + + // Other options + if ($result < 0) { + $this->error = $object->error; + $error++; + } + + unset($object->context['createfromclone']); + + // End + if (!$error) { + $this->db->commit(); + return $object->id; + } else { + $this->db->rollback(); + return -1; + } } @@ -321,354 +457,128 @@ class PaymentSalary extends CommonObject { $this->id = 0; + $this->fk_salary = ''; + $this->datec = ''; $this->tms = ''; - $this->fk_user = 1; $this->datep = ''; - $this->datev = ''; $this->amount = ''; - $this->label = ''; - $this->datesp = ''; - $this->dateep = ''; - $this->note = ''; + $this->fk_typepayment = ''; + $this->num_payment = ''; + $this->note_private = ''; + $this->note_public = ''; $this->fk_bank = ''; - $this->fk_user_author = 1; - $this->fk_user_modif = 1; + $this->fk_user_author = ''; + $this->fk_user_modif = ''; } + /** - * Create in database + * Add record into bank for payment with links between this bank record and invoices of payment. + * All payment properties must have been set first like after a call to create(). * - * @param User $user User that create - * @return int <0 if KO, >0 if OK + * @param User $user Object of user making payment + * @param string $mode 'payment_sc' + * @param string $label Label to use in bank record + * @param int $accountid Id of bank account to do link with + * @param string $emetteur_nom Name of transmitter + * @param string $emetteur_banque Name of bank + * @return int <0 if KO, >0 if OK */ - public function create($user) + public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque) { - global $conf, $langs; + global $conf; + + // Clean data + $this->num_payment = trim($this->num_payment ? $this->num_payment : $this->num_paiement); $error = 0; - $now = dol_now(); - // Clean parameters - $this->amount = price2num(trim($this->amount)); - $this->label = trim($this->label); - $this->note = trim($this->note); - $this->fk_bank = (int) $this->fk_bank; - $this->fk_user_author = (int) $this->fk_user_author; - $this->fk_user_modif = (int) $this->fk_user_modif; + if (!empty($conf->banque->enabled)) { + include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - // Check parameters - if (!$this->label) { - $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")); - return -3; - } - if ($this->fk_user <= 0 || $this->fk_user == '') { - $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Employee")); - return -4; - } - if ($this->amount < 0 || $this->amount == '') { - $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); - return -5; - } - if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) { - $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Account")); - return -6; - } - if (!empty($conf->banque->enabled) && (empty($this->type_payment) || $this->type_payment <= 0)) { - $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); - return -7; - } + $acc = new Account($this->db); + $acc->fetch($accountid); - $this->db->begin(); + $total = $this->amount; - // Insert into llx_payment_salary - $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_salary (fk_user"; - $sql .= ", datep"; - $sql .= ", datev"; - $sql .= ", amount"; - $sql .= ", fk_projet"; - $sql .= ", salary"; - $sql .= ", fk_typepayment"; - $sql .= ", num_payment"; - if ($this->note) { - $sql .= ", note"; - } - $sql .= ", label"; - $sql .= ", datesp"; - $sql .= ", dateep"; - $sql .= ", fk_user_author"; - $sql .= ", datec"; - $sql .= ", fk_bank"; - $sql .= ", entity"; - $sql .= ") "; - $sql .= " VALUES ("; - $sql .= "'".$this->db->escape($this->fk_user)."'"; - $sql .= ", '".$this->db->idate($this->datep)."'"; - $sql .= ", '".$this->db->idate($this->datev)."'"; - $sql .= ", ".$this->amount; - $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : 0); - $sql .= ", ".($this->salary > 0 ? $this->salary : "null"); - $sql .= ", ".$this->db->escape($this->type_payment); - $sql .= ", '".$this->db->escape($this->num_payment)."'"; - if ($this->note) { - $sql .= ", '".$this->db->escape($this->note)."'"; - } - $sql .= ", '".$this->db->escape($this->label)."'"; - $sql .= ", '".$this->db->idate($this->datesp)."'"; - $sql .= ", '".$this->db->idate($this->dateep)."'"; - $sql .= ", '".$this->db->escape($user->id)."'"; - $sql .= ", '".$this->db->idate($now)."'"; - $sql .= ", NULL"; - $sql .= ", ".$conf->entity; - $sql .= ")"; + // Insert payment into llx_bank + $bank_line_id = $acc->addline( + $this->datepaye, + $this->paiementtype, // Payment mode id or code ("CHQ or VIR for example") + $label, + -$total, + $this->num_payment, + '', + $user, + $emetteur_nom, + $emetteur_banque, + '', + $this->datev + ); - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_salary"); + // Mise a jour fk_bank dans llx_paiement. + // On connait ainsi le paiement qui a genere l'ecriture bancaire + if ($bank_line_id > 0) { + $result = $this->update_fk_bank($bank_line_id); + if ($result <= 0) { + $error++; + dol_print_error($this->db); + } - if ($this->id > 0) { - if (!empty($conf->banque->enabled) && !empty($this->amount)) { - // Insert into llx_bank - require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - - $acc = new Account($this->db); - $result = $acc->fetch($this->accountid); + // Add link 'payment', 'payment_supplier', 'payment_sc' in bank_url between payment and bank transaction + $url = ''; + if ($mode == 'payment_salary') $url = DOL_URL_ROOT.'/salaries/payment_salary/card.php?id='; + if ($url) { + $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); if ($result <= 0) { + $error++; dol_print_error($this->db); } - - // Update extrafield - if (!$error) { - $result = $this->insertExtraFields(); - if ($result < 0) { - $error++; - } - } - - // Insert payment into llx_bank - // Add link 'payment_salary' in bank_url between payment and bank transaction - $bank_line_id = $acc->addline( - $this->datep, - $this->type_payment, - $this->label, - -abs($this->amount), - $this->num_payment, - '', - $user, - '', - '', - '', - $this->datev - ); - - // Update fk_bank into llx_paiement. - // So we know the payment which has generate the banking ecriture - if ($bank_line_id > 0) { - $this->update_fk_bank($bank_line_id); - } else { - $this->error = $acc->error; - $error++; - } - - if (!$error) { - // Add link 'payment_salary' in bank_url between payment and bank transaction - $url = DOL_URL_ROOT.'/salaries/card.php?id='; - - $result = $acc->add_url_line($bank_line_id, $this->id, $url, "(SalaryPayment)", "payment_salary"); - if ($result <= 0) { - $this->error = $acc->error; - $error++; - } - } - - $fuser = new User($this->db); - $fuser->fetch($this->fk_user); - - // Add link 'user' in bank_url between operation and bank transaction - $result = $acc->add_url_line( - $bank_line_id, - $this->fk_user, - DOL_URL_ROOT.'/user/card.php?id=', - $fuser->getFullName($langs), - // $langs->trans("SalaryPayment").' '.$fuser->getFullName($langs).' '.dol_print_date($this->datesp,'dayrfc').' '.dol_print_date($this->dateep,'dayrfc'), - 'user' - ); - - if ($result <= 0) { - $this->error = $acc->error; - $error++; - } } - // Call trigger - $result = $this->call_trigger('PAYMENT_SALARY_CREATE', $user); - if ($result < 0) { - $error++; + // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment) + $linkaddedforthirdparty = array(); + foreach ($this->amounts as $key => $value) { + if ($mode == 'payment_salary') { + $salary = new Salary($this->db); + $salary->fetch($key); + $result = $acc->add_url_line($bank_line_id, $salary->id, DOL_URL_ROOT.'/salaries/card.php?id=', '('.$salary->label.')', 'salary'); + if ($result <= 0) dol_print_error($this->db); + } } - // End call triggers } else { + $this->error = $acc->error; $error++; } + } - if (!$error) { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -2; - } + if (!$error) { + return 1; } else { - $this->error = $this->db->error(); - $this->db->rollback(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Update link between payment salary and line generate into llx_bank + * Mise a jour du lien entre le paiement de salaire et la ligne dans llx_bank generee * - * @param int $id_bank Id bank account - * @return int <0 if KO, >0 if OK + * @param int $id_bank Id if bank + * @return int >0 if OK, <=0 if KO */ public function update_fk_bank($id_bank) { - // phpcs:enable - $sql = 'UPDATE '.MAIN_DB_PREFIX.'payment_salary SET fk_bank = '.$id_bank; - $sql .= ' WHERE rowid = '.$this->id; + // phpcs:enable + $sql = "UPDATE ".MAIN_DB_PREFIX."payment_salary SET fk_bank = ".$id_bank." WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::update_fk_bank", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { return 1; } else { - dol_print_error($this->db); - return -1; - } - } - - - /** - * Send name clicable (with possibly the picto) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param string $option link option - * @param int $notooltip 1=Disable tooltip - * @param string $morecss Add more css on link - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string Chaine with URL - */ - public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) - { - global $db, $conf, $langs, $hookmanager; - - if (!empty($conf->dol_no_mouse_hover)) { - $notooltip = 1; // Force disable tooltips - } - - $result = ''; - - $label = img_picto('', $this->picto).' <u>'.$langs->trans("SalaryPayment").'</u>'; - $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref; - if (!empty($this->label)) { - $labeltoshow = $this->label; - $reg = array(); - if (preg_match('/^\((.*)\)$/i', $this->label, $reg)) { - // Label generique car entre parentheses. On l'affiche en le traduisant - if ($reg[1] == 'paiement') { - $reg[1] = 'Payment'; - } - $labeltoshow = $langs->trans($reg[1]); - } - $label .= '<br><b>'.$langs->trans('Label').':</b> '.$labeltoshow; - } - - $url = DOL_URL_ROOT.'/salaries/card.php?id='.$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'; - } - } - - $linkclose = ''; - if (empty($notooltip)) { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label = $langs->trans("ShowMyObject"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - - /* - $hookmanager->initHooks(array('myobjectdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ - } else { - $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); - } - - $linkstart = '<a href="'.$url.'"'; - $linkstart .= $linkclose.'>'; - $linkend = '</a>'; - - $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 .= $this->ref; - } - $result .= $linkend; - //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); - - global $action, $hookmanager; - $hookmanager->initHooks(array('salarypayment')); - $parameters = array('id'=>$this->id, 'getnomurl'=>$result); - $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) { - $result = $hookmanager->resPrint; - } else { - $result .= $hookmanager->resPrint; - } - - return $result; - } - - /** - * Information on record - * - * @param int $id Id of record - * @return void - */ - public function info($id) - { - $sql = 'SELECT ps.rowid, ps.datec, ps.fk_user_author'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'payment_salary as ps'; - $sql .= ' WHERE ps.rowid = '.$id; - - dol_syslog(get_class($this).'::info', LOG_DEBUG); - $result = $this->db->query($sql); - - if ($result) { - if ($this->db->num_rows($result)) { - $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; - if ($obj->fk_user_author) { - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; - } - $this->date_creation = $this->db->jdate($obj->datec); - } - $this->db->free($result); - } else { - dol_print_error($this->db); + $this->error = $this->db->error(); + return 0; } } @@ -684,7 +594,7 @@ class PaymentSalary extends CommonObject return $this->LibStatut($this->statut, $mode); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Renvoi le libelle d'un statut donne * @@ -694,45 +604,88 @@ class PaymentSalary extends CommonObject */ public function LibStatut($status, $mode = 0) { - // phpcs:enable + // phpcs:enable global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage $langs->load('compta'); /*if ($mode == 0) - { + { if ($status == 0) return $langs->trans('ToValidate'); if ($status == 1) return $langs->trans('Validated'); - } - if ($mode == 1) - { + } + if ($mode == 1) + { if ($status == 0) return $langs->trans('ToValidate'); if ($status == 1) return $langs->trans('Validated'); - } - if ($mode == 2) - { + } + if ($mode == 2) + { if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate'); if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated'); - } - if ($mode == 3) - { + } + if ($mode == 3) + { if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1'); if ($status == 1) return img_picto($langs->trans('Validated'),'statut4'); - } - if ($mode == 4) - { + } + if ($mode == 4) + { if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate'); if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated'); - } - if ($mode == 5) - { + } + if ($mode == 5) + { if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1'); if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4'); - } - if ($mode == 6) - { + } + if ($mode == 6) + { if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1'); if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4'); - }*/ + }*/ return ''; } + + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $maxlen Longueur max libelle + * @return string Chaine avec URL + */ + public function getNomUrl($withpicto = 0, $maxlen = 0) + { + global $langs; + + $result = ''; + + if (empty($this->ref)) $this->ref = $this->lib; + + $label = img_picto('', $this->picto).' <u>'.$langs->trans("SalaryPayment").'</u>'; + $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref; + if (!empty($this->label)) { + $labeltoshow = $this->label; + $reg = array(); + if (preg_match('/^\((.*)\)$/i', $this->label, $reg)) { + // Label generique car entre parentheses. On l'affiche en le traduisant + if ($reg[1] == 'paiement') $reg[1] = 'Payment'; + $labeltoshow = $langs->trans($reg[1]); + } + $label .= '<br><b>'.$langs->trans('Label').':</b> '.$labeltoshow; + } + if ($this->datep) { + $label .= '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->datep, 'day'); + } + + if (!empty($this->id)) { + $link = '<a href="'.DOL_URL_ROOT.'/salaries/payment_salary/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; + $linkend = '</a>'; + + if ($withpicto) $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); + if ($withpicto && $withpicto != 2) $result .= ' '; + if ($withpicto != 2) $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + } + + return $result; + } } diff --git a/htdocs/salaries/class/salariesstats.class.php b/htdocs/salaries/class/salariesstats.class.php index 0fcef8682a8..123dc044a4a 100644 --- a/htdocs/salaries/class/salariesstats.class.php +++ b/htdocs/salaries/class/salariesstats.class.php @@ -1,6 +1,7 @@ <?php /* Copyright (C) 2018 Alexandre Spangaro <aspangaro@open-dsi.fr> * Copyright (c) 2018 Fidesio <contact@fidesio.com> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -61,12 +62,15 @@ class SalariesStats extends Stats $this->from = MAIN_DB_PREFIX.$object->table_element; $this->field = 'amount'; - $this->where .= " entity = ".$conf->entity; - if ($this->socid) { + $this->where = " entity = ".$conf->entity; + if ($this->socid > 0) { $this->where .= " AND fk_soc = ".$this->socid; } - if (is_array($this->userid) && count($this->userid) > 0) $this->where .= ' AND fk_user IN ('.join(',', $this->userid).')'; - elseif ($this->userid > 0) $this->where .= ' AND fk_user = '.$this->userid; + if (is_array($this->userid) && count($this->userid) > 0) { + $this->where .= ' AND fk_user IN ('.join(',', $this->userid).')'; + } elseif ($this->userid > 0) { + $this->where .= ' AND fk_user = '.$this->userid; + } } @@ -79,8 +83,8 @@ class SalariesStats extends Stats { $sql = "SELECT YEAR(datep) as dm, count(*)"; $sql .= " FROM ".$this->from; - $sql .= " GROUP BY dm DESC"; $sql .= " WHERE ".$this->where; + $sql .= " GROUP BY dm DESC"; return $this->_getNbByYear($sql); } @@ -103,7 +107,7 @@ class SalariesStats extends Stats $sql .= $this->db->order('dm', 'DESC'); $res = $this->_getNbByMonth($year, $sql, $format); - //var_dump($res);print '<br>'; + return $res; } @@ -125,7 +129,6 @@ class SalariesStats extends Stats $sql .= $this->db->order('dm', 'DESC'); $res = $this->_getAmountByMonth($year, $sql, $format); - //var_dump($res);print '<br>'; return $res; } diff --git a/htdocs/salaries/class/salary.class.php b/htdocs/salaries/class/salary.class.php new file mode 100644 index 00000000000..fdd1bfd7f73 --- /dev/null +++ b/htdocs/salaries/class/salary.class.php @@ -0,0 +1,697 @@ +<?php +/* Copyright (C) 2011-2019 Alexandre Spangaro <aspangaro@open-dsi.fr> + * Copyright (C) 2014 Juanjo Menent <jmenent@2byte.es> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * 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 <https://www.gnu.org/licenses/>. + */ + +/** + * \file htdocs/salaries/class/salary.class.php + * \ingroup salaries + * \brief Class for salaries module payment + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; + + +/** + * Class to manage salary payments + */ +class Salary extends CommonObject +{ + /** + * @var string ID to identify managed object + */ + public $element = 'salary'; + + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'salary'; + + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'salary'; + + public $tms; + + /** + * @var int User ID + */ + public $fk_user; + + public $datep; + public $datev; + public $amount; + + /** + * @var int ID + */ + public $fk_project; + + public $type_payment; + + /** + * @var string salary payments label + */ + public $label; + + public $datesp; + public $dateep; + + /** + * @var int ID + */ + public $fk_bank; + + /** + * @var int ID + */ + public $fk_user_author; + + /** + * @var int ID + */ + public $fk_user_modif; + + const STATUS_UNPAID = 0; + const STATUS_PAID = 1; + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + $this->element = 'salary'; + $this->table_element = 'salary'; + } + + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=no, 1=yes (no update trigger) + * @return int <0 if KO, >0 if OK + */ + public function update($user = null, $notrigger = 0) + { + global $conf, $langs; + + $error = 0; + + // Clean parameters + $this->amount = trim($this->amount); + $this->label = trim($this->label); + $this->note = trim($this->note); + + // Check parameters + if (empty($this->fk_user) || $this->fk_user < 0) { + $this->error = 'ErrorBadParameter'; + return -1; + } + + $this->db->begin(); + + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."salary SET"; + + $sql .= " tms='".$this->db->idate(dol_now())."',"; + $sql .= " fk_user=".$this->fk_user.","; + /*$sql .= " datep='".$this->db->idate($this->datep)."',"; + $sql .= " datev='".$this->db->idate($this->datev)."',";*/ + $sql .= " amount=".price2num($this->amount).","; + $sql .= " fk_projet=".((int) $this->fk_project).","; + $sql .= " fk_typepayment=".$this->type_payment.","; + $sql .= " label='".$this->db->escape($this->label)."',"; + $sql .= " datesp='".$this->db->idate($this->datesp)."',"; + $sql .= " dateep='".$this->db->idate($this->dateep)."',"; + $sql .= " note='".$this->db->escape($this->note)."',"; + $sql .= " fk_bank=".($this->fk_bank > 0 ? (int) $this->fk_bank : "null").","; + $sql .= " fk_user_author=".((int) $this->fk_user_author).","; + $sql .= " fk_user_modif=".($this->fk_user_modif > 0 ? (int) $this->fk_user_modif : 'null'); + + $sql .= " WHERE rowid=".((int) $this->id); + + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + + // Update extrafield + if (!$error) { + if (!$error) { + $result = $this->insertExtraFields(); + if ($result < 0) { + $error++; + } + } + } + + if (!$notrigger) { + // Call trigger + $result = $this->call_trigger('salary_MODIFY', $user); + if ($result < 0) $error++; + // End call triggers + } + + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } + + + /** + * Load object in memory from database + * + * @param int $id id object + * @param User $user User that load + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $user = null) + { + global $langs; + $sql = "SELECT"; + $sql .= " s.rowid,"; + + $sql .= " s.tms,"; + $sql .= " s.fk_user,"; + $sql .= " s.datep,"; + $sql .= " s.datev,"; + $sql .= " s.amount,"; + $sql .= " s.fk_projet as fk_project,"; + $sql .= " s.fk_typepayment,"; + $sql .= " s.label,"; + $sql .= " s.datesp,"; + $sql .= " s.dateep,"; + $sql .= " s.note,"; + $sql .= " s.paye,"; + $sql .= " s.fk_bank,"; + $sql .= " s.fk_user_author,"; + $sql .= " s.fk_user_modif,"; + $sql .= " s.fk_account"; + /*$sql .= " b.fk_type,"; + $sql .= " b.rappro";*/ + + $sql .= " FROM ".MAIN_DB_PREFIX."salary as s"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; + $sql .= " WHERE s.rowid = ".((int) $id); + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->ref = $obj->rowid; + $this->tms = $this->db->jdate($obj->tms); + $this->fk_user = $obj->fk_user; + $this->datep = $this->db->jdate($obj->datep); + $this->datev = $this->db->jdate($obj->datev); + $this->amount = $obj->amount; + $this->fk_project = $obj->fk_project; + $this->type_payment = $obj->fk_typepayment; + $this->label = $obj->label; + $this->datesp = $this->db->jdate($obj->datesp); + $this->dateep = $this->db->jdate($obj->dateep); + $this->note = $obj->note; + $this->paye = $obj->paye; + $this->fk_bank = $obj->fk_bank; + $this->fk_user_author = $obj->fk_user_author; + $this->fk_user_modif = $obj->fk_user_modif; + $this->fk_account = $this->accountid = $obj->fk_account; + $this->fk_type = $obj->fk_type; + $this->rappro = $obj->rappro; + + // Retreive all extrafield + // fetch optionals attributes and labels + $this->fetch_optionals(); + } + $this->db->free($resql); + + return 1; + } else { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } + + + /** + * Delete object in database + * + * @param User $user User that delete + * @return int <0 if KO, >0 if OK + */ + public function delete($user) + { + global $conf, $langs; + + $error = 0; + + // Call trigger + $result = $this->call_trigger('salary_DELETE', $user); + if ($result < 0) return -1; + // End call triggers + + // Delete extrafields + /*if (!$error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."salary_extrafields"; + $sql .= " WHERE fk_object=".$this->id; + + $resql = $this->db->query($sql); + if (!$resql) + { + $this->errors[] = $this->db->lasterror(); + $error++; + } + }*/ + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."salary"; + $sql .= " WHERE rowid=".((int) $this->id); + + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + + return 1; + } + + + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + public function initAsSpecimen() + { + $this->id = 0; + + $this->tms = ''; + $this->fk_user = ''; + $this->datep = ''; + $this->datev = ''; + $this->amount = ''; + $this->label = ''; + $this->datesp = ''; + $this->dateep = ''; + $this->note = ''; + $this->fk_bank = ''; + $this->fk_user_author = ''; + $this->fk_user_modif = ''; + } + + /** + * Create in database + * + * @param User $user User that create + * @return int <0 if KO, >0 if OK + */ + public function create($user) + { + global $conf, $langs; + + $error = 0; + $now = dol_now(); + + // Clean parameters + $this->amount = price2num(trim($this->amount)); + $this->label = trim($this->label); + $this->note = trim($this->note); + $this->fk_bank = trim($this->fk_bank); + $this->fk_user_author = trim($this->fk_user_author); + $this->fk_user_modif = trim($this->fk_user_modif); + $this->accountid = trim($this->accountid); + $this->paye = trim($this->paye); + + // Check parameters + if (!$this->label) { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")); + return -3; + } + if ($this->fk_user < 0 || $this->fk_user == '') { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Employee")); + return -4; + } + if ($this->amount < 0 || $this->amount == '') { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); + return -5; + } + /* if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) + { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Account")); + return -6; + } + if (!empty($conf->banque->enabled) && (empty($this->type_payment) || $this->type_payment <= 0)) + { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); + return -7; + }*/ + + $this->db->begin(); + + // Insert into llx_salary + $sql = "INSERT INTO ".MAIN_DB_PREFIX."salary (fk_user"; + //$sql .= ", datep"; + //$sql .= ", datev"; + $sql .= ", amount"; + $sql .= ", fk_projet"; + $sql .= ", salary"; + $sql .= ", fk_typepayment"; + $sql .= ", fk_account"; + if ($this->note) $sql .= ", note"; + $sql .= ", label"; + $sql .= ", datesp"; + $sql .= ", dateep"; + $sql .= ", fk_user_author"; + $sql .= ", datec"; + $sql .= ", fk_bank"; + $sql .= ", entity"; + $sql .= ") "; + $sql .= " VALUES ("; + $sql .= "'".$this->db->escape($this->fk_user)."'"; + //$sql .= ", '".$this->db->idate($this->datep)."'"; + //$sql .= ", '".$this->db->idate($this->datev)."'"; + $sql .= ", ".$this->amount; + $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : 0); + $sql .= ", ".($this->salary > 0 ? $this->salary : "null"); + $sql .= ", ".($this->type_payment > 0 ? $this->type_payment : 0); + $sql .= ", ".($this->accountid > 0 ? $this->accountid : "null"); + if ($this->note) $sql .= ", '".$this->db->escape($this->note)."'"; + $sql .= ", '".$this->db->escape($this->label)."'"; + $sql .= ", '".$this->db->idate($this->datesp)."'"; + $sql .= ", '".$this->db->idate($this->dateep)."'"; + $sql .= ", '".$this->db->escape($user->id)."'"; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", NULL"; + $sql .= ", ".$conf->entity; + $sql .= ")"; + + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."salary"); + + if ($this->id > 0) { + // Update extrafield + if (!$error) { + if (!$error) { + $result = $this->insertExtraFields(); + if ($result < 0) { + $error++; + } + } + } + + // Call trigger + $result = $this->call_trigger('salary_CREATE', $user); + if ($result < 0) $error++; + // End call triggers + } else $error++; + + if (!$error) { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -2; + } + } else { + $this->error = $this->db->error(); + $this->db->rollback(); + return -1; + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Update link between payment salary and line generate into llx_bank + * + * @param int $id_bank Id bank account + * @return int <0 if KO, >0 if OK + */ + public function update_fk_bank($id_bank) + { + // phpcs:enable + $sql = 'UPDATE '.MAIN_DB_PREFIX.'salary SET fk_bank = '.$id_bank; + $sql .= ' WHERE rowid = '.$this->id; + $result = $this->db->query($sql); + if ($result) { + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } + + + /** + * Send name clicable (with possibly the picto) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param string $option link option + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chaine with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) + { + global $db, $conf, $langs, $hookmanager; + global $dolibarr_main_authentication, $dolibarr_main_demo; + global $menumanager; + + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + + $result = ''; + + $label = '<u>'.$langs->trans("Salary").'</u>'; + $label .= '<br>'; + $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref; + + $url = DOL_URL_ROOT.'/salaries/card.php?id='.$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'; + } + + $linkclose = ''; + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $label = $langs->trans("ShowMyObject"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + + /* + $hookmanager->initHooks(array('myobjectdao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $linkclose = $hookmanager->resPrint; + */ + } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + + $linkstart = '<a href="'.$url.'"'; + $linkstart .= $linkclose.'>'; + $linkend = '</a>'; + + $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 .= $this->ref; + $result .= $linkend; + //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + + global $action, $hookmanager; + $hookmanager->initHooks(array('salarypayment')); + $parameters = array('id'=>$this->id, 'getnomurl'=>$result); + $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $result = $hookmanager->resPrint; + else $result .= $hookmanager->resPrint; + + return $result; + } + + /** + * Return amount of payments already done + * + * @return int Amount of payment already done, <0 if KO + */ + public function getSommePaiement() + { + $table = 'payment_salary'; + $field = 'fk_salary'; + + $sql = 'SELECT sum(amount) as amount'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$table; + $sql .= ' WHERE '.$field.' = '.$this->id; + + dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + $amount = 0; + + $obj = $this->db->fetch_object($resql); + if ($obj) $amount = $obj->amount ? $obj->amount : 0; + + $this->db->free($resql); + return $amount; + } else { + return -1; + } + } + + /** + * Information on record + * + * @param int $id Id of record + * @return void + */ + public function info($id) + { + $sql = 'SELECT ps.rowid, ps.datec, ps.fk_user_author'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'salary as ps'; + $sql .= ' WHERE ps.rowid = '.((int) $id); + + dol_syslog(get_class($this).'::info', LOG_DEBUG); + $result = $this->db->query($sql); + + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if ($obj->fk_user_author) { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + $this->date_creation = $this->db->jdate($obj->datec); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Tag social contribution as payed completely + * + * @param User $user Object user making change + * @return int <0 if KO, >0 if OK + */ + public function set_paid($user) + { + // phpcs:enable + $sql = "UPDATE ".MAIN_DB_PREFIX."salary SET"; + $sql .= " paye = 1"; + $sql .= " WHERE rowid = ".$this->id; + $return = $this->db->query($sql); + if ($return) return 1; + else return -1; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Remove tag payed on social contribution + * + * @param User $user Object user making change + * @return int <0 if KO, >0 if OK + */ + public function set_unpaid($user) + { + // phpcs:enable + $sql = "UPDATE ".MAIN_DB_PREFIX."salary SET"; + $sql .= " paye = 0"; + $sql .= " WHERE rowid = ".$this->id; + $return = $this->db->query($sql); + if ($return) return 1; + else return -1; + } + + + /** + * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @param double $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, 1 otherwise) + * @return string Libelle + */ + public function getLibStatut($mode = 0, $alreadypaid = -1) + { + return $this->LibStatut($this->paye, $mode, $alreadypaid); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Renvoi le libelle d'un statut donne + * + * @param int $status Id status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto + * @param double $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, 1 otherwise) + * @return string Label + */ + public function LibStatut($status, $mode = 0, $alreadypaid = -1) + { + // phpcs:enable + global $langs; + + // Load translation files required by the page + $langs->loadLangs(array("customers", "bills")); + + // We reinit status array to force to redefine them because label may change according to properties values. + $this->labelStatus = array(); + $this->labelStatusShort = array(); + + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { + global $langs; + //$langs->load("mymodule"); + $this->labelStatus[self::STATUS_UNPAID] = $langs->trans('BillStatusNotPaid'); + $this->labelStatus[self::STATUS_PAID] = $langs->trans('BillStatusPaid'); + if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans('BillStatusNotPaid'); + $this->labelStatusShort[self::STATUS_PAID] = $langs->trans('BillStatusPaid'); + if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + } + + $statusType = 'status1'; + if ($status == 0 && $alreadypaid <> 0) $statusType = 'status3'; + if ($status == 1) $statusType = 'status6'; + + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); + } +} diff --git a/htdocs/salaries/document.php b/htdocs/salaries/document.php index dc86a274837..9534d074d5f 100644 --- a/htdocs/salaries/document.php +++ b/htdocs/salaries/document.php @@ -7,6 +7,7 @@ * Copyright (C) 2011-2012 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr> * Copyright (C) 2015-2019 Alexandre Spangaro <aspangaro@open-dsi.fr> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -33,7 +34,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/salaries.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php'; // Load translation files required by the page $langs->loadLangs(array("compta", "bills", "users", "salaries", "hrm")); @@ -45,7 +46,9 @@ $confirm = GETPOST('confirm', 'alpha'); // Security check $socid = GETPOST("socid", "int"); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'salaries', '', '', ''); @@ -54,15 +57,21 @@ $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 (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} -$object = new PaymentSalary($db); +$object = new Salary($db); $object->fetch($id, $ref); $upload_dir = $conf->salaries->dir_output.'/'.dol_sanitizeFileName($object->id); @@ -73,7 +82,7 @@ $modulepart = 'salaries'; * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -84,8 +93,7 @@ $form = new Form($db); llxHeader("", $langs->trans("SalaryPayment")); -if ($object->id) -{ +if ($object->id) { $object->fetch_thirdparty(); $head = salaries_prepare_head($object); @@ -95,8 +103,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/salaries/index.html b/htdocs/salaries/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/salaries/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/salaries/info.php b/htdocs/salaries/info.php index c7a5090072e..e0e6aec7f3c 100644 --- a/htdocs/salaries/info.php +++ b/htdocs/salaries/info.php @@ -2,6 +2,7 @@ /* Copyright (C) 2005-2015 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2015 Charlie BENKE <charlie@patas-monkey.com> * Copyright (C) 2017-2019 Alexandre Spangaro <aspangaro@open-dsi.fr> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -24,7 +25,7 @@ */ require '../main.inc.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/salaries.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; @@ -36,7 +37,9 @@ $action = GETPOST('action', 'aZ09'); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'salaries', '', '', ''); @@ -46,7 +49,7 @@ $result = restrictedArea($user, 'salaries', '', '', ''); llxHeader("", $langs->trans("SalaryPayment")); -$object = new PaymentSalary($db); +$object = new Salary($db); $object->fetch($id); $object->info($id); diff --git a/htdocs/salaries/list.php b/htdocs/salaries/list.php index 119b224e76b..7bc75f52793 100644 --- a/htdocs/salaries/list.php +++ b/htdocs/salaries/list.php @@ -2,6 +2,7 @@ /* Copyright (C) 2011-2019 Alexandre Spangaro <aspangaro@open-dsi.fr> * Copyright (C) 2015-2016 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -82,10 +83,13 @@ if (!$sortorder) { $search_ref = GETPOST('search_ref', 'int'); $search_user = GETPOST('search_user', 'alpha'); $search_label = GETPOST('search_label', 'alpha'); -$search_date_start = dol_mktime(0, 0, 0, GETPOST('search_date_startmonth', 'int'), GETPOST('search_date_startday', 'int'), GETPOST('search_date_startyear', 'int')); -$search_date_end = dol_mktime(23, 59, 59, GETPOST('search_date_endmonth', 'int'), GETPOST('search_date_endday', 'int'), GETPOST('search_date_endyear', 'int')); +$search_date_start_from = dol_mktime(0, 0, 0, GETPOST('search_date_start_frommonth', 'int'), GETPOST('search_date_start_fromday', 'int'), GETPOST('search_date_start_fromyear', 'int')); +$search_date_start_to = dol_mktime(23, 59, 59, GETPOST('search_date_start_tomonth', 'int'), GETPOST('search_date_start_today', 'int'), GETPOST('search_date_start_toyear', 'int')); +$search_date_end_from = dol_mktime(0, 0, 0, GETPOST('search_date_end_frommonth', 'int'), GETPOST('search_date_end_fromday', 'int'), GETPOST('search_date_end_fromyear', 'int')); +$search_date_end_to = dol_mktime(23, 59, 59, GETPOST('search_date_end_tomonth', 'int'), GETPOST('search_date_end_today', 'int'), GETPOST('search_date_end_toyear', 'int')); $search_amount = GETPOST('search_amount', 'alpha'); $search_account = GETPOST('search_account', 'int'); +$search_status = GETPOST('search_status', 'int'); $filtre = GETPOST("filtre", 'restricthtml'); @@ -118,6 +122,10 @@ foreach ($object->fields as $key => $val) { if (GETPOST('search_'.$key, 'alpha') !== '') { $search[$key] = GETPOST('search_'.$key, 'alpha'); } + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOST('search_'.$key.'_dtstartmonth', 'int'), GETPOST('search_'.$key.'_dtstartday', 'int'), GETPOST('search_'.$key.'_dtstartyear', 'int')); + $search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOST('search_'.$key.'_dtendmonth', 'int'), GETPOST('search_'.$key.'_dtendday', 'int'), GETPOST('search_'.$key.'_dtendyear', 'int')); + } } // List of fields to search into when doing a "search in all" @@ -128,6 +136,27 @@ foreach ($object->fields as $key => $val) { } } +// Definition of array of fields for columns +$arrayfields = array(); +foreach ($object->fields as $key => $val) { + // If $val['visible']==0, then we never show the field + if (!empty($val['visible'])) { + $visible = (int) dol_eval($val['visible'], 1); + $arrayfields['t.'.$key] = array( + 'label'=>$val['label'], + 'checked'=>(($visible < 0) ? 0 : 1), + 'enabled'=>($visible != 3 && dol_eval($val['enabled'], 1)), + 'position'=>$val['position'], + 'help'=>$val['help'] + ); + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + +$object->fields = dol_sort_array($object->fields, 'position'); +$arrayfields = dol_sort_array($arrayfields, 'position'); + $permissiontoread = $user->rights->salaries->read; $permissiontoadd = $user->rights->salaries->write; $permissiontodelete = $user->rights->salaries->delete; @@ -160,10 +189,14 @@ if (empty($reshook)) { $search_ref = ""; $search_user = ""; $search_label = ""; - $search_date_start = ''; + $search_date_start_from = ''; + $search_date_start_to = ''; + $search_date_end_from = ''; + $search_date_end_to = ''; $search_date_end = ''; $search_amount = ""; $search_account = ''; + $search_status = ''; $search_type_id = ""; } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') @@ -190,7 +223,7 @@ if (empty($reshook)) { */ $form = new Form($db); -$salstatic = new PaymentSalary($db); +$salstatic = new Salary($db); $userstatic = new User($db); $accountstatic = new Account($db); @@ -198,16 +231,18 @@ $now = dol_now(); //$help_url="EN:Module_BillOfMaterials|FR:Module_BillOfMaterials_FR|ES:Módulo_BillOfMaterials"; $help_url = ''; -$title = $langs->trans('SalariesPayments'); +$title = $langs->trans('Salaries'); $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.admin, u.salary as current_salary, u.fk_soc as fk_soc, u.statut as status,"; -$sql .= " s.rowid, s.fk_user, s.amount, s.salary, s.label, s.datep as datep, s.datev as datev, s.fk_typepayment as type, s.num_payment, s.fk_bank,"; +$sql .= " s.rowid, s.fk_account, s.paye, s.fk_user, s.amount, s.salary, s.label, s.datesp, s.dateep, ps.fk_typepayment as paymenttype, "; $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 .= " pst.code as payment_code"; -$sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; -$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst.id"; -$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 .= " pst.code as payment_code,"; +$sql .= " SUM(ps.amount) as alreadypayed"; +$sql .= " FROM ".MAIN_DB_PREFIX."salary as s"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_salary as ps ON (ps.fk_salary = s.rowid) "; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON (s.fk_typepayment = pst.id) "; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account ba ON (ba.rowid = s.fk_account), "; +//$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_salary as ps ON ps.fk_salary = s.rowid, "; $sql .= " ".MAIN_DB_PREFIX."user as u"; $sql .= " WHERE u.rowid = s.fk_user"; $sql .= " AND s.entity IN (".getEntity('payment_salaries').")"; @@ -225,11 +260,11 @@ if ($search_user) { if ($search_label) { $sql .= natural_search(array('s.label'), $search_label); } -if ($search_date_start) { - $sql .= " AND s.datep >= '".$db->idate($search_date_start)."'"; +if (!empty($search_date_start_from) && !empty($search_date_start_to)) { + $sql .= " AND s.datesp BETWEEN '".$db->idate($search_date_start_from)."' AND '".$db->idate($search_date_start_to)."'"; } -if ($search_date_end) { - $sql .= " AND s.datep <= '".$db->idate($search_date_end)."'"; +if (!empty($search_date_end_from) && !empty($search_date_end_to)) { + $sql .= " AND s.dateep BETWEEN '".$db->idate($search_date_end_from)."' AND '".$db->idate($search_date_end_to)."'"; } if ($search_amount) { $sql .= natural_search("s.amount", $search_amount, 1); @@ -237,6 +272,9 @@ if ($search_amount) { if ($search_account > 0) { $sql .= " AND b.fk_account=".((int) $search_account); } +if ($search_status != '' && $search_status >= 0) { + $sql .= " AND s.paye = ".$db->escape($search_status); +} if ($filtre) { $filtre = str_replace(":", "=", $filtre); $sql .= " AND ".$filtre; @@ -244,6 +282,10 @@ if ($filtre) { if ($search_type_id) { $sql .= " AND s.fk_typepayment=".$search_type_id; } +$sql .= " GROUP BY u.rowid, u.lastname, u.firstname, u.login, u.email, u.admin, u.salary, u.fk_soc, u.statut,"; +$sql .= " s.rowid, s.fk_account, s.paye, s.fk_user, s.amount, s.salary, s.label, s.datesp, s.dateep, ps.fk_typepayment, s.fk_bank,"; +$sql .= " ba.rowid, ba.ref, ba.number, ba.account_number, ba.fk_accountancy_journal, ba.label,"; +$sql .= " pst.code"; $sql .= $db->order($sortfield, $sortorder); // Count total nb of records @@ -305,12 +347,22 @@ if ($search_label) { if ($search_account) { $param .= '&search_account='.urlencode($search_account); } -if ($search_date_start) { - $param .= '&search_date_startday='.urlencode(GETPOST('search_date_startday', 'int')).'&search_date_startmonth='.urlencode(GETPOST('search_date_startmonth', 'int')).'&search_date_startyear='.urlencode(GETPOST('search_date_startyear', 'int')); +if ($search_status != '' && $search_status != '-1') { + $param .= '&search_status='.urlencode($search_status); } -if ($search_date_end) { - $param .= '&search_date_endday='.urlencode(GETPOST('search_date_endday', 'int')).'&search_date_endmonth='.urlencode(GETPOST('search_date_endmonth', 'int')).'&search_date_endyear='.urlencode(GETPOST('search_date_endyear', 'int')); +if (!empty($search_date_start_from)) { + $param .= '&search_date_start_fromday='.urlencode(GETPOST('search_date_start_fromday')).'&search_date_start_frommonth='.urlencode(GETPOST('search_date_start_frommonth')).'&search_date_start_fromyear='.urlencode(GETPOST('search_date_start_fromyear')); } +if (!empty($search_date_start_to)) { + $param .= "&search_date_start_today=".urlencode(GETPOST('search_date_start_today'))."&search_date_start_tomonth=".urlencode(GETPOST('search_date_start_tomonth'))."&search_date_start_toyear=".urlencode(GETPOST('search_date_start_toyear')); +} +if (!empty($search_date_end_from)) { + $param .= '&search_date_end_fromday='.urlencode(GETPOST('search_date_end_fromday')).'&search_date_end_frommonth='.urlencode(GETPOST('search_date_end_frommonth')).'&search_date_end_fromyear='.urlencode(GETPOST('search_date_end_fromyear')); +} +if (!empty($search_date_end_to)) { + $param .= "&search_date_end_today=".urlencode(GETPOST('search_date_end_today'))."&search_date_end_tomonth=".urlencode(GETPOST('search_date_end_tomonth'))."&search_date_end_toyear=".urlencode(GETPOST('search_date_end_toyear')); +} + // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -367,31 +419,47 @@ print '<input class="flat" type="text" size="6" name="search_user" value="'.$db- print '</td>'; // Label print '<td class="liste_titre"><input type="text" class="flat width150" name="search_label" value="'.$db->escape($search_label).'"></td>'; -// Date payment + +// Date start print '<td class="liste_titre center">'; print '<div class="nowrap">'; -print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); +print $form->selectDate($search_date_start_from ? $search_date_start_from : -1, 'search_date_start_from', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); print '</div>'; print '<div class="nowrap">'; -print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); +print $form->selectDate($search_date_start_to ? $search_date_start_to : -1, 'search_date_start_to', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); print '</div>'; print '</td>'; -// Date value + +// Date End print '<td class="liste_titre center">'; +print '<div class="nowrap">'; +print $form->selectDate($search_date_end_from ? $search_date_end_from : -1, 'search_date_end_from', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); +print '</div>'; +print '<div class="nowrap">'; +print $form->selectDate($search_date_end_to ? $search_date_end_to : -1, 'search_date_end_to', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); +print '</div>'; print '</td>'; + // Type print '<td class="liste_titre left">'; $form->select_types_paiements($search_type_id, 'search_type_id', '', 0, 1, 1, 16); print '</td>'; -// Account + +// Bank account if (!empty($conf->banque->enabled)) { print '<td class="liste_titre">'; $form->select_comptes($search_account, 'search_account', 0, '', 1); print '</td>'; } + // Amount print '<td class="liste_titre right"><input name="search_amount" class="flat" type="text" size="8" value="'.$db->escape($search_amount).'"></td>'; +print '<td class="liste_titre maxwidthonsmartphone right">'; +$liststatus = array('0' => $langs->trans("Unpaid"), '1' => $langs->trans("Paid")); +print $form->selectarray('search_status', $liststatus, $search_status, 1); +print '</td>'; + // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; @@ -411,15 +479,16 @@ print '</tr>'."\n"; // -------------------------------------------------------------------- print '<tr class="liste_titre">'; print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "s.rowid", "", $param, "", $sortfield, $sortorder); -print_liste_field_titre("Employee", $_SERVER["PHP_SELF"], "u.rowid", "", $param, "", $sortfield, $sortorder); +print_liste_field_titre("Employee", $_SERVER["PHP_SELF"], "u.lastname", "", $param, "", $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "s.label", "", $param, 'class="left"', $sortfield, $sortorder); -print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "s.datep,s.rowid", "", $param, '', $sortfield, $sortorder, 'center '); -print_liste_field_titre("DateValue", $_SERVER["PHP_SELF"], "s.datev,s.rowid", "", $param, '', $sortfield, $sortorder, 'center '); -print_liste_field_titre("PaymentMode", $_SERVER["PHP_SELF"], "type", "", $param, 'class="left"', $sortfield, $sortorder); +print_liste_field_titre("DateStart", $_SERVER["PHP_SELF"], "s.datesp,s.rowid", "", $param, 'align="center"', $sortfield, $sortorder); +print_liste_field_titre("DateEnd", $_SERVER["PHP_SELF"], "s.dateep,s.rowid", "", $param, 'align="center"', $sortfield, $sortorder); +print_liste_field_titre("DefaultPaymentMode", $_SERVER["PHP_SELF"], "type", "", $param, 'class="left"', $sortfield, $sortorder); if (!empty($conf->banque->enabled)) { - print_liste_field_titre("BankAccount", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("DefaultBankAccount", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); } -print_liste_field_titre("PayedByThisPayment", $_SERVER["PHP_SELF"], "s.amount", "", $param, 'class="right"', $sortfield, $sortorder); +print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], "s.amount", "", $param, 'class="right"', $sortfield, $sortorder); +print_liste_field_titre('Status', $_SERVER["PHP_SELF"], "s.paye", '', $param, 'class="right"', $sortfield, $sortorder); // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields @@ -488,20 +557,20 @@ while ($i < ($limit ? min($num, $limit) : $num)) { $totalarray['nbfield']++; } - // Date payment - print '<td class="center">'.dol_print_date($db->jdate($obj->datep), 'day')."</td>\n"; + // Date Start + print '<td class="center">'.dol_print_date($db->jdate($obj->datesp), 'day')."</td>\n"; if (!$i) { $totalarray['nbfield']++; } - // Date value - print '<td class="center">'.dol_print_date($db->jdate($obj->datev), 'day')."</td>\n"; + // Date End + print '<td class="center">'.dol_print_date($db->jdate($obj->dateep), 'day')."</td>\n"; if (!$i) { $totalarray['nbfield']++; } // Type - print '<td>'.$langs->trans("PaymentTypeShort".$obj->payment_code).' '.$obj->num_payment.'</td>'; + print '<td>'.$langs->trans("PaymentTypeShort".$obj->payment_code).'</td>'; if (!$i) { $totalarray['nbfield']++; } @@ -509,7 +578,7 @@ while ($i < ($limit ? min($num, $limit) : $num)) { // Account if (!empty($conf->banque->enabled)) { print '<td>'; - if ($obj->fk_bank > 0) { + if ($obj->fk_account > 0) { //$accountstatic->fetch($obj->fk_bank); $accountstatic->id = $obj->bid; $accountstatic->ref = $obj->bref; @@ -523,7 +592,7 @@ while ($i < ($limit ? min($num, $limit) : $num)) { $accountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1); } - $accountstatic->label = $obj->blabel; + //$accountstatic->label = $obj->blabel; print $accountstatic->getNomUrl(1); } else { print '&nbsp;'; @@ -534,6 +603,8 @@ while ($i < ($limit ? min($num, $limit) : $num)) { } } + // if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalttcfield'; + // Amount print '<td class="nowrap right">'.price($obj->amount).'</td>'; if (!$i) { @@ -544,6 +615,9 @@ while ($i < ($limit ? min($num, $limit) : $num)) { } $totalarray['val']['totalttcfield'] += $obj->amount; + print '<td class="nowrap right">'.$salstatic->LibStatut($obj->paye, 5, $obj->alreadypayed).'</td>'; + if (!$i) $totalarray['nbfield']++; + // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook @@ -575,12 +649,14 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { - $colspan = 1; + /*$colspan = 1; foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) { $colspan++; } - } + }*/ + $colspan = 9; + if (!empty($conf->banque->enabled)) { $colspan++; } print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } @@ -597,7 +673,6 @@ print '</div>'."\n"; print '</form>'."\n"; - // End of page llxFooter(); $db->close(); diff --git a/htdocs/salaries/paiement_salary.php b/htdocs/salaries/paiement_salary.php new file mode 100644 index 00000000000..44b6aae4503 --- /dev/null +++ b/htdocs/salaries/paiement_salary.php @@ -0,0 +1,314 @@ +<?php +/* Copyright (C) 2004-2014 Laurent Destailleur <eldy@users.sourceforge.net> + * Copyright (C) 2016-2018 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * 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 <https://www.gnu.org/licenses/>. + */ + +/** + * \file htdocs/compta/paiement_charge.php + * \ingroup tax + * \brief Page to add payment of a tax + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + +// Load translation files required by the page +$langs->load("bills"); + +$chid = GETPOST("id", 'int'); +$action = GETPOST('action', 'alpha'); +$amounts = array(); + +// Security check +$socid = 0; +if ($user->socid > 0) { + $socid = $user->socid; +} + + +/* + * Actions + */ + +if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm == 'yes')) { + $error = 0; + + if ($_POST["cancel"]) { + $loc = DOL_URL_ROOT.'/salaries/card.php?id='.$chid; + header("Location: ".$loc); + exit; + } + + $datepaye = dol_mktime(12, 0, 0, GETPOST("remonth", 'int'), GETPOST("reday", 'int'), GETPOST("reyear", 'int')); + + if (!(GETPOST("paiementtype", 'int') > 0)) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")), null, 'errors'); + $error++; + $action = 'create'; + } + if ($datepaye == '') { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors'); + $error++; + $action = 'create'; + } + if (!empty($conf->banque->enabled) && !(GETPOST("accountid", 'int') > 0)) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountToCredit")), null, 'errors'); + $error++; + $action = 'create'; + } + + if (!$error) { + $paymentid = 0; + + // Read possible payments + foreach ($_POST as $key => $value) { + if (substr($key, 0, 7) == 'amount_') { + $other_chid = substr($key, 7); + $amounts[$other_chid] = price2num($_POST[$key]); + } + } + + if (count($amounts) <= 0) { + $error++; + setEventMessages($langs->trans("ErrorNoPaymentDefined"), null, 'errors'); + $action = 'create'; + } + + if (!$error) { + $db->begin(); + + // Create a line of payments + $paiement = new PaymentSalary($db); + $paiement->chid = $chid; + $paiement->datepaye = $datepaye; + $paiement->amounts = $amounts; // Tableau de montant + $paiement->paiementtype = GETPOST("paiementtype", 'alphanohtml'); + $paiement->num_payment = GETPOST("num_payment", 'alphanohtml'); + $paiement->note = GETPOST("note", 'none'); + $paiement->note_private = GETPOST("note", 'none'); + + if (!$error) { + $paymentid = $paiement->create($user, (GETPOST('closepaidsalary') == 'on' ? 1 : 0)); + if ($paymentid < 0) { + $error++; + setEventMessages($paiement->error, null, 'errors'); + $action = 'create'; + } + } + + if (!$error) { + $result = $paiement->addPaymentToBank($user, 'payment_salary', '(SalaryPayment)', GETPOST('accountid', 'int'), '', ''); + if (!($result > 0)) { + $error++; + setEventMessages($paiement->error, null, 'errors'); + $action = 'create'; + } + } + + if (!$error) { + $db->commit(); + $loc = DOL_URL_ROOT.'/salaries/card.php?id='.$chid; + header('Location: '.$loc); + exit; + } else { + $db->rollback(); + } + } + } +} + + +/* + * View + */ + +llxHeader(); + +$form = new Form($db); + + +// Formulaire de creation d'un paiement de charge +if ($action == 'create') { + $salary = new Salary($db); // Salary to pay + $salary->fetch($chid); + $salary->accountid = $salary->fk_account ? $salary->fk_account : $salary->accountid; + $salary->paiementtype = $salary->mode_reglement_id ? $salary->mode_reglement_id : $salary->paiementtype; + + $total = $salary->amount; + if (!empty($conf->use_javascript_ajax)) { + print "\n".'<script type="text/javascript" language="javascript">'; + + //Add js for AutoFill + print ' $(document).ready(function () {'; + print ' $(".AutoFillAmount").on(\'click touchstart\', function(){ + var amount = $(this).data("value"); + document.getElementById($(this).data(\'rowid\')).value = amount ; + });'; + print ' });'."\n"; + + print ' </script>'."\n"; + } + + print load_fiche_titre($langs->trans("DoPayment")); + print "<br>\n"; + + print '<form name="add_payment" action="'.$_SERVER['PHP_SELF'].'" method="post">'; + print '<input type="hidden" name="token" value="'.newToken().'">'; + print '<input type="hidden" name="id" value="'.$chid.'">'; + print '<input type="hidden" name="chid" value="'.$chid.'">'; + print '<input type="hidden" name="action" value="add_payment">'; + + dol_fiche_head('', ''); + + print '<table class="border centpercent">'; + + print '<tr><td class="titlefieldcreate">'.$langs->trans("Ref").'</td><td><a href="'.DOL_URL_ROOT.'/salaries/card.php?id='.$chid.'">'.$chid.'</a></td></tr>'; + print '<tr><td>'.$langs->trans("DateStart")."</td><td>".dol_print_date($salary->datesp, 'day')."</td></tr>\n"; + print '<tr><td>'.$langs->trans("DateEnd")."</td><td>".dol_print_date($salary->dateep, 'day')."</td></tr>\n"; + print '<tr><td>'.$langs->trans("Label").'</td><td>'.$salary->label."</td></tr>\n"; + /*print '<tr><td>'.$langs->trans("DateDue")."</td><td>".dol_print_date($salary->date_ech,'day')."</td></tr>\n"; + print '<tr><td>'.$langs->trans("Amount")."</td><td>".price($salary->amount,0,$outputlangs,1,-1,-1,$conf->currency).'</td></tr>';*/ + + $sql = "SELECT sum(p.amount) as total"; + $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as p"; + $sql .= " WHERE p.fk_salary = ".$chid; + $resql = $db->query($sql); + if ($resql) { + $obj = $db->fetch_object($resql); + $sumpaid = $obj->total; + $db->free(); + } + /*print '<tr><td>'.$langs->trans("AlreadyPaid").'</td><td>'.price($sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'</td></tr>'; + print '<tr><td class="tdtop">'.$langs->trans("RemainderToPay").'</td><td>'.price($total-$sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'</td></tr>';*/ + + print '<tr><td class="fieldrequired">'.$langs->trans("Date").'</td><td>'; + $datepaye = dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); + $datepayment = empty($conf->global->MAIN_AUTOFILL_DATE) ? (empty($_POST["remonth"]) ?-1 : $datepaye) : ''; + print $form->selectDate($datepayment, '', '', '', '', "add_payment", 1, 1); + print "</td>"; + print '</tr>'; + + print '<tr><td class="fieldrequired">'.$langs->trans("PaymentMode").'</td><td>'; + $form->select_types_paiements(isset($_POST["paiementtype"]) ? $_POST["paiementtype"] : $salary->type_payment, "paiementtype"); + print "</td>\n"; + print '</tr>'; + + print '<tr>'; + print '<td class="fieldrequired">'.$langs->trans('AccountToDebit').'</td>'; + print '<td>'; + $form->select_comptes(isset($_POST["accountid"]) ? $_POST["accountid"] : $salary->accountid, "accountid", 0, '', 1); // Show opend bank account list + print '</td></tr>'; + + // Number + print '<tr><td>'.$langs->trans('Numero'); + print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>'; + print '</td>'; + print '<td><input name="num_payment" type="text" value="'.GETPOST('num_payment', 'alphanohtml').'"></td></tr>'."\n"; + + print '<tr>'; + print '<td class="tdtop">'.$langs->trans("Comments").'</td>'; + print '<td class="tdtop"><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>'; + print '</tr>'; + + print '</table>'; + + dol_fiche_end(); + + /* + * Autres charges impayees + */ + $num = 1; + $i = 0; + + print '<table class="noborder centpercent">'; + print '<tr class="liste_titre">'; + //print '<td>'.$langs->trans("SocialContribution").'</td>'; + print '<td class="left">'.$langs->trans("DateEnd").'</td>'; + print '<td class="right">'.$langs->trans("Amount").'</td>'; + print '<td class="right">'.$langs->trans("AlreadyPaid").'</td>'; + print '<td class="right">'.$langs->trans("RemainderToPay").'</td>'; + print '<td class="center">'.$langs->trans("Amount").'</td>'; + print "</tr>\n"; + + $total = 0; + $totalrecu = 0; + + while ($i < $num) { + $objp = $salary; + + print '<tr class="oddeven">'; + + if ($objp->dateep > 0) { + print '<td class="left">'.dol_print_date($objp->dateep, 'day').'</td>'."\n"; + } else { + print '<td align="center"><b>!!!</b></td>'."\n"; + } + + print '<td class="right">'.price($objp->amount)."</td>"; + + print '<td class="right">'.price($sumpaid)."</td>"; + + print '<td class="right">'.price($objp->amount - $sumpaid)."</td>"; + + print '<td class="center">'; + if ($sumpaid < $objp->amount) { + $namef = "amount_".$objp->id; + $nameRemain = "remain_".$objp->id; + if (!empty($conf->use_javascript_ajax)) { + print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmount' data-rowid='".$namef."' data-value='".($objp->amount - $sumpaid)."'"); + } + $remaintopay = $objp->amount - $sumpaid; + print '<input type=hidden class="sum_remain" name="'.$nameRemain.'" value="'.$remaintopay.'">'; + print '<input type="text" size="8" name="'.$namef.'" id="'.$namef.'">'; + } else { + print '-'; + } + print "</td>"; + + print "</tr>\n"; + $total += $objp->total; + $total_ttc += $objp->total_ttc; + $totalrecu += $objp->am; + $i++; + } + if ($i > 1) { + // Print total + print '<tr class="oddeven">'; + print '<td colspan="2" class="left">'.$langs->trans("Total").':</td>'; + print '<td class="right"><b>'.price($total_ttc).'</b></td>'; + print '<td class="right"><b>'.price($totalrecu).'</b></td>'; + print '<td class="right"><b>'.price($total_ttc - $totalrecu).'</b></td>'; + print '<td align="center">&nbsp;</td>'; + print "</tr>\n"; + } + + print "</table>"; + + // Bouton Save payment + print '<br><div class="center"><input type="checkbox" checked name="closepaidsalary"> '.$langs->trans("ClosePaidSalaryAutomatically"); + print '<br><input type="submit" class="button" name="save" value="'.$langs->trans('ToMakePayment').'">'; + print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; + print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">'; + print '</div>'; + + print "</form>\n"; +} + +llxFooter(); +$db->close(); diff --git a/htdocs/salaries/payment_salary/card.php b/htdocs/salaries/payment_salary/card.php new file mode 100644 index 00000000000..3a8eb998fff --- /dev/null +++ b/htdocs/salaries/payment_salary/card.php @@ -0,0 +1,269 @@ +<?php +/* Copyright (C) 2004 Rodolphe Quiedeville <rodolphe@quiedeville.org> + * Copyright (C) 2004-2014 Laurent Destailleur <eldy@users.sourceforge.net> + * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com> + * Copyright (C) 2005-2009 Regis Houssin <regis.houssin@inodbox.com> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * 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 <https://www.gnu.org/licenses/>. + */ + +/** + * \file htdocs/compta/payment_sc/card.php + * \ingroup facture + * \brief Onglet payment of a salary + * \remarks Fichier presque identique a fournisseur/paiement/card.php + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; +if (!empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array('bills', 'banks', 'companies', 'salaries')); + +// Security check +$id = GETPOST("id", 'int'); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm'); +if ($user->socid) $socid = $user->socid; +// TODO ajouter regle pour restreindre acces paiement +//$result = restrictedArea($user, 'facture', $id,''); + +$object = new PaymentSalary($db); +if ($id > 0) { + $result = $object->fetch($id); + if (!$result) dol_print_error($db, 'Failed to get payment id '.$id); +} + + +/* + * Actions + */ + +// Delete payment +if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->salaries->delete) { + $db->begin(); + + $result = $object->delete($user); + if ($result > 0) { + $db->commit(); + header("Location: ".DOL_URL_ROOT."/salaries/payments.php"); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $db->rollback(); + } +} + + +/* + * View + */ + +llxHeader(); + +$salary = new Salary($db); + +$form = new Form($db); + +$h = 0; + +$head = array(); + +$head[$h][0] = DOL_URL_ROOT.'/salaries/payment_salary/card.php?id='.$id; +$head[$h][1] = $langs->trans("SalaryPayment"); +$hselected = $h; +$h++; + +/* +$head[$h][0] = DOL_URL_ROOT.'/compta/payment_sc/info.php?id='.$id; +$head[$h][1] = $langs->trans("Info"); +$h++; +*/ + + +dol_fiche_head($head, $hselected, $langs->trans("SalaryPayment"), -1, 'payment'); + +/* + * Deletion confirmation of payment + */ +if ($action == 'delete') { + print $form->formconfirm('card.php?id='.$object->id, $langs->trans("DeleteSalary"), $langs->trans("ConfirmDeleteSalaryPayment"), 'confirm_delete', '', 0, 2); +} + +/* + * Validation confirmation of payment + */ +/* +if ($action == 'valide') +{ + $facid = $_GET['facid']; + print $form->formconfirm('card.php?id='.$object->id.'&amp;facid='.$facid, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide','',0,2); + +} +*/ + + +$linkback = '<a href="'.DOL_URL_ROOT.'/salaries/payments.php">'.$langs->trans("BackToList").'</a>'; + +dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'id', ''); + + +print '<div class="fichecenter">'; +print '<div class="underbanner clearboth"></div>'; + +print '<table class="border centpercent">'; + +// Ref +/*print '<tr><td class="titlefield">'.$langs->trans('Ref').'</td>'; +print '<td colspan="3">'; +print $form->showrefnav($object,'id','',1,'rowid','id'); +print '</td></tr>';*/ + +// Date +print '<tr><td>'.$langs->trans('Date').'</td><td colspan="3">'.dol_print_date($object->datep, 'day').'</td></tr>'; + +// Mode +print '<tr><td>'.$langs->trans('Mode').'</td><td colspan="3">'.$langs->trans("PaymentType".$object->type_code).'</td></tr>'; + +// Numero +print '<tr><td>'.$langs->trans('Numero').'</td><td colspan="3">'.$object->num_payment.'</td></tr>'; + +// Montant +print '<tr><td>'.$langs->trans('Amount').'</td><td colspan="3">'.price($object->amount, 0, $outputlangs, 1, -1, -1, $conf->currency).'</td></tr>'; + +// Note +print '<tr><td>'.$langs->trans('Note').'</td><td colspan="3">'.nl2br($object->note).'</td></tr>'; + +// Bank account +if (!empty($conf->banque->enabled)) { + if ($object->bank_account) { + $bankline = new AccountLine($db); + $bankline->fetch($object->bank_line); + + print '<tr>'; + print '<td>'.$langs->trans('BankTransactionLine').'</td>'; + print '<td colspan="3">'; + print $bankline->getNomUrl(1, 0, 'showall'); + print '</td>'; + print '</tr>'; + } +} + +print '</table>'; + +print '</div>'; + +dol_fiche_end(); + + +/* + * List of salaries payed + */ + +$disable_delete = 0; +$sql = 'SELECT f.rowid as scid, f.label, f.paye, f.amount as sc_amount, ps.amount'; +$sql .= ' FROM '.MAIN_DB_PREFIX.'payment_salary as ps,'.MAIN_DB_PREFIX.'salary as f'; +$sql .= ' WHERE ps.fk_salary = f.rowid'; +$sql .= ' AND f.entity = '.$conf->entity; +$sql .= ' AND ps.rowid = '.$object->id; + +dol_syslog("payment_salary/card.php", LOG_DEBUG); +$resql = $db->query($sql); +if ($resql) { + $num = $db->num_rows($resql); + + $i = 0; + $total = 0; + print '<br>'; + + print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '<table class="noborder centpercent">'; + print '<tr class="liste_titre">'; + print '<td>'.$langs->trans('Salary').'</td>'; + print '<td>'.$langs->trans('Type').'</td>'; + print '<td>'.$langs->trans('Label').'</td>'; + print '<td class="right">'.$langs->trans('ExpectedToPay').'</td>'; + print '<td class="center">'.$langs->trans('Status').'</td>'; + print '<td class="right">'.$langs->trans('PayedByThisPayment').'</td>'; + print "</tr>\n"; + + if ($num > 0) { + while ($i < $num) { + $objp = $db->fetch_object($resql); + + print '<tr class="oddeven">'; + // Ref + print '<td>'; + $salary->fetch($objp->scid); + print $salary->getNomUrl(1); + print "</td>\n"; + // Type + print '<td>'; + print $salary->type_label; + /*print $salary->type;*/ + print "</td>\n"; + // Label + print '<td>'.$objp->label.'</td>'; + // Expected to pay + print '<td class="right">'.price($objp->sc_amount).'</td>'; + // Status + print '<td class="center">'.$salary->getLibStatut(4, $objp->amount).'</td>'; + // Amount payed + print '<td class="right">'.price($objp->amount).'</td>'; + print "</tr>\n"; + if ($objp->paye == 1) { + // If at least one invoice is paid, disable delete + $disable_delete = 1; + } + $total = $total + $objp->amount; + $i++; + } + } + + print "</table>\n"; + print "</div>"; + + $db->free($resql); +} else { + dol_print_error($db); +} + + + +/* + * Button actions + */ + +print '<div class="tabsAction">'; + +if ($action == '') { + if ($user->rights->salaries->delete) { + if (!$disable_delete) { + print '<a class="butActionDelete" href="card.php?id='.$_GET['id'].'&amp;action=delete">'.$langs->trans('Delete').'</a>'; + } else { + print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("CantRemovePaymentSalaryPaid")).'">'.$langs->trans('Delete').'</a>'; + } + } +} + +print '</div>'; + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/salaries/payments.php b/htdocs/salaries/payments.php new file mode 100644 index 00000000000..5c0b0c73956 --- /dev/null +++ b/htdocs/salaries/payments.php @@ -0,0 +1,513 @@ +<?php +/* Copyright (C) 2011-2019 Alexandre Spangaro <aspangaro@open-dsi.fr> + * Copyright (C) 2015-2016 Laurent Destailleur <eldy@users.sourceforge.net> + * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * 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 <https://www.gnu.org/licenses/>. + */ + +/** + * \file htdocs/salaries/list.php + * \ingroup salaries + * \brief List of salaries payments + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("compta", "salaries", "bills", "hrm")); + +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'bomlist'; // To manage different context of search +$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') + +// 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 || 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 = "s.datep,s.rowid"; +if (!$sortorder) $sortorder = "DESC,DESC"; + +// Initialize technical objects +$object = new PaymentSalary($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->user->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('salarieslist')); // Note that conf->hooks_modules contains array + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +if (!$sortfield) $sortfield = "s.datep,s.rowid"; +if (!$sortorder) $sortorder = "DESC,DESC"; + +$search_ref = GETPOST('search_ref', 'int'); +$search_ref_salary = GETPOST('search_ref_salary', 'int'); +$search_user = GETPOST('search_user', 'alpha'); +$search_label = GETPOST('search_label', 'alpha'); +$search_date_start = dol_mktime(0, 0, 0, GETPOST('search_date_startmonth', 'int'), GETPOST('search_date_startday', 'int'), GETPOST('search_date_startyear', 'int')); +$search_date_end = dol_mktime(23, 59, 59, GETPOST('search_date_endmonth', 'int'), GETPOST('search_date_endday', 'int'), GETPOST('search_date_endyear', 'int')); +$search_amount = GETPOST('search_amount', 'alpha'); +$search_account = GETPOST('search_account', 'int'); + +$filtre = GETPOST("filtre", 'restricthtml'); + +if (!GETPOST('search_type_id', 'int')) { + $newfiltre = str_replace('filtre=', '', $filtre); + $filterarray = explode('-', $newfiltre); + foreach ($filterarray as $val) { + $part = explode(':', $val); + if ($part[0] == 's.fk_typepayment') $search_type_id = $part[1]; + } +} else { + $search_type_id = GETPOST('search_type_id', 'int'); +} + +$childids = $user->getAllChildIds(1); + +// Security check +$socid = GETPOST("socid", "int"); +if ($user->socid) $socid = $user->socid; +$result = restrictedArea($user, 'salaries', '', '', ''); + +// Initialize array of search criterias +$search_all = GETPOST("search_all", 'alpha'); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); +} + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array(); +foreach ($object->fields as $key => $val) { + if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +} + +$permissiontoread = $user->rights->salaries->read; +$permissiontoadd = $user->rights->salaries->write; +$permissiontodelete = $user->rights->salaries->delete; + + +/* + * Actions + */ + +if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } + +$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 (empty($reshook)) { + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers + $search_ref = ""; + $search_ref_salary = ""; + $search_user = ""; + $search_label = ""; + $search_date_start = ''; + $search_date_end = ''; + $search_amount = ""; + $search_account = ''; + $search_type_id = ""; + } + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + // Mass actions + $objectclass = 'PaymentSalary'; + $objectlabel = 'SalariesPayments'; + $uploaddir = $conf->salaries->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + + // Validate records + if (!$error && $massaction == 'buildsepa' && $permissiontoadd) { + $objecttmp = new $objectclass($db); + + // TODO + } +} + +/* + * View + */ + +$form = new Form($db); +$salstatic = new Salary($db); +$paymentsalstatic = new PaymentSalary($db); +$userstatic = new User($db); +$accountstatic = new Account($db); + +$now = dol_now(); + +//$help_url="EN:Module_BillOfMaterials|FR:Module_BillOfMaterials_FR|ES:Módulo_BillOfMaterials"; +$help_url = ''; +$title = $langs->trans('SalariesPayments'); + +$sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.admin, u.salary as current_salary, u.fk_soc as fk_soc, u.statut as status,"; +$sql .= " s.rowid, s.fk_user, s.amount, s.salary, sal.rowid as id_salary, sal.label, s.datep as datep, b.datev as datev, s.fk_typepayment as type, s.num_payment, s.fk_bank,"; +$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 .= " pst.code as payment_code"; +$sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; +$sql .= " INNER JOIN ".MAIN_DB_PREFIX."salary as sal ON (sal.rowid = s.fk_salary)"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst.id"; +$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 .= " ".MAIN_DB_PREFIX."user as u"; +$sql .= " WHERE u.rowid = sal.fk_user"; +$sql .= " AND s.entity IN (".getEntity('payment_salaries').")"; +if (empty($user->rights->salaries->readall)) $sql .= " AND s.fk_user IN (".join(',', $childids).")"; + +// Search criteria +if ($search_ref) $sql .= " AND s.rowid=".((int) $search_ref); +if ($search_ref_salary) $sql .= " AND sal.rowid=".((int) $search_ref_salary); +if ($search_user) $sql .= natural_search(array('u.login', 'u.lastname', 'u.firstname', 'u.email'), $search_user); +if ($search_label) $sql .= natural_search(array('sal.label'), $search_label); +if ($search_date_start) $sql .= " AND s.datep >= '".$db->idate($search_date_start)."'"; +if ($search_date_end) $sql .= " AND s.datep <= '".$db->idate($search_date_end)."'"; +if ($search_amount) $sql .= natural_search("s.amount", $search_amount, 1); +if ($search_account > 0) $sql .= " AND b.fk_account=".((int) $search_account); +if ($filtre) { + $filtre = str_replace(":", "=", $filtre); + $sql .= " AND ".$filtre; +} +if ($search_type_id) { + $sql .= " AND s.fk_typepayment=".$search_type_id; +} +$sql .= $db->order($sortfield, $sortorder); + +// Count total nb of records +$nbtotalofrecords = ''; +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 + $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 || empty($limit))) { + $num = $nbtotalofrecords; +} else { + if ($limit) $sql .= $db->plimit($limit + 1, $offset); + + $resql = $db->query($sql); + if (!$resql) { + dol_print_error($db); + exit; + } + + $num = $db->num_rows($resql); +} + +// Output page +// -------------------------------------------------------------------- + +llxHeader('', $title, $help_url); + +$arrayofselected = is_array($toselect) ? $toselect : array(); + +$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_type_id) $param .= '&search_type_id='.urlencode($search_type_id); +if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); +if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); +if ($search_ref_salary) $param .= '&search_ref_salary='.urlencode($search_ref_salary); +if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); +if ($search_label) $param .= '&search_label='.urlencode($search_label); +if ($search_account) $param .= '&search_account='.urlencode($search_account); +if ($search_date_start) $param .= '&search_date_startday='.urlencode(GETPOST('search_date_startday', 'int')).'&search_date_startmonth='.urlencode(GETPOST('search_date_startmonth', 'int')).'&search_date_startyear='.urlencode(GETPOST('search_date_startyear', 'int')); +if ($search_date_end) $param .= '&search_date_endday='.urlencode(GETPOST('search_date_endday', 'int')).'&search_date_endmonth='.urlencode(GETPOST('search_date_endmonth', 'int')).'&search_date_endyear='.urlencode(GETPOST('search_date_endyear', 'int')); +// Add $param from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + +// List of mass actions available +$arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + //'buildsepa'=>$langs->trans("BuildSepa"), // TODO +); +//if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); + +print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; +if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +print '<input type="hidden" name="token" value="'.newToken().'">'; +print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; +print '<input type="hidden" name="action" value="list">'; +print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; +print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; +print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; + +$url = DOL_URL_ROOT.'/salaries/card.php?action=create'; +if (!empty($socid)) $url .= '&socid='.$socid; +$newcardbutton = dolGetButtonTitle($langs->trans('NewSalaryPayment'), '', 'fa fa-plus-circle', $url, '', $user->rights->salaries->write); + +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $totalnboflines, 'object_payment', 0, $newcardbutton, '', $limit, 0, 0, 1); + +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +//$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields = ''; +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + +print '<div class="div-table-responsive">'; +print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; + +// Fields title search +// -------------------------------------------------------------------- +print '<tr class="liste_titre_filter">'; +// Ref +print '<td class="liste_titre left">'; +print '<input class="flat" type="text" size="3" name="search_ref" value="'.$db->escape($search_ref).'">'; +print '</td>'; +// Employee +print '<td class="liste_titre">'; +print '<input class="flat" type="text" size="6" name="search_user" value="'.$db->escape($search_user).'">'; +print '</td>'; +// Salary +print '<td class="liste_titre center">'; +print '<input class="flat" type="text" size="3" name="search_ref_salary" value="'.$db->escape($search_ref_salary).'">'; +print '</td>'; +// Label +print '<td class="liste_titre"><input type="text" class="flat width150" name="search_label" value="'.$db->escape($search_label).'"></td>'; +// Date payment +print '<td class="liste_titre center">'; +print '<div class="nowrap">'; +print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); +print '</div>'; +print '<div class="nowrap">'; +print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); +print '</div>'; +print '</td>'; +// Date value +print '<td class="liste_titre center">'; +print '</td>'; +// Type +print '<td class="liste_titre left">'; +$form->select_types_paiements($search_type_id, 'search_type_id', '', 0, 1, 1, 16); +print '</td>'; +// Account +if (!empty($conf->banque->enabled)) { + print '<td class="liste_titre">'; + $form->select_comptes($search_account, 'search_account', 0, '', 1); + print '</td>'; +} +// Amount +print '<td class="liste_titre right"><input name="search_amount" class="flat" type="text" size="8" value="'.$db->escape($search_amount).'"></td>'; + +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + +// Fields from hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Action column +print '<td class="liste_titre maxwidthsearch">'; +$searchpicto = $form->showFilterButtons(); +print $searchpicto; +print '</td>'; +print '</tr>'."\n"; + + +// Fields title label +// -------------------------------------------------------------------- +print '<tr class="liste_titre">'; +print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "s.rowid", "", $param, "", $sortfield, $sortorder); +print_liste_field_titre("Employee", $_SERVER["PHP_SELF"], "u.rowid", "", $param, "", $sortfield, $sortorder); +print_liste_field_titre("Salary", $_SERVER["PHP_SELF"], "sal.rowid", "", $param, '', $sortfield, $sortorder); +print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "s.label", "", $param, 'class="left"', $sortfield, $sortorder); +print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "s.datep,s.rowid", "", $param, '', $sortfield, $sortorder, 'center '); +print_liste_field_titre("DateValue", $_SERVER["PHP_SELF"], "b.datev,s.rowid", "", $param, '', $sortfield, $sortorder, 'center '); +print_liste_field_titre("PaymentMode", $_SERVER["PHP_SELF"], "pst.code", "", $param, 'class="left"', $sortfield, $sortorder); +if (!empty($conf->banque->enabled)) print_liste_field_titre("BankAccount", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); +print_liste_field_titre("PayedByThisPayment", $_SERVER["PHP_SELF"], "s.amount", "", $param, 'class="right"', $sortfield, $sortorder); +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; +// Hook fields +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Action column +print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; +print '</tr>'."\n"; + + +// Detect if we need a fetch on each output line +$needToFetchEachLine = 0; +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object + } +} + +// Loop on record +// -------------------------------------------------------------------- +$i = 0; +$total = 0; +$totalarray = array(); +while ($i < ($limit ? min($num, $limit) : $num)) { + $obj = $db->fetch_object($resql); + if (empty($obj)) break; // Should not happen + + // Store properties in $object + $object->setVarsFromFetchObj($obj); + + // Show here line of result + print '<tr class="oddeven">'; + + $userstatic->id = $obj->uid; + $userstatic->lastname = $obj->lastname; + $userstatic->firstname = $obj->firstname; + $userstatic->admin = $obj->admin; + $userstatic->login = $obj->login; + $userstatic->email = $obj->email; + $userstatic->socid = $obj->fk_soc; + $userstatic->statut = $obj->status; + + $salstatic->id = $obj->id_salary; + $salstatic->ref = $obj->id_salary; + + $paymentsalstatic->id = $obj->rowid; + $paymentsalstatic->ref = $obj->rowid; + + // Ref + print "<td>".$paymentsalstatic->getNomUrl(1)."</td>\n"; + if (!$i) $totalarray['nbfield']++; + + // Employee + print "<td>".$userstatic->getNomUrl(1)."</td>\n"; + if (!$i) $totalarray['nbfield']++; + + print "<td>".$salstatic->getNomUrl(1)."</td>\n"; + if (!$i) $totalarray['nbfield']++; + + // Label payment + print "<td>".dol_trunc($obj->label, 40)."</td>\n"; + if (!$i) $totalarray['nbfield']++; + + // Date payment + print '<td class="center">'.dol_print_date($db->jdate($obj->datep), 'day')."</td>\n"; + if (!$i) $totalarray['nbfield']++; + + // Date value + print '<td class="center">'.dol_print_date($db->jdate($obj->datev), 'day')."</td>\n"; + if (!$i) $totalarray['nbfield']++; + + // Type + print '<td>'.$langs->trans("PaymentTypeShort".$obj->payment_code).' '.$obj->num_payment.'</td>'; + if (!$i) $totalarray['nbfield']++; + + // Account + if (!empty($conf->banque->enabled)) { + print '<td>'; + if ($obj->fk_bank > 0) { + //$accountstatic->fetch($obj->fk_bank); + $accountstatic->id = $obj->bid; + $accountstatic->ref = $obj->bref; + $accountstatic->number = $obj->bnumber; + + if (!empty($conf->accounting->enabled)) { + $accountstatic->account_number = $obj->account_number; + + $accountingjournal = new AccountingJournal($db); + $accountingjournal->fetch($obj->fk_accountancy_journal); + + $accountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1); + } + $accountstatic->label = $obj->blabel; + print $accountstatic->getNomUrl(1); + } else print '&nbsp;'; + print '</td>'; + if (!$i) $totalarray['nbfield']++; + } + + // Amount + print '<td class="nowrap right">'.price($obj->amount).'</td>'; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalttcfield'; + $totalarray['val']['totalttcfield'] += $obj->amount; + + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + // Fields from hook + $parameters = array('arrayfields'=>$arrayfields, 'object'=>$object, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Action column + print '<td class="nowrap center">'; + 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($object->id, $arrayofselected)) $selected = 1; + print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; + } + print '</td>'; + if (!$i) $totalarray['nbfield']++; + + print '</tr>'."\n"; + + $i++; +} + +// Show total line +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++; } + print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; +} + + +$db->free($resql); + +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print '</table>'."\n"; +print '</div>'."\n"; + +print '</form>'."\n"; + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/salaries/stats/index.php b/htdocs/salaries/stats/index.php index 99b2fd9042f..1fe914d38c2 100644 --- a/htdocs/salaries/stats/index.php +++ b/htdocs/salaries/stats/index.php @@ -1,6 +1,7 @@ <?php /* Copyright (C) 2018 Alexandre Spangaro <aspangaro@open-dsi.fr> * Copyright (C) 2018 Fidesio <contact@fidesio.com> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -27,18 +28,26 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; require_once DOL_DOCUMENT_ROOT.'/salaries/class/salariesstats.class.php'; // Load translation files required by the page -$langs->loadLangs(array("salaries", "companies")); +$langs->loadLangs(array("salaries", "companies", "bills")); $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; +} $id = GETPOST('id', 'int'); // Security check $socid = GETPOST("socid", "int"); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'salaries', '', '', ''); $nowyear = strftime("%Y", dol_now()); @@ -80,12 +89,10 @@ $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=salariesstats&amp;file=sala $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -112,12 +119,10 @@ $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=salariesstats&amp;file= $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px2->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -143,12 +148,10 @@ $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=salariesstats&file=salari $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px3->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -173,7 +176,9 @@ $arrayyears = array(); foreach ($data as $val) { $arrayyears[$val['year']] = $val['year']; } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; @@ -198,12 +203,14 @@ print '<input type="hidden" name="token" value="'.newToken().'">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><td class="liste_titre" colspan="2">'.$langs->trans("Filter").'</td></tr>'; // User -print '<tr><td>'.$langs->trans("User").'</td><td>'; -print $form->select_dolusers($userid, 'userid', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); +print '<tr><td>'.$langs->trans("Employee").'</td><td>'; +print $form->select_dolusers(($userid ? $userid : -1), 'userid', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); print '</td></tr>'; // Year print '<tr><td>'.$langs->trans("Year").'</td><td>'; -if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print '</td></tr>'; @@ -222,11 +229,9 @@ print '<td class="right">'.$langs->trans("AmountAverage").'</td>'; print '</tr>'; $oldyear = 0; -foreach ($data as $val) -{ +foreach ($data as $val) { $year = $val['year']; - while ($year && $oldyear > $year + 1) - { + while ($year && $oldyear > $year + 1) { // If we have empty year $oldyear--; @@ -256,7 +261,9 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; // Show graphs print '<table class="border centpercent"><tr class="pair nohover"><td align="center">'; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); print "<br>\n"; print $px2->show(); diff --git a/htdocs/societe/admin/contact_extrafields.php b/htdocs/societe/admin/contact_extrafields.php index a52bf52332b..3841a7c66ea 100644 --- a/htdocs/societe/admin/contact_extrafields.php +++ b/htdocs/societe/admin/contact_extrafields.php @@ -36,13 +36,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 = 'socpeople'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -77,8 +81,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -91,8 +94,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -104,8 +106,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/societe/admin/societe.php b/htdocs/societe/admin/societe.php index daaf9fbd623..d0edd54f946 100644 --- a/htdocs/societe/admin/societe.php +++ b/htdocs/societe/admin/societe.php @@ -35,7 +35,9 @@ $langs->loadLangs(array("admin", "companies", "other")); $action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $formcompany = new FormCompany($db); @@ -47,10 +49,8 @@ $formcompany = new FormCompany($db); include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; -if ($action == 'setcodeclient') -{ - if (dolibarr_set_const($db, "SOCIETE_CODECLIENT_ADDON", $value, 'chaine', 0, '', $conf->entity) > 0) - { +if ($action == 'setcodeclient') { + if (dolibarr_set_const($db, "SOCIETE_CODECLIENT_ADDON", $value, 'chaine', 0, '', $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -58,10 +58,8 @@ if ($action == 'setcodeclient') } } -if ($action == 'setcodecompta') -{ - if (dolibarr_set_const($db, "SOCIETE_CODECOMPTA_ADDON", $value, 'chaine', 0, '', $conf->entity) > 0) - { +if ($action == 'setcodecompta') { + if (dolibarr_set_const($db, "SOCIETE_CODECOMPTA_ADDON", $value, 'chaine', 0, '', $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -69,41 +67,40 @@ if ($action == 'setcodecompta') } } -if ($action == 'updateoptions') -{ - if (GETPOST('COMPANY_USE_SEARCH_TO_SELECT')) - { +if ($action == 'updateoptions') { + if (GETPOST('COMPANY_USE_SEARCH_TO_SELECT')) { $companysearch = GETPOST('activate_COMPANY_USE_SEARCH_TO_SELECT', 'alpha'); $res = dolibarr_set_const($db, "COMPANY_USE_SEARCH_TO_SELECT", $companysearch, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; - if (!$error) - { + if (!($res > 0)) { + $error++; + } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); } } - if (GETPOST('CONTACT_USE_SEARCH_TO_SELECT')) - { + if (GETPOST('CONTACT_USE_SEARCH_TO_SELECT')) { $contactsearch = GETPOST('activate_CONTACT_USE_SEARCH_TO_SELECT', 'alpha'); $res = dolibarr_set_const($db, "CONTACT_USE_SEARCH_TO_SELECT", $contactsearch, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; - if (!$error) - { + if (!($res > 0)) { + $error++; + } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); } } - if (GETPOST('THIRDPARTY_CUSTOMERTYPE_BY_DEFAULT')) - { + if (GETPOST('THIRDPARTY_CUSTOMERTYPE_BY_DEFAULT')) { $customertypedefault = GETPOST('defaultcustomertype', 'int'); $res = dolibarr_set_const($db, "THIRDPARTY_CUSTOMERTYPE_BY_DEFAULT", $customertypedefault, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; - if (!$error) - { + if (!($res > 0)) { + $error++; + } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -112,8 +109,7 @@ if ($action == 'updateoptions') } // Activate a document generator module -if ($action == 'set') -{ +if ($action == 'set') { $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); @@ -125,22 +121,24 @@ if ($action == 'set') $sql .= ")"; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } } // Disable a document generator module -if ($action == 'del') -{ +if ($action == 'del') { $type = 'company'; $sql = "DELETE FROM ".MAIN_DB_PREFIX."document_model"; $sql .= " WHERE nom='".$db->escape($value)."' AND type='".$db->escape($type)."' AND entity=".$conf->entity; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } } // Define default generator -if ($action == 'setdoc') -{ +if ($action == 'setdoc') { $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); @@ -164,8 +162,7 @@ if ($action == 'setdoc') $sql .= ")"; dol_syslog("societe.php", LOG_DEBUG); $result2 = $db->query($sql); - if ($result1 && $result2) - { + if ($result1 && $result2) { $db->commit(); } else { $db->rollback(); @@ -176,9 +173,10 @@ if ($action == 'setdoc') if ($action == "setaddrefinlist") { $setaddrefinlist = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "SOCIETE_ADD_REF_IN_LIST", $setaddrefinlist, 'yesno', 0, '', $conf->entity); - if (!($res > 0)) $error++; - if (!$error) - { + if (!($res > 0)) { + $error++; + } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -189,9 +187,10 @@ if ($action == "setaddrefinlist") { if ($action == "setaddadressinlist") { $val = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "COMPANY_SHOW_ADDRESS_SELECTLIST", $val, 'yesno', 0, '', $conf->entity); - if (!($res > 0)) $error++; - if (!$error) - { + if (!($res > 0)) { + $error++; + } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -202,7 +201,9 @@ if ($action == "setaddadressinlist") { if ($action == "setaddemailphonetownincontactlist") { $val = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST", $val, 'yesno', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -214,9 +215,10 @@ if ($action == "setaddemailphonetownincontactlist") { if ($action == "setaskforshippingmet") { $setaskforshippingmet = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "SOCIETE_ASK_FOR_SHIPPING_METHOD", $setaskforshippingmet, 'yesno', 0, '', $conf->entity); - if (!($res > 0)) $error++; - if (!$error) - { + if (!($res > 0)) { + $error++; + } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -227,9 +229,10 @@ if ($action == "setaskforshippingmet") { if ($action == "setdisableprospectcustomer") { $setdisableprospectcustomer = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "SOCIETE_DISABLE_PROSPECTSCUSTOMERS", $setdisableprospectcustomer, 'yesno', 0, '', $conf->entity); - if (!($res > 0)) $error++; - if (!$error) - { + if (!($res > 0)) { + $error++; + } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -237,13 +240,11 @@ if ($action == "setdisableprospectcustomer") { } //Activate ProfId unique -if ($action == 'setprofid') -{ +if ($action == 'setprofid') { $status = GETPOST('status', 'alpha'); $idprof = "SOCIETE_".$value."_UNIQUE"; - if (dolibarr_set_const($db, $idprof, $status, 'chaine', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, $idprof, $status, 'chaine', 0, '', $conf->entity) > 0) { //header("Location: ".$_SERVER["PHP_SELF"]); //exit; } else { @@ -252,13 +253,11 @@ if ($action == 'setprofid') } //Activate ProfId mandatory -if ($action == 'setprofidmandatory') -{ +if ($action == 'setprofidmandatory') { $status = GETPOST('status', 'alpha'); $idprof = "SOCIETE_".$value."_MANDATORY"; - if (dolibarr_set_const($db, $idprof, $status, 'chaine', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, $idprof, $status, 'chaine', 0, '', $conf->entity) > 0) { //header("Location: ".$_SERVER["PHP_SELF"]); //exit; } else { @@ -267,13 +266,11 @@ if ($action == 'setprofidmandatory') } //Activate ProfId invoice mandatory -if ($action == 'setprofidinvoicemandatory') -{ +if ($action == 'setprofidinvoicemandatory') { $status = GETPOST('status', 'alpha'); $idprof = "SOCIETE_".$value."_INVOICE_MANDATORY"; - if (dolibarr_set_const($db, $idprof, $status, 'chaine', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, $idprof, $status, 'chaine', 0, '', $conf->entity) > 0) { //header("Location: ".$_SERVER["PHP_SELF"]); //exit; } else { @@ -282,12 +279,10 @@ if ($action == 'setprofidinvoicemandatory') } //Set hide closed customer into combox or select -if ($action == 'sethideinactivethirdparty') -{ +if ($action == 'sethideinactivethirdparty') { $status = GETPOST('status', 'alpha'); - if (dolibarr_set_const($db, "COMPANY_HIDE_INACTIVE_IN_COMBOBOX", $status, 'chaine', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, "COMPANY_HIDE_INACTIVE_IN_COMBOBOX", $status, 'chaine', 0, '', $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -297,9 +292,10 @@ if ($action == 'sethideinactivethirdparty') if ($action == 'setonsearchandlistgooncustomerorsuppliercard') { $setonsearchandlistgooncustomerorsuppliercard = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD", $setonsearchandlistgooncustomerorsuppliercard, 'yesno', 0, '', $conf->entity); - if (!($res > 0)) $error++; - if (!$error) - { + if (!($res > 0)) { + $error++; + } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -326,7 +322,9 @@ $head = societe_admin_prepare_head(); print dol_get_fiche_head($head, 'general', $langs->trans("ThirdParties"), -1, 'company'); $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); -foreach ($conf->modules_parts['models'] as $mo) $dirsociete[] = $mo.'core/modules/societe/'; //Add more models +foreach ($conf->modules_parts['models'] as $mo) { + $dirsociete[] = $mo.'core/modules/societe/'; //Add more models +} // Module to manage customer/supplier code @@ -344,32 +342,31 @@ print "</tr>\n"; $arrayofmodules = array(); -foreach ($dirsociete as $dirroot) -{ +foreach ($dirsociete as $dirroot) { $dir = dol_buildpath($dirroot, 0); $handle = @opendir($dir); - if (is_resource($handle)) - { + if (is_resource($handle)) { // Loop on each module find in opened directory - while (($file = readdir($handle)) !== false) - { - if (substr($file, 0, 15) == 'mod_codeclient_' && substr($file, -3) == 'php') - { + while (($file = readdir($handle)) !== false) { + if (substr($file, 0, 15) == 'mod_codeclient_' && substr($file, -3) == 'php') { $file = substr($file, 0, dol_strlen($file) - 4); try { dol_include_once($dirroot.$file.'.php'); - } catch (Exception $e) - { + } catch (Exception $e) { dol_syslog($e->getMessage(), LOG_ERR); } $modCodeTiers = new $file; // Show modules according to features level - if ($modCodeTiers->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($modCodeTiers->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($modCodeTiers->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($modCodeTiers->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } $arrayofmodules[$file] = $modCodeTiers; } @@ -380,24 +377,26 @@ foreach ($dirsociete as $dirroot) $arrayofmodules = dol_sort_array($arrayofmodules, 'position'); -foreach ($arrayofmodules as $file => $modCodeTiers) -{ +foreach ($arrayofmodules as $file => $modCodeTiers) { print '<tr class="oddeven">'."\n"; print '<td width="140">'.$modCodeTiers->name.'</td>'."\n"; print '<td>'.$modCodeTiers->info($langs).'</td>'."\n"; print '<td class="nowrap">'.$modCodeTiers->getExample($langs).'</td>'."\n"; - if ($conf->global->SOCIETE_CODECLIENT_ADDON == "$file") - { + if ($conf->global->SOCIETE_CODECLIENT_ADDON == "$file") { print '<td class="center">'."\n"; print img_picto($langs->trans("Activated"), 'switch_on'); print "</td>\n"; } else { $disabled = (!empty($conf->multicompany->enabled) && (is_object($mc) && !empty($mc->sharings['referent']) && $mc->sharings['referent'] != $conf->entity) ? true : false); print '<td class="center">'; - if (!$disabled) print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setcodeclient&amp;token='.newToken().'&amp;value='.urlencode($file).'">'; + if (!$disabled) { + print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setcodeclient&amp;token='.newToken().'&amp;value='.urlencode($file).'">'; + } print img_picto($langs->trans("Disabled"), 'switch_off'); - if (!$disabled) print '</a>'; + if (!$disabled) { + print '</a>'; + } print '</td>'; } @@ -430,23 +429,18 @@ print "</tr>\n"; $arrayofmodules = array(); -foreach ($dirsociete as $dirroot) -{ +foreach ($dirsociete as $dirroot) { $dir = dol_buildpath($dirroot, 0); $handle = @opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (substr($file, 0, 15) == 'mod_codecompta_' && substr($file, -3) == 'php') - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (substr($file, 0, 15) == 'mod_codecompta_' && substr($file, -3) == 'php') { $file = substr($file, 0, dol_strlen($file) - 4); try { dol_include_once($dirroot.$file.'.php'); - } catch (Exception $e) - { + } catch (Exception $e) { dol_syslog($e->getMessage(), LOG_ERR); } @@ -462,16 +456,14 @@ foreach ($dirsociete as $dirroot) $arrayofmodules = dol_sort_array($arrayofmodules, 'position'); -foreach ($arrayofmodules as $file => $modCodeCompta) -{ +foreach ($arrayofmodules as $file => $modCodeCompta) { print '<tr class="oddeven">'; print '<td>'.$modCodeCompta->name."</td><td>\n"; print $modCodeCompta->info($langs); print '</td>'; print '<td class="nowrap">'.$modCodeCompta->getExample($langs)."</td>\n"; - if ($conf->global->SOCIETE_CODECOMPTA_ADDON == "$file") - { + if ($conf->global->SOCIETE_CODECOMPTA_ADDON == "$file") { print '<td class="center">'; print img_picto($langs->trans("Activated"), 'switch_on'); print '</td>'; @@ -503,12 +495,10 @@ $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; $sql .= " WHERE type = 'company'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $i = 0; $num_rows = $db->num_rows($resql); - while ($i < $num_rows) - { + while ($i < $num_rows) { $array = $db->fetch_array($resql); array_push($def, $array[0]); $i++; @@ -527,24 +517,19 @@ print '<td class="center" width="60">'.$langs->trans("ShortInfo").'</td>'; print '<td class="center" width="60">'.$langs->trans("Preview").'</td>'; print "</tr>\n"; -foreach ($dirsociete as $dirroot) -{ +foreach ($dirsociete as $dirroot) { $dir = dol_buildpath($dirroot.'doc/', 0); $handle = @opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/\.modules\.php$/i', $file)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/\.modules\.php$/i', $file)) { $name = substr($file, 4, dol_strlen($file) - 16); $classname = substr($file, 0, dol_strlen($file) - 12); try { dol_include_once($dirroot.'doc/'.$file); - } catch (Exception $e) - { + } catch (Exception $e) { dol_syslog($e->getMessage(), LOG_ERR); } @@ -552,22 +537,26 @@ foreach ($dirsociete as $dirroot) $modulequalified = 1; if (!empty($module->version)) { - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; - elseif ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + $modulequalified = 0; + } elseif ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + $modulequalified = 0; + } } - if ($modulequalified) - { + if ($modulequalified) { print '<tr class="oddeven"><td width="100">'; print $module->name; print "</td><td>\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } print '</td>'; // Activate / Disable - if (in_array($name, $def)) - { + if (in_array($name, $def)) { print "<td class=\"center\">\n"; //if ($conf->global->COMPANY_ADDON_PDF != "$name") //{ @@ -581,8 +570,7 @@ foreach ($dirsociete as $dirroot) //} print "</td>"; } else { - if (versioncompare($module->phpmin, versionphparray()) > 0) - { + if (versioncompare($module->phpmin, versionphparray()) > 0) { print '<td class="center">'."\n"; print img_picto(dol_escape_htmltag($langs->trans("ErrorModuleRequirePHPVersion", join('.', $module->phpmin))), 'switch_off'); print "</td>"; @@ -596,8 +584,7 @@ foreach ($dirsociete as $dirroot) // Info $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $htmltooltip .= '<br>'.$langs->trans("Height").'/'.$langs->trans("Width").': '.$module->page_hauteur.'/'.$module->page_largeur; } $htmltooltip .= '<br><br><u>'.$langs->trans("FeaturesSupported").':</u>'; @@ -609,8 +596,7 @@ foreach ($dirsociete as $dirroot) // Preview print '<td class="center nowrap">'; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { $linkspec = '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&token='.newToken().'&module='.$name.'">'.img_object($langs->trans("Preview"), 'bill').'</a>'; } else { $linkspec = img_object($langs->trans("PreviewNotAvailable"), 'generic'); @@ -659,10 +645,8 @@ $profid['EMAIL'][0] = $langs->trans("EMail"); $profid['EMAIL'][1] = $langs->trans('Email'); $nbofloop = count($profid); -foreach ($profid as $key => $val) -{ - if ($profid[$key][1] != '-') - { +foreach ($profid as $key => $val) { + if ($profid[$key][1] != '-') { print '<tr class="oddeven">'; print '<td>'.$profid[$key][0]."</td><td>\n"; print $profid[$key][1]; @@ -676,8 +660,7 @@ foreach ($profid as $key => $val) $mandatory = (empty($conf->global->$idprof_mandatory) ?false:true); $invoice_mandatory = (empty($conf->global->$idprof_invoice_mandatory) ?false:true); - if ($verif) - { + if ($verif) { print '<td class="center"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setprofid&token='.newToken().'&value='.$key.'&status=0">'; print img_picto($langs->trans("Activated"), 'switch_on'); print '</a></td>'; @@ -687,8 +670,7 @@ foreach ($profid as $key => $val) print '</a></td>'; } - if ($mandatory) - { + if ($mandatory) { print '<td class="center"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setprofidmandatory&token='.newToken().'&value='.$key.'&status=0">'; print img_picto($langs->trans("Activated"), 'switch_on'); print '</a></td>'; @@ -698,8 +680,7 @@ foreach ($profid as $key => $val) print '</a></td>'; } - if ($invoice_mandatory) - { + if ($invoice_mandatory) { print '<td class="center"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setprofidinvoicemandatory&token='.newToken().'&value='.$key.'&status=0">'; print img_picto($langs->trans("Activated"), 'switch_on'); print '</a></td>'; @@ -726,6 +707,7 @@ $form = new Form($db); print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; +print '<input type="hidden" name="page_y" value="">'; print '<input type="hidden" name="action" value="updateoptions">'; print '<div class="div-table-responsive-no-min">'; @@ -739,8 +721,7 @@ print '<td width="80">&nbsp;</td></tr>'."\n"; print '<tr class="oddeven">'; print '<td width="80%">'.$form->textwithpicto($langs->trans("DelaiedFullListToSelectCompany"), $langs->trans('UseSearchToSelectCompanyTooltip'), 1).' </td>'; -if (!$conf->use_javascript_ajax) -{ +if (!$conf->use_javascript_ajax) { print '<td class="nowrap right" colspan="2">'; print $langs->trans("NotAvailableWhenAjaxDisabled"); print "</td>"; @@ -753,7 +734,7 @@ if (!$conf->use_javascript_ajax) ); print $form->selectarray("activate_COMPANY_USE_SEARCH_TO_SELECT", $arrval, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, 0, 0, '', 0, 0, 0, '', 'minwidth75imp'); print '</td><td class="right">'; - print '<input type="submit" class="button" name="COMPANY_USE_SEARCH_TO_SELECT" value="'.$langs->trans("Modify").'">'; + print '<input type="submit" class="button reposition" name="COMPANY_USE_SEARCH_TO_SELECT" value="'.$langs->trans("Modify").'">'; print "</td>"; } print '</tr>'; @@ -761,8 +742,7 @@ print '</tr>'; print '<tr class="oddeven">'; print '<td width="80%">'.$form->textwithpicto($langs->trans("DelaiedFullListToSelectContact"), $langs->trans('UseSearchToSelectContactTooltip'), 1).'</td>'; -if (!$conf->use_javascript_ajax) -{ +if (!$conf->use_javascript_ajax) { print '<td class="nowrap right" colspan="2">'; print $langs->trans("NotAvailableWhenAjaxDisabled"); print "</td>"; @@ -775,7 +755,7 @@ if (!$conf->use_javascript_ajax) ); print $form->selectarray("activate_CONTACT_USE_SEARCH_TO_SELECT", $arrval, $conf->global->CONTACT_USE_SEARCH_TO_SELECT, 0, 0, 0, '', 0, 0, 0, '', 'minwidth75imp'); print '</td><td class="right">'; - print '<input type="submit" class="button" name="CONTACT_USE_SEARCH_TO_SELECT" value="'.$langs->trans("Modify").'">'; + print '<input type="submit" class="button reposition" name="CONTACT_USE_SEARCH_TO_SELECT" value="'.$langs->trans("Modify").'">'; print "</td>"; } print '</tr>'; @@ -786,8 +766,7 @@ print '<tr class="oddeven">'; print '<td width="80%">'.$langs->trans("AddRefInList").'</td>'; print '<td>&nbsp;</td>'; print '<td class="center">'; -if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST)) -{ +if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST)) { print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setaddrefinlist&token='.newToken().'&value=0">'; print img_picto($langs->trans("Activated"), 'switch_on'); } else { @@ -801,8 +780,7 @@ print '<tr class="oddeven">'; print '<td width="80%">'.$langs->trans("AddAdressInList").'</td>'; print '<td>&nbsp;</td>'; print '<td class="center">'; -if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) -{ +if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) { print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setaddadressinlist&token='.newToken().'&value=0">'; print img_picto($langs->trans("Activated"), 'switch_on'); } else { @@ -832,8 +810,7 @@ if (!empty($conf->expedition->enabled)) { print '<td width="80%">'.$langs->trans("AskForPreferredShippingMethod").'</td>'; print '<td>&nbsp;</td>'; print '<td class="center">'; - if (!empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD)) - { + if (!empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD)) { print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setaskforshippingmet&token='.newToken().'&value=0">'; print img_picto($langs->trans("Activated"), 'switch_on'); } else { @@ -850,8 +827,7 @@ print '<tr class="oddeven">'; print '<td width="80%">'.$langs->trans("DisableProspectCustomerType").'</td>'; print '<td>&nbsp;</td>'; print '<td class="center">'; -if (!empty($conf->global->SOCIETE_DISABLE_PROSPECTSCUSTOMERS)) -{ +if (!empty($conf->global->SOCIETE_DISABLE_PROSPECTSCUSTOMERS)) { print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setdisableprospectcustomer&token='.newToken().'&value=0">'; print img_picto($langs->trans("Activated"), 'switch_on'); } else { @@ -861,16 +837,18 @@ if (!empty($conf->global->SOCIETE_DISABLE_PROSPECTSCUSTOMERS)) print '</a></td>'; print '</tr>'; -// Default Prospect/Customer thirdparty type on customer création -print '<tr class="oddeven">'; -print '<td width="80%">'.$langs->trans("DefaultCustomerType").'</td>'; -print '<td>'; -print $formcompany->selectProspectCustomerType($conf->global->THIRDPARTY_CUSTOMERTYPE_BY_DEFAULT, 'defaultcustomertype', 'defaultcustomertype', 'admin'); -print '</td>'; -print '<td class="center">'; -print '<input type="submit" class="button" name="THIRDPARTY_CUSTOMERTYPE_BY_DEFAULT" value="'.$langs->trans("Modify").'">'; -print '</td>'; -print '</tr>'; +if (empty($conf->global->SOCIETE_DISABLE_PROSPECTSCUSTOMERS)) { + // Default Prospect/Customer thirdparty type on customer création + print '<tr class="oddeven">'; + print '<td>'.$langs->trans("DefaultCustomerType").'</td>'; + print '<td>'; + print $formcompany->selectProspectCustomerType($conf->global->THIRDPARTY_CUSTOMERTYPE_BY_DEFAULT, 'defaultcustomertype', 'defaultcustomertype', 'admin'); + print '</td>'; + print '<td class="center">'; + print '<input type="submit" class="button reposition" name="THIRDPARTY_CUSTOMERTYPE_BY_DEFAULT" value="'.$langs->trans("Modify").'">'; + print '</td>'; + print '</tr>'; +} print '</table>'; print '</div>'; diff --git a/htdocs/societe/admin/societe_extrafields.php b/htdocs/societe/admin/societe_extrafields.php index 16d88142588..d1ffffd6b87 100644 --- a/htdocs/societe/admin/societe_extrafields.php +++ b/htdocs/societe/admin/societe_extrafields.php @@ -36,13 +36,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 = 'societe'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -77,8 +81,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -91,8 +94,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -104,8 +106,7 @@ if ($action == 'create') /* Edition d'un champ optionnel */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print '<br><div id="editattrib"></div>'; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/societe/agenda.php b/htdocs/societe/agenda.php index f98f7ac7ccf..8789427c64b 100644 --- a/htdocs/societe/agenda.php +++ b/htdocs/societe/agenda.php @@ -34,10 +34,11 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $langs->loadLangs(array("companies", "bills", "propal", "orders")); -if (GETPOST('actioncode', 'array')) -{ +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)); } @@ -45,19 +46,27 @@ $search_agenda_label = GETPOST('search_agenda_label'); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'societe', $socid, '&societe'); $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,DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC'; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('agendathirdparty')); @@ -69,20 +78,19 @@ $hookmanager->initHooks(array('agendathirdparty')); $parameters = array('id'=>$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)) -{ +if (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // 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 $actioncode = ''; $search_agenda_label = ''; } @@ -96,8 +104,7 @@ if (empty($reshook)) $form = new Form($db); -if ($socid > 0) -{ +if ($socid > 0) { require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; @@ -105,10 +112,14 @@ if ($socid > 0) $result = $object->fetch($socid); $title = $langs->trans("Agenda"); - if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name." - ".$title; + if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name." - ".$title; + } llxHeader('', $title); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = societe_prepare_head($object); print dol_get_fiche_head($head, 'agenda', $langs->trans("ThirdParty"), -1, 'company'); @@ -137,29 +148,31 @@ if ($socid > 0) $out = ''; $permok = $user->rights->agenda->myactions->create; - if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) - { - if (is_object($objthirdparty) && get_class($objthirdparty) == 'Societe') $out .= '&amp;originid='.$objthirdparty->id.($objthirdparty->id > 0 ? '&amp;socid='.$objthirdparty->id : '').'&amp;backtopage='.urlencode($_SERVER['PHP_SELF'].($objthirdparty->id > 0 ? '?socid='.$objthirdparty->id : '')); + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { + if (is_object($objthirdparty) && get_class($objthirdparty) == 'Societe') { + $out .= '&amp;originid='.$objthirdparty->id.($objthirdparty->id > 0 ? '&amp;socid='.$objthirdparty->id : '').'&amp;backtopage='.urlencode($_SERVER['PHP_SELF'].($objthirdparty->id > 0 ? '?socid='.$objthirdparty->id : '')); + } $out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;percentage=-1'; $out .= '&amp;datep='.dol_print_date(dol_now(), 'dayhourlog'); } $newcardbutton = ''; - if (!empty($conf->agenda->enabled)) - { - if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) - { + if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { $newcardbutton .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out); } } - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { print '<br>'; $param = '&socid='.$socid; - 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 load_fiche_titre($langs->trans("ActionsOnCompany"), $newcardbutton, ''); //print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $newcardbutton, '', 0, 1, 1); diff --git a/htdocs/societe/ajax/company.php b/htdocs/societe/ajax/company.php index a56fa0d9f81..ba33386f360 100644 --- a/htdocs/societe/ajax/company.php +++ b/htdocs/societe/ajax/company.php @@ -22,12 +22,24 @@ * \brief File to return Ajax response on thirdparty list request */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} require '../../main.inc.php'; @@ -48,16 +60,14 @@ $showtype = GETPOST('showtype', 'int'); dol_syslog(join(',', $_GET)); //print_r($_GET); -if (!empty($action) && $action == 'fetch' && !empty($id)) -{ +if (!empty($action) && $action == 'fetch' && !empty($id)) { require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $outjson = array(); $object = new Societe($db); $ret = $object->fetch($id); - if ($ret > 0) - { + if ($ret > 0) { $outref = $object->ref; $outname = $object->name; $outdesc = ''; @@ -74,7 +84,9 @@ if (!empty($action) && $action == 'fetch' && !empty($id)) top_httphead(); - if (empty($htmlname)) return; + if (empty($htmlname)) { + return; + } $match = preg_grep('/('.$htmlname.'[0-9]+)/', array_keys($_GET)); sort($match); @@ -83,12 +95,18 @@ if (!empty($action) && $action == 'fetch' && !empty($id)) // When used from jQuery, the search term is added as GET param "term". $searchkey = (($id && GETPOST($id, 'alpha')) ?GETPOST($id, 'alpha') : (($htmlname && GETPOST($htmlname, 'alpha')) ?GETPOST($htmlname, 'alpha') : '')); - if (!$searchkey) return; + if (!$searchkey) { + return; + } - if (!is_object($form)) $form = new Form($db); + if (!is_object($form)) { + $form = new Form($db); + } $arrayresult = $form->select_thirdparty_list(0, $htmlname, $filter, 1, $showtype, 0, null, $searchkey, $outjson); $db->close(); - if ($outjson) print json_encode($arrayresult); + if ($outjson) { + print json_encode($arrayresult); + } } diff --git a/htdocs/societe/ajaxcompanies.php b/htdocs/societe/ajaxcompanies.php index da7591a419b..3221aafff55 100644 --- a/htdocs/societe/ajaxcompanies.php +++ b/htdocs/societe/ajaxcompanies.php @@ -23,12 +23,24 @@ * \brief File to return Ajax response on third parties request */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} require '../main.inc.php'; @@ -50,24 +62,25 @@ dol_syslog(join(',', $_GET)); // Generation liste des societes -if (GETPOST('newcompany') || GETPOST('socid', 'int') || GETPOST('id_fourn')) -{ +if (GETPOST('newcompany') || GETPOST('socid', 'int') || GETPOST('id_fourn')) { $return_arr = array(); // Define filter on text typed $socid = $_GET['newcompany'] ? $_GET['newcompany'] : ''; - if (!$socid) $socid = $_GET['socid'] ? $_GET['socid'] : ''; - if (!$socid) $socid = $_GET['id_fourn'] ? $_GET['id_fourn'] : ''; + if (!$socid) { + $socid = $_GET['socid'] ? $_GET['socid'] : ''; + } + if (!$socid) { + $socid = $_GET['id_fourn'] ? $_GET['id_fourn'] : ''; + } $sql = "SELECT rowid, nom"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " WHERE s.entity IN (".getEntity('societe').")"; - if ($socid) - { + if ($socid) { $sql .= " AND ("; // Add criteria on name/code - if (!empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)) // Can use index - { + if (!empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)) { // Can use index $sql .= "nom LIKE '".$db->escape($socid)."%'"; $sql .= " OR code_client LIKE '".$db->escape($socid)."%'"; $sql .= " OR code_fournisseur LIKE '".$db->escape($socid)."%'"; @@ -76,7 +89,9 @@ if (GETPOST('newcompany') || GETPOST('socid', 'int') || GETPOST('id_fourn')) $sql .= " OR code_client LIKE '%".$db->escape($socid)."%'"; $sql .= " OR code_fournisseur LIKE '%".$db->escape($socid)."%'"; } - if (!empty($conf->global->SOCIETE_ALLOW_SEARCH_ON_ROWID)) $sql .= " OR rowid = '".$db->escape($socid)."'"; + if (!empty($conf->global->SOCIETE_ALLOW_SEARCH_ON_ROWID)) { + $sql .= " OR rowid = '".$db->escape($socid)."'"; + } $sql .= ")"; } //if (GETPOST("filter")) $sql.= " AND (".GETPOST("filter", "alpha").")"; // Add other filters @@ -84,12 +99,12 @@ if (GETPOST('newcompany') || GETPOST('socid', 'int') || GETPOST('id_fourn')) //dol_syslog("ajaxcompanies", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { - while ($row = $db->fetch_array($resql)) - { + if ($resql) { + while ($row = $db->fetch_array($resql)) { $label = $row['nom']; - if ($socid) $label = preg_replace('/('.preg_quote($socid, '/').')/i', '<strong>$1</strong>', $label, 1); + if ($socid) { + $label = preg_replace('/('.preg_quote($socid, '/').')/i', '<strong>$1</strong>', $label, 1); + } $row_array['label'] = $label; $row_array['value'] = $row['nom']; $row_array['key'] = $row['rowid']; diff --git a/htdocs/societe/ajaxcountries.php b/htdocs/societe/ajaxcountries.php index dfc4ffd9015..a4efc4ecc94 100644 --- a/htdocs/societe/ajaxcountries.php +++ b/htdocs/societe/ajaxcountries.php @@ -22,12 +22,24 @@ * \brief File to return Ajax response on country request */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} require '../main.inc.php'; @@ -50,8 +62,7 @@ print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]) dol_syslog(join(',', $_POST)); // Generate list of countries -if (!empty($country)) -{ +if (!empty($country)) { global $langs; $langs->load("dict"); @@ -61,11 +72,9 @@ if (!empty($country)) $sql .= " ORDER BY label ASC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { print '<ul>'; - while ($country = $db->fetch_object($resql)) - { + while ($country = $db->fetch_object($resql)) { print '<li>'; // Si traduction existe, on l'utilise, sinon on prend le libellé par défaut print ($country->code && $langs->trans("Country".$country->code) != "Country".$country->code ? $langs->trans("Country".$country->code) : ($country->label != '-' ? $country->label : '&nbsp;')); diff --git a/htdocs/societe/canvas/actions_card_common.class.php b/htdocs/societe/canvas/actions_card_common.class.php index 5686b3660d1..da7e68d4849 100644 --- a/htdocs/societe/canvas/actions_card_common.class.php +++ b/htdocs/societe/canvas/actions_card_common.class.php @@ -66,7 +66,9 @@ abstract class ActionsCardCommon //$ret = $this->getInstanceDao(); $object = new Societe($this->db); - if (!empty($id) || !empty($ref)) $object->fetch($id, $ref); + if (!empty($id) || !empty($ref)) { + $object->fetch($id, $ref); + } $this->object = $object; } @@ -85,26 +87,37 @@ abstract class ActionsCardCommon global $conf, $langs, $db, $user, $mysoc, $canvas; global $form, $formadmin, $formcompany; - if ($action == 'add' || $action == 'update') $this->assign_post($action); + if ($action == 'add' || $action == 'update') { + $this->assign_post($action); + } - if ($_GET["type"] == 'f') { $this->object->fournisseur = 1; } - if ($_GET["type"] == 'c') { $this->object->client = 1; } - if ($_GET["type"] == 'p') { $this->object->client = 2; } - if ($_GET["type"] == 'cp') { $this->object->client = 3; } - if ($_REQUEST["private"] == 1) { $this->object->particulier = 1; } + if ($_GET["type"] == 'f') { + $this->object->fournisseur = 1; + } + if ($_GET["type"] == 'c') { + $this->object->client = 1; + } + if ($_GET["type"] == 'p') { + $this->object->client = 2; + } + if ($_GET["type"] == 'cp') { + $this->object->client = 3; + } + if ($_REQUEST["private"] == 1) { + $this->object->particulier = 1; + } - foreach ($this->object as $key => $value) - { + foreach ($this->object as $key => $value) { $this->tpl[$key] = $value; } $this->tpl['error'] = get_htmloutput_errors($this->object->error, $this->object->errors); - if (is_array($GLOBALS['errors'])) $this->tpl['error'] = get_htmloutput_mesg('', $GLOBALS['errors'], 'error'); + if (is_array($GLOBALS['errors'])) { + $this->tpl['error'] = get_htmloutput_mesg('', $GLOBALS['errors'], 'error'); + } - if ($action == 'create') - { - if ($conf->use_javascript_ajax) - { + if ($action == 'create') { + if ($conf->use_javascript_ajax) { $this->tpl['ajax_selecttype'] = "\n".'<script type="text/javascript" language="javascript"> $(document).ready(function () { $("#radiocompany").click(function() { @@ -124,10 +137,8 @@ abstract class ActionsCardCommon } } - if ($action == 'create' || $action == 'edit') - { - if ($conf->use_javascript_ajax) - { + if ($action == 'create' || $action == 'edit') { + if ($conf->use_javascript_ajax) { $this->tpl['ajax_selectcountry'] = "\n".'<script type="text/javascript" language="javascript"> $(document).ready(function () { $("#selectcountry_id").change(function() { @@ -141,20 +152,22 @@ abstract class ActionsCardCommon // Load object modCodeClient $module = (!empty($conf->global->SOCIETE_CODECLIENT_ADDON) ? $conf->global->SOCIETE_CODECLIENT_ADDON : 'mod_codeclient_leopard'); - if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') - { + if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { + foreach ($dirsociete as $dirroot) { $res = dol_include_once($dirroot.$module.'.php'); - if ($res) break; + if ($res) { + break; + } } $modCodeClient = new $module($db); $this->tpl['auto_customercode'] = $modCodeClient->code_auto; // We verified if the tag prefix is used - if ($modCodeClient->code_auto) $this->tpl['prefix_customercode'] = $modCodeClient->verif_prefixIsUsed(); + if ($modCodeClient->code_auto) { + $this->tpl['prefix_customercode'] = $modCodeClient->verif_prefixIsUsed(); + } // TODO create a function $this->tpl['select_customertype'] = Form::selectarray('client', array( @@ -166,36 +179,41 @@ abstract class ActionsCardCommon // Customer $this->tpl['customercode'] = $this->object->code_client; - if ((!$this->object->code_client || $this->object->code_client == -1) && $modCodeClient->code_auto) $this->tpl['customercode'] = $modCodeClient->getNextValue($this->object, 0); + if ((!$this->object->code_client || $this->object->code_client == -1) && $modCodeClient->code_auto) { + $this->tpl['customercode'] = $modCodeClient->getNextValue($this->object, 0); + } $this->tpl['ismodifiable_customercode'] = $this->object->codeclient_modifiable(); $s = $modCodeClient->getToolTip($langs, $this->object, 0); $this->tpl['help_customercode'] = $form->textwithpicto('', $s, 1); - if (!empty($conf->fournisseur->enabled)) - { + if (!empty($conf->fournisseur->enabled)) { $this->tpl['supplier_enabled'] = 1; // Load object modCodeFournisseur $module = $conf->global->SOCIETE_CODECLIENT_ADDON; - if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') - { + if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { + foreach ($dirsociete as $dirroot) { $res = dol_include_once($dirroot.$module.'.php'); - if ($res) break; + if ($res) { + break; + } } $modCodeFournisseur = new $module; $this->tpl['auto_suppliercode'] = $modCodeFournisseur->code_auto; // We verified if the tag prefix is used - if ($modCodeFournisseur->code_auto) $this->tpl['prefix_suppliercode'] = $modCodeFournisseur->verif_prefixIsUsed(); + if ($modCodeFournisseur->code_auto) { + $this->tpl['prefix_suppliercode'] = $modCodeFournisseur->verif_prefixIsUsed(); + } // Supplier $this->tpl['yn_supplier'] = $form->selectyesno("fournisseur", $this->object->fournisseur, 1); $this->tpl['suppliercode'] = $this->object->code_fournisseur; - if ((!$this->object->code_fournisseur || $this->object->code_fournisseur == -1) && $modCodeFournisseur->code_auto) $this->tpl['suppliercode'] = $modCodeFournisseur->getNextValue($this->object, 1); + if ((!$this->object->code_fournisseur || $this->object->code_fournisseur == -1) && $modCodeFournisseur->code_auto) { + $this->tpl['suppliercode'] = $modCodeFournisseur->getNextValue($this->object, 1); + } $this->tpl['ismodifiable_suppliercode'] = $this->object->codefournisseur_modifiable(); $s = $modCodeFournisseur->getToolTip($langs, $this->object, 1); $this->tpl['help_suppliercode'] = $form->textwithpicto('', $s, 1); @@ -216,14 +234,21 @@ abstract class ActionsCardCommon $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; + } // Language - if (!empty($conf->global->MAIN_MULTILANGS)) $this->tpl['select_lang'] = $formadmin->select_language(($this->object->default_lang ? $this->object->default_lang : $conf->global->MAIN_LANG_DEFAULT), 'default_lang', 0, 0, 1); + if (!empty($conf->global->MAIN_MULTILANGS)) { + $this->tpl['select_lang'] = $formadmin->select_language(($this->object->default_lang ? $this->object->default_lang : $conf->global->MAIN_LANG_DEFAULT), 'default_lang', 0, 0, 1); + } // VAT $this->tpl['yn_assujtva'] = $form->selectyesno('assujtva_value', $this->tpl['tva_assuj'], 1); // Assujeti par defaut en creation @@ -233,24 +258,20 @@ abstract class ActionsCardCommon // Local Tax // TODO mettre dans une classe propre au pays - if ($mysoc->country_code == 'ES') - { + if ($mysoc->country_code == 'ES') { $this->tpl['localtax'] = ''; - if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") - { + if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { $this->tpl['localtax'] .= '<tr><td>'.$langs->trans("LocalTax1IsUsedES").'</td><td>'; $this->tpl['localtax'] .= $form->selectyesno('localtax1assuj_value', $this->object->localtax1_assuj, 1); $this->tpl['localtax'] .= '</td><td>'.$langs->trans("LocalTax2IsUsedES").'</td><td>'; $this->tpl['localtax'] .= $form->selectyesno('localtax2assuj_value', $this->object->localtax1_assuj, 1); $this->tpl['localtax'] .= '</td></tr>'; - } elseif ($mysoc->localtax1_assuj == "1") - { + } elseif ($mysoc->localtax1_assuj == "1") { $this->tpl['localtax'] .= '<tr><td>'.$langs->trans("LocalTax1IsUsedES").'</td><td colspan="3">'; $this->tpl['localtax'] .= $form->selectyesno('localtax1assuj_value', $this->object->localtax1_assuj, 1); $this->tpl['localtax'] .= '</td><tr>'; - } elseif ($mysoc->localtax2_assuj == "1") - { + } elseif ($mysoc->localtax2_assuj == "1") { $this->tpl['localtax'] .= '<tr><td>'.$langs->trans("LocalTax2IsUsedES").'</td><td colspan="3">'; $this->tpl['localtax'] .= $form->selectyesno('localtax2assuj_value', $this->object->localtax1_assuj, 1); $this->tpl['localtax'] .= '</td><tr>'; @@ -269,7 +290,9 @@ abstract class ActionsCardCommon $this->tpl['address'] = dol_nl2br($this->object->address); $img = picto_from_langcode($this->object->country_code); - if ($this->object->isInEEC()) $this->tpl['country'] = $form->textwithpicto(($img ? $img.' ' : '').$this->object->country, $langs->trans("CountryIsInEEC"), 1, 0); + if ($this->object->isInEEC()) { + $this->tpl['country'] = $form->textwithpicto(($img ? $img.' ' : '').$this->object->country, $langs->trans("CountryIsInEEC"), 1, 0); + } $this->tpl['country'] = ($img ? $img.' ' : '').$this->object->country; $this->tpl['phone'] = dol_print_phone($this->object->phone, $this->object->country_code, 0, $this->object->id, 'AC_TEL'); @@ -283,8 +306,7 @@ abstract class ActionsCardCommon $arr = $formcompany->typent_array(1); $this->tpl['typent'] = $arr[$this->object->typent_code]; - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; //$s=picto_from_langcode($this->default_lang); //print ($s?$s.' ':''); @@ -300,31 +322,31 @@ abstract class ActionsCardCommon $this->tpl['sales_representatives'] = ''; $listsalesrepresentatives = $this->object->getSalesRepresentatives($user); $nbofsalesrepresentative = count($listsalesrepresentatives); - if ($nbofsalesrepresentative > 3) // We print only number - { + if ($nbofsalesrepresentative > 3) { // We print only number $this->tpl['sales_representatives'] .= $nbofsalesrepresentative; } elseif ($nbofsalesrepresentative > 0) { $userstatic = new User($this->db); $i = 0; - foreach ($listsalesrepresentatives as $val) - { + foreach ($listsalesrepresentatives as $val) { $userstatic->id = $val['id']; $userstatic->lastname = $val['name']; $userstatic->firstname = $val['firstname']; $this->tpl['sales_representatives'] .= $userstatic->getNomUrl(1); $i++; - if ($i < $nbofsalesrepresentative) $this->tpl['sales_representatives'] .= ', '; + if ($i < $nbofsalesrepresentative) { + $this->tpl['sales_representatives'] .= ', '; + } } - } else $this->tpl['sales_representatives'] .= $langs->trans("NoSalesRepresentativeAffected"); + } else { + $this->tpl['sales_representatives'] .= $langs->trans("NoSalesRepresentativeAffected"); + } // Linked member - if (!empty($conf->adherent->enabled)) - { + if (!empty($conf->adherent->enabled)) { $langs->load("members"); $adh = new Adherent($this->db); $result = $adh->fetch('', '', $this->object->id); - if ($result > 0) - { + if ($result > 0) { $adh->ref = $adh->getFullName($langs); $this->tpl['linked_member'] = $adh->getNomUrl(1); } else { @@ -334,22 +356,18 @@ abstract class ActionsCardCommon // Local Tax // TODO mettre dans une classe propre au pays - if ($mysoc->country_code == 'ES') - { + if ($mysoc->country_code == 'ES') { $this->tpl['localtax'] = ''; - if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") - { + if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { $this->tpl['localtax'] .= '<tr><td>'.$langs->trans("LocalTax1IsUsedES").'</td>'; $this->tpl['localtax'] .= '<td>'.yn($this->object->localtax1_assuj).'</td>'; $this->tpl['localtax'] .= '<td>'.$langs->trans("LocalTax2IsUsedES").'</td>'; $this->tpl['localtax'] .= '<td>'.yn($this->object->localtax2_assuj).'</td></tr>'; - } elseif ($mysoc->localtax1_assuj == "1") - { + } elseif ($mysoc->localtax1_assuj == "1") { $this->tpl['localtax'] .= '<tr><td>'.$langs->trans("LocalTax1IsUsedES").'</td>'; $this->tpl['localtax'] .= '<td colspan="3">'.yn($this->object->localtax1_assuj).'</td></tr>'; - } elseif ($mysoc->localtax2_assuj == "1") - { + } elseif ($mysoc->localtax2_assuj == "1") { $this->tpl['localtax'] .= '<tr><td>'.$langs->trans("LocalTax2IsUsedES").'</td>'; $this->tpl['localtax'] .= '<td colspan="3">'.yn($this->object->localtax2_assuj).'</td></tr>'; } @@ -405,8 +423,7 @@ abstract class ActionsCardCommon $this->object->localtax2_assuj = $_POST["localtax2assuj_value"]; // We set country_id, and country_code label of the chosen country - if ($this->object->country_id) - { + if ($this->object->country_id) { $tmparray = getCountry($this->object->country_id, 'all', $this->db, $langs, 0); $this->object->country_code = $tmparray['code']; $this->object->country_label = $tmparray['label']; diff --git a/htdocs/societe/canvas/company/actions_card_company.class.php b/htdocs/societe/canvas/company/actions_card_company.class.php index 901a2c55a56..c9ebc56533e 100644 --- a/htdocs/societe/canvas/company/actions_card_company.class.php +++ b/htdocs/societe/canvas/company/actions_card_company.class.php @@ -61,9 +61,15 @@ class ActionsCardCompany extends ActionsCardCommon $out = ''; - if ($action == 'view') $out .= $langs->trans("ThirdParty"); - if ($action == 'edit') $out .= $langs->trans("EditCompany"); - if ($action == 'create') $out .= $langs->trans("NewCompany"); + if ($action == 'view') { + $out .= $langs->trans("ThirdParty"); + } + if ($action == 'edit') { + $out .= $langs->trans("EditCompany"); + } + if ($action == 'create') { + $out .= $langs->trans("NewCompany"); + } return $out; } @@ -95,8 +101,7 @@ class ActionsCardCompany extends ActionsCardCommon $this->tpl['profid3'] = $this->object->idprof3; $this->tpl['profid4'] = $this->object->idprof4; - if ($conf->use_javascript_ajax && empty($conf->global->MAIN_DISABLEVATCHECK)) - { + if ($conf->use_javascript_ajax && empty($conf->global->MAIN_DISABLEVATCHECK)) { $js = "\n"; $js .= '<script language="JavaScript" type="text/javascript">'; $js .= "function CheckVAT(a) {\n"; @@ -107,10 +112,8 @@ class ActionsCardCompany extends ActionsCardCommon $this->tpl['js_checkVatPopup'] = $js; } - if ($action == 'create' || $action == 'edit') - { - for ($i = 1; $i <= 4; $i++) - { + if ($action == 'create' || $action == 'edit') { + for ($i = 1; $i <= 4; $i++) { $this->tpl['langprofid'.$i] = $langs->transcountry('ProfId'.$i, $this->object->country_code); $this->tpl['showprofid'.$i] = $formcompany->get_input_id_prof($i, 'idprof'.$i, $this->tpl['profid'.$i], $this->object->country_code); } @@ -126,12 +129,10 @@ class ActionsCardCompany extends ActionsCardCommon // VAT intra $s = '<input type="text" class="flat" name="tva_intra" size="12" maxlength="20" value="'.$this->object->tva_intra.'">'; - if (empty($conf->global->MAIN_DISABLEVATCHECK)) - { + if (empty($conf->global->MAIN_DISABLEVATCHECK)) { $s .= ' '; - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { $s .= '<a href="#" onclick="javascript: CheckVAT(document.formsoc.tva_intra.value);">'.$langs->trans("VATIntraCheck").'</a>'; $this->tpl['tva_intra'] = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->transnoentitiesnoconv("VATIntraCheck")), 1); } else { @@ -142,29 +143,24 @@ class ActionsCardCompany extends ActionsCardCommon } } else { // Confirm delete third party - if ($action == 'delete') - { + if ($action == 'delete') { $this->tpl['action_delete'] = $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$this->object->id, $langs->trans("DeleteACompany"), $langs->trans("ConfirmDeleteCompany"), "confirm_delete", '', 0, "1,action-delete"); } - for ($i = 1; $i <= 4; $i++) - { + for ($i = 1; $i <= 4; $i++) { $this->tpl['langprofid'.$i] = $langs->transcountry('ProfId'.$i, $this->object->country_code); $this->tpl['checkprofid'.$i] = $this->object->id_prof_check($i, $this->object); $this->tpl['urlprofid'.$i] = $this->object->id_prof_url($i, $this->object); } // TVA intra - if ($this->object->tva_intra) - { + if ($this->object->tva_intra) { $s = $this->object->tva_intra; $s .= '<input type="hidden" name="tva_intra" size="12" maxlength="20" value="'.$this->object->tva_intra.'">'; - if (empty($conf->global->MAIN_DISABLEVATCHECK)) - { + if (empty($conf->global->MAIN_DISABLEVATCHECK)) { $s .= ' &nbsp; '; - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { $s .= '<a href="#" onclick="javascript: CheckVAT(document.formsoc.tva_intra.value);">'.$langs->trans("VATIntraCheck").'</a>'; $this->tpl['tva_intra'] = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->transnoentitiesnoconv("VATIntraCheck")), 1); } else { @@ -178,8 +174,7 @@ class ActionsCardCompany extends ActionsCardCommon } // Parent company - if ($this->object->parent) - { + if ($this->object->parent) { $socm = new Societe($this->db); $socm->fetch($this->object->parent); $this->tpl['parent_company'] = $socm->getNomUrl(1).' '.($socm->code_client ? "(".$socm->code_client.")" : ""); diff --git a/htdocs/societe/canvas/company/tpl/card_create.tpl.php b/htdocs/societe/canvas/company/tpl/card_create.tpl.php index e79c1cea177..2deb1dba8b1 100644 --- a/htdocs/societe/canvas/company/tpl/card_create.tpl.php +++ b/htdocs/societe/canvas/company/tpl/card_create.tpl.php @@ -17,8 +17,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -43,7 +42,9 @@ if (empty($conf) || !is_object($conf)) <?php echo $this->control->tpl['ajax_selectcountry']; ?> <?php } ?> -<?php if ($this->control->tpl['js_checkVatPopup']) echo $this->control->tpl['js_checkVatPopup']; ?> +<?php if ($this->control->tpl['js_checkVatPopup']) { + echo $this->control->tpl['js_checkVatPopup']; +} ?> <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST" name="formsoc"> @@ -61,20 +62,20 @@ if (empty($conf) || !is_object($conf)) <td><span class="fieldrequired"><?php echo $langs->trans('ThirdPartyName'); ?></span></td> <td><input type="text" size="30" maxlength="60" name="nom" value="<?php echo $this->control->tpl['nom']; ?>"></td> <?php if (!empty($conf->global->SOCIETE_USEPREFIX)) { ?> - <td><?php echo $langs->trans('Prefix'); ?></td> - <td><input type="text" size="5" maxlength="5" name="prefix_comm" value="<?php echo $this->control->tpl['prefix_comm']; ?>"></td> - <?php } ?> + <td><?php echo $langs->trans('Prefix'); ?></td> + <td><input type="text" size="5" maxlength="5" name="prefix_comm" value="<?php echo $this->control->tpl['prefix_comm']; ?>"></td> + <?php } ?> </tr> <tr> <td width="25%"><span class="fieldrequired"><?php echo $langs->trans('ProspectCustomer'); ?></span></td> <td width="25%"><?php echo $this->control->tpl['select_customertype']; ?></td> - <td width="25%"><?php echo $langs->trans('CustomerCode'); ?></td> - <td width="25%"> + <td width="25%"><?php echo $langs->trans('CustomerCode'); ?></td> + <td width="25%"> <table class="nobordernopadding"> <tr> - <td><input type="text" name="code_client" size="16" value="<?php echo $this->control->tpl['customercode']; ?>" maxlength="15"></td> + <td><input type="text" name="code_client" size="16" value="<?php echo $this->control->tpl['customercode']; ?>" maxlength="24"></td> <td><?php echo $this->control->tpl['help_customercode']; ?></td> </tr> </table> @@ -85,14 +86,14 @@ if (empty($conf) || !is_object($conf)) <tr> <td><span class="fieldrequired"><?php echo $langs->trans('Supplier'); ?></span></td> <td><?php echo $this->control->tpl['yn_supplier']; ?></td> - <td><?php echo $langs->trans('SupplierCode'); ?></td> - <td> - <table class="nobordernopadding"> - <tr> - <td><input type="text" name="code_fournisseur" size="16" value="<?php echo $this->control->tpl['suppliercode']; ?>" maxlength="15"></td> - <td><?php echo $this->control->tpl['help_suppliercode']; ?></td> - </tr> - </table> + <td><?php echo $langs->trans('SupplierCode'); ?></td> + <td> + <table class="nobordernopadding"> + <tr> + <td><input type="text" name="code_fournisseur" size="16" value="<?php echo $this->control->tpl['suppliercode']; ?>" maxlength="24"></td> + <td><?php echo $this->control->tpl['help_suppliercode']; ?></td> + </tr> + </table> </td> </tr> @@ -155,15 +156,23 @@ if (!empty($conf->barcode->enabled)) { ?> <?php for ($i = 1; $i <= 4; $i++) { if ($this->control->tpl['langprofid'.$i] != '-') { - if ($i == 1 || $i == 3) echo '<tr>'; + if ($i == 1 || $i == 3) { + echo '<tr>'; + } echo '<td>'.$this->control->tpl['langprofid'.$i].'</td>'; echo '<td>'.$this->control->tpl['showprofid'.$i].'</td>'; - if ($i == 2 || $i == 4) echo '</tr>'; + if ($i == 2 || $i == 4) { + echo '</tr>'; + } } else { - if ($i == 1 || $i == 3) echo '<tr>'; + if ($i == 1 || $i == 3) { + echo '<tr>'; + } echo '<td>&nbsp;</td>'; echo '<td>&nbsp;</td>'; - if ($i == 2 || $i == 4) echo '</tr>'; + if ($i == 2 || $i == 4) { + echo '</tr>'; + } } } ?> @@ -194,7 +203,9 @@ for ($i = 1; $i <= 4; $i++) { <td class="nowrap"><?php echo $this->control->tpl['tva_intra']; ?></td> </tr> -<?php if (!empty($this->control->tpl['localtax'])) echo $this->control->tpl['localtax']; ?> +<?php if (!empty($this->control->tpl['localtax'])) { + echo $this->control->tpl['localtax']; +} ?> <?php if ($user->rights->societe->client->voir) { ?> <tr> diff --git a/htdocs/societe/canvas/company/tpl/card_edit.tpl.php b/htdocs/societe/canvas/company/tpl/card_edit.tpl.php index 57b8a06b019..35e38a10f0e 100644 --- a/htdocs/societe/canvas/company/tpl/card_edit.tpl.php +++ b/htdocs/societe/canvas/company/tpl/card_edit.tpl.php @@ -17,8 +17,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -34,7 +33,9 @@ $contact = $GLOBALS['objcanvas']->control->object; <?php echo $this->control->tpl['error']; ?> <?php echo $this->control->tpl['ajax_selectcountry']; ?> -<?php if ($this->control->tpl['js_checkVatPopup']) echo $this->control->tpl['js_checkVatPopup']; ?> +<?php if ($this->control->tpl['js_checkVatPopup']) { + echo $this->control->tpl['js_checkVatPopup']; +} ?> <form action="<?php echo $_SERVER["PHP_SELF"].'?socid='.$this->control->tpl['id']; ?>" method="POST" name="formsoc"> <input type="hidden" name="canvas" value="<?php echo $canvas ?>"> @@ -75,7 +76,7 @@ $contact = $GLOBALS['objcanvas']->control->object; <tr> <td> <?php if ($this->control->tpl['ismodifiable_customercode']) { ?> - <input type="text" name="code_client" size="16" value="<?php echo $this->control->tpl['customercode']; ?>" maxlength="15"> + <input type="text" name="code_client" size="16" value="<?php echo $this->control->tpl['customercode']; ?>" maxlength="24"> <?php } else { ?> <?php echo $this->control->tpl['customercode']; ?> <input type="hidden" name="code_client" value="<?php echo $this->control->tpl['customercode']; ?>"> @@ -96,7 +97,7 @@ $contact = $GLOBALS['objcanvas']->control->object; <tr> <td> <?php if ($this->control->tpl['ismodifiable_suppliercode']) { ?> - <input type="text" name="code_fournisseur" size="16" value="<?php echo $this->control->tpl['suppliercode']; ?>" maxlength="15"> + <input type="text" name="code_fournisseur" size="16" value="<?php echo $this->control->tpl['suppliercode']; ?>" maxlength="24"> <?php } else { ?> <?php echo $this->control->tpl['suppliercode']; ?> <input type="hidden" name="code_fournisseur" value="<?php echo $this->control->tpl['suppliercode']; ?>"> @@ -165,15 +166,23 @@ if (!empty($conf->barcode->enabled)) { ?> <?php for ($i = 1; $i <= 4; $i++) { if ($this->control->tpl['langprofid'.$i] != '-') { - if ($i == 1 || $i == 3) echo '<tr>'; + if ($i == 1 || $i == 3) { + echo '<tr>'; + } echo '<td>'.$this->control->tpl['langprofid'.$i].'</td>'; echo '<td>'.$this->control->tpl['showprofid'.$i].'</td>'; - if ($i == 2 || $i == 4) echo '</tr>'; + if ($i == 2 || $i == 4) { + echo '</tr>'; + } } else { - if ($i == 1 || $i == 3) echo '<tr>'; + if ($i == 1 || $i == 3) { + echo '<tr>'; + } echo '<td>&nbsp;</td>'; echo '<td>&nbsp;</td>'; - if ($i == 2 || $i == 4) echo '</tr>'; + if ($i == 2 || $i == 4) { + echo '</tr>'; + } } } ?> @@ -209,7 +218,9 @@ for ($i = 1; $i <= 4; $i++) { </tr> <?php } -if (!empty($this->control->tpl['localtax'])) echo $this->control->tpl['localtax']; ?> +if (!empty($this->control->tpl['localtax'])) { + echo $this->control->tpl['localtax']; +} ?> </table> <br> diff --git a/htdocs/societe/canvas/company/tpl/card_view.tpl.php b/htdocs/societe/canvas/company/tpl/card_view.tpl.php index c56e7f9223c..8169a6ca22f 100644 --- a/htdocs/societe/canvas/company/tpl/card_view.tpl.php +++ b/htdocs/societe/canvas/company/tpl/card_view.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -34,9 +33,15 @@ print dol_get_fiche_head($head, 'card', $langs->trans("ThirdParty"), 0, 'company ?> -<?php if ($this->control->tpl['error']) echo $this->control->tpl['error']; ?> -<?php if ($this->control->tpl['action_delete']) echo $this->control->tpl['action_delete']; ?> -<?php if ($this->control->tpl['js_checkVatPopup']) echo $this->control->tpl['js_checkVatPopup']; ?> +<?php if ($this->control->tpl['error']) { + echo $this->control->tpl['error']; +} ?> +<?php if ($this->control->tpl['action_delete']) { + echo $this->control->tpl['action_delete']; +} ?> +<?php if ($this->control->tpl['js_checkVatPopup']) { + echo $this->control->tpl['js_checkVatPopup']; +} ?> <table class="border allwidth"> @@ -120,20 +125,31 @@ print dol_get_fiche_head($head, 'card', $langs->trans("ThirdParty"), 0, 'company <?php for ($i = 1; $i <= 4; $i++) { if ($this->control->tpl['langprofid'.$i] != '-') { - if ($i == 1 || $i == 3) echo '<tr>'; + if ($i == 1 || $i == 3) { + echo '<tr>'; + } echo '<td>'.$this->control->tpl['langprofid'.$i].'</td>'; echo '<td>'.$this->control->tpl['profid'.$i]; if ($this->control->tpl['profid'.$i]) { - if ($this->control->tpl['checkprofid'.$i] > 0) echo ' &nbsp; '.$this->control->tpl['urlprofid'.$i]; - else echo ' <font class="error">('.$langs->trans("ErrorWrongValue").')</font>'; + if ($this->control->tpl['checkprofid'.$i] > 0) { + echo ' &nbsp; '.$this->control->tpl['urlprofid'.$i]; + } else { + echo ' <font class="error">('.$langs->trans("ErrorWrongValue").')</font>'; + } } echo '</td>'; - if ($i == 2 || $i == 4) echo '</tr>'; + if ($i == 2 || $i == 4) { + echo '</tr>'; + } } else { - if ($i == 1 || $i == 3) echo '<tr>'; + if ($i == 1 || $i == 3) { + echo '<tr>'; + } echo '<td>&nbsp;</td>'; echo '<td>&nbsp;</td>'; - if ($i == 2 || $i == 4) echo '</tr>'; + if ($i == 2 || $i == 4) { + echo '</tr>'; + } } } ?> @@ -145,14 +161,19 @@ for ($i = 1; $i <= 4; $i++) { <td><?php echo $this->control->tpl['tva_intra']; ?></td> </tr> -<?php if (!empty($this->control->tpl['localtax'])) echo $this->control->tpl['localtax']; ?> +<?php if (!empty($this->control->tpl['localtax'])) { + echo $this->control->tpl['localtax']; +} ?> <tr> <td><?php echo $langs->trans('Capital'); ?></td> <td colspan="3"> <?php - if ($this->control->tpl['capital']) echo $this->control->tpl['capital'].' '.$langs->trans("Currency".$conf->currency); - else echo '&nbsp;'; + if ($this->control->tpl['capital']) { + echo $this->control->tpl['capital'].' '.$langs->trans("Currency".$conf->currency); + } else { + echo '&nbsp;'; + } ?> </td> </tr> @@ -258,7 +279,7 @@ for ($i = 1; $i <= 4; $i++) { <?php /* - * Documents generes + * Generated documents */ $filedir = $conf->societe->multidir_output[$this->control->tpl['entity']].'/'.$socid; $urlsource = $_SERVER["PHP_SELF"]."?socid=".$socid; diff --git a/htdocs/societe/canvas/individual/actions_card_individual.class.php b/htdocs/societe/canvas/individual/actions_card_individual.class.php index cab8a965ee0..244a50fb719 100644 --- a/htdocs/societe/canvas/individual/actions_card_individual.class.php +++ b/htdocs/societe/canvas/individual/actions_card_individual.class.php @@ -61,9 +61,15 @@ class ActionsCardIndividual extends ActionsCardCommon $out = ''; - if ($action == 'view') $out .= $langs->trans("Individual"); - if ($action == 'edit') $out .= $langs->trans("EditCompany"); - if ($action == 'create') $out .= $langs->trans("NewCompany"); + if ($action == 'view') { + $out .= $langs->trans("Individual"); + } + if ($action == 'edit') { + $out .= $langs->trans("EditCompany"); + } + if ($action == 'create') { + $out .= $langs->trans("NewCompany"); + } return $out; } @@ -107,13 +113,11 @@ class ActionsCardIndividual extends ActionsCardCommon $this->tpl['title'] = load_fiche_titre($this->getTitle($action)); - if ($action == 'create' || $action == 'edit') - { + if ($action == 'create' || $action == 'edit') { $this->tpl['select_civility'] = $formcompany->select_civility(GETPOST('civility_id')); } else { // Confirm delete third party - if ($action == 'delete' || $conf->use_javascript_ajax) - { + if ($action == 'delete' || $conf->use_javascript_ajax) { $this->tpl['action_delete'] = $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$this->object->id, $langs->trans("DeleteAnIndividual"), $langs->trans("ConfirmDeleteIndividual"), "confirm_delete", '', 0, "1,action-delete"); } } diff --git a/htdocs/societe/canvas/individual/tpl/card_create.tpl.php b/htdocs/societe/canvas/individual/tpl/card_create.tpl.php index 649d1bf8aca..0010b87ff90 100644 --- a/htdocs/societe/canvas/individual/tpl/card_create.tpl.php +++ b/htdocs/societe/canvas/individual/tpl/card_create.tpl.php @@ -17,8 +17,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -32,15 +31,15 @@ if (empty($conf) || !is_object($conf)) <?php echo $this->control->tpl['error']; ?> <?php if ($conf->use_javascript_ajax) { ?> - <?php echo $this->control->tpl['ajax_selecttype']; ?> + <?php echo $this->control->tpl['ajax_selecttype']; ?> <br> - <?php echo $langs->trans("ThirdPartyType") ?>: &nbsp; + <?php echo $langs->trans("ThirdPartyType") ?>: &nbsp; <input type="radio" id="radiocompany" class="flat" name="private" value="0"> - <?php echo $langs->trans("CompanyFoundation"); ?> &nbsp; &nbsp; + <?php echo $langs->trans("CompanyFoundation"); ?> &nbsp; &nbsp; <input type="radio" id="radioprivate" class="flat" name="private" value="1" checked> <?php echo $langs->trans("Individual"); ?> (<?php echo $langs->trans("ToCreateContactWithSameName") ?>) <br> <br> - <?php echo $this->control->tpl['ajax_selectcountry']; ?> + <?php echo $this->control->tpl['ajax_selectcountry']; ?> <?php } ?> <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST" name="formsoc"> @@ -80,11 +79,11 @@ if (empty($conf) || !is_object($conf)) <td width="25%"><span class="fieldrequired"><?php echo $langs->trans('ProspectCustomer'); ?></span></td> <td width="25%"><?php echo $this->control->tpl['select_customertype']; ?></td> - <td width="25%"><?php echo $langs->trans('CustomerCode'); ?></td> - <td width="25%"> + <td width="25%"><?php echo $langs->trans('CustomerCode'); ?></td> + <td width="25%"> <table class="nobordernopadding"> <tr> - <td><input type="text" name="code_client" size="16" value="<?php echo $this->control->tpl['customercode']; ?>" maxlength="15"></td> + <td><input type="text" name="code_client" size="16" value="<?php echo $this->control->tpl['customercode']; ?>" maxlength="24"></td> <td><?php echo $this->control->tpl['help_customercode']; ?></td> </tr> </table> @@ -95,23 +94,23 @@ if (empty($conf) || !is_object($conf)) <tr> <td><span class="fieldrequired"><?php echo $langs->trans('Supplier'); ?></span></td> <td><?php echo $this->control->tpl['yn_supplier']; ?></td> - <td><?php echo $langs->trans('SupplierCode'); ?></td> - <td> - <table class="nobordernopadding"> - <tr> - <td><input type="text" name="code_fournisseur" size="16" value="<?php echo $this->control->tpl['suppliercode']; ?>" maxlength="15"></td> - <td><?php echo $this->control->tpl['help_suppliercode']; ?></td> - </tr> - </table> + <td><?php echo $langs->trans('SupplierCode'); ?></td> + <td> + <table class="nobordernopadding"> + <tr> + <td><input type="text" name="code_fournisseur" size="16" value="<?php echo $this->control->tpl['suppliercode']; ?>" maxlength="24"></td> + <td><?php echo $this->control->tpl['help_suppliercode']; ?></td> + </tr> + </table> </td> </tr> - <?php if (count($this->control->tpl['suppliercategory']) > 0) { ?> + <?php if (count($this->control->tpl['suppliercategory']) > 0) { ?> <tr> <td><?php echo $langs->trans('SupplierCategory'); ?></td> <td colspan="3"><?php echo $this->control->tpl['select_suppliercategory']; ?></td> </tr> - <?php } + <?php } } if (!empty($conf->barcode->enabled)) { ?> @@ -169,7 +168,9 @@ if (!empty($conf->barcode->enabled)) { ?> <td colspan="3"><?php echo $this->control->tpl['yn_assujtva']; ?></td> </tr> -<?php if (!empty($this->control->tpl['localtax'])) echo $this->control->tpl['localtax']; ?> +<?php if (!empty($this->control->tpl['localtax'])) { + echo $this->control->tpl['localtax']; +} ?> <?php if ($user->rights->societe->client->voir) { ?> <tr> diff --git a/htdocs/societe/canvas/individual/tpl/card_edit.tpl.php b/htdocs/societe/canvas/individual/tpl/card_edit.tpl.php index b5f57544c5f..7a43f256b45 100644 --- a/htdocs/societe/canvas/individual/tpl/card_edit.tpl.php +++ b/htdocs/societe/canvas/individual/tpl/card_edit.tpl.php @@ -17,8 +17,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -73,7 +72,7 @@ if (empty($conf) || !is_object($conf)) <tr> <td> <?php if ($this->control->tpl['ismodifiable_customercode']) { ?> - <input type="text" name="code_client" size="16" value="<?php echo $this->control->tpl['customercode']; ?>" maxlength="15"> + <input type="text" name="code_client" size="16" value="<?php echo $this->control->tpl['customercode']; ?>" maxlength="24"> <?php } else { ?> <?php echo $this->control->tpl['customercode']; ?> <input type="hidden" name="code_client" value="<?php echo $this->control->tpl['customercode']; ?>"> @@ -94,7 +93,7 @@ if (empty($conf) || !is_object($conf)) <tr> <td> <?php if ($this->control->tpl['ismodifiable_suppliercode']) { ?> - <input type="text" name="code_fournisseur" size="16" value="<?php echo $this->control->tpl['suppliercode']; ?>" maxlength="15"> + <input type="text" name="code_fournisseur" size="16" value="<?php echo $this->control->tpl['suppliercode']; ?>" maxlength="24"> <?php } else { ?> <?php echo $this->control->tpl['suppliercode']; ?> <input type="hidden" name="code_fournisseur" value="<?php echo $this->control->tpl['suppliercode']; ?>"> @@ -173,7 +172,9 @@ if ($this->control->tpl['fournisseur']) { <td colspan="3"><?php echo $this->control->tpl['yn_assujtva']; ?></td> </tr> -<?php if (!empty($this->control->tpl['localtax'])) echo $this->control->tpl['localtax']; ?> +<?php if (!empty($this->control->tpl['localtax'])) { + echo $this->control->tpl['localtax']; +} ?> </table> <br> diff --git a/htdocs/societe/canvas/individual/tpl/card_view.tpl.php b/htdocs/societe/canvas/individual/tpl/card_view.tpl.php index 0ee2f271312..f058d38cd7c 100644 --- a/htdocs/societe/canvas/individual/tpl/card_view.tpl.php +++ b/htdocs/societe/canvas/individual/tpl/card_view.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -32,8 +31,12 @@ $head = societe_prepare_head($object); print dol_get_fiche_head($head, 'card', $langs->trans("ThirdParty"), 0, 'company'); -if ($this->control->tpl['error']) echo $this->control->tpl['error']; -if ($this->control->tpl['action_delete']) echo $this->control->tpl['action_delete']; ?> +if ($this->control->tpl['error']) { + echo $this->control->tpl['error']; +} +if ($this->control->tpl['action_delete']) { + echo $this->control->tpl['action_delete']; +} ?> <table class="border allwidth"> @@ -119,7 +122,9 @@ if ($this->control->tpl['action_delete']) echo $this->control->tpl['action_delet <td colspan="3"><?php echo $this->control->tpl['tva_assuj']; ?></td> </tr> -<?php if (!empty($this->control->tpl['localtax'])) echo $this->control->tpl['localtax']; ?> +<?php if (!empty($this->control->tpl['localtax'])) { + echo $this->control->tpl['localtax']; +} ?> <tr> <td><?php echo $langs->trans("Type"); ?></td> @@ -200,7 +205,7 @@ if ($this->control->tpl['action_delete']) echo $this->control->tpl['action_delet <div id="builddoc"></div> <?php /* - * Documents generes + * Generated documents */ $filedir = $conf->societe->multidir_output[$this->control->tpl['entity']].'/'.$socid; $urlsource = $_SERVER["PHP_SELF"]."?socid=".$socid; diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index b471ca23ead..6f9ee362a82 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -12,7 +12,7 @@ * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr> * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com> * Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es.com> - * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -45,16 +45,32 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; -if (!empty($conf->adherent->enabled)) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; -if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; -if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; -if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +if (!empty($conf->adherent->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; +} +if (! empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +} +if (! empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +} +if (! empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +} $langs->loadLangs(array("companies", "commercial", "bills", "banks", "users")); -if (!empty($conf->adherent->enabled)) $langs->load("members"); -if (!empty($conf->categorie->enabled)) $langs->load("categories"); -if (!empty($conf->incoterm->enabled)) $langs->load("incoterm"); -if (!empty($conf->notification->enabled)) $langs->load("mails"); +if (!empty($conf->adherent->enabled)) { + $langs->load("members"); +} +if (!empty($conf->categorie->enabled)) { + $langs->load("categories"); +} +if (!empty($conf->incoterm->enabled)) { + $langs->load("incoterm"); +} +if (!empty($conf->notification->enabled)) { + $langs->load("mails"); +} $mesg = ''; $error = 0; $errors = array(); @@ -64,8 +80,12 @@ $backtopage = GETPOST('backtopage', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); $socid = GETPOST('socid', 'int') ?GETPOST('socid', 'int') : GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; -if (empty($socid) && $action == 'view') $action = 'create'; +if ($user->socid && empty($conf->global->MAIN_EXTERNAL_USERS_CAN_SEE_SUBSIDIARY_COMPANIES)) { + $socid = $user->socid; +} +if (empty($socid) && $action == 'view') { + $action = 'create'; +} $object = new Societe($db); $extrafields = new ExtraFields($db); @@ -78,10 +98,11 @@ $socialnetworks = getArrayOfSocialNetworks(); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('thirdpartycard', 'globalcard')); -if ($socid > 0) $object->fetch($socid); +if ($socid > 0) { + $object->fetch($socid); +} -if (!($object->id > 0) && $action == 'view') -{ +if (!($object->id > 0) && $action == 'view') { $langs->load("errors"); print($langs->trans('ErrorRecordNotFound')); exit; @@ -90,8 +111,7 @@ if (!($object->id > 0) && $action == 'view') // Get object canvas (By default, this is not defined, so standard usage of dolibarr) $canvas = $object->canvas ? $object->canvas : GETPOST("canvas"); $objcanvas = null; -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('thirdparty', 'card', $canvas); @@ -124,39 +144,34 @@ $upload_dir = $conf->societe->multidir_output[isset($object->entity) ? $object-> $parameters = array('id'=>$socid, '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)) -{ - if ($cancel) - { +if (empty($reshook)) { + if ($cancel) { $action = ''; - if (!empty($backtopage)) - { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } } - if ($action == 'confirm_merge' && $confirm == 'yes' && $user->rights->societe->creer) - { + if ($action == 'confirm_merge' && $confirm == 'yes' && $user->rights->societe->creer) { $error = 0; $soc_origin_id = GETPOST('soc_origin', 'int'); $soc_origin = new Societe($db); - if ($soc_origin_id <= 0) - { + if ($soc_origin_id <= 0) { $langs->load('errors'); setEventMessages($langs->trans('ErrorThirdPartyIdIsMandatory', $langs->transnoentitiesnoconv('MergeOriginThirdparty')), null, 'errors'); } else { - if (!$error && $soc_origin->fetch($soc_origin_id) < 1) - { + if (!$error && $soc_origin->fetch($soc_origin_id) < 1) { setEventMessages($langs->trans('ErrorRecordNotFound'), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { // TODO Move the merge function into class of object. $db->begin(); @@ -172,26 +187,26 @@ if (empty($reshook)) 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur', 'model_pdf', 'fk_projet' ); - foreach ($listofproperties as $property) - { - if (empty($object->$property)) $object->$property = $soc_origin->$property; + foreach ($listofproperties as $property) { + if (empty($object->$property)) { + $object->$property = $soc_origin->$property; + } } // Concat some data $listofproperties = array( 'note_public', 'note_private' ); - foreach ($listofproperties as $property) - { + foreach ($listofproperties as $property) { $object->$property = dol_concatdesc($object->$property, $soc_origin->$property); } // Merge extrafields - if (is_array($soc_origin->array_options)) - { - foreach ($soc_origin->array_options as $key => $val) - { - if (empty($object->array_options[$key])) $object->array_options[$key] = $val; + if (is_array($soc_origin->array_options)) { + foreach ($soc_origin->array_options as $key => $val) { + if (empty($object->array_options[$key])) { + $object->array_options[$key] = $val; + } } } @@ -211,8 +226,7 @@ if (empty($reshook)) // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys. if ($soc_origin->code_client == $object->code_client || $soc_origin->code_fournisseur == $object->code_fournisseur - || $soc_origin->barcode == $object->barcode) - { + || $soc_origin->barcode == $object->barcode) { dol_syslog("We clean customer and supplier code so we will be able to make the update of target"); $soc_origin->code_client = ''; $soc_origin->code_fournisseur = ''; @@ -222,19 +236,18 @@ if (empty($reshook)) // Update $result = $object->update($object->id, $user, 0, 1, 1, 'merge'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } // Move links - if (!$error) - { + if (!$error) { // This list is also into the api_thirdparties.class.php // TODO Mutualise the list into object societe.class.php $objects = array( 'Adherent' => '/adherents/class/adherent.class.php', + 'Don' => '/don/class/don.class.php', 'Societe' => '/societe/class/societe.class.php', //'Categorie' => '/categories/class/categorie.class.php', 'ActionComm' => '/comm/action/class/actioncomm.class.php', @@ -260,59 +273,51 @@ if (empty($reshook)) ); //First, all core objects must update their tables - foreach ($objects as $object_name => $object_file) - { + foreach ($objects as $object_name => $object_file) { require_once DOL_DOCUMENT_ROOT.$object_file; - if (!$error && !$object_name::replaceThirdparty($db, $soc_origin->id, $object->id)) - { + if (!$error && !$object_name::replaceThirdparty($db, $soc_origin->id, $object->id)) { $error++; setEventMessages($db->lasterror(), null, 'errors'); + break; } } } // External modules should update their ones too - if (!$error) - { + if (!$error) { $reshook = $hookmanager->executeHooks('replaceThirdparty', array( 'soc_origin' => $soc_origin->id, 'soc_dest' => $object->id ), $object, $action); - if ($reshook < 0) - { + if ($reshook < 0) { setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { $object->context = array('merge'=>1, 'mergefromid'=>$soc_origin->id); // Call trigger $result = $object->call_trigger('COMPANY_MODIFY', $user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } // End call triggers } - if (!$error) - { + if (!$error) { //We finally remove the old thirdparty - if ($soc_origin->delete($soc_origin->id, $user) < 1) - { + if ($soc_origin->delete($soc_origin->id, $user) < 1) { $error++; } } - if (!$error) - { + if (!$error) { setEventMessages($langs->trans('ThirdpartiesMergeSuccess'), null, 'mesgs'); $db->commit(); } else { @@ -324,27 +329,23 @@ if (empty($reshook)) } } - if (GETPOST('getcustomercode')) - { + if (GETPOST('getcustomercode')) { // We defined value code_client $_POST["customer_code"] = "Acompleter"; } - if (GETPOST('getsuppliercode')) - { + if (GETPOST('getsuppliercode')) { // We defined value code_fournisseur $_POST["supplier_code"] = "Acompleter"; } - if ($action == 'set_localtax1') - { + if ($action == 'set_localtax1') { //obtidre selected del combobox $value = GETPOST('lt1'); $object->fetch($socid); $res = $object->setValueFrom('localtax1_value', $value, '', null, 'text', '', $user, 'COMPANY_MODIFY'); } - if ($action == 'set_localtax2') - { + if ($action == 'set_localtax2') { //obtidre selected del combobox $value = GETPOST('lt2'); $object->fetch($socid); @@ -360,39 +361,37 @@ if (empty($reshook)) $extrafields->fetch_name_optionals_label($object->table_element); $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { $result = $object->insertExtraFields('COMPANY_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } - if ($error) $action = 'edit_extras'; + if ($error) { + $action = 'edit_extras'; + } } // Add new or update third party if ((!GETPOST('getcustomercode') && !GETPOST('getsuppliercode')) - && ($action == 'add' || $action == 'update') && $user->rights->societe->creer) - { + && ($action == 'add' || $action == 'update') && $user->rights->societe->creer) { require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - if (!GETPOST('name')) - { + if (!GETPOST('name')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdPartyName")), null, 'errors'); $error++; } - if (GETPOST('client') < 0) - { + if (GETPOST('client') < 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProspectCustomer")), null, 'errors'); $error++; } - if (GETPOST('fournisseur') < 0) - { + if (GETPOST('fournisseur') < 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Supplier")), null, 'errors'); $error++; } @@ -407,16 +406,15 @@ if (empty($reshook)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("No_Email")), null, 'errors'); } - if (!$error) - { - if ($action == 'update') - { + if (!$error) { + if ($action == 'update') { $ret = $object->fetch($socid); $object->oldcopy = clone $object; - } else $object->canvas = $canvas; + } else { + $object->canvas = $canvas; + } - if (GETPOST("private", 'int') == 1) // Ask to create a contact - { + if (GETPOST("private", 'int') == 1) { // Ask to create a contact $object->particulier = GETPOST("private", 'int'); $object->name = dolGetFirstLastname(GETPOST('firstname', 'alphanohtml'), GETPOST('name', 'alphanohtml')); @@ -489,58 +487,57 @@ if (empty($reshook)) $object->webservices_url = GETPOST('webservices_url', 'custom', 0, FILTER_SANITIZE_URL); $object->webservices_key = GETPOST('webservices_key', 'san_alpha'); - if (GETPOSTISSET('accountancy_code_sell')) $object->accountancy_code_sell = GETPOST('accountancy_code_sell', 'alpha'); - if (GETPOSTISSET('accountancy_code_buy')) $object->accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); + if (GETPOSTISSET('accountancy_code_sell')) { + $object->accountancy_code_sell = GETPOST('accountancy_code_sell', 'alpha'); + } + if (GETPOSTISSET('accountancy_code_buy')) { + $object->accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); + } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); } // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); } // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) - { + if ($ret < 0) { $error++; } // Fill array 'array_languages' with data from add form $ret = $object->setValuesForExtraLanguages(); - if ($ret < 0) - { + if ($ret < 0) { $error++; } //var_dump($object->array_languages);exit; - if (GETPOST('deletephoto')) $object->logo = ''; - elseif (!empty($_FILES['photo']['name'])) $object->logo = dol_sanitizeFileName($_FILES['photo']['name']); + if (GETPOST('deletephoto')) { + $object->logo = ''; + } elseif (!empty($_FILES['photo']['name'])) { + $object->logo = dol_sanitizeFileName($_FILES['photo']['name']); + } // Check parameters - if (!GETPOST('cancel', 'alpha')) - { - if (!empty($object->email) && !isValidEMail($object->email)) - { + if (!GETPOST('cancel', 'alpha')) { + if (!empty($object->email) && !isValidEMail($object->email)) { $langs->load("errors"); $error++; setEventMessages('', $langs->trans("ErrorBadEMail", $object->email), 'errors'); } - if (!empty($object->url) && !isValidUrl($object->url)) - { + if (!empty($object->url) && !isValidUrl($object->url)) { $langs->load("errors"); setEventMessages('', $langs->trans("ErrorBadUrl", $object->url), 'errors'); } if (!empty($object->webservices_url)) { //Check if has transport, without any the soap client will give error - if (strpos($object->webservices_url, "http") === false) - { + if (strpos($object->webservices_url, "http") === false) { $object->webservices_url = "http://".$object->webservices_url; } if (!isValidUrl($object->webservices_url)) { @@ -551,8 +548,7 @@ if (empty($reshook)) // We set country_id, country_code and country for the selected country $object->country_id = GETPOST('country_id') != '' ?GETPOST('country_id') : $mysoc->country_id; - if ($object->country_id) - { + if ($object->country_id) { $tmparray = getCountry($object->country_id, 'all'); $object->country_code = $tmparray['code']; $object->country = $tmparray['label']; @@ -560,29 +556,28 @@ if (empty($reshook)) } } - if (!$error) - { - if ($action == 'add') - { + if (!$error) { + if ($action == 'add') { $error = 0; $db->begin(); - if (empty($object->client)) $object->code_client = ''; - if (empty($object->fournisseur)) $object->code_fournisseur = ''; + if (empty($object->client)) { + $object->code_client = ''; + } + if (empty($object->fournisseur)) { + $object->code_fournisseur = ''; + } $result = $object->create($user); - if ($result >= 0) - { - if ($object->particulier) - { + if ($result >= 0) { + if ($object->particulier) { dol_syslog("We ask to create a contact/address too", LOG_DEBUG); $contcats = GETPOST('contcats', 'array'); $no_email = GETPOST('contact_no_email', 'int'); $result = $object->create_individual($user, $no_email, $contcats); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -591,8 +586,7 @@ if (empty($reshook)) // Links with users $salesreps = GETPOST('commercial', 'array'); $result = $object->setSalesRep($salesreps, true); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } @@ -600,8 +594,7 @@ if (empty($reshook)) // Customer categories association $custcats = GETPOST('custcats', 'array'); $result = $object->setCategories($custcats, 'customer'); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } @@ -609,8 +602,7 @@ if (empty($reshook)) // Supplier categories association $suppcats = GETPOST('suppcats', 'array'); $result = $object->setCategories($suppcats, 'supplier'); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } @@ -618,19 +610,15 @@ if (empty($reshook)) // Logo/Photo save $dir = $conf->societe->multidir_output[$conf->entity]."/".$object->id."/logos/"; $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']); - if ($file_OK) - { - if (image_format_supported($_FILES['photo']['name'])) - { + if ($file_OK) { + if (image_format_supported($_FILES['photo']['name'])) { dol_mkdir($dir); - if (@is_dir($dir)) - { + if (@is_dir($dir)) { $newfile = $dir.'/'.dol_sanitizeFileName($_FILES['photo']['name']); $result = dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1); - if (!$result > 0) - { + if (!$result > 0) { $errors[] = "ErrorFailedToSaveFile"; } else { // Create thumbs @@ -639,26 +627,23 @@ if (empty($reshook)) } } } else { - switch ($_FILES['photo']['error']) - { + switch ($_FILES['photo']['error']) { case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form $errors[] = "ErrorFileSizeTooLarge"; break; - case 3: //uploaded file was only partially uploaded + case 3: //uploaded file was only partially uploaded $errors[] = "ErrorFilePartiallyUploaded"; break; } - } + } } else { - if ($result == -3 && in_array('ErrorCustomerCodeAlreadyUsed', $object->errors)) - { + if ($result == -3 && in_array('ErrorCustomerCodeAlreadyUsed', $object->errors)) { $duplicate_code_error = true; $object->code_client = null; } - if ($result == -3 && in_array('ErrorSupplierCodeAlreadyUsed', $object->errors)) - { + if ($result == -3 && in_array('ErrorSupplierCodeAlreadyUsed', $object->errors)) { $duplicate_code_error = true; $object->code_fournisseur = null; } @@ -668,7 +653,7 @@ if (empty($reshook)) } setEventMessages($object->error, $object->errors, 'errors'); - $error++; + $error++; } if ($result >= 0 && !$error) { @@ -676,13 +661,18 @@ if (empty($reshook)) if (!empty($backtopage)) { $backtopage = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $backtopage); // New method to autoselect project after a New on another form object creation - if (preg_match('/\?/', $backtopage)) $backtopage .= '&socid='.$object->id; // Old method - header("Location: ".$backtopage); + if (preg_match('/\?/', $backtopage)) { + $backtopage .= '&socid='.$object->id; // Old method + } + header("Location: ".$backtopage); exit; } else { $url = $_SERVER["PHP_SELF"]."?socid=".$object->id; // Old method - if (($object->client == 1 || $object->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) $url = DOL_URL_ROOT."/comm/card.php?socid=".$object->id; - elseif ($object->fournisseur == 1) $url = DOL_URL_ROOT."/fourn/card.php?socid=".$object->id; + if (($object->client == 1 || $object->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) { + $url = DOL_URL_ROOT."/comm/card.php?socid=".$object->id; + } elseif ($object->fournisseur == 1) { + $url = DOL_URL_ROOT."/fourn/card.php?socid=".$object->id; + } header("Location: ".$url); exit; @@ -693,31 +683,31 @@ if (empty($reshook)) } } - if ($action == 'update') - { + if ($action == 'update') { $error = 0; - if (GETPOST('cancel', 'alpha')) - { - if (!empty($backtopage)) - { - header("Location: ".$backtopage); + if (GETPOST('cancel', 'alpha')) { + if (!empty($backtopage)) { + header("Location: ".$backtopage); exit; } else { - header("Location: ".$_SERVER["PHP_SELF"]."?socid=".$socid); + header("Location: ".$_SERVER["PHP_SELF"]."?socid=".$socid); exit; } } // To not set code if third party is not concerned. But if it had values, we keep them. - if (empty($object->client) && empty($object->oldcopy->code_client)) $object->code_client = ''; - if (empty($object->fournisseur) && empty($object->oldcopy->code_fournisseur)) $object->code_fournisseur = ''; + if (empty($object->client) && empty($object->oldcopy->code_client)) { + $object->code_client = ''; + } + if (empty($object->fournisseur) && empty($object->oldcopy->code_fournisseur)) { + $object->code_fournisseur = ''; + } //var_dump($object);exit; $result = $object->update($socid, $user, 1, $object->oldcopy->codeclient_modifiable(), $object->oldcopy->codefournisseur_modifiable(), 'update', 0); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -725,20 +715,17 @@ if (empty($reshook)) // Links with users $salesreps = GETPOST('commercial', 'array'); $result = $object->setSalesRep($salesreps); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } // Prevent thirdparty's emptying if a user hasn't rights $user->rights->categorie->lire (in such a case, post of 'custcats' is not defined) - if (!$error && !empty($user->rights->categorie->lire)) - { + if (!$error && !empty($user->rights->categorie->lire)) { // Customer categories association $categories = GETPOST('custcats', 'array'); $result = $object->setCategories($categories, 'customer'); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } @@ -746,8 +733,7 @@ if (empty($reshook)) // Supplier categories association $categories = GETPOST('suppcats', 'array'); $result = $object->setCategories($categories, 'supplier'); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } @@ -756,34 +742,28 @@ if (empty($reshook)) // Logo/Photo save $dir = $conf->societe->multidir_output[$object->entity]."/".$object->id."/logos"; $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']); - if (GETPOST('deletephoto') && $object->logo) - { + if (GETPOST('deletephoto') && $object->logo) { $fileimg = $dir.'/'.$object->logo; $dirthumbs = $dir.'/thumbs'; dol_delete_file($fileimg); dol_delete_dir_recursive($dirthumbs); } - if ($file_OK) - { - if (image_format_supported($_FILES['photo']['name']) > 0) - { + if ($file_OK) { + if (image_format_supported($_FILES['photo']['name']) > 0) { dol_mkdir($dir); - if (@is_dir($dir)) - { + if (@is_dir($dir)) { $newfile = $dir.'/'.dol_sanitizeFileName($_FILES['photo']['name']); $result = dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1); - if (!$result > 0) - { + if (!$result > 0) { $errors[] = "ErrorFailedToSaveFile"; } else { // Create thumbs $object->addThumbs($newfile); // Index file in database - if (!empty($conf->global->THIRDPARTY_LOGO_ALLOW_EXTERNAL_DOWNLOAD)) - { + if (!empty($conf->global->THIRDPARTY_LOGO_ALLOW_EXTERNAL_DOWNLOAD)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // the dir dirname($newfile) is directory of logo, so we should have only one file at once into index, so we delete indexes for the dir deleteFilesIntoDatabaseIndex(dirname($newfile), '', ''); @@ -796,13 +776,12 @@ if (empty($reshook)) $errors[] = "ErrorBadImageFormat"; } } else { - switch ($_FILES['photo']['error']) - { + switch ($_FILES['photo']['error']) { case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form $errors[] = "ErrorFileSizeTooLarge"; break; - case 3: //uploaded file was only partially uploaded + case 3: //uploaded file was only partially uploaded $errors[] = "ErrorFilePartiallyUploaded"; break; } @@ -811,26 +790,22 @@ if (empty($reshook)) // Update linked member - if (!$error && $object->fk_soc > 0) - { + if (!$error && $object->fk_soc > 0) { $sql = "UPDATE ".MAIN_DB_PREFIX."adherent"; $sql .= " SET fk_soc = NULL WHERE fk_soc = ".$id; - if (!$object->db->query($sql)) - { + if (!$object->db->query($sql)) { $error++; $object->error .= $object->db->lasterror(); setEventMessages($object->error, $object->errors, 'errors'); } } - if (!$error && !count($errors)) - { - if (!empty($backtopage)) - { - header("Location: ".$backtopage); + if (!$error && !count($errors)) { + if (!empty($backtopage)) { + header("Location: ".$backtopage); exit; } else { - header("Location: ".$_SERVER["PHP_SELF"]."?socid=".$socid); + header("Location: ".$_SERVER["PHP_SELF"]."?socid=".$socid); exit; } } else { @@ -844,48 +819,42 @@ if (empty($reshook)) } // Delete third party - if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->societe->supprimer) - { + if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->societe->supprimer) { $object->fetch($socid); $object->oldcopy = clone $object; $result = $object->delete($socid, $user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".DOL_URL_ROOT."/societe/list.php?restore_lastsearch_values=1&delsoc=".urlencode($object->name)); exit; } else { $langs->load("errors"); - setEventMessages($object->error, $object->errors, 'errors'); - $error++; + setEventMessages($object->error, $object->errors, 'errors'); + $error++; $action = ''; } } // Set third-party type - if ($action == 'set_thirdpartytype' && $user->rights->societe->creer) - { + if ($action == 'set_thirdpartytype' && $user->rights->societe->creer) { $object->fetch($socid); $result = $object->setThirdpartyType(GETPOST('typent_id', 'int')); } // Set incoterm - if ($action == 'set_incoterms' && $user->rights->societe->creer && !empty($conf->incoterm->enabled)) - { + if ($action == 'set_incoterms' && $user->rights->societe->creer && !empty($conf->incoterm->enabled)) { $object->fetch($socid); $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); } // Set parent company - if ($action == 'set_thirdparty' && $user->rights->societe->creer) - { + if ($action == 'set_thirdparty' && $user->rights->societe->creer) { $object->fetch($socid); $result = $object->set_parent(GETPOST('parent_id', 'int')); } // Set sales representatives - if ($action == 'set_salesrepresentatives' && $user->rights->societe->creer) - { + if ($action == 'set_salesrepresentatives' && $user->rights->societe->creer) { $object->fetch($socid); $result = $object->setSalesRep(GETPOST('commercial', 'array')); } @@ -921,73 +890,83 @@ $form = new Form($db); $formfile = new FormFile($db); $formadmin = new FormAdmin($db); $formcompany = new FormCompany($db); -if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); +if (! empty($conf->accounting->enabled)) { + $formaccounting = new FormAccounting($db); +} -if ($socid > 0 && empty($object->id)) -{ +if ($socid > 0 && empty($object->id)) { $result = $object->fetch($socid); - if ($result <= 0) dol_print_error('', $object->error); + if ($result <= 0) { + dol_print_error('', $object->error); + } } $title = $langs->trans("ThirdParty"); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name." - ".$langs->trans('Card'); -$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name." - ".$langs->trans('Card'); +} + +$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas|DE:Modul_Geschäftspartner'; + llxHeader('', $title, $help_url); $countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; -if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) -{ +if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { // ----------------------------------------- // When used with CANVAS // ----------------------------------------- - $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 { // ----------------------------------------- // When used in standard mode // ----------------------------------------- - if ($action == 'create') - { + if ($action == 'create') { /* - * Creation - */ + * Creation + */ $private = GETPOST("private", "int"); - if (!empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT) && !GETPOSTISSET('private')) $private = 1; - if (empty($private)) $private = 0; + if (!empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT) && !GETPOSTISSET('private')) { + $private = 1; + } + if (empty($private)) { + $private = 0; + } // Load object modCodeTiers $module = (!empty($conf->global->SOCIETE_CODECLIENT_ADDON) ? $conf->global->SOCIETE_CODECLIENT_ADDON : 'mod_codeclient_leopard'); - if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') - { + if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { + foreach ($dirsociete as $dirroot) { $res = dol_include_once($dirroot.$module.'.php'); - if ($res) break; + if ($res) { + break; + } } $modCodeClient = new $module; // Load object modCodeFournisseur $module = (!empty($conf->global->SOCIETE_CODECLIENT_ADDON) ? $conf->global->SOCIETE_CODECLIENT_ADDON : 'mod_codeclient_leopard'); - if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') - { + if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { + foreach ($dirsociete as $dirroot) { $res = dol_include_once($dirroot.$module.'.php'); - if ($res) break; + if ($res) { + break; + } } $modCodeFournisseur = new $module; // Define if customer/prospect or supplier status is set or not - if (GETPOST("type") != 'f') - { + if (GETPOST("type") != 'f') { $object->client = -1; - if (!empty($conf->global->THIRDPARTY_CUSTOMERPROSPECT_BY_DEFAULT)) { $object->client = 3; } + if (!empty($conf->global->THIRDPARTY_CUSTOMERPROSPECT_BY_DEFAULT)) { + $object->client = 3; + } } // Prospect / Customer if (GETPOST("type") == 'c') { @@ -997,8 +976,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $object->client = 3; } } - if (GETPOST("type") == 'p') { $object->client = 2; } - if (!empty($conf->fournisseur->enabled) && (GETPOST("type") == 'f' || (GETPOST("type") == '' && !empty($conf->global->THIRDPARTY_SUPPLIER_BY_DEFAULT)))) { $object->fournisseur = 1; } + if (GETPOST("type") == 'p') { + $object->client = 2; + } + if (!empty($conf->fournisseur->enabled) && (GETPOST("type") == 'f' || (GETPOST("type") == '' && !empty($conf->global->THIRDPARTY_SUPPLIER_BY_DEFAULT)))) { + $object->fournisseur = 1; + } $object->name = GETPOST('name', 'alphanohtml'); $object->name_alias = GETPOST('name_alias', 'alphanohtml'); @@ -1062,27 +1045,27 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $object->commercial_id = GETPOST('commercial_id', 'int'); $object->default_lang = GETPOST('default_lang'); - if (GETPOSTISSET('accountancy_code_sell')) $object->accountancy_code_sell = GETPOST('accountancy_code_sell', 'alpha'); - if (GETPOSTISSET('accountancy_code_buy')) $object->accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); + if (GETPOSTISSET('accountancy_code_sell')) { + $object->accountancy_code_sell = GETPOST('accountancy_code_sell', 'alpha'); + } + if (GETPOSTISSET('accountancy_code_buy')) { + $object->accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); + } $object->logo = (isset($_FILES['photo']) ?dol_sanitizeFileName($_FILES['photo']['name']) : ''); // Gestion du logo de la société $dir = $conf->societe->multidir_output[$conf->entity]."/".$object->id."/logos"; $file_OK = (isset($_FILES['photo']) ?is_uploaded_file($_FILES['photo']['tmp_name']) : false); - if ($file_OK) - { - if (image_format_supported($_FILES['photo']['name'])) - { + if ($file_OK) { + if (image_format_supported($_FILES['photo']['name'])) { dol_mkdir($dir); - if (@is_dir($dir)) - { + if (@is_dir($dir)) { $newfile = $dir.'/'.dol_sanitizeFileName($_FILES['photo']['name']); $result = dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1); - if (!$result > 0) - { + if (!$result > 0) { $errors[] = "ErrorFailedToSaveFile"; } else { // Create thumbs @@ -1094,8 +1077,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // We set country_id, country_code and country for the selected country $object->country_id = GETPOST('country_id') ?GETPOST('country_id') : $mysoc->country_id; - if ($object->country_id) - { + if ($object->country_id) { $tmparray = getCountry($object->country_id, 'all'); $object->country_code = $tmparray['code']; $object->country = $tmparray['label']; @@ -1121,14 +1103,18 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $("#radiocompany").click(function() { $(".individualline").hide(); $("#typent_id").val(0); + $("#typent_id").change(); $("#effectif_id").val(0); + $("#effectif_id").change(); $("#TypeName").html(document.formsoc.ThirdPartyName.value); document.formsoc.private.value=0; }); $("#radioprivate").click(function() { $(".individualline").show(); $("#typent_id").val(id_te_private); + $("#typent_id").change(); $("#effectif_id").val(id_ef15); + $("#effectif_id").change(); $("#TypeName").html(document.formsoc.LastName.value); document.formsoc.private.value=1; }); @@ -1228,7 +1214,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<input type="hidden" name="type" value='.GETPOST("type", 'alpha').'>'; print '<input type="hidden" name="LastName" value="'.$langs->trans('ThirdPartyName').' / '.$langs->trans('LastName').'">'; print '<input type="hidden" name="ThirdPartyName" value="'.$langs->trans('ThirdPartyName').'">'; - if ($modCodeClient->code_auto || $modCodeFournisseur->code_auto) print '<input type="hidden" name="code_auto" value="1">'; + if ($modCodeClient->code_auto || $modCodeFournisseur->code_auto) { + print '<input type="hidden" name="code_auto" value="1">'; + } print dol_get_fiche_head(null, 'card', '', 0, ''); @@ -1245,17 +1233,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<input type="text" class="minwidth300" maxlength="128" name="name" id="name" value="'.dol_escape_htmltag($object->name).'" autofocus="autofocus">'; print $form->widgetForTranslation("name", $object, $permissiontoadd, 'string', 'alpahnohtml', 'minwidth300'); print '</td>'; - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<td>'.$langs->trans('Prefix').'</td><td><input type="text" size="5" maxlength="5" name="prefix_comm" value="'.dol_escape_htmltag($object->prefix_comm).'"></td>'; } print '</tr>'; // If javascript on, we show option individual - if ($conf->use_javascript_ajax) - { - if (!empty($conf->global->THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION)) - { + if ($conf->use_javascript_ajax) { + if (!empty($conf->global->THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION)) { // Firstname print '<tr class="individualline"><td>'.$form->editfieldkey('FirstName', 'firstname', '', $object, 0).'</td>'; print '<td colspan="3"><input type="text" class="minwidth300" maxlength="128" name="firstname" id="firstname" value="'.dol_escape_htmltag($object->firstname).'"></td>'; @@ -1279,13 +1264,17 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print $formcompany->selectProspectCustomerType($selected); print '</td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td>'.$form->editfieldkey('CustomerCode', 'customer_code', '', $object, 0).'</td><td>'; print '<table class="nobordernopadding"><tr><td>'; $tmpcode = $object->code_client; - if (empty($tmpcode) && !empty($modCodeClient->code_auto)) $tmpcode = $modCodeClient->getNextValue($object, 0); - print '<input type="text" name="customer_code" id="customer_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">'; + if (empty($tmpcode) && !empty($modCodeClient->code_auto)) { + $tmpcode = $modCodeClient->getNextValue($object, 0); + } + print '<input type="text" name="customer_code" id="customer_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="24">'; print '</td><td>'; $s = $modCodeClient->getToolTip($langs, $object, 0); print $form->textwithpicto('', $s, 1); @@ -1293,31 +1282,34 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; if ((!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) - || (!empty($conf->supplier_proposal->enabled) && !empty($user->rights->supplier_proposal->lire))) - { + || (!empty($conf->supplier_proposal->enabled) && !empty($user->rights->supplier_proposal->lire))) { // Supplier print '<tr>'; print '<td>'.$form->editfieldkey('Vendor', 'fournisseur', '', $object, 0, 'string', '', 1).'</td><td>'; $default = -1; - if (!empty($conf->global->THIRDPARTY_SUPPLIER_BY_DEFAULT)) $default = 1; + if (!empty($conf->global->THIRDPARTY_SUPPLIER_BY_DEFAULT)) { + $default = 1; + } print $form->selectyesno("fournisseur", (GETPOST('fournisseur', 'int') != '' ? GETPOST('fournisseur', 'int') : (GETPOST("type", 'alpha') == '' ? $default : $object->fournisseur)), 1, 0, (GETPOST("type", 'alpha') == '' ? 1 : 0), 1); print '</td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td>'; - if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) - { + if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) { print $form->editfieldkey('SupplierCode', 'supplier_code', '', $object, 0); } print '</td><td>'; - if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) - { + if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) { print '<table class="nobordernopadding"><tr><td>'; $tmpcode = $object->code_fournisseur; - if (empty($tmpcode) && !empty($modCodeFournisseur->code_auto)) $tmpcode = $modCodeFournisseur->getNextValue($object, 1); - print '<input type="text" name="supplier_code" id="supplier_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">'; + if (empty($tmpcode) && !empty($modCodeFournisseur->code_auto)) { + $tmpcode = $modCodeFournisseur->getNextValue($object, 1); + } + print '<input type="text" name="supplier_code" id="supplier_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="24">'; print '</td><td>'; $s = $modCodeFournisseur->getToolTip($langs, $object, 1); print $form->textwithpicto('', $s, 1); @@ -1332,10 +1324,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Barcode - if (!empty($conf->barcode->enabled)) - { + if (!empty($conf->barcode->enabled)) { print '<tr><td>'.$form->editfieldkey('Gencod', 'barcode', '', $object, 0).'</td>'; - print '<td colspan="3"><input type="text" name="barcode" id="barcode" value="'.dol_escape_htmltag($object->barcode).'">'; + print '<td colspan="3">'; + print img_picto('', 'barcode'); + print '<input type="text" name="barcode" id="barcode" value="'.dol_escape_htmltag($object->barcode).'">'; print '</td></tr>'; } @@ -1354,7 +1347,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr><td>'.$form->editfieldkey('Zip', 'zipcode', '', $object, 0).'</td><td>'; print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth100'); print '</td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td class="tdtop">'.$form->editfieldkey('Town', 'town', '', $object, 0).'</td><td>'; print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth100 quatrevingtpercent'); print $form->widgetForTranslation("town", $object, $permissiontoadd, 'string', 'alphanohtml', 'maxwidth100 quatrevingtpercent'); @@ -1362,30 +1357,35 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Country print '<tr><td>'.$form->editfieldkey('Country', 'selectcountry_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">'; - print img_picto('', 'globe-americas', 'class="paddingrightonly"'); + print img_picto('', 'country', 'class="paddingrightonly"'); print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id') : $object->country_id), 'country_id', '', 0, 'minwidth300 maxwidth500 widthcentpercentminusx'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '</td></tr>'; // State - if (empty($conf->global->SOCIETE_DISABLE_STATE)) - { - if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) - { + if (empty($conf->global->SOCIETE_DISABLE_STATE)) { + if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) { print '<tr><td>'.$form->editfieldkey('Region-State', 'state_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">'; } else { print '<tr><td>'.$form->editfieldkey('State', 'state_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">'; } - if ($object->country_id) print $formcompany->select_state($object->state_id, $object->country_code); - else print $countrynotdefined; + if ($object->country_id) { + print $formcompany->select_state($object->state_id, $object->country_code); + } else { + print $countrynotdefined; + } print '</td></tr>'; } // Phone / Fax print '<tr><td>'.$form->editfieldkey('Phone', 'phone', '', $object, 0).'</td>'; print '<td'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>'.img_picto('', 'object_phoning').' <input type="text" name="phone" id="phone" class="maxwidth200 widthcentpercentminusx" value="'.(GETPOSTISSET('phone') ?GETPOST('phone', 'alpha') : $object->phone).'"></td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td>'.$form->editfieldkey('Fax', 'fax', '', $object, 0).'</td>'; print '<td'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>'.img_picto('', 'object_phoning_fax').' <input type="text" name="fax" id="fax" class="maxwidth200 widthcentpercentminusx" value="'.(GETPOSTISSET('fax') ?GETPOST('fax', 'alpha') : $object->fax).'"></td></tr>'; @@ -1393,7 +1393,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr><td>'.$form->editfieldkey('EMail', 'email', '', $object, 0, 'string', '', empty($conf->global->SOCIETE_EMAIL_MANDATORY) ? '' : $conf->global->SOCIETE_EMAIL_MANDATORY).'</td>'; print '<td'.(($conf->browser->layout == 'phone') || empty($conf->mailing->enabled) ? ' colspan="3"' : '').'>'.img_picto('', 'object_email').' <input type="text" class="maxwidth200 widthcentpercentminusx" name="email" id="email" value="'.$object->email.'"></td>'; if (!empty($conf->mailing->enabled) && !empty($conf->global->THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION)) { - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td class="individualline noemail">'.$form->editfieldkey($langs->trans('No_Email') .' ('.$langs->trans('Contact').')', 'contact_no_email', '', $object, 0).'</td>'; print '<td class="individualline" '.(($conf->browser->layout == 'phone') || empty($conf->mailing->enabled) ? ' colspan="3"' : '').'>'.$form->selectyesno('contact_no_email', (GETPOSTISSET("contact_no_email") ?GETPOST("contact_no_email", 'alpha') : $object->no_email), 1, false, 1).'</td>'; } @@ -1407,6 +1409,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr>'; print '<td><label for="'.$value['label'].'">'.$form->editfieldkey($value['label'], $key, '', $object, 0).'</label></td>'; print '<td colspan="3">'; + if (!empty($value['icon'])) { + print '<span class="fa '.$value['icon'].'"></span>'; + } print '<input type="text" name="'.$key.'" id="'.$key.'" class="minwidth100" maxlength="80" value="'.dol_escape_htmltag(GETPOSTISSET($key) ? GETPOST($key, 'alphanohtml') : (empty($object->socialnetworks[$key]) ? '' : $object->socialnetworks[$key])).'">'; print '</td>'; print '</tr>'; @@ -1423,26 +1428,34 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) if ($idprof != '-') { $key = 'idprof'.$i; - if (($j % $NBCOLS) == 0) print '<tr>'; + if (($j % $NBCOLS) == 0) { + print '<tr>'; + } $idprof_mandatory = 'SOCIETE_IDPROF'.($i).'_MANDATORY'; print '<td>'.$form->editfieldkey($idprof, $key, '', $object, 0, 'string', '', (empty($conf->global->$idprof_mandatory) ? 0 : 1)).'</td><td>'; print $formcompany->get_input_id_prof($i, $key, $object->$key, $object->country_code); print '</td>'; - if (($j % $NBCOLS) == ($NBCOLS - 1)) print '</tr>'; + if (($j % $NBCOLS) == ($NBCOLS - 1)) { + print '</tr>'; + } $j++; } $i++; } - if ($NBCOLS > 1 && ($j % 2 == 1)) print '<td colspan="2"></td></tr>'; + if ($NBCOLS > 1 && ($j % 2 == 1)) { + print '<td colspan="2"></td></tr>'; + } // Vat is used print '<tr><td>'.$form->editfieldkey('VATIsUsed', 'assujtva_value', '', $object, 0).'</td>'; print '<td>'; print $form->selectyesno('assujtva_value', GETPOSTISSET('assujtva_value') ?GETPOST('assujtva_value', 'int') : 1, 1); // Assujeti par defaut en creation print '</td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td class="nowrap">'.$form->editfieldkey('VATIntra', 'intra_vat', '', $object, 0).'</td>'; print '<td class="nowrap">'; $s = '<input type="text" class="flat maxwidthonsmartphone" name="tva_intra" id="intra_vat" maxlength="20" value="'.$object->tva_intra.'">'; @@ -1452,7 +1465,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) if (!empty($conf->use_javascript_ajax)) { $widthpopup = 600; - if (!empty($conf->dol_use_jmobile)) $widthpopup = 350; + if (!empty($conf->dol_use_jmobile)) { + $widthpopup = 350; + } $heightpopup = 400; print "\n"; print '<script language="JavaScript" type="text/javascript">'; @@ -1473,22 +1488,21 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Local Taxes //TODO: Place into a function to control showing by country or study better option - if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") - { + if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td>'; print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1 : 0), 1); print '</td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td>'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td>'; print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2 : 0), 1); print '</td></tr>'; - } elseif ($mysoc->localtax1_assuj == "1") - { + } elseif ($mysoc->localtax1_assuj == "1") { print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td colspan="3">'; print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1 : 0), 1); print '</td></tr>'; - } elseif ($mysoc->localtax2_assuj == "1") - { + } elseif ($mysoc->localtax2_assuj == "1") { print '<tr><td>'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td colspan="3">'; print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2 : 0), 1); print '</td></tr>'; @@ -1498,19 +1512,24 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr><td>'.$form->editfieldkey('ThirdPartyType', 'typent_id', '', $object, 0).'</td><td class="maxwidthonsmartphone"'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>'."\n"; $sortparam = (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label. print $form->selectarray("typent_id", $formcompany->typent_array(0), $object->typent_id, 1, 0, 0, '', 0, 0, 0, $sortparam, '', 1); - if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '</td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td>'.$form->editfieldkey('Workforce', 'effectif_id', '', $object, 0).'</td><td class="maxwidthonsmartphone"'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>'; print $form->selectarray("effectif_id", $formcompany->effectif_array(0), $object->effectif_id, 0, 0, 0, '', 0, 0, 0, '', '', 1); - if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '</td></tr>'; // Legal Form print '<tr><td>'.$form->editfieldkey('JuridicalStatus', 'forme_juridique_code', '', $object, 0).'</td>'; print '<td colspan="3" class="maxwidthonsmartphone">'; - if ($object->country_id) - { + if ($object->country_id) { print $formcompany->select_juridicalstatus($object->forme_juridique_code, $object->country_code, '', 'forme_juridique_code'); } else { print $countrynotdefined; @@ -1522,17 +1541,15 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<td colspan="3"><input type="text" name="capital" id="capital" class="maxwidth100" value="'.$object->capital.'"> '; print '<span class="hideonsmartphone">'.$langs->trans("Currency".$conf->currency).'</span></td></tr>'; - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { print '<tr><td>'.$form->editfieldkey('DefaultLang', 'default_lang', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">'."\n"; - print $formadmin->select_language(GETPOST('default_lang', 'alpha') ? GETPOST('default_lang', 'alpha') : ($object->default_lang ? $object->default_lang : ''), 'default_lang', 0, 0, 1, 0, 0, 'maxwidth200onsmartphone'); + print img_picto('', 'language').$formadmin->select_language(GETPOST('default_lang', 'alpha') ? GETPOST('default_lang', 'alpha') : ($object->default_lang ? $object->default_lang : ''), 'default_lang', 0, 0, 1, 0, 0, 'maxwidth200onsmartphone'); print '</td>'; print '</tr>'; } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '<tr>'; print '<td>'.$form->editfieldkey('IncotermLabel', 'incoterm_id', '', $object, 0).'</td>'; print '<td colspan="3" class="maxwidthonsmartphone">'; @@ -1541,8 +1558,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Categories - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) - { + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { $langs->load('categories'); // Customer @@ -1553,16 +1569,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print "</td></tr>"; //} - if (!empty($conf->global->THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION)) - { + if (!empty($conf->global->THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION)) { print '<tr class="individualline"><td class="toptd">'.$form->editfieldkey('ContactCategoriesShort', 'contcats', '', $object, 0).'</td><td colspan="3">'; $cate_arbo = $form->select_all_categories(Categorie::TYPE_CONTACT, null, 'parent', null, null, 1); print img_picto('', 'category').$form->multiselectarray('contcats', $cate_arbo, GETPOST('contcats', 'array'), null, null, 'quatrevingtpercent widthcentpercentminusx', 0, 0); print "</td></tr>"; } - if (!empty($conf->global->THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION)) - { + if (!empty($conf->global->THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION)) { print '<tr class="individualline"><td class="toptd">'.$form->editfieldkey('ContactCategoriesShort', 'contcats', '', $object, 0).'</td><td colspan="3">'; $cate_arbo = $form->select_all_categories(Categorie::TYPE_CONTACT, null, 'parent', null, null, 1); print img_picto('', 'category').$form->multiselectarray('contcats', $cate_arbo, GETPOST('contcats', 'array'), null, null, 'quatrevingtpercent widthcentpercentminusx', 0, 0); @@ -1579,8 +1593,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<tr>'; print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>'; print '<td colspan="3" class="maxwidthonsmartphone">'; @@ -1602,7 +1615,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print img_picto('', 'user').$form->multiselectarray('commercial', $userlist, $selected, null, null, 'quatrevingtpercent widthcentpercentminusx', 0, 0); print '</td></tr>'; - // Ajout du logo + // Add logo print '<tr class="hideonsmartphone">'; print '<td>'.$form->editfieldkey('Logo', 'photoinput', '', $object, 0).'</td>'; print '<td colspan="3">'; @@ -1616,8 +1629,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) if (!empty($conf->global->ACCOUNTANCY_USE_PRODUCT_ACCOUNT_ON_THIRDPARTY)) { print '<table class="border" width="100%">'; - if (! empty($conf->accounting->enabled)) - { + if (! empty($conf->accounting->enabled)) { // Accountancy_code_sell print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellCode").'</td>'; print '<td>'; @@ -1631,8 +1643,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); print $formaccounting->select_account($accountancy_code_buy, 'accountancy_code_buy', 1, null, 1, 1, ''); print '</td></tr>'; - } - else // For external software + } else // For external software { // Accountancy_code_sell print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellCode").'</td>'; @@ -1652,8 +1663,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<div class="center">'; print '<input type="submit" class="button" name="create" value="'.$langs->trans('AddThirdParty').'">'; - if (!empty($backtopage)) - { + if (!empty($backtopage)) { print ' &nbsp; &nbsp; '; print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; } else { @@ -1666,8 +1676,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } elseif ($action == 'edit') { //print load_fiche_titre($langs->trans("EditCompany")); - if ($socid) - { + if ($socid) { $res = $object->fetch_optionals(); //if ($res < 0) { dol_print_error($db); exit; } @@ -1675,44 +1684,41 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Load object modCodeTiers $module = (!empty($conf->global->SOCIETE_CODECLIENT_ADDON) ? $conf->global->SOCIETE_CODECLIENT_ADDON : 'mod_codeclient_leopard'); - if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') - { + if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { + foreach ($dirsociete as $dirroot) { $res = dol_include_once($dirroot.$module.'.php'); - if ($res) break; + if ($res) { + break; + } } $modCodeClient = new $module($db); // We verified if the tag prefix is used - if ($modCodeClient->code_auto) - { + if ($modCodeClient->code_auto) { $prefixCustomerIsUsed = $modCodeClient->verif_prefixIsUsed(); } $module = $conf->global->SOCIETE_CODECLIENT_ADDON; - if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') - { + if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { + foreach ($dirsociete as $dirroot) { $res = dol_include_once($dirroot.$module.'.php'); - if ($res) break; + if ($res) { + break; + } } $modCodeFournisseur = new $module($db); // On verifie si la balise prefix est utilisee - if ($modCodeFournisseur->code_auto) - { + if ($modCodeFournisseur->code_auto) { $prefixSupplierIsUsed = $modCodeFournisseur->verif_prefixIsUsed(); } $object->oldcopy = clone $object; - if (GETPOSTISSET('name')) - { + if (GETPOSTISSET('name')) { // We overwrite with values if posted $object->name = GETPOST('name', 'alphanohtml'); $object->prefix_comm = GETPOST('prefix_comm', 'alphanohtml'); @@ -1762,12 +1768,15 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $object->webservices_url = GETPOST('webservices_url', 'custom', 0, FILTER_SANITIZE_URL); $object->webservices_key = GETPOST('webservices_key', 'san_alpha'); - if (GETPOSTISSET('accountancy_code_sell')) $object->accountancy_code_sell = GETPOST('accountancy_code_sell', 'alpha'); - if (GETPOSTISSET('accountancy_code_buy')) $object->accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); + if (GETPOSTISSET('accountancy_code_sell')) { + $object->accountancy_code_sell = GETPOST('accountancy_code_sell', 'alpha'); + } + if (GETPOSTISSET('accountancy_code_buy')) { + $object->accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); + } //Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('lcoation_incoterms', 'alpha'); } @@ -1780,8 +1789,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $object->localtax2_value = GETPOST('lt2'); // We set country_id, and country_code label of the chosen country - if ($object->country_id > 0) - { + if ($object->country_id > 0) { $tmparray = getCountry($object->country_id, 'all'); $object->country_code = $tmparray['code']; $object->country = $tmparray['label']; @@ -1790,13 +1798,16 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) if ($object->localtax1_assuj == 0) { $sub = 0; - } else {$sub = 1; } + } else { + $sub = 1; + } if ($object->localtax2_assuj == 0) { $sub2 = 0; - } else {$sub2 = 1; } + } else { + $sub2 = 1; + } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print "\n".'<script type="text/javascript">'; print '$(document).ready(function () { var val='.$sub.'; @@ -1878,7 +1889,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="socid" value="'.$object->id.'">'; print '<input type="hidden" name="entity" value="'.$object->entity.'">'; - if ($modCodeClient->code_auto || $modCodeFournisseur->code_auto) print '<input type="hidden" name="code_auto" value="1">'; + if ($modCodeClient->code_auto || $modCodeFournisseur->code_auto) { + print '<input type="hidden" name="code_auto" value="1">'; + } print dol_get_fiche_head($head, 'card', $langs->trans("ThirdParty"), 0, 'company'); @@ -1887,8 +1900,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<table class="border centpercent">'; // Ref/ID - if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) - { + if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { print '<tr><td class="titlefieldcreate">'.$langs->trans("ID").'</td><td colspan="3">'; print $object->ref; print '</td></tr>'; @@ -1905,12 +1917,10 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<td colspan="3"><input type="text" class="minwidth300" name="name_alias" id="name_alias_input" value="'.dol_escape_htmltag($object->name_alias).'"></td></tr>'; // Prefix - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td>'.$form->editfieldkey('Prefix', 'prefix', '', $object, 0).'</td><td colspan="3">'; // It does not change the prefix mode using the auto numbering prefix - if (($prefixCustomerIsUsed || $prefixSupplierIsUsed) && $object->prefix_comm) - { + if (($prefixCustomerIsUsed || $prefixSupplierIsUsed) && $object->prefix_comm) { print '<input type="hidden" name="prefix_comm" value="'.dol_escape_htmltag($object->prefix_comm).'">'; print $object->prefix_comm; } else { @@ -1924,19 +1934,23 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<td class="maxwidthonsmartphone">'; print $formcompany->selectProspectCustomerType($object->client); print '</td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td>'.$form->editfieldkey('CustomerCode', 'customer_code', '', $object, 0).'</td><td>'; print '<table class="nobordernopadding"><tr><td>'; - if ((!$object->code_client || $object->code_client == -1) && $modCodeClient->code_auto) - { + if ((!$object->code_client || $object->code_client == -1) && $modCodeClient->code_auto) { $tmpcode = $object->code_client; - if (empty($tmpcode) && !empty($object->oldcopy->code_client)) $tmpcode = $object->oldcopy->code_client; // When there is an error to update a thirdparty, the number for supplier and customer code is kept to old value. - if (empty($tmpcode) && !empty($modCodeClient->code_auto)) $tmpcode = $modCodeClient->getNextValue($object, 0); - print '<input type="text" name="customer_code" id="customer_code" size="16" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">'; - } elseif ($object->codeclient_modifiable()) - { - print '<input type="text" name="customer_code" id="customer_code" size="16" value="'.dol_escape_htmltag($object->code_client).'" maxlength="15">'; + if (empty($tmpcode) && !empty($object->oldcopy->code_client)) { + $tmpcode = $object->oldcopy->code_client; // When there is an error to update a thirdparty, the number for supplier and customer code is kept to old value. + } + if (empty($tmpcode) && !empty($modCodeClient->code_auto)) { + $tmpcode = $modCodeClient->getNextValue($object, 0); + } + print '<input type="text" name="customer_code" id="customer_code" size="16" value="'.dol_escape_htmltag($tmpcode).'" maxlength="24">'; + } elseif ($object->codeclient_modifiable()) { + print '<input type="text" name="customer_code" id="customer_code" size="16" value="'.dol_escape_htmltag($object->code_client).'" maxlength="24">'; } else { print $object->code_client; print '<input type="hidden" name="customer_code" value="'.dol_escape_htmltag($object->code_client).'">'; @@ -1950,31 +1964,33 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Supplier if ((!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) - || (!empty($conf->supplier_proposal->enabled) && !empty($user->rights->supplier_proposal->lire))) - { + || (!empty($conf->supplier_proposal->enabled) && !empty($user->rights->supplier_proposal->lire))) { print '<tr>'; print '<td>'.$form->editfieldkey('Supplier', 'fournisseur', '', $object, 0, 'string', '', 1).'</td>'; print '<td class="maxwidthonsmartphone">'; print $form->selectyesno("fournisseur", $object->fournisseur, 1, false, 0, 1); print '</td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td>'; - if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) - { + if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) { print $form->editfieldkey('SupplierCode', 'supplier_code', '', $object, 0); } print '</td>'; print '<td>'; print '<table class="nobordernopadding"><tr><td>'; - if ((!$object->code_fournisseur || $object->code_fournisseur == -1) && $modCodeFournisseur->code_auto) - { + if ((!$object->code_fournisseur || $object->code_fournisseur == -1) && $modCodeFournisseur->code_auto) { $tmpcode = $object->code_fournisseur; - if (empty($tmpcode) && !empty($object->oldcopy->code_fournisseur)) $tmpcode = $object->oldcopy->code_fournisseur; // When there is an error to update a thirdparty, the number for supplier and customer code is kept to old value. - if (empty($tmpcode) && !empty($modCodeFournisseur->code_auto)) $tmpcode = $modCodeFournisseur->getNextValue($object, 1); - print '<input type="text" name="supplier_code" id="supplier_code" size="16" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">'; - } elseif ($object->codefournisseur_modifiable()) - { - print '<input type="text" name="supplier_code" id="supplier_code" size="16" value="'.dol_escape_htmltag($object->code_fournisseur).'" maxlength="15">'; + if (empty($tmpcode) && !empty($object->oldcopy->code_fournisseur)) { + $tmpcode = $object->oldcopy->code_fournisseur; // When there is an error to update a thirdparty, the number for supplier and customer code is kept to old value. + } + if (empty($tmpcode) && !empty($modCodeFournisseur->code_auto)) { + $tmpcode = $modCodeFournisseur->getNextValue($object, 1); + } + print '<input type="text" name="supplier_code" id="supplier_code" size="16" value="'.dol_escape_htmltag($tmpcode).'" maxlength="24">'; + } elseif ($object->codefournisseur_modifiable()) { + print '<input type="text" name="supplier_code" id="supplier_code" size="16" value="'.dol_escape_htmltag($object->code_fournisseur).'" maxlength="24">'; } else { print $object->code_fournisseur; print '<input type="hidden" name="supplier_code" value="'.$object->code_fournisseur.'">'; @@ -1987,10 +2003,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Barcode - if (!empty($conf->barcode->enabled)) - { + if (!empty($conf->barcode->enabled)) { print '<tr><td class="tdtop">'.$form->editfieldkey('Gencod', 'barcode', '', $object, 0).'</td>'; - print '<td colspan="3"><input type="text" name="barcode" id="barcode" value="'.dol_escape_htmltag($object->barcode).'">'; + print '<td colspan="3">'; + print img_picto('', 'barcode'); + print '<input type="text" name="barcode" id="barcode" value="'.dol_escape_htmltag($object->barcode).'">'; print '</td></tr>'; } @@ -2011,7 +2028,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr><td>'.$form->editfieldkey('Zip', 'zipcode', '', $object, 0).'</td><td>'; print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth100'); print '</td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td>'.$form->editfieldkey('Town', 'town', '', $object, 0).'</td><td>'; print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id')); print $form->widgetForTranslation("town", $object, $permissiontoadd, 'string', 'alphanohtml', 'maxwidth100 quatrevingtpercent'); @@ -2021,14 +2040,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr><td>'.$form->editfieldkey('Country', 'selectcounty_id', '', $object, 0).'</td><td colspan="3">'; print img_picto('', 'globe-americas', 'class="paddingrightonly"'); print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id') : $object->country_id), 'country_id', '', 0, 'minwidth300 maxwidth500 widthcentpercentminusx'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '</td></tr>'; // State - if (empty($conf->global->SOCIETE_DISABLE_STATE)) - { - if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) - { + if (empty($conf->global->SOCIETE_DISABLE_STATE)) { + if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) { print '<tr><td>'.$form->editfieldkey('Region-State', 'state_id', '', $object, 0).'</td><td colspan="3">'; } else { print '<tr><td>'.$form->editfieldkey('State', 'state_id', '', $object, 0).'</td><td colspan="3">'; @@ -2041,7 +2060,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Phone / Fax print '<tr><td>'.$form->editfieldkey('Phone', 'phone', GETPOST('phone', 'alpha'), $object, 0).'</td>'; print '<td>'.img_picto('', 'object_phoning').' <input type="text" name="phone" id="phone" class="maxwidth200 widthcentpercentminusx" value="'.(GETPOSTISSET('phone') ?GETPOST('phone', 'alpha') : $object->phone).'"></td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td>'.$form->editfieldkey('Fax', 'fax', GETPOST('fax', 'alpha'), $object, 0).'</td>'; print '<td>'.img_picto('', 'object_phoning_fax').' <input type="text" name="fax" id="fax" class="maxwidth200 widthcentpercentminusx" value="'.(GETPOSTISSET('fax') ?GETPOST('fax', 'alpha') : $object->fax).'"></td></tr>'; @@ -2057,7 +2078,10 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr>'; print '<td><label for="'.$value['label'].'">'.$form->editfieldkey($value['label'], $key, '', $object, 0).'</label></td>'; print '<td colspan="3">'; - print '<input type="text" name="'.$key.'" id="'.$key.'" class="minwidth100" maxlength="80" value="'.$object->socialnetworks[$key].'">'; + if (!empty($value['icon'])) { + print '<span class="fa '.$value['icon'].'"></span>'; + } + print '<input type="text" name="'.$key.'" id="'.$key.'" class="minwidth100" maxlength="80" value="'.(empty($object->socialnetworks[$key]) ? '' : $object->socialnetworks[$key]).'">'; print '</td>'; print '</tr>'; } elseif (!empty($object->socialnetworks[$key])) { @@ -2067,26 +2091,32 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Prof ids - $i = 1; $j = 0; $NBCOLS = ($conf->browser->layout == 'phone' ? 1 : 2); - while ($i <= 6) - { + $i = 1; + $j = 0; + $NBCOLS = ($conf->browser->layout == 'phone' ? 1 : 2); + while ($i <= 6) { $idprof = $langs->transcountry('ProfId'.$i, $object->country_code); - if ($idprof != '-') - { + if ($idprof != '-') { $key = 'idprof'.$i; - if (($j % $NBCOLS) == 0) print '<tr>'; + if (($j % $NBCOLS) == 0) { + print '<tr>'; + } $idprof_mandatory = 'SOCIETE_IDPROF'.($i).'_MANDATORY'; print '<td>'.$form->editfieldkey($idprof, $key, '', $object, 0, 'string', '', !(empty($conf->global->$idprof_mandatory) || !$object->isACompany())).'</td><td>'; print $formcompany->get_input_id_prof($i, $key, $object->$key, $object->country_code); print '</td>'; - if (($j % $NBCOLS) == ($NBCOLS - 1)) print '</tr>'; + if (($j % $NBCOLS) == ($NBCOLS - 1)) { + print '</tr>'; + } $j++; } $i++; } - if ($NBCOLS > 0 && $j % 2 == 1) print '<td colspan="2"></td></tr>'; + if ($NBCOLS > 0 && $j % 2 == 1) { + print '<td colspan="2"></td></tr>'; + } // VAT is used print '<tr><td>'.$form->editfieldkey('VATIsUsed', 'assujtva_value', '', $object, 0).'</td><td colspan="3">'; @@ -2095,12 +2125,10 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Local Taxes //TODO: Place into a function to control showing by country or study better option - if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") - { + if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { print '<tr><td>'.$form->editfieldkey($langs->transcountry("LocalTax1IsUsed", $mysoc->country_code), 'localtax1assuj_value', '', $object, 0).'</td><td>'; print $form->selectyesno('localtax1assuj_value', $object->localtax1_assuj, 1); - if (!isOnlyOneLocalTax(1)) - { + if (!isOnlyOneLocalTax(1)) { print '<span class="cblt1"> '.$langs->transcountry("Type", $mysoc->country_code).': '; $formcompany->select_localtax(1, $object->localtax1_value, "lt1"); print '</span>'; @@ -2109,30 +2137,25 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</tr><tr>'; print '<td>'.$form->editfieldkey($langs->transcountry("LocalTax2IsUsed", $mysoc->country_code), 'localtax2assuj_value', '', $object, 0).'</td><td>'; print $form->selectyesno('localtax2assuj_value', $object->localtax2_assuj, 1); - if (!isOnlyOneLocalTax(2)) - { + if (!isOnlyOneLocalTax(2)) { print '<span class="cblt2"> '.$langs->transcountry("Type", $mysoc->country_code).': '; $formcompany->select_localtax(2, $object->localtax2_value, "lt2"); print '</span>'; } print '</td></tr>'; - } elseif ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj != "1") - { + } elseif ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj != "1") { print '<tr><td>'.$form->editfieldkey($langs->transcountry("LocalTax1IsUsed", $mysoc->country_code), 'localtax1assuj_value', '', $object, 0).'</td><td colspan="3">'; print $form->selectyesno('localtax1assuj_value', $object->localtax1_assuj, 1); - if (!isOnlyOneLocalTax(1)) - { + if (!isOnlyOneLocalTax(1)) { print '<span class="cblt1"> '.$langs->transcountry("Type", $mysoc->country_code).': '; $formcompany->select_localtax(1, $object->localtax1_value, "lt1"); print '</span>'; } print '</td></tr>'; - } elseif ($mysoc->localtax2_assuj == "1" && $mysoc->localtax1_assuj != "1") - { + } elseif ($mysoc->localtax2_assuj == "1" && $mysoc->localtax1_assuj != "1") { print '<tr><td>'.$form->editfieldkey($langs->transcountry("LocalTax2IsUsed", $mysoc->country_code), 'localtax2assuj_value', '', $object, 0).'</td><td colspan="3">'; print $form->selectyesno('localtax2assuj_value', $object->localtax2_assuj, 1); - if (!isOnlyOneLocalTax(2)) - { + if (!isOnlyOneLocalTax(2)) { print '<span class="cblt2"> '.$langs->transcountry("Type", $mysoc->country_code).': '; $formcompany->select_localtax(2, $object->localtax2_value, "lt2"); print '</span>'; @@ -2145,14 +2168,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<td colspan="3">'; $s = '<input type="text" class="flat maxwidthonsmartphone" name="tva_intra" id="intra_vat" maxlength="20" value="'.$object->tva_intra.'">'; - if (empty($conf->global->MAIN_DISABLEVATCHECK) && isInEEC($object)) - { + if (empty($conf->global->MAIN_DISABLEVATCHECK) && isInEEC($object)) { $s .= ' &nbsp; '; - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { $widthpopup = 600; - if (!empty($conf->dol_use_jmobile)) $widthpopup = 350; + if (!empty($conf->dol_use_jmobile)) { + $widthpopup = 350; + } $heightpopup = 400; print "\n"; print '<script language="JavaScript" type="text/javascript">'; @@ -2174,12 +2197,18 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Type - Workforce/Staff print '<tr><td>'.$form->editfieldkey('ThirdPartyType', 'typent_id', '', $object, 0).'</td><td class="maxwidthonsmartphone">'; print $form->selectarray("typent_id", $formcompany->typent_array(0), $object->typent_id, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '</td>'; - if ($conf->browser->layout == 'phone') print '</tr><tr>'; + if ($conf->browser->layout == 'phone') { + print '</tr><tr>'; + } print '<td>'.$form->editfieldkey('Workforce', 'effectif_id', '', $object, 0).'</td><td class="maxwidthonsmartphone">'; print $form->selectarray("effectif_id", $formcompany->effectif_array(0), $object->effectif_id, 0, 0, 0, '', 0, 0, 0, '', '', 1); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '</td></tr>'; // Juridical type @@ -2194,27 +2223,24 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '"> <font class="hideonsmartphone">'.$langs->trans("Currency".$conf->currency).'</font></td></tr>'; // Default language - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { print '<tr><td>'.$form->editfieldkey('DefaultLang', 'default_lang', '', $object, 0).'</td><td colspan="3">'."\n"; - print $formadmin->select_language($object->default_lang, 'default_lang', 0, 0, 1); + print img_picto('', 'language').$formadmin->select_language($object->default_lang, 'default_lang', 0, 0, 1); print '</td>'; print '</tr>'; } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '<tr>'; - print '<td>'.$form->editfieldkey('IncotermLabel', 'incoterm_id', '', $object, 0).'</td>'; + print '<td>'.$form->editfieldkey('IncotermLabel', 'incoterm_id', '', $object, 0).'</td>'; print '<td colspan="3" class="maxwidthonsmartphone">'; print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : '')); print '</td></tr>'; } // Categories - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) - { + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { // Customer print '<tr class="visibleifcustomer"><td>'.$form->editfieldkey('CustomersCategoriesShort', 'custcats', '', $object, 0).'</td>'; print '<td colspan="3">'; @@ -2245,8 +2271,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<tr>'; print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>'; print '<td colspan="3" class="maxwidthonsmartphone">'; @@ -2270,13 +2295,18 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr class="hideonsmartphone">'; print '<td>'.$form->editfieldkey('Logo', 'photoinput', '', $object, 0).'</td>'; print '<td colspan="3">'; - if ($object->logo) print $form->showphoto('societe', $object); + if ($object->logo) { + print $form->showphoto('societe', $object); + } $caneditfield = 1; - if ($caneditfield) - { - if ($object->logo) print "<br>\n"; + if ($caneditfield) { + if ($object->logo) { + print "<br>\n"; + } print '<table class="nobordernopadding">'; - if ($object->logo) print '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>'; + if ($object->logo) { + print '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>'; + } //print '<tr><td>'.$langs->trans("PhotoFile").'</td></tr>'; print '<tr><td><input type="file" class="flat" name="photo" id="photoinput"></td></tr>'; print '</table>'; @@ -2290,7 +2320,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<td colspan="3" class="maxwidthonsmartphone">'; $userlist = $form->select_dolusers('', '', 0, null, 0, '', '', 0, 0, 0, 'AND u.statut = 1', 0, '', '', 0, 1); $arrayselected = GETPOST('commercial', 'array'); - if (empty($arrayselected)) $arrayselected = $object->getSalesRepresentatives($user, 1); + if (empty($arrayselected)) { + $arrayselected = $object->getSalesRepresentatives($user, 1); + } print img_picto('', 'user').$form->multiselectarray('commercial', $userlist, $arrayselected, 0, 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0, '', '', '', 1); print '</td></tr>'; @@ -2300,8 +2332,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<br>'; print '<table class="border centpercent">'; - if (! empty($conf->accounting->enabled)) - { + if (! empty($conf->accounting->enabled)) { // Accountancy_code_sell print '<tr><td class="titlefield">'.$langs->trans("ProductAccountancySellCode").'</td>'; print '<td>'; @@ -2313,8 +2344,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<td>'; print $formaccounting->select_account($object->accountancy_code_buy, 'accountancy_code_buy', 1, '', 1, 1); print '</td></tr>'; - } - else // For external software + } else // For external software { // Accountancy_code_sell print '<tr><td class="titlefield">'.$langs->trans("ProductAccountancySellCode").'</td>'; @@ -2343,10 +2373,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } } else { /* - * View - */ + * View + */ - if (!empty($object->id)) $res = $object->fetch_optionals(); + if (!empty($object->id)) { + $res = $object->fetch_optionals(); + } //if ($res < 0) { dol_print_error($db); exit; } @@ -2357,13 +2389,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $formconfirm = ''; // Confirm delete third party - if ($action == 'delete' || ($conf->use_javascript_ajax && empty($conf->dol_use_jmobile))) - { + if ($action == 'delete' || ($conf->use_javascript_ajax && empty($conf->dol_use_jmobile))) { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id, $langs->trans("DeleteACompany"), $langs->trans("ConfirmDeleteCompany"), "confirm_delete", '', 0, "action-delete"); } - if ($action == 'merge') - { + if ($action == 'merge') { $formquestion = array( array( 'name' => 'soc_origin', @@ -2379,8 +2409,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -2404,15 +2437,13 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</td></tr>'; // Prefix - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td>'.$langs->trans('Prefix').'</td><td>'.dol_escape_htmltag($object->prefix_comm).'</td>'; print '</tr>'; } // Customer code - if ($object->client) - { + if ($object->client) { print '<tr><td>'; print $langs->trans('CustomerCode'); print '</td>'; @@ -2428,8 +2459,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Supplier code - if (!empty($conf->fournisseur->enabled) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) - { + if (!empty($conf->fournisseur->enabled) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) { print '<tr><td>'; print $langs->trans('SupplierCode').'</td><td>'; print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_fournisseur)); @@ -2442,8 +2472,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Barcode - if (!empty($conf->barcode->enabled)) - { + if (!empty($conf->barcode->enabled)) { print '<tr><td>'; print $langs->trans('Gencod').'</td><td>'.showValueWithClipboardCPButton(dol_escape_htmltag($object->barcode)); print '</td>'; @@ -2452,20 +2481,20 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Prof ids $i = 1; $j = 0; - while ($i <= 6) - { + while ($i <= 6) { $idprof = $langs->transcountry('ProfId'.$i, $object->country_code); - if ($idprof != '-') - { + if ($idprof != '-') { //if (($j % 2) == 0) print '<tr>'; print '<tr>'; print '<td>'.$idprof.'</td><td>'; $key = 'idprof'.$i; print showValueWithClipboardCPButton(dol_escape_htmltag($object->$key)); - if ($object->$key) - { - if ($object->id_prof_check($i, $object) > 0) print ' &nbsp; '.$object->id_prof_url($i, $object); - else print ' <font class="error">('.$langs->trans("ErrorWrongValue").')</font>'; + if ($object->$key) { + if ($object->id_prof_check($i, $object) > 0) { + print ' &nbsp; '.$object->id_prof_url($i, $object); + } else { + print ' <font class="error">('.$langs->trans("ErrorWrongValue").')</font>'; + } } print '</td>'; //if (($j % 2) == 1) print '</tr>'; @@ -2481,8 +2510,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // We don't need them into customer profile. // Except for spain and localtax where localtax depends on buyer and not seller - if ($object->fournisseur) - { + if ($object->fournisseur) { // VAT is used print '<tr><td>'; print $form->textwithpicto($langs->trans('VATIsUsed'), $langs->trans('VATIsUsedWhenSelling')); @@ -2493,24 +2521,20 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Local Taxes - if ($object->fournisseur || $mysoc->country_code == 'ES') - { - if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") - { + if ($object->fournisseur || $mysoc->country_code == 'ES') { + if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td>'; print yn($object->localtax1_assuj); print '</td></tr><tr><td>'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td>'; print yn($object->localtax2_assuj); print '</td></tr>'; - if ($object->localtax1_assuj == "1" && (!isOnlyOneLocalTax(1))) - { + if ($object->localtax1_assuj == "1" && (!isOnlyOneLocalTax(1))) { print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'">'; print '<input type="hidden" name="action" value="set_localtax1">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<tr><td>'.$langs->transcountry("Localtax1", $mysoc->country_code).' <a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editRE&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).'</td>'; - if ($action == 'editRE') - { + if ($action == 'editRE') { print '<td class="left">'; $formcompany->select_localtax(1, $object->localtax1_value, "lt1"); print '<input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>'; @@ -2519,8 +2543,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } print '</tr></form>'; } - if ($object->localtax2_assuj == "1" && (!isOnlyOneLocalTax(2))) - { + if ($object->localtax2_assuj == "1" && (!isOnlyOneLocalTax(2))) { print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'">'; print '<input type="hidden" name="action" value="set_localtax2">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -2534,13 +2557,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } print '</tr></form>'; } - } elseif ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj != "1") - { + } elseif ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj != "1") { print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td>'; print yn($object->localtax1_assuj); print '</td></tr>'; - if ($object->localtax1_assuj == "1" && (!isOnlyOneLocalTax(1))) - { + if ($object->localtax1_assuj == "1" && (!isOnlyOneLocalTax(1))) { print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'">'; print '<input type="hidden" name="action" value="set_localtax1">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -2554,13 +2575,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } print '</tr></form>'; } - } elseif ($mysoc->localtax2_assuj == "1" && $mysoc->localtax1_assuj != "1") - { + } elseif ($mysoc->localtax2_assuj == "1" && $mysoc->localtax1_assuj != "1") { print '<tr><td>'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td>'; print yn($object->localtax2_assuj); print '</td></tr>'; - if ($object->localtax2_assuj == "1" && (!isOnlyOneLocalTax(2))) - { + if ($object->localtax2_assuj == "1" && (!isOnlyOneLocalTax(2))) { print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'">'; print '<input type="hidden" name="action" value="set_localtax2">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -2580,20 +2599,19 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Sale tax code (VAT code) print '<tr>'; print '<td class="nowrap">'.$langs->trans('VATIntra').'</td><td>'; - if ($object->tva_intra) - { + if ($object->tva_intra) { $s = ''; - $s .= dol_escape_htmltag($object->tva_intra); + $s .= showValueWithClipboardCPButton(dol_escape_htmltag($object->tva_intra)); $s .= '<input type="hidden" id="tva_intra" name="tva_intra" maxlength="20" value="'.$object->tva_intra.'">'; - if (empty($conf->global->MAIN_DISABLEVATCHECK) && isInEEC($object)) - { + if (empty($conf->global->MAIN_DISABLEVATCHECK) && isInEEC($object)) { $s .= ' &nbsp; '; - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { $widthpopup = 600; - if (!empty($conf->dol_use_jmobile)) $widthpopup = 350; + if (!empty($conf->dol_use_jmobile)) { + $widthpopup = 350; + } $heightpopup = 400; print "\n"; print '<script language="JavaScript" type="text/javascript">'; @@ -2617,7 +2635,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Third-Party Type print '<tr><td>'; print '<table class="nobordernopadding" width="100%"><tr><td>'.$langs->trans('ThirdPartyType').'</td>'; - if ($action != 'editthirdpartytype' && $user->rights->societe->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editthirdpartytype&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).'</a></td>'; + if ($action != 'editthirdpartytype' && $user->rights->societe->creer) { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editthirdpartytype&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; $html_name = ($action == 'editthirdpartytype') ? 'typent_id' : 'none'; @@ -2636,8 +2656,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<table class="border tableforfield" width="100%">'; // Tags / categories - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) - { + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { // Customer if ($object->prospect || $object->client || (!$object->fournisseur && !empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER))) { print '<tr><td>'.$langs->trans("CustomersCategoriesShort").'</td>'; @@ -2660,33 +2679,36 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Capital print '<tr><td>'.$langs->trans('Capital').'</td><td>'; - if ($object->capital) print price($object->capital, '', $langs, 0, -1, -1, $conf->currency); - else print '&nbsp;'; + if ($object->capital) { + print price($object->capital, '', $langs, 0, -1, -1, $conf->currency); + } else { + print '&nbsp;'; + } print '</td></tr>'; // Default language - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; print '<tr><td>'.$langs->trans("DefaultLang").'</td><td>'; //$s=picto_from_langcode($object->default_lang); //print ($s?$s.' ':''); $langs->load("languages"); $labellang = ($object->default_lang ? $langs->trans('Language_'.$object->default_lang) : ''); + print picto_from_langcode($object->default_lang, 'class="paddingrightonly saturatemedium opacitylow"'); print $labellang; print '</td></tr>'; } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '<tr><td>'; print '<table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans('IncotermLabel').'</td>'; - if ($action != 'editincoterm' && $user->rights->societe->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&action=editincoterm">'.img_edit('', 1).'</a></td>'; + if ($action != 'editincoterm' && $user->rights->societe->creer) { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&action=editincoterm">'.img_edit('', 1).'</a></td>'; + } print '</tr></table>'; print '</td><td colspan="3">'; - if ($action != 'editincoterm') - { + if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1); } else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?socid='.$object->id); @@ -2695,8 +2717,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<tr>'; print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>'; print '<td>'; @@ -2709,10 +2730,8 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr><td class="nowrap">'; print $langs->trans("ProductAccountancySellCode"); print '</td><td colspan="2">'; - if (! empty($conf->accounting->enabled)) - { - if (! empty($object->accountancy_code_sell)) - { + if (! empty($conf->accounting->enabled)) { + if (! empty($object->accountancy_code_sell)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->accountancy_code_sell, 1); @@ -2727,10 +2746,8 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '<tr><td class="nowrap">'; print $langs->trans("ProductAccountancyBuyCode"); print '</td><td colspan="2">'; - if (! empty($conf->accounting->enabled)) - { - if (! empty($object->accountancy_code_buy)) - { + if (! empty($conf->accounting->enabled)) { + if (! empty($object->accountancy_code_buy)) { $accountingaccount2 = new AccountingAccount($db); $accountingaccount2->fetch('', $object->accountancy_code_buy, 1); @@ -2795,62 +2812,51 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) /* - * Actions - */ - if ($action != 'presend') - { + * Actions + */ + if ($action != 'presend') { print '<div class="tabsAction">'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { $at_least_one_email_contact = false; $TContact = $object->contact_array_objects(); - foreach ($TContact as &$contact) - { - if (!empty($contact->email)) - { + foreach ($TContact as &$contact) { + if (!empty($contact->email)) { $at_least_one_email_contact = true; break; } } if (empty($user->socid)) { - if (!empty($object->email) || $at_least_one_email_contact) - { + if (!empty($object->email) || $at_least_one_email_contact) { $langs->load("mails"); print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>'; } else { $langs->load("mails"); - print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NoEMail")).'">'.$langs->trans('SendMail').'</a>'; + print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NoEMail")).'">'.$langs->trans('SendMail').'</a>'; } } - if ($user->rights->societe->creer) - { + if ($user->rights->societe->creer) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>'."\n"; } - if (!empty($conf->adherent->enabled)) - { + if (!empty($conf->adherent->enabled)) { $adh = new Adherent($db); $result = $adh->fetch('', '', $object->id); - if ($result == 0 && ($object->client == 1 || $object->client == 3) && !empty($conf->global->MEMBER_CAN_CONVERT_CUSTOMERS_TO_MEMBERS)) - { + if ($result == 0 && ($object->client == 1 || $object->client == 3) && !empty($conf->global->MEMBER_CAN_CONVERT_CUSTOMERS_TO_MEMBERS)) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/adherents/card.php?&action=create&socid='.$object->id.'" title="'.dol_escape_htmltag($langs->trans("NewMember")).'">'.$langs->trans("NewMember").'</a>'; } } - if ($user->rights->societe->supprimer) - { + if ($user->rights->societe->supprimer) { print '<a class="butActionDelete" href="card.php?action=merge&socid='.$object->id.'" title="'.dol_escape_htmltag($langs->trans("MergeThirdparties")).'">'.$langs->trans('Merge').'</a>'; } - if ($user->rights->societe->supprimer) - { - if ($conf->use_javascript_ajax && empty($conf->dol_use_jmobile)) // We can't use preloaded confirm form with jmobile - { + if ($user->rights->societe->supprimer) { + if ($conf->use_javascript_ajax && empty($conf->dol_use_jmobile)) { // We can't use preloaded confirm form with jmobile print '<span id="action-delete" class="butActionDelete">'.$langs->trans('Delete').'</span>'."\n"; } else { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n"; @@ -2866,17 +2872,15 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; - if (empty($conf->global->SOCIETE_DISABLE_BUILDDOC)) - { + if (empty($conf->global->SOCIETE_DISABLE_BUILDDOC)) { print '<a name="builddoc"></a>'; // ancre /* - * Documents generes - */ + * Generated documents + */ $filedir = $conf->societe->multidir_output[$object->entity].'/'.$object->id; $urlsource = $_SERVER["PHP_SELF"]."?socid=".$object->id; $genallowed = $user->rights->societe->lire; @@ -2886,8 +2890,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Subsidiaries list - if (empty($conf->global->SOCIETE_DISABLE_SUBSIDIARIES)) - { + if (empty($conf->global->SOCIETE_DISABLE_SUBSIDIARIES)) { $result = show_subsidiaries($conf, $langs, $db, $object); } @@ -2904,17 +2907,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '</div></div></div>'; - if (!empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD)) - { + if (!empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD)) { // Contacts list - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $result = show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id); } // Addresses list - if (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT)) - { + if (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT)) { $result = show_addresses($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id); } } diff --git a/htdocs/societe/checkvat/checkVatPopup.php b/htdocs/societe/checkvat/checkVatPopup.php index 4b3cb68e3bb..995f256bc01 100644 --- a/htdocs/societe/checkvat/checkVatPopup.php +++ b/htdocs/societe/checkvat/checkVatPopup.php @@ -45,8 +45,7 @@ print load_fiche_titre($langs->trans("VATIntraCheckableOnEUSite"), '', 'title_se $vatNumber = GETPOST("vatNumber", 'alpha'); -if (!$vatNumber) -{ +if (!$vatNumber) { print '<br>'; print '<font class="error">'.$langs->transnoentities("ErrorFieldRequired", $langs->trans("VATIntraShort")).'</font><br>'; } else { @@ -76,8 +75,7 @@ if (!$vatNumber) // Check for an error $err = $soapclient->getError(); - if ($err) - { + if ($err) { dol_syslog("Constructor error ".$WS_DOL_URL, LOG_ERR); } @@ -96,42 +94,38 @@ if (!$vatNumber) print '<b>'.$langs->trans("Response").'</b>:<br>'; // Service indisponible - if (!is_array($result) || preg_match('/SERVICE_UNAVAILABLE/i', $result['faultstring'])) - { + if (!is_array($result) || preg_match('/SERVICE_UNAVAILABLE/i', $result['faultstring'])) { print '<font class="error">'.$langs->trans("ErrorServiceUnavailableTryLater").'</font><br>'; $messagetoshow = $soapclient->response; - } elseif (preg_match('/TIMEOUT/i', $result['faultstring'])) - { + } elseif (preg_match('/TIMEOUT/i', $result['faultstring'])) { print '<font class="error">'.$langs->trans("ErrorServiceUnavailableTryLater").'</font><br>'; $messagetoshow = $soapclient->response; - } elseif (preg_match('/SERVER_BUSY/i', $result['faultstring'])) - { + } elseif (preg_match('/SERVER_BUSY/i', $result['faultstring'])) { print '<font class="error">'.$langs->trans("ErrorServiceUnavailableTryLater").'</font><br>'; $messagetoshow = $soapclient->response; - } elseif ($result['faultstring']) - { + } elseif ($result['faultstring']) { print '<font class="error">'.$langs->trans("Error").'</font><br>'; $messagetoshow = $result['faultstring']; - } - // Syntaxe ko - elseif (preg_match('/INVALID_INPUT/i', $result['faultstring']) - || ($result['requestDate'] && !$result['valid'])) - { - if ($result['requestDate']) print $langs->trans("Date").': '.$result['requestDate'].'<br>'; + } elseif (preg_match('/INVALID_INPUT/i', $result['faultstring']) + || ($result['requestDate'] && !$result['valid'])) { + // Syntaxe ko + if ($result['requestDate']) { + print $langs->trans("Date").': '.$result['requestDate'].'<br>'; + } print $langs->trans("VATIntraSyntaxIsValid").': <font class="error">'.$langs->trans("No").'</font> (Might be a non europeen VAT)<br>'; print $langs->trans("ValueIsValid").': <font class="error">'.$langs->trans("No").'</font> (Might be a non europeen VAT)<br>'; //$messagetoshow=$soapclient->response; } else { // Syntaxe ok - if ($result['requestDate']) print $langs->trans("Date").': '.$result['requestDate'].'<br>'; + if ($result['requestDate']) { + print $langs->trans("Date").': '.$result['requestDate'].'<br>'; + } print $langs->trans("VATIntraSyntaxIsValid").': <font class="ok">'.$langs->trans("Yes").'</font><br>'; print $langs->trans("ValueIsValid").': '; - if (preg_match('/MS_UNAVAILABLE/i', $result['faultstring'])) - { + if (preg_match('/MS_UNAVAILABLE/i', $result['faultstring'])) { print '<font class="error">'.$langs->trans("ErrorVATCheckMS_UNAVAILABLE", $countryCode).'</font><br>'; } else { - if (!empty($result['valid']) && ($result['valid'] == 1 || $result['valid'] == 'true')) - { + if (!empty($result['valid']) && ($result['valid'] == 1 || $result['valid'] == 'true')) { print '<font class="ok">'.$langs->trans("Yes").'</font>'; print '<br>'; print $langs->trans("Name").': '.$result['name'].'<br>'; @@ -144,10 +138,10 @@ if (!$vatNumber) } // Show log data into page - print "\n"; - print '<!-- '; - var_dump($result); - print '-->'; + // print "\n"; + // print '<!-- '; + // var_dump($result); + // print '-->'; } print '<br>'; @@ -155,8 +149,7 @@ print $langs->trans("VATIntraManualCheck", $langs->trans("VATIntraCheckURL"), $l print '<br>'; print '<div class="center"><input type="button" class="button" value="'.$langs->trans("CloseWindow").'" onclick="javascript: window.close()"></div>'; -if ($messagetoshow) -{ +if ($messagetoshow) { print '<br><br>'; print "\n".'Error returned:<br>'; print nl2br($messagetoshow); diff --git a/htdocs/societe/class/api_contacts.class.php b/htdocs/societe/class/api_contacts.class.php index 82984409325..37ad82602fb 100644 --- a/htdocs/societe/class/api_contacts.class.php +++ b/htdocs/societe/class/api_contacts.class.php @@ -34,7 +34,7 @@ class Contacts extends DolibarrApi * * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'lastname', ); @@ -71,8 +71,7 @@ class Contacts extends DolibarrApi */ public function get($id, $includecount = 0, $includeroles = 0) { - if (!DolibarrApiAccess::$user->rights->societe->contact->lire) - { + if (!DolibarrApiAccess::$user->rights->societe->contact->lire) { throw new RestException(401, 'No permission to read contacts'); } if ($id == 0) { @@ -81,23 +80,19 @@ class Contacts extends DolibarrApi $result = $this->contact->fetch($id); } - if (!$result) - { + if (!$result) { throw new RestException(404, 'Contact not found'); } - if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) - { + if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if ($includecount) - { + if ($includecount) { $this->contact->load_ref_elements(); } - if ($includeroles) - { + if ($includeroles) { $this->contact->fetchRoles(); } @@ -119,8 +114,7 @@ class Contacts extends DolibarrApi */ public function getByEmail($email, $includecount = 0, $includeroles = 0) { - if (!DolibarrApiAccess::$user->rights->societe->contact->lire) - { + if (!DolibarrApiAccess::$user->rights->societe->contact->lire) { throw new RestException(401, 'No permission to read contacts'); } if (empty($email)) { @@ -129,23 +123,19 @@ class Contacts extends DolibarrApi $result = $this->contact->fetch('', '', '', $email); } - if (!$result) - { + if (!$result) { throw new RestException(404, 'Contact not found'); } - if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) - { + if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if ($includecount) - { + if ($includecount) { $this->contact->load_ref_elements(); } - if ($includeroles) - { + if ($includeroles) { $this->contact->fetchRoles(); } @@ -176,8 +166,7 @@ class Contacts extends DolibarrApi $obj_ret = array(); - if (!DolibarrApiAccess::$user->rights->societe->contact->lire) - { + if (!DolibarrApiAccess::$user->rights->societe->contact->lire) { throw new RestException(401, 'No permission to read contacts'); } @@ -186,8 +175,9 @@ class Contacts extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t"; @@ -201,15 +191,18 @@ class Contacts extends DolibarrApi } $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON t.fk_soc = s.rowid"; $sql .= ' WHERE t.entity IN ('.getEntity('socpeople').')'; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($search_sale > 0) + } + if ($search_sale > 0) { $sql .= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } @@ -220,10 +213,8 @@ class Contacts extends DolibarrApi } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -232,10 +223,8 @@ class Contacts extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) - { - if ($page < 0) - { + if ($limit) { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -243,24 +232,19 @@ class Contacts extends DolibarrApi $sql .= $this->db->plimit($limit + 1, $offset); } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $contact_static = new Contact($this->db); - if ($contact_static->fetch($obj->rowid)) - { + if ($contact_static->fetch($obj->rowid)) { $contact_static->fetchRoles(); - if ($includecount) - { + if ($includecount) { $contact_static->load_ref_elements(); } - if ($includeroles) - { + if ($includeroles) { $contact_static->fetchRoles(); } @@ -272,8 +256,7 @@ class Contacts extends DolibarrApi } else { throw new RestException(503, 'Error when retrieve contacts : '.$sql); } - if (!count($obj_ret)) - { + if (!count($obj_ret)) { throw new RestException(404, 'Contacts not found'); } return $obj_ret; @@ -287,15 +270,13 @@ class Contacts extends DolibarrApi */ public function post($request_data = null) { - if (!DolibarrApiAccess::$user->rights->societe->contact->creer) - { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { throw new RestException(401, 'No permission to create/update contacts'); } // Check mandatory fields $result = $this->_validate($request_data); - foreach ($request_data as $field => $value) - { + foreach ($request_data as $field => $value) { $this->contact->$field = $value; } if ($this->contact->create(DolibarrApiAccess::$user) < 0) { @@ -313,30 +294,29 @@ class Contacts extends DolibarrApi */ public function put($id, $request_data = null) { - if (!DolibarrApiAccess::$user->rights->societe->contact->creer) - { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { throw new RestException(401, 'No permission to create/update contacts'); } $result = $this->contact->fetch($id); - if (!$result) - { + if (!$result) { throw new RestException(404, 'Contact not found'); } - if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) - { + if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - foreach ($request_data as $field => $value) - { - if ($field == 'id') continue; + foreach ($request_data as $field => $value) { + if ($field == 'id') { + continue; + } $this->contact->$field = $value; } - if ($this->contact->update($id, DolibarrApiAccess::$user, 1, '', '', 'update')) + if ($this->contact->update($id, DolibarrApiAccess::$user, 1, '', '', 'update')) { return $this->get($id); + } return false; } @@ -349,18 +329,15 @@ class Contacts extends DolibarrApi */ public function delete($id) { - if (!DolibarrApiAccess::$user->rights->societe->contact->supprimer) - { + if (!DolibarrApiAccess::$user->rights->societe->contact->supprimer) { throw new RestException(401, 'No permission to delete contacts'); } $result = $this->contact->fetch($id); - if (!$result) - { + if (!$result) { throw new RestException(404, 'Contact not found'); } - if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) - { + if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $this->contact->oldcopy = clone $this->contact; @@ -382,10 +359,12 @@ class Contacts extends DolibarrApi //throw new RestException(401); //} - if (!isset($request_data["login"])) + if (!isset($request_data["login"])) { throw new RestException(400, "login field missing"); - if (!isset($request_data["password"])) + } + if (!isset($request_data["password"])) { throw new RestException(400, "password field missing"); + } if (!DolibarrApiAccess::$user->rights->societe->contact->lire) { throw new RestException(401, 'No permission to read contacts'); diff --git a/htdocs/societe/class/api_thirdparties.class.php b/htdocs/societe/class/api_thirdparties.class.php index 3e8a6c91f92..ed62e5a224f 100644 --- a/htdocs/societe/class/api_thirdparties.class.php +++ b/htdocs/societe/class/api_thirdparties.class.php @@ -2,7 +2,7 @@ /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr> * Copyright (C) 2018 Pierre Chéné <pierre.chene44@gmail.com> * Copyright (C) 2019 Cedric Ancelin <icedo.anc@gmail.com> - * Copyright (C) 2020 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2020-2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -33,7 +33,7 @@ class Thirdparties extends DolibarrApi * * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'name' ); @@ -137,46 +137,68 @@ class Thirdparties extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as t"; if ($category > 0) { - if ($mode != 4) $sql .= ", ".MAIN_DB_PREFIX."categorie_societe as c"; - if (!in_array($mode, array(1, 2, 3))) $sql .= ", ".MAIN_DB_PREFIX."categorie_fournisseur as cc"; + if ($mode != 4) { + $sql .= ", ".MAIN_DB_PREFIX."categorie_societe as c"; + } + if (!in_array($mode, array(1, 2, 3))) { + $sql .= ", ".MAIN_DB_PREFIX."categorie_fournisseur as cc"; + } + } + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale } - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale $sql .= ", ".MAIN_DB_PREFIX."c_stcomm as st"; $sql .= " WHERE t.entity IN (".getEntity('societe').")"; $sql .= " AND t.fk_stcomm = st.id"; - if ($mode == 1) $sql .= " AND t.client IN (1, 3)"; - elseif ($mode == 2) $sql .= " AND t.client IN (2, 3)"; - elseif ($mode == 3) $sql .= " AND t.client IN (0)"; - elseif ($mode == 4) $sql .= " AND t.fournisseur IN (1)"; + if ($mode == 1) { + $sql .= " AND t.client IN (1, 3)"; + } elseif ($mode == 2) { + $sql .= " AND t.client IN (2, 3)"; + } elseif ($mode == 3) { + $sql .= " AND t.client IN (0)"; + } elseif ($mode == 4) { + $sql .= " AND t.fournisseur IN (1)"; + } // Select thirdparties of given category if ($category > 0) { - if (!empty($mode) && $mode != 4) { $sql .= " AND c.fk_categorie = ".$this->db->escape($category)." AND c.fk_soc = t.rowid"; } - elseif (!empty($mode) && $mode == 4) { $sql .= " AND cc.fk_categorie = ".$this->db->escape($category)." AND cc.fk_soc = t.rowid"; } - else { $sql .= " AND ((c.fk_categorie = ".$this->db->escape($category)." AND c.fk_soc = t.rowid) OR (cc.fk_categorie = ".$this->db->escape($category)." AND cc.fk_soc = t.rowid))"; } + if (!empty($mode) && $mode != 4) { + $sql .= " AND c.fk_categorie = ".$this->db->escape($category)." AND c.fk_soc = t.rowid"; + } elseif (!empty($mode) && $mode == 4) { + $sql .= " AND cc.fk_categorie = ".$this->db->escape($category)." AND cc.fk_soc = t.rowid"; + } else { + $sql .= " AND ((c.fk_categorie = ".$this->db->escape($category)." AND c.fk_soc = t.rowid) OR (cc.fk_categorie = ".$this->db->escape($category)." AND cc.fk_soc = t.rowid))"; + } } - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; + } //if ($email != NULL) $sql.= " AND s.email = \"".$email."\""; - if ($socids) $sql .= " AND t.rowid IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ($socids) { + $sql .= " AND t.rowid IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -195,13 +217,11 @@ class Thirdparties extends DolibarrApi } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $soc_static = new Societe($this->db); if ($soc_static->fetch($obj->rowid)) { @@ -235,8 +255,9 @@ class Thirdparties extends DolibarrApi foreach ($request_data as $field => $value) { $this->company->$field = $value; } - if ($this->company->create(DolibarrApiAccess::$user) < 0) + if ($this->company->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, 'Error creating thirdparty', array_merge(array($this->company->error), $this->company->errors)); + } return $this->company->id; } @@ -264,7 +285,9 @@ class Thirdparties extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->company->$field = $value; } @@ -295,8 +318,7 @@ class Thirdparties extends DolibarrApi $error = 0; - if ($id == $idtodelete) - { + if ($id == $idtodelete) { throw new RestException(400, 'Try to merge a thirdparty into itself'); } @@ -345,26 +367,26 @@ class Thirdparties extends DolibarrApi 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur', 'model_pdf', 'fk_projet' ); - foreach ($listofproperties as $property) - { - if (empty($object->$property)) $object->$property = $soc_origin->$property; + foreach ($listofproperties as $property) { + if (empty($object->$property)) { + $object->$property = $soc_origin->$property; + } } // Concat some data $listofproperties = array( 'note_public', 'note_private' ); - foreach ($listofproperties as $property) - { + foreach ($listofproperties as $property) { $object->$property = dol_concatdesc($object->$property, $soc_origin->$property); } // Merge extrafields - if (is_array($soc_origin->array_options)) - { - foreach ($soc_origin->array_options as $key => $val) - { - if (empty($object->array_options[$key])) $object->array_options[$key] = $val; + if (is_array($soc_origin->array_options)) { + foreach ($soc_origin->array_options as $key => $val) { + if (empty($object->array_options[$key])) { + $object->array_options[$key] = $val; + } } } @@ -378,8 +400,7 @@ class Thirdparties extends DolibarrApi // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys. if ($soc_origin->code_client == $object->code_client || $soc_origin->code_fournisseur == $object->code_fournisseur - || $soc_origin->barcode == $object->barcode) - { + || $soc_origin->barcode == $object->barcode) { dol_syslog("We clean customer and supplier code so we will be able to make the update of target"); $soc_origin->code_client = ''; $soc_origin->code_fournisseur = ''; @@ -389,8 +410,7 @@ class Thirdparties extends DolibarrApi // Update $result = $object->update($object->id, $user, 0, 1, 1, 'merge'); - if ($result < 0) - { + if ($result < 0) { $error++; } @@ -425,8 +445,7 @@ class Thirdparties extends DolibarrApi ); //First, all core objects must update their tables - foreach ($objects as $object_name => $object_file) - { + foreach ($objects as $object_name => $object_file) { require_once DOL_DOCUMENT_ROOT.$object_file; if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $object->id)) { @@ -584,8 +603,7 @@ class Thirdparties extends DolibarrApi } $result = $this->company->fetch($id); - if (!$result) - { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } @@ -593,13 +611,11 @@ class Thirdparties extends DolibarrApi $result = $categories->getListForItem($id, 'customer', $sortfield, $sortorder, $limit, $page); - if (is_numeric($result) && $result < 0) - { + if (is_numeric($result) && $result < 0) { throw new RestException(503, 'Error when retrieve category list : '.$categories->error); } - if (is_numeric($result) && $result == 0) // To fix a return of 0 instead of empty array of method getListForItem - { + if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem return array(); } @@ -702,8 +718,7 @@ class Thirdparties extends DolibarrApi } $result = $this->company->fetch($id); - if (!$result) - { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } @@ -711,13 +726,11 @@ class Thirdparties extends DolibarrApi $result = $categories->getListForItem($id, 'supplier', $sortfield, $sortorder, $limit, $page); - if (is_numeric($result) && $result < 0) - { + if (is_numeric($result) && $result < 0) { throw new RestException(503, 'Error when retrieve category list : '.$categories->error); } - if (is_numeric($result) && $result == 0) // To fix a return of 0 instead of empty array of method getListForItem - { + if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem return array(); } @@ -1005,8 +1018,12 @@ class Thirdparties extends DolibarrApi $sql = "SELECT f.ref, f.type as factype, re.fk_facture_source, re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc, re.description, re.fk_facture, re.fk_facture_line"; $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re, ".MAIN_DB_PREFIX."facture as f"; $sql .= " WHERE f.rowid = re.fk_facture_source AND re.fk_soc = ".$id; - if ($filter == "available") $sql .= " AND re.fk_facture IS NULL AND re.fk_facture_line IS NULL"; - if ($filter == "used") $sql .= " AND (re.fk_facture IS NOT NULL OR re.fk_facture_line IS NOT NULL)"; + if ($filter == "available") { + $sql .= " AND re.fk_facture IS NULL AND re.fk_facture_line IS NULL"; + } + if ($filter == "used") { + $sql .= " AND (re.fk_facture IS NOT NULL OR re.fk_facture_line IS NOT NULL)"; + } $sql .= $this->db->order($sortfield, $sortorder); @@ -1137,7 +1154,9 @@ class Thirdparties extends DolibarrApi $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,"; $sql .= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur"; $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib"; - if ($id) $sql .= " WHERE fk_soc = ".$id." "; + if ($id) { + $sql .= " WHERE fk_soc = ".$id." "; + } $result = $this->db->query($sql); @@ -1150,11 +1169,9 @@ class Thirdparties extends DolibarrApi $accounts = array(); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $account = new CompanyBankAccount($this->db); if ($account->fetch($obj->rowid)) { @@ -1209,8 +1226,9 @@ class Thirdparties extends DolibarrApi $account->$field = $value; } - if ($account->create(DolibarrApiAccess::$user) < 0) + if ($account->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, 'Error creating Company Bank account'); + } if (empty($account->rum)) { require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; @@ -1219,8 +1237,9 @@ class Thirdparties extends DolibarrApi $account->date_rum = dol_now(); } - if ($account->update(DolibarrApiAccess::$user) < 0) + if ($account->update(DolibarrApiAccess::$user) < 0) { throw new RestException(500, 'Error updating values'); + } return $this->_cleanObjectDatas($account); } @@ -1264,8 +1283,9 @@ class Thirdparties extends DolibarrApi $account->date_rum = dol_now(); } - if ($account->update(DolibarrApiAccess::$user) < 0) + if ($account->update(DolibarrApiAccess::$user) < 0) { throw new RestException(500, 'Error updating values'); + } return $this->_cleanObjectDatas($account); } @@ -1290,8 +1310,9 @@ class Thirdparties extends DolibarrApi $account->fetch($bankaccount_id); - if (!$account->socid == $id) + if (!$account->socid == $id) { throw new RestException(401); + } return $account->delete(DolibarrApiAccess::$user); } @@ -1342,8 +1363,12 @@ class Thirdparties extends DolibarrApi $sql = "SELECT rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib"; - if ($id) $sql .= " WHERE fk_soc = ".$id." "; - if ($companybankid) $sql .= " AND rowid = ".$companybankid.""; + if ($id) { + $sql .= " WHERE fk_soc = ".$id." "; + } + if ($companybankid) { + $sql .= " AND rowid = ".$companybankid.""; + } $i = 0; $accounts = array(); @@ -1409,7 +1434,9 @@ class Thirdparties extends DolibarrApi */ $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account"; $sql .= " WHERE fk_soc = $id"; - if ($site) $sql .= " AND site ='$site'"; + if ($site) { + $sql .= " AND site ='$site'"; + } $result = $this->db->query($sql); @@ -1422,8 +1449,7 @@ class Thirdparties extends DolibarrApi $accounts = array(); $num = $this->db->num_rows($result); - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $account = new SocieteAccount($this->db); @@ -1493,8 +1519,9 @@ class Thirdparties extends DolibarrApi $account->$field = $value; } - if ($account->create(DolibarrApiAccess::$user) < 0) + if ($account->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, 'Error creating SocieteAccount entity. Ensure that the ID of thirdparty provided does exist!'); + } $this->_cleanObjectDatas($account); @@ -1582,8 +1609,9 @@ class Thirdparties extends DolibarrApi $account->$field = $value; } - if ($account->update(DolibarrApiAccess::$user) < 0) + if ($account->update(DolibarrApiAccess::$user) < 0) { throw new RestException(500, 'Error updating SocieteAccount entity.'); + } } $this->_cleanObjectDatas($account); @@ -1624,8 +1652,9 @@ class Thirdparties extends DolibarrApi $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".$id." AND site = '".$this->db->escape($request_data['site'])."' "; $result = $this->db->query($sql); - if ($result && $this->db->num_rows($result) !== 0) + if ($result && $this->db->num_rows($result) !== 0) { throw new RestException(409, "You are trying to update this thirdparty SocieteAccount (gateway record) site member from $site to ".$request_data['site']." but another SocieteAccount entity already exists for this thirdparty with this site key."); + } } $obj = $this->db->fetch_object($result); @@ -1636,8 +1665,9 @@ class Thirdparties extends DolibarrApi $account->$field = $value; } - if ($account->update(DolibarrApiAccess::$user) < 0) + if ($account->update(DolibarrApiAccess::$user) < 0) { throw new RestException(500, 'Error updating SocieteAccount account'); + } $this->_cleanObjectDatas($account); @@ -1713,8 +1743,7 @@ class Thirdparties extends DolibarrApi $i = 0; $num = $this->db->num_rows($result); - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $account = new SocieteAccount($this->db); $account->fetch($obj->rowid); @@ -1781,8 +1810,9 @@ class Thirdparties extends DolibarrApi { $thirdparty = array(); foreach (Thirdparties::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $thirdparty[$field] = $data[$field]; } return $thirdparty; @@ -1793,7 +1823,7 @@ class Thirdparties extends DolibarrApi * * Return an array with thirdparty informations * - * @param int $rowid Id of third party to load + * @param int $rowid Id of third party to load (Use 0 to get a specimen record, use null to use other search criterias) * @param string $ref Reference of third party, name (Warning, this can return several records) * @param string $ref_ext External reference of third party (Warning, this information is a free field not provided by Dolibarr) * @param string $barcode Barcode of third party to load @@ -1815,7 +1845,7 @@ class Thirdparties extends DolibarrApi if (!DolibarrApiAccess::$user->rights->societe->lire) { throw new RestException(401); } - if ($rowid == 0) { + if ($rowid === 0) { $result = $this->company->initAsSpecimen(); } else { $result = $this->company->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias); diff --git a/htdocs/societe/class/client.class.php b/htdocs/societe/class/client.class.php index f88027b1491..6b09d88ac71 100644 --- a/htdocs/societe/class/client.class.php +++ b/htdocs/societe/class/client.class.php @@ -64,8 +64,7 @@ class Client extends Societe $sql = "SELECT count(s.rowid) as nb, s.client"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -75,12 +74,14 @@ class Client extends Societe $sql .= " GROUP BY s.client"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { - if ($obj->client == 1 || $obj->client == 3) $this->nb["customers"] += $obj->nb; - if ($obj->client == 2 || $obj->client == 3) $this->nb["prospects"] += $obj->nb; + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { + if ($obj->client == 1 || $obj->client == 3) { + $this->nb["customers"] += $obj->nb; + } + if ($obj->client == 2 || $obj->client == 3) { + $this->nb["prospects"] += $obj->nb; + } } $this->db->free($resql); return 1; @@ -101,8 +102,10 @@ class Client extends Societe { global $langs; - $sql = "SELECT id, code, libelle as label, picto FROM ".MAIN_DB_PREFIX."c_stcomm"; - if ($active >= 0) $sql .= " WHERE active = ".$active; + $sql = "SELECT id, code, libelle as label, picto FROM ".MAIN_DB_PREFIX."c_stcomm"; + if ($active >= 0) { + $sql .= " WHERE active = ".$active; + } $resql = $this->db->query($sql); $num = $this->db->num_rows($resql); $i = 0; diff --git a/htdocs/societe/class/companybankaccount.class.php b/htdocs/societe/class/companybankaccount.class.php index a123fa749c9..c611ccab462 100644 --- a/htdocs/societe/class/companybankaccount.class.php +++ b/htdocs/societe/class/companybankaccount.class.php @@ -84,32 +84,33 @@ class CompanyBankAccount extends Account $error = 0; // Correct default_rib to be sure to have always one default $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib where fk_soc = ".$this->socid." AND default_rib = 1 AND type = 'ban'"; - $result = $this->db->query($sql); - if ($result) - { + $result = $this->db->query($sql); + if ($result) { $numrows = $this->db->num_rows($result); - if ($this->default_rib && $numrows > 0) $this->default_rib = 0; - if (empty($this->default_rib) && $numrows == 0) $this->default_rib = 1; + if ($this->default_rib && $numrows > 0) { + $this->default_rib = 0; + } + if (empty($this->default_rib) && $numrows == 0) { + $this->default_rib = 1; + } } $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_rib (fk_soc, type, datec)"; $sql .= " VALUES (".$this->socid.", 'ban', '".$this->db->idate($now)."')"; $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->affected_rows($resql)) - { + if ($resql) { + if ($this->db->affected_rows($resql)) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe_rib"); - if (!$notrigger) - { - // Call trigger + if (!$notrigger) { + // Call trigger $result = $this->call_trigger('COMPANY_RIB_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if (!$error) - { + if (!$error) { return 1; } else { return 0; @@ -136,10 +137,16 @@ class CompanyBankAccount extends Account global $conf; $error = 0; - if (!$this->id) return -1; + if (!$this->id) { + return -1; + } - if (dol_strlen($this->domiciliation) > 255) $this->domiciliation = dol_trunc($this->domiciliation, 254, 'right', 'UTF-8', 1); - if (dol_strlen($this->owner_address) > 255) $this->owner_address = dol_trunc($this->owner_address, 254, 'right', 'UTF-8', 1); + if (dol_strlen($this->domiciliation) > 255) { + $this->domiciliation = dol_trunc($this->domiciliation, 254, 'right', 'UTF-8', 1); + } + if (dol_strlen($this->owner_address) > 255) { + $this->owner_address = dol_trunc($this->owner_address, 254, 'right', 'UTF-8', 1); + } $sql = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET"; $sql .= " bank = '".$this->db->escape($this->bank)."'"; @@ -153,28 +160,28 @@ class CompanyBankAccount extends Account $sql .= ",proprio = '".$this->db->escape($this->proprio)."'"; $sql .= ",owner_address = '".$this->db->escape($this->owner_address)."'"; $sql .= ",default_rib = ".$this->default_rib; - if ($conf->prelevement->enabled) - { + if ($conf->prelevement->enabled) { $sql .= ",frstrecur = '".$this->db->escape($this->frstrecur)."'"; $sql .= ",rum = '".$this->db->escape($this->rum)."'"; $sql .= ",date_rum = ".($this->date_rum ? "'".$this->db->idate($this->date_rum)."'" : "null"); } - if (trim($this->label) != '') + if (trim($this->label) != '') { $sql .= ",label = '".$this->db->escape($this->label)."'"; - else $sql .= ",label = NULL"; + } else { + $sql .= ",label = NULL"; + } $sql .= " WHERE rowid = ".$this->id; $result = $this->db->query($sql); - if ($result) - { - if (!$notrigger) - { + if ($result) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('COMPANY_RIB_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if (!$error) - { + if (!$error) { return 1; } else { return -1; @@ -199,24 +206,29 @@ class CompanyBankAccount extends Account */ public function fetch($id, $socid = 0, $default = 1, $type = 'ban') { - if (empty($id) && empty($socid)) return -1; + if (empty($id) && empty($socid)) { + return -1; + } $sql = "SELECT rowid, type, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,"; $sql .= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur, date_rum"; $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib"; - if ($id) $sql .= " WHERE rowid = ".$id; - if ($socid) - { + if ($id) { + $sql .= " WHERE rowid = ".((int) $id); + } + if ($socid) { $sql .= " WHERE fk_soc = ".$socid; - if ($default > -1) $sql .= " AND default_rib = ".$this->db->escape($default); - if ($type) $sql .= " AND type ='".$this->db->escape($type)."'"; + if ($default > -1) { + $sql .= " AND default_rib = ".$this->db->escape($default); + } + if ($type) { + $sql .= " AND type ='".$this->db->escape($type)."'"; + } } $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->ref = $obj->fk_soc.'-'.$obj->label; // Generate an artificial ref @@ -268,28 +280,26 @@ class CompanyBankAccount extends Account $this->db->begin(); - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('COMPANY_RIB_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_rib"; $sql .= " WHERE rowid = ".$this->id; - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $error++; $this->errors[] = $this->db->lasterror(); } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -332,10 +342,8 @@ class CompanyBankAccount extends Account dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); $result1 = $this->db->query($sql1); - if ($result1) - { - if ($this->db->num_rows($result1) == 0) - { + if ($result1) { + if ($this->db->num_rows($result1) == 0) { return 0; } else { $obj = $this->db->fetch_object($result1); @@ -352,8 +360,7 @@ class CompanyBankAccount extends Account dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); $result3 = $this->db->query($sql3); - if (!$result2 || !$result3) - { + if (!$result2 || !$result3) { dol_print_error($this->db); $this->db->rollback(); return -1; diff --git a/htdocs/societe/class/companypaymentmode.class.php b/htdocs/societe/class/companypaymentmode.class.php index e88ea0e4f7c..db19840fd8e 100644 --- a/htdocs/societe/class/companypaymentmode.class.php +++ b/htdocs/societe/class/companypaymentmode.class.php @@ -232,8 +232,12 @@ class CompanyPaymentMode extends CommonObject $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } } /** @@ -313,8 +317,12 @@ class CompanyPaymentMode extends CommonObject */ public function fetch($id, $ref = null, $socid = 0, $type = '', $morewhere = '') { - if ($socid) $morewhere .= " AND fk_soc = ".$this->db->escape($socid)." AND default_rib = 1"; - if ($type) $morewhere .= " AND type = '".$this->db->escape($type)."'"; + if ($socid) { + $morewhere .= " AND fk_soc = ".$this->db->escape($socid)." AND default_rib = 1"; + } + if ($type) { + $morewhere .= " AND type = '".$this->db->escape($type)."'"; + } $result = $this->fetchCommon($id, $ref, $morewhere); //if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines(); @@ -375,7 +383,9 @@ class CompanyPaymentMode extends CommonObject global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; $companylink = ''; @@ -386,33 +396,40 @@ class CompanyPaymentMode extends CommonObject $url = dol_buildpath('/monmodule/companypaymentmode_card.php', 1).'?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowCompanyPaymentMode"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = '<a href="'.$url.'"'; $linkstart .= $linkclose.'>'; $linkend = '</a>'; $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -433,33 +450,36 @@ class CompanyPaymentMode extends CommonObject dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); $result1 = $this->db->query($sql1); - if ($result1) - { - if ($this->db->num_rows($result1) == 0) - { + if ($result1) { + if ($this->db->num_rows($result1) == 0) { return 0; } else { $obj = $this->db->fetch_object($result1); $type = ''; - if (empty($alltypes)) $type = $obj->type; + if (empty($alltypes)) { + $type = $obj->type; + } $this->db->begin(); $sql2 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 0, tms = tms"; $sql2 .= " WHERE default_rib <> 0 AND fk_soc = ".$obj->fk_soc; - if ($type) $sql2 .= " AND type = '".$this->db->escape($type)."'"; + if ($type) { + $sql2 .= " AND type = '".$this->db->escape($type)."'"; + } dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); $result2 = $this->db->query($sql2); $sql3 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 1"; $sql3 .= " WHERE rowid = ".$obj->id; - if ($type) $sql3 .= " AND type = '".$this->db->escape($type)."'"; + if ($type) { + $sql3 .= " AND type = '".$this->db->escape($type)."'"; + } dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); $result3 = $this->db->query($sql3); - if (!$result2 || !$result3) - { + if (!$result2 || !$result3) { dol_print_error($this->db); $this->db->rollback(); return -1; @@ -496,8 +516,7 @@ class CompanyPaymentMode extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[self::STATUS_ENABLED] = $langs->trans('Enabled'); @@ -507,7 +526,9 @@ class CompanyPaymentMode extends CommonObject } $statusType = 'status5'; - if ($status == self::STATUS_ENABLED) $statusType = 'status4'; + if ($status == self::STATUS_ENABLED) { + $statusType = 'status4'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -523,30 +544,25 @@ class CompanyPaymentMode 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index c4d355ab62c..47d714e08db 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -905,9 +905,8 @@ class Societe extends CommonObject // Ajout du commercial affecte if ($this->commercial_id != '' && $this->commercial_id != -1) { $this->add_commercial($user, $this->commercial_id); - } - // si un commercial cree un client il lui est affecte automatiquement - elseif (empty($user->rights->societe->client->voir)) { + } elseif (empty($user->rights->societe->client->voir)) { + // si un commercial cree un client il lui est affecte automatiquement $this->add_commercial($user, $user->id); } @@ -984,6 +983,7 @@ class Societe extends CommonObject $contact->email = $this->email; $contact->zip = $this->zip; $contact->town = $this->town; + $this->setUpperOrLowerCase(); $contact->phone_pro = $this->phone; $contactId = $contact->create($user); @@ -1601,6 +1601,7 @@ class Societe extends CommonObject $sql .= ', e.libelle as effectif'; $sql .= ', c.code as country_code, c.label as country'; $sql .= ', d.code_departement as state_code, d.nom as state'; + $sql .= ', r.rowid as region_id, r.code_region as region_code'; $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto'; $sql .= ', te.code as typent_code'; $sql .= ', i.libelle as label_incoterms'; @@ -1611,6 +1612,7 @@ class Societe extends CommonObject $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region '; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_remise as sr ON sr.rowid = (SELECT MAX(rowid) FROM '.MAIN_DB_PREFIX.'societe_remise WHERE fk_soc = s.rowid AND entity IN ('.getEntity('discount').'))'; @@ -1688,6 +1690,8 @@ class Societe extends CommonObject $this->state_id = $obj->state_id; $this->state_code = $obj->state_code; + $this->region_id = $obj->region_id; + $this->region_code = $obj->region_code; $this->state = ($obj->state != '-' ? $obj->state : ''); $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm); @@ -1808,6 +1812,7 @@ class Societe extends CommonObject $this->db->free($resql); } else { $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); $result = -3; } @@ -1933,7 +1938,7 @@ class Societe extends CommonObject // Remove third party if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe"; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); if (!$this->db->query($sql)) { $error++; $this->errors[] = $this->db->lasterror(); @@ -2621,20 +2626,17 @@ class Societe extends CommonObject $s = ''; if (empty($option) || preg_match('/prospect/', $option)) { - if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) - { + if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) { $s .= '<a class="customer-back opacitymedium" title="'.$langs->trans("Prospect").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Prospect"), 0, 1).'</a>'; } } if (empty($option) || preg_match('/customer/', $option)) { - if (($this->client == 1 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) - { + if (($this->client == 1 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) { $s .= '<a class="customer-back" title="'.$langs->trans("Customer").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Customer"), 0, 1).'</a>'; } } if (empty($option) || preg_match('/supplier/', $option)) { - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $this->fournisseur) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $this->fournisseur) { $s .= '<a class="vendor-back" title="'.$langs->trans("Supplier").'" href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Supplier"), 0, 1).'</a>'; } } @@ -3631,7 +3633,7 @@ class Societe extends CommonObject $sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,"; $sql .= " fk_user_creat, fk_user_modif"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql .= " WHERE s.rowid = ".$id; + $sql .= " WHERE s.rowid = ".((int) $id); $result = $this->db->query($sql); if ($result) { @@ -3806,8 +3808,7 @@ class Societe extends CommonObject dol_syslog("We ask to create a contact/address too", LOG_DEBUG); $result = $this->create_individual($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($this->error, $this->errors, 'errors'); $this->db->rollback(); return -1; @@ -4677,8 +4678,7 @@ class Societe extends CommonObject $this->db->commit(); return 1; - } - else { + } else { $this->error=$this->db->lasterror(); $this->db->rollback(); return -1; diff --git a/htdocs/societe/class/societeaccount.class.php b/htdocs/societe/class/societeaccount.class.php index a315044683b..5be05d99a56 100644 --- a/htdocs/societe/class/societeaccount.class.php +++ b/htdocs/societe/class/societeaccount.class.php @@ -172,7 +172,9 @@ class SocieteAccount extends CommonObject $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { + $this->fields['rowid']['visible'] = 0; + } } /** @@ -248,7 +250,9 @@ class SocieteAccount extends CommonObject public function fetch($id, $ref = null) { $result = $this->fetchCommon($id, $ref); - if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); + if ($result > 0 && !empty($this->table_element_line)) { + $this->fetchLines(); + } return $result; } @@ -375,7 +379,9 @@ class SocieteAccount extends CommonObject global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -388,33 +394,40 @@ class SocieteAccount extends CommonObject $url = dol_buildpath('/website/websiteaccount_card.php', 1).'?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("WebsiteAccount"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = '<a href="'.$url.'"'; $linkstart .= $linkclose.'>'; $linkend = '</a>'; $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; return $result; @@ -444,35 +457,49 @@ class SocieteAccount extends CommonObject // phpcs:enable global $langs; - if ($mode == 0) - { + if ($mode == 0) { $prefix = ''; - if ($status == 1) return $langs->trans('Enabled'); - elseif ($status == 0) return $langs->trans('Disabled'); - } elseif ($mode == 1) - { - if ($status == 1) return $langs->trans('Enabled'); - elseif ($status == 0) return $langs->trans('Disabled'); - } elseif ($mode == 2) - { - if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled'); - elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled'); - } elseif ($mode == 3) - { - if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4'); - elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5'); - } elseif ($mode == 4) - { - if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled'); - elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled'); - } elseif ($mode == 5) - { - if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4'); - elseif ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5'); - } elseif ($mode == 6) - { - if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4'); - elseif ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5'); + if ($status == 1) { + return $langs->trans('Enabled'); + } elseif ($status == 0) { + return $langs->trans('Disabled'); + } + } elseif ($mode == 1) { + if ($status == 1) { + return $langs->trans('Enabled'); + } elseif ($status == 0) { + return $langs->trans('Disabled'); + } + } elseif ($mode == 2) { + if ($status == 1) { + return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled'); + } elseif ($status == 0) { + return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled'); + } + } elseif ($mode == 3) { + if ($status == 1) { + return img_picto($langs->trans('Enabled'), 'statut4'); + } elseif ($status == 0) { + return img_picto($langs->trans('Disabled'), 'statut5'); + } + } elseif ($mode == 4) { + if ($status == 1) { + return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled'); + } elseif ($status == 0) { + return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled'); + } + } elseif ($mode == 5) { + if ($status == 1) { + return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4'); + } elseif ($status == 0) { + return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5'); + } + } elseif ($mode == 6) { + if ($status == 1) { + return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4'); + } elseif ($status == 0) { + return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5'); + } } } @@ -487,30 +514,25 @@ class SocieteAccount 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; diff --git a/htdocs/societe/consumption.php b/htdocs/societe/consumption.php index fe8c2adb7bc..a7ef895041e 100644 --- a/htdocs/societe/consumption.php +++ b/htdocs/societe/consumption.php @@ -4,6 +4,7 @@ * Copyright (C) 2013-2015 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com> * Copyright (C) 2015-2017 Ferran Marcet <fmarcet@2byte.es> + * Copyright (C) 2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -35,22 +36,32 @@ $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'thi // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'societe', $socid, '&societe'); $object = new Societe($db); -if ($socid > 0) $object->fetch($socid); +if ($socid > 0) { + $object->fetch($socid); +} // Sort & Order fields $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 = 'dateprint'; +if (!$sortorder) { + $sortorder = 'DESC'; +} +if (!$sortfield) { + $sortfield = 'dateprint'; +} // Search fields $sref = GETPOST("sref"); @@ -59,8 +70,7 @@ $month = GETPOST('month', 'int'); $year = GETPOST('year', 'int'); // Clean up on purge search criteria ? -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $sref = ''; $sprod_fulldescr = ''; $year = ''; @@ -83,7 +93,9 @@ $hookmanager->initHooks(array('consumptionthirdparty')); $parameters = array('id'=>$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'); +} @@ -96,12 +108,13 @@ $formother = new FormOther($db); $productstatic = new Product($db); $title = $langs->trans("Referers", $object->name); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name." - ".$title; +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name." - ".$title; +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if (empty($socid)) -{ +if (empty($socid)) { dol_print_error($db); exit; } @@ -118,18 +131,16 @@ print '<div class="fichecenter">'; print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent tableforfield">'; -if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field -{ +if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td class="titlefield">'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>'; } //if ($conf->agenda->enabled && $user->rights->agenda->myactions->read) $elementTypeArray['action']=$langs->transnoentitiesnoconv('Events'); -if ($object->client) -{ +if ($object->client) { print '<tr><td class="titlefield">'; print $langs->trans('CustomerCode').'</td><td colspan="3">'; - print $object->code_client; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_client)); $tmpcheck = $object->check_codeclient(); if ($tmpcheck != 0 && $tmpcheck != -5) { print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; @@ -137,25 +148,36 @@ if ($object->client) print '</td></tr>'; $sql = "SELECT count(*) as nb from ".MAIN_DB_PREFIX."facture where fk_soc = ".$socid; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $obj = $db->fetch_object($resql); $nbFactsClient = $obj->nb; $thirdTypeArray['customer'] = $langs->trans("customer"); - if ($conf->propal->enabled && $user->rights->propal->lire) $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals'); - if ($conf->commande->enabled && $user->rights->commande->lire) $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders'); - if ($conf->facture->enabled && $user->rights->facture->lire) $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices'); - if ($conf->contrat->enabled && $user->rights->contrat->lire) $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts'); + if ($conf->propal->enabled && $user->rights->propal->lire) { + $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals'); + } + if ($conf->commande->enabled && $user->rights->commande->lire) { + $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders'); + } + if ($conf->facture->enabled && $user->rights->facture->lire) { + $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices'); + } + if ($conf->contrat->enabled && $user->rights->contrat->lire) { + $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts'); + } } -if (!empty($conf->ficheinter->enabled) && !empty($user->rights->ficheinter->lire)) $elementTypeArray['fichinter'] = $langs->transnoentitiesnoconv('Interventions'); +if (!empty($conf->ficheinter->enabled) && !empty($user->rights->ficheinter->lire)) { + $elementTypeArray['fichinter'] = $langs->transnoentitiesnoconv('Interventions'); +} -if ($object->fournisseur) -{ +if ($object->fournisseur) { $langs->load("supplier_proposal"); print '<tr><td class="titlefield">'; print $langs->trans('SupplierCode').'</td><td colspan="3">'; - print $object->code_fournisseur; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_fournisseur)); $tmpcheck = $object->check_codefournisseur(); if ($tmpcheck != 0 && $tmpcheck != -5) { print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; @@ -163,14 +185,22 @@ if ($object->fournisseur) print '</td></tr>'; $sql = "SELECT count(*) as nb from ".MAIN_DB_PREFIX."commande_fournisseur where fk_soc = ".$socid; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $obj = $db->fetch_object($resql); $nbCmdsFourn = $obj->nb; $thirdTypeArray['supplier'] = $langs->trans("supplier"); - if ($conf->fournisseur->enabled && $user->rights->fournisseur->facture->lire) $elementTypeArray['supplier_invoice'] = $langs->transnoentitiesnoconv('SuppliersInvoices'); - if ($conf->fournisseur->enabled && $user->rights->fournisseur->commande->lire) $elementTypeArray['supplier_order'] = $langs->transnoentitiesnoconv('SuppliersOrders'); - if ($conf->fournisseur->enabled && $user->rights->supplier_proposal->lire) $elementTypeArray['supplier_proposal'] = $langs->transnoentitiesnoconv('SupplierProposals'); + if ($conf->fournisseur->enabled && $user->rights->fournisseur->facture->lire) { + $elementTypeArray['supplier_invoice'] = $langs->transnoentitiesnoconv('SuppliersInvoices'); + } + if ($conf->fournisseur->enabled && $user->rights->fournisseur->commande->lire) { + $elementTypeArray['supplier_order'] = $langs->transnoentitiesnoconv('SuppliersOrders'); + } + if ($conf->fournisseur->enabled && $user->rights->supplier_proposal->lire) { + $elementTypeArray['supplier_proposal'] = $langs->transnoentitiesnoconv('SupplierProposals'); + } } print '</table>'; @@ -194,8 +224,7 @@ $sql_select = ''; $dateprint = 'f.datep'; $doc_number='f.id'; }*/ -if ($type_element == 'fichinter') -{ // Customer : show products from invoices +if ($type_element == 'fichinter') { // Customer : show products from invoices require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; $documentstatic = new Fichinter($db); $sql_select = 'SELECT f.rowid as doc_id, f.ref as doc_number, \'1\' as doc_type, f.datec as dateprint, f.fk_statut as status, '; @@ -205,8 +234,7 @@ if ($type_element == 'fichinter') $dateprint = 'f.datec'; $doc_number = 'f.ref'; } -if ($type_element == 'invoice') -{ // Customer : show products from invoices +if ($type_element == 'invoice') { // Customer : show products from invoices require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $documentstatic = new Facture($db); $sql_select = 'SELECT f.rowid as doc_id, f.ref as doc_number, f.type as doc_type, f.datef as dateprint, f.fk_statut as status, f.paye as paid, '; @@ -218,8 +246,7 @@ if ($type_element == 'invoice') $doc_number = 'f.ref'; $thirdTypeSelect = 'customer'; } -if ($type_element == 'propal') -{ +if ($type_element == 'propal') { require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $documentstatic = new Propal($db); $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.datep as dateprint, c.fk_statut as status, '; @@ -231,8 +258,7 @@ if ($type_element == 'propal') $doc_number = 'c.ref'; $thirdTypeSelect = 'customer'; } -if ($type_element == 'order') -{ +if ($type_element == 'order') { require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $documentstatic = new Commande($db); $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.date_commande as dateprint, c.fk_statut as status, '; @@ -244,8 +270,7 @@ if ($type_element == 'order') $doc_number = 'c.ref'; $thirdTypeSelect = 'customer'; } -if ($type_element == 'supplier_invoice') -{ // Supplier : Show products from invoices. +if ($type_element == 'supplier_invoice') { // Supplier : Show products from invoices. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; $documentstatic = new FactureFournisseur($db); $sql_select = 'SELECT f.rowid as doc_id, f.ref as doc_number, \'1\' as doc_type, f.datef as dateprint, f.fk_statut as status, f.paye as paid, '; @@ -257,8 +282,7 @@ if ($type_element == 'supplier_invoice') $doc_number = 'f.ref'; $thirdTypeSelect = 'supplier'; } -if ($type_element == 'supplier_proposal') -{ +if ($type_element == 'supplier_proposal') { require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; $documentstatic = new SupplierProposal($db); $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.date_valid as dateprint, c.fk_statut as status, '; @@ -270,8 +294,7 @@ if ($type_element == 'supplier_proposal') $doc_number = 'c.ref'; $thirdTypeSelect = 'supplier'; } -if ($type_element == 'supplier_order') -{ // Supplier : Show products from orders. +if ($type_element == 'supplier_order') { // Supplier : Show products from orders. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; $documentstatic = new CommandeFournisseur($db); $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.date_valid as dateprint, c.fk_statut as status, '; @@ -283,8 +306,7 @@ if ($type_element == 'supplier_order') $doc_number = 'c.ref'; $thirdTypeSelect = 'supplier'; } -if ($type_element == 'contract') -{ // Order +if ($type_element == 'contract') { // Order require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; $documentstatic = new Contrat($db); $documentstaticline = new ContratLigne($db); @@ -301,26 +323,42 @@ if ($type_element == 'contract') $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook -if (!empty($sql_select)) -{ +if (!empty($sql_select)) { $sql = $sql_select; $sql .= ' d.description as description,'; - if ($type_element != 'fichinter' && $type_element != 'contract' && $type_element != 'supplier_proposal') $sql .= ' d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_start, d.date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; - if ($type_element == 'supplier_proposal') $sql .= ' d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; - if ($type_element == 'contract') $sql .= ' d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_ouverture as date_start, d.date_cloture as date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; - if ($type_element != 'fichinter') $sql .= ' p.ref as ref, p.rowid as prod_id, p.rowid as fk_product, p.fk_product_type as prod_type, p.fk_product_type as fk_product_type, p.entity as pentity,'; + if ($type_element != 'fichinter' && $type_element != 'contract' && $type_element != 'supplier_proposal') { + $sql .= ' d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_start, d.date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; + } + if ($type_element == 'supplier_proposal') { + $sql .= ' d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; + } + if ($type_element == 'contract') { + $sql .= ' d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_ouverture as date_start, d.date_cloture as date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; + } + if ($type_element != 'fichinter') { + $sql .= ' p.ref as ref, p.rowid as prod_id, p.rowid as fk_product, p.fk_product_type as prod_type, p.fk_product_type as fk_product_type, p.entity as pentity,'; + } $sql .= " s.rowid as socid "; - if ($type_element != 'fichinter') $sql .= ", p.ref as prod_ref, p.label as product_label"; + if ($type_element != 'fichinter') { + $sql .= ", p.ref as prod_ref, p.label as product_label"; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".$tables_from; - if ($type_element != 'fichinter') $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON d.fk_product = p.rowid '; + if ($type_element != 'fichinter') { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON d.fk_product = p.rowid '; + } $sql .= $where; $sql .= dolSqlDateFilter($dateprint, 0, $month, $year); - if ($sref) $sql .= " AND ".$doc_number." LIKE '%".$db->escape($sref)."%'"; - if ($sprod_fulldescr) - { + if ($sref) { + $sql .= " AND ".$doc_number." LIKE '%".$db->escape($sref)."%'"; + } + if ($sprod_fulldescr) { $sql .= " AND (d.description LIKE '%".$db->escape($sprod_fulldescr)."%'"; - if (GETPOST('type_element') != 'fichinter') $sql .= " OR p.ref LIKE '%".$db->escape($sprod_fulldescr)."%'"; - if (GETPOST('type_element') != 'fichinter') $sql .= " OR p.label LIKE '%".$db->escape($sprod_fulldescr)."%'"; + if (GETPOST('type_element') != 'fichinter') { + $sql .= " OR p.ref LIKE '%".$db->escape($sprod_fulldescr)."%'"; + } + if (GETPOST('type_element') != 'fichinter') { + $sql .= " OR p.label LIKE '%".$db->escape($sprod_fulldescr)."%'"; + } $sql .= ")"; } $sql .= $db->order($sortfield, $sortorder); @@ -334,8 +372,7 @@ if (!empty($sql_select)) $disabled = 0; $showempty = 2; -if (empty($elementTypeArray) && !$object->client && !$object->fournisseur) -{ +if (empty($elementTypeArray) && !$object->client && !$object->fournisseur) { $showempty = $langs->trans("ThirdpartyNotCustomerNotSupplierSoNoRef"); $disabled = 1; } @@ -354,21 +391,36 @@ $param .= "&type_element=".urlencode($type_element); $total_qty = 0; -if ($sql_select) -{ +if ($sql_select) { $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $num = $db->num_rows($resql); $param = "&socid=".urlencode($socid)."&type_element=".urlencode($type_element); - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($sprod_fulldescr) $param .= "&sprod_fulldescr=".urlencode($sprod_fulldescr); - if ($sref) $param .= "&sref=".urlencode($sref); - if ($month) $param .= "&month=".urlencode($month); - if ($year) $param .= "&year=".urlencode($year); - 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 ($sprod_fulldescr) { + $param .= "&sprod_fulldescr=".urlencode($sprod_fulldescr); + } + if ($sref) { + $param .= "&sref=".urlencode($sref); + } + if ($month) { + $param .= "&month=".urlencode($month); + } + if ($year) { + $param .= "&year=".urlencode($year); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } print_barre_liste($langs->trans('ProductsIntoElements').' '.$typeElementString.' '.$button, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, '', 0, '', '', $limit); @@ -412,8 +464,7 @@ if ($sql_select) $i = 0; - while (($objp = $db->fetch_object($resql)) && $i < min($num, $limit)) - { + while (($objp = $db->fetch_object($resql)) && $i < min($num, $limit)) { $documentstatic->id = $objp->doc_id; $documentstatic->ref = $objp->doc_number; $documentstatic->type = $objp->doc_type; @@ -422,8 +473,11 @@ if ($sql_select) $documentstatic->statut = $objp->status; $documentstatic->status = $objp->status; $documentstatic->paye = $objp->paid; + $documentstatic->alreadypaid = $objp->paid; - if (is_object($documentstaticline)) $documentstaticline->statut = $objp->status; + if (is_object($documentstaticline)) { + $documentstaticline->statut = $objp->status; + } print '<tr class="oddeven">'; print '<td class="nobordernopadding nowrap" width="100">'; @@ -435,6 +489,8 @@ if ($sql_select) print '<td class="center">'; if ($type_element == 'contract') { print $documentstaticline->getLibStatut(5); + } elseif ($type_element == 'invoice') { + print $documentstatic->getLibStatut(5, $objp->paid); } else { print $documentstatic->getLibStatut(5); } @@ -444,11 +500,12 @@ if ($sql_select) print '<td class="tdoverflowmax300">'; // Define text, description and type - $text = ''; $description = ''; $type = 0; + $text = ''; + $description = ''; + $type = 0; // Code to show product duplicated from commonobject->printObjectLine - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { $product_static = new Product($db); $product_static->type = $objp->fk_product_type; @@ -459,20 +516,21 @@ if ($sql_select) } // Product - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { // Define output language - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $prod = new Product($db); $prod->fetch($objp->fk_product); $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) $newlang = $object->default_lang; - if (!empty($newlang)) - { + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if (empty($newlang)) { + $newlang = $object->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -491,39 +549,40 @@ if ($sql_select) <?php $txt = ''; print img_object($langs->trans("ShowReduc"), 'reduc').' '; - if ($objp->description == '(DEPOSIT)') $txt = $langs->trans("Deposit"); - elseif ($objp->description == '(EXCESS RECEIVED)') $txt = $langs->trans("ExcessReceived"); - elseif ($objp->description == '(EXCESS PAID)') $txt = $langs->trans("ExcessPaid"); + if ($objp->description == '(DEPOSIT)') { + $txt = $langs->trans("Deposit"); + } elseif ($objp->description == '(EXCESS RECEIVED)') { + $txt = $langs->trans("ExcessReceived"); + } elseif ($objp->description == '(EXCESS PAID)') { + $txt = $langs->trans("ExcessPaid"); + } //else $txt=$langs->trans("Discount"); print $txt; ?> </a> <?php - if ($objp->description) - { - if ($objp->description == '(CREDIT_NOTE)' && $objp->fk_remise_except > 0) - { + if ($objp->description) { + if ($objp->description == '(CREDIT_NOTE)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); echo ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0)); } - if ($objp->description == '(EXCESS RECEIVED)' && $objp->fk_remise_except > 0) - { + if ($objp->description == '(EXCESS RECEIVED)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); echo ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0)); - } elseif ($objp->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) - { + } elseif ($objp->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); echo ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0)); - } elseif ($objp->description == '(DEPOSIT)' && $objp->fk_remise_except > 0) - { + } elseif ($objp->description == '(DEPOSIT)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); echo ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0)); // Add date of deposit - if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec).')'; + if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) { + echo ' ('.dol_print_date($discount->datec).')'; + } } else { echo ($txt ? ' - ' : '').dol_htmlentitiesbr($objp->description); } @@ -536,15 +595,16 @@ if ($sql_select) echo get_date_range($objp->date_start, $objp->date_end); // Add description in form - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { print (!empty($objp->description) && $objp->description != $objp->product_label) ? '<br>'.dol_htmlentitiesbr($objp->description) : ''; } } else { - if (!empty($objp->label) || !empty($objp->description)) - { - if ($type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if (!empty($objp->label) || !empty($objp->description)) { + if ($type == 1) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($objp->label)) { $text .= ' <strong>'.$objp->label.'</strong>'; @@ -580,7 +640,9 @@ if ($sql_select) print '</td>'; //print '<td class="left">'.$prodreftxt.'</td>'; - if ($type_element == 'invoice' && $objp->doc_type == Facture::TYPE_CREDIT_NOTE) $objp->prod_qty = -($objp->prod_qty); + if ($type_element == 'invoice' && $objp->doc_type == Facture::TYPE_CREDIT_NOTE) { + $objp->prod_qty = -($objp->prod_qty); + } print '<td class="right">'.$objp->prod_qty.'</td>'; $total_qty += $objp->prod_qty; @@ -606,9 +668,7 @@ if ($sql_select) print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num); } $db->free($resql); -} -elseif (empty($type_element) || $type_element == -1) -{ +} elseif (empty($type_element) || $type_element == -1) { print_barre_liste($langs->trans('ProductsIntoElements').' '.$typeElementString.' '.$button, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', (!empty($num) ? $num : 0), '', ''); print '<table class="liste centpercent">'."\n"; diff --git a/htdocs/societe/contact.php b/htdocs/societe/contact.php index e57c059a633..570d8531efc 100644 --- a/htdocs/societe/contact.php +++ b/htdocs/societe/contact.php @@ -42,12 +42,20 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; -if (!empty($conf->adherent->enabled)) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; +if (!empty($conf->adherent->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; +} $langs->loadLangs(array("companies", "commercial", "bills", "banks", "users")); -if (!empty($conf->categorie->enabled)) $langs->load("categories"); -if (!empty($conf->incoterm->enabled)) $langs->load("incoterm"); -if (!empty($conf->notification->enabled)) $langs->load("mails"); +if (!empty($conf->categorie->enabled)) { + $langs->load("categories"); +} +if (!empty($conf->incoterm->enabled)) { + $langs->load("incoterm"); +} +if (!empty($conf->notification->enabled)) { + $langs->load("mails"); +} $mesg = ''; $error = 0; $errors = array(); @@ -56,8 +64,12 @@ $cancel = GETPOST('cancel', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); $confirm = GETPOST('confirm'); $socid = GETPOST('socid', 'int') ?GETPOST('socid', 'int') : GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; -if (empty($socid) && $action == 'view') $action = 'create'; +if ($user->socid) { + $socid = $user->socid; +} +if (empty($socid) && $action == 'view') { + $action = 'create'; +} $object = new Societe($db); $extrafields = new ExtraFields($db); @@ -68,8 +80,7 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('thirdpartycontact', 'globalcard')); -if ($object->fetch($socid) <= 0 && $action == 'view') -{ +if ($object->fetch($socid) <= 0 && $action == 'view') { $langs->load("errors"); print($langs->trans('ErrorRecordNotFound')); exit; @@ -78,8 +89,7 @@ if ($object->fetch($socid) <= 0 && $action == 'view') // Get object canvas (By default, this is not defined, so standard usage of dolibarr) $canvas = $object->canvas ? $object->canvas : GETPOST("canvas"); $objcanvas = null; -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('thirdparty', 'card', $canvas); @@ -87,7 +97,9 @@ if (!empty($canvas)) // Security check $result = restrictedArea($user, 'societe', $socid, '&societe', '', 'fk_soc', 'rowid', 0); -if (empty($user->rights->societe->contact->lire)) accessforbidden(); +if (empty($user->rights->societe->contact->lire)) { + accessforbidden(); +} /* @@ -96,15 +108,14 @@ if (empty($user->rights->societe->contact->lire)) accessforbidden(); $parameters = array('id'=>$socid, '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)) -{ - if ($cancel) - { +if (empty($reshook)) { + if ($cancel) { $action = ''; - if (!empty($backtopage)) - { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -124,21 +135,26 @@ $formfile = new FormFile($db); $formadmin = new FormAdmin($db); $formcompany = new FormCompany($db); -if ($socid > 0 && empty($object->id)) -{ +if ($socid > 0 && empty($object->id)) { $result = $object->fetch($socid); - if ($result <= 0) dol_print_error('', $object->error); + if ($result <= 0) { + dol_print_error('', $object->error); + } } $title = $langs->trans("ThirdParty"); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name." - ".$langs->trans('Card'); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name." - ".$langs->trans('Card'); +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); $countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; -if (!empty($object->id)) $res = $object->fetch_optionals(); +if (!empty($object->id)) { + $res = $object->fetch_optionals(); +} //if ($res < 0) { dol_print_error($db); exit; } @@ -154,11 +170,9 @@ print dol_get_fiche_end(); print '<br>'; -if ($action != 'presend') -{ +if ($action != 'presend') { // Contacts list - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $result = show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id); } } diff --git a/htdocs/societe/document.php b/htdocs/societe/document.php index 1d7ba3d2925..600cb03af1a 100644 --- a/htdocs/societe/document.php +++ b/htdocs/societe/document.php @@ -40,8 +40,7 @@ $id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')) $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { unset($action); $socid = $user->socid; } @@ -52,20 +51,29 @@ $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 (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; } -if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; } +if (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { + $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; +} +if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { + $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; +} -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "position_name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "position_name"; +} $object = new Societe($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref); $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id; @@ -81,7 +89,7 @@ $hookmanager->initHooks(array('thirdpartydocument', 'globalcard')); * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -91,16 +99,19 @@ include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; $form = new Form($db); $title = $langs->trans("ThirdParty").' - '.$langs->trans("Files"); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name.' - '.$langs->trans("Files"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name.' - '.$langs->trans("Files"); +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($object->id) -{ +if ($object->id) { /* * Show tabs */ - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = societe_prepare_head($object); $form = new Form($db); @@ -111,8 +122,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -126,16 +136,14 @@ if ($object->id) print '<table class="border tableforfield centpercent">'; // Prefix - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td class="titlefield">'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>'; } - if ($object->client) - { + if ($object->client) { print '<tr><td class="titlefield">'; print $langs->trans('CustomerCode').'</td><td colspan="3">'; - print $object->code_client; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_client)); $tmpcheck = $object->check_codeclient(); if ($tmpcheck != 0 && $tmpcheck != -5) { print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; @@ -143,11 +151,10 @@ if ($object->id) print '</td></tr>'; } - if ($object->fournisseur) - { + if ($object->fournisseur) { print '<tr><td class="titlefield">'; print $langs->trans('SupplierCode').'</td><td colspan="3">'; - print $object->code_fournisseur; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_fournisseur)); $tmpcheck = $object->check_codefournisseur(); if ($tmpcheck != 0 && $tmpcheck != -5) { print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; diff --git a/htdocs/societe/index.php b/htdocs/societe/index.php index 9ce38458c7f..b76a80e1148 100644 --- a/htdocs/societe/index.php +++ b/htdocs/societe/index.php @@ -29,6 +29,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; $hookmanager = new HookManager($db); @@ -38,13 +39,34 @@ $hookmanager->initHooks(array('thirdpartiesindex')); $langs->load("companies"); $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} // Security check $result = restrictedArea($user, 'societe', 0, '', '', '', ''); $thirdparty_static = new Societe($db); +if (!isset($form) || !is_object($form)) { + $form = new Form($db); +} +// Load $resultboxes +$resultboxes = FormOther::getBoxesArea($user, "3"); + +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 @@ -54,11 +76,8 @@ $transAreaType = $langs->trans("ThirdPartiesArea"); $helpurl = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:M&oacute;dulo_Terceros'; llxHeader("", $langs->trans("ThirdParties"), $helpurl); -$linkback = ''; -print load_fiche_titre($transAreaType, $linkback, 'companies'); - -print '<div class="fichecenter"><div class="fichethirdleft">'; +print load_fiche_titre($transAreaType, $resultboxes['selectboxlist'], 'companies'); /* @@ -75,37 +94,62 @@ $total = 0; $sql = "SELECT s.rowid, s.client, s.fournisseur"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= ' WHERE s.entity IN ('.getEntity('societe').')'; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND s.rowid = ".$socid; -if (!$user->rights->fournisseur->lire) $sql .= " AND (s.fournisseur <> 1 OR s.client <> 0)"; // client=0, fournisseur=0 must be visible +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} +if (!$user->rights->fournisseur->lire) { + $sql .= " AND (s.fournisseur <> 1 OR s.client <> 0)"; // client=0, fournisseur=0 must be visible +} //print $sql; $result = $db->query($sql); -if ($result) -{ - while ($objp = $db->fetch_object($result)) - { +if ($result) { + while ($objp = $db->fetch_object($result)) { $found = 0; - if (!empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS_STATS) && ($objp->client == 2 || $objp->client == 3)) { $found = 1; $third['prospect']++; } - if (!empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS_STATS) && ($objp->client == 1 || $objp->client == 3)) { $found = 1; $third['customer']++; } - if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire && empty($conf->global->SOCIETE_DISABLE_SUPPLIERS_STATS) && $objp->fournisseur) { $found = 1; $third['supplier']++; } - if (!empty($conf->societe->enabled) && $objp->client == 0 && $objp->fournisseur == 0) { $found = 1; $third['other']++; } - if ($found) $total++; + if (!empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS_STATS) && ($objp->client == 2 || $objp->client == 3)) { + $found = 1; $third['prospect']++; + } + if (!empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS_STATS) && ($objp->client == 1 || $objp->client == 3)) { + $found = 1; $third['customer']++; + } + if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire && empty($conf->global->SOCIETE_DISABLE_SUPPLIERS_STATS) && $objp->fournisseur) { + $found = 1; $third['supplier']++; + } + if (!empty($conf->societe->enabled) && $objp->client == 0 && $objp->fournisseur == 0) { + $found = 1; $third['other']++; + } + if ($found) { + $total++; + } } -} else dol_print_error($db); +} else { + dol_print_error($db); +} -print '<div class="div-table-responsive-no-min">'; -print '<table class="noborder nohover centpercent">'."\n"; -print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").'</th></tr>'; -if (!empty($conf->use_javascript_ajax) && ((round($third['prospect']) ? 1 : 0) + (round($third['customer']) ? 1 : 0) + (round($third['supplier']) ? 1 : 0) + (round($third['other']) ? 1 : 0) >= 2)) -{ - print '<tr><td class="center" colspan="2">'; +$thirdpartygraph = '<div class="div-table-responsive-no-min">'; +$thirdpartygraph .= '<table class="noborder nohover centpercent">'."\n"; +$thirdpartygraph .= '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").'</th></tr>'; +if (!empty($conf->use_javascript_ajax) && ((round($third['prospect']) ? 1 : 0) + (round($third['customer']) ? 1 : 0) + (round($third['supplier']) ? 1 : 0) + (round($third['other']) ? 1 : 0) >= 2)) { + $thirdpartygraph .= '<tr><td class="center" colspan="2">'; $dataseries = array(); - if (!empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS_STATS)) $dataseries[] = array($langs->trans("Prospects"), round($third['prospect'])); - if (!empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS_STATS)) $dataseries[] = array($langs->trans("Customers"), round($third['customer'])); - if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire && empty($conf->global->SOCIETE_DISABLE_SUPPLIERS_STATS)) $dataseries[] = array($langs->trans("Suppliers"), round($third['supplier'])); - if (!empty($conf->societe->enabled)) $dataseries[] = array($langs->trans("Others"), round($third['other'])); + if (!empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS_STATS)) { + $dataseries[] = array($langs->trans("Prospects"), round($third['prospect'])); + } + if (!empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS_STATS)) { + $dataseries[] = array($langs->trans("Customers"), round($third['customer'])); + } + if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire && empty($conf->global->SOCIETE_DISABLE_SUPPLIERS_STATS)) { + $dataseries[] = array($langs->trans("Suppliers"), round($third['supplier'])); + } + if (!empty($conf->societe->enabled)) { + $dataseries[] = array($langs->trans("Others"), round($third['other'])); + } include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; $dolgraph = new DolGraph(); $dolgraph->SetData($dataseries); @@ -114,71 +158,63 @@ if (!empty($conf->use_javascript_ajax) && ((round($third['prospect']) ? 1 : 0) + $dolgraph->SetType(array('pie')); $dolgraph->setHeight('200'); $dolgraph->draw('idgraphthirdparties'); - print $dolgraph->show(); - print '</td></tr>'."\n"; + $thirdpartygraph .= $dolgraph->show(); + $thirdpartygraph .= '</td></tr>'."\n"; } else { - if (!empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS_STATS)) - { + if (!empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS_STATS)) { $statstring = "<tr>"; $statstring .= '<td><a href="'.DOL_URL_ROOT.'/societe/list.php?type=p">'.$langs->trans("Prospects").'</a></td><td class="right">'.round($third['prospect']).'</td>'; $statstring .= "</tr>"; } - if (!empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS_STATS)) - { + if (!empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS_STATS)) { $statstring .= "<tr>"; $statstring .= '<td><a href="'.DOL_URL_ROOT.'/societe/list.php?type=c">'.$langs->trans("Customers").'</a></td><td class="right">'.round($third['customer']).'</td>'; $statstring .= "</tr>"; } - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && empty($conf->global->SOCIETE_DISABLE_SUPPLIERS_STATS) && $user->rights->fournisseur->lire) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && empty($conf->global->SOCIETE_DISABLE_SUPPLIERS_STATS) && $user->rights->fournisseur->lire) { $statstring2 = "<tr>"; $statstring2 .= '<td><a href="'.DOL_URL_ROOT.'/societe/list.php?type=f">'.$langs->trans("Suppliers").'</a></td><td class="right">'.round($third['supplier']).'</td>'; $statstring2 .= "</tr>"; } - print $statstring; - print $statstring2; + $thirdpartygraph .= $statstring; + $thirdpartygraph .= $statstring2; } -print '<tr class="liste_total"><td>'.$langs->trans("UniqueThirdParties").'</td><td class="right">'; -print $total; -print '</td></tr>'; -print '</table>'; -print '</div>'; +$thirdpartygraph .= '<tr class="liste_total"><td>'.$langs->trans("UniqueThirdParties").'</td><td class="right">'; +$thirdpartygraph .= $total; +$thirdpartygraph .= '</td></tr>'; +$thirdpartygraph .= '</table>'; +$thirdpartygraph .= '</div>'; -if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTATS_ON_THIRDPARTIES)) -{ +if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTATS_ON_THIRDPARTIES)) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $elementtype = 'societe'; - print '<br>'; - - print '<div class="div-table-responsive-no-min">'; - print '<table class="noborder nohover centpercent">'; - print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Categories").'</th></tr>'; - print '<tr><td class="center" colspan="2">'; + $thirdpartycateggraph = '<div class="div-table-responsive-no-min">'; + $thirdpartycateggraph .= '<table class="noborder nohover centpercent">'; + $thirdpartycateggraph .= '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Categories").'</th></tr>'; + $thirdpartycateggraph .= '<tr><td class="center" colspan="2">'; $sql = "SELECT c.label, count(*) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."categorie_societe as cs"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie as c ON cs.fk_categorie = c.rowid"; $sql .= " WHERE c.type = 2"; - if (!is_numeric($conf->global->CATEGORY_GRAPHSTATS_ON_THIRDPARTIES)) $sql .= " AND c.label like '".$db->escape($conf->global->CATEGORY_GRAPHSTATS_ON_THIRDPARTIES)."'"; + if (!is_numeric($conf->global->CATEGORY_GRAPHSTATS_ON_THIRDPARTIES)) { + $sql .= " AND c.label like '".$db->escape($conf->global->CATEGORY_GRAPHSTATS_ON_THIRDPARTIES)."'"; + } $sql .= " AND c.entity IN (".getEntity('category').")"; $sql .= " GROUP BY c.label"; $total = 0; $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $i = 0; - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { $dataseries = array(); $rest = 0; $nbmax = 10; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); - if ($i < $nbmax) - { + if ($i < $nbmax) { $dataseries[] = array($obj->label, round($obj->nb)); } else { $rest += $obj->nb; @@ -186,8 +222,7 @@ if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTA $total += $obj->nb; $i++; } - if ($i > $nbmax) - { + if ($i > $nbmax) { $dataseries[] = array($langs->trans("Other"), round($rest)); } include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -198,28 +233,25 @@ if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTA $dolgraph->SetType(array('pie')); $dolgraph->setHeight('200'); $dolgraph->draw('idgraphcateg'); - print $dolgraph->show(); + $thirdpartycateggraph .= $dolgraph->show(); } else { - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); - print '<tr class="oddeven"><td>'.$obj->label.'</td><td>'.$obj->nb.'</td></tr>'; + $thirdpartycateggraph .= '<tr class="oddeven"><td>'.$obj->label.'</td><td>'.$obj->nb.'</td></tr>'; $total += $obj->nb; $i++; } } } - print '</td></tr>'; - print '<tr class="liste_total"><td>'.$langs->trans("Total").'</td><td class="right">'; - print $total; - print '</td></tr>'; - print '</table>'; - print '</div>'; + $thirdpartycateggraph .= '</td></tr>'; + $thirdpartycateggraph .= '<tr class="liste_total"><td>'.$langs->trans("Total").'</td><td class="right">'; + $thirdpartycateggraph .= $total; + $thirdpartycateggraph .= '</td></tr>'; + $thirdpartycateggraph .= '</table>'; + $thirdpartycateggraph .= '</div>'; } -print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; - /* * Latest modified third parties @@ -234,37 +266,42 @@ $sql .= ", s.logo"; $sql .= ", s.entity"; $sql .= ", s.canvas, s.tms as date_modification, s.status as status"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= ' WHERE s.entity IN ('.getEntity('societe').')'; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND s.rowid = ".$socid; -if (!$user->rights->fournisseur->lire) $sql .= " AND (s.fournisseur != 1 OR s.client != 0)"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} +if (!$user->rights->fournisseur->lire) { + $sql .= " AND (s.fournisseur != 1 OR s.client != 0)"; +} $sql .= $db->order("s.tms", "DESC"); $sql .= $db->plimit($max, 0); //print $sql; $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; - if ($num > 0) - { + if ($num > 0) { $transRecordedType = $langs->trans("LastModifiedThirdParties", $max); - print "\n<!-- last thirdparties modified -->\n"; - print '<div class="div-table-responsive-no-min">'; - print '<table class="noborder centpercent">'; + $lastmodified = "\n<!-- last thirdparties modified -->\n"; + $lastmodified .= '<div class="div-table-responsive-no-min">'; + $lastmodified .= '<table class="noborder centpercent">'; - print '<tr class="liste_titre"><th colspan="2">'.$transRecordedType.'</th>'; - print '<th>&nbsp;</th>'; - print '<th class="right"><a href="'.DOL_URL_ROOT.'/societe/list.php?sortfield=s.tms&sortorder=DESC">'.$langs->trans("FullList").'</th>'; - print '</tr>'."\n"; + $lastmodified .= '<tr class="liste_titre"><th colspan="2">'.$transRecordedType.'</th>'; + $lastmodified .= '<th>&nbsp;</th>'; + $lastmodified .= '<th class="right"><a href="'.DOL_URL_ROOT.'/societe/list.php?sortfield=s.tms&sortorder=DESC">'.$langs->trans("FullList").'</th>'; + $lastmodified .= '</tr>'."\n"; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($result); $thirdparty_static->id = $objp->rowid; @@ -282,37 +319,63 @@ if ($result) $thirdparty_static->code_compta_fournisseur = $objp->code_compta_fournisseur; $thirdparty_static->code_compta = $objp->code_compta; - print '<tr class="oddeven">'; + $lastmodified .= '<tr class="oddeven">'; // Name - print '<td class="nowrap tdoverflowmax200">'; - print $thirdparty_static->getNomUrl(1); - print "</td>\n"; + $lastmodified .= '<td class="nowrap tdoverflowmax200">'; + $lastmodified .= $thirdparty_static->getNomUrl(1); + $lastmodified .= "</td>\n"; // Type - print '<td class="center">'; - print $thirdparty_static->getTypeUrl(); - print '</td>'; + $lastmodified .= '<td class="center">'; + $lastmodified .= $thirdparty_static->getTypeUrl(); + $lastmodified .= '</td>'; // Last modified date - print '<td class="right tddate">'; - print dol_print_date($thirdparty_static->date_modification, 'day'); - print "</td>"; - print '<td class="right nowrap">'; - print $thirdparty_static->getLibStatut(3); - print "</td>"; - print "</tr>\n"; + $lastmodified .= '<td class="right tddate">'; + $lastmodified .= dol_print_date($thirdparty_static->date_modification, 'day'); + $lastmodified .= "</td>"; + $lastmodified .= '<td class="right nowrap">'; + $lastmodified .= $thirdparty_static->getLibStatut(3); + $lastmodified .= "</td>"; + $lastmodified .= "</tr>\n"; $i++; } $db->free($result); - print "</table>\n"; - print '</div>'; - print "<!-- End last thirdparties modified -->\n"; + $lastmodified .= "</table>\n"; + $lastmodified .= '</div>'; + $lastmodified .= "<!-- End last thirdparties modified -->\n"; } } else { dol_print_error($db); } -print '</div></div></div>'; +//print '</div></div></div>'; + +// boxes +print '<div class="clearboth"></div>'; +print '<div class="fichecenter fichecenterbis">'; + +$boxlist = '<div class="twocolumns">'; + +$boxlist .= '<div class="firstcolumn fichehalfleft boxhalfleft" id="boxhalfleft">'; +$boxlist .= $thirdpartygraph; +$boxlist .= '<br>'; +$boxlist .= $thirdpartycateggraph; +$boxlist .= '<br>'; +$boxlist .= $resultboxes['boxlista']; +$boxlist .= '</div>'."\n"; + +$boxlist .= '<div class="secondcolumn fichehalfright boxhalfright" id="boxhalfright">'; +$boxlist .= $lastmodified; +$boxlist .= '<br>'; +$boxlist .= $resultboxes['boxlistb']; +$boxlist .= '</div>'."\n"; + +$boxlist .= '</div>'; + +print $boxlist; + +print '</div>'; $parameters = array('user' => $user); $reshook = $hookmanager->executeHooks('dashboardThirdparties', $parameters, $object); // Note that $action and $object may have been modified by hook diff --git a/htdocs/societe/list.php b/htdocs/societe/list.php index e62b17559ee..74685d37b05 100644 --- a/htdocs/societe/list.php +++ b/htdocs/societe/list.php @@ -50,14 +50,15 @@ $confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'thirdpartylist'; -if ($contextpage == 'poslist') -{ +if ($contextpage == 'poslist') { $_GET['optioncss'] = 'print'; } // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'societe', $socid, ''); $search_all = trim(GETPOST('search_all', 'alphanohtml') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); @@ -78,7 +79,7 @@ $search_zip = trim(GETPOST("search_zip", 'alpha')); $search_state = trim(GETPOST("search_state", 'alpha')); $search_region = trim(GETPOST("search_region", 'alpha')); $search_email = trim(GETPOST('search_email', 'alpha')); -$search_phone = trim(GETPOST('search_phone', 'ahttps://wiki.dolibarr.org/index.php?title=Migrer_mon_Dolibarr_vers_une_offre_Cloudlpha')); +$search_phone = trim(GETPOST('search_phone', 'alpha')); $search_fax = trim(GETPOST('search_fax', 'alpha')); $search_url = trim(GETPOST('search_url', 'alpha')); $search_idprof1 = trim(GETPOST('search_idprof1', 'alpha')); @@ -113,17 +114,47 @@ $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 (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "s.nom"; -if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $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 (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "s.nom"; +} +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $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 ($type == 'c') { if (empty($contextpage) || $contextpage == 'thirdpartylist') $contextpage = 'customerlist'; if ($search_type == '') $search_type = '1,3'; } -if ($type == 'p') { if (empty($contextpage) || $contextpage == 'thirdpartylist') $contextpage = 'prospectlist'; if ($search_type == '') $search_type = '2,3'; } -if ($type == 't') { if (empty($contextpage) || $contextpage == 'poslist') $contextpage = 'poslist'; if ($search_type == '') $search_type = '1,2,3'; } -if ($type == 'f') { if (empty($contextpage) || $contextpage == 'thirdpartylist') $contextpage = 'supplierlist'; if ($search_type == '') $search_type = '4'; } +if ($type == 'c') { + if (empty($contextpage) || $contextpage == 'thirdpartylist') { + $contextpage = 'customerlist'; + } if ($search_type == '') { + $search_type = '1,3'; + } +} +if ($type == 'p') { + if (empty($contextpage) || $contextpage == 'thirdpartylist') { + $contextpage = 'prospectlist'; + } if ($search_type == '') { + $search_type = '2,3'; + } +} +if ($type == 't') { + if (empty($contextpage) || $contextpage == 'poslist') { + $contextpage = 'poslist'; + } if ($search_type == '') { + $search_type = '1,2,3'; + } +} +if ($type == 'f') { + if (empty($contextpage) || $contextpage == 'thirdpartylist') { + $contextpage = 'supplierlist'; + } if ($search_type == '') { + $search_type = '4'; + } +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new Societe($db); @@ -154,12 +185,22 @@ $fieldstosearchall = array( 's.phone'=>"Phone", 's.fax'=>"Fax", ); -if (($tmp = $langs->transnoentities("ProfId4".$mysoc->country_code)) && $tmp != "ProfId4".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof4'] = 'ProfId4'; -if (($tmp = $langs->transnoentities("ProfId5".$mysoc->country_code)) && $tmp != "ProfId5".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof5'] = 'ProfId5'; -if (($tmp = $langs->transnoentities("ProfId6".$mysoc->country_code)) && $tmp != "ProfId6".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof6'] = 'ProfId6'; -if (!empty($conf->barcode->enabled)) $fieldstosearchall['s.barcode'] = 'Gencod'; +if (($tmp = $langs->transnoentities("ProfId4".$mysoc->country_code)) && $tmp != "ProfId4".$mysoc->country_code && $tmp != '-') { + $fieldstosearchall['s.idprof4'] = 'ProfId4'; +} +if (($tmp = $langs->transnoentities("ProfId5".$mysoc->country_code)) && $tmp != "ProfId5".$mysoc->country_code && $tmp != '-') { + $fieldstosearchall['s.idprof5'] = 'ProfId5'; +} +if (($tmp = $langs->transnoentities("ProfId6".$mysoc->country_code)) && $tmp != "ProfId6".$mysoc->country_code && $tmp != '-') { + $fieldstosearchall['s.idprof6'] = 'ProfId6'; +} +if (!empty($conf->barcode->enabled)) { + $fieldstosearchall['s.barcode'] = 'Gencod'; +} // Personalized search criterias. Example: $conf->global->THIRDPARTY_QUICKSEARCH_ON_FIELDS = 's.nom=ThirdPartyName;s.name_alias=AliasNameShort;s.code_client=CustomerCode' -if (!empty($conf->global->THIRDPARTY_QUICKSEARCH_ON_FIELDS)) $fieldstosearchall = dolExplodeIntoArray($conf->global->THIRDPARTY_QUICKSEARCH_ON_FIELDS); +if (!empty($conf->global->THIRDPARTY_QUICKSEARCH_ON_FIELDS)) { + $fieldstosearchall = dolExplodeIntoArray($conf->global->THIRDPARTY_QUICKSEARCH_ON_FIELDS); +} // Define list of fields to show into list @@ -216,8 +257,7 @@ $arrayfields = array( 's.status'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), 's.import_key'=>array('label'=>"ImportId", 'checked'=>0, 'position'=>1100), ); -if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) -{ +if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { $arrayfields['s.price_level'] =array('label'=>"PriceLevel", 'position'=>30, 'checked'=>0); } @@ -232,16 +272,14 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Actions */ -if ($action == "change") // Change customer for TakePOS -{ +if ($action == "change") { // Change customer for TakePOS $idcustomer = GETPOST('idcustomer', 'int'); // Check if draft invoice already exists, if not create it $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture where ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")' AND entity IN (".getEntity('invoice').")"; $result = $db->query($sql); $num_lines = $db->num_rows($result); - if ($num_lines == 0) - { + if ($num_lines == 0) { require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $invoice = new Facture($db); $constforthirdpartyid = 'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]; @@ -257,35 +295,39 @@ if ($action == "change") // Change customer for TakePOS $sql = "UPDATE ".MAIN_DB_PREFIX."facture set fk_soc=".$idcustomer." where ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")'"; $resql = $db->query($sql); ?> - <script> - console.log("Reload page invoice.php with place=<?php print $place; ?>"); - parent.$("#poslines").load("invoice.php?place=<?php print $place; ?>", function() { - //parent.$("#poslines").scrollTop(parent.$("#poslines")[0].scrollHeight); + <script> + console.log("Reload page invoice.php with place=<?php print $place; ?>"); + parent.$("#poslines").load("invoice.php?place=<?php print $place; ?>", function() { + //parent.$("#poslines").scrollTop(parent.$("#poslines")[0].scrollHeight); <?php if (!$resql) { ?> alert('Error failed to update customer on draft invoice.'); <?php } ?> - parent.$.colorbox.close(); /* Close the popup */ - }); - </script> - <?php + parent.$.colorbox.close(); /* Close the popup */ + }); + </script> + <?php exit; } -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Did we click on 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_nom = ''; $search_alias = ''; @@ -319,10 +361,10 @@ if (empty($reshook)) $search_staff = ''; $search_status = -1; $search_stcomm = ''; - $search_level = ''; - $search_parent_name = ''; - $search_import_key = ''; - $toselect = ''; + $search_level = ''; + $search_parent_name = ''; + $search_import_key = ''; + $toselect = ''; $search_array_options = array(); } @@ -335,19 +377,22 @@ if (empty($reshook)) $uploaddir = $conf->societe->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - if ($action == 'setstcomm') - { + if ($action == 'setstcomm') { $object = new Client($db); $result = $object->fetch(GETPOST('stcommsocid')); $object->stcomm_id = dol_getIdFromCode($db, GETPOST('stcomm', 'alpha'), 'c_stcomm'); $result = $object->update($object->id, $user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } $action = ''; } } -if ($search_status == '') $search_status = 1; // always display active thirdparty first +if ($search_status == '') { + $search_status = 1; // always display active thirdparty first +} @@ -375,9 +420,15 @@ $prospectstatic->loadCacheOfProspStatus(); $title = $langs->trans("ListOfThirdParties"); -if ($type == 'c' && (empty($search_type) || ($search_type == '1,3'))) $title = $langs->trans("ListOfCustomers"); -if ($type == 'p' && (empty($search_type) || ($search_type == '2,3'))) $title = $langs->trans("ListOfProspects"); -if ($type == 'f' && (empty($search_type) || ($search_type == '4'))) $title = $langs->trans("ListOfSuppliers"); +if ($type == 'c' && (empty($search_type) || ($search_type == '1,3'))) { + $title = $langs->trans("ListOfCustomers"); +} +if ($type == 'p' && (empty($search_type) || ($search_type == '2,3'))) { + $title = $langs->trans("ListOfProspects"); +} +if ($type == 'f' && (empty($search_type) || ($search_type == '4'))) { + $title = $langs->trans("ListOfSuppliers"); +} // Select every potentiels, and note each potentiels which fit in search parameters $tab_level = array(); @@ -386,16 +437,18 @@ $sql .= " FROM ".MAIN_DB_PREFIX."c_prospectlevel"; $sql .= " WHERE active > 0"; $sql .= " ORDER BY sortorder"; $resql = $db->query($sql); -if ($resql) -{ - while ($obj = $db->fetch_object($resql)) - { +if ($resql) { + while ($obj = $db->fetch_object($resql)) { // Compute level text $level = $langs->trans($obj->code); - if ($level == $obj->code) $level = $langs->trans($obj->label); + if ($level == $obj->code) { + $level = $langs->trans($obj->label); + } $tab_level[$obj->code] = $level; } -} else dol_print_error($db); +} else { + dol_print_error($db); +} $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.barcode, s.address, s.town, s.zip, s.datec, s.code_client, s.code_fournisseur, s.logo,"; $sql .= " s.entity,"; @@ -410,13 +463,21 @@ $sql .= " country.code as country_code, country.label as country_label,"; $sql .= " state.code_departement as state_code, state.nom as state_name,"; $sql .= " region.code_region as region_code, region.nom as region_name"; // We'll need these fields in order to filter by sale (including the case where the user can only see his prospects) -if ($search_sale) $sql .= ", sc.fk_soc, sc.fk_user"; +if ($search_sale) { + $sql .= ", sc.fk_soc, sc.fk_user"; +} // We'll need these fields in order to filter by categ -if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc"; -if ($search_categ_sup) $sql .= ", cs.fk_categorie, cs.fk_soc"; +if ($search_categ_cus) { + $sql .= ", cc.fk_categorie, cc.fk_soc"; +} +if ($search_categ_sup) { + $sql .= ", cs.fk_categorie, cs.fk_soc"; +} // 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 : ''); + 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(); @@ -424,80 +485,186 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // N $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s2 ON s.parent = s2.rowid"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (s.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (s.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_effectif as staff on (staff.id = s.fk_effectif)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_regions as region on (region. code_region = state.fk_region)"; // We'll need this table joined to the select in order to filter by categ -if (!empty($search_categ_cus)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ -if (!empty($search_categ_sup)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cs ON s.rowid = cs.fk_soc"; // We'll need this table joined to the select in order to filter by categ +if (!empty($search_categ_cus)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ +} +if (!empty($search_categ_sup)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cs ON s.rowid = cs.fk_soc"; // We'll need this table joined to the select in order to filter by categ +} $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."c_stcomm as st ON s.fk_stcomm = st.id"; // We'll need this table joined to the select in order to filter by sale -if ($search_sale == -2) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid"; -//elseif ($search_sale || (empty($user->rights->societe->client->voir) && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->societe->client->readallthirdparties_advance)) && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; -elseif ($search_sale || (empty($user->rights->societe->client->voir) && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if ($search_sale == -2) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid"; + //elseif ($search_sale || (empty($user->rights->societe->client->voir) && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->societe->client->readallthirdparties_advance)) && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} elseif ($search_sale || (empty($user->rights->societe->client->voir) && !$socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE s.entity IN (".getEntity('societe').")"; //if (empty($user->rights->societe->client->voir) && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->societe->client->readallthirdparties_advance)) && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if (empty($user->rights->societe->client->voir) && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($search_sale && $search_sale != -2) $sql .= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale -if (!$user->rights->fournisseur->lire) $sql .= " AND (s.fournisseur <> 1 OR s.client <> 0)"; // client=0, fournisseur=0 must be visible -if ($search_sale == -2) $sql .= " AND sc.fk_user IS NULL"; -elseif ($search_sale > 0) $sql .= " AND sc.fk_user = ".$db->escape($search_sale); -if ($search_categ_cus > 0) $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); -if ($search_categ_sup > 0) $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ_sup); -if ($search_categ_cus == -2) $sql .= " AND cc.fk_categorie IS NULL"; -if ($search_categ_sup == -2) $sql .= " AND cs.fk_categorie IS NULL"; +if (empty($user->rights->societe->client->voir) && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($search_sale && $search_sale != -2) { + $sql .= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale +} +if (!$user->rights->fournisseur->lire) { + $sql .= " AND (s.fournisseur <> 1 OR s.client <> 0)"; // client=0, fournisseur=0 must be visible +} +if ($search_sale == -2) { + $sql .= " AND sc.fk_user IS NULL"; +} elseif ($search_sale > 0) { + $sql .= " AND sc.fk_user = ".$db->escape($search_sale); +} +if ($search_categ_cus > 0) { + $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); +} +if ($search_categ_sup > 0) { + $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ_sup); +} +if ($search_categ_cus == -2) { + $sql .= " AND cc.fk_categorie IS NULL"; +} +if ($search_categ_sup == -2) { + $sql .= " AND cs.fk_categorie IS NULL"; +} -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); -if (strlen($search_cti)) $sql .= natural_search('s.phone', $search_cti); +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} +if (strlen($search_cti)) { + $sql .= natural_search('s.phone', $search_cti); +} -if ($search_id > 0) $sql .= natural_search("s.rowid", $search_id, 1); -if ($search_nom) $sql .= natural_search("s.nom", $search_nom); -if ($search_alias) $sql .= natural_search("s.name_alias", $search_alias); -if ($search_nom_only) $sql .= natural_search("s.nom", $search_nom_only); -if ($search_customer_code) $sql .= natural_search("s.code_client", $search_customer_code); -if ($search_supplier_code) $sql .= natural_search("s.code_fournisseur", $search_supplier_code); -if ($search_account_customer_code) $sql .= natural_search("s.code_compta", $search_account_customer_code); -if ($search_account_supplier_code) $sql .= natural_search("s.code_compta_fournisseur", $search_account_supplier_code); -if ($search_address) $sql.= natural_search('s.address', $search_address); -if ($search_town) $sql .= natural_search("s.town", $search_town); -if (strlen($search_zip)) $sql .= natural_search("s.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_region) $sql .= natural_search("region.nom", $search_region); -if ($search_country && $search_country != '-1') $sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')'; -if ($search_email) $sql .= natural_search("s.email", $search_email); -if (strlen($search_phone)) $sql .= natural_search("s.phone", $search_phone); -if (strlen($search_fax)) $sql .= natural_search("s.fax", $search_fax); -if ($search_url) $sql .= natural_search("s.url", $search_url); -if (strlen($search_idprof1)) $sql .= natural_search("s.siren", $search_idprof1); -if (strlen($search_idprof2)) $sql .= natural_search("s.siret", $search_idprof2); -if (strlen($search_idprof3)) $sql .= natural_search("s.ape", $search_idprof3); -if (strlen($search_idprof4)) $sql .= natural_search("s.idprof4", $search_idprof4); -if (strlen($search_idprof5)) $sql .= natural_search("s.idprof5", $search_idprof5); -if (strlen($search_idprof6)) $sql .= natural_search("s.idprof6", $search_idprof6); -if (strlen($search_vat)) $sql .= natural_search("s.tva_intra", $search_vat); +if ($search_id > 0) { + $sql .= natural_search("s.rowid", $search_id, 1); +} +if ($search_nom) { + $sql .= natural_search("s.nom", $search_nom); +} +if ($search_alias) { + $sql .= natural_search("s.name_alias", $search_alias); +} +if ($search_nom_only) { + $sql .= natural_search("s.nom", $search_nom_only); +} +if ($search_customer_code) { + $sql .= natural_search("s.code_client", $search_customer_code); +} +if ($search_supplier_code) { + $sql .= natural_search("s.code_fournisseur", $search_supplier_code); +} +if ($search_account_customer_code) { + $sql .= natural_search("s.code_compta", $search_account_customer_code); +} +if ($search_account_supplier_code) { + $sql .= natural_search("s.code_compta_fournisseur", $search_account_supplier_code); +} +if ($search_address) { + $sql.= natural_search('s.address', $search_address); +} +if ($search_town) { + $sql .= natural_search("s.town", $search_town); +} +if (strlen($search_zip)) { + $sql .= natural_search("s.zip", $search_zip); +} +if ($search_state) { + $sql .= natural_search("state.nom", $search_state); +} +if ($search_region) { + $sql .= natural_search("region.nom", $search_region); +} +if ($search_country && $search_country != '-1') { + $sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')'; +} +if ($search_email) { + $sql .= natural_search("s.email", $search_email); +} +if (strlen($search_phone)) { + $sql .= natural_search("s.phone", $search_phone); +} +if (strlen($search_fax)) { + $sql .= natural_search("s.fax", $search_fax); +} +if ($search_url) { + $sql .= natural_search("s.url", $search_url); +} +if (strlen($search_idprof1)) { + $sql .= natural_search("s.siren", $search_idprof1); +} +if (strlen($search_idprof2)) { + $sql .= natural_search("s.siret", $search_idprof2); +} +if (strlen($search_idprof3)) { + $sql .= natural_search("s.ape", $search_idprof3); +} +if (strlen($search_idprof4)) { + $sql .= natural_search("s.idprof4", $search_idprof4); +} +if (strlen($search_idprof5)) { + $sql .= natural_search("s.idprof5", $search_idprof5); +} +if (strlen($search_idprof6)) { + $sql .= natural_search("s.idprof6", $search_idprof6); +} +if (strlen($search_vat)) { + $sql .= natural_search("s.tva_intra", $search_vat); +} // Filter on type of thirdparty -if ($search_type > 0 && in_array($search_type, array('1,3', '1,2,3', '2,3'))) $sql .= " AND s.client IN (".$db->sanitize($db->escape($search_type)).")"; -if ($search_type > 0 && in_array($search_type, array('4'))) $sql .= " AND s.fournisseur = 1"; -if ($search_type == '0') $sql .= " AND s.client = 0 AND s.fournisseur = 0"; -if ($search_status != '' && $search_status >= 0) $sql .= natural_search("s.status", $search_status, 2); -if (!empty($conf->barcode->enabled) && $search_barcode) $sql .= natural_search("s.barcode", $search_barcode); -if ($search_prive_level && $search_prive_level != '-1') $sql .= natural_search("s.price_level", $search_prive_level, 2); -if ($search_type_thirdparty && $search_type_thirdparty > 0) $sql .= natural_search("s.fk_typent", $search_type_thirdparty, 2); -if (!empty($search_staff) && $search_staff != '-1') $sql .= natural_search("s.fk_effectif", $search_staff, 2); -if ($search_level) $sql .= natural_search("s.fk_prospectlevel", join(',', $search_level), 3); -if ($search_parent_name) $sql .= natural_search("s2.nom", $search_parent_name); -if ($search_stcomm != '' && $search_stcomm != -2) $sql .= natural_search("s.fk_stcomm", $search_stcomm, 2); -if ($search_import_key) $sql .= natural_search("s.import_key", $search_import_key); +if ($search_type > 0 && in_array($search_type, array('1,3', '1,2,3', '2,3'))) { + $sql .= " AND s.client IN (".$db->sanitize($db->escape($search_type)).")"; +} +if ($search_type > 0 && in_array($search_type, array('4'))) { + $sql .= " AND s.fournisseur = 1"; +} +if ($search_type == '0') { + $sql .= " AND s.client = 0 AND s.fournisseur = 0"; +} +if ($search_status != '' && $search_status >= 0) { + $sql .= natural_search("s.status", $search_status, 2); +} +if (!empty($conf->barcode->enabled) && $search_barcode) { + $sql .= natural_search("s.barcode", $search_barcode); +} +if ($search_prive_level && $search_prive_level != '-1') { + $sql .= natural_search("s.price_level", $search_prive_level, 2); +} +if ($search_type_thirdparty && $search_type_thirdparty > 0) { + $sql .= natural_search("s.fk_typent", $search_type_thirdparty, 2); +} +if (!empty($search_staff) && $search_staff != '-1') { + $sql .= natural_search("s.fk_effectif", $search_staff, 2); +} +if ($search_level) { + $sql .= natural_search("s.fk_prospectlevel", join(',', $search_level), 3); +} +if ($search_parent_name) { + $sql .= natural_search("s2.nom", $search_parent_name); +} +if ($search_stcomm != '' && $search_stcomm != -2) { + $sql .= natural_search("s.fk_stcomm", $search_stcomm, 2); +} +if ($search_import_key) { + $sql .= natural_search("s.import_key", $search_import_key); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks $parameters = array('socid' => $socid); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook if (empty($reshook)) { - if ($socid) $sql .= " AND s.rowid = ".$socid; + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } } $sql .= $hookmanager->resPrint; @@ -505,12 +672,10 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -519,8 +684,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if (!$resql) -{ +if (!$resql) { dol_print_error($db); exit; } @@ -551,52 +715,133 @@ $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $langs->trans("ThirdParty"), $help_url); $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_all != '') $param = "&sall=".urlencode($search_all); -if ($search_categ_cus > 0) $param .= '&search_categ_cus='.urlencode($search_categ_cus); -if ($search_categ_sup > 0) $param .= '&search_categ_sup='.urlencode($search_categ_sup); -if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); -if ($search_id > 0) $param .= "&search_id=".urlencode($search_id); -if ($search_nom != '') $param .= "&search_nom=".urlencode($search_nom); -if ($search_alias != '') $param .= "&search_alias=".urlencode($search_alias); -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_phone != '') $param .= "&search_phone=".urlencode($search_phone); -if ($search_fax != '') $param .= "&search_fax=".urlencode($search_fax); -if ($search_email != '') $param .= "&search_email=".urlencode($search_email); -if ($search_url != '') $param .= "&search_url=".urlencode($search_url); -if ($search_state != '') $param .= "&search_state=".urlencode($search_state); -if ($search_country != '') $param .= "&search_country=".urlencode($search_country); -if ($search_customer_code != '') $param .= "&search_customer_code=".urlencode($search_customer_code); -if ($search_supplier_code != '') $param .= "&search_supplier_code=".urlencode($search_supplier_code); -if ($search_account_customer_code != '') $param .= "&search_account_customer_code=".urlencode($search_account_customer_code); -if ($search_account_supplier_code != '') $param .= "&search_account_supplier_code=".urlencode($search_account_supplier_code); -if ($search_barcode != '') $param .= "&search_barcode=".urlencode($search_barcode); -if ($search_idprof1 != '') $param .= '&search_idprof1='.urlencode($search_idprof1); -if ($search_idprof2 != '') $param .= '&search_idprof2='.urlencode($search_idprof2); -if ($search_idprof3 != '') $param .= '&search_idprof3='.urlencode($search_idprof3); -if ($search_idprof4 != '') $param .= '&search_idprof4='.urlencode($search_idprof4); -if ($search_idprof5 != '') $param .= '&search_idprof5='.urlencode($search_idprof5); -if ($search_idprof6 != '') $param .= '&search_idprof6='.urlencode($search_idprof6); -if ($search_vat != '') $param .= '&search_vat='.urlencode($search_vat); -if ($search_prive_level != '') $param .= '&search_prive_level='.urlencode($search_prive_level); -if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); -if ($search_type != '') $param .= '&search_type='.urlencode($search_type); -if (is_array($search_level) && count($search_level)) foreach ($search_level as $slevel) $param .= '&search_level[]='.urlencode($slevel); -if ($search_status != '') $param .= '&search_status='.urlencode($search_status); -if ($search_stcomm != '') $param .= '&search_stcomm='.urlencode($search_stcomm); -if ($search_parent_name != '') $param .= '&search_parent_name='.urlencode($search_parent_name); -if ($search_import_key != '') $param .= '&search_import_key='.urlencode($search_import_key); -if ($type != '') $param .= '&type='.urlencode($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 ($search_all != '') { + $param = "&sall=".urlencode($search_all); +} +if ($search_categ_cus > 0) { + $param .= '&search_categ_cus='.urlencode($search_categ_cus); +} +if ($search_categ_sup > 0) { + $param .= '&search_categ_sup='.urlencode($search_categ_sup); +} +if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); +} +if ($search_id > 0) { + $param .= "&search_id=".urlencode($search_id); +} +if ($search_nom != '') { + $param .= "&search_nom=".urlencode($search_nom); +} +if ($search_alias != '') { + $param .= "&search_alias=".urlencode($search_alias); +} +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_phone != '') { + $param .= "&search_phone=".urlencode($search_phone); +} +if ($search_fax != '') { + $param .= "&search_fax=".urlencode($search_fax); +} +if ($search_email != '') { + $param .= "&search_email=".urlencode($search_email); +} +if ($search_url != '') { + $param .= "&search_url=".urlencode($search_url); +} +if ($search_state != '') { + $param .= "&search_state=".urlencode($search_state); +} +if ($search_country != '') { + $param .= "&search_country=".urlencode($search_country); +} +if ($search_customer_code != '') { + $param .= "&search_customer_code=".urlencode($search_customer_code); +} +if ($search_supplier_code != '') { + $param .= "&search_supplier_code=".urlencode($search_supplier_code); +} +if ($search_account_customer_code != '') { + $param .= "&search_account_customer_code=".urlencode($search_account_customer_code); +} +if ($search_account_supplier_code != '') { + $param .= "&search_account_supplier_code=".urlencode($search_account_supplier_code); +} +if ($search_barcode != '') { + $param .= "&search_barcode=".urlencode($search_barcode); +} +if ($search_idprof1 != '') { + $param .= '&search_idprof1='.urlencode($search_idprof1); +} +if ($search_idprof2 != '') { + $param .= '&search_idprof2='.urlencode($search_idprof2); +} +if ($search_idprof3 != '') { + $param .= '&search_idprof3='.urlencode($search_idprof3); +} +if ($search_idprof4 != '') { + $param .= '&search_idprof4='.urlencode($search_idprof4); +} +if ($search_idprof5 != '') { + $param .= '&search_idprof5='.urlencode($search_idprof5); +} +if ($search_idprof6 != '') { + $param .= '&search_idprof6='.urlencode($search_idprof6); +} +if ($search_vat != '') { + $param .= '&search_vat='.urlencode($search_vat); +} +if ($search_prive_level != '') { + $param .= '&search_prive_level='.urlencode($search_prive_level); +} +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); +} +if ($search_type != '') { + $param .= '&search_type='.urlencode($search_type); +} +if (is_array($search_level) && count($search_level)) { + foreach ($search_level as $slevel) { + $param .= '&search_level[]='.urlencode($slevel); + } +} +if ($search_status != '') { + $param .= '&search_status='.urlencode($search_status); +} +if ($search_stcomm != '') { + $param .= '&search_stcomm='.urlencode($search_stcomm); +} +if ($search_parent_name != '') { + $param .= '&search_parent_name='.urlencode($search_parent_name); +} +if ($search_import_key != '') { + $param .= '&search_import_key='.urlencode($search_import_key); +} +if ($type != '') { + $param .= '&type='.urlencode($type); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // Show delete result message -if (GETPOST('delsoc')) -{ +if (GETPOST('delsoc')) { setEventMessages($langs->trans("CompanyDeleted", GETPOST('delsoc')), null, 'mesgs'); } @@ -606,20 +851,31 @@ $arrayofmassactions = array( // 'builddoc'=>$langs->trans("PDFMerge"), ); //if($user->rights->societe->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); -if ($user->rights->societe->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if ($user->rights->societe->creer) $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete', 'preaffecttag'))) $arrayofmassactions = array(); +if ($user->rights->societe->supprimer) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if ($user->rights->societe->creer) { + $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete', 'preaffecttag'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $typefilter = ''; $label = 'MenuNewThirdParty'; -if (!empty($type)) -{ +if (!empty($type)) { $typefilter = '&amp;type='.$type; - if ($type == 'p') $label = 'MenuNewProspect'; - if ($type == 'c') $label = 'MenuNewCustomer'; - if ($type == 'f') $label = 'NewSupplier'; + if ($type == 'p') { + $label = 'MenuNewProspect'; + } + if ($type == 'c') { + $label = 'MenuNewCustomer'; + } + if ($type == 'f') { + $label = 'NewSupplier'; + } } if ($contextpage == 'poslist' && $type == 't' && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) { @@ -630,7 +886,9 @@ if ($contextpage == 'poslist' && $type == 't' && (!empty($conf->global->PRODUIT_ // but allow it too, when a user has the rights to create a new customer if ($contextpage != 'poslist') { $url = DOL_URL_ROOT.'/societe/card.php?action=create'.$typefilter; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans($label), '', 'fa fa-plus-circle', $url, '', $user->rights->societe->creer); } elseif ($user->rights->societe->creer) { $url = DOL_URL_ROOT.'/societe/card.php?action=create&type=t&contextpage=poslist&optioncss=print&backtopage='.urlencode($_SERVER["PHP_SELF"].'?type=t&contextpage=poslist&nomassaction=1&optioncss=print&place='.$place); @@ -639,7 +897,9 @@ if ($contextpage != 'poslist') { } print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'" name="formfilter" autocomplete="off">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; @@ -651,13 +911,13 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort $langs->load("other"); $textprofid = array(); -foreach (array(1, 2, 3, 4, 5, 6) as $key) -{ +foreach (array(1, 2, 3, 4, 5, 6) as $key) { $label = $langs->transnoentities("ProfId".$key.$mysoc->country_code); $textprofid[$key] = ''; - if ($label != "ProfId".$key.$mysoc->country_code) - { // Get only text between () - if (preg_match('/\((.*)\)/i', $label, $reg)) $label = $reg[1]; + if ($label != "ProfId".$key.$mysoc->country_code) { // Get only text between () + if (preg_match('/\((.*)\)/i', $label, $reg)) { + $label = $reg[1]; + } $textprofid[$key] = $langs->trans("ProfIdShortDesc", $key, $mysoc->country_code, $label); } } @@ -668,29 +928,26 @@ $objecttmp = new Societe($db); $trackid = 'thi'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } // Filter on categories $moreforfilter = ''; -if (empty($type) || $type == 'c' || $type == 'p') -{ - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) - { +if (empty($type) || $type == 'c' || $type == 'p') { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '<div class="divsearchfield">'; - $moreforfilter .= img_picto('', 'category', 'class="pictofixedwidth"'); + $moreforfilter .= img_picto('', 'category', 'class="pictofixedwidth"'); $moreforfilter .= $formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1, $langs->trans('CustomersProspectsCategoriesShort')); - $moreforfilter .= '</div>'; + $moreforfilter .= '</div>'; } } -if (empty($type) || $type == 'f') -{ - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) - { +if (empty($type) || $type == 'f') { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= img_picto('', 'category', 'class="pictofixedwidth"'); @@ -700,15 +957,13 @@ if (empty($type) || $type == 'f') } // If the user can view prospects other than his' -if ($user->rights->societe->client->voir || $socid) -{ - $moreforfilter .= '<div class="divsearchfield">'; - $moreforfilter .= img_picto('', 'user', 'class="pictofixedwidth"'); - $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, $langs->trans('SalesRepresentatives'), 'maxwidth300', 1); +if ($user->rights->societe->client->voir || $socid) { + $moreforfilter .= '<div class="divsearchfield">'; + $moreforfilter .= img_picto('', 'user', 'class="pictofixedwidth"'); + $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, $langs->trans('SalesRepresentatives'), 'maxwidth300', 1); $moreforfilter .= '</div>'; } -if ($moreforfilter) -{ +if ($moreforfilter) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; $parameters = array('type'=>$type); @@ -720,205 +975,183 @@ if ($moreforfilter) $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields // Show the massaction checkboxes only when this page is not opend from the Extended POS -if ($massactionbutton && $contextpage != 'poslist') $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +if ($massactionbutton && $contextpage != 'poslist') { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +} -if (empty($arrayfields['customerorsupplier']['checked'])) print '<input type="hidden" name="type" value="'.$type.'">'; +if (empty($arrayfields['customerorsupplier']['checked'])) { + print '<input type="hidden" name="type" value="'.$type.'">'; +} print '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; // Fields title search print '<tr class="liste_titre_filter">'; -if (!empty($arrayfields['s.rowid']['checked'])) -{ +if (!empty($arrayfields['s.rowid']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring" type="text" name="search_id" size="1" value="'.dol_escape_htmltag($search_id).'">'; print '</td>'; } -if (!empty($arrayfields['s.nom']['checked'])) -{ +if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="liste_titre">'; - if (!empty($search_nom_only) && empty($search_nom)) $search_nom = $search_nom_only; + if (!empty($search_nom_only) && empty($search_nom)) { + $search_nom = $search_nom_only; + } print '<input class="flat searchstring maxwidth75imp" type="text" name="search_nom" value="'.dol_escape_htmltag($search_nom).'">'; print '</td>'; } -if (!empty($arrayfields['s.name_alias']['checked'])) -{ +if (!empty($arrayfields['s.name_alias']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth75imp" type="text" name="search_alias" value="'.dol_escape_htmltag($search_alias).'">'; print '</td>'; } // Barcode -if (!empty($arrayfields['s.barcode']['checked'])) -{ +if (!empty($arrayfields['s.barcode']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth75imp" type="text" name="search_barcode" value="'.dol_escape_htmltag($search_barcode).'">'; print '</td>'; } // Customer code -if (!empty($arrayfields['s.code_client']['checked'])) -{ +if (!empty($arrayfields['s.code_client']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth75imp" type="text" name="search_customer_code" value="'.dol_escape_htmltag($search_customer_code).'">'; print '</td>'; } // Supplier code -if (!empty($arrayfields['s.code_fournisseur']['checked'])) -{ +if (!empty($arrayfields['s.code_fournisseur']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth75imp" type="text" name="search_supplier_code" value="'.dol_escape_htmltag($search_supplier_code).'">'; print '</td>'; } // Account Customer code -if (!empty($arrayfields['s.code_compta']['checked'])) -{ +if (!empty($arrayfields['s.code_compta']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth75imp" type="text" name="search_account_customer_code" value="'.dol_escape_htmltag($search_account_customer_code).'">'; print '</td>'; } // Account Supplier code -if (!empty($arrayfields['s.code_compta_fournisseur']['checked'])) -{ +if (!empty($arrayfields['s.code_compta_fournisseur']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat maxwidth75imp" type="text" name="search_account_supplier_code" value="'.dol_escape_htmltag($search_account_supplier_code).'">'; print '</td>'; } // Address -if (!empty($arrayfields['s.address']['checked'])) -{ +if (!empty($arrayfields['s.address']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_address" value="'.dol_escape_htmltag($search_address).'">'; print '</td>'; } // Zip -if (!empty($arrayfields['s.zip']['checked'])) -{ +if (!empty($arrayfields['s.zip']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_zip" value="'.dol_escape_htmltag($search_zip).'">'; print '</td>'; } // Town -if (!empty($arrayfields['s.town']['checked'])) -{ +if (!empty($arrayfields['s.town']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_town" value="'.dol_escape_htmltag($search_town).'">'; print '</td>'; } // State -if (!empty($arrayfields['state.nom']['checked'])) -{ +if (!empty($arrayfields['state.nom']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; print '</td>'; } // Region -if (!empty($arrayfields['region.nom']['checked'])) -{ +if (!empty($arrayfields['region.nom']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_region" value="'.dol_escape_htmltag($search_region).'">'; print '</td>'; } // Country -if (!empty($arrayfields['country.code_iso']['checked'])) -{ +if (!empty($arrayfields['country.code_iso']['checked'])) { print '<td class="liste_titre center">'; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print '</td>'; } // Company type -if (!empty($arrayfields['typent.code']['checked'])) -{ +if (!empty($arrayfields['typent.code']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone center">'; // We use showempty=0 here because there is already an unknown value into dictionary. - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), 'minwidth50 maxwidth100', 1); + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), 'minwidth50 maxwidth100', 1); print '</td>'; } // Multiprice level -if (!empty($arrayfields['s.price_level']['checked'])) -{ +if (!empty($arrayfields['s.price_level']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_prive_level" value="'.dol_escape_htmltag($search_prive_level).'">'; print '</td>'; } // Staff -if (!empty($arrayfields['staff.code']['checked'])) -{ +if (!empty($arrayfields['staff.code']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone center">'; print $form->selectarray("search_staff", $formcompany->effectif_array(0), $search_staff, 0, 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth100', 1); print '</td>'; } -if (!empty($arrayfields['s.email']['checked'])) -{ +if (!empty($arrayfields['s.email']['checked'])) { // Email print '<td class="liste_titre">'; print '<input class="flat searchemail maxwidth50imp" type="text" name="search_email" value="'.dol_escape_htmltag($search_email).'">'; print '</td>'; } -if (!empty($arrayfields['s.phone']['checked'])) -{ +if (!empty($arrayfields['s.phone']['checked'])) { // Phone print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_phone" value="'.dol_escape_htmltag($search_phone).'">'; print '</td>'; } -if (!empty($arrayfields['s.fax']['checked'])) -{ +if (!empty($arrayfields['s.fax']['checked'])) { // Fax print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_fax" value="'.dol_escape_htmltag($search_fax).'">'; print '</td>'; } -if (!empty($arrayfields['s.url']['checked'])) -{ +if (!empty($arrayfields['s.url']['checked'])) { // Url print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_url" value="'.dol_escape_htmltag($search_url).'">'; print '</td>'; } -if (!empty($arrayfields['s.siren']['checked'])) -{ +if (!empty($arrayfields['s.siren']['checked'])) { // IdProf1 print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_idprof1" value="'.dol_escape_htmltag($search_idprof1).'">'; print '</td>'; } -if (!empty($arrayfields['s.siret']['checked'])) -{ +if (!empty($arrayfields['s.siret']['checked'])) { // IdProf2 print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_idprof2" value="'.dol_escape_htmltag($search_idprof2).'">'; print '</td>'; } -if (!empty($arrayfields['s.ape']['checked'])) -{ +if (!empty($arrayfields['s.ape']['checked'])) { // IdProf3 print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_idprof3" value="'.dol_escape_htmltag($search_idprof3).'">'; print '</td>'; } -if (!empty($arrayfields['s.idprof4']['checked'])) -{ +if (!empty($arrayfields['s.idprof4']['checked'])) { // IdProf4 print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_idprof4" value="'.dol_escape_htmltag($search_idprof4).'">'; print '</td>'; } -if (!empty($arrayfields['s.idprof5']['checked'])) -{ +if (!empty($arrayfields['s.idprof5']['checked'])) { // IdProf5 print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_idprof5" value="'.dol_escape_htmltag($search_idprof5).'">'; print '</td>'; } -if (!empty($arrayfields['s.idprof6']['checked'])) -{ +if (!empty($arrayfields['s.idprof6']['checked'])) { // IdProf6 print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_idprof6" value="'.dol_escape_htmltag($search_idprof6).'">'; print '</td>'; } -if (!empty($arrayfields['s.tva_intra']['checked'])) -{ +if (!empty($arrayfields['s.tva_intra']['checked'])) { // Vat number print '<td class="liste_titre">'; print '<input class="flat searchstring maxwidth50imp" type="text" name="search_vat" value="'.dol_escape_htmltag($search_vat).'">'; @@ -926,34 +1159,31 @@ if (!empty($arrayfields['s.tva_intra']['checked'])) } // Nature (customer/prospect/supplier) -if (!empty($arrayfields['customerorsupplier']['checked'])) -{ +if (!empty($arrayfields['customerorsupplier']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone center">'; - if ($type != '') print '<input type="hidden" name="type" value="'.$type.'">'; + if ($type != '') { + print '<input type="hidden" name="type" value="'.$type.'">'; + } print $formcompany->selectProspectCustomerType($search_type, 'search_type', 'search_type', 'list'); print '</select></td>'; } // Prospect level -if (!empty($arrayfields['s.fk_prospectlevel']['checked'])) -{ - print '<td class="liste_titre center">'; - print $form->multiselectarray('search_level', $tab_level, $search_level, 0, 0, 'width75', 0, 0, '', '', '', 2); +if (!empty($arrayfields['s.fk_prospectlevel']['checked'])) { + print '<td class="liste_titre center">'; + print $form->multiselectarray('search_level', $tab_level, $search_level, 0, 0, 'width75', 0, 0, '', '', '', 2); print '</td>'; } // Prospect status -if (!empty($arrayfields['s.fk_stcomm']['checked'])) -{ +if (!empty($arrayfields['s.fk_stcomm']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone center">'; $arraystcomm = array(); - foreach ($prospectstatic->cacheprospectstatus as $key => $val) - { + foreach ($prospectstatic->cacheprospectstatus as $key => $val) { $arraystcomm[$val['id']] = ($langs->trans("StatusProspect".$val['id']) != "StatusProspect".$val['id'] ? $langs->trans("StatusProspect".$val['id']) : $val['label']); } print $form->selectarray('search_stcomm', $arraystcomm, $search_stcomm, -2, 0, 0, '', 0, 0, 0, '', '', 1); print '</td>'; } -if (!empty($arrayfields['s2.nom']['checked'])) -{ +if (!empty($arrayfields['s2.nom']['checked'])) { print '<td class="liste_titre center">'; print '<input class="flat searchstring maxwidth75imp" type="text" name="search_parent_name" value="'.dol_escape_htmltag($search_parent_name).'">'; print '</td>'; @@ -966,26 +1196,22 @@ $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation -if (!empty($arrayfields['s.datec']['checked'])) -{ +if (!empty($arrayfields['s.datec']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Date modification -if (!empty($arrayfields['s.tms']['checked'])) -{ +if (!empty($arrayfields['s.tms']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Status -if (!empty($arrayfields['s.status']['checked'])) -{ +if (!empty($arrayfields['s.status']['checked'])) { print '<td class="liste_titre center minwidth75imp">'; print $form->selectarray('search_status', array('0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), $search_status, 1, 0, 0, '', 0, 0, 0, '', '', 1); print '</td>'; } -if (!empty($arrayfields['s.import_key']['checked'])) -{ +if (!empty($arrayfields['s.import_key']['checked'])) { print '<td class="liste_titre center">'; print '<input class="flat searchstring maxwidth50" type="text" name="search_import_key" value="'.dol_escape_htmltag($search_import_key).'">'; print '</td>'; @@ -998,38 +1224,102 @@ print '</td>'; print "</tr>\n"; print '<tr class="liste_titre">'; -if (!empty($arrayfields['s.rowid']['checked'])) print_liste_field_titre($arrayfields['s.rowid']['label'], $_SERVER["PHP_SELF"], "s.rowid", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['s.name_alias']['checked'])) print_liste_field_titre($arrayfields['s.name_alias']['label'], $_SERVER["PHP_SELF"], "s.name_alias", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['s.barcode']['checked'])) print_liste_field_titre($arrayfields['s.barcode']['label'], $_SERVER["PHP_SELF"], "s.barcode", $param, '', '', $sortfield, $sortorder); -if (!empty($arrayfields['s.code_client']['checked'])) print_liste_field_titre($arrayfields['s.code_client']['label'], $_SERVER["PHP_SELF"], "s.code_client", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.code_fournisseur']['checked'])) print_liste_field_titre($arrayfields['s.code_fournisseur']['label'], $_SERVER["PHP_SELF"], "s.code_fournisseur", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.code_compta']['checked'])) print_liste_field_titre($arrayfields['s.code_compta']['label'], $_SERVER["PHP_SELF"], "s.code_compta", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.code_compta_fournisseur']['checked'])) print_liste_field_titre($arrayfields['s.code_compta_fournisseur']['label'], $_SERVER["PHP_SELF"], "s.code_compta_fournisseur", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.address']['checked'])) print_liste_field_titre($arrayfields['s.address']['label'], $_SERVER['PHP_SELF'], 's.address', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], "s.zip", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], "s.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['region.nom']['checked'])) print_liste_field_titre($arrayfields['region.nom']['label'], $_SERVER["PHP_SELF"], "region.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, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, "", $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['staff.code']['checked'])) print_liste_field_titre($arrayfields['staff.code']['label'], $_SERVER["PHP_SELF"], "staff.code", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['s.price_level']['checked'])) print_liste_field_titre($arrayfields['s.price_level']['label'], $_SERVER["PHP_SELF"], "s.price_level", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.email']['checked'])) print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.phone']['checked'])) print_liste_field_titre($arrayfields['s.phone']['label'], $_SERVER["PHP_SELF"], "s.phone", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.fax']['checked'])) print_liste_field_titre($arrayfields['s.fax']['label'], $_SERVER["PHP_SELF"], "s.fax", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.url']['checked'])) print_liste_field_titre($arrayfields['s.url']['label'], $_SERVER["PHP_SELF"], "s.url", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.siren']['checked'])) print_liste_field_titre($form->textwithpicto($langs->trans("ProfId1Short"), $textprofid[1], 1, 0), $_SERVER["PHP_SELF"], "s.siren", "", $param, '', $sortfield, $sortorder, 'nowrap '); -if (!empty($arrayfields['s.siret']['checked'])) print_liste_field_titre($form->textwithpicto($langs->trans("ProfId2Short"), $textprofid[2], 1, 0), $_SERVER["PHP_SELF"], "s.siret", "", $param, '', $sortfield, $sortorder, 'nowrap '); -if (!empty($arrayfields['s.ape']['checked'])) print_liste_field_titre($form->textwithpicto($langs->trans("ProfId3Short"), $textprofid[3], 1, 0), $_SERVER["PHP_SELF"], "s.ape", "", $param, '', $sortfield, $sortorder, 'nowrap '); -if (!empty($arrayfields['s.idprof4']['checked'])) print_liste_field_titre($form->textwithpicto($langs->trans("ProfId4Short"), $textprofid[4], 1, 0), $_SERVER["PHP_SELF"], "s.idprof4", "", $param, '', $sortfield, $sortorder, 'nowrap '); -if (!empty($arrayfields['s.idprof5']['checked'])) print_liste_field_titre($form->textwithpicto($langs->trans("ProfId5Short"), $textprofid[4], 1, 0), $_SERVER["PHP_SELF"], "s.idprof5", "", $param, '', $sortfield, $sortorder, 'nowrap '); -if (!empty($arrayfields['s.idprof6']['checked'])) print_liste_field_titre($form->textwithpicto($langs->trans("ProfId6Short"), $textprofid[4], 1, 0), $_SERVER["PHP_SELF"], "s.idprof6", "", $param, '', $sortfield, $sortorder, 'nowrap '); -if (!empty($arrayfields['s.tva_intra']['checked'])) print_liste_field_titre($arrayfields['s.tva_intra']['label'], $_SERVER["PHP_SELF"], "s.tva_intra", "", $param, '', $sortfield, $sortorder, 'nowrap '); -if (!empty($arrayfields['customerorsupplier']['checked'])) print_liste_field_titre(''); // type of customer -if (!empty($arrayfields['s.fk_prospectlevel']['checked'])) print_liste_field_titre($arrayfields['s.fk_prospectlevel']['label'], $_SERVER["PHP_SELF"], "s.fk_prospectlevel", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['s.fk_stcomm']['checked'])) print_liste_field_titre($arrayfields['s.fk_stcomm']['label'], $_SERVER["PHP_SELF"], "s.fk_stcomm", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['s2.nom']['checked'])) print_liste_field_titre($arrayfields['s2.nom']['label'], $_SERVER["PHP_SELF"], "s2.nom", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['s.rowid']['checked'])) { + print_liste_field_titre($arrayfields['s.rowid']['label'], $_SERVER["PHP_SELF"], "s.rowid", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['s.name_alias']['checked'])) { + print_liste_field_titre($arrayfields['s.name_alias']['label'], $_SERVER["PHP_SELF"], "s.name_alias", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['s.barcode']['checked'])) { + print_liste_field_titre($arrayfields['s.barcode']['label'], $_SERVER["PHP_SELF"], "s.barcode", $param, '', '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.code_client']['checked'])) { + print_liste_field_titre($arrayfields['s.code_client']['label'], $_SERVER["PHP_SELF"], "s.code_client", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.code_fournisseur']['checked'])) { + print_liste_field_titre($arrayfields['s.code_fournisseur']['label'], $_SERVER["PHP_SELF"], "s.code_fournisseur", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.code_compta']['checked'])) { + print_liste_field_titre($arrayfields['s.code_compta']['label'], $_SERVER["PHP_SELF"], "s.code_compta", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.code_compta_fournisseur']['checked'])) { + print_liste_field_titre($arrayfields['s.code_compta_fournisseur']['label'], $_SERVER["PHP_SELF"], "s.code_compta_fournisseur", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.address']['checked'])) { + print_liste_field_titre($arrayfields['s.address']['label'], $_SERVER['PHP_SELF'], 's.address', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], "s.zip", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], "s.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['region.nom']['checked'])) { + print_liste_field_titre($arrayfields['region.nom']['label'], $_SERVER["PHP_SELF"], "region.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, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, "", $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['staff.code']['checked'])) { + print_liste_field_titre($arrayfields['staff.code']['label'], $_SERVER["PHP_SELF"], "staff.code", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['s.price_level']['checked'])) { + print_liste_field_titre($arrayfields['s.price_level']['label'], $_SERVER["PHP_SELF"], "s.price_level", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.email']['checked'])) { + print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.phone']['checked'])) { + print_liste_field_titre($arrayfields['s.phone']['label'], $_SERVER["PHP_SELF"], "s.phone", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.fax']['checked'])) { + print_liste_field_titre($arrayfields['s.fax']['label'], $_SERVER["PHP_SELF"], "s.fax", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.url']['checked'])) { + print_liste_field_titre($arrayfields['s.url']['label'], $_SERVER["PHP_SELF"], "s.url", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.siren']['checked'])) { + print_liste_field_titre($form->textwithpicto($langs->trans("ProfId1Short"), $textprofid[1], 1, 0), $_SERVER["PHP_SELF"], "s.siren", "", $param, '', $sortfield, $sortorder, 'nowrap '); +} +if (!empty($arrayfields['s.siret']['checked'])) { + print_liste_field_titre($form->textwithpicto($langs->trans("ProfId2Short"), $textprofid[2], 1, 0), $_SERVER["PHP_SELF"], "s.siret", "", $param, '', $sortfield, $sortorder, 'nowrap '); +} +if (!empty($arrayfields['s.ape']['checked'])) { + print_liste_field_titre($form->textwithpicto($langs->trans("ProfId3Short"), $textprofid[3], 1, 0), $_SERVER["PHP_SELF"], "s.ape", "", $param, '', $sortfield, $sortorder, 'nowrap '); +} +if (!empty($arrayfields['s.idprof4']['checked'])) { + print_liste_field_titre($form->textwithpicto($langs->trans("ProfId4Short"), $textprofid[4], 1, 0), $_SERVER["PHP_SELF"], "s.idprof4", "", $param, '', $sortfield, $sortorder, 'nowrap '); +} +if (!empty($arrayfields['s.idprof5']['checked'])) { + print_liste_field_titre($form->textwithpicto($langs->trans("ProfId5Short"), $textprofid[4], 1, 0), $_SERVER["PHP_SELF"], "s.idprof5", "", $param, '', $sortfield, $sortorder, 'nowrap '); +} +if (!empty($arrayfields['s.idprof6']['checked'])) { + print_liste_field_titre($form->textwithpicto($langs->trans("ProfId6Short"), $textprofid[4], 1, 0), $_SERVER["PHP_SELF"], "s.idprof6", "", $param, '', $sortfield, $sortorder, 'nowrap '); +} +if (!empty($arrayfields['s.tva_intra']['checked'])) { + print_liste_field_titre($arrayfields['s.tva_intra']['label'], $_SERVER["PHP_SELF"], "s.tva_intra", "", $param, '', $sortfield, $sortorder, 'nowrap '); +} +if (!empty($arrayfields['customerorsupplier']['checked'])) { + print_liste_field_titre(''); // type of customer +} +if (!empty($arrayfields['s.fk_prospectlevel']['checked'])) { + print_liste_field_titre($arrayfields['s.fk_prospectlevel']['label'], $_SERVER["PHP_SELF"], "s.fk_prospectlevel", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['s.fk_stcomm']['checked'])) { + print_liste_field_titre($arrayfields['s.fk_stcomm']['label'], $_SERVER["PHP_SELF"], "s.fk_stcomm", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['s2.nom']['checked'])) { + print_liste_field_titre($arrayfields['s2.nom']['label'], $_SERVER["PHP_SELF"], "s2.nom", "", $param, '', $sortfield, $sortorder, 'center '); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; @@ -1037,18 +1327,25 @@ 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['s.datec']['checked'])) print_liste_field_titre($arrayfields['s.datec']['label'], $_SERVER["PHP_SELF"], "s.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['s.tms']['checked'])) print_liste_field_titre($arrayfields['s.tms']['label'], $_SERVER["PHP_SELF"], "s.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['s.status']['checked'])) print_liste_field_titre($arrayfields['s.status']['label'], $_SERVER["PHP_SELF"], "s.status", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['s.import_key']['checked'])) print_liste_field_titre($arrayfields['s.import_key']['label'], $_SERVER["PHP_SELF"], "s.import_key", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['s.datec']['checked'])) { + print_liste_field_titre($arrayfields['s.datec']['label'], $_SERVER["PHP_SELF"], "s.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['s.tms']['checked'])) { + print_liste_field_titre($arrayfields['s.tms']['label'], $_SERVER["PHP_SELF"], "s.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['s.status']['checked'])) { + print_liste_field_titre($arrayfields['s.status']['label'], $_SERVER["PHP_SELF"], "s.status", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['s.import_key']['checked'])) { + print_liste_field_titre($arrayfields['s.import_key']['label'], $_SERVER["PHP_SELF"], "s.import_key", "", $param, '', $sortfield, $sortorder, 'center '); +} print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; $i = 0; $totalarray = array(); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $companystatic->id = $obj->rowid; @@ -1068,244 +1365,281 @@ while ($i < min($num, $limit)) $companystatic->code_compta_client = $obj->code_compta; $companystatic->code_compta_fournisseur = $obj->code_compta_fournisseur; - $companystatic->fk_prospectlevel = $obj->fk_prospectlevel; - $companystatic->fk_parent = $obj->fk_parent; + $companystatic->fk_prospectlevel = $obj->fk_prospectlevel; + $companystatic->fk_parent = $obj->fk_parent; $companystatic->entity = $obj->entity; print '<tr class="oddeven"'; - if ($contextpage == 'poslist') - { + if ($contextpage == 'poslist') { print ' onclick="location.href=\'list.php?action=change&contextpage=poslist&idcustomer='.$obj->rowid.'&place='.urlencode($place).'\'"'; } print '>'; - if (!empty($arrayfields['s.rowid']['checked'])) - { + if (!empty($arrayfields['s.rowid']['checked'])) { print '<td class="tdoverflowmax50">'; print $obj->rowid; print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { $savalias = $obj->name_alias; - if (!empty($arrayfields['s.name_alias']['checked'])) $companystatic->name_alias = ''; + if (!empty($arrayfields['s.name_alias']['checked'])) { + $companystatic->name_alias = ''; + } print '<td'.(empty($conf->global->MAIN_SOCIETE_SHOW_COMPLETE_NAME) ? ' class="tdoverflowmax200"' : '').'>'; - if ($contextpage == 'poslist') - { + if ($contextpage == 'poslist') { print $obj->name; } else { print $companystatic->getNomUrl(1, '', 100, 0, 1); } print "</td>\n"; $companystatic->name_alias = $savalias; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.name_alias']['checked'])) - { + if (!empty($arrayfields['s.name_alias']['checked'])) { print '<td class="tdoverflowmax200">'; print $companystatic->name_alias; print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Barcode - if (!empty($arrayfields['s.barcode']['checked'])) - { + if (!empty($arrayfields['s.barcode']['checked'])) { print '<td>'.$obj->barcode.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Customer code - if (!empty($arrayfields['s.code_client']['checked'])) - { + if (!empty($arrayfields['s.code_client']['checked'])) { print '<td class="nowraponall">'.$obj->code_client.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Supplier code - if (!empty($arrayfields['s.code_fournisseur']['checked'])) - { + if (!empty($arrayfields['s.code_fournisseur']['checked'])) { print '<td class="nowraponall">'.$obj->code_fournisseur.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Account customer code - if (!empty($arrayfields['s.code_compta']['checked'])) - { + if (!empty($arrayfields['s.code_compta']['checked'])) { print '<td>'.$obj->code_compta.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Account supplier code - if (!empty($arrayfields['s.code_compta_fournisseur']['checked'])) - { + if (!empty($arrayfields['s.code_compta_fournisseur']['checked'])) { print '<td>'.$obj->code_compta_fournisseur.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Address - if (!empty($arrayfields['s.address']['checked'])) - { + if (!empty($arrayfields['s.address']['checked'])) { print '<td>'.$obj->address.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { + if (!empty($arrayfields['s.zip']['checked'])) { print "<td>".$obj->zip."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['s.town']['checked'])) - { + if (!empty($arrayfields['s.town']['checked'])) { print "<td>".$obj->town."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print "<td>".$obj->state_name."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Region - if (!empty($arrayfields['region.nom']['checked'])) - { + if (!empty($arrayfields['region.nom']['checked'])) { print "<td>".$obj->region_name."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print '<td class="center tdoverflowmax100">'; $labelcountry = ($obj->country_code && ($langs->trans("Country".$obj->country_code) != "Country".$obj->country_code)) ? $langs->trans("Country".$obj->country_code) : $obj->country_label; print $labelcountry; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print '<td class="center">'; - if (!is_array($typenArray) || count($typenArray) == 0) $typenArray = $formcompany->typent_array(1); + if (!is_array($typenArray) || count($typenArray) == 0) { + $typenArray = $formcompany->typent_array(1); + } print $typenArray[$obj->typent_code]; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Multiprice level - if (!empty($arrayfields['s.price_level']['checked'])) - { + if (!empty($arrayfields['s.price_level']['checked'])) { print '<td class="center">'.$obj->price_level."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Staff - if (!empty($arrayfields['staff.code']['checked'])) - { + if (!empty($arrayfields['staff.code']['checked'])) { print '<td class="center">'; - if (!is_array($staffArray) || count($staffArray) == 0) $staffArray = $formcompany->effectif_array(1); + if (!is_array($staffArray) || count($staffArray) == 0) { + $staffArray = $formcompany->effectif_array(1); + } print $staffArray[$obj->staff_code]; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.email']['checked'])) - { + if (!empty($arrayfields['s.email']['checked'])) { print '<td class="tdoverflowmax150">'.dol_print_email($obj->email, $obj->rowid, $obj->socid, 'AC_EMAIL', 0, 0, 1)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.phone']['checked'])) - { + if (!empty($arrayfields['s.phone']['checked'])) { print "<td>".dol_print_phone($obj->phone, $obj->country_code, 0, $obj->rowid, 'AC_TEL', ' ', 'phone')."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.fax']['checked'])) - { + if (!empty($arrayfields['s.fax']['checked'])) { print "<td>".dol_print_phone($obj->fax, $obj->country_code, 0, $obj->rowid, 'AC_TEL', ' ', 'fax')."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.url']['checked'])) - { + if (!empty($arrayfields['s.url']['checked'])) { print "<td>".dol_print_url($obj->url, '', '', 1)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.siren']['checked'])) - { + if (!empty($arrayfields['s.siren']['checked'])) { print "<td>".$obj->idprof1."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.siret']['checked'])) - { + if (!empty($arrayfields['s.siret']['checked'])) { print "<td>".$obj->idprof2."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.ape']['checked'])) - { + if (!empty($arrayfields['s.ape']['checked'])) { print "<td>".$obj->idprof3."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.idprof4']['checked'])) - { + if (!empty($arrayfields['s.idprof4']['checked'])) { print "<td>".$obj->idprof4."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.idprof5']['checked'])) - { + if (!empty($arrayfields['s.idprof5']['checked'])) { print "<td>".$obj->idprof5."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.idprof6']['checked'])) - { + if (!empty($arrayfields['s.idprof6']['checked'])) { print "<td>".$obj->idprof6."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // VAT - if (!empty($arrayfields['s.tva_intra']['checked'])) - { + if (!empty($arrayfields['s.tva_intra']['checked'])) { print "<td>"; print $obj->tva_intra; - if ($obj->tva_intra && !isValidVATID($companystatic)) - { + if ($obj->tva_intra && !isValidVATID($companystatic)) { print img_warning("BadVATNumber", '', ''); } print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type - if (!empty($arrayfields['customerorsupplier']['checked'])) - { + if (!empty($arrayfields['customerorsupplier']['checked'])) { print '<td class="center">'; print $companystatic->getTypeUrl(1); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.fk_prospectlevel']['checked'])) - { + if (!empty($arrayfields['s.fk_prospectlevel']['checked'])) { // Prospect level print '<td class="center">'; print $companystatic->getLibProspLevel(); print "</td>"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.fk_stcomm']['checked'])) - { + if (!empty($arrayfields['s.fk_stcomm']['checked'])) { // Prospect status print '<td class="center nowrap"><div class="nowrap">'; print '<div class="inline-block">'.$companystatic->LibProspCommStatut($obj->stcomm_id, 2, $prospectstatic->cacheprospectstatus[$obj->stcomm_id]['label'], $obj->stcomm_picto); print '</div> - <div class="inline-block">'; - foreach ($prospectstatic->cacheprospectstatus as $key => $val) - { + foreach ($prospectstatic->cacheprospectstatus as $key => $val) { $titlealt = 'default'; - if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt = $val['label']; - if ($obj->stcomm_id != $val['id']) print '<a class="pictosubstatus" href="'.$_SERVER["PHP_SELF"].'?stcommsocid='.$obj->rowid.'&stcomm='.$val['code'].'&action=setstcomm&token='.newToken().$param.($page ? '&page='.urlencode($page) : '').'">'.img_action($titlealt, $val['code'], $val['picto']).'</a>'; + if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) { + $titlealt = $val['label']; + } + if ($obj->stcomm_id != $val['id']) { + print '<a class="pictosubstatus" href="'.$_SERVER["PHP_SELF"].'?stcommsocid='.$obj->rowid.'&stcomm='.$val['code'].'&action=setstcomm&token='.newToken().$param.($page ? '&page='.urlencode($page) : '').'">'.img_action($titlealt, $val['code'], $val['picto']).'</a>'; + } } print '</div></div></td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Parent company - if (!empty($arrayfields['s2.nom']['checked'])) - { + if (!empty($arrayfields['s2.nom']['checked'])) { print '<td class="center tdoverflowmax100">'; - if ($companystatic->fk_parent > 0) - { + if ($companystatic->fk_parent > 0) { $companyparent->fetch($companystatic->fk_parent); print $companyparent->getNomUrl(1); } print "</td>"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; @@ -1314,55 +1648,65 @@ while ($i < min($num, $limit)) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['s.datec']['checked'])) - { + if (!empty($arrayfields['s.datec']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['s.tms']['checked'])) - { + if (!empty($arrayfields['s.tms']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['s.status']['checked'])) - { + if (!empty($arrayfields['s.status']['checked'])) { print '<td class="center nowrap">'.$companystatic->getLibStatut(5).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.import_key']['checked'])) - { + if (!empty($arrayfields['s.import_key']['checked'])) { print '<td class="tdoverflowmax100">'; print $obj->import_key; print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column (Show the massaction button only when this page is not opend from the Extended POS) print '<td class="nowrap center">'; - if (($massactionbutton || $massaction) && $contextpage != 'poslist') // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + if (($massactionbutton || $massaction) && $contextpage != 'poslist') { // 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'."\n"; $i++; } // If no record found -if ($num == 0) -{ +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 '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } diff --git a/htdocs/societe/note.php b/htdocs/societe/note.php index 516fb95e464..22f235df7de 100644 --- a/htdocs/societe/note.php +++ b/htdocs/societe/note.php @@ -35,11 +35,15 @@ $langs->load("companies"); // Security check $id = GETPOST('id') ?GETPOST('id', 'int') : GETPOST('socid', 'int'); -if ($user->socid) $id = $user->socid; +if ($user->socid) { + $id = $user->socid; +} $result = restrictedArea($user, 'societe', $id, '&societe'); $object = new Societe($db); -if ($id > 0) $object->fetch($id); +if ($id > 0) { + $object->fetch($id); +} $permissionnote = $user->rights->societe->creer; // Used by the include of actions_setnotes.inc.php @@ -61,16 +65,19 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, $form = new Form($db); $title = $langs->trans("ThirdParty").' - '.$langs->trans("Notes"); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name.' - '.$langs->trans("Notes"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name.' - '.$langs->trans("Notes"); +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($object->id > 0) -{ +if ($object->id > 0) { /* - * Affichage onglets - */ - if (!empty($conf->notification->enabled)) $langs->load("mails"); + * Affichage onglets + */ + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = societe_prepare_head($object); @@ -89,32 +96,31 @@ if ($object->id > 0) print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent tableforfield">'; - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td class="'.$cssclass.'">'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>'; } - if ($object->client) { - print '<tr><td class="'.$cssclass.'">'; - print $langs->trans('CustomerCode').'</td><td colspan="3">'; - print $object->code_client; - $tmpcheck = $object->check_codeclient(); - if ($tmpcheck != 0 && $tmpcheck != -5) { - print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; - } - print '</td></tr>'; - } + if ($object->client) { + print '<tr><td class="'.$cssclass.'">'; + print $langs->trans('CustomerCode').'</td><td colspan="3">'; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_client)); + $tmpcheck = $object->check_codeclient(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; + } + print '</td></tr>'; + } - if ($object->fournisseur) { - print '<tr><td class="'.$cssclass.'">'; - print $langs->trans('SupplierCode').'</td><td colspan="3">'; - print $object->code_fournisseur; - $tmpcheck = $object->check_codefournisseur(); - if ($tmpcheck != 0 && $tmpcheck != -5) { - print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; - } - print '</td></tr>'; - } + if ($object->fournisseur) { + print '<tr><td class="'.$cssclass.'">'; + print $langs->trans('SupplierCode').'</td><td colspan="3">'; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_fournisseur)); + $tmpcheck = $object->check_codefournisseur(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; + } + print '</td></tr>'; + } print "</table>"; diff --git a/htdocs/societe/notify/card.php b/htdocs/societe/notify/card.php index b911bfb034e..ad83579341d 100644 --- a/htdocs/societe/notify/card.php +++ b/htdocs/societe/notify/card.php @@ -39,16 +39,24 @@ $actionid = GETPOST('actionid'); $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'societe', '', ''); $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 (!$sortorder) $sortorder = "DESC"; -if (!$sortfield) $sortfield = "n.daten"; -if (empty($page) || $page == -1) { $page = 0; } +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "n.daten"; +} +if (empty($page) || $page == -1) { + $page = 0; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -68,39 +76,34 @@ $hookmanager->initHooks(array('thirdpartynotification', 'globalcard')); $parameters = array('id'=>$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)) -{ +if (empty($reshook)) { $error = 0; // Add a notification - if ($action == 'add') - { - if (empty($contactid)) - { + if ($action == 'add') { + if (empty($contactid)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Contact")), null, 'errors'); $error++; } - if ($actionid <= 0) - { + if ($actionid <= 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Action")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; $sql .= " WHERE fk_soc=".$socid." AND fk_contact=".$contactid." AND fk_action=".$actionid; - if ($db->query($sql)) - { + if ($db->query($sql)) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_soc, fk_contact, fk_action)"; $sql .= " VALUES ('".$db->idate($now)."',".$socid.",".$contactid.",".$actionid.")"; - if (!$db->query($sql)) - { + if (!$db->query($sql)) { $error++; dol_print_error($db); } @@ -108,8 +111,7 @@ if (empty($reshook)) dol_print_error($db); } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -118,8 +120,7 @@ if (empty($reshook)) } // Remove a notification - if ($action == 'delete') - { + if ($action == 'delete') { $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def where rowid=".GETPOST('actid', 'int'); $db->query($sql); } @@ -137,14 +138,15 @@ $object = new Societe($db); $result = $object->fetch($socid); $title = $langs->trans("ThirdParty").' - '.$langs->trans("Notification"); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name.' - '.$langs->trans("Notification"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name.' - '.$langs->trans("Notification"); +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($result > 0) -{ +if ($result > 0) { $langs->load("other"); $head = societe_prepare_head($object); @@ -161,44 +163,43 @@ if ($result > 0) print '<table class="border centpercent tableforfield">'; // Prefix - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td class="titlefield">'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>'; } - if ($object->client) { - print '<tr><td class="titlefield">'; - print $langs->trans('CustomerCode').'</td><td colspan="3">'; - print $object->code_client; - $tmpcheck = $object->check_codeclient(); - if ($tmpcheck != 0 && $tmpcheck != -5) { - print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; - } - print '</td></tr>'; - } + if ($object->client) { + print '<tr><td class="titlefield">'; + print $langs->trans('CustomerCode').'</td><td colspan="3">'; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_client)); + $tmpcheck = $object->check_codeclient(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; + } + print '</td></tr>'; + } - if (!empty($conf->fournisseur->enabled) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) { - print '<tr><td class="titlefield">'; - print $langs->trans('SupplierCode').'</td><td colspan="3">'; - print $object->code_fournisseur; - $tmpcheck = $object->check_codefournisseur(); - if ($tmpcheck != 0 && $tmpcheck != -5) { - print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; - } - print '</td></tr>'; - } + if (!empty($conf->fournisseur->enabled) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) { + print '<tr><td class="titlefield">'; + print $langs->trans('SupplierCode').'</td><td colspan="3">'; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_fournisseur)); + $tmpcheck = $object->check_codefournisseur(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; + } + print '</td></tr>'; + } /*print '<tr><td class="titlefield">'.$langs->trans("NbOfActiveNotifications").'</td>'; // Notification for this thirdparty - print '<td colspan="3">'; - $nbofrecipientemails=0; - $notify=new Notify($db); - $tmparray = $notify->getNotificationsArray('', $object->id, null, 0, array('thirdparty')); - foreach($tmparray as $tmpkey => $tmpval) - { - if (! empty($tmpkey)) $nbofrecipientemails++; - } - print $nbofrecipientemails; - print '</td></tr>';*/ + print '<td colspan="3">'; + $nbofrecipientemails=0; + $notify=new Notify($db); + $tmparray = $notify->getNotificationsArray('', $object->id, null, 0, array('thirdparty')); + foreach($tmparray as $tmpkey => $tmpval) + { + if (! empty($tmpkey)) $nbofrecipientemails++; + } + print $nbofrecipientemails; + print '</td></tr>';*/ print '</table>'; @@ -232,8 +233,7 @@ if ($result > 0) $sql .= " AND c.fk_soc = ".$object->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); } else { dol_print_error($db); @@ -261,17 +261,15 @@ if ($result > 0) // Line to add a new subscription $listofemails = $object->thirdparty_and_contact_email_array(); - if (count($listofemails) > 0) - { + if (count($listofemails) > 0) { $actions = array(); // Load array of available notifications $notificationtrigger = new InterfaceNotification($db); $listofmanagedeventfornotification = $notificationtrigger->getListOfManagedEvents(); - foreach ($listofmanagedeventfornotification as $managedeventfornotification) - { - $label = ($langs->trans("Notify_".$managedeventfornotification['code']) != "Notify_".$managedeventfornotification['code'] ? $langs->trans("Notify_".$managedeventfornotification['code']) : $managedeventfornotification['label']); + foreach ($listofmanagedeventfornotification as $managedeventfornotification) { + $label = ($langs->trans("Notify_".$managedeventfornotification['code']) != "Notify_".$managedeventfornotification['code'] ? $langs->trans("Notify_".$managedeventfornotification['code']) : $managedeventfornotification['label']); $actions[$managedeventfornotification['rowid']] = $label; } print '<tr class="oddeven nohover">'; @@ -294,14 +292,12 @@ if ($result > 0) } - if ($num) - { + if ($num) { $i = 0; $contactstatic = new Contact($db); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $contactstatic->id = $obj->contact_id; @@ -310,10 +306,8 @@ if ($result > 0) print '<tr class="oddeven">'; print '<td>'.$contactstatic->getNomUrl(1); - if ($obj->type == 'email') - { - if (isValidEmail($obj->email)) - { + if ($obj->type == 'email') { + if (isValidEmail($obj->email)) { print ' &lt;'.$obj->email.'&gt;'; } else { $langs->load("errors"); @@ -326,8 +320,12 @@ if ($result > 0) print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').$label; print '</td>'; print '<td>'; - if ($obj->type == 'email') print $langs->trans("Email"); - if ($obj->type == 'sms') print $langs->trans("SMS"); + if ($obj->type == 'email') { + print $langs->trans("Email"); + } + if ($obj->type == 'sms') { + print $langs->trans("SMS"); + } print '</td>'; print '<td class="right"><a href="card.php?socid='.$socid.'&action=delete&token='.newToken().'&actid='.$obj->rowid.'">'.img_delete().'</a></td>'; print '</tr>'; @@ -338,9 +336,9 @@ if ($result > 0) // List of notifications enabled for fixed email /* - foreach($conf->global as $key => $val) - { - if (! preg_match('/^NOTIFICATION_FIXEDEMAIL_(.*)/', $key, $reg)) continue; + foreach($conf->global as $key => $val) + { + if (! preg_match('/^NOTIFICATION_FIXEDEMAIL_(.*)/', $key, $reg)) continue; print '<tr class="oddeven"><td>'; $listtmp=explode(',',$val); $first=1; @@ -349,7 +347,7 @@ if ($result > 0) if (! $first) print ', '; $first=0; $valemail=trim($valemail); - //print $keyemail.' - '.$valemail.' - '.$reg[1].'<br>'; + //print $keyemail.' - '.$valemail.' - '.$reg[1].'<br>'; if (isValidEmail($valemail, 1)) { if ($valemail == '__SUPERVISOREMAIL__') print $valemail; @@ -377,14 +375,14 @@ if ($result > 0) print '</td>'; print '<td class="right">'.$langs->trans("SeeModuleSetup", $langs->transnoentitiesnoconv("Module600Name")).'</td>'; print '</tr>'; - }*/ + }*/ /*if ($user->admin) - { + { print '<tr class="oddeven"><td colspan="4">'; print '+ <a href="'.DOL_URL_ROOT.'/admin/notification.php">'.$langs->trans("SeeModuleSetup", $langs->transnoentitiesnoconv("Module600Name")).'</a>'; print '</td></tr>'; - }*/ + }*/ print '</table>'; print '</div>'; @@ -406,12 +404,10 @@ if ($result > 0) // Count total nb of records $nbtotalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -420,19 +416,24 @@ if ($result > 0) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); } else { dol_print_error($db); } $param = '&socid='.$object->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 '<form method="post" action="'.$_SERVER["PHP_SELF"].'" name="formfilter">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; @@ -454,19 +455,16 @@ if ($result > 0) print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "n.daten", '', $param, '', $sortfield, $sortorder, 'right '); print '</tr>'; - if ($num > 0) - { + if ($num > 0) { $i = 0; $contactstatic = new Contact($db); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven"><td>'; - if ($obj->id > 0) - { + if ($obj->id > 0) { $contactstatic->id = $obj->id; $contactstatic->lastname = $obj->lastname; $contactstatic->firstname = $obj->firstname; @@ -481,18 +479,22 @@ if ($result > 0) print $label; print '</td>'; print '<td>'; - if ($obj->type == 'email') print $langs->trans("Email"); - if ($obj->type == 'sms') print $langs->trans("Sms"); + if ($obj->type == 'email') { + print $langs->trans("Email"); + } + if ($obj->type == 'sms') { + print $langs->trans("Sms"); + } print '</td>'; // TODO Add link to object here for other types /*print '<td>'; - if ($obj->object_type == 'order') - { + if ($obj->object_type == 'order') + { $orderstatic->id=$obj->object_id; $orderstatic->ref=... print $orderstatic->getNomUrl(1); - } - print '</td>';*/ + } + print '</td>';*/ // print print'<td class="right">'.dol_print_date($db->jdate($obj->daten), 'dayhour').'</td>'; print '</tr>'; @@ -507,7 +509,9 @@ if ($result > 0) print '</div>'; print '</form>'; -} else dol_print_error('', 'RecordNotFound'); +} else { + dol_print_error('', 'RecordNotFound'); +} // End of page llxFooter(); diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 8956a80d0d8..8c321b1386d 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -44,7 +44,9 @@ $langs->loadLangs(array("companies", "commercial", "banks", "bills", 'paypal', ' // Security check $socid = GETPOST("socid", "int"); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'societe', '', ''); $id = GETPOST("id", "int"); @@ -69,12 +71,10 @@ $extrafields->fetch_name_optionals_label($object->table_element); $hookmanager->initHooks(array('thirdpartybancard', 'globalcard')); -if (!empty($conf->stripe->enabled)) -{ +if (!empty($conf->stripe->enabled)) { $service = 'StripeTest'; $servicestatus = 0; - if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) - { + if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) { $service = 'StripeLive'; $servicestatus = 1; } @@ -94,47 +94,44 @@ if (!empty($conf->stripe->enabled)) * Actions */ -if ($cancel) -{ +if ($cancel) { $action = ''; } $parameters = array('id'=>$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)) -{ - if ($cancel) - { +if (empty($reshook)) { + if ($cancel) { $action = ''; - if (!empty($backtopage)) - { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } } - if ($action == 'update') - { + if ($action == 'update') { // Modification - if (!GETPOST('label', 'alpha') || !GETPOST('bank', 'alpha')) - { - if (!GETPOST('label', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - if (!GETPOST('bank', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); + if (!GETPOST('label', 'alpha') || !GETPOST('bank', 'alpha')) { + if (!GETPOST('label', 'alpha')) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + } + if (!GETPOST('bank', 'alpha')) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); + } $action = 'edit'; $error++; } - if ($companybankaccount->needIBAN() == 1) - { - if (!GETPOST('iban')) - { + if ($companybankaccount->needIBAN() == 1) { + if (!GETPOST('iban')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); $action = 'edit'; $error++; } - if (!GETPOST('bic')) - { + if (!GETPOST('bic')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); $action = 'edit'; $error++; @@ -142,8 +139,7 @@ if (empty($reshook)) } $companybankaccount->fetch($id); - if (!$error) - { + if (!$error) { $companybankaccount->socid = $object->id; $companybankaccount->bank = GETPOST('bank', 'alpha'); @@ -162,23 +158,19 @@ if (empty($reshook)) $companybankaccount->frstrecur = GETPOST('frstrecur', 'alpha'); $companybankaccount->rum = GETPOST('rum', 'alpha'); $companybankaccount->date_rum = dol_mktime(0, 0, 0, GETPOST('date_rummonth'), GETPOST('date_rumday'), GETPOST('date_rumyear')); - if (empty($companybankaccount->rum)) - { + if (empty($companybankaccount->rum)) { $companybankaccount->rum = $prelevement->buildRumNumber($object->code_client, $companybankaccount->datec, $companybankaccount->id); } - if (empty($companybankaccount->date_rum)) - { + if (empty($companybankaccount->date_rum)) { $companybankaccount->date_rum = dol_now(); } $result = $companybankaccount->update($user); - if (!$result) - { + if (!$result) { setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors'); } else { // If this account is the default bank account, we disable others - if ($companybankaccount->default_rib) - { + if ($companybankaccount->default_rib) { $companybankaccount->setAsDefault($id); // This will make sure there is only one default rib } @@ -189,23 +181,26 @@ if (empty($reshook)) } } - if ($action == 'updatecard') - { + if ($action == 'updatecard') { // Modification - if (!GETPOST('label', 'alpha') || !GETPOST('proprio', 'alpha') || !GETPOST('exp_date_month', 'alpha') || !GETPOST('exp_date_year', 'alpha')) - { - if (!GETPOST('label', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - if (!GETPOST('proprio', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NameOnCard")), null, 'errors'); + if (!GETPOST('label', 'alpha') || !GETPOST('proprio', 'alpha') || !GETPOST('exp_date_month', 'alpha') || !GETPOST('exp_date_year', 'alpha')) { + if (!GETPOST('label', 'alpha')) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + } + if (!GETPOST('proprio', 'alpha')) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NameOnCard")), null, 'errors'); + } //if (!GETPOST('cardnumber', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardNumber")), null, 'errors'); - if (!(GETPOST('exp_date_month', 'alpha') > 0) || !(GETPOST('exp_date_year', 'alpha') > 0)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpiryDate")), null, 'errors'); + if (!(GETPOST('exp_date_month', 'alpha') > 0) || !(GETPOST('exp_date_year', 'alpha') > 0)) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpiryDate")), null, 'errors'); + } //if (!GETPOST('cvn', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CVN")), null, 'errors'); $action = 'createcard'; $error++; } $companypaymentmode->fetch($id); - if (!$error) - { + if (!$error) { $companypaymentmode->fk_soc = $object->id; $companypaymentmode->bank = GETPOST('bank', 'alpha'); @@ -225,13 +220,11 @@ if (empty($reshook)) $companypaymentmode->stripe_card_ref = GETPOST('stripe_card_ref', 'alpha'); $result = $companypaymentmode->update($user); - if (!$result) - { + if (!$result) { setEventMessages($companypaymentmode->error, $companypaymentmode->errors, 'errors'); } else { // If this account is the default bank account, we disable others - if ($companypaymentmode->default_rib) - { + if ($companypaymentmode->default_rib) { $companypaymentmode->setAsDefault($id); // This will make sure there is only one default rib } @@ -242,20 +235,21 @@ if (empty($reshook)) } } - if ($action == 'add') - { + if ($action == 'add') { $error = 0; - if (!GETPOST('label', 'alpha') || !GETPOST('bank', 'alpha')) - { - if (!GETPOST('label', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - if (!GETPOST('bank', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); + if (!GETPOST('label', 'alpha') || !GETPOST('bank', 'alpha')) { + if (!GETPOST('label', 'alpha')) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + } + if (!GETPOST('bank', 'alpha')) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); + } $action = 'create'; $error++; } - if (!$error) - { + if (!$error) { // Ajout $companybankaccount = new CompanyBankAccount($db); @@ -283,52 +277,43 @@ if (empty($reshook)) $db->begin(); // This test can be done only once properties were set - if ($companybankaccount->needIBAN() == 1) - { - if (!GETPOST('iban')) - { + if ($companybankaccount->needIBAN() == 1) { + if (!GETPOST('iban')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); $action = 'create'; $error++; } - if (!GETPOST('bic')) - { + if (!GETPOST('bic')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); $action = 'create'; $error++; } } - if (!$error) - { + if (!$error) { $result = $companybankaccount->create($user); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors'); $action = 'create'; // Force chargement page création } - if (empty($companybankaccount->rum)) - { + if (empty($companybankaccount->rum)) { $companybankaccount->rum = $prelevement->buildRumNumber($object->code_client, $companybankaccount->datec, $companybankaccount->id); $companybankaccount->date_rum = dol_now(); } } - if (!$error) - { + if (!$error) { $result = $companybankaccount->update($user); // This will set the UMR number. - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors'); $action = 'create'; } } - if (!$error) - { + if (!$error) { $db->commit(); $url = $_SERVER["PHP_SELF"].'?socid='.$object->id; @@ -340,23 +325,26 @@ if (empty($reshook)) } } - if ($action == 'addcard') - { + if ($action == 'addcard') { $error = 0; - if (!GETPOST('label', 'alpha') || !GETPOST('proprio', 'alpha') || !GETPOST('exp_date_month', 'alpha') || !GETPOST('exp_date_year', 'alpha')) - { - if (!GETPOST('label', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - if (!GETPOST('proprio', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NameOnCard")), null, 'errors'); + if (!GETPOST('label', 'alpha') || !GETPOST('proprio', 'alpha') || !GETPOST('exp_date_month', 'alpha') || !GETPOST('exp_date_year', 'alpha')) { + if (!GETPOST('label', 'alpha')) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + } + if (!GETPOST('proprio', 'alpha')) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NameOnCard")), null, 'errors'); + } //if (!GETPOST('cardnumber', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardNumber")), null, 'errors'); - if (!(GETPOST('exp_date_month', 'alpha') > 0) || !(GETPOST('exp_date_year', 'alpha') > 0)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpiryDate")), null, 'errors'); + if (!(GETPOST('exp_date_month', 'alpha') > 0) || !(GETPOST('exp_date_year', 'alpha') > 0)) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpiryDate")), null, 'errors'); + } //if (!GETPOST('cvn', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CVN")), null, 'errors'); $action = 'createcard'; $error++; } - if (!$error) - { + if (!$error) { // Ajout $companypaymentmode = new CompanyPaymentMode($db); @@ -383,19 +371,16 @@ if (empty($reshook)) $db->begin(); - if (!$error) - { + if (!$error) { $result = $companypaymentmode->create($user); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($companypaymentmode->error, $companypaymentmode->errors, 'errors'); $action = 'createcard'; // Force chargement page création } } - if (!$error) - { + if (!$error) { $db->commit(); $url = $_SERVER["PHP_SELF"].'?socid='.$object->id; @@ -407,12 +392,10 @@ if (empty($reshook)) } } - if ($action == 'setasbankdefault' && GETPOST('ribid', 'int') > 0) - { + if ($action == 'setasbankdefault' && GETPOST('ribid', 'int') > 0) { $companybankaccount = new CompanyBankAccount($db); $res = $companybankaccount->setAsDefault(GETPOST('ribid', 'int')); - if ($res) - { + if ($res) { $url = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; header('Location: '.$url); exit; @@ -421,11 +404,9 @@ if (empty($reshook)) } } - if ($action == 'confirm_deletecard' && GETPOST('confirm', 'alpha') == 'yes') - { + if ($action == 'confirm_deletecard' && GETPOST('confirm', 'alpha') == 'yes') { $companypaymentmode = new CompanyPaymentMode($db); - if ($companypaymentmode->fetch($ribid ? $ribid : $id)) - { + if ($companypaymentmode->fetch($ribid ? $ribid : $id)) { /*if ($companypaymentmode->stripe_card_ref && preg_match('/pm_/', $companypaymentmode->stripe_card_ref)) { $payment_method = \Stripe\PaymentMethod::retrieve($companypaymentmode->stripe_card_ref); @@ -436,8 +417,7 @@ if (empty($reshook)) }*/ $result = $companypaymentmode->delete($user); - if ($result > 0) - { + if ($result > 0) { $url = $_SERVER['PHP_SELF']."?socid=".$object->id; header('Location: '.$url); exit; @@ -448,14 +428,11 @@ if (empty($reshook)) setEventMessages($companypaymentmode->error, $companypaymentmode->errors, 'errors'); } } - if ($action == 'confirm_delete' && GETPOST('confirm', 'alpha') == 'yes') - { + if ($action == 'confirm_delete' && GETPOST('confirm', 'alpha') == 'yes') { $companybankaccount = new CompanyBankAccount($db); - if ($companybankaccount->fetch($ribid ? $ribid : $id)) - { + if ($companybankaccount->fetch($ribid ? $ribid : $id)) { $result = $companybankaccount->delete($user); - if ($result > 0) - { + if ($result > 0) { $url = $_SERVER['PHP_SELF']."?socid=".$object->id; header('Location: '.$url); exit; @@ -470,8 +447,7 @@ if (empty($reshook)) $savid = $id; // Actions to build doc - if ($action == 'builddocrib') - { + if ($action == 'builddocrib') { $action = 'builddoc'; $moreparams = array( 'use_companybankid'=>GETPOST('companybankid'), @@ -489,19 +465,15 @@ if (empty($reshook)) $id = $savid; // Action for stripe - if (!empty($conf->stripe->enabled) && class_exists('Stripe')) - { - if ($action == 'synccustomertostripe') - { - if ($object->client == 0) - { + if (!empty($conf->stripe->enabled) && class_exists('Stripe')) { + if ($action == 'synccustomertostripe') { + if ($object->client == 0) { $error++; setEventMessages('ThisThirdpartyIsNotACustomer', null, 'errors'); } else { // Creation of Stripe customer + update of societe_account $cu = $stripe->customerStripe($object, $stripeacc, $servicestatus, 1); - if (!$cu) - { + if (!$cu) { $error++; setEventMessages($stripe->error, $stripe->errors, 'errors'); } else { @@ -509,32 +481,27 @@ if (empty($reshook)) } } } - if ($action == 'synccardtostripe') - { + if ($action == 'synccardtostripe') { $companypaymentmode = new CompanyPaymentMode($db); $companypaymentmode->fetch($id); - if ($companypaymentmode->type != 'card') - { + if ($companypaymentmode->type != 'card') { $error++; setEventMessages('ThisPaymentModeIsNotACard', null, 'errors'); } else { // Get the Stripe customer $cu = $stripe->customerStripe($object, $stripeacc, $servicestatus); - if (!$cu) - { + if (!$cu) { $error++; setEventMessages($stripe->error, $stripe->errors, 'errors'); } - if (!$error) - { + if (!$error) { // Creation of Stripe card + update of societe_account // Note that with the new Stripe API, option to create a card is no more available, instead an error message will be returned to // ask to create the crdit card from Stripe backoffice. $card = $stripe->cardStripe($cu, $companypaymentmode, $stripeacc, $servicestatus, 1); - if (!$card) - { + if (!$card) { $error++; setEventMessages($stripe->error, $stripe->errors, 'errors'); } @@ -542,8 +509,7 @@ if (empty($reshook)) } } - if ($action == 'setkey_account') - { + if ($action == 'setkey_account') { $error = 0; $newcu = GETPOST('key_account', 'alpha'); @@ -560,8 +526,7 @@ if (empty($reshook)) $resql = $db->query($sql); $num = $db->num_rows($resql); // Note: $num is always 0 on an update and delete, it is defined for select only. if (!empty($newcu)) { - if (empty($num)) - { + if (empty($num)) { $societeaccount = new SocieteAccount($db); $societeaccount->fk_soc = $object->id; $societeaccount->login = ''; @@ -571,8 +536,7 @@ if (empty($reshook)) $societeaccount->key_account = $newcu; $societeaccount->site_account = $site_account; $result = $societeaccount->create($user); - if ($result < 0) - { + if ($result < 0) { $error++; } } else { @@ -584,8 +548,7 @@ if (empty($reshook)) } //var_dump($sql); var_dump($newcu); var_dump($num); exit; - if (!$error) - { + if (!$error) { $stripecu = $newcu; $db->commit(); } else { @@ -593,8 +556,7 @@ if (empty($reshook)) } } - if ($action == 'setkey_account_supplier') - { + if ($action == 'setkey_account_supplier') { $error = 0; $newsup = GETPOST('key_account_supplier', 'alpha'); @@ -623,8 +585,7 @@ if (empty($reshook)) $resql = $db->query($sql); $num = $db->num_rows($resql); - if (empty($num) && !empty($newsup)) - { + if (empty($num) && !empty($newsup)) { try { $stripesup = \Stripe\Account::retrieve($db->escape(GETPOST('key_account_supplier', 'alpha'))); $tokenstring['stripe_user_id'] = $stripesup->id; @@ -639,8 +600,7 @@ if (empty($reshook)) $resql = $db->query($sql); } - if (!$error) - { + if (!$error) { $stripesupplieracc = $newsup; $db->commit(); } else { @@ -648,25 +608,21 @@ if (empty($reshook)) } } - if ($action == 'setlocalassourcedefault') // Set as default when payment mode defined locally (and may be also remotely) - { + if ($action == 'setlocalassourcedefault') { // Set as default when payment mode defined locally (and may be also remotely) try { $companypaymentmode->setAsDefault($id); $url = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; header('Location: '.$url); exit; - } catch (Exception $e) - { + } catch (Exception $e) { $error++; setEventMessages($e->getMessage(), null, 'errors'); } - } elseif ($action == 'setassourcedefault') // Set as default when payment mode defined remotely only - { + } elseif ($action == 'setassourcedefault') { // Set as default when payment mode defined remotely only try { $cu = $stripe->customerStripe($object, $stripeacc, $servicestatus); - if (preg_match('/pm_/', $source)) - { + if (preg_match('/pm_/', $source)) { $cu->invoice_settings->default_payment_method = (string) $source; // New } else { $cu->default_source = (string) $source; // Old @@ -676,19 +632,15 @@ if (empty($reshook)) $url = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; header('Location: '.$url); exit; - } catch (Exception $e) - { + } catch (Exception $e) { $error++; setEventMessages($e->getMessage(), null, 'errors'); } - } elseif ($action == 'deletecard' && $source) - { + } elseif ($action == 'deletecard' && $source) { try { - if (preg_match('/pm_/', $source)) - { + if (preg_match('/pm_/', $source)) { $payment_method = \Stripe\PaymentMethod::retrieve($source, array("stripe_account" => $stripeacc)); - if ($payment_method) - { + if ($payment_method) { $payment_method->detach(); } } else { @@ -707,8 +659,7 @@ if (empty($reshook)) $url = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; header('Location: '.$url); exit; - } catch (Exception $e) - { + } catch (Exception $e) { $error++; setEventMessages($e->getMessage(), null, 'errors'); } @@ -735,54 +686,53 @@ $head = societe_prepare_head($object); { dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Paypal'),'','warning'); }*/ -if (!empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha'))) -{ +if (!empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha'))) { dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning'); } // Load Bank account -if (!$id) -{ +if (!$id) { $companybankaccount->fetch(0, $object->id); $companypaymentmode->fetch(0, null, $object->id, 'card'); } else { $companybankaccount->fetch($id); $companypaymentmode->fetch($id); } -if (empty($companybankaccount->socid)) $companybankaccount->socid = $object->id; +if (empty($companybankaccount->socid)) { + $companybankaccount->socid = $object->id; +} -if ($socid && ($action == 'edit' || $action == 'editcard') && $user->rights->societe->creer) -{ +if ($socid && ($action == 'edit' || $action == 'editcard') && $user->rights->societe->creer) { print '<form action="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; $actionforadd = 'update'; - if ($action == 'editcard') $actionforadd = 'updatecard'; + if ($action == 'editcard') { + $actionforadd = 'updatecard'; + } print '<input type="hidden" name="action" value="'.$actionforadd.'">'; print '<input type="hidden" name="id" value="'.GETPOST("id", "int").'">'; } -if ($socid && ($action == 'create' || $action == 'createcard') && $user->rights->societe->creer) -{ +if ($socid && ($action == 'create' || $action == 'createcard') && $user->rights->societe->creer) { print '<form action="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; $actionforadd = 'add'; - if ($action == 'createcard') $actionforadd = 'addcard'; + if ($action == 'createcard') { + $actionforadd = 'addcard'; + } print '<input type="hidden" name="action" value="'.$actionforadd.'">'; } // View -if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' && $action != 'createcard') -{ +if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' && $action != 'createcard') { print dol_get_fiche_head($head, 'rib', $langs->trans("ThirdParty"), -1, 'company'); // Confirm delete ban - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid ? $ribid : $id), $langs->trans("DeleteARib"), $langs->trans("ConfirmDeleteRib", $companybankaccount->getRibLabel()), "confirm_delete", '', 0, 1); } // Confirm delete card - if ($action == 'deletecard') - { + if ($action == 'deletecard') { print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid ? $ribid : $id), $langs->trans("DeleteACard"), $langs->trans("ConfirmDeleteCard", $companybankaccount->getRibLabel()), "confirm_deletecard", '', 0, 1); } @@ -791,8 +741,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom'); - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td class="titlefield">'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>'; } @@ -803,11 +752,10 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print '<div class="underbanner clearboth"></div>'; print '<table class="border tableforfield centpercent">'; - if ($object->client) - { + if ($object->client) { print '<tr><td class="titlefield">'; print $langs->trans('CustomerCode').'</td><td colspan="2">'; - print $object->code_client; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_client)); $tmpcheck = $object->check_codeclient(); if ($tmpcheck != 0 && $tmpcheck != -5) { print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; @@ -815,38 +763,46 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print '</td></tr>'; $sql = "SELECT count(*) as nb from ".MAIN_DB_PREFIX."facture where fk_soc = ".$socid; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $obj = $db->fetch_object($resql); $nbFactsClient = $obj->nb; $thirdTypeArray['customer'] = $langs->trans("customer"); - if ($conf->propal->enabled && $user->rights->propal->lire) $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals'); - if ($conf->commande->enabled && $user->rights->commande->lire) $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders'); - if ($conf->facture->enabled && $user->rights->facture->lire) $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices'); - if ($conf->contrat->enabled && $user->rights->contrat->lire) $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts'); + if ($conf->propal->enabled && $user->rights->propal->lire) { + $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals'); + } + if ($conf->commande->enabled && $user->rights->commande->lire) { + $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders'); + } + if ($conf->facture->enabled && $user->rights->facture->lire) { + $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices'); + } + if ($conf->contrat->enabled && $user->rights->contrat->lire) { + $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts'); + } - if (!empty($conf->stripe->enabled)) - { + if (!empty($conf->stripe->enabled)) { $permissiontowrite = $user->rights->societe->creer; // Stripe customer key 'cu_....' stored into llx_societe_account print '<tr><td class="titlefield">'; print $form->editfieldkey("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', 0, 2, 'socid'); print '</td><td>'; print $form->editfieldval("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', null, null, '', 2, '', 'socid'); - if (!empty($conf->stripe->enabled) && $stripecu && $action != 'editkey_account') - { + if (!empty($conf->stripe->enabled) && $stripecu && $action != 'editkey_account') { $connect = ''; - if (!empty($stripeacc)) $connect = $stripeacc.'/'; + if (!empty($stripeacc)) { + $connect = $stripeacc.'/'; + } $url = 'https://dashboard.stripe.com/'.$connect.'test/customers/'.$stripecu; - if ($servicestatus) - { + if ($servicestatus) { $url = 'https://dashboard.stripe.com/'.$connect.'customers/'.$stripecu; } print ' <a href="'.$url.'" target="_stripe">'.img_picto($langs->trans('ShowInStripe').' - Publishable key = '.$site_account, 'globe').'</a>'; } print '</td><td class="right">'; - if (empty($stripecu)) - { + if (empty($stripecu)) { print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">'; print '<input type="hidden" name="action" value="synccustomertostripe">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -858,11 +814,10 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' } } - if ($object->fournisseur) - { + if ($object->fournisseur) { print '<tr><td class="titlefield">'; print $langs->trans('SupplierCode').'</td><td colspan="2">'; - print $object->code_fournisseur; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_fournisseur)); $tmpcheck = $object->check_codefournisseur(); if ($tmpcheck != 0 && $tmpcheck != -5) { print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; @@ -870,18 +825,27 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print '</td></tr>'; $sql = "SELECT count(*) as nb from ".MAIN_DB_PREFIX."facture where fk_soc = ".$socid; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $obj = $db->fetch_object($resql); $nbFactsClient = $obj->nb; $thirdTypeArray['customer'] = $langs->trans("customer"); - if ($conf->propal->enabled && $user->rights->propal->lire) $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals'); - if ($conf->commande->enabled && $user->rights->commande->lire) $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders'); - if ($conf->facture->enabled && $user->rights->facture->lire) $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices'); - if ($conf->contrat->enabled && $user->rights->contrat->lire) $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts'); + if ($conf->propal->enabled && $user->rights->propal->lire) { + $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals'); + } + if ($conf->commande->enabled && $user->rights->commande->lire) { + $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders'); + } + if ($conf->facture->enabled && $user->rights->facture->lire) { + $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices'); + } + if ($conf->contrat->enabled && $user->rights->contrat->lire) { + $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts'); + } } - if (!empty($conf->stripe->enabled) && !empty($conf->stripeconnect->enabled) && $conf->global->MAIN_FEATURES_LEVEL >= 2) - { + if (!empty($conf->stripe->enabled) && !empty($conf->stripeconnect->enabled) && $conf->global->MAIN_FEATURES_LEVEL >= 2) { $permissiontowrite = $user->rights->societe->creer; $stripesupplieracc = $stripe->getStripeAccount($service, $object->id); // Get Stripe OAuth connect account (no network access here) @@ -890,20 +854,17 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print $form->editfieldkey("StripeConnectAccount", 'key_account_supplier', $stripesupplieracc, $object, $permissiontowrite, 'string', '', 0, 2, 'socid'); print '</td><td>'; print $form->editfieldval("StripeConnectAccount", 'key_account_supplier', $stripesupplieracc, $object, $permissiontowrite, 'string', '', null, null, '', 2, '', 'socid'); - if (!empty($conf->stripe->enabled) && $stripesupplieracc && $action != 'editkey_account_supplier') - { + if (!empty($conf->stripe->enabled) && $stripesupplieracc && $action != 'editkey_account_supplier') { $connect = ''; $url = 'https://dashboard.stripe.com/test/connect/accounts/'.$stripesupplieracc; - if ($servicestatus) - { + if ($servicestatus) { $url = 'https://dashboard.stripe.com/connect/accounts/'.$stripesupplieracc; } print ' <a href="'.$url.'" target="_stripe">'.img_picto($langs->trans('ShowInStripe').' - Publishable key '.$site_account, 'globe').'</a>'; } print '</td><td class="right">'; - if (empty($stripesupplieracc)) - { + if (empty($stripesupplieracc)) { print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">'; print '<input type="hidden" name="action" value="syncsuppliertostripe">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -923,30 +884,25 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print '<br>'; // List of Stripe payment modes - if (!(empty($conf->stripe->enabled)) && $object->client) - { + if (!(empty($conf->stripe->enabled)) && $object->client) { $morehtmlright = ''; - if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) - { + if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) { $morehtmlright .= dolGetButtonTitle($langs->trans('Add'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=createcard'); } print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc ? ' (Stripe connection with StripeConnect account '.$stripeacc.')' : ' (Stripe connection with keys from Stripe module setup)'), $morehtmlright, 'stripe-s'); $listofsources = array(); - if (is_object($stripe)) - { + if (is_object($stripe)) { try { $customerstripe = $stripe->customerStripe($object, $stripeacc, $servicestatus); if (!empty($customerstripe->id)) { // When using the Charge API architecture - if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { + if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { $listofsources = $customerstripe->sources->data; } else { $service = 'StripeTest'; $servicestatus = 0; - if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) - { + if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) { $service = 'StripeLive'; $servicestatus = 1; } @@ -964,18 +920,20 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' $paymentmethodobjsB = \Stripe\PaymentMethod::all(array("customer" => $customerstripe->id, "type" => "sepa_debit"), array("stripe_account" => $stripeacc)); } - if ($paymentmethodobjsA->data != null && $paymentmethodobjsB->data != null) { $listofsources = array_merge((array) $paymentmethodobjsA->data, (array) $paymentmethodobjsB->data); - } elseif ($paymentmethodobjsB->data != null) { $listofsources = $paymentmethodobjsB->data; } - else { $listofsources = $paymentmethodobjsA->data; } - } catch (Exception $e) - { + if ($paymentmethodobjsA->data != null && $paymentmethodobjsB->data != null) { + $listofsources = array_merge((array) $paymentmethodobjsA->data, (array) $paymentmethodobjsB->data); + } elseif ($paymentmethodobjsB->data != null) { + $listofsources = $paymentmethodobjsB->data; + } else { + $listofsources = $paymentmethodobjsA->data; + } + } catch (Exception $e) { $error++; setEventMessages($e->getMessage(), null, 'errors'); } } } - } catch (Exception $e) - { + } catch (Exception $e) { dol_syslog("Error when searching/loading Stripe customer for thirdparty id =".$object->id); } } @@ -984,8 +942,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '<table class="liste centpercent">'."\n"; print '<tr class="liste_titre">'; - if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) - { + if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) { print '<td>'.$langs->trans('LocalID').'</td>'; } print '<td>'.$langs->trans('Label').'</td>'; @@ -1009,8 +966,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' $arrayofstripecard = array(); // Show local sources - if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) - { + if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) { //$societeaccount = new SocieteAccount($db); $companypaymentmodetemp = new CompanyPaymentMode($db); @@ -1020,19 +976,15 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' $sql .= " AND status = ".$servicestatus; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num_rows = $db->num_rows($resql); - if ($num_rows) - { + if ($num_rows) { $i = 0; - while ($i < $num_rows) - { + while ($i < $num_rows) { $nblocal++; $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $companypaymentmodetemp->fetch($obj->rowid); $arrayofstripecard[$companypaymentmodetemp->stripe_card_ref] = $companypaymentmodetemp->stripe_card_ref; @@ -1046,13 +998,13 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print '</td>'; print '<td>'; print $companypaymentmodetemp->stripe_card_ref; - if ($companypaymentmodetemp->stripe_card_ref) - { + if ($companypaymentmodetemp->stripe_card_ref) { $connect = ''; - if (!empty($stripeacc)) $connect = $stripeacc.'/'; + if (!empty($stripeacc)) { + $connect = $stripeacc.'/'; + } $url = 'https://dashboard.stripe.com/'.$connect.'test/search?query='.$companypaymentmodetemp->stripe_card_ref; - if ($servicestatus) - { + if ($servicestatus) { $url = 'https://dashboard.stripe.com/'.$connect.'search?query='.$companypaymentmodetemp->stripe_card_ref; } print ' <a href="'.$url.'" target="_stripe">'.img_picto($langs->trans('ShowInStripe').' - Customer and Publishable key = '.$companypaymentmodetemp->stripe_account, 'globe').'</a>'; @@ -1062,21 +1014,27 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print img_credit_card($companypaymentmodetemp->type); print '</td>'; print '<td>'; - if ($companypaymentmodetemp->proprio) print '<span class="opacitymedium">'.$companypaymentmodetemp->proprio.'</span><br>'; - if ($companypaymentmodetemp->last_four) print '....'.$companypaymentmodetemp->last_four; - if ($companypaymentmodetemp->exp_date_month || $companypaymentmodetemp->exp_date_year) print ' - '.sprintf("%02d", $companypaymentmodetemp->exp_date_month).'/'.$companypaymentmodetemp->exp_date_year.''; + if ($companypaymentmodetemp->proprio) { + print '<span class="opacitymedium">'.$companypaymentmodetemp->proprio.'</span><br>'; + } + if ($companypaymentmodetemp->last_four) { + print '....'.$companypaymentmodetemp->last_four; + } + if ($companypaymentmodetemp->exp_date_month || $companypaymentmodetemp->exp_date_year) { + print ' - '.sprintf("%02d", $companypaymentmodetemp->exp_date_month).'/'.$companypaymentmodetemp->exp_date_year.''; + } print '</td><td>'; - if ($companypaymentmodetemp->country_code) - { + if ($companypaymentmodetemp->country_code) { $img = picto_from_langcode($companypaymentmodetemp->country_code); print $img ? $img.' ' : ''; print getCountry($companypaymentmodetemp->country_code, 1); - } else print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>'; + } else { + print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>'; + } print '</td>'; // Default print '<td class="center">'; - if (empty($companypaymentmodetemp->default_rib)) - { + if (empty($companypaymentmodetemp->default_rib)) { print '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id.'&id='.$companypaymentmodetemp->id.'&action=setlocalassourcedefault&token='.newToken().'">'; print img_picto($langs->trans("Default"), 'off'); print '</a>'; @@ -1085,8 +1043,11 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' } print '</td>'; print '<td>'; - if (empty($companypaymentmodetemp->stripe_card_ref)) print $langs->trans("Local"); - else print $langs->trans("LocalAndRemote"); + if (empty($companypaymentmodetemp->stripe_card_ref)) { + print $langs->trans("Local"); + } else { + print $langs->trans("LocalAndRemote"); + } print '</td>'; print '<td>'; print dol_print_date($companypaymentmodetemp->tms, 'dayhour'); @@ -1097,10 +1058,8 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print $hookmanager->resPrint; // Action column print '<td class="right nowraponall">'; - if ($user->rights->societe->creer) - { - if ($stripecu && empty($companypaymentmodetemp->stripe_card_ref)) - { + if ($user->rights->societe->creer) { + if ($stripecu && empty($companypaymentmodetemp->stripe_card_ref)) { print '<a href="'.$_SERVER['PHP_SELF'].'?action=synccardtostripe&socid='.$object->id.'&id='.$companypaymentmodetemp->id.'" class="paddingrightonly marginrightonly">'.$langs->trans("CreateCardOnStripe").'</a>'; } @@ -1126,7 +1085,9 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' // Show remote sources (not already shown as local source) if (is_array($listofsources) && count($listofsources)) { foreach ($listofsources as $src) { - if (!empty($arrayofstripecard[$src->id])) continue; // Already in previous list + if (!empty($arrayofstripecard[$src->id])) { + continue; // Already in previous list + } $nbremote++; @@ -1142,7 +1103,9 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print '<td>'; $connect = ''; print $src->id; - if (!empty($stripeacc)) $connect = $stripeacc.'/'; + if (!empty($stripeacc)) { + $connect = $stripeacc.'/'; + } //$url='https://dashboard.stripe.com/'.$connect.'test/sources/'.$src->id; $url = 'https://dashboard.stripe.com/'.$connect.'test/search?query='.$src->id; if ($servicestatus) { @@ -1174,16 +1137,20 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' $img = picto_from_langcode($src->country); print $img ? $img.' ' : ''; print getCountry($src->country, 1); - } else print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>'; + } else { + print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>'; + } } elseif ($src->object == 'source' && $src->type == 'card') { print '<span class="opacitymedium">'.$src->owner->name.'</span><br>....'.$src->card->last4.' - '.$src->card->exp_month.'/'.$src->card->exp_year.''; print '</td><td>'; - if ($src->card->country) { + if ($src->card->country) { $img = picto_from_langcode($src->card->country); print $img ? $img.' ' : ''; print getCountry($src->card->country, 1); - } else print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>'; + } else { + print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>'; + } } elseif ($src->object == 'source' && $src->type == 'sepa_debit') { print '<span class="opacitymedium">'.$src->billing_details->name.'</span><br>....'.$src->sepa_debit->last4; print '</td><td>'; @@ -1191,7 +1158,9 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' $img = picto_from_langcode($src->sepa_debit->country); print $img ? $img.' ' : ''; print getCountry($src->sepa_debit->country, 1); - } else print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>'; + } else { + print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>'; + } } elseif ($src->object == 'payment_method' && $src->type == 'card') { print '<span class="opacitymedium">'.$src->billing_details->name.'</span><br>....'.$src->card->last4.' - '.$src->card->exp_month.'/'.$src->card->exp_year.''; print '</td><td>'; @@ -1200,7 +1169,9 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' $img = picto_from_langcode($src->card->country); print $img ? $img.' ' : ''; print getCountry($src->card->country, 1); - } else print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>'; + } else { + print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>'; + } } elseif ($src->object == 'payment_method' && $src->type == 'sepa_debit') { print '<span class="opacitymedium">'.$src->billing_details->name.'</span><br>....'.$src->sepa_debit->last4; print '</td><td>'; @@ -1208,7 +1179,9 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' $img = picto_from_langcode($src->sepa_debit->country); print $img ? $img.' ' : ''; print getCountry($src->sepa_debit->country, 1); - } else print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>'; + } else { + print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>'; + } } else { print '</td><td>'; } @@ -1258,9 +1231,8 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print '<br>'; } - // List of Stripe payment modes - if (!empty($conf->stripe->enabled) && !empty($conf->stripeconnect->enabled) && !empty($stripesupplieracc)) - { + // List of Stripe payment modes + if (!empty($conf->stripe->enabled) && !empty($conf->stripeconnect->enabled) && !empty($stripesupplieracc)) { print load_fiche_titre($langs->trans('StripeBalance').($stripesupplieracc ? ' (Stripe connection with StripeConnect account '.$stripesupplieracc.')' : ' (Stripe connection with keys from Stripe module setup)'), $morehtmlright, 'stripe-s'); $balance = \Stripe\Balance::retrieve(array("stripe_account" => $stripesupplieracc)); print '<table class="liste centpercent">'."\n"; @@ -1272,10 +1244,8 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print '</tr>'; $currencybalance = array(); - if (is_array($balance->available) && count($balance->available)) - { - foreach ($balance->available as $cpt) - { + if (is_array($balance->available) && count($balance->available)) { + foreach ($balance->available as $cpt) { $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); if (!in_array($cpt->currency, $arrayzerounitcurrency)) { $currencybalance[$cpt->currency]['available'] = $cpt->amount / 100; @@ -1286,10 +1256,8 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' } } - if (is_array($balance->pending) && count($balance->pending)) - { - foreach ($balance->pending as $cpt) - { + if (is_array($balance->pending) && count($balance->pending)) { + foreach ($balance->pending as $cpt) { $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); if (!in_array($cpt->currency, $arrayzerounitcurrency)) { $currencybalance[$cpt->currency]['pending'] = $currencybalance[$cpt->currency]['available'] + $cpt->amount / 100; @@ -1299,10 +1267,8 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' } } - if (is_array($currencybalance)) - { - foreach ($currencybalance as $cpt) - { + if (is_array($currencybalance)) { + foreach ($currencybalance as $cpt) { print '<tr><td>'.$langs->trans("Currency".strtoupper($cpt['currency'])).'</td><td>'.price($cpt['available'], 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'</td><td>'.price($cpt->pending, 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'</td><td>'.price($cpt['available'] + $cpt->pending, 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'</td></tr>'; } } @@ -1318,8 +1284,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print load_fiche_titre($langs->trans("BankAccounts"), $morehtmlright, 'bank'); $rib_list = $object->get_all_rib(); - if (is_array($rib_list)) - { + if (is_array($rib_list)) { print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '<table class="liste centpercent">'; @@ -1329,8 +1294,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print_liste_field_titre("RIB"); print_liste_field_titre("IBAN"); print_liste_field_titre("BIC"); - if (!empty($conf->prelevement->enabled)) - { + if (!empty($conf->prelevement->enabled)) { print_liste_field_titre("RUM"); print_liste_field_titre("DateRUM"); print_liste_field_titre("WithdrawMode"); @@ -1340,8 +1304,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch '); print "</tr>\n"; - foreach ($rib_list as $rib) - { + foreach ($rib_list as $rib) { print '<tr class="oddeven">'; // Label print '<td>'.$rib->label.'</td>'; @@ -1379,7 +1342,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print '</td>'; // IBAN print '<td>'.$rib->iban; - if (!empty($rib->iban)) { + if (!empty($rib->iban)) { if (!checkIbanForAccount($rib)) { print ' '.img_picto($langs->trans("IbanNotValid"), 'warning'); } @@ -1394,8 +1357,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' } print '</td>'; - if (!empty($conf->prelevement->enabled)) - { + if (!empty($conf->prelevement->enabled)) { // RUM //print '<td>'.$prelevement->buildRumNumber($object->code_client, $rib->datec, $rib->id).'</td>'; print '<td>'.$rib->rum.'</td>'; @@ -1427,46 +1389,52 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' $modellist = ModeleBankAccountDoc::liste_modeles($db); $out = ''; - if (is_array($modellist) && count($modellist)) - { + if (is_array($modellist) && count($modellist)) { $out .= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG) ? '' : '#builddoc').'" name="'.$forname.'" id="'.$forname.'_form" method="post">'; $out .= '<input type="hidden" name="action" value="builddocrib">'; $out .= '<input type="hidden" name="token" value="'.newToken().'">'; $out .= '<input type="hidden" name="socid" value="'.$object->id.'">'; $out .= '<input type="hidden" name="companybankid" value="'.$rib->id.'">'; - if (is_array($modellist) && count($modellist) == 1) // If there is only one element - { + if (is_array($modellist) && count($modellist) == 1) { // If there is only one element $arraykeys = array_keys($modellist); $modelselected = $arraykeys[0]; } - if (!empty($conf->global->BANKADDON_PDF)) $modelselected = $conf->global->BANKADDON_PDF; + if (!empty($conf->global->BANKADDON_PDF)) { + $modelselected = $conf->global->BANKADDON_PDF; + } $out .= $form->selectarray('modelrib'.$rib->id, $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100'); $out .= ajax_combobox('modelrib'.$rib->id); // Language code (if multilang) - if ($conf->global->MAIN_MULTILANGS) - { + if ($conf->global->MAIN_MULTILANGS) { include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; $formadmin = new FormAdmin($db); $defaultlang = $codelang ? $codelang : $langs->getDefaultLang(); $morecss = 'maxwidth150'; - if ($conf->browser->layout == 'phone') $morecss = 'maxwidth100'; + if ($conf->browser->layout == 'phone') { + $morecss = 'maxwidth100'; + } $out .= $formadmin->select_language($defaultlang, 'lang_idrib'.$rib->id, 0, 0, 0, 0, 0, $morecss); } // Button $genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"'; $genbutton .= ' type="submit" value="'.$buttonlabel.'"'; - if (!$allowgenifempty && !is_array($modellist) && empty($modellist)) $genbutton .= ' disabled'; + if (!$allowgenifempty && !is_array($modellist) && empty($modellist)) { + $genbutton .= ' disabled'; + } $genbutton .= '>'; - if ($allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') - { + if ($allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') { $langs->load("errors"); $genbutton .= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated")); } - if (!$allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton = ''; - if (empty($modellist) && !$showempty && $modulepart != 'unpaid') $genbutton = ''; + if (!$allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') { + $genbutton = ''; + } + if (empty($modellist) && !$showempty && $modulepart != 'unpaid') { + $genbutton = ''; + } $out .= $genbutton; $out .= '</form>'; } @@ -1475,25 +1443,25 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' // Edit/Delete print '<td class="right nowraponall">'; - if ($user->rights->societe->creer) - { + if ($user->rights->societe->creer) { print '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&id='.$rib->id.'&action=edit">'; print img_picto($langs->trans("Modify"), 'edit'); print '</a>'; - print '<a class="marginleftonly" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&id='.$rib->id.'&action=delete&token='.newToken().'">'; - print img_picto($langs->trans("Delete"), 'delete'); - print '</a>'; + print '<a class="marginleftonly" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&id='.$rib->id.'&action=delete&token='.newToken().'">'; + print img_picto($langs->trans("Delete"), 'delete'); + print '</a>'; } print '</td>'; print '</tr>'; } - if (count($rib_list) == 0) - { + if (count($rib_list) == 0) { $colspan = 9; - if (!empty($conf->prelevement->enabled)) $colspan += 2; + if (!empty($conf->prelevement->enabled)) { + $colspan += 2; + } print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoBANRecord").'</td></tr>'; } @@ -1504,16 +1472,15 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' } - if (empty($conf->global->SOCIETE_DISABLE_BUILDDOC)) - { + if (empty($conf->global->SOCIETE_DISABLE_BUILDDOC)) { print '<br>'; print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre /* - * Documents generes - */ + * Generated documents + */ $filedir = $conf->societe->multidir_output[$object->entity].'/'.$object->id; $urlsource = $_SERVER["PHP_SELF"]."?socid=".$object->id; $genallowed = $user->rights->societe->lire; @@ -1522,8 +1489,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 0, 0, 0, 28, 0, 'entity='.$object->entity, 0, '', $object->default_lang); // Show direct download link - if (!empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) - { + if (!empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) { $companybankaccounttemp = new CompanyBankAccount($db); $companypaymentmodetemp = new CompanyPaymentMode($db); $result = $companypaymentmodetemp->fetch(0, null, $object->id, 'ban'); @@ -1531,8 +1497,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile = new EcmFiles($db); $result = $ecmfile->fetch(0, '', '', '', '', $companybankaccounttemp->table_element, $companypaymentmodetemp->id); - if ($result > 0) - { + if ($result > 0) { $companybankaccounttemp->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename; print '<br><!-- Link to download main doc -->'."\n"; print showDirectDownloadLink($companybankaccounttemp).'<br>'; @@ -1547,29 +1512,28 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print '<br>'; } /* - include_once DOL_DOCUMENT_ROOT.'/core/modules/bank/modules_bank.php'; - $modellist=ModeleBankAccountDoc::liste_modeles($db); - //print '<td>'; - if (is_array($modellist) && count($modellist) == 1) // If there is only one element - { - $arraykeys=array_keys($modellist); - $modelselected=$arraykeys[0]; - } - $out.= $form->selectarray('model', $modellist, $modelselected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100'); - $out.= ajax_combobox('model'); - //print $out; - $buttonlabel=$langs->trans("Generate"); - $genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"'; - $genbutton.= ' type="submit" value="'.$buttonlabel.'"'; - $genbutton.= '>'; - print $genbutton; - //print '</td>'; // TODO Add link to generate doc - */ + include_once DOL_DOCUMENT_ROOT.'/core/modules/bank/modules_bank.php'; + $modellist=ModeleBankAccountDoc::liste_modeles($db); + //print '<td>'; + if (is_array($modellist) && count($modellist) == 1) // If there is only one element + { + $arraykeys=array_keys($modellist); + $modelselected=$arraykeys[0]; + } + $out.= $form->selectarray('model', $modellist, $modelselected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100'); + $out.= ajax_combobox('model'); + //print $out; + $buttonlabel=$langs->trans("Generate"); + $genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"'; + $genbutton.= ' type="submit" value="'.$buttonlabel.'"'; + $genbutton.= '>'; + print $genbutton; + //print '</td>'; // TODO Add link to generate doc + */ } // Edit BAN -if ($socid && $action == 'edit' && $user->rights->societe->creer) -{ +if ($socid && $action == 'edit' && $user->rights->societe->creer) { print dol_get_fiche_head($head, 'rib', $langs->trans("ThirdParty"), 0, 'company'); $linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; @@ -1611,13 +1575,17 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) $name = 'iban'; $size = 30; $content = $companybankaccount->iban; - if ($companybankaccount->needIBAN()) $require = true; + if ($companybankaccount->needIBAN()) { + $require = true; + } $tooltip = $langs->trans("Example").':<br>LT12 1000 0111 0100 1000<br>FR14 2004 1010 0505 0001 3M02 606<br>LU28 0019 4006 4475 0000<br>DE89 3704 0044 0532 0130 00'; } elseif ($val == 'BIC') { $name = 'bic'; $size = 12; $content = $companybankaccount->bic; - if ($companybankaccount->needIBAN()) $require = true; + if ($companybankaccount->needIBAN()) { + $require = true; + } $tooltip = $langs->trans("Example").': LIABLT2XXXX'; } @@ -1649,14 +1617,15 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) print '</table>'; print '</div>'; - if ($conf->prelevement->enabled) - { + if ($conf->prelevement->enabled) { print '<br>'; print '<div class="div-table-responsive-no-min">'; print '<table class="border centpercent">'; - if (empty($companybankaccount->rum)) $companybankaccount->rum = $prelevement->buildRumNumber($object->code_client, $companybankaccount->datec, $companybankaccount->id); + if (empty($companybankaccount->rum)) { + $companybankaccount->rum = $prelevement->buildRumNumber($object->code_client, $companybankaccount->datec, $companybankaccount->id); + } // RUM print '<tr><td class="titlefield">'.$langs->trans("RUM").'</td>'; @@ -1685,8 +1654,7 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) } // Edit Card -if ($socid && $action == 'editcard' && $user->rights->societe->creer) -{ +if ($socid && $action == 'editcard' && $user->rights->societe->creer) { print dol_get_fiche_head($head, 'rib', $langs->trans("ThirdParty"), 0, 'company'); $linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; @@ -1733,8 +1701,7 @@ if ($socid && $action == 'editcard' && $user->rights->societe->creer) // Create BAN -if ($socid && $action == 'create' && $user->rights->societe->creer) -{ +if ($socid && $action == 'create' && $user->rights->societe->creer) { print dol_get_fiche_head($head, 'rib', $langs->trans("ThirdParty"), 0, 'company'); $linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; @@ -1776,13 +1743,17 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) $name = 'iban'; $size = 30; $content = $companybankaccount->iban; - if ($companybankaccount->needIBAN()) $require = true; + if ($companybankaccount->needIBAN()) { + $require = true; + } $tooltip = $langs->trans("Example").':<br>LT12 1000 0111 0100 1000<br>FR14 2004 1010 0505 0001 3M02 606<br>LU28 0019 4006 4475 0000<br>DE89 3704 0044 0532 0130 00'; } elseif ($val == 'BIC') { $name = 'bic'; $size = 12; $content = $companybankaccount->bic; - if ($companybankaccount->needIBAN()) $require = true; + if ($companybankaccount->needIBAN()) { + $require = true; + } $tooltip = $langs->trans("Example").': LIABLT2XXXX'; } @@ -1813,8 +1784,7 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) print '</table>'; - if ($conf->prelevement->enabled) - { + if ($conf->prelevement->enabled) { print '<br>'; print '<table class="border centpercent">'; @@ -1848,8 +1818,7 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) } // Create Card -if ($socid && $action == 'createcard' && $user->rights->societe->creer) -{ +if ($socid && $action == 'createcard' && $user->rights->societe->creer) { print dol_get_fiche_head($head, 'rib', $langs->trans("ThirdParty"), 0, 'company'); $linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; @@ -1897,12 +1866,10 @@ if ($socid && $action == 'createcard' && $user->rights->societe->creer) print '</div>'; } -if ($socid && ($action == 'edit' || $action == 'editcard') && $user->rights->societe->creer) -{ +if ($socid && ($action == 'edit' || $action == 'editcard') && $user->rights->societe->creer) { print '</form>'; } -if ($socid && ($action == 'create' || $action == 'createcard') && $user->rights->societe->creer) -{ +if ($socid && ($action == 'create' || $action == 'createcard') && $user->rights->societe->creer) { print '</form>'; } diff --git a/htdocs/societe/price.php b/htdocs/societe/price.php index dfcfde06c6c..cc056896414 100644 --- a/htdocs/societe/price.php +++ b/htdocs/societe/price.php @@ -49,8 +49,9 @@ $search_price_ttc = GETPOST('search_price_ttc'); // Security check $socid = GETPOST('socid', 'int') ?GETPOST('socid', 'int') : GETPOST('id', 'int'); -if ($user->socid) +if ($user->socid) { $socid = $user->socid; +} $result = restrictedArea($user, 'societe', $socid, '&societe'); $object = new Societe($db); @@ -67,12 +68,12 @@ $error = 0; $parameters = array('id'=>$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)) -{ - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers - { +if (empty($reshook)) { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $search_prod = $search_label = $search_price = $search_price_ttc = ''; } @@ -102,8 +103,7 @@ if (empty($reshook)) $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; // If value contains the unique code of vat line (new recommended method), we use it to find npr and local taxes - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in update price. $vatratecode = $reg[1]; // Get record from code @@ -113,8 +113,7 @@ if (empty($reshook)) $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $npr = $obj->recuperableonly; $localtax1 = $obj->localtax1; @@ -146,7 +145,7 @@ if (empty($reshook)) if ($action == 'delete_customer_price' && ($user->rights->produit->creer || $user->rights->service->creer)) { // Delete price by customer - $prodcustprice->id = GETPOST('lineid'); + $prodcustprice->id = GETPOST('lineid', 'int'); $result = $prodcustprice->delete($user); if ($result < 0) { @@ -193,8 +192,9 @@ $object = new Societe($db); $result = $object->fetch($socid); llxHeader("", $langs->trans("ThirdParty").'-'.$langs->trans('PriceByCustomer')); -if (!empty($conf->notification->enabled)) +if (!empty($conf->notification->enabled)) { $langs->load("mails"); +} $head = societe_prepare_head($object); print dol_get_fiche_head($head, 'price', $langs->trans("ThirdParty"), -1, 'company'); @@ -208,8 +208,7 @@ print '<div class="fichecenter">'; print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent">'; -if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field -{ +if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td class="titlefield">'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>'; } @@ -250,14 +249,18 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { $sortorder = GETPOST("sortorder", 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $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) + if (!$sortorder) { $sortorder = "ASC"; - if (!$sortfield) + } + if (!$sortfield) { $sortfield = "soc.nom"; + } // Build filter to display only concerned lines $filter = array( @@ -365,101 +368,101 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { print load_fiche_titre($langs->trans('PriceByCustomer')); $result = $prodcustprice->fetch(GETPOST('lineid', 'int')); - if ($result < 0) - { + + if ($result <= 0) { setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors'); - } - - print '<form action="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'" method="POST">'; - print '<input type="hidden" name="token" value="'.newToken().'">'; - print '<input type="hidden" name="action" value="update_customer_price_confirm">'; - print '<input type="hidden" name="lineid" value="'.$prodcustprice->id.'">'; - print '<table class="border centpercent">'; - print '<tr>'; - print '<td>'.$langs->trans('Product').'</td>'; - $staticprod = new Product($db); - $staticprod->fetch($prodcustprice->fk_product); - print "<td>".$staticprod->getNomUrl(1)."</td>"; - print '</tr>'; - - // Ref. Customer - print '<tr><td>'.$langs->trans('RefCustomer').'</td>'; - print '<td><input name="ref_customer" size="12" value="' . dol_escape_htmltag($prodcustprice->ref_customer) . '"></td></tr>'; - - // VAT - print '<tr><td>'.$langs->trans("VATRate").'</td><td>'; - print $form->load_tva("tva_tx", $prodcustprice->tva_tx, $mysoc, '', $staticprod->id, $prodcustprice->recuperableonly); - print '</td></tr>'; - - // Price base - print '<tr><td width="15%">'; - print $langs->trans('PriceBase'); - print '</td>'; - print '<td>'; - print $form->selectPriceBaseType($prodcustprice->price_base_type, "price_base_type"); - print '</td>'; - print '</tr>'; - - // Price - print '<tr><td width="20%">'; - $text = $langs->trans('SellingPrice'); - print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); - print '</td><td>'; - if ($prodcustprice->price_base_type == 'TTC') { - print '<input name="price" size="10" value="'.price($prodcustprice->price_ttc).'">'; } else { - print '<input name="price" size="10" value="'.price($prodcustprice->price).'">'; + print '<form action="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'" method="POST">'; + print '<input type="hidden" name="token" value="'.newToken().'">'; + print '<input type="hidden" name="action" value="update_customer_price_confirm">'; + print '<input type="hidden" name="lineid" value="'.$prodcustprice->id.'">'; + print '<table class="border centpercent">'; + print '<tr>'; + print '<td>'.$langs->trans('Product').'</td>'; + $staticprod = new Product($db); + $staticprod->fetch($prodcustprice->fk_product); + print "<td>".$staticprod->getNomUrl(1)."</td>"; + print '</tr>'; + + // Ref. Customer + print '<tr><td>'.$langs->trans('RefCustomer').'</td>'; + print '<td><input name="ref_customer" size="12" value="' . dol_escape_htmltag($prodcustprice->ref_customer) . '"></td></tr>'; + + // VAT + print '<tr><td>'.$langs->trans("VATRate").'</td><td>'; + print $form->load_tva("tva_tx", $prodcustprice->tva_tx, $mysoc, '', $staticprod->id, $prodcustprice->recuperableonly); + print '</td></tr>'; + + // Price base + print '<tr><td width="15%">'; + print $langs->trans('PriceBase'); + print '</td>'; + print '<td>'; + print $form->selectPriceBaseType($prodcustprice->price_base_type, "price_base_type"); + print '</td>'; + print '</tr>'; + + // Price + print '<tr><td>'; + $text = $langs->trans('SellingPrice'); + print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); + print '</td><td>'; + if ($prodcustprice->price_base_type == 'TTC') { + print '<input name="price" size="10" value="'.price($prodcustprice->price_ttc).'">'; + } else { + print '<input name="price" size="10" value="'.price($prodcustprice->price).'">'; + } + print '</td></tr>'; + + // Price minimum + print '<tr><td>'; + $text = $langs->trans('MinPrice'); + print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); + print '</td><td>'; + if ($prodcustprice->price_base_type == 'TTC') { + print '<input name="price_min" size="10" value="'.price($prodcustprice->price_min_ttc).'">'; + } else { + print '<input name="price_min" size="10" value="'.price($prodcustprice->price_min).'">'; + } + print '</td></tr>'; + + // Update all child soc + print '<tr><td>'; + print $langs->trans('ForceUpdateChildPriceSoc'); + print '</td>'; + print '<td>'; + print '<input type="checkbox" name="updatechildprice" value="1">'; + print '</td>'; + print '</tr>'; + + print '</table>'; + + print '<br><div class="center">'; + print '<input type="submit" class="button button-save" value="'.$langs->trans("Save").'">'; + print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; + print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; + print '</div>'; + + print '<br></form>'; } - print '</td></tr>'; - - // Price minimum - print '<tr><td>'; - $text = $langs->trans('MinPrice'); - print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); - print '</td><td>'; - if ($prodcustprice->price_base_type == 'TTC') { - print '<input name="price_min" size="10" value="'.price($prodcustprice->price_min_ttc).'">'; - } else { - print '<input name="price_min" size="10" value="'.price($prodcustprice->price_min).'">'; - } - print '</td></tr>'; - - // Update all child soc - print '<tr><td width="15%">'; - print $langs->trans('ForceUpdateChildPriceSoc'); - print '</td>'; - print '<td>'; - print '<input type="checkbox" name="updatechildprice" value="1">'; - print '</td>'; - print '</tr>'; - - print '</table>'; - - print '<br><div class="center">'; - print '<input type="submit" class="button button-save" value="'.$langs->trans("Save").'">'; - print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; - print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; - print '</div>'; - - print '<br></form>'; } elseif ($action == 'showlog_customer_price') { print '<br>'; print '<!-- showlog_customer_price -->'."\n"; $filter = array( - 't.fk_product' => GETPOST('prodid', 'int'), 't.fk_soc' => $socid + 't.fk_product' => GETPOST('prodid', 'int'), + 't.fk_soc' => $socid ); // Count total nb of records $nbtotalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $nbtotalofrecords = $prodcustprice->fetch_all_log($sortorder, $sortfield, $conf->liste_limit, $offset, $filter); - } - $result = $prodcustprice->fetch_all_log($sortorder, $sortfield, $conf->liste_limit, $offset, $filter); - if ($result < 0) - { + if ($result < 0) { setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors'); + } else { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { + $nbtotalofrecords = $result; + } } $option = '&socid='.GETPOST('socid', 'int').'&prodid='.GETPOST('prodid', 'int'); @@ -484,14 +487,18 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { print '<td class="right">'.$langs->trans("MinPrice").' '.$langs->trans("HT").'</td>'; print '<td class="right">'.$langs->trans("MinPrice").' '.$langs->trans("TTC").'</td>'; print '<td class="right">'.$langs->trans("ChangedBy").'</td>'; - print '<td>&nbsp;</td>'; + print '<td></td>'; print '</tr>'; foreach ($prodcustprice->lines as $line) { - print '<tr class="oddeven">'; $staticprod = new Product($db); $staticprod->fetch($line->fk_product); + $userstatic = new User($db); + $userstatic->fetch($line->fk_user); + + print '<tr class="oddeven">'; + print "<td>".$staticprod->getNomUrl(1)."</td>"; print '<td>'.$line->ref_customer.'</td>'; print "<td>".dol_print_date($line->datec, "dayhour")."</td>"; @@ -504,11 +511,10 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { print '<td class="right">'.price($line->price_min_ttc).'</td>'; // User - $userstatic = new User($db); - $userstatic->fetch($line->fk_user); print '<td class="right">'; - print $userstatic->getLoginUrl(1); + print $userstatic->getNomUrl(-1); print '</td>'; + print '<td></td>'; } print "</table>"; } else { @@ -521,12 +527,9 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { } else { // View mode - /* ************************************************************************** */ - /* */ - /* Barre d'action */ - /* */ - /* ************************************************************************** */ - + /* + * Action bar + */ print "\n".'<div class="tabsAction">'."\n"; if ($user->rights->produit->creer || $user->rights->service->creer) { @@ -537,14 +540,12 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { // Count total nb of records $nbtotalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $nbtotalofrecords = $prodcustprice->fetch_all('', '', 0, 0, $filter); } $result = $prodcustprice->fetch_all($sortorder, $sortfield, $conf->liste_limit, $offset, $filter); - if ($result < 0) - { + if ($result < 0) { setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors'); } @@ -572,18 +573,22 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { print '<td class="right">'.$langs->trans("MinPrice").' '.$langs->trans("HT").'</td>'; print '<td class="right">'.$langs->trans("MinPrice").' '.$langs->trans("TTC").'</td>'; print '<td class="right">'.$langs->trans("ChangedBy").'</td>'; - print '<td>&nbsp;</td>'; + print '<td></td>'; print '</tr>'; - if (count($prodcustprice->lines) > 0 || $search_prod) - { + if (count($prodcustprice->lines) > 0 || $search_prod) { print '<tr class="liste_titre">'; print '<td class="liste_titre"><input type="text" class="flat" name="search_prod" value="'.$search_prod.'" size="20"></td>'; print '<td class="liste_titre" ><input type="text" class="flat" name="search_label" value="'.$search_label.'" size="20"></td>'; - print '<td class="liste_titre" colspan="4">&nbsp;</td>'; - print '<td class="liste_titre" align="right"><input type="text" class="flat" name="search_price" value="'.$search_price.'" size="10"></td>'; - print '<td class="liste_titre" align="right"><input type="text" class="flat" name="search_price_ttc" value="'.$search_price_ttc.'" size="10"></td>'; - print '<td class="liste_titre" colspan="3">&nbsp;</td>'; + print '<td class="liste_titre"></td>'; + print '<td class="liste_titre"></td>'; + print '<td class="liste_titre"></td>'; + print '<td class="liste_titre"></td>'; + print '<td class="liste_titre" class="right"><input type="text" class="flat" name="search_price" value="'.$search_price.'" size="10"></td>'; + print '<td class="liste_titre" class="right"><input type="text" class="flat" name="search_price_ttc" value="'.$search_price_ttc.'" size="10"></td>'; + print '<td class="liste_titre"></td>'; + print '<td class="liste_titre"></td>'; + print '<td class="liste_titre"></td>'; // Print the search button print '<td class="liste_titre maxwidthsearch">'; $searchpicto = $form->showFilterAndCheckAddButtons(0); @@ -592,37 +597,32 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { print '</tr>'; } - if (count($prodcustprice->lines) > 0) - { - foreach ($prodcustprice->lines as $line) - { - print '<tr class="oddeven">'; - + if (count($prodcustprice->lines) > 0) { + foreach ($prodcustprice->lines as $line) { $staticprod = new Product($db); $staticprod->fetch($line->fk_product); + $userstatic = new User($db); + $userstatic->fetch($line->fk_user); + + print '<tr class="oddeven">'; + print "<td>".$staticprod->getNomUrl(1)."</td>"; print "<td>".$staticprod->label."</td>"; print '<td>'.$line->ref_customer.'</td>'; print "<td>".dol_print_date($line->datec, "dayhour")."</td>"; - print '<td class="center">'.$langs->trans($line->price_base_type)."</td>"; print '<td class="right">'.vatrate($line->tva_tx.($line->default_vat_code ? ' ('.$line->default_vat_code.')' : ''), true, $line->recuperableonly)."</td>"; print '<td class="right">'.price($line->price)."</td>"; print '<td class="right">'.price($line->price_ttc)."</td>"; print '<td class="right">'.price($line->price_min).'</td>'; print '<td class="right">'.price($line->price_min_ttc).'</td>'; - // User - $userstatic = new User($db); - $userstatic->fetch($line->fk_user); print '<td class="right">'; - print $userstatic->getLoginUrl(1); + print $userstatic->getNomUrl(-1); print '</td>'; - // Action - if ($user->rights->produit->creer || $user->rights->service->creer) - { + if ($user->rights->produit->creer || $user->rights->service->creer) { print '<td class="right nowraponall">'; print '<a class="paddingleftonly paddingrightonly" href="'.$_SERVER["PHP_SELF"].'?action=showlog_customer_price&amp;socid='.$object->id.'&amp;prodid='.$line->fk_product.'">'; print img_info(); @@ -642,7 +642,9 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { } } else { $colspan = 10; - if ($user->rights->produit->supprimer || $user->rights->service->supprimer) $colspan += 1; + if ($user->rights->produit->supprimer || $user->rights->service->supprimer) { + $colspan += 1; + } print '<tr class="oddeven"><td colspan="'.$colspan.'">'.$langs->trans('None').'</td></tr>'; } diff --git a/htdocs/societe/project.php b/htdocs/societe/project.php index 54be485d6cd..d2ad361034f 100644 --- a/htdocs/societe/project.php +++ b/htdocs/societe/project.php @@ -35,7 +35,9 @@ $langs->loadLangs(array("companies", "projects")); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'societe', $socid, '&societe'); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -48,7 +50,9 @@ $hookmanager->initHooks(array('projectthirdparty')); $parameters = array('id'=>$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'); +} @@ -60,8 +64,7 @@ $contactstatic = new Contact($db); $form = new Form($db); -if ($socid) -{ +if ($socid) { require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; @@ -72,10 +75,14 @@ if ($socid) $result = $object->fetch($socid); $title = $langs->trans("Projects"); - if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name." - ".$title; + if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name." - ".$title; + } llxHeader('', $title); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = societe_prepare_head($object); print dol_get_fiche_head($head, 'project', $langs->trans("ThirdParty"), -1, 'company'); @@ -89,16 +96,14 @@ if ($socid) print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent tableforfield">'; - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td>'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>'; } - if ($object->client) - { + if ($object->client) { print '<tr><td class="titlefield">'; print $langs->trans('CustomerCode').'</td><td colspan="3">'; - print $object->code_client; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_client)); $tmpcheck = $object->check_codeclient(); if ($tmpcheck != 0 && $tmpcheck != -5) { print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; @@ -106,11 +111,10 @@ if ($socid) print '</td></tr>'; } - if ($object->fournisseur) - { + if ($object->fournisseur) { print '<tr><td class="titlefield">'; print $langs->trans('SupplierCode').'</td><td colspan="3">'; - print $object->code_fournisseur; + print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_fournisseur)); $tmpcheck = $object->check_codefournisseur(); if ($tmpcheck != 0 && $tmpcheck != -5) { print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; diff --git a/htdocs/societe/societecontact.php b/htdocs/societe/societecontact.php index 3547c5a1e9b..449fd9d7811 100644 --- a/htdocs/societe/societecontact.php +++ b/htdocs/societe/societecontact.php @@ -43,15 +43,23 @@ $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 (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "s.nom"; -if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { $page = 0; } +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "s.nom"; +} +if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { + $page = 0; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'societe', $id, ''); $object = new Societe($db); @@ -64,51 +72,39 @@ $hookmanager->initHooks(array('contactthirdparty', 'globalcard')); * Actions */ -if ($action == 'addcontact' && $user->rights->societe->creer) -{ +if ($action == 'addcontact' && $user->rights->societe->creer) { $result = $object->fetch($id); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); $mesg = '<div class="error">'.$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType").'</div>'; } else { $mesg = '<div class="error">'.$object->error.'</div>'; } } -} - -// bascule du statut d'un contact -elseif ($action == 'swapstatut' && $user->rights->societe->creer) -{ - if ($object->fetch($id)) - { +} elseif ($action == 'swapstatut' && $user->rights->societe->creer) { + // 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' && $user->rights->societe->creer) -{ +} elseif ($action == 'deletecontact' && $user->rights->societe->creer) { + // Efface un contact $object->fetch($id); $result = $object->delete_contact($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -145,10 +141,8 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref) > 0) - { +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { $soc = new Societe($db); $soc->fetch($object->socid); @@ -169,41 +163,38 @@ if ($id > 0 || !empty($ref)) // Prospect/Customer /*print '<tr><td class="titlefield">'.$langs->trans('ProspectCustomer').'</td><td>'; - print $object->getLibCustProspStatut(); - print '</td></tr>'; + print $object->getLibCustProspStatut(); + print '</td></tr>'; - // Supplier - print '<tr><td>'.$langs->trans('Supplier').'</td><td>'; - print yn($object->fournisseur); - print '</td></tr>';*/ + // Supplier + print '<tr><td>'.$langs->trans('Supplier').'</td><td>'; + print yn($object->fournisseur); + print '</td></tr>';*/ - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td>'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>'; } - if ($object->client) - { - print '<tr><td class="titlefield">'; - print $langs->trans('CustomerCode').'</td><td colspan="3">'; - print $object->code_client; - $tmpcheck = $object->check_codeclient(); - if ($tmpcheck != 0 && $tmpcheck != -5) { - print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; - } - print '</td></tr>'; + if ($object->client) { + print '<tr><td class="titlefield">'; + print $langs->trans('CustomerCode').'</td><td colspan="3">'; + print $object->code_client; + $tmpcheck = $object->check_codeclient(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; + } + print '</td></tr>'; } - if ($object->fournisseur) - { - print '<tr><td class="titlefield">'; - print $langs->trans('SupplierCode').'</td><td colspan="3">'; - print $object->code_fournisseur; - $tmpcheck = $object->check_codefournisseur(); - if ($tmpcheck != 0 && $tmpcheck != -5) { - print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; - } - print '</td></tr>'; + if ($object->fournisseur) { + print '<tr><td class="titlefield">'; + print $langs->trans('SupplierCode').'</td><td colspan="3">'; + print $object->code_fournisseur; + $tmpcheck = $object->check_codefournisseur(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; + } + print '</td></tr>'; } print '</table>'; @@ -214,15 +205,15 @@ if ($id > 0 || !empty($ref)) // Contacts lines (modules that overwrite templates must declare this into descriptor) $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); - foreach ($dirtpls as $reldir) - { + foreach ($dirtpls as $reldir) { $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); - if ($res) break; + if ($res) { + break; + } } // additionnal list with adherents of company - if (!empty($conf->adherent->enabled) && $user->rights->adherent->lire) - { + if (!empty($conf->adherent->enabled) && $user->rights->adherent->lire) { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php'; @@ -241,12 +232,10 @@ if ($id > 0 || !empty($ref)) dol_syslog("get list sql=".$sql); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { $param = ''; $titre = $langs->trans("MembersListOfTiers"); @@ -267,8 +256,7 @@ if ($id > 0 || !empty($ref)) print "</tr>\n"; $i = 0; - while ($i < $num && $i < $conf->liste_limit) - { + while ($i < $num && $i < $conf->liste_limit) { $objp = $db->fetch_object($resql); $datefin = $db->jdate($objp->datefin); @@ -319,8 +307,7 @@ if ($id > 0 || !empty($ref)) print "</td>"; // End of subscription date - if ($datefin) - { + if ($datefin) { print '<td class="center nowrap">'; print dol_print_date($datefin, 'day'); if ($memberstatic->hasDelay()) { @@ -329,10 +316,11 @@ if ($id > 0 || !empty($ref)) print '</td>'; } else { print '<td class="left nowrap">'; - if ($objp->subscription == 'yes') - { + if ($objp->subscription == 'yes') { print $langs->trans("SubscriptionNotReceived"); - if ($objp->statut > 0) print " ".img_warning(); + if ($objp->statut > 0) { + print " ".img_warning(); + } } else { print '&nbsp;'; } diff --git a/htdocs/societe/tpl/linesalesrepresentative.tpl.php b/htdocs/societe/tpl/linesalesrepresentative.tpl.php index 1eca5b22623..f67acf2f2d3 100644 --- a/htdocs/societe/tpl/linesalesrepresentative.tpl.php +++ b/htdocs/societe/tpl/linesalesrepresentative.tpl.php @@ -67,6 +67,8 @@ if ($action == 'editsalesrepresentatives') { print $userstatic->getNomUrl(-1); print ' '; } - } else print '<span class="opacitymedium">'.$langs->trans("NoSalesRepresentativeAffected").'</span>'; + } else { + print '<span class="opacitymedium">'.$langs->trans("NoSalesRepresentativeAffected").'</span>'; + } print '</td></tr>'; } diff --git a/htdocs/societe/website.php b/htdocs/societe/website.php index ff3108d2427..e7a1e086228 100644 --- a/htdocs/societe/website.php +++ b/htdocs/societe/website.php @@ -47,19 +47,27 @@ $search_status = GETPOST('search_status'); // Security check $id = GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'societe', $socid, '&societe'); $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 = 't.login'; -if (!$sortorder) $sortorder = 'ASC'; +if (!$sortfield) { + $sortfield = 't.login'; +} +if (!$sortorder) { + $sortorder = 'ASC'; +} // Initialize technical objects $object = new Societe($db); @@ -78,24 +86,27 @@ unset($objectwebsiteaccount->fields['fk_soc']); // Remove this field, we are alr // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($objectwebsiteaccount->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($objectwebsiteaccount->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($objectwebsiteaccount->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($objectwebsiteaccount->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of fields for list $arrayfields = array(); -foreach ($objectwebsiteaccount->fields as $key => $val) -{ +foreach ($objectwebsiteaccount->fields as $key => $val) { // If $val['visible']==0, then we never show the field - if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled']); + if (!empty($val['visible'])) { + $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled']); + } } // Extra fields @@ -105,8 +116,7 @@ $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); -if ($id > 0) -{ +if ($id > 0) { $result = $object->fetch($id); } @@ -117,13 +127,13 @@ if ($id > 0) $parameters = array('id'=>$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)) -{ +if (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -132,18 +142,15 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($objectwebsiteaccount->fields as $key => $val) - { + 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 + foreach ($objectwebsiteaccount->fields as $key => $val) { $search[$key] = ''; } $toselect = ''; $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -172,14 +179,21 @@ $title = $langs->trans("WebsiteAccounts"); llxHeader('', $title); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($id > 0) $param .= '&id='.urlencode($id); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($id > 0) { + $param .= '&id='.urlencode($id); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { $param .= '&search_'.$key.'='.urlencode($search[$key]); } -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'; @@ -198,8 +212,7 @@ print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent">'; // Prefix -if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field -{ +if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td class="titlefield">'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>'; } @@ -247,29 +260,39 @@ print '<br>'; // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($objectwebsiteaccount->fields as $key => $val) -{ +foreach ($objectwebsiteaccount->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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, $objectwebsiteaccount); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; $sql = preg_replace('/, $/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX."societe_account as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($objectwebsiteaccount->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity('societeaccount').")"; -else $sql .= " WHERE 1 = 1"; -$sql .= " AND fk_soc = ".$object->id; -foreach ($search as $key => $val) -{ - $mode_search = (($objectwebsiteaccount->isInt($objectwebsiteaccount->fields[$key]) || $objectwebsiteaccount->isFloat($objectwebsiteaccount->fields[$key])) ? 1 : 0); - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if ($objectwebsiteaccount->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity('societeaccount').")"; +} else { + $sql .= " WHERE 1 = 1"; +} +$sql .= " AND fk_soc = ".$object->id; +foreach ($search as $key => $val) { + $mode_search = (($objectwebsiteaccount->isInt($objectwebsiteaccount->fields[$key]) || $objectwebsiteaccount->isFloat($objectwebsiteaccount->fields[$key])) ? 1 : 0); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -296,12 +319,10 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -310,8 +331,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if (!$resql) -{ +if (!$resql) { dol_print_error($db); exit; } @@ -325,12 +345,18 @@ $arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -if ($user->rights->mymodule->delete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($user->rights->mymodule->delete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -361,11 +387,13 @@ $moreforfilter.= '</div>';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $objectwebsiteaccount); // Note that $action and $objectwebsiteaccount 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)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -382,13 +410,20 @@ print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : // Fields title search // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($objectwebsiteaccount->fields as $key => $val) -{ +foreach ($objectwebsiteaccount->fields as $key => $val) { $align = ''; - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $align = 'center'; - if (in_array($val['type'], array('timestamp'))) $align .= ' nowrap'; - if ($key == 'status') $align .= ($align ? ' ' : '').'center'; - if (!empty($arrayfields['t.'.$key]['checked'])) print '<td class="liste_titre'.($align ? ' '.$align : '').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>'; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $align = 'center'; + } + if (in_array($val['type'], array('timestamp'))) { + $align .= ' nowrap'; + } + if ($key == 'status') { + $align .= ($align ? ' ' : '').'center'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { + print '<td class="liste_titre'.($align ? ' '.$align : '').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>'; + } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; @@ -407,13 +442,20 @@ print '</tr>'."\n"; // Fields title label // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($objectwebsiteaccount->fields as $key => $val) -{ +foreach ($objectwebsiteaccount->fields as $key => $val) { $align = ''; - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $align = 'center'; - if (in_array($val['type'], array('timestamp'))) $align .= 'nowrap'; - if ($key == 'status') $align .= ($align ? ' ' : '').'center'; - if (!empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align ? 'class="'.$align.'"' : ''), $sortfield, $sortorder, $align.' ')."\n"; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $align = 'center'; + } + if (in_array($val['type'], array('timestamp'))) { + $align .= 'nowrap'; + } + if ($key == 'status') { + $align .= ($align ? ' ' : '').'center'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align ? 'class="'.$align.'"' : ''), $sortfield, $sortorder, $align.' ')."\n"; + } } // Extra fields // Extra fields @@ -428,11 +470,11 @@ print '</tr>'."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -440,40 +482,54 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $objectwebsiteaccount->id = $obj->rowid; $objectwebsiteaccount->login = $obj->login; $objectwebsiteaccount->ref = $obj->login; - foreach ($objectwebsiteaccount->fields as $key => $val) - { - if (property_exists($obj, $key)) $object->$key = $obj->$key; + foreach ($objectwebsiteaccount->fields as $key => $val) { + if (property_exists($obj, $key)) { + $object->$key = $obj->$key; + } } // Show here line of result print '<tr class="oddeven">'; - foreach ($objectwebsiteaccount->fields as $key => $val) - { + foreach ($objectwebsiteaccount->fields as $key => $val) { $align = ''; - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $align = 'center'; - if (in_array($val['type'], array('timestamp'))) $align .= 'nowrap'; - if ($key == 'status') $align .= ($align ? ' ' : '').'center'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $align = 'center'; + } + if (in_array($val['type'], array('timestamp'))) { + $align .= 'nowrap'; + } + if ($key == 'status') { + $align .= ($align ? ' ' : '').'center'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td'; - if ($align) print ' class="'.$align.'"'; + if ($align) { + print ' class="'.$align.'"'; + } print '>'; - if ($key == 'login') print $objectwebsiteaccount->getNomUrl(1, '', 0, '', 1); - else print $objectwebsiteaccount->showOutputField($val, $key, $obj->$key, ''); + if ($key == 'login') { + print $objectwebsiteaccount->getNomUrl(1, '', 0, '', 1); + } else { + print $objectwebsiteaccount->showOutputField($val, $key, $obj->$key, ''); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $obj->$key; } } @@ -486,14 +542,17 @@ while ($i < min($num, $limit)) print $hookmanager->resPrint; // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'; @@ -505,10 +564,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } @@ -524,10 +586,11 @@ print '</div>'."\n"; print '</form>'."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/stripe/admin/stripe.php b/htdocs/stripe/admin/stripe.php index 6a52b57268b..edac0a79833 100644 --- a/htdocs/stripe/admin/stripe.php +++ b/htdocs/stripe/admin/stripe.php @@ -37,7 +37,9 @@ $servicename = 'Stripe'; // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'paypal', 'paybox', 'stripe')); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); @@ -46,64 +48,79 @@ $action = GETPOST('action', 'aZ09'); * Actions */ -if ($action == 'setvalue' && $user->admin) -{ +if ($action == 'setvalue' && $user->admin) { $db->begin(); if (empty($conf->stripeconnect->enabled)) { $result = dolibarr_set_const($db, "STRIPE_TEST_PUBLISHABLE_KEY", GETPOST('STRIPE_TEST_PUBLISHABLE_KEY', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "STRIPE_TEST_SECRET_KEY", GETPOST('STRIPE_TEST_SECRET_KEY', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "STRIPE_TEST_WEBHOOK_ID", GETPOST('STRIPE_TEST_WEBHOOK_ID', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "STRIPE_TEST_WEBHOOK_KEY", GETPOST('STRIPE_TEST_WEBHOOK_KEY', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "STRIPE_LIVE_PUBLISHABLE_KEY", GETPOST('STRIPE_LIVE_PUBLISHABLE_KEY', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "STRIPE_LIVE_SECRET_KEY", GETPOST('STRIPE_LIVE_SECRET_KEY', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "STRIPE_LIVE_WEBHOOK_ID", GETPOST('STRIPE_LIVE_WEBHOOK_ID', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "STRIPE_LIVE_WEBHOOK_KEY", GETPOST('STRIPE_LIVE_WEBHOOK_KEY', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_CREDITOR", GETPOST('ONLINE_PAYMENT_CREDITOR', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "STRIPE_BANK_ACCOUNT_FOR_PAYMENTS", GETPOST('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS', 'int'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "STRIPE_USER_ACCOUNT_FOR_ACTIONS", GETPOST('STRIPE_USER_ACCOUNT_FOR_ACTIONS', 'int'), 'chaine', 0, '', $conf->entity); if (!$result > 0) { $error++; } $result = dolibarr_set_const($db, "STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS", GETPOST('STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 'int'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_CSS_URL", GETPOST('ONLINE_PAYMENT_CSS_URL', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_FORM", GETPOST('ONLINE_PAYMENT_MESSAGE_FORM', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_OK", GETPOST('ONLINE_PAYMENT_MESSAGE_OK', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_KO", GETPOST('ONLINE_PAYMENT_MESSAGE_KO', 'alpha'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } $result = dolibarr_set_const($db, "ONLINE_PAYMENT_SENDEMAIL", GETPOST('ONLINE_PAYMENT_SENDEMAIL'), 'chaine', 0, '', $conf->entity); - if (!$result > 0) + if (!$result > 0) { $error++; + } // Stock decrement //$result = dolibarr_set_const($db, "ONLINE_PAYMENT_WAREHOUSE", (GETPOST('ONLINE_PAYMENT_WAREHOUSE', 'alpha') > 0 ? GETPOST('ONLINE_PAYMENT_WAREHOUSE', 'alpha') : ''), 'chaine', 0, '', $conf->entity); //if (! $result > 0) @@ -130,8 +147,7 @@ if ($action == 'setvalue' && $user->admin) } } -if ($action == "setlive") -{ +if ($action == "setlive") { $liveenable = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "STRIPE_LIVE", $liveenable, 'yesno', 0, '', $conf->entity); if ($res > 0) { @@ -188,8 +204,7 @@ if ($conf->use_javascript_ajax) { } print '</td><td></td></tr>'; -if (empty($conf->stripeconnect->enabled)) -{ +if (empty($conf->stripeconnect->enabled)) { print '<tr class="oddeven"><td>'; print '<span class="fieldrequired">'.$langs->trans("STRIPE_TEST_PUBLISHABLE_KEY").'</span></td><td>'; print '<input class="minwidth300" type="text" name="STRIPE_TEST_PUBLISHABLE_KEY" value="'.$conf->global->STRIPE_TEST_PUBLISHABLE_KEY.'">'; @@ -216,10 +231,8 @@ if (empty($conf->stripeconnect->enabled)) $out .= ajax_autoselect("onlinetestwebhookurl", 0); print '<br>'.$out; print '</td><td>'; - if ($conf->global->MAIN_FEATURES_LEVEL >= 2) - { - if (!empty($conf->global->STRIPE_TEST_WEBHOOK_KEY) && !empty($conf->global->STRIPE_TEST_SECRET_KEY) && !empty($conf->global->STRIPE_TEST_WEBHOOK_ID)) - { + if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { + if (!empty($conf->global->STRIPE_TEST_WEBHOOK_KEY) && !empty($conf->global->STRIPE_TEST_SECRET_KEY) && !empty($conf->global->STRIPE_TEST_WEBHOOK_ID)) { \Stripe\Stripe::setApiKey($conf->global->STRIPE_TEST_SECRET_KEY); $endpoint = \Stripe\WebhookEndpoint::retrieve($conf->global->STRIPE_TEST_WEBHOOK_ID); $endpoint->enabled_events = $stripearrayofwebhookevents; @@ -232,8 +245,7 @@ if (empty($conf->stripeconnect->enabled)) } $endpoint->url = dol_buildpath('/public/stripe/ipn.php?test', 3); $endpoint->save(); - if ($endpoint->status == 'enabled') - { + if ($endpoint->status == 'enabled') { print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=ipn&webhook='.$endpoint->id.'&status=0">'; print img_picto($langs->trans("Activated"), 'switch_on'); } else { @@ -257,8 +269,7 @@ if (empty($conf->stripeconnect->enabled)) print '</td><td></td></tr>'; } -if (empty($conf->stripeconnect->enabled)) -{ +if (empty($conf->stripeconnect->enabled)) { print '<tr class="oddeven"><td>'; print '<span class="fieldrequired">'.$langs->trans("STRIPE_LIVE_PUBLISHABLE_KEY").'</span></td><td>'; print '<input class="minwidth300" type="text" name="STRIPE_LIVE_PUBLISHABLE_KEY" value="'.$conf->global->STRIPE_LIVE_PUBLISHABLE_KEY.'">'; @@ -285,10 +296,8 @@ if (empty($conf->stripeconnect->enabled)) $out .= ajax_autoselect("onlinelivewebhookurl", 0); print '<br>'.$out; print '</td><td>'; - if ($conf->global->MAIN_FEATURES_LEVEL >= 2) - { - if (!empty($conf->global->STRIPE_LIVE_WEBHOOK_KEY) && !empty($conf->global->STRIPE_LIVE_SECRET_KEY) && !empty($conf->global->STRIPE_LIVE_WEBHOOK_ID)) - { + if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { + if (!empty($conf->global->STRIPE_LIVE_WEBHOOK_KEY) && !empty($conf->global->STRIPE_LIVE_SECRET_KEY) && !empty($conf->global->STRIPE_LIVE_WEBHOOK_ID)) { \Stripe\Stripe::setApiKey($conf->global->STRIPE_LIVE_SECRET_KEY); $endpoint = \Stripe\WebhookEndpoint::retrieve($conf->global->STRIPE_LIVE_WEBHOOK_ID); $endpoint->enabled_events = $stripearrayofwebhookevents; @@ -301,8 +310,7 @@ if (empty($conf->stripeconnect->enabled)) } $endpoint->url = dol_buildpath('/public/stripe/ipn.php', 3); $endpoint->save(); - if ($endpoint->status == 'enabled') - { + if ($endpoint->status == 'enabled') { print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=ipn&webhook='.$endpoint->id.'&status=0">'; print img_picto($langs->trans("Activated"), 'switch_on'); } else { @@ -351,8 +359,7 @@ print img_picto('', 'bank_account').' '; $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS, 'STRIPE_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1); print '</td></tr>'; -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // What is this for ? -{ +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { // What is this for ? print '<tr class="oddeven"><td>'; print $langs->trans("BankAccountForBankTransfer").'</td><td>'; $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS, 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1); @@ -360,8 +367,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // What is this for ? } // Activate Payment Request API -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // TODO Not used by current code -{ +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { // TODO Not used by current code print '<tr class="oddeven"><td>'; print $langs->trans("STRIPE_PAYMENT_REQUEST_API").'</td><td>'; if ($conf->use_javascript_ajax) { @@ -374,8 +380,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // TODO Not used by current code } // Activate SEPA DIRECT_DEBIT -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // TODO Not used by current code -{ +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { // TODO Not used by current code print '<tr class="oddeven"><td>'; print $langs->trans("STRIPE_SEPA_DIRECT_DEBIT").'</td><td>'; if ($conf->use_javascript_ajax) { @@ -388,8 +393,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // TODO Not used by current code } // Activate Bancontact -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // TODO Not used by current code -{ +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { // TODO Not used by current code print '<tr class="oddeven"><td>'; print $langs->trans("STRIPE_BANCONTACT").'</td><td>'; if ($conf->use_javascript_ajax) { @@ -403,8 +407,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // TODO Not used by current code } // Activate iDEAL -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // TODO Not used by current code -{ +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { // TODO Not used by current code print '<tr class="oddeven"><td>'; print $langs->trans("STRIPE_IDEAL").'</td><td>'; if ($conf->use_javascript_ajax) { @@ -418,8 +421,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // TODO Not used by current code } // Activate Giropay -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // TODO Not used by current code -{ +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { // TODO Not used by current code print '<tr class="oddeven"><td>'; print $langs->trans("STRIPE_GIROPAY").'</td><td>'; if ($conf->use_javascript_ajax) { @@ -433,8 +435,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // TODO Not used by current code } // Activate Sofort -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // TODO Not used by current code -{ +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { // TODO Not used by current code print '<tr class="oddeven"><td>'; print $langs->trans("STRIPE_SOFORT").'</td><td>'; if ($conf->use_javascript_ajax) { @@ -540,8 +541,7 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/onlinepaymentlinks.tpl.php'; print info_admin($langs->trans("ExampleOfTestCreditCard", '4242424242424242 (no 3DSecure) or 4000000000003063 (3DSecure required) or 4000002760003184 (3DSecure2 required on all transaction) or 4000003800000446 (3DSecure2 required, the off-session allowed)', '4000000000000101', '4000000000000069', '4000000000000341')); -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print "\n".'<script type="text/javascript">'; print '$(document).ready(function () { $("#apidoc").hide(); diff --git a/htdocs/stripe/charge.php b/htdocs/stripe/charge.php index beadfee1a89..a3598f1d29f 100644 --- a/htdocs/stripe/charge.php +++ b/htdocs/stripe/charge.php @@ -26,14 +26,18 @@ require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('compta', 'salaries', 'bills', 'hrm', 'stripe')); // Security check $socid = GETPOST("socid", "int"); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} //$result = restrictedArea($user, 'salaries', '', '', ''); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; @@ -41,7 +45,9 @@ $rowid = GETPOST("rowid", 'alpha'); $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; @@ -60,8 +66,7 @@ $stripe = new Stripe($db); llxHeader('', $langs->trans("StripeChargeList")); -if (!empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha'))) -{ +if (!empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha'))) { $service = 'StripeTest'; $servicestatus = '0'; dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning'); @@ -80,11 +85,12 @@ if (!$rowid) { $option = array('limit' => $limit + 1); $num = 0; - if (GETPOSTISSET('starting_after_'.$page)) $option['starting_after'] = GETPOST('starting_after_'.$page, 'alphanohtml'); + if (GETPOSTISSET('starting_after_'.$page)) { + $option['starting_after'] = GETPOST('starting_after_'.$page, 'alphanohtml'); + } try { - if ($stripeacc) - { + if ($stripeacc) { $list = \Stripe\Charge::all($option, array("stripe_account" => $stripeacc)); } else { $list = \Stripe\Charge::all($option); @@ -96,7 +102,9 @@ if (!$rowid) { $param = ''; //if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } $param .= '&starting_after_'.($page + 1).'='.$list->data[($limit - 1)]->id; //$param.='&ending_before_'.($page+1).'='.$list->data[($limit-1)]->id; @@ -106,7 +114,9 @@ if (!$rowid) { } print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -135,8 +145,7 @@ if (!$rowid) { //print $list; $i = 0; - foreach ($list->data as $charge) - { + foreach ($list->data as $charge) { if ($i >= $limit) { break; } @@ -179,17 +188,14 @@ if (!$rowid) { // Save into $tmparray all metadata $tmparray = dolExplodeIntoArray($FULLTAG, '.', '='); // Load origin object according to metadata - if (!empty($tmparray['CUS']) && $tmparray['CUS'] > 0) - { + if (!empty($tmparray['CUS']) && $tmparray['CUS'] > 0) { $societestatic->fetch($tmparray['CUS']); - } elseif (!empty($charge->metadata->dol_thirdparty_id) && $charge->metadata->dol_thirdparty_id > 0) - { + } elseif (!empty($charge->metadata->dol_thirdparty_id) && $charge->metadata->dol_thirdparty_id > 0) { $societestatic->fetch($charge->metadata->dol_thirdparty_id); } else { $societestatic->id = 0; } - if (!empty($tmparray['MEM']) && $tmparray['MEM'] > 0) - { + if (!empty($tmparray['MEM']) && $tmparray['MEM'] > 0) { $memberstatic->fetch($tmparray['MEM']); } else { $memberstatic->id = 0; @@ -197,40 +203,41 @@ if (!$rowid) { print '<tr class="oddeven">'; - if (!empty($stripeacc)) $connect = $stripeacc.'/'; + if (!empty($stripeacc)) { + $connect = $stripeacc.'/'; + } // Ref $url = 'https://dashboard.stripe.com/'.$connect.'test/payments/'.$charge->id; - if ($servicestatus) - { + if ($servicestatus) { $url = 'https://dashboard.stripe.com/'.$connect.'payments/'.$charge->id; } print "<td>"; print "<a href='".$url."' target='_stripe'>".img_picto($langs->trans('ShowInStripe'), 'globe')." ".$charge->id."</a>"; - if ($charge->payment_intent) print '<br><span class="opacitymedium">'.$charge->payment_intent.'</span>'; + if ($charge->payment_intent) { + print '<br><span class="opacitymedium">'.$charge->payment_intent.'</span>'; + } print "</td>\n"; // Stripe customer print "<td>"; - if (!empty($conf->stripe->enabled) && !empty($stripeacc)) $connect = $stripeacc.'/'; + if (!empty($conf->stripe->enabled) && !empty($stripeacc)) { + $connect = $stripeacc.'/'; + } $url = 'https://dashboard.stripe.com/'.$connect.'test/customers/'.$charge->customer; - if ($servicestatus) - { + if ($servicestatus) { $url = 'https://dashboard.stripe.com/'.$connect.'customers/'.$charge->customer; } - if (!empty($charge->customer)) - { + if (!empty($charge->customer)) { print '<a href="'.$url.'" target="_stripe">'.img_picto($langs->trans('ShowInStripe'), 'globe').' '.$charge->customer.'</a>'; } print "</td>\n"; // Link print "<td>"; - if ($societestatic->id > 0) - { + if ($societestatic->id > 0) { print $societestatic->getNomUrl(1); - } elseif ($memberstatic->id > 0) - { + } elseif ($memberstatic->id > 0) { print $memberstatic->getNomUrl(1); } print "</td>\n"; diff --git a/htdocs/stripe/class/actions_stripe.class.php b/htdocs/stripe/class/actions_stripe.class.php index 159444bb029..e44f3480042 100644 --- a/htdocs/stripe/class/actions_stripe.class.php +++ b/htdocs/stripe/class/actions_stripe.class.php @@ -71,25 +71,21 @@ class ActionsStripeconnect { global $db, $conf, $user, $langs, $form; - if (!empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha'))) - { + if (!empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha'))) { $service = 'StripeTest'; dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning'); } else { $service = 'StripeLive'; } - if (is_array($parameters) && !empty($parameters)) - { - foreach ($parameters as $key=>$value) - { + if (is_array($parameters) && !empty($parameters)) { + foreach ($parameters as $key => $value) { $key = $value; } } - if (is_object($object) && $object->element == 'societe') - { + if (is_object($object) && $object->element == 'societe') { $this->resprints .= '<tr><td>'; $this->resprints .= '<table width="100%" class="nobordernopadding"><tr><td>'; $this->resprints .= $langs->trans('StripeCustomer'); @@ -195,20 +191,16 @@ class ActionsStripeconnect $resteapayer = $object->total_ttc - $totalpaye; // Request a direct debit order - if ($object->statut > Facture::STATUS_DRAFT && $object->statut < Facture::STATUS_ABANDONED && $object->paye == 0) - { + if ($object->statut > Facture::STATUS_DRAFT && $object->statut < Facture::STATUS_ABANDONED && $object->paye == 0) { $stripe = new Stripe($this->db); - if ($resteapayer > 0) - { - if ($stripe->getStripeAccount($conf->entity)) // a modifier avec droit stripe - { + if ($resteapayer > 0) { + if ($stripe->getStripeAccount($conf->entity)) { // a modifier avec droit stripe $langs->load("withdrawals"); print '<a class="butActionDelete" href="'.dol_buildpath('/stripeconnect/payment.php?facid='.$object->id.'&action=create', 1).'" title="'.dol_escape_htmltag($langs->trans("StripeConnectPay")).'">'.$langs->trans("StripeConnectPay").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("StripeConnectPay").'</a>'; } - } elseif ($resteapayer == 0) - { + } elseif ($resteapayer == 0) { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("StripeConnectPay").'</a>'; } } else { diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 259e1cea935..9caf72c20e1 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -91,7 +91,9 @@ class Stripe extends CommonObject global $conf; $key = ''; - if ($entity < 0) $entity = $conf->entity; + if ($entity < 0) { + $entity = $conf->entity; + } $sql = "SELECT tokenstring"; $sql .= " FROM ".MAIN_DB_PREFIX."oauth_token"; @@ -155,8 +157,7 @@ class Stripe extends CommonObject { global $conf, $user; - if (empty($object->id)) - { + if (empty($object->id)) { dol_syslog("customerStripe is called with the parameter object that is not loaded"); return null; } @@ -193,8 +194,7 @@ class Stripe extends CommonObject //$customer = \Stripe\Customer::retrieve("$tiers", array("stripe_account" => $key)); $customer = \Stripe\Customer::retrieve(array('id'=>"$tiers", 'expand[]'=>'sources'), array("stripe_account" => $key)); } - } catch (Exception $e) - { + } catch (Exception $e) { // For exemple, we may have error: 'No such customer: cus_XXXXX; a similar object exists in live mode, but a test mode key was used to make this request.' $this->error = $e->getMessage(); } @@ -234,13 +234,10 @@ class Stripe extends CommonObject } // Create the VAT record in Stripe - if (!empty($conf->global->STRIPE_SAVE_TAX_IDS)) // We setup to save Tax info on Stripe side. Warning: This may result in error when saving customer - { - if (!empty($vatcleaned)) - { + if (!empty($conf->global->STRIPE_SAVE_TAX_IDS)) { // We setup to save Tax info on Stripe side. Warning: This may result in error when saving customer + if (!empty($vatcleaned)) { $isineec = isInEEC($object); - if ($object->country_code && $isineec) - { + if ($object->country_code && $isineec) { //$taxids = $customer->allTaxIds($customer->id); $customer->createTaxId($customer->id, array('type'=>'eu_vat', 'value'=>$vatcleaned)); } @@ -251,12 +248,10 @@ class Stripe extends CommonObject $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_account (fk_soc, login, key_account, site, site_account, status, entity, date_creation, fk_user_creat)"; $sql .= " VALUES (".$object->id.", '', '".$this->db->escape($customer->id)."', 'stripe', '".$this->db->escape($stripearrayofkeysbyenv[$status]['publishable_key'])."', ".$status.", ".$conf->entity.", '".$this->db->idate(dol_now())."', ".$user->id.")"; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->lasterror(); } - } catch (Exception $e) - { + } catch (Exception $e) { $this->error = $e->getMessage(); } } @@ -288,8 +283,7 @@ class Stripe extends CommonObject } else { $stripepaymentmethod = \Stripe\PaymentMethod::retrieve(''.$paymentmethod->id.'', array("stripe_account" => $key)); } - } catch (Exception $e) - { + } catch (Exception $e) { $this->error = $e->getMessage(); } @@ -329,12 +323,18 @@ class Stripe extends CommonObject $error = 0; - if (empty($status)) $service = 'StripeTest'; - else $service = 'StripeLive'; + if (empty($status)) { + $service = 'StripeTest'; + } else { + $service = 'StripeLive'; + } $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); - if (!in_array($currency_code, $arrayzerounitcurrency)) $stripeamount = $amount * 100; - else $stripeamount = $amount; + if (!in_array($currency_code, $arrayzerounitcurrency)) { + $stripeamount = $amount * 100; + } else { + $stripeamount = $amount; + } $fee = $amount * ($conf->global->STRIPE_APPLICATION_FEE_PERCENT / 100) + $conf->global->STRIPE_APPLICATION_FEE; if ($fee >= $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL && $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL > $conf->global->STRIPE_APPLICATION_FEE_MINIMAL) { @@ -350,8 +350,7 @@ class Stripe extends CommonObject $paymentintent = null; - if (is_object($object) && !empty($conf->global->STRIPE_REUSE_EXISTING_INTENT_IF_FOUND)) - { + if (is_object($object) && !empty($conf->global->STRIPE_REUSE_EXISTING_INTENT_IF_FOUND)) { // Warning. If a payment was tried and failed, a payment intent was created. // But if we change something on object to pay (amount or other that does not change the idempotency key), reusing same payment intent is not allowed by Stripe. // Recommended solution is to recreate a new payment intent each time we need one (old one will be automatically closed by Stripe after a delay), Stripe will @@ -369,8 +368,7 @@ class Stripe extends CommonObject $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); - if ($num) - { + if ($num) { $obj = $this->db->fetch_object($resql); $intent = $obj->ext_payment_id; @@ -386,8 +384,7 @@ class Stripe extends CommonObject } else { $paymentintent = \Stripe\PaymentIntent::retrieve($intent, array("stripe_account" => $key)); } - } - catch (Exception $e) { + } catch (Exception $e) { $error++; $this->error = $e->getMessage(); } @@ -395,25 +392,35 @@ class Stripe extends CommonObject } } - if (empty($paymentintent)) - { + if (empty($paymentintent)) { // Try to create intent. See https://stripe.com/docs/api/payment_intents/create $ipaddress = getUserRemoteIP(); $metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress); - if (is_object($object)) - { + if (is_object($object)) { $metadata['dol_type'] = $object->element; $metadata['dol_id'] = $object->id; - if (is_object($object->thirdparty) && $object->thirdparty->id > 0) $metadata['dol_thirdparty_id'] = $object->thirdparty->id; + if (is_object($object->thirdparty) && $object->thirdparty->id > 0) { + $metadata['dol_thirdparty_id'] = $object->thirdparty->id; + } } // list of payment method types $paymentmethodtypes = array("card"); - if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT)) $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC()) - if (!empty($conf->global->STRIPE_BANCONTACT)) $paymentmethodtypes[] = "bancontact"; - if (!empty($conf->global->STRIPE_IDEAL)) $paymentmethodtypes[] = "ideal"; - if (!empty($conf->global->STRIPE_GIROPAY)) $paymentmethodtypes[] = "giropay"; - if (!empty($conf->global->STRIPE_SOFORT)) $paymentmethodtypes[] = "sofort"; + if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT)) { + $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC()) + } + if (!empty($conf->global->STRIPE_BANCONTACT)) { + $paymentmethodtypes[] = "bancontact"; + } + if (!empty($conf->global->STRIPE_IDEAL)) { + $paymentmethodtypes[] = "ideal"; + } + if (!empty($conf->global->STRIPE_GIROPAY)) { + $paymentmethodtypes[] = "giropay"; + } + if (!empty($conf->global->STRIPE_SOFORT)) { + $paymentmethodtypes[] = "sofort"; + } $dataforintent = array( "confirm" => $confirmnow, // Do not confirm immediatly during creation of intent @@ -427,32 +434,32 @@ class Stripe extends CommonObject "setup_future_usage" => "on_session", "metadata" => $metadata ); - if (!is_null($customer)) $dataforintent["customer"] = $customer; + if (!is_null($customer)) { + $dataforintent["customer"] = $customer; + } // payment_method = // payment_method_types = array('card') //var_dump($dataforintent); - if ($off_session) - { + if ($off_session) { unset($dataforintent['setup_future_usage']); // We can't use both "setup_future_usage" = "off_session" and "off_session" = true. // Because $off_session parameter is dedicated to create paymentintent off_line (and not future payment), we need to use "off_session" = true. //$dataforintent["setup_future_usage"] = "off_session"; $dataforintent["off_session"] = true; } - if (!empty($conf->global->STRIPE_GIROPAY)) unset($dataforintent['setup_future_usage']); + if (!empty($conf->global->STRIPE_GIROPAY)) { + unset($dataforintent['setup_future_usage']); + } - if (!is_null($payment_method)) - { + if (!is_null($payment_method)) { $dataforintent["payment_method"] = $payment_method; $description .= ' - '.$payment_method; } - if ($conf->entity != $conf->global->STRIPECONNECT_PRINCIPAL && $stripefee > 0) - { + if ($conf->entity != $conf->global->STRIPECONNECT_PRINCIPAL && $stripefee > 0) { $dataforintent["application_fee_amount"] = $stripefee; } - if ($usethirdpartyemailforreceiptemail && is_object($object) && $object->thirdparty->email) - { + if ($usethirdpartyemailforreceiptemail && is_object($object) && $object->thirdparty->email) { $dataforintent["receipt_email"] = $object->thirdparty->email; } @@ -475,8 +482,7 @@ class Stripe extends CommonObject $paymentintent = \Stripe\PaymentIntent::create($dataforintent, $arrayofoptions); // Store the payment intent - if (is_object($object)) - { + if (is_object($object)) { $paymentintentalreadyexists = 0; // Check that payment intent $paymentintent->id is not already recorded. $sql = "SELECT pi.rowid"; @@ -489,22 +495,23 @@ class Stripe extends CommonObject $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); - if ($num) - { + if ($num) { $obj = $this->db->fetch_object($resql); - if ($obj) $paymentintentalreadyexists++; + if ($obj) { + $paymentintentalreadyexists++; + } } - } else dol_print_error($this->db); + } else { + dol_print_error($this->db); + } // If not, we create it. - if (!$paymentintentalreadyexists) - { + if (!$paymentintentalreadyexists) { $now = dol_now(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture_demande (date_demande, fk_user_demande, ext_payment_id, fk_facture, sourcetype, entity, ext_payment_site, amount)"; $sql .= " VALUES ('".$this->db->idate($now)."', ".$user->id.", '".$this->db->escape($paymentintent->id)."', ".$object->id.", '".$this->db->escape($object->element)."', ".$conf->entity.", '".$this->db->escape($service)."', ".$amount.")"; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = $this->db->lasterror(); dol_syslog(get_class($this)."::PaymentIntent failed to insert paymentintent with id=".$paymentintent->id." into database."); @@ -513,20 +520,18 @@ class Stripe extends CommonObject } else { $_SESSION["stripe_payment_intent"] = $paymentintent; } - } catch (Stripe\Error\Card $e) - { + } catch (Stripe\Error\Card $e) { $error++; $this->error = $e->getMessage(); $this->code = $e->getStripeCode(); $this->declinecode = $e->getDeclineCode(); - } catch (Exception $e) - { + } catch (Exception $e) { /*var_dump($dataforintent); - var_dump($description); - var_dump($key); - var_dump($paymentintent); - var_dump($e->getMessage()); - var_dump($e);*/ + var_dump($description); + var_dump($key); + var_dump($paymentintent); + var_dump($e->getMessage()); + var_dump($e);*/ $error++; $this->error = $e->getMessage(); $this->code = ''; @@ -570,29 +575,40 @@ class Stripe extends CommonObject $error = 0; - if (empty($status)) $service = 'StripeTest'; - else $service = 'StripeLive'; + if (empty($status)) { + $service = 'StripeTest'; + } else { + $service = 'StripeLive'; + } $setupintent = null; - if (empty($setupintent)) - { + if (empty($setupintent)) { $ipaddress = getUserRemoteIP(); $metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress); - if (is_object($object)) - { + if (is_object($object)) { $metadata['dol_type'] = $object->element; $metadata['dol_id'] = $object->id; - if (is_object($object->thirdparty) && $object->thirdparty->id > 0) $metadata['dol_thirdparty_id'] = $object->thirdparty->id; + if (is_object($object->thirdparty) && $object->thirdparty->id > 0) { + $metadata['dol_thirdparty_id'] = $object->thirdparty->id; + } } // list of payment method types $paymentmethodtypes = array("card"); - if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT)) $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC()) - if (!empty($conf->global->STRIPE_BANCONTACT)) $paymentmethodtypes[] = "bancontact"; - if (!empty($conf->global->STRIPE_IDEAL)) $paymentmethodtypes[] = "ideal"; + if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT)) { + $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC()) + } + if (!empty($conf->global->STRIPE_BANCONTACT)) { + $paymentmethodtypes[] = "bancontact"; + } + if (!empty($conf->global->STRIPE_IDEAL)) { + $paymentmethodtypes[] = "ideal"; + } // Giropay not possible for setup intent - if (!empty($conf->global->STRIPE_SOFORT)) $paymentmethodtypes[] = "sofort"; + if (!empty($conf->global->STRIPE_SOFORT)) { + $paymentmethodtypes[] = "sofort"; + } $dataforintent = array( "confirm" => $confirmnow, // Do not confirm immediatly during creation of intent @@ -600,14 +616,17 @@ class Stripe extends CommonObject "usage" => "off_session", "metadata" => $metadata ); - if (!is_null($customer)) $dataforintent["customer"] = $customer; - if (!is_null($description)) $dataforintent["description"] = $description; + if (!is_null($customer)) { + $dataforintent["customer"] = $customer; + } + if (!is_null($description)) { + $dataforintent["description"] = $description; + } // payment_method = // payment_method_types = array('card') //var_dump($dataforintent); - if ($usethirdpartyemailforreceiptemail && is_object($object) && $object->thirdparty->email) - { + if ($usethirdpartyemailforreceiptemail && is_object($object) && $object->thirdparty->email) { $dataforintent["receipt_email"] = $object->thirdparty->email; } @@ -670,8 +689,7 @@ class Stripe extends CommonObject { $_SESSION["stripe_setup_intent"] = $setupintent; }*/ - } catch (Exception $e) - { + } catch (Exception $e) { /*var_dump($dataforintent); var_dump($description); var_dump($key); @@ -682,8 +700,7 @@ class Stripe extends CommonObject } } - if (!$error) - { + if (!$error) { dol_syslog("getSetupIntent ".(is_object($setupintent) ? $setupintent->id : ''), LOG_INFO, -1); return $setupintent; } else { @@ -718,24 +735,20 @@ class Stripe extends CommonObject $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); - if ($num) - { + if ($num) { $obj = $this->db->fetch_object($resql); $cardref = $obj->stripe_card_ref; dol_syslog(get_class($this)."::cardStripe cardref=".$cardref); - if ($cardref) - { + if ($cardref) { try { if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage - if (!preg_match('/^pm_/', $cardref) && !empty($cu->sources)) - { + if (!preg_match('/^pm_/', $cardref) && !empty($cu->sources)) { $card = $cu->sources->retrieve($cardref); } else { $card = \Stripe\PaymentMethod::retrieve($cardref); } } else { - if (!preg_match('/^pm_/', $cardref) && !empty($cu->sources)) - { + if (!preg_match('/^pm_/', $cardref) && !empty($cu->sources)) { //$card = $cu->sources->retrieve($cardref, array("stripe_account" => $stripeacc)); // this API fails when array stripe_account is provided $card = $cu->sources->retrieve($cardref); } else { @@ -743,13 +756,11 @@ class Stripe extends CommonObject $card = \Stripe\PaymentMethod::retrieve($cardref); } } - } catch (Exception $e) - { + } catch (Exception $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); } - } elseif ($createifnotlinkedtostripe) - { + } elseif ($createifnotlinkedtostripe) { $exp_date_month = $obj->exp_date_month; $exp_date_year = $obj->exp_date_year; $number = $obj->number; @@ -767,20 +778,19 @@ class Stripe extends CommonObject //var_dump($a);var_dump($stripeacc);exit; try { if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage - if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { + if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { dol_syslog("Try to create card with dataforcard = ".json_encode($dataforcard)); $card = $cu->sources->create($dataforcard); - if (!$card) - { + if (!$card) { $this->error = 'Creation of card on Stripe has failed'; } } else { $connect = ''; - if (!empty($stripeacc)) $connect = $stripeacc.'/'; + if (!empty($stripeacc)) { + $connect = $stripeacc.'/'; + } $url = 'https://dashboard.stripe.com/'.$connect.'test/customers/'.$cu->id; - if ($status) - { + if ($status) { $url = 'https://dashboard.stripe.com/'.$connect.'customers/'.$cu->id; } $urtoswitchonstripe = ' <a href="'.$url.'" target="_stripe">'.img_picto($langs->trans('ShowInStripe'), 'globe').'</a>'; @@ -789,20 +799,19 @@ class Stripe extends CommonObject $this->error = $langs->trans('CreationOfPaymentModeMustBeDoneFromStripeInterface', $urtoswitchonstripe); } } else { - if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) - { + if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { dol_syslog("Try to create card with dataforcard = ".json_encode($dataforcard)); $card = $cu->sources->create($dataforcard, array("stripe_account" => $stripeacc)); - if (!$card) - { + if (!$card) { $this->error = 'Creation of card on Stripe has failed'; } } else { $connect = ''; - if (!empty($stripeacc)) $connect = $stripeacc.'/'; + if (!empty($stripeacc)) { + $connect = $stripeacc.'/'; + } $url = 'https://dashboard.stripe.com/'.$connect.'test/customers/'.$cu->id; - if ($status) - { + if ($status) { $url = 'https://dashboard.stripe.com/'.$connect.'customers/'.$cu->id; } $urtoswitchonstripe = ' <a href="'.$url.'" target="_stripe">'.img_picto($langs->trans('ShowInStripe'), 'globe').'</a>'; @@ -812,8 +821,7 @@ class Stripe extends CommonObject } } - if ($card) - { + if ($card) { $sql = "UPDATE ".MAIN_DB_PREFIX."societe_rib"; $sql .= " SET stripe_card_ref = '".$this->db->escape($card->id)."', card_type = '".$this->db->escape($card->brand)."',"; $sql .= " country_code = '".$this->db->escape($card->country)."',"; @@ -821,13 +829,11 @@ class Stripe extends CommonObject $sql .= " WHERE rowid = ".$object->id; $sql .= " AND type = 'card'"; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->lasterror(); } } - } catch (Exception $e) - { + } catch (Exception $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); } @@ -862,8 +868,11 @@ class Stripe extends CommonObject $error = 0; - if (empty($status)) $service = 'StripeTest'; - else $service = 'StripeLive'; + if (empty($status)) { + $service = 'StripeTest'; + } else { + $service = 'StripeLive'; + } $sql = "SELECT sa.key_account as key_account, sa.fk_soc, sa.entity"; $sql .= " FROM ".MAIN_DB_PREFIX."societe_account as sa"; @@ -885,11 +894,16 @@ class Stripe extends CommonObject } $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); - if (!in_array($currency, $arrayzerounitcurrency)) $stripeamount = $amount * 100; - else $stripeamount = $amount; + if (!in_array($currency, $arrayzerounitcurrency)) { + $stripeamount = $amount * 100; + } else { + $stripeamount = $amount; + } $societe = new Societe($this->db); - if ($key > 0) $societe->fetch($key); + if ($key > 0) { + $societe->fetch($key); + } $description = ""; $ref = ""; @@ -922,10 +936,8 @@ class Stripe extends CommonObject global $stripearrayofkeysbyenv; \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']); - if (empty($conf->stripeconnect->enabled)) // With a common Stripe account - { - if (preg_match('/pm_/i', $source)) - { + if (empty($conf->stripeconnect->enabled)) { // With a common Stripe account + if (preg_match('/pm_/i', $source)) { $stripecard = $source; $amountstripe = $stripeamount; $FULLTAG = 'PFBO'; // Payment From Back Office @@ -942,8 +954,7 @@ class Stripe extends CommonObject $paymentintent = $stripe->getPaymentIntent($amounttopay, $currency, $FULLTAG, $description, $invoice, $customer->id, $stripeacc, $servicestatus, 0, 'automatic', true, $stripecard->id, 1); $charge = new stdClass(); - if ($paymentintent->status == 'succeeded') - { + if ($paymentintent->status == 'succeeded') { $charge->status = 'ok'; } else { $charge->status = 'failed'; @@ -954,8 +965,7 @@ class Stripe extends CommonObject $stripefailuremessage = $stripe->error; $stripefailuredeclinecode = $stripe->declinecode; } - } elseif (preg_match('/acct_/i', $source)) - { + } elseif (preg_match('/acct_/i', $source)) { $charge = \Stripe\Charge::create(array( "amount" => "$stripeamount", "currency" => "$currency", @@ -977,8 +987,7 @@ class Stripe extends CommonObject "customer" => "$customer" ); - if ($societe->email && $usethirdpartyemailforreceiptemail) - { + if ($societe->email && $usethirdpartyemailforreceiptemail) { $paymentarray["receipt_email"] = $societe->email; } @@ -993,8 +1002,11 @@ class Stripe extends CommonObject $fee = $conf->global->STRIPE_APPLICATION_FEE_MINIMAL; } - if (!in_array($currency, $arrayzerounitcurrency)) $stripefee = round($fee * 100); - else $stripefee = round($fee); + if (!in_array($currency, $arrayzerounitcurrency)) { + $stripefee = round($fee * 100); + } else { + $stripefee = round($fee); + } $paymentarray = array( "amount" => "$stripeamount", @@ -1006,17 +1018,14 @@ class Stripe extends CommonObject "source" => "$source", "customer" => "$customer" ); - if ($conf->entity != $conf->global->STRIPECONNECT_PRINCIPAL && $stripefee > 0) - { + if ($conf->entity != $conf->global->STRIPECONNECT_PRINCIPAL && $stripefee > 0) { $paymentarray["application_fee_amount"] = $stripefee; } - if ($societe->email && $usethirdpartyemailforreceiptemail) - { + if ($societe->email && $usethirdpartyemailforreceiptemail) { $paymentarray["receipt_email"] = $societe->email; } - if (preg_match('/pm_/i', $source)) - { + if (preg_match('/pm_/i', $source)) { $stripecard = $source; $amountstripe = $stripeamount; $FULLTAG = 'PFBO'; // Payment From Back Office @@ -1033,8 +1042,7 @@ class Stripe extends CommonObject $paymentintent = $stripe->getPaymentIntent($amounttopay, $currency, $FULLTAG, $description, $invoice, $customer->id, $stripeacc, $servicestatus, 0, 'automatic', true, $stripecard->id, 1); $charge = new stdClass(); - if ($paymentintent->status == 'succeeded') - { + if ($paymentintent->status == 'succeeded') { $charge->status = 'ok'; $charge->id = $paymentintent->id; } else { @@ -1047,13 +1055,13 @@ class Stripe extends CommonObject $charge = \Stripe\Charge::create($paymentarray, array("idempotency_key" => "$description", "stripe_account" => "$account")); } } - if (isset($charge->id)) {} + if (isset($charge->id)) { + } $return->statut = 'success'; $return->id = $charge->id; - if (preg_match('/pm_/i', $source)) - { + if (preg_match('/pm_/i', $source)) { $return->message = 'Payment retrieved by card status = '.$charge->status; } else { if ($charge->source->type == 'card') { diff --git a/htdocs/stripe/config.php b/htdocs/stripe/config.php index c7fa11df498..453eeb2ae64 100644 --- a/htdocs/stripe/config.php +++ b/htdocs/stripe/config.php @@ -44,8 +44,7 @@ $stripearrayofkeysbyenv = array( ); $stripearrayofkeys = array(); -if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha')) -{ +if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha')) { $stripearrayofkeys = $stripearrayofkeysbyenv[0]; // Test } else { $stripearrayofkeys = $stripearrayofkeysbyenv[1]; // Live diff --git a/htdocs/stripe/lib/stripe.lib.php b/htdocs/stripe/lib/stripe.lib.php index f1d03ae39be..8749847b958 100644 --- a/htdocs/stripe/lib/stripe.lib.php +++ b/htdocs/stripe/lib/stripe.lib.php @@ -67,52 +67,53 @@ function html_print_stripe_footer($fromcompany, $langs) // Juridical status $line1 = ""; - if ($fromcompany->forme_juridique_code) - { + if ($fromcompany->forme_juridique_code) { $line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code); } // Capital - if ($fromcompany->capital) - { + if ($fromcompany->capital) { $line1 .= ($line1 ? " - " : "").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency); } $reg = array(); // Prof Id 1 - if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) - { + if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) { $field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1; } // Prof Id 2 - if ($fromcompany->idprof2) - { + if ($fromcompany->idprof2) { $field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof2; } // Second line of company infos $line2 = ""; // Prof Id 3 - if ($fromcompany->idprof3) - { + if ($fromcompany->idprof3) { $field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3; } // Prof Id 4 - if ($fromcompany->idprof4) - { + if ($fromcompany->idprof4) { $field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4; } // IntraCommunautary VAT - if ($fromcompany->tva_intra != '') - { + if ($fromcompany->tva_intra != '') { $line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra; } diff --git a/htdocs/stripe/payout.php b/htdocs/stripe/payout.php index baa4497f4f2..68d3a759bf5 100644 --- a/htdocs/stripe/payout.php +++ b/htdocs/stripe/payout.php @@ -26,14 +26,18 @@ require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('compta', 'salaries', 'bills', 'hrm', 'stripe')); // Security check $socid = GETPOST("socid", "int"); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} //$result = restrictedArea($user, 'salaries', '', '', ''); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; @@ -41,7 +45,9 @@ $rowid = GETPOST("rowid", 'alpha'); $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; @@ -110,15 +116,13 @@ if (!$rowid) { print "</tr>\n"; try { - if ($stripeacc) - { + if ($stripeacc) { $payout = \Stripe\Payout::all(array("limit" => $limit), array("stripe_account" => $stripeacc)); } else { $payout = \Stripe\Payout::all(array("limit" => $limit)); } - foreach ($payout->data as $payout) - { + foreach ($payout->data as $payout) { //$charge = $payout; //var_dump($payout); @@ -157,7 +161,9 @@ if (!$rowid) { print '<tr class="oddeven">'; // Ref - if (!empty($stripeacc)) $connect = $stripeacc.'/'; + if (!empty($stripeacc)) { + $connect = $stripeacc.'/'; + } $url = 'https://dashboard.stripe.com/'.$connect.'test/payouts/'.$payout->id; if ($servicestatus) { diff --git a/htdocs/stripe/transaction.php b/htdocs/stripe/transaction.php index 60e09c5d743..cde14647061 100644 --- a/htdocs/stripe/transaction.php +++ b/htdocs/stripe/transaction.php @@ -1,6 +1,6 @@ <?php /* Copyright (C) 2018-2019 Thibault FOUCART <support@ptibogxiv.net> - * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -26,14 +26,18 @@ require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('compta', 'salaries', 'bills', 'hrm', 'stripe')); // Security check $socid = GETPOST("socid", "int"); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} //$result = restrictedArea($user, 'salaries', '', '', ''); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; @@ -41,11 +45,13 @@ $rowid = GETPOST("rowid", 'alpha'); $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; - +$optioncss = GETPOST('optioncss', 'alpha'); /* @@ -60,8 +66,7 @@ $stripe = new Stripe($db); llxHeader('', $langs->trans("StripeTransactionList")); -if (!empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha'))) -{ +if (!empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha'))) { $service = 'StripeTest'; $servicestatus = '0'; dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning'); @@ -77,7 +82,9 @@ $stripeacc = $stripe->getStripeAccount($service); if (!$rowid) { print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -106,15 +113,13 @@ if (!$rowid) { print "</tr>\n"; try { - if ($stripeacc) - { + if ($stripeacc) { $txn = \Stripe\BalanceTransaction::all(array("limit" => $limit), array("stripe_account" => $stripeacc)); } else { $txn = \Stripe\BalanceTransaction::all(array("limit" => $limit)); } - foreach ($txn->data as $txn) - { + foreach ($txn->data as $txn) { //$charge = $txn; //var_dump($txn); @@ -153,7 +158,9 @@ if (!$rowid) { print '<tr class="oddeven">'; // Ref - if (!empty($stripeacc)) $connect = $stripeacc.'/'; + if (!empty($stripeacc)) { + $connect = $stripeacc.'/'; + } // Ref if (preg_match('/po_/i', $txn->source)) { @@ -178,12 +185,10 @@ if (!$rowid) { //print "<td>".$charge->customer."</td>\n"; // Link /*print "<td>"; - if ($societestatic->id > 0) - { + if ($societestatic->id > 0) { print $societestatic->getNomUrl(1); } - if ($memberstatic->id > 0) - { + if ($memberstatic->id > 0) { print $memberstatic->getNomUrl(1); } print "</td>\n";*/ diff --git a/htdocs/supplier_proposal/admin/supplier_proposal_extrafields.php b/htdocs/supplier_proposal/admin/supplier_proposal_extrafields.php index 1663ded21ad..035be6ff86d 100644 --- a/htdocs/supplier_proposal/admin/supplier_proposal_extrafields.php +++ b/htdocs/supplier_proposal/admin/supplier_proposal_extrafields.php @@ -31,13 +31,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 = 'supplier_proposal'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -72,8 +76,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create">'.$langs->trans("NewAttribute").'</a></div>'; print "</div>"; @@ -86,8 +89,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print "<br>"; print load_fiche_titre($langs->trans('NewAttribute')); @@ -99,8 +101,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/supplier_proposal/admin/supplier_proposaldet_extrafields.php b/htdocs/supplier_proposal/admin/supplier_proposaldet_extrafields.php index 8e906f2aa57..f4b63f25cd7 100644 --- a/htdocs/supplier_proposal/admin/supplier_proposaldet_extrafields.php +++ b/htdocs/supplier_proposal/admin/supplier_proposaldet_extrafields.php @@ -26,8 +26,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/supplier_proposal.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'supplier_proposal')); @@ -38,14 +39,18 @@ $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 = 'supplier_proposaldet'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -77,8 +82,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -91,8 +95,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -104,8 +107,7 @@ if ($action == 'create') /* Edition d'un champ optionnel */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index 92d38c519de..1b10c92b0dc 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -50,8 +50,9 @@ if (!empty($conf->projet->enabled)) { // Load translation files required by the page $langs->loadLangs(array('companies', 'supplier_proposal', 'compta', 'bills', 'propal', 'orders', 'products', 'deliveries', 'sendings')); -if (!empty($conf->margin->enabled)) +if (!empty($conf->margin->enabled)) { $langs->load('margins'); +} $error = 0; @@ -75,7 +76,9 @@ $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($con $NBLINES = 4; // Security check -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'supplier_proposal', $id); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -90,10 +93,12 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object if ($id > 0 || !empty($ref)) { $ret = $object->fetch($id, $ref); - if ($ret > 0) + if ($ret > 0) { $ret = $object->fetch_thirdparty(); - if ($ret < 0) + } + if ($ret < 0) { dol_print_error('', $object->error); + } } // Common permissions @@ -121,14 +126,13 @@ $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdown $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)) -{ - if ($cancel) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -142,10 +146,8 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes') - { - if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) - { + if ($action == 'confirm_clone' && $confirm == 'yes') { + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { if ($object->id > 0) { @@ -159,11 +161,8 @@ if (empty($reshook)) } } } - } - - // Delete askprice - elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) - { + } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) { + // Delete askprice $result = $object->delete($user); if ($result > 0) { header('Location: '.DOL_URL_ROOT.'/supplier_proposal/list.php'); @@ -172,15 +171,13 @@ if (empty($reshook)) $langs->load("errors"); setEventMessages($langs->trans($object->error), null, '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) + if ($result) { $object->line_order(true); + } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language @@ -196,23 +193,21 @@ 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 $result = $object->valid($user); - if ($result >= 0) - { - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if ($result >= 0) { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -225,18 +220,19 @@ if (empty($reshook)) } } else { $langs->load("errors"); - if (count($object->errors) > 0) setEventMessages($object->error, $object->errors, 'errors'); - else setEventMessages($langs->trans($object->error), null, 'errors'); + if (count($object->errors) > 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } else { + setEventMessages($langs->trans($object->error), null, 'errors'); + } } } elseif ($action == 'setdate_livraison' && $usercancreate) { $result = $object->setDeliveryDate($user, dol_mktime(12, 0, 0, $_POST['liv_month'], $_POST['liv_day'], $_POST['liv_year'])); - if ($result < 0) + if ($result < 0) { dol_print_error($db, $object->error); - } - - // Create supplier proposal - elseif ($action == 'add' && $usercancreate) - { + } + } elseif ($action == 'add' && $usercancreate) { + // Create supplier proposal $object->socid = $socid; $object->fetch_thirdparty(); @@ -248,13 +244,11 @@ if (empty($reshook)) $error++; } - if (!$error) - { + if (!$error) { $db->begin(); // Si on a selectionne une demande a copier, on realise la copie - if (GETPOST('createmode') == 'copy' && GETPOST('copie_supplier_proposal')) - { + if (GETPOST('createmode') == 'copy' && GETPOST('copie_supplier_proposal')) { if ($object->fetch(GETPOST('copie_supplier_proposal')) > 0) { $object->ref = GETPOST('ref'); $object->date_livraison = $date_delivery; // deprecated @@ -294,8 +288,7 @@ if (empty($reshook)) $object->origin_id = GETPOST('originid'); // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); } @@ -307,10 +300,8 @@ if (empty($reshook)) } } - if (!$error) - { - if ($origin && $originid) - { + if (!$error) { + if ($origin && $originid) { $element = 'supplier_proposal'; $subelement = 'supplier_proposal'; @@ -324,8 +315,7 @@ if (empty($reshook)) } $id = $object->create($user); - if ($id > 0) - { + if ($id > 0) { dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); @@ -334,19 +324,16 @@ if (empty($reshook)) dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); $result = $srcobject->fetch($object->origin_id); - if ($result > 0) - { + if ($result > 0) { $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject, 'fetch_lines')) - { + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) { $srcobject->fetch_lines(); $lines = $srcobject->lines; } $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $label = (!empty($lines[$i]->label) ? $lines[$i]->label : ''); $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->libelle); @@ -381,7 +368,8 @@ if (empty($reshook)) $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, - $lines[$i]->pa_ht, $label, + $lines[$i]->pa_ht, + $label, $array_options, $lines[$i]->ref_supplier, $lines[$i]->fk_unit @@ -416,24 +404,25 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); $error++; } - } // Standard creation - else { + } else { + // Standard creation $id = $object->create($user); } - if ($id > 0) - { - if (!$error) - { + if ($id > 0) { + if (!$error) { $db->commit(); // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -442,7 +431,9 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); @@ -458,26 +449,20 @@ 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 == SupplierProposal::STATUS_SIGNED || $object->statut == SupplierProposal::STATUS_NOTSIGNED || $object->statut == SupplierProposal::STATUS_CLOSE) { $object->reopen($user, SupplierProposal::STATUS_VALIDATED); } - } - - // Close proposal - elseif ($action == 'close' && $usercanclose && !GETPOST('cancel', 'alpha')) { + } elseif ($action == 'close' && $usercanclose && !GETPOST('cancel', 'alpha')) { + // Close proposal // prevent browser refresh from reopening proposal several times if ($object->statut == SupplierProposal::STATUS_SIGNED) { $object->setStatut(SupplierProposal::STATUS_CLOSE); } - } - - // Set accepted/refused - elseif ($action == 'setstatut' && $usercanclose && !GETPOST('cancel', 'alpha')) { + } elseif ($action == 'setstatut' && $usercanclose && !GETPOST('cancel', 'alpha')) { + // Set accepted/refused if (!GETPOST('statut')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("CloseAs")), null, 'errors'); $action = 'statut'; @@ -505,12 +490,10 @@ if (empty($reshook)) // Go back to draft - if ($action == 'modif' && $usercancreate) - { + if ($action == 'modif' && $usercancreate) { $object->setDraft($user); - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; if (!empty($conf->global->MAIN_MULTILANGS)) { @@ -521,7 +504,7 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } - } elseif ($action == "setabsolutediscount" && $usercancreate) { + } elseif ($action == "setabsolutediscount" && $usercancreate) { if ($_POST["remise_id"]) { if ($object->id > 0) { $result = $object->insert_discount($_POST["remise_id"]); @@ -533,8 +516,7 @@ if (empty($reshook)) } // Add a product line - if ($action == 'addline' && $usercancreate) - { + if ($action == 'addline' && $usercancreate) { $langs->load('errors'); $error = 0; @@ -547,17 +529,17 @@ if (empty($reshook)) $prod_entry_mode = GETPOST('prod_entry_mode'); if ($prod_entry_mode == 'free') { $idprod = 0; - $price_ht = price2num(GETPOST('price_ht'), 'MU'); + $price_ht = price2num(GETPOST('price_ht'), 'MU', 2); $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); } else { $idprod = GETPOST('idprod', 'int'); - $price_ht = price2num(GETPOST('price_ht'), 'MU'); + $price_ht = price2num(GETPOST('price_ht'), 'MU', 2); $tva_tx = ''; } $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS'); $remise_percent = price2num(GETPOST('remise_percent'.$predef), 2); - $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU'); + $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2); // Extrafields $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -575,8 +557,7 @@ if (empty($reshook)) $error++; } - if ($prod_entry_mode == 'free' && empty($idprod) && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') // Unit price can be 0 but not ''. Also price can be negative for proposal. - { + if ($prod_entry_mode == 'free' && empty($idprod) && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') { // Unit price can be 0 but not ''. Also price can be negative for proposal. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPrice")), null, 'errors'); $error++; } @@ -585,8 +566,8 @@ if (empty($reshook)) $error++; } if (!$error && ($qty >= 0)) { - $pu_ht = price2num($price_ht, 'MU'); - $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); + $pu_ht = price2num($price_ht, 'MU'); + $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); $price_min = 0; $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT'); @@ -595,50 +576,50 @@ if (empty($reshook)) // Ecrase $pu par celui du produit // Ecrase $desc par celui du produit // Ecrase $txtva par celui du produit - if (($prod_entry_mode != 'free') && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' - { + if (($prod_entry_mode != 'free') && empty($error)) { // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' $productsupplier = new ProductFournisseur($db); $idprod = 0; - if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') { + $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + } $reg = array(); - if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) - { + if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) { $idprod = $reg[1]; $res = $productsupplier->fetch($idprod); // Load product from its ID // Call to init some price properties of $productsupplier // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price - if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) - { + if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) { $fksoctosearch = 0; $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist - if ($productsupplier->fourn_socid != $socid) // The price we found is for another supplier, so we clear supplier price - { + if ($productsupplier->fourn_socid != $socid) { // The price we found is for another supplier, so we clear supplier price $productsupplier->ref_supplier = ''; } } else { $fksoctosearch = $object->thirdparty->id; $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist } - } elseif (GETPOST('idprodfournprice', 'alpha') > 0) - { + } elseif (GETPOST('idprodfournprice', 'alpha') > 0) { //$qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat. $qtytosearch = -1; // We force qty to -1 to be sure to find if the supplier price that exists $idprod = $productsupplier->get_buyprice(GETPOST('idprodfournprice', 'alpha'), $qtytosearch); $res = $productsupplier->fetch($idprod); } - if ($idprod > 0) - { + if ($idprod > 0) { $label = $productsupplier->label; // if we use supplier description of the products if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) { $desc = $productsupplier->desc_supplier; - } else $desc = $productsupplier->description; + } else { + $desc = $productsupplier->description; + } - if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + if (trim($product_desc) != trim($desc)) { + $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + } $type = $productsupplier->type; $price_base_type = ($productsupplier->fourn_price_base_type ? $productsupplier->fourn_price_base_type : 'HT'); @@ -647,11 +628,15 @@ if (empty($reshook)) $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha')); $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha')); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); - if (empty($pu_ht)) $pu_ht = 0; // If pu is '' or null, we force to have a numeric value + if (empty($pu_ht)) { + $pu_ht = 0; // If pu is '' or null, we force to have a numeric value + } // If GETPOST('idprodfournprice') is a numeric, we can use it. If it is empty or if it is 'idprod_123', we should use -1 (not used) $fournprice = (is_numeric(GETPOST('idprodfournprice', 'alpha')) ? GETPOST('idprodfournprice', 'alpha') : -1); @@ -688,28 +673,24 @@ if (empty($reshook)) ); //var_dump($tva_tx);var_dump($productsupplier->fourn_pu);var_dump($price_base_type);exit; - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } } - if ($idprod == -99 || $idprod == 0) - { + if ($idprod == -99 || $idprod == 0) { // Product not selected $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")).' '.$langs->trans("or").' '.$langs->trans("NoPriceDefinedForThisSupplier"), null, 'errors'); } - if ($idprod == -1) - { + if ($idprod == -1) { // Quantity too low $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); } - } elseif ((GETPOST('price_ht') !== '' || GETPOST('price_ttc') !== '' || GETPOST('multicurrency_price_ht') != '') && empty($error)) // Free product. // $price_ht is already set - { + } elseif ((GETPOST('price_ht') !== '' || GETPOST('price_ttc') !== '' || GETPOST('multicurrency_price_ht') != '') && empty($error)) { // Free product. // $price_ht is already set $pu_ht = price2num($price_ht, 'MU'); $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); @@ -720,14 +701,15 @@ if (empty($reshook)) $fk_unit = GETPOST('units', 'alpha'); - $tva_tx = price2num($tva_tx); // When vat is text input field + if (!preg_match('/\((.*)\)/', $tva_tx)) { + $tva_tx = price2num($tva_tx); // When vat is text input field + } // Local Taxes $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); - if ($price_ht !== '') - { + if ($price_ht !== '') { $pu_ht = price2num($price_ht, 'MU'); // $pu_ht must be rounded according to settings } else { $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); @@ -760,23 +742,26 @@ if (empty($reshook)) $fk_unit, '', // origin 0, // origin_id - $pu_ht_devise); + $pu_ht_devise + ); } - if (!$error && $result > 0) - { + if (!$error && $result > 0) { $db->commit(); $ret = $object->fetch($object->id); // Reload to get new records // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -785,7 +770,9 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } unset($_POST['prod_entry_mode']); @@ -830,16 +817,15 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // Mise a jour d'une ligne dans la demande de prix - elseif ($action == 'updateline' && $usercancreate && GETPOST('save') == $langs->trans("Save")) { + } elseif ($action == 'updateline' && $usercancreate && GETPOST('save') == $langs->trans("Save")) { + // Mise a jour d'une ligne dans la demande de prix $vat_rate = (GETPOST('tva_tx') ?GETPOST('tva_tx') : 0); // Define info_bits $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) + if (preg_match('/\*/', $vat_rate)) { $info_bits |= 0x01; + } // Clean parameters $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml')); @@ -849,22 +835,19 @@ if (empty($reshook)) $localtax1_rate = get_localtax($vat_rate, 1, $mysoc, $object->thirdparty); $localtax2_rate = get_localtax($vat_rate, 2, $mysoc, $object->thirdparty); - if (GETPOST('price_ht') != '') - { - $ht = price2num(GETPOST('price_ht')); + if (GETPOST('price_ht') != '') { + $ht = price2num(GETPOST('price_ht'), '', 2); } - if (GETPOST('price_ttc') != '') - { + if (GETPOST('price_ttc') != '') { $reg = array(); $vatratecleaned = $vat_rate; - if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) // If vat is "xx (yy)" - { + if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) { // If vat is "xx (yy)" $vatratecleaned = trim($reg[1]); $vatratecode = $reg[2]; } - $ttc = price2num(GETPOST('price_ttc')); + $ttc = price2num(GETPOST('price_ttc'), '', 2); $ht = $ttc / (1 + ($vatratecleaned / 100)); } @@ -887,16 +870,16 @@ if (empty($reshook)) // Define special_code for special lines $special_code = GETPOST('special_code'); - if (!GETPOST('qty')) $special_code = 3; + if (!GETPOST('qty')) { + $special_code = 3; + } // Check minimum price $productid = GETPOST('productid', 'int'); if (!empty($productid)) { $productsupplier = new ProductFournisseur($db); - if (!empty($conf->global->SUPPLIER_PROPOSAL_WITH_PREDEFINED_PRICES_ONLY)) - { - if ($productid > 0 && $productsupplier->get_buyprice(0, price2num($_POST['qty']), $productid, 'none', GETPOST('socid', 'int')) < 0) - { + if (!empty($conf->global->SUPPLIER_PROPOSAL_WITH_PREDEFINED_PRICES_ONLY)) { + if ($productid > 0 && $productsupplier->get_buyprice(0, price2num($_POST['qty']), $productid, 'none', GETPOST('socid', 'int')) < 0) { setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings'); } } @@ -907,8 +890,9 @@ if (empty($reshook)) $type = $product->type; $price_min = $product->price_min; - if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) + if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) { $price_min = $product->multiprices_min [$object->thirdparty->price_level]; + } $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); } else { @@ -999,61 +983,51 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } } - } elseif ($action == 'updateline' && $usercancreate && GETPOST('cancel', 'alpha') == $langs->trans("Cancel")) { + } elseif ($action == 'updateline' && $usercancreate && GETPOST('cancel', 'alpha') == $langs->trans("Cancel")) { header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); // Pour reaffichage de la fiche en cours d'edition exit(); - } - - // Set project - elseif ($action == 'classin' && $usercancreate) { + } elseif ($action == 'classin' && $usercancreate) { + // Set project $object->setProject(GETPOST('projectid'), 'int'); - } - - // Delivery delay - elseif ($action == 'setavailability' && $usercancreate) { + } elseif ($action == 'setavailability' && $usercancreate) { + // Delivery delay $result = $object->availability($_POST['availability_id']); - } - - // Terms of payments - elseif ($action == 'setconditions' && $usercancreate) { + } elseif ($action == 'setconditions' && $usercancreate) { + // Terms of payments $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); } elseif ($action == 'setremisepercent' && $usercancreate) { $result = $object->set_remise_percent($user, price2num(GETPOST('remise_percent'), 2)); } elseif ($action == 'setremiseabsolue' && $usercancreate) { $result = $object->set_remise_absolue($user, price2num(GETPOST('remise_absolue'), 'MU')); - } - - // Payment mode - elseif ($action == 'setmode' && $usercancreate) { + } elseif ($action == 'setmode' && $usercancreate) { + // Payment mode $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'))); + } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + // Multicurrency rate + $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int')); } elseif ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { $result = $object->insertExtraFields('PROPOSAL_SUPPLIER_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } - if ($error) $action = 'edit_extras'; + if ($error) { + $action = 'edit_extras'; + } } } @@ -1062,31 +1036,34 @@ if (empty($reshook)) * View */ -llxHeader('', $langs->trans('CommRequests'), 'EN:Ask_Price_Supplier|FR:Demande_de_prix_fournisseur'); +$help_url = 'EN:Ask_Price_Supplier|FR:Demande_de_prix_fournisseur'; + +llxHeader('', $langs->trans('CommRequests'), $help_url); $form = new Form($db); $formother = new FormOther($db); $formfile = new FormFile($db); $formmargin = new FormMargin($db); $companystatic = new Societe($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $now = dol_now(); // Add new askprice -if ($action == 'create') -{ +if ($action == 'create') { $currency_code = $conf->currency; print load_fiche_titre($langs->trans("NewAskPrice"), '', 'supplier_proposal'); $soc = new Societe($db); - if ($socid > 0) + if ($socid > 0) { $res = $soc->fetch($socid); + } // Load objectsrc - if (!empty($origin) && !empty($originid)) - { + if (!empty($origin) && !empty($originid)) { $element = 'supplier_proposal'; $subelement = 'supplier_proposal'; @@ -1095,8 +1072,7 @@ if ($action == 'create') $classname = ucfirst($subelement); $objectsrc = new $classname($db); $objectsrc->fetch($originid); - if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) - { + if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) { $objectsrc->fetch_lines(); } $objectsrc->fetch_thirdparty(); @@ -1113,15 +1089,20 @@ if ($action == 'create') $objectsrc->fetch_optionals(); $object->array_options = $objectsrc->array_options; - if (!empty($conf->multicurrency->enabled)) - { - if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code; - if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; + if (!empty($conf->multicurrency->enabled)) { + if (!empty($objectsrc->multicurrency_code)) { + $currency_code = $objectsrc->multicurrency_code; + } + if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) { + $currency_tx = $objectsrc->multicurrency_tx; + } } } else { $cond_reglement_id = $soc->cond_reglement_supplier_id; $mode_reglement_id = $soc->mode_reglement_supplier_id; - if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; + if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) { + $currency_code = $soc->multicurrency_code; + } } $object = new SupplierProposal($db); @@ -1157,8 +1138,7 @@ if ($action == 'create') } print '</tr>'."\n"; - if ($soc->id > 0) - { + if ($soc->id > 0) { // Discounts for third party print '<tr><td>'.$langs->trans('Discounts').'</td><td>'; @@ -1222,13 +1202,14 @@ if ($action == 'create') print "</td></tr>"; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $formproject = new FormProjets($db); - if ($origin == 'project') $projectid = ($originid ? $originid : 0); + if ($origin == 'project') { + $projectid = ($originid ? $originid : 0); + } print '<tr>'; print '<td>'.$langs->trans("Project").'</td><td colspan="2">'; @@ -1258,8 +1239,7 @@ if ($action == 'create') // Lines from source - if (!empty($origin) && !empty($originid) && is_object($objectsrc)) - { + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) { // TODO for compatibility if ($origin == 'contrat') { // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva @@ -1270,28 +1250,25 @@ if ($action == 'create') print "\n<!-- ".$classname." info -->"; print "\n"; - print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n"; - print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n"; - print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n"; - print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">'; - print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">'; + print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n"; + print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n"; + print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n"; + print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">'; + print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">'; print '<tr><td>'.$langs->trans('CommRequest').'</td><td colspan="2">'.$objectsrc->getNomUrl(1).'</td></tr>'; print '<tr><td>'.$langs->trans('AmountHT').'</td><td colspan="2">'.price($objectsrc->total_ht).'</td></tr>'; print '<tr><td>'.$langs->trans('AmountVAT').'</td><td colspan="2">'.price($objectsrc->total_tva)."</td></tr>"; - if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 - { + if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax1)."</td></tr>"; } - if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 - { + if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax2)."</td></tr>"; } print '<tr><td>'.$langs->trans('AmountTTC').'</td><td colspan="2">'.price($objectsrc->total_ttc)."</td></tr>"; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_ht).'</td></tr>'; print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_tva)."</td></tr>"; print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_ttc)."</td></tr>"; @@ -1303,12 +1280,13 @@ if ($action == 'create') /* * Combobox pour la fonction de copie - */ + */ - if (empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) print '<input type="hidden" name="createmode" value="empty">'; + if (empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) { + print '<input type="hidden" name="createmode" value="empty">'; + } - if (!empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) - { + if (!empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) { print '<br><table>'; // For backward compatibility @@ -1347,7 +1325,9 @@ if ($action == 'create') print '<td valign="top" colspan="2">'.$langs->trans("CreateEmptyAsk").'</td></tr>'; } - if (!empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) print '</table>'; + if (!empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) { + print '</table>'; + } print dol_get_fiche_end(); @@ -1390,32 +1370,29 @@ if ($action == 'create') if ($action == 'clone') { // Create an array for form $formquestion = array( - // 'text' => $langs->trans("ConfirmClone"), - // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), - // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => - // 1), - array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', 's.fournisseur=1'))); + // 'text' => $langs->trans("ConfirmClone"), + // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), + // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => + // 1), + array( + 'type' => 'other', + 'name' => 'socid', + 'label' => $langs->trans("SelectThirdParty"), + 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', 's.fournisseur=1')) + ); // Paiement incomplet. On demande si motif = escompte ou autre $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneAsk', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); - } - - // Confirm delete - elseif ($action == 'delete') { + } elseif ($action == 'delete') { + // Confirm delete $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteAsk'), $langs->trans('ConfirmDeleteAsk', $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('ConfirmReOpenAsk', $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 askprice - elseif ($action == 'validate') { + } elseif ($action == 'validate') { + // Confirm validate askprice $error = 0; // on verifie si l'objet est en numerotation provisoire @@ -1438,15 +1415,19 @@ if ($action == 'create') $text .= $notify->confirmMessage('PROPOSAL_SUPPLIER_VALIDATE', $object->socid, $object); } - if (!$error) + if (!$error) { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateAsk'), $text, 'confirm_validate', '', 0, 1); + } } // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -1462,14 +1443,14 @@ if ($action == 'create') //$morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreateorder, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/supplier_proposal/list.php?socid='.$object->thirdparty->id.'&search_societe='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherProposals").'</a>)'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/supplier_proposal/list.php?socid='.$object->thirdparty->id.'&search_societe='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherProposals").'</a>)'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($usercancreate) - { + if ($usercancreate) { if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; } @@ -1536,10 +1517,11 @@ if ($action == 'create') print '<table class="nobordernopadding" width="100%"><tr><td>'; print $langs->trans('PaymentConditionsShort'); print '</td>'; - if ($action != 'editconditions' && $object->statut != SupplierProposal::STATUS_NOTSIGNED) + if ($action != 'editconditions' && $object->statut != SupplierProposal::STATUS_NOTSIGNED) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetConditions'), 1).'</a></td>'; + } print '</tr></table>'; - print '</td><td colspan="3">'; + print '</td><td class="valuefield">'; if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id', 1); } else { @@ -1554,10 +1536,11 @@ if ($action == 'create') print '<table class="nobordernopadding" width="100%"><tr><td>'; print $langs->trans('DeliveryDate'); print '</td>'; - if ($action != 'editdate_livraison' && $object->statut == SupplierProposal::STATUS_VALIDATED) + if ($action != 'editdate_livraison' && $object->statut == SupplierProposal::STATUS_VALIDATED) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_livraison&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetDeliveryDate'), 1).'</a></td>'; + } print '</tr></table>'; - print '</td><td colspan="3">'; + print '</td><td class="valuefield">'; if ($action == 'editdate_livraison') { print '<form name="editdate_livraison" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post" class="formconsumeproduce">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -1577,10 +1560,11 @@ if ($action == 'create') print '<table class="nobordernopadding" width="100%"><tr><td>'; print $langs->trans('PaymentMode'); print '</td>'; - if ($action != 'editmode' && $object->statut != SupplierProposal::STATUS_NOTSIGNED) + if ($action != 'editmode' && $object->statut != SupplierProposal::STATUS_NOTSIGNED) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMode'), 1).'</a></td>'; + } print '</tr></table>'; - print '</td><td colspan="3">'; + print '</td><td class="valuefield">'; if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'DBIT', 1, 1); } else { @@ -1589,18 +1573,18 @@ if ($action == 'create') print '</td></tr>'; // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print '<tr>'; print '<td>'; print '<table class="nobordernopadding" width="100%"><tr><td>'; print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0); print '</td>'; - if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_VALIDATED) + if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_VALIDATED) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencycode&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>'; + } print '</tr></table>'; - print '</td><td colspan="3">'; + print '</td><td class="valuefield">'; if ($action == 'editmulticurrencycode') { $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code'); } else { @@ -1609,20 +1593,20 @@ if ($action == 'create') print '</td></tr>'; // Multicurrency rate - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { print '<tr>'; print '<td>'; print '<table class="nobordernopadding" width="100%"><tr><td>'; print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0); print '</td>'; - if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_VALIDATED && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) + if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_VALIDATED && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencyrate&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>'; + } print '</tr></table>'; - print '</td><td colspan="3">'; + print '</td><td class="valuefield">'; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { if ($action == 'actualizemulticurrencyrate') { - list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); + list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); } $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { @@ -1643,7 +1627,7 @@ if ($action == 'create') // Outstanding Bill print '<tr><td>'; print $langs->trans('OutstandingBill'); - print '</td><td class=right colspan="3">'; + print '</td><td class="valuefield">'; $arrayoutstandingbills = $soc->getOutstandingBills('supplier'); $outstandingBills = $arrayoutstandingbills['opened']; print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency); @@ -1651,17 +1635,17 @@ if ($action == 'create') print '</tr>'; }*/ - if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && !empty($conf->banque->enabled)) - { + if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && !empty($conf->banque->enabled)) { // Bank Account print '<tr><td>'; print '<table width="100%" class="nobordernopadding"><tr><td>'; print $langs->trans('BankAccount'); print '</td>'; - if ($action != 'editbankaccount' && $usercancreate) + if ($action != 'editbankaccount' && $usercancreate) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'</a></td>'; + } print '</tr></table>'; - print '</td><td colspan="3">'; + print '</td><td class="valuefield">'; if ($action == 'editbankaccount') { $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); } else { @@ -1672,7 +1656,6 @@ if ($action == 'create') } // Other attributes - $cols = 2; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '</table>'; @@ -1684,51 +1667,48 @@ if ($action == 'create') print '<table class="border tableforfield centpercent">'; - if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) - { + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { // Multicurrency Amount HT print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>'; - print '<td>'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>'; + print '<td class="valuefield">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>'; print '</tr>'; // Multicurrency Amount VAT print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).'</td>'; - print '<td>'.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>'; + print '<td class="valuefield">'.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>'; print '</tr>'; // Multicurrency Amount TTC print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).'</td>'; - print '<td>'.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>'; + print '<td class="valuefield">'.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>'; print '</tr>'; } // Amount HT print '<tr><td class="titlefieldmiddle">'.$langs->trans('AmountHT').'</td>'; - print '<td>'.price($object->total_ht, '', $langs, 0, - 1, - 1, $conf->currency).'</td>'; + print '<td class="valuefield">'.price($object->total_ht, '', $langs, 0, - 1, - 1, $conf->currency).'</td>'; print '</tr>'; // Amount VAT print '<tr><td>'.$langs->trans('AmountVAT').'</td>'; - print '<td>'.price($object->total_tva, '', $langs, 0, - 1, - 1, $conf->currency).'</td>'; + print '<td class="valuefield">'.price($object->total_tva, '', $langs, 0, - 1, - 1, $conf->currency).'</td>'; print '</tr>'; // Amount Local Taxes - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) // Localtax1 - { + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { // Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>'; - print '<td class="nowrap">'.price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency).'</td>'; + print '<td class="valuefield nowrap">'.price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency).'</td>'; print '</tr>'; } - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) // Localtax2 - { + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { // Localtax2 print '<tr><td height="10">'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>'; - print '<td class="nowrap">'.price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency).'</td>'; + print '<td class="valuefield nowrap">'.price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency).'</td>'; print '</tr>'; } // Amount TTC print '<tr><td height="10">'.$langs->trans('AmountTTC').'</td>'; - print '<td class="nowrap">'.price($object->total_ttc, '', $langs, 0, - 1, - 1, $conf->currency).'</td>'; + print '<td class="valuefield nowrap">'.price($object->total_ttc, '', $langs, 0, - 1, - 1, $conf->currency).'</td>'; print '</tr>'; print '</table>'; @@ -1781,16 +1761,17 @@ if ($action == 'create') global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax; $forceall = 1; $dateSelector = 0; $inputalsopricewithtax = 1; $senderissupplier = 2; // $senderissupplier=2 is same than 1 but disable test on minimum qty. - if (!empty($conf->global->SUPPLIER_PROPOSAL_WITH_PREDEFINED_PRICES_ONLY)) $senderissupplier = 1; + if (!empty($conf->global->SUPPLIER_PROPOSAL_WITH_PREDEFINED_PRICES_ONLY)) { + $senderissupplier = 1; + } - if (!empty($object->lines)) + if (!empty($object->lines)) { $ret = $object->printObjectLines($action, $soc, $mysoc, $lineid, $dateSelector); + } // Form to add new line - if ($object->statut == SupplierProposal::STATUS_DRAFT && $usercancreate) - { - if ($action != 'editline') - { + if ($object->statut == SupplierProposal::STATUS_DRAFT && $usercancreate) { + if ($action != 'editline') { // Add products/services form $object->formAddObjectLine($dateSelector, $soc, $mysoc); @@ -1805,31 +1786,33 @@ if ($action == 'create') print dol_get_fiche_end(); - if ($action == 'statut') - { + if ($action == 'statut') { // Form to set proposal accepted/refused - $form_close = '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST" id="formacceptrefuse" class="formconsumeproduce">'; + $form_close = '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST" id="formacceptrefuse" class="formconsumeproduce paddingbottom paddingleft paddingright">'; $form_close .= '<input type="hidden" name="token" value="'.newToken().'">'; $form_close .= '<input type="hidden" name="action" value="setstatut">'; - if (!empty($conf->global->SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL)) $form_close .= '<p class="notice">'.$langs->trans('SupplierProposalRefFournNotice').'</p>'; // TODO Suggest a permanent checkbox instead of option - $form_close .= '<table class="border centpercent">'; - $form_close .= '<tr><td width="150" class="left">'.$langs->trans("CloseAs").'</td><td class="left">'; + if (!empty($conf->global->SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL)) { + $form_close .= '<p class="notice">'.$langs->trans('SupplierProposalRefFournNotice').'</p>'; // TODO Suggest a permanent checkbox instead of option + } + $form_close .= '<table class="border centpercent marginleftonly marginrightonly">'; + $form_close .= '<tr><td>'.$langs->trans("CloseAs").'</td><td class="left">'; $form_close .= '<select id="statut" name="statut" class="flat">'; $form_close .= '<option value="0">&nbsp;</option>'; $form_close .= '<option value="2">'.$langs->trans('SupplierProposalStatusSigned').'</option>'; $form_close .= '<option value="3">'.$langs->trans('SupplierProposalStatusNotSigned').'</option>'; $form_close .= '</select>'; $form_close .= '</td></tr>'; - $form_close .= '<tr><td width="150" class="left">'.$langs->trans('Note').'</td><td class="left"><textarea cols="70" rows="'.ROWS_3.'" wrap="soft" name="note">'; - $form_close .= $object->note; + $form_close .= '<tr><td class="left">'.$langs->trans('Note').'</td><td class="left"><textarea cols="70" rows="'.ROWS_3.'" wrap="soft" name="note">'; + $form_close .= $object->note_private; $form_close .= '</textarea></td></tr>'; - $form_close .= '<tr><td class="center" colspan="2">'; + $form_close .= '</table>'; + $form_close .= '<center>'; $form_close .= '<input type="submit" class="button button-save" name="validate" value="'.$langs->trans("Save").'">'; $form_close .= ' &nbsp; <input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; $form_close .= '<a name="acceptedrefused">&nbsp;</a>'; - $form_close .= '</td>'; - $form_close .= '</tr></table></form>'; + $form_close .= '</center>'; + $form_close .= '</form>'; print $form_close; } @@ -1843,15 +1826,13 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { - if ($action != 'statut' && $action != 'editline') - { + if (empty($reshook)) { + if ($action != 'statut' && $action != 'editline') { // Validate - if ($object->statut == SupplierProposal::STATUS_DRAFT && $object->total_ttc >= 0 && count($object->lines) > 0 && $usercanvalidate) - { - if (count($object->lines) > 0) + if ($object->statut == SupplierProposal::STATUS_DRAFT && $object->total_ttc >= 0 && count($object->lines) > 0 && $usercanvalidate) { + if (count($object->lines) > 0) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=validate">'.$langs->trans('Validate').'</a></div>'; + } // else print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans('Validate').'</a>'; } @@ -1871,7 +1852,9 @@ if ($action == 'create') if ($object->statut == SupplierProposal::STATUS_VALIDATED || $object->statut == SupplierProposal::STATUS_SIGNED) { if ($usercansend) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>'; - } else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('SendMail').'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('SendMail').'</a></div>'; + } } } @@ -1910,12 +1893,11 @@ if ($action == 'create') print '</div>'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; /* - * Documents generes + * Generated documents */ $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->supplier_proposal->dir_output."/".dol_sanitizeFileName($object->ref); diff --git a/htdocs/supplier_proposal/class/api_supplier_proposals.class.php b/htdocs/supplier_proposal/class/api_supplier_proposals.class.php index bf91be32d8d..953f1d274fe 100644 --- a/htdocs/supplier_proposal/class/api_supplier_proposals.class.php +++ b/htdocs/supplier_proposal/class/api_supplier_proposals.class.php @@ -33,7 +33,7 @@ class Supplierproposals extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'socid' ); @@ -105,28 +105,37 @@ class Supplierproposals extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= ' WHERE t.entity IN ('.getEntity('propal').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -135,8 +144,7 @@ class Supplierproposals extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -146,13 +154,11 @@ class Supplierproposals extends DolibarrApi $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $propal_static = new SupplierProposal($this->db); if ($propal_static->fetch($obj->rowid)) { @@ -181,8 +187,9 @@ class Supplierproposals extends DolibarrApi { $propal = array(); foreach (SupplierProposals::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $propal[$field] = $data[$field]; } return $propal; diff --git a/htdocs/supplier_proposal/class/supplier_proposal.class.php b/htdocs/supplier_proposal/class/supplier_proposal.class.php index 405c34734f3..78b1df5f6a4 100644 --- a/htdocs/supplier_proposal/class/supplier_proposal.class.php +++ b/htdocs/supplier_proposal/class/supplier_proposal.class.php @@ -254,11 +254,12 @@ class SupplierProposal extends CommonObject // phpcs:enable global $conf, $mysoc; - if (!$qty) $qty = 1; + if (!$qty) { + $qty = 1; + } dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent"); - if ($idproduct > 0) - { + if ($idproduct > 0) { $prod = new Product($this->db); $prod->fetch($idproduct); @@ -266,13 +267,14 @@ class SupplierProposal extends CommonObject $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id); $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $this->thirdparty, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $this->thirdparty, $tva_npr); // multiprix - if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) - { + if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) { $price = $prod->multiprices[$this->thirdparty->price_level]; } else { $price = $prod->price; @@ -311,10 +313,8 @@ class SupplierProposal extends CommonObject $remise = new DiscountAbsolute($this->db); $result = $remise->fetch($idremise); - if ($result > 0) - { - if ($remise->fk_facture) // Protection against multiple submission - { + if ($result > 0) { + if ($remise->fk_facture) { // Protection against multiple submission $this->error = $langs->trans("ErrorDiscountAlreadyUsed"); $this->db->rollback(); return -5; @@ -338,11 +338,9 @@ class SupplierProposal extends CommonObject $supplier_proposalligne->total_ttc = -$remise->amount_ttc; $result = $supplier_proposalligne->insert(); - if ($result > 0) - { + if ($result > 0) { $result = $this->update_price(1); - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return 1; } else { @@ -405,12 +403,24 @@ class SupplierProposal extends CommonObject include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - if (empty($remise_percent)) $remise_percent = 0; - if (empty($qty)) $qty = 0; - if (empty($info_bits)) $info_bits = 0; - if (empty($rang)) $rang = 0; - if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0; - if (empty($pu_ht)) $pu_ht = 0; + if (empty($remise_percent)) { + $remise_percent = 0; + } + if (empty($qty)) { + $qty = 0; + } + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($rang)) { + $rang = 0; + } + if (empty($fk_parent_line) || $fk_parent_line < 0) { + $fk_parent_line = 0; + } + if (empty($pu_ht)) { + $pu_ht = 0; + } $remise_percent = price2num($remise_percent); $qty = price2num($qty); @@ -422,29 +432,26 @@ class SupplierProposal extends CommonObject $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); $pa_ht = price2num($pa_ht); - if ($price_base_type == 'HT') - { + if ($price_base_type == 'HT') { $pu = $pu_ht; } else { $pu = $pu_ttc; } // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { $this->db->begin(); - if ($fk_product > 0) - { - if (!empty($conf->global->SUPPLIER_PROPOSAL_WITH_PREDEFINED_PRICES_ONLY)) - { + if ($fk_product > 0) { + if (!empty($conf->global->SUPPLIER_PROPOSAL_WITH_PREDEFINED_PRICES_ONLY)) { // Check quantity is enough dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." fk_fournprice=".$fk_fournprice." qty=".$qty." ref_supplier=".$ref_supplier); $prod = new Product($this->db); - if ($prod->fetch($fk_product) > 0) - { + if ($prod->fetch($fk_product) > 0) { $product_type = $prod->type; $label = $prod->label; $fk_prod_fourn_price = $fk_fournprice; @@ -452,16 +459,15 @@ class SupplierProposal extends CommonObject // We use 'none' instead of $ref_supplier, because fourn_ref may not exists anymore. So we will take the first supplier price ok. // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price. $result = $prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', ($this->fk_soc ? $this->fk_soc : $this->socid)); // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$ref_supplier/$this->fk_soc - if ($result > 0) - { + if ($result > 0) { $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice // is remise percent not keyed but present for the product we add it - if ($remise_percent == 0 && $prod->remise_percent != 0) + if ($remise_percent == 0 && $prod->remise_percent != 0) { $remise_percent = $prod->remise_percent; + } } - if ($result == 0) // If result == 0, we failed to found the supplier reference price - { + if ($result == 0) { // If result == 0, we failed to found the supplier reference price $langs->load("errors"); $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier"); $this->db->rollback(); @@ -470,25 +476,23 @@ class SupplierProposal extends CommonObject //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price return -1; } - if ($result == -1) - { + if ($result == -1) { $langs->load("errors"); $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier"); $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG); return -1; } - if ($result < -1) - { + if ($result < -1) { $this->error = $prod->error; - $this->errors = $prod->errors; + $this->errors = $prod->errors; $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR); return -1; } } else { $this->error = $prod->error; - $this->errors = $prod->errors; + $this->errors = $prod->errors; $this->db->rollback(); return -1; } @@ -507,8 +511,7 @@ class SupplierProposal extends CommonObject // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -533,8 +536,7 @@ class SupplierProposal extends CommonObject // Rang to use $ranktouse = $rang; - if ($ranktouse == -1) - { + if ($ranktouse == -1) { $rangmax = $this->line_max($fk_parent_line); $ranktouse = $rangmax + 1; } @@ -543,8 +545,7 @@ class SupplierProposal extends CommonObject // Anciens indicateurs: $price, $remise (a ne plus utiliser) $price = $pu; $remise = 0; - if ($remise_percent > 0) - { + if ($remise_percent > 0) { $remise = round(($pu * $remise_percent / 100), 2); $price = $pu - $remise; } @@ -605,22 +606,24 @@ class SupplierProposal extends CommonObject $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; // Mise en option de la ligne - if (empty($qty) && empty($special_code)) $this->line->special_code = 3; + if (empty($qty) && empty($special_code)) { + $this->line->special_code = 3; + } if (is_array($array_options) && count($array_options) > 0) { $this->line->array_options = $array_options; } $result = $this->line->insert(); - if ($result > 0) - { + if ($result > 0) { // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) { + $this->line_order(true, 'DESC'); + } // Mise a jour informations denormalisees au niveau de la propale meme $result = $this->update_price(1, 'auto', 0, $this->thirdparty); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return $this->line->id; } else { @@ -631,7 +634,7 @@ class SupplierProposal extends CommonObject } } else { $this->error = $this->line->error; - $this->errors = $this->line->errors; + $this->errors = $this->line->errors; $this->db->rollback(); return -2; } @@ -685,11 +688,14 @@ class SupplierProposal extends CommonObject $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); $pa_ht = price2num($pa_ht); - if (empty($qty) && empty($special_code)) $special_code = 3; // Set option tag - if (!empty($qty) && $special_code == 3) $special_code = 0; // Remove option tag + if (empty($qty) && empty($special_code)) { + $special_code = 3; // Set option tag + } + if (!empty($qty) && $special_code == 3) { + $special_code = 0; // Remove option tag + } - if ($this->statut == 0) - { + if ($this->statut == 0) { $this->db->begin(); // Calcul du total TTC et de la TVA pour la ligne a partir de @@ -702,8 +708,7 @@ class SupplierProposal extends CommonObject // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -738,8 +743,7 @@ class SupplierProposal extends CommonObject $this->line->context = $this->context; // Reorder if fk_parent_line change - if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) - { + if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) { $rangmax = $this->line_max($fk_parent_line); $this->line->rang = $rangmax + 1; } @@ -796,10 +800,11 @@ class SupplierProposal extends CommonObject $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; $result = $this->line->update(); - if ($result > 0) - { + if ($result > 0) { // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) { + $this->line_order(true, 'DESC'); + } $this->update_price(1); @@ -827,15 +832,13 @@ class SupplierProposal extends CommonObject */ public function deleteline($lineid) { - if ($this->statut == 0) - { + if ($this->statut == 0) { $line = new SupplierProposalLine($this->db); // For triggers $line->fetch($lineid); - if ($line->delete() > 0) - { + if ($line->delete() > 0) { $this->update_price(1); return 1; @@ -867,17 +870,14 @@ class SupplierProposal extends CommonObject // Check parameters $result = $this->fetch_thirdparty(); - if ($result < 0) - { + if ($result < 0) { $this->error = "Failed to fetch company"; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -3; } - if (!empty($this->ref)) // We check that ref is not already used - { + if (!empty($this->ref)) { // We check that ref is not already used $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used - if ($result > 0) - { + if ($result > 0) { $this->error = 'ErrorRefAlreadyExists'; dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); $this->db->rollback(); @@ -889,9 +889,10 @@ class SupplierProposal extends CommonObject $delivery_date = empty($this->delivery_date) ? $this->date_livraison : $this->delivery_date; // Multicurrency - if (!empty($this->multicurrency_code)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $now); - if (empty($this->fk_multicurrency)) - { + if (!empty($this->multicurrency_code)) { + list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $now); + } + if (empty($this->fk_multicurrency)) { $this->multicurrency_code = $conf->currency; $this->fk_multicurrency = 0; $this->multicurrency_tx = 1; @@ -906,8 +907,8 @@ class SupplierProposal extends CommonObject $sql .= ", remise"; $sql .= ", remise_percent"; $sql .= ", remise_absolue"; - $sql .= ", tva"; - $sql .= ", total"; + $sql .= ", total_tva"; + $sql .= ", total_ttc"; $sql .= ", datec"; $sql .= ", ref"; $sql .= ", fk_user_author"; @@ -953,36 +954,30 @@ class SupplierProposal extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."supplier_proposal"); - if ($this->id) - { + if ($this->id) { $this->ref = '(PROV'.$this->id.')'; - $sql = 'UPDATE '.MAIN_DB_PREFIX."supplier_proposal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX."supplier_proposal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } - if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects - { + if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) - { - foreach ($this->linked_objects as $origin => $tmp_origin_id) - { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { + if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) { + foreach ($this->linked_objects as $origin => $tmp_origin_id) { + if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { dol_print_error($this->db); $error++; } @@ -992,15 +987,13 @@ class SupplierProposal extends CommonObject } /* - * Insertion du detail des produits dans la base - */ - if (!$error) - { + * Insertion du detail des produits dans la base + */ + if (!$error) { $fk_parent_line = 0; $num = count($this->lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { // Reset fk_parent_line for no child products and special product if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) { $fk_parent_line = 0; @@ -1032,8 +1025,7 @@ class SupplierProposal extends CommonObject $this->lines[$i]->rowid ); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $this->db->error; dol_print_error($this->db); @@ -1046,29 +1038,26 @@ class SupplierProposal extends CommonObject } } - if (!$error) - { + if (!$error) { // Mise a jour infos denormalisees $resql = $this->update_price(1); - if ($resql) - { + if ($resql) { $action = 'update'; // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('PROPOSAL_SUPPLIER_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } else { @@ -1081,8 +1070,7 @@ class SupplierProposal extends CommonObject $error++; } - if (!$error) - { + if (!$error) { $this->db->commit(); dol_syslog(get_class($this)."::create done id=".$this->id); return $this->id; @@ -1114,8 +1102,9 @@ class SupplierProposal extends CommonObject $this->db->begin(); // get extrafields so they will be clone - foreach ($this->lines as $line) + foreach ($this->lines as $line) { $line->fetch_optionals(); + } // Load source object $objFrom = clone $this; @@ -1123,10 +1112,8 @@ class SupplierProposal extends CommonObject $objsoc = new Societe($this->db); // Change socid if needed - if (!empty($fromid) && $fromid != $this->socid) - { - if ($objsoc->fetch($fromid) > 0) - { + if (!empty($fromid) && $fromid != $this->socid) { + if ($objsoc->fetch($fromid) > 0) { $this->socid = $objsoc->id; $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); @@ -1141,8 +1128,7 @@ class SupplierProposal extends CommonObject $this->id = 0; $this->statut = 0; - if (empty($conf->global->SUPPLIER_PROPOSAL_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.".php")) - { + if (empty($conf->global->SUPPLIER_PROPOSAL_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.".php")) { $this->error = 'ErrorSetupNotComplete'; return -1; } @@ -1161,25 +1147,26 @@ class SupplierProposal extends CommonObject // Create clone $this->context['createfromclone'] = 'createfromclone'; $result = $this->create($user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Hook of thirdparty module - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('objFrom'=>$objFrom); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } } } unset($this->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -1200,7 +1187,7 @@ class SupplierProposal extends CommonObject global $conf; $sql = "SELECT p.rowid, p.entity, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc"; - $sql .= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; + $sql .= ", p.total_ttc, p.total_tva, p.localtax1, p.localtax2, p.total_ht"; $sql .= ", p.datec"; $sql .= ", p.date_valid as datev"; $sql .= ", p.date_livraison as delivery_date"; @@ -1221,15 +1208,16 @@ class SupplierProposal extends CommonObject $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid'; $sql .= " WHERE p.fk_statut = c.id"; $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; - if ($ref) $sql .= " AND p.ref='".$ref."'"; - else $sql .= " AND p.rowid=".$rowid; + if ($ref) { + $sql .= " AND p.ref='".$ref."'"; + } else { + $sql .= " AND p.rowid=".$rowid; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $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; @@ -1239,12 +1227,11 @@ class SupplierProposal extends CommonObject $this->remise = $obj->remise; $this->remise_percent = $obj->remise_percent; $this->remise_absolue = $obj->remise_absolue; - $this->total = $obj->total; // TODO deprecated $this->total_ht = $obj->total_ht; - $this->total_tva = $obj->tva; + $this->total_tva = $obj->total_tva; $this->total_localtax1 = $obj->localtax1; $this->total_localtax2 = $obj->localtax2; - $this->total_ttc = $obj->total; + $this->total_ttc = $obj->total_ttc; $this->socid = $obj->fk_soc; $this->fk_project = $obj->fk_project; $this->model_pdf = $obj->model_pdf; @@ -1285,8 +1272,7 @@ class SupplierProposal extends CommonObject $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - if ($obj->fk_statut == 0) - { + if ($obj->fk_statut == 0) { $this->brouillon = 1; } @@ -1310,13 +1296,11 @@ class SupplierProposal extends CommonObject $sql .= " ORDER by d.rang"; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($result); $line = new SupplierProposalLine($this->db); @@ -1412,8 +1396,7 @@ class SupplierProposal extends CommonObject $now = dol_now(); if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->validate_advance))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->validate_advance))) { $this->db->begin(); // Numbering module definition @@ -1421,8 +1404,7 @@ class SupplierProposal extends CommonObject $soc->fetch($this->socid); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($soc); } else { $num = $this->ref; @@ -1436,49 +1418,46 @@ class SupplierProposal extends CommonObject dol_syslog(get_class($this)."::valid", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $error++; } // Trigger calls - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('PROPOSAL_SUPPLIER_VALIDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'supplier_proposal/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'supplier_proposal/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->supplier_proposal->dir_output.'/'.$oldref; $dirdest = $conf->supplier_proposal->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->supplier_proposal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -1531,14 +1510,12 @@ class SupplierProposal extends CommonObject */ public function setDeliveryDate($user, $delivery_date) { - if (!empty($user->rights->supplier_proposal->creer)) - { + if (!empty($user->rights->supplier_proposal->creer)) { $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal "; $sql .= " SET date_livraison = ".($delivery_date != '' ? "'".$this->db->idate($delivery_date)."'" : 'null'); $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->date_livraison = $delivery_date; $this->delivery_date = $delivery_date; return 1; @@ -1563,15 +1540,13 @@ class SupplierProposal extends CommonObject // phpcs:enable $remise = trim($remise) ?trim($remise) : 0; - if (!empty($user->rights->supplier_proposal->creer)) - { + if (!empty($user->rights->supplier_proposal->creer)) { $remise = price2num($remise); $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal SET remise_percent = ".$remise; $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->remise_percent = $remise; $this->update_price(1); return 1; @@ -1596,16 +1571,14 @@ class SupplierProposal extends CommonObject // phpcs:enable $remise = trim($remise) ?trim($remise) : 0; - if (!empty($user->rights->supplier_proposal->creer)) - { + if (!empty($user->rights->supplier_proposal->creer)) { $remise = price2num($remise); $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal "; $sql .= " SET remise_absolue = ".$remise; $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->remise_absolue = $remise; $this->update_price(1); return 1; @@ -1636,7 +1609,9 @@ class SupplierProposal extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; $sql .= " SET fk_statut = ".$this->statut.","; - if (!empty($note)) $sql .= " note_private = '".$this->db->escape($note)."',"; + if (!empty($note)) { + $sql .= " note_private = '".$this->db->escape($note)."',"; + } $sql .= " date_cloture=NULL, fk_user_cloture=NULL"; $sql .= " WHERE rowid = ".$this->id; @@ -1647,24 +1622,21 @@ class SupplierProposal extends CommonObject if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('PROPOSAL_SUPPLIER_REOPEN', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } // Commit or rollback - if ($error) - { - if (!empty($this->errors)) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + if (!empty($this->errors)) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -1701,28 +1673,23 @@ class SupplierProposal extends CommonObject $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED : (empty($this->model_pdf) ? '' : $this->model_pdf); $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_REFUSED'; - if ($status == 2) - { + if ($status == 2) { $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_SIGNED'; $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL : (empty($this->model_pdf) ? '' : $this->model_pdf); - if (!empty($conf->global->SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL)) // TODO This option was not tested correctly. Error if product ref does not exists - { + if (!empty($conf->global->SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL)) { // TODO This option was not tested correctly. Error if product ref does not exists $result = $this->updateOrCreatePriceFournisseur($user); } } - if ($status == 4) - { + if ($status == 4) { $triggerName = 'PROPOSAL_SUPPLIER_CLASSIFY_BILLED'; } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; if (!empty($conf->global->MAIN_MULTILANGS)) { @@ -1736,11 +1703,12 @@ class SupplierProposal extends CommonObject // Call trigger $result = $this->call_trigger($triggerName, $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1766,19 +1734,26 @@ class SupplierProposal extends CommonObject global $conf; dol_syslog(get_class($this)."::updateOrCreatePriceFournisseur", LOG_DEBUG); - foreach ($this->lines as $product) - { - if ($product->subprice <= 0) continue; + foreach ($this->lines as $product) { + if ($product->subprice <= 0) { + continue; + } $productsupplier = new ProductFournisseur($this->db); $multicurrency_tx = 1; $fk_multicurrency = 0; - if (empty($this->thirdparty)) $this->fetch_thirdparty(); + if (empty($this->thirdparty)) { + $this->fetch_thirdparty(); + } $ref_fourn = $product->ref_fourn; - if (empty($ref_fourn)) $ref_fourn = $product->ref_supplier; - if (!empty($conf->multicurrency->enabled) && !empty($product->multicurrency_code)) list($fk_multicurrency, $multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $product->multicurrency_code); + if (empty($ref_fourn)) { + $ref_fourn = $product->ref_supplier; + } + if (!empty($conf->multicurrency->enabled) && !empty($product->multicurrency_code)) { + list($fk_multicurrency, $multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $product->multicurrency_code); + } $productsupplier->id = $product->fk_product; $productsupplier->update_buyprice($product->qty, $product->total_ht, $user, 'HT', $this->thirdparty, '', $ref_fourn, $product->tva_tx, 0, 0, 0, $product->info_bits, '', '', array(), '', $product->multicurrency_total_ht, 'HT', $multicurrency_tx, $product->multicurrency_code, '', '', ''); @@ -1850,14 +1825,18 @@ class SupplierProposal extends CommonObject $values[] = $product->multicurrency_total_ht; $values[] = $multicurrency->rate->rate; } else { - for ($i = 0; $i < 5; $i++) $values[] = 'NULL'; + for ($i = 0; $i < 5; $i++) { + $values[] = 'NULL'; + } } } } $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'product_fournisseur_price '; $sql .= '(datec, fk_product, fk_soc, ref_fourn, price, quantity, unitprice, tva_tx, fk_user'; - if (!empty($conf->multicurrency->enabled) && !empty($product->multicurrency_code)) $sql .= ',fk_multicurrency, multicurrency_code, multicurrency_unitprice, multicurrency_price, multicurrency_tx'; + if (!empty($conf->multicurrency->enabled) && !empty($product->multicurrency_code)) { + $sql .= ',fk_multicurrency, multicurrency_code, multicurrency_unitprice, multicurrency_price, multicurrency_tx'; + } $sql .= ') VALUES ('.implode(',', $values).')'; $resql = $this->db->query($sql); @@ -1882,8 +1861,7 @@ class SupplierProposal extends CommonObject $error = 0; - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { dol_syslog(get_class($this)."::setDraft already draft status", LOG_WARNING); return 0; } @@ -1892,8 +1870,7 @@ class SupplierProposal extends CommonObject $sql .= " SET fk_statut = ".self::STATUS_DRAFT; $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { if (!$error) { $this->oldcopy = clone $this; } @@ -1901,7 +1878,9 @@ class SupplierProposal extends CommonObject if (!$error) { // Call trigger $result = $this->call_trigger('PROPOSAL_SUPPLIER_UNVALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } if (!$error) { @@ -1943,38 +1922,42 @@ class SupplierProposal extends CommonObject $sql = "SELECT s.rowid, s.nom as name, s.client,"; $sql .= " p.rowid as supplier_proposalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; $sql .= " p.datep as dp, p.fin_validite as datelimite"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user"; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as p, ".MAIN_DB_PREFIX."c_propalst as c"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE p.entity IN (".getEntity('supplier_proposal').")"; $sql .= " AND p.fk_soc = s.rowid"; $sql .= " AND p.fk_statut = c.id"; - if (!$user->rights->societe->client->voir && !$socid) //restriction - { + if (!$user->rights->societe->client->voir && !$socid) { //restriction $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } - if ($socid) $sql .= " AND s.rowid = ".$socid; - if ($draft) $sql .= " AND p.fk_statut = 0"; - if ($notcurrentuser > 0) $sql .= " AND p.fk_user_author <> ".$user->id; + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } + if ($draft) { + $sql .= " AND p.fk_statut = 0"; + } + if ($notcurrentuser > 0) { + $sql .= " AND p.fk_user_author <> ".$user->id; + } $sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->plimit($limit, $offset); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); - if ($shortlist == 1) - { + if ($shortlist == 1) { $ga[$obj->supplier_proposalid] = $obj->ref; - } elseif ($shortlist == 2) - { + } elseif ($shortlist == 2) { $ga[$obj->supplier_proposalid] = $obj->ref.' ('.$obj->name.')'; } else { $ga[$i]['id'] = $obj->supplier_proposalid; @@ -2008,57 +1991,51 @@ class SupplierProposal extends CommonObject $this->db->begin(); - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('PROPOSAL_SUPPLIER_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $main = MAIN_DB_PREFIX.'supplier_proposaldet'; $ef = $main."_extrafields"; $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_supplier_proposal = ".$this->id.")"; $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE fk_supplier_proposal = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposal WHERE rowid = ".$this->id; - if ($this->db->query($sqlef) && $this->db->query($sql)) - { + if ($this->db->query($sqlef) && $this->db->query($sql)) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive $this->deleteEcmFiles(); // We remove directory $ref = dol_sanitizeFileName($this->ref); - if ($conf->supplier_proposal->dir_output && !empty($this->ref)) - { + if ($conf->supplier_proposal->dir_output && !empty($this->ref)) { $dir = $conf->supplier_proposal->dir_output."/".$ref; $file = $dir."/".$ref.".pdf"; - if (file_exists($file)) - { + if (file_exists($file)) { dol_delete_preview($this); - if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers - { + if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers $this->error = 'ErrorFailToDeleteFile'; $this->errors = array('ErrorFailToDeleteFile'); $this->db->rollback(); return 0; } } - if (file_exists($dir)) - { + if (file_exists($dir)) { $res = @dol_delete_dir_recursive($dir); - if (!$res) - { + if (!$res) { $this->error = 'ErrorFailToDeleteDir'; $this->errors = array('ErrorFailToDeleteDir'); $this->db->rollback(); @@ -2069,19 +2046,16 @@ class SupplierProposal extends CommonObject } // Removed extrafields - if (!$error) - { + if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; $errorflag = -4; dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR); } } - if (!$error) - { + if (!$error) { dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG); $this->db->commit(); return 1; @@ -2122,10 +2096,8 @@ class SupplierProposal extends CommonObject $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -2138,15 +2110,13 @@ class SupplierProposal extends CommonObject $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; @@ -2183,8 +2153,7 @@ class SupplierProposal extends CommonObject // phpcs:enable // Init/load array of translation of status - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; $langs->load("supplier_proposal"); $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv("SupplierProposalStatusDraft"); @@ -2200,11 +2169,17 @@ class SupplierProposal extends CommonObject } $statusnew = ''; - if ($status == self::STATUS_DRAFT) $statusnew = 'status0'; - elseif ($status == self::STATUS_VALIDATED) $statusnew = 'status1'; - elseif ($status == self::STATUS_SIGNED) $statusnew = 'status4'; - elseif ($status == self::STATUS_NOTSIGNED) $statusnew = 'status9'; - elseif ($status == self::STATUS_CLOSE) $statusnew = 'status6'; + if ($status == self::STATUS_DRAFT) { + $statusnew = 'status0'; + } elseif ($status == self::STATUS_VALIDATED) { + $statusnew = 'status1'; + } elseif ($status == self::STATUS_SIGNED) { + $statusnew = 'status4'; + } elseif ($status == self::STATUS_NOTSIGNED) { + $statusnew = 'status9'; + } elseif ($status == self::STATUS_CLOSE) { + $statusnew = 'status6'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusnew, $mode); } @@ -2230,20 +2205,24 @@ class SupplierProposal extends CommonObject $sql = "SELECT p.rowid, p.ref, p.datec as datec"; $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = " AND"; } $sql .= $clause." p.entity IN (".getEntity('supplier_proposal').")"; - if ($mode == 'opened') $sql .= " AND p.fk_statut = 1"; - if ($mode == 'signed') $sql .= " AND p.fk_statut = 2"; - if ($user->socid) $sql .= " AND p.fk_soc = ".$user->socid; + if ($mode == 'opened') { + $sql .= " AND p.fk_statut = 1"; + } + if ($mode == 'signed') { + $sql .= " AND p.fk_statut = 2"; + } + if ($user->socid) { + $sql .= " AND p.fk_soc = ".$user->socid; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $label = $labelShort = ''; $status = ''; if ($mode == 'opened') { @@ -2267,14 +2246,11 @@ class SupplierProposal extends CommonObject $response->img = img_object('', "propal"); // This assignment in condition is not a bug. It allows walking the results. - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; - if ($mode == 'opened') - { + if ($mode == 'opened') { $datelimit = $this->db->jdate($obj->datefin); - if ($datelimit < ($now - $delay_warning)) - { + if ($datelimit < ($now - $delay_warning)) { $response->nbtodolate++; } } @@ -2309,12 +2285,10 @@ class SupplierProposal extends CommonObject $sql .= $this->db->plimit(100); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -2336,8 +2310,7 @@ class SupplierProposal extends CommonObject // Lines $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new SupplierProposalLine($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; $line->qty = 1; @@ -2345,8 +2318,7 @@ class SupplierProposal extends CommonObject $line->tva_tx = 19.6; $line->localtax1_tx = 0; $line->localtax2_tx = 0; - if ($xnbp == 2) - { + if ($xnbp == 2) { $line->total_ht = 50; $line->total_ttc = 59.8; $line->total_tva = 9.8; @@ -2358,8 +2330,7 @@ class SupplierProposal extends CommonObject $line->remise_percent = 00; } - if ($num_prods > 0) - { + if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; } @@ -2391,8 +2362,7 @@ class SupplierProposal extends CommonObject $sql = "SELECT count(p.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -2400,11 +2370,9 @@ class SupplierProposal extends CommonObject $sql .= " ".$clause." p.entity IN (".getEntity('supplier_proposal').")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // This assignment in condition is not a bug. It allows walking the results. - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["supplier_proposals"] = $obj->nb; } $this->db->free($resql); @@ -2429,8 +2397,7 @@ class SupplierProposal extends CommonObject global $conf, $db, $langs; $langs->load("supplier_proposal"); - if (!empty($conf->global->SUPPLIER_PROPOSAL_ADDON)) - { + if (!empty($conf->global->SUPPLIER_PROPOSAL_ADDON)) { $mybool = false; $file = $conf->global->SUPPLIER_PROPOSAL_ADDON.".php"; @@ -2445,8 +2412,7 @@ class SupplierProposal extends CommonObject $mybool |= @include_once $dir.$file; } - if (!$mybool) - { + if (!$mybool) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -2455,8 +2421,7 @@ class SupplierProposal extends CommonObject $numref = ""; $numref = $obj->getNextValue($soc, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -2484,7 +2449,9 @@ class SupplierProposal extends CommonObject { global $langs, $conf, $user; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $url = ''; $result = ''; @@ -2493,11 +2460,21 @@ class SupplierProposal extends CommonObject if (isset($this->status)) { $label .= ' '.$this->getLibStatut(5); } - if (!empty($this->ref)) $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref; - if (!empty($this->ref_fourn)) $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_fourn; - if (!empty($this->total_ht)) $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_tva)) $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_ttc)) $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->ref)) { + $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref; + } + if (!empty($this->ref_fourn)) { + $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_fourn; + } + if (!empty($this->total_ht)) { + $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); + } + if (!empty($this->total_tva)) { + $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + } + if (!empty($this->total_ttc)) { + $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + } if ($option == '') { $url = DOL_URL_ROOT.'/supplier_proposal/card.php?id='.$this->id.$get_params; @@ -2506,19 +2483,20 @@ class SupplierProposal extends CommonObject $url = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$this->id.$get_params; } - if ($option !== 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip) && $user->rights->propal->lire) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip) && $user->rights->propal->lire) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowSupplierProposal"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -2531,15 +2509,17 @@ class SupplierProposal extends CommonObject $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; - if ($addlinktonotes) - { + if ($addlinktonotes) { $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { + if ($txttoshow) { $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1); $result .= ' <span class="note inline-block">'; $result .= '<a href="'.DOL_URL_ROOT.'/supplier_proposal/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">'; @@ -2577,13 +2557,11 @@ class SupplierProposal extends CommonObject dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $this->lines[$i] = new SupplierProposalLine($this->db); @@ -2784,7 +2762,7 @@ class SupplierProposalLine extends CommonObjectLine // Bit 0: 0 si TVA normal - 1 si TVA NPR // Bit 1: 0 ligne normale - 1 si ligne de remise fixe - public $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne + public $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne public $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne public $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne @@ -2877,8 +2855,7 @@ class SupplierProposalLine extends CommonObjectLine $sql .= ' WHERE pd.rowid = '.$rowid; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $objp = $this->db->fetch_object($result); $this->id = $objp->rowid; @@ -2949,30 +2926,62 @@ class SupplierProposalLine extends CommonObjectLine dol_syslog(get_class($this)."::insert rang=".$this->rang); // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->localtax1_type)) $this->localtax1_type = 0; - if (empty($this->localtax2_type)) $this->localtax2_type = 0; - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; - if (empty($this->rang)) $this->rang = 0; - if (empty($this->remise)) $this->remise = 0; - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->info_bits)) $this->info_bits = 0; - if (empty($this->special_code)) $this->special_code = 0; - if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; - if (empty($this->fk_fournprice)) $this->fk_fournprice = 0; - if (empty($this->fk_unit)) $this->fk_unit = 0; - if (empty($this->subprice)) $this->subprice = 0; + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->localtax1_type)) { + $this->localtax1_type = 0; + } + if (empty($this->localtax2_type)) { + $this->localtax2_type = 0; + } + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } + if (empty($this->rang)) { + $this->rang = 0; + } + if (empty($this->remise)) { + $this->remise = 0; + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->info_bits)) { + $this->info_bits = 0; + } + if (empty($this->special_code)) { + $this->special_code = 0; + } + if (empty($this->fk_parent_line)) { + $this->fk_parent_line = 0; + } + if (empty($this->fk_fournprice)) { + $this->fk_fournprice = 0; + } + if (empty($this->fk_unit)) { + $this->fk_unit = 0; + } + if (empty($this->subprice)) { + $this->subprice = 0; + } - if (empty($this->pa_ht)) $this->pa_ht = 0; + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0) - { - if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) - { + if ($this->pa_ht == 0) { + if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { return $result; } else { $this->pa_ht = $result; @@ -2980,7 +2989,9 @@ class SupplierProposalLine extends CommonObjectLine } // Check parameters - if ($this->product_type < 0) return -1; + if ($this->product_type < 0) { + return -1; + } $this->db->begin(); @@ -3033,25 +3044,20 @@ class SupplierProposalLine extends CommonObjectLine dol_syslog(get_class($this).'::insert', LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'supplier_proposaldet'); - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINESUPPLIER_PROPOSAL_INSERT', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -3081,14 +3087,11 @@ class SupplierProposalLine extends CommonObjectLine $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE rowid = ".$this->id; dol_syslog("SupplierProposalLine::delete", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { // Remove extrafields - if (!$error) - { + if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); } @@ -3096,8 +3099,7 @@ class SupplierProposalLine extends CommonObjectLine // Call trigger $result = $this->call_trigger('LINESUPPLIER_PROPOSAL_DELETE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -3126,30 +3128,62 @@ class SupplierProposalLine extends CommonObjectLine $error = 0; // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; - if (empty($this->localtax1_type)) $this->localtax1_type = 0; - if (empty($this->localtax2_type)) $this->localtax2_type = 0; - if (empty($this->marque_tx)) $this->marque_tx = 0; - if (empty($this->marge_tx)) $this->marge_tx = 0; - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->info_bits)) $this->info_bits = 0; - if (empty($this->special_code)) $this->special_code = 0; - if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; - if (empty($this->fk_fournprice)) $this->fk_fournprice = 0; - if (empty($this->fk_unit)) $this->fk_unit = 0; - if (empty($this->subprice)) $this->subprice = 0; + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } + if (empty($this->localtax1_type)) { + $this->localtax1_type = 0; + } + if (empty($this->localtax2_type)) { + $this->localtax2_type = 0; + } + if (empty($this->marque_tx)) { + $this->marque_tx = 0; + } + if (empty($this->marge_tx)) { + $this->marge_tx = 0; + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->info_bits)) { + $this->info_bits = 0; + } + if (empty($this->special_code)) { + $this->special_code = 0; + } + if (empty($this->fk_parent_line)) { + $this->fk_parent_line = 0; + } + if (empty($this->fk_fournprice)) { + $this->fk_fournprice = 0; + } + if (empty($this->fk_unit)) { + $this->fk_unit = 0; + } + if (empty($this->subprice)) { + $this->subprice = 0; + } - if (empty($this->pa_ht)) $this->pa_ht = 0; + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0) - { - if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) - { + if ($this->pa_ht == 0) { + if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { return $result; } else { $this->pa_ht = $result; @@ -3174,8 +3208,7 @@ class SupplierProposalLine extends CommonObjectLine $sql .= " , subprice=".price2num($this->subprice).""; $sql .= " , remise_percent=".price2num($this->remise_percent).""; $sql .= " , info_bits='".$this->db->escape($this->info_bits)."'"; - if (empty($this->skip_update_total)) - { + if (empty($this->skip_update_total)) { $sql .= " , total_ht=".price2num($this->total_ht).""; $sql .= " , total_tva=".price2num($this->total_tva).""; $sql .= " , total_ttc=".price2num($this->total_ttc).""; @@ -3184,9 +3217,13 @@ class SupplierProposalLine extends CommonObjectLine } $sql .= " , fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null"); $sql .= " , buy_price_ht=".price2num($this->pa_ht); - if (strlen($this->special_code)) $sql .= " , special_code=".$this->special_code; + if (strlen($this->special_code)) { + $sql .= " , special_code=".$this->special_code; + } $sql .= " , fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null"); - if (!empty($this->rang)) $sql .= ", rang=".$this->rang; + if (!empty($this->rang)) { + $sql .= ", rang=".$this->rang; + } $sql .= " , ref_fourn=".(!empty($this->ref_fourn) ? "'".$this->db->escape($this->ref_fourn)."'" : "null"); $sql .= " , fk_unit=".($this->fk_unit ? $this->fk_unit : 'null'); @@ -3200,23 +3237,18 @@ class SupplierProposalLine extends CommonObjectLine dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$error) - { + if ($resql) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINESUPPLIER_PROPOSAL_UPDATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -3254,8 +3286,7 @@ class SupplierProposalLine extends CommonObjectLine dol_syslog("SupplierProposalLine::update_total", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { diff --git a/htdocs/supplier_proposal/contact.php b/htdocs/supplier_proposal/contact.php index ce76b9d8bf7..527ba87cb3e 100644 --- a/htdocs/supplier_proposal/contact.php +++ b/htdocs/supplier_proposal/contact.php @@ -39,7 +39,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'supplier_proposal', $id, 'supplier_proposal', ''); $object = new SupplierProposal($db); @@ -51,50 +53,38 @@ $permissiontoedit = $user->rights->supplier_proposal->creer; * Add a new contact */ -if ($action == 'addcontact' && $permissiontoedit) -{ +if ($action == 'addcontact' && $permissiontoedit) { $result = $object->fetch($id); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); - $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]); + $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } -} - -// Toggle the status of a contact -elseif ($action == 'swapstatut' && $permissiontoedit) -{ - if ($object->fetch($id)) - { +} elseif ($action == 'swapstatut' && $permissiontoedit) { + // Toggle the status of a contact + if ($object->fetch($id)) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { dol_print_error($db); } -} - -// Deleting a contact -elseif ($action == 'deletecontact' && $permissiontoedit) -{ +} elseif ($action == 'deletecontact' && $permissiontoedit) { + // Deleting a contact $object->fetch($id); $result = $object->delete_contact(GETPOST("lineid", 'int')); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -123,12 +113,10 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $langs->trans("SupplierProposal"); - if ($object->fetch($id, $ref) > 0) - { + if ($object->fetch($id, $ref) > 0) { $object->fetch_thirdparty(); $head = supplier_proposal_prepare_head($object); @@ -145,12 +133,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($permissiontoedit) - { + if ($permissiontoedit) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/supplier_proposal/document.php b/htdocs/supplier_proposal/document.php index 127b45466e8..11fb3149aff 100644 --- a/htdocs/supplier_proposal/document.php +++ b/htdocs/supplier_proposal/document.php @@ -45,8 +45,7 @@ $ref = GETPOST('ref', 'alpha'); // Security check $socid = ''; -if (!empty($user->socid)) -{ +if (!empty($user->socid)) { $socid = $user->socid; } $result = restrictedArea($user, 'supplier_proposal', $id); @@ -56,20 +55,25 @@ $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"; +} $object = new SupplierProposal($db); $object->fetch($id, $ref); -if ($object->id > 0) -{ +if ($object->id > 0) { $object->fetch_thirdparty(); $upload_dir = $conf->supplier_proposal->dir_output.'/'.dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; + include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; } @@ -81,8 +85,7 @@ llxHeader('', $langs->trans('CommRequest'), 'EN:Ask_Price_Supplier|FR:Demande_de $form = new Form($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $upload_dir = $conf->supplier_proposal->dir_output.'/'.dol_sanitizeFileName($object->ref); $head = supplier_proposal_prepare_head($object); @@ -91,8 +94,7 @@ if ($object->id > 0) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -108,12 +110,10 @@ if ($object->id > 0) // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->supplier_proposal->creer) - { + if ($user->rights->supplier_proposal->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/supplier_proposal/index.php b/htdocs/supplier_proposal/index.php index 476c2a14db2..0982abe467d 100644 --- a/htdocs/supplier_proposal/index.php +++ b/htdocs/supplier_proposal/index.php @@ -38,8 +38,7 @@ $langs->loadLangs(array('supplier_proposal', 'companies')); // Security check $socid = GETPOST('socid', 'int'); -if (isset($user->socid) && $user->socid > 0) -{ +if (isset($user->socid) && $user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -65,8 +64,7 @@ print '<div class="fichecenter"><div class="fichethirdleft">'; // Search form -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo print '<form method="post" action="'.DOL_URL_ROOT.'/supplier_proposal/list.php">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<div class="div-table-responsive-no-min">'; @@ -84,16 +82,21 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useles $sql = "SELECT count(p.rowid), p.fk_statut"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."supplier_proposal as p"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE p.fk_soc = s.rowid"; $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; -if ($user->socid) $sql .= ' AND p.fk_soc = '.$user->socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($user->socid) { + $sql .= ' AND p.fk_soc = '.$user->socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " AND p.fk_statut IN (0,1,2,3,4)"; $sql .= " GROUP BY p.fk_statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -103,11 +106,9 @@ if ($resql) $colorseries = array(); $vals = array(); // -1=Canceled, 0=Draft, 1=Validated, (2=Accepted/On process not managed for customer orders), 3=Closed (Sent/Received, billed or not) - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); - if ($row) - { + if ($row) { //if ($row[1]!=-1 && ($row[1]!=3 || $row[2]!=1)) { $vals[$row[1]] = $row[0]; @@ -125,25 +126,32 @@ if ($resql) print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("CommRequests").'</th></tr>'."\n"; $listofstatus = array(0, 1, 2, 3, 4); - foreach ($listofstatus as $status) - { + foreach ($listofstatus as $status) { $dataseries[] = array($supplier_proposalstatic->LibStatut($status, 1), (isset($vals[$status]) ? (int) $vals[$status] : 0)); - if ($status == SupplierProposal::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; - if ($status == SupplierProposal::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus1; - if ($status == SupplierProposal::STATUS_SIGNED) $colorseries[$status] = $badgeStatus4; - if ($status == SupplierProposal::STATUS_NOTSIGNED) $colorseries[$status] = $badgeStatus9; - if ($status == SupplierProposal::STATUS_CLOSE) $colorseries[$status] = $badgeStatus6; + if ($status == SupplierProposal::STATUS_DRAFT) { + $colorseries[$status] = '-'.$badgeStatus0; + } + if ($status == SupplierProposal::STATUS_VALIDATED) { + $colorseries[$status] = $badgeStatus1; + } + if ($status == SupplierProposal::STATUS_SIGNED) { + $colorseries[$status] = $badgeStatus4; + } + if ($status == SupplierProposal::STATUS_NOTSIGNED) { + $colorseries[$status] = $badgeStatus9; + } + if ($status == SupplierProposal::STATUS_CLOSE) { + $colorseries[$status] = $badgeStatus6; + } - if (empty($conf->use_javascript_ajax)) - { + if (empty($conf->use_javascript_ajax)) { print '<tr class="oddeven">'; print '<td>'.$supplier_proposalstatic->LibStatut($status, 0).'</td>'; print '<td class="right"><a href="list.php?statut='.$status.'">'.(isset($vals[$status]) ? $vals[$status] : 0).'</a></td>'; print "</tr>\n"; } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<tr><td class="center" colspan="2">'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -170,32 +178,34 @@ if ($resql) /* * Draft askprice */ -if (!empty($conf->supplier_proposal->enabled)) -{ +if (!empty($conf->supplier_proposal->enabled)) { $sql = "SELECT c.rowid, c.ref, s.nom as socname, s.rowid as socid, s.canvas, s.client"; $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity = ".$conf->entity; $sql .= " AND c.fk_statut = 0"; - if ($socid) $sql .= " AND c.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="2">'.$langs->trans("DraftRequests").'</th></tr>'; $langs->load("supplier_proposal"); $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -230,29 +240,32 @@ $sql = "SELECT c.rowid, c.ref, c.fk_statut, s.nom as socname, s.rowid as socid, $sql .= " date_cloture as datec"; $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity = ".$conf->entity; //$sql.= " AND c.fk_statut > 2"; -if ($socid) $sql .= " AND c.fk_soc = ".$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " ORDER BY c.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="4">'.$langs->trans("LastModifiedRequests", $max).'</th></tr>'; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -292,44 +305,48 @@ if ($resql) } } print "</table></div><br>"; -} else dol_print_error($db); +} else { + dol_print_error($db); +} /* * Opened askprice */ -if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) -{ +if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) { $langs->load("supplier_proposal"); $now = dol_now(); - $sql = "SELECT s.nom as socname, s.rowid as socid, s.canvas, s.client, p.rowid as supplier_proposalid, p.total as total_ttc, p.total_ht, p.ref, p.fk_statut, p.datec as dp"; + $sql = "SELECT s.nom as socname, s.rowid as socid, s.canvas, s.client, p.rowid as supplier_proposalid, p.total_ttc, p.total_tva, p.total_ht, p.ref, p.fk_statut, p.datec as dp"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."supplier_proposal as p"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE p.fk_soc = s.rowid"; $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; $sql .= " AND p.fk_statut = 1"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } $sql .= " ORDER BY p.rowid DESC"; $result = $db->query($sql); - if ($result) - { + if ($result) { $total = 0; $num = $db->num_rows($result); $i = 0; - if ($num > 0) - { + if ($num > 0) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><th colspan="5">'.$langs->trans("RequestsOpened").' <a href="'.DOL_URL_ROOT.'/supplier_proposal/list.php?search_status=1"><span class="badge">'.$num.'</span></a></th></tr>'; $nbofloop = min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD) ? 500 : $conf->global->MAIN_MAXLIST_OVERLOAD)); - while ($i < $nbofloop) - { + while ($i < $nbofloop) { $obj = $db->fetch_object($result); print '<tr class="oddeven">'; @@ -345,7 +362,9 @@ if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposa print $supplier_proposalstatic->getNomUrl(1); print '</td>'; print '<td width="18" class="nobordernopadding nowrap">'; - if ($db->jdate($obj->dfv) < ($now - $conf->supplier_proposal->cloture->warning_delay)) print img_warning($langs->trans("Late")); + if ($db->jdate($obj->dfv) < ($now - $conf->supplier_proposal->cloture->warning_delay)) { + print img_warning($langs->trans("Late")); + } print '</td>'; print '<td width="16" class="center nobordernopadding">'; $filename = dol_sanitizeFileName($obj->ref); @@ -370,11 +389,9 @@ if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposa $i++; $total += $obj->total_ttc; } - if ($num > $nbofloop) - { + if ($num > $nbofloop) { print '<tr class="liste_total"><td colspan="5">'.$langs->trans("XMoreLines", ($num - $nbofloop))."</td></tr>"; - } elseif ($total > 0) - { + } elseif ($total > 0) { print '<tr class="liste_total"><td colspan="3">'.$langs->trans("Total").'</td><td class="right">'.price($total)."</td><td>&nbsp;</td></tr>"; } print "</table></div><br>"; diff --git a/htdocs/supplier_proposal/info.php b/htdocs/supplier_proposal/info.php index dbff367b7c8..77268671275 100644 --- a/htdocs/supplier_proposal/info.php +++ b/htdocs/supplier_proposal/info.php @@ -39,7 +39,9 @@ $id = GETPOST('id', 'int'); $socid = GETPOST('socid', 'int'); // Security check -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'supplier_proposal', $id); @@ -72,12 +74,10 @@ $morehtmlref = '<div class="refidno">'; // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->supplier_proposal->creer) - { + if ($user->rights->supplier_proposal->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/supplier_proposal/list.php b/htdocs/supplier_proposal/list.php index 9826c2a409d..3ad210b2f77 100644 --- a/htdocs/supplier_proposal/list.php +++ b/htdocs/supplier_proposal/list.php @@ -40,8 +40,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formpropal.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; -if (!empty($conf->projet->enabled)) +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('companies', 'propal', 'supplier_proposal', 'compta', 'bills', 'orders', 'products')); @@ -89,18 +90,27 @@ $yearvalid = GETPOST("yearvalid"); $monthvalid = GETPOST("monthvalid"); $dayvalid = GETPOST("dayvalid"); +$optioncss = GETPOST('optioncss', 'alpha'); $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 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 'sp.date_livraison'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'sp.date_livraison'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} -if ($object_statut != '') $search_status = $object_statut; +if ($object_statut != '') { + $search_status = $object_statut; +} // Nombre de ligne pour choix de produit/service predefinis $NBLINES = 4; @@ -109,9 +119,10 @@ $NBLINES = 4; $module = 'supplier_proposal'; $dbtable = ''; $objectid = ''; -if (!empty($user->socid)) $socid = $user->socid; -if (!empty($socid)) -{ +if (!empty($user->socid)) { + $socid = $user->socid; +} +if (!empty($socid)) { $objectid = $socid; $module = 'societe'; $dbtable = '&societe'; @@ -138,7 +149,9 @@ $fieldstosearchall = array( 'pd.description'=>'Description', 'sp.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["p.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["p.note_private"] = "NotePrivate"; +} $checkedtypetiers = 0; $arrayfields = array( @@ -152,7 +165,7 @@ $arrayfields = array( 'sp.date_valid'=>array('label'=>$langs->trans("Date"), 'checked'=>1), 'sp.date_livraison'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1), 'sp.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'sp.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'sp.total_tva'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), 'sp.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), 'sp.multicurrency_code'=>array('label'=>'Currency', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), 'sp.multicurrency_tx'=>array('label'=>'CurrencyRate', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), @@ -176,18 +189,23 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $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'); +} include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on 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_categ = ''; $search_user = ''; $search_sale = ''; @@ -219,8 +237,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $object_statut = ''; } -if (empty($reshook)) -{ +if (empty($reshook)) { $objectclass = 'SupplierProposal'; $objectlabel = 'SupplierProposals'; $permissiontoread = $user->rights->supplier_proposal->lire; @@ -249,19 +266,25 @@ $help_url = 'EN:Ask_Price_Supplier|FR:Demande_de_prix_fournisseur'; //llxHeader('',$langs->trans('CommRequest'),$help_url); $sql = 'SELECT'; -if ($sall || $search_product_category > 0 || $search_user > 0) $sql = 'SELECT DISTINCT'; +if ($sall || $search_product_category > 0 || $search_user > 0) { + $sql = 'SELECT DISTINCT'; +} $sql .= ' s.rowid as socid, s.nom as name, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; $sql .= " typent.code as typent_code,"; $sql .= " state.code_departement as state_code, state.nom as state_name,"; -$sql .= ' sp.rowid, sp.note_private, sp.total_ht, sp.tva as total_vat, sp.total as total_ttc, sp.localtax1, sp.localtax2, sp.ref, sp.fk_statut as status, sp.fk_user_author, sp.date_valid, sp.date_livraison as dp,'; +$sql .= ' sp.rowid, sp.note_public, sp.note_private, sp.total_ht, sp.total_tva, sp.total_ttc, sp.localtax1, sp.localtax2, sp.ref, sp.fk_statut as status, sp.fk_user_author, sp.date_valid, sp.date_livraison as dp,'; $sql .= ' sp.fk_multicurrency, sp.multicurrency_code, sp.multicurrency_tx, sp.multicurrency_total_ht, sp.multicurrency_total_tva as multicurrency_total_vat, sp.multicurrency_total_ttc,'; $sql .= ' sp.datec as date_creation, sp.tms as date_update,'; $sql .= " p.rowid as project_id, p.ref as project_ref,"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk_user,"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " sc.fk_soc, sc.fk_user,"; +} $sql .= " u.firstname, u.lastname, u.photo, u.login"; // 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 : ''); + 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(); @@ -272,48 +295,93 @@ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; $sql .= ', '.MAIN_DB_PREFIX.'supplier_proposal as sp'; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (sp.rowid = ef.fk_object)"; -if ($sall || $search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'supplier_proposaldet as pd ON sp.rowid=pd.fk_supplier_proposal'; -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (sp.rowid = ef.fk_object)"; +} +if ($sall || $search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'supplier_proposaldet as pd ON sp.rowid=pd.fk_supplier_proposal'; +} +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +} $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON sp.fk_user_author = u.rowid'; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = sp.fk_projet"; // We'll need this table joined to the select in order to filter by sale -if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; -if ($search_user > 0) -{ +if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} +if ($search_user > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as c"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql .= ' WHERE sp.fk_soc = s.rowid'; $sql .= ' AND sp.entity IN ('.getEntity('supplier_proposal').')'; -if (!$user->rights->societe->client->voir && !$socid) //restriction -{ +if (!$user->rights->societe->client->voir && !$socid) { //restriction $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } -if ($search_town) $sql .= natural_search('s.town', $search_town); -if ($search_zip) $sql .= natural_search("s.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_country) $sql .= " AND s.fk_pays IN (".$search_country.')'; -if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; -if ($search_ref) $sql .= natural_search('sp.ref', $search_ref); -if ($search_societe) $sql .= natural_search('s.nom', $search_societe); -if ($search_login) $sql .= natural_search('u.login', $search_login); -if ($search_montant_ht) $sql .= natural_search('sp.total_ht=', $search_montant_ht, 1); -if ($search_montant_vat != '') $sql .= natural_search("sp.tva", $search_montant_vat, 1); -if ($search_montant_ttc != '') $sql .= natural_search("sp.total", $search_montant_ttc, 1); -if ($search_multicurrency_code != '') $sql .= ' AND sp.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; -if ($search_multicurrency_tx != '') $sql .= natural_search('sp.multicurrency_tx', $search_multicurrency_tx, 1); -if ($search_multicurrency_montant_ht != '') $sql .= natural_search('sp.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); -if ($search_multicurrency_montant_vat != '') $sql .= natural_search('sp.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); -if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('sp.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if ($socid) $sql .= ' AND s.rowid = '.$socid; -if ($search_status >= 0 && $search_status != '') $sql .= ' AND sp.fk_statut IN ('.$db->sanitize($db->escape($search_status)).')'; +if ($search_town) { + $sql .= natural_search('s.town', $search_town); +} +if ($search_zip) { + $sql .= natural_search("s.zip", $search_zip); +} +if ($search_state) { + $sql .= natural_search("state.nom", $search_state); +} +if ($search_country) { + $sql .= " AND s.fk_pays IN (".$search_country.')'; +} +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; +} +if ($search_ref) { + $sql .= natural_search('sp.ref', $search_ref); +} +if ($search_societe) { + $sql .= natural_search('s.nom', $search_societe); +} +if ($search_login) { + $sql .= natural_search('u.login', $search_login); +} +if ($search_montant_ht) { + $sql .= natural_search('sp.total_ht=', $search_montant_ht, 1); +} +if ($search_montant_vat != '') { + $sql .= natural_search("sp.total_tva", $search_montant_vat, 1); +} +if ($search_montant_ttc != '') { + $sql .= natural_search("sp.total_ttc", $search_montant_ttc, 1); +} +if ($search_multicurrency_code != '') { + $sql .= ' AND sp.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; +} +if ($search_multicurrency_tx != '') { + $sql .= natural_search('sp.multicurrency_tx', $search_multicurrency_tx, 1); +} +if ($search_multicurrency_montant_ht != '') { + $sql .= natural_search('sp.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); +} +if ($search_multicurrency_montant_vat != '') { + $sql .= natural_search('sp.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); +} +if ($search_multicurrency_montant_ttc != '') { + $sql .= natural_search('sp.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); +} +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} +if ($socid) { + $sql .= ' AND s.rowid = '.$socid; +} +if ($search_status >= 0 && $search_status != '') { + $sql .= ' AND sp.fk_statut IN ('.$db->sanitize($db->escape($search_status)).')'; +} $sql .= dolSqlDateFilter("sp.date_livraison", $day, $month, $year); $sql .= dolSqlDateFilter("sp.date_valid", $dayvalid, $monthvalid, $yearvalid); -if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale; -if ($search_user > 0) -{ +if ($search_sale > 0) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale; +} +if ($search_user > 0) { $sql .= " AND c.fk_c_type_contact = tc.rowid AND tc.element='supplier_proposal' AND tc.source='internal' AND c.element_id = sp.rowid AND c.fk_socpeople = ".$search_user; } // Add where from extra fields @@ -328,12 +396,10 @@ $sql .= ', sp.ref DESC'; // 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 resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -342,13 +408,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $objectstatic = new SupplierProposal($db); $userstatic = new User($db); - if ($socid > 0) - { + if ($socid > 0) { $soc = new Societe($db); $soc->fetch($socid); $title = $langs->trans('ListOfSupplierProposals').' - '.$soc->name; @@ -360,8 +424,7 @@ if ($resql) $arrayofselected = is_array($toselect) ? $toselect : array(); - if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) - { + if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -374,28 +437,72 @@ if ($resql) llxHeader('', $langs->trans('CommRequest'), $help_url); $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 ($month) $param .= '&month='.urlencode($month); - if ($year) $param .= '&year='.urlencode($year); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_societe) $param .= '&search_societe='.urlencode($search_societe); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); - if ($search_montant_ht) $param .= '&search_montant_ht='.urlencode($search_montant_ht); - if ($search_multicurrency_code != '') $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); - if ($search_multicurrency_tx != '') $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); - if ($search_multicurrency_montant_ht != '') $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); - if ($search_multicurrency_montant_vat != '') $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); - if ($search_multicurrency_montant_ttc != '') $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); - if ($search_login) $param .= '&search_login='.urlencode($search_login); - if ($search_town) $param .= '&search_town='.urlencode($search_town); - if ($search_zip) $param .= '&search_zip='.urlencode($search_zip); - if ($socid > 0) $param .= '&socid='.urlencode($socid); - if ($search_status != '') $param .= '&search_status='.urlencode($search_status); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); + 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 ($month) { + $param .= '&month='.urlencode($month); + } + if ($year) { + $param .= '&year='.urlencode($year); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_societe) { + $param .= '&search_societe='.urlencode($search_societe); + } + if ($search_user > 0) { + $param .= '&search_user='.urlencode($search_user); + } + if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); + } + if ($search_montant_ht) { + $param .= '&search_montant_ht='.urlencode($search_montant_ht); + } + if ($search_multicurrency_code != '') { + $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); + } + if ($search_multicurrency_tx != '') { + $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); + } + if ($search_multicurrency_montant_ht != '') { + $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); + } + if ($search_multicurrency_montant_vat != '') { + $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); + } + if ($search_multicurrency_montant_ttc != '') { + $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); + } + if ($search_login) { + $param .= '&search_login='.urlencode($search_login); + } + if ($search_town) { + $param .= '&search_town='.urlencode($search_town); + } + if ($search_zip) { + $param .= '&search_zip='.urlencode($search_zip); + } + if ($socid > 0) { + $param .= '&socid='.urlencode($socid); + } + if ($search_status != '') { + $param .= '&search_status='.urlencode($search_status); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -405,17 +512,25 @@ if ($resql) 'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->supplier_proposal->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + if ($user->rights->supplier_proposal->supprimer) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); + } + if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $url = DOL_URL_ROOT.'/supplier_proposal/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewAskPrice'), '', 'fa fa-plus-circle', $url, '', $user->rights->supplier_proposal->creer); // Fields title search print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -430,9 +545,10 @@ if ($resql) $trackid = 'spro'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } @@ -440,26 +556,23 @@ if ($resql) $moreforfilter = ''; - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { - $langs->load("commercial"); - $moreforfilter .= '<div class="divsearchfield">'; - $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; - $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth300'); - $moreforfilter .= '</div>'; - } // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + if ($user->rights->societe->client->voir || $socid) { + $langs->load("commercial"); + $moreforfilter .= '<div class="divsearchfield">'; + $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; + $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth300'); + $moreforfilter .= '</div>'; + } + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) { $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); $moreforfilter .= '</div>'; } // If the user can view products - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) - { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; @@ -469,11 +582,13 @@ if ($resql) } $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)) - { + if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -481,50 +596,50 @@ if ($resql) $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 '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; print '<tr class="liste_titre_filter">'; - if (!empty($arrayfields['sp.ref']['checked'])) - { + if (!empty($arrayfields['sp.ref']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat" size="6" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; print '</td>'; } - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="liste_titre left">'; print '<input class="flat" type="text" size="12" name="search_societe" value="'.dol_escape_htmltag($search_societe).'">'; print '</td>'; } - if (!empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>'; - if (!empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="4" name="search_zip" value="'.$search_zip.'"></td>'; + if (!empty($arrayfields['s.town']['checked'])) { + print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>'; + } + if (!empty($arrayfields['s.zip']['checked'])) { + print '<td class="liste_titre"><input class="flat" type="text" size="4" name="search_zip" value="'.$search_zip.'"></td>'; + } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; print '</td>'; } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print '<td class="liste_titre center">'; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print '</td>'; } // Company type - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone center">'; print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); print '</td>'; } // Date - if (!empty($arrayfields['sp.date_valid']['checked'])) - { + if (!empty($arrayfields['sp.date_valid']['checked'])) { print '<td class="liste_titre center">'; //print $langs->trans('Month').': '; print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="monthvalid" value="'.dol_escape_htmltag($monthvalid).'">'; @@ -534,8 +649,7 @@ if ($resql) print '</td>'; } // Date - if (!empty($arrayfields['sp.date_livraison']['checked'])) - { + if (!empty($arrayfields['sp.date_livraison']['checked'])) { print '<td class="liste_titre center">'; //print $langs->trans('Month').': '; print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="month" value="'.dol_escape_htmltag($month).'">'; @@ -545,64 +659,55 @@ if ($resql) print '</td>'; } - if (!empty($arrayfields['sp.total_ht']['checked'])) - { + if (!empty($arrayfields['sp.total_ht']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.dol_escape_htmltag($search_montant_ht).'">'; print '</td>'; } - if (!empty($arrayfields['sp.total_vat']['checked'])) - { + if (!empty($arrayfields['sp.total_tva']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.dol_escape_htmltag($search_montant_vat).'">'; print '</td>'; } - if (!empty($arrayfields['sp.total_ttc']['checked'])) - { + if (!empty($arrayfields['sp.total_ttc']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.dol_escape_htmltag($search_montant_ttc).'">'; print '</td>'; } - if (!empty($arrayfields['sp.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['sp.multicurrency_code']['checked'])) { // Currency print '<td class="liste_titre">'; print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1); print '</td>'; } - if (!empty($arrayfields['sp.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['sp.multicurrency_tx']['checked'])) { // Currency rate print '<td class="liste_titre">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="'.dol_escape_htmltag($search_multicurrency_tx).'">'; print '</td>'; } - if (!empty($arrayfields['sp.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['sp.multicurrency_total_ht']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="'.dol_escape_htmltag($search_multicurrency_montant_ht).'">'; print '</td>'; } - if (!empty($arrayfields['sp.multicurrency_total_vat']['checked'])) - { + if (!empty($arrayfields['sp.multicurrency_total_vat']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_vat" value="'.dol_escape_htmltag($search_multicurrency_montant_vat).'">'; print '</td>'; } - if (!empty($arrayfields['sp.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['sp.multicurrency_total_ttc']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ttc" value="'.dol_escape_htmltag($search_multicurrency_montant_ttc).'">'; print '</td>'; } - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { // Author print '<td class="liste_titre center">'; print '<input class="flat" size="4" type="text" name="search_login" value="'.dol_escape_htmltag($search_login).'">'; @@ -615,20 +720,17 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['sp.datec']['checked'])) - { + if (!empty($arrayfields['sp.datec']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Date modification - if (!empty($arrayfields['sp.tms']['checked'])) - { + if (!empty($arrayfields['sp.tms']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Status - if (!empty($arrayfields['sp.fk_statut']['checked'])) - { + if (!empty($arrayfields['sp.fk_statut']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone right">'; $formpropal->selectProposalStatus($search_status, 1, 0, 1, 'supplier', 'search_status'); print '</td>'; @@ -643,33 +745,75 @@ if ($resql) // Fields title print '<tr class="liste_titre">'; - if (!empty($arrayfields['sp.ref']['checked'])) print_liste_field_titre($arrayfields['sp.ref']['label'], $_SERVER["PHP_SELF"], 'sp.ref', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['sp.date_valid']['checked'])) print_liste_field_titre($arrayfields['sp.date_valid']['label'], $_SERVER["PHP_SELF"], 'sp.date_valid', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['sp.date_livraison']['checked'])) print_liste_field_titre($arrayfields['sp.date_livraison']['label'], $_SERVER["PHP_SELF"], 'sp.date_livraison', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['sp.total_ht']['checked'])) print_liste_field_titre($arrayfields['sp.total_ht']['label'], $_SERVER["PHP_SELF"], 'sp.total_ht', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['sp.total_vat']['checked'])) print_liste_field_titre($arrayfields['sp.total_vat']['label'], $_SERVER["PHP_SELF"], 'sp.total_vat', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['sp.total_ttc']['checked'])) print_liste_field_titre($arrayfields['sp.total_ttc']['label'], $_SERVER["PHP_SELF"], 'sp.total_ttc', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['sp.multicurrency_code']['checked'])) print_liste_field_titre($arrayfields['sp.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'sp.multicurrency_code', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['sp.multicurrency_tx']['checked'])) print_liste_field_titre($arrayfields['sp.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'sp.multicurrency_tx', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['sp.multicurrency_total_ht']['checked'])) print_liste_field_titre($arrayfields['sp.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'sp.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['sp.multicurrency_total_vat']['checked'])) print_liste_field_titre($arrayfields['sp.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'sp.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['sp.multicurrency_total_ttc']['checked'])) print_liste_field_titre($arrayfields['sp.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'sp.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['u.login']['checked'])) print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['sp.ref']['checked'])) { + print_liste_field_titre($arrayfields['sp.ref']['label'], $_SERVER["PHP_SELF"], 'sp.ref', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $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, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['sp.date_valid']['checked'])) { + print_liste_field_titre($arrayfields['sp.date_valid']['label'], $_SERVER["PHP_SELF"], 'sp.date_valid', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['sp.date_livraison']['checked'])) { + print_liste_field_titre($arrayfields['sp.date_livraison']['label'], $_SERVER["PHP_SELF"], 'sp.date_livraison', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['sp.total_ht']['checked'])) { + print_liste_field_titre($arrayfields['sp.total_ht']['label'], $_SERVER["PHP_SELF"], 'sp.total_ht', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['sp.total_tva']['checked'])) { + print_liste_field_titre($arrayfields['sp.total_tva']['label'], $_SERVER["PHP_SELF"], 'sp.total_tva', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['sp.total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['sp.total_ttc']['label'], $_SERVER["PHP_SELF"], 'sp.total_ttc', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['sp.multicurrency_code']['checked'])) { + print_liste_field_titre($arrayfields['sp.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'sp.multicurrency_code', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['sp.multicurrency_tx']['checked'])) { + print_liste_field_titre($arrayfields['sp.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'sp.multicurrency_tx', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['sp.multicurrency_total_ht']['checked'])) { + print_liste_field_titre($arrayfields['sp.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'sp.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['sp.multicurrency_total_vat']['checked'])) { + print_liste_field_titre($arrayfields['sp.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'sp.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['sp.multicurrency_total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['sp.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'sp.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['u.login']['checked'])) { + print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, '', $sortfield, $sortorder, 'center '); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $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['sp.datec']['checked'])) print_liste_field_titre($arrayfields['sp.datec']['label'], $_SERVER["PHP_SELF"], "sp.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['sp.tms']['checked'])) print_liste_field_titre($arrayfields['sp.tms']['label'], $_SERVER["PHP_SELF"], "sp.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap'); - if (!empty($arrayfields['sp.fk_statut']['checked'])) print_liste_field_titre($arrayfields['sp.fk_statut']['label'], $_SERVER["PHP_SELF"], "sp.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['sp.datec']['checked'])) { + print_liste_field_titre($arrayfields['sp.datec']['label'], $_SERVER["PHP_SELF"], "sp.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['sp.tms']['checked'])) { + print_liste_field_titre($arrayfields['sp.tms']['label'], $_SERVER["PHP_SELF"], "sp.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap'); + } + if (!empty($arrayfields['sp.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['sp.fk_statut']['label'], $_SERVER["PHP_SELF"], "sp.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print '</tr>'."\n"; @@ -678,8 +822,12 @@ if ($resql) $total = 0; $subtotal = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + $totalarray['nbfield'] = 0; + $totalarray['val'] = array(); + $totalarray['val']['sp.total_ht'] = 0; + $totalarray['val']['sp.total_tva'] = 0; + $totalarray['val']['sp.total_ttc'] = 0; + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->rowid; @@ -696,8 +844,7 @@ if ($resql) print '<tr class="oddeven">'; - if (!empty($arrayfields['sp.ref']['checked'])) - { + if (!empty($arrayfields['sp.ref']['checked'])) { print '<td class="nowrap">'; print '<table class="nobordernopadding"><tr class="nocellnopadd">'; @@ -708,8 +855,7 @@ if ($resql) // Warning $warnornote = ''; //if ($obj->fk_statut == 1 && $db->jdate($obj->date_valid) < ($now - $conf->supplier_proposal->warning_delay)) $warnornote .= img_warning($langs->trans("Late")); - if ($warnornote) - { + if ($warnornote) { print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; print $warnornote; print '</td>'; @@ -723,147 +869,177 @@ if ($resql) print '</td></tr></table>'; print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Thirdparty - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="tdoverflowmax200">'; print $companystatic->getNomUrl(1, 'customer'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['s.town']['checked'])) - { + if (!empty($arrayfields['s.town']['checked'])) { print '<td class="nocellnopadd">'; print $obj->town; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { + if (!empty($arrayfields['s.zip']['checked'])) { print '<td class="nocellnopadd">'; print $obj->zip; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print "<td>".$obj->state_name."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print '<td class="center">'; $tmparray = getCountry($obj->fk_pays, 'all'); print $tmparray['label']; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print '<td class="center">'; - if (count($typenArray) == 0) $typenArray = $formcompany->typent_array(1); + if (count($typenArray) == 0) { + $typenArray = $formcompany->typent_array(1); + } print $typenArray[$obj->typent_code]; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date proposal - if (!empty($arrayfields['sp.date_valid']['checked'])) - { + if (!empty($arrayfields['sp.date_valid']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_valid), 'day'); print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date delivery - if (!empty($arrayfields['sp.date_livraison']['checked'])) - { + if (!empty($arrayfields['sp.date_livraison']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->dp), 'day'); print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['sp.total_ht']['checked'])) - { + if (!empty($arrayfields['sp.total_ht']['checked'])) { print '<td class="right">'.price($obj->total_ht)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'sp.total_ht'; - $totalarray['val']['sp.total_ht'] += $obj->total_ht; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'sp.total_ht'; + } + $totalarray['val']['sp.total_ht'] += $obj->total_ht; } // Amount VAT - if (!empty($arrayfields['sp.total_vat']['checked'])) - { - print '<td class="right">'.price($obj->total_vat)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'sp.total_vat'; - $totalarray['val']['sp.total_vat'] += $obj->total_vat; + if (!empty($arrayfields['sp.total_tva']['checked'])) { + print '<td class="right">'.price($obj->total_tva)."</td>\n"; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'sp.total_tva'; + } + $totalarray['val']['sp.total_tva'] += $obj->total_tva; } // Amount TTC - if (!empty($arrayfields['sp.total_ttc']['checked'])) - { + if (!empty($arrayfields['sp.total_ttc']['checked'])) { print '<td class="right">'.price($obj->total_ttc)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'sp.total_ttc'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'sp.total_ttc'; + } $totalarray['val']['sp.total_ttc'] += $obj->total_ttc; } // Currency - if (!empty($arrayfields['sp.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['sp.multicurrency_code']['checked'])) { print '<td class="nowrap">'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Currency rate - if (!empty($arrayfields['sp.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['sp.multicurrency_tx']['checked'])) { print '<td class="nowrap">'; $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code); print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['sp.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['sp.multicurrency_total_ht']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_ht)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount VAT - if (!empty($arrayfields['sp.multicurrency_total_vat']['checked'])) - { + if (!empty($arrayfields['sp.multicurrency_total_vat']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_vat)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount TTC - if (!empty($arrayfields['sp.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['sp.multicurrency_total_ttc']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_ttc)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } $userstatic->id = $obj->fk_user_author; $userstatic->login = $obj->login; // Author - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { print '<td class="center">'; - if ($userstatic->id) print $userstatic->getLoginUrl(1); - else print '&nbsp;'; + if ($userstatic->id) { + print $userstatic->getLoginUrl(1); + } else { + print '&nbsp;'; + } print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -873,38 +1049,44 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['sp.datec']['checked'])) - { + if (!empty($arrayfields['sp.datec']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['sp.tms']['checked'])) - { + if (!empty($arrayfields['sp.tms']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['sp.fk_statut']['checked'])) - { + if (!empty($arrayfields['sp.fk_statut']['checked'])) { print '<td class="right">'.$objectstatic->getLibStatut(5)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; @@ -929,7 +1111,9 @@ if ($resql) print '</form>'."\n"; $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/supplier_proposal/note.php b/htdocs/supplier_proposal/note.php index 464f31aaaae..372b6b6d20b 100644 --- a/htdocs/supplier_proposal/note.php +++ b/htdocs/supplier_proposal/note.php @@ -40,7 +40,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'supplier_proposal', $id, 'supplier_proposal'); $object = new SupplierProposal($db); @@ -64,19 +66,18 @@ llxHeader('', $langs->trans('CommRequest'), 'EN:Ask_Price_Supplier|FR:Demande_de $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ - if ($mesg) print $mesg; +if ($id > 0 || !empty($ref)) { + if ($mesg) { + print $mesg; + } $now = dol_now(); - if ($object->fetch($id, $ref)) - { + if ($object->fetch($id, $ref)) { $object->fetch_thirdparty(); $societe = new Societe($db); - if ($societe->fetch($object->socid)) - { + if ($societe->fetch($object->socid)) { $head = supplier_proposal_prepare_head($object); print dol_get_fiche_head($head, 'note', $langs->trans('CommRequest'), -1, 'supplier_proposal'); @@ -92,12 +93,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->supplier_proposal->creer) - { + if ($user->rights->supplier_proposal->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/supplier_proposal/tpl/linkedobjectblock.tpl.php b/htdocs/supplier_proposal/tpl/linkedobjectblock.tpl.php index ea6f45e18be..c33c3b2ebac 100644 --- a/htdocs/supplier_proposal/tpl/linkedobjectblock.tpl.php +++ b/htdocs/supplier_proposal/tpl/linkedobjectblock.tpl.php @@ -18,8 +18,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -35,41 +34,41 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - <tr class="<?php echo $trclass; ?>"> - <td><?php echo $langs->trans("SupplierProposal"); ?></td> - <td><a href="<?php echo DOL_URL_ROOT.'/supplier_proposal/card.php?id='.$objectlink->id ?>"><?php echo img_object($langs->trans("ShowSupplierProposal"), "supplier_proposal").' '.$objectlink->ref; ?></a></td> - <td></td> - <td class="center"><?php echo dol_print_date($objectlink->datec, 'day'); ?></td> - <td class="right"><?php + <tr class="<?php echo $trclass; ?>"> + <td><?php echo $langs->trans("SupplierProposal"); ?></td> + <td><a href="<?php echo DOL_URL_ROOT.'/supplier_proposal/card.php?id='.$objectlink->id ?>"><?php echo img_object($langs->trans("ShowSupplierProposal"), "supplier_proposal").' '.$objectlink->ref; ?></a></td> + <td></td> + <td class="center"><?php echo dol_print_date($objectlink->datec, 'day'); ?></td> + <td class="right"><?php if ($user->rights->supplier_proposal->lire) { $total = $total + $objectlink->total_ht; echo price($objectlink->total_ht); } ?></td> - <td class="right"><?php echo $objectlink->getLibStatut(3); ?></td> - <td class="right"><a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a></td> - </tr> - <?php + <td class="right"><?php echo $objectlink->getLibStatut(3); ?></td> + <td class="right"><a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a></td> + </tr> + <?php } -if (count($linkedObjectBlock) > 1) -{ +if (count($linkedObjectBlock) > 1) { ?> - <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> - <td><?php echo $langs->trans("Total"); ?></td> - <td></td> - <td class="center"></td> - <td class="center"></td> - <td class="right"><?php echo price($total); ?></td> - <td class="right"></td> - <td class="right"></td> - </tr> - <?php + <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> + <td><?php echo $langs->trans("Total"); ?></td> + <td></td> + <td class="center"></td> + <td class="center"></td> + <td class="right"><?php echo price($total); ?></td> + <td class="right"></td> + <td class="right"></td> + </tr> + <?php } print "<!-- END PHP TEMPLATE -->\n"; diff --git a/htdocs/support/inc.php b/htdocs/support/inc.php index 43077495238..31236ab5fa9 100644 --- a/htdocs/support/inc.php +++ b/htdocs/support/inc.php @@ -25,7 +25,9 @@ */ // Define DOL_DOCUMENT_ROOT -if (!defined('DOL_DOCUMENT_ROOT')) define('DOL_DOCUMENT_ROOT', '..'); +if (!defined('DOL_DOCUMENT_ROOT')) { + define('DOL_DOCUMENT_ROOT', '..'); +} require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; @@ -44,8 +46,7 @@ $_REQUEST["logtohtml"] = 1; // Correction PHP_SELF (ex pour apache via caudium) car PHP_SELF doit valoir URL relative // et non path absolu. -if (isset($_SERVER["DOCUMENT_URI"]) && $_SERVER["DOCUMENT_URI"]) -{ +if (isset($_SERVER["DOCUMENT_URI"]) && $_SERVER["DOCUMENT_URI"]) { $_SERVER["PHP_SELF"] = $_SERVER["DOCUMENT_URI"]; } @@ -58,27 +59,28 @@ $conffiletoshowshort = "conf.php"; $conffile = "../conf/conf.php"; $conffiletoshow = "htdocs/conf/conf.php"; // For debian/redhat like systems -if (!file_exists($conffile)) -{ +if (!file_exists($conffile)) { $conffile = "/etc/dolibarr/conf.php"; $conffiletoshow = "/etc/dolibarr/conf.php"; } // Load conf file if it is already defined -if (!defined('DONOTLOADCONF') && file_exists($conffile) && filesize($conffile) > 8) // Test on filesize is to ensure that conf file is more that an empty template with just <?php in first line -{ +if (!defined('DONOTLOADCONF') && file_exists($conffile) && filesize($conffile) > 8) { // Test on filesize is to ensure that conf file is more that an empty template with just <?php in first line $result = include_once $conffile; // Load conf file - if ($result) - { - if (empty($dolibarr_main_db_type)) $dolibarr_main_db_type = 'mysql'; // For backward compatibility + if ($result) { + if (empty($dolibarr_main_db_type)) { + $dolibarr_main_db_type = 'mysql'; // For backward compatibility + } //Mysql driver support has been removed in favor of mysqli if ($dolibarr_main_db_type == 'mysql') { $dolibarr_main_db_type = 'mysqli'; } - if (empty($dolibarr_main_db_port) && ($dolibarr_main_db_type == 'mysqli')) $dolibarr_main_db_port = '3306'; // For backward compatibility + if (empty($dolibarr_main_db_port) && ($dolibarr_main_db_type == 'mysqli')) { + $dolibarr_main_db_port = '3306'; // For backward compatibility + } // Clean parameters $dolibarr_main_data_root = isset($dolibarr_main_data_root) ?trim($dolibarr_main_data_root) : ''; @@ -88,25 +90,31 @@ if (!defined('DONOTLOADCONF') && file_exists($conffile) && filesize($conffile) > $dolibarr_main_document_root_alt = isset($dolibarr_main_document_root_alt) ?trim($dolibarr_main_document_root_alt) : ''; // Remove last / or \ on directories or url value - if (!empty($dolibarr_main_document_root) && !preg_match('/^[\\/]+$/', $dolibarr_main_document_root)) $dolibarr_main_document_root = preg_replace('/[\\/]+$/', '', $dolibarr_main_document_root); - if (!empty($dolibarr_main_url_root) && !preg_match('/^[\\/]+$/', $dolibarr_main_url_root)) $dolibarr_main_url_root = preg_replace('/[\\/]+$/', '', $dolibarr_main_url_root); - if (!empty($dolibarr_main_data_root) && !preg_match('/^[\\/]+$/', $dolibarr_main_data_root)) $dolibarr_main_data_root = preg_replace('/[\\/]+$/', '', $dolibarr_main_data_root); - if (!empty($dolibarr_main_document_root_alt) && !preg_match('/^[\\/]+$/', $dolibarr_main_document_root_alt)) $dolibarr_main_document_root_alt = preg_replace('/[\\/]+$/', '', $dolibarr_main_document_root_alt); - if (!empty($dolibarr_main_url_root_alt) && !preg_match('/^[\\/]+$/', $dolibarr_main_url_root_alt)) $dolibarr_main_url_root_alt = preg_replace('/[\\/]+$/', '', $dolibarr_main_url_root_alt); + if (!empty($dolibarr_main_document_root) && !preg_match('/^[\\/]+$/', $dolibarr_main_document_root)) { + $dolibarr_main_document_root = preg_replace('/[\\/]+$/', '', $dolibarr_main_document_root); + } + if (!empty($dolibarr_main_url_root) && !preg_match('/^[\\/]+$/', $dolibarr_main_url_root)) { + $dolibarr_main_url_root = preg_replace('/[\\/]+$/', '', $dolibarr_main_url_root); + } + if (!empty($dolibarr_main_data_root) && !preg_match('/^[\\/]+$/', $dolibarr_main_data_root)) { + $dolibarr_main_data_root = preg_replace('/[\\/]+$/', '', $dolibarr_main_data_root); + } + if (!empty($dolibarr_main_document_root_alt) && !preg_match('/^[\\/]+$/', $dolibarr_main_document_root_alt)) { + $dolibarr_main_document_root_alt = preg_replace('/[\\/]+$/', '', $dolibarr_main_document_root_alt); + } + if (!empty($dolibarr_main_url_root_alt) && !preg_match('/^[\\/]+$/', $dolibarr_main_url_root_alt)) { + $dolibarr_main_url_root_alt = preg_replace('/[\\/]+$/', '', $dolibarr_main_url_root_alt); + } // Create conf object - if (!empty($dolibarr_main_document_root)) - { + if (!empty($dolibarr_main_document_root)) { $result = conf($dolibarr_main_document_root); } // Load database driver - if ($result) - { - if (!empty($dolibarr_main_document_root) && !empty($dolibarr_main_db_type)) - { + if ($result) { + if (!empty($dolibarr_main_document_root) && !empty($dolibarr_main_db_type)) { $result = include_once $dolibarr_main_document_root."/core/db/".$dolibarr_main_db_type.'.class.php'; - if (!$result) - { + if (!$result) { $includeconferror = 'ErrorBadValueForDolibarrMainDBType'; } } @@ -120,7 +128,9 @@ if (!defined('DONOTLOADCONF') && file_exists($conffile) && filesize($conffile) > $conf->global->MAIN_LOGTOHTML = 1; // Define prefix -if (!isset($dolibarr_main_db_prefix) || !$dolibarr_main_db_prefix) $dolibarr_main_db_prefix = 'llx_'; +if (!isset($dolibarr_main_db_prefix) || !$dolibarr_main_db_prefix) { + $dolibarr_main_db_prefix = 'llx_'; +} define('MAIN_DB_PREFIX', (isset($dolibarr_main_db_prefix) ? $dolibarr_main_db_prefix : '')); define('DOL_CLASS_PATH', 'class/'); // Filsystem path to class dir @@ -128,27 +138,44 @@ define('DOL_DATA_ROOT', (isset($dolibarr_main_data_root) ? $dolibarr_main_data_r define('DOL_MAIN_URL_ROOT', (isset($dolibarr_main_url_root) ? $dolibarr_main_url_root : '')); // URL relative root $uri = preg_replace('/^http(s?):\/\//i', '', constant('DOL_MAIN_URL_ROOT')); // $uri contains url without http* $suburi = strstr($uri, '/'); // $suburi contains url without domain -if ($suburi == '/') $suburi = ''; // If $suburi is /, it is now '' +if ($suburi == '/') { + $suburi = ''; // If $suburi is /, it is now '' +} define('DOL_URL_ROOT', $suburi); // URL relative root ('', '/dolibarr', ...) -if (empty($character_set_client)) $character_set_client = "UTF-8"; +if (empty($character_set_client)) { + $character_set_client = "UTF-8"; +} $conf->file->character_set_client = strtoupper($character_set_client); -if (empty($dolibarr_main_db_character_set)) $dolibarr_main_db_character_set = ($conf->db->type == 'mysql' ? 'latin1' : ''); // Old installation +if (empty($dolibarr_main_db_character_set)) { + $dolibarr_main_db_character_set = ($conf->db->type == 'mysqli' ? 'utf8' : ''); // Old installation +} $conf->db->character_set = $dolibarr_main_db_character_set; -if (empty($dolibarr_main_db_collation)) $dolibarr_main_db_collation = ($conf->db->type == 'mysql' ? 'latin1_swedish_ci' : ''); // Old installation +if (empty($dolibarr_main_db_collation)) { + $dolibarr_main_db_collation = ($conf->db->type == 'mysqli' ? 'utf8_unicode_ci' : ''); // Old installation +} $conf->db->dolibarr_main_db_collation = $dolibarr_main_db_collation; -if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption = 0; +if (empty($dolibarr_main_db_encryption)) { + $dolibarr_main_db_encryption = 0; +} $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption; -if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey = ''; +if (empty($dolibarr_main_db_cryptkey)) { + $dolibarr_main_db_cryptkey = ''; +} $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey; -if (empty($conf->db->user)) $conf->db->user = ''; +if (empty($conf->db->user)) { + $conf->db->user = ''; +} // Defini objet langs $langs = new Translate('..', $conf); -if (GETPOST('lang', 'aZ09')) $langs->setDefaultLang(GETPOST('lang', 'aZ09')); -else $langs->setDefaultLang('auto'); +if (GETPOST('lang', 'aZ09')) { + $langs->setDefaultLang(GETPOST('lang', 'aZ09')); +} else { + $langs->setDefaultLang('auto'); +} $bc[false] = ' class="bg1"'; $bc[true] = ' class="bg2"'; @@ -172,7 +199,9 @@ function conf($dolibarr_main_document_root) global $character_set_client; $return = include_once $dolibarr_main_document_root.'/core/class/conf.class.php'; - if (!$return) return -1; + if (!$return) { + return -1; + } $conf = new Conf(); $conf->db->type = trim($dolibarr_main_db_type); @@ -182,7 +211,9 @@ function conf($dolibarr_main_document_root) $conf->db->user = trim($dolibarr_main_db_user); $conf->db->pass = trim($dolibarr_main_db_pass); - if (empty($conf->db->dolibarr_main_db_collation)) $conf->db->dolibarr_main_db_collation = 'utf8_unicode_ci'; + if (empty($conf->db->dolibarr_main_db_collation)) { + $conf->db->dolibarr_main_db_collation = 'utf8_unicode_ci'; + } return 1; } diff --git a/htdocs/support/index.php b/htdocs/support/index.php index cecada7ed65..220da1290ac 100644 --- a/htdocs/support/index.php +++ b/htdocs/support/index.php @@ -31,9 +31,12 @@ include_once 'inc.php'; $uri = preg_replace('/^http(s?):\/\//i', '', $dolibarr_main_url_root); $pos = strstr($uri, '/'); // $pos contient alors url sans nom domaine -if ($pos == '/') $pos = ''; // si $pos vaut /, on le met a '' -if (!defined('DOL_URL_ROOT')) +if ($pos == '/') { + $pos = ''; // si $pos vaut /, on le met a '' +} +if (!defined('DOL_URL_ROOT')) { define('DOL_URL_ROOT', $pos); // URL racine relative +} $langs->loadLangs(array("other", $langs->load("help"))); @@ -49,10 +52,18 @@ print $langs->trans("HelpCenterDesc2")."<br>\n"; print '<br>'; $homeurl = DOL_URL_ROOT.'/'; -if (GETPOST('dol_hide_toptmenu')) $homeurl .= (strpos($homeurl, '?') === false ? '?' : '&').'dol_hide_toptmenu=1'; -if (GETPOST('dol_hide_leftmenu')) $homeurl .= (strpos($homeurl, '?') === false ? '?' : '&').'dol_hide_leftmenu=1'; -if (GETPOST('dol_no_mouse_hover')) $homeurl .= (strpos($homeurl, '?') === false ? '?' : '&').'dol_no_mouse_hover=1'; -if (GETPOST('dol_use_jmobile')) $homeurl .= (strpos($homeurl, '?') === false ? '?' : '&').'dol_use_jmobile=1'; +if (GETPOST('dol_hide_toptmenu')) { + $homeurl .= (strpos($homeurl, '?') === false ? '?' : '&').'dol_hide_toptmenu=1'; +} +if (GETPOST('dol_hide_leftmenu')) { + $homeurl .= (strpos($homeurl, '?') === false ? '?' : '&').'dol_hide_leftmenu=1'; +} +if (GETPOST('dol_no_mouse_hover')) { + $homeurl .= (strpos($homeurl, '?') === false ? '?' : '&').'dol_no_mouse_hover=1'; +} +if (GETPOST('dol_use_jmobile')) { + $homeurl .= (strpos($homeurl, '?') === false ? '?' : '&').'dol_use_jmobile=1'; +} print $langs->trans("ToGoBackToDolibarr", $homeurl); print '<br><br>'; @@ -86,20 +97,38 @@ print '<td align="center" valign="middle">'; print '<table class="nocellnopadd">'; print '<tr><td align="center">'; $urlwiki = 'https://wiki.dolibarr.org'; -if (preg_match('/fr/i', $langs->defaultlang)) $urlwiki = 'https://wiki.dolibarr.org/index.php/Accueil'; -if (preg_match('/es/i', $langs->defaultlang)) $urlwiki = 'https://wiki.dolibarr.org/index.php/Portada'; -if (preg_match('/de/i', $langs->defaultlang)) $urlwiki = 'https://wiki.dolibarr.org/index.php/Hauptseite'; +if (preg_match('/fr/i', $langs->defaultlang)) { + $urlwiki = 'https://wiki.dolibarr.org/index.php/Accueil'; +} +if (preg_match('/es/i', $langs->defaultlang)) { + $urlwiki = 'https://wiki.dolibarr.org/index.php/Portada'; +} +if (preg_match('/de/i', $langs->defaultlang)) { + $urlwiki = 'https://wiki.dolibarr.org/index.php/Hauptseite'; +} print '<br>'.$langs->trans("ForDocumentationSeeWiki", $urlwiki, $urlwiki); print '<br>'; $urlforum = 'https://www.dolibarr.org/forum/'; $urlforumlocal = 'https://www.dolibarr.org/forum/'; -if (preg_match('/fr/i', $langs->defaultlang)) $urlforumlocal = 'https://www.dolibarr.fr/forum/'; -if (preg_match('/es/i', $langs->defaultlang)) $urlforumlocal = 'https://www.dolibarr.es/foro/'; -if (preg_match('/it/i', $langs->defaultlang)) $urlforumlocal = 'http://www.dolibarr.it/forum/'; -if (preg_match('/gr/i', $langs->defaultlang)) $urlforumlocal = 'https://www.dolibarr.gr/forum/'; -if (preg_match('/de/i', $langs->defaultlang)) $urlforumlocal = 'https://www.dolibarr.de/forum/'; +if (preg_match('/fr/i', $langs->defaultlang)) { + $urlforumlocal = 'https://www.dolibarr.fr/forum/'; +} +if (preg_match('/es/i', $langs->defaultlang)) { + $urlforumlocal = 'https://www.dolibarr.es/foro/'; +} +if (preg_match('/it/i', $langs->defaultlang)) { + $urlforumlocal = 'http://www.dolibarr.it/forum/'; +} +if (preg_match('/gr/i', $langs->defaultlang)) { + $urlforumlocal = 'https://www.dolibarr.gr/forum/'; +} +if (preg_match('/de/i', $langs->defaultlang)) { + $urlforumlocal = 'https://www.dolibarr.de/forum/'; +} print '<br>'.$langs->trans("ForAnswersSeeForum", $urlforumlocal, $urlforumlocal).'<br>'; -if ($urlforumlocal != $urlforum) print '<b><a href="'.$urlforum.'">'.$urlforum.'</a></b>'; +if ($urlforumlocal != $urlforum) { + print '<b><a href="'.$urlforum.'">'.$urlforum.'</a></b>'; +} print '</td></tr></table>'; print '</td>'; print '</tr>'; diff --git a/htdocs/takepos/admin/appearance.php b/htdocs/takepos/admin/appearance.php index eb956ea9f32..ef448607b10 100644 --- a/htdocs/takepos/admin/appearance.php +++ b/htdocs/takepos/admin/appearance.php @@ -30,7 +30,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; require_once DOL_DOCUMENT_ROOT."/core/lib/takepos.lib.php"; // Security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $langs->loadLangs(array("admin", "cashdesk", "commercial")); @@ -38,8 +40,7 @@ $langs->loadLangs(array("admin", "cashdesk", "commercial")); * Actions */ -if (GETPOST('action', 'alpha') == 'set') -{ +if (GETPOST('action', 'alpha') == 'set') { $db->begin(); $res = dolibarr_set_const($db, "TAKEPOS_COLOR_THEME", GETPOST('TAKEPOS_COLOR_THEME', 'alpha'), 'chaine', 0, '', $conf->entity); @@ -47,18 +48,18 @@ if (GETPOST('action', 'alpha') == 'set') dol_syslog("admin/cashdesk: level ".GETPOST('level', 'alpha')); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { $db->rollback(); setEventMessages($langs->trans("Error"), null, 'errors'); } -} elseif (GETPOST('action', 'alpha') == 'setmethod') -{ +} elseif (GETPOST('action', 'alpha') == 'setmethod') { dolibarr_set_const($db, "TAKEPOS_PRINT_METHOD", GETPOST('value', 'alpha'), 'chaine', 0, '', $conf->entity); } diff --git a/htdocs/takepos/admin/bar.php b/htdocs/takepos/admin/bar.php index f5f678ec900..09f3b13d4d1 100644 --- a/htdocs/takepos/admin/bar.php +++ b/htdocs/takepos/admin/bar.php @@ -30,7 +30,9 @@ require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT."/core/lib/takepos.lib.php"; // Security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $langs->loadLangs(array("admin", "cashdesk", "printing")); @@ -41,22 +43,22 @@ $res = 0; * Actions */ -if (GETPOST('action', 'alpha') == 'set') -{ +if (GETPOST('action', 'alpha') == 'set') { $db->begin(); dol_syslog("admin/bar"); $suplement_category = GETPOST('TAKEPOS_SUPPLEMENTS_CATEGORY', 'alpha'); - if ($suplement_category < 0) $suplement_category = 0; + if ($suplement_category < 0) { + $suplement_category = 0; + } $res = dolibarr_set_const($db, "TAKEPOS_SUPPLEMENTS_CATEGORY", $suplement_category, 'chaine', 0, '', $conf->entity); if ($res <= 0) { $error++; } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -153,8 +155,7 @@ if ($conf->global->TAKEPOS_BAR_RESTAURANT) { print ajax_constantonoff("TAKEPOS_SUPPLEMENTS", array(), $conf->entity, 0, 0, 1, 0); print '</td></tr>'; - if ($conf->global->TAKEPOS_SUPPLEMENTS) - { + if ($conf->global->TAKEPOS_SUPPLEMENTS) { print '<tr class="oddeven"><td>'; print $langs->trans("SupplementCategory"); print '</td>'; @@ -187,8 +188,7 @@ if ($conf->global->TAKEPOS_BAR_RESTAURANT) { } if ($conf->global->TAKEPOS_BAR_RESTAURANT) { - if ($conf->global->TAKEPOS_QR_MENU) - { + if ($conf->global->TAKEPOS_QR_MENU) { $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file print '<br>'; @@ -205,8 +205,7 @@ if ($conf->global->TAKEPOS_BAR_RESTAURANT) { print '</table>'; } - if ($conf->global->TAKEPOS_AUTO_ORDER) - { + if ($conf->global->TAKEPOS_AUTO_ORDER) { print '<br>'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; diff --git a/htdocs/takepos/admin/orderprinters.php b/htdocs/takepos/admin/orderprinters.php index 9ec59fb388b..eb23f26806c 100644 --- a/htdocs/takepos/admin/orderprinters.php +++ b/htdocs/takepos/admin/orderprinters.php @@ -34,7 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; $langs->loadLangs(array("main"), "categories", "takepos", "printing"); -if (!$user->rights->categorie->lire) accessforbidden(); +if (!$user->rights->categorie->lire) { + accessforbidden(); +} $id = GETPOST('id', 'int'); $type = (GETPOST('type', 'aZ09') ? GETPOST('type', 'aZ09') : Categorie::TYPE_PRODUCT); @@ -44,31 +46,39 @@ $printer1 = GETPOST('printer1', 'alpha'); $printer2 = GETPOST('printer2', 'alpha'); $printer3 = GETPOST('printer3', 'alpha'); -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} /* * Actions */ if ($action == "SavePrinter1") { $printedcategories = ";"; - if (is_array($printer1)) foreach ($printer1 as $cat) { - $printedcategories = $printedcategories.$cat.";"; + if (is_array($printer1)) { + foreach ($printer1 as $cat) { + $printedcategories = $printedcategories.$cat.";"; + } } dolibarr_set_const($db, "TAKEPOS_PRINTED_CATEGORIES_1", $printedcategories, 'chaine', 0, '', $conf->entity); } if ($action == "SavePrinter2") { $printedcategories = ";"; - if (is_array($printer2)) foreach ($printer2 as $cat) { - $printedcategories = $printedcategories.$cat.";"; + if (is_array($printer2)) { + foreach ($printer2 as $cat) { + $printedcategories = $printedcategories.$cat.";"; + } } dolibarr_set_const($db, "TAKEPOS_PRINTED_CATEGORIES_2", $printedcategories, 'chaine', 0, '', $conf->entity); } if ($action == "SavePrinter3") { $printedcategories = ";"; - if (is_array($printer3)) foreach ($printer3 as $cat) { - $printedcategories = $printedcategories.$cat.";"; + if (is_array($printer3)) { + foreach ($printer3 as $cat) { + $printedcategories = $printedcategories.$cat.";"; + } } dolibarr_set_const($db, "TAKEPOS_PRINTED_CATEGORIES_3", $printedcategories, 'chaine', 0, '', $conf->entity); } @@ -145,8 +155,7 @@ $fulltree = $cate_arbo; // Define data (format for treeview) $data = array(); $data[] = array('rowid'=>0, 'fk_menu'=>-1, 'title'=>"racine", 'mainmenu'=>'', 'leftmenu'=>'', 'fk_mainmenu'=>'', 'fk_leftmenu'=>''); -foreach ($fulltree as $key => $val) -{ +foreach ($fulltree as $key => $val) { $categstatic->id = $val['id']; $categstatic->ref = $val['label']; $categstatic->color = $val['color']; @@ -168,13 +177,18 @@ print '<tr class="liste_titre"><td>'.$langs->trans("Printer").' 1</td><td></td>< print '</td></tr>'; $nbofentries = (count($data) - 1); print '<form action="orderprinters.php">'; -if ($nbofentries > 0) -{ +if ($nbofentries > 0) { print '<tr class="pair"><td colspan="3">'; print '<input type="hidden" name="action" value="SavePrinter1">'; foreach ($data as $row) { - if (strpos($conf->global->TAKEPOS_PRINTED_CATEGORIES_1, ';'.$row["rowid"].';') !== false) $checked = 'checked'; else $checked = ''; - if ($row["fk_menu"] == 0) print '<input type="checkbox" name="printer1[]" value="'.$row["rowid"].'" '.$checked.'>'.$row["label"].'<br>'; + if (strpos($conf->global->TAKEPOS_PRINTED_CATEGORIES_1, ';'.$row["rowid"].';') !== false) { + $checked = 'checked'; + } else { + $checked = ''; + } + if ($row["fk_menu"] == 0) { + print '<input type="checkbox" name="printer1[]" value="'.$row["rowid"].'" '.$checked.'>'.$row["label"].'<br>'; + } } print '</td></tr>'; } else { @@ -196,13 +210,18 @@ print '<tr class="liste_titre"><td>'.$langs->trans("Printer").' 2</td><td></td>< print '</td></tr>'; $nbofentries = (count($data) - 1); print '<form action="orderprinters.php">'; -if ($nbofentries > 0) -{ +if ($nbofentries > 0) { print '<tr class="pair"><td colspan="3">'; print '<input type="hidden" name="action" value="SavePrinter2">'; foreach ($data as $row) { - if (strpos($conf->global->TAKEPOS_PRINTED_CATEGORIES_2, ';'.$row["rowid"].';') !== false) $checked = 'checked'; else $checked = ''; - if ($row["fk_menu"] == 0) print '<input type="checkbox" name="printer2[]" value="'.$row["rowid"].'" '.$checked.'>'.$row["label"].'<br>'; + if (strpos($conf->global->TAKEPOS_PRINTED_CATEGORIES_2, ';'.$row["rowid"].';') !== false) { + $checked = 'checked'; + } else { + $checked = ''; + } + if ($row["fk_menu"] == 0) { + print '<input type="checkbox" name="printer2[]" value="'.$row["rowid"].'" '.$checked.'>'.$row["label"].'<br>'; + } } print '</td></tr>'; } else { @@ -224,13 +243,18 @@ print '<tr class="liste_titre"><td>'.$langs->trans("Printer").' 3</td><td></td>< print '</td></tr>'; $nbofentries = (count($data) - 1); print '<form action="orderprinters.php">'; -if ($nbofentries > 0) -{ +if ($nbofentries > 0) { print '<tr class="pair"><td colspan="3">'; print '<input type="hidden" name="action" value="SavePrinter3">'; foreach ($data as $row) { - if (strpos($conf->global->TAKEPOS_PRINTED_CATEGORIES_3, ';'.$row["rowid"].';') !== false) $checked = 'checked'; else $checked = ''; - if ($row["fk_menu"] == 0) print '<input type="checkbox" name="printer3[]" value="'.$row["rowid"].'" '.$checked.'>'.$row["label"].'<br>'; + if (strpos($conf->global->TAKEPOS_PRINTED_CATEGORIES_3, ';'.$row["rowid"].';') !== false) { + $checked = 'checked'; + } else { + $checked = ''; + } + if ($row["fk_menu"] == 0) { + print '<input type="checkbox" name="printer3[]" value="'.$row["rowid"].'" '.$checked.'>'.$row["label"].'<br>'; + } } print '</td></tr>'; } else { diff --git a/htdocs/takepos/admin/other.php b/htdocs/takepos/admin/other.php index e0beeedf502..7d0ce8897e3 100644 --- a/htdocs/takepos/admin/other.php +++ b/htdocs/takepos/admin/other.php @@ -36,7 +36,9 @@ if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY_id'])) { } // Security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $langs->loadLangs(array("admin", "cashdesk")); @@ -61,7 +63,9 @@ if ($resql) { if (GETPOST('action', 'alpha') == 'set') { $db->begin(); - if (GETPOST('socid', 'int') < 0) $_POST["socid"] = ''; + if (GETPOST('socid', 'int') < 0) { + $_POST["socid"] = ''; + } $res = dolibarr_set_const($db, "CASHDESK_SERVICES", GETPOST('CASHDESK_SERVICES', 'alpha'), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "TAKEPOS_ROOT_CATEGORY_ID", GETPOST('TAKEPOS_ROOT_CATEGORY_ID', 'alpha'), 'chaine', 0, '', $conf->entity); @@ -86,7 +90,9 @@ if (GETPOST('action', 'alpha') == 'set') { dol_syslog("admin/cashdesk: level ".GETPOST('level', 'alpha')); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } if (!$error) { $db->commit(); diff --git a/htdocs/takepos/admin/printqr.php b/htdocs/takepos/admin/printqr.php index d459fedf58f..87f742fe544 100644 --- a/htdocs/takepos/admin/printqr.php +++ b/htdocs/takepos/admin/printqr.php @@ -24,7 +24,9 @@ require '../../main.inc.php'; // Security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $langs->load("cashdesk"); @@ -37,8 +39,7 @@ print '<center>'; if (GETPOSTISSET("id")) { print '<h1><b>'.$langs->trans("ScanToOrder").'</b></h1>'; print "<img src='".DOL_URL_ROOT."/takepos/genimg/qr.php?key=".dol_encode($id)."' width='30%'>"; -} -else { +} else { print '<h1><b>'.$langs->trans("ScanToMenu").'</b></h1>'; print "<img src='".DOL_URL_ROOT."/takepos/genimg/qr.php' width='30%'>"; } diff --git a/htdocs/takepos/admin/receipt.php b/htdocs/takepos/admin/receipt.php index 01873d317c4..8c201949034 100644 --- a/htdocs/takepos/admin/receipt.php +++ b/htdocs/takepos/admin/receipt.php @@ -2,6 +2,7 @@ /* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2011-2017 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2019 Andreu Bisquerra Gaya <jove@bisquerra.com> + * Copyright (C) 2021 Nicolas ZABOURI <info@inovea-conseil.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -30,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; require_once DOL_DOCUMENT_ROOT."/core/lib/takepos.lib.php"; // Security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $langs->loadLangs(array("admin", "cashdesk", "commercial")); @@ -38,8 +41,7 @@ $langs->loadLangs(array("admin", "cashdesk", "commercial")); * Actions */ -if (GETPOST('action', 'alpha') == 'set') -{ +if (GETPOST('action', 'alpha') == 'set') { $db->begin(); $res = dolibarr_set_const($db, "TAKEPOS_HEADER", GETPOST('TAKEPOS_HEADER', 'alpha'), 'chaine', 0, '', $conf->entity); @@ -52,21 +54,23 @@ if (GETPOST('action', 'alpha') == 'set') dol_syslog("admin/cashdesk: level ".GETPOST('level', 'alpha')); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { $db->rollback(); setEventMessages($langs->trans("Error"), null, 'errors'); } -} elseif (GETPOST('action', 'alpha') == 'setmethod') -{ +} elseif (GETPOST('action', 'alpha') == 'setmethod') { dolibarr_set_const($db, "TAKEPOS_PRINT_METHOD", GETPOST('value', 'alpha'), 'chaine', 0, '', $conf->entity); // TakePOS connector require ReceiptPrinter module - if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector" && !$conf->receiptprinter->enabled) activateModule("modReceiptPrinter"); + if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector" && !$conf->receiptprinter->enabled) { + activateModule("modReceiptPrinter"); + } } @@ -102,8 +106,7 @@ print $langs->trans('Browser'); print '<td>'; print $langs->trans('BrowserMethodDescription'); print '</td><td class="right">'; -if ($conf->global->TAKEPOS_PRINT_METHOD == "browser") -{ +if ($conf->global->TAKEPOS_PRINT_METHOD == "browser") { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setmethod&token='.newToken().'&value=browser">'.img_picto($langs->trans("Disabled"), 'switch_off').'</a>'; @@ -137,8 +140,7 @@ print "TakePOS Connector"; print '<td>'; print $langs->trans('TakeposConnectorMethodDescription'); print '</td><td class="right">'; -if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") -{ +if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setmethod&token='.newToken().'&value=takeposconnector">'.img_picto($langs->trans("Disabled"), 'switch_off').'</a>'; @@ -176,15 +178,16 @@ if ($conf->global->TAKEPOS_PRINT_METHOD == "browser" || $conf->global->TAKEPOS_P $substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = '<i>'.$langs->trans("AvailableVariables").':<br>'; - foreach ($substitutionarray as $key => $val) $htmltext .= $key.'<br>'; + foreach ($substitutionarray as $key => $val) { + $htmltext .= $key.'<br>'; + } $htmltext .= '</i>'; print '<tr class="oddeven"><td>'; print $form->textwithpicto($langs->trans("FreeLegalTextOnInvoices")." - ".$langs->trans("Header"), $htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'<br>'; print '</td><td>'; $variablename = 'TAKEPOS_HEADER'; - if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) - { + if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print '<textarea name="'.$variablename.'" class="flat" cols="120">'.$conf->global->$variablename.'</textarea>'; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -197,8 +200,7 @@ if ($conf->global->TAKEPOS_PRINT_METHOD == "browser" || $conf->global->TAKEPOS_P print $form->textwithpicto($langs->trans("FreeLegalTextOnInvoices")." - ".$langs->trans("Footer"), $htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'<br>'; print '</td><td>'; $variablename = 'TAKEPOS_FOOTER'; - if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) - { + if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print '<textarea name="'.$variablename.'" class="flat" cols="120">'.$conf->global->$variablename.'</textarea>'; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -233,6 +235,14 @@ print '<td colspan="2">'; print $form->selectyesno("TAKEPOS_AUTO_PRINT_TICKETS", $conf->global->TAKEPOS_AUTO_PRINT_TICKETS, 1); print "</td></tr>\n"; + +// Show price without vat +print '<tr class="oddeven"><td>'; +print $langs->trans('ShowPriceHTOnReceipt'); +print '<td colspan="2">'; +print ajax_constantonoff("TAKEPOS_SHOW_HT_RECEIPT", array(), $conf->entity, 0, 0, 1, 0); +print "</td></tr>\n"; + if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector" && filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) { print '<tr class="oddeven"><td>'; print $langs->trans('WeighingScale'); diff --git a/htdocs/takepos/admin/setup.php b/htdocs/takepos/admin/setup.php index f3c17f6ee23..67bc8edcdf3 100644 --- a/htdocs/takepos/admin/setup.php +++ b/htdocs/takepos/admin/setup.php @@ -1,6 +1,7 @@ <?php /* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2011-2017 Juanjo Menent <jmenent@2byte.es> + * Copyright (C) 2021 Nicolas ZABOURI <info@inovea-conseil.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -31,15 +32,16 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/takepos.lib.php"; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; // If socid provided by ajax company selector -if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY_id'])) -{ +if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY_id'])) { $_GET['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); $_POST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); $_REQUEST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); } // Security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $langs->loadLangs(array("admin", "cashdesk")); @@ -66,10 +68,11 @@ $action = GETPOST('action', 'aZ09'); $error = 0; -if ($action == 'set') -{ +if ($action == 'set') { $db->begin(); - if (GETPOST('socid', 'int') < 0) $_POST["socid"] = ''; + if (GETPOST('socid', 'int') < 0) { + $_POST["socid"] = ''; + } $res = dolibarr_set_const($db, "TAKEPOS_ROOT_CATEGORY_ID", GETPOST('TAKEPOS_ROOT_CATEGORY_ID', 'alpha'), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "TAKEPOS_SUPPLEMENTS_CATEGORY", GETPOST('TAKEPOS_SUPPLEMENTS_CATEGORY', 'alpha'), 'chaine', 0, '', $conf->entity); @@ -85,10 +88,11 @@ if ($action == 'set') dol_syslog("admin/cashdesk: level ".GETPOST('level', 'alpha')); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -96,7 +100,9 @@ if ($action == 'set') } elseif ($action == 'updateMask') { $maskconst = GETPOST('maskconst', 'alpha'); $maskvalue = GETPOST('maskvalue', 'alpha'); - if ($maskconst) $res = dolibarr_set_const($db, $maskconst, $maskvalue, 'chaine', 0, '', $conf->entity); + if ($maskconst) { + $res = dolibarr_set_const($db, $maskconst, $maskvalue, 'chaine', 0, '', $conf->entity); + } if (!($res > 0)) { $error++; } @@ -121,7 +127,9 @@ if ($action != '') { $form = new Form($db); $formproduct = new FormProduct($db); -llxHeader('', $langs->trans("CashDeskSetup")); +$help_url = 'EN:Module_Point_of_sale_(TakePOS)'; + +llxHeader('', $langs->trans("CashDeskSetup"), $help_url); $linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php">'.$langs->trans("BackToModuleList").'</a>'; print load_fiche_titre($langs->trans("CashDeskSetup").' (TakePOS)', $linkback, 'title_setup'); @@ -145,21 +153,16 @@ print '</tr>'."\n"; clearstatcache(); -foreach ($dirmodels as $reldir) -{ +foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/takepos/"); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { + if (is_resource($handle)) { $var = true; - while (($file = readdir($handle)) !== false) - { - if (substr($file, 0, 16) == 'mod_takepos_ref_' && substr($file, dol_strlen($file) - 3, 3) == 'php') - { + while (($file = readdir($handle)) !== false) { + if (substr($file, 0, 16) == 'mod_takepos_ref_' && substr($file, dol_strlen($file) - 3, 3) == 'php') { $file = substr($file, 0, dol_strlen($file) - 4); require_once $dir.$file.'.php'; @@ -167,11 +170,14 @@ foreach ($dirmodels as $reldir) $module = new $file; // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } - if ($module->isEnabled()) - { + if ($module->isEnabled()) { print '<tr class="oddeven"><td>'.$module->nom."</td><td>\n"; print $module->info(); print '</td>'; @@ -182,13 +188,15 @@ foreach ($dirmodels as $reldir) if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '<div class="error">'.$langs->trans($tmp).'</div>'; - } elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); - else print $tmp; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; + } print '</td>'."\n"; print '<td align="center">'; - if ($conf->global->TAKEPOS_REF_ADDON == "$file") - { + if ($conf->global->TAKEPOS_REF_ADDON == "$file") { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print '<a href="'.$_SERVER["PHP_SELF"].'?action=setrefmod&amp;token='.newToken().'&amp;value='.urlencode($file).'">'; @@ -210,8 +218,9 @@ foreach ($dirmodels as $reldir) if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { $nextval = $langs->trans($nextval); + } $htmltooltip .= $nextval.'<br>'; } else { $htmltooltip .= $langs->trans($module->error).'<br>'; @@ -255,8 +264,7 @@ print $form->selectarray('TAKEPOS_NUM_TERMINALS', $array, (empty($conf->global-> print "</td></tr>\n"; // Services -if (!empty($conf->service->enabled)) -{ +if (!empty($conf->service->enabled)) { print '<tr class="oddeven"><td>'; print $langs->trans("CashdeskShowServices"); print '<td colspan="2">'; @@ -291,7 +299,9 @@ print "</td></tr>\n"; $substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = '<i>'.$langs->trans("AvailableVariables").':<br>'; -foreach ($substitutionarray as $key => $val) $htmltext .= $key.'<br>'; +foreach ($substitutionarray as $key => $val) { + $htmltext .= $key.'<br>'; +} $htmltext .= '</i>'; // Payment numpad @@ -371,6 +381,13 @@ print '<td colspan="2">'; print ajax_constantonoff("TAKEPOS_DELAYED_PAYMENT", array(), $conf->entity, 0, 0, 1, 0); print "</td></tr>\n"; +// Show price without vat +print '<tr class="oddeven"><td>'; +print $langs->trans('ShowPriceHT'); +print '<td colspan="2">'; +print ajax_constantonoff("TAKEPOS_SHOW_HT", array(), $conf->entity, 0, 0, 1, 0); +print "</td></tr>\n"; + // Numbering module //print '<tr class="oddeven"><td>'; //print $langs->trans("BillsNumberingModule"); diff --git a/htdocs/takepos/admin/terminal.php b/htdocs/takepos/admin/terminal.php index ed4ef31af36..3e5bb4ccc46 100644 --- a/htdocs/takepos/admin/terminal.php +++ b/htdocs/takepos/admin/terminal.php @@ -31,15 +31,16 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/takepos.lib.php"; $terminal = GETPOST('terminal', 'int'); // If socid provided by ajax company selector -if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY'.$terminal.'_id'])) -{ +if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY'.$terminal.'_id'])) { $_GET['CASHDESK_ID_THIRDPARTY'.$terminal] = GETPOST('CASHDESK_ID_THIRDPARTY'.$terminal.'_id', 'alpha'); $_POST['CASHDESK_ID_THIRDPARTY'.$terminal] = GETPOST('CASHDESK_ID_THIRDPARTY'.$terminal.'_id', 'alpha'); $_REQUEST['CASHDESK_ID_THIRDPARTY'.$terminal] = GETPOST('CASHDESK_ID_THIRDPARTY'.$terminal.'_id', 'alpha'); } // Security check -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $langs->loadLangs(array("admin", "cashdesk", "printing", "receiptprinter")); @@ -64,10 +65,11 @@ $terminaltouse = $terminal; * Actions */ -if (GETPOST('action', 'alpha') == 'set') -{ +if (GETPOST('action', 'alpha') == 'set') { $db->begin(); - if (GETPOST('socid', 'int') < 0) $_POST["socid"] = ''; + if (GETPOST('socid', 'int') < 0) { + $_POST["socid"] = ''; + } $res = dolibarr_set_const($db, "CASHDESK_ID_THIRDPARTY".$terminaltouse, (GETPOST('socid', 'int') > 0 ? GETPOST('socid', 'int') : ''), 'chaine', 0, '', $conf->entity); @@ -78,7 +80,9 @@ if (GETPOST('action', 'alpha') == 'set') $res = dolibarr_set_const($db, "CASHDESK_ID_BANKACCOUNT_SUMUP".$terminaltouse, (GETPOST('CASHDESK_ID_BANKACCOUNT_SUMUP'.$terminaltouse, 'alpha') > 0 ? GETPOST('CASHDESK_ID_BANKACCOUNT_SUMUP'.$terminaltouse, 'alpha') : ''), 'chaine', 0, '', $conf->entity); } foreach ($paiements as $modep) { - if (in_array($modep->code, array('LIQ', 'CB', 'CHQ'))) continue; + if (in_array($modep->code, array('LIQ', 'CB', 'CHQ'))) { + continue; + } $name = "CASHDESK_ID_BANKACCOUNT_".$modep->code.$terminaltouse; $res = dolibarr_set_const($db, $name, (GETPOST($name, 'alpha') > 0 ? GETPOST($name, 'alpha') : ''), 'chaine', 0, '', $conf->entity); } @@ -101,10 +105,11 @@ if (GETPOST('action', 'alpha') == 'set') dol_syslog("admin/cashdesk: level ".GETPOST('level', 'alpha')); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -147,45 +152,55 @@ print $form->select_company($conf->global->{'CASHDESK_ID_THIRDPARTY'.$terminalto print '</td></tr>'; $atleastonefound = 0; -if (!empty($conf->banque->enabled)) -{ +if (!empty($conf->banque->enabled)) { print '<tr class="oddeven"><td>'.$langs->trans("CashDeskBankAccountForSell").'</td>'; print '<td>'; $form->select_comptes($conf->global->{'CASHDESK_ID_BANKACCOUNT_CASH'.$terminaltouse}, 'CASHDESK_ID_BANKACCOUNT_CASH'.$terminaltouse, 0, "courant=2", 1); - if (!empty($conf->global->{'CASHDESK_ID_BANKACCOUNT_CASH'.$terminaltouse})) $atleastonefound++; + if (!empty($conf->global->{'CASHDESK_ID_BANKACCOUNT_CASH'.$terminaltouse})) { + $atleastonefound++; + } print '</td></tr>'; print '<tr class="oddeven"><td>'.$langs->trans("CashDeskBankAccountForCheque").'</td>'; print '<td>'; $form->select_comptes($conf->global->{'CASHDESK_ID_BANKACCOUNT_CHEQUE'.$terminaltouse}, 'CASHDESK_ID_BANKACCOUNT_CHEQUE'.$terminaltouse, 0, "courant=1", 1); - if (!empty($conf->global->{'CASHDESK_ID_BANKACCOUNT_CHEQUE'.$terminaltouse})) $atleastonefound++; + if (!empty($conf->global->{'CASHDESK_ID_BANKACCOUNT_CHEQUE'.$terminaltouse})) { + $atleastonefound++; + } print '</td></tr>'; print '<tr class="oddeven"><td>'.$langs->trans("CashDeskBankAccountForCB").'</td>'; print '<td>'; $form->select_comptes($conf->global->{'CASHDESK_ID_BANKACCOUNT_CB'.$terminaltouse}, 'CASHDESK_ID_BANKACCOUNT_CB'.$terminaltouse, 0, "courant=1", 1); - if (!empty($conf->global->{'CASHDESK_ID_BANKACCOUNT_CB'.$terminaltouse})) $atleastonefound++; + if (!empty($conf->global->{'CASHDESK_ID_BANKACCOUNT_CB'.$terminaltouse})) { + $atleastonefound++; + } print '</td></tr>'; if ($conf->global->TAKEPOS_ENABLE_SUMUP) { print '<tr class="oddeven"><td>'.$langs->trans("CashDeskBankAccountForSumup").'</td>'; print '<td>'; $form->select_comptes($conf->global->{'CASHDESK_ID_BANKACCOUNT_SUMUP'.$terminaltouse}, 'CASHDESK_ID_BANKACCOUNT_SUMUP'.$terminaltouse, 0, "courant=1", 1); - if (!empty($conf->global->{'CASHDESK_ID_BANKACCOUNT_SUMUP'.$terminaltouse})) $atleastonefound++; + if (!empty($conf->global->{'CASHDESK_ID_BANKACCOUNT_SUMUP'.$terminaltouse})) { + $atleastonefound++; + } print '</td></tr>'; } foreach ($paiements as $modep) { - if (in_array($modep->code, array('LIQ', 'CB', 'CHQ'))) continue; // Already managed before + if (in_array($modep->code, array('LIQ', 'CB', 'CHQ'))) { + continue; // Already managed before + } $name = "CASHDESK_ID_BANKACCOUNT_".$modep->code.$terminaltouse; print '<tr class="oddeven"><td>'.$langs->trans("CashDeskBankAccountFor").' '.$langs->trans($modep->label).'</td>'; print '<td>'; - if (!empty($conf->global->$name)) $atleastonefound++; + if (!empty($conf->global->$name)) { + $atleastonefound++; + } $cour = preg_match('/^LIQ.*/', $modep->code) ? 2 : 1; $form->select_comptes($conf->global->$name, $name, 0, "courant=".$cour, 1); print '</td></tr>'; } } -if (!empty($conf->stock->enabled)) -{ +if (!empty($conf->stock->enabled)) { print '<tr class="oddeven"><td>'.$langs->trans("CashDeskDoNotDecreaseStock").'</td>'; // Force warehouse (this is not a default value) print '<td>'; if (empty($conf->productbatch->enabled) || !empty($conf->global->CASHDESK_FORCE_DECREASE_STOCK)) { @@ -204,8 +219,7 @@ if (!empty($conf->stock->enabled)) print '<tr class="oddeven"><td>'.$langs->trans("CashDeskIdWareHouse").'</td>'; // Force warehouse (this is not a default value) print '<td class="minwidth300">'; - if (!$disabled) - { + if (!$disabled) { print $formproduct->selectWarehouses($conf->global->{'CASHDESK_ID_WAREHOUSE'.$terminal}, 'CASHDESK_ID_WAREHOUSE'.$terminal, '', 1, $disabled, 0, '', 0, 0, array(), 'maxwidth250'); print ' <a href="'.DOL_URL_ROOT.'/product/stock/card.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?&terminal='.$terminal).'"><span class="fa fa-plus-circle valignmiddle"></span></a>'; } else { @@ -279,44 +293,42 @@ if ($conf->global->TAKEPOS_ADDON == "terminal") { print '<td colspan="2">'; $array = array(0=>$langs->trans("Default")); $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/facture/"); - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (!is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (!is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) { $filebis = $file; $classname = preg_replace('/\.php$/', '', $file); // For compatibility - if (!is_file($dir.$filebis)) - { + if (!is_file($dir.$filebis)) { $filebis = $file."/".$file.".modules.php"; $classname = "mod_facture_".$file; } // Check if there is a filter on country preg_match('/\-(.*)_(.*)$/', $classname, $reg); - if (!empty($reg[2]) && $reg[2] != strtoupper($mysoc->country_code)) continue; + if (!empty($reg[2]) && $reg[2] != strtoupper($mysoc->country_code)) { + continue; + } $classname = preg_replace('/\-.*$/', '', $classname); - if (!class_exists($classname) && is_readable($dir.$filebis) && (preg_match('/mod_/', $filebis) || preg_match('/mod_/', $classname)) && substr($filebis, dol_strlen($filebis) - 3, 3) == 'php') - { + if (!class_exists($classname) && is_readable($dir.$filebis) && (preg_match('/mod_/', $filebis) || preg_match('/mod_/', $classname)) && substr($filebis, dol_strlen($filebis) - 3, 3) == 'php') { // Charging the numbering class require_once $dir.$filebis; $module = new $classname($db); // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } - if ($module->isEnabled()) - { + if ($module->isEnabled()) { $array[preg_replace('/\-.*$/', '', preg_replace('/\.php$/', '', $file))] = preg_replace('/\-.*$/', '', preg_replace('/mod_facture_/', '', preg_replace('/\.php$/', '', $file))); } } @@ -339,7 +351,9 @@ print '</div>'; $substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__'] = $langs->trans('Translation'); $htmltext = '<i>'.$langs->trans('AvailableVariables').':<br>'; -foreach ($substitutionarray as $key => $val) $htmltext .= $key.'<br>'; +foreach ($substitutionarray as $key => $val) { + $htmltext .= $key.'<br>'; +} $htmltext .= '</i>'; print '<br>'; @@ -386,8 +400,7 @@ print '</td></tr>'; print '</table>'; print '</div>'; -if ($atleastonefound == 0 && !empty($conf->banque->enabled)) -{ +if ($atleastonefound == 0 && !empty($conf->banque->enabled)) { print info_admin($langs->trans("AtLeastOneDefaultBankAccountMandatory"), 0, 0, 'error'); } diff --git a/htdocs/takepos/ajax/ajax.php b/htdocs/takepos/ajax/ajax.php index 6da8c74361c..136841a8683 100644 --- a/htdocs/takepos/ajax/ajax.php +++ b/htdocs/takepos/ajax/ajax.php @@ -25,17 +25,29 @@ //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} require '../../main.inc.php'; // Load $user and permissions require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; -$category = GETPOST('category', 'alpha'); +$category = GETPOST('category', 'alphanohtml'); // Can be id of category or 'supplements' $action = GETPOST('action', 'aZ09'); $term = GETPOST('term', 'alpha'); $id = GETPOST('id', 'int'); @@ -51,16 +63,15 @@ if (empty($user->rights->takepos->run)) { if ($action == 'getProducts') { $object = new Categorie($db); - if ($category == "supplements") $category = $conf->global->TAKEPOS_SUPPLEMENTS_CATEGORY; + if ($category == "supplements") { + $category = $conf->global->TAKEPOS_SUPPLEMENTS_CATEGORY; + } $result = $object->fetch($category); - if ($result > 0) - { + if ($result > 0) { $prods = $object->getObjectsInCateg("product", 0, 0, 0, $conf->global->TAKEPOS_SORTPRODUCTFIELD, 'ASC'); // Removed properties we don't need - if (is_array($prods) && count($prods) > 0) - { - foreach ($prods as $prod) - { + if (is_array($prods) && count($prods) > 0) { + foreach ($prods as $prod) { unset($prod->fields); unset($prod->db); } @@ -95,8 +106,7 @@ if ($action == 'getProducts') { //$result = $object->fetch($conf->global->TAKEPOS_ROOT_CATEGORY_ID); $arrayofcateg = $object->get_full_arbo('product', $conf->global->TAKEPOS_ROOT_CATEGORY_ID, 1); if (is_array($arrayofcateg) && count($arrayofcateg) > 0) { - foreach ($arrayofcateg as $val) - { + foreach ($arrayofcateg as $val) { $filteroncategids .= ($filteroncategids ? ', ' : '').$val['id']; } } @@ -110,8 +120,7 @@ if ($action == 'getProducts') { $sql .= ' AND tosell = 1'; $sql .= natural_search(array('ref', 'label', 'barcode'), $term); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $rows = array(); while ($obj = $db->fetch_object($resql)) { $rows[] = array( diff --git a/htdocs/takepos/css/pos.css.php b/htdocs/takepos/css/pos.css.php index 6cd6073eb48..589c10ddf62 100644 --- a/htdocs/takepos/css/pos.css.php +++ b/htdocs/takepos/css/pos.css.php @@ -27,14 +27,26 @@ //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled because need to load personalized language //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled to increase speed. Language code is found on url. -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Not disabled because need to do translations -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); -if (!defined('NOLOGIN')) define('NOLOGIN', 1); // File must be accessed by logon page so without login +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', 1); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', 1); // File must be accessed by logon page so without login +} //if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU',1); // We need top menu content -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', 1); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} define('ISLOADEDBYSTEELSHEET', '1'); @@ -48,25 +60,30 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; // Define css type top_httphead('text/css'); // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. -if (empty($dolibarr_nocache)) header('Cache-Control: max-age=10800, public, must-revalidate'); -else header('Cache-Control: no-cache'); +if (empty($dolibarr_nocache)) { + header('Cache-Control: max-age=10800, public, must-revalidate'); +} else { + header('Cache-Control: no-cache'); +} require DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; -if (defined('THEME_ONLY_CONSTANT')) return; +if (defined('THEME_ONLY_CONSTANT')) { + return; +} ?> html,body { - box-sizing: border-box; + box-sizing: border-box; padding:0px; - margin:0; - height:100%; + margin:0; + height:100%; width:100%; } .bodytakepos { - background-color: #EEE; + background-color: #EEE; } .center { @@ -74,14 +91,14 @@ html,body { } button.calcbutton.poscolorblue { - background-color: #0066AA; + background-color: #0066AA; } button.calcbutton2.poscolordelete { background: rgb(255, 188, 185); - color: #633; - /*background-color: #884444; - color: #fff;*/ + color: #633; + /*background-color: #884444; + color: #fff;*/ } button.calcbutton { @@ -96,19 +113,19 @@ button.calcbutton { width: calc(25% - 2px); height: calc(25% - 2px); font-weight: bold; - background-color: #8c907e; - color: #fff; - /* border-color: unset; */ - border-width: 0; - margin: 1px; + background-color: #8c907e; + color: #fff; + /* border-color: unset; */ + border-width: 0; + margin: 1px; font-size: 14pt; - border-radius: 3px; + border-radius: 3px; } button.calcbutton2 { - color: #fff; - background-color: #5555AA; - border-width: 0px; + color: #fff; + background-color: #5555AA; + border-width: 0px; display: inline-block; position: relative; padding: 0; @@ -122,7 +139,7 @@ button.calcbutton2 { font-weight: bold; font-size: 10pt; margin: 1px; - border-radius: 3px; + border-radius: 3px; } button.calcbutton2 .iconwithlabel { @@ -142,7 +159,7 @@ button.calcbutton3 { height: calc(25% - 2px); font-size: 14pt; margin: 1px; - border-radius: 3px; + border-radius: 3px; } button.productbutton { @@ -157,20 +174,20 @@ button.productbutton { width: calc(100% - 2px); height: calc(100% - 2px); font-weight: bold; - background-color: #a3a6a3; - color: #fff; - /* border-color: unset; */ - border-width: 0; - margin: 1px; + background-color: #a3a6a3; + color: #fff; + /* border-color: unset; */ + border-width: 0; + margin: 1px; font-size: 14pt; - border-radius: 3px; + border-radius: 3px; } button.actionbutton { - background: #EABCA6; - border: 2px solid #EEE; - min-height: 40px; - border-radius: 3px; + background: #EABCA6; + border: 2px solid #EEE; + min-height: 40px; + border-radius: 3px; } button.actionbutton { @@ -185,7 +202,7 @@ button.actionbutton { width: calc(33.33% - 2px); height: calc(25% - 2px); margin: 1px; - border-width: 0; + border-width: 0; } button.item_value { @@ -202,10 +219,10 @@ button.item_value.selected { } div[aria-describedby="dialog-info"] button:before { - content: "\f788"; - font-family: "Font Awesome 5 Free"; - font-weight: 900; - padding-right: 5px; + content: "\f788"; + font-family: "Font Awesome 5 Free"; + font-weight: 900; + padding-right: 5px; } div[aria-describedby="dialog-info"].ui-dialog .ui-dialog-buttonpane { border-width: 0; @@ -216,7 +233,7 @@ div[aria-describedby="dialog-info"].ui-dialog .ui-dialog-buttonpane { } .fa.fa-trash:before { - font-size: 1.5em; + font-size: 1.5em; } @@ -249,11 +266,11 @@ div.wrapper2{ } img.imgwrapper { - max-width: 100%; + max-width: 100%; } button:active{ - background:black; + background:black; color: white; } @@ -270,7 +287,7 @@ div.description{ text-align:center; padding-top: 30px; - background: -webkit-linear-gradient(top, rgba(250,250,250,0), rgba(250,250,250,0.5), rgba(250,250,250,0.95), rgba(250,250,250,1)); + background: -webkit-linear-gradient(top, rgba(250,250,250,0), rgba(250,250,250,0.5), rgba(250,250,250,0.95), rgba(250,250,250,1)); } div.catwatermark{ @@ -288,17 +305,17 @@ div.catwatermark{ table.postablelines tr td { line-height: unset; - padding-top: 3px; - padding-bottom: 3px; + padding-top: 3px; + padding-bottom: 3px; } .posinvoiceline td { - height: 40px !important; - background-color: var(--colorbacklineimpair1); + height: 40px !important; + background-color: var(--colorbacklineimpair1); } .postablelines td.linecolht { - line-height: 1.3em !important; + line-height: 1.3em !important; } div.paymentbordline @@ -414,11 +431,11 @@ div.paymentbordline } tr.selected, tr.selected td { - /* font-weight: bold; */ + /* font-weight: bold; */ background-color: rgb(240,230,210) !important; } .order { - color: limegreen; + color: limegreen; } .colorwhite { @@ -442,13 +459,13 @@ tr.selected, tr.selected td { .centerinmiddle { transform: translate(0,-50%); - position: relative; - top: 50%; + position: relative; + top: 50%; } .trunc { - white-space: nowrap; - text-overflow: ellipsis; - overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; } p.description_content{ @@ -457,11 +474,11 @@ p.description_content{ } div.description_content { display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: <?php echo $conf->global->TAKEPOS_LINES_TO_SHOW; ?>; - overflow: hidden; - padding-left: 2px; - padding-right: 2px; + -webkit-box-orient: vertical; + -webkit-line-clamp: <?php echo $conf->global->TAKEPOS_LINES_TO_SHOW; ?>; + overflow: hidden; + padding-left: 2px; + padding-right: 2px; } .header{ @@ -488,7 +505,7 @@ div.description_content { height: 100%; } .topnav .tmenu { - display: block; + display: block; } .topnav a{ @@ -498,8 +515,8 @@ div.description_content { } .topnav .login_block_other a { padding: 5px 10px; - margin-left: 4px; - font-size: 1.3em; + margin-left: 4px; + font-size: 1.3em; } @media screen and (max-width: 767px) { @@ -515,8 +532,8 @@ div.description_content { .topnav-left a { padding: 7px 4px 7px 4px; - margin: 8px; - margin-left: 4px; + margin: 8px; + margin-left: 4px; } .topnav-left a:hover, .topnav .login_block_other a:hover { background-color: #ddd; @@ -534,27 +551,27 @@ div.description_content { border-bottom: none !important; margin-left: 6px; font-size: 1.3em; - max-width: 250px; - border-radius: 5px; + max-width: 250px; + border-radius: 5px; } div#moreinfo, div#infowarehouse { - color: #aaa; - padding: 0 8px 0 8px; + color: #aaa; + padding: 0 8px 0 8px; } .productprice { - position: absolute; - top: 5px; - right: 5px; - background: var(--colorbackhmenu1); - color: var(--colortextbackhmenu); - font-size: 2em; - padding: 5px; - border-radius: 2px; - opacity: 0.9; - padding-left: 8px; - padding-right: 8px; + position: absolute; + top: 5px; + right: 5px; + background: var(--colorbackhmenu1); + color: var(--colortextbackhmenu); + font-size: 2em; + padding: 5px; + border-radius: 2px; + opacity: 0.9; + padding-left: 8px; + padding-right: 8px; } @@ -604,9 +621,9 @@ div#moreinfo, div#infowarehouse { @media screen and (max-width: 767px) { .header { - position: sticky; - top: 0; - z-index: 10; + position: sticky; + top: 0; + z-index: 10; } .topnav input[type="text"] { @@ -634,7 +651,7 @@ div#moreinfo, div#infowarehouse { } div#moreinfo, div#infowarehouse { - padding: 0 5px 0 5px; + padding: 0 5px 0 5px; } div.div1 { @@ -659,7 +676,7 @@ div#moreinfo, div#infowarehouse { } button.calcbutton, button.calcbutton2 { - min-height: 30px; + min-height: 30px; } .takepospay { diff --git a/htdocs/takepos/floors.php b/htdocs/takepos/floors.php index 72f25a86ce4..92d7e8288e1 100644 --- a/htdocs/takepos/floors.php +++ b/htdocs/takepos/floors.php @@ -25,11 +25,21 @@ //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} require '../main.inc.php'; // Load $user and permissions require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; @@ -37,7 +47,9 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $langs->loadLangs(array("bills", "orders", "commercial", "cashdesk")); $floor = GETPOST('floor', 'int'); -if ($floor == "") $floor = 1; +if ($floor == "") { + $floor = 1; +} $id = GETPOST('id', 'int'); $action = GETPOST('action', 'aZ09'); $left = GETPOST('left', 'alpha'); @@ -57,38 +69,45 @@ if (empty($user->rights->takepos->run)) { * Actions */ -if ($action == "getTables") -{ +if ($action == "getTables") { $sql = "SELECT rowid, entity, label, leftpos, toppos, floor FROM ".MAIN_DB_PREFIX."takepos_floor_tables where floor=".$floor; $resql = $db->query($sql); $rows = array(); while ($row = $db->fetch_array($resql)) { $invoice = new Facture($db); $result = $invoice->fetch('', '(PROV-POS'.$_SESSION['takeposterminal'].'-'.$row['rowid'].')'); - if ($result > 0) $row['occupied'] = "red"; + if ($result > 0) { + $row['occupied'] = "red"; + } $rows[] = $row; } echo json_encode($rows); exit; } -if ($action == "update") -{ - if ($left > 95) $left = 95; - if ($top > 95) $top = 95; - if ($left > 3 or $top > 4) $db->query("UPDATE ".MAIN_DB_PREFIX."takepos_floor_tables set leftpos=".$left.", toppos=".$top." WHERE rowid='".$place."'"); - else $db->query("DELETE from ".MAIN_DB_PREFIX."takepos_floor_tables where rowid='".$place."'"); +if ($action == "update") { + if ($left > 95) { + $left = 95; + } + if ($top > 95) { + $top = 95; + } + if ($left > 3 or $top > 4) { + $db->query("UPDATE ".MAIN_DB_PREFIX."takepos_floor_tables set leftpos=".$left.", toppos=".$top." WHERE rowid='".$place."'"); + } else { + $db->query("DELETE from ".MAIN_DB_PREFIX."takepos_floor_tables where rowid='".$place."'"); + } } -if ($action == "updatename") -{ +if ($action == "updatename") { $newname = preg_replace("/[^a-zA-Z0-9\s]/", "", $newname); // Only English chars - if (strlen($newname) > 3) $newname = substr($newname, 0, 3); // Only 3 chars + if (strlen($newname) > 3) { + $newname = substr($newname, 0, 3); // Only 3 chars + } $db->query("UPDATE ".MAIN_DB_PREFIX."takepos_floor_tables set label='".$db->escape($newname)."' WHERE rowid='".$place."'"); } -if ($action == "add") -{ +if ($action == "add") { $sql = "INSERT INTO ".MAIN_DB_PREFIX."takepos_floor_tables(entity, label, leftpos, toppos, floor) VALUES (".$conf->entity.", '', '45', '45', ".$floor.")"; $asdf = $db->query($sql); $db->query("update ".MAIN_DB_PREFIX."takepos_floor_tables set label=rowid where label=''"); // No empty table names @@ -101,7 +120,9 @@ if ($action == "add") // Title $title = 'TakePOS - Dolibarr '.DOL_VERSION; -if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = 'TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $title = 'TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; +} top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); ?> <link rel="stylesheet" href="css/pos.css.php?a=xxx"> @@ -159,14 +180,14 @@ function LoadPlace(place){ $( document ).ready(function() { $.getJSON('./floors.php?action=getTables&floor=<?php echo $floor; ?>', function(data) { - $.each(data, function(key, val) { + $.each(data, function(key, val) { <?php if ($mode == "edit") {?> $('body').append('<div class="tablediv" contenteditable onblur="updatename('+val.rowid+');" style="position: absolute; left: '+val.leftpos+'%; top: '+val.toppos+'%;" id="tablename'+val.rowid+'">'+val.label+'</div>'); $( "#tablename"+val.rowid ).draggable( { start: function() { $("#add").html("<?php echo $langs->trans("Delete"); ?>"); - }, + }, stop: function() { var left=$(this).offset().left*100/$(window).width(); var top=$(this).offset().top*100/$(window).height(); @@ -190,25 +211,29 @@ $( document ).ready(function() { <body style="overflow: hidden"> <?php if ($user->admin) {?> <div style="position: absolute; left: 0.1%; top: 0.8%; width:8%; height:11%;"> - <?php if ($mode == "edit") {?> + <?php if ($mode == "edit") {?> <a id="add" onclick="window.location.href='floors.php?mode=edit&action=add&floor=<?php echo $floor; ?>';"><?php echo $langs->trans("AddTable"); ?></a> - <?php } else { ?> + <?php } else { ?> <a onclick="window.location.href='floors.php?mode=edit&floor=<?php echo $floor; ?>';"><?php echo $langs->trans("Edit"); ?></a> - <?php } ?> + <?php } ?> </div> <?php } ?> <div style="position: absolute; left: 25%; bottom: 8%; width:50%; height:3%;"> - <center> - <h1> - <?php if ($floor > 1) { ?> - <img class="valignmiddle" src="./img/arrow-prev.png" width="5%" onclick="location.href='floors.php?floor=<?php if ($floor > 1) { $floor--; echo $floor; $floor++; } else echo "1"; ?>';"> - <?php } ?> - <span class="valignmiddle"><?php echo $langs->trans("Floor")." ".$floor; ?></span> - <img src="./img/arrow-next.png" class="valignmiddle" width="5%" onclick="location.href='floors.php?floor=<?php $floor++; echo $floor; ?>';"> - </h1> - </center> + <center> + <h1> + <?php if ($floor > 1) { ?> + <img class="valignmiddle" src="./img/arrow-prev.png" width="5%" onclick="location.href='floors.php?floor=<?php if ($floor > 1) { + $floor--; echo $floor; $floor++; + } else { + echo "1"; + } ?>';"> + <?php } ?> + <span class="valignmiddle"><?php echo $langs->trans("Floor")." ".$floor; ?></span> + <img src="./img/arrow-next.png" class="valignmiddle" width="5%" onclick="location.href='floors.php?floor=<?php $floor++; echo $floor; ?>';"> + </h1> + </center> </div> </body> </html> diff --git a/htdocs/takepos/freezone.php b/htdocs/takepos/freezone.php index f8ed00c5590..7c1db7a84a3 100644 --- a/htdocs/takepos/freezone.php +++ b/htdocs/takepos/freezone.php @@ -26,11 +26,21 @@ //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} require '../main.inc.php'; // Load $user and permissions require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; @@ -61,8 +71,11 @@ if ($place > 0) { // get default vat rate $constforcompanyid = 'CASHDESK_ID_THIRDPARTY'.$_SESSION['takeposterminal']; $soc = new Societe($db); -if ($invoice->socid > 0) $soc->fetch($invoice->socid); -else $soc->fetch($conf->global->$constforcompanyid); +if ($invoice->socid > 0) { + $soc->fetch($invoice->socid); +} else { + $soc->fetch($conf->global->$constforcompanyid); +} $vatRateDefault = get_default_tva($mysoc, $soc); /* @@ -109,8 +122,12 @@ top_htmlhead($head, '', 0, 0, $arrayofjs, $arrayofcss); <center> <input type="text" id="desc" name="desc" class="takepospay" style="width:40%;" placeholder="<?php echo $langs->trans('Description'); ?>"> <?php -if ($action == "freezone") echo '<input type="text" id="number" name="number" class="takepospay" style="width:15%;" placeholder="'.$langs->trans('Price').'">'; -if ($action == "addnote") echo '<input type="hidden" id="number" name="number" value="'.$idline.'">'; +if ($action == "freezone") { + echo '<input type="text" id="number" name="number" class="takepospay" style="width:15%;" placeholder="'.$langs->trans('Price').'">'; +} +if ($action == "addnote") { + echo '<input type="hidden" id="number" name="number" value="'.$idline.'">'; +} ?> <input type="hidden" name="place" class="takepospay" value="<?php echo $place; ?>"> <input type="button" class="button takepospay clearboth" value="OK" onclick="Save();"> diff --git a/htdocs/takepos/genimg/index.php b/htdocs/takepos/genimg/index.php index bdd237d1a15..2725b0c8e87 100644 --- a/htdocs/takepos/genimg/index.php +++ b/htdocs/takepos/genimg/index.php @@ -17,15 +17,29 @@ //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} -if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) require '../../main.inc.php'; // Load $user and permissions +if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { + require '../../main.inc.php'; // Load $user and permissions +} $id = GETPOST('id', 'int'); $w = GETPOST('w', 'int'); @@ -38,8 +52,7 @@ $query = GETPOST('query', 'alpha'); * View */ -if ($query == "cat") -{ +if ($query == "cat") { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/categories.lib.php'; @@ -50,10 +63,8 @@ if ($query == "cat") $pdir = get_exdir($object->id, 2, 0, 0, $object, 'category').$object->id."/photos/"; $dir = $upload_dir.'/'.$pdir; - foreach ($object->liste_photos($dir) as $key => $obj) - { - if ($obj['photo_vignette']) - { + foreach ($object->liste_photos($dir) as $key => $obj) { + if ($obj['photo_vignette']) { $filename = $obj['photo_vignette']; } else { $filename = $obj['photo']; @@ -63,8 +74,7 @@ if ($query == "cat") exit; } header('Location: ../../public/theme/common/nophoto.png'); -} elseif ($query == "pro") -{ +} elseif ($query == "pro") { require_once DOL_DOCUMENT_ROOT."/product/class/product.class.php"; $objProd = new Product($db); diff --git a/htdocs/takepos/genimg/qr.php b/htdocs/takepos/genimg/qr.php index 452eb7023e2..0fae2c3e25f 100644 --- a/htdocs/takepos/genimg/qr.php +++ b/htdocs/takepos/genimg/qr.php @@ -15,14 +15,30 @@ * along with this program. If not, see <https://www.gnu.org/licenses/>. */ -if (!defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined("NOLOGIN")) { + define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} require '../../main.inc.php'; // Load $user and permissions require '../../core/modules/barcode/doc/tcpdfbarcode.modules.php'; @@ -34,8 +50,7 @@ if (GETPOSTISSET("key")) { $key = GETPOST('key'); $module = new modTcpdfbarcode(); $result = $module->buildBarCode($urlwithroot."/takepos/public/auto_order.php?key=".$key, 'QRCODE', 'Y'); -} -else { +} else { $module = new modTcpdfbarcode(); $result = $module->buildBarCode($urlwithroot."/takepos/public/menu.php", 'QRCODE', 'Y'); } diff --git a/htdocs/takepos/index.php b/htdocs/takepos/index.php index a08df6d2b43..432afdea73a 100644 --- a/htdocs/takepos/index.php +++ b/htdocs/takepos/index.php @@ -27,11 +27,21 @@ //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} require '../main.inc.php'; // Load $user and permissions require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; @@ -47,20 +57,20 @@ $action = GETPOST('action', 'aZ09'); $setterminal = GETPOST('setterminal', 'int'); $setcurrency = GETPOST('setcurrency', 'aZ09'); -if ($_SESSION["takeposterminal"] == "") -{ - if ($conf->global->TAKEPOS_NUM_TERMINALS == "1") $_SESSION["takeposterminal"] = 1; // Use terminal 1 if there is only 1 terminal - elseif (!empty($_COOKIE["takeposterminal"])) $_SESSION["takeposterminal"] = preg_replace('/[^a-zA-Z0-9_\-]/', '', $_COOKIE["takeposterminal"]); // Restore takeposterminal from previous session +if ($_SESSION["takeposterminal"] == "") { + if ($conf->global->TAKEPOS_NUM_TERMINALS == "1") { + $_SESSION["takeposterminal"] = 1; // Use terminal 1 if there is only 1 terminal + } elseif (!empty($_COOKIE["takeposterminal"])) { + $_SESSION["takeposterminal"] = preg_replace('/[^a-zA-Z0-9_\-]/', '', $_COOKIE["takeposterminal"]); // Restore takeposterminal from previous session + } } -if ($setterminal > 0) -{ +if ($setterminal > 0) { $_SESSION["takeposterminal"] = $setterminal; setcookie("takeposterminal", $setterminal, (time() + (86400 * 354)), '/', null, false, true); // Permanent takeposterminal var in a cookie } -if ($setcurrency != "") -{ +if ($setcurrency != "") { $_SESSION["takeposcustomercurrency"] = $setcurrency; } @@ -72,13 +82,11 @@ $categorie = new Categorie($db); $maxcategbydefaultforthisdevice = 12; $maxproductbydefaultforthisdevice = 24; -if ($conf->browser->layout == 'phone') -{ +if ($conf->browser->layout == 'phone') { $maxcategbydefaultforthisdevice = 8; $maxproductbydefaultforthisdevice = 16; //REDIRECT TO BASIC LAYOUT IF TERMINAL SELECTED AND BASIC MOBILE LAYOUT ENABLED - if ($_SESSION["takeposterminal"] != "" && $conf->global->TAKEPOS_PHONE_BASIC_LAYOUT == 1) - { + if ($_SESSION["takeposterminal"] != "" && $conf->global->TAKEPOS_PHONE_BASIC_LAYOUT == 1) { $_SESSION["basiclayout"] = 1; header("Location: phone.php?mobilepage=invoice"); exit; @@ -107,7 +115,9 @@ $form = new Form($db); // Title $title = 'TakePOS - Dolibarr '.DOL_VERSION; -if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = 'TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $title = 'TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; +} $head = '<meta name="apple-mobile-web-app-title" content="TakePOS"/> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes"> @@ -118,7 +128,9 @@ top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); <link rel="stylesheet" href="css/pos.css.php"> <link rel="stylesheet" href="css/colorbox.css" type="text/css" media="screen" /> <?php -if ($conf->global->TAKEPOS_COLOR_THEME == 1) print '<link rel="stylesheet" href="css/colorful.css">'; +if ($conf->global->TAKEPOS_COLOR_THEME == 1) { + print '<link rel="stylesheet" href="css/colorful.css">'; +} ?> <script type="text/javascript" src="js/jquery.colorbox-min.js"></script> <!-- TODO It seems we don't need this --> <script language="javascript"> @@ -129,25 +141,21 @@ $categories = $categorie->get_full_arbo('product', (($conf->global->TAKEPOS_ROOT // Search root category to know its level //$conf->global->TAKEPOS_ROOT_CATEGORY_ID=0; $levelofrootcategory = 0; -if ($conf->global->TAKEPOS_ROOT_CATEGORY_ID > 0) -{ - foreach ($categories as $key => $categorycursor) - { - if ($categorycursor['id'] == $conf->global->TAKEPOS_ROOT_CATEGORY_ID) - { +if ($conf->global->TAKEPOS_ROOT_CATEGORY_ID > 0) { + foreach ($categories as $key => $categorycursor) { + if ($categorycursor['id'] == $conf->global->TAKEPOS_ROOT_CATEGORY_ID) { $levelofrootcategory = $categorycursor['level']; break; } } } + $levelofmaincategories = $levelofrootcategory + 1; $maincategories = array(); $subcategories = array(); -foreach ($categories as $key => $categorycursor) -{ - if ($categorycursor['level'] == $levelofmaincategories) - { +foreach ($categories as $key => $categorycursor) { + if ($categorycursor['level'] == $levelofmaincategories) { $maincategories[$key] = $categorycursor; } else { $subcategories[$key] = $categorycursor; @@ -174,16 +182,16 @@ var invoiceid=0; var app = this; app.hasKeyboard = false; this.keyboardPress = function() { - app.hasKeyboard = true; - $(window).unbind("keyup", app.keyboardPress); - localStorage.hasKeyboard = true; - console.log("has keyboard!") + app.hasKeyboard = true; + $(window).unbind("keyup", app.keyboardPress); + localStorage.hasKeyboard = true; + console.log("has keyboard!") } $(window).on("keyup", app.keyboardPress) if(localStorage.hasKeyboard) { - app.hasKeyboard = true; - $(window).unbind("keyup", app.keyboardPress); - console.log("has keyboard from localStorage") + app.hasKeyboard = true; + $(window).unbind("keyup", app.keyboardPress); + console.log("has keyboard from localStorage") } */ @@ -218,8 +226,8 @@ function PrintCategories(first) { } $("#catdivdesc"+i).show(); $("#catdesc"+i).text(categories[parseInt(i)+parseInt(first)]['label']); - $("#catimg"+i).attr("src","genimg/index.php?query=cat&id="+categories[parseInt(i)+parseInt(first)]['rowid']); - $("#catdiv"+i).data("rowid",categories[parseInt(i)+parseInt(first)]['rowid']); + $("#catimg"+i).attr("src","genimg/index.php?query=cat&id="+categories[parseInt(i)+parseInt(first)]['rowid']); + $("#catdiv"+i).data("rowid",categories[parseInt(i)+parseInt(first)]['rowid']); $("#catdiv"+i).attr('class', 'wrapper'); $("#catwatermark"+i).show(); } @@ -252,8 +260,8 @@ function MoreCategories(moreorless) { } $("#catdivdesc"+i).show(); $("#catdesc"+i).text(categories[i+(<?php echo ($MAXCATEG - 2); ?> * pagecategories)]['label']); - $("#catimg"+i).attr("src","genimg/index.php?query=cat&id="+categories[i+(<?php echo ($MAXCATEG - 2); ?> * pagecategories)]['rowid']); - $("#catdiv"+i).data("rowid",categories[i+(<?php echo ($MAXCATEG - 2); ?> * pagecategories)]['rowid']); + $("#catimg"+i).attr("src","genimg/index.php?query=cat&id="+categories[i+(<?php echo ($MAXCATEG - 2); ?> * pagecategories)]['rowid']); + $("#catdiv"+i).data("rowid",categories[i+(<?php echo ($MAXCATEG - 2); ?> * pagecategories)]['rowid']); $("#catwatermark"+i).show(); } @@ -273,7 +281,7 @@ function LoadProducts(position, issubcat) { if (issubcat==true) currentcat=$('#prodiv'+position).data('rowid'); else currentcat=$('#catdiv'+position).data('rowid'); } - if (currentcat == undefined) return; + if (currentcat == undefined) return; pageproducts=0; ishow=0; //product to show counter @@ -299,8 +307,7 @@ function LoadProducts(position, issubcat) { //console.log("ishow"+ishow+" idata="+idata); console.log(data[idata]); if (typeof (data[idata]) == "undefined") { - <?php if (!$conf->global->TAKEPOS_HIDE_PRODUCT_IMAGES) - { + <?php if (!$conf->global->TAKEPOS_HIDE_PRODUCT_IMAGES) { echo '$("#prodivdesc"+ishow).hide();'; echo '$("#prodesc"+ishow).text("");'; echo '$("#proimg"+ishow).attr("title","");'; @@ -322,14 +329,12 @@ function LoadProducts(position, issubcat) { $titlestring .= " + ' - ".dol_escape_js($langs->trans("Barcode").': ')."' + data[idata]['barcode']"; ?> var titlestring = <?php echo $titlestring; ?>; - <?php if (!$conf->global->TAKEPOS_HIDE_PRODUCT_IMAGES) - { + <?php if (!$conf->global->TAKEPOS_HIDE_PRODUCT_IMAGES) { echo '$("#prodivdesc"+ishow).show();'; echo '$("#prodesc"+ishow).text(data[parseInt(idata)][\'label\']);'; echo '$("#proimg"+ishow).attr("title", titlestring);'; echo '$("#proimg"+ishow).attr("src", "genimg/index.php?query=pro&id="+data[idata][\'id\']);'; - } - else { + } else { echo '$("#probutton"+ishow).show();'; echo '$("#probutton"+ishow).text(data[parseInt(idata)][\'label\']);'; } @@ -410,7 +415,7 @@ function MoreProducts(moreorless) { function ClickProduct(position) { console.log("ClickProduct"); - $('#proimg'+position).animate({opacity: '0.5'}, 1); + $('#proimg'+position).animate({opacity: '0.5'}, 1); $('#proimg'+position).animate({opacity: '1'}, 100); if ($('#prodiv'+position).data('iscat')==1){ console.log("Click on a category at position "+position); @@ -453,8 +458,8 @@ function Customer() { function History() { - console.log("Open box to select the history"); - $.colorbox({href:"../compta/facture/list.php?contextpage=poslist", width:"90%", height:"80%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("History"); ?>"}); + console.log("Open box to select the history"); + $.colorbox({href:"../compta/facture/list.php?contextpage=poslist", width:"90%", height:"80%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("History"); ?>"}); } function Reduction() { @@ -592,83 +597,83 @@ function Edit(number) { if (typeof(selectedtext) == "undefined") return; // We click on an action on the number pad but there is no line selected - var text=selectedtext+"<br> "; + var text=selectedtext+"<br> "; - if (number=='c'){ - editnumber=""; - Refresh(); - return; - } - else if (number=='qty'){ - console.log("Edit "+number); - if (editaction=='qty' && editnumber!=""){ - $("#poslines").load("invoice.php?action=updateqty&place="+place+"&idline="+selectedline+"&number="+editnumber, function() { - editnumber=""; - //$('#poslines').scrollTop($('#poslines')[0].scrollHeight); - $("#qty").html("<?php echo $langs->trans("Qty"); ?>"); - }); + if (number=='c'){ + editnumber=""; + Refresh(); + return; + } + else if (number=='qty'){ + console.log("Edit "+number); + if (editaction=='qty' && editnumber!=""){ + $("#poslines").load("invoice.php?action=updateqty&place="+place+"&idline="+selectedline+"&number="+editnumber, function() { + editnumber=""; + //$('#poslines').scrollTop($('#poslines')[0].scrollHeight); + $("#qty").html("<?php echo $langs->trans("Qty"); ?>"); + }); - setFocusOnSearchField(); - return; - } - else { - editaction="qty"; - } - } - else if (number=='p'){ - console.log("Edit "+number); - if (editaction=='p' && editnumber!=""){ - $("#poslines").load("invoice.php?action=updateprice&place="+place+"&idline="+selectedline+"&number="+editnumber, function() { - editnumber=""; - //$('#poslines').scrollTop($('#poslines')[0].scrollHeight); - $("#price").html("<?php echo $langs->trans("Price"); ?>"); - }); + setFocusOnSearchField(); + return; + } + else { + editaction="qty"; + } + } + else if (number=='p'){ + console.log("Edit "+number); + if (editaction=='p' && editnumber!=""){ + $("#poslines").load("invoice.php?action=updateprice&place="+place+"&idline="+selectedline+"&number="+editnumber, function() { + editnumber=""; + //$('#poslines').scrollTop($('#poslines')[0].scrollHeight); + $("#price").html("<?php echo $langs->trans("Price"); ?>"); + }); - ClearSearch(); - return; - } - else { - editaction="p"; - } - } - else if (number=='r'){ - console.log("Edit "+number); - if (editaction=='r' && editnumber!=""){ - $("#poslines").load("invoice.php?action=updatereduction&place="+place+"&idline="+selectedline+"&number="+editnumber, function() { - editnumber=""; - //$('#poslines').scrollTop($('#poslines')[0].scrollHeight); - $("#reduction").html("<?php echo $langs->trans("ReductionShort"); ?>"); - }); + ClearSearch(); + return; + } + else { + editaction="p"; + } + } + else if (number=='r'){ + console.log("Edit "+number); + if (editaction=='r' && editnumber!=""){ + $("#poslines").load("invoice.php?action=updatereduction&place="+place+"&idline="+selectedline+"&number="+editnumber, function() { + editnumber=""; + //$('#poslines').scrollTop($('#poslines')[0].scrollHeight); + $("#reduction").html("<?php echo $langs->trans("ReductionShort"); ?>"); + }); - ClearSearch(); - return; - } - else { - editaction="r"; - } - } - else { - editnumber=editnumber+number; - } - if (editaction=='qty'){ - text=text+"<?php echo $langs->trans("Modify")." -> ".$langs->trans("Qty").": "; ?>"; - $("#qty").html("OK"); - $("#price").html("<?php echo $langs->trans("Price"); ?>"); - $("#reduction").html("<?php echo $langs->trans("ReductionShort"); ?>"); - } - if (editaction=='p'){ - text=text+"<?php echo $langs->trans("Modify")." -> ".$langs->trans("Price").": "; ?>"; - $("#qty").html("<?php echo $langs->trans("Qty"); ?>"); - $("#price").html("OK"); - $("#reduction").html("<?php echo $langs->trans("ReductionShort"); ?>"); - } - if (editaction=='r'){ - text=text+"<?php echo $langs->trans("Modify")." -> ".$langs->trans("ReductionShort").": "; ?>"; - $("#qty").html("<?php echo $langs->trans("Qty"); ?>"); - $("#price").html("<?php echo $langs->trans("Price"); ?>"); - $("#reduction").html("OK"); - } - $('#'+selectedline).find("td:first").html(text+editnumber); + ClearSearch(); + return; + } + else { + editaction="r"; + } + } + else { + editnumber=editnumber+number; + } + if (editaction=='qty'){ + text=text+"<?php echo $langs->trans("Modify")." -> ".$langs->trans("Qty").": "; ?>"; + $("#qty").html("OK"); + $("#price").html("<?php echo $langs->trans("Price"); ?>"); + $("#reduction").html("<?php echo $langs->trans("ReductionShort"); ?>"); + } + if (editaction=='p'){ + text=text+"<?php echo $langs->trans("Modify")." -> ".$langs->trans("Price").": "; ?>"; + $("#qty").html("<?php echo $langs->trans("Qty"); ?>"); + $("#price").html("OK"); + $("#reduction").html("<?php echo $langs->trans("ReductionShort"); ?>"); + } + if (editaction=='r'){ + text=text+"<?php echo $langs->trans("Modify")." -> ".$langs->trans("ReductionShort").": "; ?>"; + $("#qty").html("<?php echo $langs->trans("Qty"); ?>"); + $("#price").html("<?php echo $langs->trans("Price"); ?>"); + $("#reduction").html("OK"); + } + $('#'+selectedline).find("td:first").html(text+editnumber); } function TakeposPrintingOrder(){ @@ -690,8 +695,11 @@ function OpenDrawer(){ $.ajax({ type: "POST", <?php - if (filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) echo "url: '".$conf->global->TAKEPOS_PRINT_SERVER."/printer/drawer.php',"; - else echo "url: 'http://".$conf->global->TAKEPOS_PRINT_SERVER.":8111/print',"; + if (filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) { + echo "url: '".$conf->global->TAKEPOS_PRINT_SERVER."/printer/drawer.php',"; + } else { + echo "url: 'http://".$conf->global->TAKEPOS_PRINT_SERVER.":8111/print',"; + } ?> data: "opendrawer" }); @@ -724,23 +732,23 @@ function MoreActions(totalactions){ function ControlCashOpening() { - $.colorbox({href:"../compta/cashcontrol/cashcontrol_card.php?action=create&contextpage=takepos", width:"90%", height:"60%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("NewCashFence"); ?>"}); + $.colorbox({href:"../compta/cashcontrol/cashcontrol_card.php?action=create&contextpage=takepos", width:"90%", height:"60%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("NewCashFence"); ?>"}); } function CloseCashFence(rowid) { - $.colorbox({href:"../compta/cashcontrol/cashcontrol_card.php?id="+rowid+"&contextpage=takepos", width:"90%", height:"90%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("NewCashFence"); ?>"}); + $.colorbox({href:"../compta/cashcontrol/cashcontrol_card.php?id="+rowid+"&contextpage=takepos", width:"90%", height:"90%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("NewCashFence"); ?>"}); } function CashReport(rowid) { - $.colorbox({href:"../compta/cashcontrol/report.php?id="+rowid+"&contextpage=takepos", width:"60%", height:"90%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("CashReport"); ?>"}); + $.colorbox({href:"../compta/cashcontrol/report.php?id="+rowid+"&contextpage=takepos", width:"60%", height:"90%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("CashReport"); ?>"}); } // TakePOS Popup function ModalBox(ModalID) { - var modal = document.getElementById(ModalID); + var modal = document.getElementById(ModalID); modal.style.display = "block"; } @@ -756,36 +764,37 @@ function FullScreen() { function WeighingScale(){ console.log("Weighing Scale"); - $.ajax({ - type: "POST", - url: '<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>/scale/index.php', - }) + $.ajax({ + type: "POST", + url: '<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>/scale/index.php', + }) .done(function( editnumber ) { $("#poslines").load("invoice.php?action=updateqty&place="+place+"&idline="+selectedline+"&number="+editnumber, function() { - editnumber=""; - }); + editnumber=""; + }); }); } $( document ).ready(function() { - PrintCategories(0); + PrintCategories(0); LoadProducts(0); Refresh(); <?php //IF NO TERMINAL SELECTED - if ($_SESSION["takeposterminal"] == "") - { + if ($_SESSION["takeposterminal"] == "") { print "ModalBox('ModalTerminal');"; } if ($conf->global->TAKEPOS_CONTROL_CASH_OPENING) { - $sql = "SELECT rowid, status FROM ".MAIN_DB_PREFIX."pos_cash_fence WHERE"; - $sql .= " entity = ".$conf->entity." AND "; - $sql .= " date_creation > '".$db->idate(dol_get_first_hour(dol_now()))."'"; + $sql = "SELECT rowid, status FROM ".MAIN_DB_PREFIX."pos_cash_fence WHERE"; + $sql .= " entity = ".$conf->entity." AND "; + $sql .= " date_creation > '".$db->idate(dol_get_first_hour(dol_now()))."'"; $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); // If there is no cash control from today open it - if ($obj->rowid == null) print "ControlCashOpening();"; + if ($obj->rowid == null) { + print "ControlCashOpening();"; + } } } ?> @@ -811,8 +820,11 @@ if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { <?php echo $langs->trans("Terminal"); ?> </span> <?php echo " "; - if ($_SESSION["takeposterminal"] == "") echo "1"; - else echo $_SESSION["takeposterminal"]; + if ($_SESSION["takeposterminal"] == "") { + echo "1"; + } else { + echo $_SESSION["takeposterminal"]; + } echo '<span class="hideonsmartphone"> - '.dol_print_date(dol_now(), "day").'</span>'; ?> </a> @@ -862,8 +874,7 @@ if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { <div class="modal-body"> <button type="button" class="block" onclick="location.href='index.php?setterminal=1'"><?php print $langs->trans("Terminal"); ?> 1</button> <?php - for ($i = 2; $i <= $conf->global->TAKEPOS_NUM_TERMINALS; $i++) - { + for ($i = 2; $i <= $conf->global->TAKEPOS_NUM_TERMINALS; $i++) { print '<button type="button" class="block" onclick="location.href=\'index.php?setterminal='.$i.'\'">'.$langs->trans("Terminal").' '.$i.'</button>'; } ?> @@ -884,10 +895,10 @@ if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency'; $sql .= " WHERE entity IN ('".getEntity('multicurrency')."')"; $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - print '<button type="button" class="block" onclick="location.href=\'index.php?setcurrency='.$obj->code.'\'">'.$obj->code.'</button>'; + if ($resql) { + while ($obj = $db->fetch_object($resql)) { + print '<button type="button" class="block" onclick="location.href=\'index.php?setcurrency='.$obj->code.'\'">'.$obj->code.'</button>'; + } } ?> </div> @@ -909,7 +920,9 @@ if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { </div> </div> - <div class="row1<?php if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) print 'withhead'; ?>"> + <div class="row1<?php if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { + print 'withhead'; + } ?>"> <div id="poslines" class="div1"> </div> @@ -946,12 +959,18 @@ $paiementsModes = array(); if ($resql) { while ($obj = $db->fetch_object($resql)) { $paycode = $obj->code; - if ($paycode == 'LIQ') $paycode = 'CASH'; - if ($paycode == 'CHQ') $paycode = 'CHEQUE'; + if ($paycode == 'LIQ') { + $paycode = 'CASH'; + } + if ($paycode == 'CHQ') { + $paycode = 'CHEQUE'; + } $constantforkey = "CASHDESK_ID_BANKACCOUNT_".$paycode.$_SESSION["takeposterminal"]; //var_dump($constantforkey.' '.$conf->global->$constantforkey); - if (!empty($conf->global->$constantforkey) && $conf->global->$constantforkey > 0) array_push($paiementsModes, $obj); + if (!empty($conf->global->$constantforkey) && $conf->global->$constantforkey > 0) { + array_push($paiementsModes, $obj); + } } } @@ -961,14 +980,19 @@ if (empty($paiementsModes)) { setEventMessages($langs->trans("ProblemIsInSetupOfTerminal", $_SESSION["takeposterminal"]), null, 'errors'); } if (count($maincategories) == 0) { - setEventMessages($langs->trans("TakeposNeedsCategories"), null, 'errors'); + if ($conf->global->TAKEPOS_ROOT_CATEGORY_ID > 0) { + $tmpcategory = new Categorie($db); + $tmpcategory->fetch($conf->global->TAKEPOS_ROOT_CATEGORY_ID); + setEventMessages($langs->trans("TakeposNeedsAtLeastOnSubCategoryIntoParentCategory", $tmpcategory->label), null, 'errors'); + } else { + setEventMessages($langs->trans("TakeposNeedsCategories"), null, 'errors'); + } } // User menu and external TakePOS modules $menus = array(); $r = 0; -if (empty($conf->global->TAKEPOS_BAR_RESTAURANT)) -{ +if (empty($conf->global->TAKEPOS_BAR_RESTAURANT)) { $menus[$r++] = array('title'=>'<span class="fa fa-layer-group paddingrightonly"></span><div class="trunc">'.$langs->trans("New").'</div>', 'action'=>'New();'); } else { // BAR RESTAURANT specific menu @@ -988,30 +1012,28 @@ if ($conf->global->TAKEPOS_DIRECT_PAYMENT) { } // BAR RESTAURANT specific menu -if ($conf->global->TAKEPOS_BAR_RESTAURANT) -{ - if ($conf->global->TAKEPOS_ORDER_PRINTERS) - { +if ($conf->global->TAKEPOS_BAR_RESTAURANT) { + if ($conf->global->TAKEPOS_ORDER_PRINTERS) { $menus[$r++] = array('title'=>$langs->trans("Order"), 'action'=>'TakeposPrintingOrder();'); } //Button to print receipt before payment - if ($conf->global->TAKEPOS_BAR_RESTAURANT) - { + if ($conf->global->TAKEPOS_BAR_RESTAURANT) { if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") { - if (filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) $menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("Receipt").'</div>', 'action'=>'TakeposConnector(placeid);'); - else $menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("Receipt").'</div>', 'action'=>'TakeposPrinting(placeid);'); + if (filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) { + $menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("Receipt").'</div>', 'action'=>'TakeposConnector(placeid);'); + } else { + $menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("Receipt").'</div>', 'action'=>'TakeposPrinting(placeid);'); + } } elseif ($conf->global->TAKEPOS_PRINT_METHOD == "receiptprinter") { $menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("Receipt").'</div>', 'action'=>'DolibarrTakeposPrinting(placeid);'); } else { $menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("Receipt").'</div>', 'action'=>'Print(placeid);'); } } - if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector" && $conf->global->TAKEPOS_ORDER_NOTES == 1) - { + if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector" && $conf->global->TAKEPOS_ORDER_NOTES == 1) { $menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("OrderNotes").'</div>', 'action'=>'TakeposOrderNotes();'); } - if ($conf->global->TAKEPOS_SUPPLEMENTS) - { + if ($conf->global->TAKEPOS_SUPPLEMENTS) { $menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("ProductSupplements").'</div>', 'action'=>'LoadProducts(\'supplements\');'); } } @@ -1030,14 +1052,14 @@ $sql = "SELECT rowid, status, entity FROM ".MAIN_DB_PREFIX."pos_cash_fence WHERE $sql .= " entity = ".$conf->entity." AND "; $sql .= " date_creation > '".$db->idate(dol_get_first_hour(dol_now()))."'"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $obj = $db->fetch_object($resql); $menus[$r++] = array('title'=>'<span class="fas fa-file-invoice-dollar paddingrightonly"></span><div class="trunc">'.$langs->trans("CashReport").'</div>', 'action'=>'CashReport('.$obj->rowid.');'); - if ($obj->status == 0) $menus[$r++] = array('title'=>'<span class="fas fa-cash-register paddingrightonly"></span><div class="trunc">'.$langs->trans("CloseCashFence").'</div>', 'action'=>'CloseCashFence('.$obj->rowid.');'); + if ($obj->status == 0) { + $menus[$r++] = array('title'=>'<span class="fas fa-cash-register paddingrightonly"></span><div class="trunc">'.$langs->trans("CloseCashFence").'</div>', 'action'=>'CloseCashFence('.$obj->rowid.');'); + } } } @@ -1053,14 +1075,15 @@ if (!empty($reshook)) { } } -if ($r % 3 == 2) $menus[$r++] = array('title'=>'', 'style'=>'visibility: hidden;'); +if ($r % 3 == 2) { + $menus[$r++] = array('title'=>'', 'style'=>'visibility: hidden;'); +} if (!empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { $menus[$r++] = array('title'=>'<span class="fa fa-sign-out-alt paddingrightonly"></span><div class="trunc">'.$langs->trans("Logout").'</div>', 'action'=>'window.location.href=\''.DOL_URL_ROOT.'/user/logout.php\';'); } -if ($conf->global->TAKEPOS_WEIGHING_SCALE) -{ +if ($conf->global->TAKEPOS_WEIGHING_SCALE) { $menus[$r++] = array('title'=>'<span class="fa fa-balance-scale paddingrightonly"></span><div class="trunc">'.$langs->trans("WeighingScale").'</div>', 'action'=>'WeighingScale();'); } @@ -1069,15 +1092,16 @@ if ($conf->global->TAKEPOS_WEIGHING_SCALE) <div class="div3"> <?php $i = 0; - foreach ($menus as $menu) - { + foreach ($menus as $menu) { $i++; - if (count($menus) > 12 and $i == 12) - { + if (count($menus) > 12 and $i == 12) { echo '<button style="'.$menu['style'].'" type="button" id="actionnext" class="actionbutton" onclick="MoreActions('.count($menus).');">'.$langs->trans("Next").'</button>'; echo '<button style="display: none;" type="button" id="action'.$i.'" class="actionbutton" onclick="'.$menu['action'].'">'.$menu['title'].'</button>'; - } elseif ($i > 12) echo '<button style="display: none;" type="button" id="action'.$i.'" class="actionbutton" onclick="'.$menu['action'].'">'.$menu['title'].'</button>'; - else echo '<button style="'.$menu['style'].'" type="button" id="action'.$i.'" class="actionbutton" onclick="'.$menu['action'].'">'.$menu['title'].'</button>'; + } elseif ($i > 12) { + echo '<button style="display: none;" type="button" id="action'.$i.'" class="actionbutton" onclick="'.$menu['action'].'">'.$menu['title'].'</button>'; + } else { + echo '<button style="'.$menu['style'].'" type="button" id="action'.$i.'" class="actionbutton" onclick="'.$menu['action'].'">'.$menu['title'].'</button>'; + } } if (!empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { @@ -1091,16 +1115,23 @@ if ($conf->global->TAKEPOS_WEIGHING_SCALE) </div> </div> - <div class="row2<?php if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) print 'withhead'; ?>"> + <div class="row2<?php if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { + print 'withhead'; + } ?>"> <!-- Show categories --> <div class="div4"> <?php $count = 0; - while ($count < $MAXCATEG) - { + while ($count < $MAXCATEG) { ?> - <div class="wrapper" <?php if ($count == ($MAXCATEG - 2)) echo 'onclick="MoreCategories(\'less\');"'; elseif ($count == ($MAXCATEG - 1)) echo 'onclick="MoreCategories(\'more\');"'; else echo 'onclick="LoadProducts('.$count.');"'; ?> id="catdiv<?php echo $count; ?>"> + <div class="wrapper" <?php if ($count == ($MAXCATEG - 2)) { + echo 'onclick="MoreCategories(\'less\');"'; + } elseif ($count == ($MAXCATEG - 1)) { + echo 'onclick="MoreCategories(\'more\');"'; + } else { + echo 'onclick="LoadProducts('.$count.');"'; + } ?> id="catdiv<?php echo $count; ?>"> <?php if ($count == ($MAXCATEG - 2)) { //echo '<img class="imgwrapper" src="img/arrow-prev-top.png" height="100%" id="catimg'.$count.'" />'; @@ -1109,7 +1140,9 @@ if ($conf->global->TAKEPOS_WEIGHING_SCALE) //echo '<img class="imgwrapper" src="img/arrow-next-top.png" height="100%" id="catimg'.$count.'" />'; echo '<span class="fa fa-chevron-right centerinmiddle" style="font-size: 5em;"></span>'; } else { - if (!$conf->global->TAKEPOS_HIDE_CATEGORY_IMAGES) echo '<img class="imgwrapper" height="100%" id="catimg'.$count.'" />'; + if (!$conf->global->TAKEPOS_HIDE_CATEGORY_IMAGES) { + echo '<img class="imgwrapper" height="100%" id="catimg'.$count.'" />'; + } } ?> <?php if ($count != ($MAXCATEG - 2) && $count != ($MAXCATEG - 1)) { ?> @@ -1119,21 +1152,26 @@ if ($conf->global->TAKEPOS_WEIGHING_SCALE) <?php } ?> <div class="catwatermark" id='catwatermark<?php echo $count; ?>'>...</div> </div> - <?php + <?php $count++; } ?> </div> - <!-- Show product --> + <!-- Show product --> <div class="div5"> - <?php + <?php $count = 0; - while ($count < $MAXPRODUCT) - { + while ($count < $MAXPRODUCT) { ?> - <div class="wrapper2" id='prodiv<?php echo $count; ?>' <?php if ($count == ($MAXPRODUCT - 2)) {?> onclick="MoreProducts('less');" <?php } if ($count == ($MAXPRODUCT - 1)) {?> onclick="MoreProducts('more');" <?php } else echo 'onclick="ClickProduct('.$count.');"'; ?>> - <?php + <div class="wrapper2" id='prodiv<?php echo $count; ?>' <?php if ($count == ($MAXPRODUCT - 2)) { + ?> onclick="MoreProducts('less');" <?php + } if ($count == ($MAXPRODUCT - 1)) { + ?> onclick="MoreProducts('more');" <?php + } else { + echo 'onclick="ClickProduct('.$count.');"'; + } ?>> + <?php if ($count == ($MAXPRODUCT - 2)) { //echo '<img class="imgwrapper" src="img/arrow-prev-top.png" height="100%" id="proimg'.$count.'" />'; print '<span class="fa fa-chevron-left centerinmiddle" style="font-size: 5em;"></span>'; @@ -1141,21 +1179,22 @@ if ($conf->global->TAKEPOS_WEIGHING_SCALE) //echo '<img class="imgwrapper" src="img/arrow-next-top.png" height="100%" id="proimg'.$count.'" />'; print '<span class="fa fa-chevron-right centerinmiddle" style="font-size: 5em;"></span>'; } else { - if ($conf->global->TAKEPOS_HIDE_PRODUCT_IMAGES) echo '<button type="button" id="probutton'.$count.'" class="productbutton" style="display: none;"></button>'; - else { + if ($conf->global->TAKEPOS_HIDE_PRODUCT_IMAGES) { + echo '<button type="button" id="probutton'.$count.'" class="productbutton" style="display: none;"></button>'; + } else { print '<div class="" id="proprice'.$count.'"></div>'; print '<img class="imgwrapper" height="100%" title="" id="proimg'.$count.'">'; } } ?> <?php if ($count != ($MAXPRODUCT - 2) && $count != ($MAXPRODUCT - 1) && !$conf->global->TAKEPOS_HIDE_PRODUCT_IMAGES) { ?> - <div class="description" id="prodivdesc<?php echo $count; ?>"> - <div class="description_content" id="prodesc<?php echo $count; ?>"></div> - </div> - <?php } ?> - <div class="catwatermark" id='prowatermark<?php echo $count; ?>'>...</div> - </div> - <?php + <div class="description" id="prodivdesc<?php echo $count; ?>"> + <div class="description_content" id="prodesc<?php echo $count; ?>"></div> + </div> + <?php } ?> + <div class="catwatermark" id='prowatermark<?php echo $count; ?>'>...</div> + </div> + <?php $count++; } ?> diff --git a/htdocs/takepos/invoice.php b/htdocs/takepos/invoice.php index 8ca516288c1..7fd162c5fbd 100644 --- a/htdocs/takepos/invoice.php +++ b/htdocs/takepos/invoice.php @@ -1,6 +1,7 @@ <?php /** * Copyright (C) 2018 Andreu Bisquerra <jove@bisquerra.com> + * Copyright (C) 2021 Nicolas ZABOURI <info@inovea-conseil.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -26,13 +27,25 @@ // if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Not disabled cause need to load personalized language // if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); -if (!defined('NOCSRFCHECK')) { define('NOCSRFCHECK', '1'); } -if (!defined('NOTOKENRENEWAL')) { define('NOTOKENRENEWAL', '1'); } -if (!defined('NOREQUIREMENU')) { define('NOREQUIREMENU', '1'); } -if (!defined('NOREQUIREHTML')) { define('NOREQUIREHTML', '1'); } -if (!defined('NOREQUIREAJAX')) { define('NOREQUIREAJAX', '1'); } +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} -if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) require '../main.inc.php'; +if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { + require '../main.inc.php'; +} require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; @@ -57,20 +70,21 @@ if (empty($user->rights->takepos->run) && !defined('INCLUDE_PHONEPAGE_FROM_PUBLI * View */ -if (($conf->global->TAKEPOS_PHONE_BASIC_LAYOUT == 1 && $conf->browser->layout == 'phone') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) -{ +if (($conf->global->TAKEPOS_PHONE_BASIC_LAYOUT == 1 && $conf->browser->layout == 'phone') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { // DIRECT LINK TO THIS PAGE FROM MOBILE AND NO TERMINAL SELECTED - if ($_SESSION["takeposterminal"] == "") - { - if ($conf->global->TAKEPOS_NUM_TERMINALS == "1") $_SESSION["takeposterminal"] = 1; - else { + if ($_SESSION["takeposterminal"] == "") { + if ($conf->global->TAKEPOS_NUM_TERMINALS == "1") { + $_SESSION["takeposterminal"] = 1; + } else { header("Location: ".DOL_URL_ROOT."/takepos/index.php"); exit; } } $mobilepage = GETPOST('mobilepage', 'alpha'); $title = 'TakePOS - Dolibarr '.DOL_VERSION; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = 'TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $title = 'TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; + } $head = '<meta name="apple-mobile-web-app-title" content="TakePOS"/> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes"> @@ -107,9 +121,15 @@ $amountofpayment = price2num(GETPOST('amount', 'alpha')); $invoiceid = GETPOST('invoiceid', 'int'); $paycode = $pay; -if ($pay == 'cash') $paycode = 'LIQ'; // For backward compatibility -if ($pay == 'card') $paycode = 'CB'; // For backward compatibility -if ($pay == 'cheque') $paycode = 'CHQ'; // For backward compatibility +if ($pay == 'cash') { + $paycode = 'LIQ'; // For backward compatibility +} +if ($pay == 'card') { + $paycode = 'CB'; // For backward compatibility +} +if ($pay == 'cheque') { + $paycode = 'CHQ'; // For backward compatibility +} // Retrieve paiementid $sql = "SELECT id FROM ".MAIN_DB_PREFIX."c_paiement"; @@ -120,22 +140,23 @@ $obj = $db->fetch_object($resql); $paiementid = $obj->id; $invoice = new Facture($db); -if ($invoiceid > 0) -{ +if ($invoiceid > 0) { $ret = $invoice->fetch($invoiceid); } else { $ret = $invoice->fetch('', '(PROV-POS'.$_SESSION["takeposterminal"].'-'.$place.')'); } -if ($ret > 0) -{ +if ($ret > 0) { $placeid = $invoice->id; } $constforcompanyid = 'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]; $soc = new Societe($db); -if ($invoice->socid > 0) $soc->fetch($invoice->socid); -else $soc->fetch($conf->global->$constforcompanyid); +if ($invoice->socid > 0) { + $soc->fetch($invoice->socid); +} else { + $soc->fetch($conf->global->$constforcompanyid); +} /* @@ -143,18 +164,20 @@ else $soc->fetch($conf->global->$constforcompanyid); */ // Action to record a payment on a TakePOS invoice -if ($action == 'valid' && $user->rights->facture->creer) -{ +if ($action == 'valid' && $user->rights->facture->creer) { $bankaccount = 0; $error = 0; if (!empty($conf->global->TAKEPOS_CAN_FORCE_BANK_ACCOUNT_DURING_PAYMENT)) { $bankaccount = GETPOST('accountid', 'int'); } else { - if ($pay == "cash") $bankaccount = $conf->global->{'CASHDESK_ID_BANKACCOUNT_CASH'.$_SESSION["takeposterminal"]}; // For backward compatibility - elseif ($pay == "card") $bankaccount = $conf->global->{'CASHDESK_ID_BANKACCOUNT_CB'.$_SESSION["takeposterminal"]}; // For backward compatibility - elseif ($pay == "cheque") $bankaccount = $conf->global->{'CASHDESK_ID_BANKACCOUNT_CHEQUE'.$_SESSION["takeposterminal"]}; // For backward compatibility - else { + if ($pay == "cash") { + $bankaccount = $conf->global->{'CASHDESK_ID_BANKACCOUNT_CASH'.$_SESSION["takeposterminal"]}; // For backward compatibility + } elseif ($pay == "card") { + $bankaccount = $conf->global->{'CASHDESK_ID_BANKACCOUNT_CB'.$_SESSION["takeposterminal"]}; // For backward compatibility + } elseif ($pay == "cheque") { + $bankaccount = $conf->global->{'CASHDESK_ID_BANKACCOUNT_CHEQUE'.$_SESSION["takeposterminal"]}; // For backward compatibility + } else { $accountname = "CASHDESK_ID_BANKACCOUNT_".$pay.$_SESSION["takeposterminal"]; $bankaccount = $conf->global->$accountname; } @@ -252,11 +275,15 @@ if ($action == 'valid' && $user->rights->facture->creer) $payment->datepaye = $now; $payment->fk_account = $bankaccount; $payment->amounts[$invoice->id] = $amountofpayment; - if ($pay == 'cash') $payment->pos_change = price2num(GETPOST('excess', 'alpha')); + if ($pay == 'cash') { + $payment->pos_change = price2num(GETPOST('excess', 'alpha')); + } // If user has not used change control, add total invoice payment // Or if user has used change control and the amount of payment is higher than remain to pay, add the remain to pay - if ($amountofpayment == 0 || $amountofpayment > $remaintopay) $payment->amounts[$invoice->id] = $remaintopay; + if ($amountofpayment == 0 || $amountofpayment > $remaintopay) { + $payment->amounts[$invoice->id] = $remaintopay; + } $payment->paiementid = $paiementid; $payment->num_payment = $invoice->ref; @@ -271,7 +298,9 @@ if ($action == 'valid' && $user->rights->facture->creer) if ($remaintopay == 0) { dol_syslog("Invoice is paid, so we set it to status Paid"); $result = $invoice->setPaid($user); - if ($result > 0) $invoice->paye = 1; + if ($result > 0) { + $invoice->paye = 1; + } // set payment method $invoice->setPaymentMethods($paiementid); } else { @@ -282,8 +311,7 @@ if ($action == 'valid' && $user->rights->facture->creer) } } -if ($action == 'creditnote') -{ +if ($action == 'creditnote') { $creditnote = new Facture($db); $creditnote->socid = $invoice->socid; $creditnote->date = dol_now(); @@ -293,8 +321,7 @@ if ($action == 'creditnote') $creditnote->remise_percent = $invoice->remise_percent; $creditnote->create($user); - foreach ($invoice->lines as $line) - { + foreach ($invoice->lines as $line) { // Extrafields if (method_exists($line, 'fetch_optionals')) { // load extrafields @@ -304,21 +331,17 @@ if ($action == 'creditnote') if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { $fk_parent_line = 0; } - if ($invoice->type == Facture::TYPE_SITUATION) - { + if ($invoice->type == Facture::TYPE_SITUATION) { $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from - if (!empty($invoice->tab_previous_situation_invoice)) - { + if (!empty($invoice->tab_previous_situation_invoice)) { // search the last standard invoice in cycle and the possible credit note between this last and invoice // TODO Move this out of loop of $invoice->lines $tab_jumped_credit_notes = array(); $lineIndex = count($invoice->tab_previous_situation_invoice) - 1; $searchPreviousInvoice = true; - while ($searchPreviousInvoice) - { - if ($invoice->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) - { + while ($searchPreviousInvoice) { + if ($invoice->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) { $searchPreviousInvoice = false; // find, exit; break; } else { @@ -330,10 +353,8 @@ if ($action == 'creditnote') } $maxPrevSituationPercent = 0; - foreach ($invoice->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) - { - if ($prevLine->id == $source_fk_prev_id) - { + foreach ($invoice->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) { + if ($prevLine->id == $source_fk_prev_id) { $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent); //$line->subprice = $line->subprice - $prevLine->subprice; @@ -358,10 +379,8 @@ if ($action == 'creditnote') // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta) $maxPrevSituationPercent = 0; foreach ($tab_jumped_credit_notes as $index => $creditnoteid) { - foreach ($invoice->tab_previous_situation_invoice[$index]->lines as $prevLine) - { - if ($prevLine->fk_prev_id == $source_fk_prev_id) - { + foreach ($invoice->tab_previous_situation_invoice[$index]->lines as $prevLine) { + if ($prevLine->fk_prev_id == $source_fk_prev_id) { $maxPrevSituationPercent = $prevLine->situation_percent; $line->total_ht -= $prevLine->total_ht; @@ -430,10 +449,12 @@ if ($action == 'creditnote') } } -if ($action == 'history' || $action == 'creditnote') -{ - if ($action == 'creditnote') $placeid = $creditnote->id; - else $placeid = (int) GETPOST('placeid', 'int'); +if ($action == 'history' || $action == 'creditnote') { + if ($action == 'creditnote') { + $placeid = $creditnote->id; + } else { + $placeid = (int) GETPOST('placeid', 'int'); + } $invoice = new Facture($db); $invoice->fetch($placeid); } @@ -442,22 +463,19 @@ if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency" $invoice->setMulticurrencyCode($_SESSION["takeposcustomercurrency"]); } -if (($action == "addline" || $action == "freezone") && $placeid == 0) -{ +if (($action == "addline" || $action == "freezone") && $placeid == 0) { $invoice->socid = $conf->global->$constforcompanyid; $invoice->date = dol_now(); $invoice->module_source = 'takepos'; $invoice->pos_source = $_SESSION["takeposterminal"]; $invoice->entity = !empty($_SESSION["takeposinvoiceentity"]) ? $_SESSION["takeposinvoiceentity"] : $conf->entity; - if ($invoice->socid <= 0) - { + if ($invoice->socid <= 0) { $langs->load('errors'); dol_htmloutput_errors($langs->trans("ErrorModuleSetupNotComplete", "TakePos"), null, 1); } else { $placeid = $invoice->create($user); - if ($placeid < 0) - { + if ($placeid < 0) { dol_htmloutput_errors($invoice->error, $invoice->errors, 1); } $sql = "UPDATE ".MAIN_DB_PREFIX."facture set ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")' where rowid=".$placeid; @@ -465,8 +483,7 @@ if (($action == "addline" || $action == "freezone") && $placeid == 0) } } -if ($action == "addline") -{ +if ($action == "addline") { $prod = new Product($db); $prod->fetch($idproduct); @@ -486,19 +503,20 @@ if ($action == "addline") $localtax1_tx = get_localtax($tva_tx, 1, $customer, $mysoc, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $customer, $mysoc, $tva_npr); - if (!empty($conf->global->TAKEPOS_SUPPLEMENTS)) - { + if (!empty($conf->global->TAKEPOS_SUPPLEMENTS)) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $cat = new Categorie($db); $categories = $cat->containing($idproduct, 'product'); $found = (array_search($conf->global->TAKEPOS_SUPPLEMENTS_CATEGORY, array_column($categories, 'id'))); - if ($found !== false) // If this product is a supplement - { + if ($found !== false) { // If this product is a supplement $sql = "SELECT fk_parent_line FROM ".MAIN_DB_PREFIX."facturedet where rowid=$selectedline"; $resql = $db->query($sql); $row = $db->fetch_array($resql); - if ($row[0] == null) $parent_line = $selectedline; - else $parent_line = $row[0]; //If the parent line is already a supplement, add the supplement to the main product + if ($row[0] == null) { + $parent_line = $selectedline; + } else { + $parent_line = $row[0]; //If the parent line is already a supplement, add the supplement to the main product + } } } @@ -530,7 +548,9 @@ if ($action == "freezone") { $tva_tx = GETPOST('tva_tx', 'alpha'); if ($tva_tx != '') { - $tva_tx = price2num($tva_tx); + if (!preg_match('/\((.*)\)/', $tva_tx)) { + $tva_tx = price2num($tva_tx); + } } else { $tva_tx = get_default_tva($mysoc, $customer); } @@ -544,10 +564,8 @@ if ($action == "freezone") { } if ($action == "addnote") { - foreach ($invoice->lines as $line) - { - if ($line->id == $number) - { + foreach ($invoice->lines as $line) { + if ($line->id == $number) { $line->array_options['order_notes'] = $desc; $result = $invoice->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit); } @@ -580,8 +598,7 @@ if ($action == "delete") { if ($placeid > 0) { $result = $invoice->fetch($placeid); - if ($result > 0 && $invoice->statut == Facture::STATUS_DRAFT) - { + if ($result > 0 && $invoice->statut == Facture::STATUS_DRAFT) { $db->begin(); // We delete the lines @@ -601,22 +618,19 @@ if ($action == "delete") { $resql1 = $db->query($sql); if ($resdeletelines && $resql1) { - $db->commit(); - } else { - $db->rollback(); - } + $db->commit(); + } else { + $db->rollback(); + } $invoice->fetch($placeid); } } } -if ($action == "updateqty") -{ - foreach ($invoice->lines as $line) - { - if ($line->id == $idline) - { +if ($action == "updateqty") { + foreach ($invoice->lines as $line) { + if ($line->id == $idline) { $result = $invoice->updateline($line->id, $line->desc, $line->subprice, $number, $line->remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit); } } @@ -624,12 +638,9 @@ if ($action == "updateqty") $invoice->fetch($placeid); } -if ($action == "updateprice") -{ - foreach ($invoice->lines as $line) - { - if ($line->id == $idline) - { +if ($action == "updateprice") { + foreach ($invoice->lines as $line) { + if ($line->id == $idline) { $prod = new Product($db); $prod->fetch($line->fk_product); $customer = new Societe($db); @@ -639,21 +650,19 @@ if ($action == "updateprice") $usercanproductignorepricemin = ((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)); $pu_ht = price2num($number / (1 + ($line->tva_tx / 100)), 'MU'); //Check min price - if ($usercanproductignorepricemin && (!empty($price_min) && (price2num($pu_ht) * (1 - price2num($line->remise_percent) / 100) < price2num($price_min)))) - { + if ($usercanproductignorepricemin && (!empty($price_min) && (price2num($pu_ht) * (1 - price2num($line->remise_percent) / 100) < price2num($price_min)))) { echo $langs->trans("CantBeLessThanMinPrice"); - } else $result = $invoice->updateline($line->id, $line->desc, $number, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'TTC', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit); + } else { + $result = $invoice->updateline($line->id, $line->desc, $number, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'TTC', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit); + } } } $invoice->fetch($placeid); } -if ($action == "updatereduction") -{ - foreach ($invoice->lines as $line) - { - if ($line->id == $idline) - { +if ($action == "updatereduction") { + foreach ($invoice->lines as $line) { + if ($line->id == $idline) { $prod = new Product($db); $prod->fetch($line->fk_product); $customer = new Societe($db); @@ -663,10 +672,11 @@ if ($action == "updatereduction") $usercanproductignorepricemin = ((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)); $pu_ht = price2num($line->multicurrency_subprice / (1 + ($line->tva_tx / 100)), 'MU'); //Check min price - if ($usercanproductignorepricemin && (!empty($price_min) && (price2num($line->multicurrency_subprice) * (1 - price2num($number) / 100) < price2num($price_min)))) - { + if ($usercanproductignorepricemin && (!empty($price_min) && (price2num($line->multicurrency_subprice) * (1 - price2num($number) / 100) < price2num($price_min)))) { echo $langs->trans("CantBeLessThanMinPrice"); - } else $result = $invoice->updateline($line->id, $line->desc, $line->multicurrency_subprice, $line->qty, $number, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit); + } else { + $result = $invoice->updateline($line->id, $line->desc, $line->multicurrency_subprice, $line->qty, $number, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit); + } } } $invoice->fetch($placeid); @@ -678,8 +688,7 @@ if ($action == "updatereduction") $invoice->fetch($placeid); } -if ($action == "order" and $placeid != 0) -{ +if ($action == "order" and $placeid != 0) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; if ($conf->global->TAKEPOS_PRINT_METHOD == "receiptprinter" || $conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") { require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php'; @@ -697,8 +706,7 @@ if ($action == "order" and $placeid != 0) $catsprinter1 = explode(';', $conf->global->TAKEPOS_PRINTED_CATEGORIES_1); $catsprinter2 = explode(';', $conf->global->TAKEPOS_PRINTED_CATEGORIES_2); $catsprinter3 = explode(';', $conf->global->TAKEPOS_PRINTED_CATEGORIES_3); - foreach ($invoice->lines as $line) - { + foreach ($invoice->lines as $line) { if ($line->special_code == "4") { continue; } @@ -706,16 +714,23 @@ if ($action == "order" and $placeid != 0) $existing = $c->containing($line->fk_product, Categorie::TYPE_PRODUCT, 'id'); $result = array_intersect($catsprinter1, $existing); $count = count($result); - if (!$line->fk_product) $count++; // Print Free-text item (Unassigned printer) to Printer 1 + if (!$line->fk_product) { + $count++; // Print Free-text item (Unassigned printer) to Printer 1 + } if ($count > 0) { $linestoprint++; $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='1' where rowid=".$line->id; //Set to print on printer 1 $db->query($sql); $order_receipt_printer1 .= '<tr><td class="left">'; - if ($line->fk_product) $order_receipt_printer1 .= $line->product_label; - else $order_receipt_printer1 .= $line->description; + if ($line->fk_product) { + $order_receipt_printer1 .= $line->product_label; + } else { + $order_receipt_printer1 .= $line->description; + } $order_receipt_printer1 .= '</td><td class="right">'.$line->qty; - if (!empty($line->array_options['options_order_notes'])) $order_receipt_printer1 .= "<br>(".$line->array_options['options_order_notes'].")"; + if (!empty($line->array_options['options_order_notes'])) { + $order_receipt_printer1 .= "<br>(".$line->array_options['options_order_notes'].")"; + } $order_receipt_printer1 .= '</td></tr>'; } } @@ -732,8 +747,7 @@ if ($action == "order" and $placeid != 0) $invoice->fetch($placeid); //Reload object after set lines as printed $linestoprint = 0; - foreach ($invoice->lines as $line) - { + foreach ($invoice->lines as $line) { if ($line->special_code == "4") { continue; } @@ -746,7 +760,9 @@ if ($action == "order" and $placeid != 0) $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='2' where rowid=".$line->id; //Set to print on printer 2 $db->query($sql); $order_receipt_printer2 .= '<tr>'.$line->product_label.'<td class="right">'.$line->qty; - if (!empty($line->array_options['options_order_notes'])) $order_receipt_printer2 .= "<br>(".$line->array_options['options_order_notes'].")"; + if (!empty($line->array_options['options_order_notes'])) { + $order_receipt_printer2 .= "<br>(".$line->array_options['options_order_notes'].")"; + } $order_receipt_printer2 .= '</td></tr>'; } } @@ -763,8 +779,7 @@ if ($action == "order" and $placeid != 0) $invoice->fetch($placeid); //Reload object after set lines as printed $linestoprint = 0; - foreach ($invoice->lines as $line) - { + foreach ($invoice->lines as $line) { if ($line->special_code == "4") { continue; } @@ -777,7 +792,9 @@ if ($action == "order" and $placeid != 0) $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='3' where rowid=".$line->id; //Set to print on printer 3 $db->query($sql); $order_receipt_printer3 .= '<tr>'.$line->product_label.'<td class="right">'.$line->qty; - if (!empty($line->array_options['options_order_notes'])) $order_receipt_printer3 .= "<br>(".$line->array_options['options_order_notes'].")"; + if (!empty($line->array_options['options_order_notes'])) { + $order_receipt_printer3 .= "<br>(".$line->array_options['options_order_notes'].")"; + } $order_receipt_printer3 .= '</td></tr>'; } } @@ -795,23 +812,27 @@ if ($action == "order" and $placeid != 0) } $sectionwithinvoicelink = ''; -if ($action == "valid" || $action == "history" || $action == 'creditnote') -{ +if ($action == "valid" || $action == "history" || $action == 'creditnote') { $sectionwithinvoicelink .= '<!-- Section with invoice link -->'."\n"; $sectionwithinvoicelink .= '<span style="font-size:120%;" class="center">'; $sectionwithinvoicelink .= $invoice->getNomUrl(1, '', 0, 0, '', 0, 0, -1, '_backoffice')." - "; $remaintopay = $invoice->getRemainToPay(); - if ($remaintopay > 0) - { + if ($remaintopay > 0) { $sectionwithinvoicelink .= $langs->trans('RemainToPay').': <span class="amountremaintopay" style="font-size: unset">'.price($remaintopay, 1, $langs, 1, -1, -1, $conf->currency).'</span>'; } else { - if ($invoice->paye) $sectionwithinvoicelink .= '<span class="amountpaymentcomplete" style="font-size: unset">'.$langs->trans("Paid").'</span>'; - else $sectionwithinvoicelink .= $langs->trans('BillShortStatusValidated'); + if ($invoice->paye) { + $sectionwithinvoicelink .= '<span class="amountpaymentcomplete" style="font-size: unset">'.$langs->trans("Paid").'</span>'; + } else { + $sectionwithinvoicelink .= $langs->trans('BillShortStatusValidated'); + } } $sectionwithinvoicelink .= '</span><br>'; if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") { - if (filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="TakeposConnector('.$placeid.');">'.$langs->trans('PrintTicket').'</button>'; - else $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="TakeposPrinting('.$placeid.');">'.$langs->trans('PrintTicket').'</button>'; + if (filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) { + $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="TakeposConnector('.$placeid.');">'.$langs->trans('PrintTicket').'</button>'; + } else { + $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="TakeposPrinting('.$placeid.');">'.$langs->trans('PrintTicket').'</button>'; + } } elseif ($conf->global->TAKEPOS_PRINT_METHOD == "receiptprinter") { $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="DolibarrTakeposPrinting('.$placeid.');">'.$langs->trans('PrintTicket').'</button>'; } else { @@ -820,14 +841,16 @@ if ($action == "valid" || $action == "history" || $action == 'creditnote') $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="Print('.$placeid.', 1);">'.$langs->trans('GiftReceipt').'</button>'; } } - if ($conf->global->TAKEPOS_EMAIL_TEMPLATE_INVOICE > 0) - { + if ($conf->global->TAKEPOS_EMAIL_TEMPLATE_INVOICE > 0) { $sectionwithinvoicelink .= ' <button id="buttonsend" type="button" onclick="SendTicket('.$placeid.');">'.$langs->trans('SendTicket').'</button>'; } - if ($remaintopay <= 0 && $conf->global->TAKEPOS_AUTO_PRINT_TICKETS) $sectionwithinvoicelink .= '<script language="javascript">$("#buttonprint").click();</script>'; + if ($remaintopay <= 0 && $conf->global->TAKEPOS_AUTO_PRINT_TICKETS) { + $sectionwithinvoicelink .= '<script language="javascript">$("#buttonprint").click();</script>'; + } } + /* * View */ @@ -842,27 +865,27 @@ var placeid=<?php echo ($placeid > 0 ? $placeid : 0); ?>; $(document).ready(function() { var idoflineadded = <?php echo ($idoflineadded ? $idoflineadded : 0); ?>; - $('.posinvoiceline').click(function(){ - console.log("Click done on "+this.id); - $('.posinvoiceline').removeClass("selected"); - $(this).addClass("selected"); - if (selectedline==this.id) return; // If is already selected - else selectedline=this.id; - selectedtext=$('#'+selectedline).find("td:first").html(); + $('.posinvoiceline').click(function(){ + console.log("Click done on "+this.id); + $('.posinvoiceline').removeClass("selected"); + $(this).addClass("selected"); + if (selectedline==this.id) return; // If is already selected + else selectedline=this.id; + selectedtext=$('#'+selectedline).find("td:first").html(); <?php if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { print '$("#phonediv1").load("auto_order.php?action=editline&placeid="+placeid+"&selectedline="+selectedline, function() { });'; } ?> - }); + }); - /* Autoselect the line */ - if (idoflineadded > 0) - { - console.log("Auto select "+idoflineadded); - $('.posinvoiceline#'+idoflineadded).click(); - } + /* Autoselect the line */ + if (idoflineadded > 0) + { + console.log("Auto select "+idoflineadded); + $('.posinvoiceline#'+idoflineadded).click(); + } <?php if ($action == "order" and $order_receipt_printer1 != "") { @@ -874,8 +897,7 @@ if ($action == "order" and $order_receipt_printer1 != "") { data: 'invoice='+orderprinter1esc }); <?php - } - else { + } else { ?> $.ajax({ type: "POST", @@ -896,8 +918,7 @@ if ($action == "order" and $order_receipt_printer2 != "") { data: 'invoice='+orderprinter2esc }); <?php - } - else { + } else { ?> $.ajax({ type: "POST", @@ -905,7 +926,7 @@ if ($action == "order" and $order_receipt_printer2 != "") { data: '<?php print $headerorder.$order_receipt_printer2.$footerorder; ?>' }); - <?php + <?php } } @@ -925,25 +946,25 @@ if ($action == "order" and $order_receipt_printer3 != "") { if ($action == "search" || $action == "valid") { ?> parent.setFocusOnSearchField(); - <?php + <?php } if ($action == "temp" and $ticket_printer1 != "") { ?> - $.ajax({ - type: "POST", - url: 'http://<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>:8111/print', - data: '<?php + $.ajax({ + type: "POST", + url: 'http://<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>:8111/print', + data: '<?php print $header_soc.$header_ticket.$body_ticket.$ticket_printer1.$ticket_total.$footer_ticket; ?>' - }); - <?php + }); + <?php } if ($action == "search") { ?> - $('#search').focus(); - <?php + $('#search').focus(); + <?php } ?> @@ -952,45 +973,45 @@ if ($action == "search") { function SendTicket(id) { - console.log("Open box to select the Print/Send form"); - $.colorbox({href:"send.php?facid="+id, width:"70%", height:"30%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("SendTicket"); ?>"}); + console.log("Open box to select the Print/Send form"); + $.colorbox({href:"send.php?facid="+id, width:"70%", height:"30%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("SendTicket"); ?>"}); } function Print(id, gift){ - $.colorbox({href:"receipt.php?facid="+id+"&gift="+gift, width:"40%", height:"90%", transition:"none", iframe:"true", title:"<?php + $.colorbox({href:"receipt.php?facid="+id+"&gift="+gift, width:"40%", height:"90%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("PrintTicket"); ?>"}); } function TakeposPrinting(id){ - var receipt; + var receipt; console.log("TakeposPrinting" + id); - $.get("receipt.php?facid="+id, function(data, status){ - receipt=data.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, ''); - $.ajax({ - type: "POST", - url: 'http://<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>:8111/print', - data: receipt - }); - }); + $.get("receipt.php?facid="+id, function(data, status){ + receipt=data.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, ''); + $.ajax({ + type: "POST", + url: 'http://<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>:8111/print', + data: receipt + }); + }); } function TakeposConnector(id){ console.log("TakeposConnector" + id); $.get("ajax/ajax.php?action=printinvoiceticket&term=<?php echo $_SESSION["takeposterminal"]; ?>&id="+id, function(data, status){ - $.ajax({ + $.ajax({ type: "POST", url: '<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>/printer/index.php', data: 'invoice='+data }); - }); + }); } function DolibarrTakeposPrinting(id) { - console.log("DolibarrTakeposPrinting Printing invoice ticket " + id) - $.ajax({ - type: "GET", - url: "<?php print dol_buildpath('/takepos/ajax/ajax.php', 1).'?action=printinvoiceticket&term='.$_SESSION["takeposterminal"].'&id='; ?>" + id, - }); + console.log("DolibarrTakeposPrinting Printing invoice ticket " + id) + $.ajax({ + type: "GET", + url: "<?php print DOL_URL_ROOT.'/takepos/ajax/ajax.php?action=printinvoiceticket&term='.$_SESSION["takeposterminal"].'&id='; ?>" + id, + }); } function CreditNote() { @@ -1002,14 +1023,14 @@ function CreditNote() { $( document ).ready(function() { console.log("Set customer info and sales in header placeid=<?php echo $placeid; ?> status=<?php echo $invoice->statut; ?>"); - <?php + <?php $s = $langs->trans("Customer"); if ($invoice->id > 0 && ($invoice->socid != $conf->global->$constforcompanyid)) { $s = $soc->name; } ?> - $("#customerandsales").html(''); + $("#customerandsales").html(''); $("#customerandsales").append('<a class="valignmiddle tdoverflowmax100 minwidth100" id="customer" onclick="Customer();" title="<?php print dol_escape_js($s); ?>"><span class="fas fa-building paddingrightonly"></span><?php print dol_escape_js($s); ?></a>'); @@ -1033,13 +1054,19 @@ $( document ).ready(function() { echo '<a class="valignmiddle" title="'.dol_escape_js($langs->trans("SaleStartedAt", dol_print_date($db->jdate($obj->datec), '%H:%M', 'tzuser'))).'" onclick="place=\\\''; $num_sale = str_replace(")", "", str_replace("(PROV-POS".$_SESSION["takeposterminal"]."-", "", $obj->ref)); echo $num_sale; - if (str_replace("-", "", $num_sale) > $max_sale) $max_sale = str_replace("-", "", $num_sale); + if (str_replace("-", "", $num_sale) > $max_sale) { + $max_sale = str_replace("-", "", $num_sale); + } echo '\\\'; invoiceid=\\\''; echo $obj->rowid; echo '\\\'; Refresh();">'; - if ($placeid == $obj->rowid) echo "<b>"; + if ($placeid == $obj->rowid) { + echo "<b>"; + } echo dol_print_date($db->jdate($obj->datec), '%H:%M', 'tzuser'); - if ($placeid == $obj->rowid) echo "</b>"; + if ($placeid == $obj->rowid) { + echo "</b>"; + } echo '</a>\');'; } echo '$("#customerandsales").append(\'<a onclick="place=\\\'0-'; @@ -1052,8 +1079,7 @@ $( document ).ready(function() { $s = ''; $constantforkey = 'CASHDESK_NO_DECREASE_STOCK'.$_SESSION["takeposterminal"]; - if (!empty($conf->stock->enabled) && $conf->global->$constantforkey != "1") - { + if (!empty($conf->stock->enabled) && $conf->global->$constantforkey != "1") { $s = '<span class="small">'; $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"]; $warehouse = new Entrepot($db); @@ -1063,36 +1089,39 @@ $( document ).ready(function() { } ?> - $("#infowarehouse").html('<?php print dol_escape_js($s); ?>'); + $("#infowarehouse").html('<?php print dol_escape_js($s); ?>'); <?php // Module Adherent $s = ''; - if (!empty($conf->adherent->enabled) && $invoice->socid > 0 && $invoice->socid != $conf->global->$constforcompanyid) - { + if (!empty($conf->adherent->enabled) && $invoice->socid > 0 && $invoice->socid != $conf->global->$constforcompanyid) { $s = '<span class="small">'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; $langs->load("members"); $s .= $langs->trans("Member").': '; $adh = new Adherent($db); $result = $adh->fetch('', '', $invoice->socid); - if ($result > 0) - { + if ($result > 0) { $adh->ref = $adh->getFullName($langs); - if (empty($adh->statut)) { $s .= "<s>"; } + if (empty($adh->statut)) { + $s .= "<s>"; + } $s .= $adh->getFullName($langs); $s .= ' - '.$adh->type; - if ($adh->datefin) - { + if ($adh->datefin) { $s .= '<br>'.$langs->trans("SubscriptionEndDate").': '.dol_print_date($adh->datefin, 'day'); if ($adh->hasDelay()) { $s .= " ".img_warning($langs->trans("Late")); } } else { $s .= '<br>'.$langs->trans("SubscriptionNotReceived"); - if ($adh->statut > 0) $s .= " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated + if ($adh->statut > 0) { + $s .= " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated + } + } + if (empty($adh->statut)) { + $s .= "</s>"; } - if (empty($adh->statut)) { $s .= "</s>"; } } else { $s .= '<br>'.$langs->trans("ThirdpartyNotLinkedToMember"); } @@ -1108,8 +1137,7 @@ $( document ).ready(function() { <?php // Add again js for footer because this content is injected into index.php page so all init // for tooltip and other js beautifiers must be reexecuted too. -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n"; print '<script src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.($ext ? '&'.$ext : '').'"></script>'."\n"; } @@ -1118,7 +1146,11 @@ print '<!-- invoice.php place='.(int) $place.' invoice='.$invoice->ref.' mobilep print '<div class="div-table-responsive-no-min invoice">'; print '<table id="tablelines" class="noborder noshadow postablelines" width="100%">'; if ($sectionwithinvoicelink && ($mobilepage == "invoice" || $mobilepage == "")) { - print '<tr><td colspan="4">'.$sectionwithinvoicelink.'</td></tr>'; + if (!empty($conf->global->TAKEPOS_SHOW_HT)) { + print '<tr><td colspan="5">'.$sectionwithinvoicelink.'</td></tr>'; + } else { + print '<tr><td colspan="4">'.$sectionwithinvoicelink.'</td></tr>'; + } } print '<tr class="liste_titre nodrag nodrop">'; print '<td class="linecoldescription">'; @@ -1126,13 +1158,11 @@ print '<td class="linecoldescription">'; if ($mobilepage == "invoice" || $mobilepage == "") { print '<input type="hidden" name="invoiceid" id="invoiceid" value="'.$invoice->id.'">'; } -if ($conf->global->TAKEPOS_BAR_RESTAURANT) -{ +if ($conf->global->TAKEPOS_BAR_RESTAURANT) { $sql = "SELECT floor, label FROM ".MAIN_DB_PREFIX."takepos_floor_tables where rowid=".((int) $place); $resql = $db->query($sql); $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $label = $obj->label; $floor = $obj->floor; } @@ -1140,18 +1170,37 @@ if ($conf->global->TAKEPOS_BAR_RESTAURANT) if ($mobilepage == "invoice" || $mobilepage == "") { print '<span class="opacitymedium">'.$langs->trans('Place')."</span> <b>".$label."</b><br>"; print '<span class="opacitymedium">'.$langs->trans('Floor')."</span> <b>".$floor."</b>"; + } elseif (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { + print $mysoc->name; + } elseif ($mobilepage == "cats") { + print $langs->trans('Category'); + } elseif ($mobilepage == "products") { + print $langs->trans('Label'); } - elseif (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) print $mysoc->name; - elseif ($mobilepage == "cats") print $langs->trans('Category'); - elseif ($mobilepage == "products") print $langs->trans('Label'); } else { print $langs->trans("Products"); } print '</td>'; -if ($_SESSION["basiclayout"] != 1) -{ +if ($_SESSION["basiclayout"] != 1) { print '<td class="linecolqty right">'.$langs->trans('ReductionShort').'</td>'; print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>'; + if ($conf->global->TAKEPOS_SHOW_HT) { + print '<td class="linecolht right nowraponall">'; + print '<span class="opacitymedium small">' . $langs->trans('TotalHTShort') . '</span><br>'; + // In phone version only show when it is invoice page + if ($mobilepage == "invoice" || $mobilepage == "") { + print '<span id="linecolht-span-total" style="font-size:1.3em; font-weight: bold;">' . price($invoice->total_ht, 1, '', 1, -1, -1, $conf->currency) . '</span>'; + if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"] != "" && $conf->currency != $_SESSION["takeposcustomercurrency"]) { + //Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency + include_once DOL_DOCUMENT_ROOT . '/multicurrency/class/multicurrency.class.php'; + $multicurrency = new MultiCurrency($db); + $multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]); + print '<br><span id="linecolht-span-total" style="font-size:0.9em; font-style:italic;">(' . price($invoice->total_ht * $multicurrency->rate->rate) . ' ' . $_SESSION["takeposcustomercurrency"] . ')</span>'; + } + print '</td>'; + } + print '</td>'; + } print '<td class="linecolht right nowraponall">'; print '<span class="opacitymedium small">'.$langs->trans('TotalTTCShort').'</span><br>'; // In phone version only show when it is invoice page @@ -1167,36 +1216,43 @@ if ($_SESSION["basiclayout"] != 1) print '</td>'; } print '</td>'; +} elseif ($mobilepage == "invoice") { + print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>'; } -elseif ($mobilepage == "invoice") print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>'; print "</tr>\n"; -if ($_SESSION["basiclayout"] == 1) -{ - if ($mobilepage == "cats") - { +if ($_SESSION["basiclayout"] == 1) { + if ($mobilepage == "cats") { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $categorie = new Categorie($db); $categories = $categorie->get_full_arbo('product'); $htmlforlines = ''; foreach ($categories as $row) { - if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) $htmlforlines .= '<div class="leftcat'; - else $htmlforlines .= '<tr class="drag drop oddeven posinvoiceline'; + if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { + $htmlforlines .= '<div class="leftcat'; + } else { + $htmlforlines .= '<tr class="drag drop oddeven posinvoiceline'; + } $htmlforlines .= '" onclick="LoadProducts('.$row['id'].');">'; - if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) $htmlforlines .= '<img class="imgwrapper" width="33%" src="'.DOL_URL_ROOT.'/takepos/public/auto_order.php?genimg=cat&query=cat&id='.$row['id'].'"><br>'; - else $htmlforlines .= '<td class="left">'; + if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { + $htmlforlines .= '<img class="imgwrapper" width="33%" src="'.DOL_URL_ROOT.'/takepos/public/auto_order.php?genimg=cat&query=cat&id='.$row['id'].'"><br>'; + } else { + $htmlforlines .= '<td class="left">'; + } $htmlforlines .= $row['label']; - if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) $htmlforlines .= '</div>'."\n"; - else $htmlforlines .= '</td></tr>'."\n"; + if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { + $htmlforlines .= '</div>'."\n"; + } else { + $htmlforlines .= '</td></tr>'."\n"; + } } $htmlforlines .= '</table>'; $htmlforlines .= '</table>'; print $htmlforlines; } - if ($mobilepage == "products") - { + if ($mobilepage == "products") { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $object = new Categorie($db); $catid = GETPOST('catid', 'int'); @@ -1204,15 +1260,17 @@ if ($_SESSION["basiclayout"] == 1) $prods = $object->getObjectsInCateg("product"); $htmlforlines = ''; foreach ($prods as $row) { - if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) $htmlforlines .= '<div class="leftcat'; - else $htmlforlines .= '<tr class="drag drop oddeven posinvoiceline'; + if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { + $htmlforlines .= '<div class="leftcat'; + } else { + $htmlforlines .= '<tr class="drag drop oddeven posinvoiceline'; + } $htmlforlines .= '" onclick="AddProduct(\''.$place.'\', '.$row->id.')">'; if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { $htmlforlines .= '<img class="imgwrapper" width="33%" src="'.DOL_URL_ROOT.'/takepos/public/auto_order.php?genimg=pro&query=pro&id='.$row->id.'"><br>'; $htmlforlines .= $row->label.''.price($row->price_ttc, 1, $langs, 1, -1, -1, $conf->currency); $htmlforlines .= '</div>'."\n"; - } - else { + } else { $htmlforlines .= '<td class="left">'; $htmlforlines .= $row->label; $htmlforlines .= '<div class="right">'.price($row->price_ttc, 1, $langs, 1, -1, -1, $conf->currency).'</div>'; @@ -1223,8 +1281,7 @@ if ($_SESSION["basiclayout"] == 1) print $htmlforlines; } - if ($mobilepage == "places") - { + if ($mobilepage == "places") { $sql = "SELECT rowid, entity, label, leftpos, toppos, floor FROM ".MAIN_DB_PREFIX."takepos_floor_tables"; $resql = $db->query($sql); $rows = array(); @@ -1243,39 +1300,40 @@ if ($_SESSION["basiclayout"] == 1) } } -if ($placeid > 0) -{ +if ($placeid > 0) { //In Phone basic layout hide some content depends situation - if ($_SESSION["basiclayout"] == 1 && $mobilepage != "invoice" && $action != "order") return; + if ($_SESSION["basiclayout"] == 1 && $mobilepage != "invoice" && $action != "order") { + return; + } - if (is_array($invoice->lines) && count($invoice->lines)) - { + if (is_array($invoice->lines) && count($invoice->lines)) { print '<!-- invoice.php show lines of invoices -->'."\n"; $tmplines = array_reverse($invoice->lines); - foreach ($tmplines as $line) - { - if ($line->fk_parent_line != false) - { + foreach ($tmplines as $line) { + if ($line->fk_parent_line != false) { $htmlsupplements[$line->fk_parent_line] .= '<tr class="drag drop oddeven posinvoiceline'; - if ($line->special_code == "4") $htmlsupplements[$line->fk_parent_line] .= ' order'; + if ($line->special_code == "4") { + $htmlsupplements[$line->fk_parent_line] .= ' order'; + } $htmlsupplements[$line->fk_parent_line] .= '" id="'.$line->id.'">'; $htmlsupplements[$line->fk_parent_line] .= '<td class="left">'; $htmlsupplements[$line->fk_parent_line] .= img_picto('', 'rightarrow'); - if ($line->product_label) $htmlsupplements[$line->fk_parent_line] .= $line->product_label; - if ($line->product_label && $line->desc) $htmlsupplements[$line->fk_parent_line] .= '<br>'; - if ($line->product_label != $line->desc) - { + if ($line->product_label) { + $htmlsupplements[$line->fk_parent_line] .= $line->product_label; + } + if ($line->product_label && $line->desc) { + $htmlsupplements[$line->fk_parent_line] .= '<br>'; + } + if ($line->product_label != $line->desc) { $firstline = dolGetFirstLineOfText($line->desc); - if ($firstline != $line->desc) - { + if ($firstline != $line->desc) { $htmlsupplements[$line->fk_parent_line] .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc); } else { $htmlsupplements[$line->fk_parent_line] .= $line->desc; } } $htmlsupplements[$line->fk_parent_line] .= '</td>'; - if ($_SESSION["basiclayout"] != 1) - { + if ($_SESSION["basiclayout"] != 1) { $htmlsupplements[$line->fk_parent_line] .= '<td class="right">'.vatrate($line->remise_percent, true).'</td>'; $htmlsupplements[$line->fk_parent_line] .= '<td class="right">'.$line->qty.'</td>'; $htmlsupplements[$line->fk_parent_line] .= '<td class="right">'.price($line->total_ttc).'</td>'; @@ -1291,11 +1349,15 @@ if ($placeid > 0) } $htmlforlines .= '" id="'.$line->id.'">'; $htmlforlines .= '<td class="left">'; - if ($_SESSION["basiclayout"] == 1) $htmlforlines .= '<span class="phoneqty">'.$line->qty."</span> x "; - if (isset($line->product_type)) - { - if (empty($line->product_type)) $htmlforlines .= img_object('', 'product').' '; - else $htmlforlines .= img_object('', 'service').' '; + if ($_SESSION["basiclayout"] == 1) { + $htmlforlines .= '<span class="phoneqty">'.$line->qty."</span> x "; + } + if (isset($line->product_type)) { + if (empty($line->product_type)) { + $htmlforlines .= img_object('', 'product').' '; + } else { + $htmlforlines .= img_object('', 'service').' '; + } } if (empty($conf->global->TAKEPOS_SHOW_N_FIRST_LINES)) { $tooltiptext = ''; @@ -1303,45 +1365,53 @@ if ($placeid > 0) $tooltiptext .= '<b>'.$langs->trans("Ref").'</b> : '.$line->product_ref.'<br>'; $tooltiptext .= '<b>'.$langs->trans("Label").'</b> : '.$line->product_label.'<br>'; if ($line->product_label != $line->desc) { - if ($line->desc) $tooltiptext .= '<br>'; + if ($line->desc) { + $tooltiptext .= '<br>'; + } $tooltiptext .= $line->desc; } } $htmlforlines .= $form->textwithpicto($line->product_label ? $line->product_label : ($line->product_ref ? $line->product_ref : dolGetFirstLineOfText($line->desc, 1)), $tooltiptext); } else { - if ($line->product_label) $htmlforlines .= $line->product_label; - if ($line->product_label != $line->desc) - { - if ($line->product_label && $line->desc) $htmlforlines .= '<br>'; + if ($line->product_label) { + $htmlforlines .= $line->product_label; + } + if ($line->product_label != $line->desc) { + if ($line->product_label && $line->desc) { + $htmlforlines .= '<br>'; + } $firstline = dolGetFirstLineOfText($line->desc, $conf->global->TAKEPOS_SHOW_N_FIRST_LINES); - if ($firstline != $line->desc) - { + if ($firstline != $line->desc) { $htmlforlines .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc); } else { $htmlforlines .= $line->desc; } } } - if (!empty($line->array_options['options_order_notes'])) $htmlforlines .= "<br>(".$line->array_options['options_order_notes'].")"; + if (!empty($line->array_options['options_order_notes'])) { + $htmlforlines .= "<br>(".$line->array_options['options_order_notes'].")"; + } if ($_SESSION["basiclayout"] == 1) { $htmlforlines .= '</td><td class="right phonetable"><button type="button" onclick="SetQty(place, '.$line->rowid.', '.($line->qty - 1).');" class="publicphonebutton2 phonered">-</button>&nbsp;&nbsp;<button type="button" onclick="SetQty(place, '.$line->rowid.', '.($line->qty + 1).');" class="publicphonebutton2 phonegreen">+</button>'; } - if ($_SESSION["basiclayout"] != 1) - { + if ($_SESSION["basiclayout"] != 1) { $moreinfo = ''; $moreinfo .= $langs->transcountry("TotalHT", $mysoc->country_code).': '.price($line->total_ht); - if ($line->vat_src_code) $moreinfo .= '<br>'.$langs->trans("VATCode").': '.$line->vat_src_code; + if ($line->vat_src_code) { + $moreinfo .= '<br>'.$langs->trans("VATCode").': '.$line->vat_src_code; + } $moreinfo .= '<br>'.$langs->transcountry("TotalVAT", $mysoc->country_code).': '.price($line->total_tva); $moreinfo .= '<br>'.$langs->transcountry("TotalLT1", $mysoc->country_code).': '.price($line->total_localtax1); $moreinfo .= '<br>'.$langs->transcountry("TotalLT2", $mysoc->country_code).': '.price($line->total_localtax2); $moreinfo .= '<br>'.$langs->transcountry("TotalTTC", $mysoc->country_code).': '.price($line->total_ttc); //$moreinfo .= $langs->trans("TotalHT").': '.$line->total_ht; - if ($line->date_start || $line->date_end) $htmlforlines .= '<br><div class="clearboth nowraponall">'.get_date_range($line->date_start, $line->date_end).'</div>'; + if ($line->date_start || $line->date_end) { + $htmlforlines .= '<br><div class="clearboth nowraponall">'.get_date_range($line->date_start, $line->date_end).'</div>'; + } $htmlforlines .= '</td>'; $htmlforlines .= '<td class="right">'.vatrate($line->remise_percent, true).'</td>'; $htmlforlines .= '<td class="right">'; - if (!empty($conf->stock->enabled) && !empty($user->rights->stock->mouvement->lire)) - { + if (!empty($conf->stock->enabled) && !empty($user->rights->stock->mouvement->lire)) { $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"]; if (!empty($conf->global->$constantforkey) && $line->fk_product > 0) { $sql = "SELECT e.rowid, e.ref, e.lieu, e.fk_parent, e.statut, ps.reel, ps.rowid as product_stock_id, p.pmp"; @@ -1357,9 +1427,13 @@ if ($placeid > 0) $obj = $db->fetch_object($resql); $stock_real = price2num($obj->reel, 'MS'); $htmlforlines .= $line->qty; - if ($line->qty && $line->qty > $stock_real) $htmlforlines .= '<span style="color: var(--amountremaintopaycolor)">'; + if ($line->qty && $line->qty > $stock_real) { + $htmlforlines .= '<span style="color: var(--amountremaintopaycolor)">'; + } $htmlforlines .= ' <span class="posstocktoolow">('.$langs->trans("Stock").' '.$stock_real.')</span>'; - if ($line->qty && $line->qty > $stock_real) $htmlforlines .= "</span>"; + if ($line->qty && $line->qty > $stock_real) { + $htmlforlines .= "</span>"; + } } else { dol_print_error($db); } @@ -1371,6 +1445,18 @@ if ($placeid > 0) } $htmlforlines .= '</td>'; + if ($conf->global->TAKEPOS_SHOW_HT) { + $htmlforlines .= '<td class="right classfortooltip" title="'.$moreinfo.'">'; + $htmlforlines .= price($line->total_ht, 1, '', 1, -1, -1, $conf->currency); + if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"] != "" && $conf->currency != $_SESSION["takeposcustomercurrency"]) { + //Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency + include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; + $multicurrency = new MultiCurrency($db); + $multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]); + $htmlforlines .= '<br><span id="linecolht-span-total" style="font-size:0.9em; font-style:italic;">('.price($line->total_ht * $multicurrency->rate->rate).' '.$_SESSION["takeposcustomercurrency"].')</span>'; + } + $htmlforlines .= '</td>'; + } $htmlforlines .= '<td class="right classfortooltip" title="'.$moreinfo.'">'; $htmlforlines .= price($line->total_ttc, 1, '', 1, -1, -1, $conf->currency); if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"] != "" && $conf->currency != $_SESSION["takeposcustomercurrency"]) { @@ -1388,10 +1474,19 @@ if ($placeid > 0) print $htmlforlines; } } else { - print '<tr class="drag drop oddeven"><td class="left"><span class="opacitymedium">'.$langs->trans("Empty").'</span></td><td></td><td></td><td></td></tr>'; + print '<tr class="drag drop oddeven"><td class="left"><span class="opacitymedium">'.$langs->trans("Empty").'</span></td><td></td><td></td><td></td>'; + if (!empty($conf->global->TAKEPOS_SHOW_HT)) { + print '<td></td>'; + } + print '</tr>'; } } else { // No invoice generated yet - print '<tr class="drag drop oddeven"><td class="left"><span class="opacitymedium">'.$langs->trans("Empty").'</span></td><td></td><td></td><td></td></tr>'; + print '<tr class="drag drop oddeven"><td class="left"><span class="opacitymedium">'.$langs->trans("Empty").'</span></td><td></td><td></td><td></td>'; + + if (!empty($conf->global->TAKEPOS_SHOW_HT)) { + print '<td></td>'; + } + print '</tr>'; } print '</table>'; @@ -1401,8 +1496,7 @@ if (($action == "valid" || $action == "history") && $invoice->type != Facture::T } -if ($action == "search") -{ +if ($action == "search") { print '<center> <input type="text" id="search" name="search" onkeyup="Search2();" name="search" style="width:80%;font-size: 150%;" placeholder=' . $langs->trans('Search').' </center>'; diff --git a/htdocs/takepos/pay.php b/htdocs/takepos/pay.php index c1683073371..d4b6c023186 100644 --- a/htdocs/takepos/pay.php +++ b/htdocs/takepos/pay.php @@ -25,11 +25,21 @@ //if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} require '../main.inc.php'; // Load $user and permissions require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; @@ -50,19 +60,16 @@ if (empty($user->rights->takepos->run)) { */ $invoice = new Facture($db); -if ($invoiceid > 0) -{ +if ($invoiceid > 0) { $invoice->fetch($invoiceid); } else { $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture where ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")'"; $resql = $db->query($sql); $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $invoiceid = $obj->rowid; } - if (!$invoiceid) - { + if (!$invoiceid) { $invoiceid = 0; // Invoice does not exist yet } else { $invoice->fetch($invoiceid); @@ -92,9 +99,15 @@ $resql = $db->query($sql); if ($resql) { while ($obj = $db->fetch_object($resql)) { $paycode = $obj->code; - if ($paycode == 'LIQ') $paycode = 'CASH'; - if ($paycode == 'CB') $paycode = 'CB'; - if ($paycode == 'CHQ') $paycode = 'CHEQUE'; + if ($paycode == 'LIQ') { + $paycode = 'CASH'; + } + if ($paycode == 'CB') { + $paycode = 'CB'; + } + if ($paycode == 'CHQ') { + $paycode = 'CHEQUE'; + } $accountname = "CASHDESK_ID_BANKACCOUNT_".$paycode.$_SESSION["takeposterminal"]; if (!empty($conf->global->$accountname) && $conf->global->$accountname > 0) { @@ -106,7 +119,9 @@ if ($resql) { ?> <link rel="stylesheet" href="css/pos.css.php"> <?php -if ($conf->global->TAKEPOS_COLOR_THEME == 1) print '<link rel="stylesheet" href="css/colorful.css">'; +if ($conf->global->TAKEPOS_COLOR_THEME == 1) { + print '<link rel="stylesheet" href="css/colorful.css">'; +} ?> </head> <body> @@ -114,58 +129,63 @@ if ($conf->global->TAKEPOS_COLOR_THEME == 1) print '<link rel="stylesheet" href= <script> <?php $remaintopay = 0; -if ($invoice->id > 0) -{ +if ($invoice->id > 0) { $remaintopay = $invoice->getRemainToPay(); } $alreadypayed = (is_object($invoice) ? ($invoice->total_ttc - $remaintopay) : 0); -if ($conf->global->TAKEPOS_NUMPAD == 0) print "var received='';"; -else print "var received=0;"; +if ($conf->global->TAKEPOS_NUMPAD == 0) { + print "var received='';"; +} else { + print "var received=0;"; +} ?> var alreadypayed = <?php echo $alreadypayed ?>; function addreceived(price) { - <?php - if (empty($conf->global->TAKEPOS_NUMPAD)) print 'received+=String(price);'."\n"; - else print 'received+=parseFloat(price);'."\n"; + <?php + if (empty($conf->global->TAKEPOS_NUMPAD)) { + print 'received+=String(price);'."\n"; + } else { + print 'received+=parseFloat(price);'."\n"; + } ?> - $('.change1').html(pricejs(parseFloat(received), 'MT')); - $('.change1').val(parseFloat(received)); + $('.change1').html(pricejs(parseFloat(received), 'MT')); + $('.change1').val(parseFloat(received)); alreadypaydplusreceived=price2numjs(alreadypayed + parseFloat(received)); - //console.log("already+received = "+alreadypaydplusreceived); - //console.log("total_ttc = "+<?php echo $invoice->total_ttc; ?>); - if (alreadypaydplusreceived > <?php echo $invoice->total_ttc; ?>) - { + //console.log("already+received = "+alreadypaydplusreceived); + //console.log("total_ttc = "+<?php echo $invoice->total_ttc; ?>); + if (alreadypaydplusreceived > <?php echo $invoice->total_ttc; ?>) + { var change=parseFloat(alreadypayed + parseFloat(received) - <?php echo $invoice->total_ttc; ?>); $('.change2').html(pricejs(change, 'MT')); - $('.change2').val(change); - $('.change1').removeClass('colorred'); - $('.change1').addClass('colorgreen'); - $('.change2').removeClass('colorwhite'); - $('.change2').addClass('colorred'); + $('.change2').val(change); + $('.change1').removeClass('colorred'); + $('.change1').addClass('colorgreen'); + $('.change2').removeClass('colorwhite'); + $('.change2').addClass('colorred'); } - else - { + else + { $('.change2').html(pricejs(0, 'MT')); - $('.change2').val(0); - if (alreadypaydplusreceived == <?php echo $invoice->total_ttc; ?>) - { - $('.change1').removeClass('colorred'); - $('.change1').addClass('colorgreen'); - $('.change2').removeClass('colorred'); - $('.change2').addClass('colorwhite'); - } - else - { - $('.change1').removeClass('colorgreen'); - $('.change1').addClass('colorred'); - $('.change2').removeClass('colorred'); - $('.change2').addClass('colorwhite'); - } - } + $('.change2').val(0); + if (alreadypaydplusreceived == <?php echo $invoice->total_ttc; ?>) + { + $('.change1').removeClass('colorred'); + $('.change1').addClass('colorgreen'); + $('.change2').removeClass('colorred'); + $('.change2').addClass('colorwhite'); + } + else + { + $('.change1').removeClass('colorgreen'); + $('.change1').addClass('colorred'); + $('.change2').removeClass('colorred'); + $('.change2').addClass('colorwhite'); + } + } } function reset() @@ -175,10 +195,10 @@ else print "var received=0;"; $('.change1').val(price2numjs(received)); $('.change2').html(pricejs(received, 'MT')); $('.change2').val(price2numjs(received)); - $('.change1').removeClass('colorgreen'); - $('.change1').addClass('colorred'); - $('.change2').removeClass('colorred'); - $('.change2').addClass('colorwhite'); + $('.change1').removeClass('colorgreen'); + $('.change1').addClass('colorred'); + $('.change2').removeClass('colorred'); + $('.change2').addClass('colorwhite'); } function Validate(payment) @@ -192,10 +212,10 @@ else print "var received=0;"; } console.log("We click on the payment mode to pay amount = "+amountpayed); parent.$("#poslines").load("invoice.php?place=<?php echo $place; ?>&action=valid&pay="+payment+"&amount="+amountpayed+"&excess="+excess+"&invoiceid="+invoiceid+"&accountid="+accountid, function() { - if (amountpayed > <?php echo $remaintopay; ?> || amountpayed == <?php echo $remaintopay; ?> || amountpayed==0 ) { - console.log("Close popup"); - parent.$.colorbox.close(); - } + if (amountpayed > <?php echo $remaintopay; ?> || amountpayed == <?php echo $remaintopay; ?> || amountpayed==0 ) { + console.log("Close popup"); + parent.$.colorbox.close(); + } else { console.log("Amount is not comple, so we do NOT close popup and reload it."); location.reload(); @@ -206,32 +226,32 @@ else print "var received=0;"; function ValidateSumup() { console.log("Launch ValidateSumup"); <?php $_SESSION['SMP_CURRENT_PAYMENT'] = "NEW" ?> - var invoiceid = <?php echo($invoiceid > 0 ? $invoiceid : 0); ?>; - var amountpayed = $("#change1").val(); - if (amountpayed > <?php echo $invoice->total_ttc; ?>) { - amountpayed = <?php echo $invoice->total_ttc; ?>; - } + var invoiceid = <?php echo($invoiceid > 0 ? $invoiceid : 0); ?>; + var amountpayed = $("#change1").val(); + if (amountpayed > <?php echo $invoice->total_ttc; ?>) { + amountpayed = <?php echo $invoice->total_ttc; ?>; + } - // Starting sumup app - window.open('sumupmerchant://pay/1.0?affiliate-key=<?php echo $conf->global->TAKEPOS_SUMUP_AFFILIATE ?>&app-id=<?php echo $conf->global->TAKEPOS_SUMUP_APPID ?>&total=' + amountpayed + '&currency=EUR&title=' + invoiceid + '&callback=<?php echo DOL_MAIN_URL_ROOT ?>/takepos/smpcb.php'); + // Starting sumup app + window.open('sumupmerchant://pay/1.0?affiliate-key=<?php echo $conf->global->TAKEPOS_SUMUP_AFFILIATE ?>&app-id=<?php echo $conf->global->TAKEPOS_SUMUP_APPID ?>&total=' + amountpayed + '&currency=EUR&title=' + invoiceid + '&callback=<?php echo DOL_MAIN_URL_ROOT ?>/takepos/smpcb.php'); - var loop = window.setInterval(function () { - $.ajax('<?php echo DOL_URL_ROOT ?>/takepos/smpcb.php?status').done(function (data) { - console.log(data); - if (data === "SUCCESS") { - parent.$("#poslines").load("invoice.php?place=<?php echo $place; ?>&action=valid&pay=CB&amount=" + amountpayed + "&invoiceid=" + invoiceid, function () { - //parent.$("#poslines").scrollTop(parent.$("#poslines")[0].scrollHeight); - parent.$.colorbox.close(); - //parent.setFocusOnSearchField(); // This does not have effect - }); - clearInterval(loop); - } else if (data === "FAILED") { - parent.$.colorbox.close(); - clearInterval(loop); - } - }); - }, 2500); - } + var loop = window.setInterval(function () { + $.ajax('<?php echo DOL_URL_ROOT ?>/takepos/smpcb.php?status').done(function (data) { + console.log(data); + if (data === "SUCCESS") { + parent.$("#poslines").load("invoice.php?place=<?php echo $place; ?>&action=valid&pay=CB&amount=" + amountpayed + "&invoiceid=" + invoiceid, function () { + //parent.$("#poslines").scrollTop(parent.$("#poslines")[0].scrollHeight); + parent.$.colorbox.close(); + //parent.setFocusOnSearchField(); // This does not have effect + }); + clearInterval(loop); + } else if (data === "FAILED") { + parent.$.colorbox.close(); + clearInterval(loop); + } + }); + }, 2500); + } </script> <div style="position:relative; padding-top: 20px; left:5%; height:150px; width:90%;"> @@ -245,7 +265,7 @@ else print "var received=0;"; </div> <?php } ?> <div class="paymentbordline paymentbordlinereceived"> - <center><span class="takepospay"><font color="white"><?php echo $langs->trans("Received"); ?>: </font><span class="change1 colorred"><?php echo price(0, 1, '', 1, -1, -1, $invoice->multicurrency_code); ?></span><input type="hidden" id="change1" class="change1" value="0"></span></center> + <center><span class="takepospay"><font color="white"><?php echo $langs->trans("Received"); ?>: </font><span class="change1 colorred"><?php echo price(0, 1, '', 1, -1, -1, $invoice->multicurrency_code); ?></span><input type="hidden" id="change1" class="change1" value="0"></span></center> </div> <div class="paymentbordline paymentbordlinechange"> <center><span class="takepospay"><font color="white"><?php echo $langs->trans("Change"); ?>: </font><span class="change2 colorwhite"><?php echo price(0, 1, '', 1, -1, -1, $invoice->multicurrency_code); ?></span><input type="hidden" id="change2" class="change2" value="0"></span></center> @@ -294,13 +314,19 @@ print '<button type="button" class="calcbutton" onclick="addreceived('.($numpad $payIcon = ''; if ($paycode == 'LIQ') { $paycode = 'cash'; - if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'coins'; + if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) { + $payIcon = 'coins'; + } } elseif ($paycode == 'CB') { $paycode = 'card'; - if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'credit-card'; + if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) { + $payIcon = 'credit-card'; + } } elseif ($paycode == 'CHQ') { $paycode = 'cheque'; - if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'money-check'; + if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) { + $payIcon = 'money-check'; + } } print '<button type="button" class="calcbutton2" onclick="Validate(\''.$langs->trans($paycode).'\');">'.(!empty($payIcon) ? '<span class="fa fa-2x fa-'.$payIcon.' iconwithlabel"></span><span class="hideonsmartphone"><br>'. $langs->trans("PaymentTypeShort".$arrayOfValidPaymentModes[0]->code) : $langs->trans("PaymentTypeShort".$arrayOfValidPaymentModes[0]->code)).'</span></button>'; @@ -317,13 +343,19 @@ print '<button type="button" class="calcbutton" onclick="addreceived('.($numpad $payIcon = ''; if ($paycode == 'LIQ') { $paycode = 'cash'; - if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'coins'; + if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) { + $payIcon = 'coins'; + } } elseif ($paycode == 'CB') { $paycode = 'card'; - if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'credit-card'; + if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) { + $payIcon = 'credit-card'; + } } elseif ($paycode == 'CHQ') { $paycode = 'cheque'; - if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'money-check'; + if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) { + $payIcon = 'money-check'; + } } print '<button type="button" class="calcbutton2" onclick="Validate(\''.$langs->trans($paycode).'\');">'.(!empty($payIcon) ? '<span class="fa fa-2x fa-'.$payIcon.' iconwithlabel"></span><br> '. $langs->trans("PaymentTypeShort".$arrayOfValidPaymentModes[1]->code) : $langs->trans("PaymentTypeShort".$arrayOfValidPaymentModes[1]->code)).'</button>'; @@ -341,13 +373,19 @@ print '<button type="button" class="calcbutton" onclick="addreceived('.($numpad $payIcon = ''; if ($paycode == 'LIQ') { $paycode = 'cash'; - if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'coins'; + if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) { + $payIcon = 'coins'; + } } elseif ($paycode == 'CB') { $paycode = 'card'; - if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'credit-card'; + if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) { + $payIcon = 'credit-card'; + } } elseif ($paycode == 'CHQ') { $paycode = 'cheque'; - if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'money-check'; + if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) { + $payIcon = 'money-check'; + } } print '<button type="button" class="calcbutton2" onclick="Validate(\''.$langs->trans($paycode).'\');">'.(!empty($payIcon) ? '<span class="fa fa-2x fa-'.$payIcon.' iconwithlabel"></span>'.(!empty($conf->global->TAKEPOS_NUMPAD_FORCE_PAYMENT_ICONS_LABELS) ? '<br> '. $langs->trans("PaymentTypeShort".$arrayOfValidPaymentModes[2]->code) : '') : $langs->trans("PaymentTypeShort".$arrayOfValidPaymentModes[2]->code)).'</button>'; diff --git a/htdocs/takepos/phone.php b/htdocs/takepos/phone.php index 9084fc448f1..7eaa4d9ec68 100644 --- a/htdocs/takepos/phone.php +++ b/htdocs/takepos/phone.php @@ -25,13 +25,25 @@ //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} -if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) require '../main.inc.php'; +if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { + require '../main.inc.php'; +} require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; @@ -47,8 +59,7 @@ $action = GETPOST('action', 'aZ09'); $setterminal = GETPOST('setterminal', 'int'); $idproduct = GETPOST('idproduct', 'int'); -if ($setterminal > 0) -{ +if ($setterminal > 0) { $_SESSION["takeposterminal"] = $setterminal; } @@ -83,8 +94,7 @@ if ($action == "productinfo") { print '<h1>'.$langs->trans('StatusOrderDelivered').'</h1>'; print '<button type="button" class="publicphonebutton2 phoneblue total" onclick="CheckPlease();">'.$langs->trans('Payment').'</button>'; print '<br>'; -} -elseif ($action == "checkplease") { +} elseif ($action == "checkplease") { if (GETPOSTISSET("payment")) { print '<h1>'.$langs->trans('StatusOrderDelivered').'</h1>'; require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php'; @@ -114,10 +124,8 @@ elseif ($action == "checkplease") { $selectedline = GETPOST('selectedline', 'int'); $invoice = new Facture($db); $invoice->fetch($placeid); - foreach ($invoice->lines as $line) - { - if ($line->id == $selectedline) - { + foreach ($invoice->lines as $line) { + if ($line->id == $selectedline) { $prod = new Product($db); $prod->fetch($line->fk_product); print "<b>".$prod->label."</b><br>"; @@ -133,7 +141,9 @@ elseif ($action == "checkplease") { } else { // Title $title = 'TakePOS - Dolibarr '.DOL_VERSION; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = 'TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $title = 'TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; + } $head = '<meta name="apple-mobile-web-app-title" content="TakePOS"/> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes"> @@ -149,12 +159,9 @@ elseif ($action == "checkplease") { // Search root category to know its level //$conf->global->TAKEPOS_ROOT_CATEGORY_ID=0; $levelofrootcategory = 0; - if ($conf->global->TAKEPOS_ROOT_CATEGORY_ID > 0) - { - foreach ($categories as $key => $categorycursor) - { - if ($categorycursor['id'] == $conf->global->TAKEPOS_ROOT_CATEGORY_ID) - { + if ($conf->global->TAKEPOS_ROOT_CATEGORY_ID > 0) { + foreach ($categories as $key => $categorycursor) { + if ($categorycursor['id'] == $conf->global->TAKEPOS_ROOT_CATEGORY_ID) { $levelofrootcategory = $categorycursor['level']; break; } @@ -164,10 +171,8 @@ elseif ($action == "checkplease") { $maincategories = array(); $subcategories = array(); - foreach ($categories as $key => $categorycursor) - { - if ($categorycursor['level'] == $levelofmaincategories) - { + foreach ($categories as $key => $categorycursor) { + if ($categorycursor['level'] == $levelofmaincategories) { $maincategories[$key] = $categorycursor; } else { $subcategories[$key] = $categorycursor; @@ -193,23 +198,22 @@ var editnumber=""; $( document ).ready(function() { - console.log("Refresh"); + console.log("Refresh"); LoadPlace(place); }); function LoadPlace(placeid){ - place=placeid; + place=placeid; <?php if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { echo '$("#phonediv2").load("auto_order.php?mobilepage=invoice&place="+place, function() { });'; - } - else { + } else { echo '$("#phonediv2").load("invoice.php?mobilepage=invoice&place="+place, function() { });'; } ?> - LoadCats(); + LoadCats(); } function AddProduct(placeid, productid){ @@ -219,8 +223,7 @@ function AddProduct(placeid, productid){ print 'place=placeid; $("#phonediv1").load("auto_order.php?action=productinfo&place="+place+"&idproduct="+productid, function() { });'; - } - else { + } else { print 'AddProductConfirm(placeid, productid);'; } ?> @@ -237,8 +240,7 @@ function AddProductConfirm(placeid, productid){ if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { echo '$("#phonediv2").load("auto_order.php?mobilepage=invoice&action=addline&place="+place+"&idproduct="+productid, function() { });'; - } - else { + } else { echo '$("#phonediv2").load("invoice.php?mobilepage=invoice&action=addline&place="+place+"&idproduct="+productid, function() { });'; } @@ -258,8 +260,7 @@ function SetQty(place, selectedline, qty){ }); } <?php - } - else { + } else { ?> if (qty==0){ $("#phonediv2").load("invoice.php?mobilepage=invoice&action=deleteline&token=<?php echo newToken(); ?>&place="+place+"&idline="+selectedline, function() { @@ -278,7 +279,7 @@ function SetQty(place, selectedline, qty){ function SetNote(place, selectedline){ var note = prompt("<?php $langs->trans('Note'); ?>", ""); $("#phonediv2").load("auto_order.php?mobilepage=invoice&action=updateqty&place="+place+"&idline="+selectedline+"&number="+qty, function() { - }); + }); LoadCats(); } @@ -287,8 +288,7 @@ function LoadCats(){ if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { echo '$("#phonediv1").load("auto_order.php?mobilepage=cats&place="+place, function() { });'; - } - else { + } else { echo '$("#phonediv1").load("invoice.php?mobilepage=cats&place="+place, function() { });'; } @@ -301,8 +301,7 @@ function LoadProducts(idcat){ if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { echo '$("#phonediv1").load("auto_order.php?mobilepage=products&catid="+idcat+"&place="+place, function() { });'; - } - else { + } else { echo '$("#phonediv1").load("invoice.php?mobilepage=products&catid="+idcat+"&place="+place, function() { });'; } @@ -310,20 +309,19 @@ function LoadProducts(idcat){ } function LoadPlacesList(){ - $("#phonediv1").load("invoice.php?mobilepage=places", function() { - }); + $("#phonediv1").load("invoice.php?mobilepage=places", function() { + }); } function TakeposPrintingOrder(){ - console.log("TakeposPrintingOrder"); + console.log("TakeposPrintingOrder"); <?php if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) { echo '$("#phonediv2").load("auto_order.php?action=order&mobilepage=order&place="+place, function() { });'; echo '$("#phonediv1").load("auto_order.php?action=publicpayment&place="+place, function() { });'; - } - else { + } else { echo '$("#phonediv2").load("invoice.php?action=order&place="+place, function() { });'; } @@ -331,7 +329,7 @@ function TakeposPrintingOrder(){ } function Exit(){ - window.location.href='../user/logout.php'; + window.location.href='../user/logout.php'; } function CheckPlease(payment){ @@ -350,7 +348,9 @@ function CheckPlease(payment){ <body style="background-color:#D1D1D1;"> <?php - if ($conf->global->TAKEPOS_NUM_TERMINALS != "1" && $_SESSION["takeposterminal"] == "") print '<div class="dialog-info-takepos-terminal" id="dialog-info" title="TakePOS">'.$langs->trans('TerminalSelect').'</div>'; + if ($conf->global->TAKEPOS_NUM_TERMINALS != "1" && $_SESSION["takeposterminal"] == "") { + print '<div class="dialog-info-takepos-terminal" id="dialog-info" title="TakePOS">'.$langs->trans('TerminalSelect').'</div>'; + } ?> <div class="container"> <div class="phonebuttonsrow"> @@ -360,8 +360,7 @@ function CheckPlease(payment){ print '<button type="button" class="phonebutton" onclick="LoadCats();">'.strtoupper(substr($langs->trans('Categories'), 0, 3)).'</button>'; print '<button type="button" class="phonebutton" onclick="TakeposPrintingOrder();">'.strtoupper(substr($langs->trans('Order'), 0, 3)).'</button>'; print '<button type="button" class="phonebutton" onclick="Exit();">'.strtoupper(substr($langs->trans('Logout'), 0, 3)).'</button>'; - } - else { + } else { print '<button type="button" class="publicphonebutton phoneblue" onclick="LoadCats();">'.strtoupper(substr($langs->trans('Categories'), 0, 5)).'</button>'; print '<button type="button" class="publicphonebutton phoneorange" onclick="PublicPreOrder();">'.strtoupper(substr($langs->trans('Order'), 0, 5)).'</button>'; print '<button type="button" class="publicphonebutton phonegreen" onclick="CheckPlease();">'.strtoupper(substr($langs->trans('Payment'), 0, 5)).'</button>'; diff --git a/htdocs/takepos/public/auto_order.php b/htdocs/takepos/public/auto_order.php index e7853f7141b..308cd75b12e 100644 --- a/htdocs/takepos/public/auto_order.php +++ b/htdocs/takepos/public/auto_order.php @@ -21,18 +21,30 @@ * \brief Public orders for customers */ -if (!defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined("NOLOGIN")) { + define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} require '../../main.inc.php'; -if (!$conf->global->TAKEPOS_AUTO_ORDER) accessforbidden(); // If Auto Order is disabled never allow NO LOGIN access +if (!$conf->global->TAKEPOS_AUTO_ORDER) { + accessforbidden(); // If Auto Order is disabled never allow NO LOGIN access +} $_SESSION["basiclayout"] = 1; $_SESSION["takeposterminal"] = 1; define('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE', 1); -if (GETPOSTISSET("mobilepage")) require '../invoice.php'; -elseif (GETPOSTISSET("genimg")) require DOL_DOCUMENT_ROOT.'/takepos/genimg/index.php'; -else require '../phone.php'; +if (GETPOSTISSET("mobilepage")) { + require '../invoice.php'; +} elseif (GETPOSTISSET("genimg")) { + require DOL_DOCUMENT_ROOT.'/takepos/genimg/index.php'; +} else { + require '../phone.php'; +} diff --git a/htdocs/takepos/public/menu.php b/htdocs/takepos/public/menu.php index 5814888f2cf..ad4dfd9035e 100644 --- a/htdocs/takepos/public/menu.php +++ b/htdocs/takepos/public/menu.php @@ -21,15 +21,23 @@ * \brief Public menu for customers */ -if (!defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) -if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); +if (!defined("NOLOGIN")) { + define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) +} +if (!defined('NOIPCHECK')) { + define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +} +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', '1'); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; -if (!$conf->global->TAKEPOS_QR_MENU) accessforbidden(); // If Restaurant Menu is disabled never allow NO LOGIN access +if (!$conf->global->TAKEPOS_QR_MENU) { + accessforbidden(); // If Restaurant Menu is disabled never allow NO LOGIN access +} ?> <!DOCTYPE html> <html> @@ -43,21 +51,18 @@ if (!$conf->global->TAKEPOS_QR_MENU) accessforbidden(); // If Restaurant Menu is <body> <!-- partial:index.partial.html --> <body> - <div class="grid-container"> - <div class="grid-x grid-padding-x menu2"> - <div class="cell small-12"> - <h1><?php print $mysoc->name; ?> - <small><?php print $langs->trans('RestaurantMenu'); ?></small></h1> + <div class="grid-container"> + <div class="grid-x grid-padding-x menu2"> + <div class="cell small-12"> + <h1><?php print $mysoc->name; ?> - <small><?php print $langs->trans('RestaurantMenu'); ?></small></h1> <?php $categorie = new Categorie($db); $categories = $categorie->get_full_arbo('product', (($conf->global->TAKEPOS_ROOT_CATEGORY_ID > 0) ? $conf->global->TAKEPOS_ROOT_CATEGORY_ID : 0), 1); $levelofrootcategory = 0; -if ($conf->global->TAKEPOS_ROOT_CATEGORY_ID > 0) -{ - foreach ($categories as $key => $categorycursor) - { - if ($categorycursor['id'] == $conf->global->TAKEPOS_ROOT_CATEGORY_ID) - { +if ($conf->global->TAKEPOS_ROOT_CATEGORY_ID > 0) { + foreach ($categories as $key => $categorycursor) { + if ($categorycursor['id'] == $conf->global->TAKEPOS_ROOT_CATEGORY_ID) { $levelofrootcategory = $categorycursor['level']; break; } @@ -67,10 +72,8 @@ $levelofmaincategories = $levelofrootcategory + 1; $maincategories = array(); $subcategories = array(); -foreach ($categories as $key => $categorycursor) -{ - if ($categorycursor['level'] == $levelofmaincategories) - { +foreach ($categories as $key => $categorycursor) { + if ($categorycursor['level'] == $levelofmaincategories) { $maincategories[$key] = $categorycursor; } else { $subcategories[$key] = $categorycursor; @@ -103,12 +106,12 @@ foreach ($maincategories as $cat) { ?> </div> </div> - </div> - <footer class="footer"> - <div class="container"> - <p class="text-muted"><?php print $mysoc->name; ?></p> - </div> - </footer> + </div> + <footer class="footer"> + <div class="container"> + <p class="text-muted"><?php print $mysoc->name; ?></p> + </div> + </footer> </body> <!-- partial --> <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script> diff --git a/htdocs/takepos/receipt.php b/htdocs/takepos/receipt.php index 6a305362839..dd895eb4265 100644 --- a/htdocs/takepos/receipt.php +++ b/htdocs/takepos/receipt.php @@ -4,6 +4,7 @@ * Copyright (C) 2012 Marcos García <marcosgdf@gmail.com> * Copyright (C) 2018 Andreu Bisquerra <jove@bisquerra.com> * Copyright (C) 2019 Josep Lluís Amador <joseplluis@lliuretic.cat> + * Copyright (C) 2021 Nicolas ZABOURI <info@inovea-conseil.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -30,10 +31,18 @@ if (!isset($action)) { //if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); - if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); - if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); - if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); - if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); + if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); + } + if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); + } + if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); + } + if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); + } require '../main.inc.php'; // If this file is called from send.php avoid load again } @@ -58,13 +67,11 @@ if (empty($user->rights->takepos->run)) { top_httphead('text/html'); -if ($place > 0) -{ +if ($place > 0) { $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture where ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")'"; $resql = $db->query($sql); $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $facid = $obj->rowid; } } @@ -85,13 +92,13 @@ if (!empty($hookmanager->resPrint)) { <body> <style> .right { - text-align: right; + text-align: right; } .center { - text-align: center; + text-align: center; } .left { - text-align: left; + text-align: left; } </style> <center> @@ -103,12 +110,15 @@ if (!empty($hookmanager->resPrint)) { <p class="left"> <?php $constFreeText = 'TAKEPOS_HEADER'.$_SESSION['takeposterminal']; -if (!empty($conf->global->TAKEPOS_HEADER) || !empty($conf->global->{$constFreeText})) -{ +if (!empty($conf->global->TAKEPOS_HEADER) || !empty($conf->global->{$constFreeText})) { $newfreetext = ''; $substitutionarray = getCommonSubstitutionArray($langs); - if (!empty($conf->global->TAKEPOS_HEADER)) $newfreetext .= make_substitutions($conf->global->TAKEPOS_HEADER, $substitutionarray); - if (!empty($conf->global->{$constFreeText})) $newfreetext .= make_substitutions($conf->global->{$constFreeText}, $substitutionarray); + if (!empty($conf->global->TAKEPOS_HEADER)) { + $newfreetext .= make_substitutions($conf->global->TAKEPOS_HEADER, $substitutionarray); + } + if (!empty($conf->global->{$constFreeText})) { + $newfreetext .= make_substitutions($conf->global->{$constFreeText}, $substitutionarray); + } print $newfreetext; } ?> @@ -116,16 +126,22 @@ if (!empty($conf->global->TAKEPOS_HEADER) || !empty($conf->global->{$constFreeTe <p class="right"> <?php print $langs->trans('Date')." ".dol_print_date($object->date, 'day').'<br>'; -if (!empty($conf->global->TAKEPOS_RECEIPT_NAME)) print $conf->global->TAKEPOS_RECEIPT_NAME." "; -if ($object->statut == Facture::STATUS_DRAFT) print str_replace(")", "", str_replace("-", " ".$langs->trans('Place')." ", str_replace("(PROV-POS", $langs->trans("Terminal")." ", $object->ref))); -else print $object->ref; -if ($conf->global->TAKEPOS_SHOW_CUSTOMER) -{ - if ($object->socid != $conf->global->{'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]}) - { +if (!empty($conf->global->TAKEPOS_RECEIPT_NAME)) { + print $conf->global->TAKEPOS_RECEIPT_NAME." "; +} +if ($object->statut == Facture::STATUS_DRAFT) { + print str_replace(")", "", str_replace("-", " ".$langs->trans('Place')." ", str_replace("(PROV-POS", $langs->trans("Terminal")." ", $object->ref))); +} else { + print $object->ref; +} +if ($conf->global->TAKEPOS_SHOW_CUSTOMER) { + if ($object->socid != $conf->global->{'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]}) { $soc = new Societe($db); - if ($object->socid > 0) $soc->fetch($object->socid); - else $soc->fetch($conf->global->{'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]}); + if ($object->socid > 0) { + $soc->fetch($object->socid); + } else { + $soc->fetch($conf->global->{'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]}); + } print "<br>".$langs->trans("Customer").': '.$soc->name; } } @@ -134,43 +150,69 @@ if ($conf->global->TAKEPOS_SHOW_CUSTOMER) <br> <table width="100%" style="border-top-style: double;"> - <thead> + <thead> <tr> - <th class="center"><?php print $langs->trans("Label"); ?></th> - <th class="right"><?php print $langs->trans("Qty"); ?></th> - <th class="right"><?php if ($gift != 1) print $langs->trans("Price"); ?></th> - <th class="right"><?php if ($gift != 1) print $langs->trans("TotalTTC"); ?></th> + <th class="center"><?php print $langs->trans("Label"); ?></th> + <th class="right"><?php print $langs->trans("Qty"); ?></th> + <th class="right"><?php if ($gift != 1) { + print $langs->trans("Price"); + } ?></th> + <?php if (!empty($conf->global->TAKEPOS_SHOW_HT_RECEIPT)) { ?> + <th class="right"><?php if ($gift != 1) { + print $langs->trans("TotalHT"); + } ?></th> + <?php } ?> + <th class="right"><?php if ($gift != 1) { + print $langs->trans("TotalTTC"); + } ?></th> </tr> - </thead> - <tbody> - <?php - foreach ($object->lines as $line) - { + </thead> + <tbody> + <?php + foreach ($object->lines as $line) { ?> - <tr> - <td> - <?php if (!empty($line->product_label)) echo $line->product_label; - else echo $line->description; ?> - </td> - <td class="right"><?php echo $line->qty; ?></td> - <td class="right"><?php if ($gift != 1) echo price(price2num($line->total_ttc / $line->qty, 'MT'), 1); ?></td> - <td class="right"><?php if ($gift != 1) echo price($line->total_ttc, 1); ?></td> - </tr> - <?php + <tr> + <td> + <?php if (!empty($line->product_label)) { + echo $line->product_label; + } else { + echo $line->description; + } ?> + </td> + <td class="right"><?php echo $line->qty; ?></td> + <td class="right"><?php if ($gift != 1) { + echo price(price2num($line->total_ttc / $line->qty, 'MT'), 1); + } ?></td> + <?php + if (!empty($conf->global->TAKEPOS_SHOW_HT_RECEIPT)) { ?> + <td class="right"><?php if ($gift != 1) { + echo price($line->total_ht, 1); + } ?></td> + <?php + } + ?> + <td class="right"><?php if ($gift != 1) { + echo price($line->total_ttc, 1); + } ?></td> + </tr> + <?php } ?> - </tbody> + </tbody> </table> <br> <table class="right"> <tr> - <th class="right"><?php if ($gift != 1) echo $langs->trans("TotalHT"); ?></th> - <td class="right"><?php if ($gift != 1) echo price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td> + <th class="right"><?php if ($gift != 1) { + echo $langs->trans("TotalHT"); + } ?></th> + <td class="right"><?php if ($gift != 1) { + echo price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency)."\n"; + } ?></td> </tr> <?php if ($conf->global->TAKEPOS_TICKET_VAT_GROUPPED) { $vat_groups = array(); - foreach ($object->lines as $line) - { + foreach ($object->lines as $line) { if (!array_key_exists($line->tva_tx, $vat_groups)) { $vat_groups[$line->tva_tx] = 0; } @@ -179,18 +221,26 @@ if ($conf->global->TAKEPOS_SHOW_CUSTOMER) foreach ($vat_groups as $key => $val) { ?> <tr> - <th align="right"><?php if ($gift != 1) echo $langs->trans("VAT").' '.vatrate($key, 1); ?></th> - <td align="right"><?php if ($gift != 1) echo price($val, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td> + <th align="right"><?php if ($gift != 1) { + echo $langs->trans("VAT").' '.vatrate($key, 1); + } ?></th> + <td align="right"><?php if ($gift != 1) { + echo price($val, 1, '', 1, - 1, - 1, $conf->currency)."\n"; + } ?></td> </tr> - <?php + <?php } } else { ?> <tr> - <th class="right"><?php if ($gift != 1) echo $langs->trans("TotalVAT").'</th><td class="right">'.price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td> + <th class="right"><?php if ($gift != 1) { + echo $langs->trans("TotalVAT").'</th><td class="right">'.price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency)."\n"; + } ?></td> </tr> <?php } ?> <tr> - <th class="right"><?php if ($gift != 1) echo ''.$langs->trans("TotalTTC").'</th><td class="right">'.price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td> + <th class="right"><?php if ($gift != 1) { + echo ''.$langs->trans("TotalTTC").'</th><td class="right">'.price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency)."\n"; + } ?></td> </tr> <?php if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"] != "" && $conf->currency != $_SESSION["takeposcustomercurrency"]) { @@ -199,7 +249,9 @@ if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency" $multicurrency = new MultiCurrency($db); $multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]); echo '<tr><th class="right">'; - if ($gift != 1) echo ''.$langs->trans("TotalTTC").' '.$_SESSION["takeposcustomercurrency"].'</th><td class="right">'.price($object->total_ttc * $multicurrency->rate->rate, 1, '', 1, - 1, - 1, $_SESSION["takeposcustomercurrency"])."\n"; + if ($gift != 1) { + echo ''.$langs->trans("TotalTTC").' '.$_SESSION["takeposcustomercurrency"].'</th><td class="right">'.price($object->total_ttc * $multicurrency->rate->rate, 1, '', 1, - 1, - 1, $_SESSION["takeposcustomercurrency"])."\n"; + } echo '</td></tr>'; } @@ -211,8 +263,7 @@ if ($conf->global->TAKEPOS_PRINT_PAYMENT_METHOD) { $sql .= " WHERE pf.fk_paiement = p.rowid AND pf.fk_facture = ".$facid; $sql .= " ORDER BY p.datep"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; while ($i < $num) { @@ -223,12 +274,13 @@ if ($conf->global->TAKEPOS_PRINT_PAYMENT_METHOD) { echo '</td>'; echo '<td class="right">'; $amount_payment = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) ? $row->multicurrency_amount : $row->amount; - if ($row->code == "LIQ") $amount_payment = $amount_payment + $row->pos_change; // Show amount with excess received if is cash payment + if ($row->code == "LIQ") { + $amount_payment = $amount_payment + $row->pos_change; // Show amount with excess received if is cash payment + } echo price($amount_payment, 1, '', 1, - 1, - 1, $conf->currency); echo '</td>'; echo '</tr>'; - if ($row->code == "LIQ" && $row->pos_change > 0) // Print change only in cash payments - { + if ($row->code == "LIQ" && $row->pos_change > 0) { // Print change only in cash payments echo '<tr>'; echo '<td class="right">'; echo $langs->trans("Change"); @@ -250,18 +302,21 @@ if ($conf->global->TAKEPOS_PRINT_PAYMENT_METHOD) { <br> <?php $constFreeText = 'TAKEPOS_FOOTER'.$_SESSION['takeposterminal']; -if (!empty($conf->global->TAKEPOS_FOOTER) || !empty($conf->global->{$constFreeText})) -{ +if (!empty($conf->global->TAKEPOS_FOOTER) || !empty($conf->global->{$constFreeText})) { $newfreetext = ''; $substitutionarray = getCommonSubstitutionArray($langs); - if (!empty($conf->global->{$constFreeText})) $newfreetext .= make_substitutions($conf->global->{$constFreeText}, $substitutionarray); - if (!empty($conf->global->TAKEPOS_FOOTER)) $newfreetext .= make_substitutions($conf->global->TAKEPOS_FOOTER, $substitutionarray); + if (!empty($conf->global->{$constFreeText})) { + $newfreetext .= make_substitutions($conf->global->{$constFreeText}, $substitutionarray); + } + if (!empty($conf->global->TAKEPOS_FOOTER)) { + $newfreetext .= make_substitutions($conf->global->TAKEPOS_FOOTER, $substitutionarray); + } print $newfreetext; } ?> <script type="text/javascript"> - window.print(); + window.print(); </script> </body> </html> diff --git a/htdocs/takepos/reduction.php b/htdocs/takepos/reduction.php index dd808d9a19d..38b284a8ed0 100644 --- a/htdocs/takepos/reduction.php +++ b/htdocs/takepos/reduction.php @@ -25,11 +25,21 @@ //if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} require '../main.inc.php'; // Load $user and permissions require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; @@ -48,19 +58,16 @@ if (empty($user->rights->takepos->run)) { */ $invoice = new Facture($db); -if ($invoiceid > 0) -{ +if ($invoiceid > 0) { $invoice->fetch($invoiceid); } else { $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture where ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")'"; $resql = $db->query($sql); $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $invoiceid = $obj->rowid; } - if (!$invoiceid) - { + if (!$invoiceid) { $invoiceid = 0; // Invoice does not exist yet } else { $invoice->fetch($invoiceid); @@ -87,111 +94,111 @@ if (!isset($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON) || !empty($conf->glob <body> <script> - var reductionType =''; + var reductionType =''; var reductionTotal = ''; - var editAction = ''; - var editNumber = ''; + var editAction = ''; + var editNumber = ''; var htmlBtnOK = '<span style="font-size: 14pt;">OK</span>'; var htmlReductionPercent = '<?php echo dol_escape_js($htmlReductionPercent); ?>'; var htmlReductionAmount = '<?php echo dol_escape_js($htmlReductionAmount); ?>'; - /** - * Reset values - */ - function Reset() - { - reductionType = ''; - reductionTotal = ''; - editAction = ''; - editNumber = ''; - jQuery('#reduction_total').val(reductionTotal); + /** + * Reset values + */ + function Reset() + { + reductionType = ''; + reductionTotal = ''; + editAction = ''; + editNumber = ''; + jQuery('#reduction_total').val(reductionTotal); jQuery("#reduction_type_percent").html(htmlReductionPercent); jQuery('#reduction_type_amount').html(htmlReductionAmount); - } + } - /** - * Edit action - * - * @param {string} number Number pressed - */ - function Edit(number) - { - console.log('Edit ' + number); + /** + * Edit action + * + * @param {string} number Number pressed + */ + function Edit(number) + { + console.log('Edit ' + number); - if (number === 'p') { - if (editAction === 'p' && reductionType === 'percent'){ - ValidateReduction(); - } else { - editAction = 'p'; - } - reductionType = 'percent'; - } else if (number === 'a') { - if (editAction === 'a' && reductionType === 'amount'){ - ValidateReduction(); - } else { - editAction = 'a'; - } - reductionType = 'amount'; - } + if (number === 'p') { + if (editAction === 'p' && reductionType === 'percent'){ + ValidateReduction(); + } else { + editAction = 'p'; + } + reductionType = 'percent'; + } else if (number === 'a') { + if (editAction === 'a' && reductionType === 'amount'){ + ValidateReduction(); + } else { + editAction = 'a'; + } + reductionType = 'amount'; + } - if (editAction === 'p'){ + if (editAction === 'p'){ jQuery('#reduction_type_percent').html(htmlBtnOK); jQuery('#reduction_type_amount').html(htmlReductionAmount); - } else if (editAction === 'a'){ + } else if (editAction === 'a'){ jQuery('#reduction_type_amount').html(htmlBtnOK); jQuery("#reduction_type_percent").html(htmlReductionPercent); - } else { + } else { jQuery('#reduction_type_percent').html(htmlReductionPercent); jQuery('#reduction_type_amount').html(htmlReductionAmount); - } - } + } + } - /** - * Add a number in reduction input - * - * @param {string} reductionNumber Number pressed - */ - function AddReduction(reductionNumber) - { - console.log('AddReduction ' + reductionNumber); + /** + * Add a number in reduction input + * + * @param {string} reductionNumber Number pressed + */ + function AddReduction(reductionNumber) + { + console.log('AddReduction ' + reductionNumber); - reductionTotal += String(reductionNumber); - jQuery('#reduction_total').val(reductionTotal); - } + reductionTotal += String(reductionNumber); + jQuery('#reduction_total').val(reductionTotal); + } - /** - * Validate a reduction - */ + /** + * Validate a reduction + */ function ValidateReduction() { - console.log('ValidateReduction'); + console.log('ValidateReduction'); - if (reductionTotal.length <= 0) { - console.error('Error no reduction'); - return; - } + if (reductionTotal.length <= 0) { + console.error('Error no reduction'); + return; + } - var reductionNumber = parseFloat(reductionTotal); - if (isNaN(reductionNumber)) { - console.error('Error not a valid number :', reductionNumber); - return; - } + var reductionNumber = parseFloat(reductionTotal); + if (isNaN(reductionNumber)) { + console.error('Error not a valid number :', reductionNumber); + return; + } - if (reductionType === 'percent') { - var invoiceid = <?php echo ($invoiceid > 0 ? $invoiceid : 0); ?>; - parent.$("#poslines").load("invoice.php?action=update_reduction_global&place=<?php echo $place; ?>&number="+reductionNumber+"&invoiceid="+invoiceid, function() { - Reset(); - parent.$.colorbox.close(); - }); - } else if (reductionType === 'amount') { - var desc = "<?php echo dol_escape_js($langs->transnoentities('Reduction')); ?>"; - parent.$("#poslines").load("invoice.php?action=freezone&place=<?php echo $place; ?>&number=-"+reductionNumber+"&desc="+desc, function() { - Reset(); - parent.$.colorbox.close(); - }); - } else { - console.error('Error bad reduction type :', reductionType); - } + if (reductionType === 'percent') { + var invoiceid = <?php echo ($invoiceid > 0 ? $invoiceid : 0); ?>; + parent.$("#poslines").load("invoice.php?action=update_reduction_global&place=<?php echo $place; ?>&number="+reductionNumber+"&invoiceid="+invoiceid, function() { + Reset(); + parent.$.colorbox.close(); + }); + } else if (reductionType === 'amount') { + var desc = "<?php echo dol_escape_js($langs->transnoentities('Reduction')); ?>"; + parent.$("#poslines").load("invoice.php?action=freezone&place=<?php echo $place; ?>&number=-"+reductionNumber+"&desc="+desc, function() { + Reset(); + parent.$.colorbox.close(); + }); + } else { + console.error('Error bad reduction type :', reductionType); + } } </script> diff --git a/htdocs/takepos/send.php b/htdocs/takepos/send.php index f33457992a7..9f98d5fbd7d 100644 --- a/htdocs/takepos/send.php +++ b/htdocs/takepos/send.php @@ -26,11 +26,21 @@ //if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} require '../main.inc.php'; // Load $user and permissions require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -51,8 +61,7 @@ $invoice->fetch($facid); $customer = new Societe($db); $customer->fetch($invoice->socid); -if ($action == "send") -{ +if ($action == "send") { include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); @@ -87,9 +96,9 @@ top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); <script> function SendMail() { $.ajax({ - type: "GET", - url: "<?php print dol_buildpath('/takepos/send.php', 1).'?action=send&facid='.$facid.'&email='; ?>" + $("#email"). val(), - }); + type: "GET", + url: "<?php print dol_buildpath('/takepos/send.php', 1).'?action=send&facid='.$facid.'&email='; ?>" + $("#email"). val(), + }); parent.$.colorbox.close(); } diff --git a/htdocs/takepos/smpcb.php b/htdocs/takepos/smpcb.php index 1e02e9bc591..7cc504abdf0 100644 --- a/htdocs/takepos/smpcb.php +++ b/htdocs/takepos/smpcb.php @@ -21,11 +21,21 @@ * \brief Page with the content for smpcb payment */ -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} require '../main.inc.php'; diff --git a/htdocs/theme/common/everybody.png b/htdocs/theme/common/everybody.png new file mode 100644 index 00000000000..efe0d3e2807 Binary files /dev/null and b/htdocs/theme/common/everybody.png differ diff --git a/htdocs/theme/common/paypal.png b/htdocs/theme/common/paypal.png deleted file mode 100644 index 32cae0ca9eb..00000000000 Binary files a/htdocs/theme/common/paypal.png and /dev/null differ diff --git a/htdocs/theme/common/treemenu/trash.gif b/htdocs/theme/common/treemenu/trash.gif deleted file mode 100644 index cfa0f000e1e..00000000000 Binary files a/htdocs/theme/common/treemenu/trash.gif and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/index.html b/htdocs/theme/common/weather/index.html similarity index 100% rename from htdocs/theme/eldy/img/menus/index.html rename to htdocs/theme/common/weather/index.html diff --git a/htdocs/theme/eldy/img/weather/weather-clear-night.png b/htdocs/theme/common/weather/weather-clear-night.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-clear-night.png rename to htdocs/theme/common/weather/weather-clear-night.png diff --git a/htdocs/theme/eldy/img/weather/weather-clear.png b/htdocs/theme/common/weather/weather-clear.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-clear.png rename to htdocs/theme/common/weather/weather-clear.png diff --git a/htdocs/theme/eldy/img/weather/weather-clouds-night.png b/htdocs/theme/common/weather/weather-clouds-night.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-clouds-night.png rename to htdocs/theme/common/weather/weather-clouds-night.png diff --git a/htdocs/theme/eldy/img/weather/weather-clouds.png b/htdocs/theme/common/weather/weather-clouds.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-clouds.png rename to htdocs/theme/common/weather/weather-clouds.png diff --git a/htdocs/theme/eldy/img/weather/weather-few-clouds-night.png b/htdocs/theme/common/weather/weather-few-clouds-night.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-few-clouds-night.png rename to htdocs/theme/common/weather/weather-few-clouds-night.png diff --git a/htdocs/theme/eldy/img/weather/weather-few-clouds.png b/htdocs/theme/common/weather/weather-few-clouds.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-few-clouds.png rename to htdocs/theme/common/weather/weather-few-clouds.png diff --git a/htdocs/theme/eldy/img/weather/weather-freezing-rain.png b/htdocs/theme/common/weather/weather-freezing-rain.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-freezing-rain.png rename to htdocs/theme/common/weather/weather-freezing-rain.png diff --git a/htdocs/theme/eldy/img/weather/weather-hail.png b/htdocs/theme/common/weather/weather-hail.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-hail.png rename to htdocs/theme/common/weather/weather-hail.png diff --git a/htdocs/theme/eldy/img/weather/weather-many-clouds.png b/htdocs/theme/common/weather/weather-many-clouds.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-many-clouds.png rename to htdocs/theme/common/weather/weather-many-clouds.png diff --git a/htdocs/theme/eldy/img/weather/weather-mist.png b/htdocs/theme/common/weather/weather-mist.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-mist.png rename to htdocs/theme/common/weather/weather-mist.png diff --git a/htdocs/theme/eldy/img/weather/weather-showers-day.png b/htdocs/theme/common/weather/weather-showers-day.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-showers-day.png rename to htdocs/theme/common/weather/weather-showers-day.png diff --git a/htdocs/theme/eldy/img/weather/weather-showers-night.png b/htdocs/theme/common/weather/weather-showers-night.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-showers-night.png rename to htdocs/theme/common/weather/weather-showers-night.png diff --git a/htdocs/theme/eldy/img/weather/weather-showers-scattered-day.png b/htdocs/theme/common/weather/weather-showers-scattered-day.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-showers-scattered-day.png rename to htdocs/theme/common/weather/weather-showers-scattered-day.png diff --git a/htdocs/theme/eldy/img/weather/weather-showers-scattered-night.png b/htdocs/theme/common/weather/weather-showers-scattered-night.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-showers-scattered-night.png rename to htdocs/theme/common/weather/weather-showers-scattered-night.png diff --git a/htdocs/theme/eldy/img/weather/weather-showers-scattered.png b/htdocs/theme/common/weather/weather-showers-scattered.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-showers-scattered.png rename to htdocs/theme/common/weather/weather-showers-scattered.png diff --git a/htdocs/theme/eldy/img/weather/weather-showers.png b/htdocs/theme/common/weather/weather-showers.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-showers.png rename to htdocs/theme/common/weather/weather-showers.png diff --git a/htdocs/theme/eldy/img/weather/weather-snow-rain.png b/htdocs/theme/common/weather/weather-snow-rain.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-snow-rain.png rename to htdocs/theme/common/weather/weather-snow-rain.png diff --git a/htdocs/theme/eldy/img/weather/weather-snow-scattered-day.png b/htdocs/theme/common/weather/weather-snow-scattered-day.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-snow-scattered-day.png rename to htdocs/theme/common/weather/weather-snow-scattered-day.png diff --git a/htdocs/theme/eldy/img/weather/weather-snow-scattered-night.png b/htdocs/theme/common/weather/weather-snow-scattered-night.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-snow-scattered-night.png rename to htdocs/theme/common/weather/weather-snow-scattered-night.png diff --git a/htdocs/theme/eldy/img/weather/weather-snow-scattered.png b/htdocs/theme/common/weather/weather-snow-scattered.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-snow-scattered.png rename to htdocs/theme/common/weather/weather-snow-scattered.png diff --git a/htdocs/theme/eldy/img/weather/weather-snow.png b/htdocs/theme/common/weather/weather-snow.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-snow.png rename to htdocs/theme/common/weather/weather-snow.png diff --git a/htdocs/theme/eldy/img/weather/weather-storm-day.png b/htdocs/theme/common/weather/weather-storm-day.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-storm-day.png rename to htdocs/theme/common/weather/weather-storm-day.png diff --git a/htdocs/theme/eldy/img/weather/weather-storm-night.png b/htdocs/theme/common/weather/weather-storm-night.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-storm-night.png rename to htdocs/theme/common/weather/weather-storm-night.png diff --git a/htdocs/theme/eldy/img/weather/weather-storm.png b/htdocs/theme/common/weather/weather-storm.png similarity index 100% rename from htdocs/theme/eldy/img/weather/weather-storm.png rename to htdocs/theme/common/weather/weather-storm.png diff --git a/htdocs/theme/eldy/badges.inc.php b/htdocs/theme/eldy/badges.inc.php index 00c2a91a29c..f3f311eccca 100644 --- a/htdocs/theme/eldy/badges.inc.php +++ b/htdocs/theme/eldy/badges.inc.php @@ -1,140 +1,142 @@ <?php -if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); +if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* Badge style is based on boostrap framework */ .badge { - display: inline-block; - padding: .1em .35em; - font-size: 80%; - font-weight: 700 !important; - line-height: 1; - text-align: center; - white-space: nowrap; - vertical-align: baseline; - border-radius: .25rem; - transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out; - border-width: 2px; - border-style: solid; - border-color: rgba(255,255,255,0); - box-sizing: border-box; + display: inline-block; + padding: .1em .35em; + font-size: 80%; + font-weight: 700 !important; + line-height: 1; + text-align: center; + white-space: nowrap; + vertical-align: baseline; + border-radius: .25rem; + transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out; + border-width: 2px; + border-style: solid; + border-color: rgba(255,255,255,0); + box-sizing: border-box; } .badge-status { - font-size: 0.95em; - padding: .19em .35em; /* more than 0.19 generate a change into heigth of lines */ + font-size: 0.95em; + padding: .19em .35em; /* more than 0.19 generate a change into heigth of lines */ } .tabBar .arearef .statusref .badge-status, .tabBar .arearefnobottom .statusref .badge-status { - font-size: 1.1em; - padding: .4em .4em; + font-size: 1.1em; + padding: .4em .4em; } /* Force values for small screen 767 */ @media only screen and (max-width: 767px) { .tabBar .arearef .statusref .badge-status, .tabBar .arearefnobottom .statusref .badge-status { - font-size: 0.95em; - padding: .3em .2em; + font-size: 0.95em; + padding: .3em .2em; } } .badge-pill, .tabs .badge { - padding-right: .5em; - padding-left: .5em; - border-radius: 0.25rem; + padding-right: .5em; + padding-left: .5em; + border-radius: 0.25rem; } .badge-dot { - padding: 0; - border-radius: 50%; - padding: 0.45em; - vertical-align: text-top; + padding: 0; + border-radius: 50%; + padding: 0.45em; + vertical-align: text-top; } a.badge:focus, a.badge:hover { - text-decoration: none; + text-decoration: none; } .liste_titre .badge:not(.nochangebackground) { - background-color: <?php print $badgeSecondary; ?>; - color: #fff; + background-color: <?php print $badgeSecondary; ?>; + color: #fff; } span.badgeneutral { - padding: 2px 7px 2px 7px; - background-color: #e4e4e4; - color: #666; - border-radius: 10px; + padding: 2px 7px 2px 7px; + background-color: #e4e4e4; + color: #666; + border-radius: 10px; } /* PRIMARY */ .badge-primary{ - color: #fff !important; - background-color: <?php print $badgePrimary; ?>; + color: #fff !important; + background-color: <?php print $badgePrimary; ?>; } a.badge-primary.focus, a.badge-primary:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgePrimary, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgePrimary, 0.5); ?>; } a.badge-primary:focus, a.badge-primary:hover { - color: #fff !important; - background-color: <?php print colorDarker($badgePrimary, 10); ?>; + color: #fff !important; + background-color: <?php print colorDarker($badgePrimary, 10); ?>; } /* SECONDARY */ .badge-secondary, .tabs .badge { - color: #fff !important; - background-color: <?php print $badgeSecondary; ?>; + color: #fff !important; + background-color: <?php print $badgeSecondary; ?>; } a.badge-secondary.focus, a.badge-secondary:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeSecondary, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeSecondary, 0.5); ?>; } a.badge-secondary:focus, a.badge-secondary:hover { - color: #fff !important; - background-color: <?php print colorDarker($badgeSecondary, 10); ?>; + color: #fff !important; + background-color: <?php print colorDarker($badgeSecondary, 10); ?>; } /* SUCCESS */ .badge-success { - color: #fff !important; - background-color: <?php print $badgeSuccess; ?>; + color: #fff !important; + background-color: <?php print $badgeSuccess; ?>; } a.badge-success.focus, a.badge-success:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeSuccess, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeSuccess, 0.5); ?>; } a.badge-success:focus, a.badge-success:hover { - color: #fff !important; - background-color: <?php print colorDarker($badgeSuccess, 10); ?>; + color: #fff !important; + background-color: <?php print colorDarker($badgeSuccess, 10); ?>; } /* DANGER */ .badge-danger { - color: #fff !important; - background-color: <?php print $badgeDanger; ?>; + color: #fff !important; + background-color: <?php print $badgeDanger; ?>; } a.badge-danger.focus, a.badge-danger:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeDanger, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeDanger, 0.5); ?>; } a.badge-danger:focus, a.badge-danger:hover { - color: #fff !important; - background-color: <?php print colorDarker($badgeDanger, 10); ?>; + color: #fff !important; + background-color: <?php print colorDarker($badgeDanger, 10); ?>; } /* WARNING */ .badge-warning { - color: #fff !important; - background-color: <?php print $badgeWarning; ?>; + color: #fff !important; + background-color: <?php print $badgeWarning; ?>; } a.badge-warning.focus, a.badge-warning:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeWarning, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeWarning, 0.5); ?>; } a.badge-warning:focus, a.badge-warning:hover { - color: #212529 !important; - background-color: <?php print colorDarker($badgeWarning, 10); ?>; + color: #212529 !important; + background-color: <?php print colorDarker($badgeWarning, 10); ?>; } /* WARNING colorblind */ @@ -150,53 +152,53 @@ body[class*="colorblind-"] a.badge-warning:focus, a.badge-warning:hover { /* INFO */ .badge-info { - color: #fff !important; - background-color: <?php print $badgeInfo; ?>; + color: #fff !important; + background-color: <?php print $badgeInfo; ?>; } a.badge-info.focus, a.badge-info:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeInfo, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeInfo, 0.5); ?>; } a.badge-info:focus, a.badge-info:hover { - color: #fff !important; - background-color: <?php print colorDarker($badgeInfo, 10); ?>; + color: #fff !important; + background-color: <?php print colorDarker($badgeInfo, 10); ?>; } /* LIGHT */ .badge-light { - color: #212529 !important; - background-color: <?php print $badgeLight; ?>; + color: #212529 !important; + background-color: <?php print $badgeLight; ?>; } a.badge-light.focus, a.badge-light:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeLight, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeLight, 0.5); ?>; } a.badge-light:focus, a.badge-light:hover { - color: #212529 !important; - background-color: <?php print colorDarker($badgeLight, 10); ?>; + color: #212529 !important; + background-color: <?php print colorDarker($badgeLight, 10); ?>; } /* DARK */ .badge-dark { - color: #fff !important; - background-color: <?php print $badgeDark; ?>; + color: #fff !important; + background-color: <?php print $badgeDark; ?>; } a.badge-dark.focus, a.badge-dark:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeDark, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeDark, 0.5); ?>; } a.badge-dark:focus, a.badge-dark:hover { - color: #fff !important; - background-color: <?php print colorDarker($badgeDark, 10); ?>; + color: #fff !important; + background-color: <?php print colorDarker($badgeDark, 10); ?>; } @media only screen and (max-width: 570px) { span.badge.badge-status { - overflow: hidden; - max-width: 130px; - text-overflow: ellipsis; + overflow: hidden; + max-width: 130px; + text-overflow: ellipsis; } } @@ -246,8 +248,12 @@ function _createStatusBadgeCss($statusName, $statusVarNamePrefix = '', $commentL $thisBadgeBackgroundColor = "#fff"; } - if (in_array((string) $statusName, array('0', '5', '9'))) $thisBadgeTextColor = '#999999'; - if (in_array((string) $statusName, array('6'))) $thisBadgeTextColor = '#777777'; + if (in_array((string) $statusName, array('0', '5', '9'))) { + $thisBadgeTextColor = '#999999'; + } + if (in_array((string) $statusName, array('6'))) { + $thisBadgeTextColor = '#777777'; + } print $cssPrefix.".badge-status".$statusName." {\n"; print " color: ".$thisBadgeTextColor." !important;\n"; diff --git a/htdocs/theme/eldy/btn.inc.php b/htdocs/theme/eldy/btn.inc.php index d6a2251b390..2d6916659cb 100644 --- a/htdocs/theme/eldy/btn.inc.php +++ b/htdocs/theme/eldy/btn.inc.php @@ -1,19 +1,21 @@ <?php -if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> +if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* <style type="text/css" > */ :root { - --btncolortext:rgb(<?php print $colortextlink; ?>); - --btncolorbg: #fbfbfb; - --btncolorborderhover: none; - --btncolorborder: #FFF; - /* --butactionbg:rgba(150, 110, 162, 0.95); */ - --butactionbg:rgb(118, 145, 225); - --butactionbg:rgba(150, 110, 162, 0.95); - --butactiondeletebg: rgb(234,228,225); - /* tertiary color */ - /* --butactionbg:rgb(218, 235, 225); */ - /* --butactionbg:rgb(228, 218, 235); */ + --btncolortext:rgb(<?php print $colortextlink; ?>); + --btncolorbg: #fbfbfb; + --btncolorborderhover: none; + --btncolorborder: #FFF; + /* --butactionbg:rgba(150, 110, 162, 0.95); */ + --butactionbg:rgb(118, 145, 225); + --butactionbg:rgba(150, 110, 162, 0.95); + --butactiondeletebg: rgb(234,228,225); + /* tertiary color */ + /* --butactionbg:rgb(218, 235, 225); */ + /* --butactionbg:rgb(228, 218, 235); */ } <?php @@ -45,60 +47,65 @@ if (!empty($conf->global->THEME_DARKMODEENABLED)) { /* ============================================================================== */ div.divButAction { - margin-bottom: 1.4em; + margin-bottom: 1.4em; } div.tabsAction > a.butAction, div.tabsAction > a.butActionRefused, div.tabsAction > a.butActionDelete, div.tabsAction > span.butAction, div.tabsAction > span.butActionRefused, div.tabsAction > span.butActionDelete { - margin-bottom: 1.4em !important; + margin-bottom: 1.4em !important; } div.tabsActionNoBottom > a.butAction, div.tabsActionNoBottom > a.butActionRefused { - margin-bottom: 0 !important; + margin-bottom: 0 !important; } span.butAction, span.butActionDelete { - cursor: pointer; + cursor: pointer; } .paginationafterarrows .butAction { - font-size: 0.9em; + font-size: 0.9em; } .butAction { - background: var(--butactionbg); - color: #FFF !important; - border-radius: 3px; - /* background: rgb(230, 232, 239); */ + background: var(--butactionbg); + color: #FFF !important; + /* background: rgb(230, 232, 239); */ +} +.butActionRefused, .butAction, .butActionDelete { + border-radius: 3px; +} +.butActionRefused:last-child, .butAction:last-child, .butActionDelete:last-child { + margin-right: 0px !important; } .butActionRefused, .butAction, .butAction:link, .butAction:visited, .butAction:hover, .butAction:active, .butActionDelete, .butActionDelete:link, .butActionDelete:visited, .butActionDelete:hover, .butActionDelete:active { - text-decoration: none; - text-transform: uppercase; - font-weight: bold; + text-decoration: none; + text-transform: uppercase; + font-weight: bold; - margin: 0em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.9'); ?>em; - padding: 0.6em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.7'); ?>em; - display: inline-block; - text-align: center; - cursor: pointer; - /* color: #fff; */ - /* background: rgb(<?php echo $colorbackhmenu1 ?>); */ - color: #444; - /* border: 1px solid #aaa; */ - /* border-color: rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.25); */ + margin: 0em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.9'); ?>em; + padding: 0.6em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.7'); ?>em; + display: inline-block; + text-align: center; + cursor: pointer; + /* color: #fff; */ + /* background: rgb(<?php echo $colorbackhmenu1 ?>); */ + color: #444; + /* border: 1px solid #aaa; */ + /* border-color: rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.25); */ - /*border-top-right-radius: 0 !important; - border-bottom-right-radius: 0 !important; - border-top-left-radius: 0 !important; - border-bottom-left-radius: 0 !important;*/ + /*border-top-right-radius: 0 !important; + border-bottom-right-radius: 0 !important; + border-top-left-radius: 0 !important; + border-bottom-left-radius: 0 !important;*/ } .butActionNew, .butActionNewRefused, .butActionNew:link, .butActionNew:visited, .butActionNew:hover, .butActionNew:active { - text-decoration: none; - text-transform: uppercase; - font-weight: normal; + text-decoration: none; + text-transform: uppercase; + font-weight: normal; - margin: 0em 0.3em 0 0.3em !important; - padding: 0.2em <?php echo ($dol_optimize_smallscreen ? '0.4' : '0.7'); ?>em 0.3em; - font-family: <?php print $fontlist ?>; - display: inline-block; - /* text-align: center; New button are on right of screen */ - cursor: pointer; + margin: 0em 0.3em 0 0.3em !important; + padding: 0.2em <?php echo ($dol_optimize_smallscreen ? '0.4' : '0.7'); ?>em 0.3em; + font-family: <?php print $fontlist ?>; + display: inline-block; + /* text-align: center; New button are on right of screen */ + cursor: pointer; } .tableforfieldcreate a.butActionNew>span.fa-plus-circle, .tableforfieldcreate a.butActionNew>span.fa-plus-circle:hover, @@ -127,66 +134,66 @@ span.butActionNewRefused>span.fa, span.butActionNewRefused>span.fa:hover } .butAction:hover { - -webkit-box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); - box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); + -webkit-box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); + box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); } .butActionNew:hover { - text-decoration: underline; - box-shadow: unset !important; + text-decoration: underline; + box-shadow: unset !important; } .butActionDelete, .butActionDelete:link, .butActionDelete:visited, .butActionDelete:hover, .butActionDelete:active, .buttonDelete { - background: var(--butactiondeletebg); - /* border: 1px solid #633; */ - color: #633; + background: var(--butactiondeletebg); + /* border: 1px solid #633; */ + color: #633; } .butActionDelete:hover { - -webkit-box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); - box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); + -webkit-box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); + box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); } .butActionRefused { - text-decoration: none !important; - text-transform: uppercase; - font-weight: bold !important; + text-decoration: none !important; + text-transform: uppercase; + font-weight: bold !important; - white-space: nowrap !important; - cursor: not-allowed !important; - margin: 0em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.9'); ?>em; - padding: 0.6em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.7'); ?>em; - font-family: <?php print $fontlist ?> !important; - display: inline-block; - text-align: center; - cursor: pointer; - color: #999 !important; - border: 1px solid #ccc; - box-sizing: border-box; - -moz-box-sizing: border-box; - -webkit-box-sizing: border-box; + white-space: nowrap !important; + cursor: not-allowed !important; + margin: 0em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.9'); ?>em; + padding: 0.6em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.7'); ?>em; + font-family: <?php print $fontlist ?> !important; + display: inline-block; + text-align: center; + cursor: pointer; + color: #999 !important; + border: 1px solid #ccc; + box-sizing: border-box; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; } .butActionNewRefused, .butActionNewRefused:link, .butActionNewRefused:visited, .butActionNewRefused:hover, .butActionNewRefused:active { - text-decoration: none !important; - text-transform: uppercase; - font-weight: normal !important; + text-decoration: none !important; + text-transform: uppercase; + font-weight: normal !important; - white-space: nowrap !important; - cursor: not-allowed !important; - margin: 0em <?php echo ($dol_optimize_smallscreen ? '0.7' : '0.9'); ?>em; - padding: 0.2em <?php echo ($dol_optimize_smallscreen ? '0.4' : '0.7'); ?>em; - font-family: <?php print $fontlist ?> !important; - display: inline-block; - /* text-align: center; New button are on right of screen */ - cursor: pointer; - color: #999 !important; - padding-top: 0.2em; - box-shadow: none !important; - -webkit-box-shadow: none !important; + white-space: nowrap !important; + cursor: not-allowed !important; + margin: 0em <?php echo ($dol_optimize_smallscreen ? '0.7' : '0.9'); ?>em; + padding: 0.2em <?php echo ($dol_optimize_smallscreen ? '0.4' : '0.7'); ?>em; + font-family: <?php print $fontlist ?> !important; + display: inline-block; + /* text-align: center; New button are on right of screen */ + cursor: pointer; + color: #999 !important; + padding-top: 0.2em; + box-shadow: none !important; + -webkit-box-shadow: none !important; } .butActionTransparent { - color: #222 ! important; - background-color: transparent ! important; + color: #222 ! important; + background-color: transparent ! important; } @@ -195,37 +202,37 @@ TITLE BUTTON */ .btnTitle, a.btnTitle { - display: inline-block; - padding: 4px 4px 4px 4px; - font-weight: 400; - /* line-height: 1; */ - text-align: center; - white-space: nowrap; - vertical-align: middle; - -ms-touch-action: manipulation; - touch-action: manipulation; - cursor: pointer; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; - box-shadow: var(--btncolorbg); - text-decoration: none; - position: relative; - /* margin: 0 0 0 8px; */ - min-width: 72px; - text-align: center; - color: var(--btncolortext); - border: none; - font-size: 12px; - font-weight: 300; - background-color: var(--btncolorbg); + display: inline-block; + padding: 4px 4px 4px 4px; + font-weight: 400; + /* line-height: 1; */ + text-align: center; + white-space: nowrap; + vertical-align: middle; + -ms-touch-action: manipulation; + touch-action: manipulation; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + box-shadow: var(--btncolorbg); + text-decoration: none; + position: relative; + /* margin: 0 0 0 8px; */ + min-width: 72px; + text-align: center; + color: var(--btncolortext); + border: none; + font-size: 12px; + font-weight: 300; + background-color: var(--btncolorbg); border: 1px solid var(--btncolorborder); } a.btnTitle.btnTitleSelected { - border: 1px solid #ccc; - border-radius: 3px; + border: 1px solid #ccc; + border-radius: 3px; } .btnTitle > .btnTitle-icon{ @@ -233,43 +240,43 @@ a.btnTitle.btnTitleSelected { } .btnTitle > .btnTitle-label{ - color: #666666; + color: #666666; } .btnTitle:hover, a.btnTitle:hover { border: 1px solid #bbb; - border-radius: 3px; - position: relative; - text-align: center; - /* color: #ffffff; - background-color: rgb(<?php print $colortextlink; ?>); */ - font-size: 12px; - text-decoration: none; - box-shadow: none; + border-radius: 3px; + position: relative; + text-align: center; + /* color: #ffffff; + background-color: rgb(<?php print $colortextlink; ?>); */ + font-size: 12px; + text-decoration: none; + box-shadow: none; } .btnTitle.refused, a.btnTitle.refused, .btnTitle.refused:hover, a.btnTitle.refused:hover { - color: #8a8a8a; - cursor: not-allowed; - background-color: #fbfbfb; - background: repeating-linear-gradient( 45deg, #ffffff, #f1f1f1 4px, #f1f1f1 4px, #f1f1f1 4px ); + color: #8a8a8a; + cursor: not-allowed; + background-color: #fbfbfb; + background: repeating-linear-gradient( 45deg, #ffffff, #f1f1f1 4px, #f1f1f1 4px, #f1f1f1 4px ); } .btnTitle:hover .btnTitle-label{ - color: var(--btncolorborderhover); + color: var(--btncolorborderhover); } .btnTitle.refused .btnTitle-label, .btnTitle.refused:hover .btnTitle-label{ - color: #8a8a8a; + color: #8a8a8a; } .btnTitle>.fa { - font-size: 20px; - display: block; + font-size: 20px; + display: block; } div.pagination li:first-child a.btnTitle{ - margin-left: 10px; + margin-left: 10px; } @@ -284,15 +291,15 @@ div.pagination li:first-child a.btnTitle{ font-size: 0.95em; } .btnTitle, a.btnTitle { - display: inline-block; - padding: 4px 4px 4px 4px; + display: inline-block; + padding: 4px 4px 4px 4px; min-width: unset; } } <?php if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin)) { ?> .butActionRefused, .butActionNewRefused, .btnTitle.refused { - display: none !important; + display: none !important; } <?php } ?> diff --git a/htdocs/theme/eldy/ckeditor/config.js b/htdocs/theme/eldy/ckeditor/config.js index 50bf77c00ff..e041516a292 100644 --- a/htdocs/theme/eldy/ckeditor/config.js +++ b/htdocs/theme/eldy/ckeditor/config.js @@ -11,6 +11,7 @@ CKEDITOR.editorConfig = function( config ) config.enterMode = CKEDITOR.ENTER_BR; //config.forceSimpleAmpersand = true; // When you put a <img src="x?a=a&b=b"> into the textarea, and go into "source", then ckeditor change the & into &amp;. We don't want this. But this option does not fix this. //config.entities = false; // When you put a <img src="x?a=a&b=b"> into the textarea, and go into "source", then ckeditor change the & into &amp;. We don't want this. But this option does not fix this. + //config.entities_greek = false; config.resize_enabled = false; //config.resize_maxHeight = 3000; //config.resize_maxWidth = 3000; diff --git a/htdocs/theme/eldy/doc/doc.css b/htdocs/theme/eldy/doc/doc.css deleted file mode 100644 index a8908185d17..00000000000 --- a/htdocs/theme/eldy/doc/doc.css +++ /dev/null @@ -1,5 +0,0 @@ -/* Simple css for Doc page */ -body.docpage{ - background: #fff; - padding:20px; -} \ No newline at end of file diff --git a/htdocs/theme/eldy/dropdown.inc.php b/htdocs/theme/eldy/dropdown.inc.php index 1140589a2e2..871ee5aa68c 100644 --- a/htdocs/theme/eldy/dropdown.inc.php +++ b/htdocs/theme/eldy/dropdown.inc.php @@ -1,63 +1,65 @@ <?php -if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> +if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* <style type="text/css" > dont remove this line it's an ide hack */ /* * Dropdown of user popup */ button.dropdown-item.global-search-item { - outline: none; + outline: none; } .open>.dropdown-search, .open>.dropdown-bookmark, .open>.dropdown-quickadd, .open>.dropdown-menu, .dropdown dd ul.open { - display: block; + display: block; } .dropdown-search { - border-color: #eee; + border-color: #eee; - position: absolute; - top: 100%; - left: 0; - z-index: 1000; - display: none; - float: left; - min-width: 160px; - margin: 2px 0 0; - font-size: 14px; - text-align: left; - list-style: none; - background-color: #fff; - -webkit-background-clip: padding-box; - background-clip: padding-box; - border: 1px solid #ccc; - border: 1px solid rgba(0,0,0,.15); - border-radius: 4px; - -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); - box-shadow: 0 6px 12px rgba(0,0,0,.175); + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 160px; + margin: 2px 0 0; + font-size: 14px; + text-align: left; + list-style: none; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0,0,0,.15); + border-radius: 4px; + -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); + box-shadow: 0 6px 12px rgba(0,0,0,.175); } .dropdown-bookmark { - border-color: #eee; + border-color: #eee; - position: absolute; - top: 100%; - left: 0; - z-index: 1000; - display: none; - float: left; - min-width: 160px; - margin: 2px 0 0; - font-size: 14px; - text-align: left; - list-style: none; - background-color: #fff; - -webkit-background-clip: padding-box; - background-clip: padding-box; - border: 1px solid #ccc; - border: 1px solid rgba(0,0,0,.15); - border-radius: 4px; - -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); - box-shadow: 0 6px 12px rgba(0,0,0,.175); + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 160px; + margin: 2px 0 0; + font-size: 14px; + text-align: left; + list-style: none; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0,0,0,.15); + border-radius: 4px; + -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); + box-shadow: 0 6px 12px rgba(0,0,0,.175); } .dropdown-quickadd { border-color: #eee; @@ -83,107 +85,107 @@ button.dropdown-item.global-search-item { box-shadow: 0 6px 12px rgba(0,0,0,.175); } .dropdown-menu { - border-color: #eee; + border-color: #eee; - position: absolute; - top: 100%; - left: 0; - z-index: 1000; - display: none; - float: left; - min-width: 160px; - margin: 2px 0 0; - font-size: 14px; - text-align: left; - list-style: none; - background-color: #fff; - -webkit-background-clip: padding-box; - background-clip: padding-box; - border: 1px solid #ccc; - border: 1px solid rgba(0,0,0,.15); - border-radius: 4px; - -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); - box-shadow: 0 6px 12px rgba(0,0,0,.175); + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 160px; + margin: 2px 0 0; + font-size: 14px; + text-align: left; + list-style: none; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0,0,0,.15); + border-radius: 4px; + -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); + box-shadow: 0 6px 12px rgba(0,0,0,.175); } .dropdown-toggle{ - text-decoration: none !important; + text-decoration: none !important; } .dropdown-toggle::after { - /* font part */ - font-family: "Font Awesome 5 Free"; - font-size: 0.7em; - font-weight: 900; - font-style: normal; - font-variant: normal; - text-rendering: auto; - -webkit-font-smoothing: antialiased; - text-align:center; - text-decoration:none; - margin: auto 3px; - display: inline-block; - content: "\f078"; + /* font part */ + font-family: "Font Awesome 5 Free"; + font-size: 0.7em; + font-weight: 900; + font-style: normal; + font-variant: normal; + text-rendering: auto; + -webkit-font-smoothing: antialiased; + text-align:center; + text-decoration:none; + margin: auto 3px; + display: inline-block; + content: "\f078"; - -webkit-transition: -webkit-transform .2s ease-in-out; - -ms-transition: -ms-transform .2s ease-in-out; - transition: transform .2s ease-in-out; + -webkit-transition: -webkit-transform .2s ease-in-out; + -ms-transition: -ms-transform .2s ease-in-out; + transition: transform .2s ease-in-out; } .open>.dropdown-toggle::after { - transform: rotate(180deg); + transform: rotate(180deg); } /* * MENU Dropdown */ .login_block.usedropdown .logout-btn{ - display: none; + display: none; } .tmenu .open.dropdown, .tmenu .open.dropdown { - background: rgba(0, 0, 0, 0.1); + background: rgba(0, 0, 0, 0.1); } .tmenu .dropdown-menu, .login_block .dropdown-menu, .topnav .dropdown-menu { - position: absolute; - right: 2px; - <?php echo $left; ?>: auto; - line-height:1.3em; + position: absolute; + right: 2px; + <?php echo $left; ?>: auto; + line-height:1.3em; } .tmenu .dropdown-menu, .login_block .dropdown-menu .user-body { - border-bottom-right-radius: 4px; - border-bottom-left-radius: 4px; + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; } .user-body { - color: #333; + color: #333; } .side-nav-vert .user-menu .dropdown-menu, .topnav .user-menu .dropdown-menu { - border-top-right-radius: 0; - border-top-left-radius: 0; - padding: 1px 0 0 0; - border-top-width: 0; - width: 300px; + border-top-right-radius: 0; + border-top-left-radius: 0; + padding: 1px 0 0 0; + border-top-width: 0; + width: 300px; } .topnav .user-menu .dropdown-menu { top: 50px; } .side-nav-vert .user-menu .dropdown-menu, .topnav .user-menu .dropdown-menu { - margin-top: 0; - border-top-left-radius: 0; - border-top-right-radius: 0; + margin-top: 0; + border-top-left-radius: 0; + border-top-right-radius: 0; } .side-nav-vert .user-menu .dropdown-menu > .user-header, .topnav .user-menu .dropdown-menu > .user-header { - min-height: 100px; - padding: 10px; - text-align: center; - white-space: normal; + min-height: 100px; + padding: 10px; + text-align: center; + white-space: normal; } #topmenu-global-search-dropdown .dropdown-menu{ - width: 300px; - max-width: 100%; + width: 300px; + max-width: 100%; } div#topmenu-global-search-dropdown, div#topmenu-bookmark-dropdown, div#topmenu-quickadd-dropdown { @@ -192,184 +194,184 @@ div#topmenu-global-search-dropdown, div#topmenu-bookmark-dropdown, div#topmenu-q <?php } ?> } a.top-menu-dropdown-link { - padding: 8px; + padding: 8px; } .dropdown-user-image { - border-radius: 50%; - vertical-align: middle; - z-index: 5; - height: 90px; - width: 90px; - border: 3px solid; - border-color: transparent; - border-color: rgba(255, 255, 255, 0.2); - max-width: 100%; - max-height :100%; + border-radius: 50%; + vertical-align: middle; + z-index: 5; + height: 90px; + width: 90px; + border: 3px solid; + border-color: transparent; + border-color: rgba(255, 255, 255, 0.2); + max-width: 100%; + max-height :100%; } .dropdown-menu > .user-header{ - background: var(--colorbackhmenu1); + background: var(--colorbackhmenu1); } .dropdown-menu .dropdown-header{ - padding: 8px 8px 8px 8px; + padding: 8px 8px 8px 8px; } .dropdown-menu > .user-footer { - border-top: 1px solid #f0f0f0; - background-color: #f9f9f9; - padding: 10px; + border-top: 1px solid #f0f0f0; + background-color: #f9f9f9; + padding: 10px; } .user-footer:after { - clear: both; + clear: both; } .dropdown-menu > .bookmark-footer{ - border-top: 1px solid #f0f0f0; - background-color: #f9f9f9; - padding: 10px; + border-top: 1px solid #f0f0f0; + background-color: #f9f9f9; + padding: 10px; } .dropdown-menu > .user-body, .dropdown-body{ - padding: 15px; - border-bottom: 1px solid #f4f4f4; - border-top: 1px solid #dddddd; - white-space: normal; + padding: 15px; + border-bottom: 1px solid #f4f4f4; + border-top: 1px solid #dddddd; + white-space: normal; } .dropdown-menu > .bookmark-body, .dropdown-body{ - overflow-y: auto; - max-height: 60vh ; /* fallback for browsers without support for calc() */ - max-height: calc(90vh - 110px) ; + overflow-y: auto; + max-height: 60vh ; /* fallback for browsers without support for calc() */ + max-height: calc(90vh - 110px) ; white-space: normal; } #topmenu-bookmark-dropdown .dropdown-menu > .bookmark-body, #topmenu-bookmark-dropdown .dropdown-body{ - max-height: 60vh ; /* fallback for browsers without support for calc() */ - max-height: calc(90vh - 200px) ; + max-height: 60vh ; /* fallback for browsers without support for calc() */ + max-height: calc(90vh - 200px) ; } .dropdown-body::-webkit-scrollbar { - width: 8px; - } + width: 8px; + } .dropdown-body::-webkit-scrollbar-thumb { - -webkit-border-radius: 0; - border-radius: 0; - /* background: rgb(<?php echo $colorbackhmenu1 ?>); */ - background: #aaa; + -webkit-border-radius: 0; + border-radius: 0; + /* background: rgb(<?php echo $colorbackhmenu1 ?>); */ + background: #aaa; } .dropdown-body::-webkit-scrollbar-track { - -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); - -webkit-border-radius: 0; - border-radius: 0; + -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); + -webkit-border-radius: 0; + border-radius: 0; } #topmenu-login-dropdown, #topmenu-bookmark-dropdown, #topmenu-global-search-dropdown { - padding: 0 5px 0 5px; + padding: 0 5px 0 5px; } #topmenu-login-dropdown a:hover{ - text-decoration: none; + text-decoration: none; } #topmenuloginmoreinfo-btn{ - display: block; - text-aling: right; - color:#666; - cursor: pointer; + display: block; + text-aling: right; + color:#666; + cursor: pointer; } #topmenuloginmoreinfo{ - display: none; - clear: both; - font-size: 0.95em; + display: none; + clear: both; + font-size: 0.95em; } .button-top-menu-dropdown { - display: inline-block; - padding: 6px 12px; - margin-bottom: 0; - font-size: 14px; - font-weight: 400; - line-height: 1.42857143; - text-align: center; - white-space: nowrap; - vertical-align: middle; - -ms-touch-action: manipulation; - touch-action: manipulation; - cursor: pointer; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; - background-image: none; - border: 1px solid transparent; - border-radius: 4px; + display: inline-block; + padding: 6px 12px; + margin-bottom: 0; + font-size: 14px; + font-weight: 400; + line-height: 1.42857143; + text-align: center; + white-space: nowrap; + vertical-align: middle; + -ms-touch-action: manipulation; + touch-action: manipulation; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + background-image: none; + border: 1px solid transparent; + border-radius: 4px; } .user-footer .button-top-menu-dropdown { - color: #666666; - border-radius: 0; - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; - border-width: 1px; - background-color: #f4f4f4; - border-color: #ddd; + color: #666666; + border-radius: 0; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + border-width: 1px; + background-color: #f4f4f4; + border-color: #ddd; } .dropdown-menu a.top-menu-dropdown-link { - color: rgb(<?php print $colortextlink; ?>) !important; - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; - display: block; - margin: 5px 0px; + color: rgb(<?php print $colortextlink; ?>) !important; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + display: block; + margin: 5px 0px; } .dropdown-item { - display: block !important; - box-sizing: border-box; - width: 100%; - padding: .3em 1.5em .4em 1em; - clear: both; - font-weight: 400; - color: #212529 !important; - text-align: inherit; - background-color: transparent; - border: 0; + display: block !important; + box-sizing: border-box; + width: 100%; + padding: .3em 1.5em .4em 1em; + clear: both; + font-weight: 400; + color: #212529 !important; + text-align: inherit; + background-color: transparent; + border: 0; - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; } .dropdown-item::before { - /* font part */ - font-family: "Font Awesome 5 Free"; - font-weight: 900; - font-style: normal; - font-variant: normal; - text-rendering: auto; - -webkit-font-smoothing: antialiased; - text-align:center; - text-decoration:none; - margin-right: 5px; - display: inline-block; - content: "\f0da"; - /* color: rgba(0,0,0,0.3); */ + /* font part */ + font-family: "Font Awesome 5 Free"; + font-weight: 900; + font-style: normal; + font-variant: normal; + text-rendering: auto; + -webkit-font-smoothing: antialiased; + text-align:center; + text-decoration:none; + margin-right: 5px; + display: inline-block; + content: "\f0da"; + /* color: rgba(0,0,0,0.3); */ } .dropdown-item.bookmark-item-external::before { content: "\f35d"; } .dropdown-item.active, .dropdown-item:hover, .dropdown-item:focus { - color: #<?php echo $colortextbackhmenu; ?> !important; - text-decoration: none; - background: rgb(<?php echo $colorbackhmenu1 ?>); + color: #<?php echo $colortextbackhmenu; ?> !important; + text-decoration: none; + background: rgb(<?php echo $colorbackhmenu1 ?>); } /* @@ -377,34 +379,34 @@ a.top-menu-dropdown-link { */ .dropdown-search-input { - width: 100%; - padding: 10px 35px 10px 20px; + width: 100%; + padding: 10px 35px 10px 20px; - background-color: transparent; - /*font-size: 14px; - line-height: 16px;*/ - box-sizing: border-box; + background-color: transparent; + /*font-size: 14px; + line-height: 16px;*/ + box-sizing: border-box; - color: #575756; - background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'/%3E%3Cpath d='M0 0h24v24H0z' fill='none'/%3E%3C/svg%3E"); - background-repeat: no-repeat; - background-size: 16px 16px; - background-position: 95% center; - border-radius: 10px; - border: 1px solid #c4c4c2 !important; - transition: all 250ms ease-in-out; - backface-visibility: hidden; - transform-style: preserve-3d; + color: #575756; + background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'/%3E%3Cpath d='M0 0h24v24H0z' fill='none'/%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-size: 16px 16px; + background-position: 95% center; + border-radius: 10px; + border: 1px solid #c4c4c2 !important; + transition: all 250ms ease-in-out; + backface-visibility: hidden; + transform-style: preserve-3d; } .dropdown-search-input::placeholder { - color: color(#575756 a(0.8)); - letter-spacing: 1.5px; + color: color(#575756 a(0.8)); + letter-spacing: 1.5px; } .hidden-search-result{ - display: none !important; + display: none !important; } /* @@ -468,11 +470,11 @@ div.quickaddblock:focus { @media only screen and (max-width: 767px) { .dropdown-search-input { - width: 100%; + width: 100%; } .tmenu .dropdown-menu, .login_block .dropdown-menu, .topnav .dropdown-menu { - margin-left: 5px; - right: 0; - } + margin-left: 5px; + right: 0; + } } diff --git a/htdocs/theme/eldy/global.inc.php b/htdocs/theme/eldy/global.inc.php index d39e7a3e1b5..9a9b4e7ed6c 100644 --- a/htdocs/theme/eldy/global.inc.php +++ b/htdocs/theme/eldy/global.inc.php @@ -1,4 +1,6 @@ -<?php if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> +<?php if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* <style type="text/css" > */ /* ============================================================================== */ @@ -101,12 +103,12 @@ body { font-size: <?php print is_numeric($fontsize) ? $fontsize.'px' : $fontsize; ?>; line-height: 1.4; font-family: <?php print $fontlist ?>; - margin-top: 0; - margin-bottom: 0; - margin-right: 0; - margin-left: 0; - font-weight: 400; - <?php print 'direction: '.$langs->trans("DIRECTION").";\n"; ?> + margin-top: 0; + margin-bottom: 0; + margin-right: 0; + margin-left: 0; + font-weight: 400; + <?php print 'direction: '.$langs->trans("DIRECTION").";\n"; ?> } /* Style used to protect html content in output to avoid attack by replacing full page with js content */ @@ -138,10 +140,10 @@ select.vmenusearchselectcombo { } table.liste th.wrapcolumntitle.liste_titre:not(.maxwidthsearch), table.liste td.wrapcolumntitle.liste_titre:not(.maxwidthsearch) { - overflow: hidden; - white-space: nowrap; - max-width: 100px; - text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; + max-width: 100px; + text-overflow: ellipsis; } .liste_titre input[name=month_date_when], .liste_titre input[name=monthvalid], .liste_titre input[name=search_ordermonth], .liste_titre input[name=search_deliverymonth], .liste_titre input[name=search_smonth], .liste_titre input[name=search_month], .liste_titre input[name=search_emonth], .liste_titre input[name=smonth], .liste_titre input[name=month], .liste_titre select[name=month], @@ -164,20 +166,20 @@ input[type=submit], input[type=submit]:hover { margin-left: 5px; } input[type=checkbox], input[type=radio] { - margin: 0 3px 0 3px; + margin: 0 3px 0 3px; } input, input.flat, form.flat select, select, select.flat, .dataTables_length label select { border: none; } input, input.flat, textarea, textarea.flat, form.flat select, select, select.flat, .dataTables_length label select { - font-family: <?php print $fontlist ?>; - outline: none; - margin: 0px 0px 0px 0px; - border<?php echo empty($conf->global->THEME_SHOW_BORDER_ON_INPUT) ? '-bottom' : ''; ?>: solid 1px var(--inputbordercolor); + font-family: <?php print $fontlist ?>; + outline: none; + margin: 0px 0px 0px 0px; + border<?php echo empty($conf->global->THEME_SHOW_BORDER_ON_INPUT) ? '-bottom' : ''; ?>: solid 1px var(--inputbordercolor); } input { - line-height: 1.3em; + line-height: 1.3em; padding: 4px; padding-left: 5px; } @@ -199,11 +201,11 @@ input, select { background: var(--butactionbg); color: #FFF !important; border-radius: 3px; - border-collapse: collapse; - border: none; + border-collapse: collapse; + border: none; } #mainbody span.websitetools input.button:not(.buttongen):not(.bordertransp) { - color: #000 !important; + color: #000 !important; } #mainbody input.buttongen, #mainbody button.buttongen { padding: 3px 4px; @@ -214,11 +216,11 @@ input.button:focus { } input.button.massactionconfirmed { - margin: 4px; + margin: 4px; } input:invalid, select:invalid { - border-color: #ea1212; + border-color: #ea1212; } /* Focus definitions must be after standard definition */ @@ -233,7 +235,7 @@ textarea.cke_source:focus box-shadow: none; } div#cke_dp_desc { - margin-top: 5px; + margin-top: 5px; } textarea { border-radius: 0; @@ -279,7 +281,7 @@ input.buttonpayment, button.buttonpayment, div.buttonpayment { max-width: 350px; } div.buttonpayment input:focus { - color: #008; + color: #008; } .buttonpaymentsmall { font-size: 0.65em; @@ -287,12 +289,12 @@ div.buttonpayment input:focus { padding-right: 5px; } div.buttonpayment input { - background-color: unset; - color: #fff; - border-bottom: unset; - font-weight: bold; - text-transform: uppercase; - cursor: pointer; + background-color: unset; + color: #fff; + border-bottom: unset; + font-weight: bold; + text-transform: uppercase; + cursor: pointer; } input.buttonpaymentcb { background-image: url(<?php echo dol_buildpath($path.'/theme/common/credit_card.png', 1) ?>); @@ -329,17 +331,17 @@ input.buttonpaymentstripe { a.butStatus { padding-left: 5px; padding-right: 5px; - background-color: transparent; - color: var(--colortext) !important; - border: 2px solid var( --butactionbg); - margin: 0 0.45em !important; + background-color: transparent; + color: var(--colortext) !important; + border: 2px solid var( --butactionbg); + margin: 0 0.45em !important; } /* Used by timesheets */ span.timesheetalreadyrecorded input { - border: none; - border-bottom: solid 1px rgba(0,0,0,0.4); - margin-right: 1px !important; + border: none; + border-bottom: solid 1px rgba(0,0,0,0.4); + margin-right: 1px !important; } td.onholidaymorning, td.onholidayafternoon { background-color: #fdf6f2; @@ -363,15 +365,15 @@ td.rightborder { } td.actionbuttons a { - padding-left: 6px; + padding-left: 6px; } select.flat, form.flat select, .pageplusone { font-weight: normal; font-size: unset; } input.pageplusone { - padding-bottom: 4px; - padding-top: 4px; + padding-bottom: 4px; + padding-top: 4px; } .saturatemedium { @@ -391,7 +393,7 @@ input.pageplusone { opacity: 0.6; } .opacityhigh { - opacity: 0.2; + opacity: 0.24; } .opacitytransp { opacity: 0; @@ -400,17 +402,17 @@ input.pageplusone { color: #fff; } .colorgrey { - color: #888 !important; + color: #888 !important; } .colorblack { color: #000; } .vmirror { - transform: scale(1, -1); + transform: scale(1, -1); } .hmirror { - transform: scale(-1, 1); + transform: scale(-1, 1); } select:invalid { @@ -437,7 +439,7 @@ input[type=file ] { border-left: none; border-right: none; <?php } ?> - border<?php echo empty($conf->global->THEME_SHOW_BORDER_ON_INPUT) ? '-bottom' : ''; ?>: solid 1px var(--inputbordercolor); + border<?php echo empty($conf->global->THEME_SHOW_BORDER_ON_INPUT) ? '-bottom' : ''; ?>: solid 1px var(--inputbordercolor); } input[type=checkbox] { background-color: transparent; border: none; box-shadow: none; } input[type=radio] { background-color: transparent; border: none; box-shadow: none; } @@ -462,11 +464,12 @@ input#onlinepaymenturl, input#directdownloadlink { .formconsumeproduce { background: #f3f3f3; - padding: 20px 0px 0px 0px; + padding: 20px 0px 0px 0px; + border-radius: 8px; } div#moretabsList, div#moretabsListaction { - z-index: 5; + z-index: 5; } hr { border: 0; border-top: 1px solid #ccc; } @@ -500,6 +503,12 @@ hr { border: 0; border-top: 1px solid #ccc; } text-transform: uppercase; color: #444; } +.valuefield .button, .valuefieldcreate .button, .refidno .button { + margin-top: 0 !important; + margin-bottom: 0 !important; + font-size: 0.85em !important; + padding: 5px !important; +} .button:focus, .buttonDelete:focus { -webkit-box-shadow: 0px 0px 5px 1px rgba(0, 0, 60, 0.2), 0px 0px 0px rgba(60,60,60,0.1); box-shadow: 0px 0px 5px 1px rgba(0, 0, 60, 0.2), 0px 0px 0px rgba(60,60,60,0.1); @@ -511,38 +520,38 @@ hr { border: 0; border-top: 1px solid #ccc; } } .button:disabled, .buttonDelete:disabled, .button.disabled { opacity: 0.4; - box-shadow: none; - -webkit-box-shadow: none; - cursor: auto; + box-shadow: none; + -webkit-box-shadow: none; + cursor: auto; } .buttonRefused { pointer-events: none; - cursor: default; + cursor: default; opacity: 0.4; - box-shadow: none; - -webkit-box-shadow: none; + box-shadow: none; + -webkit-box-shadow: none; } .button_search, .button_removefilter { - border: unset; - background-color: unset; + border: unset; + background-color: unset; } .button_search:hover, .button_removefilter:hover { - cursor: pointer; + cursor: pointer; } form { - padding:0px; - margin:0px; + padding:0px; + margin:0px; } form#addproduct { - padding-top: 10px; + padding-top: 10px; } div.float, span.floatleft { - float:<?php print $left; ?>; + float:<?php print $left; ?>; } div.floatright { - float:<?php print $right; ?>; + float:<?php print $right; ?>; } .block { @@ -553,14 +562,14 @@ div.floatright display:inline-block; } .largenumber { - font-size: 1.4em; + font-size: 1.4em; } button[name='button_search_x'] span.fa.fa-search { - font-size: 1.3em; + font-size: 1.3em; } button[name='button_removefilter_x'] span.fa.fa-remove { - opacity: 0.5; - font-size: 1.3em; + opacity: 0.5; + font-size: 1.3em; } button:focus { outline: none; @@ -568,8 +577,8 @@ button:focus { th .button { - -webkit-box-shadow: none !important; - box-shadow: none !important; + -webkit-box-shadow: none !important; + box-shadow: none !important; -webkit-border-radius:0px !important; border-radius:0px !important; } @@ -608,27 +617,27 @@ textarea.centpercent { width: 96%; } .small, small { - font-size: 85%; + font-size: 85%; } .h1 .small, .h1 small, .h2 .small, .h2 small, .h3 .small, .h3 small, h1 .small, h1 small, h2 .small, h2 small, h3 .small, h3 small { - font-size: 65%; + font-size: 65%; } .h1 .small, .h1 small, .h2 .small, .h2 small, .h3 .small, .h3 small, .h4 .small, .h4 small, .h5 .small, .h5 small, .h6 .small, .h6 small, h1 .small, h1 small, h2 .small, h2 small, h3 .small, h3 small, h4 .small, h4 small, h5 .small, h5 small, h6 .small, h6 small { - font-weight: 400; - line-height: 1; - color: #777; + font-weight: 400; + line-height: 1; + color: #777; } .flip { - transform: scaleX(-1); + transform: scaleX(-1) translate(2px, 0); } .center { - text-align: center; - margin: 0px auto; + text-align: center; + margin: 0px auto; } .alignstart { - text-align: start; + text-align: start; } .left { text-align: <?php print $left; ?>; @@ -640,10 +649,10 @@ textarea.centpercent { text-align: justify; } .pull-left { - float: left!important; + float: left!important; } .pull-right { - float: right!important; + float: right!important; } .nowrap { white-space: <?php print ($dol_optimize_smallscreen ? 'normal' : 'nowrap'); ?>; @@ -679,7 +688,7 @@ textarea.centpercent { text-transform: uppercase; } .nounderline { - text-decoration: none; + text-decoration: none; } .nopadding { padding: 0; @@ -733,48 +742,54 @@ textarea.centpercent { cursor: not-allowed; } .backgroundblank { - background-color: #fff; + background-color: #fff; } .nobackground, .nobackground tr { background: unset !important; } .checkboxattachfilelabel { - font-size: 0.85em; - opacity: 0.7; + font-size: 0.85em; + opacity: 0.7; } .borderimp { border: 1px solid #888 !important; } .text-warning{ - color : <?php print $textWarning; ?> + color : <?php print $textWarning; ?> } .longmessagecut { - max-height: 250px; - max-width: 100%; - overflow-y: auto; + max-height: 250px; + max-width: 100%; + overflow-y: auto; +} + +i.fa-mars::before, i.fa-venus::before, i.fa-genderless::before { + color: #888 !important; + opacity: 0.4; + padding-<?php echo $left; ?>: 3px; } body[class*="colorblind-"] .text-warning{ - color : <?php print $colorblind_deuteranopes_textWarning; ?> + color : <?php print $colorblind_deuteranopes_textWarning; ?> } .text-success{ - color : <?php print $textSuccess; ?> + color : <?php print $textSuccess; ?> } body[class*="colorblind-"] .text-success{ - color : <?php print $colorblind_deuteranopes_textSuccess; ?> + color : <?php print $colorblind_deuteranopes_textSuccess; ?> } .text-danger{ - color : <?php print $textDanger; ?> + color : <?php print $textDanger; ?> } .editfielda span.fa-pencil-alt, .editfielda span.fa-pencil-ruler, .editfielda span.fa-trash, .editfielda span.fa-crop, .editfieldlang { - color: #ccc !important; + color: #ccc !important; } .editfielda span.fa-pencil-alt:hover, .editfielda span.fa-pencil-ruler:hover, .editfielda span.fa-trash:hover, .editfielda span.fa-crop:hover, .editfieldlang:hover { - color: var(--colortexttitle) !important; + color: var(--colortexttitle) !important; } .fawidth30 { width: 20px; @@ -784,9 +799,9 @@ body[class*="colorblind-"] .text-success{ } span.fa.fa-plus-circle.paddingleft { - padding-right: 4px; - padding-top: 3px; - padding-bottom: 2px; + padding-right: 4px; + padding-top: 3px; + padding-bottom: 2px; } .size15x { font-size: 1.5em !important; } @@ -801,7 +816,7 @@ span.fa.fa-plus-circle.paddingleft { /* Themes for badges */ - <?php include dol_buildpath($path.'/theme/'.$theme.'/badges.inc.php', 0); ?> + <?php include dol_buildpath($path.'/theme/'.$theme.'/badges.inc.php', 0); ?> .borderrightlight { @@ -815,8 +830,8 @@ span.fa.fa-plus-circle.paddingleft { margin-top: 4px; } #formuserfile input[type='file'] { - font-size: 1em; - /* opacity: 0.5em; */ + font-size: 1em; + /* opacity: 0.5em; */ } /*#formuserfile input[type='file']:valid { color: #a00; @@ -829,56 +844,56 @@ span.fa.fa-plus-circle.paddingleft { margin-left: 1px; } #formuserfile_link input[type='text'] { - font-size: 1em; + font-size: 1em; } .listofinvoicetype { height: 28px; vertical-align: middle; } .divsocialnetwork:not(:first-child) { - padding-left: 20px; + padding-left: 20px; } div.divsearchfield { float: <?php print $left; ?>; margin-<?php print $right; ?>: 12px; - margin-<?php print $left; ?>: 2px; + margin-<?php print $left; ?>: 2px; margin-top: 4px; - margin-bottom: 4px; - padding-left: 2px; + margin-bottom: 4px; + padding-left: 2px; } .divsearchfieldfilter { - text-overflow: clip; - overflow: auto; - padding-bottom: 5px; - opacity: 0.6; + text-overflow: clip; + overflow: auto; + padding-bottom: 5px; + opacity: 0.6; } .divadvancedsearchfield:first-child { - margin-top: 3px; + margin-top: 3px; } .divadvancedsearchfield { - float: left; - padding-left: 15px; - padding-right: 15px; - padding-bottom: 2px; - padding-top: 2px; + float: left; + padding-left: 15px; + padding-right: 15px; + padding-bottom: 2px; + padding-top: 2px; } .divadvancedsearchfield span.select2.select2-container.select2-container--default { padding-bottom: 4px; } .search_component_params { /*display: flex; */ - -webkit-flex-flow: row wrap; - flex-flow: row wrap; - background: #fff; - padding-top: 3px; - padding-bottom: 3px; - padding-left: 10px; - padding-right: 10px; - border-bottom: solid 1px rgba(0,0,0,.2); - height: 24px; + -webkit-flex-flow: row wrap; + flex-flow: row wrap; + background: #fff; + padding-top: 3px; + padding-bottom: 3px; + padding-left: 10px; + padding-right: 10px; + border-bottom: solid 1px rgba(0,0,0,.2); + height: 24px; } .search_component_searchtext { - padding-top: 2px; + padding-top: 2px; } .search_component_params_text, .search_component_params_text:focus { border-bottom: none; @@ -888,16 +903,16 @@ div.divsearchfield { } .a-filter, .a-mesure { - border-radius: 50px; - background: var(--colortexttitlenotab); - color: #fff; - padding: 8px 10px 8px 6px; + border-radius: 50px; + background: var(--colortexttitlenotab); + color: #fff; + padding: 8px 10px 8px 6px; } .a-filter:before { - content: "\f0b0"; + content: "\f0b0"; } .a-mesure:before { - content: "\f080"; + content: "\f080"; } .a-filter:before, .a-mesure:before { font-family: "Font Awesome 5 Free"; @@ -906,10 +921,10 @@ div.divsearchfield { padding-left: 5px; } .a-filter-disabled, .a-mesure-disabled { - border-radius: 50px; - background: var(--colorbacktitle1); - padding: 8px; - opacity: 0.6; + border-radius: 50px; + background: var(--colorbacktitle1); + padding: 8px; + opacity: 0.6; } div.div-for-modal { @@ -920,9 +935,9 @@ div.div-for-modal { width:500px; /* adjust as per your needs */ height:400px; /* adjust as per your needs */ background: #fff; - border: 1px solid #bbb; - box-shadow: 2px 2px 20px #ddd; - z-index: 100; + border: 1px solid #bbb; + box-shadow: 2px 2px 20px #ddd; + z-index: 100; } <?php @@ -930,7 +945,7 @@ div.div-for-modal { if ($conf->browser->layout == 'phone') { ?> .divsearchfieldfilter { - white-space: nowrap; + white-space: nowrap; } <?php } ?> div.confirmmessage { @@ -957,12 +972,12 @@ ul.attendees li { padding-bottom: 10px; } .checkallactions { - margin-left: 2px; /* left must be same than right to keep checkbox centered */ - margin-right: 2px; /* left must be same than right to keep checkbox centered */ - vertical-align: middle; + margin-left: 2px; /* left must be same than right to keep checkbox centered */ + margin-right: 2px; /* left must be same than right to keep checkbox centered */ + vertical-align: middle; } select.flat.selectlimit { - max-width: 62px; + max-width: 62px; } .selectlimit, .marginrightonly { margin-right: 10px !important; @@ -989,16 +1004,16 @@ select.flat.selectlimit { margin-bottom: 3px !important; } .nomargintop { - margin-top: 0 !important; + margin-top: 0 !important; } .nomarginbottom { - margin-bottom: 0 !important; + margin-bottom: 0 !important; } .selectlimit, .selectlimit:focus { - border-left: none !important; - border-top: none !important; - border-right: none !important; - outline: none; + border-left: none !important; + border-top: none !important; + border-right: none !important; + outline: none; } .strikefordisabled { text-decoration: line-through; @@ -1011,69 +1026,69 @@ select.flat.selectlimit { text-overflow: none; } .tdoverflow { - max-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax50 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 50px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 50px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax100 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 100px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 100px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax100imp { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 100px !important; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 100px !important; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax125 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 125px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 125px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax150 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 150px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 150px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax200 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 200px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 200px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax300 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 300px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 300px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowauto { - max-width: 0; - overflow: auto; + max-width: 0; + overflow: auto; } .divintowithtwolinesmax { - width: 75px; - display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: 2; - overflow: hidden; + width: 75px; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow: hidden; } .twolinesmax { - display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: 2; - overflow: hidden; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow: hidden; } .tablelistofcalendars { @@ -1082,8 +1097,8 @@ select.flat.selectlimit { /* Styles for amount on card */ table.paymenttable td.amountpaymentcomplete, table.paymenttable td.amountremaintopay { - padding-top: 0px; - padding-bottom: 0px; + padding-top: 0px; + padding-bottom: 0px; } .amountalreadypaid { } @@ -1108,10 +1123,10 @@ table.paymenttable td.amountpaymentcomplete, table.paymenttable td.amountremaint } .onlinepaymentbody .amountpaymentcomplete { - background-color: var(--amountpaymentcomplete); - color: #fff; - padding: 5px; - border-radius: 5px; + background-color: var(--amountpaymentcomplete); + color: #fff; + padding: 5px; + border-radius: 5px; } .savingdocmask { @@ -1119,19 +1134,19 @@ table.paymenttable td.amountpaymentcomplete, table.paymenttable td.amountremaint margin-bottom: 12px; } #builddoc_form ~ .showlinkedobjectblock { - margin-top: 20px; + margin-top: 20px; } /* For the long description of module */ .moduledesclong p img, .moduledesclong p a img { - max-width: 90% !important; - height: auto !important; + max-width: 90% !important; + height: auto !important; } .imgdoc { - margin: 18px; - border: 1px solid #ccc; - box-shadow: 1px 1px 25px #aaa; - max-width: calc(100% - 56px); + margin: 18px; + border: 1px solid #ccc; + box-shadow: 1px 1px 25px #aaa; + max-width: calc(100% - 56px); } .fa-file-text-o, .fa-file-code-o, .fa-file-powerpoint-o, .fa-file-excel-o, .fa-file-word-o, .fa-file-o, .fa-file-image-o, .fa-file-video-o, .fa-file-audio-o, .fa-file-archive-o, .fa-file-pdf-o { color: #055; @@ -1143,51 +1158,53 @@ table.paymenttable td.amountpaymentcomplete, table.paymenttable td.amountremaint /* DOL_XXX for future usage (when left menu has been removed). If we do not use datatable */ /*.table-responsive { - width: calc(100% - 330px); - margin-bottom: 15px; - overflow-y: hidden; - -ms-overflow-style: -ms-autohiding-scrollbar; + width: calc(100% - 330px); + margin-bottom: 15px; + overflow-y: hidden; + -ms-overflow-style: -ms-autohiding-scrollbar; }*/ /* Style used for most tables */ .div-table-responsive, .div-table-responsive-no-min { - overflow-x: auto; - min-height: 0.01%; + overflow-x: auto; + min-height: 0.01%; } .div-table-responsive { - line-height: 120%; + line-height: 120%; } /* Style used for full page tables with field selector and no content after table (priority before previous for such tables) */ div.fiche>form>div.div-table-responsive, div.fiche>form>div.div-table-responsive-no-min { - overflow-x: auto; + overflow-x: auto; } div.fiche>form>div.div-table-responsive { - min-height: 392px; + min-height: 392px; } div.fiche>div.tabBar>form>div.div-table-responsive { - min-height: 392px; + min-height: 392px; } div.fiche { /* text-align: justify; */ } .flexcontainer { - <?php if (in_array($conf->browser->name, array('chrome', 'firefox'))) echo 'display: inline-flex;'."\n"; ?> - flex-flow: row wrap; - justify-content: flex-start; + <?php if (in_array($conf->browser->name, array('chrome', 'firefox'))) { + echo 'display: inline-flex;'."\n"; + } ?> + flex-flow: row wrap; + justify-content: flex-start; } .thumbstat { - min-width: 148px; + min-width: 148px; } .thumbstat150 { - min-width: 168px; - max-width: 169px; - /* width: 168px; If I use with, there is trouble on size of flex boxes solved with min+max that is a little bit higer than min */ + min-width: 168px; + max-width: 169px; + /* width: 168px; If I use with, there is trouble on size of flex boxes solved with min+max that is a little bit higer than min */ } .thumbstat, .thumbstat150 { <?php if ($conf->browser->name == 'ie') { ?> - min-width: 150px; - width: 100%; - display: inline; + min-width: 150px; + width: 100%; + display: inline; <?php } else { ?> flex-grow: 1; flex-shrink: 0; @@ -1202,7 +1219,7 @@ select.selectarrowonleft option { } table[summary="list_of_modules"] .fa-cog { - font-size: 1.5em; + font-size: 1.5em; } .linkedcol-element { @@ -1238,24 +1255,24 @@ table[summary="list_of_modules"] .fa-cog { { .width20 { width: 20px; } .width25 { width: 25px; } - .width50 { width: 50px; } - .width75 { width: 75px; } - .width100 { width: 100px; } - .width200 { width: 200px; } - .minwidth100 { min-width: 100px; } - .minwidth150 { min-width: 150px; } - .minwidth200 { min-width: 200px; } - .minwidth300 { min-width: 300px; } - .minwidth400 { min-width: 400px; } - .minwidth500 { min-width: 500px; } - .minwidth50imp { min-width: 50px !important; } - .minwidth75imp { min-width: 75px !important; } - .minwidth100imp { min-width: 100px !important; } - .minwidth200imp { min-width: 200px !important; } - .minwidth250imp { min-width: 250px !important; } - .minwidth300imp { min-width: 300px !important; } - .minwidth400imp { min-width: 400px !important; } - .minwidth500imp { min-width: 500px !important; } + .width50 { width: 50px; } + .width75 { width: 75px; } + .width100 { width: 100px; } + .width200 { width: 200px; } + .minwidth100 { min-width: 100px; } + .minwidth150 { min-width: 150px; } + .minwidth200 { min-width: 200px; } + .minwidth300 { min-width: 300px; } + .minwidth400 { min-width: 400px; } + .minwidth500 { min-width: 500px; } + .minwidth50imp { min-width: 50px !important; } + .minwidth75imp { min-width: 75px !important; } + .minwidth100imp { min-width: 100px !important; } + .minwidth200imp { min-width: 200px !important; } + .minwidth250imp { min-width: 250px !important; } + .minwidth300imp { min-width: 300px !important; } + .minwidth400imp { min-width: 400px !important; } + .minwidth500imp { min-width: 500px !important; } } .widthauto { width: auto; } .width20 { width: 20px; } @@ -1307,16 +1324,16 @@ table[summary="list_of_modules"] .fa-cog { .titlefield { /* width: 30% !important; */ } .titlefieldcreate { width: 30% !important; } .minwidth50imp { min-width: 50px !important; } - .minwidth75imp { min-width: 75px !important; } - .minwidth100imp { min-width: 100px !important; } - .minwidth150imp { min-width: 150px !important; } - .minwidth200imp { min-width: 200px !important; } - .minwidth250imp { min-width: 250px !important; } - .minwidth300imp { min-width: 300px !important; } - .minwidth400imp { min-width: 300px !important; } - .minwidth500imp { min-width: 300px !important; } + .minwidth75imp { min-width: 75px !important; } + .minwidth100imp { min-width: 100px !important; } + .minwidth150imp { min-width: 150px !important; } + .minwidth200imp { min-width: 200px !important; } + .minwidth250imp { min-width: 250px !important; } + .minwidth300imp { min-width: 300px !important; } + .minwidth400imp { min-width: 300px !important; } + .minwidth500imp { min-width: 300px !important; } - .linkedcol-element { + .linkedcol-element { min-width: unset; } } @@ -1324,16 +1341,16 @@ table[summary="list_of_modules"] .fa-cog { /* Force values for small screen 1000 */ @media only screen and (max-width: 1000px) { - .maxwidthonsmartphone { max-width: 100px; } + .maxwidthonsmartphone { max-width: 100px; } .minwidth50imp { min-width: 50px !important; } - .minwidth75imp { min-width: 75px !important; } - .minwidth100imp { min-width: 100px !important; } - .minwidth150imp { min-width: 110px !important; } - .minwidth200imp { min-width: 110px !important; } - .minwidth250imp { min-width: 115px !important; } - .minwidth300imp { min-width: 120px !important; } - .minwidth400imp { min-width: 150px !important; } - .minwidth500imp { min-width: 250px !important; } + .minwidth75imp { min-width: 75px !important; } + .minwidth100imp { min-width: 100px !important; } + .minwidth150imp { min-width: 110px !important; } + .minwidth200imp { min-width: 110px !important; } + .minwidth250imp { min-width: 115px !important; } + .minwidth300imp { min-width: 120px !important; } + .minwidth400imp { min-width: 150px !important; } + .minwidth500imp { min-width: 250px !important; } } select.widthcentpercentminusx, span.widthcentpercentminusx:not(.select2-selection), input.widthcentpercentminusx { @@ -1352,16 +1369,16 @@ select.widthcentpercentminusxx, span.widthcentpercentminusxx:not(.select2-select font-size: <?php print is_numeric($fontsize) ? ($fontsize + 3).'px' : $fontsize; ?> !important; } .divadvancedsearchfield { - padding-left: 5px; - padding-right: 5px; - } - - div.divphotoref { - padding-right: 10px !important; + padding-left: 5px; + padding-right: 5px; } - .hideonsmartphone { display: none; } - .hideonsmartphoneimp { display: none !important; } + div.divphotoref { + padding-right: 10px !important; + } + + .hideonsmartphone { display: none; } + .hideonsmartphoneimp { display: none !important; } span.pictotitle { margin-<?php echo $left; ?>: 0 !important; @@ -1383,17 +1400,17 @@ select.widthcentpercentminusxx, span.widthcentpercentminusxx:not(.select2-select width: auto !important; } .poweredbypublicpayment { - float: unset !important; + float: unset !important; top: unset !important; - bottom: 8px; - position: relative !important; - } - .poweredbyimg { - width: 48px; - } - input.buttonpayment, button.buttonpayment, div.buttonpayment { - min-width: 270px; - } + bottom: 8px; + position: relative !important; + } + .poweredbyimg { + width: 48px; + } + input.buttonpayment, button.buttonpayment, div.buttonpayment { + min-width: 270px; + } } /* Force values for small screen 570 */ @@ -1419,31 +1436,31 @@ select.widthcentpercentminusxx, span.widthcentpercentminusxx:not(.select2-select .divmainbodylarge { margin-left: 20px !important; margin-right: 20px !important; } - .tdoverflowonsmartphone { - max-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - .tdoverflowmax100onsmartphone { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 100px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + .tdoverflowonsmartphone { + max-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } - .tdoverflowmax150onsmartphone { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 100px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + .tdoverflowmax100onsmartphone { /* For tdoverflow, the max-midth become a minimum ! */ + max-width: 100px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .tdoverflowmax150onsmartphone { /* For tdoverflow, the max-midth become a minimum ! */ + max-width: 100px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .border tbody tr, .border tbody tr td, div.tabBar table.border tr, div.tabBar table.border tr td, div.tabBar div.border .table-border-row, div.tabBar div.border .table-key-border-col, div.tabBar div.border .table-val-border-col { + height: 40px !important; } - .border tbody tr, .border tbody tr td, div.tabBar table.border tr, div.tabBar table.border tr td, div.tabBar div.border .table-border-row, div.tabBar div.border .table-key-border-col, div.tabBar div.border .table-val-border-col { - height: 40px !important; - } - .quatrevingtpercent, .inputsearch { - width: 95%; - } + .quatrevingtpercent, .inputsearch { + width: 95%; + } select { padding-top: 4px; @@ -1455,36 +1472,36 @@ select.widthcentpercentminusxx, span.widthcentpercentminusxx:not(.select2-select } input, input[type=text], input[type=password], select, textarea { min-width: 20px; - } - .trinputlogin input[type=text], input[type=password] { + } + .trinputlogin input[type=text], input[type=password] { max-width: 140px; } - .vmenu .searchform input { + .vmenu .searchform input { max-width: 138px; /* length of input text in the quick search box when using a smartphone and without dolidroid */ } - .noenlargeonsmartphone { width : 50px !important; display: inline !important; } - .maxwidthonsmartphone, #search_newcompany.ui-autocomplete-input { max-width: 100px; } - .maxwidth50onsmartphone { max-width: 40px; } - .maxwidth75onsmartphone { max-width: 50px; } - .maxwidth100onsmartphone { max-width: 70px; } - .maxwidth150onsmartphone { max-width: 120px; } - .maxwidth150onsmartphoneimp { max-width: 120px !important; } - .maxwidth200onsmartphone { max-width: 200px; } - .maxwidth250onsmartphone { max-width: 250px; } - .maxwidth300onsmartphone { max-width: 300px; } - .maxwidth400onsmartphone { max-width: 400px; } + .noenlargeonsmartphone { width : 50px !important; display: inline !important; } + .maxwidthonsmartphone, #search_newcompany.ui-autocomplete-input { max-width: 100px; } + .maxwidth50onsmartphone { max-width: 40px; } + .maxwidth75onsmartphone { max-width: 50px; } + .maxwidth100onsmartphone { max-width: 70px; } + .maxwidth150onsmartphone { max-width: 120px; } + .maxwidth150onsmartphoneimp { max-width: 120px !important; } + .maxwidth200onsmartphone { max-width: 200px; } + .maxwidth250onsmartphone { max-width: 250px; } + .maxwidth300onsmartphone { max-width: 300px; } + .maxwidth400onsmartphone { max-width: 400px; } .minwidth50imp { min-width: 50px !important; } .minwidth75imp { min-width: 75px !important; } - .minwidth100imp { min-width: 100px !important; } - .minwidth150imp { min-width: 110px !important; } - .minwidth200imp { min-width: 110px !important; } - .minwidth250imp { min-width: 115px !important; } - .minwidth300imp { min-width: 120px !important; } - .minwidth400imp { min-width: 150px !important; } - .minwidth500imp { min-width: 250px !important; } - .titlefield { width: auto; } - .titlefieldcreate { width: auto; } + .minwidth100imp { min-width: 100px !important; } + .minwidth150imp { min-width: 110px !important; } + .minwidth200imp { min-width: 110px !important; } + .minwidth250imp { min-width: 115px !important; } + .minwidth300imp { min-width: 120px !important; } + .minwidth400imp { min-width: 150px !important; } + .minwidth500imp { min-width: 250px !important; } + .titlefield { width: auto; } + .titlefieldcreate { width: auto; } #tooltip { position: absolute; @@ -1499,38 +1516,38 @@ select.widthcentpercentminusxx, span.widthcentpercentminusxx:not(.select2-select div.divphotoref { padding-<?php echo $right; ?>: 5px; - padding-bottom: 5px; + padding-bottom: 5px; + } + img.photoref, div.photoref { + border: 1px solid rgba(0, 0, 0, 0.2); + box-shadow: none; + -webkit-box-shadow: none; + padding: 4px; + height: 20px; + width: 20px; + object-fit: contain; } - img.photoref, div.photoref { - border: 1px solid rgba(0, 0, 0, 0.2); - box-shadow: none; - -webkit-box-shadow: none; - padding: 4px; - height: 20px; - width: 20px; - object-fit: contain; - } div.statusref { - padding-right: 10px; - } + padding-right: 10px; + } div.statusref img { - padding-right: 3px !important; - } + padding-right: 3px !important; + } div.statusrefbis { - padding-right: 3px !important; - } + padding-right: 3px !important; + } /* TODO div.statusref { - padding-top: 0px !important; - padding-left: 0px !important; - border: none !important; - } + padding-top: 0px !important; + padding-left: 0px !important; + border: none !important; + } */ - input.buttonpayment { + input.buttonpayment { min-width: 300px; - } + } } .linkobject { cursor: pointer; } @@ -1596,7 +1613,7 @@ td.showDragHandle { float: left; } .classforhorizontalscrolloftabs #id-right { - width:calc(100% - 210px); + width: calc(100% - 210px); display: inline-block; } @@ -1629,23 +1646,23 @@ div.blockvmenulogo border-bottom: 0 !important; } .menulogocontainer { - margin: <?php echo $disableimages ? '0' : '6'; ?>px; - margin-left: 11px; - margin-right: 9px; - padding: 0; - height: <?php echo $disableimages ? '20' : '32'; ?>px; - /* width: 100px; */ - max-width: 100px; - vertical-align: middle; + margin: <?php echo $disableimages ? '0' : '6'; ?>px; + margin-left: 11px; + margin-right: 9px; + padding: 0; + height: <?php echo $disableimages ? '20' : '32'; ?>px; + /* width: 100px; */ + max-width: 100px; + vertical-align: middle; } .backgroundforcompanylogo { - background-color: rgba(255,255,255,0.7); - border-radius: 4px; + background-color: rgba(255,255,255,0.7); + border-radius: 4px; } .menulogocontainer img.mycompany { - object-fit: contain; - width: inherit; - height: inherit; + object-fit: contain; + width: inherit; + height: inherit; } #mainmenutd_companylogo::after, #mainmenutd_menu::after { content: unset !important; @@ -1680,8 +1697,8 @@ div.vmenu, td.vmenu { padding-right: 10px !important; } .blockvmenu .menu_titre { - margin-top: 4px; - margin-bottom: 1px; + margin-top: 4px; + margin-bottom: 1px; } /* Try responsive even not on smartphone @@ -1700,10 +1717,17 @@ div.vmenu, td.vmenu { /* rule to reduce top menu - 3rd reduction: The menu for user is on left */ @media only screen and (max-width: <?php echo empty($conf->global->THEME_ELDY_WITDHOFFSET_FOR_REDUC3) ? round($nbtopmenuentries * 47, 0) + 130 : $conf->global->THEME_ELDY_WITDHOFFSET_FOR_REDUC3; ?>px) /* reduction 3 */ { + /* no side-nav */ body.sidebar-collapse .side-nav { display: none; } + /* if no side-nav, we don't need to have width forced */ + .classforhorizontalscrolloftabs #id-right { + width: unset; + display: unset; + } + body.sidebar-collapse .login_block { display: none; } @@ -1721,7 +1745,7 @@ div.vmenu, td.vmenu { padding-left: 20px; padding-right: 20px; position: absolute; - z-index: 90; + z-index: 90; } div.blockvmenulogo { @@ -1757,10 +1781,14 @@ div.vmenu, td.vmenu { div.fiche { - margin-<?php print $left; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 6 : (empty($conf->dol_optimize_smallscreen) ? '30' : '6')); ?>px; - margin-<?php print $right; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 6 : (empty($conf->dol_optimize_smallscreen) ? '28' : '6')); ?>px; - <?php if (!empty($dol_hide_leftmenu)) print 'margin-bottom: 12px;'."\n"; ?> - <?php if (!empty($dol_hide_leftmenu)) print 'margin-top: 12px;'."\n"; ?> + margin-<?php print $left; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 6 : (empty($conf->dol_optimize_smallscreen) ? '32' : '6')); ?>px; + margin-<?php print $right; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 6 : (empty($conf->dol_optimize_smallscreen) ? '30' : '6')); ?>px; + <?php if (!empty($dol_hide_leftmenu)) { + print 'margin-bottom: 12px;'."\n"; + } ?> + <?php if (!empty($dol_hide_leftmenu)) { + print 'margin-top: 12px;'."\n"; + } ?> } body.onlinepaymentbody div.fiche { /* For online payment page */ margin: 20px !important; @@ -1779,74 +1807,99 @@ div.fichecenterbis { margin-top: 8px; } div.fichethirdleft { - <?php if ($conf->browser->layout != 'phone') { print "float: ".$left.";\n"; } ?> - <?php if ($conf->browser->layout != 'phone') { print "width: 50%;\n"; } ?> - <?php if ($conf->browser->layout == 'phone') { print "padding-bottom: 6px;\n"; } ?> + <?php if ($conf->browser->layout != 'phone') { + print "float: ".$left.";\n"; + } ?> + <?php if ($conf->browser->layout != 'phone') { + print "width: 50%;\n"; + } ?> + <?php if ($conf->browser->layout == 'phone') { + print "padding-bottom: 6px;\n"; + } ?> } div.fichetwothirdright { - <?php if ($conf->browser->layout != 'phone') { print "float: ".$right.";\n"; } ?> - <?php if ($conf->browser->layout != 'phone') { print "width: 50%;\n"; } ?> - <?php if ($conf->browser->layout == 'phone') { print "padding-bottom: 6px\n"; } ?> + <?php if ($conf->browser->layout != 'phone') { + print "float: ".$right.";\n"; + } ?> + <?php if ($conf->browser->layout != 'phone') { + print "width: 50%;\n"; + } ?> + <?php if ($conf->browser->layout == 'phone') { + print "padding-bottom: 6px\n"; + } ?> } div.fichetwothirdright div.ficheaddleft { - padding-<?php echo $left; ?>: 20px; + padding-<?php echo $left; ?>: 28px; } div.fichehalfleft { - <?php if ($conf->browser->layout != 'phone') { print "float: ".$left.";\n"; } ?> - <?php if ($conf->browser->layout != 'phone') { print "width: calc(50% - 10px);\n"; } ?> + <?php if ($conf->browser->layout != 'phone') { + print "float: ".$left.";\n"; + } ?> + <?php if ($conf->browser->layout != 'phone') { + print "width: calc(50% - 14px);\n"; + } ?> } div.fichehalfright { - <?php if ($conf->browser->layout != 'phone') { print "float: ".$right.";\n"; } ?> - <?php if ($conf->browser->layout != 'phone') { print "width: calc(50% - 10px);\n"; } ?> + <?php if ($conf->browser->layout != 'phone') { + print "float: ".$right.";\n"; + } ?> + <?php if ($conf->browser->layout != 'phone') { + print "width: calc(50% - 14px);\n"; + } ?> } div.fichehalfright { - <?php if ($conf->browser->layout == 'phone') { print "margin-top: 10px;\n"; } ?> + <?php if ($conf->browser->layout == 'phone') { + print "margin-top: 10px;\n"; + } ?> } -div.firstcolumn div.box { + +/*div.firstcolumn div.box { padding-right: 10px; } div.secondcolumn div.box { padding-left: 10px; -} +}*/ + + /* Force values on one colum for small screen */ @media only screen and (max-width: 1000px) { - div.fiche { - margin-<?php print $left; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 6 : ($dol_hide_leftmenu ? '6' : '20')); ?>px; - margin-<?php print $right; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 8 : 6); ?>px; - } - div.fichecenter { - width: 100%; - clear: both; /* This is to have div fichecenter that are true rectangles */ - } - div.fichecenterbis { - margin-top: 8px; - } - div.fichethirdleft { - float: none; - width: auto; - padding-bottom: 6px; - } - div.fichetwothirdright { - float: none; - width: auto; - padding-bottom: 6px; - } - div.fichetwothirdright div.ficheaddleft { - padding-left: 0; + div.fiche { + margin-<?php print $left; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 6 : ($dol_hide_leftmenu ? '6' : '20')); ?>px; + margin-<?php print $right; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 8 : 6); ?>px; } - div.fichehalfleft { - float: none; - width: auto; - } - div.fichehalfright { - float: none; - width: auto; - } - div.fichehalfright { - margin-top: 10px; - } - div.firstcolumn div.box { + div.fichecenter { + width: 100%; + clear: both; /* This is to have div fichecenter that are true rectangles */ + } + div.fichecenterbis { + margin-top: 8px; + } + div.fichethirdleft { + float: none; + width: auto; + padding-bottom: 6px; + } + div.fichetwothirdright { + float: none; + width: auto; + padding-bottom: 6px; + } + div.fichetwothirdright div.ficheaddleft { + padding-left: 0; + } + div.fichehalfleft { + float: none; + width: auto; + } + div.fichehalfright { + float: none; + width: auto; + } + div.fichehalfright { + margin-top: 10px; + } + div.firstcolumn div.box { padding-right: 0px; } div.secondcolumn div.box { @@ -1857,23 +1910,23 @@ div.secondcolumn div.box { /* Force values on one colum for small screen */ @media only screen and (max-width: 1599px) { - div.fichehalfleft-lg { - float: none; - width: auto; - } - div.fichehalfright-lg { - float: none; - width: auto; - } + div.fichehalfleft-lg { + float: none; + width: auto; + } + div.fichehalfright-lg { + float: none; + width: auto; + } - .fichehalfright-lg .fichehalfright { - padding-left:0; - } + .fichehalfright-lg .fichehalfright { + padding-left:0; + } } /* For table into table into card */ div.fichehalfright tr.liste_titre:first-child td table.nobordernopadding td { - padding: 0 0 0 0; + padding: 0 0 0 0; } div.nopadding { padding: 0 !important; @@ -1885,28 +1938,28 @@ div.nopadding { } td.nobordernopadding.widthpictotitle.col-picto { - color: #bbb; - opacity: 0.85; + color: #bbb; + opacity: 0.85; } .table-list-of-attached-files .col-picto, .table-list-of-links .col-picto { - opacity: 0.7 !important; - font-size: 0.7em; - width: 20px; + opacity: 0.7 !important; + font-size: 0.7em; + width: 20px; } .table-list-of-attached-files .col-picto .widthpictotitle, .table-list-of-links .col-picto .widthpictotitle { width: unset; - color: #999; + color: #999; } /* span.widthpictotitle.pictotitle { - background: var(--colortexttitlenotab); - opacity: 0.8; - color: #fff !important; - padding: 7px; - border-radius: 2px; - min-width: 30px; - text-align: center; + background: var(--colortexttitlenotab); + opacity: 0.8; + color: #fff !important; + padding: 7px; + border-radius: 2px; + min-width: 30px; + text-align: center; } */ .pictotitle { @@ -1918,8 +1971,8 @@ span.widthpictotitle.pictotitle { width: 14px; } .pictosubstatus { - padding-left: 2px; - padding-right: 2px; + padding-left: 2px; + padding-right: 2px; } .pictostatus { width: 15px; @@ -1927,14 +1980,14 @@ span.widthpictotitle.pictotitle { margin-top: -3px } .pictowarning, .pictoerror, .pictopreview { - padding-<?php echo $left; ?>: 3px; + padding-<?php echo $left; ?>: 3px; } .pictowarning { - /* vertical-align: text-bottom; */ - color: <?php echo $badgeWarning ?>; + /* vertical-align: text-bottom; */ + color: <?php echo $badgeWarning ?>; } .pictoerror { - color: <?php echo $badgeDanger ?>; + color: <?php echo $badgeDanger ?>; } .pictomodule { width: 14px; @@ -1945,12 +1998,12 @@ span.widthpictotitle.pictotitle { .fiche .arearef img.pictoedit, .fiche .arearef span.pictoedit, .fiche .fichecenter img.pictoedit, .fiche .fichecenter span.pictoedit, .tagtdnote span.pictoedit { - opacity: 0.4; + opacity: 0.4; } .pictofixedwidth { - text-align: left; - width: 18px; - padding-right: 0; + text-align: left; + width: 20px; + padding-right: 0; } .colorthumb { @@ -1958,7 +2011,7 @@ span.widthpictotitle.pictotitle { padding-right: 1px; padding-top: 1px; padding-bottom: 1px; - width: 44px; + width: 50px; text-align:center; } div.attacharea { @@ -1990,9 +2043,9 @@ div.paginationref { } /* TODO div.statusref { - padding: 10px; - border: 1px solid #bbb; - border-radius: 6px; + padding: 10px; + border: 1px solid #bbb; + border-radius: 6px; } */ div.statusref { float: right; @@ -2000,33 +2053,33 @@ div.statusref { margin-top: 8px; margin-bottom: 10px; clear: both; - text-align: right; + text-align: right; } div.statusref img { - padding-left: 8px; - padding-right: 9px; - vertical-align: text-bottom; - width: 18px; + padding-left: 8px; + padding-right: 9px; + vertical-align: text-bottom; + width: 18px; } div.statusrefbis { - padding-left: 8px; - padding-right: 9px; - vertical-align: text-bottom; + padding-left: 8px; + padding-right: 9px; + vertical-align: text-bottom; } img.photoref, div.photoref { /* border: 1px solid #DDD; */ - -webkit-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.2); - box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.2); - padding: 4px; + -webkit-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.2); + box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.2); + padding: 4px; height: 80px; width: 80px; - object-fit: contain; + object-fit: contain; } div.photoref .fa, div.photoref .fas, div.photoref .far { font-size: 2.5em; } img.fitcontain { - object-fit: contain; + object-fit: contain; } div.photoref { display:table-cell; @@ -2034,12 +2087,12 @@ div.photoref { text-align:center; } img.photorefnoborder { - padding: 2px; + padding: 2px; height: 48px; width: 48px; - object-fit: contain; - border: 1px solid #AAA; - border-radius: 100px; + object-fit: contain; + border: 1px solid #AAA; + border-radius: 100px; } .underrefbanner { } @@ -2048,8 +2101,8 @@ img.photorefnoborder { /* border-bottom: 2px solid var(--colorbackhmenu1); */ } .trextrafieldseparator td, .trextrafields_collapse_last td { - /* border-bottom: 2px solid var(--colorbackhmenu1) !important; */ - border-bottom: 2px solid rgb(<?php echo $colortopbordertitle1 ?>) !important; + /* border-bottom: 2px solid var(--colorbackhmenu1) !important; */ + border-bottom: 2px solid rgb(<?php echo $colortopbordertitle1 ?>) !important; } .tdhrthin { @@ -2079,12 +2132,12 @@ div#tmenu_tooltip { <?php } ?> -webkit-touch-callout: none; /* iOS Safari */ - -webkit-user-select: none; /* Safari */ - -khtml-user-select: none; /* Konqueror HTML */ - -moz-user-select: none; /* Firefox */ - -ms-user-select: none; /* Internet Explorer/Edge */ - user-select: none; /* Non-prefixed version, currently - supported by Chrome and Opera */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; /* Non-prefixed version, currently + supported by Chrome and Opera */ } @@ -2099,25 +2152,25 @@ div.tmenudiv { <?php if (GETPOST('optioncss', 'aZ09') == 'print') { ?> display:none; <?php } else { ?> - position: relative; - display: block; - white-space: nowrap; - border-top: 0px; - border-<?php print $left; ?>: 0px; - border-<?php print $right; ?>: 0px; - padding: 0px 0px 0px 0px; /* t r b l */ - margin: 0px 0px 0px 0px; /* t r b l */ + position: relative; + display: block; + white-space: nowrap; + border-top: 0px; + border-<?php print $left; ?>: 0px; + border-<?php print $right; ?>: 0px; + padding: 0px 0px 0px 0px; /* t r b l */ + margin: 0px 0px 0px 0px; /* t r b l */ font-size: 13px; - font-weight: normal; + font-weight: normal; color: #000000; - text-decoration: none; + text-decoration: none; <?php } ?> } div.tmenudisabled, a.tmenudisabled { opacity: 0.6; } a.tmenu, a.tmenusel, a.tmenudisabled { - /* font-weight: 300; */ + /* font-weight: 300; */ } a.tmenudisabled:link, a.tmenudisabled:visited, a.tmenudisabled:hover, a.tmenudisabled:active { padding: 0px 5px 0px 5px; @@ -2131,7 +2184,7 @@ a.tmenu:link, a.tmenu:visited, a.tmenu:hover, a.tmenu:active { padding: 0px 2px 0px 2px; white-space: nowrap; color: var(--colortextbackhmenu); - text-decoration: none; + text-decoration: none; } a.tmenusel:link, a.tmenusel:visited, a.tmenusel:hover, a.tmenusel:active { padding: 0px 4px 0px 4px; @@ -2143,8 +2196,8 @@ a.tmenusel:link, a.tmenusel:visited, a.tmenusel:hover, a.tmenusel:active { ul.tmenu { /* t r b l */ - padding: 0px 0px 0px 0px; - margin: 0px 0px 0px 0px; + padding: 0px 0px 0px 0px; + margin: 0px 0px 0px 0px; list-style: none; display: table; } @@ -2156,7 +2209,7 @@ li.tmenu, li.tmenusel { vertical-align: bottom; <?php if (empty($conf->global->MAIN_MENU_INVERT)) { ?> float: <?php print $left; ?>; - <?php } ?> + <?php } ?> position:relative; display: block; padding: 0 0 0 0; @@ -2204,9 +2257,9 @@ div.tmenucenter height: 26px; <?php } else { ?> padding-top: 2px; - height: <?php print $heightmenu; ?>px; + height: <?php print $heightmenu; ?>px; <?php } ?> - /* width: 100%; */ + /* width: 100%; */ } #menu_titre_logo { padding-top: 0; @@ -2216,8 +2269,8 @@ div.menu_titre { padding-top: 4px; padding-bottom: 4px; overflow: hidden; - text-overflow: ellipsis; - width: 188px; /* required to have overflow working. must be same than menu_contenu */ + text-overflow: ellipsis; + width: 188px; /* required to have overflow working. must be same than menu_contenu */ } .mainmenuaspan { @@ -2237,10 +2290,10 @@ div.mainmenu { } a.tmenuimage:focus, .mainmenu.topmenuimage:focus { - outline: none; + outline: none; } button.ui-button.ui-corner-all.ui-widget:focus { - outline: none; + outline: none; } /* For mainmenu, we always load the img */ @@ -2250,10 +2303,10 @@ div.mainmenu.menu { <?php print $disableimages ? '' : 'top: 7px'; ?> } #mainmenutd_menu a.tmenuimage { - display: unset; + display: unset; } a.tmenuimage { - display: block; + display: block; } a.tmenuimage:hover{ @@ -2266,9 +2319,9 @@ a.tmenuimage:hover{ /* Do not load menu img for other if hidden to save bandwidth */ <?php if (empty($dol_hide_topmenu)) { ?> - <?php include dol_buildpath($path.'/theme/'.$theme.'/main_menu_fa_icons.inc.php', 0); ?> + <?php include dol_buildpath($path.'/theme/'.$theme.'/main_menu_fa_icons.inc.php', 0); ?> - <?php + <?php // Add here more div for other menu entries. moduletomainmenu=array('module name'=>'name of class for div') $moduletomainmenu = array( @@ -2280,8 +2333,7 @@ a.tmenuimage:hover{ 'barcode'=>'', 'fckeditor'=>'', 'categorie'=>'', ); $mainmenuused = 'home'; - foreach ($conf->modules as $val) - { + foreach ($conf->modules as $val) { $mainmenuused .= ','.(isset($moduletomainmenu[$val]) ? $moduletomainmenu[$val] : $val); } $mainmenuusedarray = array_unique(explode(',', $mainmenuused)); @@ -2291,29 +2343,29 @@ a.tmenuimage:hover{ $divalreadydefined = array('home', 'companies', 'products', 'mrp', 'commercial', 'externalsite', 'accountancy', 'project', 'tools', 'members', 'agenda', 'ftp', 'holiday', 'hrm', 'bookmark', 'cashdesk', 'takepos', 'ecm', 'geoipmaxmind', 'gravatar', 'clicktodial', 'paypal', 'stripe', 'webservices', 'website'); // Put here list of menu entries we are sure we don't want $divnotrequired = array('multicurrency', 'salaries', 'ticket', 'margin', 'opensurvey', 'paybox', 'expensereport', 'incoterm', 'prelevement', 'propal', 'workflow', 'notification', 'supplier_proposal', 'cron', 'product', 'productbatch', 'expedition'); - foreach ($mainmenuusedarray as $val) - { - if (empty($val) || in_array($val, $divalreadydefined)) continue; - if (in_array($val, $divnotrequired)) continue; + foreach ($mainmenuusedarray as $val) { + if (empty($val) || in_array($val, $divalreadydefined)) { + continue; + } + if (in_array($val, $divnotrequired)) { + continue; + } //print "XXX".$val; // Search img file in module dir $found = 0; $url = ''; - foreach ($conf->file->dol_document_root as $dirroot) - { - if (file_exists($dirroot."/".$val."/img/".$val.".png")) - { + foreach ($conf->file->dol_document_root as $dirroot) { + if (file_exists($dirroot."/".$val."/img/".$val.".png")) { $url = dol_buildpath('/'.$val.'/img/'.$val.'.png', 1); $found = 1; break; } } // Img file not found - if (!$found) - { + if (!$found) { if (!defined('DISABLE_FONT_AWSOME')) { print "/* A mainmenu entry was found but img file ".$val.".png not found (check /".$val."/img/".$val.".png), so we use a generic one. */\n"; - print "/* Overwrite this definition in your own css with a different content to use your own font awesome icon. */\n"; + print "/* Overwrite this definition in your own css with a different content to use your own font awesome icon. */\n"; print 'div.mainmenu.'.$val.'::before { content: "\f249"; }'."\n"; @@ -2336,11 +2388,11 @@ a.tmenuimage:hover{ <?php } // End test if $dol_hide_topmenu ?> .tmenuimage { - padding:0 0 0 0 !important; - margin:0 0px 0 0 !important; - <?php if ($disableimages) { ?> - display: none; - <?php } ?> + padding:0 0 0 0 !important; + margin:0 0px 0 0 !important; + <?php if ($disableimages) { ?> + display: none; + <?php } ?> } @@ -2351,14 +2403,14 @@ a.tmenuimage:hover{ { background: #f0f0f0; display: table; - position: absolute; - height: 100%; - width: 100%; - font-size: 1em; + position: absolute; + height: 100%; + width: 100%; + font-size: 1em; } .login_center { display: table-cell; - vertical-align: middle; + vertical-align: middle; } .login_vertical_align { padding: 10px; @@ -2418,10 +2470,10 @@ if (!empty($conf->global->MAIN_LOGIN_BACKGROUND)) { margin: 8px; } .login_table .tdinputlogin { - background-color: transparent; - /* border: 2px solid #ccc; */ - min-width: 220px; - border-radius: 2px; + background-color: transparent; + /* border: 2px solid #ccc; */ + min-width: 220px; + border-radius: 2px; } .login_table .tdinputlogin .fa { padding-left: 10px; @@ -2434,7 +2486,7 @@ if (!empty($conf->global->MAIN_LOGIN_BACKGROUND)) { font-size: 1em; } .login_main_home { - word-break: break-word; + word-break: break-word; } .login_main_message { text-align: center; @@ -2455,7 +2507,7 @@ div#login_left, div#login_right { vertical-align: middle; } div#login_right select#entity { - margin-top: 10px; + margin-top: 10px; } table.login_table tr td table.none tr td { padding: 2px; @@ -2518,17 +2570,17 @@ div.login a:hover { text-decoration:underline; } .login_block_elem a span.atoplogin, .login_block_elem span.atoplogin { - vertical-align: middle; + vertical-align: middle; } div.login_block_user { display: inline-block; - vertical-align: middle; + vertical-align: middle; line-height: <?php echo $disableimages ? '25' : '50'; ?>px; height: <?php echo $disableimages ? '25' : '50'; ?>px; } div.login_block_other { display: inline-block; - vertical-align: middle; + vertical-align: middle; clear: <?php echo $disableimages ? 'none' : 'both'; ?>; padding-top: 0; text-align: right; @@ -2566,11 +2618,11 @@ div.login_block_other { text-decoration:underline !important; } span.fa.atoplogin, span.fa.atoplogin:hover { - font-size: 16px; - text-decoration: none !important; + font-size: 16px; + text-decoration: none !important; } .atoplogin #dropdown-icon-down, .atoplogin #dropdown-icon-up { - font-size: 0.7em; + font-size: 0.7em; } img.login, img.printer, img.entity { /* padding: 0px 0px 0px 4px; */ @@ -2581,33 +2633,33 @@ img.login, img.printer, img.entity { } .userimg.atoplogin img.userphoto, .userimgatoplogin img.userphoto { /* size for user photo in login bar */ width: <?php echo $disableimages ? '26' : '30'; ?>px; - height: <?php echo $disableimages ? '26' : '30'; ?>px; - border-radius: 50%; - background-size: contain; - background-size: contain; - border: 1px solid; - border-color: rgba(255, 255, 255, 0.2); + height: <?php echo $disableimages ? '26' : '30'; ?>px; + border-radius: 50%; + background-size: contain; + background-size: contain; + border: 1px solid; + border-color: rgba(255, 255, 255, 0.2); } img.userphoto { /* size for user photo in lists */ border-radius: 0.72em; width: 1.4em; - height: 1.4em; - background-size: contain; - vertical-align: middle; + height: 1.4em; + background-size: contain; + vertical-align: middle; } img.userphotosmall { /* size for user photo in lists */ border-radius: 0.6em; width: 1.2em; - height: 1.2em; - background-size: contain; - vertical-align: middle; - background-color: #FFF; + height: 1.2em; + background-size: contain; + vertical-align: middle; + background-color: #FFF; } img.userphoto[alt="Gravatar avatar"], img.photouserphoto.dropdown-user-image[alt="Gravatar avatar"] { - background: #fff; + background: #fff; } form[name="addtime"] img.userphoto { - border: 1px solid #444; + border: 1px solid #444; } .span-icon-user { background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/object_user.png', 1); ?>); @@ -2623,20 +2675,20 @@ form[name="addtime"] img.userphoto { /* ============================================================================== */ div.vmenu, td.vmenu { - margin-<?php print $right; ?>: 2px; - position: relative; - float: left; - padding: 0px; - padding-bottom: 0px; - padding-top: 1px; - width: 190px; + margin-<?php print $right; ?>: 2px; + position: relative; + float: left; + padding: 0px; + padding-bottom: 0px; + padding-top: 1px; + width: 190px; } .vmenu { - width: 190px; + width: 190px; margin-left: 6px; <?php if (GETPOST('optioncss', 'aZ09') == 'print') { ?> - display: none; + display: none; <?php } ?> } @@ -2652,8 +2704,8 @@ input.vmenusearchselectcombo[type=text] { padding-top: 3px; padding-bottom: 3px; overflow: hidden; - text-overflow: ellipsis; - width: 188px; /* required to have overflow working. must be same than .menu_titre */ + text-overflow: ellipsis; + width: 188px; /* required to have overflow working. must be same than .menu_titre */ } #menu_contenu_logo { /* padding-top: 0; */ } .companylogo { } @@ -2686,22 +2738,22 @@ a.help:link, a.help:visited, a.help:hover, a.help:active, span.help { text-align /* color: #f3e4ac !important; */ } .helppresentcircle { - color: var(--colorbackhmenu1); - filter: invert(0.8); - margin-left: -7px; - display: inline-block; - margin-top: -10px; - font-size: x-small; - vertical-align: super; - opacity: 0.95; + color: var(--colorbackhmenu1); + filter: invert(0.8); + margin-left: -7px; + display: inline-block; + margin-top: -10px; + font-size: x-small; + vertical-align: super; + opacity: 0.95; } .vmenu div.blockvmenufirst, .vmenu div.blockvmenulogo, .vmenu div.blockvmenusearchphone, .vmenu div.blockvmenubookmarks { - border-top: 1px solid #BBB; + border-top: 1px solid #BBB; } a.vsmenu.addbookmarkpicto { - padding-right: 10px; + padding-right: 10px; } div.blockvmenusearchphone { @@ -2735,16 +2787,16 @@ div.blockvmenupair, div.blockvmenuimpair, div.blockvmenubookmarks, div.blockvmen color: #000000; text-align: <?php print $left; ?>; text-decoration: none; - padding-left: 5px; - padding-right: 1px; - padding-top: 4px; - padding-bottom: 7px; - margin: 0 0 0 2px; + padding-left: 5px; + padding-right: 1px; + padding-top: 4px; + padding-bottom: 7px; + margin: 0 0 0 2px; background: var(--colorbackvmenu1); - border-left: 1px solid #AAA; - border-right: 1px solid #BBB; + border-left: 1px solid #AAA; + border-right: 1px solid #BBB; } div.blockvmenusearch @@ -2753,7 +2805,7 @@ div.blockvmenusearch color: #000000; text-align: <?php print $left; ?>; text-decoration: none; - margin: 1px 0px 0px 2px; + margin: 1px 0px 0px 2px; background: var(--colorbackvmenu1); } @@ -2771,13 +2823,13 @@ div.blockvmenuhelp color: #000000; text-align: center; text-decoration: none; - padding-left: 0px; - padding-right: 6px; - padding-top: 3px; - padding-bottom: 3px; - margin: 4px 0px 0px 0px; + padding-left: 0px; + padding-right: 6px; + padding-top: 3px; + padding-bottom: 3px; + margin: 4px 0px 0px 0px; <?php } else { ?> - display: none; + display: none; <?php } ?> } @@ -2800,7 +2852,7 @@ td.barre_select { td.photo { background: #F4F4F4; color: #000000; - border: 1px solid #bbb; + border: 1px solid #bbb; } /* ============================================================================== */ @@ -2812,14 +2864,14 @@ td.photo { */ #mainContent, #leftContent .ui-layout-pane { - padding: 0px; - overflow: auto; + padding: 0px; + overflow: auto; } #mainContent, #leftContent .ui-layout-center { padding: 0px; position: relative; /* contain floated or positioned elements */ - overflow: auto; /* add scrolling to content-div */ + overflow: auto; /* add scrolling to content-div */ } @@ -2828,29 +2880,29 @@ td.photo { /* ============================================================================== */ td.ecmroot { - padding-bottom: 0 !important; + padding-bottom: 0 !important; } .largebutton { /* border-top: 1px solid #CCC !important; */ - padding: 0px 4px 14px 4px !important; - min-height: 32px; + padding: 0px 4px 14px 4px !important; + min-height: 32px; } a.toolbarbutton { - margin-top: 0px; - margin-left: 4px; - margin-right: 4px; - height: 30px; + margin-top: 0px; + margin-left: 4px; + margin-right: 4px; + height: 30px; } img.toolbarbutton { margin-top: 1px; - height: 30px; + height: 30px; } li.expanded > a.fmdirlia.jqft.ecmjqft { - font-weight: bold !important; + font-weight: bold !important; } @@ -2860,10 +2912,10 @@ li.expanded > a.fmdirlia.jqft.ecmjqft { /* Onglets */ /* ============================================================================== */ div.tabs { - text-align: <?php print $left; ?>; - margin-top: 10px; - padding-left: 6px; - padding-right: 6px; + text-align: <?php print $left; ?>; + margin-top: 10px; + padding-left: 6px; + padding-right: 6px; clear:both; height:100%; } @@ -2872,20 +2924,20 @@ div.tabsElem { } /* To avoid overlap of tabs when not browser */ /* div.tabsElem a.tabactive::before, div.tabsElem a.tabunactive::before { - content: "\f0da"; - font-family: "Font Awesome 5 Free"; - padding-right: 2px; - font-weight: 900; + content: "\f0da"; + font-family: "Font Awesome 5 Free"; + padding-right: 2px; + font-weight: 900; } */ div.tabBar { - color: var(--colortextbacktab); - padding-top: 16px; - padding-left: 0px; padding-right: 0px; - padding-bottom: 2px; - margin: 0px 0px 16px 0px; - border-top: 1px solid #BBB; - /* border-bottom: 1px solid #AAA; */ + color: var(--colortextbacktab); + padding-top: 16px; + padding-left: 0px; padding-right: 0px; + padding-bottom: 2px; + margin: 0px 0px 16px 0px; + border-top: 1px solid #BBB; + /* border-bottom: 1px solid #AAA; */ width: auto; background: var(--colorbacktabcard1); } @@ -2897,8 +2949,8 @@ div.fiche table:not(.table-fiche-title) tr.titre td { } div.tabBar.tabBarNoTop { - padding-top: 0; - border-top: 0; + padding-top: 0; + border-top: 0; } /* tabBar used for creation/update/send forms */ @@ -2914,11 +2966,11 @@ div.tabBarWithBottom table.border>tbody>tr:last-of-type>td { } div.tabBar table.tableforservicepart2:last-child { - border-bottom: 1px solid #aaa; + border-bottom: 1px solid #aaa; } .tableforservicepart1 .tdhrthin { height: unset; - padding-top: 0 !important; + padding-top: 0 !important; } /* Payment Screen : Pointer cursor in the autofill image */ .AutoFillAmount { @@ -2942,26 +2994,26 @@ div.popuptab { /* ============================================================================== */ div.tabsAction { - margin: 20px 0em 30px 0em; - padding: 0em 0em; - text-align: right; + margin: 20px 0em 30px 0em; + padding: 0em 0em; + text-align: right; } div.tabsActionNoBottom { - margin-bottom: 0px; + margin-bottom: 0px; } div.tabsAction > a { margin-bottom: 16px !important; } a.tabTitle { - color: rgba(0,0,0,0.4) !important; - text-shadow:1px 1px 1px #ffffff; + color: rgba(0,0,0,0.4) !important; + text-shadow:1px 1px 1px #ffffff; font-family: <?php print $fontlist ?>; font-weight: normal !important; - padding: 4px 6px 2px 0px; - margin-<?php print $right; ?>: 10px; - text-decoration: none; - white-space: nowrap; + padding: 4px 6px 2px 0px; + margin-<?php print $right; ?>: 10px; + text-decoration: none; + white-space: nowrap; } .tabTitleText { display: none; @@ -2970,18 +3022,18 @@ a.tabTitle { max-height: 14px; } div.tabs div.tabsElem:first-of-type a.tab { - margin-left: 0px !important; + margin-left: 0px !important; } a.tabunactive { - color: var(--colortextlink) !important; + color: var(--colortextlink) !important; } a.tab:link, a.tab:visited, a.tab:hover, a.tab#active { font-family: <?php print $fontlist ?>; padding: 12px 14px 13px; - margin: 0em 0.2em; - text-decoration: none; - white-space: nowrap; + margin: 0em 0.2em; + text-decoration: none; + white-space: nowrap; /*border-right: 1px solid #ddd; border-left: 1px solid #ddd; @@ -3011,30 +3063,30 @@ a.tab:hover text-decoration: underline; } a.tabimage { - color: #434956; + color: #434956; font-family: <?php print $fontlist ?>; - text-decoration: none; - white-space: nowrap; + text-decoration: none; + white-space: nowrap; } td.tab { - background: #dee7ec; + background: #dee7ec; } span.tabspan { - background: #dee7ec; - color: #434956; + background: #dee7ec; + color: #434956; font-family: <?php print $fontlist ?>; - padding: 0px 6px; - margin: 0em 0.2em; - text-decoration: none; - white-space: nowrap; + padding: 0px 6px; + margin: 0em 0.2em; + text-decoration: none; + white-space: nowrap; -webkit-border-radius:4px 4px 0px 0px; border-radius:4px 4px 0px 0px; - border-<?php print $right; ?>: 1px solid #555555; - border-<?php print $left; ?>: 1px solid #D8D8D8; - border-top: 1px solid #D8D8D8; + border-<?php print $right; ?>: 1px solid #555555; + border-<?php print $left; ?>: 1px solid #D8D8D8; + border-top: 1px solid #D8D8D8; } /* ============================================================================== */ @@ -3082,10 +3134,10 @@ tr.nocellnopadd td.nobordernopadding, tr.nocellnopadd td.nocellnopadd } .smallpaddingimp { - padding: 4px !important; + padding: 4px !important; } input.button.smallpaddingimp { - font-size: 0.8em; + font-size: 0.8em; } .nopaddingleft { padding-<?php print $left; ?>: 0px; @@ -3122,8 +3174,8 @@ div.tabs.nopaddingleft { } table.tableforemailform tr td { - padding-top: 3px; - padding-bottom: 3px; + padding-top: 3px; + padding-bottom: 3px; } table.border, table.bordernooddeven, table.dataTable, .table-border, .table-border-col, .table-key-border-col, .table-val-border-col, div.border { @@ -3137,14 +3189,14 @@ table.borderplus { height: 22px; } tr.liste_titre.box_titre td table td, .bordernooddeven tr td { - height: 22px; + height: 22px; } div.tabBar div.border .table-border-row, div.tabBar div.border .table-key-border-col, div.tabBar .table-val-border-col { vertical-align: middle; } div .tdtop { - vertical-align: top !important; + vertical-align: top !important; /*padding-top: 10px !important; padding-bottom: 2px !important; */ } @@ -3176,10 +3228,10 @@ td.border, div.tagtable div div.border { /* Main boxes */ .nobordertop, .nobordertop tr:first-of-type td { - border-top: none !important; + border-top: none !important; } .noborderbottom, .noborderbottom tr:last-of-type td { - border-bottom: none !important; + border-bottom: none !important; } .bordertop { border-top: 1px solid rgb(<?php echo $colortopbordertitle1 ?>); @@ -3202,14 +3254,14 @@ table.liste, table.noborder, table.formdoc, div.noborder { margin: 0px 0px 5px 0px; /*width: calc(100% - 7px); - border-collapse: separate !important; - border-spacing: 0px; - border-top-width: 0px; - border-top-color: rgb(215,215,215); - border-top-style: solid; - margin: 0px 0px 5px 2px; - box-shadow: 1px 1px 5px #ddd; - */ + border-collapse: separate !important; + border-spacing: 0px; + border-top-width: 0px; + border-top-color: rgb(215,215,215); + border-top-style: solid; + margin: 0px 0px 5px 2px; + box-shadow: 1px 1px 5px #ddd; + */ } #tablelines { border-bottom-width: 1px; @@ -3222,7 +3274,7 @@ table.liste tr:last-of-type td, table.noborder:not(#tablelines) tr:last-of-type border-bottom-style: solid; } div.tabBar div.fichehalfright table.noborder:not(.margintable):not(.paymenttable):not(.lastrecordtable):last-of-type { - border-bottom: 1px solid rgb(<?php echo $colortopbordertitle1 ?>); + border-bottom: 1px solid rgb(<?php echo $colortopbordertitle1 ?>); } div.tabBar table.border>tbody>tr:last-of-type>td { border-bottom-width: 1px; @@ -3230,7 +3282,7 @@ div.tabBar table.border>tbody>tr:last-of-type>td { border-bottom-style: solid; } div.tabBar div.fichehalfright table.noborder { - border-bottom: none; + border-bottom: none; } table.paddingtopbottomonly tr td { @@ -3241,11 +3293,11 @@ table.paddingtopbottomonly tr td { background: var(--colorbacktitle1) !important; } .liste_titre2 { - background: var(--colorbackhmenu1) !important; - color: #fff; + background: var(--colorbackhmenu1) !important; + color: #fff; } table:not(.listwithfilterbefore) tr.liste_titre_filter:first-of-type td.liste_titre { - padding-top: 5px; + padding-top: 5px; } tr.liste_titre_filter td.liste_titre { @@ -3258,19 +3310,19 @@ tr.liste_titre_filter td.liste_titre:first-of-type { } .liste_titre_create td, .liste_titre_create th, .liste_titre_create .tagtd { - border-bottom-width: 0 !important; - border-top-width: 1px; - border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); - border-top-style: solid; + border-bottom-width: 0 !important; + border-top-width: 1px; + border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); + border-top-style: solid; } tr#trlinefordates td { - border-bottom: 0px !important; + border-bottom: 0px !important; } .liste_titre_add td, .liste_titre_add th, .liste_titre_add .tagtd { - border-top-width: 1px; - border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); - border-top-style: solid; + border-top-width: 1px; + border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); + border-top-style: solid; } table.liste tr, table.noborder tr, div.noborder form { border-top-color: #FEFEFE; @@ -3308,13 +3360,13 @@ table.border tr td table.nobordernopadding tr td { padding-bottom: 0; } td.borderright { - border: none; /* to erase value for table.nobordernopadding td */ + border: none; /* to erase value for table.nobordernopadding td */ border-right-width: 1px !important; border-right-color: #BBB !important; border-right-style: solid !important; } td.borderleft { - border: none; /* to erase value for table.nobordernopadding td */ + border: none; /* to erase value for table.nobordernopadding td */ border-left-width: 1px !important; border-left-color: #BBB !important; border-left-style: solid !important; @@ -3339,19 +3391,19 @@ div.refidpadding { } div.refid { font-weight: bold; - color: var(--colortexttitlenotab); - font-size: 1.2em; - word-break: break-word; + color: var(--colortexttitlenotab); + font-size: 1.2em; + word-break: break-word; } div.refidno { padding-top: 3px; font-weight: normal; - color: var(--refidnocolor); - font-size: <?php print is_numeric($fontsize) ? $fontsize.'px' : $fontsize ?>; - line-height: 21px; + color: var(--refidnocolor); + font-size: <?php print is_numeric($fontsize) ? $fontsize.'px' : $fontsize ?>; + line-height: 21px; } div.refidno form { - display: inline-block; + display: inline-block; } div.pagination { @@ -3361,10 +3413,10 @@ div.pagination a { font-weight: normal; } /*div.pagination a.butAction, div.fichehalfright a.butAction { - margin-right: 0px !important; + margin-right: 0px !important; } div.tabsAction a.butActionDelete:last-child, div.tabsAction a.butAction:last-child { - margin-right: 0px !important; + margin-right: 0px !important; }*/ div.pagination ul { @@ -3402,8 +3454,8 @@ div.pagination li.pagination span.inactive { li.noborder.litext, li.noborder.litext a, div.pagination li a.inactive:hover, div.pagination li span.inactive:hover { - -webkit-box-shadow: none !important; - box-shadow: none !important; + -webkit-box-shadow: none !important; + box-shadow: none !important; } /*div.pagination li.litext { padding-top: 8px; @@ -3491,18 +3543,19 @@ table.hidepaginationnext .paginationnext { display: none; } .tabBar .arearef .pagination.paginationref { - max-width: calc(30%); + max-width: calc(30%); } .paginationafterarrows a.btnTitlePlus, .titre_right a.btnTitlePlus { - border: 1px solid var(--btncolorborder); + border: 1px solid var(--btncolorborder); } .paginationafterarrows a.btnTitlePlus:hover span:before, .titre_right a.btnTitlePlus:hover span:before { - /* text-shadow: 0px 0px 5px #ccc; */ - /* filter: invert(0.3); */ - font-size: 1.07em; + /* text-shadow: 0px 0px 5px #ccc; */ + /* filter: invert(0.3); */ + font-size: 1.07em; } + /* Set the color for hover lines */ .oddeven:hover, .evenodd:hover, .impair:hover, .pair:hover { @@ -3514,7 +3567,7 @@ table.hidepaginationnext .paginationnext { } .treditedlinefordate { background: var(--colorbacklinepairchecked) !important; /* Must be background to be stronger than background of odd or even */ - border-bottom: 0px; + border-bottom: 0px; } <?php if ($colorbacklinepairchecked) { ?> .highlight { @@ -3565,34 +3618,34 @@ td.evenodd, tr.nohoverpair td, #trlinefordates td { } .trforbreak td { font-weight: 500; - border-bottom: 1pt solid black !important; + border-bottom: 1pt solid black !important; background-color: var(--colorbacklinebreak) !important; } .trforbreak.nobold td a, .trforbreak.nobold span.secondary { - font-weight: normal !important; + font-weight: normal !important; } table.dataTable td { - padding: 5px 8px 5px 8px !important; + padding: 5px 8px 5px 8px !important; } tr.pair td, tr.impair td, form.impair div.tagtd, form.pair div.tagtd, div.impair div.tagtd, div.pair div.tagtd, div.liste_titre div.tagtd { - padding: 7px 8px 7px 8px; - border-bottom: 1px solid #ddd; + padding: 7px 8px 7px 8px; + border-bottom: 1px solid #ddd; } form.pair, form.impair { font-weight: normal; } form.tagtr:last-of-type div.tagtd, tr.pair:last-of-type td, tr.impair:last-of-type td { - border-bottom: 0px !important; + border-bottom: 0px !important; } tr.nobottom td { - border-bottom: 0px !important; + border-bottom: 0px !important; } div.tableforcontact form.tagtr:last-of-type div.tagtd { - border-bottom: 1px solid #ddd !important; + border-bottom: 1px solid #ddd !important; } tr.pair td .nobordernopadding tr td, tr.impair td .nobordernopadding tr td { - border-bottom: 0px !important; + border-bottom: 0px !important; } table.nobottomiftotal tr.liste_total td { background-color: #fff; @@ -3612,8 +3665,8 @@ div.liste_titre { } div.liste_titre_bydiv { border-top-width: <?php echo $borderwidth ?>px; - border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); - border-top-style: solid; + border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); + border-top-style: solid; border-collapse: collapse; display: table; @@ -3638,9 +3691,9 @@ div.liste_titre_bydiv, .liste_titre div.tagtr, tr.liste_titre, tr.liste_titre_se background: var(--colorbacktitle1); font-weight: <?php echo $useboldtitle ? 'bold' : 'normal'; ?>; - color: var(--colortexttitle); - font-family: <?php print $fontlist ?>; - text-align: <?php echo $left; ?>; + color: var(--colortexttitle); + font-family: <?php print $fontlist ?>; + text-align: <?php echo $left; ?>; } tr.liste_titre th, tr.liste_titre td, th.liste_titre { @@ -3652,10 +3705,10 @@ tr.liste_titre:first-child th, tr:first-child th.liste_titre { } tr.liste_titre th, th.liste_titre, tr.liste_titre td, td.liste_titre, form.liste_titre div { - font-family: <?php print $fontlist ?>; - font-weight: <?php echo $useboldtitle ? 'bold' : 'normal'; ?>; - vertical-align: middle; - height: 24px; + font-family: <?php print $fontlist ?>; + font-weight: <?php echo $useboldtitle ? 'bold' : 'normal'; ?>; + vertical-align: middle; + height: 24px; } tr.liste_titre th a, th.liste_titre a, tr.liste_titre td a, td.liste_titre a, form.liste_titre div a, div.liste_titre a { text-shadow: none !important; @@ -3663,8 +3716,8 @@ tr.liste_titre th a, th.liste_titre a, tr.liste_titre td a, td.liste_titre a, fo } tr.liste_titre_topborder td { border-top-width: <?php echo $borderwidth; ?>px; - border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); - border-top-style: solid; + border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); + border-top-style: solid; } .liste_titre td a { text-shadow: none !important; @@ -3677,8 +3730,8 @@ tr.liste_titre_topborder td { background: transparent; } tr.liste_titre:last-child th.liste_titre, tr.liste_titre:last-child th.liste_titre_sel, tr.liste_titre td.liste_titre, tr.liste_titre td.liste_titre_sel, form.liste_titre div.tagtd { /* For last line of table headers only */ - /* border-bottom: 1px solid #ddd; */ - border-bottom: unset; + /* border-bottom: 1px solid #ddd; */ + border-bottom: unset; } div.liste_titre { @@ -3686,30 +3739,30 @@ div.liste_titre { } tr.liste_titre_sel th, th.liste_titre_sel, tr.liste_titre_sel td, td.liste_titre_sel, form.liste_titre_sel div { - font-family: <?php print $fontlist ?>; - font-weight: normal; - border-bottom: 1px solid #FDFFFF; - text-decoration: underline; + font-family: <?php print $fontlist ?>; + font-weight: normal; + border-bottom: 1px solid #FDFFFF; + text-decoration: underline; } input.liste_titre { - background: transparent; - border: 0px; + background: transparent; + border: 0px; } .listactionlargetitle .liste_titre { line-height: 24px; } .noborder tr.liste_total td, tr.liste_total td, form.liste_total div, .noborder tr.liste_total_wrap td, tr.liste_total_wrap td, form.liste_total_wrap div { - color: var(--listetotal); - font-weight: normal; + color: var(--listetotal); + font-weight: normal; } .noborder tr.liste_total td, tr.liste_total td, form.liste_total div { - white-space: nowrap; + white-space: nowrap; } .noborder tr.liste_total_wrap td, tr.liste_total_wrap td, form.liste_total_wrap div { white-space: normal; } form.liste_total div { - border-top: 1px solid #DDDDDD; + border-top: 1px solid #DDDDDD; } tr.liste_sub_total, tr.liste_sub_total td { border-bottom: 1px solid #aaa; @@ -3722,10 +3775,10 @@ tr.liste_sub_total, tr.liste_sub_total td { border-bottom: none; } table.tableforservicepart1:first-of-type tr:first-of-type td { - border-top: 1px solid #888; + border-top: 1px solid #888; } table.tableforservicepart1 tr td { - border-top: 0px; + border-top: 0px; } .paymenttable, .margintable { @@ -3733,7 +3786,7 @@ table.tableforservicepart1 tr td { margin: 0px 0px 0px 0px !important; } table.noborder.paymenttable { - border-bottom: none !important; + border-bottom: none !important; } .paymenttable tr td:first-child, .margintable tr td:first-child { @@ -3762,7 +3815,7 @@ div.tabBar .noborder { border-bottom: 1px solid rgb(<?php echo $colortopbordertitle1 ?>) !important; } #tablelines tr td { - height: unset; + height: unset; } /* Prepare to remove class pair - impair */ @@ -3809,48 +3862,48 @@ ul.noborder li:nth-child(even):not(.liste_titre) { */ .box { - overflow-x: auto; - min-height: 40px; - padding-right: 0px; - padding-left: 0px; - padding-bottom: 10px; + overflow-x: auto; + min-height: 40px; + padding-right: 0px; + padding-left: 0px; + padding-bottom: 10px; } .ficheaddleft div.boxstats, .ficheaddright div.boxstats { - border: none; + border: none; } .boxstatsborder { - /* border: 1px solid #CCC !important; */ + /* border: 1px solid #CCC !important; */ } .boxstats, .boxstats130 { - display: inline-block; - margin-left: 8px; - margin-right: 8px; - margin-top: 5px; - margin-bottom: 5px; - text-align: center; + display: inline-block; + margin-left: 8px; + margin-right: 8px; + margin-top: 5px; + margin-bottom: 5px; + text-align: center; - background: var(--colorbackbody); - border: 1px solid var(--colorboxstatsborder); - border-left: 6px solid var(--colorboxstatsborder); - /* box-shadow: 1px 1px 8px var(--colorboxstatsborder); */ - border-radius: 0px; + background: var(--colorbackbody); + border: 1px solid var(--colorboxstatsborder); + border-left: 6px solid var(--colorboxstatsborder); + /* box-shadow: 1px 1px 8px var(--colorboxstatsborder); */ + border-radius: 0px; } .boxstats, .boxstats130, .boxstatscontent { white-space: nowrap; overflow: hidden; - text-overflow: ellipsis; + text-overflow: ellipsis; } .boxstats130 { - width: 100%; - height: 59px; - /* padding: 3px; */ + width: 100%; + height: 59px; + /* padding: 3px; */ } .boxstats { - padding-left: 6px; - padding-right: 6px; - padding-top: 2px; - padding-bottom: 2px; - width: 118px; + padding-left: 6px; + padding-right: 6px; + padding-top: 2px; + padding-bottom: 2px; + width: 118px; } .boxtable:not(.widgetstats) td.tdboxstats .boxstats { @@ -3858,37 +3911,37 @@ ul.noborder li:nth-child(even):not(.liste_titre) { } .tabBar .fichehalfright .boxstats { - padding-top: 8px; - padding-bottom: 4px; + padding-top: 8px; + padding-bottom: 4px; } .boxstatscontent { padding: 3px; } .boxstatsempty { - width: 121px; - padding-left: 3px; - padding-right: 3px; - margin-left: 8px; - margin-right: 8px; + width: 121px; + padding-left: 3px; + padding-right: 3px; + margin-left: 8px; + margin-right: 8px; } .boxstats150empty { - width: 158px; - padding-left: 3px; - padding-right: 3px; - margin-left: 8px; - margin-right: 8px; + width: 158px; + padding-left: 3px; + padding-right: 3px; + margin-left: 8px; + margin-right: 8px; } @media only screen and (max-width: 767px) { .tabBar .arearef .pagination.paginationref { - max-width: calc(50%); + max-width: calc(50%); } .clearbothonsmartphone { - clear: both; - display: block !important; + clear: both; + display: block !important; } div.tabs { @@ -3909,31 +3962,31 @@ ul.noborder li:nth-child(even):not(.liste_titre) { } .boxstats, .boxstats130 { margin: 3px; - } - .boxstats130 { - text-align: <?php echo $left; ?> - } + } + .boxstats130 { + text-align: <?php echo $left; ?> + } .thumbstat { flex: 1 1 110px; margin-bottom: 8px; - min-width: <?php echo isset($_SESSION['dol_screenwidth']) ?min(160, round($_SESSION['dol_screenwidth'] / 2 - 20)) : 150; ?>px; /* on screen < 320, we guaranty to have 2 columns */ + min-width: <?php echo isset($_SESSION['dol_screenwidth']) ?min(160, round($_SESSION['dol_screenwidth'] / 2 - 20)) : 150; ?>px; /* on screen < 320, we guaranty to have 2 columns */ } .thumbstat150 { flex: 1 1 110px; margin-bottom: 8px; - min-width: <?php echo isset($_SESSION['dol_screenwidth']) ?min(160, round($_SESSION['dol_screenwidth'] / 2 - 20)) : 160; ?>px; /* on screen < 320, we guaranty to have 2 columns */ - max-width: <?php echo isset($_SESSION['dol_screenwidth']) ?min(161, round($_SESSION['dol_screenwidth'] / 2 - 20)) : 161; ?>px; /* on screen < 320, we guaranty to have 2 columns */ - /* width: ...px; If I use with, there is trouble on size of flex boxes solved with min + (max that is a little bit higer than min) */ + min-width: <?php echo isset($_SESSION['dol_screenwidth']) ?min(160, round($_SESSION['dol_screenwidth'] / 2 - 20)) : 160; ?>px; /* on screen < 320, we guaranty to have 2 columns */ + max-width: <?php echo isset($_SESSION['dol_screenwidth']) ?min(161, round($_SESSION['dol_screenwidth'] / 2 - 20)) : 161; ?>px; /* on screen < 320, we guaranty to have 2 columns */ + /* width: ...px; If I use with, there is trouble on size of flex boxes solved with min + (max that is a little bit higer than min) */ } - .dashboardlineindicator { - float: left; - padding-left: 5px; - } - .boxstats { - width: 111px; - } - .boxstatsempty { - width: 111px; + .dashboardlineindicator { + float: left; + padding-left: 5px; + } + .boxstats { + width: 111px; + } + .boxstatsempty { + width: 111px; } } @@ -3945,8 +3998,8 @@ span.boxstatstext span:not(.fas) { opacity: 0.5; } span.boxstatstext { - line-height: 18px; - color: var(--colortext); + line-height: 18px; + color: var(--colortext); } span.boxstatstext img, a.dashboardlineindicatorlate img { border: 0; @@ -3984,42 +4037,42 @@ span.dashboardlineko { .dashboardlinelatecoin { float: right; position: relative; - text-align: right; - top: -27px; - right: 2px; - padding: 0px 5px 0px 5px; - border-radius: .25em; + text-align: right; + top: -27px; + right: 2px; + padding: 0px 5px 0px 5px; + border-radius: .25em; - background-color: #9f4705; + background-color: #9f4705; } .imglatecoin { - padding: 1px 3px 1px 1px; - margin-left: 4px; - margin-right: 2px; - background-color: #8c4446; - color: #FFFFFF ! important; - border-radius: .25em; + padding: 1px 3px 1px 1px; + margin-left: 4px; + margin-right: 2px; + background-color: #8c4446; + color: #FFFFFF ! important; + border-radius: .25em; display: inline-block; vertical-align: middle; } .boxtable { - margin-bottom: 25px !important; - border-bottom-width: 1px; + margin-bottom: 25px !important; + border-bottom-width: 1px; background: var(--colorbackbody); - border-top: <?php echo $borderwidth ?>px solid rgb(<?php echo $colortopbordertitle1 ?>); + border-top: <?php echo $borderwidth ?>px solid rgb(<?php echo $colortopbordertitle1 ?>); /* border-top: 2px solid var(--colorbackhmenu1) !important; */ } table.noborder.boxtable tr td { - height: unset; + height: unset; } .boxtablenotop { - border-top-width: 0 !important; + border-top-width: 0 !important; } .boxtablenobottom { - border-bottom-width: 0 !important; + border-bottom-width: 0 !important; } .boxtable .fichehalfright, .boxtable .fichehalfleft { - min-width: 275px; /* increasing this, make chart on box not side by side on laptops */ + min-width: 275px; /* increasing this, make chart on box not side by side on laptops */ } .tdboxstats { text-align: center; @@ -4029,23 +4082,23 @@ table.noborder.boxtable tr td { padding-right: 0px !important; } a.valignmiddle.dashboardlineindicator { - line-height: 30px; + line-height: 30px; } tr.box_titre { - height: 26px; + height: 26px; - /* TO MATCH BOOTSTRAP */ + /* TO MATCH BOOTSTRAP */ /*background: #ddd; color: #000 !important;*/ /* TO MATCH ELDY */ background: var(--colorbacktitle1); color: var(--colortexttitle); - font-family: <?php print $fontlist ?>, sans-serif; - font-weight: <?php echo $useboldtitle ? 'bold' : 'normal'; ?>; - border-bottom: 1px solid #FDFFFF; - white-space: nowrap; + font-family: <?php print $fontlist ?>, sans-serif; + font-weight: <?php echo $useboldtitle ? 'bold' : 'normal'; ?>; + border-bottom: 1px solid #FDFFFF; + white-space: nowrap; } tr.box_titre td.boxclose { @@ -4069,8 +4122,8 @@ img.boxhandle, img.boxclose { margin-right: 1px; } .prod_entry_mode_free, .prod_entry_mode_predef { - height: 26px !important; - vertical-align: middle; + height: 26px !important; + vertical-align: middle; } .modulebuilderbox { @@ -4095,24 +4148,24 @@ div.ok { /* Info admin */ div.info { border-<?php print $left; ?>: solid 5px #87cfd2; - padding-top: 8px; - padding-left: 10px; - padding-right: 4px; - padding-bottom: 8px; - margin: 1em 0em 1em 0em; - background: #eff8fc; - color: #558; -} - -/* Warning message */ -div.warning { - border-<?php print $left; ?>: solid 5px #f2cf87; padding-top: 8px; padding-left: 10px; padding-right: 4px; padding-bottom: 8px; margin: 1em 0em 1em 0em; - background: #fcf8e3; + background: #eff8fc; + color: #558; +} + +/* Warning message */ +div.warning { + border-<?php print $left; ?>: solid 5px #f2cf87; + padding-top: 8px; + padding-left: 10px; + padding-right: 4px; + padding-bottom: 8px; + margin: 1em 0em 1em 0em; + background: #fcf8e3; } div.warning a, div.info a, div.error a { color: var(--colortextlink); @@ -4120,7 +4173,7 @@ div.warning a, div.info a, div.error a { /* Error message */ div.error { - border-<?php print $left; ?>: solid 5px #f28787; + border-<?php print $left; ?>: solid 5px #f28787; padding-top: 8px; padding-left: 10px; padding-right: 4px; @@ -4150,13 +4203,13 @@ a.impayee:hover { font-weight: bold; color: #550000; } */ .framecontent { - width: 100%; - height: 100%; + width: 100%; + height: 100%; } .framecontent iframe { - width: 100%; - height: 100%; + width: 100%; + height: 100%; } @@ -4165,11 +4218,11 @@ a.impayee:hover { font-weight: bold; color: #550000; } */ .opened-dash-board-wrap { - margin-bottom: 25px; + margin-bottom: 25px; } div.boximport { - min-height: unset; + min-height: unset; } .product_line_stock_ok { color: #002200; } @@ -4190,11 +4243,11 @@ div.dolgraph div.legend table tbody tr { height: auto; } td.legendColorBox { padding: 2px 2px 2px 0 !important; } td.legendLabel { padding: 2px 2px 2px 0 !important; } td.legendLabel { - text-align: <?php echo $left; ?>; + text-align: <?php echo $left; ?>; } label.radioprivate { - white-space: nowrap; + white-space: nowrap; } .photo { @@ -4205,7 +4258,7 @@ label.radioprivate { margin-top: 10px; } div.divphotoref > a > .photowithmargin { /* Margin right for photo not inside a div.photoref frame only */ - margin-right: 15px; + margin-right: 15px; } .photowithborder { border: 1px solid #f0f0f0; @@ -4228,33 +4281,33 @@ div.divphotoref > a > .photowithmargin { /* Margin right for photo not inside a { content:url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/nographyet.svg', 1) ?>); display: inline-block; - opacity: 0.1; - background-repeat: no-repeat; + opacity: 0.1; + background-repeat: no-repeat; } .nographyettext { - opacity: 0.5; + opacity: 0.5; } div.titre { font-size: 1.1em; text-decoration: none; padding-top: 5px; - padding-bottom: 5px; - font-weight: 400; + padding-bottom: 5px; + font-weight: 400; } div.fiche > table.table-fiche-title:first-of-type div { - color: var(--colortexttitlenotab); - font-size: 1.05em; - /* text-transform: uppercase; */ - /* font-weight: 600; */ + color: var(--colortexttitlenotab); + font-size: 1.05em; + /* text-transform: uppercase; */ + /* font-weight: 600; */ } div.titre { - color: var(--colortexttitlenotab); + color: var(--colortexttitlenotab); } .secondary { - color: var(--colortexttitlenotab); + color: var(--colortexttitlenotab); } .tertiary { color: var(--colortexttitlenotab2); @@ -4273,11 +4326,11 @@ div.backgreypublicpayment { background-color: #f0f0f0; padding: 20px; border-bot .poweredbypublicpayment { float: right; top: 8px; - right: 8px; - position: absolute; - font-size: 0.8em; - color: #222; - opacity: 0.3; + right: 8px; + position: absolute; + font-size: 0.8em; + color: #222; + opacity: 0.3; } #dolpaymenttable { min-width: 290px; font-size: 16px; } /* Width must have min to make stripe input area visible. Lower than 320 makes input area crazy for credit card that need zip code */ #tablepublicpayment { border: 1px solid #CCCCCC !important; width: 100%; padding: 20px; } @@ -4285,7 +4338,7 @@ div.backgreypublicpayment { background-color: #f0f0f0; padding: 20px; border-bot #tablepublicpayment tr.liste_total { border-bottom: 1px solid #CCCCCC !important; } #tablepublicpayment tr.liste_total td { border-top: none; } input#cardholder-name { - font-size: 1em; + font-size: 1em; } .divmainbodylarge { margin-left: 40px; margin-right: 40px; } @@ -4293,13 +4346,13 @@ input#cardholder-name { #tablesubscribe { width: 100%; } div#card-element { - border: 1px solid #ccc; + border: 1px solid #ccc; } div#card-errors { color: #fa755a; - text-align: center; - padding-top: 3px; - max-width: 320px; + text-align: center; + padding-top: 3px; + max-width: 320px; } @@ -4358,8 +4411,8 @@ div#card-errors { /* .ui-dialog-content.ui-widget-content > object { - max-height: none; - width: auto; margin-left: auto; margin-right: auto; display: block; + max-height: none; + width: auto; margin-left: auto; margin-right: auto; display: block; } */ @@ -4369,16 +4422,16 @@ div#card-errors { /* ============================================================================== */ table.valid { - /* border-top: solid 1px #E6E6E6; */ - border-<?php print $left; ?>: solid 5px #f2cf87; - /* border-<?php print $right; ?>: solid 1px #444444; - border-bottom: solid 1px #555555; */ + /* border-top: solid 1px #E6E6E6; */ + border-<?php print $left; ?>: solid 5px #f2cf87; + /* border-<?php print $right; ?>: solid 1px #444444; + border-bottom: solid 1px #555555; */ padding-top: 8px; padding-left: 10px; padding-right: 4px; padding-bottom: 4px; margin: 0px 0px; - background: #fcf8e3; + background: #fcf8e3; } .validtitre { @@ -4392,7 +4445,7 @@ table.valid { /* For tooltip using dialog */ .ui-dialog.highlight.ui-widget.ui-widget-content.ui-front { - z-index: 3000; + z-index: 3000; } div.ui-tooltip { @@ -4423,20 +4476,20 @@ div.ui-tooltip.mytooltip { /* ============================================================================== */ /*div.divfordateinput img.ui-datepicker-trigger { - float: left; - display: inline-block; - vertical-align: middle; - padding-top: 10px; + float: left; + display: inline-block; + vertical-align: middle; + padding-top: 10px; } .hasDatepicker { - padding-bottom: 6px; + padding-bottom: 6px; }*/ .ui-datepicker-calendar .ui-state-default, .ui-datepicker-calendar .ui-widget-content .ui-state-default, .ui-datepicker-calendar .ui-widget-header .ui-state-default, .ui-datepicker-calendar .ui-button, html .ui-datepicker-calendar .ui-button.ui-state-disabled:hover, html .ui-button.ui-state-disabled:active { - border: unset; + border: unset; } img.datecallink { padding-left: 2px !important; padding-right: 2px !important; } @@ -4456,13 +4509,13 @@ img.datecallink { padding-left: 2px !important; padding-right: 2px !important; } margin-bottom: 5px; } table.dp { - width: 180px; - background-color: var(--inputbackgroundcolor); - border-top: solid 2px #DDDDDD; - border-<?php print $left; ?>: solid 2px #DDDDDD; - border-<?php print $right; ?>: solid 1px #222222; - border-bottom: solid 1px #222222; - padding: 0px; + width: 180px; + background-color: var(--inputbackgroundcolor); + border-top: solid 2px #DDDDDD; + border-<?php print $left; ?>: solid 2px #DDDDDD; + border-<?php print $right; ?>: solid 1px #222222; + border-bottom: solid 1px #222222; + padding: 0px; border-spacing: 0px; border-collapse: collapse; } @@ -4508,14 +4561,14 @@ table.dp { /* Bouton X fermer */ .dpInvisibleButtons { - border-style:none; - background-color:transparent; - padding:0px; - font-size: 0.85em; - border-width:0px; - color:#0B63A2; - vertical-align:middle; - cursor: pointer; + border-style:none; + background-color:transparent; + padding:0px; + font-size: 0.85em; + border-width:0px; + color:#0B63A2; + vertical-align:middle; + cursor: pointer; } .datenowlink { @@ -4528,15 +4581,15 @@ table.dp { /* ============================================================================== */ div.visible { - display: block; + display: block; } -div.hidden, td.hidden, img.hidden, span.hidden { - display: none; +div.hidden, td.hidden, img.hidden, span.hidden, div.showifmore { + display: none; } tr.visible { - display: block; + display: block; } @@ -4545,10 +4598,10 @@ tr.visible { /* ============================================================================== */ .exampleapachesetup { - overflow-y: auto; - height: 100px; - font-size: 0.8em; - border: 1px solid #aaa; + overflow-y: auto; + height: 100px; + font-size: 0.8em; + border: 1px solid #aaa; } span[phptag] { @@ -4556,16 +4609,21 @@ span[phptag] { } .nobordertransp { - border: 0px; - background-color: transparent; - background-image: none; + border: 0px; + background-color: transparent; + background-image: none; } .bordertransp { - background-color: transparent; - background-image: none; - border: none; + background-color: transparent; + background-image: none; + border: none; font-weight: normal; } +.websitebar .button.bordertransp { + color: unset; + text-decoration: unset !important; +} + .websitebar { border-bottom: 1px solid #ccc; background: #e6e6e6; @@ -4580,9 +4638,9 @@ span[phptag] { { padding: 4px 5px 4px 5px !important; margin: 2px 4px 2px 4px !important; - line-height: normal; - background: #f5f5f5 !important; - border: 1px solid #ccc !important; + line-height: normal; + background: #f5f5f5 !important; + border: 1px solid #ccc !important; } .websiteselection { /* display: inline-block; */ @@ -4599,9 +4657,9 @@ span[phptag] { padding-bottom: 3px; */ } .websiteinputurl { - display: inline-block; - vertical-align: top; - line-height: 28px; + display: inline-block; + vertical-align: top; + line-height: 28px; } .websiteiframenoborder { border: 0px; @@ -4617,9 +4675,9 @@ span.websitebuttonsitepreviewdisabled img, a.websitebuttonsitepreviewdisabled im opacity: 0.2; } .websitehelp { - vertical-align: middle; - float: right; - padding-top: 8px; + vertical-align: middle; + float: right; + padding-top: 8px; } .websiteselectionsection { border-left: 1px solid #bbb; @@ -4629,7 +4687,11 @@ span.websitebuttonsitepreviewdisabled img, a.websitebuttonsitepreviewdisabled im margin-right: 5px; } .websitebar input#previewpageurl { - line-height: 1em; + line-height: 1em; +} + +#divbodywebsite section p { + margin: unset; } @@ -4639,7 +4701,7 @@ span.websitebuttonsitepreviewdisabled img, a.websitebuttonsitepreviewdisabled im /* ============================================================================== */ .dayevent .tagtr:first-of-type { - height: 24px; + height: 24px; } .agendacell { height: 60px; } @@ -4665,10 +4727,10 @@ table.cal_month td { padding-left: 1px !important; padding-right: 1px !important .cal_peruser { padding-top: 0 !important; padding-bottom: 0 !important; padding-<?php print $left; ?>: 1px !important; padding-<?php print $right; ?>: 1px !important; } .cal_impair { background: linear-gradient(bottom, var(--colorbacklinepair1) 85%, var(--colorbacklinepair2) 100%); - background: -o-linear-gradient(bottom, var(--colorbacklinepair1) 85%, var(--colorbacklinepair2) 100%); - background: -moz-linear-gradient(bottom, var(--colorbacklinepair1) 85%, var(--colorbacklinepair2) 100%); - background: -webkit-linear-gradient(bottom, var(--colorbacklinepair1) 85%, var(--colorbacklinepair2) 100%); - /* background: -ms-linear-gradient(bottom, var(--colorbacklinepair1) 85%, var(--colorbacklinepair2) 100%); */ + background: -o-linear-gradient(bottom, var(--colorbacklinepair1) 85%, var(--colorbacklinepair2) 100%); + background: -moz-linear-gradient(bottom, var(--colorbacklinepair1) 85%, var(--colorbacklinepair2) 100%); + background: -webkit-linear-gradient(bottom, var(--colorbacklinepair1) 85%, var(--colorbacklinepair2) 100%); + /* background: -ms-linear-gradient(bottom, var(--colorbacklinepair1) 85%, var(--colorbacklinepair2) 100%); */ } .cal_today_peruser_impair { background: #F8F8F0; } .peruser_busy { } @@ -4689,7 +4751,7 @@ table.cal_event td.cal_event_right { padding: 4px 4px !important; } table.cal_month tr td table.nobordernopadding tr td { padding: 0 2px 0 2px; } table.cal_month tr.liste_titre td.tdfordaytitle { min-width: 120px; } a.dayevent-aday { - padding-left: 8px; + padding-left: 8px; } .calendarviewcontainertr { height: 100px; } @@ -4708,28 +4770,28 @@ td.cal_other_month { .ui-autocomplete-loading { background: white url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/working.gif', 1) ?>) right center no-repeat; } .ui-autocomplete { - position:absolute; - width:auto; - font-size: 1.0em; - background-color: var(--inputbackgroundcolor); - border:1px solid #888; - margin:0px; + position:absolute; + width:auto; + font-size: 1.0em; + background-color: var(--inputbackgroundcolor); + border:1px solid #888; + margin:0px; /* padding:0px; This make combo crazy */ - } + } .ui-autocomplete ul { - list-style-type:none; - margin:0px; - padding:0px; - } + list-style-type:none; + margin:0px; + padding:0px; + } .ui-autocomplete ul li.selected { background-color: var(--inputbackgroundcolor);} .ui-autocomplete ul li { - list-style-type:none; - display:block; - margin:0; - padding:2px; - height:18px; - cursor:pointer; - } + list-style-type:none; + display:block; + margin:0; + padding:2px; + height:18px; + cursor:pointer; + } /* ============================================================================== */ @@ -4905,22 +4967,22 @@ A.none, A.none:active, A.none:visited, A.none:hover { /* Style to overwrites JQuery styles */ .ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { - border: 1px solid #888; - background: var(--colorbacktitle1); - color: unset; + border: 1px solid #888; + background: var(--colorbacktitle1); + color: unset; } .ui-menu .ui-menu-item a { - text-decoration:none; - display:block; - padding:.2em .4em; - line-height:1.5; - font-weight: normal; - font-family:<?php echo $fontlist; ?>; - font-size:1em; + text-decoration:none; + display:block; + padding:.2em .4em; + line-height:1.5; + font-weight: normal; + font-family:<?php echo $fontlist; ?>; + font-size:1em; } .ui-widget { - font-family:<?php echo $fontlist; ?>; + font-family:<?php echo $fontlist; ?>; } /* .ui-button { margin-left: -2px; <?php print (preg_match('/chrome/', $conf->browser->name) ? 'padding-top: 1px;' : ''); ?> } */ .ui-button { margin-left: -2px; } @@ -4928,7 +4990,7 @@ A.none, A.none:active, A.none:visited, A.none:hover { .ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: 2px 0px 6px 0px; } .ui-button-text { - line-height: 1em !important; + line-height: 1em !important; } .ui-autocomplete-input { margin: 0; padding: 4px; } @@ -4938,28 +5000,28 @@ A.none, A.none:active, A.none:visited, A.none:hover { /* ============================================================================== */ body.cke_show_borders { - margin: 5px !important; + margin: 5px !important; } .cke_dialog { - border: 1px #bbb solid ! important; + border: 1px #bbb solid ! important; } /*.cke_editor table, .cke_editor tr, .cke_editor td { - border: 0px solid #FF0000 !important; + border: 0px solid #FF0000 !important; } span.cke_skin_kama { padding: 0 !important; }*/ .cke_wrapper { padding: 4px !important; } a.cke_dialog_ui_button { - font-family: <?php print $fontlist ?> !important; + font-family: <?php print $fontlist ?> !important; background-image: url(<?php echo $img_button ?>) !important; background-position: bottom !important; - border: 1px solid #C0C0C0 !important; + border: 1px solid #C0C0C0 !important; -webkit-border-radius:0px 5px 0px 5px !important; border-radius:0px 5px 0px 5px !important; - -webkit-box-shadow: 3px 3px 4px #DDD !important; - box-shadow: 3px 3px 4px #DDD !important; + -webkit-box-shadow: 3px 3px 4px #DDD !important; + box-shadow: 3px 3px 4px #DDD !important; } .cke_dialog_ui_hbox_last { @@ -4973,8 +5035,8 @@ a.cke_dialog_ui_button } */ a.cke_dialog_ui_button_ok span { - text-shadow: none !important; - color: #333 !important; + text-shadow: none !important; + color: #333 !important; } @@ -4982,28 +5044,28 @@ a.cke_dialog_ui_button_ok span { /* ACE editor */ /* ============================================================================== */ .ace_editor { - border: 1px solid #ddd; + border: 1px solid #ddd; margin: 0; } .aceeditorstatusbar { - margin: 0; - padding: 0; - padding-<?php echo $left; ?>: 10px; - left: 0; - right: 0; - bottom: 0; - background-color: #ebebeb; - height: 28px; - line-height: 2.2em; + margin: 0; + padding: 0; + padding-<?php echo $left; ?>: 10px; + left: 0; + right: 0; + bottom: 0; + background-color: #ebebeb; + height: 28px; + line-height: 2.2em; } .ace_status-indicator { - color: gray; - position: relative; - right: 0; - border-left: 1px solid; + color: gray; + position: relative; + right: 0; + border-left: 1px solid; } pre#editfilecontentaceeditorid { - margin-top: 5px; + margin-top: 5px; } @@ -5012,7 +5074,7 @@ pre#editfilecontentaceeditorid { /* ============================================================================== */ .template-upload { - height: 72px !important; + height: 72px !important; } @@ -5033,32 +5095,32 @@ pre#editfilecontentaceeditorid { /* ============================================================================== */ #types .btn { - cursor: pointer; + cursor: pointer; } #types .btn-primary { - font-weight: bold; + font-weight: bold; } #types form { - padding: 20px; + padding: 20px; } #types label { - display:inline-block; - width:100px; - margin-right: 20px; - padding: 4px; - text-align: right; - vertical-align: top; + display:inline-block; + width:100px; + margin-right: 20px; + padding: 4px; + text-align: right; + vertical-align: top; } #types input.text, #types textarea { - width: 400px; + width: 400px; } #types textarea { - height: 100px; + height: 100px; } @@ -5070,55 +5132,55 @@ pre#editfilecontentaceeditorid { box-sizing:border-box; } #comment .comment { - border-radius:7px; - margin-bottom:10px; - overflow:hidden; + border-radius:7px; + margin-bottom:10px; + overflow:hidden; } #comment .comment-table { - display:table; - height:100%; + display:table; + height:100%; } #comment .comment-cell { - display:table-cell; + display:table-cell; } #comment .comment-info { - font-size:0.8em; - border-right:1px solid #dedede; - margin-right:10px; - width:160px; - text-align:center; - background:rgba(255,255,255,0.5); - vertical-align:middle; - padding:10px 2px; + font-size:0.8em; + border-right:1px solid #dedede; + margin-right:10px; + width:160px; + text-align:center; + background:rgba(255,255,255,0.5); + vertical-align:middle; + padding:10px 2px; } #comment .comment-info a { - color:inherit; + color:inherit; } #comment .comment-right { - vertical-align:top; + vertical-align:top; } #comment .comment-description { - padding:10px; - vertical-align:top; + padding:10px; + vertical-align:top; } #comment .comment-delete { - width: 100px; - text-align:center; - vertical-align:middle; + width: 100px; + text-align:center; + vertical-align:middle; } #comment .comment-delete:hover { - background:rgba(250,20,20,0.8); + background:rgba(250,20,20,0.8); } #comment .comment-edit { - width: 100px; - text-align:center; - vertical-align:middle; + width: 100px; + text-align:center; + vertical-align:middle; } #comment .comment-edit:hover { - background:rgba(0,184,148,0.8); + background:rgba(0,184,148,0.8); } #comment textarea { - width: 100%; + width: 100%; } @@ -5132,7 +5194,7 @@ div.scroll2 { } div#GanttChartDIVglisthead, div#GanttChartDIVgcharthead { - line-height: 2; + line-height: 2; } .gtaskname div, .gtaskname, .gstartdate div, .gstartdate, .genddate div, .genddate { @@ -5145,50 +5207,50 @@ div.gantt, .gtaskheading, .gmajorheading, .gminorheading, .gminorheadingwkend { color: #000 !important; } div.gTaskInfo { - background: #f0f0f0 !important; + background: #f0f0f0 !important; } .gtaskblue { background: rgb(108,152,185) !important; } .gtaskgreen { - background: rgb(160,173,58) !important; + background: rgb(160,173,58) !important; } td.gtaskname { - overflow: hidden; - text-overflow: ellipsis; + overflow: hidden; + text-overflow: ellipsis; } td.gminorheadingwkend { - color: #888 !important; + color: #888 !important; } td.gminorheading { - color: #666 !important; + color: #666 !important; } .glistlbl, .glistgrid { width: 582px !important; } /*.gtaskname div, .gtaskname { - min-width: 250px !important; - max-width: 250px !important; - width: 250px !important; + min-width: 250px !important; + max-width: 250px !important; + width: 250px !important; }*/ .gtaskname div, .gtaskname { - min-width: 250px !important; - max-width: unset !important; - width: unset !important; + min-width: 250px !important; + max-width: unset !important; + width: unset !important; } .gpccomplete div, .gpccomplete { - min-width: 40px !important; - max-width: 40px !important; - width: 40px !important; + min-width: 40px !important; + max-width: 40px !important; + width: 40px !important; } td.gtaskheading.gstartdate, td.gtaskheading.genddate { - white-space: break-spaces; + white-space: break-spaces; } .gtasktableh tr:nth-child(2) td:nth-child(2), .gtasktableh tr:nth-child(2) td:nth-child(3), .gtasktableh tr:nth-child(2) td:nth-child(4), .gtasktableh tr:nth-child(2) td:nth-child(5), .gtasktableh tr:nth-child(2) td:nth-child(6), .gtasktableh tr:nth-child(2) td:nth-child(7) { - color: transparent !important; - border-left: none; - border-right: none; - border-top: none; + color: transparent !important; + border-left: none; + border-right: none; + border-top: none; } /* ============================================================================== */ @@ -5212,25 +5274,25 @@ td.gtaskheading.gstartdate, td.gtaskheading.genddate { } div.filedirelem { - position: relative; - display: block; - text-decoration: none; + position: relative; + display: block; + text-decoration: none; } ul.filedirelem { - padding: 2px; - margin: 0 5px 5px 5px; + padding: 2px; + margin: 0 5px 5px 5px; } ul.filedirelem li { - list-style: none; - padding: 2px; - margin: 0 10px 20px 10px; - width: 160px; - height: 120px; - text-align: center; - display: block; - float: <?php print $left; ?>; - border: solid 1px #DDDDDD; + list-style: none; + padding: 2px; + margin: 0 10px 20px 10px; + width: 160px; + height: 120px; + text-align: center; + display: block; + float: <?php print $left; ?>; + border: solid 1px #DDDDDD; } ul.ecmjqft { @@ -5261,7 +5323,7 @@ ul.ecmjqft a:active { font-weight: bold !important; } ul.ecmjqft a:hover { - text-decoration: underline; + text-decoration: underline; } div.ecmjqft { vertical-align: middle; @@ -5275,16 +5337,16 @@ div.ecmjqft { min-height: 40px; } #ecm-layout-north div.attachareaformuserfileecm { - padding-bottom: 0px; + padding-bottom: 0px; } div#ecm-layout-west { - width: 380px; - vertical-align: top; + width: 380px; + vertical-align: top; } div#ecm-layout-center { - width: calc(100% - 390px); - vertical-align: top; - float: right; + width: calc(100% - 390px); + vertical-align: top; + float: right; } .ecmjqft LI.directory { font-weight:normal; background: url(<?php echo dol_buildpath($path.'/theme/common/treemenu/folder2.png', 1); ?>) left top no-repeat; } @@ -5314,14 +5376,14 @@ div#ecm-layout-center { font-weight: normal; } .jnotify-container .jnotify-notification-warning .jnotify-close, .jnotify-container .jnotify-notification-warning .jnotify-message { - color: #a28918 !important; + color: #a28918 !important; } /* use or not ? */ div.jnotify-background { opacity : 0.95 !important; - -webkit-box-shadow: 2px 2px 4px #888 !important; - box-shadow: 2px 2px 4px #888 !important; + -webkit-box-shadow: 2px 2px 4px #888 !important; + box-shadow: 2px 2px 4px #888 !important; } /* ============================================================================== */ @@ -5384,7 +5446,7 @@ table.dataTable tr.odd td.sorting_1, table.dataTable tr.even td.sorting_1 { .paginate_button { font-weight: normal !important; - text-decoration: none !important; + text-decoration: none !important; } .paging_full_numbers { height: inherit !important; @@ -5397,7 +5459,7 @@ table.dataTable tr.odd td.sorting_1, table.dataTable tr.even td.sorting_1 { border-radius: inherit !important; } .paging_full_numbers a.paginate_button_disabled:hover, .paging_full_numbers a.disabled:hover { - background-color: var(--colorbackbody) !important; + background-color: var(--colorbackbody) !important; } .paginate_button, .paginate_active { border: 1px solid #ddd !important; @@ -5436,23 +5498,23 @@ span.select2-selection--single.flat[aria-disabled="true"] span.select2-selection } span#select2-taskid-container[title^='--'] { - opacity: 0.3; + opacity: 0.3; } .select2-container--default .select2-results__option--highlighted[aria-selected] { - background-color: rgb(<?php echo $colorbackhmenu1 ?>); - color: var(--colortextbackhmenu); + background-color: rgb(<?php echo $colorbackhmenu1 ?>); + color: var(--colortextbackhmenu); } .select2-container--default .select2-results__option--highlighted[aria-selected] span { - color: #fff !important; + color: #fff !important; } span.select2.select2-container.select2-container--default { <?php if (empty($conf->global->THEME_SHOW_BORDER_ON_INPUT)) { ?> - border-left: none; - border-top: none; - border-right: none; - <?php } ?> + border-left: none; + border-top: none; + border-right: none; + <?php } ?> } input.select2-input { border-bottom: none ! important; @@ -5472,36 +5534,36 @@ input.select2-input { border: none; } .select2-container--focus span.select2-selection.select2-selection--single { - border-bottom: 1px solid #666 !important; + border-bottom: 1px solid #666 !important; } .blockvmenusearch .select2-container--default .select2-selection--single, .blockvmenubookmarks .select2-container--default .select2-selection--single { - background-color: var(--colorbackvmenu1); + background-color: var(--colorbackvmenu1); } .select2-container--default .select2-selection--single { - background-color: var(--colorbackbody); + background-color: var(--colorbackbody); } #blockvmenusearch .select2-container--default .select2-selection--single .select2-selection__placeholder { - color: var(--colortextbackvmenu); + color: var(--colortextbackvmenu); } .select2-container--default .select2-selection--single .select2-selection__rendered { - color: var(--colortext); - /* background-color: var(--colorbackvmenu1); */ + color: var(--colortext); + /* background-color: var(--colorbackvmenu1); */ } .select2-default { - color: #999 !important; + color: #999 !important; } .select2-choice, .select2-container .select2-choice { border-bottom: solid 1px rgba(0,0,0,.4); } .select2-container .select2-choice > .select2-chosen { - margin-right: 23px; + margin-right: 23px; } .select2-container .select2-choice .select2-arrow { border-radius: 0; - background: transparent; + background: transparent; } .select2-container-multi .select2-choices { background-image: none; @@ -5528,7 +5590,7 @@ input.select2-input { box-shadow: none !important; } .select2-container--open .select2-dropdown--above { - border-bottom: solid 1px var(--inputbordercolor); + border-bottom: solid 1px var(--inputbordercolor); } .select2-drop.select2-drop-above.select2-drop-active { border-top: 1px solid #ccc; @@ -5675,36 +5737,36 @@ a span.select2-chosen } .select2-container--default .select2-results>.select2-results__options{ - max-height: 400px; + max-height: 400px; } /* Special case for the select2 add widget */ #addbox .select2-container .select2-choice > .select2-chosen, #actionbookmark .select2-container .select2-choice > .select2-chosen { - text-align: <?php echo $left; ?>; - opacity: 0.4; + text-align: <?php echo $left; ?>; + opacity: 0.4; } .select2-container--default .select2-selection--single .select2-selection__placeholder { color: var(--colortext); opacity: 0.4; } span#select2-boxbookmark-container, span#select2-boxcombo-container { - text-align: <?php echo $left; ?>; + text-align: <?php echo $left; ?>; } span#select2-boxbookmark-container { - opacity: 0.4; + opacity: 0.4; } .select2-container .select2-selection--single .select2-selection__rendered { padding-left: 6px; } /* Style used before the select2 js is executed on boxcombo */ #boxbookmark.boxcombo, #boxcombo.boxcombo { - text-align: left; - opacity: 0.4; - border-bottom: solid 1px rgba(0,0,0,.4) !important; - height: 26px; - line-height: 24px; - padding: 0 0 2px 0; - vertical-align: top; + text-align: left; + opacity: 0.4; + border-bottom: solid 1px rgba(0,0,0,.4) !important; + height: 26px; + line-height: 24px; + padding: 0 0 2px 0; + vertical-align: top; } /* To emulate select 2 style */ @@ -5758,7 +5820,7 @@ span#select2-boxbookmark-container { border-radius: 5px !important; box-shadow: none; -webkit-box-shadow: none !important; - box-shadow: none !important; + box-shadow: none !important; } span.noborderoncategories a, li.noborderoncategories a { line-height: normal; @@ -5848,9 +5910,9 @@ span.noborderoncategories { } .multi-select-menuitem { - clear: both; - float: left; - padding-left: 5px + clear: both; + float: left; + padding-left: 5px } @@ -5859,52 +5921,52 @@ span.noborderoncategories { /* ============================================================================== */ ul.ulselectedfields { - z-index: 95; /* To have the select box appears on first plan even when near buttons are decorated by jmobile */ + z-index: 95; /* To have the select box appears on first plan even when near buttons are decorated by jmobile */ } dl.dropdown { - margin:0px; + margin:0px; margin-left: 2px; - margin-right: 2px; - padding:0px; - vertical-align: middle; - display: inline-block; + margin-right: 2px; + padding:0px; + vertical-align: middle; + display: inline-block; } .dropdown dd, .dropdown dt { - margin:0px; - padding:0px; + margin:0px; + padding:0px; } .dropdown ul { - margin: -1px 0 0 0; - text-align: <?php echo $left; ?>; + margin: -1px 0 0 0; + text-align: <?php echo $left; ?>; } .dropdown dd { - position:relative; + position:relative; } .dropdown dt a { - display:block; - overflow: hidden; - border:0; + display:block; + overflow: hidden; + border:0; } .dropdown dt a span, .multiSel span { - cursor:pointer; - display:inline-block; - padding: 0 3px 2px 0; + cursor:pointer; + display:inline-block; + padding: 0 3px 2px 0; } .dropdown span.value { - display:none; + display:none; } .dropdown dd ul { - background-color: var(--inputbackgroundcolor); - box-shadow: 1px 1px 10px #aaa; - display:none; - <?php echo $right; ?>:0px; /* pop is align on right */ - padding: 0 0 0 0; - position:absolute; - top:2px; - list-style:none; - max-height: 264px; - overflow: auto; - border-radius: 2px; + background-color: var(--inputbackgroundcolor); + box-shadow: 1px 1px 10px #aaa; + display:none; + <?php echo $right; ?>:0px; /* pop is align on right */ + padding: 0 0 0 0; + position:absolute; + top:2px; + list-style:none; + max-height: 264px; + overflow: auto; + border-radius: 2px; } .dropdown dd ul li { white-space: nowrap; @@ -5917,22 +5979,22 @@ dl.dropdown { background: #eee; } .dropdown dd ul li input[type="checkbox"] { - margin-<?php echo $right; ?>: 3px; + margin-<?php echo $right; ?>: 3px; } .dropdown dd ul li a, .dropdown dd ul li span { - padding: 3px; - display: block; + padding: 3px; + display: block; } .dropdown dd ul li span { color: #888; } /*.dropdown dd ul li a:hover { - background-color: var(--inputbackgroundcolor); + background-color: var(--inputbackgroundcolor); }*/ dd.dropdowndd ul li { - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; } @@ -5954,11 +6016,11 @@ dd.dropdowndd ul li { /* ============================================================================== */ .searchpage .tagtr .tagtd { - padding-bottom: 3px; + padding-bottom: 3px; } .searchpage .tagtr .tagtd .button { background: unset; - border: unset; + border: unset; } li.ui-li-divider .ui-link { @@ -5994,16 +6056,16 @@ a.ui-link, a.ui-link:hover, .ui-btn:hover, span.ui-btn-text:hover, span.ui-btn-i padding-left: 30px; } .ui-select .ui-btn-icon-right .ui-icon { - right: 8px; + right: 8px; } .ui-btn-icon-left > .ui-btn-inner > .ui-icon, .ui-btn-icon-right > .ui-btn-inner > .ui-icon { - margin-top: -10px; + margin-top: -10px; } select { - /* display: inline-block; */ /* We can't set this. This disable ability to make */ - overflow:hidden; - white-space: nowrap; /* Enabling this make behaviour strange when selecting the empty value if this empty value is '' instead of '&nbsp;' */ - text-overflow: ellipsis; + /* display: inline-block; */ /* We can't set this. This disable ability to make */ + overflow:hidden; + white-space: nowrap; /* Enabling this make behaviour strange when selecting the empty value if this empty value is '' instead of '&nbsp;' */ + text-overflow: ellipsis; } .fiche .ui-controlgroup { margin: 0px; @@ -6086,40 +6148,40 @@ ul.ulmenu { /* Style for first level menu with jmobile */ .ui-li .ui-btn-inner a.ui-link-inherit, .ui-li-static.ui-li { - padding: 1em 15px; - display: block; + padding: 1em 15px; + display: block; } .ui-btn-up-c { font-weight: normal; } .ui-focus, .ui-btn:focus { - -webkit-box-shadow: none; - box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; } .ui-bar-b { - /*border: 1px solid #888;*/ - border: none; - background: none; - text-shadow: none; - color: var(--colortexttitlenotab) !important; + /*border: 1px solid #888;*/ + border: none; + background: none; + text-shadow: none; + color: var(--colortexttitlenotab) !important; } .ui-bar-b, .lilevel0 { - background-repeat: repeat-x; - border: none; - background: none; - text-shadow: none; - color: var(--colortexttitlenotab) !important; + background-repeat: repeat-x; + border: none; + background: none; + text-shadow: none; + color: var(--colortexttitlenotab) !important; } .alilevel0 { font-weight: normal !important; } .ui-li.ui-last-child, .ui-li.ui-field-contain.ui-last-child { - border-bottom-width: 0px !important; + border-bottom-width: 0px !important; } .alilevel0 { - color: var(--colortexttitle) !important; - background: #f8f8f8 + color: var(--colortexttitle) !important; + background: #f8f8f8 } .ulmenu { box-shadow: none !important; @@ -6147,11 +6209,11 @@ div.tabsElem a.tab { background: transparent; } .alilevel1 { - color: var(--colortexttitlenotab) !important; + color: var(--colortexttitlenotab) !important; } .lilevel1 { - border-top: 2px solid #444; - background: #fff ! important; + border-top: 2px solid #444; + background: #fff ! important; } .lilevel1 div div a { font-weight: bold !important; @@ -6159,7 +6221,7 @@ div.tabsElem a.tab { .lilevel2 { padding-left: 22px; - background: #fff ! important; + background: #fff ! important; } .lilevel3 { @@ -6169,12 +6231,12 @@ div.tabsElem a.tab { .lilevel4 { padding-left: 66px; - background: #fff ! important; + background: #fff ! important; } .lilevel5 { padding-left: 88px; - background: #fff ! important; + background: #fff ! important; } @@ -6208,14 +6270,14 @@ div.tabsElem a.tab { color: #6d3f6d; } .menu li.menu_choix1 { - padding-top: 6px; - padding-right: 10px; - padding-bottom: 2px; + padding-top: 6px; + padding-right: 10px; + padding-bottom: 2px; } .menu li.menu_choix2 { - padding-top: 6px; - padding-right: 10px; - padding-bottom: 2px; + padding-top: 6px; + padding-right: 10px; + padding-bottom: 2px; } @media only screen and (max-width: 767px) { @@ -6224,13 +6286,13 @@ div.tabsElem a.tab { height: 30px; padding-left: 40px; } - .menu li.menu_choix1, .menu li.menu_choix2 { - padding-left: 4px; - padding-right: 0; - } - .liste_articles { - margin-right: 0 !important; - } + .menu li.menu_choix1, .menu li.menu_choix2 { + padding-left: 4px; + padding-right: 0; + } + .liste_articles { + margin-right: 0 !important; + } } @@ -6258,7 +6320,7 @@ div.tabsElem a.tab { .ticketpublicarea { margin-left: 15%; - margin-right: 15%; + margin-right: 15%; } .publicnewticketform { /* margin-top: 25px !important; */ @@ -6296,11 +6358,11 @@ div.tabsElem a.tab { } @media only screen and (min-width: 1170px) { #cd-timeline { - margin-bottom: 3em; + margin-bottom: 3em; } #cd-timeline::before { - left: 50%; - margin-left: -2px; + left: 50%; + margin-left: -2px; } } @@ -6321,13 +6383,13 @@ div.tabsElem a.tab { } @media only screen and (min-width: 1170px) { .cd-timeline-block { - margin: 4em 0; + margin: 4em 0; } .cd-timeline-block:first-child { - margin-top: 0; + margin-top: 0; } .cd-timeline-block:last-child { - margin-bottom: 0; + margin-bottom: 0; } } @@ -6362,80 +6424,80 @@ div.tabsElem a.tab { } @media only screen and (min-width: 1170px) { .cd-timeline-img { - width: 60px; - height: 60px; - left: 50%; - margin-left: -30px; - /* Force Hardware Acceleration in WebKit */ - -webkit-transform: translateZ(0); - -webkit-backface-visibility: hidden; + width: 60px; + height: 60px; + left: 50%; + margin-left: -30px; + /* Force Hardware Acceleration in WebKit */ + -webkit-transform: translateZ(0); + -webkit-backface-visibility: hidden; } .cssanimations .cd-timeline-img.is-hidden { - visibility: hidden; + visibility: hidden; } .cssanimations .cd-timeline-img.bounce-in { - visibility: visible; - -webkit-animation: cd-bounce-1 0.6s; - -moz-animation: cd-bounce-1 0.6s; - animation: cd-bounce-1 0.6s; + visibility: visible; + -webkit-animation: cd-bounce-1 0.6s; + -moz-animation: cd-bounce-1 0.6s; + animation: cd-bounce-1 0.6s; } } @-webkit-keyframes cd-bounce-1 { 0% { - opacity: 0; - -webkit-transform: scale(0.5); + opacity: 0; + -webkit-transform: scale(0.5); } 60% { - opacity: 1; - -webkit-transform: scale(1.2); + opacity: 1; + -webkit-transform: scale(1.2); } 100% { - -webkit-transform: scale(1); + -webkit-transform: scale(1); } } @-moz-keyframes cd-bounce-1 { 0% { - opacity: 0; - -moz-transform: scale(0.5); + opacity: 0; + -moz-transform: scale(0.5); } 60% { - opacity: 1; - -moz-transform: scale(1.2); + opacity: 1; + -moz-transform: scale(1.2); } 100% { - -moz-transform: scale(1); + -moz-transform: scale(1); } } @keyframes cd-bounce-1 { 0% { - opacity: 0; - -webkit-transform: scale(0.5); - -moz-transform: scale(0.5); - -ms-transform: scale(0.5); - -o-transform: scale(0.5); - transform: scale(0.5); + opacity: 0; + -webkit-transform: scale(0.5); + -moz-transform: scale(0.5); + -ms-transform: scale(0.5); + -o-transform: scale(0.5); + transform: scale(0.5); } 60% { - opacity: 1; - -webkit-transform: scale(1.2); - -moz-transform: scale(1.2); - -ms-transform: scale(1.2); - -o-transform: scale(1.2); - transform: scale(1.2); + opacity: 1; + -webkit-transform: scale(1.2); + -moz-transform: scale(1.2); + -ms-transform: scale(1.2); + -o-transform: scale(1.2); + transform: scale(1.2); } 100% { - -webkit-transform: scale(1); - -moz-transform: scale(1); - -ms-transform: scale(1); - -o-transform: scale(1); - transform: scale(1); + -webkit-transform: scale(1); + -moz-transform: scale(1); + -ms-transform: scale(1); + -o-transform: scale(1); + transform: scale(1); } } .cd-timeline-content { @@ -6487,58 +6549,58 @@ div.tabsElem a.tab { } @media only screen and (min-width: 768px) { .cd-timeline-content h2 { - font-size: 20px; - font-size: 1.25rem; + font-size: 20px; + font-size: 1.25rem; } .cd-timeline-content { - font-size: 16px; - font-size: 1rem; + font-size: 16px; + font-size: 1rem; } .cd-timeline-content .cd-read-more, .cd-timeline-content .cd-date { - font-size: 14px; - font-size: 0.875rem; + font-size: 14px; + font-size: 0.875rem; } } @media only screen and (min-width: 1170px) { .cd-timeline-content { - margin-left: 0; - padding: 1.6em; - width: 43%; + margin-left: 0; + padding: 1.6em; + width: 43%; } .cd-timeline-content::before { - top: 24px; - left: 100%; - border-color: transparent; - border-left-color: white; + top: 24px; + left: 100%; + border-color: transparent; + border-left-color: white; } .cd-timeline-content .cd-read-more { - float: left; + float: left; } .cd-timeline-content .cd-date { - position: absolute; - width: 55%; - left: 115%; - top: 6px; - font-size: 16px; - font-size: 1rem; + position: absolute; + width: 55%; + left: 115%; + top: 6px; + font-size: 16px; + font-size: 1rem; } .cd-timeline-block:nth-child(even) .cd-timeline-content { - float: right; + float: right; } .cd-timeline-block:nth-child(even) .cd-timeline-content::before { - top: 24px; - left: auto; - right: 100%; - border-color: transparent; - border-right-color: white; + top: 24px; + left: auto; + right: 100%; + border-color: transparent; + border-right-color: white; } .cd-timeline-block:nth-child(even) .cd-timeline-content .cd-read-more { - float: right; + float: right; } .cd-timeline-block:nth-child(even) .cd-timeline-content .cd-date { - left: auto; - right: 115%; - text-align: right; + left: auto; + right: 115%; + text-align: right; } } @@ -6552,21 +6614,21 @@ div.phpdebugbar * { font-weight: unset; } span.phpdebugbar-tooltip.phpdebugbar-tooltip-extra-wide, span.phpdebugbar-tooltip.phpdebugbar-tooltip-wide { - width: 250px !important; + width: 250px !important; } .phpdebugbar-indicator span.phpdebugbar-tooltip { - opacity: .95 !important; + opacity: .95 !important; } a.phpdebugbar-tab.phpdebugbar-active { background-image: unset !important; } .phpdebugbar-fa-tags:before { - content: "\f121"; - font-weight: 600 !important; + content: "\f121"; + font-weight: 600 !important; } .phpdebugbar-fa-tasks:before { - content: "\f550"; - font-weight: 600 !important; + content: "\f550"; + font-weight: 600 !important; } .phpdebugbar-fa-tags, .phpdebugbar-fa-tasks, .phpdebugbar-indicator .fa { font-family: "Font Awesome 5 Free"; @@ -6595,10 +6657,10 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before /* ============================================================================== */ .dol-xaxis-vertical .flot-x-axis .flot-tick-label.tickLabel { - text-orientation: sideways; - font-weight: 400; - writing-mode: vertical-rl; - white-space: nowrap; + text-orientation: sideways; + font-weight: 400; + writing-mode: vertical-rl; + white-space: nowrap; } @@ -6632,14 +6694,14 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before width: <?php print dol_size(350, 'width'); ?>px; } - div.tabBar { - padding-left: 0px; - padding-right: 0px; - -webkit-border-radius: 0; - border-radius: 0px; - border-right: none; - border-left: none; - } + div.tabBar { + padding-left: 0px; + padding-right: 0px; + -webkit-border-radius: 0; + border-radius: 0px; + border-right: none; + border-left: none; + } } @media only screen and (max-width: 1024px) @@ -6658,27 +6720,27 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before @media only screen and (max-width: <?php echo empty($conf->global->THEME_ELDY_WITDHOFFSET_FOR_REDUC1) ? round($nbtopmenuentries * 90, 0) + 340 : $conf->global->THEME_ELDY_WITDHOFFSET_FOR_REDUC1; ?>px) /* reduction 1 */ { div.tmenucenter { - width: <?php echo round(52); ?>px; /* size of viewport */ - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - color: var(--colortextbackhmenu); + width: <?php echo round(52); ?>px; /* size of viewport */ + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: var(--colortextbackhmenu); } .mainmenuaspan { - font-size: 0.9em; - padding-right: 0; - } - .topmenuimage { - background-size: 22px auto; - margin-top: 0px; + font-size: 0.9em; + padding-right: 0; + } + .topmenuimage { + background-size: 22px auto; + margin-top: 0px; } - li.tmenu, li.tmenusel { - min-width: 36px; - } - div.mainmenu { - min-width: auto; - } + li.tmenu, li.tmenusel { + min-width: 36px; + } + div.mainmenu { + min-width: auto; + } div.tmenuleft { display: none; } @@ -6697,21 +6759,21 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before height: 23px; } div.tmenucenter { - max-width: <?php echo round(26); ?>px; /* size of viewport */ - text-overflow: clip; + max-width: <?php echo round(26); ?>px; /* size of viewport */ + text-overflow: clip; } span.mainmenuaspan { - margin-left: 1px; + margin-left: 1px; } .mainmenuaspan { - font-size: 0.9em; - padding-left: 0; - padding-right: 0; - } - .topmenuimage { - background-size: 20px auto; - margin-top: 2px; - left: 4px; + font-size: 0.9em; + padding-left: 0; + padding-right: 0; + } + .topmenuimage { + background-size: 20px auto; + margin-top: 2px; + left: 4px; } .dropdown dd ul { @@ -6725,16 +6787,16 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before z-index: 200; background: var(--colorbackvmenu1); padding-top: 70px; - } + } #id-left { - z-index: 201; + z-index: 201; background: var(--colorbackvmenu1); } - .login_vertical_align { - padding-left: 20px; - padding-right: 20px; - } + .login_vertical_align { + padding-left: 20px; + padding-right: 20px; + } /* Reduce login top right info */ .help { @@ -6754,34 +6816,34 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before width: 100%; } div.login_block a { - color: unset; - } + color: unset; + } div.login_block { /* Style when phone layout or when using the menuhider */ padding-top: 10px; padding-left: 20px; - padding-right: 20px; - padding-bottom: 16px; + padding-right: 20px; + padding-bottom: 16px; top: inherit !important; left: 0 !important; text-align: center; - vertical-align: middle; + vertical-align: middle; background: var(--colorbackvmenu1); - height: 50px; + height: 50px; - z-index: 202; - min-width: 200px; /* must be width of menu + padding + padding of sidenav */ - max-width: 200px; /* must be width of menu + padding + padding of sidenav */ - width: 200px; /* must be width of menu + padding + padding of sidenav */ - } - .side-nav-vert .user-menu .dropdown-menu { - width: 234px !important; - } - div.login_block_other { - margin-right: unset; - } + z-index: 202; + min-width: 200px; /* must be width of menu + padding + padding of sidenav */ + max-width: 200px; /* must be width of menu + padding + padding of sidenav */ + width: 200px; /* must be width of menu + padding + padding of sidenav */ + } + .side-nav-vert .user-menu .dropdown-menu { + width: 234px !important; + } + div.login_block_other { + margin-right: unset; + } div.login_block_user, div.login_block_other { clear: both; } .atoplogin, .atoplogin:hover { @@ -6793,32 +6855,32 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before padding: 0 !important; height: 38px; } - li.tmenu, li.tmenusel { - min-width: 32px; - } + li.tmenu, li.tmenusel { + min-width: 32px; + } div.mainmenu { height: 23px; } div.tmenucenter { - text-overflow: clip; + text-overflow: clip; } - .topmenuimage { - background-size: 20px auto; - margin-top: 2px !important; - left: 2px; + .topmenuimage { + background-size: 20px auto; + margin-top: 2px !important; + left: 2px; } div.mainmenu { - min-width: 20px; - } + min-width: 20px; + } .titlefield { - width: auto !important; /* We want to ignore the 30%, try to use more if you can */ + width: auto !important; /* We want to ignore the 30%, try to use more if you can */ } .tableforfield>tr>td:first-child, .tableforfield>tbody>tr>td:first-child, div.tableforfield div.tagtr>div.tagtd:first-of-type { - /* max-width: 100px; */ /* but no more than 100px */ + /* max-width: 100px; */ /* but no more than 100px */ } .tableforfield>tr>td:nth-child(2), .tableforfield>tbody>tr>td:nth-child(2), div.tableforfield div.tagtr>div.tagtd:nth-child(2) { - word-break: break-word; + word-break: break-word; } .badge { min-width: auto; @@ -6860,7 +6922,9 @@ include dol_buildpath($path.'/theme/'.$theme.'/info-box.inc.php', 0); include dol_buildpath($path.'/theme/'.$theme.'/progress.inc.php', 0); include dol_buildpath($path.'/theme/'.$theme.'/timeline.inc.php', 0); -if (!empty($conf->global->THEME_CUSTOM_CSS)) print $conf->global->THEME_CUSTOM_CSS; +if (!empty($conf->global->THEME_CUSTOM_CSS)) { + print $conf->global->THEME_CUSTOM_CSS; +} ?> diff --git a/htdocs/theme/eldy/img/menus/README.md b/htdocs/theme/eldy/img/menus/README.md deleted file mode 100644 index 72f376c3f2b..00000000000 --- a/htdocs/theme/eldy/img/menus/README.md +++ /dev/null @@ -1,14 +0,0 @@ - -Tutorial to create a new image for menu: - -1) First find an image. -2) With Gimp, open image and check there is a alpha channel. If not add one (Menu Color - Convert to alpha). -3) Convert image into black and white (Menu Image - Mode - Grey levels). -4) Use the degrade tool with option (Menu Tools - Paint - Degrade - CTRL+L): -* Mode: Erase color (you can also try "Clear only") -* Opacity: 50 +/- -* Offset: 0 -* PP toward transparent -* Shape: Linear -* Select on image top of file and drag to bottom. -Il est possible aussi d'augmenter la transparence globale depuis le calque. diff --git a/htdocs/theme/eldy/img/menus/agenda.png b/htdocs/theme/eldy/img/menus/agenda.png deleted file mode 100644 index 0caf60eb271..00000000000 Binary files a/htdocs/theme/eldy/img/menus/agenda.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/agenda_over.png b/htdocs/theme/eldy/img/menus/agenda_over.png deleted file mode 100644 index 3c695cc3c80..00000000000 Binary files a/htdocs/theme/eldy/img/menus/agenda_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/bank.png b/htdocs/theme/eldy/img/menus/bank.png deleted file mode 100644 index 9e15a9a2dc8..00000000000 Binary files a/htdocs/theme/eldy/img/menus/bank.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/bank_over.png b/htdocs/theme/eldy/img/menus/bank_over.png deleted file mode 100644 index bca5ce3c449..00000000000 Binary files a/htdocs/theme/eldy/img/menus/bank_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/commercial.png b/htdocs/theme/eldy/img/menus/commercial.png deleted file mode 100644 index 2c36155fb96..00000000000 Binary files a/htdocs/theme/eldy/img/menus/commercial.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/commercial_over.png b/htdocs/theme/eldy/img/menus/commercial_over.png deleted file mode 100644 index 51146c72359..00000000000 Binary files a/htdocs/theme/eldy/img/menus/commercial_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/company.png b/htdocs/theme/eldy/img/menus/company.png deleted file mode 100644 index 39a3b75db68..00000000000 Binary files a/htdocs/theme/eldy/img/menus/company.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/company_over.png b/htdocs/theme/eldy/img/menus/company_over.png deleted file mode 100644 index c86e6fcf97e..00000000000 Binary files a/htdocs/theme/eldy/img/menus/company_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/ecm.png b/htdocs/theme/eldy/img/menus/ecm.png deleted file mode 100644 index 3ba3f280a54..00000000000 Binary files a/htdocs/theme/eldy/img/menus/ecm.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/ecm_over.png b/htdocs/theme/eldy/img/menus/ecm_over.png deleted file mode 100644 index d72bc896f38..00000000000 Binary files a/htdocs/theme/eldy/img/menus/ecm_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/externalsite.png b/htdocs/theme/eldy/img/menus/externalsite.png deleted file mode 100644 index cda6eddc774..00000000000 Binary files a/htdocs/theme/eldy/img/menus/externalsite.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/externalsite_over.png b/htdocs/theme/eldy/img/menus/externalsite_over.png deleted file mode 100644 index 4620d6f3461..00000000000 Binary files a/htdocs/theme/eldy/img/menus/externalsite_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/ftp.png b/htdocs/theme/eldy/img/menus/ftp.png deleted file mode 100644 index 1f544834fbe..00000000000 Binary files a/htdocs/theme/eldy/img/menus/ftp.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/ftp_over.png b/htdocs/theme/eldy/img/menus/ftp_over.png deleted file mode 100644 index ca707d5d645..00000000000 Binary files a/htdocs/theme/eldy/img/menus/ftp_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/generic1.png b/htdocs/theme/eldy/img/menus/generic1.png deleted file mode 100644 index ef13122ace5..00000000000 Binary files a/htdocs/theme/eldy/img/menus/generic1.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/generic1_over.png b/htdocs/theme/eldy/img/menus/generic1_over.png deleted file mode 100644 index 29023816e67..00000000000 Binary files a/htdocs/theme/eldy/img/menus/generic1_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/generic2.png b/htdocs/theme/eldy/img/menus/generic2.png deleted file mode 100644 index ef13122ace5..00000000000 Binary files a/htdocs/theme/eldy/img/menus/generic2.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/generic2_over.png b/htdocs/theme/eldy/img/menus/generic2_over.png deleted file mode 100644 index 62eed5564b6..00000000000 Binary files a/htdocs/theme/eldy/img/menus/generic2_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/generic3.png b/htdocs/theme/eldy/img/menus/generic3.png deleted file mode 100644 index ef13122ace5..00000000000 Binary files a/htdocs/theme/eldy/img/menus/generic3.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/generic3_over.png b/htdocs/theme/eldy/img/menus/generic3_over.png deleted file mode 100644 index 29023816e67..00000000000 Binary files a/htdocs/theme/eldy/img/menus/generic3_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/generic4.png b/htdocs/theme/eldy/img/menus/generic4.png deleted file mode 100644 index ef13122ace5..00000000000 Binary files a/htdocs/theme/eldy/img/menus/generic4.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/generic4_over.png b/htdocs/theme/eldy/img/menus/generic4_over.png deleted file mode 100644 index 29023816e67..00000000000 Binary files a/htdocs/theme/eldy/img/menus/generic4_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/globe.png b/htdocs/theme/eldy/img/menus/globe.png deleted file mode 100644 index 87d8e86d4e8..00000000000 Binary files a/htdocs/theme/eldy/img/menus/globe.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/globe_over.png b/htdocs/theme/eldy/img/menus/globe_over.png deleted file mode 100644 index 9bfc263168f..00000000000 Binary files a/htdocs/theme/eldy/img/menus/globe_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/holiday.png b/htdocs/theme/eldy/img/menus/holiday.png deleted file mode 100644 index 146dcdaf120..00000000000 Binary files a/htdocs/theme/eldy/img/menus/holiday.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/holiday_over.png b/htdocs/theme/eldy/img/menus/holiday_over.png deleted file mode 100644 index 146dcdaf120..00000000000 Binary files a/htdocs/theme/eldy/img/menus/holiday_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/home.png b/htdocs/theme/eldy/img/menus/home.png deleted file mode 100644 index 175c9e9df71..00000000000 Binary files a/htdocs/theme/eldy/img/menus/home.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/home_over.png b/htdocs/theme/eldy/img/menus/home_over.png deleted file mode 100644 index e2cd61164ca..00000000000 Binary files a/htdocs/theme/eldy/img/menus/home_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/mail.png b/htdocs/theme/eldy/img/menus/mail.png deleted file mode 100644 index ef09835e61f..00000000000 Binary files a/htdocs/theme/eldy/img/menus/mail.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/mail_over.png b/htdocs/theme/eldy/img/menus/mail_over.png deleted file mode 100644 index cebc59aac9d..00000000000 Binary files a/htdocs/theme/eldy/img/menus/mail_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/members.png b/htdocs/theme/eldy/img/menus/members.png deleted file mode 100644 index bf195586d1a..00000000000 Binary files a/htdocs/theme/eldy/img/menus/members.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/members_over.png b/htdocs/theme/eldy/img/menus/members_over.png deleted file mode 100644 index 9ff7409af9a..00000000000 Binary files a/htdocs/theme/eldy/img/menus/members_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/menu.png b/htdocs/theme/eldy/img/menus/menu.png deleted file mode 100644 index 526e1975ab0..00000000000 Binary files a/htdocs/theme/eldy/img/menus/menu.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/money.png b/htdocs/theme/eldy/img/menus/money.png deleted file mode 100644 index 2190aa22c70..00000000000 Binary files a/htdocs/theme/eldy/img/menus/money.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/money_over.png b/htdocs/theme/eldy/img/menus/money_over.png deleted file mode 100644 index 47b61f2013d..00000000000 Binary files a/htdocs/theme/eldy/img/menus/money_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/pointofsale.png b/htdocs/theme/eldy/img/menus/pointofsale.png deleted file mode 100644 index 3f1d00e3add..00000000000 Binary files a/htdocs/theme/eldy/img/menus/pointofsale.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/pointofsale_over.png b/htdocs/theme/eldy/img/menus/pointofsale_over.png deleted file mode 100644 index 9ef02b49295..00000000000 Binary files a/htdocs/theme/eldy/img/menus/pointofsale_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/products.png b/htdocs/theme/eldy/img/menus/products.png deleted file mode 100644 index 2e3f6f70c4d..00000000000 Binary files a/htdocs/theme/eldy/img/menus/products.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/products_over.png b/htdocs/theme/eldy/img/menus/products_over.png deleted file mode 100644 index a36e3d0afd7..00000000000 Binary files a/htdocs/theme/eldy/img/menus/products_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/project.png b/htdocs/theme/eldy/img/menus/project.png deleted file mode 100644 index dfb2fa7c0a0..00000000000 Binary files a/htdocs/theme/eldy/img/menus/project.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/project_over.png b/htdocs/theme/eldy/img/menus/project_over.png deleted file mode 100644 index 0f86a34b5fa..00000000000 Binary files a/htdocs/theme/eldy/img/menus/project_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/shop.png b/htdocs/theme/eldy/img/menus/shop.png deleted file mode 100644 index 83cabd58266..00000000000 Binary files a/htdocs/theme/eldy/img/menus/shop.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/shop_over.png b/htdocs/theme/eldy/img/menus/shop_over.png deleted file mode 100644 index 4458d1804a0..00000000000 Binary files a/htdocs/theme/eldy/img/menus/shop_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/ticket.png b/htdocs/theme/eldy/img/menus/ticket.png deleted file mode 100644 index 57fc2aedb5b..00000000000 Binary files a/htdocs/theme/eldy/img/menus/ticket.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/ticket_over.png b/htdocs/theme/eldy/img/menus/ticket_over.png deleted file mode 100644 index 57fc2aedb5b..00000000000 Binary files a/htdocs/theme/eldy/img/menus/ticket_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/tools.png b/htdocs/theme/eldy/img/menus/tools.png deleted file mode 100644 index de26cd9b4cf..00000000000 Binary files a/htdocs/theme/eldy/img/menus/tools.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus/tools_over.png b/htdocs/theme/eldy/img/menus/tools_over.png deleted file mode 100644 index b04305187df..00000000000 Binary files a/htdocs/theme/eldy/img/menus/tools_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/agenda.png b/htdocs/theme/eldy/img/menus_black/agenda.png deleted file mode 100644 index ca69e7a53ab..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/agenda.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/agenda_over.png b/htdocs/theme/eldy/img/menus_black/agenda_over.png deleted file mode 100644 index 4e4f1d58543..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/agenda_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/bank.png b/htdocs/theme/eldy/img/menus_black/bank.png deleted file mode 100644 index f2ab8dcf64c..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/bank.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/bank_over.png b/htdocs/theme/eldy/img/menus_black/bank_over.png deleted file mode 100644 index b71c896a486..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/bank_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/commercial.png b/htdocs/theme/eldy/img/menus_black/commercial.png deleted file mode 100644 index 9f74d3ff193..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/commercial.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/commercial_over.png b/htdocs/theme/eldy/img/menus_black/commercial_over.png deleted file mode 100644 index 73345ebd2d2..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/commercial_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/company.png b/htdocs/theme/eldy/img/menus_black/company.png deleted file mode 100644 index 3db34e9a4d7..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/company.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/company_over.png b/htdocs/theme/eldy/img/menus_black/company_over.png deleted file mode 100644 index 54f61141f69..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/company_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/ecm.png b/htdocs/theme/eldy/img/menus_black/ecm.png deleted file mode 100644 index 4d8295ca0dd..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/ecm.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/ecm_over.png b/htdocs/theme/eldy/img/menus_black/ecm_over.png deleted file mode 100644 index a71608da773..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/ecm_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/externalsite.png b/htdocs/theme/eldy/img/menus_black/externalsite.png deleted file mode 100644 index b04fe8d6f62..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/externalsite.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/externalsite_over.png b/htdocs/theme/eldy/img/menus_black/externalsite_over.png deleted file mode 100644 index 968cff8042a..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/externalsite_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/ftp.png b/htdocs/theme/eldy/img/menus_black/ftp.png deleted file mode 100644 index 3132f4977d1..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/ftp.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/ftp_over.png b/htdocs/theme/eldy/img/menus_black/ftp_over.png deleted file mode 100644 index f8cca29d214..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/ftp_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/generic1.png b/htdocs/theme/eldy/img/menus_black/generic1.png deleted file mode 100644 index 3aa0f69fd23..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/generic1.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/generic1_over.png b/htdocs/theme/eldy/img/menus_black/generic1_over.png deleted file mode 100644 index e78c61ecb6e..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/generic1_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/generic2.png b/htdocs/theme/eldy/img/menus_black/generic2.png deleted file mode 100644 index 3aa0f69fd23..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/generic2.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/generic2_over.png b/htdocs/theme/eldy/img/menus_black/generic2_over.png deleted file mode 100644 index e78c61ecb6e..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/generic2_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/generic3.png b/htdocs/theme/eldy/img/menus_black/generic3.png deleted file mode 100644 index 3aa0f69fd23..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/generic3.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/generic3_over.png b/htdocs/theme/eldy/img/menus_black/generic3_over.png deleted file mode 100644 index e78c61ecb6e..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/generic3_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/generic4.png b/htdocs/theme/eldy/img/menus_black/generic4.png deleted file mode 100644 index 3aa0f69fd23..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/generic4.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/generic4_over.png b/htdocs/theme/eldy/img/menus_black/generic4_over.png deleted file mode 100644 index e78c61ecb6e..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/generic4_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/globe.png b/htdocs/theme/eldy/img/menus_black/globe.png deleted file mode 100644 index 8ea33cbadc6..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/globe.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/globe_over.png b/htdocs/theme/eldy/img/menus_black/globe_over.png deleted file mode 100644 index 409cf638196..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/globe_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/holiday.png b/htdocs/theme/eldy/img/menus_black/holiday.png deleted file mode 100644 index 24d9e498948..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/holiday.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/holiday_over.png b/htdocs/theme/eldy/img/menus_black/holiday_over.png deleted file mode 100644 index 24d9e498948..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/holiday_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/home.png b/htdocs/theme/eldy/img/menus_black/home.png deleted file mode 100644 index 15dafc01b06..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/home.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/home_over.png b/htdocs/theme/eldy/img/menus_black/home_over.png deleted file mode 100644 index f19ae6ec4b6..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/home_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/mail.png b/htdocs/theme/eldy/img/menus_black/mail.png deleted file mode 100644 index bab0121d1f2..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/mail.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/mail_over.png b/htdocs/theme/eldy/img/menus_black/mail_over.png deleted file mode 100644 index e0c2e0a98b8..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/mail_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/members.png b/htdocs/theme/eldy/img/menus_black/members.png deleted file mode 100644 index 4010af188cd..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/members.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/members_over.png b/htdocs/theme/eldy/img/menus_black/members_over.png deleted file mode 100644 index 3548942d14c..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/members_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/menu.png b/htdocs/theme/eldy/img/menus_black/menu.png deleted file mode 100644 index 0b080a18715..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/menu.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/money.png b/htdocs/theme/eldy/img/menus_black/money.png deleted file mode 100644 index c9668b65fb9..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/money.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/money_over.png b/htdocs/theme/eldy/img/menus_black/money_over.png deleted file mode 100644 index 6ed4fe78532..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/money_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/pointofsale.png b/htdocs/theme/eldy/img/menus_black/pointofsale.png deleted file mode 100644 index 21740c2d335..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/pointofsale.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/pointofsale_over.png b/htdocs/theme/eldy/img/menus_black/pointofsale_over.png deleted file mode 100644 index ce906378a8b..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/pointofsale_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/products.png b/htdocs/theme/eldy/img/menus_black/products.png deleted file mode 100644 index 08ec9b25477..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/products.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/products_over.png b/htdocs/theme/eldy/img/menus_black/products_over.png deleted file mode 100644 index e9e586bfda7..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/products_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/project.png b/htdocs/theme/eldy/img/menus_black/project.png deleted file mode 100644 index 3313e646419..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/project.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/project_over.png b/htdocs/theme/eldy/img/menus_black/project_over.png deleted file mode 100644 index ecd01444b4b..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/project_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/shop.png b/htdocs/theme/eldy/img/menus_black/shop.png deleted file mode 100644 index 5db29cb0e3a..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/shop.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/shop_over.png b/htdocs/theme/eldy/img/menus_black/shop_over.png deleted file mode 100644 index e1429d1b97e..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/shop_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/ticket.png b/htdocs/theme/eldy/img/menus_black/ticket.png deleted file mode 100644 index 998efdbaf82..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/ticket.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/ticket_over.png b/htdocs/theme/eldy/img/menus_black/ticket_over.png deleted file mode 100644 index 998efdbaf82..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/ticket_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/tools.png b/htdocs/theme/eldy/img/menus_black/tools.png deleted file mode 100644 index 5008c2fb98c..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/tools.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/menus_black/tools_over.png b/htdocs/theme/eldy/img/menus_black/tools_over.png deleted file mode 100644 index 7d200d2e7ae..00000000000 Binary files a/htdocs/theme/eldy/img/menus_black/tools_over.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/weather/index.html b/htdocs/theme/eldy/img/weather/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/theme/eldy/info-box.inc.php b/htdocs/theme/eldy/info-box.inc.php index 2da8de5cff3..ad47245eec5 100644 --- a/htdocs/theme/eldy/info-box.inc.php +++ b/htdocs/theme/eldy/info-box.inc.php @@ -1,5 +1,7 @@ <?php -if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> +if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* <style type="text/css" > */ /* @@ -8,33 +10,33 @@ if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> */ .info-box-module-external span.info-box-icon-version { - background: #bbb; + background: #bbb; } .info-box { display: block; - position: relative; + position: relative; min-height: 90px; /* background: #fff; */ width: 100%; box-shadow: 1px 1px 15px rgba(192, 192, 192, 0.2); - border-radius: 2px; - border: 1px solid #e9e9e9; + border-radius: 2px; + border: 1px solid #e9e9e9; margin-bottom: 15px; } .info-box.info-box-sm { - min-height: 80px; - margin-bottom: 10px; - /* background: #fff; */ + min-height: 80px; + margin-bottom: 10px; + /* background: #fff; */ } .opened-dash-board-wrap .info-box.info-box-sm { - border-radius: 0 0 0 20px; + border-radius: 0 0 0 20px; } .info-box-more { - float: right; - top: 5px; - position: absolute; - right: 8px; + float: right; + top: 5px; + position: absolute; + right: 8px; } .info-box small { @@ -71,7 +73,7 @@ if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> border-bottom-right-radius: 0; border-bottom-left-radius: 2px; display: block; - overflow: hidden; + overflow: hidden; float: left; height: 90px; width: 90px; @@ -82,20 +84,20 @@ if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> } .info-box-module .info-box-icon { - padding-top: 5px; - padding-bottom: 5px; + padding-top: 5px; + padding-bottom: 5px; } .info-box-sm .info-box-icon { - height: 80px; - width: 78px; - font-size: 25px; - line-height: 92px; + height: 80px; + width: 78px; + font-size: 25px; + line-height: 92px; } .opened-dash-board-wrap .info-box-sm .info-box-icon { - border-radius: 0 0 0 20px; + border-radius: 0 0 0 20px; } .opened-dash-board-wrap .info-box-sm .info-box-icon { - line-height: 80px; + line-height: 80px; } .info-box-module .info-box-icon { height: 98px; @@ -104,75 +106,75 @@ if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> max-width: 100%; } .info-box-module .info-box-icon > img { - max-width: 60%; + max-width: 60%; } a.info-box-text.info-box-text-a { - display: table-cell; + display: table-cell; } a.info-box-text-a i.fa.fa-exclamation-triangle { - font-size: 0.9em; + font-size: 0.9em; } .info-box-icon-text{ - box-sizing: border-box; - display: block; - position: absolute; - width: 90px; - bottom: 0px; - color: #ffffff; - background-color: rgba(0,0,0,0.1); - cursor: default; + box-sizing: border-box; + display: block; + position: absolute; + width: 90px; + bottom: 0px; + color: #ffffff; + background-color: rgba(0,0,0,0.1); + cursor: default; - font-size: 10px; - line-height: 15px; - padding: 0px 3px; - text-align: center; - opacity: 0; - -webkit-transition: opacity 0.5s, visibility 0s 0.5s; - transition: opacity 0.5s, visibility 0s 0.5s; + font-size: 10px; + line-height: 15px; + padding: 0px 3px; + text-align: center; + opacity: 0; + -webkit-transition: opacity 0.5s, visibility 0s 0.5s; + transition: opacity 0.5s, visibility 0s 0.5s; } .info-box-icon-version { - box-sizing: border-box; - display: block; - position: absolute; - width: 90px; - bottom: 0px; - color: #ffffff; - background-color: rgba(0,0,0,0.1); - cursor: default; + box-sizing: border-box; + display: block; + position: absolute; + width: 90px; + bottom: 0px; + color: #ffffff; + background-color: rgba(0,0,0,0.1); + cursor: default; - font-size: 10px; - line-height: 22px; - padding: 0px 3px; - text-align: center; - opacity: 1; - -webkit-transition: opacity 0.5s, visibility 0s 0.5s; - transition: opacity 0.5s, visibility 0s 0.5s; + font-size: 10px; + line-height: 22px; + padding: 0px 3px; + text-align: center; + opacity: 1; + -webkit-transition: opacity 0.5s, visibility 0s 0.5s; + transition: opacity 0.5s, visibility 0s 0.5s; } .box-flex-item.info-box-module.info-box-module-disabled { - /* opacity: 0.6; */ + /* opacity: 0.6; */ } .info-box-actions { position: absolute; - right: 0; - bottom: 0; + right: 0; + bottom: 0; } <?php if (empty($conf->global->MAIN_DISABLE_GLOBAL_BOXSTATS) && !empty($conf->global->MAIN_INCLUDE_GLOBAL_STATS_IN_OPENED_DASHBOARD)) { ?> .info-box-icon-text{ - opacity: 1; + opacity: 1; } <?php } ?> .info-box-sm .info-box-icon-text, .info-box-sm .info-box-icon-version{ - overflow: hidden; - width: 80px; + overflow: hidden; + width: 80px; } .info-box:hover .info-box-icon-text{ - opacity: 1; + opacity: 1; } .info-box-content { @@ -180,11 +182,11 @@ a.info-box-text-a i.fa.fa-exclamation-triangle { margin-left: 84px; } .info-box-sm .info-box-content{ - margin-left: 80px; + margin-left: 80px; } .info-box-sm .info-box-module-enabled { - /* background: linear-gradient(0.35turn, #fff, #fff, #f6faf8, #e4efe8) */ - background: linear-gradient(0.4turn, #fff, #fff, #fff, #e4efe8); + /* background: linear-gradient(0.35turn, #fff, #fff, #f6faf8, #e4efe8) */ + background: linear-gradient(0.4turn, #fff, #fff, #fff, #e4efe8); } .info-box-content-warning span.font-status4 { color: #bc9526 !important; @@ -193,7 +195,7 @@ a.info-box-text-a i.fa.fa-exclamation-triangle { background: #ffd7a3; }*/ /*.info-box-icon.info-box-icon-module-enabled { - background: #e4f0e4 !important; + background: #e4f0e4 !important; }*/ .info-box-number { @@ -240,20 +242,26 @@ a.info-box-text{ text-decoration: none;} include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $prefix = ''; -if (!empty($conf->global->THEME_INFOBOX_COLOR_ON_BACKGROUND)) $prefix = 'background-'; +if (!empty($conf->global->THEME_INFOBOX_COLOR_ON_BACKGROUND)) { + $prefix = 'background-'; +} -if (!isset($conf->global->THEME_SATURATE_RATIO)) $conf->global->THEME_SATURATE_RATIO = 0.7; -if (GETPOSTISSET('THEME_SATURATE_RATIO')) $conf->global->THEME_SATURATE_RATIO = GETPOST('THEME_SATURATE_RATIO', 'int'); +if (!isset($conf->global->THEME_SATURATE_RATIO)) { + $conf->global->THEME_SATURATE_RATIO = 0.7; +} +if (GETPOSTISSET('THEME_SATURATE_RATIO')) { + $conf->global->THEME_SATURATE_RATIO = GETPOST('THEME_SATURATE_RATIO', 'int'); +} ?> .info-box-icon { <?php if ($prefix) { ?> color: #fff !important; <?php } ?> - opacity: 0.95; - <?php if (isset($conf->global->THEME_SATURATE_RATIO)) { ?> - filter: saturate(<?php echo $conf->global->THEME_SATURATE_RATIO; ?>); - <?php } ?> + opacity: 0.95; + <?php if (isset($conf->global->THEME_SATURATE_RATIO)) { ?> + filter: saturate(<?php echo $conf->global->THEME_SATURATE_RATIO; ?>); + <?php } ?> } .customer-back { @@ -287,7 +295,7 @@ if (GETPOSTISSET('THEME_SATURATE_RATIO')) $conf->global->THEME_SATURATE_RATIO = <?php echo $prefix; ?>color: #b06080 !important; } .bg-infobox-propal, .bg-infobox-facture, .bg-infobox-commande { - <?php echo $prefix; ?>color: #55955d !important; + <?php echo $prefix; ?>color: #65953d !important; } .bg-infobox-supplier_proposal, .bg-infobox-invoice_supplier, .bg-infobox-order_supplier { <?php echo $prefix; ?>color: #599caf !important; @@ -317,11 +325,13 @@ if (GETPOSTISSET('THEME_SATURATE_RATIO')) $conf->global->THEME_SATURATE_RATIO = .infobox-action{ color: #b06080 !important; } +/* Color for customer object */ .infobox-propal:not(.pictotitle), .infobox-facture:not(.pictotitle), .infobox-commande:not(.pictotitle) { - color: #65955d !important; + color: #65953d !important; } +/* Color for vendor object */ .infobox-supplier_proposal:not(.pictotitle), .infobox-invoice_supplier:not(.pictotitle), .infobox-order_supplier:not(.pictotitle){ @@ -435,13 +445,13 @@ if (GETPOSTISSET('THEME_SATURATE_RATIO')) $conf->global->THEME_SATURATE_RATIO = } .info-box-module { min-width: 350px; - max-width: 350px; + max-width: 350px; } @media only screen and (max-width: 1740px) { .info-box-module { - min-width: 315px; - max-width: 315px; + min-width: 315px; + max-width: 315px; } } @@ -463,8 +473,8 @@ if (GETPOSTISSET('THEME_SATURATE_RATIO')) $conf->global->THEME_SATURATE_RATIO = @media only screen and (max-width: 767px) { .box-flex-container { - margin: 0 0 0 0px !important; - width: 100% !important; + margin: 0 0 0 0px !important; + width: 100% !important; } .info-box-module { width: 100%; diff --git a/htdocs/theme/eldy/main_menu_fa_icons.inc.php b/htdocs/theme/eldy/main_menu_fa_icons.inc.php index fbccc810fe7..339235ce2c7 100644 --- a/htdocs/theme/eldy/main_menu_fa_icons.inc.php +++ b/htdocs/theme/eldy/main_menu_fa_icons.inc.php @@ -1,23 +1,25 @@ -<?php if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> +<?php if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* <style type="text/css" > */ .mainmenu::before{ - /* font part */ - font-family: "Font Awesome 5 Free"; - font-weight: 900; - font-style: normal; - font-variant: normal; - text-rendering: auto; - line-height: 23px; + /* font part */ + font-family: "Font Awesome 5 Free"; + font-weight: 900; + font-style: normal; + font-variant: normal; + text-rendering: auto; + line-height: 23px; font-size: <?php echo $topMenuFontSize; ?>; - -webkit-font-smoothing: antialiased; - text-align:center; + -webkit-font-smoothing: antialiased; + text-align:center; text-decoration:none; color: #<?php echo $colortextbackhmenu; ?>; } .fa-15x { - font-size: 1.5em; + font-size: 1.5em; } div.mainmenu.menu { @@ -34,116 +36,118 @@ div.mainmenu.home::before{ } div.mainmenu.billing::before { - content: "\f51e"; + content: "\f51e"; } div.mainmenu.accountancy::before { - content: "\f53d"; + /* content: "\f53d"; */ + content: "\f688"; + font-size: 1.2em; } div.mainmenu.agenda::before { - content: "\f073"; + content: "\f073"; } div.mainmenu.bank::before { - content: "\f19c"; + content: "\f19c"; } <?php if ($conf->global->MAIN_FEATURES_LEVEL == 2) { ?> /* TESTING USAGE OF SVG WITHOUT FONT */ div.mainmenu.cashdesk { - line-height: 26px; + line-height: 26px; } div.mainmenu.cashdesk .tmenuimage { - line-height: 26px; - display: inline-block; - vertical-align: middle; - height: <?php echo $topMenuFontSize; ?>; + line-height: 26px; + display: inline-block; + vertical-align: middle; + height: <?php echo $topMenuFontSize; ?>; background-color: #<?php echo $colortextbackhmenu; ?>; - width: 100%; - -webkit-mask: url(<?php echo DOL_URL_ROOT.'/theme/common/fontawesome-5/svgs/solid/cash-register.svg' ?>) no-repeat 50% 50%; /* for old webkit browser */ - mask: url(<?php echo DOL_URL_ROOT.'/theme/common/fontawesome-5/svgs/solid/cash-register.svg' ?>) no-repeat 50% 50%; + width: 100%; + -webkit-mask: url(<?php echo DOL_URL_ROOT.'/theme/common/fontawesome-5/svgs/solid/cash-register.svg' ?>) no-repeat 50% 50%; /* for old webkit browser */ + mask: url(<?php echo DOL_URL_ROOT.'/theme/common/fontawesome-5/svgs/solid/cash-register.svg' ?>) no-repeat 50% 50%; } <?php } else { ?> div.mainmenu.cashdesk::before { - content: "\f788"; + content: "\f788"; } <?php } ?> div.mainmenu.takepos::before { - content: "\f788"; + content: "\f788"; } div.mainmenu.companies::before { - content: "\f1ad"; + content: "\f1ad"; } div.mainmenu.commercial::before { - content: "\f0f2"; + content: "\f0f2"; } div.mainmenu.ecm::before { - content: "\f07c"; + content: "\f07c"; } div.mainmenu.externalsite::before { - content: "\f360"; + content: "\f360"; } div.mainmenu.ftp::before { - content: "\f362"; + content: "\f362"; } div.mainmenu.hrm::before { - content: "\f508"; + content: "\f508"; } div.mainmenu.members::before { - content: "\f0c0"; + content: "\f007"; } div.mainmenu.products::before { - content: "\f1b2"; + content: "\f1b2"; } div.mainmenu.mrp::before { - content: "\f1b3"; + content: "\f1b3"; } div.mainmenu.project::before { - content: "\f0e8"; + content: "\f542"; } div.mainmenu.ticket::before { - content: "\f3ff"; + content: "\f3ff"; } div.mainmenu.tools::before { - content: "\f0ad"; + content: "\f0ad"; } div.mainmenu.website::before { - content: "\f57d"; + content: "\f57d"; } div.mainmenu.generic1::before { - content: "\f249"; + content: "\f249"; } div.mainmenu.generic2::before { - content: "\f249"; + content: "\f249"; } div.mainmenu.generic3::before { - content: "\f249"; + content: "\f249"; } div.mainmenu.generic4::before { - content: "\f249"; + content: "\f249"; } /* Define color of some picto */ @@ -199,3 +203,14 @@ div.mainmenu.generic4::before { margin-left: 30px; } +.menu_titre .em092 { + font-size: 0.92em; +} + +.menu_titre .em088 { + font-size: 0.88em; +} + +.menu_titre .em080 { + font-size: 0.80em; +} diff --git a/htdocs/theme/eldy/manifest.json.php b/htdocs/theme/eldy/manifest.json.php index 8af5af5a756..7d0f75614c7 100644 --- a/htdocs/theme/eldy/manifest.json.php +++ b/htdocs/theme/eldy/manifest.json.php @@ -25,27 +25,58 @@ * \brief File for The Web App */ -if (!defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOLOGIN')) define('NOLOGIN', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIREUSER')) { + define('NOREQUIREUSER', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOREQUIRETRAN')) { + define('NOREQUIRETRAN', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} require_once __DIR__.'/../../main.inc.php'; top_httphead('text/json'); +// Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. +if (empty($dolibarr_nocache)) { + header('Cache-Control: max-age=10800, public, must-revalidate'); + // For a text/json, we must set an Expires to avoid to have it forced to an expired value by the web server + header('Expires: '.gmdate('D, d M Y H:i:s', dol_now('gmt') + 10800) . ' GMT'); +} else { + header('Cache-Control: no-cache'); +} $manifest = new stdClass(); $manifest->name = constant('DOL_APPLICATION_TITLE'); -if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $manifest->name = $conf->global->MAIN_APPLICATION_TITLE; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $manifest->name = $conf->global->MAIN_APPLICATION_TITLE; +} $manifest->theme_color = !empty($conf->global->MAIN_MANIFEST_APPLI_THEME_COLOR)?$conf->global->MAIN_MANIFEST_APPLI_THEME_COLOR:'#F05F40'; @@ -54,21 +85,23 @@ $manifest->display = "standalone"; $manifest->splash_pages = null; $manifest->icons = array(); -if (!empty($conf->global->MAIN_MANIFEST_APPLI_LOGO_URL)){ +if (!empty($conf->global->MAIN_MANIFEST_APPLI_LOGO_URL)) { $icon = new stdClass(); $icon->src = $conf->global->MAIN_MANIFEST_APPLI_LOGO_URL; - if ($conf->global->MAIN_MANIFEST_APPLI_LOGO_URL_SIZE) { $icon->sizes = $conf->global->MAIN_MANIFEST_APPLI_LOGO_URL_SIZE."x".$conf->global->MAIN_MANIFEST_APPLI_LOGO_URL_SIZE; } - else { $icon->sizes = "512x512"; } + if ($conf->global->MAIN_MANIFEST_APPLI_LOGO_URL_SIZE) { + $icon->sizes = $conf->global->MAIN_MANIFEST_APPLI_LOGO_URL_SIZE."x".$conf->global->MAIN_MANIFEST_APPLI_LOGO_URL_SIZE; + } else { + $icon->sizes = "512x512"; + } $icon->type = "image/png"; $manifest->icons[] = $icon; -} -elseif (!empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED)){ - if (!empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI)){ +} elseif (!empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED)) { + if (!empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI)) { $iconRelativePath = 'logos/thumbs/'.$conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI; $iconPath = $conf->mycompany->dir_output.'/'.$iconRelativePath; if (is_readable($iconPath)) { $imgSize = getimagesize($iconPath); - if ($imgSize){ + if ($imgSize) { $icon = new stdClass(); $icon->src = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode($iconRelativePath); $icon->sizes = $imgSize[0]."x".$imgSize[1]; @@ -78,12 +111,12 @@ elseif (!empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED)){ } } - if (!empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL)){ + if (!empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL)) { $iconRelativePath = 'logos/thumbs/'.$conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL; $iconPath = $conf->mycompany->dir_output.'/'.$iconRelativePath; if (is_readable($iconPath)) { $imgSize = getimagesize($iconPath); - if ($imgSize){ + if ($imgSize) { $icon = new stdClass(); $icon->src = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode($iconRelativePath); $icon->sizes = $imgSize[0]."x".$imgSize[1]; @@ -93,12 +126,12 @@ elseif (!empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED)){ } } - if (!empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED)){ + if (!empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED)) { $iconRelativePath = 'logos/'.$conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED; $iconPath = $conf->mycompany->dir_output.'/'.$iconRelativePath; if (is_readable($iconPath)) { $imgSize = getimagesize($iconPath); - if ($imgSize){ + if ($imgSize) { $icon = new stdClass(); $icon->src = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode($iconRelativePath); $icon->sizes = $imgSize[0]."x".$imgSize[1]; @@ -110,7 +143,7 @@ elseif (!empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED)){ } // Add Dolibarr std icon -if (empty($manifest->icons)){ +if (empty($manifest->icons)) { $icon = new stdClass(); $icon->src = DOL_URL_ROOT.'/theme/dolibarr_256x256_color.png'; $icon->sizes = "256x256"; diff --git a/htdocs/theme/eldy/progress.inc.php b/htdocs/theme/eldy/progress.inc.php index 71f25ff35ba..e74c84cf89e 100644 --- a/htdocs/theme/eldy/progress.inc.php +++ b/htdocs/theme/eldy/progress.inc.php @@ -1,5 +1,7 @@ <?php -if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> +if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* <style type="text/css" > */ /* progress style is based on boostrap and admin lte framework @@ -12,183 +14,183 @@ if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> */ .progress * { - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; } .progress { - height: 20px; - overflow: hidden; - background-color: #f5f5f5; - background-color: rgba(128, 128, 128, 0.1); - border-radius: 4px; - -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); - box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + height: 20px; + overflow: hidden; + background-color: #f5f5f5; + background-color: rgba(128, 128, 128, 0.1); + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); } .progress.spaced{ - margin-bottom: 20px; + margin-bottom: 20px; } .progress-bar { - float: left; - width: 0; - height: 100%; - font-size: 12px; - line-height: 20px; - color: #fff; - text-align: center; - background-color: #337ab7; - -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.15); - box-shadow: inset 0 -1px 0 rgba(0,0,0,.15); - -webkit-transition: width .6s ease; - -o-transition: width .6s ease; - transition: width .6s ease; + float: left; + width: 0; + height: 100%; + font-size: 12px; + line-height: 20px; + color: #fff; + text-align: center; + background-color: #337ab7; + -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.15); + box-shadow: inset 0 -1px 0 rgba(0,0,0,.15); + -webkit-transition: width .6s ease; + -o-transition: width .6s ease; + transition: width .6s ease; } .progress-group > .progress{ - clear: both; + clear: both; } .progress, .progress > .progress-bar { - -webkit-box-shadow: none; - box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; } .progress, .progress > .progress-bar, .progress .progress-bar, .progress > .progress-bar .progress-bar { - border-radius: 1px; + border-radius: 1px; } /* size variation */ .progress.sm, .progress-sm { - height: 10px; + height: 10px; } .progress.sm, .progress-sm, .progress.sm .progress-bar, .progress-sm .progress-bar { - border-radius: 1px; + border-radius: 1px; } .progress.xs, .progress-xs { - height: 7px; + height: 7px; } .progress.xs, .progress-xs, .progress.xs .progress-bar, .progress-xs .progress-bar { - border-radius: 1px; + border-radius: 1px; } .progress.xxs, .progress-xxs { - height: 3px; + height: 3px; } .progress.xxs, .progress-xxs, .progress.xxs .progress-bar, .progress-xxs .progress-bar { - border-radius: 1px; + border-radius: 1px; } /* Vertical bars */ .progress.vertical { - position: relative; - width: 30px; - height: 200px; - display: inline-block; - margin-right: 10px; + position: relative; + width: 30px; + height: 200px; + display: inline-block; + margin-right: 10px; } .progress.vertical > .progress-bar { - width: 100%; - position: absolute; - bottom: 0; + width: 100%; + position: absolute; + bottom: 0; } .progress.vertical.sm, .progress.vertical.progress-sm { - width: 20px; + width: 20px; } .progress.vertical.xs, .progress.vertical.progress-xs { - width: 10px; + width: 10px; } .progress.vertical.xxs, .progress.vertical.progress-xxs { - width: 3px; + width: 3px; } .progress-group .progress-text { - /* font-weight: 600; */ + /* font-weight: 600; */ } .progress-group .progress-number { - float: right; + float: right; } /* Remove margins from progress bars when put in a table */ .table tr > td .progress { - margin: 0; + margin: 0; } .progress-bar-light-blue, .progress-bar-primary { - background-color: #3c8dbc; + background-color: #3c8dbc; } .progress-striped .progress-bar-light-blue, .progress-striped .progress-bar-primary { - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-green, .progress-bar-success { - background-color: <?php echo $badgeSuccess ?>; + background-color: <?php echo $badgeSuccess ?>; } .progress-striped .progress-bar-green, .progress-striped .progress-bar-success { - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } body[class*="colorblind-"] .progress-bar-green, body[class*="colorblind-"] .progress-bar-success { - background-color: <?php echo $colorblind_deuteranopes_badgeSuccess ?>; + background-color: <?php echo $colorblind_deuteranopes_badgeSuccess ?>; } body[class*="colorblind-"] .progress-bar-red, body[class*="colorblind-"] .progress-bar-danger { - background-color: <?php echo $colorblind_deuteranopes_badgeDanger ?>; + background-color: <?php echo $colorblind_deuteranopes_badgeDanger ?>; } .progress-bar-aqua, .progress-bar-info { - background-color: #00c0ef; + background-color: #00c0ef; } .progress-striped .progress-bar-aqua, .progress-striped .progress-bar-info { - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-yellow, .progress-bar-warning { - background-color: <?php echo $badgeWarning ?>; + background-color: <?php echo $badgeWarning ?>; } .progress-striped .progress-bar-yellow, .progress-striped .progress-bar-warning { - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-red, .progress-bar-danger { - background-color: <?php echo $badgeDanger ?>; + background-color: <?php echo $badgeDanger ?>; } .progress-striped .progress-bar-red, .progress-striped .progress-bar-danger { - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-consumed { background-color: rgb(0, 0, 0, 0.15); diff --git a/htdocs/theme/eldy/style.css.php b/htdocs/theme/eldy/style.css.php index 319789b6fde..44a0a7d7b20 100644 --- a/htdocs/theme/eldy/style.css.php +++ b/htdocs/theme/eldy/style.css.php @@ -27,21 +27,35 @@ //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled because need to load personalized language //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled to increase speed. Language code is found on url. -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Not disabled because need to do translations -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); -if (!defined('NOLOGIN')) define('NOLOGIN', 1); // File must be accessed by logon page so without login. +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', 1); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', 1); // File must be accessed by logon page so without login. +} //if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU',1); // We load menu manager class (note that object loaded may have wrong content because NOLOGIN is set and some values depends on login) -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', 1); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} define('ISLOADEDBYSTEELSHEET', '1'); require __DIR__.'/theme_vars.inc.php'; -if (defined('THEME_ONLY_CONSTANT')) return; +if (defined('THEME_ONLY_CONSTANT')) { + return; +} session_cache_limiter('public'); @@ -51,8 +65,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; // Load user to have $user->conf loaded (not done into main because of NOLOGIN constant defined) // and permission, so we can later calculate number of top menu ($nbtopmenuentries) according to user profile. -if (empty($user->id) && !empty($_SESSION['dol_login'])) -{ +if (empty($user->id) && !empty($_SESSION['dol_login'])) { $user->fetch('', $_SESSION['dol_login'], '', 1); $user->getrights(); @@ -65,12 +78,21 @@ if (empty($user->id) && !empty($_SESSION['dol_login'])) // Define css type top_httphead('text/css'); // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. -if (empty($dolibarr_nocache)) header('Cache-Control: max-age=10800, public, must-revalidate'); -else header('Cache-Control: no-cache'); +if (empty($dolibarr_nocache)) { + header('Cache-Control: max-age=10800, public, must-revalidate'); +} else { + header('Cache-Control: no-cache'); +} -if (GETPOST('theme', 'alpha')) $conf->theme = GETPOST('theme', 'alpha'); // If theme was forced on URL -if (GETPOST('lang', 'aZ09')) $langs->setDefaultLang(GETPOST('lang', 'aZ09')); // If language was forced on URL -if (GETPOST('THEME_DARKMODEENABLED', 'int')) $conf->global->THEME_DARKMODEENABLED = GETPOST('THEME_DARKMODEENABLED', 'int'); // If darkmode was forced on URL +if (GETPOST('theme', 'alpha')) { + $conf->theme = GETPOST('theme', 'alpha'); // If theme was forced on URL +} +if (GETPOST('lang', 'aZ09')) { + $langs->setDefaultLang(GETPOST('lang', 'aZ09')); // If language was forced on URL +} +if (GETPOST('THEME_DARKMODEENABLED', 'int')) { + $conf->global->THEME_DARKMODEENABLED = GETPOST('THEME_DARKMODEENABLED', 'int'); // If darkmode was forced on URL +} $langs->load("main", 0, 1); $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right'); @@ -78,7 +100,9 @@ $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left'); $path = ''; // This value may be used in future for external module to overwrite theme $theme = 'eldy'; // Value of theme -if (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) { $path = '/'.$conf->global->MAIN_OVERWRITE_THEME_RES; $theme = $conf->global->MAIN_OVERWRITE_THEME_RES; } +if (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) { + $path = '/'.$conf->global->MAIN_OVERWRITE_THEME_RES; $theme = $conf->global->MAIN_OVERWRITE_THEME_RES; +} // Define image path files and other constants $fontlist = 'arial,tahoma,verdana,helvetica'; //$fontlist='helvetica, verdana, arial, sans-serif'; @@ -98,19 +122,36 @@ $useboldtitle = (isset($conf->global->THEME_ELDY_USEBOLDTITLE) ? $conf->global-> $borderwidth = 1; // Case of option always editable -if (!isset($conf->global->THEME_ELDY_BACKBODY)) $conf->global->THEME_ELDY_BACKBODY = $colorbackbody; -if (!isset($conf->global->THEME_ELDY_TOPMENU_BACK1)) $conf->global->THEME_ELDY_TOPMENU_BACK1 = $colorbackhmenu1; -if (!isset($conf->global->THEME_ELDY_VERMENU_BACK1)) $conf->global->THEME_ELDY_VERMENU_BACK1 = $colorbackvmenu1; -if (!isset($conf->global->THEME_ELDY_BACKTITLE1)) $conf->global->THEME_ELDY_BACKTITLE1 = $colorbacktitle1; -if (!isset($conf->global->THEME_ELDY_USE_HOVER)) $conf->global->THEME_ELDY_USE_HOVER = $colorbacklinepairhover; -if (!isset($conf->global->THEME_ELDY_USE_CHECKED)) $conf->global->THEME_ELDY_USE_CHECKED = $colorbacklinepairchecked; -if (!isset($conf->global->THEME_ELDY_LINEBREAK)) $conf->global->THEME_ELDY_LINEBREAK = $colorbacklinebreak; -if (!isset($conf->global->THEME_ELDY_TEXTTITLENOTAB)) $conf->global->THEME_ELDY_TEXTTITLENOTAB = $colortexttitlenotab; -if (!isset($conf->global->THEME_ELDY_TEXTLINK)) $conf->global->THEME_ELDY_TEXTLINK = $colortextlink; +if (!isset($conf->global->THEME_ELDY_BACKBODY)) { + $conf->global->THEME_ELDY_BACKBODY = $colorbackbody; +} +if (!isset($conf->global->THEME_ELDY_TOPMENU_BACK1)) { + $conf->global->THEME_ELDY_TOPMENU_BACK1 = $colorbackhmenu1; +} +if (!isset($conf->global->THEME_ELDY_VERMENU_BACK1)) { + $conf->global->THEME_ELDY_VERMENU_BACK1 = $colorbackvmenu1; +} +if (!isset($conf->global->THEME_ELDY_BACKTITLE1)) { + $conf->global->THEME_ELDY_BACKTITLE1 = $colorbacktitle1; +} +if (!isset($conf->global->THEME_ELDY_USE_HOVER)) { + $conf->global->THEME_ELDY_USE_HOVER = $colorbacklinepairhover; +} +if (!isset($conf->global->THEME_ELDY_USE_CHECKED)) { + $conf->global->THEME_ELDY_USE_CHECKED = $colorbacklinepairchecked; +} +if (!isset($conf->global->THEME_ELDY_LINEBREAK)) { + $conf->global->THEME_ELDY_LINEBREAK = $colorbacklinebreak; +} +if (!isset($conf->global->THEME_ELDY_TEXTTITLENOTAB)) { + $conf->global->THEME_ELDY_TEXTTITLENOTAB = $colortexttitlenotab; +} +if (!isset($conf->global->THEME_ELDY_TEXTLINK)) { + $conf->global->THEME_ELDY_TEXTLINK = $colortextlink; +} // Case of option editable only if option THEME_ELDY_ENABLE_PERSONALIZED is on -if (empty($conf->global->THEME_ELDY_ENABLE_PERSONALIZED)) -{ +if (empty($conf->global->THEME_ELDY_ENABLE_PERSONALIZED)) { $conf->global->THEME_ELDY_BACKTABCARD1 = '255,255,255'; // card $conf->global->THEME_ELDY_BACKTABACTIVE = '234,234,234'; $conf->global->THEME_ELDY_TEXT = '0,0,0'; @@ -142,8 +183,7 @@ $fontsizesmaller = empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED) ? (emp // Hover color $colorbacklinepairhover = ((!isset($conf->global->THEME_ELDY_USE_HOVER) || (string) $conf->global->THEME_ELDY_USE_HOVER === '255,255,255') ? '' : ($conf->global->THEME_ELDY_USE_HOVER === '1' ? 'e6edf0' : $conf->global->THEME_ELDY_USE_HOVER)); $colorbacklinepairchecked = ((!isset($conf->global->THEME_ELDY_USE_CHECKED) || (string) $conf->global->THEME_ELDY_USE_CHECKED === '255,255,255') ? '' : ($conf->global->THEME_ELDY_USE_CHECKED === '1' ? 'e6edf0' : $conf->global->THEME_ELDY_USE_CHECKED)); -if (!empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)) -{ +if (!empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)) { $colorbacklinepairhover = ((!isset($user->conf->THEME_ELDY_USE_HOVER) || $user->conf->THEME_ELDY_USE_HOVER === '0') ? '' : ($user->conf->THEME_ELDY_USE_HOVER === '1' ? 'e6edf0' : $user->conf->THEME_ELDY_USE_HOVER)); $colorbacklinepairchecked = ((!isset($user->conf->THEME_ELDY_USE_CHECKED) || $user->conf->THEME_ELDY_USE_CHECKED === '0') ? '' : ($user->conf->THEME_ELDY_USE_CHECKED === '1' ? 'e6edf0' : $user->conf->THEME_ELDY_USE_CHECKED)); } @@ -153,26 +193,42 @@ if (!empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)) $colorbackhmenu1 = join(',', colorStringToArray($colorbackhmenu1)); // Normalize value to 'x,y,z' $tmppart = explode(',', $colorbackhmenu1); $tmpval = (!empty($tmppart[0]) ? $tmppart[0] : 0) + (!empty($tmppart[1]) ? $tmppart[1] : 0) + (!empty($tmppart[2]) ? $tmppart[2] : 0); -if ($tmpval <= 460) $colortextbackhmenu = 'FFFFFF'; -else $colortextbackhmenu = '000000'; +if ($tmpval <= 460) { + $colortextbackhmenu = 'FFFFFF'; +} else { + $colortextbackhmenu = '000000'; +} $colorbackvmenu1 = join(',', colorStringToArray($colorbackvmenu1)); // Normalize value to 'x,y,z' $tmppart = explode(',', $colorbackvmenu1); $tmpval = (!empty($tmppart[0]) ? $tmppart[0] : 0) + (!empty($tmppart[1]) ? $tmppart[1] : 0) + (!empty($tmppart[2]) ? $tmppart[2] : 0); -if ($tmpval <= 460) { $colortextbackvmenu = 'FFFFFF'; } else { $colortextbackvmenu = '000000'; } +if ($tmpval <= 460) { + $colortextbackvmenu = 'FFFFFF'; +} else { + $colortextbackvmenu = '000000'; +} $colorbacktitle1 = join(',', colorStringToArray($colorbacktitle1)); // Normalize value to 'x,y,z' $tmppart = explode(',', $colorbacktitle1); -if ($colortexttitle == '') -{ +if ($colortexttitle == '') { $tmpval = (!empty($tmppart[0]) ? $tmppart[0] : 0) + (!empty($tmppart[1]) ? $tmppart[1] : 0) + (!empty($tmppart[2]) ? $tmppart[2] : 0); - if ($tmpval <= 460) { $colortexttitle = 'FFFFFF'; $colorshadowtitle = '888888'; } else { $colortexttitle = '000000'; $colorshadowtitle = 'FFFFFF'; } -} else $colorshadowtitle = '888888'; + if ($tmpval <= 460) { + $colortexttitle = 'FFFFFF'; $colorshadowtitle = '888888'; + } else { + $colortexttitle = '000000'; $colorshadowtitle = 'FFFFFF'; + } +} else { + $colorshadowtitle = '888888'; +} $colorbacktabcard1 = join(',', colorStringToArray($colorbacktabcard1)); // Normalize value to 'x,y,z' $tmppart = explode(',', $colorbacktabcard1); $tmpval = (!empty($tmppart[0]) ? $tmppart[0] : 0) + (!empty($tmppart[1]) ? $tmppart[1] : 0) + (!empty($tmppart[2]) ? $tmppart[2] : 0); -if ($tmpval <= 460) { $colortextbacktab = 'FFFFFF'; } else { $colortextbacktab = '000000'; } +if ($tmpval <= 460) { + $colortextbacktab = 'FFFFFF'; +} else { + $colortextbacktab = '000000'; +} // Format color value to match expected format (may be 'FFFFFF' or '255,255,255') @@ -185,8 +241,12 @@ $colorbacklineimpair1 = join(',', colorStringToArray($colorbacklineimpair1)); $colorbacklineimpair2 = join(',', colorStringToArray($colorbacklineimpair2)); $colorbacklinepair1 = join(',', colorStringToArray($colorbacklinepair1)); $colorbacklinepair2 = join(',', colorStringToArray($colorbacklinepair2)); -if ($colorbacklinepairhover != '') $colorbacklinepairhover = join(',', colorStringToArray($colorbacklinepairhover)); -if ($colorbacklinepairchecked != '') $colorbacklinepairchecked = join(',', colorStringToArray($colorbacklinepairchecked)); +if ($colorbacklinepairhover != '') { + $colorbacklinepairhover = join(',', colorStringToArray($colorbacklinepairhover)); +} +if ($colorbacklinepairchecked != '') { + $colorbacklinepairchecked = join(',', colorStringToArray($colorbacklinepairchecked)); +} $colorbackbody = join(',', colorStringToArray($colorbackbody)); $colortexttitlenotab = join(',', colorStringToArray($colortexttitlenotab)); $colortexttitle = join(',', colorStringToArray($colortexttitle)); @@ -195,7 +255,9 @@ $colortextlink = join(',', colorStringToArray($colortextlink)); $nbtopmenuentries = $menumanager->showmenu('topnb'); -if ($conf->browser->layout == 'phone') $nbtopmenuentries = max($nbtopmenuentries, 10); +if ($conf->browser->layout == 'phone') { + $nbtopmenuentries = max($nbtopmenuentries, 10); +} $minwidthtmenu = 66; /* minimum width for one top menu entry */ @@ -203,11 +265,19 @@ $heightmenu = 50; /* height of top menu, part with image */ $heightmenu2 = 49; /* height of top menu, part with login */ $disableimages = 0; $maxwidthloginblock = 180; -if (!empty($conf->global->THEME_TOPMENU_DISABLE_IMAGE)) { $disableimages = 1; $maxwidthloginblock = $maxwidthloginblock + 50; $minwidthtmenu = 0; } +if (!empty($conf->global->THEME_TOPMENU_DISABLE_IMAGE)) { + $disableimages = 1; $maxwidthloginblock = $maxwidthloginblock + 50; $minwidthtmenu = 0; +} -if (!empty($conf->global->MAIN_USE_TOP_MENU_QUICKADD_DROPDOWN)) { $maxwidthloginblock = $maxwidthloginblock + 55; } -if (!empty($conf->global->MAIN_USE_TOP_MENU_SEARCH_DROPDOWN)) { $maxwidthloginblock = $maxwidthloginblock + 55; } -if (!empty($conf->bookmark->enabled)) { $maxwidthloginblock = $maxwidthloginblock + 55; } +if (!empty($conf->global->MAIN_USE_TOP_MENU_QUICKADD_DROPDOWN)) { + $maxwidthloginblock = $maxwidthloginblock + 55; +} +if (!empty($conf->global->MAIN_USE_TOP_MENU_SEARCH_DROPDOWN)) { + $maxwidthloginblock = $maxwidthloginblock + 55; +} +if (!empty($conf->bookmark->enabled)) { + $maxwidthloginblock = $maxwidthloginblock + 55; +} print '/*'."\n"; @@ -247,4 +317,6 @@ print '*/'."\n"; require __DIR__.'/global.inc.php'; -if (is_object($db)) $db->close(); +if (is_object($db)) { + $db->close(); +} diff --git a/htdocs/theme/eldy/theme_vars.inc.php b/htdocs/theme/eldy/theme_vars.inc.php index cc73803f452..8bb2fd3bbca 100644 --- a/htdocs/theme/eldy/theme_vars.inc.php +++ b/htdocs/theme/eldy/theme_vars.inc.php @@ -33,12 +33,9 @@ global $theme_bordercolor, $theme_datacolor, $theme_bgcolor, $theme_bgcoloronglet; $theme_bordercolor = array(235, 235, 224); $theme_datacolor = array(array(137, 86, 161), array(60, 147, 183), array(250, 190, 80), array(80, 166, 90), array(190, 190, 100), array(91, 115, 247), array(140, 140, 220), array(190, 120, 120), array(115, 125, 150), array(100, 170, 20), array(150, 135, 125), array(85, 135, 150), array(150, 135, 80), array(150, 80, 150)); -if (!defined('ISLOADEDBYSTEELSHEET')) // File is run after an include of a php page, not by the style sheet, if the constant is not defined. -{ - if (!empty($conf->global->MAIN_OPTIMIZEFORCOLORBLIND)) // user is loaded by dolgraph.class.php - { - if ($conf->global->MAIN_OPTIMIZEFORCOLORBLIND == 'flashy') - { +if (!defined('ISLOADEDBYSTEELSHEET')) { // File is run after an include of a php page, not by the style sheet, if the constant is not defined. + if (!empty($conf->global->MAIN_OPTIMIZEFORCOLORBLIND)) { // user is loaded by dolgraph.class.php + if ($conf->global->MAIN_OPTIMIZEFORCOLORBLIND == 'flashy') { $theme_datacolor = array(array(157, 56, 191), array(0, 147, 183), array(250, 190, 30), array(221, 75, 57), array(0, 166, 90), array(140, 140, 220), array(190, 120, 120), array(190, 190, 100), array(115, 125, 150), array(100, 170, 20), array(150, 135, 125), array(85, 135, 150), array(150, 135, 80), array(150, 80, 150)); } else { // for now we use the same configuration for all types of color blind diff --git a/htdocs/theme/eldy/timeline.inc.php b/htdocs/theme/eldy/timeline.inc.php index d5fba863b3d..161505f77ea 100644 --- a/htdocs/theme/eldy/timeline.inc.php +++ b/htdocs/theme/eldy/timeline.inc.php @@ -1,6 +1,6 @@ <?php /*! - Source : + Source : * AdminLTE v2.4.8 * Author: Almsaeed Studio * Website: Almsaeed Studio <https://adminlte.io> @@ -8,7 +8,9 @@ * Please visit http://opensource.org/licenses/MIT for more information */ -if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> +if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* <style type="text/css" > */ @@ -17,68 +19,68 @@ if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> * ------------------- */ .timeline { - position: relative; - margin: 0 0 30px 0; - padding: 0; - list-style: none; + position: relative; + margin: 0 0 30px 0; + padding: 0; + list-style: none; } .timeline:before { - content: ''; - position: absolute; - top: 0; - bottom: 0; - width: 4px; - background: #ddd; - left: 31px; - margin: 0; - border-radius: 2px; + content: ''; + position: absolute; + top: 0; + bottom: 0; + width: 4px; + background: #ddd; + left: 31px; + margin: 0; + border-radius: 2px; } .timeline > li { - position: relative; - margin-right: 0; - margin-bottom: 15px; + position: relative; + margin-right: 0; + margin-bottom: 15px; } .timeline > li:before, .timeline > li:after { - content: " "; - display: table; + content: " "; + display: table; } .timeline > li:after { - clear: both; + clear: both; } .timeline > li > .timeline-item { - -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); - border:1px solid #d2d2d2; - border-radius: 3px; - margin-top: 0; - background: #fff; - color: #444; - margin-left: 60px; - margin-right: 0px; - padding: 0; - position: relative; + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + border:1px solid #d2d2d2; + border-radius: 3px; + margin-top: 0; + background: #fff; + color: #444; + margin-left: 60px; + margin-right: 0px; + padding: 0; + position: relative; } .timeline > li.timeline-code-ticket_msg_private > .timeline-item { background: #fffbe5; - border-color: #d0cfc0; + border-color: #d0cfc0; } .timeline > li > .timeline-item > .time{ - color: #6f6f6f; - float: right; - padding: 10px; - font-size: 12px; + color: #6f6f6f; + float: right; + padding: 10px; + font-size: 12px; } .timeline > li > .timeline-item > .timeline-header-action{ - color: #6f6f6f; - float: right; - padding: 7px; - font-size: 12px; + color: #6f6f6f; + float: right; + padding: 7px; + font-size: 12px; } @@ -87,43 +89,43 @@ a.timeline-btn:visited, a.timeline-btn:hover, a.timeline-btn:active { - display: inline-block; - margin-bottom: 0; - font-weight: 400; - border-radius: 0; - box-shadow: none; - padding: 1px 5px; - font-size: 12px; - line-height: 1.5; - text-align: center; - white-space: nowrap; - vertical-align: middle; - touch-action: manipulation; - cursor: pointer; - user-select: none; - background-image: none; - text-decoration: none; - background-color: #f4f4f4; - color: #444; - border: 1px solid #ddd; + display: inline-block; + margin-bottom: 0; + font-weight: 400; + border-radius: 0; + box-shadow: none; + padding: 1px 5px; + font-size: 12px; + line-height: 1.5; + text-align: center; + white-space: nowrap; + vertical-align: middle; + touch-action: manipulation; + cursor: pointer; + user-select: none; + background-image: none; + text-decoration: none; + background-color: #f4f4f4; + color: #444; + border: 1px solid #ddd; } a.timeline-btn:hover { - background-color: #e7e7e7; - color: #333; - border-color: #adadad; + background-color: #e7e7e7; + color: #333; + border-color: #adadad; } .timeline > li > .timeline-item > .timeline-header { - margin: 0; - color: #333; - border-bottom: 1px solid #f4f4f4; - padding: 10px; - font-size: 14px; - font-weight: normal; - line-height: 1.1; + margin: 0; + color: #333; + border-bottom: 1px solid #f4f4f4; + padding: 10px; + font-size: 14px; + font-weight: normal; + line-height: 1.1; } .timeline > li > .timeline-item > .timeline-footer { @@ -131,74 +133,74 @@ a.timeline-btn:hover } .timeline > li.timeline-code-ticket_msg_private > .timeline-item > .timeline-header, .timeline > li.timeline-code-ticket_msg_private > .timeline-item > .timeline-footer { - border-color: #ecebda; + border-color: #ecebda; } .timeline > li > .timeline-item > .timeline-header > a { - font-weight: 600; + font-weight: 600; } .timeline > li > .timeline-item > .timeline-body, .timeline > li > .timeline-item > .timeline-footer { - padding: 10px; + padding: 10px; } .timeline > li > .fa, .timeline > li > .glyphicon, .timeline > li > .ion { - width: 30px; - height: 30px; - font-size: 15px; - line-height: 30px; - position: absolute; - color: #666; - background: #d2d6de; - border-radius: 50%; - text-align: center; - left: 18px; - top: 5px; + width: 30px; + height: 30px; + font-size: 15px; + line-height: 30px; + position: absolute; + color: #666; + background: #d2d6de; + border-radius: 50%; + text-align: center; + left: 18px; + top: 5px; } .timeline > .time-label > span { - font-weight: 600; - padding: 5px; - display: inline-block; - background-color: #fff; - border-radius: 4px; + font-weight: 600; + padding: 5px; + display: inline-block; + background-color: #fff; + border-radius: 4px; } .timeline-inverse > li > .timeline-item { - background: #f0f0f0; - border: 1px solid #ddd; - -webkit-box-shadow: none; - box-shadow: none; + background: #f0f0f0; + border: 1px solid #ddd; + -webkit-box-shadow: none; + box-shadow: none; } .timeline-inverse > li > .timeline-item > .timeline-header { - border-bottom-color: #ddd; + border-bottom-color: #ddd; } .timeline-icon-todo, .timeline-icon-in-progress, .timeline-icon-done{ - color: #fff !important; + color: #fff !important; } .timeline-icon-not-applicble{ - color: #000; - background-color: #f7f7f7; + color: #000; + background-color: #f7f7f7; } .timeline-icon-todo{ - background-color: #dd4b39 !important; + background-color: #dd4b39 !important; } .timeline-icon-in-progress{ - background-color: #00c0ef !important; + background-color: #00c0ef !important; } .timeline-icon-done{ - background-color: #00a65a !important; + background-color: #00a65a !important; } .timeline-badge-date{ - background-color: #0073b7 !important; - color: #fff !important; + background-color: #0073b7 !important; + color: #fff !important; } .timeline-documents-container{ diff --git a/htdocs/theme/md/badges.inc.php b/htdocs/theme/md/badges.inc.php index 1ce2d912669..7dd0229ae46 100644 --- a/htdocs/theme/md/badges.inc.php +++ b/htdocs/theme/md/badges.inc.php @@ -1,135 +1,137 @@ <?php -if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> +if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* <style type="text/css" > */ /* Badge style is based on boostrap framework */ .badge { - display: inline-block; - padding: .1em .35em; - font-size: 80%; - font-weight: 700 !important; - line-height: 1; - text-align: center; - white-space: nowrap; - vertical-align: baseline; - border-radius: .25rem; - transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out; - border-width: 2px; - border-style: solid; - border-color: rgba(255,255,255,0); - box-sizing: border-box; + display: inline-block; + padding: .1em .35em; + font-size: 80%; + font-weight: 700 !important; + line-height: 1; + text-align: center; + white-space: nowrap; + vertical-align: baseline; + border-radius: .25rem; + transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out; + border-width: 2px; + border-style: solid; + border-color: rgba(255,255,255,0); + box-sizing: border-box; } .badge-status { - font-size: 1em; - padding: .19em .35em; /* more than 0.19 generate a change into heigth of lines */ + font-size: 1em; + padding: .19em .35em; /* more than 0.19 generate a change into heigth of lines */ } .tabBar .arearef .statusref .badge-status, .tabBar .arearefnobottom .statusref .badge-status { - font-size: 1.1em; - padding: .4em .4em; + font-size: 1.1em; + padding: .4em .4em; } /* Force values for small screen 767 */ @media only screen and (max-width: 767px) { .tabBar .arearef .statusref .badge-status, .tabBar .arearefnobottom .statusref .badge-status { - font-size: 0.95em; - padding: .3em .2em; + font-size: 0.95em; + padding: .3em .2em; } } .badge-pill, .tabs .badge { - padding-right: .5em; - padding-left: .5em; - border-radius: 0.25rem; + padding-right: .5em; + padding-left: .5em; + border-radius: 0.25rem; } .badge-dot { - padding: 0; - border-radius: 50%; - padding: 0.45em; - vertical-align: unset; + padding: 0; + border-radius: 50%; + padding: 0.45em; + vertical-align: unset; } a.badge:focus, a.badge:hover { - text-decoration: none; + text-decoration: none; } .liste_titre .badge:not(.nochangebackground) { - background-color: <?php print $badgeSecondary; ?>; - color: #fff; + background-color: <?php print $badgeSecondary; ?>; + color: #fff; } /* PRIMARY */ .badge-primary{ - color: #fff !important; - background-color: <?php print $badgePrimary; ?>; + color: #fff !important; + background-color: <?php print $badgePrimary; ?>; } a.badge-primary.focus, a.badge-primary:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgePrimary, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgePrimary, 0.5); ?>; } a.badge-primary:focus, a.badge-primary:hover { - color: #fff !important; - background-color: <?php print colorDarker($badgePrimary, 10); ?>; + color: #fff !important; + background-color: <?php print colorDarker($badgePrimary, 10); ?>; } /* SECONDARY */ .badge-secondary, .tabs .badge { - color: #fff !important; - background-color: <?php print $badgeSecondary; ?>; + color: #fff !important; + background-color: <?php print $badgeSecondary; ?>; } a.badge-secondary.focus, a.badge-secondary:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeSecondary, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeSecondary, 0.5); ?>; } a.badge-secondary:focus, a.badge-secondary:hover { - color: #fff !important; - background-color: <?php print colorDarker($badgeSecondary, 10); ?>; + color: #fff !important; + background-color: <?php print colorDarker($badgeSecondary, 10); ?>; } /* SUCCESS */ .badge-success { - color: #fff !important; - background-color: <?php print $badgeSuccess; ?>; + color: #fff !important; + background-color: <?php print $badgeSuccess; ?>; } a.badge-success.focus, a.badge-success:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeSuccess, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeSuccess, 0.5); ?>; } a.badge-success:focus, a.badge-success:hover { - color: #fff !important; - background-color: <?php print colorDarker($badgeSuccess, 10); ?>; + color: #fff !important; + background-color: <?php print colorDarker($badgeSuccess, 10); ?>; } /* DANGER */ .badge-danger { - color: #fff !important; - background-color: <?php print $badgeDanger; ?>; + color: #fff !important; + background-color: <?php print $badgeDanger; ?>; } a.badge-danger.focus, a.badge-danger:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeDanger, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeDanger, 0.5); ?>; } a.badge-danger:focus, a.badge-danger:hover { - color: #fff !important; - background-color: <?php print colorDarker($badgeDanger, 10); ?>; + color: #fff !important; + background-color: <?php print colorDarker($badgeDanger, 10); ?>; } /* WARNING */ .badge-warning { - color: #fff !important; - background-color: <?php print $badgeWarning; ?>; + color: #fff !important; + background-color: <?php print $badgeWarning; ?>; } a.badge-warning.focus, a.badge-warning:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeWarning, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeWarning, 0.5); ?>; } a.badge-warning:focus, a.badge-warning:hover { - color: #212529 !important; - background-color: <?php print colorDarker($badgeWarning, 10); ?>; + color: #212529 !important; + background-color: <?php print colorDarker($badgeWarning, 10); ?>; } /* WARNING colorblind */ @@ -145,44 +147,44 @@ body[class*="colorblind-"] a.badge-warning:focus, a.badge-warning:hover { /* INFO */ .badge-info { - color: #fff !important; - background-color: <?php print $badgeInfo; ?>; + color: #fff !important; + background-color: <?php print $badgeInfo; ?>; } a.badge-info.focus, a.badge-info:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeInfo, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeInfo, 0.5); ?>; } a.badge-info:focus, a.badge-info:hover { - color: #fff !important; - background-color: <?php print colorDarker($badgeInfo, 10); ?>; + color: #fff !important; + background-color: <?php print colorDarker($badgeInfo, 10); ?>; } /* LIGHT */ .badge-light { - color: #212529 !important; - background-color: <?php print $badgeLight; ?>; + color: #212529 !important; + background-color: <?php print $badgeLight; ?>; } a.badge-light.focus, a.badge-light:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeLight, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeLight, 0.5); ?>; } a.badge-light:focus, a.badge-light:hover { - color: #212529 !important; - background-color: <?php print colorDarker($badgeLight, 10); ?>; + color: #212529 !important; + background-color: <?php print colorDarker($badgeLight, 10); ?>; } /* DARK */ .badge-dark { - color: #fff !important; - background-color: <?php print $badgeDark; ?>; + color: #fff !important; + background-color: <?php print $badgeDark; ?>; } a.badge-dark.focus, a.badge-dark:focus { - outline: 0; - box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeDark, 0.5); ?>; + outline: 0; + box-shadow: 0 0 0 0.2rem <?php print colorHexToRgb($badgeDark, 0.5); ?>; } a.badge-dark:focus, a.badge-dark:hover { - color: #fff !important; - background-color: <?php print colorDarker($badgeDark, 10); ?>; + color: #fff !important; + background-color: <?php print colorDarker($badgeDark, 10); ?>; } @@ -231,8 +233,12 @@ function _createStatusBadgeCss($statusName, $statusVarNamePrefix = '', $commentL $thisBadgeBackgroundColor = "#fff"; } - if (in_array((string) $statusName, array('0', '5', '9'))) $thisBadgeTextColor = '#999999'; - if (in_array((string) $statusName, array('6'))) $thisBadgeTextColor = '#777777'; + if (in_array((string) $statusName, array('0', '5', '9'))) { + $thisBadgeTextColor = '#999999'; + } + if (in_array((string) $statusName, array('6'))) { + $thisBadgeTextColor = '#777777'; + } print $cssPrefix.".badge-status".$statusName." {\n"; print " color: ".$thisBadgeTextColor." !important;\n"; diff --git a/htdocs/theme/md/btn.inc.php b/htdocs/theme/md/btn.inc.php index 1b27e7eeafb..c0d6e2c9cd7 100644 --- a/htdocs/theme/md/btn.inc.php +++ b/htdocs/theme/md/btn.inc.php @@ -1,17 +1,19 @@ <?php -if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> +if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* <style type="text/css" > */ :root { - --btncolortext:rgb(<?php print $colortextlink; ?>); - --btncolorbg: #fbfbfb; - --btncolorborderhover: none; - --btncolorborder: #FFF; - --butactiondeletebg: rgb(234,228,225); - /* tertiary color */ - /* --butactionbg:rgb(218, 235, 225); */ - /* --butactionbg:rgb(228, 218, 235); */ - --butactionbg:rgb(118, 145, 225); + --btncolortext:rgb(<?php print $colortextlink; ?>); + --btncolorbg: #fbfbfb; + --btncolorborderhover: none; + --btncolorborder: #FFF; + --butactiondeletebg: rgb(234,228,225); + /* tertiary color */ + /* --butactionbg:rgb(218, 235, 225); */ + /* --butactionbg:rgb(228, 218, 235); */ + --butactionbg:rgb(118, 145, 225); } <?php @@ -50,7 +52,7 @@ div.tabsAction > span.butAction, div.tabsAction > span.butActionRefused, div.tab margin-bottom: 1.4em !important; } div.tabsActionNoBottom > a.butAction, div.tabsActionNoBottom > a.butActionRefused { - margin-bottom: 0 !important; + margin-bottom: 0 !important; } span.butAction, span.butActionDelete { @@ -58,44 +60,49 @@ span.butAction, span.butActionDelete { } .butAction { - background: var(--butactionbg); - color: #FFF !important; - border-radius: 3px; - /* background: rgb(230, 232, 239); */ + background: var(--butactionbg); + color: #FFF !important; + /* background: rgb(230, 232, 239); */ +} +.butActionRefused, .butAction, .butActionDelete { + border-radius: 3px; +} +.butActionRefused:last-child, .butAction:last-child, .butActionDelete:last-child { + margin-right: 0px !important; } .butActionRefused, .butAction, .butAction:link, .butAction:visited, .butAction:hover, .butAction:active, .butActionDelete, .butActionDelete:link, .butActionDelete:visited, .butActionDelete:hover, .butActionDelete:active { - text-decoration: none; - text-transform: uppercase; - font-weight: bold; + text-decoration: none; + text-transform: uppercase; + font-weight: bold; - margin: 0em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.9'); ?>em; - padding: 0.6em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.7'); ?>em; - font-family: <?php print $fontlist ?>; - display: inline-block; - text-align: center; - cursor: pointer; - /* color: #fff; */ - /* background: rgb(<?php echo $colorbackhmenu1 ?>); */ - color: #444; - /* border: 1px solid #aaa; */ - /* border-color: rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.25); */ + margin: 0em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.9'); ?>em; + padding: 0.6em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.7'); ?>em; + font-family: <?php print $fontlist ?>; + display: inline-block; + text-align: center; + cursor: pointer; + /* color: #fff; */ + /* background: rgb(<?php echo $colorbackhmenu1 ?>); */ + color: #444; + /* border: 1px solid #aaa; */ + /* border-color: rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.25); */ - /*border-top-right-radius: 0 !important; - border-bottom-right-radius: 0 !important; - border-top-left-radius: 0 !important; - border-bottom-left-radius: 0 !important;*/ + /*border-top-right-radius: 0 !important; + border-bottom-right-radius: 0 !important; + border-top-left-radius: 0 !important; + border-bottom-left-radius: 0 !important;*/ } .butActionNew, .butActionNewRefused, .butActionNew:link, .butActionNew:visited, .butActionNew:hover, .butActionNew:active { - text-decoration: none; - text-transform: uppercase; - font-weight: normal; + text-decoration: none; + text-transform: uppercase; + font-weight: normal; - margin: 0em 0.3em 0 0.3em !important; - padding: 0.2em <?php echo ($dol_optimize_smallscreen ? '0.4' : '0.7'); ?>em 0.3em; - font-family: <?php print $fontlist ?>; - display: inline-block; - /* text-align: center; New button are on right of screen */ - cursor: pointer; + margin: 0em 0.3em 0 0.3em !important; + padding: 0.2em <?php echo ($dol_optimize_smallscreen ? '0.4' : '0.7'); ?>em 0.3em; + font-family: <?php print $fontlist ?>; + display: inline-block; + /* text-align: center; New button are on right of screen */ + cursor: pointer; } .button { @@ -211,61 +218,61 @@ span.butActionNewRefused>span.fa, span.butActionNewRefused>span.fa:hover } .butAction:hover { - -webkit-box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); - box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); + -webkit-box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); + box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); } .butActionNew:hover { - text-decoration: underline; - box-shadow: unset !important; + text-decoration: underline; + box-shadow: unset !important; } .butActionDelete, .butActionDelete:link, .butActionDelete:visited, .butActionDelete:hover, .butActionDelete:active, .buttonDelete { - background: var(--butactiondeletebg); - /* border: 1px solid #633; */ - color: #633; + background: var(--butactiondeletebg); + /* border: 1px solid #633; */ + color: #633; } .butActionDelete:hover { - -webkit-box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); - box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); + -webkit-box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); + box-shadow: 0px 0px 6px 1px rgba(50, 50, 50, 0.4), 0px 0px 0px rgba(60,60,60,0.1); } .butActionRefused { - text-decoration: none !important; - text-transform: uppercase; - font-weight: bold !important; + text-decoration: none !important; + text-transform: uppercase; + font-weight: bold !important; - white-space: nowrap !important; - cursor: not-allowed !important; - margin: 0em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.9'); ?>em; - padding: 0.6em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.7'); ?>em; - font-family: <?php print $fontlist ?> !important; - display: inline-block; - text-align: center; - cursor: pointer; - color: #999 !important; - border: 1px solid #ccc; - box-sizing: border-box; - -moz-box-sizing: border-box; - -webkit-box-sizing: border-box; + white-space: nowrap !important; + cursor: not-allowed !important; + margin: 0em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.9'); ?>em; + padding: 0.6em <?php echo ($dol_optimize_smallscreen ? '0.6' : '0.7'); ?>em; + font-family: <?php print $fontlist ?> !important; + display: inline-block; + text-align: center; + cursor: pointer; + color: #999 !important; + border: 1px solid #ccc; + box-sizing: border-box; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; } .butActionNewRefused, .butActionNewRefused:link, .butActionNewRefused:visited, .butActionNewRefused:hover, .butActionNewRefused:active { - text-decoration: none !important; - text-transform: uppercase; - font-weight: normal !important; + text-decoration: none !important; + text-transform: uppercase; + font-weight: normal !important; - white-space: nowrap !important; - cursor: not-allowed !important; - margin: 0em <?php echo ($dol_optimize_smallscreen ? '0.7' : '0.9'); ?>em; - padding: 0.2em <?php echo ($dol_optimize_smallscreen ? '0.4' : '0.7'); ?>em; - font-family: <?php print $fontlist ?> !important; - display: inline-block; - /* text-align: center; New button are on right of screen */ - cursor: pointer; - color: #999 !important; - padding-top: 0.2em; - box-shadow: none !important; - -webkit-box-shadow: none !important; + white-space: nowrap !important; + cursor: not-allowed !important; + margin: 0em <?php echo ($dol_optimize_smallscreen ? '0.7' : '0.9'); ?>em; + padding: 0.2em <?php echo ($dol_optimize_smallscreen ? '0.4' : '0.7'); ?>em; + font-family: <?php print $fontlist ?> !important; + display: inline-block; + /* text-align: center; New button are on right of screen */ + cursor: pointer; + color: #999 !important; + padding-top: 0.2em; + box-shadow: none !important; + -webkit-box-shadow: none !important; } .butActionTransparent { @@ -279,41 +286,41 @@ TITLE BUTTON */ div.pagination li:first-child a.btnTitle { - margin-left: 10px; + margin-left: 10px; } .btnTitle, a.btnTitle { - display: inline-block; - padding: 6px 12px; - font-size: 14px - font-weight: 400; - line-height: 1.4; - text-align: center; - white-space: nowrap; - vertical-align: middle; - -ms-touch-action: manipulation; - touch-action: manipulation; - cursor: pointer; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; - box-shadow: none; - text-decoration: none; - position: relative; - margin: 0 0 0 10px; - min-width: 80px; - text-align: center; - color: rgb(<?php print $colortextlink; ?>); - border: none; - font-size: 12px; - font-weight: 300; - background-color: #fbfbfb; + display: inline-block; + padding: 6px 12px; + font-size: 14px + font-weight: 400; + line-height: 1.4; + text-align: center; + white-space: nowrap; + vertical-align: middle; + -ms-touch-action: manipulation; + touch-action: manipulation; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + box-shadow: none; + text-decoration: none; + position: relative; + margin: 0 0 0 10px; + min-width: 80px; + text-align: center; + color: rgb(<?php print $colortextlink; ?>); + border: none; + font-size: 12px; + font-weight: 300; + background-color: #fbfbfb; } a.btnTitle.btnTitleSelected { - border: 1px solid #ccc; - border-radius: 3px; + border: 1px solid #ccc; + border-radius: 3px; } .btnTitle > .btnTitle-icon{ @@ -321,42 +328,42 @@ a.btnTitle.btnTitleSelected { } .btnTitle > .btnTitle-label{ - color: #666666; + color: #666666; } .btnTitle:hover, a.btnTitle:hover { - border-radius: 3px; - position: relative; - margin: 0 0 0 10px; - text-align: center; - color: #ffffff; - background-color: rgb(<?php print $colortextlink; ?>); - font-size: 12px; - text-decoration: none; - box-shadow: none; + border-radius: 3px; + position: relative; + margin: 0 0 0 10px; + text-align: center; + color: #ffffff; + background-color: rgb(<?php print $colortextlink; ?>); + font-size: 12px; + text-decoration: none; + box-shadow: none; } .btnTitle.refused, a.btnTitle.refused, .btnTitle.refused:hover, a.btnTitle.refused:hover { - color: #8a8a8a; - cursor: not-allowed; - background-color: #fbfbfb; - background: repeating-linear-gradient( 45deg, #ffffff, #f1f1f1 4px, #f1f1f1 4px, #f1f1f1 4px ); + color: #8a8a8a; + cursor: not-allowed; + background-color: #fbfbfb; + background: repeating-linear-gradient( 45deg, #ffffff, #f1f1f1 4px, #f1f1f1 4px, #f1f1f1 4px ); } .btnTitle:hover .btnTitle-label{ - color: #ffffff; + color: #ffffff; } div.pagination .btnTitle:hover .btnTitle-label{ color: rgb(<?php print $colortextlink; ?>); } .btnTitle.refused .btnTitle-label, .btnTitle.refused:hover .btnTitle-label{ - color: #8a8a8a; + color: #8a8a8a; } .btnTitle>.fa { - font-size: 20px; - display: block; + font-size: 20px; + display: block; } /* rule to reduce top menu - 2nd reduction: Reduce width of top menu icons again */ @@ -366,15 +373,15 @@ div.pagination .btnTitle:hover .btnTitle-label{ font-size: 0.95em; } .btnTitle, a.btnTitle { - display: inline-block; - padding: 4px 4px 4px 4px; + display: inline-block; + padding: 4px 4px 4px 4px; min-width: unset; } } <?php if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin)) { ?> .butActionRefused, .butActionNewRefused, .btnTitle.refused { - display: none !important; + display: none !important; } <?php } ?> diff --git a/htdocs/theme/md/ckeditor/config.js b/htdocs/theme/md/ckeditor/config.js index 50ff0cc6eed..acd38268f8f 100644 --- a/htdocs/theme/md/ckeditor/config.js +++ b/htdocs/theme/md/ckeditor/config.js @@ -9,6 +9,9 @@ CKEDITOR.editorConfig = function( config ) // http://docs.cksource.com/CKEditor_3.x/Developers_Guide // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html config.enterMode = CKEDITOR.ENTER_BR; + //config.forceSimpleAmpersand = true; // When you put a <img src="x?a=a&b=b"> into the textarea, and go into "source", then ckeditor change the & into &amp;. We don't want this. But this option does not fix this. + //config.entities = false; // When you put a <img src="x?a=a&b=b"> into the textarea, and go into "source", then ckeditor change the & into &amp;. We don't want this. But this option does not fix this. + //config.entities_greek = false; config.resize_enabled = false; //config.resize_maxHeight = 3000; //config.resize_maxWidth = 3000; diff --git a/htdocs/theme/md/dropdown.inc.php b/htdocs/theme/md/dropdown.inc.php index 6f7d55a285c..9b96c9b061b 100644 --- a/htdocs/theme/md/dropdown.inc.php +++ b/htdocs/theme/md/dropdown.inc.php @@ -1,5 +1,7 @@ <?php -if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> +if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* <style type="text/css" > dont remove this line it's an ide hack */ /* @@ -7,15 +9,15 @@ if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> */ .bookmark-footer a.top-menu-dropdown-link { - white-space: normal; + white-space: normal; } button.dropdown-item.global-search-item { - outline: none; + outline: none; } .open>.dropdown-search, .open>.dropdown-bookmark, .open>.dropdown-menu, .dropdown dd ul.open { - display: block; + display: block; } @@ -23,9 +25,9 @@ button.dropdown-item.global-search-item { color: #fff; } div#topmenu-bookmark-dropdown { - position: fixed; - right: 20px; - top: 0px; + position: fixed; + right: 20px; + top: 0px; } #topmenu-login-dropdown .dropdown-toggle:after { @@ -33,347 +35,347 @@ div#topmenu-bookmark-dropdown { } #topmenu-bookmark-dropdown .dropdown-menu { - width: 300px; + width: 300px; } button.dropdown-item.global-search-item { - outline: none; + outline: none; } .open>.dropdown-search, .open>.dropdown-bookmark, .open>.dropdown-menu{ - display: block; + display: block; } .dropdown-search { - border-color: #eee; + border-color: #eee; - position: absolute; - top: 100%; - left: 0; - z-index: 1000; - display: none; - float: left; - min-width: 160px; - margin: 2px 0 0; - font-size: 14px; - text-align: left; - list-style: none; - background-color: #fff; - -webkit-background-clip: padding-box; - background-clip: padding-box; - border: 1px solid #ccc; - border: 1px solid rgba(0,0,0,.15); - border-radius: 4px; - -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); - box-shadow: 0 6px 12px rgba(0,0,0,.175); + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 160px; + margin: 2px 0 0; + font-size: 14px; + text-align: left; + list-style: none; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0,0,0,.15); + border-radius: 4px; + -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); + box-shadow: 0 6px 12px rgba(0,0,0,.175); } .dropdown-bookmark { - border-color: #eee; + border-color: #eee; - position: absolute; - top: 100%; - left: 0; - z-index: 1000; - display: none; - float: left; - min-width: 160px; - margin: 2px 0 0; - font-size: 14px; - text-align: left; - list-style: none; - background-color: #fff; - -webkit-background-clip: padding-box; - background-clip: padding-box; - border: 1px solid #ccc; - border: 1px solid rgba(0,0,0,.15); - border-radius: 4px; - -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); - box-shadow: 0 6px 12px rgba(0,0,0,.175); + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 160px; + margin: 2px 0 0; + font-size: 14px; + text-align: left; + list-style: none; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0,0,0,.15); + border-radius: 4px; + -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); + box-shadow: 0 6px 12px rgba(0,0,0,.175); } .dropdown-menu { - border-color: #eee; + border-color: #eee; - position: absolute; - top: 100%; - left: 0; - z-index: 1000; - display: none; - float: left; - min-width: 160px; - margin: 2px 0 0; - font-size: 14px; - text-align: left; - list-style: none; - background-color: #fff; - -webkit-background-clip: padding-box; - background-clip: padding-box; - border: 1px solid #ccc; - border: 1px solid rgba(0,0,0,.15); - border-radius: 4px; - -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); - box-shadow: 0 6px 12px rgba(0,0,0,.175); + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 160px; + margin: 2px 0 0; + font-size: 14px; + text-align: left; + list-style: none; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0,0,0,.15); + border-radius: 4px; + -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); + box-shadow: 0 6px 12px rgba(0,0,0,.175); } .dropdown-toggle{ - text-decoration: none !important; + text-decoration: none !important; } .dropdown-toggle::after { - /* font part */ - font-family: "Font Awesome 5 Free"; - font-size: 0.7em; - font-weight: 900; - font-style: normal; - font-variant: normal; - text-rendering: auto; - -webkit-font-smoothing: antialiased; - text-align:center; - text-decoration:none; - margin: auto 3px; - display: inline-block; - content: "\f078"; + /* font part */ + font-family: "Font Awesome 5 Free"; + font-size: 0.7em; + font-weight: 900; + font-style: normal; + font-variant: normal; + text-rendering: auto; + -webkit-font-smoothing: antialiased; + text-align:center; + text-decoration:none; + margin: auto 3px; + display: inline-block; + content: "\f078"; - -webkit-transition: -webkit-transform .2s ease-in-out; - -ms-transition: -ms-transform .2s ease-in-out; - transition: transform .2s ease-in-out; + -webkit-transition: -webkit-transform .2s ease-in-out; + -ms-transition: -ms-transform .2s ease-in-out; + transition: transform .2s ease-in-out; } .open>.dropdown-toggle::after { - transform: rotate(180deg); + transform: rotate(180deg); } /* * MENU Dropdown */ .login_block.usedropdown .logout-btn{ - /* display: none; */ + /* display: none; */ } .tmenu .open.dropdown, .tmenu .open.dropdown { - background: rgba(0, 0, 0, 0.1); + background: rgba(0, 0, 0, 0.1); } .tmenu .dropdown-menu, .login_block .dropdown-menu { - position: absolute; - right: 0; - <?php echo $left; ?>: auto; - line-height:1.3em; + position: absolute; + right: 0; + <?php echo $left; ?>: auto; + line-height:1.3em; } .tmenu .dropdown-menu, .login_block .dropdown-menu .user-body { - border-bottom-right-radius: 4px; - border-bottom-left-radius: 4px; + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; } .user-body { - color: #333; + color: #333; } .side-nav-vert .user-menu .dropdown-menu { - border-top-right-radius: 0; - border-top-left-radius: 0; - padding: 1px 0 0 0; - border-top-width: 0; - width: 300px; + border-top-right-radius: 0; + border-top-left-radius: 0; + padding: 1px 0 0 0; + border-top-width: 0; + width: 300px; } .side-nav-vert .user-menu .dropdown-menu { - margin-top: 0; - border-top-left-radius: 0; - border-top-right-radius: 0; + margin-top: 0; + border-top-left-radius: 0; + border-top-right-radius: 0; } .side-nav-vert .user-menu .dropdown-menu > .user-header { - min-height: 100px; - padding: 10px; - text-align: center; - white-space: normal; + min-height: 100px; + padding: 10px; + text-align: center; + white-space: normal; } #topmenu-global-search-dropdown .dropdown-menu{ - width: 300px; - max-width: 100%; + width: 300px; + max-width: 100%; } div#topmenu-global-search-dropdown, div#topmenu-bookmark-dropdown { - line-height: 46px; + line-height: 46px; } a.top-menu-dropdown-link { - padding: 8px; + padding: 8px; } .dropdown-user-image { - border-radius: 50%; - vertical-align: middle; - z-index: 5; - height: 90px; - width: 90px; - border: 3px solid; - border-color: transparent; - border-color: rgba(255, 255, 255, 0.2); - max-width: 100%; - max-height :100%; + border-radius: 50%; + vertical-align: middle; + z-index: 5; + height: 90px; + width: 90px; + border: 3px solid; + border-color: transparent; + border-color: rgba(255, 255, 255, 0.2); + max-width: 100%; + max-height :100%; } .dropdown-menu > .user-header{ - background: rgb(<?php echo $colorbackhmenu1 ?>); + background: rgb(<?php echo $colorbackhmenu1 ?>); } .dropdown-menu .dropdown-header{ - padding: 8px 10px 10px 10px; + padding: 8px 10px 10px 10px; } .dropdown-menu > .user-footer { - background-color: #f9f9f9; - padding: 10px; + background-color: #f9f9f9; + padding: 10px; } .user-footer:after { - clear: both; + clear: both; } .dropdown-menu > .bookmark-footer{ - border-top: 1px solid #f0f0f0; - background-color: #f9f9f9; - padding: 10px; + border-top: 1px solid #f0f0f0; + background-color: #f9f9f9; + padding: 10px; } .dropdown-menu > .user-body, .dropdown-body{ - padding: 15px; - border-bottom: 1px solid #f4f4f4; - border-top: 1px solid #dddddd; - white-space: normal; + padding: 15px; + border-bottom: 1px solid #f4f4f4; + border-top: 1px solid #dddddd; + white-space: normal; } .dropdown-menu > .bookmark-body, .dropdown-body{ - padding: 10px 0; - overflow-y: auto; - max-height: 60vh ; /* fallback for browsers without support for calc() */ - max-height: calc(90vh - 110px) ; + padding: 10px 0; + overflow-y: auto; + max-height: 60vh ; /* fallback for browsers without support for calc() */ + max-height: calc(90vh - 110px) ; white-space: normal; } #topmenu-bookmark-dropdown .dropdown-menu > .bookmark-body, #topmenu-bookmark-dropdown .dropdown-body{ - max-height: 60vh ; /* fallback for browsers without support for calc() */ - max-height: calc(90vh - 200px) ; + max-height: 60vh ; /* fallback for browsers without support for calc() */ + max-height: calc(90vh - 200px) ; } .dropdown-body::-webkit-scrollbar { - width: 8px; - } + width: 8px; + } .dropdown-body::-webkit-scrollbar-thumb { - -webkit-border-radius: 0; - border-radius: 0; - /* background: rgb(<?php echo $colorbackhmenu1 ?>); */ - background: #aaa; + -webkit-border-radius: 0; + border-radius: 0; + /* background: rgb(<?php echo $colorbackhmenu1 ?>); */ + background: #aaa; } .dropdown-body::-webkit-scrollbar-track { - -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); - -webkit-border-radius: 0; - border-radius: 0; + -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); + -webkit-border-radius: 0; + border-radius: 0; } #topmenu-login-dropdown, #topmenu-bookmark-dropdown, #topmenu-global-search-dropdown { - padding: 0 5px 0 5px; + padding: 0 5px 0 5px; } #topmenu-login-dropdown a:hover{ - text-decoration: none; + text-decoration: none; } #topmenuloginmoreinfo-btn{ - display: block; - text-aling: right; - color:#666; - cursor: pointer; + display: block; + text-aling: right; + color:#666; + cursor: pointer; } #topmenuloginmoreinfo{ - display: none; - clear: both; - font-size: 0.95em; + display: none; + clear: both; + font-size: 0.95em; } .button-top-menu-dropdown { - display: inline-block; - padding: 6px 12px; - margin-bottom: 0; - font-size: 14px; - font-weight: 400; - line-height: 1.42857143; - text-align: center; - white-space: nowrap; - vertical-align: middle; - -ms-touch-action: manipulation; - touch-action: manipulation; - cursor: pointer; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; - background-image: none; - border: 1px solid transparent; - border-radius: 4px; + display: inline-block; + padding: 6px 12px; + margin-bottom: 0; + font-size: 14px; + font-weight: 400; + line-height: 1.42857143; + text-align: center; + white-space: nowrap; + vertical-align: middle; + -ms-touch-action: manipulation; + touch-action: manipulation; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + background-image: none; + border: 1px solid transparent; + border-radius: 4px; } .user-footer .button-top-menu-dropdown { - color: #666666; - border-radius: 0; - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; - border-width: 1px; - background-color: #f4f4f4; - border-color: #ddd; + color: #666666; + border-radius: 0; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + border-width: 1px; + background-color: #f4f4f4; + border-color: #ddd; } .dropdown-menu a.top-menu-dropdown-link { - color: rgb(<?php print $colortextlink; ?>) !important; - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; - display: block; - margin: 5px 0px; + color: rgb(<?php print $colortextlink; ?>) !important; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + display: block; + margin: 5px 0px; } .dropdown-item { - display: block !important; - box-sizing: border-box; - width: 100%; - padding: .25rem 1.5rem .25rem 1rem; - clear: both; - font-weight: 400; - color: #212529 !important; - text-align: inherit; - background-color: transparent; - border: 0; + display: block !important; + box-sizing: border-box; + width: 100%; + padding: .25rem 1.5rem .25rem 1rem; + clear: both; + font-weight: 400; + color: #212529 !important; + text-align: inherit; + background-color: transparent; + border: 0; - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; } .dropdown-item::before { - /* font part */ - font-family: "Font Awesome 5 Free"; - font-weight: 900; - font-style: normal; - font-variant: normal; - text-rendering: auto; - -webkit-font-smoothing: antialiased; - text-align:center; - text-decoration:none; - margin-right: 5px; - display: inline-block; - content: "\f0da"; - color: rgba(0,0,0,0.3); + /* font part */ + font-family: "Font Awesome 5 Free"; + font-weight: 900; + font-style: normal; + font-variant: normal; + text-rendering: auto; + -webkit-font-smoothing: antialiased; + text-align:center; + text-decoration:none; + margin-right: 5px; + display: inline-block; + content: "\f0da"; + color: rgba(0,0,0,0.3); } .dropdown-item.active, .dropdown-item:hover, .dropdown-item:focus { - color: #<?php echo $colortextbackhmenu; ?> !important; - text-decoration: none; - background: rgb(<?php echo $colorbackhmenu1 ?>); + color: #<?php echo $colortextbackhmenu; ?> !important; + text-decoration: none; + background: rgb(<?php echo $colorbackhmenu1 ?>); } /* @@ -381,26 +383,26 @@ a.top-menu-dropdown-link { */ .dropdown-search-input { - width: 100%; - padding: 10px 35px 10px 20px; + width: 100%; + padding: 10px 35px 10px 20px; - background-color: transparent; - font-size: 14px; - line-height: 16px; - box-sizing: border-box; + background-color: transparent; + font-size: 14px; + line-height: 16px; + box-sizing: border-box; - color: #575756; - background-color: transparent; - background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'/%3E%3Cpath d='M0 0h24v24H0z' fill='none'/%3E%3C/svg%3E"); - background-repeat: no-repeat; - background-size: 16px 16px; - background-position: 95% center; - border-radius: 50px; - border: 1px solid #c4c4c2 !important; - transition: all 250ms ease-in-out; - backface-visibility: hidden; - transform-style: preserve-3d; + color: #575756; + background-color: transparent; + background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'/%3E%3Cpath d='M0 0h24v24H0z' fill='none'/%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-size: 16px 16px; + background-position: 95% center; + border-radius: 50px; + border: 1px solid #c4c4c2 !important; + transition: all 250ms ease-in-out; + backface-visibility: hidden; + transform-style: preserve-3d; } @@ -421,11 +423,11 @@ a.top-menu-dropdown-link { } div#topmenu-global-search-dropdown, div#topmenu-bookmark-dropdown { - line-height: unset; + line-height: unset; } ul.tmenu { - margin-right: 2px; + margin-right: 2px; } } @@ -450,10 +452,10 @@ a.top-menu-dropdown-link { .dropdown-search-input::placeholder { - color: color(#575756 a(0.8)); - letter-spacing: 1.5px; + color: color(#575756 a(0.8)); + letter-spacing: 1.5px; } .hidden-search-result{ - display: none !important; + display: none !important; } diff --git a/htdocs/theme/md/img/menus/agenda.png b/htdocs/theme/md/img/menus/agenda.png deleted file mode 100644 index 35d8b1b3169..00000000000 Binary files a/htdocs/theme/md/img/menus/agenda.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/bank.png b/htdocs/theme/md/img/menus/bank.png deleted file mode 100644 index b83e7cd310a..00000000000 Binary files a/htdocs/theme/md/img/menus/bank.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/cart.png b/htdocs/theme/md/img/menus/cart.png deleted file mode 100644 index 8d8da880f0e..00000000000 Binary files a/htdocs/theme/md/img/menus/cart.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/chart.png b/htdocs/theme/md/img/menus/chart.png deleted file mode 100644 index 18559b692d1..00000000000 Binary files a/htdocs/theme/md/img/menus/chart.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/commercial.png b/htdocs/theme/md/img/menus/commercial.png deleted file mode 100644 index ba06d79a766..00000000000 Binary files a/htdocs/theme/md/img/menus/commercial.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/company.png b/htdocs/theme/md/img/menus/company.png deleted file mode 100644 index 7b9227c0674..00000000000 Binary files a/htdocs/theme/md/img/menus/company.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/ecm.png b/htdocs/theme/md/img/menus/ecm.png deleted file mode 100644 index 1bb8e0dafd6..00000000000 Binary files a/htdocs/theme/md/img/menus/ecm.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/externalsite.png b/htdocs/theme/md/img/menus/externalsite.png deleted file mode 100644 index 8abd6437ea6..00000000000 Binary files a/htdocs/theme/md/img/menus/externalsite.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/ftp.png b/htdocs/theme/md/img/menus/ftp.png deleted file mode 100644 index a70a9d29b77..00000000000 Binary files a/htdocs/theme/md/img/menus/ftp.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/generic1.png b/htdocs/theme/md/img/menus/generic1.png deleted file mode 100644 index ef13122ace5..00000000000 Binary files a/htdocs/theme/md/img/menus/generic1.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/generic1_over.png b/htdocs/theme/md/img/menus/generic1_over.png deleted file mode 100644 index 29023816e67..00000000000 Binary files a/htdocs/theme/md/img/menus/generic1_over.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/generic2.png b/htdocs/theme/md/img/menus/generic2.png deleted file mode 100644 index ef13122ace5..00000000000 Binary files a/htdocs/theme/md/img/menus/generic2.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/generic2_over.png b/htdocs/theme/md/img/menus/generic2_over.png deleted file mode 100644 index 62eed5564b6..00000000000 Binary files a/htdocs/theme/md/img/menus/generic2_over.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/generic3.png b/htdocs/theme/md/img/menus/generic3.png deleted file mode 100644 index ef13122ace5..00000000000 Binary files a/htdocs/theme/md/img/menus/generic3.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/generic3_over.png b/htdocs/theme/md/img/menus/generic3_over.png deleted file mode 100644 index 29023816e67..00000000000 Binary files a/htdocs/theme/md/img/menus/generic3_over.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/generic4.png b/htdocs/theme/md/img/menus/generic4.png deleted file mode 100644 index ef13122ace5..00000000000 Binary files a/htdocs/theme/md/img/menus/generic4.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/generic4_over.png b/htdocs/theme/md/img/menus/generic4_over.png deleted file mode 100644 index 29023816e67..00000000000 Binary files a/htdocs/theme/md/img/menus/generic4_over.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/globe.png b/htdocs/theme/md/img/menus/globe.png deleted file mode 100644 index 0bc7dfd4802..00000000000 Binary files a/htdocs/theme/md/img/menus/globe.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/graph.png b/htdocs/theme/md/img/menus/graph.png deleted file mode 100644 index fb04031d47a..00000000000 Binary files a/htdocs/theme/md/img/menus/graph.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/holiday.png b/htdocs/theme/md/img/menus/holiday.png deleted file mode 100644 index 014c9918c2e..00000000000 Binary files a/htdocs/theme/md/img/menus/holiday.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/home.png b/htdocs/theme/md/img/menus/home.png deleted file mode 100644 index c5441fa2962..00000000000 Binary files a/htdocs/theme/md/img/menus/home.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/index.html b/htdocs/theme/md/img/menus/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/theme/md/img/menus/mail.png b/htdocs/theme/md/img/menus/mail.png deleted file mode 100644 index 7b65a3d522e..00000000000 Binary files a/htdocs/theme/md/img/menus/mail.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/members.png b/htdocs/theme/md/img/menus/members.png deleted file mode 100644 index 270e4de2e05..00000000000 Binary files a/htdocs/theme/md/img/menus/members.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/menu.png b/htdocs/theme/md/img/menus/menu.png deleted file mode 100644 index 526e1975ab0..00000000000 Binary files a/htdocs/theme/md/img/menus/menu.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/money.png b/htdocs/theme/md/img/menus/money.png deleted file mode 100644 index 707d1676167..00000000000 Binary files a/htdocs/theme/md/img/menus/money.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/pointofsale.png b/htdocs/theme/md/img/menus/pointofsale.png deleted file mode 100644 index 8826337cd31..00000000000 Binary files a/htdocs/theme/md/img/menus/pointofsale.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/products.png b/htdocs/theme/md/img/menus/products.png deleted file mode 100644 index f614d17171a..00000000000 Binary files a/htdocs/theme/md/img/menus/products.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/project.png b/htdocs/theme/md/img/menus/project.png deleted file mode 100644 index 54f4aa382fe..00000000000 Binary files a/htdocs/theme/md/img/menus/project.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/shop.png b/htdocs/theme/md/img/menus/shop.png deleted file mode 100644 index 16b6cd01fbc..00000000000 Binary files a/htdocs/theme/md/img/menus/shop.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/ticket.png b/htdocs/theme/md/img/menus/ticket.png deleted file mode 100644 index 57fc2aedb5b..00000000000 Binary files a/htdocs/theme/md/img/menus/ticket.png and /dev/null differ diff --git a/htdocs/theme/md/img/menus/tools.png b/htdocs/theme/md/img/menus/tools.png deleted file mode 100644 index 244478041a4..00000000000 Binary files a/htdocs/theme/md/img/menus/tools.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/index.html b/htdocs/theme/md/img/weather/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/theme/md/img/weather/weather-clear-night.png b/htdocs/theme/md/img/weather/weather-clear-night.png deleted file mode 100644 index f89b2ad8cad..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-clear-night.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-clear.png b/htdocs/theme/md/img/weather/weather-clear.png deleted file mode 100644 index ed1d48065f3..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-clear.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-clouds-night.png b/htdocs/theme/md/img/weather/weather-clouds-night.png deleted file mode 100644 index 0c74a6a37b4..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-clouds-night.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-clouds.png b/htdocs/theme/md/img/weather/weather-clouds.png deleted file mode 100644 index 75a8d230e50..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-clouds.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-few-clouds-night.png b/htdocs/theme/md/img/weather/weather-few-clouds-night.png deleted file mode 100644 index e2bbfee2b0e..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-few-clouds-night.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-few-clouds.png b/htdocs/theme/md/img/weather/weather-few-clouds.png deleted file mode 100644 index 3f188e6220d..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-few-clouds.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-freezing-rain.png b/htdocs/theme/md/img/weather/weather-freezing-rain.png deleted file mode 100644 index d270b5ae1bb..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-freezing-rain.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-hail.png b/htdocs/theme/md/img/weather/weather-hail.png deleted file mode 100644 index 9df0bdc24d7..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-hail.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-many-clouds.png b/htdocs/theme/md/img/weather/weather-many-clouds.png deleted file mode 100644 index de4cae7e8e1..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-many-clouds.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-mist.png b/htdocs/theme/md/img/weather/weather-mist.png deleted file mode 100644 index a2b57a5e408..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-mist.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-showers-day.png b/htdocs/theme/md/img/weather/weather-showers-day.png deleted file mode 100644 index 0b8e3149311..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-showers-day.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-showers-night.png b/htdocs/theme/md/img/weather/weather-showers-night.png deleted file mode 100644 index 1fff3febf5c..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-showers-night.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-showers-scattered-day.png b/htdocs/theme/md/img/weather/weather-showers-scattered-day.png deleted file mode 100644 index ae098117351..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-showers-scattered-day.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-showers-scattered-night.png b/htdocs/theme/md/img/weather/weather-showers-scattered-night.png deleted file mode 100644 index ad0283a08db..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-showers-scattered-night.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-showers-scattered.png b/htdocs/theme/md/img/weather/weather-showers-scattered.png deleted file mode 100644 index 9d4abf53203..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-showers-scattered.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-showers.png b/htdocs/theme/md/img/weather/weather-showers.png deleted file mode 100644 index 38cd41f03b5..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-showers.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-snow-rain.png b/htdocs/theme/md/img/weather/weather-snow-rain.png deleted file mode 100644 index dc742aa1c4c..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-snow-rain.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-snow-scattered-day.png b/htdocs/theme/md/img/weather/weather-snow-scattered-day.png deleted file mode 100644 index 0048fec3df0..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-snow-scattered-day.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-snow-scattered-night.png b/htdocs/theme/md/img/weather/weather-snow-scattered-night.png deleted file mode 100644 index d8b0ccaa7ff..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-snow-scattered-night.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-snow-scattered.png b/htdocs/theme/md/img/weather/weather-snow-scattered.png deleted file mode 100644 index dff11fb3342..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-snow-scattered.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-snow.png b/htdocs/theme/md/img/weather/weather-snow.png deleted file mode 100644 index 16e4b472e7e..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-snow.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-storm-day.png b/htdocs/theme/md/img/weather/weather-storm-day.png deleted file mode 100644 index 3d434f5a768..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-storm-day.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-storm-night.png b/htdocs/theme/md/img/weather/weather-storm-night.png deleted file mode 100644 index 4075950838a..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-storm-night.png and /dev/null differ diff --git a/htdocs/theme/md/img/weather/weather-storm.png b/htdocs/theme/md/img/weather/weather-storm.png deleted file mode 100644 index 6e5360313b7..00000000000 Binary files a/htdocs/theme/md/img/weather/weather-storm.png and /dev/null differ diff --git a/htdocs/theme/md/info-box.inc.php b/htdocs/theme/md/info-box.inc.php index a784a1ec7d9..0946315391a 100644 --- a/htdocs/theme/md/info-box.inc.php +++ b/htdocs/theme/md/info-box.inc.php @@ -1,5 +1,7 @@ <?php -if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> +if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* <style type="text/css" > */ @@ -12,10 +14,16 @@ if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $prefix = ''; -if (!empty($conf->global->THEME_INFOBOX_COLOR_ON_BACKGROUND)) $prefix = 'background-'; +if (!empty($conf->global->THEME_INFOBOX_COLOR_ON_BACKGROUND)) { + $prefix = 'background-'; +} -if (!isset($conf->global->THEME_SATURATE_RATIO)) $conf->global->THEME_SATURATE_RATIO = 0.7; -if (GETPOSTISSET('THEME_SATURATE_RATIO')) $conf->global->THEME_SATURATE_RATIO = GETPOST('THEME_SATURATE_RATIO', 'int'); +if (!isset($conf->global->THEME_SATURATE_RATIO)) { + $conf->global->THEME_SATURATE_RATIO = 0.7; +} +if (GETPOSTISSET('THEME_SATURATE_RATIO')) { + $conf->global->THEME_SATURATE_RATIO = GETPOST('THEME_SATURATE_RATIO', 'int'); +} ?> @@ -112,14 +120,14 @@ if (GETPOSTISSET('THEME_SATURATE_RATIO')) $conf->global->THEME_SATURATE_RATIO = .info-box-module-external span.info-box-icon-version { - background: #bbb; + background: #bbb; } a.info-box-text.info-box-text-a { - display: table-cell; + display: table-cell; } a.info-box-text-a i.fa.fa-exclamation-triangle { - font-size: 0.9em; + font-size: 0.9em; } .info-box { @@ -134,14 +142,14 @@ a.info-box-text-a i.fa.fa-exclamation-triangle { border: 1px solid #e9e9e9; } .info-box.info-box-sm{ - min-height: 80px; - margin-bottom: 10px; + min-height: 80px; + margin-bottom: 10px; } .info-box-more { - float: right; - top: 4px; - position: absolute; - right: 10px; + float: right; + top: 4px; + position: absolute; + right: 10px; } .info-box small { @@ -182,17 +190,17 @@ a.info-box-text-a i.fa.fa-exclamation-triangle { font-size: 45px; line-height: 90px; background: #eee; - <?php if (isset($conf->global->THEME_SATURATE_RATIO)) { ?> - filter: saturate(<?php echo $conf->global->THEME_SATURATE_RATIO; ?>); - <?php } ?> + <?php if (isset($conf->global->THEME_SATURATE_RATIO)) { ?> + filter: saturate(<?php echo $conf->global->THEME_SATURATE_RATIO; ?>); + <?php } ?> } .info-box-sm .info-box-icon { - width: 80px; - font-size: 25px; - line-height: 92px; + width: 80px; + font-size: 25px; + line-height: 92px; } .opened-dash-board-wrap .info-box-sm .info-box-icon { - line-height: 80px; + line-height: 80px; } .info-box-module .info-box-icon { height: 98px; @@ -201,69 +209,69 @@ a.info-box-text-a i.fa.fa-exclamation-triangle { max-width: 100%; } .info-box-module .info-box-icon > img { - max-width: 55%; + max-width: 55%; } .info-box-icon-text{ - box-sizing: border-box; - display: block; - position: absolute; - width: 90px; - bottom: 0px; - color: #ffffff; - background-color: rgba(0,0,0,0.1); - cursor: default; + box-sizing: border-box; + display: block; + position: absolute; + width: 90px; + bottom: 0px; + color: #ffffff; + background-color: rgba(0,0,0,0.1); + cursor: default; - font-size: 10px; - line-height: 15px; - padding: 0px 3px; - text-align: center; - opacity: 0; - -webkit-transition: opacity 0.5s, visibility 0s 0.5s; - transition: opacity 0.5s, visibility 0s 0.5s; + font-size: 10px; + line-height: 15px; + padding: 0px 3px; + text-align: center; + opacity: 0; + -webkit-transition: opacity 0.5s, visibility 0s 0.5s; + transition: opacity 0.5s, visibility 0s 0.5s; } .info-box-icon-version { - box-sizing: border-box; - display: block; - position: absolute; - width: 90px; - bottom: 0px; - color: #ffffff; - background-color: rgba(0,0,0,0.1); - cursor: default; + box-sizing: border-box; + display: block; + position: absolute; + width: 90px; + bottom: 0px; + color: #ffffff; + background-color: rgba(0,0,0,0.1); + cursor: default; - font-size: 10px; - line-height: 22px; - padding: 0px 3px; - text-align: center; - opacity: 1; - -webkit-transition: opacity 0.5s, visibility 0s 0.5s; - transition: opacity 0.5s, visibility 0s 0.5s; + font-size: 10px; + line-height: 22px; + padding: 0px 3px; + text-align: center; + opacity: 1; + -webkit-transition: opacity 0.5s, visibility 0s 0.5s; + transition: opacity 0.5s, visibility 0s 0.5s; } .box-flex-item.info-box-module.info-box-module-disabled { - /* opacity: 0.6; */ + /* opacity: 0.6; */ } .info-box-actions { position: absolute; - right: 0; - bottom: 0; + right: 0; + bottom: 0; } <?php if (empty($conf->global->MAIN_DISABLE_GLOBAL_BOXSTATS) && !empty($conf->global->MAIN_INCLUDE_GLOBAL_STATS_IN_OPENED_DASHBOARD)) { ?> .info-box-icon-text{ - opacity: 1; + opacity: 1; } <?php } ?> .info-box-sm .info-box-icon-text, .info-box-sm .info-box-icon-version{ - overflow: hidden; - width: 80px; + overflow: hidden; + width: 80px; } .info-box:hover .info-box-icon-text{ - opacity: 1; + opacity: 1; } .info-box-content { @@ -291,7 +299,7 @@ a.info-box-text-a i.fa.fa-exclamation-triangle { margin-bottom: 6px; } .info-box-title { - width: calc(100% - 20px); + width: calc(100% - 20px); } .info-box-text{ font-size: 0.92em; @@ -315,8 +323,12 @@ a.info-box-text{ text-decoration: none;} } <?php include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -if (!isset($conf->global->THEME_SATURATE_RATIO)) $conf->global->THEME_SATURATE_RATIO = 0.7; -if (GETPOSTISSET('THEME_SATURATE_RATIO')) $conf->global->THEME_SATURATE_RATIO = GETPOST('THEME_SATURATE_RATIO', 'int'); +if (!isset($conf->global->THEME_SATURATE_RATIO)) { + $conf->global->THEME_SATURATE_RATIO = 0.7; +} +if (GETPOSTISSET('THEME_SATURATE_RATIO')) { + $conf->global->THEME_SATURATE_RATIO = GETPOST('THEME_SATURATE_RATIO', 'int'); +} ?> .bg-infobox-project i.fa{ color: #605ca8 !important; @@ -363,7 +375,7 @@ if (GETPOSTISSET('THEME_SATURATE_RATIO')) $conf->global->THEME_SATURATE_RATIO = content: "\f571"; } .fa-dol-project:before { - content: "\f0e8"; + content: "\f542"; } .fa-dol-commande:before, .fa-dol-order_supplier:before { @@ -471,7 +483,7 @@ if (GETPOSTISSET('THEME_SATURATE_RATIO')) $conf->global->THEME_SATURATE_RATIO = .info-box-module { min-width: 350px; - max-width: 350px; + max-width: 350px; } .info-box-module .info-box-content { @@ -481,8 +493,8 @@ if (GETPOSTISSET('THEME_SATURATE_RATIO')) $conf->global->THEME_SATURATE_RATIO = @media only screen and (max-width: 1740px) { .info-box-module { - min-width: 315px; - max-width: 315px; + min-width: 315px; + max-width: 315px; } } @media only screen and (max-width: 767px) { diff --git a/htdocs/theme/md/main_menu_fa_icons.inc.php b/htdocs/theme/md/main_menu_fa_icons.inc.php index 3aa45726975..d5392c5b086 100644 --- a/htdocs/theme/md/main_menu_fa_icons.inc.php +++ b/htdocs/theme/md/main_menu_fa_icons.inc.php @@ -1,48 +1,134 @@ -<?php if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> +<?php if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} ?> /* <style type="text/css" > */ .mainmenu::before{ - /* font part */ - font-family: "Font Awesome 5 Free"; - font-weight: 900; - font-style: normal; - font-variant: normal; - text-rendering: auto; - line-height: 26px; + /* font part */ + font-family: "Font Awesome 5 Free"; + font-weight: 900; + font-style: normal; + font-variant: normal; + text-rendering: auto; + line-height: 26px; font-size: 1.5em; - -webkit-font-smoothing: antialiased; - text-align:center; + -webkit-font-smoothing: antialiased; + text-align:center; text-decoration:none; color: #<?php echo $colortextbackhmenu; ?>; } .fa-15x { - font-size: 1.5em; + font-size: 1.5em; +} + +div.mainmenu { + background-image: none !important; +} + +div.mainmenu.menu::before { + content: "\f0c9"; +} + + +div.mainmenu.home::before{ + content: "\f015"; +} + +div.mainmenu.billing::before { + content: "\f51e"; +} + +div.mainmenu.accountancy::before { + /* content: "\f53d"; */ + content: "\f688"; + font-size: 1.2em; +} + +div.mainmenu.agenda::before { + content: "\f073"; +} + +div.mainmenu.bank::before { + content: "\f19c"; +} + +div.mainmenu.cashdesk::before { + content: "\f788"; +} + + +div.mainmenu.takepos::before { + content: "\f788"; +} + +div.mainmenu.companies::before { + content: "\f1ad"; +} + +div.mainmenu.commercial::before { + content: "\f0f2"; +} + +div.mainmenu.ecm::before { + content: "\f07c"; +} + +div.mainmenu.externalsite::before { + content: "\f360"; +} + +div.mainmenu.ftp::before { + content: "\f362"; +} + +div.mainmenu.hrm::before { + content: "\f508"; +} + +div.mainmenu.members::before { + content: "\f007"; +} + +div.mainmenu.products::before { + content: "\f1b2"; +} + +div.mainmenu.mrp::before { + content: "\f1b3"; +} + +div.mainmenu.project::before { + content: "\f542"; } div.mainmenu.ticket::before { - content: "\f3ff"; -} -div.mainmenu.ticket { - background-image: none !important; + content: "\f3ff"; } +div.mainmenu.tools::before { + content: "\f0ad"; +} + +div.mainmenu.website::before { + content: "\f57d"; +} div.mainmenu.generic1::before { - content: "\f249"; + content: "\f249"; } div.mainmenu.generic2::before { - content: "\f249"; + content: "\f249"; } div.mainmenu.generic3::before { - content: "\f249"; + content: "\f249"; } div.mainmenu.generic4::before { - content: "\f249"; + content: "\f249"; } /* Define color of some picto */ @@ -97,3 +183,15 @@ div.mainmenu.generic4::before { border-bottom: solid 60px currentColor; margin-left: 30px; } + +.menu_titre .em092 { + font-size: 0.92em; +} + +.menu_titre .em088 { + font-size: 0.88em; +} + +.menu_titre .em080 { + font-size: 0.80em; +} diff --git a/htdocs/theme/md/manifest.json.php b/htdocs/theme/md/manifest.json.php index 03c5894fdde..b249e81e7df 100644 --- a/htdocs/theme/md/manifest.json.php +++ b/htdocs/theme/md/manifest.json.php @@ -25,35 +25,68 @@ * \brief File for The Web App */ -if (!defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); -if (!defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOLOGIN')) define('NOLOGIN', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIREUSER')) { + define('NOREQUIREUSER', '1'); +} +if (!defined('NOREQUIREDB')) { + define('NOREQUIREDB', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOREQUIRETRAN')) { + define('NOREQUIRETRAN', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} require_once __DIR__.'/../../main.inc.php'; $appli = constant('DOL_APPLICATION_TITLE'); -if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli = $conf->global->MAIN_APPLICATION_TITLE; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $appli = $conf->global->MAIN_APPLICATION_TITLE; +} top_httphead('text/json'); +// Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. +if (empty($dolibarr_nocache)) { + header('Cache-Control: max-age=10800, public, must-revalidate'); + // For a text/json, we must set an Expires to avoid to have it forced to an expired value by the web server + header('Expires: '.gmdate('D, d M Y H:i:s', dol_now('gmt') + 10800) . ' GMT'); +} else { + header('Cache-Control: no-cache'); +} ?> { - "name": "<?php echo $appli; ?>", - "icons": [ - { - "src": "<?php echo DOL_URL_ROOT.'/theme/dolibarr_256x256_color.png'; ?>", - "sizes": "256x256", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" + "name": "<?php echo $appli; ?>", + "icons": [ + { + "src": "<?php echo DOL_URL_ROOT.'/theme/dolibarr_256x256_color.png'; ?>", + "sizes": "256x256", + "type": "image/png" + } + ], + "theme_color": "#ffffff", + "background_color": "#ffffff", + "display": "standalone" } \ No newline at end of file diff --git a/htdocs/theme/md/progress.inc.php b/htdocs/theme/md/progress.inc.php index 9a78141ace0..979f8b8034e 100644 --- a/htdocs/theme/md/progress.inc.php +++ b/htdocs/theme/md/progress.inc.php @@ -1,5 +1,7 @@ <?php -if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); +if (!defined('ISLOADEDBYSTEELSHEET')) { + die('Must be call by steelsheet'); +} include dol_buildpath($path.'/theme/eldy/progress.inc.php', 0); // actually md use same style as eldy theme diff --git a/htdocs/theme/md/style.css.php b/htdocs/theme/md/style.css.php index 623ecb2a779..2209c87c22b 100644 --- a/htdocs/theme/md/style.css.php +++ b/htdocs/theme/md/style.css.php @@ -28,21 +28,35 @@ //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled because need to load personalized language //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled to increase speed. Language code is found on url. -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Not disabled because need to do translations -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); -if (!defined('NOLOGIN')) define('NOLOGIN', 1); // File must be accessed by logon page so without login +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', 1); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', 1); // File must be accessed by logon page so without login +} //if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU',1); // We need top menu content -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', 1); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} define('ISLOADEDBYSTEELSHEET', '1'); require __DIR__.'/theme_vars.inc.php'; -if (defined('THEME_ONLY_CONSTANT')) return; +if (defined('THEME_ONLY_CONSTANT')) { + return; +} session_cache_limiter('public'); @@ -52,8 +66,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; // Load user to have $user->conf loaded (not done into main because of NOLOGIN constant defined) // and permission, so we can later calculate number of top menu ($nbtopmenuentries) according to user profile. -if (empty($user->id) && !empty($_SESSION['dol_login'])) -{ +if (empty($user->id) && !empty($_SESSION['dol_login'])) { $user->fetch('', $_SESSION['dol_login'], '', 1); $user->getrights(); @@ -66,11 +79,18 @@ if (empty($user->id) && !empty($_SESSION['dol_login'])) // Define css type top_httphead('text/css'); // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. -if (empty($dolibarr_nocache)) header('Cache-Control: max-age=10800, public, must-revalidate'); -else header('Cache-Control: no-cache'); +if (empty($dolibarr_nocache)) { + header('Cache-Control: max-age=10800, public, must-revalidate'); +} else { + header('Cache-Control: no-cache'); +} -if (GETPOST('theme', 'alpha')) $conf->theme = GETPOST('theme', 'alpha'); // If theme was forced on URL -if (GETPOST('lang', 'aZ09')) $langs->setDefaultLang(GETPOST('lang', 'aZ09')); // If language was forced on URL +if (GETPOST('theme', 'alpha')) { + $conf->theme = GETPOST('theme', 'alpha'); // If theme was forced on URL +} +if (GETPOST('lang', 'aZ09')) { + $langs->setDefaultLang(GETPOST('lang', 'aZ09')); // If language was forced on URL +} $langs->load("main", 0, 1); $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right'); @@ -78,7 +98,9 @@ $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left'); $path = ''; // This value may be used in future for external module to overwrite theme $theme = 'md'; // Value of theme -if (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) { $path = '/'.$conf->global->MAIN_OVERWRITE_THEME_RES; $theme = $conf->global->MAIN_OVERWRITE_THEME_RES; } +if (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) { + $path = '/'.$conf->global->MAIN_OVERWRITE_THEME_RES; $theme = $conf->global->MAIN_OVERWRITE_THEME_RES; +} // Define image path files and other constants $fontlist = 'roboto,arial,tahoma,verdana,helvetica'; //$fontlist='verdana,helvetica,arial,sans-serif'; @@ -98,19 +120,36 @@ $useboldtitle = (isset($conf->global->THEME_ELDY_USEBOLDTITLE) ? $conf->global-> $borderwidth = 2; // Case of option always editable -if (!isset($conf->global->THEME_ELDY_BACKBODY)) $conf->global->THEME_ELDY_BACKBODY = $colorbackbody; -if (!isset($conf->global->THEME_ELDY_TOPMENU_BACK1)) $conf->global->THEME_ELDY_TOPMENU_BACK1 = $colorbackhmenu1; -if (!isset($conf->global->THEME_ELDY_VERMENU_BACK1)) $conf->global->THEME_ELDY_VERMENU_BACK1 = $colorbackvmenu1; -if (!isset($conf->global->THEME_ELDY_BACKTITLE1)) $conf->global->THEME_ELDY_BACKTITLE1 = $colorbacktitle1; -if (!isset($conf->global->THEME_ELDY_USE_HOVER)) $conf->global->THEME_ELDY_USE_HOVER = $colorbacklinepairhover; -if (!isset($conf->global->THEME_ELDY_USE_CHECKED)) $conf->global->THEME_ELDY_USE_CHECKED = $colorbacklinepairchecked; -if (!isset($conf->global->THEME_ELDY_LINEBREAK)) $conf->global->THEME_ELDY_LINEBREAK = $colorbacklinebreak; -if (!isset($conf->global->THEME_ELDY_TEXTTITLENOTAB)) $conf->global->THEME_ELDY_TEXTTITLENOTAB = $colortexttitlenotab; -if (!isset($conf->global->THEME_ELDY_TEXTLINK)) $conf->global->THEME_ELDY_TEXTLINK = $colortextlink; +if (!isset($conf->global->THEME_ELDY_BACKBODY)) { + $conf->global->THEME_ELDY_BACKBODY = $colorbackbody; +} +if (!isset($conf->global->THEME_ELDY_TOPMENU_BACK1)) { + $conf->global->THEME_ELDY_TOPMENU_BACK1 = $colorbackhmenu1; +} +if (!isset($conf->global->THEME_ELDY_VERMENU_BACK1)) { + $conf->global->THEME_ELDY_VERMENU_BACK1 = $colorbackvmenu1; +} +if (!isset($conf->global->THEME_ELDY_BACKTITLE1)) { + $conf->global->THEME_ELDY_BACKTITLE1 = $colorbacktitle1; +} +if (!isset($conf->global->THEME_ELDY_USE_HOVER)) { + $conf->global->THEME_ELDY_USE_HOVER = $colorbacklinepairhover; +} +if (!isset($conf->global->THEME_ELDY_USE_CHECKED)) { + $conf->global->THEME_ELDY_USE_CHECKED = $colorbacklinepairchecked; +} +if (!isset($conf->global->THEME_ELDY_LINEBREAK)) { + $conf->global->THEME_ELDY_LINEBREAK = $colorbacklinebreak; +} +if (!isset($conf->global->THEME_ELDY_TEXTTITLENOTAB)) { + $conf->global->THEME_ELDY_TEXTTITLENOTAB = $colortexttitlenotab; +} +if (!isset($conf->global->THEME_ELDY_TEXTLINK)) { + $conf->global->THEME_ELDY_TEXTLINK = $colortextlink; +} // Case of option editable only if option THEME_ELDY_ENABLE_PERSONALIZED is on -if (empty($conf->global->THEME_ELDY_ENABLE_PERSONALIZED)) -{ +if (empty($conf->global->THEME_ELDY_ENABLE_PERSONALIZED)) { // 90A4AE, 607D8B, 455A64, 37474F $conf->global->THEME_ELDY_BACKTABCARD1 = '255,255,255'; // card $conf->global->THEME_ELDY_BACKTABACTIVE = '234,234,234'; @@ -143,38 +182,55 @@ $fontsizesmaller = empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED) ? (emp // Hover color $colorbacklinepairhover = ((!isset($conf->global->THEME_ELDY_USE_HOVER) || (string) $conf->global->THEME_ELDY_USE_HOVER === '255,255,255') ? '' : ($conf->global->THEME_ELDY_USE_HOVER === '1' ? 'edf4fb' : $conf->global->THEME_ELDY_USE_HOVER)); $colorbacklinepairchecked = ((!isset($conf->global->THEME_ELDY_USE_CHECKED) || (string) $conf->global->THEME_ELDY_USE_CHECKED === '255,255,255') ? '' : ($conf->global->THEME_ELDY_USE_CHECKED === '1' ? 'edf4fb' : $conf->global->THEME_ELDY_USE_CHECKED)); -if (!empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)) -{ +if (!empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)) { $colorbacklinepairhover = ((!isset($user->conf->THEME_ELDY_USE_HOVER) || $user->conf->THEME_ELDY_USE_HOVER === '255,255,255') ? '' : ($user->conf->THEME_ELDY_USE_HOVER === '1' ? 'edf4fb' : $user->conf->THEME_ELDY_USE_HOVER)); $colorbacklinepairchecked = ((!isset($user->conf->THEME_ELDY_USE_CHECKED) || $user->conf->THEME_ELDY_USE_CHECKED === '255,255,255') ? '' : ($user->conf->THEME_ELDY_USE_CHECKED === '1' ? 'edf4fb' : $user->conf->THEME_ELDY_USE_CHECKED)); } -if (empty($colortopbordertitle1)) $colortopbordertitle1 = $colorbackhmenu1; +if (empty($colortopbordertitle1)) { + $colortopbordertitle1 = $colorbackhmenu1; +} // Set text color to black or white $colorbackhmenu1 = join(',', colorStringToArray($colorbackhmenu1)); // Normalize value to 'x,y,z' $tmppart = explode(',', $colorbackhmenu1); $tmpval = (!empty($tmppart[0]) ? $tmppart[0] : 0) + (!empty($tmppart[1]) ? $tmppart[1] : 0) + (!empty($tmppart[2]) ? $tmppart[2] : 0); -if ($tmpval <= 460) $colortextbackhmenu = 'FFFFFF'; -else $colortextbackhmenu = '000000'; +if ($tmpval <= 460) { + $colortextbackhmenu = 'FFFFFF'; +} else { + $colortextbackhmenu = '000000'; +} $colorbackvmenu1 = join(',', colorStringToArray($colorbackvmenu1)); // Normalize value to 'x,y,z' $tmppart = explode(',', $colorbackvmenu1); $tmpval = (!empty($tmppart[0]) ? $tmppart[0] : 0) + (!empty($tmppart[1]) ? $tmppart[1] : 0) + (!empty($tmppart[2]) ? $tmppart[2] : 0); -if ($tmpval <= 460) { $colortextbackvmenu = 'FFFFFF'; } else { $colortextbackvmenu = '000000'; } +if ($tmpval <= 460) { + $colortextbackvmenu = 'FFFFFF'; +} else { + $colortextbackvmenu = '000000'; +} $colorbacktitle1 = join(',', colorStringToArray($colorbacktitle1)); // Normalize value to 'x,y,z' $tmppart = explode(',', $colorbacktitle1); -if ($colortexttitle == '') -{ +if ($colortexttitle == '') { $tmpval = (!empty($tmppart[0]) ? $tmppart[0] : 0) + (!empty($tmppart[1]) ? $tmppart[1] : 0) + (!empty($tmppart[2]) ? $tmppart[2] : 0); - if ($tmpval <= 460) { $colortexttitle = 'FFFFFF'; $colorshadowtitle = '888888'; } else { $colortexttitle = '101010'; $colorshadowtitle = 'FFFFFF'; } -} else $colorshadowtitle = '888888'; + if ($tmpval <= 460) { + $colortexttitle = 'FFFFFF'; $colorshadowtitle = '888888'; + } else { + $colortexttitle = '101010'; $colorshadowtitle = 'FFFFFF'; + } +} else { + $colorshadowtitle = '888888'; +} $colorbacktabcard1 = join(',', colorStringToArray($colorbacktabcard1)); // Normalize value to 'x,y,z' $tmppart = explode(',', $colorbacktabcard1); $tmpval = (!empty($tmppart[0]) ? $tmppart[0] : 0) + (!empty($tmppart[1]) ? $tmppart[1] : 0) + (!empty($tmppart[2]) ? $tmppart[2] : 0); -if ($tmpval <= 460) { $colortextbacktab = 'FFFFFF'; } else { $colortextbacktab = '111111'; } +if ($tmpval <= 460) { + $colortextbacktab = 'FFFFFF'; +} else { + $colortextbacktab = '111111'; +} // Format color value to match expected format (may be 'FFFFFF' or '255,255,255') $colorbackhmenu1 = join(',', colorStringToArray($colorbackhmenu1)); @@ -186,8 +242,12 @@ $colorbacklineimpair1 = join(',', colorStringToArray($colorbacklineimpair1)); $colorbacklineimpair2 = join(',', colorStringToArray($colorbacklineimpair2)); $colorbacklinepair1 = join(',', colorStringToArray($colorbacklinepair1)); $colorbacklinepair2 = join(',', colorStringToArray($colorbacklinepair2)); -if ($colorbacklinepairhover != '') $colorbacklinepairhover = join(',', colorStringToArray($colorbacklinepairhover)); -if ($colorbacklinepairchecked != '') $colorbacklinepairchecked = join(',', colorStringToArray($colorbacklinepairchecked)); +if ($colorbacklinepairhover != '') { + $colorbacklinepairhover = join(',', colorStringToArray($colorbacklinepairhover)); +} +if ($colorbacklinepairchecked != '') { + $colorbacklinepairchecked = join(',', colorStringToArray($colorbacklinepairchecked)); +} $colorbackbody = join(',', colorStringToArray($colorbackbody)); $colortexttitlenotab = join(',', colorStringToArray($colortexttitlenotab)); $colortexttitle = join(',', colorStringToArray($colortexttitle)); @@ -195,7 +255,9 @@ $colortext = join(',', colorStringToArray($colortext)); $colortextlink = join(',', colorStringToArray($colortextlink)); $nbtopmenuentries = $menumanager->showmenu('topnb'); -if ($conf->browser->layout == 'phone') $nbtopmenuentries = max($nbtopmenuentries, 10); +if ($conf->browser->layout == 'phone') { + $nbtopmenuentries = max($nbtopmenuentries, 10); +} print '/*'."\n"; print 'colorbackbody='.$colorbackbody."\n"; @@ -278,11 +340,11 @@ body { font-size: <?php print is_numeric($fontsize) ? $fontsize.'px' : $fontsize; ?>; line-height: 1.3; font-family: <?php print $fontlist ?>; - margin-top: 0; - margin-bottom: 0; - margin-right: 0; - margin-left: 0; - <?php print 'direction: '.$langs->trans("DIRECTION").";\n"; ?> + margin-top: 0; + margin-bottom: 0; + margin-right: 0; + margin-left: 0; + <?php print 'direction: '.$langs->trans("DIRECTION").";\n"; ?> } .sensiblehtmlcontent * { @@ -301,14 +363,14 @@ input { font-size: unset; } input, input.flat, textarea, textarea.flat, form.flat select, select, select.flat, .dataTables_length label select { - background-color: #FDFDFD; + background-color: #FDFDFD; } select.vmenusearchselectcombo { background-color: unset; } textarea:focus, button:focus { - /* v6 box-shadow: 0 0 4px #8091BF; */ + /* v6 box-shadow: 0 0 4px #8091BF; */ border: 1px solid #aaa !important; } input:focus, textarea:focus, button:focus, select:focus { @@ -321,10 +383,10 @@ textarea.cke_source:focus } th.wrapcolumntitle.liste_titre:not(.maxwidthsearch), td.wrapcolumntitle.liste_titre:not(.maxwidthsearch) { - overflow: hidden; - white-space: nowrap; - max-width: 120px; - text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; + max-width: 120px; + text-overflow: ellipsis; } .liste_titre input[name=month_date_when], .liste_titre input[name=monthvalid], .liste_titre input[name=search_ordermonth], .liste_titre input[name=search_deliverymonth], .liste_titre input[name=search_smonth], .liste_titre input[name=search_month], .liste_titre input[name=search_emonth], .liste_titre input[name=smonth], .liste_titre input[name=month], @@ -344,14 +406,14 @@ select#date_startday, select#date_startmonth, select#date_endday, select#date_en } input, input.flat, textarea, textarea.flat, form.flat select, select, select.flat, .dataTables_length label select { font-family: <?php print $fontlist ?>; - border: none; - border<?php echo empty($conf->global->THEME_HIDE_BORDER_ON_INPUT) ? '-bottom' : ''; ?>: solid 1px rgba(0,0,0,.2); - outline: none; - margin: 0px 0px 0px 0px; + border: none; + border<?php echo empty($conf->global->THEME_HIDE_BORDER_ON_INPUT) ? '-bottom' : ''; ?>: solid 1px rgba(0,0,0,.2); + outline: none; + margin: 0px 0px 0px 0px; } input { - line-height: 17px; + line-height: 17px; padding: 4px; padding-left: 5px; } @@ -367,7 +429,7 @@ input, select { margin-top:1px; } input.button.massactionconfirmed { - margin: 4px; + margin: 4px; } textarea { @@ -399,8 +461,8 @@ input.buttonpayment, button.buttonpayment, div.buttonpayment { min-width: 290px; margin-bottom: 15px; margin-top: 15px; - margin-left: 5px; - margin-right: 5px; + margin-left: 5px; + margin-right: 5px; background-image: none; line-height: 24px; padding: 8px; @@ -412,15 +474,15 @@ input.buttonpayment, button.buttonpayment, div.buttonpayment { color: #888 !important; } div.buttonpayment input { - background-color: unset; - border-bottom: unset; - font-weight: bold; - text-transform: uppercase; + background-color: unset; + border-bottom: unset; + font-weight: bold; + text-transform: uppercase; color: #333; cursor: pointer; } div.buttonpayment input:focus { - color: #008; + color: #008; } input.buttonpaymentcb { background-image: url(<?php echo dol_buildpath($path.'/theme/common/credit_card.png', 1) ?>); @@ -466,16 +528,16 @@ a.butStatus { padding-left: 5px; padding-right: 5px; background-color: transparent; - color: var(--colortext) !important; - border: 2px solid var( --butactionbg); - margin: 0 0.45em !important; + color: var(--colortext) !important; + border: 2px solid var( --butactionbg); + margin: 0 0.45em !important; } /* Used by timesheets */ span.timesheetalreadyrecorded input { - border: none; - border-bottom: solid 1px rgba(0,0,0,0.1); - margin-right: 1px !important; + border: none; + border-bottom: solid 1px rgba(0,0,0,0.1); + margin-right: 1px !important; } td.onholidaymorning, td.onholidayafternoon { background-color: #fdf6f2; @@ -494,7 +556,7 @@ td.rightborder { } td.actionbuttons a { - padding-left: 6px; + padding-left: 6px; } select.flat, form.flat select, .pageplusone { font-weight: normal; @@ -502,8 +564,8 @@ select.flat, form.flat select, .pageplusone { height: 2em; } input.pageplusone { - padding-bottom: 4px; - padding-top: 4px; + padding-bottom: 4px; + padding-top: 4px; } .saturatemedium { @@ -523,7 +585,7 @@ input.pageplusone { opacity: 0.6; } .opacityhigh { - opacity: 0.2; + opacity: 0.24; } .opacitytransp { opacity: 0; @@ -536,10 +598,10 @@ input.pageplusone { } .vmirror { - transform: scale(1, -1); + transform: scale(1, -1); } .hmirror { - transform: scale(-1, 1); + transform: scale(-1, 1); } select:invalid { @@ -588,7 +650,7 @@ input#onlinepaymenturl, input#directdownloadlink { } div#moretabsList, div#moretabsListaction { - z-index: 5; + z-index: 5; } hr { border: 0; border-top: 1px solid #ccc; } @@ -600,7 +662,7 @@ hr { border: 0; border-top: 1px solid #ccc; } padding: 4px 14px; margin-bottom: 0; margin-top: 0; - font-family: <?php print $fontlist ?>; + font-family: <?php print $fontlist ?>; text-align: center; cursor: pointer; color: #333333 !important; @@ -632,35 +694,35 @@ hr { border: 0; border-top: 1px solid #ccc; } } .button:disabled, .buttonDelete:disabled, .button.disabled, .buttonDelete.disabled { opacity: 0.4; - box-shadow: none; - -webkit-box-shadow: none; - cursor: auto; + box-shadow: none; + -webkit-box-shadow: none; + cursor: auto; } .buttonRefused { pointer-events: none; - cursor: default; + cursor: default; opacity: 0.4; - box-shadow: none; - -webkit-box-shadow: none; + box-shadow: none; + -webkit-box-shadow: none; } .button_search, .button_removefilter { - border: unset; - background: unset; + border: unset; + background: unset; } .button_search:hover, .button_removefilter:hover { - cursor: pointer; + cursor: pointer; } form { - padding:0px; - margin:0px; + padding:0px; + margin:0px; } div.float, span.floatleft { - float:<?php print $left; ?>; + float:<?php print $left; ?>; } div.floatright { - float:<?php print $right; ?>; + float:<?php print $right; ?>; } .block { @@ -671,12 +733,12 @@ div.floatright display:inline-block; } .largenumber { - font-size: 1.4em; + font-size: 1.4em; } th .button { - -webkit-box-shadow: none !important; - box-shadow: none !important; + -webkit-box-shadow: none !important; + box-shadow: none !important; -webkit-border-radius:0px !important; border-radius:0px !important; } @@ -713,21 +775,21 @@ textarea.centpercent { width: 96%; } .small, small { - font-size: 85%; + font-size: 85%; } .h1 .small, .h1 small, .h2 .small, .h2 small, .h3 .small, .h3 small, h1 .small, h1 small, h2 .small, h2 small, h3 .small, h3 small { - font-size: 65%; + font-size: 65%; } .h1 .small, .h1 small, .h2 .small, .h2 small, .h3 .small, .h3 small, .h4 .small, .h4 small, .h5 .small, .h5 small, .h6 .small, .h6 small, h1 .small, h1 small, h2 .small, h2 small, h3 .small, h3 small, h4 .small, h4 small, h5 .small, h5 small, h6 .small, h6 small { - font-weight: 400; - line-height: 1; - color: #777; + font-weight: 400; + line-height: 1; + color: #777; } .center { - text-align: center; - margin: 0px auto; + text-align: center; + margin: 0px auto; } .left { text-align: <?php print $left; ?>; @@ -739,10 +801,10 @@ textarea.centpercent { text-align: justify; } .pull-left { - float: left!important; + float: left!important; } .pull-right { - float: right!important; + float: right!important; } .nowrap { white-space: <?php print ($dol_optimize_smallscreen ? 'normal' : 'nowrap'); ?>; @@ -775,7 +837,7 @@ textarea.centpercent { font-weight: normal !important; } .nounderline { - text-decoration: none; + text-decoration: none; } .nopadding { padding: 0; @@ -817,43 +879,49 @@ textarea.centpercent { cursor: not-allowed; } .backgroundblank { - background-color: #fff; + background-color: #fff; } .nobackground, .nobackground tr { background: unset !important; } .checkboxattachfilelabel { - font-size: 0.85em; - opacity: 0.7; + font-size: 0.85em; + opacity: 0.7; } .longmessagecut { - max-height: 250px; - max-width: 100%; - overflow-y: auto; + max-height: 250px; + max-width: 100%; + overflow-y: auto; +} + +i.fa-mars::before, i.fa-venus::before, i.fa-genderless::before { + color: #888 !important; + opacity: 0.4; + padding-<?php echo $left; ?>: 3px; } .text-warning{ - color : <?php print $textWarning; ?> + color : <?php print $textWarning; ?> } body[class*="colorblind-"] .text-warning{ - color : <?php print $colorblind_deuteranopes_textWarning; ?> + color : <?php print $colorblind_deuteranopes_textWarning; ?> } .text-success{ - color : <?php print $textSuccess; ?> + color : <?php print $textSuccess; ?> } body[class*="colorblind-"] .text-success{ - color : <?php print $colorblind_deuteranopes_textSuccess; ?> + color : <?php print $colorblind_deuteranopes_textSuccess; ?> } .text-danger{ - color : <?php print $textDanger; ?> + color : <?php print $textDanger; ?> } .editfielda span.fa-pencil-alt, .editfielda span.fa-trash { - color: #ccc !important; + color: #ccc !important; } .editfielda span.fa-pencil-alt:hover, .editfielda span.fa-trash:hover { - color: rgb(<?php echo $colortexttitle; ?>) !important; + color: rgb(<?php echo $colortexttitle; ?>) !important; } .size15x { font-size: 1.5em !important; } @@ -891,32 +959,32 @@ body[class*="colorblind-"] .text-success{ vertical-align: middle; } .divsocialnetwork:not(:first-child) { - padding-left: 20px; + padding-left: 20px; } div.divsearchfield { float: <?php print $left; ?>; margin-<?php print $right; ?>: 12px; margin-<?php print $left; ?>: 2px; margin-top: 4px; - margin-bottom: 4px; - padding-left: 2px; + margin-bottom: 4px; + padding-left: 2px; } .divsearchfieldfilter { - text-overflow: clip; - overflow: auto; - white-space: nowrap; - padding-bottom: 5px; - opacity: 0.6; + text-overflow: clip; + overflow: auto; + white-space: nowrap; + padding-bottom: 5px; + opacity: 0.6; } .divadvancedsearchfield:first-child { - margin-top: 3px; + margin-top: 3px; } .divadvancedsearchfield { - float: left; - padding-left: 15px; - padding-right: 15px; - padding-bottom: 2px; - padding-top: 2px; + float: left; + padding-left: 15px; + padding-right: 15px; + padding-bottom: 2px; + padding-top: 2px; } .divadvancedsearchfield span.select2.select2-container.select2-container--default { padding-bottom: 4px; @@ -926,22 +994,22 @@ div.divsearchfield { if ($conf->browser->layout == 'phone') { ?> .divsearchfieldfilter { - white-space: nowrap; + white-space: nowrap; } <?php } ?> .a-filter, .a-mesure { - border-radius: 50px; - background: var(--colortexttitlenotab); - color: #fff; - padding: 8px 10px 8px 6px; + border-radius: 50px; + background: var(--colortexttitlenotab); + color: #fff; + padding: 8px 10px 8px 6px; } .a-filter:before { - content: "\f0b0"; + content: "\f0b0"; } .a-mesure:before { - content: "\f080"; + content: "\f080"; } .a-filter:before, .a-mesure:before { font-family: "Font Awesome 5 Free"; @@ -950,10 +1018,10 @@ if ($conf->browser->layout == 'phone') { padding-left: 5px; } .a-filter-disabled, .a-mesure-disabled { - border-radius: 50px; - background: var(--colorbacktitle1); - padding: 8px; - opacity: 0.6; + border-radius: 50px; + background: var(--colorbacktitle1); + padding: 8px; + opacity: 0.6; } @@ -982,12 +1050,12 @@ input > ul.attendees { padding-bottom: 10px; } .checkallactions { - margin-left: 2px; /* left must be same than right to keep checkbox centered */ - margin-right: 2px; /* left must be same than right to keep checkbox centered */ - vertical-align: middle; + margin-left: 2px; /* left must be same than right to keep checkbox centered */ + margin-right: 2px; /* left must be same than right to keep checkbox centered */ + vertical-align: middle; } select.flat.selectlimit { - max-width: 62px; + max-width: 62px; } .selectlimit, .marginrightonly { margin-right: 10px !important; @@ -1008,17 +1076,17 @@ select.flat.selectlimit { margin-bottom: 10px !important; } .nomargintop { - margin-top: 0 !important; + margin-top: 0 !important; } .nomarginbottom { - margin-bottom: 0 !important; + margin-bottom: 0 !important; } .selectlimit, .selectlimit:focus { - border-left: none !important; - border-top: none !important; - border-right: none !important; - outline: none; + border-left: none !important; + border-top: none !important; + border-right: none !important; + outline: none; } .strikefordisabled { text-decoration: line-through; @@ -1028,69 +1096,69 @@ select.flat.selectlimit { } /* using a tdoverflowxxx make the min-width not working */ .tdoverflow { - max-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax50 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 50px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 50px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax100 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 100px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 100px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax100imp { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 100px !important; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 100px !important; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax125 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 125px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 125px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax150 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 150px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 150px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax200 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 200px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 200px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowmax300 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 300px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + max-width: 300px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .tdoverflowauto { - max-width: 0; - overflow: auto; + max-width: 0; + overflow: auto; } .divintodwithtwolinesmax { - width: 75px; - display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: 2; - overflow: hidden; + width: 75px; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow: hidden; } .twolinesmax { - display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: 2; - overflow: hidden; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow: hidden; } .tablelistofcalendars { @@ -1118,19 +1186,19 @@ select.flat.selectlimit { margin-bottom: 12px; } #builddoc_form ~ .showlinkedobjectblock { - margin-top: 20px; + margin-top: 20px; } /* For the long description of module */ .moduledesclong p img,.moduledesclong p a img { - max-width: 90% !important; - height: auto !important; + max-width: 90% !important; + height: auto !important; } .imgdoc { - margin: 18px; - border: 1px solid #ccc; - box-shadow: 1px 1px 25px #aaa; - max-width: calc(100% - 56px); + margin: 18px; + border: 1px solid #ccc; + box-shadow: 1px 1px 25px #aaa; + max-width: calc(100% - 56px); } .fa-file-text-o, .fa-file-code-o, .fa-file-powerpoint-o, .fa-file-excel-o, .fa-file-word-o, .fa-file-o, .fa-file-image-o, .fa-file-video-o, .fa-file-audio-o, .fa-file-archive-o, .fa-file-pdf-o { color: #505; @@ -1142,34 +1210,36 @@ select.flat.selectlimit { /* DOL_XXX for future usage (when left menu has been removed). If we do not use datatable */ /*.table-responsive { - width: calc(100% - 330px); - margin-bottom: 15px; - overflow-y: hidden; - -ms-overflow-style: -ms-autohiding-scrollbar; + width: calc(100% - 330px); + margin-bottom: 15px; + overflow-y: hidden; + -ms-overflow-style: -ms-autohiding-scrollbar; }*/ /* Style used for most tables */ div.fiche>div.tabBar>form>div.div-table-responsive { - min-height: 392px; + min-height: 392px; } .div-table-responsive, .div-table-responsive-no-min { - overflow-x: auto; - min-height: 0.01%; + overflow-x: auto; + min-height: 0.01%; } .div-table-responsive { - line-height: 120%; + line-height: 120%; } /* Style used for full page tables with field selector and no content after table (priority before previous for such tables) */ div.fiche>form>div.div-table-responsive, div.fiche>form>div.div-table-responsive-no-min { - overflow-x: auto; + overflow-x: auto; } div.fiche>form>div.div-table-responsive { - min-height: 392px; + min-height: 392px; } .flexcontainer { - <?php if (in_array($conf->browser->name, array('chrome', 'firefox'))) echo 'display: inline-flex;' ?> - flex-flow: row wrap; - justify-content: flex-start; + <?php if (in_array($conf->browser->name, array('chrome', 'firefox'))) { + echo 'display: inline-flex;'; + } ?> + flex-flow: row wrap; + justify-content: flex-start; } .thumbstat { flex: 1 1 116px; @@ -1178,13 +1248,13 @@ div.fiche>form>div.div-table-responsive { flex: 1 1 150px; } .thumbstat, .thumbstat150 { - flex-grow: 1; - flex-shrink: 1; - /* flex-basis: 140px; */ - /* min-width: 150px; */ - width: 158px; - justify-content: flex-start; - align-self: flex-start; + flex-grow: 1; + flex-shrink: 1; + /* flex-basis: 140px; */ + /* min-width: 150px; */ + width: 158px; + justify-content: flex-start; + align-self: flex-start; } select.selectarrowonleft { @@ -1195,7 +1265,7 @@ select.selectarrowonleft option { } table[summary="list_of_modules"] .fa-cog { - font-size: 1.5em; + font-size: 1.5em; } .linkedcol-element { @@ -1221,10 +1291,10 @@ table[summary="list_of_modules"] .fa-cog { { .width20 { width: 20px; } .width25 { width: 25px; } - .width50 { width: 50px; } - .width75 { width: 75px; } - .width100 { width: 100px; } - .width200 { width: 200px; } + .width50 { width: 50px; } + .width75 { width: 75px; } + .width100 { width: 100px; } + .width200 { width: 200px; } .minwidth100 { min-width: 100px; } .minwidth150 { min-width: 150px; } .minwidth200 { min-width: 200px; } @@ -1232,10 +1302,10 @@ table[summary="list_of_modules"] .fa-cog { .minwidth400 { min-width: 400px; } .minwidth500 { min-width: 500px; } .minwidth50imp { min-width: 50px !important; } - .minwidth75imp { min-width: 75px !important; } + .minwidth75imp { min-width: 75px !important; } .minwidth100imp { min-width: 100px !important; } .minwidth200imp { min-width: 200px !important; } - .minwidth250imp { min-width: 250px !important; } + .minwidth250imp { min-width: 250px !important; } .minwidth300imp { min-width: 300px !important; } .minwidth400imp { min-width: 400px !important; } .minwidth500imp { min-width: 500px !important; } @@ -1287,16 +1357,16 @@ table[summary="list_of_modules"] .fa-cog { .titlefield { /* width: 30% !important; */ } .titlefieldcreate { width: 30% !important; } .minwidth50imp { min-width: 50px !important; } - .minwidth75imp { min-width: 75px !important; } - .minwidth100imp { min-width: 100px !important; } - .minwidth150imp { min-width: 150px !important; } - .minwidth200imp { min-width: 200px !important; } - .minwidth250imp { min-width: 250px !important; } - .minwidth300imp { min-width: 300px !important; } - .minwidth400imp { min-width: 300px !important; } - .minwidth500imp { min-width: 300px !important; } + .minwidth75imp { min-width: 75px !important; } + .minwidth100imp { min-width: 100px !important; } + .minwidth150imp { min-width: 150px !important; } + .minwidth200imp { min-width: 200px !important; } + .minwidth250imp { min-width: 250px !important; } + .minwidth300imp { min-width: 300px !important; } + .minwidth400imp { min-width: 300px !important; } + .minwidth500imp { min-width: 300px !important; } - .linkedcol-element { + .linkedcol-element { min-width: unset; } } @@ -1304,16 +1374,16 @@ table[summary="list_of_modules"] .fa-cog { /* Force values for small screen 1000 */ @media only screen and (max-width: 1000px) { - .maxwidthonsmartphone { max-width: 100px; } + .maxwidthonsmartphone { max-width: 100px; } .minwidth50imp { min-width: 50px !important; } - .minwidth75imp { min-width: 70px !important; } - .minwidth100imp { min-width: 100px !important; } - .minwidth150imp { min-width: 110px !important; } - .minwidth200imp { min-width: 110px !important; } - .minwidth250imp { min-width: 115px !important; } - .minwidth300imp { min-width: 120px !important; } - .minwidth400imp { min-width: 150px !important; } - .minwidth500imp { min-width: 250px !important; } + .minwidth75imp { min-width: 70px !important; } + .minwidth100imp { min-width: 100px !important; } + .minwidth150imp { min-width: 110px !important; } + .minwidth200imp { min-width: 110px !important; } + .minwidth250imp { min-width: 115px !important; } + .minwidth300imp { min-width: 120px !important; } + .minwidth400imp { min-width: 150px !important; } + .minwidth500imp { min-width: 250px !important; } } /* Set a width. Note: add also a max-width, for example maxwidth500, that will be used in priority */ @@ -1337,7 +1407,7 @@ table[summary="list_of_modules"] .fa-cog { } div.divphotoref { - padding-right: 10px !important; + padding-right: 10px !important; } } @@ -1353,51 +1423,51 @@ table[summary="list_of_modules"] .fa-cog { } .login_vertical_align { - padding-left: 0; - } - .login_table input#username, .login_table input#password, .login_table input#securitycode { + padding-left: 0; + } + .login_table input#username, .login_table input#password, .login_table input#securitycode { margin-left: 5px !important; - } + } div#login_left, div#login_right { - min-width: 150px !important; - padding-left: 5px !important; - padding-right: 5px !important; - } - .login_table div#login_right .tdinputlogin, .login_table div#login_right .tdinputlogin input { - min-width: 150px !important; - } + min-width: 150px !important; + padding-left: 5px !important; + padding-right: 5px !important; + } + .login_table div#login_right .tdinputlogin, .login_table div#login_right .tdinputlogin input { + min-width: 150px !important; + } .divmainbodylarge { margin-left: 20px; margin-right: 20px; } - .tdoverflowonsmartphone { - max-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - .tdoverflowmax100onsmartphone { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 100px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + .tdoverflowonsmartphone { + max-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } - .tdoverflowmax150onsmartphone { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 100px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + .tdoverflowmax100onsmartphone { /* For tdoverflow, the max-midth become a minimum ! */ + max-width: 100px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .tdoverflowmax150onsmartphone { /* For tdoverflow, the max-midth become a minimum ! */ + max-width: 100px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } div.fiche { - margin-top: <?php print ($dol_hide_topmenu ? '12' : '6'); ?>px !important; + margin-top: <?php print ($dol_hide_topmenu ? '12' : '6'); ?>px !important; + } + .border tbody tr, .border tbody tr td, div.tabBar table.border tr, div.tabBar table.border tr td, div.tabBar div.border .table-border-row, div.tabBar div.border .table-key-border-col, div.tabBar div.border .table-val-border-col { + height: 40px !important; } - .border tbody tr, .border tbody tr td, div.tabBar table.border tr, div.tabBar table.border tr td, div.tabBar div.border .table-border-row, div.tabBar div.border .table-key-border-col, div.tabBar div.border .table-val-border-col { - height: 40px !important; - } - .quatrevingtpercent, .inputsearch { - width: 95%; - } + .quatrevingtpercent, .inputsearch { + width: 95%; + } select { padding-top: 4px; @@ -1409,34 +1479,34 @@ table[summary="list_of_modules"] .fa-cog { } input, input[type=text], input[type=password], select, textarea { min-width: 20px; - min-height: 1.4em; - line-height: 1.4em; - } + min-height: 1.4em; + line-height: 1.4em; + } - .hideonsmartphone { display: none; } - .hideonsmartphoneimp { display: none !important; } - .noenlargeonsmartphone { width : 50px !important; display: inline !important; } - .maxwidthonsmartphone, #search_newcompany.ui-autocomplete-input { max-width: 100px; } - .maxwidth50onsmartphone { max-width: 40px; } - .maxwidth75onsmartphone { max-width: 50px; } - .maxwidth100onsmartphone { max-width: 70px; } - .maxwidth150onsmartphone { max-width: 120px; } - .maxwidth150onsmartphoneimp { max-width: 120px !important; } - .maxwidth200onsmartphone { max-width: 200px; } - .maxwidth250onsmartphone { max-width: 250px; } - .maxwidth300onsmartphone { max-width: 300px; } - .maxwidth400onsmartphone { max-width: 400px; } + .hideonsmartphone { display: none; } + .hideonsmartphoneimp { display: none !important; } + .noenlargeonsmartphone { width : 50px !important; display: inline !important; } + .maxwidthonsmartphone, #search_newcompany.ui-autocomplete-input { max-width: 100px; } + .maxwidth50onsmartphone { max-width: 40px; } + .maxwidth75onsmartphone { max-width: 50px; } + .maxwidth100onsmartphone { max-width: 70px; } + .maxwidth150onsmartphone { max-width: 120px; } + .maxwidth150onsmartphoneimp { max-width: 120px !important; } + .maxwidth200onsmartphone { max-width: 200px; } + .maxwidth250onsmartphone { max-width: 250px; } + .maxwidth300onsmartphone { max-width: 300px; } + .maxwidth400onsmartphone { max-width: 400px; } .minwidth50imp { min-width: 50px !important; } .minwidth75imp { min-width: 75px !important; } - .minwidth100imp { min-width: 100px !important; } - .minwidth150imp { min-width: 110px !important; } - .minwidth200imp { min-width: 110px !important; } - .minwidth250imp { min-width: 115px !important; } - .minwidth300imp { min-width: 120px !important; } - .minwidth400imp { min-width: 150px !important; } - .minwidth500imp { min-width: 250px !important; } - .titlefield { width: auto; } - .titlefieldcreate { width: auto; } + .minwidth100imp { min-width: 100px !important; } + .minwidth150imp { min-width: 110px !important; } + .minwidth200imp { min-width: 110px !important; } + .minwidth250imp { min-width: 115px !important; } + .minwidth300imp { min-width: 120px !important; } + .minwidth400imp { min-width: 150px !important; } + .minwidth500imp { min-width: 250px !important; } + .titlefield { width: auto; } + .titlefieldcreate { width: auto; } #tooltip { position: absolute; @@ -1451,31 +1521,31 @@ table[summary="list_of_modules"] .fa-cog { div.divphotoref { padding-<?php echo $right; ?>: 5px; - padding-bottom: 5px; + padding-bottom: 5px; + } + img.photoref, div.photoref { + border: none; + -webkit-box-shadow: none; + box-shadow: none; + padding: 4px; + height: 20px; + width: 20px; + object-fit: contain; } - img.photoref, div.photoref { - border: none; - -webkit-box-shadow: none; - box-shadow: none; - padding: 4px; - height: 20px; - width: 20px; - object-fit: contain; - } div.statusref { - padding-right: 10px; - } + padding-right: 10px; + } div.statusref img { - padding-right: 3px !important; - } + padding-right: 3px !important; + } div.statusrefbis { - padding-right: 3px !important; - } + padding-right: 3px !important; + } - input.buttonpayment { + input.buttonpayment { min-width: 300px; - } + } } .linkobject { cursor: pointer; } @@ -1533,7 +1603,7 @@ td.showDragHandle { padding-bottom: 10px; <?php if (GETPOST('optioncss', 'aZ09') != 'print') { ?> padding-left: 229px; - padding-top: 12px; + padding-top: 16px; <?php } ?> } @@ -1690,7 +1760,7 @@ div.login_block { color: #333 !important; } .login_block_elem a span.atoplogin, .login_block_elem span.atoplogin { - vertical-align: middle; + vertical-align: middle; } @@ -1716,9 +1786,11 @@ div.fiche { <?php } ?> div.fiche { - margin-<?php print $left; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 6 : (empty($conf->dol_optimize_smallscreen) ? '24' : '6')); ?>px; - margin-<?php print $right; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 6 : (empty($conf->dol_optimize_smallscreen) ? '22' : '6')); ?>px; - <?php if (!empty($dol_hide_leftmenu) && !empty($dol_hide_topmenu)) print 'margin-top: 12px;'; ?> + margin-<?php print $left; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 6 : (empty($conf->dol_optimize_smallscreen) ? '30' : '6')); ?>px; + margin-<?php print $right; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 6 : (empty($conf->dol_optimize_smallscreen) ? '28' : '6')); ?>px; + <?php if (!empty($dol_hide_leftmenu) && !empty($dol_hide_topmenu)) { + print 'margin-top: 12px;'; + } ?> margin-bottom: 15px; } body.onlinepaymentbody div.fiche { /* For online payment page */ @@ -1735,76 +1807,102 @@ div.fichecenterbis { margin-top: 8px; } div.fichethirdleft { - <?php if ($conf->browser->layout != 'phone') { print "float: ".$left.";\n"; } ?> - <?php if ($conf->browser->layout != 'phone') { print "width: 50%;\n"; } ?> - <?php if ($conf->browser->layout == 'phone') { print "padding-bottom: 6px;\n"; } ?> + <?php if ($conf->browser->layout != 'phone') { + print "float: ".$left.";\n"; + } ?> + <?php if ($conf->browser->layout != 'phone') { + print "width: 50%;\n"; + } ?> + <?php if ($conf->browser->layout == 'phone') { + print "padding-bottom: 6px;\n"; + } ?> } div.fichetwothirdright { - <?php if ($conf->browser->layout != 'phone') { print "float: ".$right.";\n"; } ?> - <?php if ($conf->browser->layout != 'phone') { print "width: 50%;\n"; } ?> - <?php if ($conf->browser->layout == 'phone') { print "padding-bottom: 6px\n"; } ?> + <?php if ($conf->browser->layout != 'phone') { + print "float: ".$right.";\n"; + } ?> + <?php if ($conf->browser->layout != 'phone') { + print "width: 50%;\n"; + } ?> + <?php if ($conf->browser->layout == 'phone') { + print "padding-bottom: 6px\n"; + } ?> } div.fichetwothirdright div.ficheaddleft { - padding-left: 20px; + padding-left: 20px; } div.fichehalfleft { - <?php if ($conf->browser->layout != 'phone') { print "float: ".$left.";\n"; } ?> - <?php if ($conf->browser->layout != 'phone') { print "width: calc(50% - 10px);\n"; } ?> + <?php if ($conf->browser->layout != 'phone') { + print "float: ".$left.";\n"; + } ?> + <?php if ($conf->browser->layout != 'phone') { + print "width: calc(50% - 10px);\n"; + } ?> } div.fichehalfright { - <?php if ($conf->browser->layout != 'phone') { print "float: ".$right.";\n"; } ?> - <?php if ($conf->browser->layout != 'phone') { print "width: calc(50% - 10px);\n"; } ?> + <?php if ($conf->browser->layout != 'phone') { + print "float: ".$right.";\n"; + } ?> + <?php if ($conf->browser->layout != 'phone') { + print "width: calc(50% - 10px);\n"; + } ?> } div.fichehalfright { - <?php if ($conf->browser->layout == 'phone') { print "margin-top: 10px;\n"; } ?> + <?php if ($conf->browser->layout == 'phone') { + print "margin-top: 10px;\n"; + } ?> } -div.firstcolumn div.box { + +/*div.firstcolumn div.box { padding-right: 10px; } div.secondcolumn div.box { padding-left: 10px; -} +}*/ + /* Force values on one colum for small screen */ @media only screen and (max-width: 900px) { - div.fiche { - margin-<?php print $left; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 6 : ($dol_hide_leftmenu ? '4' : '20')); ?>px; - margin-<?php print $right; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 8 : 16); ?>px; - <?php if (!empty($conf->dol_hide_leftmenu) && !empty($conf->dol_hide_topmenu)) print 'margin-top: 4px;'; ?> - margin-bottom: 15px; - } - div.fichecenter { - width: 100%; - clear: both; /* This is to have div fichecenter that are true rectangles */ - } - div.fichecenterbis { - margin-top: 8px; - } - div.fichethirdleft { - float: none; - width: auto; - padding-bottom: 6px; - } - div.fichetwothirdright { - float: none; - width: auto; - padding-bottom: 6px; - } - div.fichetwothirdright div.ficheaddleft { - padding-left: 0; + div.fiche { + margin-<?php print $left; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 6 : ($dol_hide_leftmenu ? '4' : '20')); ?>px; + margin-<?php print $right; ?>: <?php print (GETPOST('optioncss', 'aZ09') == 'print' ? 8 : 16); ?>px; + <?php if (!empty($conf->dol_hide_leftmenu) && !empty($conf->dol_hide_topmenu)) { + print 'margin-top: 4px;'; + } ?> + margin-bottom: 15px; } - div.fichehalfleft { - float: none; - width: auto; - } - div.fichehalfright { - float: none; - width: auto; - } - div.fichehalfright { - margin-top: 10px; - } - div.firstcolumn div.box { + div.fichecenter { + width: 100%; + clear: both; /* This is to have div fichecenter that are true rectangles */ + } + div.fichecenterbis { + margin-top: 8px; + } + div.fichethirdleft { + float: none; + width: auto; + padding-bottom: 6px; + } + div.fichetwothirdright { + float: none; + width: auto; + padding-bottom: 6px; + } + div.fichetwothirdright div.ficheaddleft { + padding-left: 0; + } + div.fichehalfleft { + float: none; + width: auto; + } + div.fichehalfright { + float: none; + width: auto; + } + div.fichehalfright { + margin-top: 10px; + } + div.firstcolumn div.box { padding-right: 0px; } div.secondcolumn div.box { @@ -1814,7 +1912,7 @@ div.secondcolumn div.box { /* For table into table into card */ div.fichehalfright tr.liste_titre:first-child td table.nobordernopadding td { - padding: 0 0 0 0; + padding: 0 0 0 0; } div.nopadding { padding: 0 !important; @@ -1833,17 +1931,17 @@ div.nopadding { width: 14px; } .table-list-of-attached-files .col-picto, .table-list-of-links .col-picto { - opacity: 0.7 !important; - font-size: 1em; - width: 20px; + opacity: 0.7 !important; + font-size: 1em; + width: 20px; } .table-list-of-attached-files .col-picto .widthpictotitle, .table-list-of-links .col-picto .widthpictotitle { width: unset; - color: #999; + color: #999; } .pictosubstatus { - padding-left: 2px; - padding-right: 2px; + padding-left: 2px; + padding-right: 2px; } .pictostatus { width: 15px; @@ -1851,14 +1949,14 @@ div.nopadding { margin-top: -3px } .pictowarning, .pictoerror, .pictopreview { - padding-<?php echo $left; ?>: 3px; + padding-<?php echo $left; ?>: 3px; } .pictowarning { - /* vertical-align: text-bottom; */ - color: <?php echo $badgeWarning; ?>; + /* vertical-align: text-bottom; */ + color: <?php echo $badgeWarning; ?>; } .pictoerror { - color: <?php echo $badgeDanger ?>; + color: <?php echo $badgeDanger ?>; } .pictomodule { width: 14px; @@ -1866,14 +1964,16 @@ div.nopadding { .fiche .arearef img.pictoedit, .fiche .arearef span.pictoedit, .fiche .fichecenter img.pictoedit, .fiche .fichecenter span.pictoedit, .tagtdnote span.pictoedit { - opacity: 0.6; + opacity: 0.6; } img.hideonsmartphone.pictoactionview { - vertical-align: bottom; + vertical-align: bottom; } + .pictofixedwidth { - text-align: left; - width: 16px; + text-align: left; + width: 20px; + padding-right: 0; } .colorthumb { @@ -1881,7 +1981,7 @@ img.hideonsmartphone.pictoactionview { padding-right: 1px; padding-top: 1px; padding-bottom: 1px; - width: 44px; + width: 50px; text-align:center; } div.attacharea { @@ -1918,32 +2018,32 @@ div.statusref { clear: both; } div.statusref img { - padding-left: 8px; - padding-right: 9px; - vertical-align: text-bottom; - width: 18px; + padding-left: 8px; + padding-right: 9px; + vertical-align: text-bottom; + width: 18px; } div.statusrefbis { - padding-left: 8px; - padding-right: 9px; - vertical-align: text-bottom; + padding-left: 8px; + padding-right: 9px; + vertical-align: text-bottom; } img.photoref, div.photoref { border: 1px solid #CCC; - -webkit-box-shadow: 3px 3px 4px #DDD; - box-shadow: 3px 3px 4px #DDD; - padding: 4px; + -webkit-box-shadow: 3px 3px 4px #DDD; + box-shadow: 3px 3px 4px #DDD; + padding: 4px; height: 80px; width: 80px; - object-fit: contain; + object-fit: contain; } div.photoref .fa, div.photoref .fas, div.photoref .far { - font-size: 2.5em; + font-size: 2.5em; } img.fitcontain { - object-fit: contain; + object-fit: contain; } div.photoref { display:table-cell; @@ -1951,12 +2051,12 @@ div.photoref { text-align:center; } img.photorefnoborder { - padding: 2px; + padding: 2px; height: 48px; width: 48px; - object-fit: contain; - border: 1px solid #AAA; - border-radius: 100px; + object-fit: contain; + border: 1px solid #AAA; + border-radius: 100px; } .underrefbanner { } @@ -1965,7 +2065,7 @@ img.photorefnoborder { } .trextrafieldseparator td, .trextrafields_collapse_last td { - border-bottom: 1px solid rgb(<?php echo $colortopbordertitle1 ?>) !important; + border-bottom: 1px solid rgb(<?php echo $colortopbordertitle1 ?>) !important; } .tdhrthin { margin: 0; @@ -1987,7 +2087,9 @@ $heightmenu = 48; /* height of top menu, part with image */ $heightmenu2 = 48; /* height of top menu, ârt with login */ $disableimages = 0; $maxwidthloginblock = 110; -if (!empty($conf->global->THEME_TOPMENU_DISABLE_IMAGE)) { $heightmenu = 30; $disableimages = 1; $maxwidthloginblock = 180; $minwidthtmenu = 0; } +if (!empty($conf->global->THEME_TOPMENU_DISABLE_IMAGE)) { + $heightmenu = 30; $disableimages = 1; $maxwidthloginblock = 180; $minwidthtmenu = 0; +} ?> div#tmenu_tooltip { @@ -2024,25 +2126,25 @@ div.tmenudiv { <?php if (GETPOST('optioncss', 'aZ09') == 'print') { ?> display:none; <?php } else { ?> - position: relative; - display: block; - white-space: nowrap; - border-top: 0px; - border-<?php print $left; ?>: 0px; - border-<?php print $right; ?>: 0px; - padding: 0px 0px 0px 0px; /* t r b l */ - margin: 0px 0px 0px 0px; /* t r b l */ + position: relative; + display: block; + white-space: nowrap; + border-top: 0px; + border-<?php print $left; ?>: 0px; + border-<?php print $right; ?>: 0px; + padding: 0px 0px 0px 0px; /* t r b l */ + margin: 0px 0px 0px 0px; /* t r b l */ font-size: 13px; - font-weight: normal; + font-weight: normal; color: #000000; - text-decoration: none; + text-decoration: none; <?php } ?> } div.tmenudisabled, a.tmenudisabled { opacity: 0.6; } a.tmenudisabled:link, a.tmenudisabled:visited, a.tmenudisabled:hover, a.tmenudisabled:active { - font-weight: normal; + font-weight: normal; padding: 0px 5px 0px 5px; white-space: nowrap; color: #<?php echo $colortextbackhmenu; ?>; @@ -2051,12 +2153,12 @@ a.tmenudisabled:link, a.tmenudisabled:visited, a.tmenudisabled:hover, a.tmenudis } a.tmenu:link, a.tmenu:visited, a.tmenu:hover, a.tmenu:active { - font-weight: normal; + font-weight: normal; padding: 0px 5px 0px 5px; white-space: nowrap; /* text-shadow: 1px 1px 1px #000000; */ color: #<?php echo $colortextbackhmenu; ?>; - text-decoration: none; + text-decoration: none; } a.tmenusel:link, a.tmenusel:visited, a.tmenusel:hover, a.tmenusel:active { font-weight: normal; @@ -2069,12 +2171,12 @@ a.tmenusel:link, a.tmenusel:visited, a.tmenusel:hover, a.tmenusel:active { ul.tmenu { /* t r b l */ - padding: 0px 0px 0px 0px; - margin: 0px 0px 0px 0px; + padding: 0px 0px 0px 0px; + margin: 0px 0px 0px 0px; list-style: none; display: table; - margin-right: 65px; /* to keep space for bookmark */ - padding-left: 5px; + margin-right: 65px; /* to keep space for bookmark */ + padding-left: 5px; } ul.tmenu li { background: rgb(<?php echo $colorbackhmenu1 ?>); @@ -2093,12 +2195,13 @@ li.tmenu, li.tmenusel { vertical-align: bottom; <?php if (empty($conf->global->MAIN_MENU_INVERT)) { ?> float: <?php print $left; ?>; - <?php if (!$disableimages) { ?> - height: <?php print $heightmenu; ?>px; + <?php if (!$disableimages) { ?> + height: <?php print $heightmenu; ?>px; padding: 0px 0px 2px 0px; - <?php } else { ?> - padding: 0px 0px 0px 0px; - <?php } } ?> + <?php } else { ?> + padding: 0px 0px 0px 0px; + <?php } + } ?> position:relative; display: block; margin: 0px 0px 0px 0px; @@ -2133,14 +2236,14 @@ div.tmenucenter height: 26px; <?php } else { ?> padding-top: 2px; - height: <?php print $heightmenu; ?>px; + height: <?php print $heightmenu; ?>px; <?php } ?> - width: 100%; + width: 100%; } div.menu_titre { padding-bottom: 2px; overflow: hidden; - text-overflow: ellipsis; + text-overflow: ellipsis; } .mainmenuaspan { @@ -2157,14 +2260,14 @@ div.mainmenu { min-width: 40px; } a.tmenuimage:focus, .mainmenu.topmenuimage:focus { - outline: none; + outline: none; } /* Do not load menu img if hidden to save bandwidth */ <?php if (empty($dol_hide_topmenu)) { ?> - <?php if (!defined('DISABLE_FONT_AWSOME')) { ?> - <?php include dol_buildpath($path.'/theme/'.$theme.'/main_menu_fa_icons.inc.php', 0); ?> - <?php } ?> + <?php if (!defined('DISABLE_FONT_AWSOME')) { ?> + <?php include dol_buildpath($path.'/theme/'.$theme.'/main_menu_fa_icons.inc.php', 0); ?> + <?php } ?> div.mainmenu.home{ background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/home.png', 1) ?>); @@ -2184,7 +2287,7 @@ div.mainmenu.agenda { } div.mainmenu.bank { - background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/bank.png', 1) ?>); + background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/bank.png', 1) ?>); } div.mainmenu.cashdesk { @@ -2212,7 +2315,7 @@ div.mainmenu.externalsite { } div.mainmenu.ftp { - background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/tools.png', 1) ?>); + background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/tools.png', 1) ?>); } div.mainmenu.hrm { @@ -2265,8 +2368,7 @@ div.mainmenu.website { 'barcode'=>'', 'fckeditor'=>'', 'categorie'=>'', ); $mainmenuused = 'home'; - foreach ($conf->modules as $val) - { + foreach ($conf->modules as $val) { $mainmenuused .= ','.(isset($moduletomainmenu[$val]) ? $moduletomainmenu[$val] : $val); } $mainmenuusedarray = array_unique(explode(',', $mainmenuused)); @@ -2276,26 +2378,26 @@ div.mainmenu.website { $divalreadydefined = array('home', 'companies', 'products', 'mrp', 'commercial', 'externalsite', 'accountancy', 'project', 'tools', 'members', 'agenda', 'ftp', 'holiday', 'hrm', 'bookmark', 'cashdesk', 'takepos', 'ecm', 'geoipmaxmind', 'gravatar', 'clicktodial', 'paypal', 'stripe', 'webservices', 'website'); // Put here list of menu entries we are sure we don't want $divnotrequired = array('multicurrency', 'salaries', 'ticket', 'margin', 'opensurvey', 'paybox', 'expensereport', 'incoterm', 'prelevement', 'propal', 'workflow', 'notification', 'supplier_proposal', 'cron', 'product', 'productbatch', 'expedition'); - foreach ($mainmenuusedarray as $val) - { - if (empty($val) || in_array($val, $divalreadydefined)) continue; - if (in_array($val, $divnotrequired)) continue; + foreach ($mainmenuusedarray as $val) { + if (empty($val) || in_array($val, $divalreadydefined)) { + continue; + } + if (in_array($val, $divnotrequired)) { + continue; + } //print "XXX".$val; // Search img file in module dir $found = 0; $url = ''; - foreach ($conf->file->dol_document_root as $dirroot) - { - if (file_exists($dirroot."/".$val."/img/".$val.".png")) - { + foreach ($conf->file->dol_document_root as $dirroot) { + if (file_exists($dirroot."/".$val."/img/".$val.".png")) { $url = dol_buildpath('/'.$val.'/img/'.$val.'.png', 1); $found = 1; break; } } // Img file not found - if (!$found) - { + if (!$found) { if (!defined('DISABLE_FONT_AWSOME')) { print "/* A mainmenu entry was found but img file ".$val.".png not found (check /".$val."/img/".$val.".png), so we use a generic one */\n"; print 'div.mainmenu.'.$val.'::before { @@ -2320,22 +2422,22 @@ div.mainmenu.website { } // End test if $dol_hide_topmenu ?> .tmenuimage { - padding:0 0 0 0 !important; - margin:0 0px 0 0 !important; - <?php if ($disableimages) { ?> - display: none; - <?php } ?> + padding:0 0 0 0 !important; + margin:0 0px 0 0 !important; + <?php if ($disableimages) { ?> + display: none; + <?php } ?> } .topmenuimage { <?php if ($disableimages) { ?> - display: none; - <?php } ?> + display: none; + <?php } ?> } a.tmenuimage { - display: block; + display: block; } a.tmenuimage:focus { - outline: none; + outline: none; } @@ -2345,13 +2447,13 @@ a.tmenuimage:focus { { background: #f0f0f0; display: table; - position: absolute; - height: 100%; - width: 100%; + position: absolute; + height: 100%; + width: 100%; } .login_center { display: table-cell; - vertical-align: middle; + vertical-align: middle; } .login_vertical_align { padding: 10px; @@ -2404,9 +2506,9 @@ form#login { margin: 8px; } .login_table .tdinputlogin { - background-color: #fff; - min-width: 220px; - border-radius: 2px; + background-color: #fff; + min-width: 220px; + border-radius: 2px; } .login_table .tdinputlogin { border-bottom: 1px solid #ccc; @@ -2417,7 +2519,7 @@ form#login { } .login_main_home { - word-break: break-word; + word-break: break-word; } .login_main_message { text-align: center; @@ -2438,7 +2540,7 @@ div#login_left, div#login_right { vertical-align: middle; } div#login_right select#entity { - margin-top: 10px; + margin-top: 10px; } table.login_table tr td table.none tr td { padding: 2px; @@ -2468,8 +2570,8 @@ table.login_table_securitycode tr td { div.login_block { border-right: 1px solid rgba(0,0,0,0.3); - padding-top: 3px; - padding-bottom: 3px; + padding-top: 3px; + padding-bottom: 3px; <?php print $left; ?>: 0; top: 0px; <?php if (in_array($conf->browser->layout, array('phone', 'tablet')) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { ?> @@ -2507,13 +2609,13 @@ div.login_block_other { padding-top: 3px; } .topnav div.login_block_user { display: inline-block; - vertical-align: middle; + vertical-align: middle; line-height: <?php echo $disableimages ? '25' : '50'; ?>px; height: <?php echo $disableimages ? '25' : '50'; ?>px; } .topnav div.login_block_other { display: inline-block; - vertical-align: middle; + vertical-align: middle; clear: <?php echo $disableimages ? 'none' : 'both'; ?>; padding-top: 0; text-align: right; @@ -2531,11 +2633,11 @@ div.login_block_other { padding-top: 3px; } margin-top: 1px; } a.aversion { - white-space: nowrap; - width: 48px; - overflow: hidden; - text-overflow: ellipsis; - display: block; + white-space: nowrap; + width: 48px; + overflow: hidden; + text-overflow: ellipsis; + display: block; } .atoplogin, .atoplogin:hover { @@ -2550,8 +2652,8 @@ a.aversion { text-decoration:underline !important; } span.fa.atoplogin, span.fa.atoplogin:hover { - font-size: 16px; - text-decoration: none !important; + font-size: 16px; + text-decoration: none !important; } img.login, img.printer, img.entity { /* padding: 0px 0px 0px 4px; */ @@ -2564,29 +2666,29 @@ img.login, img.printer, img.entity { border-radius: 8px; width: 16px; height: 16px; - background-size: contain; + background-size: contain; vertical-align: text-bottom; background-color: #FFF; } img.userphoto { /* size for user photo in lists */ - border-radius: 0.75em; - width: 1.5em; - height: 1.5em; - background-size: contain; - vertical-align: middle; + border-radius: 0.75em; + width: 1.5em; + height: 1.5em; + background-size: contain; + vertical-align: middle; } img.userphotosmall { /* size for user photo in lists */ border-radius: 0.6em; width: 1.2em; - height: 1.2em; - background-size: contain; - vertical-align: middle; + height: 1.2em; + background-size: contain; + vertical-align: middle; } img.userphoto[alt="Gravatar avatar"] { - background: #fff; + background: #fff; } form[name="addtime"] img.userphoto { - border: 1px solid #444; + border: 1px solid #444; } .span-icon-user { background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/object_user.png', 1); ?>); @@ -2602,19 +2704,19 @@ form[name="addtime"] img.userphoto { /* ============================================================================== */ div.vmenu, td.vmenu { - margin-<?php print $right; ?>: 2px; - position: relative; - float: left; - padding: 0px; - padding-bottom: 0px; - padding-top: 0px; - width: 222px; + margin-<?php print $right; ?>: 2px; + position: relative; + float: left; + padding: 0px; + padding-bottom: 0px; + padding-top: 0px; + width: 222px; } .vmenu { margin-left: 4px; <?php if (GETPOST('optioncss', 'aZ09') == 'print') { ?> - display: none; + display: none; <?php } ?> } @@ -2626,7 +2728,7 @@ div.vmenu, td.vmenu { padding-top: 4px; padding-bottom: 3px; overflow: hidden; - text-overflow: ellipsis; + text-overflow: ellipsis; } #menu_contenu_logo { padding-right: 4px; } .companylogo { padding-top: 4px; } @@ -2644,14 +2746,14 @@ font.vsmenudisabledmargin { margin: 1px 1px 1px 8px; } a.help:link, a.help:visited, a.help:hover, a.help:active, span.help { text-align: <?php print $left; ?>; font-weight: normal; color: #999; text-decoration: none; } .helppresentcircle { - color: var(--colorbackhmenu1); - filter: invert(0.5); - margin-left: -7px; - display: inline-block; - margin-top: -10px; - font-size: x-small; - vertical-align: super; - opacity: 0.95; + color: var(--colorbackhmenu1); + filter: invert(0.5); + margin-left: -7px; + display: inline-block; + margin-top: -10px; + font-size: x-small; + vertical-align: super; + opacity: 0.95; } div.blockvmenulogo @@ -2659,23 +2761,23 @@ div.blockvmenulogo border-bottom: 0 !important; } .menulogocontainer { - margin: <?php echo $disableimages ? '0' : '6'; ?>px; - margin-left: 12px; - margin-right: 6px; - padding: 0; - height: <?php echo $disableimages ? '20' : '32'; ?>px; - /* width: 100px; */ - max-width: 100px; - vertical-align: middle; + margin: <?php echo $disableimages ? '0' : '6'; ?>px; + margin-left: 12px; + margin-right: 6px; + padding: 0; + height: <?php echo $disableimages ? '20' : '32'; ?>px; + /* width: 100px; */ + max-width: 100px; + vertical-align: middle; } .backgroundforcompanylogo { background-color: rgba(255,255,255,0.7); border-radius: 5px; } .menulogocontainer img.mycompany { - object-fit: contain; - width: inherit; - height: inherit; + object-fit: contain; + width: inherit; + height: inherit; } #mainmenutd_companylogo::after { content: unset; @@ -2701,14 +2803,14 @@ div.blockvmenupair, div.blockvmenuimpair color: #000000; text-align: <?php print $left; ?>; text-decoration: none; - padding-left: 5px; - padding-right: 1px; - padding-top: 3px; - padding-bottom: 3px; - margin: 1px 0px 8px 0px; + padding-left: 5px; + padding-right: 1px; + padding-top: 3px; + padding-bottom: 3px; + margin: 1px 0px 8px 0px; - padding-bottom: 10px; - border-bottom: 1px solid #e0e0e0; + padding-bottom: 10px; + border-bottom: 1px solid #e0e0e0; } div.blockvmenubookmarks { @@ -2719,7 +2821,7 @@ div.blockvmenuend { padding-left: 0 !important; } a.vsmenu.addbookmarkpicto { - padding-right: 10px; + padding-right: 10px; } div.blockvmenufirst { padding-top: 10px; @@ -2731,14 +2833,14 @@ div.blockvmenusearch, div.blockvmenubookmarks color: #000000; text-align: <?php print $left; ?>; text-decoration: none; - padding-left: 5px; - padding-right: 1px; - padding-top: 3px; - padding-bottom: 3px; - margin: 1px 0px 2px 0px; + padding-left: 5px; + padding-right: 1px; + padding-top: 3px; + padding-bottom: 3px; + margin: 1px 0px 2px 0px; - padding-bottom: 10px; - /* border-bottom: 1px solid #f4f4f4; */ + padding-bottom: 10px; + /* border-bottom: 1px solid #f4f4f4; */ } div.blockvmenusearchphone { @@ -2753,13 +2855,13 @@ div.blockvmenuhelp color: #000000; text-align: center; text-decoration: none; - padding-left: 0px; - padding-right: 8px; - padding-top: 3px; - padding-bottom: 3px; - margin: 4px 0px 0px 0px; + padding-left: 0px; + padding-right: 8px; + padding-top: 3px; + padding-bottom: 3px; + margin: 4px 0px 0px 0px; <?php } else { ?> - display: none; + display: none; <?php } ?> } @@ -2782,7 +2884,7 @@ td.barre_select { td.photo { background: #F4F4F4; color: #000000; - border: 1px solid #bbb; + border: 1px solid #bbb; } /* ============================================================================== */ @@ -2794,14 +2896,14 @@ td.photo { */ #mainContent, #leftContent .ui-layout-pane { - padding: 0px; - overflow: auto; + padding: 0px; + overflow: auto; } #mainContent, #leftContent .ui-layout-center { padding: 0px; position: relative; /* contain floated or positioned elements */ - overflow: auto; /* add scrolling to content-div */ + overflow: auto; /* add scrolling to content-div */ } @@ -2810,29 +2912,29 @@ td.photo { /* ============================================================================== */ td.ecmroot { - padding-bottom: 0 !important; + padding-bottom: 0 !important; } .largebutton { /* border-top: 1px solid #CCC !important; */ - padding: 0px 4px 14px 4px !important; - min-height: 32px; + padding: 0px 4px 14px 4px !important; + min-height: 32px; } a.toolbarbutton { - margin-top: 0px; - margin-left: 4px; - margin-right: 4px; - height: 30px; + margin-top: 0px; + margin-left: 4px; + margin-right: 4px; + height: 30px; } img.toolbarbutton { margin-top: 1px; - height: 30px; + height: 30px; } li.expanded > a.fmdirlia.jqft.ecmjqft { - font-weight: bold !important; + font-weight: bold !important; } @@ -2840,30 +2942,30 @@ li.expanded > a.fmdirlia.jqft.ecmjqft { /* Onglets */ /* ============================================================================== */ div.tabs { - text-align: <?php print $left; ?>; - margin-left: 6px !important; - margin-right: 6px !important; - clear:both; + text-align: <?php print $left; ?>; + margin-left: 6px !important; + margin-right: 6px !important; + clear:both; height:100%; } div.tabsElem { margin-top: 6px; } /* To avoid overlap of tabs when not browser */ div.tabsElem a { - font-weight: normal !important; + font-weight: normal !important; } div.tabBar { - color: #<?php echo $colortextbacktab; ?>; - padding-top: 16px; - padding-left: 16px; - padding-right: 16px; + color: #<?php echo $colortextbacktab; ?>; + padding-top: 16px; + padding-left: 16px; + padding-right: 16px; padding-bottom: 16px; - margin: 0px 0px 16px 0px; - -webkit-border-radius: 3px; + margin: 0px 0px 16px 0px; + -webkit-border-radius: 3px; border-radius: 3px; - border-right: 1px solid #BBB; - border-left: 1px solid #BBB; - border-top: 1px solid #CCC; + border-right: 1px solid #BBB; + border-left: 1px solid #BBB; + border-top: 1px solid #CCC; width: auto; background: rgb(<?php echo $colorbacktabcard1; ?>); border-bottom: 1px solid #aaa; @@ -2875,8 +2977,8 @@ div.tabBar tr.titre td { /* div.tabBar.tabBarNoTop { - padding-top: 0; - border-top: 0; + padding-top: 0; + border-top: 0; } */ @@ -2886,7 +2988,7 @@ div.tabBarWithBottom { border-bottom: 1px solid #aaa; } div.tabBar table.tableforservicepart2:last-child { - border-bottom: 1px solid #aaa; + border-bottom: 1px solid #aaa; } .tableforservicepart1 .tdhrthin { height: unset; @@ -2904,12 +3006,12 @@ div.divButAction { margin-bottom: 1.4em; } div.tabsAction { - margin: 20px 0em 20px 0em; - padding: 0em 0em; - text-align: right; + margin: 20px 0em 20px 0em; + padding: 0em 0em; + text-align: right; } div.tabsActionNoBottom { - margin-bottom: 0px; + margin-bottom: 0px; } div.tabsAction > a { margin-bottom: 16px !important; @@ -2928,15 +3030,15 @@ div.popuptab { } a.tabTitle { - color:rgba(0,0,0,.5); - margin-<?php print $right; ?>: 10px; - text-shadow:1px 1px 1px #ffffff; + color:rgba(0,0,0,.5); + margin-<?php print $right; ?>: 10px; + text-shadow:1px 1px 1px #ffffff; font-family: <?php print $fontlist ?>; font-weight: normal; - padding: 4px 6px 2px 6px; - margin: 0px 6px; - text-decoration: none; - white-space: nowrap; + padding: 4px 6px 2px 6px; + margin: 0px 6px; + text-decoration: none; + white-space: nowrap; } .tabTitleText { display: none; @@ -2945,22 +3047,22 @@ a.tabTitle { max-height: 14px; } div.tabs div.tabsElem:first-of-type a.tab { - margin-left: 0px !important; + margin-left: 0px !important; } a.tab:link, a.tab:visited, a.tab:hover, a.tab#active { font-family: <?php print $fontlist ?>; padding: 12px 13px 12px; - margin: 0em 0.2em; - text-decoration: none; - white-space: nowrap; + margin: 0em 0.2em; + text-decoration: none; + white-space: nowrap; background-image: none !important; } .tabunactive { /* We add some border on tabunactive to avoid change of position of title when switching tabs (border of tabunactive = border of tabactive) */ - border-right: 1px solid rgb(<?php echo $colorbackbody; ?>); - border-left: 1px solid rgb(<?php echo $colorbackbody; ?>); + border-right: 1px solid rgb(<?php echo $colorbackbody; ?>); + border-left: 1px solid rgb(<?php echo $colorbackbody; ?>); } .tabactive, a.tab#active { @@ -2980,30 +3082,30 @@ a.tab:hover text-decoration: underline; } a.tabimage { - color: #434956; + color: #434956; font-family: <?php print $fontlist ?>; - text-decoration: none; - white-space: nowrap; + text-decoration: none; + white-space: nowrap; } td.tab { - background: #dee7ec; + background: #dee7ec; } span.tabspan { - background: #dee7ec; - color: #434956; + background: #dee7ec; + color: #434956; font-family: <?php print $fontlist ?>; - padding: 0px 6px; - margin: 0em 0.2em; - text-decoration: none; - white-space: nowrap; + padding: 0px 6px; + margin: 0em 0.2em; + text-decoration: none; + white-space: nowrap; -webkit-border-radius:3px 3px 0px 0px; border-radius:3px 3px 0px 0px; - border-<?php print $right; ?>: 1px solid #555555; - border-<?php print $left; ?>: 1px solid #D8D8D8; - border-top: 1px solid #D8D8D8; + border-<?php print $right; ?>: 1px solid #555555; + border-<?php print $left; ?>: 1px solid #D8D8D8; + border-top: 1px solid #D8D8D8; } /* ============================================================================== */ @@ -3051,7 +3153,7 @@ tr.nocellnopadd td.nobordernopadding, tr.nocellnopadd td.nocellnopadd } .smallpaddingimp { - padding: 4px !important; + padding: 4px !important; } .nopaddingleft { padding-<?php print $left; ?>: 0px; @@ -3085,8 +3187,8 @@ tr.nocellnopadd td.nobordernopadding, tr.nocellnopadd td.nocellnopadd } table.tableforemailform tr td { - padding-top: 3px; - padding-bottom: 3px; + padding-top: 3px; + padding-bottom: 3px; } table.border, table.bordernooddeven, table.dataTable, .table-border, .table-border-col, .table-key-border-col, .table-val-border-col, div.border { @@ -3102,7 +3204,7 @@ table.borderplus { height: 26px; } tr.liste_titre.box_titre td table td, .bordernooddeven tr td { - height: 26px; + height: 26px; } table.border td, table.bordernooddeven td, div.border div div.tagtd { @@ -3129,10 +3231,10 @@ td.border, div.tagtable div div.border { /* Main boxes */ .nobordertop, .nobordertop tr:first-of-type td { - border-top: none !important; + border-top: none !important; } .noborderbottom, .noborderbottom tr:last-of-type td { - border-bottom: none !important; + border-bottom: none !important; } .bordertop { border-top: 1px solid rgb(<?php echo $colortopbordertitle1 ?>); @@ -3151,8 +3253,8 @@ div.colorback margin-top: 5px; } .liste_titre_bydiv { - border-right: 1px solid #ccc; - border-left: 1px solid #ccc; + border-right: 1px solid #ccc; + border-left: 1px solid #ccc; } table.liste, table.noborder, table.formdoc, div.noborder { width: calc(100% - 1px); /* -1 to fix a bug. Without, a scroll appears due to overflow-x: auto; of div-table-responsive */ @@ -3168,8 +3270,8 @@ table.liste, table.noborder, table.formdoc, div.noborder { border-bottom-color: #BBB; border-bottom-style: solid; - border-right: 1px solid #ccc; - border-left: 1px solid #ccc; + border-right: 1px solid #ccc; + border-left: 1px solid #ccc; margin: 0px 0px 8px 0px; @@ -3202,21 +3304,21 @@ tr.liste_titre_filter td.liste_titre { } .liste_titre_create td, .liste_titre_create th, .liste_titre_create .tagtd { - /*border-top-width: 1px; - border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); - border-top-style: solid;*/ + /*border-top-width: 1px; + border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); + border-top-style: solid;*/ } .liste_titre_add td, .liste_titre_add th, .liste_titre_add .tagtd { - border-top-width: 2px; - border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); - border-top-style: solid; + border-top-width: 2px; + border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); + border-top-style: solid; } .liste_titre_add td, .liste_titre_add .tagtd { - border-top-width: 1px; - border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); - border-top-style: solid; + border-top-width: 1px; + border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); + border-top-style: solid; } table.liste th, table.noborder th, table.noborder tr.liste_titre td { @@ -3227,7 +3329,7 @@ table.noborder td, div.noborder form, div.noborder form div, table.tableforservi } form.tagtable { padding: unset !important; - border: unset !important; + border: unset !important; } table.liste td, table.noborder td, div.noborder form div { @@ -3254,13 +3356,13 @@ table.border tr td table.nobordernopadding tr td { padding-bottom: 0; } td.borderright { - border: none; /* to erase value for table.nobordernopadding td */ + border: none; /* to erase value for table.nobordernopadding td */ border-right-width: 1px !important; border-right-color: #BBB !important; border-right-style: solid !important; } td.borderleft { - border: none; /* to erase value for table.nobordernopadding td */ + border: none; /* to erase value for table.nobordernopadding td */ border-left-width: 1px !important; border-left-color: #BBB !important; border-left-style: solid !important; @@ -3284,17 +3386,17 @@ div.refidpadding { div.refid { font-weight: bold; color: rgb(<?php print $colortexttitlenotab; ?>); - font-size: 160%; + font-size: 160%; } div.refidno { padding-top: 8px; font-weight: normal; - color: #444; - font-size: <?php print $fontsize ?>px; - line-height: 21px; + color: #444; + font-size: <?php print $fontsize ?>px; + line-height: 21px; } div.refidno form { - display: inline-block; + display: inline-block; } div.pagination { @@ -3362,10 +3464,10 @@ div.pagination li a:hover, div.pagination li span:hover, div.pagination li a:focus, div.pagination li span:focus { - color: #000; - background-color: #eee; - border-color: #ddd; - /* padding-top: 8px; */ + color: #000; + background-color: #eee; + border-color: #ddd; + /* padding-top: 8px; */ } div.pagination li .active a, div.pagination li .active span, @@ -3410,12 +3512,12 @@ table.hidepaginationnext .paginationnext { display: none; } .paginationafterarrows a.btnTitlePlus { - border: 1px solid var(--btncolorborder); + border: 1px solid var(--btncolorborder); } .paginationafterarrows a.btnTitlePlus:hover span:before { - /* text-shadow: 0px 0px 5px #ccc; */ - /* filter: invert(0.3); */ - font-size: 1.03em; + /* text-shadow: 0px 0px 5px #ccc; */ + /* filter: invert(0.3); */ + font-size: 1.03em; } @@ -3527,25 +3629,25 @@ td.evenodd, tr.nohoverpair td, #trlinefordates td { } .trforbreak td { font-weight: bold; - border-bottom: 1pt solid black !important; + border-bottom: 1pt solid black !important; background-color: var(--colorbacklinebreak) !important; } table.dataTable td { - padding: 5px 2px 5px 3px !important; + padding: 5px 2px 5px 3px !important; } tr.pair td, tr.impair td, form.impair div.tagtd, form.pair div.tagtd, div.impair div.tagtd, div.pair div.tagtd, div.liste_titre div.tagtd { - padding: 5px 2px 5px 3px; - border-bottom: 1px solid #eee; + padding: 5px 2px 5px 3px; + border-bottom: 1px solid #eee; } form.pair, form.impair { font-weight: normal; } tr.pair:last-of-type td, tr.impair:last-of-type td { - border-bottom: 0px !important; + border-bottom: 0px !important; } tr.pair td .nobordernopadding tr td, tr.impair td .nobordernopadding tr td { - border-bottom: 0px !important; + border-bottom: 0px !important; } /* table.nobottomiftotal tr.liste_total td { @@ -3576,8 +3678,8 @@ div.liste_titre { } div.liste_titre_bydiv { border-top-width: <?php echo $borderwidth ?>px; - border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); - border-top-style: solid; + border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); + border-top-style: solid; box-shadow: none; border-collapse: collapse; @@ -3593,11 +3695,11 @@ div.liste_titre_bydiv, .liste_titre div.tagtr, tr.liste_titre, tr.liste_titre_se { background: rgb(<?php echo $colorbacktitle1; ?>); font-weight: <?php echo $useboldtitle ? 'bold' : 'normal'; ?>; - border-bottom: 1px solid #FDFFFF; + border-bottom: 1px solid #FDFFFF; - color: rgb(<?php echo $colortexttitle; ?>); - font-family: <?php print $fontlist ?>; - text-align: <?php echo $left; ?>; + color: rgb(<?php echo $colortexttitle; ?>); + font-family: <?php print $fontlist ?>; + text-align: <?php echo $left; ?>; } tr.liste_titre th, tr.liste_titre td, th.liste_titre { @@ -3605,14 +3707,14 @@ tr.liste_titre th, tr.liste_titre td, th.liste_titre } /* TODO Once title line is moved under title search, make border bottom of all th black and force to whit when it's first tr */ tr:first-child th.liste_titre, tr:first-child th.liste_titre_sel { - border-bottom: 1px solid #FFF ! important; + border-bottom: 1px solid #FFF ! important; } tr.liste_titre th, th.liste_titre, tr.liste_titre td, td.liste_titre, form.liste_titre div, div.liste_titre { - font-family: <?php print $fontlist ?>; - font-weight: <?php echo $useboldtitle ? 'bold' : 'normal'; ?>; - vertical-align: middle; - height: 24px; + font-family: <?php print $fontlist ?>; + font-weight: <?php echo $useboldtitle ? 'bold' : 'normal'; ?>; + vertical-align: middle; + height: 24px; } tr.liste_titre th a, th.liste_titre a, tr.liste_titre td a, td.liste_titre a, form.liste_titre div a, div.liste_titre a { text-shadow: none !important; @@ -3620,8 +3722,8 @@ tr.liste_titre th a, th.liste_titre a, tr.liste_titre td a, td.liste_titre a, fo } tr.liste_titre_topborder td { border-top-width: <?php echo $borderwidth; ?>px; - border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); - border-top-style: solid; + border-top-color: rgb(<?php echo $colortopbordertitle1 ?>); + border-top-style: solid; } .liste_titre td a { text-shadow: none !important; @@ -3634,7 +3736,7 @@ tr.liste_titre_topborder td { background: transparent; } tr.liste_titre:last-child th.liste_titre, tr.liste_titre:last-child th.liste_titre_sel, tr.liste_titre td.liste_titre, tr.liste_titre td.liste_titre_sel, form.liste_titre div.tagtd { /* For last line of table headers only */ - border-bottom: 1px solid rgb(<?php echo $colortopbordertitle1 ?>); + border-bottom: 1px solid rgb(<?php echo $colortopbordertitle1 ?>); } div.liste_titre { @@ -3642,23 +3744,23 @@ div.liste_titre { } tr.liste_titre_sel th, th.liste_titre_sel, tr.liste_titre_sel td, td.liste_titre_sel, form.liste_titre_sel div { - font-family: <?php print $fontlist ?>; - font-weight: normal; - border-bottom: 1px solid #FDFFFF; - text-decoration: underline; + font-family: <?php print $fontlist ?>; + font-weight: normal; + border-bottom: 1px solid #FDFFFF; + text-decoration: underline; } input.liste_titre { - background: transparent; - border: 0px; + background: transparent; + border: 0px; } .noborder tr.liste_total td, tr.liste_total td, form.liste_total div, .noborder tr.liste_total_wrap td, tr.liste_total_wrap td, form.liste_total_wrap div { - color: #332266; - /* padding: 4px; */ + color: #332266; + /* padding: 4px; */ } .noborder tr.liste_total td, tr.liste_total td, form.liste_total div { - white-space: nowrap; - line-height: 1.5em; + white-space: nowrap; + line-height: 1.5em; } } .noborder tr.liste_total_wrap td, tr.liste_total_wrap td, form.liste_total_wrap div { @@ -3706,7 +3808,7 @@ div.tabBar .noborder { box-shadow: 0px 0px 0px #f4f4f4 !important; } div .tdtop { - vertical-align: top !important; + vertical-align: top !important; padding-top: 5px !important; padding-bottom: 0px !important; } @@ -3715,7 +3817,7 @@ div .tdtop { border-bottom: 1px solid #AAA !important; } #tablelines tr td { - height: unset; + height: unset; } @@ -3763,50 +3865,50 @@ ul.noborder li:nth-child(even):not(.liste_titre) { */ .box { - overflow-x: auto; - min-height: 40px; - padding-right: 0px; - padding-left: 0px; - padding-bottom: 12px; + overflow-x: auto; + min-height: 40px; + padding-right: 0px; + padding-left: 0px; + padding-bottom: 12px; } .ficheaddleft div.boxstats, .ficheaddright div.boxstats { - border: none; + border: none; } .boxstatsborder { - /* border: 1px solid #CCC !important; */ + /* border: 1px solid #CCC !important; */ } .boxstats, .boxstats130 { - display: inline-block; - margin: 8px; - /* border: 1px solid #CCC; */ - text-align: center; - border-radius: 2px; - background: #eee; + display: inline-block; + margin: 8px; + /* border: 1px solid #CCC; */ + text-align: center; + border-radius: 2px; + background: #eee; } .boxstats, .boxstats130, .boxstatscontent { white-space: nowrap; overflow: hidden; - text-overflow: ellipsis; + text-overflow: ellipsis; } .boxstats { - padding: 3px; - width: 100px; - min-height: 40px; + padding: 3px; + width: 100px; + min-height: 40px; } .boxstats130 { - width: 135px; - height: 54px; - padding: 3px; + width: 135px; + height: 54px; + padding: 3px; } @media only screen and (max-width: 767px) { .tabBar .arearef .pagination.paginationref { - max-width: calc(50%); + max-width: calc(50%); } .clearbothonsmartphone { - clear: both; - display: block !important; + clear: both; + display: block !important; } div.tabs { @@ -3817,34 +3919,34 @@ ul.noborder li:nth-child(even):not(.liste_titre) { .boxstats, .boxstats130 { margin: 3px; - border: 1px solid #ddd; - box-shadow: none; - background: #eee; - } + border: 1px solid #ddd; + box-shadow: none; + background: #eee; + } .thumbstat { flex: 1 1 110px; } .thumbstat150 { flex: 1 1 110px; } - .dashboardlineindicator { - float: left; - padding-left: 5px; - } - .boxstats130 { - width: 148px; - } - .boxstats { - width: 100px; - } + .dashboardlineindicator { + float: left; + padding-left: 5px; + } + .boxstats130 { + width: 148px; + } + .boxstats { + width: 100px; + } } .boxstats:hover { box-shadow: 0px 0px 8px 0px rgba(0,0,0,0.20); } span.boxstatstext { - /* opacity: 0.7; */ /* a bug if browser make z-index infintie when opacity is set so we disable it */ - line-height: 18px; - color: #000; + /* opacity: 0.7; */ /* a bug if browser make z-index infintie when opacity is set so we disable it */ + line-height: 18px; + color: #000; } .boxstatsindicator.thumbstat150 { /* If we remove this, box position is ko on ipad */ display: inline-flex; @@ -3874,29 +3976,29 @@ span.dashboardlineko { .dashboardlinelatecoin { float: right; position: relative; - text-align: right; - top: -24px; - padding: 1px 6px 1px 6px; - background-color: #8c4446; - color: #FFFFFF ! important; - border-radius: .25em; + text-align: right; + top: -24px; + padding: 1px 6px 1px 6px; + background-color: #8c4446; + color: #FFFFFF ! important; + border-radius: .25em; } .boxtable { - margin-bottom: 8px !important; - border-bottom-width: 1px; + margin-bottom: 8px !important; + border-bottom-width: 1px; } .boxtable { - margin-bottom: 8px !important; - border-bottom-width: 1px; + margin-bottom: 8px !important; + border-bottom-width: 1px; } .boxtablenotop { - /* border-top-width: 0 !important; */ + /* border-top-width: 0 !important; */ } .boxtablenobottom { - /* border-bottom-width: 0 !important; */ + /* border-bottom-width: 0 !important; */ } .boxtable .fichehalfright, .boxtable .fichehalfleft { - min-width: 275px; + min-width: 275px; } .tdboxstats { text-align: center; @@ -3906,25 +4008,25 @@ span.dashboardlineko { padding-right: 1px !important; } a.valignmiddle.dashboardlineindicator { - line-height: 30px; + line-height: 30px; } tr.box_titre { - height: 26px !important; + height: 26px !important; - /* TO MATCH BOOTSTRAP */ + /* TO MATCH BOOTSTRAP */ /*background: #ddd; color: #000 !important; */ /* TO MATCH ELDY */ background: rgb(<?php echo $colorbacktitle1; ?>); - background-repeat: repeat-x; - color: rgb(<?php echo $colortexttitle; ?>); - font-family: <?php print $fontlist ?>, sans-serif; - font-weight: <?php echo $useboldtitle ? 'bold' : 'normal'; ?>; - border-bottom: 1px solid #FDFFFF; - white-space: nowrap; + background-repeat: repeat-x; + color: rgb(<?php echo $colortexttitle; ?>); + font-family: <?php print $fontlist ?>, sans-serif; + font-weight: <?php echo $useboldtitle ? 'bold' : 'normal'; ?>; + border-bottom: 1px solid #FDFFFF; + white-space: nowrap; } tr.box_titre td.boxclose { @@ -3949,8 +4051,8 @@ img.boxhandle, img.boxclose { } .prod_entry_mode_free, .prod_entry_mode_predef { - height: 26px !important; - vertical-align: middle; + height: 26px !important; + vertical-align: middle; } .modulebuilderbox { @@ -3975,23 +4077,23 @@ div.ok { /* Info admin */ div.info { border-<?php print $left; ?>: solid 5px #87cfd2; - padding-top: 8px; - padding-left: 10px; - padding-right: 4px; - padding-bottom: 8px; - margin: 0.5em 0em 0.5em 0em; - background: #eff8fc; -} - -/* Warning message */ -div.warning { - border-<?php print $left; ?>: solid 5px #f2cf87; padding-top: 8px; padding-left: 10px; padding-right: 4px; padding-bottom: 8px; margin: 0.5em 0em 0.5em 0em; - background: #fcf8e3; + background: #eff8fc; +} + +/* Warning message */ +div.warning { + border-<?php print $left; ?>: solid 5px #f2cf87; + padding-top: 8px; + padding-left: 10px; + padding-right: 4px; + padding-bottom: 8px; + margin: 0.5em 0em 0.5em 0em; + background: #fcf8e3; } div.warning a, div.info a, div.error a { color: rgb(<?php echo $colortextlink; ?>); @@ -3999,7 +4101,7 @@ div.warning a, div.info a, div.error a { /* Error message */ div.error { - border-<?php print $left; ?>: solid 5px #f28787; + border-<?php print $left; ?>: solid 5px #f28787; padding-top: 8px; padding-left: 10px; padding-right: 4px; @@ -4030,13 +4132,13 @@ a.impayee:hover { font-weight: bold; color: #550000; } */ .framecontent { - width: 100%; - height: 100%; + width: 100%; + height: 100%; } .framecontent iframe { - width: 100%; - height: 100%; + width: 100%; + height: 100%; } @@ -4046,11 +4148,11 @@ a.impayee:hover { font-weight: bold; color: #550000; } */ .opened-dash-board-wrap { - margin-bottom: 25px; + margin-bottom: 25px; } div.boximport { - min-height: unset; + min-height: unset; } .product_line_stock_ok { color: #002200; } @@ -4070,11 +4172,11 @@ div.dolgraph div.legend table tbody tr { height: auto; } td.legendColorBox { padding: 2px 2px 2px 0 !important; } td.legendLabel { padding: 2px 2px 2px 0 !important; } td.legendLabel { - text-align: <?php echo $left; ?>; + text-align: <?php echo $left; ?>; } label.radioprivate { - white-space: nowrap; + white-space: nowrap; } .photo { @@ -4085,7 +4187,7 @@ label.radioprivate { margin-top: 2px; } div.divphotoref > a > .photowithmargin { /* Margin right for photo not inside a div.photoref frame only */ - margin-right: 15px; + margin-right: 15px; } .photowithborder { border: 1px solid #f0f0f0; @@ -4108,20 +4210,20 @@ div.divphotoref > a > .photowithmargin { /* Margin right for photo not inside a { content:url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/nographyet.svg', 1) ?>); display: inline-block; - opacity: 0.1; - background-repeat: no-repeat; + opacity: 0.1; + background-repeat: no-repeat; } .nographyettext { - opacity: 0.5; + opacity: 0.5; } div.titre { font-size: 14px; text-decoration: none; padding-top: 5px; - padding-bottom: 5px; - text-transform: uppercase; + padding-bottom: 5px; + text-transform: uppercase; /* text-shadow: 1px 1px 2px #FFFFFF; */ } div.titre { @@ -4146,14 +4248,14 @@ div.backgreypublicpayment { background-color: #f0f0f0; padding: 20px; border-bot .poweredbypublicpayment { float: right; top: 8px; - right: 8px; - position: absolute; - font-size: 0.8em; - color: #222; - opacity: 0.3; + right: 8px; + position: absolute; + font-size: 0.8em; + color: #222; + opacity: 0.3; } span.buttonpaymentsmall { - text-shadow: none; + text-shadow: none; } #dolpaymenttable { min-width: 320px; font-size: 16px; } /* Width must have min to make stripe input area visible. Lower than 320 makes input area crazy for credit card that need zip code */ #tablepublicpayment { border: 1px solid #CCCCCC !important; width: 100%; padding: 20px; } @@ -4166,13 +4268,13 @@ span.buttonpaymentsmall { #tablesubscribe { width: 100%; } div#card-element { - border: 1px solid #ccc; + border: 1px solid #ccc; } div#card-errors { color: #fa755a; - text-align: center; - padding-top: 3px; - max-width: 320px; + text-align: center; + padding-top: 3px; + max-width: 320px; } @@ -4224,7 +4326,7 @@ div#card-errors { .ui-dialog-titlebar { } .ui-dialog-content { - font-size: <?php print $fontsize; ?>px !important; + font-size: <?php print $fontsize; ?>px !important; } @@ -4234,8 +4336,8 @@ div#card-errors { /* .ui-dialog-content.ui-widget-content > object { - max-height: none; - width: auto; margin-left: auto; margin-right: auto; display: block; + max-height: none; + width: auto; margin-left: auto; margin-right: auto; display: block; } */ @@ -4245,16 +4347,16 @@ div#card-errors { /* ============================================================================== */ table.valid { - /* border-top: solid 1px #E6E6E6; */ - border-<?php print $left; ?>: solid 5px #f2cf87; - /* border-<?php print $right; ?>: solid 1px #444444; - border-bottom: solid 1px #555555; */ + /* border-top: solid 1px #E6E6E6; */ + border-<?php print $left; ?>: solid 5px #f2cf87; + /* border-<?php print $right; ?>: solid 1px #444444; + border-bottom: solid 1px #555555; */ padding-top: 8px; padding-left: 10px; padding-right: 4px; padding-bottom: 4px; margin: 0px 0px; - background: #fcf8e3; + background: #fcf8e3; } .validtitre { @@ -4268,7 +4370,7 @@ table.valid { /* For tooltip using dialog */ .ui-dialog.highlight.ui-widget.ui-widget-content.ui-front { - z-index: 3000; + z-index: 3000; } div.ui-tooltip { @@ -4300,7 +4402,7 @@ div.ui-tooltip.mytooltip { .ui-datepicker-calendar .ui-widget-header .ui-state-default, .ui-datepicker-calendar .ui-button, html .ui-datepicker-calendar .ui-button.ui-state-disabled:hover, html .ui-button.ui-state-disabled:active { - border: unset; + border: unset; } img.datecallink { padding-left: 2px !important; padding-right: 2px !important; } @@ -4320,13 +4422,13 @@ img.datecallink { padding-left: 2px !important; padding-right: 2px !important; } margin-bottom: 5px; } table.dp { - width: 180px; - background-color: #FFFFFF; - /*border-top: solid 2px #f4f4f4; - border-<?php print $left; ?>: solid 2px #f4f4f4; - border-<?php print $right; ?>: solid 1px #222222; - border-bottom: solid 1px #222222; */ - padding: 0px; + width: 180px; + background-color: #FFFFFF; + /*border-top: solid 2px #f4f4f4; + border-<?php print $left; ?>: solid 2px #f4f4f4; + border-<?php print $right; ?>: solid 1px #222222; + border-bottom: solid 1px #222222; */ + padding: 0px; border-spacing: 0px; border-collapse: collapse; } @@ -4372,14 +4474,14 @@ table.dp { /* Bouton X fermer */ .dpInvisibleButtons { - border-style:none; - background-color:transparent; - padding:0px; - font-size: 0.85em; - border-width:0px; - color: #eee; - vertical-align:middle; - cursor: pointer; + border-style:none; + background-color:transparent; + padding:0px; + font-size: 0.85em; + border-width:0px; + color: #eee; + vertical-align:middle; + cursor: pointer; } .datenowlink { @@ -4399,15 +4501,15 @@ table.dp { /* ============================================================================== */ div.visible { - display: block; + display: block; } -div.hidden, td.hidden, img.hidden, span.hidden { - display: none; +div.hidden, td.hidden, img.hidden, span.hidden, div.showifmore { + display: none; } tr.visible { - display: block; + display: block; } @@ -4416,10 +4518,10 @@ tr.visible { /* ============================================================================== */ .exampleapachesetup { - overflow-y: auto; - max-height: 100px; - font-size: 0.8em; - border: 1px solid #aaa; + overflow-y: auto; + max-height: 100px; + font-size: 0.8em; + border: 1px solid #aaa; } span[phptag] { @@ -4427,16 +4529,16 @@ span[phptag] { } .nobordertransp { - border: 0px; - background-color: transparent; - background-image: none; - color: #000 !important; - text-shadow: none; + border: 0px; + background-color: transparent; + background-image: none; + color: #000 !important; + text-shadow: none; } .bordertransp { - background-color: transparent; - background-image: none; - border: 1px solid #aaa; + background-color: transparent; + background-image: none; + border: 1px solid #aaa; font-weight: normal; color: #444 !important; } @@ -4444,7 +4546,7 @@ span[phptag] { border-bottom: 1px solid #ccc; background: #eee; display: inline-block; - padding: 4px 0 4px 0; + padding: 4px 0 4px 0; } .websitebar .buttonDelete, .websitebar .button { text-shadow: none; @@ -4453,11 +4555,11 @@ span[phptag] { { padding: 2px 4px 2px 4px !important; margin: 2px 4px 2px 4px !important; - line-height: normal; + line-height: normal; } .websitebar input.button.bordertransp, .websitebar input.buttonDelete.bordertransp { - color: #444 !important; - text-shadow: none; + color: #444 !important; + text-shadow: none; } .websiteselection { /* display: inline-block; */ @@ -4473,9 +4575,9 @@ span[phptag] { padding-bottom: 3px; */ } .websiteinputurl { - display: inline-block; - vertical-align: top; - line-height: 28px; + display: inline-block; + vertical-align: top; + line-height: 28px; } .websiteiframenoborder { border: 0px; @@ -4494,9 +4596,9 @@ span.websitebuttonsitepreviewdisabled img, a.websitebuttonsitepreviewdisabled im border: 0px; } .websitehelp { - vertical-align: middle; - float: right; - padding-top: 8px; + vertical-align: middle; + float: right; + padding-top: 8px; } .websiteselectionsection { border-left: 1px solid #bbb; @@ -4506,7 +4608,11 @@ span.websitebuttonsitepreviewdisabled img, a.websitebuttonsitepreviewdisabled im margin-right: 5px; } .websitebar input#previewpageurl { - line-height: 1em; + line-height: 1em; +} + +#divbodywebsite section p { + margin: unset; } @@ -4515,7 +4621,7 @@ span.websitebuttonsitepreviewdisabled img, a.websitebuttonsitepreviewdisabled im /* ============================================================================== */ .dayevent .tagtr:first-of-type { - height: 24px; + height: 24px; } .agendacell { height: 60px; } table.cal_month { border-spacing: 0px; } @@ -4573,28 +4679,28 @@ td.cal_other_month { .ui-autocomplete-loading { background: white url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/working.gif', 1) ?>) right center no-repeat; } .ui-autocomplete { - position:absolute; - width:auto; - font-size: 1.0em; - background-color:white; - border:1px solid #888; - margin:0px; + position:absolute; + width:auto; + font-size: 1.0em; + background-color:white; + border:1px solid #888; + margin:0px; /* padding:0px; This make combo crazy */ - } + } .ui-autocomplete ul { - list-style-type:none; - margin:0px; - padding:0px; - } + list-style-type:none; + margin:0px; + padding:0px; + } .ui-autocomplete ul li.selected { background-color: #D3E5EC;} .ui-autocomplete ul li { - list-style-type:none; - display:block; - margin:0; - padding:2px; - height:18px; - cursor:pointer; - } + list-style-type:none; + display:block; + margin:0; + padding:2px; + height:18px; + cursor:pointer; + } /* ============================================================================== */ @@ -4602,8 +4708,8 @@ td.cal_other_month { /* ============================================================================== */ td.gtaskname { - overflow: hidden; - text-overflow: ellipsis; + overflow: hidden; + text-overflow: ellipsis; } @@ -4779,29 +4885,29 @@ A.none, A.none:active, A.none:visited, A.none:hover { /* Style to overwrites JQuery styles */ .ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { - border: 1px solid #888; - background: rgb(<?php echo $colorbacktitle1; ?>); - color: unset; + border: 1px solid #888; + background: rgb(<?php echo $colorbacktitle1; ?>); + color: unset; } .ui-menu .ui-menu-item a { - text-decoration:none; - display:block; - padding:.2em .4em; - line-height:1.5; - font-weight: normal; - font-family:<?php echo $fontlist; ?>; - font-size:1em; + text-decoration:none; + display:block; + padding:.2em .4em; + line-height:1.5; + font-weight: normal; + font-family:<?php echo $fontlist; ?>; + font-size:1em; } .ui-widget { - font-family:<?php echo $fontlist; ?>; + font-family:<?php echo $fontlist; ?>; } .ui-button { margin-left: -2px; <?php print (preg_match('/chrome/', $conf->browser->name) ? 'padding-top: 1px;' : ''); ?> } .ui-button-icon-only .ui-button-text { height: 8px; } .ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: 2px 0px 6px 0px; } .ui-button-text { - line-height: 1em !important; + line-height: 1em !important; } .ui-autocomplete-input { margin: 0; padding: 4px; } @@ -4811,28 +4917,28 @@ A.none, A.none:active, A.none:visited, A.none:hover { /* ============================================================================== */ body.cke_show_borders { - margin: 5px !important; + margin: 5px !important; } .cke_dialog { - border: 1px #bbb solid ! important; + border: 1px #bbb solid ! important; } /*.cke_editor table, .cke_editor tr, .cke_editor td { - border: 0px solid #FF0000 !important; + border: 0px solid #FF0000 !important; } span.cke_skin_kama { padding: 0 !important; }*/ .cke_wrapper { padding: 4px !important; } a.cke_dialog_ui_button { - font-family: <?php print $fontlist ?> !important; + font-family: <?php print $fontlist ?> !important; background-image: url(<?php echo $img_button ?>) !important; background-position: bottom !important; - border: 1px solid #C0C0C0 !important; + border: 1px solid #C0C0C0 !important; -webkit-border-radius:0px 2px 0px 2px !important; border-radius:0px 2px 0px 2px !important; - -webkit-box-shadow: 3px 3px 4px #f4f4f4 !important; - box-shadow: 3px 3px 4px #f4f4f4 !important; + -webkit-box-shadow: 3px 3px 4px #f4f4f4 !important; + box-shadow: 3px 3px 4px #f4f4f4 !important; } .cke_dialog_ui_hbox_last { @@ -4846,8 +4952,8 @@ a.cke_dialog_ui_button } */ a.cke_dialog_ui_button_ok span { - text-shadow: none !important; - color: #333 !important; + text-shadow: none !important; + color: #333 !important; } @@ -4855,28 +4961,28 @@ a.cke_dialog_ui_button_ok span { /* ACE editor */ /* ============================================================================== */ .ace_editor { - border: 1px solid #ddd; + border: 1px solid #ddd; margin: 0; } .aceeditorstatusbar { - margin: 0; - padding: 0; - padding-<?php echo $left; ?>: 10px; - left: 0; - right: 0; - bottom: 0; - color: #666; - height: 28px; - line-height: 2.2em; + margin: 0; + padding: 0; + padding-<?php echo $left; ?>: 10px; + left: 0; + right: 0; + bottom: 0; + color: #666; + height: 28px; + line-height: 2.2em; } .ace_status-indicator { - color: gray; - position: relative; - right: 0; - border-left: 1px solid; + color: gray; + position: relative; + right: 0; + border-left: 1px solid; } pre#editfilecontentaceeditorid { - margin-top: 5px; + margin-top: 5px; } @@ -4885,7 +4991,7 @@ pre#editfilecontentaceeditorid { /* ============================================================================== */ .template-upload { - height: 72px !important; + height: 72px !important; } @@ -4906,32 +5012,32 @@ pre#editfilecontentaceeditorid { /* ============================================================================== */ #types .btn { - cursor: pointer; + cursor: pointer; } #types .btn-primary { - font-weight: bold; + font-weight: bold; } #types form { - padding: 20px; + padding: 20px; } #types label { - display:inline-block; - width:100px; - margin-right: 20px; - padding: 4px; - text-align: right; - vertical-align: top; + display:inline-block; + width:100px; + margin-right: 20px; + padding: 4px; + text-align: right; + vertical-align: top; } #types input.text, #types textarea { - width: 400px; + width: 400px; } #types textarea { - height: 100px; + height: 100px; } @@ -4943,55 +5049,55 @@ pre#editfilecontentaceeditorid { box-sizing:border-box; } #comment .comment { - border-radius:7px; - margin-bottom:10px; - overflow:hidden; + border-radius:7px; + margin-bottom:10px; + overflow:hidden; } #comment .comment-table { - display:table; - height:100%; + display:table; + height:100%; } #comment .comment-cell { - display:table-cell; + display:table-cell; } #comment .comment-info { - font-size:0.8em; - border-right:1px solid #dedede; - margin-right:10px; - width:160px; - text-align:center; - background:rgba(255,255,255,0.5); - vertical-align:middle; - padding:10px 2px; + font-size:0.8em; + border-right:1px solid #dedede; + margin-right:10px; + width:160px; + text-align:center; + background:rgba(255,255,255,0.5); + vertical-align:middle; + padding:10px 2px; } #comment .comment-info a { - color:inherit; + color:inherit; } #comment .comment-right { - vertical-align:top; + vertical-align:top; } #comment .comment-description { - padding:10px; - vertical-align:top; + padding:10px; + vertical-align:top; } #comment .comment-delete { - width: 100px; - text-align:center; - vertical-align:middle; + width: 100px; + text-align:center; + vertical-align:middle; } #comment .comment-delete:hover { - background:rgba(250,20,20,0.8); + background:rgba(250,20,20,0.8); } #comment .comment-edit { - width: 100px; - text-align:center; - vertical-align:middle; + width: 100px; + text-align:center; + vertical-align:middle; } #comment .comment-edit:hover { - background:rgba(0,184,148,0.8); + background:rgba(0,184,148,0.8); } #comment textarea { - width: 100%; + width: 100%; } @@ -5004,7 +5110,7 @@ div.scroll2 { } div#GanttChartDIVglisthead, div#GanttChartDIVgcharthead { - line-height: 2; + line-height: 2; } .gtaskname div, .gtaskname, .gstartdate div, .gstartdate, .genddate div, .genddate { @@ -5017,45 +5123,45 @@ div.gantt, .gtaskheading, .gmajorheading, .gminorheading, .gminorheadingwkend { color: #000 !important; } div.gTaskInfo { - background: #f0f0f0 !important; + background: #f0f0f0 !important; } .gtaskblue { background: rgb(108,152,185) !important; } .gtaskgreen { - background: rgb(160,173,58) !important; + background: rgb(160,173,58) !important; } td.gtaskname { - overflow: hidden; - text-overflow: ellipsis; + overflow: hidden; + text-overflow: ellipsis; } td.gminorheadingwkend { - color: #888 !important; + color: #888 !important; } td.gminorheading { - color: #666 !important; + color: #666 !important; } .glistlbl, .glistgrid { width: 582px !important; } .gtaskname div, .gtaskname { - min-width: 250px !important; - max-width: 250px !important; - width: 250px !important; + min-width: 250px !important; + max-width: 250px !important; + width: 250px !important; } .gpccomplete div, .gpccomplete { - min-width: 40px !important; - max-width: 40px !important; - width: 40px !important; + min-width: 40px !important; + max-width: 40px !important; + width: 40px !important; } td.gtaskheading.gstartdate, td.gtaskheading.genddate { - white-space: break-spaces; + white-space: break-spaces; } .gtasktableh tr:nth-child(2) td:nth-child(2), .gtasktableh tr:nth-child(2) td:nth-child(3), .gtasktableh tr:nth-child(2) td:nth-child(4), .gtasktableh tr:nth-child(2) td:nth-child(5), .gtasktableh tr:nth-child(2) td:nth-child(6), .gtasktableh tr:nth-child(2) td:nth-child(7) { - color: transparent !important; - border-left: none; - border-right: none; - border-top: none; + color: transparent !important; + border-left: none; + border-right: none; + border-top: none; } @@ -5080,25 +5186,25 @@ td.gtaskheading.gstartdate, td.gtaskheading.genddate { } div.filedirelem { - position: relative; - display: block; - text-decoration: none; + position: relative; + display: block; + text-decoration: none; } ul.filedirelem { - padding: 2px; - margin: 0 5px 5px 5px; + padding: 2px; + margin: 0 5px 5px 5px; } ul.filedirelem li { - list-style: none; - padding: 2px; - margin: 0 10px 20px 10px; - width: 160px; - height: 120px; - text-align: center; - display: block; - float: <?php print $left; ?>; - border: solid 1px #f4f4f4; + list-style: none; + padding: 2px; + margin: 0 10px 20px 10px; + width: 160px; + height: 120px; + text-align: center; + display: block; + float: <?php print $left; ?>; + border: solid 1px #f4f4f4; } ul.ecmjqft { @@ -5128,7 +5234,7 @@ ul.ecmjqft a:active { font-weight: bold !important; } ul.ecmjqft a:hover { - text-decoration: underline; + text-decoration: underline; } div.ecmjqft { @@ -5140,13 +5246,13 @@ div.ecmjqft { clear: both; } div#ecm-layout-west { - width: 380px; - vertical-align: top; + width: 380px; + vertical-align: top; } div#ecm-layout-center { - width: calc(100% - 390px); - vertical-align: top; - float: right; + width: calc(100% - 390px); + vertical-align: top; + float: right; } .ecmjqft LI.directory { font-weight:normal; background: url(<?php echo dol_buildpath($path.'/theme/common/treemenu/folder2.png', 1); ?>) left top no-repeat; } @@ -5176,14 +5282,14 @@ div#ecm-layout-center { font-weight: normal; } .jnotify-container .jnotify-notification-warning .jnotify-close, .jnotify-container .jnotify-notification-warning .jnotify-message { - color: #a28918 !important; + color: #a28918 !important; } /* use or not ? */ div.jnotify-background { opacity : 0.95 !important; - -webkit-box-shadow: 2px 2px 4px #888 !important; - box-shadow: 2px 2px 4px #888 !important; + -webkit-box-shadow: 2px 2px 4px #888 !important; + box-shadow: 2px 2px 4px #888 !important; } /* ============================================================================== */ @@ -5246,7 +5352,7 @@ table.dataTable tr.odd td.sorting_1, table.dataTable tr.even td.sorting_1 { .paginate_button { font-weight: normal !important; - text-decoration: none !important; + text-decoration: none !important; } .paging_full_numbers { height: inherit !important; @@ -5259,7 +5365,7 @@ table.dataTable tr.odd td.sorting_1, table.dataTable tr.even td.sorting_1 { border-radius: inherit !important; } .paging_full_numbers a.paginate_button_disabled:hover, .paging_full_numbers a.disabled:hover { - background-color: #FFF !important; + background-color: #FFF !important; } .paginate_button, .paginate_active { border: 1px solid #ddd !important; @@ -5295,7 +5401,7 @@ div.dataTables_length select { /* ============================================================================== */ span#select2-taskid-container[title^='--'] { - opacity: 0.3; + opacity: 0.3; } input.select2-input { @@ -5312,16 +5418,16 @@ input.select2-input { .blockvmenusearch .select2-container--default .select2-selection--single, .blockvmenubookmarks .select2-container--default .select2-selection--single { - background-color: unset; + background-color: unset; } .select2-container--default .select2-selection--single .select2-selection__rendered { - color: unset; + color: unset; } .select2-container .select2-choice { border-bottom: 1px solid #ccc; } .select2-container .select2-choice > .select2-chosen { - margin-right: 23px; + margin-right: 23px; } .select2-container .select2-choice .select2-arrow { border-radius: 0; @@ -5353,7 +5459,7 @@ input.select2-input { box-shadow: none !important; } .select2-container--open .select2-dropdown--above { - border-bottom: solid 1px rgba(0,0,0,.2); + border-bottom: solid 1px rgba(0,0,0,.2); } .select2-drop.select2-drop-above.select2-drop-active { border-top: 1px solid #ccc; @@ -5482,34 +5588,34 @@ a span.select2-chosen border-left: 1px solid #ddd; } .select2-container--default .select2-results>.select2-results__options{ - max-height: 400px; + max-height: 400px; } /* Special case for the select2 add widget */ #addbox .select2-container .select2-choice > .select2-chosen, #actionbookmark .select2-container .select2-choice > .select2-chosen { - text-align: <?php echo $left; ?>; - opacity: 0.3; + text-align: <?php echo $left; ?>; + opacity: 0.3; } .select2-container--default .select2-selection--single .select2-selection__placeholder { color: unset; opacity: 0.5; } span#select2-boxbookmark-container, span#select2-boxcombo-container { - text-align: <?php echo $left; ?>; - opacity: 0.5; + text-align: <?php echo $left; ?>; + opacity: 0.5; } .select2-container .select2-selection--single .select2-selection__rendered { padding-left: 6px; } /* Style used before the select2 js is executed on boxcombo */ #boxbookmark.boxcombo, #boxcombo.boxcombo { - text-align: left; - opacity: 0.3; - border-bottom: solid 1px rgba(0,0,0,.4) !important; - height: 26px; - line-height: 24px; - padding: 0 0 5px 5px; - vertical-align: top; + text-align: left; + opacity: 0.3; + border-bottom: solid 1px rgba(0,0,0,.4) !important; + height: 26px; + line-height: 24px; + padding: 0 0 5px 5px; + vertical-align: top; } /* To emulate select 2 style */ @@ -5563,7 +5669,7 @@ span#select2-boxbookmark-container, span#select2-boxcombo-container { border-radius: 5px !important; box-shadow: none; -webkit-box-shadow: none !important; - box-shadow: none !important; + box-shadow: none !important; } span.noborderoncategories a, li.noborderoncategories a { line-height: normal; @@ -5651,9 +5757,9 @@ span.noborderoncategories { } .multi-select-menuitem { - clear: both; - float: left; - padding-left: 5px + clear: both; + float: left; + padding-left: 5px } @@ -5662,51 +5768,51 @@ span.noborderoncategories { /* ============================================================================== */ ul.ulselectedfields { - z-index: 90; /* To have the select box appears on first plan even when near buttons are decorated by jmobile */ + z-index: 90; /* To have the select box appears on first plan even when near buttons are decorated by jmobile */ } dl.dropdown { - margin:0px; - padding:0px; + margin:0px; + padding:0px; margin-left: 2px; - margin-right: 2px; - vertical-align: middle; - display: inline-block; + margin-right: 2px; + vertical-align: middle; + display: inline-block; } .dropdown dd, .dropdown dt { - margin:0px; - padding:0px; + margin:0px; + padding:0px; } .dropdown ul { - margin: -1px 0 0 0; - text-align: <?php echo $left; ?>; + margin: -1px 0 0 0; + text-align: <?php echo $left; ?>; } .dropdown dd { - position:relative; + position:relative; } .dropdown dt a { - display:block; - overflow: hidden; - border:0; + display:block; + overflow: hidden; + border:0; } .dropdown dt a span, .multiSel span { - cursor:pointer; - display:inline-block; - padding: 0 3px 2px 0; + cursor:pointer; + display:inline-block; + padding: 0 3px 2px 0; } .dropdown span.value { - display:none; + display:none; } .dropdown dd ul { - background-color: #FFF; - box-shadow: 1px 1px 10px #aaa; - display:none; - <?php echo $right; ?>:0px; /* pop is align on right */ - padding: 0 0 0 0; - position:absolute; - top:2px; - list-style:none; - max-height: 264px; - overflow: auto; + background-color: #FFF; + box-shadow: 1px 1px 10px #aaa; + display:none; + <?php echo $right; ?>:0px; /* pop is align on right */ + padding: 0 0 0 0; + position:absolute; + top:2px; + list-style:none; + max-height: 264px; + overflow: auto; } .dropdown dd ul li { white-space: nowrap; @@ -5719,23 +5825,23 @@ dl.dropdown { background: #eee; } .dropdown dd ul li input[type="checkbox"] { - margin-<?php echo $right; ?>: 3px; + margin-<?php echo $right; ?>: 3px; } .dropdown dd ul li a, .dropdown dd ul li span { - padding: 3px; - display: block; + padding: 3px; + display: block; } .dropdown dd ul li span { color: #888; } .dropdown dd ul li a:hover { - background-color: #eee; + background-color: #eee; } dd.dropdowndd ul li { - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; } @@ -5757,11 +5863,11 @@ dd.dropdowndd ul li { /* ============================================================================== */ .searchpage .tagtr .tagtd { - padding-bottom: 3px; + padding-bottom: 3px; } .searchpage .tagtr .tagtd .button { background: unset; - border: unset; + border: unset; } li.ui-li-divider .ui-link { @@ -5797,16 +5903,16 @@ a.ui-link, a.ui-link:hover, .ui-btn:hover, span.ui-btn-text:hover, span.ui-btn-i padding-left: 30px; } .ui-select .ui-btn-icon-right .ui-icon { - right: 8px; + right: 8px; } .ui-btn-icon-left > .ui-btn-inner > .ui-icon, .ui-btn-icon-right > .ui-btn-inner > .ui-icon { - margin-top: -10px; + margin-top: -10px; } select { - /* display: inline-block; */ /* We can't set this. This disable ability to make */ - overflow:hidden; - white-space: nowrap; /* Enabling this make behaviour strange when selecting the empty value if this empty value is '' instead of '&nbsp;' */ - text-overflow: ellipsis; + /* display: inline-block; */ /* We can't set this. This disable ability to make */ + overflow:hidden; + white-space: nowrap; /* Enabling this make behaviour strange when selecting the empty value if this empty value is '' instead of '&nbsp;' */ + text-overflow: ellipsis; } .fiche .ui-controlgroup { margin: 0px; @@ -5889,39 +5995,39 @@ ul.ulmenu { /* Style for first level menu with jmobile */ .ui-li .ui-btn-inner a.ui-link-inherit, .ui-li-static.ui-li { - padding: 1em 15px; - display: block; + padding: 1em 15px; + display: block; } .ui-btn-up-c { font-weight: normal; } .ui-focus, .ui-btn:focus { - -webkit-box-shadow: none; - box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; } .ui-bar-b { - /*border: 1px solid #888;*/ - border: none; - background: none; - text-shadow: none; - color: rgb(<?php print $colortexttitlenotab; ?>) !important; + /*border: 1px solid #888;*/ + border: none; + background: none; + text-shadow: none; + color: rgb(<?php print $colortexttitlenotab; ?>) !important; } .ui-bar-b, .lilevel0 { - background-repeat: repeat-x; - border: none; - background: none; - text-shadow: none; - color: rgb(<?php print $colortexttitlenotab; ?>) !important; + background-repeat: repeat-x; + border: none; + background: none; + text-shadow: none; + color: rgb(<?php print $colortexttitlenotab; ?>) !important; } .alilevel0 { font-weight: normal !important; } .ui-li.ui-last-child, .ui-li.ui-field-contain.ui-last-child { - border-bottom-width: 0px !important; + border-bottom-width: 0px !important; } .alilevel0 { - color: rgb(<?php echo $colortexttitle; ?>) !important; + color: rgb(<?php echo $colortexttitle; ?>) !important; } .ulmenu { box-shadow: none !important; @@ -5964,11 +6070,11 @@ border-top-right-radius: 6px; }*/ .alilevel1 { - color: rgb(<?php print $colortexttitlenotab; ?>) !important; + color: rgb(<?php print $colortexttitlenotab; ?>) !important; } .lilevel1 { - border-top: 2px solid #444; - background: #fff ! important; + border-top: 2px solid #444; + background: #fff ! important; } .lilevel1 div div a { font-weight: bold !important; @@ -5976,22 +6082,22 @@ border-top-right-radius: 6px; .lilevel2 { padding-left: 22px; - background: #fff ! important; + background: #fff ! important; } .lilevel3 { padding-left: 44px; - background: #fff ! important; + background: #fff ! important; } .lilevel4 { padding-left: 66px; - background: #fff ! important; + background: #fff ! important; } .lilevel5 { padding-left: 88px; - background: #fff ! important; + background: #fff ! important; } @@ -6028,14 +6134,14 @@ border-top-right-radius: 6px; color: #6d3f6d; } .menu li.menu_choix1 { - padding-top: 6px; - padding-right: 10px; - padding-bottom: 2px; + padding-top: 6px; + padding-right: 10px; + padding-bottom: 2px; } .menu li.menu_choix2 { - padding-top: 6px; - padding-right: 10px; - padding-bottom: 2px; + padding-top: 6px; + padding-right: 10px; + padding-bottom: 2px; } @media only screen and (max-width: 767px) { @@ -6044,13 +6150,13 @@ border-top-right-radius: 6px; background-position-y: 6px; padding-left: 40px; } - .menu li.menu_choix1, .menu li.menu_choix2 { - padding-left: 4px; - padding-right: 0; - } - .liste_articles { - margin-right: 0 !important; - } + .menu li.menu_choix1, .menu li.menu_choix2 { + padding-left: 4px; + padding-right: 0; + } + .liste_articles { + margin-right: 0 !important; + } } @@ -6073,7 +6179,7 @@ border-top-right-radius: 6px; .ticketpublicarea { margin-left: 15%; - margin-right: 15%; + margin-right: 15%; } .publicnewticketform { /* margin-top: 25px !important; */ @@ -6111,11 +6217,11 @@ border-top-right-radius: 6px; } @media only screen and (min-width: 1170px) { #cd-timeline { - margin-bottom: 3em; + margin-bottom: 3em; } #cd-timeline::before { - left: 50%; - margin-left: -2px; + left: 50%; + margin-left: -2px; } } @@ -6136,13 +6242,13 @@ border-top-right-radius: 6px; } @media only screen and (min-width: 1170px) { .cd-timeline-block { - margin: 4em 0; + margin: 4em 0; } .cd-timeline-block:first-child { - margin-top: 0; + margin-top: 0; } .cd-timeline-block:last-child { - margin-bottom: 0; + margin-bottom: 0; } } @@ -6177,80 +6283,80 @@ border-top-right-radius: 6px; } @media only screen and (min-width: 1170px) { .cd-timeline-img { - width: 60px; - height: 60px; - left: 50%; - margin-left: -30px; - /* Force Hardware Acceleration in WebKit */ - -webkit-transform: translateZ(0); - -webkit-backface-visibility: hidden; + width: 60px; + height: 60px; + left: 50%; + margin-left: -30px; + /* Force Hardware Acceleration in WebKit */ + -webkit-transform: translateZ(0); + -webkit-backface-visibility: hidden; } .cssanimations .cd-timeline-img.is-hidden { - visibility: hidden; + visibility: hidden; } .cssanimations .cd-timeline-img.bounce-in { - visibility: visible; - -webkit-animation: cd-bounce-1 0.6s; - -moz-animation: cd-bounce-1 0.6s; - animation: cd-bounce-1 0.6s; + visibility: visible; + -webkit-animation: cd-bounce-1 0.6s; + -moz-animation: cd-bounce-1 0.6s; + animation: cd-bounce-1 0.6s; } } @-webkit-keyframes cd-bounce-1 { 0% { - opacity: 0; - -webkit-transform: scale(0.5); + opacity: 0; + -webkit-transform: scale(0.5); } 60% { - opacity: 1; - -webkit-transform: scale(1.2); + opacity: 1; + -webkit-transform: scale(1.2); } 100% { - -webkit-transform: scale(1); + -webkit-transform: scale(1); } } @-moz-keyframes cd-bounce-1 { 0% { - opacity: 0; - -moz-transform: scale(0.5); + opacity: 0; + -moz-transform: scale(0.5); } 60% { - opacity: 1; - -moz-transform: scale(1.2); + opacity: 1; + -moz-transform: scale(1.2); } 100% { - -moz-transform: scale(1); + -moz-transform: scale(1); } } @keyframes cd-bounce-1 { 0% { - opacity: 0; - -webkit-transform: scale(0.5); - -moz-transform: scale(0.5); - -ms-transform: scale(0.5); - -o-transform: scale(0.5); - transform: scale(0.5); + opacity: 0; + -webkit-transform: scale(0.5); + -moz-transform: scale(0.5); + -ms-transform: scale(0.5); + -o-transform: scale(0.5); + transform: scale(0.5); } 60% { - opacity: 1; - -webkit-transform: scale(1.2); - -moz-transform: scale(1.2); - -ms-transform: scale(1.2); - -o-transform: scale(1.2); - transform: scale(1.2); + opacity: 1; + -webkit-transform: scale(1.2); + -moz-transform: scale(1.2); + -ms-transform: scale(1.2); + -o-transform: scale(1.2); + transform: scale(1.2); } 100% { - -webkit-transform: scale(1); - -moz-transform: scale(1); - -ms-transform: scale(1); - -o-transform: scale(1); - transform: scale(1); + -webkit-transform: scale(1); + -moz-transform: scale(1); + -ms-transform: scale(1); + -o-transform: scale(1); + transform: scale(1); } } .cd-timeline-content { @@ -6302,58 +6408,58 @@ border-top-right-radius: 6px; } @media only screen and (min-width: 768px) { .cd-timeline-content h2 { - font-size: 20px; - font-size: 1.25rem; + font-size: 20px; + font-size: 1.25rem; } .cd-timeline-content { - font-size: 16px; - font-size: 1rem; + font-size: 16px; + font-size: 1rem; } .cd-timeline-content .cd-read-more, .cd-timeline-content .cd-date { - font-size: 14px; - font-size: 0.875rem; + font-size: 14px; + font-size: 0.875rem; } } @media only screen and (min-width: 1170px) { .cd-timeline-content { - margin-left: 0; - padding: 1.6em; - width: 43%; + margin-left: 0; + padding: 1.6em; + width: 43%; } .cd-timeline-content::before { - top: 24px; - left: 100%; - border-color: transparent; - border-left-color: white; + top: 24px; + left: 100%; + border-color: transparent; + border-left-color: white; } .cd-timeline-content .cd-read-more { - float: left; + float: left; } .cd-timeline-content .cd-date { - position: absolute; - width: 55%; - left: 115%; - top: 6px; - font-size: 16px; - font-size: 1rem; + position: absolute; + width: 55%; + left: 115%; + top: 6px; + font-size: 16px; + font-size: 1rem; } .cd-timeline-block:nth-child(even) .cd-timeline-content { - float: right; + float: right; } .cd-timeline-block:nth-child(even) .cd-timeline-content::before { - top: 24px; - left: auto; - right: 100%; - border-color: transparent; - border-right-color: white; + top: 24px; + left: auto; + right: 100%; + border-color: transparent; + border-right-color: white; } .cd-timeline-block:nth-child(even) .cd-timeline-content .cd-read-more { - float: right; + float: right; } .cd-timeline-block:nth-child(even) .cd-timeline-content .cd-date { - left: auto; - right: 115%; - text-align: right; + left: auto; + right: 115%; + text-align: right; } } @@ -6364,10 +6470,10 @@ border-top-right-radius: 6px; /* ============================================================================== */ span.phpdebugbar-tooltip.phpdebugbar-tooltip-extra-wide, span.phpdebugbar-tooltip.phpdebugbar-tooltip-wide { - width: 250px !important; + width: 250px !important; } .phpdebugbar-indicator span.phpdebugbar-tooltip { - opacity: .95 !important; + opacity: .95 !important; } a.phpdebugbar-tab.phpdebugbar-active { background-image: unset !important; @@ -6399,10 +6505,10 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before /* ============================================================================== */ .dol-xaxis-vertical .flot-x-axis .flot-tick-label.tickLabel { - text-orientation: sideways; - font-weight: 400; - writing-mode: vertical-rl; - white-space: nowrap; + text-orientation: sideways; + font-weight: 400; + writing-mode: vertical-rl; + white-space: nowrap; } @@ -6423,17 +6529,17 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before width: <?php print dol_size(350, 'width'); ?>px; } - div.tabBar { - padding-left: 8px; - padding-right: 8px; - -webkit-border-radius: 0; - border-radius: 0px; - border-right: none; - border-left: none; - } + div.tabBar { + padding-left: 8px; + padding-right: 8px; + -webkit-border-radius: 0; + border-radius: 0px; + border-right: none; + border-left: none; + } .box-flex-container { - margin: 0 0 0 -8px !important; + margin: 0 0 0 -8px !important; } } @@ -6459,26 +6565,26 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before @media only screen and (max-width: <?php echo round($nbtopmenuentries * $fontsize * 7, 0) + 300; ?>px) { div.tmenucenter { - max-width: <?php echo round($fontsize * 4); ?>px; /* size of viewport */ - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - color: #<?php echo $colortextbackhmenu; ?>; + max-width: <?php echo round($fontsize * 4); ?>px; /* size of viewport */ + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: #<?php echo $colortextbackhmenu; ?>; } .mainmenuaspan { - font-size: 0.9em; - /* font-weight: 300; */ - } - .topmenuimage { - background-size: 24px auto; - margin-top: 0px; + font-size: 0.9em; + /* font-weight: 300; */ + } + .topmenuimage { + background-size: 24px auto; + margin-top: 0px; + } + li.tmenu, li.tmenusel { + min-width: 34px; + } + div.mainmenu { + min-width: auto; } - li.tmenu, li.tmenusel { - min-width: 34px; - } - div.mainmenu { - min-width: auto; - } div.tmenuleft { display: none; } @@ -6491,17 +6597,17 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before } div.tmenucenter { - max-width: <?php echo round($fontsize * 2); ?>px; /* size of viewport */ - text-overflow: clip; + max-width: <?php echo round($fontsize * 2); ?>px; /* size of viewport */ + text-overflow: clip; } .mainmenuaspan { - font-size: 10px; - padding-left: 0; - padding-right: 0; - } - .topmenuimage { - background-size: 20px auto; - margin-top: 2px; + font-size: 10px; + padding-left: 0; + padding-right: 0; + } + .topmenuimage { + background-size: 20px auto; + margin-top: 2px; } } /* rule to reduce top menu - 3rd reduction */ @@ -6514,20 +6620,20 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before /* padding-<?php echo $right; ?>: 78px; */ <?php } ?> } - li.tmenu, li.tmenusel { - min-width: 30px; - } + li.tmenu, li.tmenusel { + min-width: 30px; + } div.tmenucenter { - text-overflow: clip; + text-overflow: clip; } - .topmenuimage { - background-size: 20px auto; - margin-top: 2px !important; + .topmenuimage { + background-size: 20px auto; + margin-top: 2px !important; } div.mainmenu { - min-width: 20px; - } + min-width: 20px; + } #tooltip { position: absolute; @@ -6540,22 +6646,22 @@ div.phpdebugbar-widgets-templates a.phpdebugbar-widgets-editor-link:before div.divphotoref { padding-right: 5px; } - img.photoref, div.photoref { - border: 1px solid rgba(0, 0, 0, 0.2); - -webkit-box-shadow: none; - box-shadow: none; - padding: 4px; - object-fit: contain; - } + img.photoref, div.photoref { + border: 1px solid rgba(0, 0, 0, 0.2); + -webkit-box-shadow: none; + box-shadow: none; + padding: 4px; + object-fit: contain; + } .titlefield { width: auto !important; /* We want to ignore the 30%, try to use more if you can */ } .tableforfield>tr>td:first-child, .tableforfield>tbody>tr>td:first-child, div.tableforfield div.tagtr>div.tagtd:first-of-type { - /* max-width: 100px; */ /* but no more than 100px */ + /* max-width: 100px; */ /* but no more than 100px */ } .tableforfield>tr>td:nth-child(2), .tableforfield>tbody>tr>td:nth-child(2), div.tableforfield div.tagtr>div.tagtd:nth-child(2) { - word-break: break-word; + word-break: break-word; } table.table-fiche-title .col-title div.titre{ @@ -6574,9 +6680,13 @@ include dol_buildpath($path.'/theme/'.$theme.'/info-box.inc.php', 0); include dol_buildpath($path.'/theme/'.$theme.'/progress.inc.php', 0); include dol_buildpath($path.'/theme/eldy/timeline.inc.php', 0); // actually md use same style as eldy theme -if (!empty($conf->global->THEME_CUSTOM_CSS)) print $conf->global->THEME_CUSTOM_CSS; +if (!empty($conf->global->THEME_CUSTOM_CSS)) { + print $conf->global->THEME_CUSTOM_CSS; +} -if (is_object($db)) $db->close(); +if (is_object($db)) { + $db->close(); +} ?> /* This must be at end */ diff --git a/htdocs/theme/md/theme_vars.inc.php b/htdocs/theme/md/theme_vars.inc.php index e74c206ad20..23b34119cf0 100644 --- a/htdocs/theme/md/theme_vars.inc.php +++ b/htdocs/theme/md/theme_vars.inc.php @@ -29,12 +29,9 @@ global $theme_bordercolor, $theme_datacolor, $theme_bgcolor, $theme_bgcoloronglet; $theme_bordercolor = array(235, 235, 224); $theme_datacolor = array(array(137, 86, 161), array(60, 147, 183), array(250, 190, 80), array(191, 75, 57), array(80, 166, 90), array(140, 140, 220), array(190, 120, 120), array(190, 190, 100), array(115, 125, 150), array(100, 170, 20), array(150, 135, 125), array(85, 135, 150), array(150, 135, 80), array(150, 80, 150)); -if (!defined('ISLOADEDBYSTEELSHEET')) // File is run after an include of a php page, not by the style sheet, if the constant is not defined. -{ - if (!empty($conf->global->MAIN_OPTIMIZEFORCOLORBLIND)) // user is loaded by dolgraph.class.php - { - if ($conf->global->MAIN_OPTIMIZEFORCOLORBLIND == 'flashy') - { +if (!defined('ISLOADEDBYSTEELSHEET')) { // File is run after an include of a php page, not by the style sheet, if the constant is not defined. + if (!empty($conf->global->MAIN_OPTIMIZEFORCOLORBLIND)) { // user is loaded by dolgraph.class.php + if ($conf->global->MAIN_OPTIMIZEFORCOLORBLIND == 'flashy') { $theme_datacolor = array(array(157, 56, 191), array(0, 147, 183), array(250, 190, 30), array(221, 75, 57), array(0, 166, 90), array(140, 140, 220), array(190, 120, 120), array(190, 190, 100), array(115, 125, 150), array(100, 170, 20), array(150, 135, 125), array(85, 135, 150), array(150, 135, 80), array(150, 80, 150)); } else { // for now we use the same configuration for all types of color blind diff --git a/htdocs/ticket/agenda.php b/htdocs/ticket/agenda.php index be68e1f68ee..d2611e562d2 100644 --- a/htdocs/ticket/agenda.php +++ b/htdocs/ticket/agenda.php @@ -46,16 +46,21 @@ $sortorder = GETPOST("sortorder", 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = is_numeric($page) ? $page : 0; $page = $page == -1 ? 0 : $page; -if (!$sortfield) $sortfield = "a.datep,a.id"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "a.datep,a.id"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (GETPOST('actioncode', 'array')) -{ +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)); } @@ -83,8 +88,7 @@ if (!$user->rights->ticket->read) { accessforbidden(); } // restrict access for externals users -if ($user->socid > 0 && ($object->fk_soc != $user->socid)) -{ +if ($user->socid > 0 && ($object->fk_soc != $user->socid)) { accessforbidden(); } // or for unauthorized internals users @@ -100,17 +104,17 @@ if (!$user->socid && ($conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY && $object- $parameters = array('id'=>$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)) -{ +if (empty($reshook)) { // Set view style $_SESSION['ticket-view-type'] = "list"; } // Purge search criteria -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers $actioncode = ''; $search_agenda_label = ''; } @@ -126,7 +130,9 @@ $userstat = new User($db); $formticket = new FormTicket($db); $title = $langs->trans("Ticket").' - '.$object->ref.' '.$object->name; -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/ticketnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Info"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/ticketnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->ref.' '.$object->name.' - '.$langs->trans("Info"); +} $help_url = 'FR:DocumentationModuleTicket'; llxHeader('', $title, $help_url); @@ -167,8 +173,7 @@ if (!empty($object->origin_email)) { } // Thirdparty -if (!empty($conf->societe->enabled)) -{ +if (!empty($conf->societe->enabled)) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty'); /*if ($action != 'editcustomer' && $object->fk_statut < 8 && !$user->socid && $user->rights->ticket->write) { $morehtmlref.='<a class="editfielda" href="' . $url_page_current . '?action=editcustomer&amp;track_id=' . $object->track_id . '">' . img_edit($langs->transnoentitiesnoconv('Edit'), 1) . '</a>'; @@ -182,12 +187,10 @@ if (!empty($conf->societe->enabled)) } // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project'); - if ($user->rights->ticket->write) - { + if ($user->rights->ticket->write) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a>'; $morehtmlref .= ' : '; @@ -225,11 +228,14 @@ print dol_get_fiche_end(); print '<br>'; -if (!empty($object->id)) -{ +if (!empty($object->id)) { $param = '&id='.$object->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; + } $morehtmlright = ''; diff --git a/htdocs/ticket/card.php b/htdocs/ticket/card.php index 6d14d29202f..c5e27979121 100644 --- a/htdocs/ticket/card.php +++ b/htdocs/ticket/card.php @@ -60,7 +60,9 @@ $sortorder = GETPOST('sortorder', 'aZ09comma'); 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)); } @@ -80,12 +82,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} //Select mail models is same action as add_message if (GETPOST('modelselected', 'alpha')) { @@ -96,8 +101,7 @@ if (GETPOST('modelselected', 'alpha')) { //include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals if ($id || $track_id || $ref) { $res = $object->fetch($id, $ref, $track_id); - if ($res >= 0) - { + if ($res >= 0) { $id = $object->id; $track_id = $object->track_id; } @@ -125,13 +129,14 @@ $now = dol_now(); $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'); +} $error = 0; if (empty($reshook)) { // Purge search criteria - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers{ - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers{ $actioncode = ''; $search_agenda_label = ''; } @@ -159,7 +164,9 @@ if (empty($reshook)) { $action = 'create'; } $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } if (!$error) { $db->begin(); @@ -289,7 +296,9 @@ if (empty($reshook)) { array_push($object->errors, $langs->trans('ErrorFieldRequired', $langs->transnoentities('Subject'))); } $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } if (!$error) { @@ -301,7 +310,9 @@ if (empty($reshook)) { $object->severity_code = GETPOST('severity_code', 'alpha'); $ret = $object->update($user); - if ($ret <= 0) $error++; + if ($ret <= 0) { + $error++; + } if ($error) { $db->rollback(); @@ -354,11 +365,12 @@ if (empty($reshook)) { if (!$error) { $ret = $object->assignUser($user, $usertoassign); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } - if (!$error) // Update list of contacts - { + if (!$error) { // Update list of contacts // Si déjà un user assigné on le supprime des contacts if ($useroriginassign > 0) { $internal_contacts = $object->listeContact(-1, 'internal'); @@ -373,7 +385,9 @@ if (empty($reshook)) { } } - if ($usertoassign > 0) $object->add_contact($usertoassign, "SUPPORTTEC", 'internal', $notrigger = 0); + if ($usertoassign > 0) { + $object->add_contact($usertoassign, "SUPPORTTEC", 'internal', $notrigger = 0); + } } if (!$error) { @@ -517,16 +531,16 @@ if (empty($reshook)) { } } } - } // Categorisation dans projet - elseif ($action == 'classin' && $user->rights->ticket->write) { + } elseif ($action == 'classin' && $user->rights->ticket->write) { + // Categorisation dans projet if ($object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')) >= 0) { $object->setProject(GETPOST('projectid', 'int')); $url = 'card.php?action=view&track_id='.$object->track_id; header("Location: ".$url); exit(); } - } // Categorisation dans contrat - elseif ($action == 'setcontract' && $user->rights->ticket->write) { + } elseif ($action == 'setcontract' && $user->rights->ticket->write) { + // Categorisation dans contrat if ($object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')) >= 0) { $object->setContract(GETPOST('contractid', 'int')); $url = 'card.php?action=view&track_id='.$object->track_id; @@ -557,8 +571,8 @@ if (empty($reshook)) { } $action = 'view'; - } // Reopen ticket - elseif ($action == 'confirm_set_status' && $user->rights->ticket->write && !GETPOST('cancel')) { + } elseif ($action == 'confirm_set_status' && $user->rights->ticket->write && !GETPOST('cancel')) { + // Reopen ticket if ($object->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { $new_status = GETPOST('new_status', 'int'); $old_status = $object->fk_statut; @@ -582,11 +596,15 @@ if (empty($reshook)) { $object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')); $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } if (!$error) { $result = $object->insertExtraFields(empty($triggermodname) ? '' : $triggermodname, $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } } if ($error) { @@ -634,7 +652,9 @@ if (empty($reshook)) { include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Set $action to correct value for the case we used presend action to add a message - if (GETPOSTISSET('actionbis') && $action == 'presend') $action = 'presend_addmessage'; + if (GETPOSTISSET('actionbis') && $action == 'presend') { + $action = 'presend_addmessage'; + } } @@ -645,15 +665,17 @@ if (empty($reshook)) { $userstat = new User($db); $form = new Form($db); $formticket = new FormTicket($db); -if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} + +$help_url = 'EN:Module_Ticket|FR:DocumentationModuleTicket'; -$help_url = 'FR:DocumentationModuleTicket'; $page_title = $actionobject->getTitle($action); llxHeader('', $page_title, $help_url); -if ($action == 'create' || $action == 'presend') -{ +if ($action == 'create' || $action == 'presend') { $formticket = new FormTicket($db); print load_fiche_titre($langs->trans('NewTicket'), '', 'ticket'); @@ -725,12 +747,9 @@ if ($action == 'create' || $action == 'presend') print '</div>'; print '</form>'; -} -elseif (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'dellink' || $action == 'presend' || $action == 'presend_addmessage' || $action == 'close' || $action == 'delete' || $action == 'editcustomer' || $action == 'progression' || $action == 'reopen' - || $action == 'editsubject' || $action == 'edit_extras' || $action == 'update_extras' || $action == 'edit_extrafields' || $action == 'set_extrafields' || $action == 'classify' || $action == 'sel_contract' || $action == 'edit_message_init' || $action == 'set_status' || $action == 'dellink') -{ - if ($res > 0) - { +} elseif (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'dellink' || $action == 'presend' || $action == 'presend_addmessage' || $action == 'close' || $action == 'delete' || $action == 'editcustomer' || $action == 'progression' || $action == 'reopen' + || $action == 'editsubject' || $action == 'edit_extras' || $action == 'update_extras' || $action == 'edit_extrafields' || $action == 'set_extrafields' || $action == 'classify' || $action == 'sel_contract' || $action == 'edit_message_init' || $action == 'set_status' || $action == 'dellink') { + if ($res > 0) { // or for unauthorized internals users if (!$user->socid && ($conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY && $object->fk_user_assign != $user->id) && !$user->rights->ticket->manage) { accessforbidden('', 0, 1); @@ -774,8 +793,8 @@ elseif (empty($action) || $action == 'view' || $action == 'addlink' || $action = print dol_get_fiche_head($head, 'ticket', $langs->trans("Project"), 0, ($projectstat->public ? 'projectpub' : 'project')); /* - * Projet synthese pour rappel - */ + * Projet synthese pour rappel + */ print '<table class="border centpercent">'; $linkback = '<a href="'.DOL_URL_ROOT.'/projet/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; @@ -878,19 +897,20 @@ elseif (empty($action) || $action == 'view' || $action == 'addlink' || $action = $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; if ($user->rights->ticket->write) { - if ($action != 'classify') + if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a>'; - $morehtmlref .= ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; - $morehtmlref .= '<input type="hidden" name="action" value="classin">'; - $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; - $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1, 0, 'maxwidth500'); - $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; - $morehtmlref .= '</form>'; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + $morehtmlref .= ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref .= '<input type="hidden" name="action" value="classin">'; + $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1, 0, 'maxwidth500'); + $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref .= '</form>'; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); } } else { if (!empty($object->fk_project)) { @@ -1010,8 +1030,7 @@ elseif (empty($action) || $action == 'view' || $action == 'addlink' || $action = print '</tr>'; // Timing (Duration sum of linked fichinter) - if ($conf->fichinter->enabled) - { + if ($conf->fichinter->enabled) { $object->fetchObjectLinked(); $num = count($object->linkedObjects); $timing = 0; @@ -1120,8 +1139,7 @@ elseif (empty($action) || $action == 'view' || $action == 'addlink' || $action = } - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { print load_fiche_titre($langs->trans('Contacts'), '', 'title_companies.png'); print '<div class="div-table-responsive-no-min">'; @@ -1245,10 +1263,11 @@ elseif (empty($action) || $action == 'view' || $action == 'addlink' || $action = print '<div class="tabsAction">'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Show link to add a message (if read and not closed) if ($object->fk_statut < Ticket::STATUS_CLOSED && $action != "presend" && $action != "presend_addmessage") { print '<div class="inline-block divButAction"><a class="butAction reposition" href="card.php?track_id='.$object->track_id.'&action=presend_addmessage&mode=init">'.$langs->trans('TicketAddMessage').'</a></div>'; @@ -1292,11 +1311,12 @@ elseif (empty($action) || $action == 'view' || $action == 'addlink' || $action = $action = 'presend'; } // Set $action to correct value for the case we used presend action to add a message - if (GETPOSTISSET('actionbis') && $action == 'presend') $action = 'presend_addmessage'; + if (GETPOSTISSET('actionbis') && $action == 'presend') { + $action = 'presend_addmessage'; + } // add a message - if ($action == 'presend' || $action == 'presend_addmessage') - { + if ($action == 'presend' || $action == 'presend_addmessage') { $action = 'add_message'; // action to use to post the message $modelmail = 'ticket_send'; @@ -1375,10 +1395,18 @@ elseif (empty($action) || $action == 'view' || $action == 'addlink' || $action = // Show messages on card (Note: this is a duplicate of the view Events/Agenda but on the main tab) if (!empty($conf->global->TICKET_SHOW_MESSAGES_ON_CARD)) { $param = '&id='.$object->id; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; - if ($actioncode) $param .= '&actioncode='.urlencode($actioncode); - if ($search_agenda_label) $param .= '&search_agenda_label='.urlencode($search_agenda_label); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.$contextpage; + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; + } + if ($actioncode) { + $param .= '&actioncode='.urlencode($actioncode); + } + if ($search_agenda_label) { + $param .= '&search_agenda_label='.urlencode($search_agenda_label); + } $morehtmlright = ''; diff --git a/htdocs/ticket/class/actions_ticket.class.php b/htdocs/ticket/class/actions_ticket.class.php index 40fc22e1347..eb6193d58f1 100644 --- a/htdocs/ticket/class/actions_ticket.class.php +++ b/htdocs/ticket/class/actions_ticket.class.php @@ -262,14 +262,15 @@ class ActionsTicket // Load logs in cache $ret = $this->dao->loadCacheMsgsTicket(); - if ($ret < 0) dol_print_error($this->dao->db); + if ($ret < 0) { + dol_print_error($this->dao->db); + } $action = GETPOST('action', 'aZ09'); $this->viewTicketOriginalMessage($user, $action, $object); - if (is_array($this->dao->cache_msgs_ticket) && count($this->dao->cache_msgs_ticket) > 0) - { + if (is_array($this->dao->cache_msgs_ticket) && count($this->dao->cache_msgs_ticket) > 0) { print '<table class="border" style="width:100%;">'; print '<tr class="liste_titre">'; diff --git a/htdocs/ticket/class/api_tickets.class.php b/htdocs/ticket/class/api_tickets.class.php index 4a0bcbe7b92..d8e36933ea6 100644 --- a/htdocs/ticket/class/api_tickets.class.php +++ b/htdocs/ticket/class/api_tickets.class.php @@ -114,8 +114,7 @@ class Tickets extends DolibarrApi { try { return $this->getCommon(0, '', $ref); - } catch (Exception $e) - { + } catch (Exception $e) { throw $e; } } diff --git a/htdocs/ticket/class/ticket.class.php b/htdocs/ticket/class/ticket.class.php index 306f861097b..237edd265de 100644 --- a/htdocs/ticket/class/ticket.class.php +++ b/htdocs/ticket/class/ticket.class.php @@ -254,7 +254,7 @@ class Ticket extends CommonObject 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>0, 'enabled'=>1, 'position'=>5, 'notnull'=>1, 'index'=>1), 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'css'=>''), 'track_id' => array('type'=>'varchar(255)', 'label'=>'TicketTrackId', 'visible'=>-2, 'enabled'=>1, 'position'=>11, 'notnull'=>-1, 'searchall'=>1, 'help'=>"Help text"), - 'fk_user_create' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Author', 'visible'=>1, 'enabled'=>1, 'position'=>15, 'notnull'=>1, 'css'=>'tdoverflowmax150 maxwidth150onsmartphone'), + 'fk_user_create' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Author', 'visible'=>1, 'enabled'=>1, 'position'=>15, 'notnull'=>1, 'css'=>'tdoverflowmax125 maxwidth150onsmartphone'), 'origin_email' => array('type'=>'mail', 'label'=>'OriginEmail', 'visible'=>-2, 'enabled'=>1, 'position'=>16, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'css'=>'tdoverflowmax150'), 'subject' => array('type'=>'varchar(255)', 'label'=>'Subject', 'visible'=>1, 'enabled'=>1, 'position'=>18, 'notnull'=>-1, 'searchall'=>1, 'help'=>"", 'css'=>'maxwidth200 tdoverflowmax200', 'autofocusoncreate'=>1), 'type_code' => array('type'=>'varchar(32)', 'label'=>'Type', 'visible'=>1, 'enabled'=>1, 'position'=>20, 'notnull'=>-1, 'help'=>"", 'css'=>'maxwidth125 tdoverflowmax50'), @@ -266,7 +266,7 @@ class Ticket extends CommonObject 'timing' => array('type'=>'varchar(20)', 'label'=>'Timing', 'visible'=>-1, 'enabled'=>1, 'position'=>42, 'notnull'=>-1, 'help'=>""), 'datec' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>1, 'enabled'=>1, 'position'=>500, 'notnull'=>1), 'date_read' => array('type'=>'datetime', 'label'=>'TicketReadOn', 'visible'=>-1, 'enabled'=>1, 'position'=>501, 'notnull'=>1), - 'fk_user_assign' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'AssignedTo', 'visible'=>1, 'enabled'=>1, 'position'=>505, 'notnull'=>1, 'css'=>'tdoverflowmax150'), + 'fk_user_assign' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'AssignedTo', 'visible'=>1, 'enabled'=>1, 'position'=>505, 'notnull'=>1, 'css'=>'tdoverflowmax125'), 'date_close' => array('type'=>'datetime', 'label'=>'TicketCloseOn', 'visible'=>-1, 'enabled'=>1, 'position'=>510, 'notnull'=>1), 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-1, 'enabled'=>1, 'position'=>520, 'notnull'=>1), 'message' => array('type'=>'text', 'label'=>'Message', 'visible'=>-2, 'enabled'=>1, 'position'=>540, 'notnull'=>-1,), @@ -410,7 +410,9 @@ class Ticket extends CommonObject // Clean parameters $this->datec = dol_now(); - if (empty($this->track_id)) $this->track_id = generate_random_id(16); + if (empty($this->track_id)) { + $this->track_id = generate_random_id(16); + } // Check more parameters // If error, this->errors[] is filled @@ -581,8 +583,7 @@ class Ticket extends CommonObject dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - if ($this->db->num_rows($resql)) - { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -711,7 +712,7 @@ class Ticket extends CommonObject if (!empty($filter)) { foreach ($filter as $key => $value) { if (strpos($key, 'date')) { // To allow $filter['YEAR(s.dated)']=>$year - $sql .= ' AND '.$key." = '".$this->db->scape($value)."'"; + $sql .= ' AND '.$key." = '".$this->db->escape($value)."'"; } elseif (($key == 't.fk_user_assign') || ($key == 't.type_code') || ($key == 't.category_code') || ($key == 't.severity_code') || ($key == 't.fk_soc')) { $sql .= " AND ".$key." = '".$this->db->escape($value)."'"; } elseif ($key == 't.fk_statut') { @@ -913,7 +914,7 @@ class Ticket extends CommonObject $sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').","; $sql .= " date_read=".(dol_strlen($this->date_read) != 0 ? "'".$this->db->idate($this->date_read)."'" : 'null').","; $sql .= " date_close=".(dol_strlen($this->date_close) != 0 ? "'".$this->db->idate($this->date_close)."'" : 'null').""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); @@ -991,7 +992,9 @@ class Ticket extends CommonObject if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } // Removed extrafields @@ -1005,7 +1008,7 @@ class Ticket extends CommonObject if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."ticket"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete sql=".$sql); $resql = $this->db->query($sql); @@ -1319,7 +1322,9 @@ class Ticket extends CommonObject global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -1332,33 +1337,40 @@ class Ticket extends CommonObject $url = dol_buildpath('/ticket/card.php', 1).'?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowTicket"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = '<a href="'.$url.'"'; $linkstart .= $linkclose.'>'; $linkend = '</a>'; $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 .= $this->ref; + 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 .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -1437,8 +1449,7 @@ class Ticket extends CommonObject $this->oldcopy = dol_clone($this); $sql = "UPDATE ".MAIN_DB_PREFIX."ticket"; - if ($id_assign_user > 0) - { + if ($id_assign_user > 0) { $sql .= " SET fk_user_assign=".$id_assign_user.", fk_statut = ".Ticket::STATUS_ASSIGNED; } else { $sql .= " SET fk_user_assign=null, fk_statut = ".Ticket::STATUS_READ; @@ -1447,8 +1458,7 @@ class Ticket extends CommonObject dol_syslog(get_class($this)."::assignUser sql=".$sql); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->fk_user_assign = $id_assign_user; // May be used by trigger if (!$notrigger) { @@ -1588,29 +1598,29 @@ class Ticket extends CommonObject // TODO Read the table llx_actioncomm /* - $sql = "SELECT rowid, fk_user_create, datec, message"; - $sql .= " FROM " . MAIN_DB_PREFIX . "ticket_logs"; - $sql .= " WHERE fk_track_id ='" . $this->db->escape($this->track_id) . "'"; - $sql .= " ORDER BY datec DESC"; + $sql = "SELECT rowid, fk_user_create, datec, message"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ticket_logs"; + $sql .= " WHERE fk_track_id ='" . $this->db->escape($this->track_id) . "'"; + $sql .= " ORDER BY datec DESC"; - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) { - $obj = $this->db->fetch_object($resql); - $this->cache_logs_ticket[$i]['id'] = $obj->rowid; - $this->cache_logs_ticket[$i]['fk_user_create'] = $obj->fk_user_create; - $this->cache_logs_ticket[$i]['datec'] = $this->db->jdate($obj->datec); - $this->cache_logs_ticket[$i]['message'] = $obj->message; - $i++; - } - return $num; - } else { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::loadCacheLogsTicket " . $this->error, LOG_ERR); - return -1; - }*/ + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + $this->cache_logs_ticket[$i]['id'] = $obj->rowid; + $this->cache_logs_ticket[$i]['fk_user_create'] = $obj->fk_user_create; + $this->cache_logs_ticket[$i]['datec'] = $this->db->jdate($obj->datec); + $this->cache_logs_ticket[$i]['message'] = $obj->message; + $i++; + } + return $num; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::loadCacheLogsTicket " . $this->error, LOG_ERR); + return -1; + }*/ return 0; } @@ -1669,14 +1679,12 @@ class Ticket extends CommonObject $actioncomm->attachedfiles = $attachedfiles; } - if (!empty($mimefilename_list) && is_array($mimefilename_list)) - { + if (!empty($mimefilename_list) && is_array($mimefilename_list)) { $actioncomm->note_private = dol_concatdesc($actioncomm->note_private, "\n".$langs->transnoentities("AttachedFiles").': '.join(';', $mimefilename_list)); } $actionid = $actioncomm->create($user); - if ($actionid <= 0) - { + if ($actionid <= 0) { $error++; $this->error = $actioncomm->error; $this->errors = $actioncomm->errors; @@ -1760,8 +1768,7 @@ class Ticket extends CommonObject if (!empty($conf->ficheinter->enabled) && !empty($conf->global->WORKFLOW_TICKET_CLOSE_INTERVENTION)) { dol_syslog("We have closed the ticket, so we close all linked interventions"); $this->fetchObjectLinked($this->id, $this->element, null, 'fichinter'); - if ($this->linkedObjectsIds) - { + if ($this->linkedObjectsIds) { foreach ($this->linkedObjectsIds['fichinter'] as $fichinter_id) { $fichinter = new Fichinter($this->db); $fichinter->fetch($fichinter_id); @@ -2148,8 +2155,7 @@ class Ticket extends CommonObject $sendto = $obj->firstname." ".$obj->lastname." <".$obj->email.">"; $actiondefid = $obj->adid; - if (dol_strlen($sendto)) - { + if (dol_strlen($sendto)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $application = ($conf->global->MAIN_APPLICATION_TITLE ? $conf->global->MAIN_APPLICATION_TITLE : 'Dolibarr ERP/CRM'); @@ -2465,8 +2471,7 @@ class Ticket extends CommonObject foreach ($filename as $i => $val) { $destfile = $destdir.'/'.$filename[$i]; // If destination file already exists, we add a suffix to avoid to overwrite - if (is_file($destfile)) - { + if (is_file($destfile)) { $pathinfo = pathinfo($filename[$i]); $now = dol_now(); $destfile = $destdir.'/'.$pathinfo['filename'].' - '.dol_print_date($now, 'dayhourlog').'.'.$pathinfo['extension']; @@ -2626,11 +2631,10 @@ class Ticket extends CommonObject $this->sendTicketMessageByEmail($subject, $message, '', $sendto, $listofpaths, $listofmimes, $listofnames); } } - } - /* - * Private area - */ - else { + } else { + /* + * Private area + */ /* * Send emails to internal users (linked contacts) */ @@ -2670,7 +2674,9 @@ class Ticket extends CommonObject } if ($info_sendto['email'] != '') { - if (!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">"; + if (!empty($info_sendto['email'])) { + $sendto[] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">"; + } //Contact type $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1').' ('.strtolower($info_sendto['libelle']).')'; @@ -2686,7 +2692,9 @@ class Ticket extends CommonObject // Add global email address recipient if ($conf->global->TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS && !in_array($conf->global->TICKET_NOTIFICATION_EMAIL_TO, $sendto)) { - if (!empty($conf->global->TICKET_NOTIFICATION_EMAIL_TO)) $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO; + if (!empty($conf->global->TICKET_NOTIFICATION_EMAIL_TO)) { + $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO; + } } // altairis: dont try to send email if no recipient @@ -2744,7 +2752,9 @@ class Ticket extends CommonObject } if ($info_sendto['email'] != '' && $info_sendto['email'] != $object->origin_email) { - if (!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">"; + if (!empty($info_sendto['email'])) { + $sendto[] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">"; + } $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1').' ('.strtolower($info_sendto['libelle']).')'; $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient').' : '.$recipient.'<br>' : ''); @@ -2769,12 +2779,16 @@ class Ticket extends CommonObject if ($object->fk_soc > 0 && !in_array($object->origin_email, $sendto)) { $object->socid = $object->fk_soc; $object->fetch_thirdparty(); - if (!empty($object->thirdparty->email)) $sendto[] = $object->thirdparty->email; + if (!empty($object->thirdparty->email)) { + $sendto[] = $object->thirdparty->email; + } } // altairis: Add global email address reciepient if ($conf->global->TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS && !in_array($conf->global->TICKET_NOTIFICATION_EMAIL_TO, $sendto)) { - if (!empty($conf->global->TICKET_NOTIFICATION_EMAIL_TO)) $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO; + if (!empty($conf->global->TICKET_NOTIFICATION_EMAIL_TO)) { + $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO; + } } // altairis: dont try to send email when no recipient @@ -2787,8 +2801,7 @@ class Ticket extends CommonObject } // Set status to "answered" if not set yet, but only if internal user - if ($object->fk_statut < 3 && !$user->socid) - { + if ($object->fk_statut < 3 && !$user->socid) { $object->setStatut(3); } @@ -2842,8 +2855,7 @@ class Ticket extends CommonObject $from = $conf->global->TICKET_NOTIFICATION_EMAIL_FROM; if (is_array($array_receiver) && count($array_receiver) > 0) { - foreach ($array_receiver as $key => $receiver) - { + foreach ($array_receiver as $key => $receiver) { $deliveryreceipt = 0; $filepath = $filename_list; $filename = $mimefilename_list; @@ -2897,25 +2909,28 @@ class Ticket extends CommonObject global $conf, $user, $langs; $now = dol_now(); + $delay_warning = 0; $this->nbtodo = $this->nbtodolate = 0; $clause = " WHERE"; $sql = "SELECT p.rowid, p.ref, p.datec as datec"; $sql .= " FROM ".MAIN_DB_PREFIX."ticket as p"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = " AND"; } $sql .= $clause." p.entity IN (".getEntity('ticket').")"; - if ($mode == 'opened') $sql .= " AND p.fk_statut NOT IN (".Ticket::STATUS_CLOSED.", ".Ticket::STATUS_CANCELED.")"; - if ($user->socid) $sql .= " AND p.fk_soc = ".$user->socid; + if ($mode == 'opened') { + $sql .= " AND p.fk_statut NOT IN (".Ticket::STATUS_CLOSED.", ".Ticket::STATUS_CANCELED.")"; + } + if ($user->socid) { + $sql .= " AND p.fk_soc = ".$user->socid; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $label = $labelShort = ''; $status = ''; if ($mode == 'opened') { @@ -2934,14 +2949,11 @@ class Ticket extends CommonObject $response->img = img_object('', "ticket"); // This assignment in condition is not a bug. It allows walking the results. - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; - if ($mode == 'opened') - { - $datelimit = $this->db->jdate($obj->datefin); - if ($datelimit < ($now - $delay_warning)) - { + if ($mode == 'opened') { + $datelimit = $this->db->jdate($obj->datec) + $delay_warning; + if ($datelimit < $now) { //$response->nbtodolate++; } } @@ -2970,8 +2982,7 @@ class Ticket extends CommonObject $sql = "SELECT count(p.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."ticket as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -2979,11 +2990,9 @@ class Ticket extends CommonObject $sql .= " ".$clause." p.entity IN (".getEntity('ticket').")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // This assignment in condition is not a bug. It allows walking the results. - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["ticket"] = $obj->nb; } $this->db->free($resql); diff --git a/htdocs/ticket/class/utils_diff.class.php b/htdocs/ticket/class/utils_diff.class.php index 6edccdfa0ff..e18418d78a6 100644 --- a/htdocs/ticket/class/utils_diff.class.php +++ b/htdocs/ticket/class/utils_diff.class.php @@ -78,8 +78,7 @@ class Diff } $end2 = ($compareCharacters ? strlen($sequence1) : count($sequence1)); - for ($index = $end1 + 1; $index < $end2; $index++) - { + for ($index = $end1 + 1; $index < $end2; $index++) { $diff[] = array($sequence1[$index], self::UNMODIFIED); } @@ -313,12 +312,12 @@ class Diff self::DELETED ); $rightCell = self::getCellContent( - $diff, - $indentation, - $separator, - $index, - self::INSERTED - ); + $diff, + $indentation, + $separator, + $index, + self::INSERTED + ); break; // display the inserted content on the right diff --git a/htdocs/ticket/contact.php b/htdocs/ticket/contact.php index 13419cf795e..7e04dd12104 100644 --- a/htdocs/ticket/contact.php +++ b/htdocs/ticket/contact.php @@ -124,8 +124,7 @@ $contactstatic = new Contact($db); $userstatic = new User($db); if ($id > 0 || !empty($track_id) || !empty($ref)) { - if ($object->fetch($id, $ref, $track_id) > 0) - { + if ($object->fetch($id, $ref, $track_id) > 0) { if ($socid > 0) { $object->fetch_thirdparty(); $head = societe_prepare_head($object->thirdparty); @@ -161,12 +160,11 @@ if ($id > 0 || !empty($track_id) || !empty($ref)) { } // Thirdparty - if (!empty($conf->societe->enabled)) - { + if (!empty($conf->societe->enabled)) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty'); /*if ($action != 'editcustomer' && $object->fk_statut < 8 && !$user->socid && $user->rights->ticket->write) { - $morehtmlref.='<a class="editfielda" href="' . $url_page_current . '?action=editcustomer&amp;track_id=' . $object->track_id . '">' . img_edit($langs->transnoentitiesnoconv('Edit'), 1) . '</a>'; - }*/ + $morehtmlref.='<a class="editfielda" href="' . $url_page_current . '?action=editcustomer&amp;track_id=' . $object->track_id . '">' . img_edit($langs->transnoentitiesnoconv('Edit'), 1) . '</a>'; + }*/ $morehtmlref .= ' : '; if ($action == 'editcustomer') { $morehtmlref .= $form->form_thirdparty($url_page_current.'?track_id='.$object->track_id, $object->socid, 'editcustomer', '', 1, 0, 0, array(), 1); @@ -176,12 +174,10 @@ if ($id > 0 || !empty($track_id) || !empty($ref)) { } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->ticket->write) - { + if ($user->rights->ticket->write) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a>'; $morehtmlref .= ' : '; diff --git a/htdocs/ticket/css/styles.css.php b/htdocs/ticket/css/styles.css.php index 7391dd19012..8898dbce104 100644 --- a/htdocs/ticket/css/styles.css.php +++ b/htdocs/ticket/css/styles.css.php @@ -22,14 +22,26 @@ //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled because need to load personalized language //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled to increase speed. Language code is found on url. -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Not disabled because need to do translations -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); -if (!defined('NOLOGIN')) define('NOLOGIN', 1); // File must be accessed by logon page so without login +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', 1); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', 1); // File must be accessed by logon page so without login +} //if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU',1); // We need top menu content -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', 1); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} session_cache_limiter('public'); @@ -39,13 +51,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; // Define css type top_httphead('text/css'); // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. -if (empty($dolibarr_nocache)) header('Cache-Control: max-age=3600, public, must-revalidate'); -else header('Cache-Control: no-cache'); +if (empty($dolibarr_nocache)) { + header('Cache-Control: max-age=3600, public, must-revalidate'); +} else { + header('Cache-Control: no-cache'); +} ?> html { - min-height: 100%; height: 100%; + min-height: 100%; height: 100%; } html { @@ -58,49 +73,49 @@ if (!empty($conf->global->TICKET_SHOW_MODULE_LOGO)) { div.ticketform { - font-family: arial; - position: static; - padding: 2em 1em; - overflow-x: auto; - border: 2px solid rgb(153, 153, 153); - background-color: rgb(255, 255, 255); - box-shadow: 2px 2px 2px rgb(245, 245, 245); - border-radius: 10px 10px 10px 10px; - margin: 1.5em; - background : #ffffff; + font-family: arial; + position: static; + padding: 2em 1em; + overflow-x: auto; + border: 2px solid rgb(153, 153, 153); + background-color: rgb(255, 255, 255); + box-shadow: 2px 2px 2px rgb(245, 245, 245); + border-radius: 10px 10px 10px 10px; + margin: 1.5em; + background : #ffffff; text-align: center; } div.ticketform .index_create, .index_display { display: inline-block; - width: 200px; - height: 45px; - text-align: center; - vertical-align: middle; - margin: 20px; - text-transform: uppercase; + width: 200px; + height: 45px; + text-align: center; + vertical-align: middle; + margin: 20px; + text-transform: uppercase; } #form_create_ticket, #form_view_ticket { - margin-left: 10px; - margin-right: 10px; - padding-left:1em; - padding-right:1em; - padding-top:1.5em; - padding-bottom:12px; + margin-left: 10px; + margin-right: 10px; + padding-left:1em; + padding-right:1em; + padding-top:1.5em; + padding-bottom:12px; - border: 1px solid #C0C0C0; - background-color: #E0E0E0; + border: 1px solid #C0C0C0; + background-color: #E0E0E0; - -moz-box-shadow: 4px 4px 4px #DDD; - -webkit-box-shadow: 4px 4px 4px #DDD; - box-shadow: 4px 4px 4px #DDD; + -moz-box-shadow: 4px 4px 4px #DDD; + -webkit-box-shadow: 4px 4px 4px #DDD; + box-shadow: 4px 4px 4px #DDD; - border-radius: 8px; - border:solid 1px rgba(168,168,168,.4); - border-top:solid 1px f8f8f8; - background-color: #f8f8f8; + border-radius: 8px; + border:solid 1px rgba(168,168,168,.4); + border-top:solid 1px f8f8f8; + background-color: #f8f8f8; } #form_create_ticket input.text, #form_create_ticket textarea { width:450px;} diff --git a/htdocs/ticket/document.php b/htdocs/ticket/document.php index 45ee7aba268..b8e0e79eede 100644 --- a/htdocs/ticket/document.php +++ b/htdocs/ticket/document.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 = "ASC"; -if (!$sortfield) $sortfield = "position_name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "position_name"; +} $object = new Ticket($db); $result = $object->fetch($id, $ref, $track_id); @@ -73,7 +79,7 @@ if ($result < 0) { * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; @@ -86,8 +92,7 @@ $form = new Form($db); $help_url = ''; llxHeader('', $langs->trans("TicketDocumentsLinked").' - '.$langs->trans("Files"), $help_url); -if ($object->id) -{ +if ($object->id) { /* * Show tabs */ @@ -126,12 +131,11 @@ if ($object->id) } // Thirdparty - if (!empty($conf->societe->enabled)) - { + if (!empty($conf->societe->enabled)) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty'); /*if ($action != 'editcustomer' && $object->fk_statut < 8 && !$user->socid && $user->rights->ticket->write) { - $morehtmlref.='<a class="editfielda" href="' . $url_page_current . '?action=editcustomer&amp;track_id=' . $object->track_id . '">' . img_edit($langs->transnoentitiesnoconv('Edit'), 1) . '</a>'; - }*/ + $morehtmlref.='<a class="editfielda" href="' . $url_page_current . '?action=editcustomer&amp;track_id=' . $object->track_id . '">' . img_edit($langs->transnoentitiesnoconv('Edit'), 1) . '</a>'; + }*/ $morehtmlref .= ' : '; if ($action == 'editcustomer') { $morehtmlref .= $form->form_thirdparty($url_page_current.'?track_id='.$object->track_id, $object->socid, 'editcustomer', '', 1, 0, 0, array(), 1); @@ -141,12 +145,10 @@ if ($object->id) } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->ticket->write) - { + if ($user->rights->ticket->write) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a>'; $morehtmlref .= ' : '; @@ -190,11 +192,11 @@ if ($object->id) //$object->ref = $object->track_id; // For compatibility we use track ID for directory $modulepart = 'ticket'; - $permission = $user->rights->ticket->write; - $permtoedit = $user->rights->ticket->write; - $param = '&id='.$object->id; + $permission = $user->rights->ticket->write; + $permtoedit = $user->rights->ticket->write; + $param = '&id='.$object->id; - include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { accessforbidden('', 0, 1); } diff --git a/htdocs/ticket/index.php b/htdocs/ticket/index.php index f871fafa893..2a3850d1e59 100644 --- a/htdocs/ticket/index.php +++ b/htdocs/ticket/index.php @@ -1,6 +1,7 @@ <?php /* Copyright (C) - 2013-2016 Jean-François FERRY <hello@librethic.io> * Copyright (C) - 2019 Nicolas ZABOURI <info@inovea-conseil.com> + * Copyright (C) 2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -26,6 +27,7 @@ require_once DOL_DOCUMENT_ROOT.'/ticket/class/actions_ticket.class.php'; require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticketstats.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; $hookmanager = new HookManager($db); @@ -44,6 +46,7 @@ $msg_id = GETPOST('msg_id', 'int'); $action = GETPOST('action', 'aZ09'); +$socid = 0; if ($user->socid) { $socid = $user->socid; } @@ -70,6 +73,7 @@ $object = new Ticket($db); /* * View */ +$resultboxes = FormOther::getBoxesArea($user, "11"); // Load $resultboxes (selectboxlist + boxactivated + boxlista + boxlistb) $form = new Form($db); $tickesupstatic = new Ticket($db); @@ -77,7 +81,7 @@ $tickesupstatic = new Ticket($db); llxHeader('', $langs->trans('TicketsIndex'), ''); $linkback = ''; -print load_fiche_titre($langs->trans('TicketsIndex'), $linkback, 'ticket'); +print load_fiche_titre($langs->trans('TicketsIndex'), $resultboxes['selectboxlist'], 'ticket'); $dir = ''; @@ -112,7 +116,12 @@ $startyear = $endyear - 1; $WIDTH = (($shownb && $showtot) || !empty($conf->dol_optimize_smallscreen)) ? '100%' : '80%'; $HEIGHT = '200'; -print '<div class="fichecenter"><div class="fichethirdleft">'; +print '<div class="clearboth"></div>'; +print '<div class="fichecenter fichecenterbis">'; + +print '<div class="twocolumns">'; + +print '<div class="firstcolumn fichehalfleft boxhalfleft" id="boxhalfleft">'; /* * Statistics area @@ -120,11 +129,13 @@ print '<div class="fichecenter"><div class="fichethirdleft">'; $tick = array( 'unread' => 0, 'read' => 0, + 'needmoreinfo' => 0, 'answered' => 0, 'assigned' => 0, 'inprogress' => 0, 'waiting' => 0, 'closed' => 0, + 'canceled' => 0, 'deleted' => 0, ); @@ -137,7 +148,7 @@ $sql .= ' WHERE t.entity IN ('.getEntity('ticket').')'; $sql .= dolSqlDateFilter('datec', 0, 0, $endyear); if (!$user->rights->societe->client->voir && !$socid) { - $sql .= " AND t.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + $sql .= " AND t.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id); } // External users restriction @@ -146,7 +157,7 @@ if ($user->socid > 0) { } else { // For internals users, if (!empty($conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY) && !$user->rights->ticket->manage) { - $sql .= " AND t.fk_user_assign = ".$user->id; + $sql .= " AND t.fk_user_assign = ".((int) $user->id); } } $sql .= " GROUP BY t.fk_statut"; @@ -181,7 +192,7 @@ if ($result) { } } - include_once DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; + include DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; $dataseries = array(); $colorseries = array(); @@ -279,8 +290,13 @@ print '</div>'; // Build graphic number of object $data = $stats->getNbByMonthWithPrevYear($endyear, $startyear); -print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; +print '<br>'."\n"; +print $resultboxes['boxlista']; + +print '</div>'."\n"; + +print '<div class="secondcolumn fichehalfright boxhalfright" id="boxhalfright">'; /* * Latest tickets @@ -310,7 +326,7 @@ if ($user->socid > 0) { $sql .= " AND t.fk_soc= ".((int) $user->socid); } else { // Restricted to assigned user only - if ($conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY && !$user->rights->ticket->manage) { + if (!empty($conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY) && !$user->rights->ticket->manage) { $sql .= " AND t.fk_user_assign=".$user->id; } } @@ -398,12 +414,20 @@ if ($result) { dol_print_error($db); } -print '</div></div></div>'; +print $resultboxes['boxlistb']; + +print '</div>'; +print '</div>'; +print '</div>'; + + print '<div style="clear:both"></div>'; $parameters = array('user' => $user); $reshook = $hookmanager->executeHooks('dashboardTickets', $parameters, $object); // Note that $action and $object may have been modified by hook + + // End of page llxFooter(''); $db->close(); diff --git a/htdocs/ticket/list.php b/htdocs/ticket/list.php index 0c6db4a4a2d..53bc1281d5b 100644 --- a/htdocs/ticket/list.php +++ b/htdocs/ticket/list.php @@ -72,7 +72,9 @@ $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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -81,32 +83,44 @@ $pagenext = $page + 1; $object = new Ticket($db); $extrafields = new ExtraFields($db); $diroutputmassaction = $conf->ticket->dir_output.'/temp/massgeneration/'.$user->id; -if ($socid > 0) $hookmanager->initHooks(array('thirdpartyticket')); -elseif ($projectid > 0) $hookmanager->initHooks(array('projectticket')); -else $hookmanager->initHooks(array('ticketlist')); +if ($socid > 0) { + $hookmanager->initHooks(array('thirdpartyticket')); +} elseif ($projectid > 0) { + $hookmanager->initHooks(array('projectticket')); +} else { + $hookmanager->initHooks(array('ticketlist')); +} // Fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "t.datec"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "t.datec"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} -if (GETPOST('search_fk_status', 'alpha') == 'non_closed') $_GET['search_fk_statut'][] = 'openall'; // For backward compatibility +if (GETPOST('search_fk_status', 'alpha') == 'non_closed') { + $_GET['search_fk_statut'][] = 'openall'; // For backward compatibility +} // Initialize array of search criterias $search_all = trim(GETPOSTISSET("search_all") ?GETPOSTISSET("search_all", 'alpha') : GETPOST('sall')); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } $fieldstosearchall['s.name_alias'] = "AliasNameShort"; $fieldstosearchall['s.zip'] = "Zip"; @@ -114,10 +128,11 @@ $fieldstosearchall['s.town'] = "Town"; // Definition of fields for list $arrayfields = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field - if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); + if (!empty($val['visible'])) { + $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); + } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; @@ -136,8 +151,7 @@ if (!$user->rights->ticket->read) { // Store current page url $url_page_current = dol_buildpath('/ticket/list.php', 1); -if ($project_ref) -{ +if ($project_ref) { $tmpproject = new Project($db); $tmpproject->fetch(0, $project_ref); $projectid = $tmpproject->id; @@ -155,25 +169,32 @@ $error = 0; * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $parameters = array(); -if ($socid > 0) $parameters['socid'] = $socid; -if ($projectid > 0) $parameters['projectid'] = $projectid; +if ($socid > 0) { + $parameters['socid'] = $socid; +} +if ($projectid > 0) { + $parameters['projectid'] = $projectid; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($object->fields as $key => $val) - { + 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 + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $toselect = ''; @@ -186,8 +207,7 @@ if (empty($reshook)) $search_dateclose_end = ''; } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -198,26 +218,23 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; // Close records - if (!$error && $massaction == 'close' && $permissiontoadd) - { + if (!$error && $massaction == 'close' && $permissiontoadd) { $objecttmp = new $objectclass($db); - if (!$error) - { + if (!$error) { $db->begin(); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $result = $objecttmp->close($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -225,10 +242,12 @@ if (empty($reshook)) } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -238,27 +257,24 @@ if (empty($reshook)) } // Reopen records - if (!$error && $massaction == 'reopen' && $permissiontoadd) - { + if (!$error && $massaction == 'reopen' && $permissiontoadd) { $objecttmp = new $objectclass($db); - if (!$error) - { + if (!$error) { $db->begin(); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { if ($objecttmp->status == Ticket::STATUS_CLOSED || $objecttmp->status == Ticket::STATUS_CANCELED) { $result = $objecttmp->setStatut(Ticket::STATUS_ASSIGNED); - if ($result < 0) - { + if ($result < 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { $langs->load("errors"); setEventMessages($langs->trans("ErrorObjectMustHaveStatusClosedToBeReOpened", $objecttmp->ref), null, 'errors'); @@ -272,10 +288,12 @@ if (empty($reshook)) } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -307,34 +325,37 @@ $title = $langs->trans('TicketList'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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, $object); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; $sql = preg_replace('/, $/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)"; $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -if ($socid > 0) -{ +if ($socid > 0) { $sql .= " AND t.fk_soc = ".$socid; } -foreach ($search as $key => $val) -{ - if ($key == 'fk_statut' && !empty($search['fk_statut'])) - { +foreach ($search as $key => $val) { + if ($key == 'fk_statut' && !empty($search['fk_statut'])) { $newarrayofstatus = array(); foreach ($search['fk_statut'] as $key2 => $val2) { - if (in_array($val2, array('openall', 'closeall'))) continue; + if (in_array($val2, array('openall', 'closeall'))) { + continue; + } $newarrayofstatus[] = $val2; } if ($search['fk_statut'] == 'openall' || in_array('openall', $search['fk_statut'])) { @@ -349,31 +370,56 @@ foreach ($search as $key => $val) $newarrayofstatus[] = Ticket::STATUS_CLOSED; $newarrayofstatus[] = Ticket::STATUS_CANCELED; } - if (count($newarrayofstatus)) $sql .= natural_search($key, join(',', $newarrayofstatus), 2); + if (count($newarrayofstatus)) { + $sql .= natural_search($key, join(',', $newarrayofstatus), 2); + } continue; } - if ($key == 'fk_user_assign' || $key == 'fk_user_create') - { - if ($search[$key] > 0) $sql .= natural_search($key, $search[$key], 2); + if ($key == 'fk_user_assign' || $key == 'fk_user_create' || $key == 'fk_project') { + if ($search[$key] > 0) { + $sql .= natural_search($key, $search[$key], 2); + } continue; } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], $mode_search); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], $mode_search); + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} +if ($search_societe) { + $sql .= natural_search('s.nom', $search_societe); +} +if ($search_fk_project > 0) { + $sql .= natural_search('fk_project', $search_fk_project, 2); +} +if ($search_date_start) { + $sql .= " AND t.datec >= '".$db->idate($search_date_start)."'"; +} +if ($search_date_end) { + $sql .= " AND t.datec <= '".$db->idate($search_date_end)."'"; +} +if ($search_dateread_start) { + $sql .= " AND t.date_read >= '".$db->idate($search_dateread_start)."'"; +} +if ($search_dateread_end) { + $sql .= " AND t.date_read <= '".$db->idate($search_dateread_end)."'"; +} +if ($search_dateclose_start) { + $sql .= " AND t.date_close >= '".$db->idate($search_dateclose_start)."'"; +} +if ($search_dateclose_end) { + $sql .= " AND t.date_close <= '".$db->idate($search_dateclose_end)."'"; } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); -if ($search_societe) $sql .= natural_search('s.nom', $search_societe); -if ($search_fk_project) $sql .= natural_search('fk_project', $search_fk_project, 2); -if ($search_date_start) $sql .= " AND t.datec >= '".$db->idate($search_date_start)."'"; -if ($search_date_end) $sql .= " AND t.datec <= '".$db->idate($search_date_end)."'"; -if ($search_dateread_start) $sql .= " AND t.date_read >= '".$db->idate($search_dateread_start)."'"; -if ($search_dateread_end) $sql .= " AND t.date_read <= '".$db->idate($search_dateread_end)."'"; -if ($search_dateclose_start) $sql .= " AND t.date_close >= '".$db->idate($search_dateclose_start)."'"; -if ($search_dateclose_end) $sql .= " AND t.date_close <= '".$db->idate($search_dateclose_end)."'"; if (!$user->socid && ($mode == "mine" || (!$user->admin && $conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY))) { $sql .= " AND (t.fk_user_assign = ".$user->id; - if (empty($conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY)) $sql .= " OR t.fk_user_create = ".$user->id; + if (empty($conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY)) { + $sql .= " OR t.fk_user_create = ".$user->id; + } $sql .= ")"; } @@ -388,26 +434,22 @@ $sql .= $db->order($sortfield, $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; } @@ -416,8 +458,7 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/ticket/card.php?id='.$id); @@ -449,30 +490,30 @@ if ($socid && !$projectid && !$project_ref && $user->rights->societe->lire) { print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent tableforfield">'; - // Customer code - if ($socstat->client && !empty($socstat->code_client)) { - print '<tr><td class="titlefield">'; - print $langs->trans('CustomerCode').'</td><td>'; - print $socstat->code_client; - $tmpcheck = $socstat->check_codeclient(); - if ($tmpcheck != 0 && $tmpcheck != -5) { - print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; - } - print '</td>'; - print '</tr>'; - } - // Supplier code - if ($socstat->fournisseur && !empty($socstat->code_fournisseur)) { - print '<tr><td class="titlefield">'; - print $langs->trans('SupplierCode').'</td><td>'; - print $socstat->code_fournisseur; - $tmpcheck = $socstat->check_codefournisseur(); - if ($tmpcheck != 0 && $tmpcheck != -5) { - print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; - } - print '</td>'; - print '</tr>'; - } + // Customer code + if ($socstat->client && !empty($socstat->code_client)) { + print '<tr><td class="titlefield">'; + print $langs->trans('CustomerCode').'</td><td>'; + print showValueWithClipboardCPButton(dol_escape_htmltag($socstat->code_client)); + $tmpcheck = $socstat->check_codeclient(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; + } + print '</td>'; + print '</tr>'; + } + // Supplier code + if ($socstat->fournisseur && !empty($socstat->code_fournisseur)) { + print '<tr><td class="titlefield">'; + print $langs->trans('SupplierCode').'</td><td>'; + print showValueWithClipboardCPButton(dol_escape_htmltag($socstat->code_fournisseur)); + $tmpcheck = $socstat->check_codefournisseur(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; + } + print '</td>'; + print '</tr>'; + } print '</table>'; print '</div>'; @@ -506,15 +547,13 @@ if ($projectid > 0 || $project_ref) { // Title $morehtmlref .= $object->title; // Thirdparty - if ($object->thirdparty->id > 0) - { + if ($object->thirdparty->id > 0) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project'); } $morehtmlref .= '</div>'; // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { + if (!$user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); $object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } @@ -549,39 +588,75 @@ if ($projectid > 0 || $project_ref) { $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ - if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); - else $param .= '&search_'.$key.'='.urlencode($search[$key]); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +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 ($socid) $param .= '&socid='.urlencode($socid); -if ($projectid) $param .= '&projectid='.urlencode($projectid); +if ($socid) { + $param .= '&socid='.urlencode($socid); +} +if ($projectid) { + $param .= '&projectid='.urlencode($projectid); +} -if ($search_date_start) $param .= '&search_date_start='.urlencode($search_date_start); -if ($search_date_end) $param .= '&search_date_end='.urlencode($search_date_end); -if ($search_dateread_start) $param .= '&search_dateread_start='.urlencode($search_dateread_start); -if ($search_dateread_end) $param .= '&search_dateread_end='.urlencode($search_dateread_end); -if ($search_dateclose_start) $param .= '&search_dateclose_start='.urlencode($search_dateclose_start); -if ($search_dateclose_end) $param .= '&search_dateclose_end='.urlencode($search_dateclose_end); +if ($search_date_start) { + $param .= '&search_date_start='.urlencode($search_date_start); +} +if ($search_date_end) { + $param .= '&search_date_end='.urlencode($search_date_end); +} +if ($search_dateread_start) { + $param .= '&search_dateread_start='.urlencode($search_dateread_start); +} +if ($search_dateread_end) { + $param .= '&search_dateread_end='.urlencode($search_dateread_end); +} +if ($search_dateclose_start) { + $param .= '&search_dateclose_start='.urlencode($search_dateclose_start); +} +if ($search_dateclose_end) { + $param .= '&search_dateclose_end='.urlencode($search_dateclose_end); +} // List of mass actions available $arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -if ($user->rights->ticket->write) $arrayofmassactions['close'] = $langs->trans("Close"); -if ($user->rights->ticket->write) $arrayofmassactions['reopen'] = $langs->trans("ReOpen"); -if ($user->rights->ticket->delete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($user->rights->ticket->write) { + $arrayofmassactions['close'] = $langs->trans("Close"); +} +if ($user->rights->ticket->write) { + $arrayofmassactions['reopen'] = $langs->trans("ReOpen"); +} +if ($user->rights->ticket->delete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -589,15 +664,23 @@ print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; print '<input type="hidden" name="mode" value="'.$mode.'" >'; -if ($socid) print '<input type="hidden" name="socid" value="'.$socid.'" >'; -if ($projectid) print '<input type="hidden" name="projectid" value="'.$projectid.'" >'; +if ($socid) { + print '<input type="hidden" name="socid" value="'.$socid.'" >'; +} +if ($projectid) { + print '<input type="hidden" name="projectid" value="'.$projectid.'" >'; +} $url = DOL_URL_ROOT.'/ticket/card.php?action=create'.($socid ? '&socid='.$socid : '').($projectid ? '&origin=projet_project&originid='.$projectid : ''); -if (!empty($socid)) $url .= '&socid='.$socid; +if (!empty($socid)) { + $url .= '&socid='.$socid; +} $newcardbutton = dolGetButtonTitle($langs->trans('NewTicket'), '', 'fa fa-plus-circle', $url, '', $user->rights->ticket->write); $picto = 'ticket'; -if ($socid > 0) $picto = ''; +if ($socid > 0) { + $picto = ''; +} print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $picto, 0, $newcardbutton, '', $limit, 0, 0, 1); @@ -611,9 +694,10 @@ $objecttmp = new Ticket($db); $trackid = 'tic'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } @@ -624,11 +708,13 @@ $moreforfilter.= '</div>';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -645,13 +731,17 @@ print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : // Fields title search // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'fk_statut') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if ($key == 'fk_statut') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } if (!empty($arrayfields['t.'.$key]['checked'])) { if ($key == 'type_code') { print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; @@ -667,28 +757,31 @@ foreach ($object->fields as $key => $val) print '</td>'; } elseif ($key == 'fk_user_assign' || $key == 'fk_user_create') { print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; - print $form->select_dolusers($search[$key], 'search_'.$key, 1, null, 0, '', '', '0', 0, 0, '', 0, '', ($val['css'] ? $val['css'] : 'maxwidth150')); + print $form->select_dolusers($search[$key], 'search_'.$key, 1, null, 0, '', '', '0', 0, 0, '', 0, '', ($val['css'] ? $val['css'] : 'maxwidth125')); print '</td>'; } elseif ($key == 'fk_statut') { $arrayofstatus = array(); $arrayofstatus['openall'] = '-- '.$langs->trans('OpenAll').' --'; - foreach ($object->statuts_short as $key2 => $val2) - { - if ($key2 == Ticket::STATUS_CLOSED) $arrayofstatus['closeall'] = '-- '.$langs->trans('ClosedAll').' --'; + foreach ($object->statuts_short as $key2 => $val2) { + if ($key2 == Ticket::STATUS_CLOSED) { + $arrayofstatus['closeall'] = '-- '.$langs->trans('ClosedAll').' --'; + } $arrayofstatus[$key2] = $val2; } print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; //var_dump($arrayofstatus);var_dump($search['fk_statut']);var_dump(array_values($search[$key])); $selectedarray = null; - if ($search[$key]) $selectedarray = array_values($search[$key]); - print Form::multiselectarray('search_fk_statut', $arrayofstatus, $selectedarray, 0, 0, 'minwidth150', 1, 0, '', '', ''); + if ($search[$key]) { + $selectedarray = array_values($search[$key]); + } + print Form::multiselectarray('search_fk_statut', $arrayofstatus, $selectedarray, 0, 0, 'minwidth100 maxwidth150', 1, 0, '', '', ''); print '</td>'; } elseif ($key == "fk_soc") { print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'"><input type="text" class="flat maxwidth75" name="search_societe" value="'.dol_escape_htmltag($search_societe).'"></td>'; - } elseif ($key == "datec" || $key == 'date_read' || $key == 'date_close'){ + } elseif ($key == "datec" || $key == 'date_read' || $key == 'date_close') { print '<td class="liste_titre center">'; print '<div class="nowrap">'; - switch ($key){ + switch ($key) { case 'datec': print $form->selectDate($search_date_start ?: -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); break; @@ -700,7 +793,7 @@ foreach ($object->fields as $key => $val) } print '</div>'; print '<div class="nowrap">'; - switch ($key){ + switch ($key) { case 'datec': print $form->selectDate($search_date_end ?: -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")); break; @@ -712,13 +805,15 @@ foreach ($object->fields as $key => $val) } print '</div>'; print '</td>'; - } - else { + } else { print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - elseif (strpos($val['type'], 'integer:') === 0) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { + print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } print '</td>'; } } @@ -741,15 +836,18 @@ print '</tr>'."\n"; // Fields title label // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'fk_statut' || $key == 'severity_code') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'fk_statut' || $key == 'severity_code') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, '', $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -765,11 +863,11 @@ print '</tr>'."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -779,70 +877,83 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co $i = 0; $totalarray = array(); $cacheofoutputfield = array(); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->id = $obj->rowid; - foreach ($object->fields as $key => $val) - { - if (property_exists($obj, $key)) $object->$key = $obj->$key; + foreach ($object->fields as $key => $val) { + if (property_exists($obj, $key)) { + $object->$key = $obj->$key; + } } $langs->load("ticket"); // Show here line of result print '<tr class="oddeven">'; - foreach ($object->fields as $key => $val) - { + foreach ($object->fields as $key => $val) { $cssforfield = ''; - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - if (in_array($key, array('ref', 'fk_project'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowraponall'; - if ($key == 'fk_statut' || $key == 'severity_code') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } + if (in_array($key, array('ref', 'fk_project'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowraponall'; + } + if ($key == 'fk_statut' || $key == 'severity_code') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td'; - if ($cssforfield || $val['css']) print ' class="'; + if ($cssforfield || $val['css']) { + print ' class="'; + } print $cssforfield; - if ($cssforfield && $val['css']) print ' '; + if ($cssforfield && $val['css']) { + print ' '; + } print $val['css']; - if ($cssforfield || $val['css']) print '"'; + if ($cssforfield || $val['css']) { + print '"'; + } print '>'; - if ($key == 'fk_statut') print $object->getLibStatut(5); - elseif ($key == 'subject') { + if ($key == 'fk_statut') { + print $object->getLibStatut(5); + } elseif ($key == 'subject') { $s = $obj->subject; print '<span title="'.$s.'">'; print $s; print '</span>'; - } - elseif ($key == 'type_code') { + } elseif ($key == 'type_code') { $s = $langs->getLabelFromKey($db, 'TicketTypeShort'.$object->type_code, 'c_ticket_type', 'code', 'label', $object->type_code); print '<span title="'.$s.'">'; print $s; print '</span>'; - } - elseif ($key == 'category_code') { + } elseif ($key == 'category_code') { $s = $langs->getLabelFromKey($db, 'TicketCategoryShort'.$object->category_code, 'c_ticket_category', 'code', 'label', $object->category_code); print '<span title="'.$s.'">'; print $s; print '</span>'; - } - elseif ($key == 'severity_code') { + } elseif ($key == 'severity_code') { $s = $langs->getLabelFromKey($db, 'TicketSeverityShort'.$object->severity_code, 'c_ticket_severity', 'code', 'label', $object->severity_code); print '<span title="'.$s.'">'; print $s; print '</span>'; - } - elseif ($key == 'tms') print dol_print_date($db->jdate($obj->$key), 'dayhour', 'tzuser'); - elseif ($key == 'fk_user_create') { + } elseif ($key == 'tms') { + print dol_print_date($db->jdate($obj->$key), 'dayhour', 'tzuser'); + } elseif ($key == 'fk_user_create') { if ($object->fk_user_create > 0) { $user_create->fetch($object->fk_user_create); print $user_create->getNomUrl(-1); } - } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); - else { // Example: key=fk_soc, obj->key=123 val=array('type'=>'integer', ... + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); + } else { // Example: key=fk_soc, obj->key=123 val=array('type'=>'integer', ... $tmp = explode(':', $val['type']); if ($tmp[0] == 'integer' && !empty($tmp[1]) && class_exists($tmp[1])) { // It is a type of an foreign field. We will try to reduce the number of fetch that the showOutputField is making. @@ -860,10 +971,13 @@ while ($i < min($num, $limit)) } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $obj->$key; } } @@ -876,14 +990,17 @@ while ($i < min($num, $limit)) print $hookmanager->resPrint; // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'; @@ -895,10 +1012,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } @@ -916,10 +1036,11 @@ print '</form>'."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/ticket/messaging.php b/htdocs/ticket/messaging.php index 49f15412965..527b28c8fac 100644 --- a/htdocs/ticket/messaging.php +++ b/htdocs/ticket/messaging.php @@ -46,16 +46,21 @@ $sortorder = GETPOST("sortorder", 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = is_numeric($page) ? $page : 0; $page = $page == -1 ? 0 : $page; -if (!$sortfield) $sortfield = "a.datep,a.id"; -if (!$sortorder) $sortorder = "desc"; +if (!$sortfield) { + $sortfield = "a.datep,a.id"; +} +if (!$sortorder) { + $sortorder = "desc"; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (GETPOST('actioncode', 'array')) -{ +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)); } @@ -82,8 +87,7 @@ if (!$user->rights->ticket->read) { accessforbidden(); } // restrict access for externals users -if ($user->socid > 0 && ($object->fk_soc != $user->socid)) -{ +if ($user->socid > 0 && ($object->fk_soc != $user->socid)) { accessforbidden(); } // or for unauthorized internals users @@ -99,17 +103,17 @@ if (!$user->socid && ($conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY && $object- $parameters = array('id'=>$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)) -{ +if (empty($reshook)) { // Set view style $_SESSION['ticket-view-type'] = "messaging"; } // Purge search criteria -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers $actioncode = ''; $search_agenda_label = ''; } @@ -125,7 +129,9 @@ $userstat = new User($db); $formticket = new FormTicket($db); $title = $langs->trans("Ticket").' - '.$object->ref.' '.$object->name; -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/ticketnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Info"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/ticketnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->ref.' '.$object->name.' - '.$langs->trans("Info"); +} $help_url = 'FR:DocumentationModuleTicket'; llxHeader('', $title, $help_url); @@ -166,8 +172,7 @@ if (!empty($object->origin_email)) { } // Thirdparty -if (!empty($conf->societe->enabled)) -{ +if (!empty($conf->societe->enabled)) { $morehtmlref .= '<br>'.$langs->trans('ThirdParty'); /*if ($action != 'editcustomer' && $object->fk_statut < 8 && !$user->socid && $user->rights->ticket->write) { $morehtmlref.='<a class="editfielda" href="' . $url_page_current . '?action=editcustomer&amp;track_id=' . $object->track_id . '">' . img_edit($langs->transnoentitiesnoconv('Edit'), 1) . '</a>'; @@ -181,12 +186,10 @@ if (!empty($conf->societe->enabled)) } // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project'); - if ($user->rights->ticket->write) - { + if ($user->rights->ticket->write) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a>'; $morehtmlref .= ' : '; @@ -224,11 +227,14 @@ print dol_get_fiche_end(); print '<br>'; -if (!empty($object->id)) -{ +if (!empty($object->id)) { $param = '&id='.$object->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; + } $morehtmlright = ''; diff --git a/htdocs/ticket/stats/index.php b/htdocs/ticket/stats/index.php index 045943bbfda..9f6e1cc5471 100644 --- a/htdocs/ticket/stats/index.php +++ b/htdocs/ticket/stats/index.php @@ -30,15 +30,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; $WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); -if (!$user->rights->ticket->read) accessforbidden(); +if (!$user->rights->ticket->read) { + accessforbidden(); +} $object_status = GETPOST('object_status', 'intcomma'); $userid = GETPOST('userid', 'int'); $socid = GETPOST('socid', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -70,7 +71,9 @@ print load_fiche_titre($title, '', 'ticket'); dol_mkdir($dir); $stats = new TicketStats($db, $socid, ($userid > 0 ? $userid : 0)); -if ($object_status != '' && $object_status >= -1) $stats->where .= ' AND fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +if ($object_status != '' && $object_status >= -1) { + $stats->where .= ' AND fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +} // Build graphic number of object @@ -80,8 +83,7 @@ $data = $stats->getNbByMonthWithPrevYear($endyear, $startyear); // $data = array(array('Lib',val1,val2,val3),...) -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filenamenb = $dir.'/ticketsnbinyear-'.$user->id.'-'.$year.'.png'; $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=ticketstats&file=ticketsnbinyear-'.$user->id.'-'.$year.'.png'; } else { @@ -91,12 +93,10 @@ if (!$user->rights->societe->client->voir || $user->socid) $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -119,8 +119,7 @@ $data = $stats->getAmountByMonthWithPrevYear($endyear, $startyear); //var_dump($data); // $data = array(array('Lib',val1,val2,val3),...) -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filenameamount = $dir.'/ticketsamountinyear-'.$user->id.'-'.$year.'.png'; $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=ticketstats&file=ticketsamountinyear-'.$user->id.'-'.$year.'.png'; } else { @@ -130,12 +129,10 @@ if (!$user->rights->societe->client->voir || $user->socid) $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px2->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -156,8 +153,7 @@ if (!$mesg) $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filename_avg = $dir.'/ticketsaverage-'.$user->id.'-'.$year.'.png'; $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=ticketstats&file=ticketsaverage-'.$user->id.'-'.$year.'.png'; } else { @@ -167,12 +163,10 @@ if (!$user->rights->societe->client->voir || $user->socid) $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px3->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -200,7 +194,9 @@ foreach ($data as $val) { $arrayyears[$val['year']] = $val['year']; } } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; $head = array(); @@ -239,8 +235,12 @@ print $form->selectarray('object_status', $liststatus, GETPOST('object_status', print '</td></tr>'; // Year print '<tr><td class="left">'.$langs->trans("Year").'</td><td class="left">'; -if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; -if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} +if (!in_array($nowyear, $arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print '</td></tr>'; @@ -263,11 +263,9 @@ print '<td class="right">%</td>'; print '</tr>'; $oldyear = 0; -foreach ($data as $val) -{ +foreach ($data as $val) { $year = $val['year']; - while (!empty($year) && $oldyear > $year + 1) - { // If we have empty year + while (!empty($year) && $oldyear > $year + 1) { // If we have empty year $oldyear--; print '<tr class="oddeven" height="24">'; @@ -303,7 +301,9 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; // Show graphs print '<table class="border centpercent"><tr class="pair nohover"><td class="center">'; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); print "<br>\n"; //print $px2->show(); diff --git a/htdocs/ticket/tpl/linkedobjectblock.tpl.php b/htdocs/ticket/tpl/linkedobjectblock.tpl.php index 572ffc0672f..17da4cd2db5 100644 --- a/htdocs/ticket/tpl/linkedobjectblock.tpl.php +++ b/htdocs/ticket/tpl/linkedobjectblock.tpl.php @@ -16,8 +16,7 @@ * along with this program. If not, see <https://www.gnu.org/licenses/>. */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -38,52 +37,54 @@ $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'datec', 'desc', 0, 0, 1 $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - <tr class="<?php echo $trclass; ?>" > - <td class="linkedcol-element" ><?php echo $langs->trans("Ticket"); ?> - <?php if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) print '<a class="objectlinked_importbtn" href="'.$objectlink->getNomUrl(0, '', 0, 1).'&amp;action=selectlines" data-element="'.$objectlink->element.'" data-id="'.$objectlink->id.'" > <i class="fa fa-indent"></i> </a'; ?> - </td> - <td class="linkedcol-name nowraponall" ><?php echo $objectlink->getNomUrl(1); ?></td> - <td class="linkedcol-ref center"><?php echo $objectlink->ref_client; ?></td> - <td class="linkedcol-date center"><?php echo dol_print_date($objectlink->datec, 'day'); ?></td> - <?php + <tr class="<?php echo $trclass; ?>" > + <td class="linkedcol-element" ><?php echo $langs->trans("Ticket"); ?> + <?php if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) { + print '<a class="objectlinked_importbtn" href="'.$objectlink->getNomUrl(0, '', 0, 1).'&amp;action=selectlines" data-element="'.$objectlink->element.'" data-id="'.$objectlink->id.'" > <i class="fa fa-indent"></i> </a'; + } ?> + </td> + <td class="linkedcol-name nowraponall" ><?php echo $objectlink->getNomUrl(1); ?></td> + <td class="linkedcol-ref center"><?php echo $objectlink->ref_client; ?></td> + <td class="linkedcol-date center"><?php echo dol_print_date($objectlink->datec, 'day'); ?></td> + <?php //$objectlink->socid = $objectlink->fk_soc; //$objectlink->fetch_thirdparty(); ?> - <td class="linkedcol-amount right"><?php //echo $objectlink->thirdparty->getNomUrl(1); ?></td> - <td class="linkedcol-statut right"><?php echo $objectlink->getLibStatut(3); ?></td> - <td class="linkedcol-action right"> - <?php + <td class="linkedcol-amount right"><?php //echo $objectlink->thirdparty->getNomUrl(1); ?></td> + <td class="linkedcol-statut right"><?php echo $objectlink->getLibStatut(3); ?></td> + <td class="linkedcol-action right"> + <?php // For now, shipments must stay linked to order, so link is not deletable if ($object->element != 'shipping') { ?> - <a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a> - <?php + <a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a> + <?php } ?> - </td> + </td> </tr> <?php } -if (count($linkedObjectBlock) > 1) -{ +if (count($linkedObjectBlock) > 1) { ?> - <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> - <td><?php echo $langs->trans("Total"); ?></td> - <td></td> - <td class="center"></td> - <td class="center"></td> - <td class="right"><?php echo price($total); ?></td> - <td class="right"></td> - <td class="right"></td> - </tr> - <?php + <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> + <td><?php echo $langs->trans("Total"); ?></td> + <td></td> + <td class="center"></td> + <td class="center"></td> + <td class="right"><?php echo price($total); ?></td> + <td class="right"></td> + <td class="right"></td> + </tr> + <?php } print "<!-- END PHP TEMPLATE -->\n"; diff --git a/htdocs/user/admin/group_extrafields.php b/htdocs/user/admin/group_extrafields.php index fd71d43d4f0..627af1c3b9d 100644 --- a/htdocs/user/admin/group_extrafields.php +++ b/htdocs/user/admin/group_extrafields.php @@ -38,13 +38,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 = 'usergroup'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -79,8 +83,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -93,8 +96,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -106,8 +108,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/user/admin/user_extrafields.php b/htdocs/user/admin/user_extrafields.php index 45d645ce3dd..25141ed4fcd 100644 --- a/htdocs/user/admin/user_extrafields.php +++ b/htdocs/user/admin/user_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 = 'user'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -78,8 +82,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -92,8 +95,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -105,8 +107,7 @@ if ($action == 'create') /* Editing an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/user/agenda_extsites.php b/htdocs/user/agenda_extsites.php index 8d320a839ef..3faf6dc770c 100644 --- a/htdocs/user/agenda_extsites.php +++ b/htdocs/user/agenda_extsites.php @@ -41,7 +41,9 @@ $actiontest = GETPOST('test', 'alpha'); $actionsave = GETPOST('save', 'alpha'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'useragenda'; // To manage different context of search -if (empty($conf->global->AGENDA_EXT_NB)) $conf->global->AGENDA_EXT_NB = 5; +if (empty($conf->global->AGENDA_EXT_NB)) { + $conf->global->AGENDA_EXT_NB = 5; +} $MAXAGENDA = $conf->global->AGENDA_EXT_NB; // List of available colors @@ -55,14 +57,17 @@ $object->getrights(); // Security check $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} $feature2 = (($socid && $user->rights->user->self->creer) ? '' : 'user'); $result = restrictedArea($user, 'user', $id, 'user&user', $feature2); // If user is not user that read and no permission to read other users, we stop -if (($object->id != $user->id) && (!$user->rights->user->user->lire)) - accessforbidden(); +if (($object->id != $user->id) && (!$user->rights->user->user->lire)) { + accessforbidden(); +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('usercard', 'useragenda', 'globalcard')); @@ -73,7 +78,9 @@ $hookmanager->initHooks(array('usercard', 'useragenda', 'globalcard')); $parameters = array('id'=>$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)) { if ($actionsave) { @@ -167,8 +174,12 @@ print '<br>'; print '<span class="opacitymedium">'.$langs->trans("AgendaExtSitesDesc")."</span><br>\n"; print "<br>\n"; -$selectedvalue = $conf->global->AGENDA_DISABLE_EXT; -if ($selectedvalue == 1) $selectedvalue = 0; else $selectedvalue = 1; +$selectedvalue = empty($conf->global->AGENDA_DISABLE_EXT) ? 0 : $conf->global->AGENDA_DISABLE_EXT; +if ($selectedvalue == 1) { + $selectedvalue = 0; +} else { + $selectedvalue = 1; +} print '<div class="div-table-responsive">'; @@ -183,28 +194,30 @@ print '<td class="right">'.$langs->trans("Color").'</td>'; print "</tr>"; $i = 1; -while ($i <= $MAXAGENDA) -{ +while ($i <= $MAXAGENDA) { $key = $i; $name = 'AGENDA_EXT_NAME_'.$id.'_'.$key; $src = 'AGENDA_EXT_SRC_'.$id.'_'.$key; $offsettz = 'AGENDA_EXT_OFFSETTZ_'.$id.'_'.$key; $color = 'AGENDA_EXT_COLOR_'.$id.'_'.$key; - print '<tr class="oddeven">'; // Nb print '<td class="maxwidth50onsmartphone">'.$langs->trans("AgendaExtNb", $key)."</td>"; // Name - print '<td class="maxwidth50onsmartphone"><input type="text" class="flat hideifnotset minwidth100" name="AGENDA_EXT_NAME_'.$id.'_'.$key.'" value="'.(GETPOST('AGENDA_EXT_NAME_'.$id.'_'.$key) ?GETPOST('AGENDA_EXT_NAME_'.$id.'_'.$key) : $object->conf->$name).'"></td>'; + $name_value = (GETPOST('AGENDA_EXT_NAME_'.$id.'_'.$key) ?GETPOST('AGENDA_EXT_NAME_'.$id.'_'.$key) : (empty($object->conf->$name) ? '' : $object->conf->$name)); + print '<td class="maxwidth50onsmartphone"><input type="text" class="flat hideifnotset minwidth100" name="AGENDA_EXT_NAME_'.$id.'_'.$key.'" value="'.$name_value.'"></td>'; // URL - print '<td class="maxwidth50onsmartphone"><input type="url" class="flat hideifnotset" name="AGENDA_EXT_SRC_'.$id.'_'.$key.'" value="'.(GETPOST('AGENDA_EXT_SRC_'.$id.'_'.$key) ?GETPOST('AGENDA_EXT_SRC_'.$id.'_'.$key) : $object->conf->$src).'"></td>'; + $src_value = (GETPOST('AGENDA_EXT_SRC_'.$id.'_'.$key) ?GETPOST('AGENDA_EXT_SRC_'.$id.'_'.$key) : (empty($object->conf->$src) ? '' : $object->conf->$src)); + print '<td class="maxwidth50onsmartphone"><input type="url" class="flat hideifnotset" name="AGENDA_EXT_SRC_'.$id.'_'.$key.'" value="'.$src_value.'"></td>'; // Offset TZ - print '<td><input type="text" class="flat hideifnotset" name="AGENDA_EXT_OFFSETTZ_'.$id.'_'.$key.'" value="'.(GETPOST('AGENDA_EXT_OFFSETTZ_'.$id.'_'.$key) ?GETPOST('AGENDA_EXT_OFFSETTZ_'.$id.'_'.$key) : $object->conf->$offsettz).'" size="1"></td>'; + $offsettz_value = (GETPOST('AGENDA_EXT_OFFSETTZ_'.$id.'_'.$key) ? GETPOST('AGENDA_EXT_OFFSETTZ_'.$id.'_'.$key) : (empty($object->conf->$offsettz) ? 0 : $object->conf->$offsettz)); + print '<td><input type="text" class="flat hideifnotset" name="AGENDA_EXT_OFFSETTZ_'.$id.'_'.$key.'" value="'.$offsettz_value.'" size="1"></td>'; // Color (Possible colors are limited by Google) print '<td class="nowrap right">'; //print $formadmin->selectColor($conf->global->$color, "google_agenda_color".$key, $colorlist); - print $formother->selectColor((GETPOST("AGENDA_EXT_COLOR_".$id.'_'.$key) ?GETPOST("AGENDA_EXT_COLOR_".$id.'_'.$key) : $object->conf->$color), "AGENDA_EXT_COLOR_".$id.'_'.$key, 'extsitesconfig', 1, '', 'hideifnotset'); + $color_value = (GETPOST("AGENDA_EXT_COLOR_".$id.'_'.$key) ?GETPOST("AGENDA_EXT_COLOR_".$id.'_'.$key) : (empty($object->conf->$color) ? 'ffffff' : $object->conf->$color)); + print $formother->selectColor($color_value, "AGENDA_EXT_COLOR_".$id.'_'.$key, 'extsitesconfig', 1, '', 'hideifnotset'); print '</td>'; print "</tr>"; $i++; diff --git a/htdocs/user/bank.php b/htdocs/user/bank.php index 20369e37d69..df5757992f0 100644 --- a/htdocs/user/bank.php +++ b/htdocs/user/bank.php @@ -6,6 +6,7 @@ * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr> * Copyright (C) 2015-2016 Marcos García <marcosgdf@gmail.com> * Copyright (C) 2015 Alexandre Spangaro <aspangaro@open-dsi.fr> + * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -32,9 +33,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/userbankaccount.class.php'; -if (!empty($conf->holiday->enabled)) require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; -if (!empty($conf->expensereport->enabled)) require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; -if (!empty($conf->salaries->enabled)) require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; +if (!empty($conf->holiday->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; +} +if (!empty($conf->expensereport->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +} +if (!empty($conf->salaries->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; +} // Load translation files required by page $langs->loadLangs(array('companies', 'commercial', 'banks', 'bills', 'trips', 'holiday', 'salaries')); @@ -47,35 +54,44 @@ $cancel = GETPOST('cancel', 'alpha'); // Security check $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} $feature2 = (($socid && $user->rights->user->self->creer) ? '' : 'user'); // Ok if user->rights->salaries->read or user->rights->hrm->read //$result = restrictedArea($user, 'salaries|hrm', $id, 'user&user', $feature2); $ok = false; -if ($user->id == $id) $ok = true; // A user can always read its own card -if (!empty($user->rights->salaries->read)) $ok = true; -if (!empty($user->rights->hrm->read)) $ok = true; -if (!empty($user->rights->expensereport->lire) && ($user->id == $object->id || $user->rights->expensereport->readall)) $ok = true; -if (!$ok) -{ +if ($user->id == $id) { + $ok = true; // A user can always read its own card +} +if (!empty($user->rights->salaries->read)) { + $ok = true; +} +if (!empty($user->rights->hrm->read)) { + $ok = true; +} +if (!empty($user->rights->expensereport->lire) && ($user->id == $object->id || $user->rights->expensereport->readall)) { + $ok = true; +} +if (!$ok) { accessforbidden(); } $object = new User($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref, '', 1); $object->getrights(); } $account = new UserBankAccount($db); -if (!$bankid) -{ +if (!$bankid) { $account->fetch(0, '', $id); } else { $account->fetch($bankid); } -if (empty($account->userid)) $account->userid = $object->id; +if (empty($account->userid)) { + $account->userid = $object->id; +} $permissiontoaddbankaccount = (!empty($user->rights->salaries->write) || !empty($user->rights->hrm->employee->write) || !empty($user->rights->user->creer)); @@ -84,8 +100,7 @@ $permissiontoaddbankaccount = (!empty($user->rights->salaries->write) || !empty( * Actions */ -if ($action == 'add' && !$cancel) -{ +if ($action == 'add' && !$cancel) { $account->userid = $object->id; $account->bank = GETPOST('bank', 'alpha'); @@ -103,8 +118,7 @@ if ($action == 'add' && !$cancel) $result = $account->create($user); - if (!$result) - { + if (!$result) { setEventMessages($account->error, $account->errors, 'errors'); $action = 'edit'; // Force chargement page edition } else { @@ -113,52 +127,51 @@ if ($action == 'add' && !$cancel) } } -if ($action == 'update' && !$cancel) -{ +if ($action == 'update' && !$cancel) { $account->userid = $object->id; /* - if ($action == 'update' && !$cancel) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + if ($action == 'update' && !$cancel) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if ($canedituser) // Case we can edit all field - { - $error = 0; + if ($canedituser) // Case we can edit all field + { + $error = 0; - if (!$error) - { - $objectuser->fetch($id); + if (!$error) + { + $objectuser->fetch($id); - $objectuser->oldcopy = clone $objectuser; + $objectuser->oldcopy = clone $objectuser; - $db->begin(); + $db->begin(); - $objectuser->default_range = GETPOST('default_range'); - $objectuser->default_c_exp_tax_cat = GETPOST('default_c_exp_tax_cat'); + $objectuser->default_range = GETPOST('default_range'); + $objectuser->default_c_exp_tax_cat = GETPOST('default_c_exp_tax_cat'); - if (!$error) { - $ret = $objectuser->update($user); - if ($ret < 0) { - $error++; - if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $langs->load("errors"); - setEventMessages($langs->trans("ErrorLoginAlreadyExists", $objectuser->login), null, 'errors'); - } else { - setEventMessages($objectuser->error, $objectuser->errors, 'errors'); - } - } - } + if (!$error) { + $ret = $objectuser->update($user); + if ($ret < 0) { + $error++; + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + $langs->load("errors"); + setEventMessages($langs->trans("ErrorLoginAlreadyExists", $objectuser->login), null, 'errors'); + } else { + setEventMessages($objectuser->error, $objectuser->errors, 'errors'); + } + } + } - if (!$error && !count($objectuser->errors)) { - setEventMessages($langs->trans("UserModified"), null, 'mesgs'); - $db->commit(); - } else { - $db->rollback(); - } - } - } - }*/ + if (!$error && !count($objectuser->errors)) { + setEventMessages($langs->trans("UserModified"), null, 'mesgs'); + $db->commit(); + } else { + $db->rollback(); + } + } + } + }*/ $account->bank = GETPOST('bank', 'alpha'); $account->label = GETPOST('label', 'alpha'); @@ -188,28 +201,36 @@ if ($action == 'update' && !$cancel) if ($action == 'setpersonal_email') { $object->personal_email = (string) GETPOST('personal_email', 'alphanohtml'); $result = $object->update($user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // update personal mobile if ($action == 'setpersonal_mobile') { $object->personal_mobile = (string) GETPOST('personal_mobile', 'alphanohtml'); $result = $object->update($user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // update default_c_exp_tax_cat if ($action == 'setdefault_c_exp_tax_cat') { $object->default_c_exp_tax_cat = GETPOST('default_c_exp_tax_cat', 'int'); $result = $object->update($user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // update default range if ($action == 'setdefault_range') { $object->default_range = GETPOST('default_range', 'int'); $result = $object->update($user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } @@ -226,16 +247,14 @@ llxHeader(null, $langs->trans("BankAccounts")); $head = user_prepare_head($object); -if ($id && $bankid && $action == 'edit' && $user->rights->user->user->creer) -{ +if ($id && $bankid && $action == 'edit' && $user->rights->user->user->creer) { print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="id" value="'.GETPOST("id", 'int').'">'; print '<input type="hidden" name="bankid" value="'.$bankid.'">'; } -if ($id && $action == 'create' && $user->rights->user->user->creer) -{ +if ($id && $action == 'create' && $user->rights->user->user->creer) { print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; @@ -244,8 +263,7 @@ if ($id && $action == 'create' && $user->rights->user->user->creer) // View -if ($action != 'edit' && $action != 'create') // If not bank account yet, $account may be empty -{ +if ($action != 'edit' && $action != 'create') { // If not bank account yet, $account may be empty $title = $langs->trans("User"); print dol_get_fiche_head($head, 'bank', $title, -1, 'user'); @@ -283,8 +301,7 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco print '</td>'; print '</tr>'; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) - { + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { print '<tr class="nowrap">'; print '<td>'; print $form->editfieldkey("DefaultCategoryCar", 'default_c_exp_tax_cat', $object->default_c_exp_tax_cat, $object, $user->rights->user->user->creer); @@ -338,38 +355,36 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco // Latest payments of salaries if (!empty($conf->salaries->enabled) && $user->rights->salaries->read && (in_array($object->id, $childids) || $object->id == $user->id) - ) - { - $salary = new PaymentSalary($db); + ) { + $payment_salary = new PaymentSalary($db); - $sql = "SELECT ps.rowid, ps.datesp, ps.dateep, ps.amount"; + $sql = "SELECT ps.rowid, s.datesp, s.dateep, ps.amount"; $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as ps"; - $sql .= " WHERE ps.fk_user = ".$object->id; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."salary as s ON (s.rowid = ps.fk_salary)"; + $sql .= " WHERE s.fk_user = ".$object->id; $sql .= " AND ps.entity = ".$conf->entity; - $sql .= " ORDER BY ps.datesp DESC"; + $sql .= " ORDER BY ps.rowid DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; - print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastSalaries", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/salaries/list.php?search_user='.$object->login.'">'.$langs->trans("AllSalaries").'<span class="badge marginleftonlyshort">'.$num.'</span></a></td>'; - print '</tr></table></td>'; - print '</tr>'; + print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastSalaries", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/salaries/payments.php?search_user='.$object->login.'">'.$langs->trans("AllSalaries").'<span class="badge marginleftonlyshort">'.$num.'</span></a></td>'; + print '</tr></table></td>'; + print '</tr>'; $i = 0; - while ($i < $num && $i < $MAXLIST) - { + while ($i < $num && $i < $MAXLIST) { $objp = $db->fetch_object($resql); print '<tr class="oddeven">'; print '<td class="nowraponall">'; - $salary->id = $objp->rowid; - $salary->ref = $objp->rowid; - print $salary->getNomUrl(1); + $payment_salary->id = $objp->rowid; + $payment_salary->ref = $objp->rowid; + print $payment_salary->getNomUrl(1); print '</td>'; print '<td class="right" width="80px">'.dol_print_date($db->jdate($objp->datesp), 'day')."</td>\n"; @@ -381,7 +396,9 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco } $db->free($resql); - if ($num <= 0) print '<td colspan="4" class="opacitymedium">'.$langs->trans("None").'</a>'; + if ($num <= 0) { + print '<td colspan="4" class="opacitymedium">'.$langs->trans("None").'</a>'; + } print "</table>"; } else { dol_print_error($db); @@ -393,8 +410,7 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco */ if (!empty($conf->holiday->enabled) && ($user->rights->holiday->readall || ($user->rights->holiday->read && $object->id == $user->id)) - ) - { + ) { $holiday = new Holiday($db); $sql = "SELECT h.rowid, h.statut as status, h.fk_type, h.date_debut, h.date_fin, h.halfday"; @@ -404,20 +420,18 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco $sql .= " ORDER BY h.date_debut DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; - print '<td colspan="4"><table class="nobordernopadding centpercent"><tr><td>'.$langs->trans("LastHolidays", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/holiday/list.php?id='.$object->id.'">'.$langs->trans("AllHolidays").'<span class="badge marginleftonlyshort">'.$num.'</span></a></td>'; - print '</tr></table></td>'; - print '</tr>'; + print '<td colspan="4"><table class="nobordernopadding centpercent"><tr><td>'.$langs->trans("LastHolidays", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/holiday/list.php?id='.$object->id.'">'.$langs->trans("AllHolidays").'<span class="badge marginleftonlyshort">'.$num.'</span></a></td>'; + print '</tr></table></td>'; + print '</tr>'; $i = 0; - while ($i < $num && $i < $MAXLIST) - { + while ($i < $num && $i < $MAXLIST) { $objp = $db->fetch_object($resql); $holiday->id = $objp->rowid; @@ -436,7 +450,9 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco } $db->free($resql); - if ($num <= 0) print '<td colspan="4" class="opacitymedium">'.$langs->trans("None").'</a>'; + if ($num <= 0) { + print '<td colspan="4" class="opacitymedium">'.$langs->trans("None").'</a>'; + } print "</table>"; } else { dol_print_error($db); @@ -448,8 +464,7 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco */ if (!empty($conf->expensereport->enabled) && ($user->rights->expensereport->readall || ($user->rights->expensereport->lire && $object->id == $user->id)) - ) - { + ) { $exp = new ExpenseReport($db); $sql = "SELECT e.rowid, e.ref, e.fk_statut as status, e.date_debut, e.total_ttc"; @@ -459,20 +474,18 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco $sql .= " ORDER BY e.date_debut DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; - print '<td colspan="4"><table class="nobordernopadding centpercent"><tr><td>'.$langs->trans("LastExpenseReports", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/expensereport/list.php?id='.$object->id.'">'.$langs->trans("AllExpenseReports").'<span class="badge marginleftonlyshort">'.$num.'</span></a></td>'; - print '</tr></table></td>'; - print '</tr>'; + print '<td colspan="4"><table class="nobordernopadding centpercent"><tr><td>'.$langs->trans("LastExpenseReports", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/expensereport/list.php?id='.$object->id.'">'.$langs->trans("AllExpenseReports").'<span class="badge marginleftonlyshort">'.$num.'</span></a></td>'; + print '</tr></table></td>'; + print '</tr>'; $i = 0; - while ($i < $num && $i < $MAXLIST) - { + while ($i < $num && $i < $MAXLIST) { $objp = $db->fetch_object($resql); $exp->id = $objp->rowid; @@ -490,7 +503,9 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco } $db->free($resql); - if ($num <= 0) print '<td colspan="4" class="opacitymedium">'.$langs->trans("None").'</a>'; + if ($num <= 0) { + print '<td colspan="4" class="opacitymedium">'.$langs->trans("None").'</a>'; + } print "</table>"; } else { dol_print_error($db); @@ -589,8 +604,7 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco } - if ($account->id == 0) - { + if ($account->id == 0) { $colspan = 6; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoBANRecord").'</td></tr>'; } @@ -600,8 +614,7 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco } // Edit -if ($id && ($action == 'edit' || $action == 'create') && $user->rights->user->user->creer) -{ +if ($id && ($action == 'edit' || $action == 'create') && $user->rights->user->user->creer) { $title = $langs->trans("User"); print dol_get_fiche_head($head, 'bank', $title, 0, 'user'); @@ -679,9 +692,13 @@ if ($id && ($action == 'edit' || $action == 'create') && $user->rights->user->us print '</div>'; } -if ($id && $action == 'edit' && $user->rights->user->user->creer) print '</form>'; +if ($id && $action == 'edit' && $user->rights->user->user->creer) { + print '</form>'; +} -if ($id && $action == 'create' && $user->rights->user->user->creer) print '</form>'; +if ($id && $action == 'create' && $user->rights->user->user->creer) { + print '</form>'; +} // End of page llxFooter(); diff --git a/htdocs/user/card.php b/htdocs/user/card.php index c5820db60b7..a72dde04fb1 100644 --- a/htdocs/user/card.php +++ b/htdocs/user/card.php @@ -13,7 +13,7 @@ * Copyright (C) 2015 Ari Elbaz (elarifr) <github@accedinfo.com> * Copyright (C) 2015-2018 Charlene Benke <charlie@patas-monkey.com> * Copyright (C) 2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr> - * Copyright (C) 2018-2020 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr> * Copyright (C) 2018 David Beniamine <David.Beniamine@Tetras-Libre.fr> * * This program is free software; you can redistribute it and/or modify @@ -48,10 +48,18 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; -if (!empty($conf->ldap->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; -if (!empty($conf->adherent->enabled)) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; -if (!empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; -if (!empty($conf->stock->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; +if (!empty($conf->ldap->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; +} +if (!empty($conf->adherent->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; +} +if (!empty($conf->categorie->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +} +if (!empty($conf->stock->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; +} $id = GETPOST('id', 'int'); $action = GETPOST('action', 'aZ09'); @@ -74,15 +82,13 @@ $canedituser = (!empty($user->admin) || $user->rights->user->user->creer); $candisableuser = (!empty($user->admin) || $user->rights->user->user->supprimer); $canreadgroup = $canreaduser; $caneditgroup = $canedituser; -if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $canreadgroup = (!empty($user->admin) || $user->rights->user->group_advance->read); $caneditgroup = (!empty($user->admin) || $user->rights->user->group_advance->write); } // Define value to know what current user can do on properties of edited user -if ($id) -{ +if ($id) { // $user est le user qui edite, $id est l'id de l'utilisateur edite $caneditfield = ((($user->id == $id) && $user->rights->user->self->creer) || (($user->id != $id) && $user->rights->user->user->creer)); @@ -92,11 +98,15 @@ if ($id) // Security check $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} $feature2 = 'user'; $result = restrictedArea($user, 'user', $id, 'user', $feature2); -if ($user->id <> $id && !$canreaduser) accessforbidden(); +if ($user->id <> $id && !$canreaduser) { + accessforbidden(); +} // Load translation files required by page $langs->loadLangs(array('users', 'companies', 'ldap', 'admin', 'hrm', 'stocks')); @@ -120,7 +130,9 @@ $hookmanager->initHooks(array('usercard', 'globalcard')); $parameters = array('id' => $id, 'socid' => $socid, 'group' => $group, 'caneditgroup' => $caneditgroup); $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 == 'confirm_disable' && $confirm == "yes" && $candisableuser) { @@ -153,12 +165,9 @@ if (empty($reshook)) { } } - if ($action == 'confirm_delete' && $confirm == "yes" && $candisableuser) - { - if ($id <> $user->id) - { - if (!GETPOSTISSET('token')) - { + if ($action == 'confirm_delete' && $confirm == "yes" && $candisableuser) { + if ($id <> $user->id) { + if (!GETPOSTISSET('token')) { print 'Error, token required for this critical operation'; exit; } @@ -315,10 +324,8 @@ if (empty($reshook)) { } // Action add usergroup - if (($action == 'addgroup' || $action == 'removegroup') && $caneditgroup) - { - if ($group) - { + if (($action == 'addgroup' || $action == 'removegroup') && $caneditgroup) { + if ($group) { $editgroup = new UserGroup($db); $editgroup->fetch($group); $editgroup->oldcopy = clone $editgroup; @@ -340,12 +347,10 @@ if (empty($reshook)) { } } - if ($action == 'update' && !$cancel) - { + if ($action == 'update' && !$cancel) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if ($caneditfield) // Case we can edit all field - { + if ($caneditfield) { // Case we can edit all field $error = 0; if (!GETPOST("lastname", 'alpha')) { @@ -359,8 +364,7 @@ if (empty($reshook)) { $error++; } - if (!$error) - { + if (!$error) { $object->fetch($id); $object->oldcopy = clone $object; @@ -374,7 +378,9 @@ if (empty($reshook)) { $object->gender = GETPOST("gender", 'aZ09'); $object->pass = GETPOST("password", 'none'); $object->api_key = (GETPOST("api_key", 'alphanohtml')) ? GETPOST("api_key", 'alphanohtml') : $object->api_key; - if (!empty($user->admin)) $object->admin = GETPOST("admin", "int"); // admin flag can only be set/unset by an admin user. A test is also done later when forging sql request + if (!empty($user->admin)) { + $object->admin = GETPOST("admin", "int"); // admin flag can only be set/unset by an admin user. A test is also done later when forging sql request + } $object->address = GETPOST('address', 'alphanohtml'); $object->zip = GETPOST('zipcode', 'alphanohtml'); $object->town = GETPOST('town', 'alphanohtml'); @@ -421,20 +427,16 @@ if (empty($reshook)) { $object->dateendvalidity = $dateendvalidity; $object->birth = $dateofbirth; - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { $object->fk_warehouse = GETPOST('fk_warehouse', 'int'); } $object->lang = GETPOST('default_lang', 'aZ09'); - if (!empty($conf->multicompany->enabled)) - { - if (!empty($_POST["superadmin"])) - { + if (!empty($conf->multicompany->enabled)) { + if (!empty($_POST["superadmin"])) { $object->entity = 0; - } elseif (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { + } elseif (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { $object->entity = 1; // all users in master entity } else { $object->entity = (!GETPOST('entity', 'int') ? 0 : GETPOST('entity', 'int')); @@ -452,11 +454,9 @@ if (empty($reshook)) { if (GETPOST('deletephoto')) { $object->photo = ''; } - if (!empty($_FILES['photo']['name'])) - { + if (!empty($_FILES['photo']['name'])) { $isimage = image_format_supported($_FILES['photo']['name']); - if ($isimage > 0) - { + if ($isimage > 0) { $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); } else { $error++; @@ -541,8 +541,7 @@ if (empty($reshook)) { } } - if (!$error && !count($object->errors)) - { + if (!$error && !count($object->errors)) { // Then we add the associated categories $categories = GETPOST('usercats', 'array'); $object->setCategories($categories); @@ -553,8 +552,7 @@ if (empty($reshook)) { $db->commit(); $login = $_SESSION["dol_login"]; - if ($login && $login == $object->oldcopy->login && $object->oldcopy->login != $object->login) // Current user has changed its login - { + if ($login && $login == $object->oldcopy->login && $object->oldcopy->login != $object->login) { // Current user has changed its login $error++; $langs->load("errors"); setEventMessages($langs->transnoentitiesnoconv("WarningYourLoginWasModifiedPleaseLogin"), null, 'warnings'); @@ -564,8 +562,7 @@ if (empty($reshook)) { } } } else { - if ($caneditpassword) // Case we can edit only password - { + if ($caneditpassword) { // Case we can edit only password dol_syslog("Not allowed to change fields, only password"); $object->fetch($id); @@ -574,8 +571,7 @@ if (empty($reshook)) { $object->oldcopy = clone $object; $ret = $object->setPassword($user, GETPOST("password", "none")); - if ($ret < 0) - { + if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); } } @@ -596,8 +592,7 @@ if (empty($reshook)) { } else { // Succes if ($action == 'confirm_passwordsend' && $confirm == 'yes') { - if ($object->send_password($user, $newpassword) > 0) - { + if ($object->send_password($user, $newpassword) > 0) { setEventMessages($langs->trans("PasswordChangedAndSentTo", $object->email), null, 'mesgs'); } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -686,25 +681,24 @@ $formother = new FormOther($db); $formcompany = new FormCompany($db); $formadmin = new FormAdmin($db); $formfile = new FormFile($db); -if (!empty($conf->stock->enabled)) $formproduct = new FormProduct($db); +if (!empty($conf->stock->enabled)) { + $formproduct = new FormProduct($db); +} llxHeader('', $langs->trans("UserCard")); -if ($action == 'create' || $action == 'adduserldap') -{ +if ($action == 'create' || $action == 'adduserldap') { print load_fiche_titre($langs->trans("NewUser"), '', 'user'); print '<span class="opacitymedium">'.$langs->trans("CreateInternalUserDesc")."</span><br>\n"; print "<br>"; - if (!empty($conf->ldap->enabled) && (isset($conf->global->LDAP_SYNCHRO_ACTIVE) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr')) - { + if (!empty($conf->ldap->enabled) && (isset($conf->global->LDAP_SYNCHRO_ACTIVE) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr')) { // Show form to add an account from LDAP if sync LDAP -> Dolibarr is set $ldap = new Ldap(); $result = $ldap->connect_bind(); - if ($result >= 0) - { + if ($result >= 0) { $required_fields = array( $conf->global->LDAP_KEY_USERS, $conf->global->LDAP_FIELD_FULLNAME, @@ -730,21 +724,17 @@ if ($action == 'create' || $action == 'adduserldap') // Get from LDAP database an array of results $ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 1); - if (is_array($ldapusers)) - { + if (is_array($ldapusers)) { $liste = array(); - foreach ($ldapusers as $key => $ldapuser) - { + foreach ($ldapusers as $key => $ldapuser) { // Define the label string for this user $label = ''; - foreach ($required_fields as $value) - { - if ($value === $conf->global->LDAP_FIELD_PASSWORD || $value === $conf->global->LDAP_FIELD_PASSWORD_CRYPTED) - { - $label .= $value."=******* "; - } elseif ($value) { - $label .= $value."=".$ldapuser[$value]." "; - } + foreach ($required_fields as $value) { + if ($value === $conf->global->LDAP_FIELD_PASSWORD || $value === $conf->global->LDAP_FIELD_PASSWORD_CRYPTED) { + $label .= $value."=******* "; + } elseif ($value) { + $label .= $value."=".$ldapuser[$value]." "; + } } $liste[$key] = $label; } @@ -756,35 +746,36 @@ if ($action == 'create' || $action == 'adduserldap') } // If user list is full, we show drop-down list - print "\n\n<!-- Form liste LDAP debut -->\n"; + print "\n\n<!-- Form liste LDAP debut -->\n"; - print '<form name="add_user_ldap" action="'.$_SERVER["PHP_SELF"].'" method="post">'; - print '<input type="hidden" name="token" value="'.newToken().'">'; - print '<table class="border centpercent"><tr>'; - print '<td width="160">'; - print $langs->trans("LDAPUsers"); - print '</td>'; - print '<td>'; - print '<input type="hidden" name="action" value="adduserldap">'; - if (is_array($liste) && count($liste)) - { + print '<form name="add_user_ldap" action="'.$_SERVER["PHP_SELF"].'" method="post">'; + print '<input type="hidden" name="token" value="'.newToken().'">'; + print '<table class="border centpercent"><tr>'; + print '<td width="160">'; + print $langs->trans("LDAPUsers"); + print '</td>'; + print '<td>'; + print '<input type="hidden" name="action" value="adduserldap">'; + if (is_array($liste) && count($liste)) { print $form->selectarray('users', $liste, '', 1, 0, 0, '', 0, 0, 0, '', 'maxwidth500'); print ajax_combobox('users'); } - print '</td><td class="center">'; - print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Get')).'"'.(count($liste) ? '' : ' disabled').'>'; - print '</td></tr></table>'; - print '</form>'; + print '</td><td class="center">'; + print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Get')).'"'.(count($liste) ? '' : ' disabled').'>'; + print '</td></tr></table>'; + print '</form>'; - print "\n<!-- Form liste LDAP fin -->\n\n"; - print '<br>'; + print "\n<!-- Form liste LDAP fin -->\n\n"; + print '<br>'; } print '<form action="'.$_SERVER['PHP_SELF'].'" method="POST" name="createuser">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; - if (!empty($ldap_sid)) print '<input type="hidden" name="ldap_sid" value="'.dol_escape_htmltag($ldap_sid).'">'; + if (!empty($ldap_sid)) { + print '<input type="hidden" name="ldap_sid" value="'.dol_escape_htmltag($ldap_sid).'">'; + } print '<input type="hidden" name="entity" value="'.$conf->entity.'">'; print dol_get_fiche_head('', '', '', 0, ''); @@ -802,8 +793,7 @@ if ($action == 'create' || $action == 'adduserldap') print '<tr>'; print '<td class="titlefieldcreate"><span class="fieldrequired">'.$langs->trans("Lastname").'</span></td>'; print '<td>'; - if (!empty($ldap_lastname)) - { + if (!empty($ldap_lastname)) { print '<input type="hidden" id="lastname" name="lastname" value="'.dol_escape_htmltag($ldap_lastname).'">'; print $ldap_lastname; } else { @@ -814,8 +804,7 @@ if ($action == 'create' || $action == 'adduserldap') // Firstname print '<tr><td>'.$langs->trans("Firstname").'</td>'; print '<td>'; - if (!empty($ldap_firstname)) - { + if (!empty($ldap_firstname)) { print '<input type="hidden" name="firstname" value="'.dol_escape_htmltag($ldap_firstname).'">'; print $ldap_firstname; } else { @@ -826,12 +815,10 @@ if ($action == 'create' || $action == 'adduserldap') // Login print '<tr><td><span class="fieldrequired">'.$langs->trans("Login").'</span></td>'; print '<td>'; - if (!empty($ldap_login)) - { + if (!empty($ldap_login)) { print '<input type="hidden" name="login" value="'.dol_escape_htmltag($ldap_login).'">'; print $ldap_login; - } elseif (!empty($ldap_loginsmb)) - { + } elseif (!empty($ldap_loginsmb)) { print '<input type="hidden" name="login" value="'.dol_escape_htmltag($ldap_loginsmb).'">'; print $ldap_loginsmb; } else { @@ -840,8 +827,7 @@ if ($action == 'create' || $action == 'adduserldap') print '</td></tr>'; $generated_password = ''; - if (empty($ldap_sid)) // ldap_sid is for activedirectory - { + if (empty($ldap_sid)) { // ldap_sid is for activedirectory $generated_password = getRandomPassword(false); } $password = (GETPOSTISSET('password') ?GETPOST('password') : $generated_password); @@ -850,18 +836,14 @@ if ($action == 'create' || $action == 'adduserldap') print '<tr><td class="fieldrequired">'.$langs->trans("Password").'</td>'; print '<td>'; $valuetoshow = ''; - if (preg_match('/ldap/', $dolibarr_main_authentication)) - { + if (preg_match('/ldap/', $dolibarr_main_authentication)) { $valuetoshow .= ($valuetoshow ? ', ' : '').$langs->trans("PasswordOfUserInLDAP"); } - if (preg_match('/http/', $dolibarr_main_authentication)) - { + if (preg_match('/http/', $dolibarr_main_authentication)) { $valuetoshow .= ($valuetoshow ? ', ' : '').$langs->trans("HTTPBasicPassword"); } - if (preg_match('/dolibarr/', $dolibarr_main_authentication)) - { - if (!empty($ldap_pass)) // For very old system comaptibilty. Now clear password can't be viewed from LDAP read - { + if (preg_match('/dolibarr/', $dolibarr_main_authentication)) { + if (!empty($ldap_pass)) { // For very old system comaptibilty. Now clear password can't be viewed from LDAP read $valuetoshow .= ($valuetoshow ? ', ' : '').'<input type="hidden" name="password" value="'.$ldap_pass.'">'; // Dolibarr password is preffiled with LDAP known password $valuetoshow .= preg_replace('/./i', '*', $ldap_pass); } else { @@ -873,21 +855,24 @@ if ($action == 'create' || $action == 'adduserldap') // Other form for user password $parameters = array('valuetoshow' => $valuetoshow, 'password' => $password); $reshook = $hookmanager->executeHooks('printUserPasswordField', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook > 0) $valuetoshow = $hookmanager->resPrint; // to replace - else $valuetoshow .= $hookmanager->resPrint; // to add + if ($reshook > 0) { + $valuetoshow = $hookmanager->resPrint; // to replace + } else { + $valuetoshow .= $hookmanager->resPrint; // to add + } print $valuetoshow; print '</td></tr>'; - if (!empty($conf->api->enabled)) - { + if (!empty($conf->api->enabled)) { // API key //$generated_password = getRandomPassword(false); print '<tr><td>'.$langs->trans("ApiKey").'</td>'; print '<td>'; print '<input size="30" maxsize="32" type="text" id="api_key" name="api_key" value="'.GETPOST('api_key', 'alphanohtml').'" autocomplete="off">'; - if (!empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) { print '&nbsp;'.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_api_key" class="linkobject"'); + } print '</td></tr>'; } else { // PARTIAL WORKAROUND @@ -896,16 +881,13 @@ if ($action == 'create' || $action == 'adduserldap') } // Administrator - if (!empty($user->admin)) - { + if (!empty($user->admin)) { print '<tr><td>'.$langs->trans("Administrator").'</td>'; print '<td>'; print $form->selectyesno('admin', GETPOST('admin'), 1); - if (!empty($conf->multicompany->enabled) && !$user->entity) - { - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->multicompany->enabled) && !$user->entity) { + if (!empty($conf->use_javascript_ajax)) { print '<script type="text/javascript"> $(function() { $("select[name=admin]").change(function() { @@ -934,7 +916,7 @@ if ($action == 'create' || $action == 'adduserldap') } $checked = (GETPOST('superadmin', 'int') ? ' checked' : ''); $disabled = (GETPOST('superadmin', 'int') ? '' : ' disabled'); - print '<input type="checkbox" name="superadmin" value="1"'.$checked.$disabled.' /> '.$langs->trans("SuperAdministrator"); + print '<input type="checkbox" name="superadmin" id="superadmin" value="1"'.$checked.$disabled.' /> <label for="superadmin">'.$langs->trans("SuperAdministrator").'</span>'; } print "</td></tr>\n"; } @@ -961,8 +943,7 @@ if ($action == 'create' || $action == 'adduserldap') print "</tr>\n"; // Expense report validator - if (!empty($conf->expensereport->enabled)) - { + if (!empty($conf->expensereport->enabled)) { print '<tr><td class="titlefieldcreate">'; $text = $langs->trans("ForceUserExpenseValidator"); print $form->textwithpicto($text, $langs->trans("ValidatorIsSupervisorByDefault"), 1, 'help'); @@ -974,8 +955,7 @@ if ($action == 'create' || $action == 'adduserldap') } // Holiday request validator - if (!empty($conf->holiday->enabled)) - { + if (!empty($conf->holiday->enabled)) { print '<tr><td class="titlefieldcreate">'; $text = $langs->trans("ForceUserHolidayValidator"); print $form->textwithpicto($text, $langs->trans("ValidatorIsSupervisorByDefault"), 1, 'help'); @@ -1013,13 +993,15 @@ if ($action == 'create' || $action == 'adduserldap') // Country print '<tr><td>'.$form->editfieldkey('Country', 'selectcountry_id', '', $object, 0).'</td><td class="maxwidthonsmartphone">'; + print img_picto('', 'country', 'class="paddingrightonly"'); print $form->select_country((GETPOST('country_id') != '' ?GETPOST('country_id') : $object->country_id)); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '</td></tr>'; // State - if (empty($conf->global->USER_DISABLE_STATE)) - { + if (empty($conf->global->USER_DISABLE_STATE)) { print '<tr><td>'.$form->editfieldkey('State', 'state_id', '', $object, 0).'</td><td class="maxwidthonsmartphone">'; print $formcompany->select_state($object->state_id, $object->country_code, 'state_id'); print '</td></tr>'; @@ -1029,8 +1011,7 @@ if ($action == 'create' || $action == 'adduserldap') print '<tr><td>'.$langs->trans("PhonePro").'</td>'; print '<td>'; print img_picto('', 'object_phoning'); - if (!empty($ldap_phone)) - { + if (!empty($ldap_phone)) { print '<input type="hidden" name="office_phone" value="'.dol_escape_htmltag($ldap_phone).'">'; print $ldap_phone; } else { @@ -1042,8 +1023,7 @@ if ($action == 'create' || $action == 'adduserldap') print '<tr><td>'.$langs->trans("PhoneMobile").'</td>'; print '<td>'; print img_picto('', 'object_phoning_mobile'); - if (!empty($ldap_mobile)) - { + if (!empty($ldap_mobile)) { print '<input type="hidden" name="user_mobile" value="'.dol_escape_htmltag($ldap_mobile).'">'; print $ldap_mobile; } else { @@ -1055,8 +1035,7 @@ if ($action == 'create' || $action == 'adduserldap') print '<tr><td>'.$langs->trans("Fax").'</td>'; print '<td>'; print img_picto('', 'object_phoning_fax'); - if (!empty($ldap_fax)) - { + if (!empty($ldap_fax)) { print '<input type="hidden" name="office_fax" value="'.dol_escape_htmltag($ldap_fax).'">'; print $ldap_fax; } else { @@ -1068,8 +1047,7 @@ if ($action == 'create' || $action == 'adduserldap') print '<tr><td'.(!empty($conf->global->USER_MAIL_REQUIRED) ? ' class="fieldrequired"' : '').'>'.$langs->trans("EMail").'</td>'; print '<td>'; print img_picto('', 'object_email'); - if (!empty($ldap_mail)) - { + if (!empty($ldap_mail)) { print '<input type="hidden" name="email" value="'.dol_escape_htmltag($ldap_mail).'">'; print $ldap_mail; } else { @@ -1082,6 +1060,9 @@ if ($action == 'create' || $action == 'adduserldap') if ($value['active']) { print '<tr><td>'.$langs->trans($value['label']).'</td>'; print '<td>'; + if (!empty($value['icon'])) { + print '<span class="fa '.$value['icon'].'"></span>'; + } if (!empty($ldap_social[$key])) { print '<input type="hidden" name="'.$key.'" value="'.$ldap_social[$key].'">'; print $ldap_social[$key]; @@ -1101,8 +1082,7 @@ if ($action == 'create' || $action == 'adduserldap') } // Accountancy code - if ($conf->accounting->enabled) - { + if ($conf->accounting->enabled) { print '<tr><td>'.$langs->trans("AccountancyCode").'</td>'; print '<td>'; print '<input type="text" name="accountancy_code" value="'.dol_escape_htmltag(GETPOST('accountancy_code', 'alphanohtml')).'">'; @@ -1110,8 +1090,7 @@ if ($action == 'create' || $action == 'adduserldap') } // User color - if (!empty($conf->agenda->enabled)) - { + if (!empty($conf->agenda->enabled)) { print '<tr><td>'.$langs->trans("ColorUser").'</td>'; print '<td>'; print $formother->selectColor(GETPOSTISSET('color') ?GETPOST('color', 'alphanohtml') : $object->color, 'color', null, 1, '', 'hideifnotset'); @@ -1119,31 +1098,26 @@ if ($action == 'create' || $action == 'adduserldap') } // Categories - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) - { + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { print '<tr><td>'.$form->editfieldkey('Categories', 'usercats', '', $object, 0).'</td><td colspan="3">'; $cate_arbo = $form->select_all_categories('user', null, 'parent', null, null, 1); - print $form->multiselectarray('usercats', $cate_arbo, GETPOST('usercats', 'array'), null, null, null, null, '90%'); + print img_picto('', 'category').$form->multiselectarray('usercats', $cate_arbo, GETPOST('usercats', 'array'), null, null, null, null, '90%'); print "</td></tr>"; } - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { print '<tr><td>'.$form->editfieldkey('DefaultLang', 'default_lang', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">'."\n"; - print $formadmin->select_language(GETPOST('default_lang', 'alpha') ?GETPOST('default_lang', 'alpha') : ($object->lang ? $object->lang : ''), 'default_lang', 0, 0, 1, 0, 0, 'maxwidth200onsmartphone'); + print img_picto('', 'language').$formadmin->select_language(GETPOST('default_lang', 'alpha') ?GETPOST('default_lang', 'alpha') : ($object->lang ? $object->lang : ''), 'default_lang', 0, 0, 1, 0, 0, 'maxwidth200onsmartphone'); print '</td>'; print '</tr>'; } // Multicompany - if (!empty($conf->multicompany->enabled) && is_object($mc)) - { + if (!empty($conf->multicompany->enabled) && is_object($mc)) { // This is now done with hook formObjectOptions. Keep this code for backward compatibility with old multicompany module - if (!method_exists($mc, 'formObjectOptions')) - { - if (empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) // condition must be same for create and edit mode - { - print "<tr>".'<td>'.$langs->trans("Entity").'</td>'; + if (!method_exists($mc, 'formObjectOptions')) { + if (empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) { // condition must be same for create and edit mode + print "<tr>".'<td>'.$langs->trans("Entity").'</td>'; print "<td>".$mc->select_entities($conf->entity); print "</td></tr>\n"; } else { @@ -1180,8 +1154,7 @@ if ($action == 'create' || $action == 'adduserldap') // TODO Move this into tab RH (HierarchicalResponsible must be on both tab) // Default warehouse - if (!empty($conf->stock->enabled) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) { print '<tr><td>'.$langs->trans("DefaultWarehouse").'</td><td>'; print $formproduct->selectWarehouses($object->fk_warehouse, 'fk_warehouse', 'warehouseopen', 1); print '</td></tr>'; @@ -1194,8 +1167,7 @@ if ($action == 'create' || $action == 'adduserldap') print '</td></tr>'; if ((!empty($conf->salaries->enabled) && !empty($user->rights->salaries->read)) - || (!empty($conf->hrm->enabled) && !empty($user->rights->hrm->employee->read))) - { + || (!empty($conf->hrm->enabled) && !empty($user->rights->hrm->employee->read))) { $langs->load("salaries"); // THM @@ -1204,7 +1176,7 @@ if ($action == 'create' || $action == 'adduserldap') print $form->textwithpicto($text, $langs->trans("THMDescription"), 1, 'help', 'classthm'); print '</td>'; print '<td>'; - print '<input size="8" type="text" name="thm" value="'.dol_escape_htmltag(GETPOST('thm')).'">'; + print '<input size="8" type="text" name="thm" value="'.dol_escape_htmltag(GETPOST('thm')).'"> '.$langs->getCurrencySymbol($conf->currency); print '</td>'; print "</tr>\n"; @@ -1214,14 +1186,14 @@ if ($action == 'create' || $action == 'adduserldap') print $form->textwithpicto($text, $langs->trans("TJMDescription"), 1, 'help', 'classtjm'); print '</td>'; print '<td>'; - print '<input size="8" type="text" name="tjm" value="'.dol_escape_htmltag(GETPOST('tjm')).'">'; + print '<input size="8" type="text" name="tjm" value="'.dol_escape_htmltag(GETPOST('tjm')).'"> '.$langs->getCurrencySymbol($conf->currency); print '</td>'; print "</tr>\n"; // Salary print '<tr><td>'.$langs->trans("Salary").'</td>'; print '<td>'; - print '<input size="8" type="text" name="salary" value="'.dol_escape_htmltag(GETPOST('salary')).'">'; + print img_picto('', 'salary', 'class="pictofixedwidth paddingright"').'<input size="8" type="text" name="salary" value="'.dol_escape_htmltag(GETPOST('salary')).'"> '.$langs->getCurrencySymbol($conf->currency); print '</td>'; print "</tr>\n"; } @@ -1264,7 +1236,7 @@ if ($action == 'create' || $action == 'adduserldap') print "</table>\n"; - print dol_get_fiche_end(); + print dol_get_fiche_end(); print '<div class="center">'; print '<input class="button" value="'.$langs->trans("CreateUser").'" name="create" type="submit">'; @@ -1275,31 +1247,31 @@ if ($action == 'create' || $action == 'adduserldap') print "</form>"; } else { // View and edit mode - if ($id > 0) - { - $object->fetch($id, '', '', 1); - if ($res < 0) { dol_print_error($db, $object->error); exit; } + if ($id > 0) { + $res = $object->fetch($id, '', '', 1); + if ($res < 0) { + dol_print_error($db, $object->error); + exit; + } $res = $object->fetch_optionals(); // Check if user has rights - if (empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { + if (empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { $object->getrights(); - if (empty($object->nb_rights) && $object->statut != 0 && empty($object->admin)) setEventMessages($langs->trans('UserHasNoPermissions'), null, 'warnings'); + if (empty($object->nb_rights) && $object->statut != 0 && empty($object->admin)) { + setEventMessages($langs->trans('UserHasNoPermissions'), null, 'warnings'); + } } // Connexion ldap // pour recuperer passDoNotExpire et userChangePassNextLogon - if (!empty($conf->ldap->enabled) && !empty($object->ldap_sid)) - { + if (!empty($conf->ldap->enabled) && !empty($object->ldap_sid)) { $ldap = new Ldap(); $result = $ldap->connect_bind(); - if ($result > 0) - { + if ($result > 0) { $userSearchFilter = '('.$conf->global->LDAP_FILTER_CONNECTION.'('.$ldap->getUserIdentifier().'='.$object->login.'))'; $entries = $ldap->fetch($object->login, $userSearchFilter); - if (!$entries) - { + if (!$entries) { setEventMessages($ldap->error, $ldap->errors, 'errors'); } @@ -1309,12 +1281,9 @@ if ($action == 'create' || $action == 'adduserldap') $statutUACF = ''; // Check options of user account - if (count($ldap->uacf) > 0) - { - foreach ($ldap->uacf as $key => $statut) - { - if ($key == 65536) - { + if (count($ldap->uacf) > 0) { + foreach ($ldap->uacf as $key => $statut) { + if ($key == 65536) { $passDoNotExpire = 1; $statutUACF = $statut; } @@ -1324,16 +1293,14 @@ if ($action == 'create' || $action == 'adduserldap') $statutUACF = "ACCOUNTDISABLE"; } - if ($ldap->pwdlastset == 0) - { + if ($ldap->pwdlastset == 0) { $userChangePassNextLogon = 1; } } } // Show tabs - if ($mode == 'employee') // For HRM module development - { + if ($mode == 'employee') { // For HRM module development $title = $langs->trans("Employee"); $linkback = '<a href="'.DOL_URL_ROOT.'/hrm/employee/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; } else { @@ -1348,50 +1315,44 @@ if ($action == 'create' || $action == 'adduserldap') $head = user_prepare_head($object); /* - * Confirmation reinitialisation mot de passe - */ - if ($action == 'password') - { + * Confirmation reinitialisation mot de passe + */ + if ($action == 'password') { print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id", $langs->trans("ReinitPassword"), $langs->trans("ConfirmReinitPassword", $object->login), "confirm_password", '', 0, 1); } /* - * Confirmation envoi mot de passe - */ - if ($action == 'passwordsend') - { + * Confirmation envoi mot de passe + */ + if ($action == 'passwordsend') { print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id", $langs->trans("SendNewPassword"), $langs->trans("ConfirmSendNewPassword", $object->login), "confirm_passwordsend", '', 0, 1); } /* - * Confirm deactivation - */ - if ($action == 'disable') - { + * Confirm deactivation + */ + if ($action == 'disable') { print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id", $langs->trans("DisableAUser"), $langs->trans("ConfirmDisableUser", $object->login), "confirm_disable", '', 0, 1); } /* - * Confirm activation - */ - if ($action == 'enable') - { + * Confirm activation + */ + if ($action == 'enable') { print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id", $langs->trans("EnableAUser"), $langs->trans("ConfirmEnableUser", $object->login), "confirm_enable", '', 0, 1); } /* - * Confirmation suppression - */ - if ($action == 'delete') - { + * Confirmation suppression + */ + if ($action == 'delete') { print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id", $langs->trans("DeleteAUser"), $langs->trans("ConfirmDeleteUser", $object->login), "confirm_delete", '', 0, 1); } /* - * Fiche en mode visu - */ - if ($action != 'edit') - { + * Fiche en mode visu + */ + if ($action != 'edit') { print dol_get_fiche_head($head, 'user', $title, -1, 'user'); dol_banner_tab($object, 'id', $linkback, $user->rights->user->user->lire || $user->admin); @@ -1404,8 +1365,7 @@ if ($action == 'create' || $action == 'adduserldap') // Login print '<tr><td class="titlefield">'.$langs->trans("Login").'</td>'; - if (!empty($object->ldap_sid) && $object->statut == 0) - { + if (!empty($object->ldap_sid) && $object->statut == 0) { print '<td class="error">'.$langs->trans("LoginAccountDisableInDolibarr").'</td>'; } else { print '<td>'.$object->login.'</td>'; @@ -1417,18 +1377,13 @@ if ($action == 'create' || $action == 'adduserldap') print '<td class="wordbreak">'; $valuetoshow = ''; - if (preg_match('/ldap/', $dolibarr_main_authentication)) - { - if (!empty($object->ldap_sid)) - { - if ($passDoNotExpire) - { + if (preg_match('/ldap/', $dolibarr_main_authentication)) { + if (!empty($object->ldap_sid)) { + if ($passDoNotExpire) { $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$langs->trans("LdapUacf_".$statutUACF); - } elseif ($userChangePassNextLogon) - { + } elseif ($userChangePassNextLogon) { $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').'<span class="warning">'.$langs->trans("UserMustChangePassNextLogon", $ldap->domainFQDN).'</span>'; - } elseif ($userDisabled) - { + } elseif ($userDisabled) { $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').'<span class="warning">'.$langs->trans("LdapUacf_".$statutUACF, $ldap->domainFQDN).'</span>'; } else { $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$langs->trans("PasswordOfUserInLDAP"); @@ -1437,12 +1392,10 @@ if ($action == 'create' || $action == 'adduserldap') $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$langs->trans("PasswordOfUserInLDAP"); } } - if (preg_match('/http/', $dolibarr_main_authentication)) - { + if (preg_match('/http/', $dolibarr_main_authentication)) { $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$langs->trans("HTTPBasicPassword"); } - if (preg_match('/dolibarr/', $dolibarr_main_authentication)) - { + if (preg_match('/dolibarr/', $dolibarr_main_authentication)) { if ($object->pass) { $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : ''); $valuetoshow .= '<span class="opacitymedium">'.$langs->trans("Hidden").'</span>'; @@ -1453,16 +1406,20 @@ if ($action == 'create' || $action == 'adduserldap') $valuetoshow .= '<span class="opacitymedium">'.$langs->trans("Hidden").'</span>'; // TODO Add a feature to reveal the hash $valuetoshow .= '<!-- Crypted into '.$object->pass_indatabase_crypted.' -->'; + } else { + $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').'<span class="opacitymedium">'.$langs->trans("Hidden").'</span>'; } - else $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').'<span class="opacitymedium">'.$langs->trans("Hidden").'</span>'; } } // Other form for user password $parameters = array('valuetoshow' => $valuetoshow); $reshook = $hookmanager->executeHooks('printUserPasswordField', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook > 0) $valuetoshow = $hookmanager->resPrint; // to replace - else $valuetoshow .= $hookmanager->resPrint; // to add + if ($reshook > 0) { + $valuetoshow = $hookmanager->resPrint; // to replace + } else { + $valuetoshow .= $hookmanager->resPrint; // to add + } print $valuetoshow; print "</td>"; @@ -1472,7 +1429,9 @@ if ($action == 'create' || $action == 'adduserldap') if (!empty($conf->api->enabled) && $user->admin) { print '<tr><td>'.$langs->trans("ApiKey").'</td>'; print '<td>'; - if (!empty($object->api_key)) print '<span class="opacitymedium">'.preg_replace('/./', '*', $object->api_key).'</span>'; + if (!empty($object->api_key)) { + print '<span class="opacitymedium">'.preg_replace('/./', '*', $object->api_key).'</span>'; + } if ($user->admin || $user->id == $object->id) { // TODO Add a feature to reveal the hash } @@ -1481,11 +1440,9 @@ if ($action == 'create' || $action == 'adduserldap') // Administrator print '<tr><td>'.$langs->trans("Administrator").'</td><td>'; - if (!empty($conf->multicompany->enabled) && $object->admin && !$object->entity) - { + if (!empty($conf->multicompany->enabled) && $object->admin && !$object->entity) { print $form->textwithpicto(yn($object->admin), $langs->trans("SuperAdministratorDesc"), 1, "superadmin"); - } elseif ($object->admin) - { + } elseif ($object->admin) { print $form->textwithpicto(yn($object->admin), $langs->trans("AdministratorDesc"), 1, "admin"); } else { print yn($object->admin); @@ -1498,25 +1455,22 @@ if ($action == 'create' || $action == 'adduserldap') print $form->textwithpicto($text, $langs->trans("InternalExternalDesc")); print '</td><td>'; $type = $langs->trans("Internal"); - if ($object->socid > 0) $type = $langs->trans("External"); + if ($object->socid > 0) { + $type = $langs->trans("External"); + } print $type; - if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; + if ($object->ldap_sid) { + print ' ('.$langs->trans("DomainUser").')'; + } print '</td></tr>'."\n"; // Ldap sid - if ($object->ldap_sid) - { + if ($object->ldap_sid) { print '<tr><td>'.$langs->trans("Type").'</td><td>'; print $langs->trans("DomainUser", $ldap->domainFQDN); print '</td></tr>'."\n"; } - // Gender - print '<tr><td>'.$langs->trans("Gender").'</td>'; - print '<td>'; - if ($object->gender) print $langs->trans("Gender".$object->gender); - print '</td></tr>'; - // Employee print '<tr><td>'.$langs->trans("Employee").'</td><td colspan="2">'; print yn($object->employee); @@ -1570,8 +1524,7 @@ if ($action == 'create' || $action == 'adduserldap') } // Default warehouse - if (!empty($conf->stock->enabled) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; print '<tr><td>'.$langs->trans("DefaultWarehouse").'</td><td>'; if ($object->fk_warehouse > 0) { @@ -1590,8 +1543,7 @@ if ($action == 'create' || $action == 'adduserldap') //$childids = $user->getAllChildIds(1); if ((!empty($conf->salaries->enabled) && !empty($user->rights->salaries->read)) - || (!empty($conf->hrm->enabled) && !empty($user->rights->hrm->employee->read))) - { + || (!empty($conf->hrm->enabled) && !empty($user->rights->hrm->employee->read))) { // Even a superior can't see this info of its subordinates wihtout $user->rights->salaries->read and $user->rights->hrm->employee->read (setting/viewing is reserverd to HR people). // However, he can see the valuation of timesheet of its subordinates even without these permissions. $langs->load("salaries"); @@ -1619,7 +1571,7 @@ if ($action == 'create' || $action == 'adduserldap') // Salary print '<tr><td>'.$langs->trans("Salary").'</td>'; print '<td>'; - print ($object->salary != '' ?price($object->salary, '', $langs, 1, -1, -1, $conf->currency) : ''); + print ($object->salary != '' ? img_picto('', 'salary', 'class="pictofixedwidth paddingright"').price($object->salary, '', $langs, 1, -1, -1, $conf->currency) : ''); print '</td>'; print "</tr>\n"; } @@ -1667,8 +1619,7 @@ if ($action == 'create' || $action == 'adduserldap') print "</tr>\n"; // Accountancy code - if ($conf->accounting->enabled) - { + if ($conf->accounting->enabled) { print '<tr><td>'.$langs->trans("AccountancyCode").'</td>'; print '<td>'.$object->accountancy_code.'</td></tr>'; } @@ -1682,8 +1633,7 @@ if ($action == 'create' || $action == 'adduserldap') print '<table class="border tableforfield centpercent">'; // Color user - if (!empty($conf->agenda->enabled)) - { + if (!empty($conf->agenda->enabled)) { print '<tr><td>'.$langs->trans("ColorUser").'</td>'; print '<td>'; print $formother->showColor($object->color, ''); @@ -1692,8 +1642,7 @@ if ($action == 'create' || $action == 'adduserldap') } // Categories - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) - { + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { print '<tr><td>'.$langs->trans("Categories").'</td>'; print '<td colspan="3">'; print $form->showCategories($object->id, Categorie::TYPE_USER, 1); @@ -1701,8 +1650,7 @@ if ($action == 'create' || $action == 'adduserldap') } // Default language - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; print '<tr><td>'.$langs->trans("DefaultLang").'</td><td>'; //$s=picto_from_langcode($object->default_lang); @@ -1713,8 +1661,7 @@ if ($action == 'create' || $action == 'adduserldap') print '</td></tr>'; } - if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->file->main_authentication) && !empty($conf->global->MAIN_OPENIDURL_PERUSER)) - { + if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->file->main_authentication) && !empty($conf->global->MAIN_OPENIDURL_PERUSER)) { print '<tr><td>'.$langs->trans("OpenIDURL").'</td>'; print '<td>'.$object->openid.'</td>'; print "</tr>\n"; @@ -1729,21 +1676,18 @@ if ($action == 'create' || $action == 'adduserldap') print "</tr>\n"; // Multicompany - if (!empty($conf->multicompany->enabled) && is_object($mc)) - { + if (!empty($conf->multicompany->enabled) && is_object($mc)) { // This is now done with hook formObjectOptions. Keep this code for backward compatibility with old multicompany module - if (!method_exists($mc, 'formObjectOptions')) - { - if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) - { - print '<tr><td>'.$langs->trans("Entity").'</td><td>'; - if (empty($object->entity)) { - print $langs->trans("AllEntities"); - } else { - $mc->getInfo($object->entity); - print $mc->label; - } - print "</td></tr>\n"; + if (!method_exists($mc, 'formObjectOptions')) { + if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) { + print '<tr><td>'.$langs->trans("Entity").'</td><td>'; + if (empty($object->entity)) { + print $langs->trans("AllEntities"); + } else { + $mc->getInfo($object->entity); + print $mc->label; + } + print "</td></tr>\n"; } } } @@ -1752,13 +1696,11 @@ if ($action == 'create' || $action == 'adduserldap') include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; // Company / Contact - if (!empty($conf->societe->enabled)) - { + if (!empty($conf->societe->enabled)) { print '<tr><td>'.$langs->trans("LinkToCompanyContact").'</td>'; print '<td>'; $s = ''; - if (isset($object->socid) && $object->socid > 0) - { + if (isset($object->socid) && $object->socid > 0) { $societe = new Societe($db); $societe->fetch($object->socid); if ($societe->id > 0) { @@ -1767,13 +1709,15 @@ if ($action == 'create' || $action == 'adduserldap') } else { $s .= '<span class="opacitymedium hideonsmartphone">'.$langs->trans("ThisUserIsNot").'</span>'; } - if (!empty($object->contact_id)) - { + if (!empty($object->contact_id)) { $contact = new Contact($db); $contact->fetch($object->contact_id); if ($contact->id > 0) { - if ($object->socid > 0 && $s) $s .= ' / '; - else $s .= '<br>'; + if ($object->socid > 0 && $s) { + $s .= ' / '; + } else { + $s .= '<br>'; + } $s .= $contact->getNomUrl(1, ''); } } @@ -1783,13 +1727,11 @@ if ($action == 'create' || $action == 'adduserldap') } // Module Adherent - if (!empty($conf->adherent->enabled)) - { + if (!empty($conf->adherent->enabled)) { $langs->load("members"); print '<tr><td>'.$langs->trans("LinkedToDolibarrMember").'</td>'; print '<td>'; - if ($object->fk_member) - { + if ($object->fk_member) { $adh = new Adherent($db); $adh->fetch($object->fk_member); $adh->ref = $adh->getFullname($langs); // Force to show login instead of id @@ -1826,18 +1768,16 @@ if ($action == 'create' || $action == 'adduserldap') /* - * Buttons actions - */ + * Buttons actions + */ print '<div class="tabsAction">'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { if (empty($user->socid)) { - if (!empty($object->email)) - { + if (!empty($object->email)) { $langs->load("mails"); print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>'; } else { @@ -1846,65 +1786,56 @@ if ($action == 'create' || $action == 'adduserldap') } } - if ($caneditfield && (empty($conf->multicompany->enabled) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { + if ($caneditfield && (empty($conf->multicompany->enabled) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("DisabledInMonoUserMode")).'">'.$langs->trans("Modify").'</a></div>'; } else { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'; } } elseif ($caneditpassword && !$object->ldap_sid && - (empty($conf->multicompany->enabled) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { + (empty($conf->multicompany->enabled) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("EditPassword").'</a></div>'; } // Si on a un gestionnaire de generation de mot de passe actif - if ($conf->global->USER_PASSWORD_GENERATED != 'none') - { - if ($object->statut == 0) - { + if ($conf->global->USER_PASSWORD_GENERATED != 'none') { + if ($object->statut == 0) { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("UserDisabled")).'">'.$langs->trans("ReinitPassword").'</a></div>'; } elseif (($user->id != $id && $caneditpassword) && $object->login && !$object->ldap_sid && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=password">'.$langs->trans("ReinitPassword").'</a></div>'; } - if ($object->statut == 0) - { + if ($object->statut == 0) { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("UserDisabled")).'">'.$langs->trans("SendNewPassword").'</a></div>'; } elseif (($user->id != $id && $caneditpassword) && $object->login && !$object->ldap_sid && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { - if ($object->email) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=passwordsend">'.$langs->trans("SendNewPassword").'</a></div>'; - else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NoEMail")).'">'.$langs->trans("SendNewPassword").'</a></div>'; + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { + if ($object->email) { + print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=passwordsend">'.$langs->trans("SendNewPassword").'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NoEMail")).'">'.$langs->trans("SendNewPassword").'</a></div>'; + } } } // Enable user if ($user->id <> $id && $candisableuser && $object->statut == 0 && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=enable">'.$langs->trans("Reactivate").'</a></div>'; } // Disable user if ($user->id <> $id && $candisableuser && $object->statut == 1 && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?action=disable&amp;id='.$object->id.'">'.$langs->trans("DisableUser").'</a></div>'; } else { - if ($user->id == $id) - { + if ($user->id == $id) { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("CantDisableYourself").'">'.$langs->trans("DisableUser").'</a></div>'; } } // Delete if ($user->id <> $id && $candisableuser && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { - if ($user->admin || !$object->admin) // If user edited is admin, delete is possible on for an admin - { + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { + if ($user->admin || !$object->admin) { // If user edited is admin, delete is possible on for an admin print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?action=delete&amp;token='.newToken().'&amp;id='.$object->id.'">'.$langs->trans("DeleteUser").'</a></div>'; } else { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("MustBeAdminToDeleteOtherAdmin")).'">'.$langs->trans("DeleteUser").'</a></div>'; @@ -1917,7 +1848,9 @@ if ($action == 'create' || $action == 'adduserldap') //Select mail models is same action as presend - if (GETPOST('modelselected')) $action = 'presend'; + if (GETPOST('modelselected')) { + $action = 'presend'; + } // Presend form $modelmail = 'user'; @@ -1927,14 +1860,12 @@ if ($action == 'create' || $action == 'adduserldap') include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; - if ($action != 'presend' && $action != 'send') - { + if ($action != 'presend' && $action != 'send') { /* - * List of groups of user - */ + * List of groups of user + */ - if ($canreadgroup) - { + if ($canreadgroup) { print '<!-- Group section -->'."\n"; print load_fiche_titre($langs->trans("ListOfGroupsForUser"), '', ''); @@ -1945,10 +1876,8 @@ if ($action == 'create' || $action == 'adduserldap') $usergroup = new UserGroup($db); $groupslist = $usergroup->listGroupsForUser($object->id); - if (!empty($groupslist)) - { - foreach ($groupslist as $groupforuser) - { + if (!empty($groupslist)) { + foreach ($groupslist as $groupforuser) { $exclude[] = $groupforuser->id; } } @@ -1958,10 +1887,8 @@ if ($action == 'create' || $action == 'adduserldap') $reshook = $hookmanager->executeHooks('formAddUserToGroup', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { - if ($caneditgroup) - { + if (empty($reshook)) { + if ($caneditgroup) { print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$id.'" method="POST">'."\n"; print '<input type="hidden" name="token" value="'.newToken().'" />'; print '<input type="hidden" name="action" value="addgroup" />'; @@ -1970,8 +1897,7 @@ if ($action == 'create' || $action == 'adduserldap') print '<table class="noborder centpercent">'."\n"; print '<tr class="liste_titre"><th class="liste_titre">'.$langs->trans("Groups").'</th>'."\n"; print '<th class="liste_titre right">'; - if ($caneditgroup) - { + if ($caneditgroup) { print $form->select_dolgroups('', 'group', 1, $exclude, 0, '', '', $object->entity); print ' &nbsp; '; print '<input type="hidden" name="entity" value="'.$conf->entity.'" />'; @@ -1980,22 +1906,18 @@ if ($action == 'create' || $action == 'adduserldap') print '</th></tr>'."\n"; // List of groups of user - if (!empty($groupslist)) - { - foreach ($groupslist as $group) - { + if (!empty($groupslist)) { + foreach ($groupslist as $group) { print '<tr class="oddeven">'; print '<td>'; - if ($caneditgroup) - { + if ($caneditgroup) { print $group->getNomUrl(1); } else { print img_object($langs->trans("ShowGroup"), "group").' '.$group->name; } print '</td>'; print '<td class="right">'; - if ($caneditgroup) - { + if ($caneditgroup) { print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=removegroup&amp;group='.$group->id.'">'; print img_picto($langs->trans("RemoveFromGroup"), 'unlink'); print '</a>'; @@ -2010,8 +1932,7 @@ if ($action == 'create' || $action == 'adduserldap') print "</table>"; - if ($caneditgroup) - { + if ($caneditgroup) { print '</form>'; } print "<br>"; @@ -2021,10 +1942,9 @@ if ($action == 'create' || $action == 'adduserldap') } /* - * Card in edit mode - */ - if ($action == 'edit' && ($canedituser || $caneditfield || $caneditpassword || ($user->id == $object->id))) - { + * Card in edit mode + */ + if ($action == 'edit' && ($canedituser || $caneditfield || $caneditpassword || ($user->id == $object->id))) { print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="POST" name="updateuser" enctype="multipart/form-data">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; @@ -2035,8 +1955,7 @@ if ($action == 'create' || $action == 'adduserldap') print '<table class="border centpercent">'; // Ref/ID - if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) - { + if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { print '<tr><td class="titlefield">'.$langs->trans("Ref").'</td>'; print '<td>'; print $object->id; @@ -2053,8 +1972,7 @@ if ($action == 'create' || $action == 'adduserldap') print "<tr>"; print '<td class="titlefield fieldrequired">'.$langs->trans("Lastname").'</td>'; print '<td>'; - if ($caneditfield && !$object->ldap_sid) - { + if ($caneditfield && !$object->ldap_sid) { print '<input class="minwidth100" type="text" class="flat" name="lastname" value="'.$object->lastname.'">'; } else { print '<input type="hidden" name="lastname" value="'.$object->lastname.'">'; @@ -2066,8 +1984,7 @@ if ($action == 'create' || $action == 'adduserldap') // Firstname print "<tr>".'<td>'.$langs->trans("Firstname").'</td>'; print '<td>'; - if ($caneditfield && !$object->ldap_sid) - { + if ($caneditfield && !$object->ldap_sid) { print '<input class="minwidth100" type="text" class="flat" name="firstname" value="'.$object->firstname.'">'; } else { print '<input type="hidden" name="firstname" value="'.$object->firstname.'">'; @@ -2078,8 +1995,7 @@ if ($action == 'create' || $action == 'adduserldap') // Login print "<tr>".'<td><span class="fieldrequired">'.$langs->trans("Login").'</span></td>'; print '<td>'; - if ($user->admin && !$object->ldap_sid) - { + if ($user->admin && !$object->ldap_sid) { print '<input maxlength="50" type="text" class="flat" name="login" value="'.$object->login.'">'; } else { print '<input type="hidden" name="login" value="'.$object->login.'">'; @@ -2092,18 +2008,14 @@ if ($action == 'create' || $action == 'adduserldap') print '<tr><td>'.$langs->trans("Password").'</td>'; print '<td>'; $valuetoshow = ''; - if (preg_match('/ldap/', $dolibarr_main_authentication)) - { + if (preg_match('/ldap/', $dolibarr_main_authentication)) { $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$langs->trans("PasswordOfUserInLDAP"); } - if (preg_match('/http/', $dolibarr_main_authentication)) - { + if (preg_match('/http/', $dolibarr_main_authentication)) { $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$form->textwithpicto($text, $langs->trans("DolibarrInHttpAuthenticationSoPasswordUseless", $dolibarr_main_authentication), 1, 'warning'); } - if (preg_match('/dolibarr/', $dolibarr_main_authentication)) - { - if ($caneditpassword) - { + if (preg_match('/dolibarr/', $dolibarr_main_authentication)) { + if ($caneditpassword) { $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').'<input maxlength="32" type="password" class="flat" name="password" value="'.$object->pass.'" autocomplete="new-password">'; } else { $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').preg_replace('/./i', '*', $object->pass); @@ -2113,27 +2025,29 @@ if ($action == 'create' || $action == 'adduserldap') // Other form for user password $parameters = array('valuetoshow' => $valuetoshow, 'caneditpassword' => $caneditpassword); $reshook = $hookmanager->executeHooks('printUserPasswordField', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook > 0) $valuetoshow = $hookmanager->resPrint; // to replace - else $valuetoshow .= $hookmanager->resPrint; // to add + if ($reshook > 0) { + $valuetoshow = $hookmanager->resPrint; // to replace + } else { + $valuetoshow .= $hookmanager->resPrint; // to add + } print $valuetoshow; print "</td></tr>\n"; // API key - if (!empty($conf->api->enabled) && $user->admin) - { + if (!empty($conf->api->enabled) && $user->admin) { print '<tr><td>'.$langs->trans("ApiKey").'</td>'; print '<td>'; print '<input class="minwidth300" maxsize="32" type="text" id="api_key" name="api_key" value="'.$object->api_key.'" autocomplete="off">'; - if (!empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) { print '&nbsp;'.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_api_key" class="linkobject"'); + } print '</td></tr>'; } // Administrator print '<tr><td>'.$langs->trans("Administrator").'</td>'; - if ($object->socid > 0) - { + if ($object->socid > 0) { $langs->load("admin"); print '<td>'; print '<input type="hidden" name="admin" value="'.$object->admin.'">'.yn($object->admin); @@ -2151,14 +2065,11 @@ if ($action == 'create' || $action == 'adduserldap') (empty($conf->multicompany->enabled) && $nbAdmin >= 1) || (!empty($conf->multicompany->enabled) && (($object->entity > 0 || ($user->entity == 0 && $object->entity == 0)) || $nbSuperAdmin > 1)) // Don't downgrade a superadmin if alone ) - ) - { + ) { print $form->selectyesno('admin', $object->admin, 1); - if (!empty($conf->multicompany->enabled) && !$user->entity) - { - if ($conf->use_javascript_ajax) - { + if (!empty($conf->multicompany->enabled) && !$user->entity) { + if ($conf->use_javascript_ajax) { print '<script type="text/javascript"> $(function() { var admin = $("select[name=admin]").val(); @@ -2197,28 +2108,31 @@ if ($action == 'create' || $action == 'adduserldap') } $checked = (($object->admin && !$object->entity) ? ' checked' : ''); - print '<input type="checkbox" name="superadmin" value="1"'.$checked.' /> '.$langs->trans("SuperAdministrator"); + print '<input type="checkbox" name="superadmin" id="superadmin" value="1"'.$checked.' /> <label for="superadmin">'.$langs->trans("SuperAdministrator").'</span>'; } } else { $yn = yn($object->admin); print '<input type="hidden" name="admin" value="'.$object->admin.'">'; print '<input type="hidden" name="superadmin" value="'.(empty($object->entity) ? 1 : 0).'">'; - if (!empty($conf->multicompany->enabled) && empty($object->entity)) print $form->textwithpicto($yn, $langs->trans("DontDowngradeSuperAdmin"), 1, 'warning'); - else print $yn; + if (!empty($conf->multicompany->enabled) && empty($object->entity)) { + print $form->textwithpicto($yn, $langs->trans("DontDowngradeSuperAdmin"), 1, 'warning'); + } else { + print $yn; + } } print '</td></tr>'; } - // Gender - print '<tr><td>'.$langs->trans("Gender").'</td>'; - print '<td>'; - $arraygender = array('man'=>$langs->trans("Genderman"), 'woman'=>$langs->trans("Genderwoman"), 'other'=>$langs->trans("Genderother")); - if ($caneditfield) { - print $form->selectarray('gender', $arraygender, GETPOSTISSET('gender') ?GETPOST('gender') : $object->gender, 1); - } else { - print $arraygender[$object->gender]; - } - print '</td></tr>'; + // Gender + print '<tr><td>'.$langs->trans("Gender").'</td>'; + print '<td>'; + $arraygender = array('man'=>$langs->trans("Genderman"), 'woman'=>$langs->trans("Genderwoman"), 'other'=>$langs->trans("Genderother")); + if ($caneditfield) { + print $form->selectarray('gender', $arraygender, GETPOSTISSET('gender') ?GETPOST('gender') : $object->gender, 1); + } else { + print $arraygender[$object->gender]; + } + print '</td></tr>'; // Employee print '<tr>'; @@ -2235,19 +2149,18 @@ if ($action == 'create' || $action == 'adduserldap') print '</td></tr>'; // Hierarchy - print '<tr><td class="titlefield">'.$langs->trans("HierarchicalResponsible").'</td>'; - print '<td>'; - if ($caneditfield) - { - print $form->select_dolusers($object->fk_user, 'fk_user', 1, array($object->id), 0, '', 0, $object->entity, 0, 0, '', 0, '', 'maxwidth300'); - } else { - print '<input type="hidden" name="fk_user" value="'.$object->fk_user.'">'; - $huser = new User($db); - $huser->fetch($object->fk_user); - print $huser->getNomUrl(1); - } - print '</td>'; - print "</tr>\n"; + print '<tr><td class="titlefield">'.$langs->trans("HierarchicalResponsible").'</td>'; + print '<td>'; + if ($caneditfield) { + print img_picto('', 'user').$form->select_dolusers($object->fk_user, 'fk_user', 1, array($object->id), 0, '', 0, $object->entity, 0, 0, '', 0, '', 'maxwidth300'); + } else { + print '<input type="hidden" name="fk_user" value="'.$object->fk_user.'">'; + $huser = new User($db); + $huser->fetch($object->fk_user); + print $huser->getNomUrl(1); + } + print '</td>'; + print "</tr>\n"; // Expense report validator if (!empty($conf->expensereport->enabled)) { @@ -2256,9 +2169,8 @@ if ($action == 'create' || $action == 'adduserldap') print $form->textwithpicto($text, $langs->trans("ValidatorIsSupervisorByDefault"), 1, 'help'); print '</td>'; print '<td>'; - if ($caneditfield) - { - print $form->select_dolusers($object->fk_user_expense_validator, 'fk_user_expense_validator', 1, array($object->id), 0, '', 0, $object->entity, 0, 0, '', 0, '', 'maxwidth300'); + if ($caneditfield) { + print img_picto('', 'user').$form->select_dolusers($object->fk_user_expense_validator, 'fk_user_expense_validator', 1, array($object->id), 0, '', 0, $object->entity, 0, 0, '', 0, '', 'maxwidth300'); } else { print '<input type="hidden" name="fk_user_expense_validator" value="'.$object->fk_user_expense_validator.'">'; $evuser = new User($db); @@ -2276,9 +2188,8 @@ if ($action == 'create' || $action == 'adduserldap') print $form->textwithpicto($text, $langs->trans("ValidatorIsSupervisorByDefault"), 1, 'help'); print '</td>'; print '<td>'; - if ($caneditfield) - { - print $form->select_dolusers($object->fk_user_holiday_validator, 'fk_user_holiday_validator', 1, array($object->id), 0, '', 0, $object->entity, 0, 0, '', 0, '', 'maxwidth300'); + if ($caneditfield) { + print img_picto('', 'user').$form->select_dolusers($object->fk_user_holiday_validator, 'fk_user_holiday_validator', 1, array($object->id), 0, '', 0, $object->entity, 0, 0, '', 0, '', 'maxwidth300'); } else { print '<input type="hidden" name="fk_user_holiday_validator" value="'.$object->fk_user_holiday_validator.'">'; $hvuser = new User($db); @@ -2292,26 +2203,35 @@ if ($action == 'create' || $action == 'adduserldap') // External user ? print '<tr><td>'.$langs->trans("ExternalUser").' ?</td>'; print '<td>'; - if ($user->id == $object->id || !$user->admin) - { + if ($user->id == $object->id || !$user->admin) { // Read mode $type = $langs->trans("Internal"); - if ($object->socid) $type = $langs->trans("External"); + if ($object->socid) { + $type = $langs->trans("External"); + } print $form->textwithpicto($type, $langs->trans("InternalExternalDesc")); - if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; + if ($object->ldap_sid) { + print ' ('.$langs->trans("DomainUser").')'; + } } else { // Select mode $type = 0; - if ($object->contact_id) $type = $object->contact_id; + if ($object->contact_id) { + $type = $object->contact_id; + } if ($object->socid > 0 && !($object->contact_id > 0)) { // external user but no link to a contact print img_picto('', 'company').$form->select_company($object->socid, 'socid', '', '&nbsp;'); print img_picto('', 'contact').$form->selectcontacts(0, 0, 'contactid', 1, '', '', 1, '', false, 1); - if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; + if ($object->ldap_sid) { + print ' ('.$langs->trans("DomainUser").')'; + } } elseif ($object->socid > 0 && $object->contact_id > 0) { // external user with a link to a contact print img_picto('', 'company').$form->select_company(0, 'socid', '', '&nbsp;'); // We keep thirdparty empty, contact is already set print img_picto('', 'contact').$form->selectcontacts(0, $object->contact_id, 'contactid', 1, '', '', 1, '', false, 1); - if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; + if ($object->ldap_sid) { + print ' ('.$langs->trans("DomainUser").')'; + } } else { // $object->socid is not > 0 here print img_picto('', 'company').$form->select_company(0, 'socid', '', '&nbsp;'); // We keep thirdparty empty, contact is already set print img_picto('', 'contact').$form->selectcontacts(0, 0, 'contactid', 1, '', '', 1, '', false, 1); @@ -2319,15 +2239,19 @@ if ($action == 'create' || $action == 'adduserldap') } print '</td></tr>'; - print '</table><hr><table class="border centpercent">'; + print '</table><hr><table class="border centpercent">'; // Address print '<tr><td class="tdtop titlefield">'.$form->editfieldkey('Address', 'address', '', $object, 0).'</td>'; print '<td>'; - if ($caneditfield) print '<textarea name="address" id="address" class="quatrevingtpercent" rows="3" wrap="soft">'; + if ($caneditfield) { + print '<textarea name="address" id="address" class="quatrevingtpercent" rows="3" wrap="soft">'; + } print $object->address; - if ($caneditfield) print '</textarea>'; + if ($caneditfield) { + print '</textarea>'; + } print '</td></tr>'; // Zip @@ -2352,7 +2276,9 @@ if ($action == 'create' || $action == 'adduserldap') print '<tr><td>'.$form->editfieldkey('Country', 'selectcounty_id', '', $object, 0).'</td><td>'; if ($caneditfield) { print $form->select_country((GETPOST('country_id') != '' ?GETPOST('country_id') : $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); + } } else { $countrylabel = getCountry($object->country_id, '0'); print $countrylabel; @@ -2360,8 +2286,7 @@ if ($action == 'create' || $action == 'adduserldap') print '</td></tr>'; // State - if (empty($conf->global->USER_DISABLE_STATE)) - { + if (empty($conf->global->USER_DISABLE_STATE)) { print '<tr><td class="tdoverflow">'.$form->editfieldkey('State', 'state_id', '', $object, 0).'</td><td>'; if ($caneditfield) { print $formcompany->select_state($object->state_id, $object->country_code, 'state_id'); @@ -2375,8 +2300,7 @@ if ($action == 'create' || $action == 'adduserldap') print "<tr>".'<td>'.$langs->trans("PhonePro").'</td>'; print '<td>'; print img_picto('', 'object_phoning'); - if ($caneditfield && empty($object->ldap_sid)) - { + if ($caneditfield && empty($object->ldap_sid)) { print '<input type="text" name="office_phone" class="flat maxwidth200" value="'.$object->office_phone.'">'; } else { print '<input type="hidden" name="office_phone" value="'.$object->office_phone.'">'; @@ -2388,8 +2312,7 @@ if ($action == 'create' || $action == 'adduserldap') print "<tr>".'<td>'.$langs->trans("PhoneMobile").'</td>'; print '<td>'; print img_picto('', 'object_phoning_mobile'); - if ($caneditfield && empty($object->ldap_sid)) - { + if ($caneditfield && empty($object->ldap_sid)) { print '<input type="text" name="user_mobile" class="flat maxwidth200" value="'.$object->user_mobile.'">'; } else { print '<input type="hidden" name="user_mobile" value="'.$object->user_mobile.'">'; @@ -2401,8 +2324,7 @@ if ($action == 'create' || $action == 'adduserldap') print "<tr>".'<td>'.$langs->trans("Fax").'</td>'; print '<td>'; print img_picto('', 'object_phoning_fax'); - if ($caneditfield && empty($object->ldap_sid)) - { + if ($caneditfield && empty($object->ldap_sid)) { print '<input type="text" name="office_fax" class="flat maxwidth200" value="'.$object->office_fax.'">'; } else { print '<input type="hidden" name="office_fax" value="'.$object->office_fax.'">'; @@ -2414,8 +2336,7 @@ if ($action == 'create' || $action == 'adduserldap') print "<tr>".'<td'.(!empty($conf->global->USER_MAIL_REQUIRED) ? ' class="fieldrequired"' : '').'>'.$langs->trans("EMail").'</td>'; print '<td>'; print img_picto('', 'object_email'); - if ($caneditfield && empty($object->ldap_sid)) - { + if ($caneditfield && empty($object->ldap_sid)) { print '<input class="minwidth100 maxwidth500 widthcentpercentminusx" type="text" name="email" class="flat" value="'.$object->email.'">'; } else { print '<input type="hidden" name="email" value="'.$object->email.'">'; @@ -2428,6 +2349,9 @@ if ($action == 'create' || $action == 'adduserldap') if ($value['active']) { print '<tr><td>'.$langs->trans($value['label']).'</td>'; print '<td>'; + if (!empty($value['icon'])) { + print '<span class="fa '.$value['icon'].'"></span>'; + } if ($caneditfield && empty($object->ldap_sid)) { print '<input size="40" type="text" name="'.$key.'" class="flat" value="'.$object->socialnetworks[$key].'">'; } else { @@ -2443,12 +2367,10 @@ if ($action == 'create' || $action == 'adduserldap') } // OpenID url - if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->file->main_authentication) && !empty($conf->global->MAIN_OPENIDURL_PERUSER)) - { + if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->file->main_authentication) && !empty($conf->global->MAIN_OPENIDURL_PERUSER)) { print "<tr>".'<td>'.$langs->trans("OpenIDURL").'</td>'; print '<td>'; - if ($caneditfield) - { + if ($caneditfield) { print '<input class="minwidth100" type="url" name="openid" class="flat" value="'.$object->openid.'">'; } else { print '<input type="hidden" name="openid" value="'.$object->openid.'">'; @@ -2460,13 +2382,11 @@ if ($action == 'create' || $action == 'adduserldap') print '</table><hr><table class="border centpercent">'; // Accountancy code - if ($conf->accounting->enabled) - { + if ($conf->accounting->enabled) { print "<tr>"; print '<td class="titlefield">'.$langs->trans("AccountancyCode").'</td>'; print '<td>'; - if ($caneditfield) - { + if ($caneditfield) { print '<input size="30" type="text" class="flat" name="accountancy_code" value="'.$object->accountancy_code.'">'; } else { print '<input type="hidden" name="accountancy_code" value="'.$object->accountancy_code.'">'; @@ -2477,12 +2397,10 @@ if ($action == 'create' || $action == 'adduserldap') } // User color - if (!empty($conf->agenda->enabled)) - { + if (!empty($conf->agenda->enabled)) { print '<tr><td>'.$langs->trans("ColorUser").'</td>'; print '<td>'; - if ($caneditfield) - { + if ($caneditfield) { print $formother->selectColor(GETPOSTISSET('color') ?GETPOST('color', 'alphanohtml') : $object->color, 'color', null, 1, '', 'hideifnotset'); } else { print $formother->showColor($object->color, ''); @@ -2499,18 +2417,17 @@ if ($action == 'create' || $action == 'adduserldap') print '</tr>'; // Categories - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) - { + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { print '<tr><td>'.$form->editfieldkey('Categories', 'usercats', '', $object, 0).'</td>'; print '<td>'; + print img_picto('', 'category'); $cate_arbo = $form->select_all_categories(Categorie::TYPE_USER, null, null, null, null, 1); $c = new Categorie($db); $cats = $c->containing($object->id, Categorie::TYPE_USER); foreach ($cats as $cat) { $arrayselected[] = $cat->id; } - if ($caneditfield) - { + if ($caneditfield) { print $form->multiselectarray('usercats', $cate_arbo, $arrayselected, '', 0, '', 0, '90%'); } else { print $form->showCategories($object->id, Categorie::TYPE_USER, 1); @@ -2519,10 +2436,9 @@ if ($action == 'create' || $action == 'adduserldap') } // Default language - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { print '<tr><td>'.$form->editfieldkey('DefaultLang', 'default_lang', '', $object, 0).'</td><td colspan="3">'."\n"; - print $formadmin->select_language($object->lang, 'default_lang', 0, 0, 1); + print img_picto('', 'language').$formadmin->select_language($object->lang, 'default_lang', 0, 0, 1); print '</td>'; print '</tr>'; } @@ -2534,17 +2450,14 @@ if ($action == 'create' || $action == 'adduserldap') print '</td></tr>'; // Company / Contact - if (!empty($conf->societe->enabled)) - { + if (!empty($conf->societe->enabled)) { print '<tr><td>'.$langs->trans("LinkToCompanyContact").'</td>'; print '<td>'; - if ($object->socid > 0) - { + if ($object->socid > 0) { $societe = new Societe($db); $societe->fetch($object->socid); print $societe->getNomUrl(1, ''); - if ($object->contact_id) - { + if ($object->contact_id) { $contact = new Contact($db); $contact->fetch($object->contact_id); print ' / <a href="'.DOL_URL_ROOT.'/contact/card.php?id='.$object->contact_id.'">'.img_object($langs->trans("ShowContact"), 'contact').' '.dol_trunc($contact->getFullName($langs), 32).'</a>'; @@ -2558,13 +2471,11 @@ if ($action == 'create' || $action == 'adduserldap') } // Module Adherent - if (!empty($conf->adherent->enabled)) - { + if (!empty($conf->adherent->enabled)) { $langs->load("members"); print '<tr><td>'.$langs->trans("LinkedToDolibarrMember").'</td>'; print '<td>'; - if ($object->fk_member) - { + if ($object->fk_member) { $adh = new Adherent($db); $adh->fetch($object->fk_member); $adh->ref = $adh->login; // Force to show login instead of id @@ -2578,13 +2489,10 @@ if ($action == 'create' || $action == 'adduserldap') // Multicompany // TODO check if user not linked with the current entity before change entity (thirdparty, invoice, etc.) !! - if (!empty($conf->multicompany->enabled) && is_object($mc)) - { + if (!empty($conf->multicompany->enabled) && is_object($mc)) { // This is now done with hook formObjectOptions. Keep this code for backward compatibility with old multicompany module - if (!method_exists($mc, 'formObjectOptions')) - { - if (empty($conf->multicompany->transverse_mode) && $conf->entity == 1 && $user->admin && !$user->entity) - { + if (!method_exists($mc, 'formObjectOptions')) { + if (empty($conf->multicompany->transverse_mode) && $conf->entity == 1 && $user->admin && !$user->entity) { print "<tr>".'<td>'.$langs->trans("Entity").'</td>'; print "<td>".$mc->select_entities($object->entity, 'entity', '', 0, 1, false, false, 1); // last parameter 1 means, show also a choice 0=>'all entities' print "</td></tr>\n"; @@ -2599,8 +2507,7 @@ if ($action == 'create' || $action == 'adduserldap') //include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; // We do not use common tpl here because we need a special test on $caneditfield $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { if ($caneditfield) { print $object->showOptionals($extrafields, 'edit'); } else { @@ -2611,8 +2518,7 @@ if ($action == 'create' || $action == 'adduserldap') // Signature print '<tr><td class="tdtop">'.$langs->trans("Signature").'</td>'; print '<td>'; - if ($caneditfield) - { + if ($caneditfield) { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor('signature', $object->signature, '', 138, 'dolibarr_notes', 'In', false, true, empty($conf->global->FCKEDITOR_ENABLE_USERSIGN) ? 0 : 1, ROWS_4, '90%'); print $doleditor->Create(1); @@ -2628,8 +2534,7 @@ if ($action == 'create' || $action == 'adduserldap') // TODO Move this into tab RH (HierarchicalResponsible must be on both tab) // Default warehouse - if (!empty($conf->stock->enabled) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) { print '<tr><td>'.$langs->trans("DefaultWarehouse").'</td><td>'; print $formproduct->selectWarehouses($object->fk_warehouse, 'fk_warehouse', 'warehouseopen', 1); print ' <a href="'.DOL_URL_ROOT.'/product/stock/card.php?action=create&amp;backtopage='.urlencode($_SERVER['PHP_SELF'].'?id='.$object->id.'&action=edit').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddWarehouse").'"></span></a>'; @@ -2639,8 +2544,7 @@ if ($action == 'create' || $action == 'adduserldap') // Position/Job print '<tr><td class="titlefield">'.$langs->trans("PostOrFunction").'</td>'; print '<td>'; - if ($caneditfield) - { + if ($caneditfield) { print '<input size="30" type="text" name="job" value="'.dol_escape_htmltag($object->job).'">'; } else { print '<input type="hidden" name="job" value="'.dol_escape_htmltag($object->job).'">'; @@ -2649,8 +2553,7 @@ if ($action == 'create' || $action == 'adduserldap') print '</td></tr>'; if ((!empty($conf->salaries->enabled) && !empty($user->rights->salaries->read)) - || (!empty($conf->hrm->enabled) && !empty($user->rights->hrm->employee->read))) - { + || (!empty($conf->hrm->enabled) && !empty($user->rights->hrm->employee->read))) { $langs->load("salaries"); // THM @@ -2673,8 +2576,7 @@ if ($action == 'create' || $action == 'adduserldap') print $form->textwithpicto($text, $langs->trans("TJMDescription"), 1, 'help', 'classthm'); print '</td>'; print '<td>'; - if ($caneditfield) - { + if ($caneditfield) { print '<input size="8" type="text" name="tjm" value="'.price2num(GETPOST('tjm') ?GETPOST('tjm') : $object->tjm).'">'; } else { print ($object->tjm != '' ?price($object->tjm, '', $langs, 1, -1, -1, $conf->currency) : ''); @@ -2685,7 +2587,7 @@ if ($action == 'create' || $action == 'adduserldap') // Salary print '<tr><td>'.$langs->trans("Salary").'</td>'; print '<td>'; - print '<input size="8" type="text" name="salary" value="'.price2num(GETPOST('salary') ?GETPOST('salary') : $object->salary).'">'; + print img_picto('', 'salary', 'class="pictofixedwidth paddingright"').'<input size="8" type="text" name="salary" value="'.price2num(GETPOST('salary') ?GETPOST('salary') : $object->salary).'">'; print '</td>'; print "</tr>\n"; } @@ -2693,8 +2595,7 @@ if ($action == 'create' || $action == 'adduserldap') // Weeklyhours print '<tr><td>'.$langs->trans("WeeklyHours").'</td>'; print '<td>'; - if ($caneditfield) - { + if ($caneditfield) { print '<input size="8" type="text" name="weeklyhours" value="'.price2num(GETPOST('weeklyhours') ?GETPOST('weeklyhours') : $object->weeklyhours).'">'; } else { print price2num($object->weeklyhours); @@ -2705,17 +2606,17 @@ if ($action == 'create' || $action == 'adduserldap') // Date employment print '<tr><td>'.$langs->trans("DateEmployment").'</td>'; print '<td>'; - if ($caneditfield) - { + if ($caneditfield) { print $form->selectDate($dateemployment ? $dateemployment : $object->dateemployment, 'dateemployment', 0, 0, 1, 'formdateemployment', 1, 1); } else { print dol_print_date($object->dateemployment, 'day'); } - if ($dateemployment && $dateemploymentend) print ' - '; + if ($dateemployment && $dateemploymentend) { + print ' - '; + } - if ($caneditfield) - { + if ($caneditfield) { print $form->selectDate($dateemploymentend ? $dateemploymentend : $object->dateemploymentend, 'dateemploymentend', 0, 0, 1, 'formdateemploymentend', 1, 0); } else { print dol_print_date($object->dateemploymentend, 'day'); @@ -2727,17 +2628,17 @@ if ($action == 'create' || $action == 'adduserldap') // Date login validity print '<tr><td>'.$langs->trans("RangeOfLoginValidity").'</td>'; print '<td>'; - if ($caneditfield) - { + if ($caneditfield) { print $form->selectDate($datestartvalidity ? $datestartvalidity : $object->datestartvalidity, 'datestartvalidity', 0, 0, 1, 'formdatestartvalidity', 1, 1); } else { print dol_print_date($object->datestartvalidity, 'day'); } - if ($datestartvalidity && $dateendvalidity) print ' - '; + if ($datestartvalidity && $dateendvalidity) { + print ' - '; + } - if ($caneditfield) - { + if ($caneditfield) { print $form->selectDate($dateendvalidity ? $datendevalidity : $object->dateendvalidity, 'dateendvalidity', 0, 0, 1, 'formdateendvalidity', 1, 0); } else { print dol_print_date($object->dateendvalidity, 'day'); @@ -2770,12 +2671,11 @@ if ($action == 'create' || $action == 'adduserldap') print '</form>'; } - if ($action != 'edit' && $action != 'presend') - { + if ($action != 'edit' && $action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; /* - * Documents generes - */ + * Generated documents + */ $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->user->dir_output."/".dol_sanitizeFileName($object->ref); $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; @@ -2800,12 +2700,13 @@ if ($action == 'create' || $action == 'adduserldap') print '</div></div></div>'; } - if (!empty($conf->ldap->enabled) && !empty($object->ldap_sid)) $ldap->close(); + if (!empty($conf->ldap->enabled) && !empty($object->ldap_sid)) { + $ldap->close(); + } } } -if (!empty($conf->api->enabled) && !empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->api->enabled) && !empty($conf->use_javascript_ajax)) { print "\n".'<script type="text/javascript">'; print '$(document).ready(function () { $("#generate_api_key").click(function() { diff --git a/htdocs/user/class/user.class.php b/htdocs/user/class/user.class.php index 8f8f8c67ca8..b27e12e3f3e 100644 --- a/htdocs/user/class/user.class.php +++ b/htdocs/user/class/user.class.php @@ -457,7 +457,7 @@ class User extends CommonObject } elseif ($email) { $sql .= " AND u.email = '".$this->db->escape($email)."'"; } else { - $sql .= " AND u.rowid = ".$id; + $sql .= " AND u.rowid = ".((int) $id); } $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities @@ -611,31 +611,31 @@ class User extends CommonObject public function loadDefaultValues() { global $conf; + if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) { + // Load user->default_values for user. TODO Save this in memcached ? + require_once DOL_DOCUMENT_ROOT.'/core/class/defaultvalues.class.php'; - // Load user->default_values for user. TODO Save this in memcached ? - $sql = "SELECT rowid, entity, type, page, param, value"; - $sql .= " FROM ".MAIN_DB_PREFIX."default_values"; - $sql .= " WHERE entity IN (".($this->entity > 0 ? $this->entity.", " : "").$conf->entity.")"; // Entity of user (if defined) + current entity - $sql .= " AND user_id IN (0".($this->id > 0 ? ", ".$this->id : "").")"; // User 0 (all) + me (if defined) - $resql = $this->db->query($sql); - if ($resql) { - while ($obj = $this->db->fetch_object($resql)) { - if (!empty($obj->page) && !empty($obj->type) && !empty($obj->param)) { - // $obj->page is relative URL with or without params - // $obj->type can be 'filters', 'sortorder', 'createform', ... - // $obj->param is key or param - $pagewithoutquerystring = $obj->page; - $pagequeries = ''; - $reg = array(); - if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param - $pagewithoutquerystring = $reg[1]; - $pagequeries = $reg[2]; + $defaultValues = new DefaultValues($this->db); + $result = $defaultValues->fetchAll('', '', 0, 0, array('t.user_id'=>array(0, $this->id), 'entity'=>array($this->entity, $conf->entity))); // User 0 (all) + me (if defined) + + if (!is_array($result) && $result < 0) { + setEventMessages($defaultValues->error, $defaultValues->errors, 'errors'); + dol_print_error($this->db); + return -1; + } elseif (count($result) > 0) { + foreach ($result as $defval) { + if (!empty($defval->page) && !empty($defval->type) && !empty($defval->param)) { + $pagewithoutquerystring = $defval->page; + $pagequeries = ''; + $reg = array(); + if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param + $pagewithoutquerystring = $reg[1]; + $pagequeries = $reg[2]; + } + $this->default_values[$pagewithoutquerystring][$defval->type][$pagequeries ? $pagequeries : '_noquery_'][$defval->param] = $defval->value; } - $this->default_values[$pagewithoutquerystring][$obj->type][$pagequeries ? $pagequeries : '_noquery_'][$obj->param] = $obj->value; - //if ($pagequeries) $this->default_values[$pagewithoutquerystring][$obj->type.'_queries']=$pagequeries; } } - // Sort by key, so _noquery_ is last if (!empty($this->default_values)) { foreach ($this->default_values as $a => $b) { foreach ($b as $c => $d) { @@ -643,13 +643,8 @@ class User extends CommonObject } } } - $this->db->free($resql); - - return 1; - } else { - dol_print_error($this->db); - return -1; } + return 1; } /** @@ -1402,6 +1397,7 @@ class User extends CommonObject $this->address = $contact->address; $this->zip = $contact->zip; $this->town = $contact->town; + $this->setUpperOrLowerCase(); $this->state_id = $contact->state_id; $this->country_id = $contact->country_id; $this->employee = 0; @@ -1474,12 +1470,13 @@ class User extends CommonObject $this->civility_code = $member->civility_id; $this->lastname = $member->lastname; $this->firstname = $member->firstname; - $this->gender = $member->gender; + $this->gender = $member->gender; $this->email = $member->email; $this->fk_member = $member->id; $this->address = $member->address; $this->zip = $member->zip; $this->town = $member->town; + $this->setUpperOrLowerCase(); $this->state_id = $member->state_id; $this->country_id = $member->country_id; $this->socialnetworks = $member->socialnetworks; @@ -1506,7 +1503,7 @@ class User extends CommonObject } elseif (!empty($this->pass_crypted)) { // If a crypted password is already known, we save it directly into database because the previous create did not save it. $sql = "UPDATE ".MAIN_DB_PREFIX."user"; $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $resql = $this->db->query($sql); if (!$resql) { @@ -1517,7 +1514,7 @@ class User extends CommonObject if ($result > 0 && $member->fk_soc) { // If member is linked to a thirdparty $sql = "UPDATE ".MAIN_DB_PREFIX."user"; $sql .= " SET fk_soc=".$member->fk_soc; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG); $resql = $this->db->query($sql); @@ -1637,6 +1634,7 @@ class User extends CommonObject $this->address = empty($this->address) ? '' : $this->address; $this->zip = empty($this->zip) ? '' : $this->zip; $this->town = empty($this->town) ? '' : $this->town; + $this->setUpperOrLowerCase(); $this->accountancy_code = trim($this->accountancy_code); $this->color = empty($this->color) ? '' : $this->color; $this->dateemployment = empty($this->dateemployment) ? '' : $this->dateemployment; @@ -2500,9 +2498,8 @@ class User extends CommonObject // Only picto if ($withpictoimg > 0) { $picto = '<!-- picto user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>'; - } - // Picto must be a photo - else { + } else { + // Picto must be a photo $picto = '<!-- picto photo user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'"'.($paddafterimage ? ' '.$paddafterimage : '').'>'.Form::showphoto('userphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1).'</span>'; } $result .= $picto; @@ -2737,9 +2734,9 @@ class User extends CommonObject if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) { $info[$conf->global->LDAP_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)) { @@ -2747,9 +2744,8 @@ class User extends CommonObject $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase_crypted, 5); // Create OpenLDAP MD5 password from Dolibarr MD5 password } } - } - // Use $this->pass_indatabase value if exists - elseif (!empty($this->pass_indatabase)) { + } elseif (!empty($this->pass_indatabase)) { + // Use $this->pass_indatabase value if exists if (!empty($conf->global->LDAP_FIELD_PASSWORD)) { $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte } @@ -2870,7 +2866,7 @@ class User extends CommonObject $sql = "SELECT u.rowid, u.login as ref, u.datec,"; $sql .= " u.tms as date_modification, u.entity"; $sql .= " FROM ".MAIN_DB_PREFIX."user as u"; - $sql .= " WHERE u.rowid = ".$id; + $sql .= " WHERE u.rowid = ".((int) $id); $result = $this->db->query($sql); if ($result) { diff --git a/htdocs/user/class/userbankaccount.class.php b/htdocs/user/class/userbankaccount.class.php index 2fc43e929ec..7323fb93ab2 100644 --- a/htdocs/user/class/userbankaccount.class.php +++ b/htdocs/user/class/userbankaccount.class.php @@ -96,10 +96,8 @@ class UserBankAccount extends Account $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_rib (fk_user, datec)"; $sql .= " VALUES (".$this->userid.", '".$this->db->idate($now)."')"; $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->affected_rows($resql)) - { + if ($resql) { + if ($this->db->affected_rows($resql)) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."user_rib"); return $this->update($user); @@ -121,8 +119,7 @@ class UserBankAccount extends Account { global $conf; - if (!$this->id) - { + if (!$this->id) { $this->create(); } @@ -138,14 +135,15 @@ class UserBankAccount extends Account $sql .= ",proprio = '".$this->db->escape($this->proprio)."'"; $sql .= ",owner_address = '".$this->db->escape($this->owner_address)."'"; - if (trim($this->label) != '') + if (trim($this->label) != '') { $sql .= ",label = '".$this->db->escape($this->label)."'"; - else $sql .= ",label = NULL"; + } else { + $sql .= ",label = NULL"; + } $sql .= " WHERE rowid = ".$this->id; $result = $this->db->query($sql); - if ($result) - { + if ($result) { return 1; } else { dol_print_error($this->db); @@ -163,20 +161,26 @@ class UserBankAccount extends Account */ public function fetch($id, $ref = '', $userid = 0) { - if (empty($id) && empty($ref) && empty($userid)) return -1; + if (empty($id) && empty($ref) && empty($userid)) { + return -1; + } $sql = "SELECT rowid, fk_user, entity, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,"; $sql .= " owner_address, label, datec, tms as datem"; $sql .= " FROM ".MAIN_DB_PREFIX."user_rib"; - if ($id) $sql .= " WHERE rowid = ".$id; - if ($ref) $sql .= " WHERE label = '".$this->db->escape($ref)."'"; - if ($userid) $sql .= " WHERE fk_user = ".((int) $userid); + if ($id) { + $sql .= " WHERE rowid = ".((int) $id); + } + if ($ref) { + $sql .= " WHERE label = '".$this->db->escape($ref)."'"; + } + if ($userid) { + $sql .= " WHERE fk_user = ".((int) $userid); + } $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; diff --git a/htdocs/user/class/usergroup.class.php b/htdocs/user/class/usergroup.class.php index 5ba6b5553af..f0b6bcdfe87 100644 --- a/htdocs/user/class/usergroup.class.php +++ b/htdocs/user/class/usergroup.class.php @@ -28,7 +28,9 @@ */ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; -if (!empty($conf->ldap->enabled)) require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"; +if (!empty($conf->ldap->enabled)) { + require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"; +} /** @@ -154,8 +156,7 @@ class UserGroup extends CommonObject global $conf; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - if (!empty($groupname)) - { + if (!empty($groupname)) { $result = $this->fetchCommon(0, '', ' AND nom = \''.$this->db->escape($groupname).'\''); } else { $result = $this->fetchCommon($id); @@ -163,10 +164,8 @@ class UserGroup extends CommonObject $this->name = $this->nom; // For compatibility with field name - if ($result) - { - if ($load_members) - { + if ($result) { + if ($load_members) { $this->members = $this->listUsersForGroup(); } @@ -196,8 +195,7 @@ class UserGroup extends CommonObject $sql .= " ".MAIN_DB_PREFIX."usergroup_user as ug"; $sql .= " WHERE ug.fk_usergroup = g.rowid"; $sql .= " AND ug.fk_user = ".$userid; - if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) - { + if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) { $sql .= " AND g.entity IS NOT NULL"; } else { $sql .= " AND g.entity IN (0,".$conf->entity.")"; @@ -206,12 +204,9 @@ class UserGroup extends CommonObject dol_syslog(get_class($this)."::listGroupsForUser", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - while ($obj = $this->db->fetch_object($result)) - { - if (!array_key_exists($obj->rowid, $ret)) - { + if ($result) { + while ($obj = $this->db->fetch_object($result)) { + if (!array_key_exists($obj->rowid, $ret)) { $newgroup = new UserGroup($this->db); $newgroup->fetch($obj->rowid, '', $load_members); $ret[$obj->rowid] = $newgroup; @@ -243,37 +238,43 @@ class UserGroup extends CommonObject $ret = array(); $sql = "SELECT u.rowid"; - if (!empty($this->id)) $sql .= ", ug.entity as usergroup_entity"; + if (!empty($this->id)) { + $sql .= ", ug.entity as usergroup_entity"; + } $sql .= " FROM ".MAIN_DB_PREFIX."user as u"; - if (!empty($this->id)) $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug"; + if (!empty($this->id)) { + $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug"; + } $sql .= " WHERE 1 = 1"; - if (!empty($this->id)) $sql .= " AND ug.fk_user = u.rowid"; - if (!empty($this->id)) $sql .= " AND ug.fk_usergroup = ".$this->id; - if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) - { + if (!empty($this->id)) { + $sql .= " AND ug.fk_user = u.rowid"; + } + if (!empty($this->id)) { + $sql .= " AND ug.fk_usergroup = ".$this->id; + } + if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) { $sql .= " AND u.entity IS NOT NULL"; } else { $sql .= " AND u.entity IN (0,".$conf->entity.")"; } - 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); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { - if (!array_key_exists($obj->rowid, $ret)) - { - if ($mode != 1) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { + if (!array_key_exists($obj->rowid, $ret)) { + if ($mode != 1) { $newuser = new User($this->db); $newuser->fetch($obj->rowid); $ret[$obj->rowid] = $newuser; - } else $ret[$obj->rowid] = $obj->rowid; + } else { + $ret[$obj->rowid] = $obj->rowid; + } } - if ($mode != 1 && !empty($obj->usergroup_entity)) - { + if ($mode != 1 && !empty($obj->usergroup_entity)) { $ret[$obj->rowid]->usergroup_entity[] = $obj->usergroup_entity; } } @@ -308,8 +309,7 @@ class UserGroup extends CommonObject $this->db->begin(); - if (!empty($rid)) - { + if (!empty($rid)) { $module = $perms = $subperms = ''; // Si on a demande ajout d'un droit en particulier, on recupere @@ -335,25 +335,27 @@ class UserGroup extends CommonObject // Where pour la liste des droits a ajouter $whereforadd = "id=".((int) $rid); // Find also rights that are herited to add them too - if ($subperms) $whereforadd .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))"; - elseif ($perms) $whereforadd .= " OR (module='".$this->db->escape($module)."' AND (perms='lire' OR perms='read') AND subperms IS NULL)"; + if ($subperms) { + $whereforadd .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))"; + } elseif ($perms) { + $whereforadd .= " OR (module='".$this->db->escape($module)."' AND (perms='lire' OR perms='read') AND subperms IS NULL)"; + } } else { // Where pour la liste des droits a ajouter - if (!empty($allmodule)) - { - if ($allmodule == 'allmodules') - { + if (!empty($allmodule)) { + if ($allmodule == 'allmodules') { $whereforadd = 'allmodules'; } else { $whereforadd = "module='".$this->db->escape($allmodule)."'"; - if (!empty($allperms)) $whereforadd .= " AND perms='".$this->db->escape($allperms)."'"; + if (!empty($allperms)) { + $whereforadd .= " AND perms='".$this->db->escape($allperms)."'"; + } } } } // Add permission of the list $whereforadd - if (!empty($whereforadd)) - { + if (!empty($whereforadd)) { //print "$module-$perms-$subperms"; $sql = "SELECT id"; $sql .= " FROM ".MAIN_DB_PREFIX."rights_def"; @@ -363,19 +365,21 @@ class UserGroup extends CommonObject } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $nid = $obj->id; $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_rights WHERE fk_usergroup = $this->id AND fk_id=".$nid." AND entity = ".$entity; - if (!$this->db->query($sql)) $error++; + if (!$this->db->query($sql)) { + $error++; + } $sql = "INSERT INTO ".MAIN_DB_PREFIX."usergroup_rights (entity, fk_usergroup, fk_id) VALUES (".$entity.", ".$this->id.", ".$nid.")"; - if (!$this->db->query($sql)) $error++; + if (!$this->db->query($sql)) { + $error++; + } $i++; } @@ -384,14 +388,15 @@ class UserGroup extends CommonObject dol_print_error($this->db); } - if (!$error) - { + if (!$error) { $langs->load("other"); $this->context = array('audit'=>$langs->trans("PermissionsAdd").($rid ? ' (id='.$rid.')' : '')); // Call trigger $result = $this->call_trigger('USERGROUP_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } @@ -426,8 +431,7 @@ class UserGroup extends CommonObject $this->db->begin(); - if (!empty($rid)) - { + if (!empty($rid)) { $module = $perms = $subperms = ''; // Si on a demande supression d'un droit en particulier, on recupere @@ -453,29 +457,32 @@ class UserGroup extends CommonObject // Where pour la liste des droits a supprimer $wherefordel = "id=".$this->db->escape($rid); // Suppression des droits induits - if ($subperms == 'lire' || $subperms == 'read') $wherefordel .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)"; - if ($perms == 'lire' || $perms == 'read') $wherefordel .= " OR (module='".$this->db->escape($module)."')"; + if ($subperms == 'lire' || $subperms == 'read') { + $wherefordel .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)"; + } + if ($perms == 'lire' || $perms == 'read') { + $wherefordel .= " OR (module='".$this->db->escape($module)."')"; + } // Pour compatibilite, si lowid = 0, on est en mode suppression de tout // TODO A virer quand sera gere par l'appelant //if (substr($rid,-1,1) == 0) $wherefordel="module='$module'"; } else { // Add permission of the list $wherefordel - if (!empty($allmodule)) - { - if ($allmodule == 'allmodules') - { + if (!empty($allmodule)) { + if ($allmodule == 'allmodules') { $wherefordel = 'allmodules'; } else { $wherefordel = "module='".$this->db->escape($allmodule)."'"; - if (!empty($allperms)) $wherefordel .= " AND perms='".$this->db->escape($allperms)."'"; + if (!empty($allperms)) { + $wherefordel .= " AND perms='".$this->db->escape($allperms)."'"; + } } } } // Suppression des droits de la liste wherefordel - if (!empty($wherefordel)) - { + if (!empty($wherefordel)) { //print "$module-$perms-$subperms"; $sql = "SELECT id"; $sql .= " FROM ".MAIN_DB_PREFIX."rights_def"; @@ -485,12 +492,10 @@ class UserGroup extends CommonObject } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $nid = 0; $obj = $this->db->fetch_object($result); @@ -501,7 +506,9 @@ class UserGroup extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_rights"; $sql .= " WHERE fk_usergroup = $this->id AND fk_id=".$nid; $sql .= " AND entity = ".$entity; - if (!$this->db->query($sql)) $error++; + if (!$this->db->query($sql)) { + $error++; + } $i++; } @@ -510,14 +517,15 @@ class UserGroup extends CommonObject dol_print_error($this->db); } - if (!$error) - { + if (!$error) { $langs->load("other"); $this->context = array('audit'=>$langs->trans("PermissionsDelete").($rid ? ' (id='.$rid.')' : '')); // Call trigger $result = $this->call_trigger('USERGROUP_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } @@ -542,14 +550,12 @@ class UserGroup extends CommonObject { global $conf; - if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) - { + if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) { // Rights for this module are already loaded, so we leave return; } - if (!empty($this->all_permissions_are_loaded)) - { + if (!empty($this->all_permissions_are_loaded)) { // We already loaded all rights for this group, so we leave return; } @@ -564,16 +570,16 @@ class UserGroup extends CommonObject $sql .= " AND u.entity = ".$conf->entity; $sql .= " AND u.fk_usergroup = ".$this->id; $sql .= " AND r.perms IS NOT NULL"; - if ($moduletag) $sql .= " AND r.module = '".$this->db->escape($moduletag)."'"; + if ($moduletag) { + $sql .= " AND r.module = '".$this->db->escape($moduletag)."'"; + } dol_syslog(get_class($this).'::getrights', LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); if ($obj) { @@ -581,17 +587,25 @@ class UserGroup extends CommonObject $perms = $obj->perms; $subperms = $obj->subperms; - if ($perms) - { - if (!isset($this->rights)) $this->rights = new stdClass(); // For avoid error - if (!isset($this->rights->$module) || !is_object($this->rights->$module)) $this->rights->$module = new stdClass(); - if ($subperms) - { - if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) $this->rights->$module->$perms = new stdClass(); - if (empty($this->rights->$module->$perms->$subperms)) $this->nb_rights++; + if ($perms) { + if (!isset($this->rights)) { + $this->rights = new stdClass(); // For avoid error + } + if (!isset($this->rights->$module) || !is_object($this->rights->$module)) { + $this->rights->$module = new stdClass(); + } + if ($subperms) { + if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) { + $this->rights->$module->$perms = new stdClass(); + } + if (empty($this->rights->$module->$perms->$subperms)) { + $this->nb_rights++; + } $this->rights->$module->$perms->$subperms = 1; } else { - if (empty($this->rights->$module->$perms)) $this->nb_rights++; + if (empty($this->rights->$module->$perms)) { + $this->nb_rights++; + } $this->rights->$module->$perms = 1; } } @@ -602,8 +616,7 @@ class UserGroup extends CommonObject $this->db->free($resql); } - if ($moduletag == '') - { + if ($moduletag == '') { // Si module etait non defini, alors on a tout charge, on peut donc considerer // que les droits sont en cache (car tous charges) pour cet instance de group $this->all_permissions_are_loaded = 1; @@ -641,7 +654,9 @@ class UserGroup extends CommonObject $this->nom = $this->name; // Field for 'name' is called 'nom' in database } - if (!isset($this->entity)) $this->entity = $conf->entity; // If not defined, we use default value + if (!isset($this->entity)) { + $this->entity = $conf->entity; // If not defined, we use default value + } return $this->createCommon($user, $notrigger); } @@ -708,7 +723,9 @@ class UserGroup extends CommonObject global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) $withpicto = 0; + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) { + $withpicto = 0; + } $result = ''; $label = ''; @@ -720,19 +737,20 @@ class UserGroup extends CommonObject $url = DOL_URL_ROOT.'/user/group/card.php?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ""; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $langs->load("users"); $label = $langs->trans("ShowGroup"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1, 1).'"'; @@ -753,16 +771,23 @@ class UserGroup extends CommonObject $linkend = '</a>'; $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 .= $this->name; + 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 .= $this->name; + } $result .= $linkend; global $action; $hookmanager->initHooks(array('groupdao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -783,9 +808,15 @@ class UserGroup extends CommonObject // phpcs:enable global $conf; $dn = ''; - if ($mode == 0) $dn = $conf->global->LDAP_KEY_GROUPS."=".$info[$conf->global->LDAP_KEY_GROUPS].",".$conf->global->LDAP_GROUP_DN; - if ($mode == 1) $dn = $conf->global->LDAP_GROUP_DN; - if ($mode == 2) $dn = $conf->global->LDAP_KEY_GROUPS."=".$info[$conf->global->LDAP_KEY_GROUPS]; + if ($mode == 0) { + $dn = $conf->global->LDAP_KEY_GROUPS."=".$info[$conf->global->LDAP_KEY_GROUPS].",".$conf->global->LDAP_GROUP_DN; + } + if ($mode == 1) { + $dn = $conf->global->LDAP_GROUP_DN; + } + if ($mode == 2) { + $dn = $conf->global->LDAP_KEY_GROUPS."=".$info[$conf->global->LDAP_KEY_GROUPS]; + } return $dn; } @@ -808,14 +839,16 @@ class UserGroup extends CommonObject $info["objectclass"] = explode(',', $conf->global->LDAP_GROUP_OBJECT_CLASS); // Champs - if ($this->name && !empty($conf->global->LDAP_GROUP_FIELD_FULLNAME)) $info[$conf->global->LDAP_GROUP_FIELD_FULLNAME] = $this->name; + if ($this->name && !empty($conf->global->LDAP_GROUP_FIELD_FULLNAME)) { + $info[$conf->global->LDAP_GROUP_FIELD_FULLNAME] = $this->name; + } //if ($this->name && ! empty($conf->global->LDAP_GROUP_FIELD_NAME)) $info[$conf->global->LDAP_GROUP_FIELD_NAME] = $this->name; - if ($this->note && !empty($conf->global->LDAP_GROUP_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_GROUP_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note, 2); - if (!empty($conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS)) - { + if ($this->note && !empty($conf->global->LDAP_GROUP_FIELD_DESCRIPTION)) { + $info[$conf->global->LDAP_GROUP_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note, 2); + } + if (!empty($conf->global->LDAP_GROUP_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. $muser = new User($this->db); $muser->fetch($val->id); $info2 = $muser->_load_ldap_info(); @@ -875,10 +908,8 @@ class UserGroup extends CommonObject $langs->load("user"); // Positionne le modele sur le nom du modele a utiliser - if (!dol_strlen($modele)) - { - if (!empty($conf->global->USERGROUP_ADDON_PDF)) - { + if (!dol_strlen($modele)) { + if (!empty($conf->global->USERGROUP_ADDON_PDF)) { $modele = $conf->global->USERGROUP_ADDON_PDF; } else { $modele = 'grass'; diff --git a/htdocs/user/clicktodial.php b/htdocs/user/clicktodial.php index cb113166cad..0a9a65a2852 100644 --- a/htdocs/user/clicktodial.php +++ b/htdocs/user/clicktodial.php @@ -33,7 +33,9 @@ $id = (int) GETPOST('id', 'int'); // Security check $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} $feature2 = (($socid && $user->rights->user->self->creer) ? '' : 'user'); $result = restrictedArea($user, 'user', $id, 'user&user', $feature2); @@ -47,7 +49,9 @@ $hookmanager->initHooks(array('usercard', 'globalcard')); $parameters = array('id'=>$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)) { if ($action == 'update' && !GETPOST('cancel', 'alpha')) { @@ -76,8 +80,7 @@ $form = new Form($db); llxHeader("", "ClickToDial"); -if ($id > 0) -{ +if ($id > 0) { $object = new User($db); $object->fetch($id, '', '', 1); $object->getrights(); @@ -107,17 +110,14 @@ if ($id > 0) print '<div class="underbanner clearboth"></div>'; // Edit mode - if ($action == 'edit') - { + if ($action == 'edit') { print '<table class="border centpercent">'; - if ($user->admin) - { + if ($user->admin) { print '<tr><td class="titlefield fieldrequired">ClickToDial URL</td>'; print '<td class="valeur">'; print '<input name="url" value="'.(!empty($object->clicktodial_url) ? $object->clicktodial_url : '').'" size="92">'; - if (empty($conf->global->CLICKTODIAL_URL) && empty($object->clicktodial_url)) - { + if (empty($conf->global->CLICKTODIAL_URL) && empty($object->clicktodial_url)) { $langs->load("errors"); print '<font class="error">'.$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("ClickToDial")).'</font>'; } else { @@ -147,14 +147,14 @@ if ($id > 0) { print '<table class="border centpercent tableforfield">'; - if (!empty($user->admin)) - { + if (!empty($user->admin)) { print '<tr><td class="titlefield">ClickToDial URL</td>'; print '<td class="valeur">'; $url = $conf->global->CLICKTODIAL_URL; - if (!empty($object->clicktodial_url)) $url = $object->clicktodial_url; - if (empty($url)) - { + if (!empty($object->clicktodial_url)) { + $url = $object->clicktodial_url; + } + if (empty($url)) { $langs->load("errors"); print '<font class="error">'.$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("ClickToDial")).'</font>'; } else { @@ -181,8 +181,7 @@ if ($id > 0) print dol_get_fiche_end(); - if ($action == 'edit') - { + if ($action == 'edit') { print '<br>'; print '<div class="center"><input class="button button-save" type="submit" value="'.$langs->trans("Save").'">'; print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; @@ -194,12 +193,11 @@ if ($id > 0) print '</form>'; /* - * Barre d'actions - */ + * Action bar + */ print '<div class="tabsAction">'; - if (!empty($user->admin) && $action <> 'edit') - { + if (!empty($user->admin) && $action <> 'edit') { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>'; } diff --git a/htdocs/user/document.php b/htdocs/user/document.php index 5440ceeb725..138408a3c2d 100644 --- a/htdocs/user/document.php +++ b/htdocs/user/document.php @@ -47,14 +47,12 @@ $canedituser = (!empty($user->admin) || $user->rights->user->user->creer); $candisableuser = (!empty($user->admin) || $user->rights->user->user->supprimer); $canreadgroup = $canreaduser; $caneditgroup = $canedituser; -if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $canreadgroup = (!empty($user->admin) || $user->rights->user->group_advance->read); $caneditgroup = (!empty($user->admin) || $user->rights->user->group_advance->write); } // Define value to know what current user can do on properties of edited user -if ($id) -{ +if ($id) { // $user est le user qui edite, $id est l'id de l'utilisateur edite $caneditfield = ((($user->id == $id) && $user->rights->user->self->creer) || (($user->id != $id) && $user->rights->user->user->creer)); @@ -64,28 +62,37 @@ if ($id) // Security check $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} $feature2 = 'user'; $result = restrictedArea($user, 'user', $id, 'user&user', $feature2); -if ($user->id <> $id && !$canreaduser) accessforbidden(); +if ($user->id <> $id && !$canreaduser) { + accessforbidden(); +} // Get parameters $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 (empty($page) || $page == -1) { + $page = 0; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "position_name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "position_name"; +} $object = new User($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref, '', 1); $object->getrights(); //$upload_dir = $conf->user->multidir_output[$object->entity] . "/" . $object->id ; @@ -103,10 +110,12 @@ $hookmanager->initHooks(array('usercard', 'userdoc', 'globalcard')); $parameters = array('id'=>$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)) { - include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; + include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; } @@ -118,12 +127,13 @@ $form = new Form($db); llxHeader('', $langs->trans("UserCard").' - '.$langs->trans("Files")); -if ($object->id) -{ +if ($object->id) { /* * Affichage onglets */ - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = user_prepare_head($object); $form = new Form($db); @@ -143,8 +153,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/user/group/card.php b/htdocs/user/group/card.php index 68d9639990c..05945c02855 100644 --- a/htdocs/user/group/card.php +++ b/htdocs/user/group/card.php @@ -38,8 +38,7 @@ $candisableperms = ($user->admin || $user->rights->user->user->supprimer); $feature2 = 'user'; // Advanced permissions -if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $canreadperms = ($user->admin || $user->rights->user->group_advance->read); $caneditperms = ($user->admin || $user->rights->user->group_advance->write); $candisableperms = ($user->admin || $user->rights->user->group_advance->delete); @@ -62,8 +61,7 @@ $userid = GETPOST('user', 'int'); $result = restrictedArea($user, 'user', $id, 'usergroup&usergroup', $feature2); // Users/Groups management only in master entity if transverse mode -if (!empty($conf->multicompany->enabled) && $conf->entity > 1 && $conf->global->MULTICOMPANY_TRANSVERSE_MODE) -{ +if (!empty($conf->multicompany->enabled) && $conf->entity > 1 && $conf->global->MULTICOMPANY_TRANSVERSE_MODE) { accessforbidden(); } @@ -87,29 +85,31 @@ $hookmanager->initHooks(array('groupcard', 'globalcard')); $parameters = array('id' => $id, 'userid' => $userid, 'caneditperms' => $caneditperms); $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)) { $backurlforlist = DOL_URL_ROOT.'/user/group/list.php'; if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = dol_buildpath('/user/group/card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('/user/group/card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + } } } - if ($cancel) - { + if ($cancel) { header("Location: ".$backtopage); exit; } // Action remove group - if ($action == 'confirm_delete' && $confirm == "yes") - { - if ($caneditperms) - { + if ($action == 'confirm_delete' && $confirm == "yes") { + if ($caneditperms) { $object->fetch($id); $object->delete($user); header("Location: ".DOL_URL_ROOT."/user/group/list.php?restore_lastsearch_values=1"); @@ -121,10 +121,8 @@ if (empty($reshook)) { } // Action add group - if ($action == 'add') - { - if ($caneditperms) - { + if ($action == 'add') { + if ($caneditperms) { if (!GETPOST("nom", "nohtml")) { setEventMessages($langs->trans("NameNotDefined"), null, 'errors'); $action = "create"; // Go back to create page @@ -134,17 +132,21 @@ 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++; + } - if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) $object->entity = 0; - else $object->entity = $_POST["entity"]; + if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + $object->entity = 0; + } else { + $object->entity = $_POST["entity"]; + } $db->begin(); $id = $object->create(); - if ($id > 0) - { + if ($id > 0) { $db->commit(); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); @@ -164,22 +166,22 @@ if (empty($reshook)) { } // Add/Remove user into group - if ($action == 'adduser' || $action == 'removeuser') - { - if ($caneditperms) - { - if ($userid > 0) - { + if ($action == 'adduser' || $action == 'removeuser') { + if ($caneditperms) { + if ($userid > 0) { $object->fetch($id); $object->oldcopy = clone $object; $edituser = new User($db); $edituser->fetch($userid); - if ($action == 'adduser') $result = $edituser->SetInGroup($object->id, $object->entity); - if ($action == 'removeuser') $result = $edituser->RemoveFromGroup($object->id, $object->entity); + if ($action == 'adduser') { + $result = $edituser->SetInGroup($object->id, $object->entity); + } + if ($action == 'removeuser') { + $result = $edituser->RemoveFromGroup($object->id, $object->entity); + } - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -193,10 +195,8 @@ if (empty($reshook)) { } - if ($action == 'update') - { - if ($caneditperms) - { + if ($action == 'update') { + if ($caneditperms) { $db->begin(); $object->fetch($id); @@ -208,15 +208,19 @@ 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++; + } - if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) $object->entity = 0; - else $object->entity = $_POST["entity"]; + if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + $object->entity = 0; + } else { + $object->entity = $_POST["entity"]; + } $ret = $object->update(); - if ($ret >= 0 && !count($object->errors)) - { + if ($ret >= 0 && !count($object->errors)) { setEventMessages($langs->trans("GroupModified"), null, 'mesgs'); $db->commit(); } else { @@ -247,8 +251,7 @@ $fuserstatic = new User($db); $form = new Form($db); $formfile = new FormFile($db); -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewGroup"), '', 'object_group'); print dol_set_focus('#nom'); @@ -263,10 +266,8 @@ if ($action == 'create') print '<table class="border centpercent tableforfieldcreate">'; // Multicompany - if (!empty($conf->multicompany->enabled) && is_object($mc)) - { - if (empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) - { + if (!empty($conf->multicompany->enabled) && is_object($mc)) { + if (empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) { print "<tr>".'<td class="tdtop">'.$langs->trans("Entity").'</td>'; print "<td>".$mc->select_entities($conf->entity); print "</td></tr>\n"; @@ -292,17 +293,13 @@ if ($action == 'create') print '</div>'; print "</form>"; -} - - -/* ************************************************************************** */ -/* */ -/* Visu et edition */ -/* */ -/* ************************************************************************** */ -else { - if ($id) - { +} else { + /* ************************************************************************** */ + /* */ + /* Visu et edition */ + /* */ + /* ************************************************************************** */ + if ($id) { $res = $object->fetch_optionals(); $head = group_prepare_head($object); @@ -311,8 +308,7 @@ else { /* * Confirmation suppression */ - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("DeleteAGroup"), $langs->trans("ConfirmDeleteGroup", $object->name), "confirm_delete", '', 0, 1); } @@ -320,8 +316,7 @@ else { * Fiche en mode visu */ - if ($action != 'edit') - { + if ($action != 'edit') { print dol_get_fiche_head($head, 'group', $title, -1, 'group'); $linkback = '<a href="'.DOL_URL_ROOT.'/user/group/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; @@ -335,20 +330,17 @@ else { print '<table class="border centpercent tableforfield">'; // Name (already in dol_banner, we keep it to have the GlobalGroup picto, but we should move it in dol_banner) - if (!empty($conf->mutlicompany->enabled)) - { + if (!empty($conf->mutlicompany->enabled)) { print '<tr><td class="titlefield">'.$langs->trans("Name").'</td>'; print '<td class="valeur">'.dol_escape_htmltag($object->name); - if (empty($object->entity)) - { + if (empty($object->entity)) { print img_picto($langs->trans("GlobalGroup"), 'redstar'); } print "</td></tr>\n"; } // Multicompany - if (!empty($conf->multicompany->enabled) && is_object($mc) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) - { + if (!empty($conf->multicompany->enabled) && is_object($mc) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) { $mc->getInfo($object->entity); print "<tr>".'<td class="titlefield">'.$langs->trans("Entity").'</td>'; print '<td class="valeur">'.dol_escape_htmltag($mc->label); @@ -374,22 +366,21 @@ else { /* - * Barre d'actions + * Action bar */ - print '<div class="tabsAction">'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if ($caneditperms) - { + if ($caneditperms) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=edit&amp;token='.newToken().'">'.$langs->trans("Modify").'</a>'; } - if ($candisableperms) - { + if ($candisableperms) { print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?action=delete&amp;id='.$object->id.'&amp;token='.newToken().'">'.$langs->trans("DeleteGroup").'</a>'; } @@ -402,10 +393,8 @@ else { // On selectionne les users qui ne sont pas deja dans le groupe $exclude = array(); - if (!empty($object->members)) - { - foreach ($object->members as $useringroup) - { + if (!empty($object->members)) { + foreach ($object->members as $useringroup) { $exclude[] = $useringroup->id; } } @@ -415,10 +404,8 @@ else { $reshook = $hookmanager->executeHooks('formAddUserToGroup', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { - if ($caneditperms) - { + if (empty($reshook)) { + if ($caneditperms) { print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="POST">'."\n"; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="adduser">'; @@ -447,10 +434,8 @@ else { print '<td class="liste_titre right" width="5">&nbsp;</td>'; print "</tr>\n"; - if (!empty($object->members)) - { - foreach ($object->members as $useringroup) - { + if (!empty($object->members)) { + foreach ($object->members as $useringroup) { print '<tr class="oddeven">'; print '<td>'; print $useringroup->getNomUrl(-1, '', 0, 0, 24, 0, 'login'); @@ -484,8 +469,8 @@ else { print '<div class="fichecenter"><div class="fichehalfleft">'; /* - * Documents generes - */ + * Generated documents + */ $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->usergroup->dir_output."/".dol_sanitizeFileName($object->ref); @@ -510,11 +495,10 @@ else { } /* - * Fiche en mode edition - */ + * Fiche en mode edition + */ - if ($action == 'edit' && $caneditperms) - { + if ($action == 'edit' && $caneditperms) { print '<form action="'.$_SERVER['PHP_SELF'].'" method="post" name="updategroup" enctype="multipart/form-data">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; @@ -526,10 +510,8 @@ else { print '<table class="border centpercent tableforfieldedit">'."\n"; // Multicompany - if (!empty($conf->multicompany->enabled) && is_object($mc)) - { - if (empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) - { + if (!empty($conf->multicompany->enabled) && is_object($mc)) { + if (empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) { print "<tr>".'<td class="tdtop">'.$langs->trans("Entity").'</td>'; print "<td>".$mc->select_entities($object->entity); print "</td></tr>\n"; diff --git a/htdocs/user/group/ldap.php b/htdocs/user/group/ldap.php index c17512b6169..dcefbf4a413 100644 --- a/htdocs/user/group/ldap.php +++ b/htdocs/user/group/ldap.php @@ -34,14 +34,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; $langs->loadLangs(array('companies', 'ldap', 'users', 'admin')); // Users/Groups management only in master entity if transverse mode -if (!empty($conf->multicompany->enabled) && $conf->entity > 1 && $conf->global->MULTICOMPANY_TRANSVERSE_MODE) -{ +if (!empty($conf->multicompany->enabled) && $conf->entity > 1 && $conf->global->MULTICOMPANY_TRANSVERSE_MODE) { accessforbidden(); } $canreadperms = true; -if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $canreadperms = ($user->admin || $user->rights->user->group_advance->read); } @@ -49,7 +47,9 @@ $id = GETPOST('id', 'int'); $action = GETPOST('action', 'aZ09'); $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} $object = new Usergroup($db); $object->fetch($id); @@ -60,13 +60,11 @@ $object->getrights(); * Actions */ -if ($action == 'dolibarr2ldap') -{ +if ($action == 'dolibarr2ldap') { $ldap = new Ldap(); $result = $ldap->connect_bind(); - if ($result > 0) - { + if ($result > 0) { $info = $object->_load_ldap_info(); // Get a gid number for objectclass PosixGroup @@ -80,8 +78,7 @@ if ($action == 'dolibarr2ldap') $result = $ldap->update($dn, $info, $user, $olddn); } - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans("GroupSynchronized"), null, 'mesgs'); } else { setEventMessages($ldap->error, $ldap->errors, 'errors'); @@ -111,12 +108,10 @@ print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent">'; // Name (already in dol_banner, we keep it to have the GlobalGroup picto, but we should move it in dol_banner) -if (!empty($conf->mutlicompany->enabled)) -{ +if (!empty($conf->mutlicompany->enabled)) { print '<tr><td class="titlefield">'.$langs->trans("Name").'</td>'; print '<td class="valeur">'.$object->name; - if (!$object->entity) - { + if (!$object->entity) { print img_picto($langs->trans("GlobalGroup"), 'redstar'); } print "</td></tr>\n"; @@ -148,19 +143,19 @@ print dol_get_fiche_end(); /* - * Barre d'actions + * Action bar */ - print '<div class="tabsAction">'; -if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') -{ +if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=dolibarr2ldap">'.$langs->trans("ForceSynchronize").'</a>'; } print "</div>\n"; -if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') print "<br>\n"; +if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') { + print "<br>\n"; +} @@ -177,8 +172,7 @@ print '</tr>'; // Lecture LDAP $ldap = new Ldap(); $result = $ldap->connect_bind(); -if ($result > 0) -{ +if ($result > 0) { $info = $object->_load_ldap_info(); $dn = $object->_load_ldap_dn($info, 1); $search = "(".$object->_load_ldap_dn($info, 2).")"; @@ -188,10 +182,8 @@ if ($result > 0) //var_dump($records); // Show tree - if (((!is_numeric($records)) || $records != 0) && (!isset($records['count']) || $records['count'] > 0)) - { - if (!is_array($records)) - { + if (((!is_numeric($records)) || $records != 0) && (!isset($records['count']) || $records['count'] > 0)) { + if (!is_array($records)) { print '<tr class="oddeven"><td colspan="2"><font class="error">'.$langs->trans("ErrorFailedToReadLDAP").'</font></td></tr>'; } else { $result = show_ldap_content($records, 0, $records['count'], true); diff --git a/htdocs/user/group/list.php b/htdocs/user/group/list.php index 3fce8718287..7281bc93639 100644 --- a/htdocs/user/group/list.php +++ b/htdocs/user/group/list.php @@ -28,15 +28,14 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php'; -if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ - if (!$user->rights->user->group_advance->read && !$user->admin) +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { + if (!$user->rights->user->group_advance->read && !$user->admin) { accessforbidden(); + } } // Users/Groups management only in master entity if transverse mode -if (!empty($conf->multicompany->enabled) && $conf->entity > 1 && $conf->global->MULTICOMPANY_TRANSVERSE_MODE) -{ +if (!empty($conf->multicompany->enabled) && $conf->entity > 1 && $conf->global->MULTICOMPANY_TRANSVERSE_MODE) { accessforbidden(); } @@ -50,8 +49,7 @@ $optioncss = GETPOST('optioncss', 'alpha'); // Defini si peux lire/modifier utilisateurs et permisssions $caneditperms = ($user->admin || $user->rights->user->user->creer); // Advanced permissions -if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $caneditperms = ($user->admin || $user->rights->user->group_advance->write); } @@ -60,13 +58,19 @@ $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 (empty($page) || $page == -1) { + $page = 0; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = "g.nom"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "g.nom"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -79,21 +83,25 @@ $fieldstosearchall = array( * 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(); $reshook = $hookmanager->executeHooks('doActions', $parameters); // 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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers $search_label = ""; $search_date_creation = ""; $search_date_update = ""; @@ -113,20 +121,22 @@ $sql = "SELECT g.rowid, g.nom as name, g.note, g.entity, g.datec, COUNT(DISTINCT $sql .= " FROM ".MAIN_DB_PREFIX."usergroup as g"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_usergroup = g.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_rights as ugr ON ugr.fk_usergroup = g.rowid"; -if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && ($conf->global->MULTICOMPANY_TRANSVERSE_MODE || ($user->admin && !$user->entity))) -{ +if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && ($conf->global->MULTICOMPANY_TRANSVERSE_MODE || ($user->admin && !$user->entity))) { $sql .= " WHERE g.entity IS NOT NULL"; } else { $sql .= " WHERE g.entity IN (0,".$conf->entity.")"; } -if (!empty($search_group)) natural_search(array("g.nom", "g.note"), $search_group); -if ($sall) $sql .= natural_search(array("g.nom", "g.note"), $sall); +if (!empty($search_group)) { + natural_search(array("g.nom", "g.note"), $search_group); +} +if ($sall) { + $sql .= natural_search(array("g.nom", "g.note"), $sall); +} $sql .= " GROUP BY g.rowid, g.nom, g.note, g.entity, g.datec"; $sql .= $db->order($sortfield, $sortorder); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $nbtotalofrecords = $num; @@ -134,18 +144,21 @@ if ($resql) $i = 0; $param = "&amp;search_group=".urlencode($search_group)."&amp;sall=".urlencode($sall); - if ($optioncss != '') $param .= '&amp;optioncss='.$optioncss; + if ($optioncss != '') { + $param .= '&amp;optioncss='.$optioncss; + } $text = $langs->trans("ListOfGroups"); $newcardbutton = ''; - if ($caneditperms) - { + if ($caneditperms) { $newcardbutton .= dolGetButtonTitle($langs->trans('NewGroup'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/user/group/card.php?action=create&leftmenu='); } print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; @@ -155,9 +168,10 @@ if ($resql) print_barre_liste($text, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, "", $num, $nbtotalofrecords, 'object_group', 0, $newcardbutton, '', $limit, 0, 0, 1); - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } @@ -172,8 +186,7 @@ if ($resql) print '<tr class="liste_titre">'; print_liste_field_titre("Group", $_SERVER["PHP_SELF"], "g.nom", $param, "", "", $sortfield, $sortorder); //multicompany - if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) - { + if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) { print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], "g.entity", $param, "", '', $sortfield, $sortorder, 'center '); } print_liste_field_titre("NbOfUsers", $_SERVER["PHP_SELF"], "nb", $param, "", '', $sortfield, $sortorder, 'center '); @@ -184,8 +197,7 @@ if ($resql) $grouptemp = new UserGroup($db); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $grouptemp->id = $obj->rowid; @@ -195,14 +207,12 @@ if ($resql) print '<tr class="oddeven">'; print '<td>'; print $grouptemp->getNomUrl(1); - if (!$obj->entity) - { + if (!$obj->entity) { print img_picto($langs->trans("GlobalGroup"), 'redstar'); } print "</td>"; //multicompany - if (!empty($conf->multicompany->enabled) && is_object($mc) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) - { + if (!empty($conf->multicompany->enabled) && is_object($mc) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) { $mc->getInfo($obj->entity); print '<td class="center">'.$mc->label.'</td>'; } diff --git a/htdocs/user/group/perms.php b/htdocs/user/group/perms.php index ee60b90b994..618d705bfcf 100644 --- a/htdocs/user/group/perms.php +++ b/htdocs/user/group/perms.php @@ -47,14 +47,15 @@ $canreadperms = ($user->admin || $user->rights->user->user->lire); $caneditperms = ($user->admin || $user->rights->user->user->creer); // Advanced permissions $advancedpermsactive = false; -if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $advancedpermsactive = true; $canreadperms = ($user->admin || ($user->rights->user->group_advance->read && $user->rights->user->group_advance->readperms)); $caneditperms = ($user->admin || $user->rights->user->group_advance->write); } -if (!$canreadperms) accessforbidden(); +if (!$canreadperms) { + accessforbidden(); +} $object = new Usergroup($db); $object->fetch($id); @@ -71,7 +72,9 @@ $hookmanager->initHooks(array('groupperms', '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 == 'addrights' && $caneditperms) { @@ -110,8 +113,7 @@ $form = new Form($db); llxHeader('', $langs->trans("Permissions")); -if ($object->id > 0) -{ +if ($object->id > 0) { /* * Affichage onglets */ @@ -127,32 +129,24 @@ if ($object->id > 0) $db->begin(); - foreach ($modulesdir as $dir) - { + foreach ($modulesdir as $dir) { $handle = @opendir(dol_osencode($dir)); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') { $modName = substr($file, 0, dol_strlen($file) - 10); - if ($modName) - { + if ($modName) { include_once $dir.$file; $objMod = new $modName($db); // Load all lang files of module - if (isset($objMod->langfiles) && is_array($objMod->langfiles)) - { - foreach ($objMod->langfiles as $domain) - { + if (isset($objMod->langfiles) && is_array($objMod->langfiles)) { + foreach ($objMod->langfiles as $domain) { $langs->load($domain); } } // Load all permissions - if ($objMod->rights_class) - { + if ($objMod->rights_class) { $ret = $objMod->insert_permissions(0, $entity); $modules[$objMod->rights_class] = $objMod; } @@ -176,15 +170,14 @@ if ($object->id > 0) dol_syslog("get user perms", LOG_DEBUG); $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); - if (!isset($permsgroupbyentity[$obj->entity])) + if (!isset($permsgroupbyentity[$obj->entity])) { $permsgroupbyentity[$obj->entity] = array(); + } array_push($permsgroupbyentity[$obj->entity], $obj->id); $i++; } @@ -207,12 +200,10 @@ if ($object->id > 0) print '<table class="border centpercent tableforfield">'; // Name (already in dol_banner, we keep it to have the GlobalGroup picto, but we should move it in dol_banner) - if (!empty($conf->mutlicompany->enabled)) - { + if (!empty($conf->mutlicompany->enabled)) { print '<tr><td class="titlefield">'.$langs->trans("Name").'</td>'; print '<td colspan="2">'.$object->name.''; - if (!$object->entity) - { + if (!$object->entity) { print img_picto($langs->trans("GlobalGroup"), 'redstar'); } print "</td></tr>\n"; @@ -227,19 +218,22 @@ if ($object->id > 0) print '</table><br>'; - if ($user->admin) print info_admin($langs->trans("WarningOnlyPermissionOfActivatedModules")); + if ($user->admin) { + print info_admin($langs->trans("WarningOnlyPermissionOfActivatedModules")); + } $parameters = array(); $reshook = $hookmanager->executeHooks('insertExtraHeader', $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'); + } print "\n"; print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<td>'.$langs->trans("Module").'</td>'; - if ($caneditperms) - { + if ($caneditperms) { print '<td class="center nowrap">'; print '<a class="reposition commonlink" title="'.dol_escape_htmltag($langs->trans("All")).'" alt="'.dol_escape_htmltag($langs->trans("All")).'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addrights&amp;entity='.$entity.'&amp;module=allmodules">'.$langs->trans("All")."</a>"; print '/'; @@ -248,36 +242,36 @@ if ($object->id > 0) } print '<td class="center" width="24">&nbsp;</td>'; print '<td>'.$langs->trans("Permissions").'</td>'; - if ($user->admin) print '<td class="right">'.$langs->trans("ID").'</td>'; + if ($user->admin) { + print '<td class="right">'.$langs->trans("ID").'</td>'; + } print '</tr>'."\n"; $sql = "SELECT r.id, r.libelle as label, r.module"; $sql .= " FROM ".MAIN_DB_PREFIX."rights_def as r"; $sql .= " WHERE r.libelle NOT LIKE 'tou%'"; // On ignore droits "tous" $sql .= " AND r.entity = ".$entity; - if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is disable + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { + $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is disable + } $sql .= " ORDER BY r.module, r.id"; $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $i = 0; $oldmod = ''; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); // If line is for a module that doe snot existe anymore (absent of includes/module), we ignore it - if (empty($modules[$obj->module])) - { + if (empty($modules[$obj->module])) { $i++; continue; } - if ($oldmod <> $obj->module) - { + if ($oldmod <> $obj->module) { $oldmod = $obj->module; // Break detected, we get objMod @@ -290,8 +284,7 @@ if ($object->id > 0) print img_object('', $picto, 'class="pictoobjectwidth paddingright"').' '.$objMod->getName(); print '<a name="'.$objMod->getName().'"></a>'; print '</td>'; - if ($caneditperms) - { + if ($caneditperms) { print '<td class="center nowrap">'; print '<a class="reposition" title='.$langs->trans("All").' alt='.$langs->trans("All").' href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addrights&amp;entity='.$entity.'&amp;module='.$obj->module.'">'.$langs->trans("All")."</a>"; print '/'; @@ -303,7 +296,9 @@ if ($object->id > 0) print '<td colspan="2">&nbsp;</td>'; // Permission id - if ($user->admin) print '<td class="right"></td>'; + if ($user->admin) { + print '<td class="right"></td>'; + } print '</tr>'; } @@ -316,13 +311,10 @@ if ($object->id > 0) //print img_object('', $picto, 'class="inline-block pictoobjectwidth"').' '.$objMod->getName(); print '</td>'; - if (is_array($permsgroupbyentity[$entity])) - { - if (in_array($obj->id, $permsgroupbyentity[$entity])) - { + if (is_array($permsgroupbyentity[$entity])) { + if (in_array($obj->id, $permsgroupbyentity[$entity])) { // Own permission by group - if ($caneditperms) - { + if ($caneditperms) { print '<td class="center"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delrights&amp;entity='.$entity.'&amp;rights='.$obj->id.'">'; //print img_edit_remove($langs->trans("Remove")); print img_picto($langs->trans("Remove"), 'switch_on'); @@ -333,8 +325,7 @@ if ($object->id > 0) print '</td>'; } else { // Do not own permission - if ($caneditperms) - { + if ($caneditperms) { print '<td class="center"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addrights&amp;entity='.$entity.'&amp;rights='.$obj->id.'">'; //print img_edit_add($langs->trans("Add")); print img_picto($langs->trans("Add"), 'switch_off'); @@ -344,8 +335,7 @@ if ($object->id > 0) } } else { // Do not own permission - if ($caneditperms) - { + if ($caneditperms) { print '<td class="center"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addrights&amp;entity='.$entity.'&amp;rights='.$obj->id.'">'; //print img_edit_add($langs->trans("Add")); print img_picto($langs->trans("Add"), 'switch_off'); @@ -358,7 +348,9 @@ if ($object->id > 0) print '<td class="maxwidthonsmartphone">'.$permlabel.'</td>'; // Permission id - if ($user->admin) print '<td class="right"><span class="opacitymedium">'.$obj->id.'</span></td>'; + if ($user->admin) { + print '<td class="right"><span class="opacitymedium">'.$obj->id.'</span></td>'; + } print '</tr>'."\n"; @@ -372,7 +364,9 @@ if ($object->id > 0) $parameters = array(); $reshook = $hookmanager->executeHooks('insertExtraFooter', $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'); + } print dol_get_fiche_end(); } diff --git a/htdocs/user/hierarchy.php b/htdocs/user/hierarchy.php index 1a6a630d27c..6073ca4c88f 100644 --- a/htdocs/user/hierarchy.php +++ b/htdocs/user/hierarchy.php @@ -4,7 +4,7 @@ * Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com> * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com> - * Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr> + * Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -29,19 +29,22 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/treeview.lib.php'; -if (!$user->rights->user->user->lire && !$user->admin) +if (!$user->rights->user->user->lire && !$user->admin) { accessforbidden(); +} // Load translation files required by page $langs->loadLangs(array('users', 'companies')); // Security check (for external users) $socid = 0; -if ($user->socid > 0) +if ($user->socid > 0) { $socid = $user->socid; +} $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $search_user = GETPOST('search_user', 'alpha'); +$optioncss = GETPOST('optioncss', 'alpha'); // Load mode employee $mode = GETPOST("mode", 'alpha'); @@ -49,10 +52,11 @@ $mode = GETPOST("mode", 'alpha'); $userstatic = new User($db); $search_statut = GETPOST('search_statut', 'int'); -if ($search_statut == '') $search_statut = '1'; +if ($search_statut == '') { + $search_statut = '1'; +} -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $search_statut = ""; } @@ -79,8 +83,7 @@ llxHeader('', $langs->trans("ListOfUsers").' - '.$langs->trans("HierarchicView") // Load hierarchy of users $user_arbo = $userstatic->get_full_tree(0, ($search_statut != '' && $search_statut >= 0) ? "statut = ".$search_statut : ''); -if (!is_array($user_arbo) && $user_arbo < 0) -{ +if (!is_array($user_arbo) && $user_arbo < 0) { setEventMessages($userstatic->error, $userstatic->errors, 'warnings'); } else { // Define fulltree array @@ -89,8 +92,7 @@ if (!is_array($user_arbo) && $user_arbo < 0) // Define data (format for treeview) $data = array(); $data[] = array('rowid'=>0, 'fk_menu'=>-1, 'title'=>"racine", 'mainmenu'=>'', 'leftmenu'=>'', 'fk_mainmenu'=>'', 'fk_leftmenu'=>''); - foreach ($fulltree as $key => $val) - { + foreach ($fulltree as $key => $val) { $userstatic->id = $val['id']; $userstatic->ref = $val['label']; $userstatic->login = $val['login']; @@ -108,10 +110,8 @@ if (!is_array($user_arbo) && $user_arbo < 0) $entitystring = ''; // TODO Set of entitystring should be done with a hook - if (!empty($conf->multicompany->enabled) && is_object($mc)) - { - if (empty($entity)) - { + if (!empty($conf->multicompany->enabled) && is_object($mc)) { + if (empty($entity)) { $entitystring = $langs->trans("AllEntities"); } else { $mc->getInfo($entity); @@ -120,11 +120,9 @@ if (!is_array($user_arbo) && $user_arbo < 0) } $li = $userstatic->getNomUrl(-1, '', 0, 1); - if (!empty($conf->multicompany->enabled) && $userstatic->admin && !$userstatic->entity) - { + if (!empty($conf->multicompany->enabled) && $userstatic->admin && !$userstatic->entity) { $li .= img_picto($langs->trans("SuperAdministrator"), 'redstar'); - } elseif ($userstatic->admin) - { + } elseif ($userstatic->admin) { $li .= img_picto($langs->trans("Administrator"), 'star'); } $li .= ' ('.$val['login'].($entitystring ? ' - '.$entitystring : '').')'; @@ -155,7 +153,9 @@ if (!is_array($user_arbo) && $user_arbo < 0) print load_fiche_titre($title, $morehtmlright.' '.$newcardbutton, 'user'); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; @@ -188,8 +188,7 @@ if (!is_array($user_arbo) && $user_arbo < 0) $nbofentries = (count($data) - 1); - if ($nbofentries > 0) - { + if ($nbofentries > 0) { print '<tr><td colspan="3">'; tree_recur($data, $data[0], 0); print '</td>'; diff --git a/htdocs/user/home.php b/htdocs/user/home.php index b10bd9267f8..dfb201bc441 100644 --- a/htdocs/user/home.php +++ b/htdocs/user/home.php @@ -24,11 +24,11 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'userhome'; // To manage different context of search -if (!$user->rights->user->user->lire && !$user->admin) -{ +if (!$user->rights->user->user->lire && !$user->admin) { // Redirection vers la page de l'utilisateur header("Location: card.php?id=".$user->id); exit; @@ -38,21 +38,39 @@ if (!$user->rights->user->user->lire && !$user->admin) $langs->load("users"); $canreadperms = true; -if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $canreadperms = ($user->admin || $user->rights->user->group_advance->read); } // Security check (for external users) $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} $companystatic = new Societe($db); $fuserstatic = new User($db); // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array $hookmanager->initHooks(array('userhome')); +if (!isset($form) || !is_object($form)) { + $form = new Form($db); +} +// Load $resultboxes (selectboxlist + boxactivated + boxlista + boxlistb) +$resultboxes = FormOther::getBoxesArea($user, "1"); +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 @@ -61,41 +79,35 @@ $hookmanager->initHooks(array('userhome')); llxHeader(); -print load_fiche_titre($langs->trans("MenuUsersAndGroups"), '', 'user'); - - -print '<div class="fichecenter"><div class="fichethirdleft">'; +print load_fiche_titre($langs->trans("MenuUsersAndGroups"), $resultboxes['selectboxlist'], 'user'); // Search User -print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">'; -print '<input type="hidden" name="token" value="'.newToken().'">'; +$searchbox = '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">'; +$searchbox .= '<input type="hidden" name="token" value="'.newToken().'">'; -print '<table class="noborder nohover centpercent">'; -print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Search").'</td></tr>'; -print '<tr><td>'; -print $langs->trans("User").':</td><td><input class="flat inputsearch" type="text" name="search_user" size="18"></td></tr>'; +$searchbox .= '<table class="noborder nohover centpercent">'; +$searchbox .= '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Search").'</td></tr>'; +$searchbox .= '<tr><td>'; +$searchbox .= $langs->trans("User").':</td><td><input class="flat inputsearch" type="text" name="search_user" size="18"></td></tr>'; // Search Group -if ($canreadperms) -{ - print '<tr><td>'; - print $langs->trans("Group").':</td><td><input class="flat inputsearch" type="text" name="search_group" size="18"></td></tr>'; +if ($canreadperms) { + $searchbox .= '<tr><td>'; + $searchbox .= $langs->trans("Group").':</td><td><input class="flat inputsearch" type="text" name="search_group" size="18"></td></tr>'; } -print '<tr><td class="center" colspan="2"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td></tr>'; -print "</table><br>\n"; +$searchbox .= '<tr><td class="center" colspan="2"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td></tr>'; +$searchbox .= "</table><br>\n"; -print '</form>'; - -print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; +$searchbox .= '</form>'; /* * Latest created users */ $max = 10; - +$lastcreatedbox = ''; $sql = "SELECT DISTINCT u.rowid, u.lastname, u.firstname, u.admin, u.login, u.fk_soc, u.datec, u.statut"; $sql .= ", u.entity"; $sql .= ", u.ldap_sid"; @@ -115,24 +127,24 @@ if ($reshook > 0) { } else { $sql .= " WHERE u.entity IN (".getEntity('user').")"; } -if (!empty($socid)) $sql .= " AND u.fk_soc = ".$socid; +if (!empty($socid)) { + $sql .= " AND u.fk_soc = ".$socid; +} $sql .= $db->order("u.datec", "DESC"); $sql .= $db->plimit($max); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); - print '<div class="div-table-responsive-no-min">'; - print '<table class="noborder centpercent">'; - print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("LastUsersCreated", min($num, $max)).'</td>'; - print '<td class="right" colspan="2"><a class="commonlink" href="'.DOL_URL_ROOT.'/user/list.php?sortfield=u.datec&sortorder=DESC">'.$langs->trans("FullList").'</td>'; - print '</tr>'."\n"; + $lastcreatedbox .='<div class="div-table-responsive-no-min">'; + $lastcreatedbox .='<table class="noborder centpercent">'; + $lastcreatedbox .='<tr class="liste_titre"><td colspan="3">'.$langs->trans("LastUsersCreated", min($num, $max)).'</td>'; + $lastcreatedbox .='<td class="right" colspan="2"><a class="commonlink" href="'.DOL_URL_ROOT.'/user/list.php?sortfield=u.datec&sortorder=DESC">'.$langs->trans("FullList").'</td>'; + $lastcreatedbox .='</tr>'."\n"; $i = 0; - while ($i < $num && $i < $max) - { + while ($i < $num && $i < $max) { $obj = $db->fetch_object($resql); $fuserstatic->id = $obj->rowid; @@ -150,56 +162,50 @@ if ($resql) $companystatic->code_client = $obj->code_client; $companystatic->canvas = $obj->canvas; - print '<tr class="oddeven">'; - print '<td class="nowraponall">'; - print $fuserstatic->getNomUrl(-1); - if (!empty($conf->multicompany->enabled) && $obj->admin && !$obj->entity) - { - print img_picto($langs->trans("SuperAdministrator"), 'redstar'); - } elseif ($obj->admin) - { - print img_picto($langs->trans("Administrator"), 'star'); + $lastcreatedbox .='<tr class="oddeven">'; + $lastcreatedbox .='<td class="nowraponall">'; + $lastcreatedbox .=$fuserstatic->getNomUrl(-1); + if (!empty($conf->multicompany->enabled) && $obj->admin && !$obj->entity) { + $lastcreatedbox .=img_picto($langs->trans("SuperAdministrator"), 'redstar'); + } elseif ($obj->admin) { + $lastcreatedbox .=img_picto($langs->trans("Administrator"), 'star'); } - print "</td>"; - print '<td>'.$obj->login.'</td>'; - print "<td>"; - if ($obj->fk_soc) - { - print $companystatic->getNomUrl(1); + $lastcreatedbox .="</td>"; + $lastcreatedbox .='<td>'.$obj->login.'</td>'; + $lastcreatedbox .="<td>"; + if ($obj->fk_soc) { + $lastcreatedbox .=$companystatic->getNomUrl(1); } else { - print $langs->trans("InternalUser"); + $lastcreatedbox .=$langs->trans("InternalUser"); } - if ($obj->ldap_sid) - { - print ' ('.$langs->trans("DomainUser").')'; + if ($obj->ldap_sid) { + $lastcreatedbox .=' ('.$langs->trans("DomainUser").')'; } $entity = $obj->entity; $entitystring = ''; // TODO Set of entitystring should be done with a hook - if (!empty($conf->multicompany->enabled) && is_object($mc)) - { - if (empty($entity)) - { + if (!empty($conf->multicompany->enabled) && is_object($mc)) { + if (empty($entity)) { $entitystring = $langs->trans("AllEntities"); } else { $mc->getInfo($entity); $entitystring = $mc->label; } } - print ($entitystring ? ' ('.$entitystring.')' : ''); + $lastcreatedbox .=($entitystring ? ' ('.$entitystring.')' : ''); - print '</td>'; - print '<td class="center nowrap">'.dol_print_date($db->jdate($obj->datec), 'dayhour').'</td>'; - print '<td class="right">'; - print $fuserstatic->getLibStatut(3); - print '</td>'; + $lastcreatedbox .='</td>'; + $lastcreatedbox .='<td class="center nowrap">'.dol_print_date($db->jdate($obj->datec), 'dayhour').'</td>'; + $lastcreatedbox .='<td class="right">'; + $lastcreatedbox .=$fuserstatic->getLibStatut(3); + $lastcreatedbox .='</td>'; - print '</tr>'; + $lastcreatedbox .='</tr>'; $i++; } - print "</table>"; - print "</div><br>"; + $lastcreatedbox .="</table>"; + $lastcreatedbox .="</div><br>"; $db->free($resql); } else { @@ -210,14 +216,13 @@ if ($resql) /* * Last groups created */ -if ($canreadperms) -{ +$lastgroupbox = ''; +if ($canreadperms) { $max = 5; $sql = "SELECT g.rowid, g.nom as name, g.note, g.entity, g.datec"; $sql .= " FROM ".MAIN_DB_PREFIX."usergroup as g"; - if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && ($conf->global->MULTICOMPANY_TRANSVERSE_MODE || ($user->admin && !$user->entity))) - { + if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && ($conf->global->MULTICOMPANY_TRANSVERSE_MODE || ($user->admin && !$user->entity))) { $sql .= " WHERE g.entity IS NOT NULL"; } else { $sql .= " WHERE g.entity IN (0,".$conf->entity.")"; @@ -226,50 +231,48 @@ if ($canreadperms) $sql .= $db->plimit($max); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $colspan = 1; - if (!empty($conf->multicompany->enabled)) $colspan++; + if (!empty($conf->multicompany->enabled)) { + $colspan++; + } $num = $db->num_rows($resql); - print '<div class="div-table-responsive-no-min">'; - print '<table class="noborder centpercent">'; - print '<tr class="liste_titre"><td colspan="'.$colspan.'">'.$langs->trans("LastGroupsCreated", ($num ? $num : $max)).'</td>'; - print '<td class="right"><a class="commonlink" href="'.DOL_URL_ROOT.'/user/group/list.php?sortfield=g.datec&sortorder=DESC">'.$langs->trans("FullList").'</td>'; - print '</tr>'; + $lastgroupbox .='<div class="div-table-responsive-no-min">'; + $lastgroupbox .='<table class="noborder centpercent">'; + $lastgroupbox .='<tr class="liste_titre"><td colspan="'.$colspan.'">'.$langs->trans("LastGroupsCreated", ($num ? $num : $max)).'</td>'; + $lastgroupbox .='<td class="right"><a class="commonlink" href="'.DOL_URL_ROOT.'/user/group/list.php?sortfield=g.datec&sortorder=DESC">'.$langs->trans("FullList").'</td>'; + $lastgroupbox .='</tr>'; $i = 0; $grouptemp = new UserGroup($db); - while ($i < $num && (!$max || $i < $max)) - { + while ($i < $num && (!$max || $i < $max)) { $obj = $db->fetch_object($resql); $grouptemp->id = $obj->rowid; $grouptemp->name = $obj->name; $grouptemp->note = $obj->note; - print '<tr class="oddeven">'; - print '<td>'; - print $grouptemp->getNomUrl(1); - if (!$obj->entity) - { - print img_picto($langs->trans("GlobalGroup"), 'redstar'); + $lastgroupbox .='<tr class="oddeven">'; + $lastgroupbox .='<td>'; + $lastgroupbox .=$grouptemp->getNomUrl(1); + if (!$obj->entity) { + $lastgroupbox .=img_picto($langs->trans("GlobalGroup"), 'redstar'); } - print "</td>"; - if (!empty($conf->multicompany->enabled) && is_object($mc)) - { + $lastgroupbox .="</td>"; + if (!empty($conf->multicompany->enabled) && is_object($mc)) { $mc->getInfo($obj->entity); - print '<td>'; - print $mc->label; - print '</td>'; + $lastgroupbox .='<td>'; + $lastgroupbox .=$mc->label; + $lastgroupbox .='</td>'; } - print '<td class="nowrap right">'.dol_print_date($db->jdate($obj->datec), 'dayhour').'</td>'; - print "</tr>"; + $lastgroupbox .='<td class="nowrap right">'.dol_print_date($db->jdate($obj->datec), 'dayhour').'</td>'; + $lastgroupbox .="</tr>"; $i++; } - print "</table>"; - print "</div><br>"; + $lastgroupbox .= "</table>"; + $lastgroupbox .= "</div><br>"; $db->free($resql); } else { @@ -277,7 +280,28 @@ if ($canreadperms) } } -print '</div></div></div>'; +// boxes +print '<div class="clearboth"></div>'; +print '<div class="fichecenter fichecenterbis">'; + +$boxlist = '<div class="twocolumns">'; + +$boxlist .= '<div class="firstcolumn fichehalfleft boxhalfleft" id="boxhalfleft">'; +$boxlist .= $searchbox; +$boxlist .= $resultboxes['boxlista']; +$boxlist .= '</div>'."\n"; + +$boxlist .= '<div class="secondcolumn fichehalfright boxhalfright" id="boxhalfright">'; +$boxlist .= $lastcreatedbox; +$boxlist .= $lastgroupbox; +$boxlist .= $resultboxes['boxlistb']; +$boxlist .= '</div>'."\n"; + +$boxlist .= '</div>'; + +print $boxlist; + +print '</div>'; // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array $parameters = array('user' => $user); diff --git a/htdocs/user/info.php b/htdocs/user/info.php index f38d9ef2162..74b7e70e582 100644 --- a/htdocs/user/info.php +++ b/htdocs/user/info.php @@ -33,22 +33,24 @@ $langs->load("users"); // Security check $id = GETPOST('id', 'int'); $object = new User($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref, '', 1); $object->getrights(); } // Security check $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} $feature2 = (($socid && $user->rights->user->self->creer) ? '' : 'user'); $result = restrictedArea($user, 'user', $id, 'user&user', $feature2); // If user is not user that read and no permission to read other users, we stop -if (($object->id != $user->id) && (!$user->rights->user->user->lire)) - accessforbidden(); +if (($object->id != $user->id) && (!$user->rights->user->user->lire)) { + accessforbidden(); +} diff --git a/htdocs/user/ldap.php b/htdocs/user/ldap.php index 44c7f553d11..e6cee6f6f73 100644 --- a/htdocs/user/ldap.php +++ b/htdocs/user/ldap.php @@ -35,7 +35,9 @@ $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'use // Security check $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} $feature2 = (($socid && $user->rights->user->self->creer) ? '' : 'user'); $result = restrictedArea($user, 'user', $id, 'user&user', $feature2); @@ -55,17 +57,16 @@ $hookmanager->initHooks(array('usercard', 'userldap', 'globalcard')); $parameters = array('id'=>$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)) -{ - if ($_GET["action"] == 'dolibarr2ldap') - { +if (empty($reshook)) { + if ($_GET["action"] == 'dolibarr2ldap') { $ldap = new Ldap(); $result = $ldap->connect_bind(); - if ($result > 0) - { + if ($result > 0) { $info = $object->_load_ldap_info(); $dn = $object->_load_ldap_dn($info); $olddn = $dn; // We can say that old dn = dn as we force synchro @@ -109,20 +110,17 @@ print '<table class="border centpercent">'; // Login print '<tr><td class="titlefield">'.$langs->trans("Login").'</td>'; -if ($object->ldap_sid) -{ +if ($object->ldap_sid) { print '<td class="warning">'.$langs->trans("LoginAccountDisableInDolibarr").'</td>'; } else { print '<td>'.$object->login.'</td>'; } print '</tr>'; -if ($conf->global->LDAP_SERVER_TYPE == "activedirectory") -{ +if ($conf->global->LDAP_SERVER_TYPE == "activedirectory") { $ldap = new Ldap(); $result = $ldap->connect_bind(); - if ($result > 0) - { + if ($result > 0) { $userSID = $ldap->getObjectSid($object->login); } print '<tr><td class="valigntop">'.$langs->trans("SID").'</td>'; @@ -150,19 +148,19 @@ print '</div>'; print dol_get_fiche_end(); /* - * Barre d'actions + * Action bar */ - print '<div class="tabsAction">'; -if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') -{ +if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=dolibarr2ldap">'.$langs->trans("ForceSynchronize").'</a>'; } print "</div>\n"; -if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') print "<br>\n"; +if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') { + print "<br>\n"; +} @@ -179,8 +177,7 @@ print '</tr>'; // Lecture LDAP $ldap = new Ldap(); $result = $ldap->connect_bind(); -if ($result > 0) -{ +if ($result > 0) { $info = $object->_load_ldap_info(); $dn = $object->_load_ldap_dn($info, 1); $search = "(".$object->_load_ldap_dn($info, 2).")"; @@ -190,10 +187,8 @@ if ($result > 0) //print_r($records); // Affichage arbre - if (((!is_numeric($records)) || $records != 0) && (!isset($records['count']) || $records['count'] > 0)) - { - if (!is_array($records)) - { + if (((!is_numeric($records)) || $records != 0) && (!isset($records['count']) || $records['count'] > 0)) { + if (!is_array($records)) { print '<tr class="oddeven"><td colspan="2"><font class="error">'.$langs->trans("ErrorFailedToReadLDAP").'</font></td></tr>'; } else { $result = show_ldap_content($records, 0, $records['count'], true); diff --git a/htdocs/user/list.php b/htdocs/user/list.php index 1f471cd3ad9..f9703116d62 100644 --- a/htdocs/user/list.php +++ b/htdocs/user/list.php @@ -62,7 +62,9 @@ $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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -78,15 +80,20 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); -if (!$sortfield) $sortfield = "u.login"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "u.login"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Initialize array of search criterias $search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } $userstatic = new User($db); @@ -104,28 +111,27 @@ $fieldstosearchall = array( 'u.email'=>"EMail", 'u.note'=>"Note", ); -if (!empty($conf->api->enabled)) -{ +if (!empty($conf->api->enabled)) { $fieldstosearchall['u.api_key'] = "ApiKey"; } // Definition of fields for list $arrayfields = array( 'u.login'=>array('label'=>"Login", 'checked'=>1, 'position'=>10), - 'u.lastname'=>array('label'=>"Lastname", 'checked'=>1, 'position'=>15), - 'u.firstname'=>array('label'=>"Firstname", 'checked'=>1, 'position'=>20), - 'u.entity'=>array('label'=>"Entity", 'checked'=>1, 'position'=>50, 'enabled'=>(!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))), - 'u.gender'=>array('label'=>"Gender", 'checked'=>0, 'position'=>22), - 'u.employee'=>array('label'=>"Employee", 'checked'=>($mode == 'employee' ? 1 : 0), 'position'=>25), - 'u.fk_user'=>array('label'=>"HierarchicalResponsible", 'checked'=>1, 'position'=>27), - 'u.accountancy_code'=>array('label'=>"AccountancyCode", 'checked'=>0, 'position'=>30), + 'u.lastname'=>array('label'=>"Lastname", 'checked'=>1, 'position'=>15), + 'u.firstname'=>array('label'=>"Firstname", 'checked'=>1, 'position'=>20), + 'u.entity'=>array('label'=>"Entity", 'checked'=>1, 'position'=>50, 'enabled'=>(!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))), + 'u.gender'=>array('label'=>"Gender", 'checked'=>0, 'position'=>22), + 'u.employee'=>array('label'=>"Employee", 'checked'=>($mode == 'employee' ? 1 : 0), 'position'=>25), + 'u.fk_user'=>array('label'=>"HierarchicalResponsible", 'checked'=>1, 'position'=>27), + 'u.accountancy_code'=>array('label'=>"AccountancyCode", 'checked'=>0, 'position'=>30), 'u.office_phone'=>array('label'=>"PhonePro", 'checked'=>1, 'position'=>31), 'u.user_mobile'=>array('label'=>"PhoneMobile", 'checked'=>1, 'position'=>32), - 'u.email'=>array('label'=>"EMail", 'checked'=>1, 'position'=>35), - 'u.api_key'=>array('label'=>"ApiKey", 'checked'=>0, 'position'=>40, "enabled"=>($conf->api->enabled && $user->admin)), - 'u.fk_soc'=>array('label'=>"Company", 'checked'=>($contextpage == 'employeelist' ? 0 : 1), 'position'=>45), - 'u.salary'=>array('label'=>"Salary", 'checked'=>1, 'position'=>80, 'enabled'=>($conf->salaries->enabled && !empty($user->rights->salaries->readall))), - 'u.datelastlogin'=>array('label'=>"LastConnexion", 'checked'=>1, 'position'=>100), + 'u.email'=>array('label'=>"EMail", 'checked'=>1, 'position'=>35), + 'u.api_key'=>array('label'=>"ApiKey", 'checked'=>0, 'position'=>40, "enabled"=>($conf->api->enabled && $user->admin)), + 'u.fk_soc'=>array('label'=>"Company", 'checked'=>($contextpage == 'employeelist' ? 0 : 1), 'position'=>45), + 'u.salary'=>array('label'=>"Salary", 'checked'=>1, 'position'=>80, 'enabled'=>($conf->salaries->enabled && !empty($user->rights->salaries->readall))), + 'u.datelastlogin'=>array('label'=>"LastConnexion", 'checked'=>1, 'position'=>100), 'u.datepreviouslogin'=>array('label'=>"PreviousConnexion", 'checked'=>0, 'position'=>110), 'u.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500), 'u.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), @@ -158,8 +164,12 @@ $search_categ = GETPOST("search_categ", 'int'); $catid = GETPOST('catid', 'int'); // Default search -if ($search_statut == '') $search_statut = '1'; -if ($mode == 'employee' && !GETPOSTISSET('search_employee')) $search_employee = 1; +if ($search_statut == '') { + $search_statut = '1'; +} +if ($mode == 'employee' && !GETPOSTISSET('search_employee')) { + $search_employee = 1; +} // Define value to know what current user can do on users $permissiontoadd = (!empty($user->admin) || $user->rights->user->user->creer); @@ -168,8 +178,7 @@ $canedituser = (!empty($user->admin) || $user->rights->user->user->creer); $candisableuser = (!empty($user->admin) || $user->rights->user->user->supprimer); $canreadgroup = $canreaduser; $caneditgroup = $canedituser; -if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $canreadgroup = (!empty($user->admin) || $user->rights->user->group_advance->read); $caneditgroup = (!empty($user->admin) || $user->rights->user->group_advance->write); } @@ -183,21 +192,25 @@ $childids = $user->getAllChildIds(1); * 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(); $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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_user = ""; $search_login = ""; $search_lastname = ""; @@ -227,17 +240,14 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; // Disable or Enable records - if (!$error && ($massaction == 'disable' || $massaction == 'reactivate') && $permissiontoadd) - { + if (!$error && ($massaction == 'disable' || $massaction == 'reactivate') && $permissiontoadd) { $objecttmp = new User($db); - if (!$error) - { + if (!$error) { $db->begin(); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { if ($toselectid == $user->id) { setEventMessages($langs->trans($massaction == 0 ? 'CantDisableYourself' : 'CanEnableYourself'), null, 'errors'); $error++; @@ -259,7 +269,9 @@ if (empty($reshook)) setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -275,10 +287,12 @@ if (empty($reshook)) } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -294,8 +308,8 @@ if (empty($reshook)) $formother = new FormOther($db); -//$help_url="EN:Module_MyObject|FR:Module_MyObject_FR|ES:Módulo_MyObject"; -$help_url = ''; +$help_url = 'EN:Module_Users|FR:Module_Utilisateurs|ES:M&oacute;dulo_Usuarios|DE:Modul_Benutzer'; + if ($contextpage == 'employeelist' && $search_employee == 1) { $text = $langs->trans("ListOfEmployees"); } else { @@ -327,7 +341,9 @@ if (is_array($extrafields->attributes[$object->table_element]['label']) && count } $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON u.fk_soc = s.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u2 ON u.fk_user = u2.rowid"; -if (!empty($search_categ) || !empty($catid)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_user as cu ON u.rowid = cu.fk_user"; // We'll need this table joined to the select in order to filter by categ +if (!empty($search_categ) || !empty($catid)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_user as cu ON u.rowid = cu.fk_user"; // We'll need this table joined to the select in order to filter by categ +} // Add fields from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook @@ -336,29 +352,67 @@ if ($reshook > 0) { } else { $sql .= " WHERE u.entity IN (".getEntity('user').")"; } -if ($socid > 0) $sql .= " AND u.fk_soc = ".$socid; +if ($socid > 0) { + $sql .= " AND u.fk_soc = ".$socid; +} //if ($search_user != '') $sql.=natural_search(array('u.login', 'u.lastname', 'u.firstname'), $search_user); -if ($search_supervisor > 0) $sql .= " AND u.fk_user IN (".$db->sanitize($db->escape($search_supervisor)).")"; -if ($search_thirdparty != '') $sql .= natural_search(array('s.nom'), $search_thirdparty); -if ($search_login != '') $sql .= natural_search("u.login", $search_login); -if ($search_lastname != '') $sql .= natural_search("u.lastname", $search_lastname); -if ($search_firstname != '') $sql .= natural_search("u.firstname", $search_firstname); -if ($search_gender != '' && $search_gender != '-1') $sql .= " AND u.gender = '".$db->escape($search_gender)."'"; // Cannot use natural_search as looking for %man% also includes woman +if ($search_supervisor > 0) { + $sql .= " AND u.fk_user IN (".$db->sanitize($db->escape($search_supervisor)).")"; +} +if ($search_thirdparty != '') { + $sql .= natural_search(array('s.nom'), $search_thirdparty); +} +if ($search_login != '') { + $sql .= natural_search("u.login", $search_login); +} +if ($search_lastname != '') { + $sql .= natural_search("u.lastname", $search_lastname); +} +if ($search_firstname != '') { + $sql .= natural_search("u.firstname", $search_firstname); +} +if ($search_gender != '' && $search_gender != '-1') { + $sql .= " AND u.gender = '".$db->escape($search_gender)."'"; // Cannot use natural_search as looking for %man% also includes woman +} if (is_numeric($search_employee) && $search_employee >= 0) { $sql .= ' AND u.employee = '.(int) $search_employee; } -if ($search_accountancy_code != '') $sql .= natural_search("u.accountancy_code", $search_accountancy_code); -if ($search_phonepro != '') $sql .= natural_search("u.office_phone", $search_phonepro); -if ($search_phonemobile != '') $sql .= natural_search("u.user_mobile", $search_phonemobile); -if ($search_email != '') $sql .= natural_search("u.email", $search_email); -if ($search_api_key != '') $sql .= natural_search("u.api_key", $search_api_key); -if ($search_statut != '' && $search_statut >= 0) $sql .= " AND u.statut IN (".$db->sanitize($db->escape($search_statut)).")"; -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if ($catid > 0) $sql .= " AND cu.fk_categorie = ".((int) $catid); -if ($catid == -2) $sql .= " AND cu.fk_categorie IS NULL"; -if ($search_categ > 0) $sql .= " AND cu.fk_categorie = ".$db->escape($search_categ); -if ($search_categ == -2) $sql .= " AND cu.fk_categorie IS NULL"; -if ($mode == 'employee' && empty($user->rights->salaries->readall)) $sql .= " AND u.fk_user IN (".join(',', $childids).")"; +if ($search_accountancy_code != '') { + $sql .= natural_search("u.accountancy_code", $search_accountancy_code); +} +if ($search_phonepro != '') { + $sql .= natural_search("u.office_phone", $search_phonepro); +} +if ($search_phonemobile != '') { + $sql .= natural_search("u.user_mobile", $search_phonemobile); +} +if ($search_email != '') { + $sql .= natural_search("u.email", $search_email); +} +if ($search_api_key != '') { + $sql .= natural_search("u.api_key", $search_api_key); +} +if ($search_statut != '' && $search_statut >= 0) { + $sql .= " AND u.statut IN (".$db->sanitize($db->escape($search_statut)).")"; +} +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} +if ($catid > 0) { + $sql .= " AND cu.fk_categorie = ".((int) $catid); +} +if ($catid == -2) { + $sql .= " AND cu.fk_categorie IS NULL"; +} +if ($search_categ > 0) { + $sql .= " AND cu.fk_categorie = ".$db->escape($search_categ); +} +if ($search_categ == -2) { + $sql .= " AND cu.fk_categorie IS NULL"; +} +if ($mode == 'employee' && empty($user->rights->salaries->readall)) { + $sql .= " AND u.fk_user IN (".join(',', $childids).")"; +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -369,26 +423,24 @@ $sql .= $db->order($sortfield, $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 || empty($limit))) -{ +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -397,8 +449,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/user/card.php?id='.$id); @@ -411,40 +462,88 @@ if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $ llxHeader('', $langs->trans("ListOfUsers"), $help_url); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&amp;contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&amp;limit='.urlencode($limit); -if ($sall != '') $param .= '&amp;sall='.urlencode($sall); -if ($search_user != '') $param .= "&amp;search_user=".urlencode($search_user); -if ($search_login != '') $param .= "&amp;search_login=".urlencode($search_login); -if ($search_lastname != '') $param .= "&amp;search_lastname=".urlencode($search_lastname); -if ($search_firstname != '') $param .= "&amp;search_firstname=".urlencode($search_firstname); -if ($search_gender != '') $param .= "&amp;search_gender=".urlencode($search_gender); -if ($search_employee != '') $param .= "&amp;search_employee=".urlencode($search_employee); -if ($search_accountancy_code != '') $param .= "&amp;search_accountancy_code=".urlencode($search_accountancy_code); -if ($search_phonepro != '') $param .= "&amp;search_phonepro=".urlencode($search_phonepro); -if ($search_phonemobile != '') $param .= "&amp;search_phonemobile=".urlencode($search_phonemobile); -if ($search_email != '') $param .= "&amp;search_email=".urlencode($search_email); -if ($search_api_key != '') $param .= "&amp;search_api_key=".urlencode($search_api_key); -if ($search_supervisor > 0) $param .= "&amp;search_supervisor=".urlencode($search_supervisor); -if ($search_statut != '') $param .= "&amp;search_statut=".urlencode($search_statut); -if ($optioncss != '') $param .= '&amp;optioncss='.urlencode($optioncss); -if ($mode != '') $param .= '&amp;mode='.urlencode($mode); -if ($search_categ > 0) $param .= "&amp;search_categ=".urlencode($search_categ); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&amp;contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&amp;limit='.urlencode($limit); +} +if ($sall != '') { + $param .= '&amp;sall='.urlencode($sall); +} +if ($search_user != '') { + $param .= "&amp;search_user=".urlencode($search_user); +} +if ($search_login != '') { + $param .= "&amp;search_login=".urlencode($search_login); +} +if ($search_lastname != '') { + $param .= "&amp;search_lastname=".urlencode($search_lastname); +} +if ($search_firstname != '') { + $param .= "&amp;search_firstname=".urlencode($search_firstname); +} +if ($search_gender != '') { + $param .= "&amp;search_gender=".urlencode($search_gender); +} +if ($search_employee != '') { + $param .= "&amp;search_employee=".urlencode($search_employee); +} +if ($search_accountancy_code != '') { + $param .= "&amp;search_accountancy_code=".urlencode($search_accountancy_code); +} +if ($search_phonepro != '') { + $param .= "&amp;search_phonepro=".urlencode($search_phonepro); +} +if ($search_phonemobile != '') { + $param .= "&amp;search_phonemobile=".urlencode($search_phonemobile); +} +if ($search_email != '') { + $param .= "&amp;search_email=".urlencode($search_email); +} +if ($search_api_key != '') { + $param .= "&amp;search_api_key=".urlencode($search_api_key); +} +if ($search_supervisor > 0) { + $param .= "&amp;search_supervisor=".urlencode($search_supervisor); +} +if ($search_statut != '') { + $param .= "&amp;search_statut=".urlencode($search_statut); +} +if ($optioncss != '') { + $param .= '&amp;optioncss='.urlencode($optioncss); +} +if ($mode != '') { + $param .= '&amp;mode='.urlencode($mode); +} +if ($search_categ > 0) { + $param .= "&amp;search_categ=".urlencode($search_categ); +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available $arrayofmassactions = array(); -if ($permissiontoadd) $arrayofmassactions['disable'] = $langs->trans("DisableUser"); -if ($permissiontoadd) $arrayofmassactions['reactivate'] = $langs->trans("Reactivate"); -if ($permissiontoadd) $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); +if ($permissiontoadd) { + $arrayofmassactions['disable'] = $langs->trans("DisableUser"); +} +if ($permissiontoadd) { + $arrayofmassactions['reactivate'] = $langs->trans("Reactivate"); +} +if ($permissiontoadd) { + $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); +} //if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete', 'preaffecttag'))) $arrayofmassactions = array(); +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete', 'preaffecttag'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; @@ -453,7 +552,9 @@ print '<input type="hidden" name="mode" value="'.$mode.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; $url = DOL_URL_ROOT.'/user/card.php?action=create'.($mode == 'employee' ? '&employee=1' : '').'&leftmenu='; -if (!empty($socid)) $url .= '&socid='.$socid; +if (!empty($socid)) { + $url .= '&socid='.$socid; +} $newcardbutton = dolGetButtonTitle($langs->trans('NewUser'), '', 'fa fa-plus-circle', $url, '', $permissiontoadd); @@ -471,8 +572,7 @@ $objecttmp = new User($db); $trackid = 'use'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if (!empty($catid)) -{ +if (!empty($catid)) { print "<div id='ways'>"; $c = new Categorie($db); $ways = $c->print_all_ways(' &gt; ', 'user/list.php'); @@ -480,9 +580,10 @@ if (!empty($catid)) print "</div><br>"; } -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } @@ -492,8 +593,7 @@ $moreforfilter = ''; $moreforfilter.= '</div>';*/ // Filter on categories -if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) -{ +if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('Categories').': '; $moreforfilter .= $formother->select_categories(Categorie::TYPE_USER, $search_categ, 'search_categ', 1); @@ -502,11 +602,13 @@ if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -522,76 +624,60 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit // Fields title search // -------------------------------------------------------------------- print '<tr class="liste_titre_filter">'; -if (!empty($arrayfields['u.login']['checked'])) -{ +if (!empty($arrayfields['u.login']['checked'])) { print '<td class="liste_titre"><input type="text" name="search_login" class="maxwidth50" value="'.$search_login.'"></td>'; } -if (!empty($arrayfields['u.lastname']['checked'])) -{ +if (!empty($arrayfields['u.lastname']['checked'])) { print '<td class="liste_titre"><input type="text" name="search_lastname" class="maxwidth50" value="'.$search_lastname.'"></td>'; } -if (!empty($arrayfields['u.firstname']['checked'])) -{ +if (!empty($arrayfields['u.firstname']['checked'])) { print '<td class="liste_titre"><input type="text" name="search_firstname" class="maxwidth50" value="'.$search_firstname.'"></td>'; } -if (!empty($arrayfields['u.gender']['checked'])) -{ +if (!empty($arrayfields['u.gender']['checked'])) { print '<td class="liste_titre">'; $arraygender = array('man'=>$langs->trans("Genderman"), 'woman'=>$langs->trans("Genderwoman"), 'other'=>$langs->trans("Genderother")); print $form->selectarray('search_gender', $arraygender, $search_gender, 1); print '</td>'; } -if (!empty($arrayfields['u.employee']['checked'])) -{ +if (!empty($arrayfields['u.employee']['checked'])) { print '<td class="liste_titre">'; print $form->selectyesno('search_employee', $search_employee, 1, false, 1); print '</td>'; } // Supervisor -if (!empty($arrayfields['u.fk_user']['checked'])) -{ - print '<td class="liste_titre">'; - print $form->select_dolusers($search_supervisor, 'search_supervisor', 1, array(), 0, '', 0, 0, 0, 0, '', 0, '', 'maxwidth200'); - print '</td>'; +if (!empty($arrayfields['u.fk_user']['checked'])) { + print '<td class="liste_titre">'; + print $form->select_dolusers($search_supervisor, 'search_supervisor', 1, array(), 0, '', 0, 0, 0, 0, '', 0, '', 'maxwidth200'); + print '</td>'; } -if (!empty($arrayfields['u.accountancy_code']['checked'])) -{ +if (!empty($arrayfields['u.accountancy_code']['checked'])) { print '<td class="liste_titre"><input type="text" name="search_accountancy_code" class="maxwidth50" value="'.$search_accountancy_code.'"></td>'; } -if (!empty($arrayfields['u.office_phone']['checked'])) -{ +if (!empty($arrayfields['u.office_phone']['checked'])) { print '<td class="liste_titre"><input type="text" name="search_phonepro" class="maxwidth75" value="'.$search_phonepro.'"></td>'; } -if (!empty($arrayfields['u.user_mobile']['checked'])) -{ +if (!empty($arrayfields['u.user_mobile']['checked'])) { print '<td class="liste_titre"><input type="text" name="search_phonemobile" class="maxwidth75" value="'.$search_phonemobile.'"></td>'; } -if (!empty($arrayfields['u.email']['checked'])) -{ +if (!empty($arrayfields['u.email']['checked'])) { print '<td class="liste_titre"><input type="text" name="search_email" class="maxwidth75" value="'.$search_email.'"></td>'; } -if (!empty($arrayfields['u.api_key']['checked'])) -{ +if (!empty($arrayfields['u.api_key']['checked'])) { print '<td class="liste_titre"><input type="text" name="search_api_key" class="maxwidth50" value="'.$search_api_key.'"></td>'; } -if (!empty($arrayfields['u.fk_soc']['checked'])) -{ +if (!empty($arrayfields['u.fk_soc']['checked'])) { print '<td class="liste_titre"><input type="text" name="search_thirdparty" class="maxwidth75" value="'.$search_thirdparty.'"></td>'; } -if (!empty($arrayfields['u.entity']['checked'])) -{ +if (!empty($arrayfields['u.entity']['checked'])) { print '<td class="liste_titre"></td>'; } -if (!empty($arrayfields['u.salary']['checked'])) -{ - print '<td class="liste_titre"></td>'; -} -if (!empty($arrayfields['u.datelastlogin']['checked'])) -{ +if (!empty($arrayfields['u.salary']['checked'])) { print '<td class="liste_titre"></td>'; } -if (!empty($arrayfields['u.datepreviouslogin']['checked'])) -{ +if (!empty($arrayfields['u.datelastlogin']['checked'])) { + print '<td class="liste_titre"></td>'; +} +if (!empty($arrayfields['u.datepreviouslogin']['checked'])) { print '<td class="liste_titre"></td>'; } // Extra fields @@ -600,20 +686,17 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (!empty($arrayfields['u.datec']['checked'])) -{ +if (!empty($arrayfields['u.datec']['checked'])) { // Date creation print '<td class="liste_titre">'; print '</td>'; } -if (!empty($arrayfields['u.tms']['checked'])) -{ +if (!empty($arrayfields['u.tms']['checked'])) { // Date modification print '<td class="liste_titre">'; print '</td>'; } -if (!empty($arrayfields['u.statut']['checked'])) -{ +if (!empty($arrayfields['u.statut']['checked'])) { // Status print '<td class="liste_titre center">'; print $form->selectarray('search_statut', array('-1'=>'', '0'=>$langs->trans('Disabled'), '1'=>$langs->trans('Enabled')), $search_statut); @@ -628,31 +711,69 @@ print '</tr>'."\n"; print '<tr class="liste_titre">'; -if (!empty($arrayfields['u.login']['checked'])) print_liste_field_titre("Login", $_SERVER['PHP_SELF'], "u.login", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.lastname']['checked'])) print_liste_field_titre("Lastname", $_SERVER['PHP_SELF'], "u.lastname", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.firstname']['checked'])) print_liste_field_titre("FirstName", $_SERVER['PHP_SELF'], "u.firstname", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.gender']['checked'])) print_liste_field_titre("Gender", $_SERVER['PHP_SELF'], "u.gender", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.employee']['checked'])) print_liste_field_titre("Employee", $_SERVER['PHP_SELF'], "u.employee", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.fk_user']['checked'])) print_liste_field_titre("HierarchicalResponsible", $_SERVER['PHP_SELF'], "u.fk_user", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.accountancy_code']['checked'])) print_liste_field_titre("AccountancyCode", $_SERVER['PHP_SELF'], "u.accountancy_code", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.office_phone']['checked'])) print_liste_field_titre("PhonePro", $_SERVER['PHP_SELF'], "u.office_phone", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.user_mobile']['checked'])) print_liste_field_titre("PhoneMobile", $_SERVER['PHP_SELF'], "u.user_mobile", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.email']['checked'])) print_liste_field_titre("EMail", $_SERVER['PHP_SELF'], "u.email", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.api_key']['checked'])) print_liste_field_titre("ApiKey", $_SERVER['PHP_SELF'], "u.api_key", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.fk_soc']['checked'])) print_liste_field_titre("Company", $_SERVER['PHP_SELF'], "u.fk_soc", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.entity']['checked'])) print_liste_field_titre("Entity", $_SERVER['PHP_SELF'], "u.entity", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['u.salary']['checked'])) print_liste_field_titre("Salary", $_SERVER['PHP_SELF'], "u.salary", $param, "", "", $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['u.datelastlogin']['checked'])) print_liste_field_titre("LastConnexion", $_SERVER['PHP_SELF'], "u.datelastlogin", $param, "", '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['u.datepreviouslogin']['checked'])) print_liste_field_titre("PreviousConnexion", $_SERVER['PHP_SELF'], "u.datepreviouslogin", $param, "", '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['u.login']['checked'])) { + print_liste_field_titre("Login", $_SERVER['PHP_SELF'], "u.login", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.lastname']['checked'])) { + print_liste_field_titre("Lastname", $_SERVER['PHP_SELF'], "u.lastname", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.firstname']['checked'])) { + print_liste_field_titre("FirstName", $_SERVER['PHP_SELF'], "u.firstname", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.gender']['checked'])) { + print_liste_field_titre("Gender", $_SERVER['PHP_SELF'], "u.gender", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.employee']['checked'])) { + print_liste_field_titre("Employee", $_SERVER['PHP_SELF'], "u.employee", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.fk_user']['checked'])) { + print_liste_field_titre("HierarchicalResponsible", $_SERVER['PHP_SELF'], "u.fk_user", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.accountancy_code']['checked'])) { + print_liste_field_titre("AccountancyCode", $_SERVER['PHP_SELF'], "u.accountancy_code", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.office_phone']['checked'])) { + print_liste_field_titre("PhonePro", $_SERVER['PHP_SELF'], "u.office_phone", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.user_mobile']['checked'])) { + print_liste_field_titre("PhoneMobile", $_SERVER['PHP_SELF'], "u.user_mobile", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.email']['checked'])) { + print_liste_field_titre("EMail", $_SERVER['PHP_SELF'], "u.email", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.api_key']['checked'])) { + print_liste_field_titre("ApiKey", $_SERVER['PHP_SELF'], "u.api_key", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.fk_soc']['checked'])) { + print_liste_field_titre("Company", $_SERVER['PHP_SELF'], "u.fk_soc", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.entity']['checked'])) { + print_liste_field_titre("Entity", $_SERVER['PHP_SELF'], "u.entity", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['u.salary']['checked'])) { + print_liste_field_titre("Salary", $_SERVER['PHP_SELF'], "u.salary", $param, "", "", $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['u.datelastlogin']['checked'])) { + print_liste_field_titre("LastConnexion", $_SERVER['PHP_SELF'], "u.datelastlogin", $param, "", '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['u.datepreviouslogin']['checked'])) { + print_liste_field_titre("PreviousConnexion", $_SERVER['PHP_SELF'], "u.datepreviouslogin", $param, "", '', $sortfield, $sortorder, 'center '); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (!empty($arrayfields['u.datec']['checked'])) print_liste_field_titre("DateCreationShort", $_SERVER["PHP_SELF"], "u.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['u.tms']['checked'])) print_liste_field_titre("DateModificationShort", $_SERVER["PHP_SELF"], "u.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['u.statut']['checked'])) print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "u.statut", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['u.datec']['checked'])) { + print_liste_field_titre("DateCreationShort", $_SERVER["PHP_SELF"], "u.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['u.tms']['checked'])) { + print_liste_field_titre("DateModificationShort", $_SERVER["PHP_SELF"], "u.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['u.statut']['checked'])) { + print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "u.statut", "", $param, '', $sortfield, $sortorder, 'center '); +} // Action column print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; print '</tr>'."\n"; @@ -660,11 +781,11 @@ print '</tr>'."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -674,10 +795,11 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co $i = 0; $totalarray = array(); $arrayofselected = is_array($toselect) ? $toselect : array(); -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->setVarsFromFetchObj($obj); @@ -700,154 +822,163 @@ while ($i < ($limit ? min($num, $limit) : $num)) $li = $userstatic->getNomUrl(-1, '', 0, 0, 24, 1, 'login', '', 1); print '<tr class="oddeven">'; - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { print '<td class="nowraponall">'; print $li; - if (!empty($conf->multicompany->enabled) && $obj->admin && !$obj->entity) - { - print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); - } elseif ($obj->admin) - { + if (!empty($conf->multicompany->enabled) && $obj->admin && !$obj->entity) { + print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); + } elseif ($obj->admin) { print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['u.lastname']['checked'])) - { + if (!empty($arrayfields['u.lastname']['checked'])) { print '<td class="tdoverflowmax150">'.$obj->lastname.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['u.firstname']['checked'])) - { + if (!empty($arrayfields['u.firstname']['checked'])) { print '<td class="tdoverflowmax150">'.$obj->firstname.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['u.gender']['checked'])) - { + if (!empty($arrayfields['u.gender']['checked'])) { print '<td>'; - if ($obj->gender) print $langs->trans("Gender".$obj->gender); + if ($obj->gender) { + print $langs->trans("Gender".$obj->gender); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['u.employee']['checked'])) - { + if (!empty($arrayfields['u.employee']['checked'])) { print '<td>'.yn($obj->employee).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Supervisor - if (!empty($arrayfields['u.fk_user']['checked'])) - { - // Resp - print '<td class="nowrap">'; - if ($obj->login2) - { - $user2->id = $obj->id2; - $user2->login = $obj->login2; - $user2->lastname = $obj->lastname2; - $user2->firstname = $obj->firstname2; - $user2->gender = $obj->gender2; - $user2->photo = $obj->photo2; - $user2->admin = $obj->admin2; + if (!empty($arrayfields['u.fk_user']['checked'])) { + // Resp + print '<td class="nowrap">'; + if ($obj->login2) { + $user2->id = $obj->id2; + $user2->login = $obj->login2; + $user2->lastname = $obj->lastname2; + $user2->firstname = $obj->firstname2; + $user2->gender = $obj->gender2; + $user2->photo = $obj->photo2; + $user2->admin = $obj->admin2; $user2->office_phone = $obj->office_phone; $user2->user_mobile = $obj->user_mobile; - $user2->email = $obj->email2; - $user2->socid = $obj->fk_soc2; - $user2->statut = $obj->statut2; - print $user2->getNomUrl(-1, '', 0, 0, 24, 0, '', '', 1); - if (!empty($conf->multicompany->enabled) && $obj->admin2 && !$obj->entity2) - { - print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); - } elseif ($obj->admin2) - { - print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); - } - } - print '</td>'; - if (!$i) $totalarray['nbfield']++; + $user2->email = $obj->email2; + $user2->socid = $obj->fk_soc2; + $user2->statut = $obj->statut2; + print $user2->getNomUrl(-1, '', 0, 0, 24, 0, '', '', 1); + if (!empty($conf->multicompany->enabled) && $obj->admin2 && !$obj->entity2) { + print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); + } elseif ($obj->admin2) { + print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); + } + } + print '</td>'; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['u.accountancy_code']['checked'])) - { + if (!empty($arrayfields['u.accountancy_code']['checked'])) { print '<td>'.$obj->accountancy_code.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['u.office_phone']['checked'])) - { + if (!empty($arrayfields['u.office_phone']['checked'])) { print "<td>".dol_print_phone($obj->office_phone, $obj->country_code, 0, $obj->rowid, 'AC_TEL', ' ', 'phone')."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['u.user_mobile']['checked'])) - { + if (!empty($arrayfields['u.user_mobile']['checked'])) { print "<td>".dol_print_phone($obj->user_mobile, $obj->country_code, 0, $obj->rowid, 'AC_TEL', ' ', 'mobile')."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['u.email']['checked'])) - { + if (!empty($arrayfields['u.email']['checked'])) { print '<td class="tdoverflowmax150">'.dol_print_email($obj->email, $obj->rowid, $obj->socid, 'AC_EMAIL', 0, 0, 1)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['u.api_key']['checked'])) - { + if (!empty($arrayfields['u.api_key']['checked'])) { print '<td>'.$obj->api_key.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['u.fk_soc']['checked'])) - { - print "<td>"; - if ($obj->fk_soc) - { + if (!empty($arrayfields['u.fk_soc']['checked'])) { + print '<td class="tdoverflowmax200">'; + if ($obj->fk_soc) { $companystatic->id = $obj->fk_soc; $companystatic->name = $obj->name; $companystatic->canvas = $obj->canvas; print $companystatic->getNomUrl(1); - } elseif ($obj->ldap_sid) - { - print $langs->trans("DomainUser"); + } elseif ($obj->ldap_sid) { + print '<span class="opacitymedium">'.$langs->trans("DomainUser").'</span>'; } else { - print $langs->trans("InternalUser"); + print '<span class="opacitymedium">'.$langs->trans("InternalUser").'</span>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Multicompany enabled - if (!empty($conf->multicompany->enabled) && is_object($mc) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - if (!empty($arrayfields['u.entity']['checked'])) - { + if (!empty($conf->multicompany->enabled) && is_object($mc) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + if (!empty($arrayfields['u.entity']['checked'])) { print '<td>'; - if (!$obj->entity) - { + if (!$obj->entity) { print $langs->trans("AllEntities"); } else { $mc->getInfo($obj->entity); print $mc->label; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } } // Salary - if (!empty($arrayfields['u.salary']['checked'])) - { - print '<td class="nowraponall right">'.($obj->salary ? price($obj->salary) : '').'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!empty($arrayfields['u.salary']['checked'])) { + print '<td class="nowraponall right">'.($obj->salary ? price($obj->salary) : '').'</td>'; + if (!$i) { + $totalarray['nbfield']++; + } } // Date last login - if (!empty($arrayfields['u.datelastlogin']['checked'])) - { + if (!empty($arrayfields['u.datelastlogin']['checked'])) { print '<td class="nowrap center">'.dol_print_date($db->jdate($obj->datelastlogin), "dayhour").'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date previous login - if (!empty($arrayfields['u.datepreviouslogin']['checked'])) - { + if (!empty($arrayfields['u.datepreviouslogin']['checked'])) { print '<td class="nowrap center">'.dol_print_date($db->jdate($obj->datepreviouslogin), "dayhour").'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -857,38 +988,44 @@ while ($i < ($limit ? min($num, $limit) : $num)) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['u.datec']['checked'])) - { + if (!empty($arrayfields['u.datec']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['u.tms']['checked'])) - { + if (!empty($arrayfields['u.tms']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['u.statut']['checked'])) - { + if (!empty($arrayfields['u.statut']['checked'])) { $userstatic->statut = $obj->statut; print '<td class="center">'.$userstatic->getLibStatut(5).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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($object->id, $arrayofselected)) $selected = 1; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'."\n"; @@ -899,10 +1036,13 @@ while ($i < ($limit ? min($num, $limit) : $num)) include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } diff --git a/htdocs/user/logout.php b/htdocs/user/logout.php index 5cb03af224f..57a653a01d1 100644 --- a/htdocs/user/logout.php +++ b/htdocs/user/logout.php @@ -24,17 +24,24 @@ */ //if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Uncomment creates pb to relogon after a disconnect -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // We need company to get correct logo onto home page -if (!defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) define('EVEN_IF_ONLY_LOGIN_ALLOWED', '1'); +if (!defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) { + define('EVEN_IF_ONLY_LOGIN_ALLOWED', '1'); +} require_once '../main.inc.php'; // This can happen only with a bookmark or forged url call. -if (!empty($_SESSION["dol_authmode"]) && ($_SESSION["dol_authmode"] == 'forceuser' || $_SESSION["dol_authmode"] == 'http')) -{ +if (!empty($_SESSION["dol_authmode"]) && ($_SESSION["dol_authmode"] == 'forceuser' || $_SESSION["dol_authmode"] == 'http')) { unset($_SESSION["dol_login"]); die("Applicative disconnection should be useless when connection was made in mode ".$_SESSION["dol_authmode"]); } @@ -43,7 +50,9 @@ global $conf, $langs, $user; // Call trigger $result = $user->call_trigger('USER_LOGOUT', $user); -if ($result < 0) $error++; +if ($result < 0) { + $error++; +} // End call triggers // Hooks on logout @@ -51,26 +60,41 @@ $action = ''; $hookmanager->initHooks(array('logout')); $parameters = array(); $reshook = $hookmanager->executeHooks('afterLogout', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) { $error++; } +if ($reshook < 0) { + $error++; +} // Define url to go after disconnect $urlfrom = empty($_SESSION["urlfrom"]) ? '' : $_SESSION["urlfrom"]; // Define url to go $url = DOL_URL_ROOT."/index.php"; // By default go to login page -if ($urlfrom) $url = DOL_URL_ROOT.$urlfrom; -if (!empty($conf->global->MAIN_LOGOUT_GOTO_URL)) $url = $conf->global->MAIN_LOGOUT_GOTO_URL; +if ($urlfrom) { + $url = DOL_URL_ROOT.$urlfrom; +} +if (!empty($conf->global->MAIN_LOGOUT_GOTO_URL)) { + $url = $conf->global->MAIN_LOGOUT_GOTO_URL; +} -if (GETPOST('dol_hide_topmenu')) $url .= (preg_match('/\?/', $url) ? '&' : '?').'dol_hide_topmenu=1'; -if (GETPOST('dol_hide_leftmenu')) $url .= (preg_match('/\?/', $url) ? '&' : '?').'dol_hide_leftmenu=1'; -if (GETPOST('dol_optimize_smallscreen')) $url .= (preg_match('/\?/', $url) ? '&' : '?').'dol_optimize_smallscreen=1'; -if (GETPOST('dol_no_mouse_hover')) $url .= (preg_match('/\?/', $url) ? '&' : '?').'dol_no_mouse_hover=1'; -if (GETPOST('dol_use_jmobile')) $url .= (preg_match('/\?/', $url) ? '&' : '?').'dol_use_jmobile=1'; +if (GETPOST('dol_hide_topmenu')) { + $url .= (preg_match('/\?/', $url) ? '&' : '?').'dol_hide_topmenu=1'; +} +if (GETPOST('dol_hide_leftmenu')) { + $url .= (preg_match('/\?/', $url) ? '&' : '?').'dol_hide_leftmenu=1'; +} +if (GETPOST('dol_optimize_smallscreen')) { + $url .= (preg_match('/\?/', $url) ? '&' : '?').'dol_optimize_smallscreen=1'; +} +if (GETPOST('dol_no_mouse_hover')) { + $url .= (preg_match('/\?/', $url) ? '&' : '?').'dol_no_mouse_hover=1'; +} +if (GETPOST('dol_use_jmobile')) { + $url .= (preg_match('/\?/', $url) ? '&' : '?').'dol_use_jmobile=1'; +} // Destroy session dol_syslog("End of session ".session_id()); -if (session_status() === PHP_SESSION_ACTIVE) -{ +if (session_status() === PHP_SESSION_ACTIVE) { session_destroy(); } @@ -80,5 +104,7 @@ unset($_SESSION['dol_login']); unset($_SESSION['dol_entity']); unset($_SESSION['urlfrom']); -if (GETPOST('noredirect')) return; +if (GETPOST('noredirect')) { + return; +} header("Location: ".$url); // Default behaviour is redirect to index.php page diff --git a/htdocs/user/note.php b/htdocs/user/note.php index 95527747d2e..e0c23842347 100644 --- a/htdocs/user/note.php +++ b/htdocs/user/note.php @@ -39,11 +39,15 @@ $object->fetch($id, '', '', 1); $object->getrights(); // If user is not user read and no permission to read other users, we stop -if (($object->id != $user->id) && (!$user->rights->user->user->lire)) accessforbidden(); +if (($object->id != $user->id) && (!$user->rights->user->user->lire)) { + accessforbidden(); +} // Security check $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} $feature2 = (($socid && $user->rights->user->self->creer) ? '' : 'user'); $result = restrictedArea($user, 'user', $id, 'user&user', $feature2); @@ -58,7 +62,9 @@ $hookmanager->initHooks(array('usercard', 'usernote', 'globalcard')); $parameters = array('id'=>$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)) { if ($action == 'update' && $user->rights->user->user->creer && !$_POST["cancel"]) { @@ -83,8 +89,7 @@ llxHeader(); $form = new Form($db); -if ($id) -{ +if ($id) { $head = user_prepare_head($object); $title = $langs->trans("User"); @@ -114,8 +119,7 @@ if ($id) // Note print '<tr><td class="tdtop">'.$langs->trans("Note").'</td>'; print '<td class="'.($editenabled ? '' : 'sensiblehtmlcontent').'">'; - if ($editenabled) - { + if ($editenabled) { print "<input type=\"hidden\" name=\"action\" value=\"update\">"; print "<input type=\"hidden\" name=\"id\" value=\"".$object->id."\">"; // Editeur wysiwyg @@ -132,8 +136,7 @@ if ($id) print dol_get_fiche_end(); - if ($action == 'edit') - { + if ($action == 'edit') { print '<div class="center">'; print '<input type="submit" class="button button-save" name="update" value="'.$langs->trans("Save").'">'; print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; @@ -143,13 +146,12 @@ if ($id) /* - * Actions - */ + * Actions + */ print '<div class="tabsAction">'; - if ($user->rights->user->user->creer && $action != 'edit') - { + if ($user->rights->user->user->creer && $action != 'edit') { print "<a class=\"butAction\" href=\"note.php?id=".$object->id."&amp;action=edit\">".$langs->trans('Modify')."</a>"; } diff --git a/htdocs/user/notify/card.php b/htdocs/user/notify/card.php index d09ee52077f..fa2cf5a5d41 100644 --- a/htdocs/user/notify/card.php +++ b/htdocs/user/notify/card.php @@ -39,16 +39,24 @@ $action = GETPOST('action', 'aZ09'); $actionid = GETPOST('actionid'); // Security check -if ($user->socid) $id = $user->socid; +if ($user->socid) { + $id = $user->socid; +} $result = restrictedArea($user, 'societe', '', ''); $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 (!$sortorder) $sortorder = "DESC"; -if (!$sortfield) $sortfield = "n.daten"; -if (empty($page) || $page == -1) { $page = 0; } +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "n.daten"; +} +if (empty($page) || $page == -1) { + $page = 0; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -61,29 +69,24 @@ $now = dol_now(); */ // Add a notification -if ($action == 'add') -{ +if ($action == 'add') { $error = 0; - if ($actionid <= 0) - { + if ($actionid <= 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Action")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; $sql .= " WHERE fk_user=".$id." AND fk_action=".$actionid; - if ($db->query($sql)) - { + if ($db->query($sql)) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_action)"; $sql .= " VALUES ('".$db->idate($now)."',".$id.",".$actionid.")"; - if (!$db->query($sql)) - { + if (!$db->query($sql)) { $error++; dol_print_error($db); } @@ -91,8 +94,7 @@ if ($action == 'add') dol_print_error($db); } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -101,8 +103,7 @@ if ($action == 'add') } // Remove a notification -if ($action == 'delete') -{ +if ($action == 'delete') { $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def where rowid=".GETPOST("actid", "int"); $db->query($sql); } @@ -120,13 +121,14 @@ $result = $object->fetch($id, '', '', 1); $object->getrights(); $title = $langs->trans("ThirdParty").' - '.$langs->trans("Notification"); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name.' - '.$langs->trans("Notification"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name.' - '.$langs->trans("Notification"); +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($result > 0) -{ +if ($result > 0) { $langs->load("other"); $head = user_prepare_head($object); @@ -144,8 +146,7 @@ if ($result > 0) // Login print '<tr><td class="titlefield">'.$langs->trans("Login").'</td>'; - if (!empty($object->ldap_sid) && $object->statut == 0) - { + if (!empty($object->ldap_sid) && $object->statut == 0) { print '<td class="error">'.$langs->trans("LoginAccountDisableInDolibarr").'</td>'; } else { print '<td>'.$object->login.'</td>'; @@ -153,16 +154,16 @@ if ($result > 0) print '</tr>'."\n"; /*print '<tr><td class="titlefield">'.$langs->trans("NbOfActiveNotifications").'</td>'; // Notification for this thirdparty - print '<td colspan="3">'; - $nbofrecipientemails=0; - $notify=new Notify($db); - $tmparray = $notify->getNotificationsArray('', 0, null, $object->id, array('user')); - foreach($tmparray as $tmpkey => $tmpval) - { - $nbofrecipientemails++; - } - print $nbofrecipientemails; - print '</td></tr>';*/ + print '<td colspan="3">'; + $nbofrecipientemails=0; + $notify=new Notify($db); + $tmparray = $notify->getNotificationsArray('', 0, null, $object->id, array('user')); + foreach($tmparray as $tmpkey => $tmpval) + { + $nbofrecipientemails++; + } + print $nbofrecipientemails; + print '</td></tr>';*/ print '</table>'; @@ -203,23 +204,20 @@ if ($result > 0) // $listofemails=$object->thirdparty_and_contact_email_array(); - if ($object->email) - { + if ($object->email) { $actions = array(); // Load array of available notifications $notificationtrigger = new InterfaceNotification($db); $listofnotifiedevents = $notificationtrigger->getListOfManagedEvents(); - foreach ($listofnotifiedevents as $notifiedevent) - { - $label = ($langs->trans("Notify_".$notifiedevent['code']) != "Notify_".$notifiedevent['code'] ? $langs->trans("Notify_".$notifiedevent['code']) : $notifiedevent['label']); + foreach ($listofnotifiedevents as $notifiedevent) { + $label = ($langs->trans("Notify_".$notifiedevent['code']) != "Notify_".$notifiedevent['code'] ? $langs->trans("Notify_".$notifiedevent['code']) : $notifiedevent['label']); $actions[$notifiedevent['rowid']] = $label; } print '<tr class="oddeven nohover"><td>'; print $object->getNomUrl(1); - if (isValidEmail($object->email)) - { + if (isValidEmail($object->email)) { print ' &lt;'.$object->email.'&gt;'; } else { $langs->load("errors"); @@ -258,8 +256,7 @@ if ($result > 0) $sql .= " AND c.rowid = ".$object->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); } else { dol_print_error($db); @@ -280,24 +277,20 @@ if ($result > 0) $langs->load("errors"); $langs->load("other"); - if ($num) - { + if ($num) { $i = 0; $userstatic = new user($db); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $userstatic->id = $obj->userid; $userstatic->lastname = $obj->lastname; $userstatic->firstname = $obj->firstname; print '<tr class="oddeven"><td>'.$userstatic->getNomUrl(1); - if ($obj->type == 'email') - { - if (isValidEmail($obj->email)) - { + if ($obj->type == 'email') { + if (isValidEmail($obj->email)) { print ' &lt;'.$obj->email.'&gt;'; } else { $langs->load("errors"); @@ -310,8 +303,12 @@ if ($result > 0) print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').$label; print '</td>'; print '<td>'; - if ($obj->type == 'email') print $langs->trans("Email"); - if ($obj->type == 'sms') print $langs->trans("SMS"); + if ($obj->type == 'email') { + print $langs->trans("Email"); + } + if ($obj->type == 'sms') { + print $langs->trans("SMS"); + } print '</td>'; print '<td class="right"><a href="card.php?id='.$id.'&amp;action=delete&amp;token='.newToken().'&amp;actid='.$obj->rowid.'">'.img_delete().'</a></td>'; print '</tr>'; @@ -322,8 +319,8 @@ if ($result > 0) // List of notifications enabled for fixed email /* - foreach($conf->global as $key => $val) { - if (! preg_match('/^NOTIFICATION_FIXEDEMAIL_(.*)/', $key, $reg)) continue; + foreach($conf->global as $key => $val) { + if (! preg_match('/^NOTIFICATION_FIXEDEMAIL_(.*)/', $key, $reg)) continue; print '<tr class="oddeven"><td>'; $listtmp=explode(',',$val); $first=1; @@ -332,7 +329,7 @@ if ($result > 0) if (! $first) print ', '; $first=0; $valemail=trim($valemail); - //print $keyemail.' - '.$valemail.' - '.$reg[1].'<br>'; + //print $keyemail.' - '.$valemail.' - '.$reg[1].'<br>'; if (isValidEmail($valemail, 1)) { if ($valemail == '__SUPERVISOREMAIL__') print $valemail; @@ -359,14 +356,14 @@ if ($result > 0) print '</td>'; print '<td class="right">'.$langs->trans("SeeModuleSetup", $langs->transnoentitiesnoconv("Module600Name")).'</td>'; print '</tr>'; - }*/ + }*/ /*if ($user->admin) - { - $var = ! $var; + { + $var = ! $var; print '<tr class="oddeven"><td colspan="4">'; print '+ <a href="'.DOL_URL_ROOT.'/admin/notification.php">'.$langs->trans("SeeModuleSetup", $langs->transnoentitiesnoconv("Module600Name")).'</a>'; print '</td></tr>'; - }*/ + }*/ print '</table>'; @@ -387,12 +384,10 @@ if ($result > 0) // Count total nb of records $nbtotalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -401,19 +396,24 @@ if ($result > 0) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); } else { dol_print_error($db); } $param = '&id='.$object->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 '<form method="post" action="'.$_SERVER["PHP_SELF"].'" name="formfilter">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; @@ -434,19 +434,16 @@ if ($result > 0) print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "n.daten", '', $param, '', $sortfield, $sortorder, 'right '); print '</tr>'; - if ($num) - { + if ($num) { $i = 0; $userstatic = new User($db); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven"><td>'; - if ($obj->id > 0) - { + if ($obj->id > 0) { $userstatic->id = $obj->id; $userstatic->lastname = $obj->lastname; $userstatic->firstname = $obj->firstname; @@ -461,18 +458,22 @@ if ($result > 0) print $label; print '</td>'; print '<td>'; - if ($obj->type == 'email') print $langs->trans("Email"); - if ($obj->type == 'sms') print $langs->trans("Sms"); + if ($obj->type == 'email') { + print $langs->trans("Email"); + } + if ($obj->type == 'sms') { + print $langs->trans("Sms"); + } print '</td>'; // TODO Add link to object here for other types /*print '<td>'; - if ($obj->object_type == 'order') - { + if ($obj->object_type == 'order') + { $orderstatic->id=$obj->object_id; $orderstatic->ref=... print $orderstatic->getNomUrl(1); - } - print '</td>';*/ + } + print '</td>';*/ // print print'<td class="right">'.dol_print_date($db->jdate($obj->daten), 'dayhour').'</td>'; print '</tr>'; @@ -486,7 +487,9 @@ if ($result > 0) print '</table>'; print '</form>'; -} else dol_print_error('', 'RecordNotFound'); +} else { + dol_print_error('', 'RecordNotFound'); +} // End of page llxFooter(); diff --git a/htdocs/user/param_ihm.php b/htdocs/user/param_ihm.php index 52f7a28be44..228066b7051 100644 --- a/htdocs/user/param_ihm.php +++ b/htdocs/user/param_ihm.php @@ -38,8 +38,7 @@ $id = GETPOST('id', 'int'); $action = GETPOST('action', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'userihm'; // To manage different context of search -if ($id) -{ +if ($id) { // $user est le user qui edite, $id est l'id de l'utilisateur edite $caneditfield = ((($user->id == $id) && $user->rights->user->self->creer) || (($user->id != $id) && $user->rights->user->user->creer)); @@ -47,11 +46,15 @@ if ($id) // Security check $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} $feature2 = (($socid && $user->rights->user->self->creer) ? '' : 'user'); $result = restrictedArea($user, 'user', $id, 'user&user', $feature2); -if ($user->id <> $id && !$canreaduser) accessforbidden(); +if ($user->id <> $id && !$canreaduser) { + accessforbidden(); +} $dirtop = "../core/menus/standard"; $dirleft = "../core/menus/standard"; @@ -81,7 +84,9 @@ $hookmanager->initHooks(array('usercard', 'userihm', 'globalcard')); $parameters = array('id'=>$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)) { if ($action == 'update' && ($caneditfield || !empty($user->admin))) { @@ -122,16 +127,20 @@ if (empty($reshook)) { if ($val == '') { $tabparam['THEME_ELDY_TOPMENU_BACK1'] = ''; } else { - $tabparam['THEME_ELDY_TOPMENU_BACK1'] = join(',', - colorStringToArray(GETPOST('THEME_ELDY_TOPMENU_BACK1', 'alphanohtml'), array())); + $tabparam['THEME_ELDY_TOPMENU_BACK1'] = join( + ',', + colorStringToArray(GETPOST('THEME_ELDY_TOPMENU_BACK1', 'alphanohtml'), array()) + ); } $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_BACKTITLE1', 'alphanohtml'), array())))); if ($val == '') { $tabparam['THEME_ELDY_BACKTITLE1'] = ''; } else { - $tabparam['THEME_ELDY_BACKTITLE1'] = join(',', - colorStringToArray(GETPOST('THEME_ELDY_BACKTITLE1', 'alphanohtml'), array())); + $tabparam['THEME_ELDY_BACKTITLE1'] = join( + ',', + colorStringToArray(GETPOST('THEME_ELDY_BACKTITLE1', 'alphanohtml'), array()) + ); } if (GETPOST('check_THEME_ELDY_USE_HOVER') == 'on') { @@ -174,21 +183,36 @@ llxHeader(); // List of possible landing pages $tmparray = array('index.php'=>'Dashboard'); -if (!empty($conf->societe->enabled)) $tmparray['societe/index.php?mainmenu=companies&leftmenu='] = 'ThirdPartiesArea'; -if (!empty($conf->projet->enabled)) $tmparray['projet/index.php?mainmenu=project&leftmenu='] = 'ProjectsArea'; -if (!empty($conf->holiday->enabled) || !empty($conf->expensereport->enabled)) $tmparray['hrm/index.php?mainmenu=hrm&leftmenu='] = 'HRMArea'; // TODO Complete list with first level of menus -if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) $tmparray['product/index.php?mainmenu=products&leftmenu='] = 'ProductsAndServicesArea'; -if (!empty($conf->propal->enabled) || !empty($conf->commande->enabled) || !empty($conf->ficheinter->enabled) || !empty($conf->contrat->enabled)) $tmparray['comm/index.php?mainmenu=commercial&leftmenu='] = 'CommercialArea'; -if (!empty($conf->comptabilite->enabled) || !empty($conf->accounting->enabled)) $tmparray['compta/index.php?mainmenu=compta&leftmenu='] = 'AccountancyTreasuryArea'; -if (!empty($conf->adherent->enabled)) $tmparray['adherents/index.php?mainmenu=members&leftmenu='] = 'MembersArea'; -if (!empty($conf->agenda->enabled)) $tmparray['comm/action/index.php?mainmenu=agenda&leftmenu='] = 'Agenda'; +if (!empty($conf->societe->enabled)) { + $tmparray['societe/index.php?mainmenu=companies&leftmenu='] = 'ThirdPartiesArea'; +} +if (!empty($conf->projet->enabled)) { + $tmparray['projet/index.php?mainmenu=project&leftmenu='] = 'ProjectsArea'; +} +if (!empty($conf->holiday->enabled) || !empty($conf->expensereport->enabled)) { + $tmparray['hrm/index.php?mainmenu=hrm&leftmenu='] = 'HRMArea'; // TODO Complete list with first level of menus +} +if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) { + $tmparray['product/index.php?mainmenu=products&leftmenu='] = 'ProductsAndServicesArea'; +} +if (!empty($conf->propal->enabled) || !empty($conf->commande->enabled) || !empty($conf->ficheinter->enabled) || !empty($conf->contrat->enabled)) { + $tmparray['comm/index.php?mainmenu=commercial&leftmenu='] = 'CommercialArea'; +} +if (!empty($conf->comptabilite->enabled) || !empty($conf->accounting->enabled)) { + $tmparray['compta/index.php?mainmenu=compta&leftmenu='] = 'AccountancyTreasuryArea'; +} +if (!empty($conf->adherent->enabled)) { + $tmparray['adherents/index.php?mainmenu=members&leftmenu='] = 'MembersArea'; +} +if (!empty($conf->agenda->enabled)) { + $tmparray['comm/action/index.php?mainmenu=agenda&leftmenu='] = 'Agenda'; +} $head = user_prepare_head($object); $title = $langs->trans("User"); -if ($action == 'edit') -{ +if ($action == 'edit') { print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; @@ -196,8 +220,7 @@ if ($action == 'edit') } -if ($action == 'edit') -{ +if ($action == 'edit') { print dol_get_fiche_head($head, 'guisetup', $title, -1, 'user'); $linkback = ''; @@ -208,22 +231,20 @@ if ($action == 'edit') dol_banner_tab($object, 'id', $linkback, $user->rights->user->user->lire || $user->admin); - if (!empty($conf->use_javascript_ajax)) - {/* - print '<script type="text/javascript" language="javascript"> - jQuery(document).ready(function() { - $("#main_lang_default").change(function() { - $("#check_MAIN_LANG_DEFAULT").prop("checked", true); - }); - $("#main_size_liste_limit").keyup(function() { - if ($(this).val().length) $("#check_SIZE_LISTE_LIMIT").prop("checked", true); - else $("#check_SIZE_LISTE_LIMIT").prop("checked", false); - }); - }); - </script>';*/ + if (!empty($conf->use_javascript_ajax)) {/* + print '<script type="text/javascript" language="javascript"> + jQuery(document).ready(function() { + $("#main_lang_default").change(function() { + $("#check_MAIN_LANG_DEFAULT").prop("checked", true); + }); + $("#main_size_liste_limit").keyup(function() { + if ($(this).val().length) $("#check_SIZE_LISTE_LIMIT").prop("checked", true); + else $("#check_SIZE_LISTE_LIMIT").prop("checked", false); + }); + }); + </script>';*/ } - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print '<script type="text/javascript" language="javascript"> jQuery(document).ready(function() { function init_myfunc() @@ -357,10 +378,11 @@ if ($action == 'edit') print empty($dolibarr_main_demo) ? '' : ' disabled="disabled"'; // Disabled for demo print '> '.$langs->trans("UsePersonalValue").'</td>'; print '<td>'; - if (!empty($tmparray[$object->conf->MAIN_LANDING_PAGE])) - { + if (!empty($tmparray[$object->conf->MAIN_LANDING_PAGE])) { print $langs->trans($tmparray[$object->conf->MAIN_LANDING_PAGE]); - } else print $object->conf->MAIN_LANDING_PAGE; + } else { + print $object->conf->MAIN_LANDING_PAGE; + } //print $form->selectarray('MAIN_LANDING_PAGE', $tmparray, (! empty($object->conf->MAIN_LANDING_PAGE)?$object->conf->MAIN_LANDING_PAGE:''), 0, 0, 0, '', 1); print '</td></tr>'; @@ -371,7 +393,9 @@ if ($action == 'edit') print '<td class="nowrap" width="20%"><input class="oddeven" type="checkbox" disabled '.(!empty($object->conf->AGENDA_DEFAULT_VIEW) ? " checked" : "").'> '.$langs->trans("UsePersonalValue").'</td>'; print '<td>'."\n"; $tmplist = array(''=>'&nbsp;', 'show_list'=>$langs->trans("ViewList"), 'show_month'=>$langs->trans("ViewCal"), 'show_week'=>$langs->trans("ViewWeek"), 'show_day'=>$langs->trans("ViewDay"), 'show_peruser'=>$langs->trans("ViewPerUser")); - if (!empty($object->conf->AGENDA_DEFAULT_VIEW)) print $form->selectarray('AGENDA_DEFAULT_VIEW', $tmplist, $object->conf->AGENDA_DEFAULT_VIEW, 0, 0, 0, '', 0, 0, 1); + if (!empty($object->conf->AGENDA_DEFAULT_VIEW)) { + print $form->selectarray('AGENDA_DEFAULT_VIEW', $tmplist, $object->conf->AGENDA_DEFAULT_VIEW, 0, 0, 0, '', 0, 0, 1); + } print '</td></tr>'."\n"; // Max size for lists @@ -390,12 +414,10 @@ if ($action == 'edit') print '<div class="tabsAction">'; - if (empty($user->admin) && !empty($dolibarr_main_demo)) - { + if (empty($user->admin) && !empty($dolibarr_main_demo)) { print "<a class=\"butActionRefused classfortooltip\" title=\"".$langs->trans("FeatureDisabledInDemo")."\" href=\"#\">".$langs->trans("Modify")."</a>"; } else { - if ($caneditfield || !empty($user->admin)) // Si utilisateur edite = utilisateur courant (pas besoin de droits particulier car il s'agit d'une page de modif d'output et non de données) ou si admin - { + if ($caneditfield || !empty($user->admin)) { // Si utilisateur edite = utilisateur courant (pas besoin de droits particulier car il s'agit d'une page de modif d'output et non de données) ou si admin print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&amp;id='.$object->id.'">'.$langs->trans("Modify").'</a>'; } else { print "<a class=\"butActionRefused classfortooltip\" title=\"".$langs->trans("NotEnoughPermissions")."\" href=\"#\">".$langs->trans("Modify")."</a>"; @@ -405,8 +427,7 @@ if ($action == 'edit') print '</div>'; } -if ($action == 'edit') -{ +if ($action == 'edit') { print '</form>'; } diff --git a/htdocs/user/passwordforgotten.php b/htdocs/user/passwordforgotten.php index 15df6371891..f2ad3faf42e 100644 --- a/htdocs/user/passwordforgotten.php +++ b/htdocs/user/passwordforgotten.php @@ -29,21 +29,24 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -if (!empty($conf->ldap->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; +if (!empty($conf->ldap->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; +} // Load translation files required by page $langs->loadLangs(array('errors', 'users', 'companies', 'ldap', 'other')); // Security check -if (!empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK)) -{ +if (!empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK)) { header("Location: ".DOL_URL_ROOT.'/'); exit; } $action = GETPOST('action', 'aZ09'); $mode = $dolibarr_main_authentication; -if (!$mode) $mode = 'http'; +if (!$mode) { + $mode = 'http'; +} $username = GETPOST('username', 'alphanohtml'); $passwordhash = GETPOST('passwordhash', 'alpha'); @@ -53,11 +56,21 @@ $conf->entity = (GETPOST('entity', 'int') ? GETPOST('entity', 'int') : 1); $hookmanager->initHooks(array('passwordforgottenpage')); -if (GETPOST('dol_hide_leftmenu', 'alpha') || !empty($_SESSION['dol_hide_leftmenu'])) $conf->dol_hide_leftmenu = 1; -if (GETPOST('dol_hide_topmenu', 'alpha') || !empty($_SESSION['dol_hide_topmenu'])) $conf->dol_hide_topmenu = 1; -if (GETPOST('dol_optimize_smallscreen', 'alpha') || !empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen = 1; -if (GETPOST('dol_no_mouse_hover', 'alpha') || !empty($_SESSION['dol_no_mouse_hover'])) $conf->dol_no_mouse_hover = 1; -if (GETPOST('dol_use_jmobile', 'alpha') || !empty($_SESSION['dol_use_jmobile'])) $conf->dol_use_jmobile = 1; +if (GETPOST('dol_hide_leftmenu', 'alpha') || !empty($_SESSION['dol_hide_leftmenu'])) { + $conf->dol_hide_leftmenu = 1; +} +if (GETPOST('dol_hide_topmenu', 'alpha') || !empty($_SESSION['dol_hide_topmenu'])) { + $conf->dol_hide_topmenu = 1; +} +if (GETPOST('dol_optimize_smallscreen', 'alpha') || !empty($_SESSION['dol_optimize_smallscreen'])) { + $conf->dol_optimize_smallscreen = 1; +} +if (GETPOST('dol_no_mouse_hover', 'alpha') || !empty($_SESSION['dol_no_mouse_hover'])) { + $conf->dol_no_mouse_hover = 1; +} +if (GETPOST('dol_use_jmobile', 'alpha') || !empty($_SESSION['dol_use_jmobile'])) { + $conf->dol_use_jmobile = 1; +} /** @@ -67,96 +80,86 @@ if (GETPOST('dol_use_jmobile', 'alpha') || !empty($_SESSION['dol_use_jmobile'])) $parameters = array('username' => $username); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { - $message = $hookmanager->error; + $message = $hookmanager->error; } if (empty($reshook)) { - // Validate new password - if ($action == 'validatenewpassword' && $username && $passwordhash) - { - $edituser = new User($db); - $result = $edituser->fetch('', $_GET["username"]); - if ($result < 0) - { - $message = '<div class="error">'.dol_escape_htmltag($langs->trans("ErrorLoginDoesNotExists", $username)).'</div>'; - } else { - if (dol_verifyHash($edituser->pass_temp, $passwordhash)) - { - // Clear session - unset($_SESSION['dol_login']); - $_SESSION['dol_loginmesg'] = $langs->trans('NewPasswordValidated'); // Save message for the session page + // Validate new password + if ($action == 'validatenewpassword' && $username && $passwordhash) { + $edituser = new User($db); + $result = $edituser->fetch('', $_GET["username"]); + if ($result < 0) { + $message = '<div class="error">'.dol_escape_htmltag($langs->trans("ErrorLoginDoesNotExists", $username)).'</div>'; + } else { + if (dol_verifyHash($edituser->pass_temp, $passwordhash)) { + // Clear session + unset($_SESSION['dol_login']); + $_SESSION['dol_loginmesg'] = $langs->trans('NewPasswordValidated'); // Save message for the session page - $newpassword = $edituser->setPassword($user, $edituser->pass_temp, 0); - dol_syslog("passwordforgotten.php new password for user->id=".$edituser->id." validated in database"); - header("Location: ".DOL_URL_ROOT.'/'); - exit; - } else { - $langs->load("errors"); - $message = '<div class="error">'.$langs->trans("ErrorFailedToValidatePasswordReset").'</div>'; - } - } - } - // Action modif mot de passe - if ($action == 'buildnewpassword' && $username) - { - $sessionkey = 'dol_antispam_value'; - $ok = (array_key_exists($sessionkey, $_SESSION) === true && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code']))); + $newpassword = $edituser->setPassword($user, $edituser->pass_temp, 0); + dol_syslog("passwordforgotten.php new password for user->id=".$edituser->id." validated in database"); + header("Location: ".DOL_URL_ROOT.'/'); + exit; + } else { + $langs->load("errors"); + $message = '<div class="error">'.$langs->trans("ErrorFailedToValidatePasswordReset").'</div>'; + } + } + } + // Action modif mot de passe + if ($action == 'buildnewpassword' && $username) { + $sessionkey = 'dol_antispam_value'; + $ok = (array_key_exists($sessionkey, $_SESSION) === true && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code']))); - // Verify code - if (!$ok) - { - $message = '<div class="error">'.$langs->trans("ErrorBadValueForCode").'</div>'; - } else { - $isanemail = preg_match('/@/', $username); + // Verify code + if (!$ok) { + $message = '<div class="error">'.$langs->trans("ErrorBadValueForCode").'</div>'; + } else { + $isanemail = preg_match('/@/', $username); - $edituser = new User($db); - $result = $edituser->fetch('', $username, '', 1); - if ($result == 0 && $isanemail) - { - $result = $edituser->fetch('', '', '', 1, -1, $username); - } + $edituser = new User($db); + $result = $edituser->fetch('', $username, '', 1); + if ($result == 0 && $isanemail) { + $result = $edituser->fetch('', '', '', 1, -1, $username); + } - if ($result <= 0 && $edituser->error == 'USERNOTFOUND') - { - $message = '<div class="warning paddingtopbottom'.(empty($conf->global->MAIN_LOGIN_BACKGROUND) ? '' : ' backgroundsemitransparent').'">'; - if (!$isanemail) { - $message .= $langs->trans("IfLoginExistPasswordRequestSent"); - } else { - $message .= $langs->trans("IfEmailExistPasswordRequestSent"); - } - $message .= '</div>'; - $username = ''; - } else { - if (!$edituser->email) - { - $message = '<div class="error">'.$langs->trans("ErrorLoginHasNoEmail").'</div>'; - } else { - $newpassword = $edituser->setPassword($user, '', 1); - if ($newpassword < 0) - { - // Failed - $message = '<div class="error">'.$langs->trans("ErrorFailedToChangePassword").'</div>'; - } else { - // Success - if ($edituser->send_password($user, $newpassword, 1) > 0) - { - $message = '<div class="warning paddingtopbottom'.(empty($conf->global->MAIN_LOGIN_BACKGROUND) ? '' : ' backgroundsemitransparent').'">'; - if (!$isanemail) { - $message .= $langs->trans("IfLoginExistPasswordRequestSent"); - } else { - $message .= $langs->trans("IfEmailExistPasswordRequestSent"); - } - //$message .= $langs->trans("PasswordChangeRequestSent", $edituser->login, dolObfuscateEmail($edituser->email)); - $message .= '</div>'; - $username = ''; - } else { - $message .= '<div class="error">'.$edituser->error.'</div>'; - } - } - } - } - } - } + if ($result <= 0 && $edituser->error == 'USERNOTFOUND') { + $message = '<div class="warning paddingtopbottom'.(empty($conf->global->MAIN_LOGIN_BACKGROUND) ? '' : ' backgroundsemitransparent').'">'; + if (!$isanemail) { + $message .= $langs->trans("IfLoginExistPasswordRequestSent"); + } else { + $message .= $langs->trans("IfEmailExistPasswordRequestSent"); + } + $message .= '</div>'; + $username = ''; + } else { + if (!$edituser->email) { + $message = '<div class="error">'.$langs->trans("ErrorLoginHasNoEmail").'</div>'; + } else { + $newpassword = $edituser->setPassword($user, '', 1); + if ($newpassword < 0) { + // Failed + $message = '<div class="error">'.$langs->trans("ErrorFailedToChangePassword").'</div>'; + } else { + // Success + if ($edituser->send_password($user, $newpassword, 1) > 0) { + $message = '<div class="warning paddingtopbottom'.(empty($conf->global->MAIN_LOGIN_BACKGROUND) ? '' : ' backgroundsemitransparent').'">'; + if (!$isanemail) { + $message .= $langs->trans("IfLoginExistPasswordRequestSent"); + } else { + $message .= $langs->trans("IfEmailExistPasswordRequestSent"); + } + //$message .= $langs->trans("PasswordChangeRequestSent", $edituser->login, dolObfuscateEmail($edituser->email)); + $message .= '</div>'; + $username = ''; + } else { + $message .= '<div class="error">'.$edituser->error.'</div>'; + } + } + } + } + } + } } @@ -168,46 +171,49 @@ $dol_url_root = DOL_URL_ROOT; // Title $title = 'Dolibarr '.DOL_VERSION; -if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = $conf->global->MAIN_APPLICATION_TITLE; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $title = $conf->global->MAIN_APPLICATION_TITLE; +} // Select templates -if (file_exists(DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/tpl/passwordforgotten.tpl.php")) -{ +if (file_exists(DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/tpl/passwordforgotten.tpl.php")) { $template_dir = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/tpl/"; } else { $template_dir = DOL_DOCUMENT_ROOT."/core/tpl/"; } -if (!$username) $focus_element = 'username'; -else $focus_element = 'password'; +if (!$username) { + $focus_element = 'username'; +} else { + $focus_element = 'password'; +} // Send password button enabled ? $disabled = 'disabled'; -if (preg_match('/dolibarr/i', $mode)) $disabled = ''; -if (!empty($conf->global->MAIN_SECURITY_ENABLE_SENDPASSWORD)) $disabled = ''; // To force button enabled +if (preg_match('/dolibarr/i', $mode)) { + $disabled = ''; +} +if (!empty($conf->global->MAIN_SECURITY_ENABLE_SENDPASSWORD)) { + $disabled = ''; // To force button enabled +} // Show logo (search in order: small company logo, large company logo, theme logo, common logo) $width = 0; $rowspan = 2; $urllogo = DOL_URL_ROOT.'/theme/common/login_logo.png'; -if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) -{ +if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small); -} elseif (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) -{ +} elseif (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/'.$mysoc->logo); $width = 128; -} elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.svg')) -{ +} elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.svg')) { $urllogo = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.svg'; -} elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) -{ +} elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) { $urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.svg'; } // Security graphical code -if (function_exists("imagecreatefrompng") && !$disabled) -{ +if (function_exists("imagecreatefrompng") && !$disabled) { $captcha = 1; $captcha_refresh = img_picto($langs->trans("Refresh"), 'refresh', 'id="captcha_refresh_img"'); } diff --git a/htdocs/user/perms.php b/htdocs/user/perms.php index a05fd76df7b..f14fcee2e0f 100644 --- a/htdocs/user/perms.php +++ b/htdocs/user/perms.php @@ -26,7 +26,9 @@ * \brief Page to set permission of a user record */ -if (!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +if (!defined('CSRFCHECK_WITH_TOKEN')) { + define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +} require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php'; @@ -43,15 +45,16 @@ $module = GETPOST('module', 'alpha'); $rights = GETPOST('rights', 'int'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'userperms'; // To manage different context of search -if (!isset($id) || empty($id)) accessforbidden(); +if (!isset($id) || empty($id)) { + accessforbidden(); +} // Define if user can read permissions $canreaduser = ($user->admin || $user->rights->user->user->lire); // Define if user can modify other users and permissions $caneditperms = ($user->admin || $user->rights->user->user->creer); // Advanced permissions -if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) -{ +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { $canreaduser = ($user->admin || ($user->rights->user->user->lire && $user->rights->user->user_advance->readperms)); $caneditselfperms = ($user->id == $id && $user->rights->user->self_advance->writeperms); $caneditperms = (($caneditperms || $caneditselfperms) ? 1 : 0); @@ -59,16 +62,19 @@ if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) // Security check $socid = 0; -if (isset($user->socid) && $user->socid > 0) $socid = $user->socid; +if (isset($user->socid) && $user->socid > 0) { + $socid = $user->socid; +} $feature2 = (($socid && $user->rights->user->self->creer) ? '' : 'user'); // A user can always read its own card if not advanced perms enabled, or if he has advanced perms, except for admin -if ($user->id == $id && (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->user->self_advance->readperms) && empty($user->admin))) -{ +if ($user->id == $id && (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->user->self_advance->readperms) && empty($user->admin))) { accessforbidden(); } $result = restrictedArea($user, 'user', $id, 'user&user', $feature2); -if ($user->id <> $id && !$canreaduser) accessforbidden(); +if ($user->id <> $id && !$canreaduser) { + accessforbidden(); +} $object = new User($db); $object->fetch($id, '', '', 1); @@ -86,15 +92,16 @@ $hookmanager->initHooks(array('usercard', 'userperms', 'globalcard')); $parameters = array('id'=>$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)) { if ($action == 'addrights' && $caneditperms && $confirm == 'yes') { $edituser = new User($db); $edituser->fetch($object->id); $result = $edituser->addrights($rights, $module, '', $entity); - if ($result < 0) - { + if ($result < 0) { setEventMessages($edituser->error, $edituser->errors, 'errors'); } @@ -113,8 +120,7 @@ if (empty($reshook)) { $edituser = new User($db); $edituser->fetch($object->id); $result = $edituser->delrights($rights, $module, '', $entity); - if ($result < 0) - { + if ($result < 0) { setEventMessages($edituser->error, $edituser->errors, 'errors'); } @@ -151,33 +157,25 @@ $db->begin(); $modules = array(); $modulesdir = dolGetModulesDirs(); -foreach ($modulesdir as $dir) -{ +foreach ($modulesdir as $dir) { $handle = @opendir(dol_osencode($dir)); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') { $modName = substr($file, 0, dol_strlen($file) - 10); - if ($modName) - { + if ($modName) { include_once $dir.$file; $objMod = new $modName($db); // Load all lang files of module - if (isset($objMod->langfiles) && is_array($objMod->langfiles)) - { - foreach ($objMod->langfiles as $domain) - { + if (isset($objMod->langfiles) && is_array($objMod->langfiles)) { + foreach ($objMod->langfiles as $domain) { $langs->load($domain); } } // Load all permissions - if ($objMod->rights_class) - { + if ($objMod->rights_class) { $ret = $objMod->insert_permissions(0, $entity); $modules[$objMod->rights_class] = $objMod; //print "modules[".$objMod->rights_class."]=$objMod;"; @@ -200,12 +198,10 @@ $sql .= " AND ur.fk_user = ".$object->id; dol_syslog("get user perms", LOG_DEBUG); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); array_push($permsuser, $obj->fk_id); $i++; @@ -227,15 +223,14 @@ $sql .= " AND gu.fk_user = ".$object->id; dol_syslog("get user perms", LOG_DEBUG); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); - if (!isset($permsgroupbyentity[$obj->entity])) + if (!isset($permsgroupbyentity[$obj->entity])) { $permsgroupbyentity[$obj->entity] = array(); + } array_push($permsgroupbyentity[$obj->entity], $obj->fk_id); $i++; } @@ -260,13 +255,19 @@ dol_banner_tab($object, 'id', $linkback, $user->rights->user->user->lire || $use print '<div class="underbanner clearboth"></div>'; -if ($user->admin) print info_admin($langs->trans("WarningOnlyPermissionOfActivatedModules")); +if ($user->admin) { + print info_admin($langs->trans("WarningOnlyPermissionOfActivatedModules")); +} // Show warning about external users -if (empty($user->socid)) print info_admin(showModulesExludedForExternal($modules))."\n"; +if (empty($user->socid)) { + print info_admin(showModulesExludedForExternal($modules))."\n"; +} $parameters = array('permsgroupbyentity'=>$permsgroupbyentity); $reshook = $hookmanager->executeHooks('insertExtraHeader', $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'); +} print "\n"; @@ -275,10 +276,8 @@ print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<td>'.$langs->trans("Module").'</td>'; -if (($caneditperms && empty($objMod->rights_admin_allowed)) || empty($object->admin)) -{ - if ($caneditperms) - { +if (($caneditperms && empty($objMod->rights_admin_allowed)) || empty($object->admin)) { + if ($caneditperms) { print '<td class="center nowrap">'; print '<a class="reposition commonlink" title="'.dol_escape_htmltag($langs->trans("All")).'" alt="'.dol_escape_htmltag($langs->trans("All")).'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addrights&amp;entity='.$entity.'&amp;module=allmodules&amp;confirm=yes&amp;token='.newToken().'">'.$langs->trans("All")."</a>"; print ' / '; @@ -288,7 +287,9 @@ if (($caneditperms && empty($objMod->rights_admin_allowed)) || empty($object->ad print '<td class="center" width="24">&nbsp;</td>'; } print '<td>'.$langs->trans("Permissions").'</td>'; -if ($user->admin) print '<td class="right">'.$langs->trans("ID").'</td>'; +if ($user->admin) { + print '<td class="right">'.$langs->trans("ID").'</td>'; +} print '</tr>'."\n"; //print "xx".$conf->global->MAIN_USE_ADVANCED_PERMS; @@ -296,32 +297,29 @@ $sql = "SELECT r.id, r.libelle as label, r.module, r.perms, r.subperms, r.module $sql .= " FROM ".MAIN_DB_PREFIX."rights_def as r"; $sql .= " WHERE r.libelle NOT LIKE 'tou%'"; // On ignore droits "tous" $sql .= " AND r.entity = ".$entity; -if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled +if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { + $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled +} $sql .= " ORDER BY r.family_position, r.module_position, r.module, r.id"; $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; $oldmod = ''; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); // If line is for a module that doe snot existe anymore (absent of includes/module), we ignore it - if (empty($modules[$obj->module])) - { + if (empty($modules[$obj->module])) { $i++; continue; } // Save field module_position in database if value is still zero - if (empty($obj->module_position)) - { - if (is_object($modules[$obj->module]) && ($modules[$obj->module]->module_position > 0)) - { + if (empty($obj->module_position)) { + if (is_object($modules[$obj->module]) && ($modules[$obj->module]->module_position > 0)) { // TODO Define familyposition $family = $modules[$obj->module]->family_position; $familyposition = 0; @@ -332,8 +330,7 @@ if ($result) } } - if (isset($obj->module) && ($oldmod <> $obj->module)) - { + if (isset($obj->module) && ($oldmod <> $obj->module)) { $oldmod = $obj->module; // Break detected, we get objMod @@ -346,10 +343,8 @@ if ($result) print img_object('', $picto, 'class="pictoobjectwidth paddingright"').' '.$objMod->getName(); print '<a name="'.$objMod->getName().'"></a>'; print '</td>'; - if (($caneditperms && empty($objMod->rights_admin_allowed)) || empty($object->admin)) - { - if ($caneditperms) - { + if (($caneditperms && empty($objMod->rights_admin_allowed)) || empty($object->admin)) { + if ($caneditperms) { print '<td class="center nowrap">'; print '<a class="reposition" title="'.dol_escape_htmltag($langs->trans("All")).'" alt="'.dol_escape_htmltag($langs->trans("All")).'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addrights&amp;entity='.$entity.'&amp;module='.$obj->module.'&amp;confirm=yes&amp;token='.newToken().'">'.$langs->trans("All")."</a>"; print ' / '; @@ -358,8 +353,7 @@ if ($result) } print '<td>&nbsp;</td>'; } else { - if ($caneditperms) - { + if ($caneditperms) { print '<td>&nbsp;</td>'; } print '<td>&nbsp;</td>'; @@ -367,7 +361,9 @@ if ($result) print '<td>&nbsp;</td>'; // Permission id - if ($user->admin) print '<td class="right"></td>'; + if ($user->admin) { + print '<td class="right"></td>'; + } print '</tr>'."\n"; } @@ -381,19 +377,15 @@ if ($result) print '</td>'; // Permission and tick - if (!empty($object->admin) && !empty($objMod->rights_admin_allowed)) // Permission granted because admin - { - if ($caneditperms) - { + if (!empty($object->admin) && !empty($objMod->rights_admin_allowed)) { // Permission granted because admin + if ($caneditperms) { print '<td class="center">'.img_picto($langs->trans("Administrator"), 'star').'</td>'; } print '<td class="center nowrap">'; print img_picto($langs->trans("Active"), 'tick'); print '</td>'; - } elseif (in_array($obj->id, $permsuser)) // Permission granted by user - { - if ($caneditperms) - { + } elseif (in_array($obj->id, $permsuser)) { // Permission granted by user + if ($caneditperms) { print '<td class="center"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delrights&amp;entity='.$entity.'&amp;rights='.$obj->id.'&amp;confirm=yes&amp;token='.newToken().'">'; //print img_edit_remove($langs->trans("Remove")); print img_picto($langs->trans("Remove"), 'switch_on'); @@ -402,12 +394,9 @@ if ($result) print '<td class="center nowrap">'; print img_picto($langs->trans("Active"), 'tick'); print '</td>'; - } elseif (is_array($permsgroupbyentity[$entity])) - { - if (in_array($obj->id, $permsgroupbyentity[$entity])) // Permission granted by group - { - if ($caneditperms) - { + } elseif (is_array($permsgroupbyentity[$entity])) { + if (in_array($obj->id, $permsgroupbyentity[$entity])) { // Permission granted by group + if ($caneditperms) { print '<td class="center">'; print $form->textwithtooltip($langs->trans("Inherited"), $langs->trans("PermissionInheritedFromAGroup")); print '</td>'; @@ -417,8 +406,7 @@ if ($result) print '</td>'; } else { // Do not own permission - if ($caneditperms) - { + if ($caneditperms) { print '<td class="center"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addrights&amp;entity='.$entity.'&amp;rights='.$obj->id.'&amp;confirm=yes&amp;token='.newToken().'">'; //print img_edit_add($langs->trans("Add")); print img_picto($langs->trans("Add"), 'switch_off'); @@ -428,8 +416,7 @@ if ($result) } } else { // Do not own permission - if ($caneditperms) - { + if ($caneditperms) { print '<td class="center"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addrights&amp;entity='.$entity.'&amp;rights='.$obj->id.'&amp;confirm=yes&amp;token='.newToken().'">'; //print img_edit_add($langs->trans("Add")); print img_picto($langs->trans("Add"), 'switch_off'); @@ -450,19 +437,25 @@ if ($result) print '</td>'; // Permission id - if ($user->admin) print '<td class="right"><span class="opacitymedium">'.$obj->id.'</span></td>'; + if ($user->admin) { + print '<td class="right"><span class="opacitymedium">'.$obj->id.'</span></td>'; + } print '</tr>'."\n"; $i++; } -} else dol_print_error($db); +} else { + dol_print_error($db); +} print '</table>'; print '</div>'; $parameters = array(); $reshook = $hookmanager->executeHooks('insertExtraFooter', $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'); +} print dol_get_fiche_end(); diff --git a/htdocs/user/vcard.php b/htdocs/user/vcard.php index 6cdcd04417f..57778c44259 100644 --- a/htdocs/user/vcard.php +++ b/htdocs/user/vcard.php @@ -36,14 +36,15 @@ $id = GETPOST('id', 'int'); // Security check $socid = 0; -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} $feature2 = 'user'; $result = restrictedArea($user, 'user', $id, 'user', $feature2); $result = $user2->fetch($id); -if ($result <= 0) -{ +if ($result <= 0) { dol_print_error($user2->error); exit; } @@ -51,8 +52,7 @@ if ($result <= 0) $physicalperson = 1; $company = new Societe($db); -if ($user2->socid) -{ +if ($user2->socid) { $result = $company->fetch($user2->socid); } @@ -79,33 +79,32 @@ $v->setNote($user2->note); $v->setTitle($user2->poste); // Data from linked company -if ($company->id) -{ +if ($company->id) { $v->setURL($company->url, "TYPE=WORK"); - if (!$user2->phone_pro) $v->setPhoneNumber($company->phone, "TYPE=WORK;VOICE"); - if (!$user2->fax) $v->setPhoneNumber($company->fax, "TYPE=WORK;FAX"); - if (!$user2->zip) $v->setAddress("", "", $company->address, $company->town, $company->state, $company->zip, $company->country, "TYPE=WORK;POSTAL"); + if (!$user2->phone_pro) { + $v->setPhoneNumber($company->phone, "TYPE=WORK;VOICE"); + } + if (!$user2->fax) { + $v->setPhoneNumber($company->fax, "TYPE=WORK;FAX"); + } + if (!$user2->zip) { + $v->setAddress("", "", $company->address, $company->town, $company->state, $company->zip, $company->country, "TYPE=WORK;POSTAL"); + } // when company e-mail is empty, use only user e-mail - if (empty(trim($company->email))) - { + if (empty(trim($company->email))) { // was set before, don't set twice - } - // when user e-mail is empty, use only company e-mail - elseif (empty(trim($user2->email))) - { + } elseif (empty(trim($user2->email))) { + // when user e-mail is empty, use only company e-mail $v->setEmail($company->email); - } - // when e-mail domain of user and company are the same, use user e-mail at first (and company e-mail at second) - elseif (strtolower(end(explode("@", $user2->email))) == strtolower(end(explode("@", $company->email)))) - { + } elseif (strtolower(end(explode("@", $user2->email))) == strtolower(end(explode("@", $company->email)))) { + // when e-mail domain of user and company are the same, use user e-mail at first (and company e-mail at second) $v->setEmail($user2->email); // support by Microsoft Outlook (2019 and possible earlier) $v->setEmail($company->email, 'INTERNET'); - } - // when e-mail of user and company complete different use company e-mail at first (and user e-mail at second) - else { + } else { + // when e-mail of user and company complete different use company e-mail at first (and user e-mail at second) $v->setEmail($company->email); // support by Microsoft Outlook (2019 and possible earlier) @@ -113,12 +112,16 @@ if ($company->id) } // Si user lie a un tiers non de type "particulier" - if ($user2->typent_code != 'TE_PRIVATE') $v->setOrg($company->name); + if ($user2->typent_code != 'TE_PRIVATE') { + $v->setOrg($company->name); + } } // Personal informations $v->setPhoneNumber($user2->phone_perso, "TYPE=HOME;VOICE"); -if ($user2->birth) $v->setBirthday($user2->birth); +if ($user2->birth) { + $v->setBirthday($user2->birth); +} $db->close(); diff --git a/htdocs/variants/admin/admin.php b/htdocs/variants/admin/admin.php index 64209076916..f5467760a89 100644 --- a/htdocs/variants/admin/admin.php +++ b/htdocs/variants/admin/admin.php @@ -25,8 +25,9 @@ $langs->loadLangs(array("admin", "products")); $action = GETPOST('action', 'alphanohtml'); // Security check -if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) +if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) { accessforbidden(); +} $error = 0; diff --git a/htdocs/variants/ajax/getCombinations.php b/htdocs/variants/ajax/getCombinations.php index 67c1dd4284c..adb227c2fd6 100644 --- a/htdocs/variants/ajax/getCombinations.php +++ b/htdocs/variants/ajax/getCombinations.php @@ -16,11 +16,21 @@ * along with this program. If not, see <https://www.gnu.org/licenses/>. */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; diff --git a/htdocs/variants/ajax/get_attribute_values.php b/htdocs/variants/ajax/get_attribute_values.php index e80cb9aae2b..e61676339ee 100644 --- a/htdocs/variants/ajax/get_attribute_values.php +++ b/htdocs/variants/ajax/get_attribute_values.php @@ -15,11 +15,21 @@ * along with this program. If not, see <https://www.gnu.org/licenses/>. */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; diff --git a/htdocs/variants/ajax/orderAttribute.php b/htdocs/variants/ajax/orderAttribute.php index 8b851c9be6b..c787517e5c7 100644 --- a/htdocs/variants/ajax/orderAttribute.php +++ b/htdocs/variants/ajax/orderAttribute.php @@ -16,12 +16,24 @@ * along with this program. If not, see <https://www.gnu.org/licenses/>. */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disable token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); // Disable token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOREQUIRETRAN')) { + define('NOREQUIRETRAN', '1'); +} require '../../main.inc.php'; diff --git a/htdocs/variants/card.php b/htdocs/variants/card.php index 986db1b14bc..7a15a4ede97 100644 --- a/htdocs/variants/card.php +++ b/htdocs/variants/card.php @@ -41,7 +41,9 @@ if ($object->fetch($id) < 1) { * Actions */ -if ($cancel) $action = ''; +if ($cancel) { + $action = ''; +} if ($action) { if ($action == 'update') { @@ -60,19 +62,16 @@ if ($action) { $objectval->ref = $ref; $objectval->value = GETPOST('value', 'alpha'); - if (empty($objectval->ref)) - { + if (empty($objectval->ref)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")), null, 'errors'); } - if (empty($objectval->value)) - { + if (empty($objectval->value)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); } - if (!$error) - { + if (!$error) { if ($objectval->update($user) > 0) { setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); } else { @@ -102,8 +101,7 @@ if ($confirm == 'yes') { header('Location: '.dol_buildpath('/variants/list.php', 2)); } exit(); - } elseif ($action == 'confirm_deletevalue') - { + } elseif ($action == 'confirm_deletevalue') { if ($objectval->fetch($valueid) > 0) { if ($objectval->delete($user) < 1) { setEventMessages($langs->trans('CoreErrorMessage'), $objectval->errors, 'errors'); @@ -124,9 +122,11 @@ if ($confirm == 'yes') { $langs->load('products'); +$help_url = 'EN:Module_Products#Variants'; + $title = $langs->trans('ProductAttributeName', dol_htmlentities($object->label)); -llxHeader('', $title); +llxHeader('', $title, $help_url); //print load_fiche_titre($title); diff --git a/htdocs/variants/class/ProductAttribute.class.php b/htdocs/variants/class/ProductAttribute.class.php index bbc3a188137..b823cbea470 100644 --- a/htdocs/variants/class/ProductAttribute.class.php +++ b/htdocs/variants/class/ProductAttribute.class.php @@ -116,8 +116,7 @@ class ProductAttribute extends CommonObject $sql = 'SELECT rowid, ref, ref_ext, label, rang FROM '.MAIN_DB_PREFIX."product_attribute WHERE entity IN (".getEntity('product').')'; $sql .= $this->db->order('rang', 'asc'); $query = $this->db->query($sql); - if ($query) - { + if ($query) { while ($result = $this->db->fetch_object($query)) { $tmp = new ProductAttribute($this->db); $tmp->id = $result->rowid; @@ -128,8 +127,9 @@ class ProductAttribute extends CommonObject $return[] = $tmp; } + } else { + dol_print_error($this->db); } - else dol_print_error($this->db); return $return; } @@ -159,8 +159,7 @@ class ProductAttribute extends CommonObject VALUES ('".$this->db->escape($this->ref)."', '".$this->db->escape($this->ref_ext)."', '".$this->db->escape($this->label)."', ".(int) $this->entity.", ".(int) $this->rang.")"; $query = $this->db->query($sql); - if ($query) - { + if ($query) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'product_attribute'); return $this->id; diff --git a/htdocs/variants/class/ProductCombination.class.php b/htdocs/variants/class/ProductCombination.class.php index 9152336bbe4..8606b12602d 100644 --- a/htdocs/variants/class/ProductCombination.class.php +++ b/htdocs/variants/class/ProductCombination.class.php @@ -174,8 +174,7 @@ class ProductCombination */ if ($fk_price_level > 0) { $combination_price_levels[$fk_price_level] = ProductCombinationLevel::createFromParent($this->db, $this, $fk_price_level); - } - else { + } else { for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { $combination_price_levels[$i] = ProductCombinationLevel::createFromParent($this->db, $this, $i); } @@ -227,8 +226,7 @@ class ProductCombination if ($error) { return $error * -1; - } - else { + } else { return 1; } } @@ -327,7 +325,9 @@ class ProductCombination $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) $nb = $obj->nb; + if ($obj) { + $nb = $obj->nb; + } } return $nb; @@ -470,11 +470,12 @@ class ProductCombination } /** - * Updates the weight of the child product. The price must be updated using Product::updatePrices + * Updates the weight of the child product. The price must be updated using Product::updatePrices. + * This method is called by the update() of a product. * - * @param Product $parent Parent product + * @param Product $parent Parent product * @param User $user Object user - * @return int >0 OK <0 KO + * @return int >0 if OK, <0 if KO */ public function updateProperties(Product $parent, User $user) { @@ -487,6 +488,8 @@ class ProductCombination $child->price_autogen = $parent->price_autogen; $child->weight = $parent->weight; + $child->status = $parent->status; + if ($this->variation_weight) { // If we must add a delta on weight $child->weight = ($child->weight ? $child->weight : 0) + $this->variation_weight; } @@ -506,8 +509,7 @@ class ProductCombination // MultiPrix if (!empty($conf->global->PRODUIT_MULTIPRICES)) { - for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) - { + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { if ($parent->multiprices[$i] != '' || isset($this->combination_price_levels[$i]->variation_price)) { $new_type = $parent->multiprices_base_type[$i]; $new_min_price = $parent->multiprices_min[$i]; @@ -709,8 +711,7 @@ class ProductCombination //Final price impact if (!is_array($forced_pricevar)) { $price_impact[1] = (float) $forced_pricevar; // If false, return 0 - } - else { + } else { $price_impact = $forced_pricevar; } @@ -765,8 +766,7 @@ class ProductCombination // Manage Price levels if ($conf->global->PRODUIT_MULTIPRICES) { - for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) - { + for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { $price_impact[$i] += (float) price2num($variations[$currcombattr][$currcombval]['price']); } } @@ -826,8 +826,7 @@ class ProductCombination $newproduct->barcode = -1; $result = $newproduct->create($user); - if ($result < 0) - { + if ($result < 0) { //In case the error is not related with an already existing product if ($newproduct->error != 'ErrorProductAlreadyExists') { $this->error[] = $newproduct->error; @@ -867,8 +866,7 @@ class ProductCombination } } else { $result = $newproduct->update($newproduct->id, $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -876,8 +874,7 @@ class ProductCombination $newcomb->fk_product_child = $newproduct->id; - if ($newcomb->update($user) < 0) - { + if ($newcomb->update($user) < 0) { $this->error = $newcomb->error; $this->errors = $newcomb->errors; $this->db->rollback(); @@ -925,8 +922,7 @@ class ProductCombination $combination->variation_price_percentage, $combination->variation_price, $combination->variation_weight - ) < 0) - { + ) < 0) { return -1; } } @@ -954,12 +950,10 @@ class ProductCombination $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); - if ($obj->label) - { + if ($obj->label) { $label .= ' '.$obj->label; } $i++; diff --git a/htdocs/variants/combinations.php b/htdocs/variants/combinations.php index 933d379e48a..218ee874bd6 100644 --- a/htdocs/variants/combinations.php +++ b/htdocs/variants/combinations.php @@ -58,8 +58,7 @@ $prodattr = new ProductAttribute($db); $prodattr_val = new ProductAttributeValue($db); $object = new Product($db); -if ($id > 0 || $ref) -{ +if ($id > 0 || $ref) { $object->fetch($id, $ref); } @@ -80,16 +79,13 @@ if (!$object->isProduct() && !$object->isService()) { header('Location: '.dol_buildpath('/product/card.php?id='.$object->id, 2)); exit(); } -if ($action == 'add') -{ +if ($action == 'add') { unset($selectedvariant); unset($_SESSION['addvariant_'.$object->id]); } -if ($action == 'create' && GETPOST('selectvariant', 'alpha')) // We click on select combination -{ +if ($action == 'create' && GETPOST('selectvariant', 'alpha')) { // We click on select combination $action = 'add'; - if (GETPOST('attribute') != '-1' && GETPOST('value') != '-1') - { + if (GETPOST('attribute') != '-1' && GETPOST('value') != '-1') { $selectedvariant[GETPOST('attribute').':'.GETPOST('value')] = GETPOST('attribute').':'.GETPOST('value'); $_SESSION['addvariant_'.$object->id] = $selectedvariant; } @@ -101,8 +97,7 @@ $prodcomb2val = new ProductCombination2ValuePair($db); $productCombination2ValuePairs1 = array(); -if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST('selectvariant', 'alpha')) // We click on Create all defined combinations -{ +if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST('selectvariant', 'alpha')) { // We click on Create all defined combinations //$features = GETPOST('features', 'array'); $features = $_SESSION['addvariant_'.$object->id]; @@ -121,8 +116,7 @@ if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST( // for conf PRODUIT_MULTIPRICES if ($conf->global->PRODUIT_MULTIPRICES) { $level_price_impact = array_map('price2num', $level_price_impact); - } - else { + } else { $level_price_impact = array(1 => $price_impact); $level_price_impact_percent = array(1 => $price_impact_percent); } @@ -156,11 +150,9 @@ if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST( // sanit_feature is an array with 1 (and only 1) value per attribute. // For example: Color->blue, Size->Small, Option->2 //var_dump($sanit_features); - if (!$prodcomb->fetchByProductCombination2ValuePairs($id, $sanit_features)) - { + if (!$prodcomb->fetchByProductCombination2ValuePairs($id, $sanit_features)) { $result = $prodcomb->createProductCombination($user, $object, $sanit_features, array(), $level_price_impact_percent, $level_price_impact, $weight_impact, $reference); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); unset($_SESSION['addvariant_'.$object->id]); @@ -243,8 +235,7 @@ if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST( $prodcomb->variation_price = $level_price_impact[1]; $prodcomb->variation_price_percentage = (bool) $level_price_impact_percent[1]; - } - else { + } else { $level_price_impact = array(1 => $price_impact); $level_price_impact_percent = array(1 => $price_impact_percent); @@ -330,12 +321,13 @@ if ($action === 'confirm_deletecombination') { $form = new Form($db); -if (!empty($id) || !empty($ref)) -{ +if (!empty($id) || !empty($ref)) { llxHeader("", "", $langs->trans("CardProduct".$object->type)); $showbarcode = empty($conf->barcode->enabled) ? 0 : 1; - if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0; + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) { + $showbarcode = 0; + } $head = product_prepare_head($object); $titre = $langs->trans("CardProduct".$object->type); @@ -357,17 +349,25 @@ if (!empty($id) || !empty($ref)) print '<tr><td class="titlefield">'.$langs->trans("DefaultTaxRate").'</td><td>'; $positiverates = ''; - if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates = '0'; + if (price2num($object->tva_tx)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + } + if (price2num($object->localtax1_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + } + if (price2num($object->localtax2_type)) { + $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + } + if (empty($positiverates)) { + $positiverates = '0'; + } echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); /* - if ($object->default_vat_code) - { - print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; - } - else print vatrate($object->tva_tx, true, $object->tva_npr, true);*/ + if ($object->default_vat_code) + { + print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; + } + else print vatrate($object->tva_tx, true, $object->tva_npr, true);*/ print '</td></tr>'; // Price @@ -390,8 +390,7 @@ if (!empty($id) || !empty($ref)) // Weight print '<tr><td>'.$langs->trans("Weight").'</td><td>'; - if ($object->weight != '') - { + if ($object->weight != '') { print $object->weight." ".measuringUnitString(0, "weight", $object->weight_units); } else { print '&nbsp;'; @@ -466,14 +465,14 @@ if (!empty($id) || !empty($ref)) foreach ($productCombination2ValuePairs1 as $pc2v) { $prodattr_val->fetch($pc2v->fk_prod_attr_val); ?> - variants_selected.index.push(<?php echo $pc2v->fk_prod_attr ?>); - variants_selected.info[<?php echo $pc2v->fk_prod_attr ?>] = { - attribute: variants_available[<?php echo $pc2v->fk_prod_attr ?>], - value: { - id: <?php echo $pc2v->fk_prod_attr_val ?>, - label: '<?php echo $prodattr_val->value ?>' - } - }; + variants_selected.index.push(<?php echo $pc2v->fk_prod_attr ?>); + variants_selected.info[<?php echo $pc2v->fk_prod_attr ?>] = { + attribute: variants_available[<?php echo $pc2v->fk_prod_attr ?>], + value: { + id: <?php echo $pc2v->fk_prod_attr_val ?>, + label: '<?php echo $prodattr_val->value ?>' + } + }; <?php } ?> @@ -604,8 +603,7 @@ if (!empty($id) || !empty($ref)) print '<table class="border" style="width: 100%">'; // When in edit mode - if (is_array($productCombination2ValuePairs1) && count($productCombination2ValuePairs1)) - { + if (is_array($productCombination2ValuePairs1) && count($productCombination2ValuePairs1)) { ?> <tr> <td class="titlefieldcreate tdtop"><label for="features"><?php echo $langs->trans('Combination') ?></label></td> @@ -616,8 +614,7 @@ if (!empty($id) || !empty($ref)) $result1 = $prodattr->fetch($val->fk_prod_attr); $result2 = $prodattr_val->fetch($val->fk_prod_attr_val); //print 'rr'.$result1.' '.$result2; - if ($result1 > 0 && $result2 > 0) - { + if ($result1 > 0 && $result2 > 0) { print $prodattr->label.' - '.$prodattr_val->value.'<br>'; // TODO Add delete link } @@ -651,8 +648,7 @@ if (!empty($id) || !empty($ref)) } else { $prodcomb->fetchCombinationPriceLevels(); - for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) - { + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { print '<tr>'; print '<td><label for="level_price_impact_'.$i.'">'.$langs->trans('ImpactOnPriceLevel', $i).'</label>'; if ($i === 1) { @@ -703,7 +699,9 @@ if (!empty($id) || !empty($ref)) ?> <div style="text-align: center"> - <input type="submit" name="create" <?php if (!is_array($productCombination2ValuePairs1)) print ' disabled="disabled"'; ?> value="<?php echo $action == 'add' ? $langs->trans('Create') : $langs->trans("Save") ?>" class="button button-save"> + <input type="submit" name="create" <?php if (!is_array($productCombination2ValuePairs1)) { + print ' disabled="disabled"'; + } ?> value="<?php echo $action == 'add' ? $langs->trans('Create') : $langs->trans("Save") ?>" class="button button-save"> &nbsp; <input type="submit" name="cancel" value="<?php echo $langs->trans("Cancel"); ?>" class="button button-cancel"> </div> @@ -732,8 +730,7 @@ if (!empty($id) || !empty($ref)) $comb2val = new ProductCombination2ValuePair($db); - if ($productCombinations) - { + if ($productCombinations) { ?> <script type="text/javascript"> @@ -767,8 +764,7 @@ if (!empty($id) || !empty($ref)) print '<a href="combinations.php?id='.$object->id.'&action=add&token='.newToken().'" class="butAction">'.$langs->trans('NewProductCombination').'</a>'; // NewVariant - if ($productCombinations) - { + if ($productCombinations) { print '<a href="combinations.php?id='.$object->id.'&action=copy&token='.newToken().'" class="butAction">'.$langs->trans('PropagateVariant').'</a>'; } @@ -791,8 +787,8 @@ if (!empty($id) || !empty($ref)) // List of mass actions available /* $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), ); if ($user->rights->product->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); @@ -800,8 +796,7 @@ if (!empty($id) || !empty($ref)) */ $aaa = ''; - if (count($productCombinations)) - { + if (count($productCombinations)) { $aaa = '<label for="massaction">'.$langs->trans('BulkActions').'</label>'; $aaa .= '<select id="bulk_action" name="massaction" class="flat">'; $aaa .= ' <option value="nothing">&nbsp;</option>'; @@ -826,11 +821,13 @@ if (!empty($id) || !empty($ref)) <td class="liste_titre"><?php echo $langs->trans('Product') ?></td> <td class="liste_titre"><?php echo $langs->trans('Combination') ?></td> <td class="liste_titre right"><?php echo $langs->trans('PriceImpact') ?></td> - <?php if ($object->isProduct()) print'<td class="liste_titre right">'.$langs->trans('WeightImpact').'</td>'; ?> + <?php if ($object->isProduct()) { + print'<td class="liste_titre right">'.$langs->trans('WeightImpact').'</td>'; + } ?> <td class="liste_titre center"><?php echo $langs->trans('OnSell') ?></td> <td class="liste_titre center"><?php echo $langs->trans('OnBuy') ?></td> <td class="liste_titre"></td> - <?php + <?php print '<td class="liste_titre center">'; $searchpicto = $form->showCheckAddButtons('checkforselect', 1); print $searchpicto; @@ -839,10 +836,8 @@ if (!empty($id) || !empty($ref)) </tr> <?php - if (count($productCombinations)) - { - foreach ($productCombinations as $currcomb) - { + if (count($productCombinations)) { + foreach ($productCombinations as $currcomb) { $prodstatic->fetch($currcomb->fk_product_child); print '<tr class="oddeven">'; print '<td>'.$prodstatic->getNomUrl(1).'</td>'; @@ -869,10 +864,11 @@ if (!empty($id) || !empty($ref)) print '<a class="paddingleft paddingright" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=delete&token='.newToken().'&valueid='.$currcomb->id.'">'.img_delete().'</a>'; print '</td>'; print '<td class="nowrap center">'; - if ($productCombinations || $massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + if ($productCombinations || $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($prodstatic->id, $arrayofselected)) $selected = 1; + if (in_array($prodstatic->id, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; diff --git a/htdocs/variants/create.php b/htdocs/variants/create.php index e37548f39f3..8f3a1d28d9f 100644 --- a/htdocs/variants/create.php +++ b/htdocs/variants/create.php @@ -40,8 +40,7 @@ if ($action == 'add') { $resid = $prodattr->create($user); if ($resid > 0) { setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); - if ($backtopage) - { + if ($backtopage) { header('Location: '.$backtopage); } else { header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$resid.'&backtopage='.urlencode($backtopage)); @@ -60,9 +59,12 @@ $langs->load('products'); * View */ +$help_url = 'EN:Module_Products#Variants'; + $title = $langs->trans('NewProductAttribute'); -llxHeader('', $title); +llxHeader('', $title, $help_url); + print load_fiche_titre($title); diff --git a/htdocs/variants/create_val.php b/htdocs/variants/create_val.php index b422df90120..22dc2a1a110 100644 --- a/htdocs/variants/create_val.php +++ b/htdocs/variants/create_val.php @@ -41,8 +41,7 @@ if ($object->fetch($id) < 1) { * Actions */ -if ($cancel) -{ +if ($cancel) { $action = ''; header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$object->id); exit(); @@ -56,8 +55,7 @@ if ($cancel) * View */ -if ($action == 'add') -{ +if ($action == 'add') { if (empty($ref) || empty($value)) { setEventMessages($langs->trans('ErrorFieldsRequired'), null, 'errors'); } else { @@ -77,9 +75,11 @@ if ($action == 'add') $langs->load('products'); +$help_url = 'EN:Module_Products#Variants'; + $title = $langs->trans('ProductAttributeName', dol_htmlentities($object->label)); -llxHeader('', $title); +llxHeader('', $title, $help_url); $h = 0; $head[$h][0] = DOL_URL_ROOT.'/variants/card.php?id='.$object->id; diff --git a/htdocs/variants/list.php b/htdocs/variants/list.php index 683b28719a9..dde43397671 100644 --- a/htdocs/variants/list.php +++ b/htdocs/variants/list.php @@ -56,8 +56,7 @@ $variants = $object->fetchAll(); llxHeader('', $title); $newcardbutton = ''; -if ($user->rights->produit->creer) -{ +if ($user->rights->produit->creer) { $newcardbutton .= dolGetButtonTitle($langs->trans('Create'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/variants/create.php'); } diff --git a/htdocs/viewimage.php b/htdocs/viewimage.php index 983c7996898..e01bad39d77 100644 --- a/htdocs/viewimage.php +++ b/htdocs/viewimage.php @@ -28,48 +28,84 @@ //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOREQUIRETRAN')) { + define('NOREQUIRETRAN', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} // Some value of modulepart can be used to get resources that are public so no login are required. // Note that only directory logo is free to access without login. -if (isset($_GET["modulepart"]) && $_GET["modulepart"] == 'mycompany' && preg_match('/^\/?logos\//', $_GET['file'])) -{ - if (!defined("NOLOGIN")) define("NOLOGIN", 1); - if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. - if (!defined("NOIPCHECK")) define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (isset($_GET["modulepart"]) && $_GET["modulepart"] == 'mycompany' && preg_match('/^\/?logos\//', $_GET['file'])) { + if (!defined("NOLOGIN")) { + define("NOLOGIN", 1); + } + if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. + } + if (!defined("NOIPCHECK")) { + define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip + } } // For direct external download link, we don't need to load/check we are into a login session -if (isset($_GET["hashp"]) && !defined("NOLOGIN")) -{ - if (!defined("NOLOGIN")) define("NOLOGIN", 1); - if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. - if (!defined("NOIPCHECK")) define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (isset($_GET["hashp"]) && !defined("NOLOGIN")) { + if (!defined("NOLOGIN")) { + define("NOLOGIN", 1); + } + if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. + } + if (!defined("NOIPCHECK")) { + define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip + } } // Some value of modulepart can be used to get resources that are public so no login are required. -if (isset($_GET["modulepart"]) && $_GET["modulepart"] == 'medias') -{ - if (!defined("NOLOGIN")) define("NOLOGIN", 1); - if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. - if (!defined("NOIPCHECK")) define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (isset($_GET["modulepart"]) && $_GET["modulepart"] == 'medias') { + if (!defined("NOLOGIN")) { + define("NOLOGIN", 1); + } + if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. + } + if (!defined("NOIPCHECK")) { + define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip + } } // Used by TakePOS Auto Order -if (isset($_GET["modulepart"]) && $_GET["modulepart"] == 'product' && isset($_GET["publictakepos"])) -{ - if (!defined("NOLOGIN")) define("NOLOGIN", 1); - if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. - if (!defined("NOIPCHECK")) define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (isset($_GET["modulepart"]) && $_GET["modulepart"] == 'product' && isset($_GET["publictakepos"])) { + if (!defined("NOLOGIN")) { + define("NOLOGIN", 1); + } + if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. + } + if (!defined("NOIPCHECK")) { + define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip + } } // For multicompany $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); +if (is_numeric($entity)) { + define("DOLENTITY", $entity); +} /** * Header empty @@ -101,9 +137,15 @@ $urlsource = GETPOST('urlsource', 'alpha'); $entity = GETPOST('entity', 'int') ?GETPOST('entity', 'int') : $conf->entity; // Security check -if (empty($modulepart) && empty($hashp)) accessforbidden('Bad link. Bad value for parameter modulepart', 0, 0, 1); -if (empty($original_file) && empty($hashp) && $modulepart != 'barcode') accessforbidden('Bad link. Missing identification to find file (param file or hashp)', 0, 0, 1); -if ($modulepart == 'fckeditor') $modulepart = 'medias'; // For backward compatibility +if (empty($modulepart) && empty($hashp)) { + accessforbidden('Bad link. Bad value for parameter modulepart', 0, 0, 1); +} +if (empty($original_file) && empty($hashp) && $modulepart != 'barcode') { + accessforbidden('Bad link. Missing identification to find file (param file or hashp)', 0, 0, 1); +} +if ($modulepart == 'fckeditor') { + $modulepart = 'medias'; // For backward compatibility +} @@ -119,38 +161,33 @@ if ($modulepart == 'fckeditor') $modulepart = 'medias'; // For backward compatib * View */ -if (GETPOST("cache", 'alpha')) -{ +if (GETPOST("cache", 'alpha')) { // Important: Following code is to avoid page request by browser and PHP CPU at // each Dolibarr page access. - if (empty($dolibarr_nocache)) - { + if (empty($dolibarr_nocache)) { header('Cache-Control: max-age=3600, public, must-revalidate'); header('Pragma: cache'); // This is to avoid having Pragma: no-cache - } else header('Cache-Control: no-cache'); + } else { + header('Cache-Control: no-cache'); + } //print $dolibarr_nocache; exit; } // If we have a hash public (hashp), we guess the original_file. -if (!empty($hashp)) -{ +if (!empty($hashp)) { include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile = new EcmFiles($db); $result = $ecmfile->fetch(0, '', '', '', $hashp); - if ($result > 0) - { + if ($result > 0) { $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory // filepath can be 'users/X' or 'X/propale/PR11111' - if (is_numeric($tmp[0])) // If first tmp is numeric, it is subdir of company for multicompany, we take next part. - { + if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part. $tmp = explode('/', $tmp[1], 2); } $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path - if ($modulepart) // Not required, so often not defined, for link using public hashp parameter. - { - if ($moduleparttocheck == $modulepart) - { + if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter. + if ($moduleparttocheck == $modulepart) { // We remove first level of directory $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir //var_dump($original_file); exit; @@ -169,13 +206,20 @@ if (!empty($hashp)) // Define mime type $type = 'application/octet-stream'; -if (GETPOST('type', 'alpha')) $type = GETPOST('type', 'alpha'); -else $type = dol_mimetype($original_file); +if (GETPOST('type', 'alpha')) { + $type = GETPOST('type', 'alpha'); +} else { + $type = dol_mimetype($original_file); +} // Security: This wrapper is for images. We do not allow type/html -if (preg_match('/html/i', $type)) accessforbidden('Error: Using the image wrapper to output a file with a mime type HTML is not possible.', 0, 0, 1); +if (preg_match('/html/i', $type)) { + accessforbidden('Error: Using the image wrapper to output a file with a mime type HTML is not possible.', 0, 0, 1); +} // Security: This wrapper is for images. We do not allow files ending with .noexe -if (preg_match('/\.noexe$/i', $original_file)) accessforbidden('Error: Using the image wrapper to output a file ending with .noexe is not allowed.', 0, 0, 1); +if (preg_match('/\.noexe$/i', $original_file)) { + accessforbidden('Error: Using the image wrapper to output a file ending with .noexe is not allowed.', 0, 0, 1); +} // Security: Delete string ../ into $original_file $original_file = str_replace("../", "/", $original_file); @@ -184,7 +228,9 @@ $original_file = str_replace("../", "/", $original_file); $refname = basename(dirname($original_file)."/"); // Security check -if (empty($modulepart)) accessforbidden('Bad value for parameter modulepart', 0, 0, 1); +if (empty($modulepart)) { + accessforbidden('Bad value for parameter modulepart', 0, 0, 1); +} $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $refname); $accessallowed = $check_access['accessallowed']; @@ -200,20 +246,15 @@ if (!empty($hashp)) { } } else { // Basic protection (against external users only) - if ($user->socid > 0) - { - if ($sqlprotectagainstexternals) - { + if ($user->socid > 0) { + if ($sqlprotectagainstexternals) { $resql = $db->query($sqlprotectagainstexternals); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($user->socid != $obj->fk_soc) - { + if ($user->socid != $obj->fk_soc) { $accessallowed = 0; break; } @@ -226,15 +267,13 @@ if (!empty($hashp)) { // Security: // Limit access if permissions are wrong -if (!$accessallowed) -{ +if (!$accessallowed) { accessforbidden(); } // Security: // On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers. -if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) -{ +if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) { dol_syslog("Refused to deliver file ".$fullpath_original_file); print "ErrorFileNameInvalid: ".dol_escape_htmltag($original_file); exit; @@ -242,15 +281,13 @@ if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $full -if ($modulepart == 'barcode') -{ +if ($modulepart == 'barcode') { $generator = GETPOST("generator", "alpha"); $code = GETPOST("code", 'none'); // This can be rich content (qrcode, datamatrix, ...) $encoding = GETPOST("encoding", "alpha"); $readable = GETPOST("readable", 'alpha') ?GETPOST("readable", "alpha") : "Y"; - if (empty($generator) || empty($encoding)) - { + if (empty($generator) || empty($encoding)) { print 'Error: Parameter "generator" or "encoding" not defined'; exit; } @@ -259,23 +296,25 @@ if ($modulepart == 'barcode') $result = 0; - foreach ($dirbarcode as $reldir) - { + foreach ($dirbarcode as $reldir) { $dir = dol_buildpath($reldir, 0); $newdir = dol_osencode($dir); // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php) - if (!is_dir($newdir)) continue; + if (!is_dir($newdir)) { + continue; + } $result = @include_once $newdir.$generator.'.modules.php'; - if ($result) break; + if ($result) { + break; + } } // Load barcode class $classname = "mod".ucfirst($generator); $module = new $classname($db); - if ($module->encodingIsSupported($encoding)) - { + if ($module->encodingIsSupported($encoding)) { $result = $module->buildBarCode($code, $encoding, $readable); } } else { @@ -288,17 +327,15 @@ if ($modulepart == 'barcode') dol_syslog("viewimage.php return file $fullpath_original_file filename=$filename content-type=$type"); // This test is to avoid error images when image is not available (for example thumbs). - if (!dol_is_file($fullpath_original_file) && empty($_GET["noalt"])) - { + if (!dol_is_file($fullpath_original_file) && empty($_GET["noalt"])) { $fullpath_original_file = DOL_DOCUMENT_ROOT.'/public/theme/common/nophoto.png'; /*$error='Error: File '.$_GET["file"].' does not exists or filesystems permissions are not allowed'; - print $error; - exit;*/ + print $error; + exit;*/ } // Permissions are ok and file found, so we return it - if ($type) - { + if ($type) { top_httphead($type); header('Content-Disposition: inline; filename="'.basename($fullpath_original_file).'"'); } else { @@ -312,4 +349,6 @@ if ($modulepart == 'barcode') } -if (is_object($db)) $db->close(); +if (is_object($db)) { + $db->close(); +} diff --git a/htdocs/webservices/admin/index.php b/htdocs/webservices/admin/index.php index 2c14d2d07f5..1c78acae84d 100644 --- a/htdocs/webservices/admin/index.php +++ b/htdocs/webservices/admin/index.php @@ -29,26 +29,24 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; $langs->load("admin"); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $actionsave = GETPOST("save"); // Sauvegardes parametres -if ($actionsave) -{ +if ($actionsave) { $i = 0; $db->begin(); $i += dolibarr_set_const($db, 'WEBSERVICES_KEY', GETPOST("WEBSERVICES_KEY"), 'chaine', 0, '', $conf->entity); - if ($i >= 1) - { + if ($i >= 1) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } - else { + } else { $db->rollback(); setEventMessages($langs->trans("Error"), null, 'errors'); } @@ -84,8 +82,9 @@ print "</tr>"; print '<tr class="oddeven">'; print '<td class="fieldrequired">'.$langs->trans("KeyForWebServicesAccess").'</td>'; print '<td><input type="text" class="flat" id="WEBSERVICES_KEY" name="WEBSERVICES_KEY" value="'.(GETPOST('WEBSERVICES_KEY') ?GETPOST('WEBSERVICES_KEY') : (!empty($conf->global->WEBSERVICES_KEY) ? $conf->global->WEBSERVICES_KEY : '')).'" size="40">'; -if (!empty($conf->use_javascript_ajax)) +if (!empty($conf->use_javascript_ajax)) { print '&nbsp;'.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"'); +} print '</td>'; print '<td>&nbsp;</td>'; print '</tr>'; @@ -118,9 +117,10 @@ $webservices = array( // WSDL print '<u>'.$langs->trans("WSDLCanBeDownloadedHere").':</u><br>'; -foreach ($webservices as $name => $right) -{ - if (!empty($right) && !verifCond($right)) continue; +foreach ($webservices as $name => $right) { + if (!empty($right) && !verifCond($right)) { + continue; + } $url = DOL_MAIN_URL_ROOT.'/webservices/server_'.$name.'.php?wsdl'; print img_picto('', 'globe').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n"; } @@ -129,9 +129,10 @@ print '<br>'; // Endpoint print '<u>'.$langs->trans("EndPointIs").':</u><br>'; -foreach ($webservices as $name => $right) -{ - if (!empty($right) && !verifCond($right)) continue; +foreach ($webservices as $name => $right) { + if (!empty($right) && !verifCond($right)) { + continue; + } $url = DOL_MAIN_URL_ROOT.'/webservices/server_'.$name.'.php'; print img_picto('', 'globe').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n"; } @@ -141,8 +142,7 @@ print '<br>'; print '<br>'; print $langs->trans("OnlyActiveElementsAreShown", DOL_URL_ROOT.'/admin/modules.php'); -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print "\n".'<script type="text/javascript">'; print '$(document).ready(function () { $("#generate_token").click(function() { diff --git a/htdocs/webservices/index.php b/htdocs/webservices/index.php index e6e76692b05..72b0548ec52 100644 --- a/htdocs/webservices/index.php +++ b/htdocs/webservices/index.php @@ -38,8 +38,7 @@ $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces"); // Enable and test if module web services is enabled -if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) -{ +if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) { $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; diff --git a/htdocs/webservices/server_actioncomm.php b/htdocs/webservices/server_actioncomm.php index 140351e7d21..4be0847bc51 100644 --- a/htdocs/webservices/server_actioncomm.php +++ b/htdocs/webservices/server_actioncomm.php @@ -23,7 +23,9 @@ * \brief File that is entry point to call Dolibarr WebServices */ -if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); +if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", '1'); +} require "../master.inc.php"; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP @@ -37,8 +39,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; dol_syslog("Call ActionComm webservices interfaces"); // Enable and test if module web services is enabled -if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) -{ +if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) { $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; @@ -122,18 +123,21 @@ $extrafield_array = null; if (is_array($extrafields) && count($extrafields) > 0) { $extrafield_array = array(); } -if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) -{ - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { +if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $type = $extrafields->attributes[$elementtype]['type'][$key]; - if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } - else {$type = 'xsd:string'; } + if ($type == 'date' || $type == 'datetime') { + $type = 'xsd:dateTime'; + } else { + $type = 'xsd:string'; + } $extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type); } } -if (is_array($extrafield_array)) $actioncomm_fields = array_merge($actioncomm_fields, $extrafield_array); +if (is_array($extrafield_array)) { + $actioncomm_fields = array_merge($actioncomm_fields, $extrafield_array); +} // Define other specific objects $server->wsdl->addComplexType( @@ -255,7 +259,9 @@ function getActionComm($authentication, $id) dol_syslog("Function: getActionComm login=".$authentication['login']." id=".$id); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -263,22 +269,18 @@ function getActionComm($authentication, $id) $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if ($error || (!$id)) - { + if ($error || (!$id)) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->agenda->allactions->read) - { + if ($fuser->rights->agenda->allactions->read) { $actioncomm = new ActionComm($db); $result = $actioncomm->fetch($id); - if ($result > 0) - { + if ($result > 0) { $actioncomm_result_fields = array( 'id' => $actioncomm->id, 'ref'=> $actioncomm->ref, @@ -315,10 +317,8 @@ function getActionComm($authentication, $id) //Get extrafield values $actioncomm->fetch_optionals(); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $actioncomm_result_fields = array_merge($actioncomm_result_fields, array('options_'.$key => $actioncomm->array_options['options_'.$key])); } } @@ -327,20 +327,17 @@ function getActionComm($authentication, $id) $objectresp = array( 'result'=>array('result_code'=>'OK', 'result_label'=>''), 'actioncomm'=>$actioncomm_result_fields); - } - else { + } else { $error++; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; } - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -360,7 +357,9 @@ function getListActionCommType($authentication) dol_syslog("Function: getListActionCommType login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -368,18 +367,15 @@ function getListActionCommType($authentication) $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->agenda->myactions->read) - { + if ($fuser->rights->agenda->myactions->read) { $cactioncomm = new CActionComm($db); $result = $cactioncomm->liste_array('', 'code'); - if ($result > 0) - { + if ($result > 0) { $resultarray = array(); - foreach ($cactioncomm->liste_array as $code=>$libeller) { + foreach ($cactioncomm->liste_array as $code => $libeller) { $resultarray[] = array('code'=>$code, 'libelle'=>$libeller); } @@ -396,8 +392,7 @@ function getListActionCommType($authentication) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -420,7 +415,9 @@ function createActionComm($authentication, $actioncomm) dol_syslog("Function: createActionComm login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -428,8 +425,7 @@ function createActionComm($authentication, $actioncomm) $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); - if (!$error) - { + if (!$error) { $newobject = new ActionComm($db); $newobject->datep = $actioncomm['datep']; @@ -454,10 +450,8 @@ function createActionComm($authentication, $actioncomm) // fetch optionals attributes and labels $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($elementtype, true); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $key = 'options_'.$key; $newobject->array_options[$key] = $actioncomm[$key]; } @@ -466,17 +460,14 @@ function createActionComm($authentication, $actioncomm) $db->begin(); $result = $newobject->create($fuser); - if ($result <= 0) - { + if ($result <= 0) { $error++; } - if (!$error) - { + if (!$error) { $db->commit(); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id); - } - else { + } else { $db->rollback(); $error++; $errorcode = 'KO'; @@ -484,8 +475,7 @@ function createActionComm($authentication, $actioncomm) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -507,7 +497,9 @@ function updateActionComm($authentication, $actioncomm) dol_syslog("Function: updateActionComm login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -519,8 +511,7 @@ function updateActionComm($authentication, $actioncomm) $error++; $errorcode = 'KO'; $errorlabel = "Actioncomm id is mandatory."; } - if (!$error) - { + if (!$error) { $objectfound = false; $object = new ActionComm($db); @@ -551,10 +542,8 @@ function updateActionComm($authentication, $actioncomm) // fetch optionals attributes and labels $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($elementtype, true); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $key = 'options_'.$key; $object->array_options[$key] = $actioncomm[$key]; } @@ -568,16 +557,13 @@ function updateActionComm($authentication, $actioncomm) } } - if ((!$error) && ($objectfound)) - { + if ((!$error) && ($objectfound)) { $db->commit(); $objectresp = array( 'result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$object->id ); - } - elseif ($objectfound) - { + } elseif ($objectfound) { $db->rollback(); $error++; $errorcode = 'KO'; @@ -589,8 +575,7 @@ function updateActionComm($authentication, $actioncomm) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } diff --git a/htdocs/webservices/server_category.php b/htdocs/webservices/server_category.php index 949c95dc530..f016a65f61f 100644 --- a/htdocs/webservices/server_category.php +++ b/htdocs/webservices/server_category.php @@ -21,7 +21,9 @@ * \brief File that is entry point to call Dolibarr WebServices */ -if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); +if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", '1'); +} require "../master.inc.php"; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP @@ -32,8 +34,7 @@ require_once DOL_DOCUMENT_ROOT."/categories/class/categorie.class.php"; dol_syslog("Call Dolibarr webservices interfaces"); // Enable and test if module web services is enabled -if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) -{ +if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) { $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; @@ -109,12 +110,12 @@ $server->wsdl->addComplexType( * Image of product */ $server->wsdl->addComplexType( - 'PhotosArray', - 'complexType', - 'array', - 'sequence', - '', - array( + 'PhotosArray', + 'complexType', + 'array', + 'sequence', + '', + array( 'image' => array( 'name' => 'image', 'type' => 'tns:image', @@ -128,12 +129,12 @@ $server->wsdl->addComplexType( * An image */ $server->wsdl->addComplexType( - 'image', - 'complexType', - 'struct', - 'all', - '', - array( + 'image', + 'complexType', + 'struct', + 'all', + '', + array( 'photo' => array('name'=>'photo', 'type'=>'xsd:string'), 'photo_vignette' => array('name'=>'photo_vignette', 'type'=>'xsd:string'), 'imgWidth' => array('name'=>'imgWidth', 'type'=>'xsd:string'), @@ -194,30 +195,28 @@ function getCategory($authentication, $id) dol_syslog("Function: getCategory login=".$authentication['login']." id=".$id); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } $objectresp = array(); $errorcode = ''; $errorlabel = ''; $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); - if (!$error && !$id) - { + if (!$error && !$id) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id must be provided."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); $nbmax = 10; - if ($fuser->rights->categorie->lire) - { + if ($fuser->rights->categorie->lire) { $categorie = new Categorie($db); $result = $categorie->fetch($id); - if ($result > 0) - { + if ($result > 0) { $dir = (!empty($conf->categorie->dir_output) ? $conf->categorie->dir_output : $conf->service->dir_output); $pdir = get_exdir($categorie->id, 2, 0, 0, $categorie, 'category').$categorie->id."/photos/"; $dir = $dir.'/'.$pdir; @@ -235,10 +234,8 @@ function getCategory($authentication, $id) ); $cats = $categorie->get_filles(); - if (count($cats) > 0) - { - foreach ($cats as $fille) - { + if (count($cats) > 0) { + foreach ($cats as $fille) { $dir = (!empty($conf->categorie->dir_output) ? $conf->categorie->dir_output : $conf->service->dir_output); $pdir = get_exdir($fille->id, 2, 0, 0, $categorie, 'category').$fille->id."/photos/"; $dir = $dir.'/'.$pdir; @@ -261,20 +258,17 @@ function getCategory($authentication, $id) 'result'=>array('result_code'=>'OK', 'result_label'=>''), 'categorie'=> $cat ); - } - else { + } else { $error++; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id; } - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } diff --git a/htdocs/webservices/server_contact.php b/htdocs/webservices/server_contact.php index 97b219c7aba..9f57a445cc3 100644 --- a/htdocs/webservices/server_contact.php +++ b/htdocs/webservices/server_contact.php @@ -21,7 +21,9 @@ * \brief File that is entry point to call Dolibarr WebServices */ -if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); +if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", '1'); +} require "../master.inc.php"; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP @@ -33,8 +35,7 @@ require_once DOL_DOCUMENT_ROOT."/core/class/extrafields.class.php"; dol_syslog("Call Contact webservices interfaces"); // Enable and test if module web services is enabled -if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) -{ +if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) { $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; @@ -127,18 +128,21 @@ $extrafield_array = null; if (is_array($extrafields) && count($extrafields) > 0) { $extrafield_array = array(); } -if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) -{ - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { +if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $type = $extrafields->attributes[$elementtype]['type'][$key]; - if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } - else {$type = 'xsd:string'; } + if ($type == 'date' || $type == 'datetime') { + $type = 'xsd:dateTime'; + } else { + $type = 'xsd:string'; + } $extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type); } } -if (is_array($extrafield_array)) $contact_fields = array_merge($contact_fields, $extrafield_array); +if (is_array($extrafield_array)) { + $contact_fields = array_merge($contact_fields, $extrafield_array); +} // Define other specific objects $server->wsdl->addComplexType( @@ -247,7 +251,9 @@ function getContact($authentication, $id, $ref_ext) dol_syslog("Function: getContact login=".$authentication['login']." id=".$id." ref_ext=".$ref_ext); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -255,24 +261,20 @@ function getContact($authentication, $id, $ref_ext) $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (!$error && ($id && $ref_ext)) - { + if (!$error && ($id && $ref_ext)) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be both provided. You must choose one or other but not both."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); $contact = new Contact($db); $result = $contact->fetch($id, 0, $ref_ext); - if ($result > 0) - { + if ($result > 0) { // Only internal user who have contact read permission // Or for external user who have contact read permission, with restrict on socid - if ( - $fuser->rights->societe->contact->lire && !$fuser->socid + if ($fuser->rights->societe->contact->lire && !$fuser->socid || ($fuser->rights->societe->contact->lire && ($fuser->socid == $contact->socid)) ) { $contact_result_fields = array( @@ -319,10 +321,8 @@ function getContact($authentication, $id, $ref_ext) //Get extrafield values $contact->fetch_optionals(); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $contact_result_fields = array_merge($contact_result_fields, array('options_'.$key => $contact->array_options['options_'.$key])); } } @@ -332,20 +332,17 @@ function getContact($authentication, $id, $ref_ext) 'result'=>array('result_code'=>'OK', 'result_label'=>''), 'contact'=>$contact_result_fields ); - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } - } - else { + } else { $error++; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref_ext='.$ref_ext; } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -368,7 +365,9 @@ function createContact($authentication, $contact) dol_syslog("Function: createContact login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -376,13 +375,11 @@ function createContact($authentication, $contact) $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (empty($contact['lastname'])) - { + if (empty($contact['lastname'])) { $error++; $errorcode = 'KO'; $errorlabel = "Name is mandatory."; } - if (!$error) - { + if (!$error) { $newobject = new Contact($db); $newobject->id = $contact['id']; @@ -424,10 +421,8 @@ function createContact($authentication, $contact) // fetch optionals attributes and labels $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($elementtype, true); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $key = 'options_'.$key; $newobject->array_options[$key] = $contact[$key]; } @@ -439,17 +434,14 @@ function createContact($authentication, $contact) $db->begin(); $result = $newobject->create($fuser); - if ($result <= 0) - { + if ($result <= 0) { $error++; } - if (!$error) - { + if (!$error) { $db->commit(); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref); - } - else { + } else { $db->rollback(); $error++; $errorcode = 'KO'; @@ -457,8 +449,7 @@ function createContact($authentication, $contact) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -478,7 +469,9 @@ function getContactsForThirdParty($authentication, $idthirdparty) dol_syslog("Function: getContactsForThirdParty login=".$authentication['login']." idthirdparty=".$idthirdparty); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -486,14 +479,12 @@ function getContactsForThirdParty($authentication, $idthirdparty) $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (!$error && empty($idthirdparty)) - { + if (!$error && empty($idthirdparty)) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter id is not provided'; } - if (!$error) - { + if (!$error) { $linesinvoice = array(); $sql = "SELECT c.rowid, c.fk_soc, c.civility as civility_id, c.lastname, c.firstname, c.statut as status,"; @@ -515,12 +506,10 @@ function getContactsForThirdParty($authentication, $idthirdparty) $sql .= " WHERE c.fk_soc = ".$idthirdparty; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { // En attendant remplissage par boucle $obj = $db->fetch_object($resql); @@ -580,15 +569,13 @@ function getContactsForThirdParty($authentication, $idthirdparty) 'contacts'=>$linescontact ); - } - else { + } else { $error++; $errorcode = $db->lasterrno(); $errorlabel = $db->lasterror(); } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -611,7 +598,9 @@ function updateContact($authentication, $contact) dol_syslog("Function: updateContact login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -623,14 +612,12 @@ function updateContact($authentication, $contact) $error++; $errorcode = 'KO'; $errorlabel = "Contact id or ref_ext is mandatory."; } // Check parameters - if (!$error && ($id && $ref_ext)) - { + if (!$error && ($id && $ref_ext)) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be all provided. You must choose one of them."; } - if (!$error) - { + if (!$error) { $objectfound = false; include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -650,7 +637,9 @@ function updateContact($authentication, $contact) $object->town = $contact['town']; $object->country_id = $contact['country_id']; - if ($contact['country_code']) $object->country_id = getCountry($contact['country_code'], 3); + if ($contact['country_code']) { + $object->country_id = getCountry($contact['country_code'], 3); + } $object->province_id = $contact['province_id']; @@ -671,10 +660,8 @@ function updateContact($authentication, $contact) // fetch optionals attributes and labels $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($elementtype, true); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $key = 'options_'.$key; $object->array_options[$key] = $contact[$key]; } @@ -688,16 +675,13 @@ function updateContact($authentication, $contact) } } - if ((!$error) && ($objectfound)) - { + if ((!$error) && ($objectfound)) { $db->commit(); $objectresp = array( 'result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$object->id ); - } - elseif ($objectfound) - { + } elseif ($objectfound) { $db->rollback(); $error++; $errorcode = 'KO'; @@ -709,8 +693,7 @@ function updateContact($authentication, $contact) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } diff --git a/htdocs/webservices/server_invoice.php b/htdocs/webservices/server_invoice.php index e696258e5d9..d1382ac7c62 100644 --- a/htdocs/webservices/server_invoice.php +++ b/htdocs/webservices/server_invoice.php @@ -21,7 +21,9 @@ * \brief File that is entry point to call Dolibarr WebServices */ -if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); +if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", '1'); +} require '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP @@ -38,8 +40,7 @@ dol_syslog("Call Dolibarr webservices interfaces"); $langs->load("main"); // Enable and test if module web services is enabled -if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) -{ +if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) { $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; @@ -112,16 +113,16 @@ $server->wsdl->addComplexType( ); /*$server->wsdl->addComplexType( - 'LinesArray', - 'complexType', - 'array', - '', - 'SOAP-ENC:Array', - array(), - array( - array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:line[]') - ), - 'tns:line' + 'LinesArray', + 'complexType', + 'array', + '', + 'SOAP-ENC:Array', + array(), + array( + array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:line[]') + ), + 'tns:line' );*/ $server->wsdl->addComplexType( 'LinesArray2', @@ -176,16 +177,16 @@ $server->wsdl->addComplexType( ); /* $server->wsdl->addComplexType( - 'InvoicesArray', - 'complexType', - 'array', - '', - 'SOAP-ENC:Array', - array(), - array( - array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:invoice[]') - ), - 'tns:invoice' + 'InvoicesArray', + 'complexType', + 'array', + '', + 'SOAP-ENC:Array', + array(), + array( + array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:invoice[]') + ), + 'tns:invoice' );*/ $server->wsdl->addComplexType( 'InvoicesArray2', @@ -252,16 +253,16 @@ $server->register( 'WS to create an invoice' ); $server->register( - 'createInvoiceFromOrder', - // Entry values + 'createInvoiceFromOrder', + // Entry values array('authentication'=>'tns:authentication', 'id_order'=>'xsd:string', 'ref_order'=>'xsd:string', 'ref_ext_order'=>'xsd:string'), - // Exit values + // Exit values array('result'=>'tns:result', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'), - $ns, - $ns.'#createInvoiceFromOrder', - $styledoc, - $styleuse, - 'WS to create an invoice from an order' + $ns, + $ns.'#createInvoiceFromOrder', + $styledoc, + $styleuse, + 'WS to create an invoice from an order' ); $server->register( 'updateInvoice', @@ -292,7 +293,9 @@ function getInvoice($authentication, $id = '', $ref = '', $ref_ext = '') dol_syslog("Function: getInvoice login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -300,26 +303,21 @@ function getInvoice($authentication, $id = '', $ref = '', $ref_ext = '') $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) - { + if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->facture->lire) - { + if ($fuser->rights->facture->lire) { $invoice = new Facture($db); $result = $invoice->fetch($id, $ref, $ref_ext); - if ($result > 0) - { + if ($result > 0) { $linesresp = array(); $i = 0; - foreach ($invoice->lines as $line) - { + foreach ($invoice->lines as $line) { //var_dump($line); exit; $linesresp[] = array( 'id'=>$line->id, @@ -346,7 +344,7 @@ function getInvoice($authentication, $id = '', $ref = '', $ref_ext = '') 'result'=>array('result_code'=>'OK', 'result_label'=>''), 'invoice'=>array( 'id' => $invoice->id, - 'ref' => $invoice->ref, + 'ref' => $invoice->ref, 'ref_ext' => $invoice->ref_ext ? $invoice->ref_ext : '', // If not defined, field is not added into soap 'thirdparty_id' => $invoice->socid, 'fk_user_author' => $invoice->user_author ? $invoice->user_author : '', @@ -369,20 +367,17 @@ function getInvoice($authentication, $id = '', $ref = '', $ref_ext = '') 'payment_mode_id' => $invoice->mode_reglement_id ? $invoice->mode_reglement_id : '', 'lines' => $linesresp )); - } - else { + } else { $error++; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; } - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -403,7 +398,9 @@ function getInvoicesForThirdParty($authentication, $idthirdparty) dol_syslog("Function: getInvoicesForThirdParty login=".$authentication['login']." idthirdparty=".$idthirdparty); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -411,31 +408,31 @@ function getInvoicesForThirdParty($authentication, $idthirdparty) $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); - if ($fuser->socid) $socid = $fuser->socid; + if ($fuser->socid) { + $socid = $fuser->socid; + } // Check parameters - if (!$error && empty($idthirdparty)) - { + if (!$error && empty($idthirdparty)) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter idthirdparty is not provided'; } - if (!$error) - { + if (!$error) { $linesinvoice = array(); $sql = 'SELECT f.rowid as facid, ref as ref, ref_ext, type, fk_statut as status, total_ttc, total, tva'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f'; $sql .= " WHERE f.entity IN (".getEntity('invoice').")"; - if ($idthirdparty != 'all') $sql .= " AND f.fk_soc = ".$db->escape($idthirdparty); + if ($idthirdparty != 'all') { + $sql .= " AND f.fk_soc = ".$db->escape($idthirdparty); + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { // En attendant remplissage par boucle $obj = $db->fetch_object($resql); @@ -443,18 +440,15 @@ function getInvoicesForThirdParty($authentication, $idthirdparty) $invoice->fetch($obj->facid); // Sécurité pour utilisateur externe - if ($socid && ($socid != $invoice->socid)) - { + if ($socid && ($socid != $invoice->socid)) { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = $invoice->socid.' User does not have permission for this request'; } - if (!$error) - { + if (!$error) { // Define lines of invoice $linesresp = array(); - foreach ($invoice->lines as $line) - { + foreach ($invoice->lines as $line) { $linesresp[] = array( 'id'=>$line->id, 'type'=>$line->product_type, @@ -508,15 +502,13 @@ function getInvoicesForThirdParty($authentication, $idthirdparty) 'invoices'=>$linesinvoice ); - } - else { + } else { $error++; $errorcode = $db->lasterrno(); $errorlabel = $db->lasterror(); } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -539,7 +531,9 @@ function createInvoice($authentication, $invoice) dol_syslog("Function: createInvoice login=".$authentication['login']." id=".$invoice['id'].", ref=".$invoice['ref'].", ref_ext=".$invoice['ref_ext']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -552,8 +546,7 @@ function createInvoice($authentication, $invoice) $error++; $errorcode = 'KO'; $errorlabel = "Invoice id or ref or ref_ext is mandatory."; } - if (!$error) - { + if (!$error) { $new_invoice = new Facture($db); $new_invoice->socid = $invoice['thirdparty_id']; $new_invoice->type = $invoice['type']; @@ -571,16 +564,19 @@ function createInvoice($authentication, $invoice) if ($res > 0) { $new_invoice->mode_reglement_id = !empty($invoice['payment_mode_id']) ? $invoice['payment_mode_id'] : $soc->mode_reglement_id; $new_invoice->cond_reglement_id = $soc->cond_reglement_id; + } else { + $new_invoice->mode_reglement_id = $invoice['payment_mode_id']; } - else $new_invoice->mode_reglement_id = $invoice['payment_mode_id']; // Trick because nusoap does not store data with same structure if there is one or several lines $arrayoflines = array(); - if (isset($invoice['lines']['line'][0])) $arrayoflines = $invoice['lines']['line']; - else $arrayoflines = $invoice['lines']; + if (isset($invoice['lines']['line'][0])) { + $arrayoflines = $invoice['lines']['line']; + } else { + $arrayoflines = $invoice['lines']; + } - foreach ($arrayoflines as $line) - { + foreach ($arrayoflines as $line) { // $key can be 'line' or '0','1',... $newline = new FactureLigne($db); $newline->product_type = $line['type']; @@ -603,27 +599,22 @@ function createInvoice($authentication, $invoice) $db->begin(); $result = $new_invoice->create($fuser, 0, dol_stringtotime($invoice['date_due'], 'dayrfc')); - if ($result < 0) - { + if ($result < 0) { $error++; } - if (!$error && $invoice['status'] == Facture::STATUS_VALIDATED) // We want invoice to have status validated - { + if (!$error && $invoice['status'] == Facture::STATUS_VALIDATED) { // We want invoice to have status validated $result = $new_invoice->validate($fuser); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error) - { + if (!$error) { $db->commit(); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$new_invoice->id, 'ref'=>$new_invoice->ref, 'ref_ext'=>$new_invoice->ref_ext); - } - else { + } else { $db->rollback(); $error++; $errorcode = 'KO'; @@ -632,8 +623,7 @@ function createInvoice($authentication, $invoice) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -655,14 +645,18 @@ function createInvoiceFromOrder($authentication, $id_order = '', $ref_order = '' dol_syslog("Function: createInvoiceFromOrder login=".$authentication['login']." id=".$id_order.", ref=".$ref_order.", ref_ext=".$ref_ext_order); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); $errorcode = ''; $errorlabel = ''; $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); - if ($fuser->socid) $socid = $fuser->socid; + if ($fuser->socid) { + $socid = $fuser->socid; + } // Check parameters if (empty($id_order) && empty($ref_order) && empty($ref_ext_order)) { @@ -670,51 +664,41 @@ function createInvoiceFromOrder($authentication, $id_order = '', $ref_order = '' } ////////////////////// - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->commande->lire) - { + if ($fuser->rights->commande->lire) { $order = new Commande($db); $result = $order->fetch($id_order, $ref_order, $ref_ext_order); - if ($result > 0) - { + if ($result > 0) { // Security for external user - if ($socid && ($socid != $order->socid)) - { + if ($socid && ($socid != $order->socid)) { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = $order->socid.'User does not have permission for this request'; } - if (!$error) - { + if (!$error) { $newobject = new Facture($db); $result = $newobject->createFromOrder($order, $fuser); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog("Webservice server_invoice:: invoice creation from order failed", LOG_ERR); } } - } - else { + } else { $error++; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id_order.' nor ref='.$ref_order.' nor ref_ext='.$ref_ext_order; } - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); - } - else { + } else { $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref, 'ref_ext'=>$newobject->ref_ext); } @@ -735,7 +719,9 @@ function updateInvoice($authentication, $invoice) dol_syslog("Function: updateInvoice login=".$authentication['login']." id=".$invoice['id']. ", ref=".$invoice['ref'].", ref_ext=".$invoice['ref_ext']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -748,8 +734,7 @@ function updateInvoice($authentication, $invoice) $error++; $errorcode = 'KO'; $errorlabel = "Invoice id or ref or ref_ext is mandatory."; } - if (!$error) - { + if (!$error) { $objectfound = false; $object = new Facture($db); @@ -760,18 +745,14 @@ function updateInvoice($authentication, $invoice) $db->begin(); - if (isset($invoice['status'])) - { - if ($invoice['status'] == Facture::STATUS_DRAFT) - { + if (isset($invoice['status'])) { + if ($invoice['status'] == Facture::STATUS_DRAFT) { $result = $object->setDraft($fuser); } - if ($invoice['status'] == Facture::STATUS_VALIDATED) - { + if ($invoice['status'] == Facture::STATUS_VALIDATED) { $result = $object->validate($fuser); - if ($result >= 0) - { + if ($result >= 0) { // Define output language $outputlangs = $langs; $object->generateDocument($object->model_pdf, $outputlangs); @@ -806,8 +787,7 @@ function updateInvoice($authentication, $invoice) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } diff --git a/htdocs/webservices/server_order.php b/htdocs/webservices/server_order.php index 8c278768990..8f3d5af17e6 100644 --- a/htdocs/webservices/server_order.php +++ b/htdocs/webservices/server_order.php @@ -22,7 +22,9 @@ * \brief File that is entry point to call Dolibarr WebServices */ -if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); +if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", '1'); +} require '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP @@ -36,8 +38,7 @@ dol_syslog("Call Dolibarr webservices interfaces"); $langs->load("main"); // Enable and test if module web services is enabled -if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) -{ +if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) { $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; @@ -56,12 +57,12 @@ $server->wsdl->schemaTargetNamespace = $ns; // Define WSDL Authentication object $server->wsdl->addComplexType( - 'authentication', - 'complexType', - 'struct', - 'all', - '', - array( + 'authentication', + 'complexType', + 'struct', + 'all', + '', + array( 'dolibarrkey' => array('name'=>'dolibarrkey', 'type'=>'xsd:string'), 'sourceapplication' => array('name'=>'sourceapplication', 'type'=>'xsd:string'), 'login' => array('name'=>'login', 'type'=>'xsd:string'), @@ -71,12 +72,12 @@ $server->wsdl->addComplexType( ); // Define WSDL Return object $server->wsdl->addComplexType( - 'result', - 'complexType', - 'struct', - 'all', - '', - array( + 'result', + 'complexType', + 'struct', + 'all', + '', + array( 'result_code' => array('name'=>'result_code', 'type'=>'xsd:string'), 'result_label' => array('name'=>'result_label', 'type'=>'xsd:string'), ) @@ -120,27 +121,30 @@ $extrafield_line_array = null; if (is_array($extrafields) && count($extrafields) > 0) { $extrafield_line_array = array(); } -if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) -{ - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { +if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { //$value=$object->array_options["options_".$key]; $type = $extrafields->attributes[$elementtype]['type'][$key]; - if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } - else {$type = 'xsd:string'; } + if ($type == 'date' || $type == 'datetime') { + $type = 'xsd:dateTime'; + } else { + $type = 'xsd:string'; + } $extrafield_line_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type); } } -if (is_array($extrafield_line_array)) $line_fields = array_merge($line_fields, $extrafield_line_array); +if (is_array($extrafield_line_array)) { + $line_fields = array_merge($line_fields, $extrafield_line_array); +} // Define other specific objects $server->wsdl->addComplexType( - 'line', - 'complexType', - 'struct', - 'all', - '', - $line_fields + 'line', + 'complexType', + 'struct', + 'all', + '', + $line_fields ); /*$server->wsdl->addComplexType( @@ -159,12 +163,12 @@ $server->wsdl->addComplexType( 'tns:line' );*/ $server->wsdl->addComplexType( - 'LinesArray2', - 'complexType', - 'array', - 'sequence', - '', - array( + 'LinesArray2', + 'complexType', + 'array', + 'sequence', + '', + array( 'line' => array( 'name' => 'line', 'type' => 'tns:line', @@ -224,26 +228,29 @@ $extrafield_array = null; if (is_array($extrafields) && count($extrafields) > 0) { $extrafield_array = array(); } -if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) -{ - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { +if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { //$value=$object->array_options["options_".$key]; $type = $extrafields->attributes[$elementtype]['type'][$key]; - if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } - else {$type = 'xsd:string'; } + if ($type == 'date' || $type == 'datetime') { + $type = 'xsd:dateTime'; + } else { + $type = 'xsd:string'; + } $extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type); } } -if (is_array($extrafield_array)) $order_fields = array_merge($order_fields, $extrafield_array); +if (is_array($extrafield_array)) { + $order_fields = array_merge($order_fields, $extrafield_array); +} $server->wsdl->addComplexType( - 'order', - 'complexType', - 'struct', - 'all', - '', - $order_fields + 'order', + 'complexType', + 'struct', + 'all', + '', + $order_fields ); /* @@ -263,12 +270,12 @@ $server->wsdl->addComplexType( 'tns:order' );*/ $server->wsdl->addComplexType( - 'OrdersArray2', - 'complexType', - 'array', - 'sequence', - '', - array( + 'OrdersArray2', + 'complexType', + 'array', + 'sequence', + '', + array( 'order' => array( 'name' => 'order', 'type' => 'tns:order', @@ -289,58 +296,58 @@ $styleuse = 'encoded'; // encoded/literal/literal wrapped // Register WSDL $server->register( - 'getOrder', - array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'), // Entry values - array('result'=>'tns:result', 'order'=>'tns:order'), // Exit values - $ns, - $ns.'#getOrder', - $styledoc, - $styleuse, - 'WS to get a particular invoice' + 'getOrder', + array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'), // Entry values + array('result'=>'tns:result', 'order'=>'tns:order'), // Exit values + $ns, + $ns.'#getOrder', + $styledoc, + $styleuse, + 'WS to get a particular invoice' ); $server->register( - 'getOrdersForThirdParty', - array('authentication'=>'tns:authentication', 'idthirdparty'=>'xsd:string'), // Entry values - array('result'=>'tns:result', 'orders'=>'tns:OrdersArray2'), // Exit values - $ns, - $ns.'#getOrdersForThirdParty', - $styledoc, - $styleuse, - 'WS to get all orders of a third party' + 'getOrdersForThirdParty', + array('authentication'=>'tns:authentication', 'idthirdparty'=>'xsd:string'), // Entry values + array('result'=>'tns:result', 'orders'=>'tns:OrdersArray2'), // Exit values + $ns, + $ns.'#getOrdersForThirdParty', + $styledoc, + $styleuse, + 'WS to get all orders of a third party' ); $server->register( - 'createOrder', - array('authentication'=>'tns:authentication', 'order'=>'tns:order'), // Entry values - array('result'=>'tns:result', 'id'=>'xsd:string', 'ref'=>'xsd:string'), // Exit values - $ns, - $ns.'#createOrder', - $styledoc, - $styleuse, - 'WS to create an order' + 'createOrder', + array('authentication'=>'tns:authentication', 'order'=>'tns:order'), // Entry values + array('result'=>'tns:result', 'id'=>'xsd:string', 'ref'=>'xsd:string'), // Exit values + $ns, + $ns.'#createOrder', + $styledoc, + $styleuse, + 'WS to create an order' ); $server->register( - 'updateOrder', - array('authentication'=>'tns:authentication', 'order'=>'tns:order'), // Entry values - array('result'=>'tns:result', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'), // Exit values - $ns, - $ns.'#updateOrder', - $styledoc, - $styleuse, - 'WS to update an order' + 'updateOrder', + array('authentication'=>'tns:authentication', 'order'=>'tns:order'), // Entry values + array('result'=>'tns:result', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'), // Exit values + $ns, + $ns.'#updateOrder', + $styledoc, + $styleuse, + 'WS to update an order' ); $server->register( - 'validOrder', - array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'id_warehouse'=>'xsd:string'), // Entry values - array('result'=>'tns:result'), // Exit values - $ns, - $ns.'#validOrder', - $styledoc, - $styleuse, - 'WS to valid an order' + 'validOrder', + array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'id_warehouse'=>'xsd:string'), // Entry values + array('result'=>'tns:result'), // Exit values + $ns, + $ns.'#validOrder', + $styledoc, + $styleuse, + 'WS to valid an order' ); /** @@ -358,7 +365,9 @@ function getOrder($authentication, $id = '', $ref = '', $ref_ext = '') dol_syslog("Function: getOrder login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -368,38 +377,33 @@ function getOrder($authentication, $id = '', $ref = '', $ref_ext = '') $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); - if ($fuser->socid) $socid = $fuser->socid; + if ($fuser->socid) { + $socid = $fuser->socid; + } // Check parameters - if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) - { + if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->commande->lire) - { + if ($fuser->rights->commande->lire) { $order = new Commande($db); $result = $order->fetch($id, $ref, $ref_ext); - if ($result > 0) - { + if ($result > 0) { // Security for external user - if ($socid && $socid != $order->socid) - { + if ($socid && $socid != $order->socid) { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } - if (!$error) - { + if (!$error) { $linesresp = array(); $i = 0; - foreach ($order->lines as $line) - { + foreach ($order->lines as $line) { //var_dump($line); exit; $linesresp[] = array( 'id'=>$line->rowid, @@ -473,22 +477,19 @@ function getOrder($authentication, $id = '', $ref = '', $ref_ext = '') 'lines' => $linesresp )); } - } - else { + } else { $error++; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; } - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -509,7 +510,9 @@ function getOrdersForThirdParty($authentication, $idthirdparty) dol_syslog("Function: getOrdersForThirdParty login=".$authentication['login']." idthirdparty=".$idthirdparty); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -517,32 +520,32 @@ function getOrdersForThirdParty($authentication, $idthirdparty) $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); - if ($fuser->socid) $socid = $fuser->socid; + if ($fuser->socid) { + $socid = $fuser->socid; + } // Check parameters - if (!$error && empty($idthirdparty)) - { + if (!$error && empty($idthirdparty)) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter id is not provided'; } - if (!$error) - { + if (!$error) { $linesorders = array(); $sql = 'SELECT c.rowid as orderid'; $sql .= ' FROM '.MAIN_DB_PREFIX.'commande as c'; $sql .= " WHERE c.entity = ".$conf->entity; - if ($idthirdparty != 'all') $sql .= " AND c.fk_soc = ".$db->escape($idthirdparty); + if ($idthirdparty != 'all') { + $sql .= " AND c.fk_soc = ".$db->escape($idthirdparty); + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { // En attendant remplissage par boucle $obj = $db->fetch_object($resql); @@ -550,19 +553,16 @@ function getOrdersForThirdParty($authentication, $idthirdparty) $order->fetch($obj->orderid); // Sécurité pour utilisateur externe - if ($socid && ($socid != $order->socid)) - { + if ($socid && ($socid != $order->socid)) { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = $order->socid.' User does not have permission for this request'; } - if (!$error) - { + if (!$error) { // Define lines of invoice $linesresp = array(); - foreach ($order->lines as $line) - { + foreach ($order->lines as $line) { $linesresp[] = array( 'id'=>$line->rowid, 'type'=>$line->product_type, @@ -638,15 +638,13 @@ function getOrdersForThirdParty($authentication, $idthirdparty) 'orders'=>$linesorders ); - } - else { + } else { $error++; $errorcode = $db->lasterrno(); $errorlabel = $db->lasterror(); } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -671,7 +669,9 @@ function createOrder($authentication, $order) dol_syslog("Function: createOrder login=".$authentication['login']." socid :".$order['socid']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -683,8 +683,7 @@ function createOrder($authentication, $order) // Check parameters - if (!$error) - { + if (!$error) { $newobject = new Commande($db); $newobject->socid = $order['thirdparty_id']; $newobject->type = $order['type']; @@ -706,10 +705,8 @@ function createOrder($authentication, $order) // fetch optionals attributes and labels $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($elementtype, true); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $key = 'options_'.$key; $newobject->array_options[$key] = $order[$key]; } @@ -717,11 +714,13 @@ function createOrder($authentication, $order) // Trick because nusoap does not store data with same structure if there is one or several lines $arrayoflines = array(); - if (isset($order['lines']['line'][0])) $arrayoflines = $order['lines']['line']; - else $arrayoflines = $order['lines']; + if (isset($order['lines']['line'][0])) { + $arrayoflines = $order['lines']['line']; + } else { + $arrayoflines = $order['lines']; + } - foreach ($arrayoflines as $key => $line) - { + foreach ($arrayoflines as $key => $line) { // $key can be 'line' or '0','1',... $newline = new OrderLine($db); @@ -744,10 +743,8 @@ function createOrder($authentication, $order) // fetch optionals attributes and labels $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($elementtype, true); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $key = 'options_'.$key; $newline->array_options[$key] = $line[$key]; } @@ -761,30 +758,25 @@ function createOrder($authentication, $order) dol_syslog("Webservice server_order:: order creation start", LOG_DEBUG); $result = $newobject->create($fuser); dol_syslog('Webservice server_order:: order creation done with $result='.$result, LOG_DEBUG); - if ($result < 0) - { + if ($result < 0) { dol_syslog("Webservice server_order:: order creation failed", LOG_ERR); $error++; } - if ($order['status'] == 1) // We want order to have status validated - { + if ($order['status'] == 1) { // We want order to have status validated dol_syslog("Webservice server_order:: order validation start", LOG_DEBUG); $result = $newobject->valid($fuser); - if ($result < 0) - { + if ($result < 0) { dol_syslog("Webservice server_order:: order validation failed", LOG_ERR); $error++; } } - if ($result >= 0) - { + if ($result >= 0) { dol_syslog("Webservice server_order:: order creation & validation succeeded, commit", LOG_DEBUG); $db->commit(); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref); - } - else { + } else { dol_syslog("Webservice server_order:: order creation or validation failed, rollback", LOG_ERR); $db->rollback(); $error++; @@ -793,8 +785,7 @@ function createOrder($authentication, $order) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -821,45 +812,40 @@ function validOrder($authentication, $id = '', $id_warehouse = 0) $errorcode = ''; $errorlabel = ''; $error = 0; - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->commande->lire) - { + if ($fuser->rights->commande->lire) { $order = new Commande($db); $result = $order->fetch($id); $order->fetch_thirdparty(); $db->begin(); - if ($result > 0) - { + if ($result > 0) { $result = $order->valid($fuser, $id_warehouse); - if ($result >= 0) - { + if ($result >= 0) { // Define output language $outputlangs = $langs; $order->generateDocument($order->model_pdf, $outputlangs); - } - else { + } else { $db->rollback(); $error++; $errorcode = 'KO'; $errorlabel = $order->error; } - } - else { + } else { $db->rollback(); $error++; $errorcode = 'KO'; $errorlabel = $order->error; } - } - else { + } else { $db->rollback(); $error++; $errorcode = 'KO'; @@ -867,11 +853,9 @@ function validOrder($authentication, $id = '', $id_warehouse = 0) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); - } - else { + } else { $db->commit(); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>'')); } @@ -892,7 +876,9 @@ function updateOrder($authentication, $order) dol_syslog("Function: updateOrder login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -904,8 +890,7 @@ function updateOrder($authentication, $order) $error++; $errorcode = 'KO'; $errorlabel = "Order id or ref or ref_ext is mandatory."; } - if (!$error) - { + if (!$error) { $objectfound = false; include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -918,27 +903,33 @@ function updateOrder($authentication, $order) $db->begin(); - if (isset($order['status'])) - { - if ($order['status'] == -1) $result = $object->cancel($fuser); - if ($order['status'] == 1) - { + if (isset($order['status'])) { + if ($order['status'] == -1) { + $result = $object->cancel($fuser); + } + if ($order['status'] == 1) { $result = $object->valid($fuser); - if ($result >= 0) - { + if ($result >= 0) { // Define output language $outputlangs = $langs; $object->generateDocument($order->model_pdf, $outputlangs); } } - if ($order['status'] == 0) $result = $object->set_reopen($fuser); - if ($order['status'] == 3) $result = $object->cloture($fuser); + if ($order['status'] == 0) { + $result = $object->set_reopen($fuser); + } + if ($order['status'] == 3) { + $result = $object->cloture($fuser); + } } - if (isset($order['billed'])) - { - if ($order['billed']) $result = $object->classifyBilled($fuser); - if (!$order['billed']) $result = $object->classifyUnBilled($fuser); + if (isset($order['billed'])) { + if ($order['billed']) { + $result = $object->classifyBilled($fuser); + } + if (!$order['billed']) { + $result = $object->classifyUnBilled($fuser); + } } $elementtype = 'commande'; @@ -947,13 +938,10 @@ function updateOrder($authentication, $order) // fetch optionals attributes and labels $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($elementtype, true); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $key = 'options_'.$key; - if (isset($order[$key])) - { + if (isset($order[$key])) { $result = $object->setValueFrom($key, $order[$key], 'commande_extrafields'); } } @@ -964,8 +952,7 @@ function updateOrder($authentication, $order) } } - if ((!$error) && ($objectfound)) - { + if ((!$error) && ($objectfound)) { $db->commit(); $objectresp = array( 'result'=>array('result_code'=>'OK', 'result_label'=>''), @@ -973,9 +960,7 @@ function updateOrder($authentication, $order) 'ref'=>$object->ref, 'ref_ext'=>$object->ref_ext ); - } - elseif ($objectfound) - { + } elseif ($objectfound) { $db->rollback(); $error++; $errorcode = 'KO'; @@ -987,8 +972,7 @@ function updateOrder($authentication, $order) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } diff --git a/htdocs/webservices/server_other.php b/htdocs/webservices/server_other.php index 3494f928cde..ae1a480710f 100644 --- a/htdocs/webservices/server_other.php +++ b/htdocs/webservices/server_other.php @@ -20,7 +20,9 @@ * \brief File that is entry point to call Dolibarr WebServices */ -if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); +if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", '1'); +} require '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP @@ -35,8 +37,7 @@ dol_syslog("Call Dolibarr webservices interfaces"); $langs->load("main"); // Enable and test if module web services is enabled -if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) -{ +if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) { $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; @@ -149,7 +150,9 @@ function getVersions($authentication) dol_syslog("Function: getVersions login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -159,8 +162,7 @@ function getVersions($authentication) // Check parameters - if (!$error) - { + if (!$error) { $objectresp['result'] = array('result_code'=>'OK', 'result_label'=>''); $objectresp['dolibarr'] = version_dolibarr(); $objectresp['os'] = version_os(); @@ -168,8 +170,7 @@ function getVersions($authentication) $objectresp['webserver'] = version_webserver(); } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -192,7 +193,9 @@ function getDocument($authentication, $modulepart, $file, $refname = '') dol_syslog("Function: getDocument login=".$authentication['login'].' - modulepart='.$modulepart.' - file='.$file); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } $objectresp = array(); $errorcode = ''; $errorlabel = ''; @@ -208,24 +211,26 @@ function getDocument($authentication, $modulepart, $file, $refname = '') $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); - if ($fuser->socid) $socid = $fuser->socid; + if ($fuser->socid) { + $socid = $fuser->socid; + } // Check parameters - if (!$error && (!$file || !$modulepart)) - { + if (!$error && (!$file || !$modulepart)) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter file and modulepart must be both provided."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); // Suppression de la chaine de caractere ../ dans $original_file $original_file = str_replace("../", "/", $original_file); // find the subdirectory name as the reference - if (empty($refname)) $refname = basename(dirname($original_file)."/"); + if (empty($refname)) { + $refname = basename(dirname($original_file)."/"); + } // Security check $check_access = dol_check_secure_access_document($modulepart, $original_file, $conf->entity, $fuser, $refname); @@ -234,20 +239,15 @@ function getDocument($authentication, $modulepart, $file, $refname = '') $original_file = $check_access['original_file']; // Basic protection (against external users only) - if ($fuser->socid > 0) - { - if ($sqlprotectagainstexternals) - { + if ($fuser->socid > 0) { + if ($sqlprotectagainstexternals) { $resql = $db->query($sqlprotectagainstexternals); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($fuser->socid != $obj->fk_soc) - { + if ($fuser->socid != $obj->fk_soc) { $accessallowed = 0; break; } @@ -259,8 +259,7 @@ function getDocument($authentication, $modulepart, $file, $refname = '') // Security: // Limite acces si droits non corrects - if (!$accessallowed) - { + if (!$accessallowed) { $errorcode = 'NOT_PERMITTED'; $errorlabel = 'Access not allowed'; $error++; @@ -269,8 +268,7 @@ function getDocument($authentication, $modulepart, $file, $refname = '') // Security: // On interdit les remontees de repertoire ainsi que les pipe dans // les noms de fichiers. - if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) - { + if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) { dol_syslog("Refused to deliver file ".$original_file); $errorcode = 'REFUSED'; $errorlabel = ''; @@ -279,10 +277,8 @@ function getDocument($authentication, $modulepart, $file, $refname = '') clearstatcache(); - if (!$error) - { - if (file_exists($original_file)) - { + if (!$error) { + if (file_exists($original_file)) { dol_syslog("Function: getDocument $original_file content-type=$type"); $f = fopen($original_file, 'r'); @@ -300,8 +296,7 @@ function getDocument($authentication, $modulepart, $file, $refname = '') 'result'=>array('result_code'=>'OK', 'result_label'=>''), 'document'=>$objectret ); - } - else { + } else { dol_syslog("File doesn't exist ".$original_file); $errorcode = 'NOT_FOUND'; $errorlabel = ''; @@ -310,8 +305,7 @@ function getDocument($authentication, $modulepart, $file, $refname = '') } } - if ($error) - { + if ($error) { $objectresp = array( 'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel) ); diff --git a/htdocs/webservices/server_payment.php b/htdocs/webservices/server_payment.php index 3fd3868a36a..6bf43bf78f6 100644 --- a/htdocs/webservices/server_payment.php +++ b/htdocs/webservices/server_payment.php @@ -42,8 +42,7 @@ dol_syslog("Call Dolibarr webservices interfaces"); $langs->load("main"); // Enable and test if module web services is enabled -if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) -{ +if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) { $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); @@ -147,7 +146,9 @@ function createPayment($authentication, $payment) dol_syslog("Function: createPayment login=".$authentication['login']." id=".$payment->id. ", ref=".$payment->ref.", ref_ext=".$payment->ref_ext); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -163,8 +164,7 @@ function createPayment($authentication, $payment) $errorlabel = "You must specify the amount and the third party's ID."; } - if (!$error) - { + if (!$error) { $soc = new Societe($db); $soc->fetch($payment['thirdparty_id']); @@ -188,17 +188,14 @@ function createPayment($authentication, $payment) $new_payment->addPaymentToBank($fuser, 'payment', $payment['int_label'], $payment['bank_account'], $payment['emitter'], $payment['bank_source']); } - if ($result < 0) - { + if ($result < 0) { $error++; } - if (!$error) - { + if (!$error) { $db->commit(); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$new_payment->id); - } - else { + } else { $db->rollback(); $error++; $errorcode = 'KO'; @@ -207,8 +204,7 @@ function createPayment($authentication, $payment) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } diff --git a/htdocs/webservices/server_productorservice.php b/htdocs/webservices/server_productorservice.php index 3b2110b9602..259f3ec67fe 100644 --- a/htdocs/webservices/server_productorservice.php +++ b/htdocs/webservices/server_productorservice.php @@ -712,7 +712,9 @@ function updateProductOrService($authentication, $product) $newobject->seuil_stock_alerte = isset($product['stock_alert']) ? $product['stock_alert'] : null; $newobject->country_id = isset($product['country_id']) ? $product['country_id'] : 0; - if (!empty($product['country_code'])) $newobject->country_id = getCountry($product['country_code'], 3); + if (!empty($product['country_code'])) { + $newobject->country_id = getCountry($product['country_code'], 3); + } $newobject->customcode = isset($product['customcode']) ? $product['customcode'] : ''; $newobject->canvas = isset($product['canvas']) ? $product['canvas'] : ''; diff --git a/htdocs/webservices/server_project.php b/htdocs/webservices/server_project.php index 8d76786df71..b64ccc94d59 100644 --- a/htdocs/webservices/server_project.php +++ b/htdocs/webservices/server_project.php @@ -21,7 +21,9 @@ * \brief File that is entry point to call Dolibarr WebServices */ -if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); +if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", '1'); +} require '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP @@ -37,8 +39,7 @@ dol_syslog("Call Dolibarr webservices interfaces"); $langs->load("main"); // Enable and test if module web services is enabled -if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) -{ +if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) { $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; @@ -131,8 +132,7 @@ $server->wsdl->addComplexType( ); $project_elements = array(); -foreach ($listofreferent as $key => $label) -{ +foreach ($listofreferent as $key => $label) { $project_elements[$key] = array('name'=>$key, 'type'=>'tns:elementsArray'); } $server->wsdl->addComplexType( @@ -169,18 +169,21 @@ $extrafield_array = null; if (is_array($extrafields) && count($extrafields) > 0) { $extrafield_array = array(); } -if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) -{ - foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label) - { +if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { //$value=$object->array_options["options_".$key]; $type = $extrafields->attributes[$elementtype]['type'][$key]; - if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } - else {$type = 'xsd:string'; } + if ($type == 'date' || $type == 'datetime') { + $type = 'xsd:dateTime'; + } else { + $type = 'xsd:string'; + } $extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type); } } -if (is_array($extrafield_array)) $project_fields = array_merge($project_fields, $extrafield_array); +if (is_array($extrafield_array)) { + $project_fields = array_merge($project_fields, $extrafield_array); +} $server->wsdl->addComplexType( 'project', @@ -240,7 +243,9 @@ function createProject($authentication, $project) dol_syslog("Function: createProject login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -248,18 +253,15 @@ function createProject($authentication, $project) $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (empty($project['ref'])) - { + if (empty($project['ref'])) { $error++; $errorcode = 'KO'; $errorlabel = "Name is mandatory."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->projet->creer) - { + if ($fuser->rights->projet->creer) { $newobject = new Project($db); $newobject->ref = $project['ref']; $newobject->title = $project['label']; @@ -277,10 +279,8 @@ function createProject($authentication, $project) // fetch optionals attributes and labels $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($elementtype, true); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $key = 'options_'.$key; $newobject->array_options[$key] = $project[$key]; } @@ -289,39 +289,32 @@ function createProject($authentication, $project) $db->begin(); $result = $newobject->create($fuser); - if (!$error && $result > 0) - { + if (!$error && $result > 0) { // Add myself as project leader $result = $newobject->add_contact($fuser->id, 'PROJECTLEADER', 'internal'); - if ($result < 0) - { + if ($result < 0) { $error++; } - } - else { + } else { $error++; } - if (!$error) - { + if (!$error) { $db->commit(); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref); - } - else { + } else { $db->rollback(); $error++; $errorcode = 'KO'; $errorlabel = $newobject->error; } - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -342,7 +335,9 @@ function getProject($authentication, $id = '', $ref = '') dol_syslog("Function: getProject login=".$authentication['login']." id=".$id." ref=".$ref); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -350,22 +345,18 @@ function getProject($authentication, $id = '', $ref = '') $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (!$error && (($id && $ref))) - { + if (!$error && (($id && $ref))) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref can't be both provided. You must choose one or other but not both."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->projet->lire) - { + if ($fuser->rights->projet->lire) { $project = new Project($db); $result = $project->fetch($id, $ref); - if ($result > 0) - { + if ($result > 0) { $project_result_fields = array( 'id' => $project->id, 'ref' => $project->ref, @@ -386,11 +377,9 @@ function getProject($authentication, $id = '', $ref = '') $extrafields->fetch_name_optionals_label($elementtype, true); //Get extrafield values - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { $project->fetch_optionals(); - foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) - { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $project_result_fields = array_merge($project_result_fields, array('options_'.$key => $project->array_options['options_'.$key])); } } @@ -398,14 +387,11 @@ function getProject($authentication, $id = '', $ref = '') //Get linked elements global $listofreferent; $elements = array(); - foreach ($listofreferent as $key => $tablename) - { + foreach ($listofreferent as $key => $tablename) { $elements[$key] = array(); $element_array = $project->get_element_list($key, $tablename); - if (count($element_array) > 0 && is_array($element_array)) - { - foreach ($element_array as $element) - { + if (count($element_array) > 0 && is_array($element_array)) { + foreach ($element_array as $element) { $tmp = explode('_', $element); $idofelement = count($tmp) > 0 ? $tmp[0] : ""; $idofelementuser = count($tmp) > 1 ? $tmp[1] : ""; @@ -420,20 +406,17 @@ function getProject($authentication, $id = '', $ref = '') 'result'=>array('result_code'=>'OK', 'result_label'=>''), 'project'=>$project_result_fields ); - } - else { + } else { $error++; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref; } - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } diff --git a/htdocs/webservices/server_supplier_invoice.php b/htdocs/webservices/server_supplier_invoice.php index 507095ac78b..122d4b10694 100644 --- a/htdocs/webservices/server_supplier_invoice.php +++ b/htdocs/webservices/server_supplier_invoice.php @@ -20,7 +20,9 @@ * \brief File that is entry point to call Dolibarr WebServices */ -if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); +if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", '1'); +} require '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP @@ -34,8 +36,7 @@ dol_syslog("Call Dolibarr webservices interfaces"); $langs->load("main"); // Enable and test if module web services is enabled -if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) -{ +if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) { $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; @@ -229,7 +230,9 @@ function getSupplierInvoice($authentication, $id = '', $ref = '', $ref_ext = '') dol_syslog("Function: getSupplierInvoice login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -237,26 +240,21 @@ function getSupplierInvoice($authentication, $id = '', $ref = '', $ref_ext = '') $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) - { + if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->fournisseur->facture->lire) - { + if ($fuser->rights->fournisseur->facture->lire) { $invoice = new FactureFournisseur($db); $result = $invoice->fetch($id, $ref, $ref_ext); - if ($result > 0) - { + if ($result > 0) { $linesresp = array(); $i = 0; - foreach ($invoice->lines as $line) - { + foreach ($invoice->lines as $line) { //var_dump($line); exit; $linesresp[] = array( 'id'=>$line->rowid, @@ -275,7 +273,7 @@ function getSupplierInvoice($authentication, $id = '', $ref = '', $ref_ext = '') 'result'=>array('result_code'=>'OK', 'result_label'=>''), 'invoice'=>array( 'id' => $invoice->id, - 'ref' => $invoice->ref, + 'ref' => $invoice->ref, 'ref_supplier'=>$invoice->ref_supplier, 'ref_ext' => $invoice->ref_ext, 'fk_user_author' => $invoice->fk_user_author, @@ -302,20 +300,17 @@ function getSupplierInvoice($authentication, $id = '', $ref = '', $ref_ext = '') // '1'=>array('id'=>333,'type'=>1)), )); - } - else { + } else { $error++; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; } - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -337,7 +332,9 @@ function getSupplierInvoicesForThirdParty($authentication, $idthirdparty) dol_syslog("Function: getSupplierInvoicesForThirdParty login=".$authentication['login']." idthirdparty=".$idthirdparty); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -346,14 +343,12 @@ function getSupplierInvoicesForThirdParty($authentication, $idthirdparty) $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (!$error && empty($idthirdparty)) - { + if (!$error && empty($idthirdparty)) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter id is not provided'; } - if (!$error) - { + if (!$error) { $linesinvoice = array(); $sql .= 'SELECT f.rowid as facid'; @@ -363,22 +358,21 @@ function getSupplierInvoicesForThirdParty($authentication, $idthirdparty) //$sql.=" WHERE f.fk_soc = s.rowid AND nom = '".$db->escape($idthirdparty)."'"; //$sql.=" WHERE f.fk_soc = s.rowid AND nom = '".$db->escape($idthirdparty)."'"; $sql .= " WHERE f.entity = ".$conf->entity; - if ($idthirdparty != 'all') $sql .= " AND f.fk_soc = ".$db->escape($idthirdparty); + if ($idthirdparty != 'all') { + $sql .= " AND f.fk_soc = ".$db->escape($idthirdparty); + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { // En attendant remplissage par boucle $obj = $db->fetch_object($resql); $invoice = new FactureFournisseur($db); $result = $invoice->fetch($obj->facid); - if ($result < 0) - { + if ($result < 0) { $error++; $errorcode = $result; $errorlabel = $invoice->error; break; @@ -386,9 +380,8 @@ function getSupplierInvoicesForThirdParty($authentication, $idthirdparty) // Define lines of invoice $linesresp = array(); - foreach ($invoice->lines as $line) - { - $linesresp[] = array( + foreach ($invoice->lines as $line) { + $linesresp[] = array( 'id'=>$line->rowid, 'type'=>$line->product_type, 'desc'=>dol_htmlcleanlastbr($line->description), @@ -397,10 +390,10 @@ function getSupplierInvoicesForThirdParty($authentication, $idthirdparty) 'total'=>$line->total_ttc, 'vat_rate'=>$line->tva_tx, 'qty'=>$line->qty, - 'product_ref'=>$line->product_ref, + 'product_ref'=>$line->product_ref, 'product_label'=>$line->product_label, 'product_desc'=>$line->product_desc, - ); + ); } // Now define invoice @@ -439,15 +432,13 @@ function getSupplierInvoicesForThirdParty($authentication, $idthirdparty) 'invoices'=>$linesinvoice ); - } - else { + } else { $error++; $errorcode = $db->lasterrno(); $errorlabel = $db->lasterror(); } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } diff --git a/htdocs/webservices/server_thirdparty.php b/htdocs/webservices/server_thirdparty.php index d7ded82cc3f..60b28ad06d0 100644 --- a/htdocs/webservices/server_thirdparty.php +++ b/htdocs/webservices/server_thirdparty.php @@ -20,7 +20,9 @@ * \brief File that is entry point to call Dolibarr WebServices */ -if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); +if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", '1'); +} require_once '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP @@ -36,8 +38,7 @@ dol_syslog("Call Dolibarr webservices interfaces"); $langs->load("main"); // Enable and test if module web services is enabled -if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) -{ +if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) { $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; @@ -130,20 +131,23 @@ $extrafield_array = null; if (is_array($extrafields) && count($extrafields) > 0) { $extrafield_array = array(); } -if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) -{ - foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) - { +if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { //$value=$object->array_options["options_".$key]; $type = $extrafields->attributes[$elementtype]['type'][$key]; - if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } - else {$type = 'xsd:string'; } + if ($type == 'date' || $type == 'datetime') { + $type = 'xsd:dateTime'; + } else { + $type = 'xsd:string'; + } $extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type); } } -if (is_array($extrafield_array)) $thirdparty_fields = array_merge($thirdparty_fields, $extrafield_array); +if (is_array($extrafield_array)) { + $thirdparty_fields = array_merge($thirdparty_fields, $extrafield_array); +} // Define other specific objects $server->wsdl->addComplexType( @@ -265,16 +269,16 @@ $server->register( // Register WSDL $server->register( - 'deleteThirdParty', - // Entry values + 'deleteThirdParty', + // Entry values array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'), - // Exit values + // Exit values array('result'=>'tns:result', 'id'=>'xsd:string'), - $ns, - $ns.'#deleteThirdParty', - $styledoc, - $styleuse, - 'WS to delete a thirdparty from its id, ref or ref_ext' + $ns, + $ns.'#deleteThirdParty', + $styledoc, + $styleuse, + 'WS to delete a thirdparty from its id, ref or ref_ext' ); @@ -294,7 +298,9 @@ function getThirdParty($authentication, $id = '', $ref = '', $ref_ext = '') dol_syslog("Function: getThirdParty login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -302,27 +308,23 @@ function getThirdParty($authentication, $id = '', $ref = '', $ref_ext = '') $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) - { + if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->societe->lire) - { + if ($fuser->rights->societe->lire) { $thirdparty = new Societe($db); $result = $thirdparty->fetch($id, $ref, $ref_ext); - if ($result > 0) - { + if ($result > 0) { $thirdparty_result_fields = array( 'id' => $thirdparty->id, - 'ref' => $thirdparty->name, - 'ref_ext' => $thirdparty->ref_ext, - 'status' => $thirdparty->status, + 'ref' => $thirdparty->name, + 'ref_ext' => $thirdparty->ref_ext, + 'status' => $thirdparty->status, 'client' => $thirdparty->client, 'supplier' => $thirdparty->fournisseur, 'customer_code' => $thirdparty->code_client, @@ -351,7 +353,7 @@ function getThirdParty($authentication, $id = '', $ref = '', $ref_ext = '') 'profid5' => $thirdparty->idprof5, 'profid6' => $thirdparty->idprof6, 'capital' => $thirdparty->capital, - 'barcode' => $thirdparty->barcode, + 'barcode' => $thirdparty->barcode, 'vat_used' => $thirdparty->tva_assuj, 'vat_number' => $thirdparty->tva_intra, 'note_private' => $thirdparty->note_private, @@ -366,10 +368,8 @@ function getThirdParty($authentication, $id = '', $ref = '', $ref_ext = '') //Get extrafield values $thirdparty->fetch_optionals(); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { if (isset($thirdparty->array_options['options_'.$key])) { $thirdparty_result_fields = array_merge($thirdparty_result_fields, array('options_'.$key => $thirdparty->array_options['options_'.$key])); } @@ -380,20 +380,17 @@ function getThirdParty($authentication, $id = '', $ref = '', $ref_ext = '') $objectresp = array( 'result'=>array('result_code'=>'OK', 'result_label'=>''), 'thirdparty'=>$thirdparty_result_fields); - } - else { + } else { $error++; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; } - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -417,7 +414,9 @@ function createThirdParty($authentication, $thirdparty) dol_syslog("Function: createThirdParty login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -425,14 +424,12 @@ function createThirdParty($authentication, $thirdparty) $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (empty($thirdparty['ref'])) - { + if (empty($thirdparty['ref'])) { $error++; $errorcode = 'KO'; $errorlabel = "Name is mandatory."; } - if (!$error) - { + if (!$error) { include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; $newobject = new Societe($db); @@ -454,7 +451,9 @@ function createThirdParty($authentication, $thirdparty) $newobject->town = $thirdparty['town']; $newobject->country_id = $thirdparty['country_id']; - if ($thirdparty['country_code']) $newobject->country_id = getCountry($thirdparty['country_code'], 3); + if ($thirdparty['country_code']) { + $newobject->country_id = getCountry($thirdparty['country_code'], 3); + } $newobject->province_id = $thirdparty['province_id']; //if ($thirdparty['province_code']) $newobject->province_code=getCountry($thirdparty['province_code'],3); @@ -484,10 +483,8 @@ function createThirdParty($authentication, $thirdparty) // fetch optionals attributes and labels $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($elementtype, true); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $key = 'options_'.$key; if (isset($thirdparty[$key])) { $newobject->array_options[$key] = $thirdparty[$key]; @@ -503,22 +500,20 @@ function createThirdParty($authentication, $thirdparty) $newobject->name_bis = $thirdparty['lastname']; $result = $newobject->create_individual($fuser); } - if ($result <= 0) - { + if ($result <= 0) { $error++; } - if (!$error) - { + if (!$error) { $db->commit(); // Patch to add capability to associate (one) sale representative - if (!empty($thirdparty['commid']) && $thirdparty['commid'] > 0) + if (!empty($thirdparty['commid']) && $thirdparty['commid'] > 0) { $newobject->add_commercial($fuser, $thirdparty["commid"]); + } $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref); - } - else { + } else { $db->rollback(); $error++; $errorcode = 'KO'; @@ -526,8 +521,7 @@ function createThirdParty($authentication, $thirdparty) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -549,7 +543,9 @@ function updateThirdParty($authentication, $thirdparty) dol_syslog("Function: updateThirdParty login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -561,8 +557,7 @@ function updateThirdParty($authentication, $thirdparty) $error++; $errorcode = 'KO'; $errorlabel = "Thirdparty id is mandatory."; } - if (!$error) - { + if (!$error) { $objectfound = false; include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -591,7 +586,9 @@ function updateThirdParty($authentication, $thirdparty) $object->town = $thirdparty['town']; $object->country_id = $thirdparty['country_id']; - if ($thirdparty['country_code']) $object->country_id = getCountry($thirdparty['country_code'], 3); + if ($thirdparty['country_code']) { + $object->country_id = getCountry($thirdparty['country_code'], 3); + } $object->province_id = $thirdparty['province_id']; //if ($thirdparty['province_code']) $newobject->province_code=getCountry($thirdparty['province_code'],3); @@ -620,10 +617,8 @@ function updateThirdParty($authentication, $thirdparty) // fetch optionals attributes and labels $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($elementtype, true); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $key = 'options_'.$key; if (isset($thirdparty[$key])) { $object->array_options[$key] = $thirdparty[$key]; @@ -639,16 +634,13 @@ function updateThirdParty($authentication, $thirdparty) } } - if ((!$error) && ($objectfound)) - { + if ((!$error) && ($objectfound)) { $db->commit(); $objectresp = array( 'result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$object->id ); - } - elseif ($objectfound) - { + } elseif ($objectfound) { $db->rollback(); $error++; $errorcode = 'KO'; @@ -660,8 +652,7 @@ function updateThirdParty($authentication, $thirdparty) } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -683,7 +674,9 @@ function getListOfThirdParties($authentication, $filterthirdparty) dol_syslog("Function: getListOfThirdParties login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -694,20 +687,26 @@ function getListOfThirdParties($authentication, $filterthirdparty) $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (!$error) - { + if (!$error) { $sql = "SELECT s.rowid as socRowid, s.nom as ref, s.ref_ext, s.address, s.zip, s.town, c.label as country, s.phone, s.fax, s.url, extra.*"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON s.fk_pays = c.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_extrafields as extra ON s.rowid=fk_object"; $sql .= " WHERE entity=".$conf->entity; - foreach ($filterthirdparty as $key => $val) - { - if ($key == 'name' && $val != '') $sql .= " AND s.name LIKE '%".$db->escape($val)."%'"; - if ($key == 'client' && (int) $val > 0) $sql .= " AND s.client = ".$db->escape($val); - if ($key == 'supplier' && (int) $val > 0) $sql .= " AND s.fournisseur = ".$db->escape($val); - if ($key == 'category' && (int) $val > 0) $sql .= " AND s.rowid IN (SELECT fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe WHERE fk_categorie=".$db->escape($val).") "; + foreach ($filterthirdparty as $key => $val) { + if ($key == 'name' && $val != '') { + $sql .= " AND s.name LIKE '%".$db->escape($val)."%'"; + } + if ($key == 'client' && (int) $val > 0) { + $sql .= " AND s.client = ".$db->escape($val); + } + if ($key == 'supplier' && (int) $val > 0) { + $sql .= " AND s.fournisseur = ".$db->escape($val); + } + if ($key == 'category' && (int) $val > 0) { + $sql .= " AND s.rowid IN (SELECT fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe WHERE fk_categorie=".$db->escape($val).") "; + } } dol_syslog("Function: getListOfThirdParties", LOG_DEBUG); @@ -718,20 +717,16 @@ function getListOfThirdParties($authentication, $filterthirdparty) $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $extrafieldsOptions = array(); $obj = $db->fetch_object($resql); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { if (isset($obj->{$key})) { $extrafieldsOptions['options_'.$key] = $obj->{$key}; } @@ -753,22 +748,19 @@ function getListOfThirdParties($authentication, $filterthirdparty) $i++; } - } - else { + } else { $error++; $errorcode = $db->lasterrno(); $errorlabel = $db->lasterror(); } } - if ($error) - { + if ($error) { $objectresp = array( 'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel), 'thirdparties'=>$arraythirdparties ); - } - else { + } else { $objectresp = array( 'result'=>array('result_code' => 'OK', 'result_label' => ''), 'thirdparties'=>$arraythirdparties @@ -793,7 +785,9 @@ function deleteThirdParty($authentication, $id = '', $ref = '', $ref_ext = '') dol_syslog("Function: deleteThirdParty login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -801,56 +795,47 @@ function deleteThirdParty($authentication, $id = '', $ref = '', $ref_ext = '') $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) - { + if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) { dol_syslog("Function: deleteThirdParty checkparam"); $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; } dol_syslog("Function: deleteThirdParty 1"); - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->societe->lire && $fuser->rights->societe->supprimer) - { + if ($fuser->rights->societe->lire && $fuser->rights->societe->supprimer) { $thirdparty = new Societe($db); $result = $thirdparty->fetch($id, $ref, $ref_ext); - if ($result > 0) - { + if ($result > 0) { $db->begin(); $result = $thirdparty->delete($thirdparty->id, $fuser); - if ($result > 0) - { + if ($result > 0) { $db->commit(); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>'')); - } - else { + } else { $db->rollback(); $error++; $errorcode = 'KO'; $errorlabel = $thirdparty->error; dol_syslog("Function: deleteThirdParty cant delete"); } - } - else { + } else { $error++; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; } - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } diff --git a/htdocs/webservices/server_user.php b/htdocs/webservices/server_user.php index 6c4e472d1c7..cdd39ae24d7 100644 --- a/htdocs/webservices/server_user.php +++ b/htdocs/webservices/server_user.php @@ -20,7 +20,9 @@ * \brief File that is entry point to call Dolibarr WebServices */ -if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); +if (!defined("NOCSRFCHECK")) { + define("NOCSRFCHECK", '1'); +} require_once '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP @@ -36,8 +38,7 @@ dol_syslog("Call User webservices interfaces"); $langs->load("main"); // Enable and test if module web services is enabled -if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) -{ +if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) { $langs->load("admin"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; @@ -193,19 +194,22 @@ $extrafield_array = null; if (is_array($extrafields) && count($extrafields) > 0) { $extrafield_array = array(); } -if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) -{ - foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) - { +if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $type = $extrafields->attributes[$elementtype]['type'][$key]; - if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } - else {$type = 'xsd:string'; } + if ($type == 'date' || $type == 'datetime') { + $type = 'xsd:dateTime'; + } else { + $type = 'xsd:string'; + } $extrafield_array['contact_options_'.$key] = array('name'=>'contact_options_'.$key, 'type'=>$type); } } -if (is_array($extrafield_array)) $thirdpartywithuser_fields = array_merge($thirdpartywithuser_fields, $extrafield_array); +if (is_array($extrafield_array)) { + $thirdpartywithuser_fields = array_merge($thirdpartywithuser_fields, $extrafield_array); +} $server->wsdl->addComplexType( @@ -312,7 +316,9 @@ function getUser($authentication, $id, $ref = '', $ref_ext = '') dol_syslog("Function: getUser login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -320,25 +326,21 @@ function getUser($authentication, $id, $ref = '', $ref_ext = '') $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) - { + if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); if ($fuser->rights->user->user->lire || ($fuser->rights->user->self->creer && $id && $id == $fuser->id) || ($fuser->rights->user->self->creer && $ref && $ref == $fuser->login) - || ($fuser->rights->user->self->creer && $ref_ext && $ref_ext == $fuser->ref_ext)) - { + || ($fuser->rights->user->self->creer && $ref_ext && $ref_ext == $fuser->ref_ext)) { $user = new User($db); $result = $user->fetch($id, $ref, $ref_ext); - if ($result > 0) - { + if ($result > 0) { // Create $objectresp = array( 'result'=>array('result_code'=>'OK', 'result_label'=>''), @@ -371,20 +373,17 @@ function getUser($authentication, $id, $ref = '', $ref_ext = '') 'canvas' => $user->canvas ) ); - } - else { + } else { $error++; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; } - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } } - if ($error) - { + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } @@ -403,7 +402,9 @@ function getListOfGroups($authentication) dol_syslog("Function: getListOfGroups login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } // Init and check authentication $objectresp = array(); @@ -413,47 +414,39 @@ function getListOfGroups($authentication) $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); // Check parameters - if (!$error) - { + if (!$error) { $sql = "SELECT g.rowid, g.nom as name, g.entity, g.datec, COUNT(DISTINCT ugu.fk_user) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."usergroup as g"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_usergroup = g.rowid"; - if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && ($conf->global->MULTICOMPANY_TRANSVERSE_MODE || ($user->admin && !$user->entity))) - { + if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && ($conf->global->MULTICOMPANY_TRANSVERSE_MODE || ($user->admin && !$user->entity))) { $sql .= " WHERE g.entity IS NOT NULL"; - } - else { + } else { $sql .= " WHERE g.entity IN (0,".$conf->entity.")"; } $sql .= " GROUP BY g.rowid, g.nom, g.entity, g.datec"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $arraygroups[] = array('id'=>$obj->rowid, 'name'=>$obj->name, 'datec'=>$obj->datec, 'nb'=>$obj->nb); $i++; } - } - else { + } else { $error++; $errorcode = $db->lasterrno(); $errorlabel = $db->lasterror(); } } - if ($error) - { + if ($error) { $objectresp = array( 'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel), 'groups'=>$arraygroups ); - } - else { + } else { $objectresp = array( 'result'=>array('result_code' => 'OK', 'result_label' => ''), 'groups'=>$arraygroups @@ -477,7 +470,9 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser) dol_syslog("Function: createUserFromThirdparty login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } $objectresp = array(); $errorcode = ''; $errorlabel = ''; @@ -485,20 +480,19 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser) $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); - if ($fuser->socid) $socid = $fuser->socid; + if ($fuser->socid) { + $socid = $fuser->socid; + } - if (!$error && !$thirdpartywithuser) - { + if (!$error && !$thirdpartywithuser) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter thirdparty must be provided."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->societe->creer) - { + if ($fuser->rights->societe->creer) { $thirdparty = new Societe($db); // If a contact / company already exists with the email, return the corresponding socid @@ -510,16 +504,13 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser) $sql .= $db->plimit(1); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { // If a company or contact is found with the same email we return an error $row = $db->fetch_object($resql); - if ($row) - { + if ($row) { $error++; $errorcode = 'ALREADY_EXIST'; $errorlabel = 'Object not create : company or contact exists '.$thirdpartywithuser['email']; - } - else { + } else { $db->begin(); /* * Company creation @@ -541,11 +532,9 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser) $sql .= " AND code='".$db->escape($thirdparty->country_code)."'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $obj = $db->fetch_object($resql); $thirdparty->country_id = $obj->rowid; } @@ -567,8 +556,7 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser) $socid_return = $thirdparty->create($fuser); - if ($socid_return > 0) - { + if ($socid_return > 0) { $thirdparty->fetch($socid_return); /* @@ -597,10 +585,8 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser) // fetch optionals attributes and labels $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($elementtype, true); - if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) - { - foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) - { + if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) { + foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) { $key = 'contact_options_'.$key; $key = substr($key, 8); // Remove 'contact_' prefix $contact->array_options[$key] = $thirdpartywithuser[$key]; @@ -609,8 +595,7 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser) $contact_id = $contact->create($fuser); - if ($contact_id > 0) - { + if ($contact_id > 0) { /* * User creation * @@ -618,19 +603,17 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser) $edituser = new User($db); $id = $edituser->create_from_contact($contact, $thirdpartywithuser["login"]); - if ($id > 0) - { + if ($id > 0) { $edituser->setPassword($fuser, trim($thirdpartywithuser['password'])); - if ($thirdpartywithuser['group_id'] > 0) + if ($thirdpartywithuser['group_id'] > 0) { $edituser->SetInGroup($thirdpartywithuser['group_id'], $conf->entity); - } - else { + } + } else { $error++; $errorcode = 'NOT_CREATE'; $errorlabel = 'Object not create : '.$edituser->error; } - } - else { + } else { $error++; $errorcode = 'NOT_CREATE'; $errorlabel = 'Object not create : '.$contact->error; } @@ -656,8 +639,7 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser) } } - if ($error) - { + if ($error) { $db->rollback(); $objectresp = array( 'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel) @@ -682,7 +664,9 @@ function setUserPassword($authentication, $shortuser) dol_syslog("Function: setUserPassword login=".$authentication['login']); - if ($authentication['entity']) $conf->entity = $authentication['entity']; + if ($authentication['entity']) { + $conf->entity = $authentication['entity']; + } $objectresp = array(); $errorcode = ''; $errorlabel = ''; @@ -690,50 +674,43 @@ function setUserPassword($authentication, $shortuser) $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); - if ($fuser->socid) $socid = $fuser->socid; + if ($fuser->socid) { + $socid = $fuser->socid; + } - if (!$error && !$shortuser) - { + if (!$error && !$shortuser) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter shortuser must be provided."; } - if (!$error) - { + if (!$error) { $fuser->getrights(); - if ($fuser->rights->user->user->password || $fuser->rights->user->self->password) - { + if ($fuser->rights->user->user->password || $fuser->rights->user->self->password) { $userstat = new User($db); $res = $userstat->fetch('', $shortuser['login']); - if ($res) - { + if ($res) { $res = $userstat->setPassword($userstat, $shortuser['password']); - if ($res) - { + if ($res) { $objectresp = array( 'result'=>array('result_code' => 'OK', 'result_label' => ''), ); - } - else { + } else { $error++; $errorcode = 'NOT_MODIFIED'; $errorlabel = 'Error when changing password'; } - } - else { + } else { $error++; $errorcode = 'NOT_FOUND'; $errorlabel = 'User not found'; } - } - else { + } else { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; } } - if ($error) - { + if ($error) { $objectresp = array( 'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel) ); diff --git a/htdocs/website/class/website.class.php b/htdocs/website/class/website.class.php index 34cc78e9a05..1d30b71ad0a 100644 --- a/htdocs/website/class/website.class.php +++ b/htdocs/website/class/website.class.php @@ -244,7 +244,9 @@ class Website extends CommonObject if (is_array($tmplangarray)) { dol_mkdir($conf->website->dir_output.'/'.$this->ref); foreach ($tmplangarray as $val) { - if (trim($val) == $this->lang) continue; + if (trim($val) == $this->lang) { + continue; + } dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val)); } } @@ -520,7 +522,7 @@ class Website extends CommonObject $sql .= ' fk_user_modif = '.(!isset($this->fk_user_modif) ? $user->id : $this->fk_user_modif).','; $sql .= ' date_creation = '.(!isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').','; $sql .= ' tms = '.(dol_strlen($this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : "'".$this->db->idate(dol_now())."'"); - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); $this->db->begin(); @@ -540,7 +542,9 @@ class Website extends CommonObject if (is_array($tmplangarray)) { dol_mkdir($conf->website->dir_output.'/'.$this->ref); foreach ($tmplangarray as $val) { - if (trim($val) == $this->lang) continue; + if (trim($val) == $this->lang) { + continue; + } dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val)); } } @@ -593,7 +597,7 @@ class Website extends CommonObject if (!$error) { $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) { @@ -603,8 +607,7 @@ class Website extends CommonObject } } - if (!$error && !empty($this->ref)) - { + if (!$error && !empty($this->ref)) { $pathofwebsite = DOL_DATA_ROOT.'/website/'.$this->ref; dol_delete_dir_recursive($pathofwebsite); @@ -645,8 +648,7 @@ class Website extends CommonObject $object = new self($this->db); // Check no site with ref exists - if ($object->fetch(0, $newref) > 0) - { + if ($object->fetch(0, $newref) > 0) { $this->error = 'ErrorNewRefIsAlreadyUsed'; return -1; } @@ -678,7 +680,9 @@ class Website extends CommonObject $object->fk_user_creat = $user->id; $object->position = ((int) $object->position) + 1; $object->status = self::STATUS_DRAFT; - if (empty($object->lang)) $object->lang = substr($langs->defaultlang, 0, 2); // Should not happen. Protection for corrupted site with no languages + if (empty($object->lang)) { + $object->lang = substr($langs->defaultlang, 0, 2); // Should not happen. Protection for corrupted site with no languages + } // Create clone $object->context['createfromclone'] = 'createfromclone'; @@ -690,15 +694,13 @@ class Website extends CommonObject dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } - if (!$error) - { + if (!$error) { dolCopyDir($pathofwebsiteold, $pathofwebsitenew, $conf->global->MAIN_UMASK, 0, null, 2); // Check symlink to medias and restore it if ko $pathtomedias = DOL_DATA_ROOT.'/medias'; // Target $pathtomediasinwebsite = $pathofwebsitenew.'/medias'; // Source / Link name - if (!is_link(dol_osencode($pathtomediasinwebsite))) - { + if (!is_link(dol_osencode($pathtomediasinwebsite))) { dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists $result = symlink($pathtomedias, $pathtomediasinwebsite); @@ -718,8 +720,7 @@ class Website extends CommonObject // Duplicate pages $objectpages = new WebsitePage($this->db); $listofpages = $objectpages->fetchAll($fromid); - foreach ($listofpages as $pageid => $objectpageold) - { + foreach ($listofpages as $pageid => $objectpageold) { // Delete old file $filetplold = $pathofwebsitenew.'/page'.$pageid.'.tpl.php'; dol_delete_file($filetplold); @@ -728,43 +729,41 @@ class Website extends CommonObject $objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id, 1); //print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'<br>'; - if (is_object($objectpagenew) && $objectpagenew->pageurl) - { + if (is_object($objectpagenew) && $objectpagenew->pageurl) { $filealias = $pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php'; $filetplnew = $pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php'; // Save page alias $result = dolSavePageAlias($filealias, $object, $objectpagenew); - if (!$result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + if (!$result) { + setEventMessages('Failed to write file '.$filealias, null, 'errors'); + } $result = dolSavePageContent($filetplnew, $object, $objectpagenew); - if (!$result) setEventMessages('Failed to write file '.$filetplnew, null, 'errors'); + if (!$result) { + setEventMessages('Failed to write file '.$filetplnew, null, 'errors'); + } - if ($pageid == $oldidforhome) - { + if ($pageid == $oldidforhome) { $newidforhome = $objectpagenew->id; } - } - else { + } else { setEventMessages($objectpageold->error, $objectpageold->errors, 'errors'); $error++; } } } - if (!$error) - { + if (!$error) { // Restore id of home page $object->fk_default_home = $newidforhome; $res = $object->update($user); - if (!($res > 0)) - { + if (!($res > 0)) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } - if (!$error) - { + if (!$error) { $filetpl = $pathofwebsitenew.'/page'.$newidforhome.'.tpl.php'; $filewrapper = $pathofwebsitenew.'/wrapper.php'; @@ -821,10 +820,11 @@ class Website extends CommonObject $linkstart = $linkend = ''; - if ($withpicto) - { + if ($withpicto) { $result .= ($linkstart.img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? '' : 'class="classfortooltip"')).$linkend); - if ($withpicto != 2) $result .= ' '; + if ($withpicto != 2) { + $result .= ' '; + } } $result .= $linkstart.$this->ref.$linkend; return $result; @@ -854,8 +854,7 @@ class Website extends CommonObject // phpcs:enable global $langs; - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Disabled'); @@ -865,7 +864,9 @@ class Website extends CommonObject } $statusType = 'status5'; - if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -909,16 +910,14 @@ class Website extends CommonObject $website = $this; - if (empty($website->id) || empty($website->ref)) - { + if (empty($website->id) || empty($website->ref)) { setEventMessages("Website id or ref is not defined", null, 'errors'); return ''; } dol_syslog("Create temp dir ".$conf->website->dir_temp); dol_mkdir($conf->website->dir_temp); - if (!is_writable($conf->website->dir_temp)) - { + if (!is_writable($conf->website->dir_temp)) { setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors'); return ''; } @@ -928,8 +927,7 @@ class Website extends CommonObject dol_syslog("Clear temp dir ".$destdir); $count = 0; $countreallydeleted = 0; $counttodelete = dol_delete_dir_recursive($destdir, $count, 1, 0, $countreallydeleted); - if ($counttodelete != $countreallydeleted) - { + if ($counttodelete != $countreallydeleted) { setEventMessages("Failed to clean temp directory ".$destdir, null, 'errors'); return ''; } @@ -987,8 +985,7 @@ class Website extends CommonObject // Build sql file $filesql = $conf->website->dir_temp.'/'.$website->ref.'/website_pages.sql'; $fp = fopen($filesql, "w"); - if (empty($fp)) - { + if (empty($fp)) { setEventMessages("Failed to create file ".$filesql, null, 'errors'); return ''; } @@ -998,20 +995,16 @@ class Website extends CommonObject // Assign ->newid and ->newfk_page $i = 1; - foreach ($listofpages as $pageid => $objectpageold) - { + foreach ($listofpages as $pageid => $objectpageold) { $objectpageold->newid = $i; $i++; } $i = 1; - foreach ($listofpages as $pageid => $objectpageold) - { + foreach ($listofpages as $pageid => $objectpageold) { // Search newid $newfk_page = 0; - foreach ($listofpages as $pageid2 => $objectpageold2) - { - if ($pageid2 == $objectpageold->fk_page) - { + foreach ($listofpages as $pageid2 => $objectpageold2) { + if ($pageid2 == $objectpageold->fk_page) { $newfk_page = $objectpageold2->newid; break; } @@ -1019,8 +1012,7 @@ class Website extends CommonObject $objectpageold->newfk_page = $newfk_page; $i++; } - foreach ($listofpages as $pageid => $objectpageold) - { + foreach ($listofpages as $pageid => $objectpageold) { $allaliases = $objectpageold->pageurl; $allaliases .= ($objectpageold->aliasalt ? ','.$objectpageold->aliasalt : ''); @@ -1081,8 +1073,7 @@ class Website extends CommonObject // Add line to update home page id during import //var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit; - if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0)) // This is the record with home page - { + if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0)) { // This is the record with home page // Warning: We must keep llx_ here. It is a generic SQL. $line = "UPDATE llx_website SET fk_default_home = ".($objectpageold->newid > 0 ? $this->db->escape($objectpageold->newid)."__+MAX_llx_website_page__" : "null")." WHERE rowid = __WEBSITE_ID__;"; $line .= "\n"; @@ -1091,8 +1082,9 @@ class Website extends CommonObject } fclose($fp); - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { @chmod($filesql, octdec($conf->global->MAIN_UMASK)); + } // Build zip file $filedir = $conf->website->dir_temp.'/'.$website->ref.'/.'; @@ -1102,11 +1094,9 @@ class Website extends CommonObject dol_delete_file($fileglob, 0); $result = dol_compress_file($filedir, $filename, 'zip'); - if ($result > 0) - { + if ($result > 0) { return $filename; - } - else { + } else { global $errormsg; $this->error = $errormsg; return ''; @@ -1127,8 +1117,7 @@ class Website extends CommonObject $error = 0; $object = $this; - if (empty($object->ref)) - { + if (empty($object->ref)) { $this->error = 'Function importWebSite called on object not loaded (object->ref is empty)'; return -1; } @@ -1137,16 +1126,14 @@ class Website extends CommonObject dol_mkdir($conf->website->dir_temp.'/'.$object->ref); $filename = basename($pathtofile); - if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) - { + if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) { $this->errors[] = 'Bad format for filename '.$filename.'. Must be website_XXX-VERSION.'; return -1; } $result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref); - if (!empty($result['error'])) - { + if (!empty($result['error'])) { $this->errors[] = 'Failed to unzip file '.$pathtofile.'.'; return -1; } @@ -1172,8 +1159,7 @@ class Website extends CommonObject // Now generate the master.inc.php page $filemaster = $conf->website->dir_output.'/'.$object->ref.'/master.inc.php'; $result = dolSaveMasterFile($filemaster); - if (!$result) - { + if (!$result) { $this->errors[] = 'Failed to write file '.$filemaster; $error++; } @@ -1190,16 +1176,14 @@ class Website extends CommonObject // Search the $maxrowid because we need it later $sqlgetrowid = 'SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page'; $resql = $this->db->query($sqlgetrowid); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $maxrowid = $obj->max; } // Load sql record $runsql = run_sql($sqlfile, 1, '', 0, '', 'none', 0, 1); // The maxrowid of table is searched into this function two - if ($runsql <= 0) - { + if ($runsql <= 0) { $this->errors[] = 'Failed to load sql file '.$sqlfile; $error++; } @@ -1208,16 +1192,13 @@ class Website extends CommonObject // Make replacement of IDs $fp = fopen($sqlfile, "r"); - if ($fp) - { - while (!feof($fp)) - { + if ($fp) { + while (!feof($fp)) { $reg = array(); // Warning fgets with second parameter that is null or 0 hang. $buf = fgets($fp, 65000); - if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.*)\s--;/i', $buf, $reg)) - { + if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.*)\s--;/i', $buf, $reg)) { $oldid = $reg[1]; $newid = ($reg[2] + $maxrowid); $aliasesarray = explode(',', $reg[3]); @@ -1237,12 +1218,9 @@ class Website extends CommonObject } // Regenerate alternative aliases pages - if (is_array($aliasesarray)) - { - foreach ($aliasesarray as $aliasshortcuttocreate) - { - if (trim($aliasshortcuttocreate)) - { + if (is_array($aliasesarray)) { + foreach ($aliasesarray as $aliasshortcuttocreate) { + if (trim($aliasshortcuttocreate)) { $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php'; $result = dolSavePageAlias($filealias, $object, $objectpagestatic); if (!$result) { @@ -1274,12 +1252,10 @@ class Website extends CommonObject $pathofwebsite = $conf->website->dir_output.'/'.$object->ref; dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php', $pathofwebsite.'/wrapper.php'); - if ($error) - { + if ($error) { $this->db->rollback(); return -1; - } - else { + } else { $this->db->commit(); return $object->id; } @@ -1298,8 +1274,7 @@ class Website extends CommonObject $error = 0; $object = $this; - if (empty($object->ref)) - { + if (empty($object->ref)) { $this->error = 'Function rebuildWebSiteFiles called on object not loaded (object->ref is empty)'; return -1; } @@ -1386,7 +1361,9 @@ class Website extends CommonObject { global $websitepagefile, $website; - if (!is_object($weblangs)) return 'ERROR componentSelectLang called with parameter $weblangs not defined'; + if (!is_object($weblangs)) { + return 'ERROR componentSelectLang called with parameter $weblangs not defined'; + } $arrayofspecialmainlanguages = array( 'en'=>'en_US', @@ -1396,7 +1373,7 @@ class Website extends CommonObject 'bn'=>'bn_DB', 'bs'=>'bs_BA', 'ca'=>'ca_ES', - 'zh'=>'zh_TW', + 'zh'=>'zh_CN', 'cs'=>'cs_CZ', 'da'=>'da_DK', 'et'=>'et_EE', @@ -1419,51 +1396,55 @@ class Website extends CommonObject $tmppage = new WebsitePage($this->db); $pageid = 0; - if (!empty($websitepagefile)) - { + if (!empty($websitepagefile)) { $websitepagefileshort = basename($websitepagefile); - if ($websitepagefileshort == 'index.php') $pageid = $website->fk_default_home; - else $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort); - if ($pageid > 0) - { + if ($websitepagefileshort == 'index.php') { + $pageid = $website->fk_default_home; + } else { + $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort); + } + if ($pageid > 0) { $tmppage->fetch($pageid); } } // Fill $languagecodes array with existing translation, nothing if none - if (!is_array($languagecodes) && $pageid > 0) - { + if (!is_array($languagecodes) && $pageid > 0) { $languagecodes = array(); $sql = "SELECT wp.rowid, wp.lang, wp.pageurl, wp.fk_page"; $sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp"; $sql .= " WHERE wp.fk_website = ".$website->id; $sql .= " AND (wp.fk_page = ".$pageid." OR wp.rowid = ".$pageid; - if ($tmppage->fk_page > 0) $sql .= " OR wp.fk_page = ".$tmppage->fk_page." OR wp.rowid = ".$tmppage->fk_page; + if ($tmppage->fk_page > 0) { + $sql .= " OR wp.fk_page = ".$tmppage->fk_page." OR wp.rowid = ".$tmppage->fk_page; + } $sql .= ")"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $newlang = $obj->lang; - if ($obj->rowid == $pageid) $newlang = $obj->lang; - if (!in_array($newlang, $languagecodes)) $languagecodes[] = $newlang; + if ($obj->rowid == $pageid) { + $newlang = $obj->lang; + } + if (!in_array($newlang, $languagecodes)) { + $languagecodes[] = $newlang; + } } } } // Now $languagecodes is always an array. Example array('en', 'fr', 'es'); $languagecodeselected = substr($weblangs->defaultlang, 0, 2); // Because we must init with a value, but real value is the lang of main parent container - if (!empty($websitepagefile)) - { + if (!empty($websitepagefile)) { $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile)); - if ($pageid > 0) - { + if ($pageid > 0) { $pagelang = substr($tmppage->lang, 0, 2); $languagecodeselected = substr($pagelang, 0, 2); - if (!in_array($pagelang, $languagecodes)) $languagecodes[] = $pagelang; // We add language code of page into combo list + if (!in_array($pagelang, $languagecodes)) { + $languagecodes[] = $pagelang; // We add language code of page into combo list + } } } @@ -1474,7 +1455,9 @@ class Website extends CommonObject $url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url); // We remove param l from url //$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url); // We remove param lang from url $url .= (preg_match('/\?/', $url) ? '&' : '?').'l='; - if (!preg_match('/^\//', $url)) $url = '/'.$url; + if (!preg_match('/^\//', $url)) { + $url = '/'.$url; + } $HEIGHTOPTION = 40; $MAXHEIGHT = 4 * $HEIGHTOPTION; @@ -1504,8 +1487,7 @@ class Website extends CommonObject $out .= '</style>'; $out .= '<ul class="componentSelectLang'.$htmlname.($morecss ? ' '.$morecss : '').'">'; - if ($languagecodeselected) - { + if ($languagecodeselected) { // Convert $languagecodeselected into a long language code if (strlen($languagecodeselected) == 2) { $languagecodeselected = (empty($arrayofspecialmainlanguages[$languagecodeselected]) ? $languagecodeselected.'_'.strtoupper($languagecodeselected) : $arrayofspecialmainlanguages[$languagecodeselected]); @@ -1513,28 +1495,34 @@ class Website extends CommonObject $countrycode = strtolower(substr($languagecodeselected, -2)); $label = $weblangs->trans("Language_".$languagecodeselected); - if ($countrycode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label); + if ($countrycode == 'us') { + $label = preg_replace('/\s*\(.*\)/', '', $label); + } $out .= '<a href="'.$url.substr($languagecodeselected, 0, 2).'"><li><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>'; $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />'; $out .= '</li></a>'; } $i = 0; - if (is_array($languagecodes)) - { - foreach ($languagecodes as $languagecode) - { + if (is_array($languagecodes)) { + foreach ($languagecodes as $languagecode) { // Convert $languagecode into a long language code if (strlen($languagecode) == 2) { $languagecode = (empty($arrayofspecialmainlanguages[$languagecode]) ? $languagecode.'_'.strtoupper($languagecode) : $arrayofspecialmainlanguages[$languagecode]); } - if ($languagecode == $languagecodeselected) continue; // Already output + if ($languagecode == $languagecodeselected) { + continue; // Already output + } $countrycode = strtolower(substr($languagecode, -2)); $label = $weblangs->trans("Language_".$languagecode); - if ($countrycode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label); + if ($countrycode == 'us') { + $label = preg_replace('/\s*\(.*\)/', '', $label); + } $out .= '<a href="'.$url.substr($languagecode, 0, 2).'"><li><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>'; - if (empty($i) && empty($languagecodeselected)) $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />'; + if (empty($i) && empty($languagecodeselected)) { + $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />'; + } $out .= '</li></a>'; $i++; } diff --git a/htdocs/website/class/websitepage.class.php b/htdocs/website/class/websitepage.class.php index bacc4664791..f59b8bbc5a5 100644 --- a/htdocs/website/class/websitepage.class.php +++ b/htdocs/website/class/websitepage.class.php @@ -106,9 +106,9 @@ class WebsitePage extends CommonObject */ public $author_alias; - /** - * @var string path of external object - */ + /** + * @var string path of external object + */ public $object_type; /** @@ -229,7 +229,9 @@ class WebsitePage extends CommonObject { $this->description = dol_trunc($this->description, 255, 'right', 'utf-8', 1); $this->keywords = dol_trunc($this->keywords, 255, 'right', 'utf-8', 1); - if ($this->aliasalt) $this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,' + if ($this->aliasalt) { + $this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,' + } // Remove spaces and be sure we have main language only $this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en @@ -281,12 +283,12 @@ class WebsitePage extends CommonObject $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; //$sql .= ' WHERE entity IN ('.getEntity('website').')'; // entity is on website level $sql .= ' WHERE 1 = 1'; - if ($id > 0) - { - $sql .= ' AND t.rowid = '.$id; - } - else { - if ($id < 0) $sql .= ' AND t.rowid <> '.abs($id); + if ($id > 0) { + $sql .= ' AND t.rowid = '.((int) $id); + } else { + if ($id < 0) { + $sql .= ' AND t.rowid <> '.abs($id); + } if (null !== $website_id) { $sql .= " AND t.fk_website = '".$this->db->escape($website_id)."'"; if ($page) { @@ -295,12 +297,18 @@ class WebsitePage extends CommonObject $tmppage = explode('/', $page); if (!empty($tmppage[1])) { $pagetouse = $tmppage[1]; - if (strlen($tmppage[0])) $langtouse = $tmppage[0]; + if (strlen($tmppage[0])) { + $langtouse = $tmppage[0]; + } } $sql .= " AND t.pageurl = '".$this->db->escape($pagetouse)."'"; - if ($langtouse) $sql .= " AND t.lang = '".$this->db->escape($langtouse)."'"; + if ($langtouse) { + $sql .= " AND t.lang = '".$this->db->escape($langtouse)."'"; + } + } + if ($aliasalt) { + $sql .= " AND (t.aliasalt LIKE '%,".$this->db->escape($aliasalt).",%' OR t.aliasalt LIKE '%, ".$this->db->escape($aliasalt).",%')"; } - if ($aliasalt) $sql .= " AND (t.aliasalt LIKE '%,".$this->db->escape($aliasalt).",%' OR t.aliasalt LIKE '%, ".$this->db->escape($aliasalt).",%')"; } } $sql .= $this->db->plimit(1); @@ -419,7 +427,9 @@ class WebsitePage extends CommonObject $listoflang[] = "'".$this->db->escape(substr(str_replace("'", '', $tmpvalue), 0, 2))."'"; } $stringtouse = $key." IN (".join(',', $listoflang).")"; - if ($foundnull) $stringtouse = '('.$stringtouse.' OR '.$key.' IS NULL)'; + if ($foundnull) { + $stringtouse = '('.$stringtouse.' OR '.$key.' IS NULL)'; + } $sqlwhere[] = $stringtouse; } else { $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; @@ -441,8 +451,7 @@ class WebsitePage extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $record = new self($this->db); $record->id = $obj->rowid; @@ -520,7 +529,9 @@ class WebsitePage extends CommonObject $listoflang[] = "'".$this->db->escape(substr(str_replace("'", '', $tmpvalue), 0, 2))."'"; } $stringtouse = $key." IN (".join(',', $listoflang).")"; - if ($foundnull) $stringtouse = '('.$stringtouse.' OR '.$key.' IS NULL)'; + if ($foundnull) { + $stringtouse = '('.$stringtouse.' OR '.$key.' IS NULL)'; + } $sqlwhere[] = $stringtouse; } else { $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; @@ -561,7 +572,9 @@ class WebsitePage extends CommonObject { $this->description = dol_trunc($this->description, 255, 'right', 'utf-8', 1); $this->keywords = dol_trunc($this->keywords, 255, 'right', 'utf-8', 1); - if ($this->aliasalt) $this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,' + if ($this->aliasalt) { + $this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,' + } // Remove spaces and be sure we have main language only $this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en @@ -595,8 +608,7 @@ class WebsitePage extends CommonObject // Delete all child tables if (!$error) { - foreach ($this->childtablesoncascade as $table) - { + foreach ($this->childtablesoncascade as $table) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table; $sql .= " WHERE fk_website_page = ".(int) $this->id; @@ -611,19 +623,16 @@ class WebsitePage extends CommonObject if (!$error) { $result = $this->deleteCommon($user, $trigger); - if ($result <= 0) - { + if ($result <= 0) { $error++; } } - if (!$error) - { + if (!$error) { $websiteobj = new Website($this->db); $result = $websiteobj->fetch($this->fk_website); - if ($result > 0) - { + if ($result > 0) { global $dolibarr_main_data_root; $pathofwebsite = $dolibarr_main_data_root.'/website/'.$websiteobj->ref; @@ -696,10 +705,17 @@ class WebsitePage extends CommonObject $object->date_creation = $now; $object->title = ($newtitle == '1' ? $object->title : ($newtitle ? $newtitle : $object->title)); $object->description = $object->title; - if (!empty($newlang)) $object->lang = $newlang; - if ($istranslation) $object->fk_page = $fromid; - else $object->fk_page = 0; - if (!empty($newwebsite)) $object->fk_website = $newwebsite; + if (!empty($newlang)) { + $object->lang = $newlang; + } + if ($istranslation) { + $object->fk_page = $fromid; + } else { + $object->fk_page = 0; + } + if (!empty($newwebsite)) { + $object->fk_website = $newwebsite; + } $object->import_key = ''; // Create clone @@ -755,17 +771,16 @@ class WebsitePage extends CommonObject $url = DOL_URL_ROOT.'/website/index.php?websiteid='.$this->fk_website.'&pageid='.$this->id; $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowMyObject"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } - else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $linkstart = '<a href="'.$url.'"'; $linkstart .= $linkclose.'>'; @@ -774,8 +789,12 @@ class WebsitePage extends CommonObject //$linkstart = $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_picto(($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 .= $this->ref; + if ($withpicto) { + $result .= img_picto(($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 .= $this->ref; + } $result .= $linkend; return $result; @@ -805,8 +824,7 @@ class WebsitePage extends CommonObject // phpcs:enable global $langs; - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Disabled'); @@ -816,7 +834,9 @@ class WebsitePage extends CommonObject } $statusType = 'status5'; - if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } diff --git a/htdocs/website/index.php b/htdocs/website/index.php index ebcf31ad2c5..034583d3440 100644 --- a/htdocs/website/index.php +++ b/htdocs/website/index.php @@ -38,13 +38,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formwebsite.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; require_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $langs->loadLangs(array("admin", "other", "website", "errors")); -if (!$user->rights->website->read) accessforbidden(); +if (!$user->rights->website->read) { + accessforbidden(); +} $conf->dol_hide_leftmenu = 1; // Force hide of left menu. @@ -70,38 +73,78 @@ $section_dir = GETPOST('section_dir', 'alpha'); $file_manager = GETPOST('file_manager', 'alpha'); $replacesite = GETPOST('replacesite', 'alpha'); -if (GETPOST('deletesite', 'alpha')) { $action = 'deletesite'; } -if (GETPOST('delete', 'alpha')) { $action = 'delete'; } -if (GETPOST('preview', 'alpha')) $action = 'preview'; -if (GETPOST('createsite', 'alpha')) { $action = 'createsite'; } -if (GETPOST('createcontainer', 'alpha')) { $action = 'createcontainer'; } -if (GETPOST('editcss', 'alpha')) { $action = 'editcss'; } -if (GETPOST('editmenu', 'alpha')) { $action = 'editmenu'; } -if (GETPOST('setashome', 'alpha')) { $action = 'setashome'; } -if (GETPOST('editmeta', 'alpha')) { $action = 'editmeta'; } -if (GETPOST('editsource', 'alpha')) { $action = 'editsource'; } -if (GETPOST('editcontent', 'alpha')) { $action = 'editcontent'; } -if (GETPOST('exportsite', 'alpha')) { $action = 'exportsite'; } -if (GETPOST('importsite', 'alpha')) { $action = 'importsite'; } -if (GETPOST('createfromclone', 'alpha')) { $action = 'createfromclone'; } -if (GETPOST('createpagefromclone', 'alpha')) { $action = 'createpagefromclone'; } -if (empty($action) && $file_manager) $action = 'file_manager'; -if (empty($action) && $replacesite) $action = 'replacesite'; -if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x')) $pageid = 0; +if (GETPOST('deletesite', 'alpha')) { + $action = 'deletesite'; +} +if (GETPOST('delete', 'alpha')) { + $action = 'delete'; +} +if (GETPOST('preview', 'alpha')) { + $action = 'preview'; +} +if (GETPOST('createsite', 'alpha')) { + $action = 'createsite'; +} +if (GETPOST('createcontainer', 'alpha')) { + $action = 'createcontainer'; +} +if (GETPOST('editcss', 'alpha')) { + $action = 'editcss'; +} +if (GETPOST('editmenu', 'alpha')) { + $action = 'editmenu'; +} +if (GETPOST('setashome', 'alpha')) { + $action = 'setashome'; +} +if (GETPOST('editmeta', 'alpha')) { + $action = 'editmeta'; +} +if (GETPOST('editsource', 'alpha')) { + $action = 'editsource'; +} +if (GETPOST('editcontent', 'alpha')) { + $action = 'editcontent'; +} +if (GETPOST('exportsite', 'alpha')) { + $action = 'exportsite'; +} +if (GETPOST('importsite', 'alpha')) { + $action = 'importsite'; +} +if (GETPOST('createfromclone', 'alpha')) { + $action = 'createfromclone'; +} +if (GETPOST('createpagefromclone', 'alpha')) { + $action = 'createpagefromclone'; +} +if (empty($action) && $file_manager) { + $action = 'file_manager'; +} +if (empty($action) && $replacesite) { + $action = 'replacesite'; +} +if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x')) { + $pageid = 0; +} // Load variable for pagination $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='name'; //if (! $sortorder) $sortorder='ASC'; -if (empty($action)) $action = 'preview'; +if (empty($action)) { + $action = 'preview'; +} $object = new Website($db); $objectpage = new WebsitePage($db); @@ -109,16 +152,13 @@ $objectpage = new WebsitePage($db); $object->fetchAll('ASC', 'position'); // Init $object->records with list of websites // If website not defined, we take first found -if (!($websiteid > 0) && empty($websitekey) && $action != 'createsite') -{ - foreach ($object->records as $key => $valwebsite) - { +if (!($websiteid > 0) && empty($websitekey) && $action != 'createsite') { + foreach ($object->records as $key => $valwebsite) { $websitekey = $valwebsite->ref; break; } } -if ($websiteid > 0 || $websitekey) -{ +if ($websiteid > 0 || $websitekey) { $res = $object->fetch($websiteid, $websitekey); $websitekey = $object->ref; } @@ -126,38 +166,33 @@ if ($websiteid > 0 || $websitekey) $website = $object; // Check pageid received as parameter -if ($pageid < 0) $pageid = 0; -if (($pageid > 0 || $pageref) && $action != 'addcontainer') -{ +if ($pageid < 0) { + $pageid = 0; +} +if (($pageid > 0 || $pageref) && $action != 'addcontainer') { $res = $objectpage->fetch($pageid, ($object->id > 0 ? $object->id : null), $pageref); - if ($res == 0) - { + if ($res == 0) { $res = $objectpage->fetch($pageid, ($object->id > 0 ? $object->id : null), null, $pageref); } // Check if pageid is inside the new website, if not we reset param pageid - if ($res >= 0 && $object->id > 0) - { - if ($objectpage->fk_website != $object->id) // We have a bad page that does not belong to web site - { - if ($object->fk_default_home > 0) - { + if ($res >= 0 && $object->id > 0) { + if ($objectpage->fk_website != $object->id) { // We have a bad page that does not belong to web site + if ($object->fk_default_home > 0) { $res = $objectpage->fetch($object->fk_default_home, $object->id, ''); // We search first page of web site - if ($res > 0) $pageid = $object->fk_default_home; - } - else { - $res = $objectpage->fetch(0, $object->id, ''); // We search first page of web site - if ($res == 0) // Page was not found, we reset it - { - $objectpage = new WebsitePage($db); + if ($res > 0) { + $pageid = $object->fk_default_home; } - else // We found a page, we set pageid to it. + } else { + $res = $objectpage->fetch(0, $object->id, ''); // We search first page of web site + if ($res == 0) { // Page was not found, we reset it + $objectpage = new WebsitePage($db); + } else // We found a page, we set pageid to it. { $pageid = $objectpage->id; } } - } - else // We have a valid page. We force pageid for the case we got the page with a fetch on ref. + } else // We have a valid page. We force pageid for the case we got the page with a fetch on ref. { $pageid = $objectpage->id; } @@ -165,20 +200,23 @@ if (($pageid > 0 || $pageref) && $action != 'addcontainer') } // Define pageid if pageid and pageref not received as parameter or was wrong -if (empty($pageid) && empty($pageref) && $object->id > 0 && $action != 'createcontainer') -{ +if (empty($pageid) && empty($pageref) && $object->id > 0 && $action != 'createcontainer') { $pageid = $object->fk_default_home; - if (empty($pageid)) - { + if (empty($pageid)) { $array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl'); - if (!is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); + if (!is_array($array) && $array < 0) { + dol_print_error('', $objectpage->error, $objectpage->errors); + } $atleastonepage = (is_array($array) && count($array) > 0); $firstpageid = 0; $homepageid = 0; - foreach ($array as $key => $valpage) - { - if (empty($firstpageid)) $firstpageid = $valpage->id; - if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid = $valpage->id; + foreach ($array as $key => $valpage) { + if (empty($firstpageid)) { + $firstpageid = $valpage->id; + } + if ($object->fk_default_home && $key == $object->fk_default_home) { + $homepageid = $valpage->id; + } } $pageid = ($homepageid ? $homepageid : $firstpageid); // We choose home page and if not defined yet, we take first page } @@ -267,9 +305,15 @@ $manifestjsoncontentdefault .= '{ $listofpages = array(); $algo = ''; -if (GETPOST('optionmeta')) $algo .= 'meta'; -if (GETPOST('optioncontent')) $algo .= 'content'; -if (GETPOST('optionsitefiles')) $algo .= 'sitefiles'; +if (GETPOST('optionmeta')) { + $algo .= 'meta'; +} +if (GETPOST('optioncontent')) { + $algo .= 'content'; +} +if (GETPOST('optionsitefiles')) { + $algo .= 'sitefiles'; +} if (empty($sortfield)) { if ($action == 'file_manager') { @@ -301,52 +345,62 @@ $permissiontodelete = $user->rights->website->delete; */ // Protections -if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x')) -{ +if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x')) { $action = 'preview'; // To avoid to make an action on another page or another site when we click on button to select another site or page. } -if (GETPOST('refreshsite', 'alpha') || GETPOST('refreshsite.x', 'alpha') || GETPOST('refreshsite_x', 'alpha')) // If we change the site, we reset the pageid and cancel addsite action. -{ - if ($action == 'addsite') $action = 'preview'; - if ($action == 'updatesource') $action = 'preview'; +if (GETPOST('refreshsite', 'alpha') || GETPOST('refreshsite.x', 'alpha') || GETPOST('refreshsite_x', 'alpha')) { // If we change the site, we reset the pageid and cancel addsite action. + if ($action == 'addsite') { + $action = 'preview'; + } + if ($action == 'updatesource') { + $action = 'preview'; + } $pageid = $object->fk_default_home; - if (empty($pageid)) - { + if (empty($pageid)) { $array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl'); - if (!is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); + if (!is_array($array) && $array < 0) { + dol_print_error('', $objectpage->error, $objectpage->errors); + } $atleastonepage = (is_array($array) && count($array) > 0); $firstpageid = 0; $homepageid = 0; - foreach ($array as $key => $valpage) - { - if (empty($firstpageid)) $firstpageid = $valpage->id; - if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid = $valpage->id; + foreach ($array as $key => $valpage) { + if (empty($firstpageid)) { + $firstpageid = $valpage->id; + } + if ($object->fk_default_home && $key == $object->fk_default_home) { + $homepageid = $valpage->id; + } } $pageid = ($homepageid ? $homepageid : $firstpageid); // We choose home page and if not defined yet, we take first page } } -if (GETPOST('refreshpage', 'alpha') && !in_array($action, array('updatecss'))) $action = 'preview'; +if (GETPOST('refreshpage', 'alpha') && !in_array($action, array('updatecss'))) { + $action = 'preview'; +} if ($cancel && $action == 'renamefile') { $cancel = ''; } // Cancel -if ($cancel) -{ +if ($cancel) { $action = 'preview'; - if ($backtopage) - { + if ($backtopage) { header("Location: ".$backtopage); exit; } } $savbacktopage = $backtopage; -$backtopage = $_SERVER["PHP_SELF"].'?file_manager=1&website='.$websitekey.'&pageid='.$pageid.(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : ''); // used after a confirm_deletefile into actions_linkedfiles.inc.php -if ($sortfield) $backtopage .= '&sortfield='.$sortfield; -if ($sortorder) $backtopage .= '&sortorder='.$sortorder; +$backtopage = $_SERVER["PHP_SELF"].'?file_manager=1&website='.urlencode($websitekey).'&pageid='.urlencode($pageid).(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : ''); // used after a confirm_deletefile into actions_linkedfiles.inc.php +if ($sortfield) { + $backtopage .= '&sortfield='.urlencode($sortfield); +} +if ($sortorder) { + $backtopage .= '&sortorder='.urlencode($sortorder); +} include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; $backtopage = $savbacktopage; @@ -354,43 +408,37 @@ if ($action == 'renamefile') { // Must be after include DOL_DOCUMENT_ROOT.'/core $action = 'file_manager'; } -if ($action == 'seteditinline') -{ +if ($action == 'seteditinline') { dolibarr_set_const($db, 'WEBSITE_EDITINLINE', 1); setEventMessages($langs->trans("FeatureNotYetAvailable"), null, 'warnings'); - dolibarr_set_const($db, 'WEBSITE_SUBCONTAINERSINLINE', 0); // Force disable of 'Include dynamic content' + //dolibarr_set_const($db, 'WEBSITE_SUBCONTAINERSINLINE', 0); // Force disable of 'Include dynamic content' header("Location: ".$_SERVER["PHP_SELF"].'?website='.GETPOST('website', 'alphanohtml').'&pageid='.GETPOST('pageid', 'int')); exit; } -if ($action == 'unseteditinline') -{ +if ($action == 'unseteditinline') { dolibarr_del_const($db, 'WEBSITE_EDITINLINE'); header("Location: ".$_SERVER["PHP_SELF"].'?website='.GETPOST('website', 'alphanohtml').'&pageid='.GETPOST('pageid', 'int')); exit; } -if ($action == 'setshowsubcontainers') -{ +if ($action == 'setshowsubcontainers') { dolibarr_set_const($db, 'WEBSITE_SUBCONTAINERSINLINE', 1); - dolibarr_set_const($db, 'WEBSITE_EDITINLINE', 0); // Force disable of edit inline + //dolibarr_set_const($db, 'WEBSITE_EDITINLINE', 0); // Force disable of edit inline header("Location: ".$_SERVER["PHP_SELF"].'?website='.GETPOST('website', 'alphanohtml').'&pageid='.GETPOST('pageid', 'int')); exit; } -if ($action == 'unsetshowsubcontainers') -{ +if ($action == 'unsetshowsubcontainers') { dolibarr_del_const($db, 'WEBSITE_SUBCONTAINERSINLINE'); header("Location: ".$_SERVER["PHP_SELF"].'?website='.GETPOST('website', 'alphanohtml').'&pageid='.GETPOST('pageid', 'int')); exit; } -if ($massaction == 'replace' && GETPOST('confirmmassaction', 'alpha') && !$searchkey) -{ +if ($massaction == 'replace' && GETPOST('confirmmassaction', 'alpha') && !$searchkey) { $action = 'replacesite'; $massaction = ''; } // Set category -if ($massaction == 'setcategory' && GETPOST('confirmmassaction', 'alpha') && $usercanedit) -{ +if ($massaction == 'setcategory' && GETPOST('confirmmassaction', 'alpha') && $usercanedit) { $error = 0; $nbupdate = 0; @@ -429,17 +477,14 @@ if ($massaction == 'setcategory' && GETPOST('confirmmassaction', 'alpha') && $us } // Replacement of string into pages -if ($massaction == 'replace' && GETPOST('confirmmassaction', 'alpha')) -{ +if ($massaction == 'replace' && GETPOST('confirmmassaction', 'alpha')) { $replacestring = GETPOST('replacestring', 'none'); if (empty($user->rights->website->writephp)) { setEventMessages("NotAllowedToAddDynamicContent", null, 'errors'); - } - elseif (!$replacestring) { + } elseif (!$replacestring) { setEventMessages("ErrorReplaceStringEmpty", null, 'errors'); - } - else { + } else { $nbreplacement = 0; foreach ($toselect as $keyselected) { @@ -461,15 +506,13 @@ if ($massaction == 'replace' && GETPOST('confirmmassaction', 'alpha')) // Save page alias $result = dolSavePageAlias($filealias, $object, $objectpage); - if (!$result) - { + if (!$result) { setEventMessages('Failed to write file '.basename($filealias), null, 'errors'); } // Save page of content $result = dolSavePageContent($filetpl, $object, $objectpage); - if ($result) - { + if ($result) { $nbreplacement++; //var_dump($objectpage->content);exit; $objectpage->update($user); @@ -524,31 +567,26 @@ if ($action == 'adddir' && $permtouploadfile) */ // Add site -if ($action == 'addsite') -{ +if ($action == 'addsite') { $db->begin(); - if (GETPOST('virtualhost', 'alpha') && !preg_match('/^http/', GETPOST('virtualhost', 'alpha'))) - { + if (GETPOST('virtualhost', 'alpha') && !preg_match('/^http/', GETPOST('virtualhost', 'alpha'))) { $error++; setEventMessages($langs->trans('ErrorURLMustStartWithHttp', $langs->transnoentitiesnoconv("VirtualHost")), null, 'errors'); } - if (!$error && !GETPOST('WEBSITE_REF', 'alpha')) - { + if (!$error && !GETPOST('WEBSITE_REF', 'alpha')) { $error++; $langs->load("errors"); setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); } - if (!$error && !preg_match('/^[a-z0-9_\-\.]+$/i', GETPOST('WEBSITE_REF', 'alpha'))) - { + if (!$error && !preg_match('/^[a-z0-9_\-\.]+$/i', GETPOST('WEBSITE_REF', 'alpha'))) { $error++; $langs->load("errors"); setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities("Ref")), null, 'errors'); } - if (!$error) - { + if (!$error) { $arrayotherlang = explode(',', GETPOST('WEBSITE_OTHERLANG', 'alphanohtml')); foreach ($arrayotherlang as $key => $val) { $arrayotherlang[$key] = substr(trim($val), 0, 2); // Kept short language code only @@ -562,75 +600,64 @@ if ($action == 'addsite') $tmpobject->virtualhost = GETPOST('virtualhost', 'alpha'); $result = $tmpobject->create($user); - if ($result <= 0) - { + if ($result <= 0) { $error++; setEventMessages($tmpobject->error, $tmpobject->errors, 'errors'); } } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SiteAdded", $object->ref), null, 'mesgs'); $action = ''; header("Location: ".$_SERVER["PHP_SELF"].'?website='.$tmpobject->ref); exit; - } - else { + } else { $db->rollback(); $action = 'createsite'; } - if (!$error) - { + if (!$error) { $action = 'preview'; $id = $object->id; } } // Add page/container -if ($action == 'addcontainer') -{ +if ($action == 'addcontainer') { dol_mkdir($pathofwebsite); $db->begin(); $objectpage->fk_website = $object->id; - if (GETPOSTISSET('fetchexternalurl')) // Fetch from external url - { + if (GETPOSTISSET('fetchexternalurl')) { // Fetch from external url $urltograb = GETPOST('externalurl', 'alpha'); $grabimages = GETPOST('grabimages', 'alpha'); $grabimagesinto = GETPOST('grabimagesinto', 'alpha'); include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; - if (empty($urltograb)) - { + if (empty($urltograb)) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("URL")), null, 'errors'); $action = 'createcontainer'; - } - elseif (!preg_match('/^http/', $urltograb)) - { + } elseif (!preg_match('/^http/', $urltograb)) { $error++; $langs->load("errors"); setEventMessages('Error URL must start with http:// or https://', null, 'errors'); $action = 'createcontainer'; } - if (!$error) - { + if (!$error) { // Clean url to grab, so url can be // http://www.example.com/ or http://www.example.com/dir1/ or http://www.example.com/dir1/aaa $urltograbwithoutdomainandparam = preg_replace('/^https?:\/\/[^\/]+\/?/i', '', $urltograb); //$urltograbwithoutdomainandparam = preg_replace('/^file:\/\/[^\/]+\/?/i', '', $urltograb); $urltograbwithoutdomainandparam = preg_replace('/\?.*$/', '', $urltograbwithoutdomainandparam); - if (empty($urltograbwithoutdomainandparam) && !preg_match('/\/$/', $urltograb)) - { + if (empty($urltograbwithoutdomainandparam) && !preg_match('/\/$/', $urltograb)) { $urltograb .= '/'; } $pageurl = dol_sanitizeFileName(preg_replace('/[\/\.]/', '-', preg_replace('/\/+$/', '', $urltograbwithoutdomainandparam))); @@ -642,34 +669,27 @@ if ($action == 'addcontainer') } // Check pageurl is not already used - if ($pageurl) - { + if ($pageurl) { $tmpwebsitepage = new WebsitePage($db); $result = $tmpwebsitepage->fetch(0, $object->id, $pageurl); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans("AliasPageAlreadyExists", $pageurl), null, 'errors'); $error++; $action = 'createcontainer'; } } - if (!$error) - { + if (!$error) { $tmp = getURLContent($urltograb); - if ($tmp['curl_error_no']) - { + if ($tmp['curl_error_no']) { $error++; setEventMessages('Error getting '.$urltograb.': '.$tmp['curl_error_msg'], null, 'errors'); $action = 'createcontainer'; - } - elseif ($tmp['http_code'] != '200') - { + } elseif ($tmp['http_code'] != '200') { $error++; setEventMessages('Error getting '.$urltograb.': '.$tmp['http_code'], null, 'errors'); $action = 'createcontainer'; - } - else { + } else { // Remove comments $tmp['content'] = removeHtmlComment($tmp['content']); @@ -679,36 +699,34 @@ if ($action == 'addcontainer') $head = $regs[1]; $objectpage->type_container = 'page'; - $objectpage->pageurl = $pageurl; - if (empty($objectpage->pageurl)) - { - $tmpdomain = getDomainFromURL($urltograb); - $objectpage->pageurl = $tmpdomain.'-home'; - } + $objectpage->pageurl = $pageurl; + if (empty($objectpage->pageurl)) { + $tmpdomain = getDomainFromURL($urltograb); + $objectpage->pageurl = $tmpdomain.'-home'; + } - $objectpage->aliasalt = ''; + $objectpage->aliasalt = ''; - if (preg_match('/^(\d+)\-/', basename($urltograb), $regs)) $objectpage->aliasalt = $regs[1]; + if (preg_match('/^(\d+)\-/', basename($urltograb), $regs)) { + $objectpage->aliasalt = $regs[1]; + } - $regtmp = array(); - if (preg_match('/<title>(.*)<\/title>/ims', $head, $regtmp)) - { + $regtmp = array(); + if (preg_match('/<title>(.*)<\/title>/ims', $head, $regtmp)) { $objectpage->title = $regtmp[1]; } - if (preg_match('/<meta name="title"[^"]+content="([^"]+)"/ims', $head, $regtmp)) - { - if (empty($objectpage->title)) $objectpage->title = $regtmp[1]; // If title not found into <title>, we get it from <meta title> + if (preg_match('/<meta name="title"[^"]+content="([^"]+)"/ims', $head, $regtmp)) { + if (empty($objectpage->title)) { + $objectpage->title = $regtmp[1]; // If title not found into <title>, we get it from <meta title> + } } - if (preg_match('/<meta name="description"[^"]+content="([^"]+)"/ims', $head, $regtmp)) - { + if (preg_match('/<meta name="description"[^"]+content="([^"]+)"/ims', $head, $regtmp)) { $objectpage->description = $regtmp[1]; } - if (preg_match('/<meta name="keywords"[^"]+content="([^"]+)"/ims', $head, $regtmp)) - { + if (preg_match('/<meta name="keywords"[^"]+content="([^"]+)"/ims', $head, $regtmp)) { $objectpage->keywords = $regtmp[1]; } - if (preg_match('/<html\s+lang="([^"]+)"/ims', $tmp['content'], $regtmp)) - { + if (preg_match('/<html\s+lang="([^"]+)"/ims', $tmp['content'], $regtmp)) { $tmplang = explode('-', $regtmp[1]); $objectpage->lang = $tmplang[0].($tmplang[1] ? '_'.strtoupper($tmplang[1]) : ''); } @@ -749,22 +767,18 @@ if ($action == 'addcontainer') // We grab files found into <script> tags preg_match_all('/<script([^\.>]+)src=["\']([^"\'>]+)["\']([^>]*)><\/script>/i', $objectpage->htmlheader, $regs); $errorforsubresource = 0; - foreach ($regs[0] as $key => $val) - { + foreach ($regs[0] as $key => $val) { dol_syslog("We will grab the script resource found into script tag ".$regs[2][$key]); $linkwithoutdomain = $regs[2][$key]; - if (preg_match('/^\//', $regs[2][$key])) - { + if (preg_match('/^\//', $regs[2][$key])) { $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot - } - else { + } else { $urltograbbis = $urltograbdirwithoutslash.'/'.$regs[2][$key]; // We use dir of grabbed file } //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key]; - if (preg_match('/^http/', $regs[2][$key])) - { + if (preg_match('/^http/', $regs[2][$key])) { $urltograbbis = $regs[2][$key]; $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]); //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; @@ -776,17 +790,19 @@ if ($action == 'addcontainer') // Test if this is an external URL of grabbed web site. If yes, we do not load resource $domaintograb = getDomainFromURL($urltograbdirwithoutslash); $domaintograbbis = getDomainFromURL($urltograbbis); - if ($domaintograb != $domaintograbbis) continue; + if ($domaintograb != $domaintograbbis) { + continue; + } /* - $tmpgeturl = getURLContent($urltograbbis); - if ($tmpgeturl['curl_error_no']) - { - $error++; - setEventMessages('Error getting script url '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors'); - $errorforsubresource++; - $action='createcontainer'; - } + $tmpgeturl = getURLContent($urltograbbis); + if ($tmpgeturl['curl_error_no']) + { + $error++; + setEventMessages('Error getting script url '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors'); + $errorforsubresource++; + $action='createcontainer'; + } elseif ($tmpgeturl['http_code'] != '200') { $error++; @@ -795,15 +811,15 @@ if ($action == 'addcontainer') $action='createcontainer'; } else - { - dol_mkdir(dirname($filetosave)); + { + dol_mkdir(dirname($filetosave)); - $fp = fopen($filetosave, "w"); - fputs($fp, $tmpgeturl['content']); - fclose($fp); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($file, octdec($conf->global->MAIN_UMASK)); - } + $fp = fopen($filetosave, "w"); + fputs($fp, $tmpgeturl['content']); + fclose($fp); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($file, octdec($conf->global->MAIN_UMASK)); + } */ //$filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; @@ -817,22 +833,18 @@ if ($action == 'addcontainer') preg_match_all('/<link([^\.>]+)href=["\']([^"\'>]+\.css[^"\'>]*)["\']([^>]*)>/i', $objectpage->htmlheader, $regs); $errorforsubresource = 0; - foreach ($regs[0] as $key => $val) - { + foreach ($regs[0] as $key => $val) { dol_syslog("We will grab the css resources found into link tag ".$regs[2][$key]); $linkwithoutdomain = $regs[2][$key]; - if (preg_match('/^\//', $regs[2][$key])) - { + if (preg_match('/^\//', $regs[2][$key])) { $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot - } - else { + } else { $urltograbbis = $urltograbdirwithoutslash.'/'.$regs[2][$key]; // We use dir of grabbed file } //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key]; - if (preg_match('/^http/', $regs[2][$key])) - { + if (preg_match('/^http/', $regs[2][$key])) { $urltograbbis = $regs[2][$key]; $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]); //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; @@ -844,24 +856,22 @@ if ($action == 'addcontainer') // Test if this is an external URL of grabbed web site. If yes, we do not load resource $domaintograb = getDomainFromURL($urltograbdirwithoutslash); $domaintograbbis = getDomainFromURL($urltograbbis); - if ($domaintograb != $domaintograbbis) continue; + if ($domaintograb != $domaintograbbis) { + continue; + } $tmpgeturl = getURLContent($urltograbbis); - if ($tmpgeturl['curl_error_no']) - { + if ($tmpgeturl['curl_error_no']) { $errorforsubresource++; setEventMessages('Error getting link tag url '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors'); dol_syslog('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg']); $action = 'createcontainer'; - } - elseif ($tmpgeturl['http_code'] != '200') - { + } elseif ($tmpgeturl['http_code'] != '200') { $errorforsubresource++; setEventMessages('Error getting link tag url '.$urltograbbis.': '.$tmpgeturl['http_code'], null, 'errors'); dol_syslog('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg']); $action = 'createcontainer'; - } - else { + } else { // Clean some comment //$tmpgeturl['content'] = dol_string_is_good_iso($tmpgeturl['content'], 1); //$tmpgeturl['content'] = utf8_encode(utf8_decode($tmpgeturl['content'])); @@ -959,7 +969,9 @@ if ($action == 'addcontainer') $objectpage->fk_page = $pageidfortranslation; $sample = GETPOST('sample', 'alpha'); - if (empty($sample)) $sample = 'empty'; + if (empty($sample)) { + $sample = 'empty'; + } $pathtosample = DOL_DOCUMENT_ROOT.'/website/samples/page-sample-'.dol_sanitizeFileName($sample).'.html'; @@ -967,38 +979,31 @@ if ($action == 'addcontainer') $objectpage->content = make_substitutions(@file_get_contents($pathtosample), $substitutionarray); } - if (!$error) - { - if (empty($objectpage->pageurl)) - { + if (!$error) { + if (empty($objectpage->pageurl)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); $error++; $action = 'createcontainer'; - } - elseif (!preg_match('/^[a-z0-9\-\_]+$/i', $objectpage->pageurl)) - { + } elseif (!preg_match('/^[a-z0-9\-\_]+$/i', $objectpage->pageurl)) { $langs->load("errors"); setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors'); $error++; $action = 'createcontainer'; } - if (empty($objectpage->title)) - { + if (empty($objectpage->title)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_TITLE")), null, 'errors'); $error++; $action = 'createcontainer'; } - if ($objectpage->fk_page > 0 && empty($objectpage->lang)) - { + if ($objectpage->fk_page > 0 && empty($objectpage->lang)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorLanguageRequiredIfPageIsTranslationOfAnother"), null, 'errors'); $error++; $action = 'createcontainer'; } - if ($objectpage->fk_page > 0 && !empty($objectpage->lang)) - { + if ($objectpage->fk_page > 0 && !empty($objectpage->lang)) { if ($objectpage->lang == $website->lang) { $langs->load("errors"); setEventMessages($langs->trans("ErrorLanguageMustNotBeSourceLanguageIfPageIsTranslationOfAnother"), null, 'errors'); @@ -1008,8 +1013,7 @@ if ($action == 'addcontainer') } } - if (!$error) - { + if (!$error) { $pageid = $objectpage->create($user); if ($pageid <= 0) { $error++; @@ -1022,8 +1026,7 @@ if ($action == 'addcontainer') // Website categories association $categoriesarray = GETPOST('categories', 'array'); $result = $objectpage->setCategories($categoriesarray); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } @@ -1034,8 +1037,7 @@ if ($action == 'addcontainer') if (empty($object->fk_default_home)) { $object->fk_default_home = $pageid; $res = $object->update($user); - if ($res <= 0) - { + if ($res <= 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } else { @@ -1044,50 +1046,44 @@ if ($action == 'addcontainer') // Generate the index.php page (to be the home page) and wrapper.php file $result = dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper); - if ($result <= 0) setEventMessages('Failed to write file '.$fileindex, null, 'errors'); + if ($result <= 0) { + setEventMessages('Failed to write file '.$fileindex, null, 'errors'); + } } } } - if (!$error) - { - if (!empty($objectpage->content)) - { + if (!$error) { + if (!empty($objectpage->content)) { $filealias = $pathofwebsite.'/'.$objectpage->pageurl.'.php'; $filetpl = $pathofwebsite.'/page'.$objectpage->id.'.tpl.php'; // Save page alias $result = dolSavePageAlias($filealias, $object, $objectpage); - if (!$result) - { + if (!$result) { setEventMessages('Failed to write file '.basename($filealias), null, 'errors'); } // Save page of content $result = dolSavePageContent($filetpl, $object, $objectpage); - if ($result) - { + if ($result) { setEventMessages($langs->trans("Saved"), null, 'mesgs'); - } - else { + } else { setEventMessages('Failed to write file '.$filetpl, null, 'errors'); $action = 'createcontainer'; } } } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); $action = ''; - } - else { + } else { $db->rollback(); } - if (!$error) - { + if (!$error) { $pageid = $objectpage->id; // To generate the CSS, robot and htmlheader file. @@ -1095,64 +1091,54 @@ if ($action == 'addcontainer') // Check symlink to medias and restore it if ko $pathtomedias = DOL_DATA_ROOT.'/medias'; $pathtomediasinwebsite = $pathofwebsite.'/medias'; - if (!is_link(dol_osencode($pathtomediasinwebsite))) - { + if (!is_link(dol_osencode($pathtomediasinwebsite))) { dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists $result = symlink($pathtomedias, $pathtomediasinwebsite); } // Now generate the master.inc.php page if it does not exists yet - if (!dol_is_file($filemaster)) - { + if (!dol_is_file($filemaster)) { $result = dolSaveMasterFile($filemaster); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filemaster, null, 'errors'); } } - if (!dol_is_file($filehtmlheader)) - { + if (!dol_is_file($filehtmlheader)) { $htmlheadercontent = "<html>\n"; $htmlheadercontent .= $htmlheadercontentdefault; $htmlheadercontent .= "</html>"; $result = dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent); } - if (!dol_is_file($filecss)) - { + if (!dol_is_file($filecss)) { $csscontent = "/* CSS content (all pages) */\nbody.bodywebsite { margin: 0; font-family: 'Open Sans', sans-serif; }\n.bodywebsite h1 { margin-top: 0; margin-bottom: 0; padding: 10px;}"; $result = dolSaveCssFile($filecss, $csscontent); } - if (!dol_is_file($filejs)) - { + if (!dol_is_file($filejs)) { $jscontent = "/* JS content (all pages) */\n"; $result = dolSaveJsFile($filejs, $jscontent); } - if (!dol_is_file($filerobot)) - { + if (!dol_is_file($filerobot)) { $robotcontent = "# Robot file. Generated with Dolibarr\nUser-agent: *\nAllow: /public/\nDisallow: /administrator/"; $result = dolSaveRobotFile($filerobot, $robotcontent); } - if (!dol_is_file($filehtaccess)) - { + if (!dol_is_file($filehtaccess)) { $htaccesscontent = "# Order allow,deny\n# Deny from all"; $result = dolSaveHtaccessFile($filehtaccess, $htaccesscontent); } - if (!dol_is_file($filemanifestjson)) - { + if (!dol_is_file($filemanifestjson)) { $manifestjsoncontent = ""; $result = dolSaveManifestJson($filemanifestjson, $manifestjsoncontent); } - if (!dol_is_file($filereadme)) - { + if (!dol_is_file($filereadme)) { $readmecontent = "Website generated by Dolibarr ERP CRM"; $result = dolSaveReadme($filereadme, $readmecontent); } @@ -1162,8 +1148,7 @@ if ($action == 'addcontainer') } // Delete site -if ($action == 'confirm_deletesite' && $confirm == 'yes') -{ +if ($action == 'confirm_deletesite' && $confirm == 'yes') { $error = 0; $db->begin(); @@ -1171,40 +1156,33 @@ if ($action == 'confirm_deletesite' && $confirm == 'yes') $res = $object->fetch(GETPOST('id', 'int')); $website = $object; - if ($res > 0) - { + if ($res > 0) { $res = $object->delete($user); - if ($res <= 0) - { + if ($res <= 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } } - if (!$error) - { - if (GETPOST('delete_also_js', 'alpha') == 'on') - { + if (!$error) { + if (GETPOST('delete_also_js', 'alpha') == 'on') { $pathofwebsitejs = DOL_DATA_ROOT.'/medias/js/'.$object->ref; dol_delete_dir_recursive($pathofwebsitejs); } - if (GETPOST('delete_also_medias', 'alpha') == 'on') - { + if (GETPOST('delete_also_medias', 'alpha') == 'on') { $pathofwebsitemedias = DOL_DATA_ROOT.'/medias/image/'.$object->ref; dol_delete_dir_recursive($pathofwebsitemedias); } } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SiteDeleted", $object->ref), null, 'mesgs'); header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id); exit; - } - else { + } else { $db->rollback(); dol_print_error($db); } @@ -1221,25 +1199,21 @@ if (GETPOSTISSET('pageid') && $action == 'delete' && $permissiontodelete) { $res = $objectpage->fetch($pageid, $object->id); - if ($res > 0) - { + if ($res > 0) { $res = $objectpage->delete($user); - if ($res <= 0) - { + if ($res <= 0) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); } } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $websitekey), null, 'mesgs'); header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey); exit; - } - else { + } else { $db->rollback(); dol_print_error($db); } @@ -1250,25 +1224,23 @@ if (!GETPOSTISSET('pageid')) { // Add part of code from actions_massactions.inc.php // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before) - if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) - { + if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) { $db->begin(); $objecttmp = new $objectclass($db); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $result = $objecttmp->delete($user); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -1276,10 +1248,12 @@ if (!GETPOSTISSET('pageid')) { } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -1302,29 +1276,23 @@ if (!GETPOSTISSET('pageid')) { } // Update css Update site properties -if ($action == 'updatecss') -{ +if ($action == 'updatecss') { // If we tried to reload another site/page, we stay on editcss mode. - if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x')) - { + if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x')) { $action = 'editcss'; - } - else { + } else { $res = $object->fetch(0, $websitekey); $website = $object; - if (GETPOSTISSET('virtualhost')) - { + if (GETPOSTISSET('virtualhost')) { $tmpvirtualhost = preg_replace('/\/$/', '', GETPOST('virtualhost', 'alpha')); - if ($tmpvirtualhost && !preg_match('/^http/', $tmpvirtualhost)) - { + if ($tmpvirtualhost && !preg_match('/^http/', $tmpvirtualhost)) { $error++; setEventMessages($langs->trans('ErrorURLMustStartWithHttp', $langs->transnoentitiesnoconv("VirtualHost")), null, 'errors'); $action = 'editcss'; } - if (!$error) - { + if (!$error) { $arrayotherlang = explode(',', GETPOST('WEBSITE_OTHERLANG', 'alphanohtml')); foreach ($arrayotherlang as $key => $val) { $arrayotherlang[$key] = substr(trim($val), 0, 2); // Kept short language code only @@ -1336,8 +1304,7 @@ if ($action == 'updatecss') $object->use_manifest = GETPOST('use_manifest', 'alpha'); $result = $object->update($user); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); $action = 'editcss'; @@ -1345,8 +1312,7 @@ if ($action == 'updatecss') } } - if (!$error) - { + if (!$error) { // Save master.inc.php file dol_syslog("Save master file ".$filemaster); @@ -1354,8 +1320,7 @@ if ($action == 'updatecss') // Now generate the master.inc.php page $result = dolSaveMasterFile($filemaster); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filemaster, null, 'errors'); } @@ -1365,26 +1330,25 @@ if ($action == 'updatecss') $htmlheadercontent = ''; /* We disable php code since htmlheader is never executed as an include but only read by fgets_content. - $htmlheadercontent.= "<?php // BEGIN PHP\n"; - $htmlheadercontent.= '$websitekey=basename(__DIR__);'."\n"; - $htmlheadercontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load env if not already loaded"."\n"; - $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; - $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; - $htmlheadercontent.= "ob_start();\n"; - // $htmlheadercontent.= "header('Content-type: text/html');\n"; // Not required. htmlheader.html is never call as a standalone page - $htmlheadercontent.= "// END PHP ?>\n";*/ + $htmlheadercontent.= "<?php // BEGIN PHP\n"; + $htmlheadercontent.= '$websitekey=basename(__DIR__);'."\n"; + $htmlheadercontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load env if not already loaded"."\n"; + $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $htmlheadercontent.= "ob_start();\n"; + // $htmlheadercontent.= "header('Content-type: text/html');\n"; // Not required. htmlheader.html is never call as a standalone page + $htmlheadercontent.= "// END PHP ?>\n";*/ $htmlheadercontent .= preg_replace(array('/<html>\n*/ims', '/<\/html>\n*/ims'), array('', ''), GETPOST('WEBSITE_HTML_HEADER', 'none')); /*$htmlheadercontent.= "\n".'<?php // BEGIN PHP'."\n"; - $htmlheadercontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n"; - $htmlheadercontent.= "// END PHP ?>"."\n";*/ + $htmlheadercontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n"; + $htmlheadercontent.= "// END PHP ?>"."\n";*/ $htmlheadercontent = trim($htmlheadercontent)."\n"; $result = dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filehtmlheader, null, 'errors'); } @@ -1414,8 +1378,7 @@ if ($action == 'updatecss') dol_syslog("Save css content into ".$filecss); $result = dolSaveCssFile($filecss, $csscontent); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filecss, null, 'errors'); } @@ -1441,8 +1404,7 @@ if ($action == 'updatecss') $jscontent .= "// END PHP ?>\n"; $result = dolSaveJsFile($filejs, $jscontent); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filejs, null, 'errors'); } @@ -1452,24 +1414,23 @@ if ($action == 'updatecss') $robotcontent = ''; /*$robotcontent.= "<?php // BEGIN PHP\n"; - $robotcontent.= '$websitekey=basename(__DIR__);'."\n"; - $robotcontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load env if not already loaded"."\n"; - $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; - $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; - $robotcontent.= "ob_start();\n"; - $robotcontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; - $robotcontent.= "header('Content-type: text/css');\n"; - $robotcontent.= "// END PHP ?>\n";*/ + $robotcontent.= '$websitekey=basename(__DIR__);'."\n"; + $robotcontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load env if not already loaded"."\n"; + $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $robotcontent.= "ob_start();\n"; + $robotcontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; + $robotcontent.= "header('Content-type: text/css');\n"; + $robotcontent.= "// END PHP ?>\n";*/ $robotcontent .= trim(GETPOST('WEBSITE_ROBOT', 'restricthtml'))."\n"; /*$robotcontent.= "\n".'<?php // BEGIN PHP'."\n"; - $robotcontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "robot");'."\n"; - $robotcontent.= "// END PHP ?>"."\n";*/ + $robotcontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "robot");'."\n"; + $robotcontent.= "// END PHP ?>"."\n";*/ $result = dolSaveRobotFile($filerobot, $robotcontent); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filerobot, null, 'errors'); } @@ -1480,87 +1441,81 @@ if ($action == 'updatecss') $htaccesscontent .= trim(GETPOST('WEBSITE_HTACCESS', 'restricthtml'))."\n"; $result = dolSaveHtaccessFile($filehtaccess, $htaccesscontent); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filehtaccess, null, 'errors'); } - // manifest.json file - $manifestjsoncontent = ''; + // manifest.json file + $manifestjsoncontent = ''; - $manifestjsoncontent .= "<?php // BEGIN PHP\n"; - $manifestjsoncontent .= '$websitekey=basename(__DIR__);'."\n"; - $manifestjsoncontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file. - $manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; - $manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; - $manifestjsoncontent .= "ob_start();\n"; - $manifestjsoncontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; - $manifestjsoncontent .= "header('Content-type: application/manifest+json');\n"; - $manifestjsoncontent .= "// END PHP ?>\n"; + $manifestjsoncontent .= "<?php // BEGIN PHP\n"; + $manifestjsoncontent .= '$websitekey=basename(__DIR__);'."\n"; + $manifestjsoncontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file. + $manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $manifestjsoncontent .= "ob_start();\n"; + $manifestjsoncontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; + $manifestjsoncontent .= "header('Content-type: application/manifest+json');\n"; + $manifestjsoncontent .= "// END PHP ?>\n"; - $manifestjsoncontent .= trim(GETPOST('WEBSITE_MANIFEST_JSON', 'none'))."\n"; + $manifestjsoncontent .= trim(GETPOST('WEBSITE_MANIFEST_JSON', 'none'))."\n"; - $manifestjsoncontent .= '<?php // BEGIN PHP'."\n"; - $manifestjsoncontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n"; - $manifestjsoncontent .= "// END PHP ?>\n"; + $manifestjsoncontent .= '<?php // BEGIN PHP'."\n"; + $manifestjsoncontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n"; + $manifestjsoncontent .= "// END PHP ?>\n"; - $result = dolSaveManifestJson($filemanifestjson, $manifestjsoncontent); - if (!$result) - { - $error++; - setEventMessages('Failed to write file '.$filemanifestjson, null, 'errors'); - } + $result = dolSaveManifestJson($filemanifestjson, $manifestjsoncontent); + if (!$result) { + $error++; + setEventMessages('Failed to write file '.$filemanifestjson, null, 'errors'); + } - // README.md file - $readmecontent = ''; + // README.md file + $readmecontent = ''; - /*$readmecontent.= "<?php // BEGIN PHP\n"; - $readmecontent.= '$websitekey=basename(__DIR__);'."\n"; - $readmecontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded"."\n"; // For the css, we need to set path of master using the dirname of css file. - $readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; - $readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; - $readmecontent.= "ob_start();\n"; - $readmecontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; - $readmecontent.= "header('Content-type: application/manifest+json');\n"; - $readmecontent.= "// END PHP ?>\n";*/ + /*$readmecontent.= "<?php // BEGIN PHP\n"; + $readmecontent.= '$websitekey=basename(__DIR__);'."\n"; + $readmecontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded"."\n"; // For the css, we need to set path of master using the dirname of css file. + $readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $readmecontent.= "ob_start();\n"; + $readmecontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; + $readmecontent.= "header('Content-type: application/manifest+json');\n"; + $readmecontent.= "// END PHP ?>\n";*/ - $readmecontent .= trim(GETPOST('WEBSITE_README', 'restricthtml'))."\n"; + $readmecontent .= trim(GETPOST('WEBSITE_README', 'restricthtml'))."\n"; - /*$readmecontent.= '<?php // BEGIN PHP'."\n"; - $readmecontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n"; - $readmecontent.= "// END PHP ?>"."\n";*/ + /*$readmecontent.= '<?php // BEGIN PHP'."\n"; + $readmecontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n"; + $readmecontent.= "// END PHP ?>"."\n";*/ - $result = dolSaveReadme($filereadme, $readmecontent); - if (!$result) - { - $error++; - setEventMessages('Failed to write file '.$filereadme, null, 'errors'); - } + $result = dolSaveReadme($filereadme, $readmecontent); + if (!$result) { + $error++; + setEventMessages('Failed to write file '.$filereadme, null, 'errors'); + } - // Save wrapper.php + // Save wrapper.php $result = dolSaveIndexPage($pathofwebsite, '', '', $filewrapper); // Message if no error - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("Saved"), null, 'mesgs'); } - if (!GETPOSTISSET('updateandstay')) // If we click on "Save And Stay", we don not make the redirect - { + if (!GETPOSTISSET('updateandstay')) { // If we click on "Save And Stay", we don not make the redirect $action = 'preview'; - if ($backtopage) - { + if ($backtopage) { + $backtopage = preg_replace('/searchstring=[^&]*/', '', $backtopage); // Clean backtopage url header("Location: ".$backtopage); exit; } - } - else { + } else { $action = 'editcss'; } } @@ -1568,22 +1523,19 @@ if ($action == 'updatecss') } // Update page -if ($action == 'setashome') -{ +if ($action == 'setashome') { $db->begin(); $object->fetch(0, $websitekey); $website = $object; $object->fk_default_home = $pageid; $res = $object->update($user); - if (! ($res > 0)) - { + if (! ($res > 0)) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } - if (!$error) - { + if (!$error) { $db->commit(); $filetpl = $pathofwebsite.'/page'.$pageid.'.tpl.php'; @@ -1591,19 +1543,20 @@ if ($action == 'setashome') // Generate the index.php page to be the home page $result = dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper); - if ($result) setEventMessages($langs->trans("Saved"), null, 'mesgs'); - else setEventMessages('Failed to write file '.$fileindex, null, 'errors'); + if ($result) { + setEventMessages($langs->trans("Saved"), null, 'mesgs'); + } else { + setEventMessages('Failed to write file '.$fileindex, null, 'errors'); + } $action = 'preview'; - } - else { + } else { $db->rollback(); } } // Update page properties (meta) -if ($action == 'updatemeta') -{ +if ($action == 'updatemeta') { $db->begin(); $result = $object->fetch(0, $websitekey); @@ -1612,8 +1565,7 @@ if ($action == 'updatemeta') $objectpage->fk_website = $object->id; // Check parameters - if (!preg_match('/^[a-z0-9\-\_]+$/i', GETPOST('WEBSITE_PAGENAME', 'alpha'))) - { + if (!preg_match('/^[a-z0-9\-\_]+$/i', GETPOST('WEBSITE_PAGENAME', 'alpha'))) { $error++; $langs->load("errors"); setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors'); @@ -1621,38 +1573,32 @@ if ($action == 'updatemeta') } $res = $objectpage->fetch($pageid, $object->id); - if ($res <= 0) - { + if ($res <= 0) { $error++; setEventMessages('Page not found '.$objectpage->error, $objectpage->errors, 'errors'); } // Check alias not exists - if (!$error && GETPOST('WEBSITE_PAGENAME', 'alpha')) - { + if (!$error && GETPOST('WEBSITE_PAGENAME', 'alpha')) { $websitepagetemp = new WebsitePage($db); $result = $websitepagetemp->fetch(-1 * $objectpage->id, $object->id, GETPOST('WEBSITE_PAGENAME', 'alpha')); - if ($result < 0) - { + if ($result < 0) { $error++; $langs->load("errors"); setEventMessages($websitepagetemp->error, $websitepagetemp->errors, 'errors'); $action = 'editmeta'; } - if ($result > 0) - { + if ($result > 0) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorAPageWithThisNameOrAliasAlreadyExists", $websitepagetemp->pageurl), null, 'errors'); $action = 'editmeta'; } } - if (!$error && GETPOST('WEBSITE_ALIASALT', 'alpha')) - { + if (!$error && GETPOST('WEBSITE_ALIASALT', 'alpha')) { $arrayofaliastotest = explode(',', GETPOST('WEBSITE_ALIASALT', 'alpha')); $websitepagetemp = new WebsitePage($db); - foreach ($arrayofaliastotest as $aliastotest) - { + foreach ($arrayofaliastotest as $aliastotest) { // Disallow alias name pageX (already used to save the page with id) if (preg_match('/^page\d+/i', $aliastotest)) { $error++; @@ -1662,16 +1608,14 @@ if ($action == 'updatemeta') break; } else { $result = $websitepagetemp->fetch(-1 * $objectpage->id, $object->id, $aliastotest); - if ($result < 0) - { + if ($result < 0) { $error++; $langs->load("errors"); setEventMessages($websitepagetemp->error, $websitepagetemp->errors, 'errors'); $action = 'editmeta'; break; } - if ($result > 0) - { + if ($result > 0) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorAPageWithThisNameOrAliasAlreadyExists", $websitepagetemp->pageurl), null, 'errors'); @@ -1682,8 +1626,7 @@ if ($action == 'updatemeta') } } - if (!$error) - { + if (!$error) { $objectpage->old_object = clone $objectpage; $objectpage->title = str_replace(array('<', '>'), '', GETPOST('WEBSITE_TITLE', 'alphanohtml')); @@ -1703,20 +1646,19 @@ if ($action == 'updatemeta') $objectpage->fk_object = GETPOST('WEBSITE_OBJECTID', 'aZ09'); $newdatecreation = dol_mktime(GETPOST('datecreationhour', 'int'), GETPOST('datecreationmin', 'int'), GETPOST('datecreationsec', 'int'), GETPOST('datecreationmonth', 'int'), GETPOST('datecreationday', 'int'), GETPOST('datecreationyear', 'int')); - if ($newdatecreation) $objectpage->date_creation = $newdatecreation; + if ($newdatecreation) { + $objectpage->date_creation = $newdatecreation; + } $res = $objectpage->update($user); - if (!($res > 0)) - { + if (!($res > 0)) { $langs->load("errors"); - if ($db->lasterrno == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($db->lasterrno == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorAPageWithThisNameOrAliasAlreadyExists"), null, 'errors'); $action = 'editmeta'; - } - else { + } else { $error++; $langs->load("errors"); setEventMessages($objectpage->error, $objectpage->errors, 'errors'); @@ -1729,23 +1671,19 @@ if ($action == 'updatemeta') // Website categories association $categoriesarray = GETPOST('categories', 'array'); $result = $objectpage->setCategories($categoriesarray); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } } - if (!$error) - { + if (!$error) { $db->commit(); - } - else { + } else { $db->rollback(); } - if (!$error) - { + if (!$error) { $filemaster = $pathofwebsite.'/master.inc.php'; $fileoldalias = $pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; $filealias = $pathofwebsite.'/'.$objectpage->pageurl.'.php'; @@ -1754,11 +1692,12 @@ if ($action == 'updatemeta') // Now generate the master.inc.php page $result = dolSaveMasterFile($filemaster); - if (!$result) setEventMessages('Failed to write file '.$filemaster, null, 'errors'); + if (!$result) { + setEventMessages('Failed to write file '.$filemaster, null, 'errors'); + } // Now delete the alias.php page - if (!empty($fileoldalias)) - { + if (!empty($fileoldalias)) { dol_syslog("We delete old alias page name=".$fileoldalias." to build a new alias page=".$filealias); dol_delete_file($fileoldalias); @@ -1774,13 +1713,10 @@ if ($action == 'updatemeta') } } // Now delete the alternative alias.php pages - if (!empty($objectpage->old_object->aliasalt)) - { + if (!empty($objectpage->old_object->aliasalt)) { $tmpaltaliases = explode(',', $objectpage->old_object->aliasalt); - if (is_array($tmpaltaliases)) - { - foreach ($tmpaltaliases as $tmpaliasalt) - { + if (is_array($tmpaltaliases)) { + foreach ($tmpaltaliases as $tmpaliasalt) { dol_syslog("We delete old alt alias pages name=".trim($tmpaliasalt)); dol_delete_file($pathofwebsite.'/'.trim($tmpaliasalt).'.php'); @@ -1800,20 +1736,20 @@ if ($action == 'updatemeta') // Save page main alias $result = dolSavePageAlias($filealias, $object, $objectpage); - if (!$result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + if (!$result) { + setEventMessages('Failed to write file '.$filealias, null, 'errors'); + } // Save alt aliases - if (!empty($objectpage->aliasalt)) - { + if (!empty($objectpage->aliasalt)) { $tmpaltaliases = explode(',', $objectpage->aliasalt); - if (is_array($tmpaltaliases)) - { - foreach ($tmpaltaliases as $tmpaliasalt) - { - if (trim($tmpaliasalt)) - { + if (is_array($tmpaltaliases)) { + foreach ($tmpaltaliases as $tmpaliasalt) { + if (trim($tmpaliasalt)) { $filealias = $pathofwebsite.'/'.trim($tmpaliasalt).'.php'; $result = dolSavePageAlias($filealias, $object, $objectpage); - if (!$result) setEventMessages('Failed to write file '.basename($filealias), null, 'errors'); + if (!$result) { + setEventMessages('Failed to write file '.basename($filealias), null, 'errors'); + } } } } @@ -1822,24 +1758,20 @@ if ($action == 'updatemeta') // Save page of content $result = dolSavePageContent($filetpl, $object, $objectpage); - if ($result) - { + if ($result) { setEventMessages($langs->trans("Saved"), null, 'mesgs'); - if (!GETPOSTISSET('updateandstay')) // If we click on "Save And Stay", we do not make the redirect - { + if (!GETPOSTISSET('updateandstay')) { // If we click on "Save And Stay", we do not make the redirect //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey.'&pageid='.$pageid); //exit; $action = 'preview'; - } - else { + } else { $action = 'editmeta'; } - } - else { + } else { setEventMessages('Failed to write file '.$filetpl, null, 'errors'); //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey.'&pageid='.$pageid); - //exit; + //exit; $action = 'preview'; } } @@ -1847,27 +1779,23 @@ if ($action == 'updatemeta') // Update page if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'confirm_createfromclone' || $action == 'confirm_createpagefromclone') - || ($action == 'preview' && (GETPOST('refreshsite') || GETPOST('refreshpage') || GETPOST('preview')))) -{ + || ($action == 'preview' && (GETPOST('refreshsite') || GETPOST('refreshpage') || GETPOST('preview')))) { $object->fetch(0, $websitekey); $website = $object; - if ($action == 'confirm_createfromclone') - { + if ($action == 'confirm_createfromclone') { $db->begin(); $objectnew = new Website($db); $result = $objectnew->createFromClone($user, GETPOST('id', 'int'), GETPOST('siteref', 'aZ09'), (GETPOST('newlang', 'aZ09') ?GETPOST('newlang', 'aZ09') : '')); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($objectnew->error, $objectnew->errors, 'errors'); $action = 'preview'; $db->rollback(); - } - else { + } else { $object = $objectnew; $id = $object->id; $pageid = $object->fk_default_home; @@ -1877,12 +1805,10 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf } } - if ($action == 'confirm_createpagefromclone') - { + if ($action == 'confirm_createpagefromclone') { $istranslation = (GETPOST('is_a_translation', 'aZ09') == 'on' ? 1 : 0); // Protection if it is a translation page - if ($istranslation) - { + if ($istranslation) { if (GETPOST('newlang', 'aZ09') == $objectpage->lang || !GETPOST('newlang', 'aZ09')) { $error++; setEventMessages($langs->trans("LanguageMustNotBeSameThanClonedPage"), null, 'errors'); @@ -1895,27 +1821,23 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf } } - if (!$error) - { + if (!$error) { $db->begin(); $newwebsiteid = GETPOST('newwebsite', 'int'); $pathofwebsitenew = $pathofwebsite; $tmpwebsite = new Website($db); - if ($newwebsiteid > 0 && $newwebsiteid != $object->id) - { + if ($newwebsiteid > 0 && $newwebsiteid != $object->id) { $tmpwebsite->fetch($newwebsiteid); $pathofwebsitenew = $dolibarr_main_data_root.'/website/'.$tmpwebsite->ref; - } - else { + } else { $tmpwebsite = $object; } $objectpage = new WebsitePage($db); $resultpage = $objectpage->createFromClone($user, $pageid, GETPOST('newpageurl', 'aZ09'), (GETPOST('newlang', 'aZ09') ? GETPOST('newlang', 'aZ09') : ''), $istranslation, $newwebsiteid, GETPOST('newtitle', 'alphanohtml')); - if ($resultpage < 0) - { + if ($resultpage < 0) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); $action = 'createpagefromclone'; @@ -1933,8 +1855,7 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf dolSavePageContent($filetpl, $tmpwebsite, $resultpage); // Switch on the new page if web site of new page/container is same - if (empty($newwebsiteid) || $newwebsiteid == $object->id) - { + if (empty($newwebsiteid) || $newwebsiteid == $object->id) { $pageid = $resultpage->id; } @@ -1945,47 +1866,39 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf $res = 0; - if (!$error) - { + if (!$error) { // Check symlink to medias and restore it if ko $pathtomedias = DOL_DATA_ROOT.'/medias'; $pathtomediasinwebsite = $pathofwebsite.'/medias'; - if (!is_link(dol_osencode($pathtomediasinwebsite))) - { + if (!is_link(dol_osencode($pathtomediasinwebsite))) { dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists $result = symlink($pathtomedias, $pathtomediasinwebsite); } /*if (GETPOST('savevirtualhost') && $object->virtualhost != GETPOST('previewsite')) - { - $object->virtualhost = GETPOST('previewsite', 'alpha'); - $object->update($user); - }*/ + { + $object->virtualhost = GETPOST('previewsite', 'alpha'); + $object->update($user); + }*/ $objectpage->fk_website = $object->id; - if ($pageid > 0) - { + if ($pageid > 0) { $res = $objectpage->fetch($pageid); - } - else { + } else { $res = 0; - if ($object->fk_default_home > 0) - { + if ($object->fk_default_home > 0) { $res = $objectpage->fetch($object->fk_default_home); } - if (!($res > 0)) - { + if (!($res > 0)) { $res = $objectpage->fetch(0, $object->id); } } } - if (!$error && $res > 0) - { - if ($action == 'updatesource' || $action == 'updatecontent') - { + if (!$error && $res > 0) { + if ($action == 'updatesource' || $action == 'updatecontent') { $db->begin(); $phpfullcodestringold = dolKeepOnlyPhpCode($objectpage->content); @@ -1995,30 +1908,33 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf // Security analysis $phpfullcodestring = dolKeepOnlyPhpCode($objectpage->content); //print dol_escape_htmltag($phpfullcodestring);exit; - $forbiddenphpcommands = array("exec", "passthru", "system", "shell_exec", "proc_open"); - if (empty($conf->global->WEBSITE_PHP_ALLOW_WRITE)) // If option is not on, we disallow functions to write files - { + $forbiddenphpcommands = array("exec", "passthru", "system", "shell_exec", "proc_open", "eval", "dol_eval"); + if (empty($conf->global->WEBSITE_PHP_ALLOW_WRITE)) { // If option is not on, we disallow functions to write files $forbiddenphpcommands = array_merge($forbiddenphpcommands, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "unlink", "mkdir", "rmdir", "symlink", "touch", "umask")); } - foreach ($forbiddenphpcommands as $forbiddenphpcommand) - { - if (preg_match('/'.$forbiddenphpcommand.'\s*\(/ms', $phpfullcodestring)) - { + foreach ($forbiddenphpcommands as $forbiddenphpcommand) { + if (preg_match('/'.$forbiddenphpcommand.'\s*\(/ms', $phpfullcodestring)) { $error++; setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", $forbiddenphpcommand), null, 'errors'); - if ($action == 'updatesource') $action = 'editsource'; - if ($action == 'updatecontent') $action = 'editcontent'; + if ($action == 'updatesource') { + $action = 'editsource'; + } + if ($action == 'updatecontent') { + $action = 'editcontent'; + } } } - if (empty($user->rights->website->writephp)) - { - if ($phpfullcodestringold != $phpfullcodestring) - { + if (empty($user->rights->website->writephp)) { + if ($phpfullcodestringold != $phpfullcodestring) { $error++; setEventMessages($langs->trans("NotAllowedToAddDynamicContent"), null, 'errors'); - if ($action == 'updatesource') $action = 'editsource'; - if ($action == 'updatecontent') $action = 'editcontent'; + if ($action == 'updatesource') { + $action = 'editsource'; + } + if ($action == 'updatecontent') { + $action = 'editcontent'; + } } } @@ -2028,16 +1944,18 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf $res = $objectpage->update($user); - if ($res < 0) - { + if ($res < 0) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - if ($action == 'updatesource') $action = 'editsource'; - if ($action == 'updatecontent') $action = 'editcontent'; + if ($action == 'updatesource') { + $action = 'editsource'; + } + if ($action == 'updatecontent') { + $action = 'editcontent'; + } } - if (!$error) - { + if (!$error) { $db->commit(); $filemaster = $pathofwebsite.'/master.inc.php'; @@ -2049,7 +1967,9 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf // Now generate the master.inc.php page $result = dolSaveMasterFile($filemaster); - if (!$result) setEventMessages('Failed to write the master file file '.$filemaster, null, 'errors'); + if (!$result) { + setEventMessages('Failed to write the master file file '.$filemaster, null, 'errors'); + } // Now delete the old alias.php page if we removed one /*if (!empty($fileoldalias)) @@ -2071,16 +1991,16 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf // Save page alias $result = dolSavePageAlias($filealias, $object, $objectpage); - if (!$result) setEventMessages('Failed to write the alias file '.basename($filealias), null, 'errors'); + if (!$result) { + setEventMessages('Failed to write the alias file '.basename($filealias), null, 'errors'); + } // Save page content $result = dolSavePageContent($filetpl, $object, $objectpage); - if ($result) - { + if ($result) { setEventMessages($langs->trans("Saved"), null, 'mesgs'); - if (!GETPOSTISSET('updateandstay')) // If we click on "Save And Stay", we do not make the redirect - { + if (!GETPOSTISSET('updateandstay')) { // If we click on "Save And Stay", we do not make the redirect if ($backtopage) { header("Location: ".$backtopage); exit; @@ -2089,13 +2009,17 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf exit; } } else { - if ($action == 'updatesource') $action = 'editsource'; - if ($action == 'updatecontent') $action = 'editcontent'; + if ($action == 'updatesource') { + $action = 'editsource'; + } + if ($action == 'updatecontent') { + $action = 'editcontent'; + } } } else { setEventMessages('Failed to write file '.$filetpl, null, 'errors'); header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey.'&pageid='.$pageid); - exit; + exit; } } else { $db->rollback(); @@ -2105,10 +2029,8 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf exit; } } else { - if (!$error) - { - if (empty($websitekey) || $websitekey == '-1') - { + if (!$error) { + if (empty($websitekey) || $websitekey == '-1') { setEventMessages($langs->trans("NoWebSiteCreateOneFirst"), null, 'warnings'); } else { setEventMessages($langs->trans("NoPageYet"), null, 'warnings'); @@ -2119,12 +2041,10 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf } // Export site -if ($action == 'exportsite') -{ +if ($action == 'exportsite') { $fileofzip = $object->exportWebSite(); - if ($fileofzip) - { + if ($fileofzip) { $file_name = basename($fileofzip); header("Content-Type: application/zip"); @@ -2133,19 +2053,29 @@ if ($action == 'exportsite') readfile($fileofzip); exit; - } - else { + } else { setEventMessages($object->error, $object->errors, 'errors'); $action = 'preview'; } } // Regenerate site -if ($action == 'regeneratesite') -{ +if ($action == 'regeneratesite') { + // Check symlink to medias and restore it if ko. Recreate also dir of website if not found. + $pathtomedias = DOL_DATA_ROOT.'/medias'; + $pathtomediasinwebsite = $pathofwebsite.'/medias'; + if (!is_link(dol_osencode($pathtomediasinwebsite))) { + dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); + dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists + $result = symlink($pathtomedias, $pathtomediasinwebsite); + if (!$result) { + setEventMessages($langs->trans("ErrorFieldToCreateSymLinkToMedias", $pathtomediasinwebsite, $pathtomedias), null, 'errors'); + $action = 'preview'; + } + } + $result = $object->rebuildWebSiteFiles(); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans("PagesRegenerated", $result), null, 'mesgs'); $action = 'preview'; } else { @@ -2155,83 +2085,68 @@ if ($action == 'regeneratesite') } // Import site -if ($action == 'importsiteconfirm') -{ - if (empty($_FILES) && !GETPOSTISSET('templateuserfile')) - { +if ($action == 'importsiteconfirm') { + if (empty($_FILES) && !GETPOSTISSET('templateuserfile')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors'); $action = 'importsite'; - } - else { - if (!empty($_FILES) || GETPOSTISSET('templateuserfile')) - { - // Check symlink to medias and restore it if ko + } else { + if (!empty($_FILES) || GETPOSTISSET('templateuserfile')) { + // Check symlink to medias and restore it if ko. Recreate also dir of website if not found. $pathtomedias = DOL_DATA_ROOT.'/medias'; $pathtomediasinwebsite = $pathofwebsite.'/medias'; - if (!is_link(dol_osencode($pathtomediasinwebsite))) - { + if (!is_link(dol_osencode($pathtomediasinwebsite))) { dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists $result = symlink($pathtomedias, $pathtomediasinwebsite); - if (!$result) - { + if (!$result) { setEventMessages($langs->trans("ErrorFieldToCreateSymLinkToMedias", $pathtomediasinwebsite, $pathtomedias), null, 'errors'); $action = 'importsite'; } } $fileofzip = ''; - if (GETPOSTISSET('templateuserfile')) - { + if (GETPOSTISSET('templateuserfile')) { $fileofzip = DOL_DATA_ROOT.'/doctemplates/websites/'.GETPOST('templateuserfile', 'alpha'); - } - elseif (!empty($_FILES)) - { - if (is_array($_FILES['userfile']['tmp_name'])) $userfiles = $_FILES['userfile']['tmp_name']; - else $userfiles = array($_FILES['userfile']['tmp_name']); + } elseif (!empty($_FILES)) { + if (is_array($_FILES['userfile']['tmp_name'])) { + $userfiles = $_FILES['userfile']['tmp_name']; + } else { + $userfiles = array($_FILES['userfile']['tmp_name']); + } - foreach ($userfiles as $key => $userfile) - { - if (empty($_FILES['userfile']['tmp_name'][$key])) - { + foreach ($userfiles as $key => $userfile) { + if (empty($_FILES['userfile']['tmp_name'][$key])) { $error++; if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2) { setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors'); $action = 'importsite'; - } - else { + } else { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors'); $action = 'importsite'; } } } - if (!$error) - { + if (!$error) { $upload_dir = $conf->website->dir_temp; $result = dol_add_file_process($upload_dir, 1, -1, 'userfile', ''); } // Get name of file (take last one if several name provided) $fileofzip = $upload_dir.'/unknown'; - foreach ($_FILES as $key => $ifile) - { - foreach ($ifile['name'] as $key2 => $ifile2) - { + foreach ($_FILES as $key => $ifile) { + foreach ($ifile['name'] as $key2 => $ifile2) { $fileofzip = $upload_dir.'/'.$ifile2; } } } - if (!$error) - { + if (!$error) { $result = $object->importWebSite($fileofzip); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = 'importsite'; - } - else { + } else { // Force mode dynamic on dolibarr_set_const($db, 'WEBSITE_SUBCONTAINERSINLINE', 1, 'chaine', 0, '', $conf->entity); @@ -2243,7 +2158,77 @@ if ($action == 'importsiteconfirm') } } +$domainname = '0.0.0.0:8080'; +$tempdir = $conf->website->dir_output.'/'.$websitekey.'/'; +// Generate web site sitemaps +if ($action == 'generatesitemaps') { + $domtree = new DOMDocument('1.0', 'UTF-8'); + $root = $domtree->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'urlset'); + $domtree->formatOutput = true; + $xmlname = 'sitemap.'.$websitekey.'.xml'; + + $sql = "SELECT wp.type_container , wp.pageurl, wp.lang, wp.tms as tms, w.virtualhost"; + $sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp, ".MAIN_DB_PREFIX."website as w"; + $sql .= " WHERE wp.type_container IN ('page', 'blogpost')"; + $sql .= " AND wp.fk_website = w.rowid"; + $sql .= " AND w.ref = '".dol_escape_json($websitekey)."'"; + $resql = $db->query($sql); + if ($resql) { + $num_rows = $db->num_rows($resql); + if ($num_rows > 0) { + $i = 0; + while ($i < $num_rows) { + $objp = $db->fetch_object($resql); + $url = $domtree->createElement('url'); + $pageurl = $objp->pageurl; + if ($objp->lang) { + $pageurl = $objp->lang.'/'.$pageurl; + } + if ($objp->virtualhost) { + $domainname = $objp->virtualhost; + } + $loc = $domtree->createElement('loc', 'http://'.$domainname.'/'.$pageurl); + $lastmod = $domtree->createElement('lastmod', $db->jdate($objp->tms)); + + $url->appendChild($loc); + $url->appendChild($lastmod); + $root->appendChild($url); + $i++; + } + $domtree->appendChild($root); + if ($domtree->save($tempdir.$xmlname)) { + if (!empty($conf->global->MAIN_UMASK)) { + @chmod($tempdir.$xmlname, octdec($conf->global->MAIN_UMASK)); + } + setEventMessages($langs->trans("SitemapGenerated"), null, 'mesgs'); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } else { + dol_print_error($db); + } + $robotcontent = @file_get_contents($filerobot); + $result = preg_replace('/<?php // BEGIN PHP[^?]END PHP ?>\n/ims', '', $robotcontent); + if ($result) { + $robotcontent = $result; + } + $robotsitemap = "Sitemap: ".$domainname."/".$xmlname; + $result = strpos($robotcontent, 'Sitemap: '); + if ($result) { + $result = preg_replace("/Sitemap.*\n/", $robotsitemap, $robotcontent); + $robotcontent = $result ? $result : $robotcontent; + } else { + $robotcontent .= $robotsitemap."\n"; + } + $result = dolSaveRobotFile($filerobot, $robotcontent); + if (!$result) { + $error++; + setEventMessages('Failed to write file '.$filerobot, null, 'errors'); + } + $action = 'preview'; +} /* @@ -2255,6 +2240,12 @@ $formadmin = new FormAdmin($db); $formwebsite = new FormWebsite($db); $formother = new FormOther($db); +// Confirm generation of website sitemaps +if ($action == 'confirmgeneratesitemaps') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?website='.$website->ref, $langs->trans('ConfirmSitemapsCreation'), $langs->trans('ConfirmGenerateSitemaps', $object->ref), 'generatesitemaps', '', "yes", 1); + $action = 'preview'; +} + $helpurl = 'EN:Module_Website|FR:Module_Website_FR|ES:M&oacute;dulo_Website'; $arrayofjs = array( @@ -2271,7 +2262,9 @@ $moreheadjs = ''; $arrayofjs[] = 'includes/jquery/plugins/blockUI/jquery.blockUI.js'; $arrayofjs[] = 'core/js/blockUI.js'; // Used by ecm/tpl/enabledfiletreeajax.tpl.php -if (empty($conf->global->MAIN_ECM_DISABLE_JS)) $arrayofjs[] = "includes/jquery/plugins/jqueryFileTree/jqueryFileTree.js"; +if (empty($conf->global->MAIN_ECM_DISABLE_JS)) { + $arrayofjs[] = "includes/jquery/plugins/jqueryFileTree/jqueryFileTree.js"; +} $moreheadjs .= '<script type="text/javascript">'."\n"; $moreheadjs .= 'var indicatorBlockUI = \''.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'\';'."\n"; @@ -2284,56 +2277,43 @@ print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" enctype="multipart/ print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; -if ($action == 'createsite') -{ +if ($action == 'createsite') { print '<input type="hidden" name="action" value="addsite">'; } -if ($action == 'createcontainer') -{ +if ($action == 'createcontainer') { print '<input type="hidden" name="action" value="addcontainer">'; } -if ($action == 'editcss') -{ +if ($action == 'editcss') { print '<input type="hidden" name="action" value="updatecss">'; } -if ($action == 'editmenu') -{ +if ($action == 'editmenu') { print '<input type="hidden" name="action" value="updatemenu">'; } -if ($action == 'setashome') -{ +if ($action == 'setashome') { print '<input type="hidden" name="action" value="updateashome">'; } -if ($action == 'editmeta') -{ +if ($action == 'editmeta') { print '<input type="hidden" name="action" value="updatemeta">'; } -if ($action == 'editsource') -{ +if ($action == 'editsource') { print '<input type="hidden" name="action" value="updatesource">'; } -if ($action == 'editcontent') -{ +if ($action == 'editcontent') { print '<input type="hidden" name="action" value="updatecontent">'; } -if ($action == 'edit') -{ +if ($action == 'edit') { print '<input type="hidden" name="action" value="update">'; } -if ($action == 'importsite') -{ +if ($action == 'importsite') { print '<input type="hidden" name="action" value="importsiteconfirm">'; } -if ($action == 'file_manager') -{ +if ($action == 'file_manager') { print '<input type="hidden" name="action" value="file_manager">'; } -if ($action == 'replacesite') -{ +if ($action == 'replacesite') { print '<input type="hidden" name="action" value="replacesiteconfirm">'; } -if ($action == 'replacesiteconfirm') -{ +if ($action == 'replacesiteconfirm') { print '<input type="hidden" name="action" value="replacesiteconfirm">'; } @@ -2341,28 +2321,33 @@ print '<div>'; // Add a margin under toolbar ? $style = ''; -if ($action != 'preview' && $action != 'editcontent' && $action != 'editsource' && !GETPOST('createpagefromclone', 'alphanohtml')) $style = ' margin-bottom: 5px;'; +if ($action != 'preview' && $action != 'editcontent' && $action != 'editsource' && !GETPOST('createpagefromclone', 'alphanohtml')) { + $style = ' margin-bottom: 5px;'; +} -if (!GETPOST('hide_websitemenu')) -{ +if (!GETPOST('hide_websitemenu')) { $disabled = ''; - if (empty($user->rights->website->write)) $disabled = ' disabled="disabled"'; + if (empty($user->rights->website->write)) { + $disabled = ' disabled="disabled"'; + } - if ($websitekey) - { + if ($websitekey) { $virtualurl = ''; $dataroot = DOL_DATA_ROOT.'/website/'.$websitekey; - if (!empty($object->virtualhost)) $virtualurl = $object->virtualhost; + if (!empty($object->virtualhost)) { + $virtualurl = $object->virtualhost; + } } $array = array(); - if ($object->id > 0) - { + if ($object->id > 0) { $array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl'); $object->lines = $array; } - if (!is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); + if (!is_array($array) && $array < 0) { + dol_print_error('', $objectpage->error, $objectpage->errors); + } $atleastonepage = (is_array($array) && count($array) > 0); @@ -2390,21 +2375,26 @@ if (!GETPOST('hide_websitemenu')) print '<span class="websiteselection">'; $out = ''; $out .= '<select name="website" class="minwidth100 width200 maxwidth150onsmartphone" id="website">'; - if (empty($object->records)) $out .= '<option value="-1">&nbsp;</option>'; + if (empty($object->records)) { + $out .= '<option value="-1">&nbsp;</option>'; + } if (!empty($conf->use_javascript_ajax)) { $valueoption = '<span class="classlink">'.img_picto('', 'add', 'class="paddingrightonly"').$langs->trans("AddWebsite").'</span>'; $out .= '<option value="-2" data-html="'.dol_escape_htmltag($valueoption).'">'.$valueoption.'</option>'; } // Loop on each sites $i = 0; - foreach ($object->records as $key => $valwebsite) - { + foreach ($object->records as $key => $valwebsite) { if (empty($websitekey)) { - if ($action != 'createsite') $websitekey = $valwebsite->ref; + if ($action != 'createsite') { + $websitekey = $valwebsite->ref; + } } $out .= '<option value="'.$valwebsite->ref.'"'; - if ($websitekey == $valwebsite->ref) $out .= ' selected'; // To preselect a value + if ($websitekey == $valwebsite->ref) { + $out .= ' selected'; // To preselect a value + } //$outoption = $valwebsite->getLibStatut(3).' '.$valwebsite->ref.' '; $outoption = (($valwebsite->status == $valwebsite::STATUS_DRAFT) ? '<span class="opacitymedium">' : '').$valwebsite->ref.(($valwebsite->status == $valwebsite::STATUS_DRAFT) ? '</span>' : ''); $out .= ' data-html="'.dol_escape_htmltag($outoption).'"'; @@ -2436,11 +2426,11 @@ if (!GETPOST('hide_websitemenu')) print '<input type="image" class="valignmiddle" src="'.img_picto('', 'refresh', '', 0, 1).'" name="refreshsite" value="'.$langs->trans("Load").'">'; } - if ($websitekey && $websitekey != '-1' && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) - { + if ($websitekey && $websitekey != '-1' && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) { print ' &nbsp; '; - print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditCss")).'" name="editcss">'; + //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditCss")).'" name="editcss">'; + print '<a href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$pageid.'&action=editcss" class="button bordertransp"'.$disabled.'>'.dol_escape_htmltag($langs->trans("EditCss")).'</a>'; $importlabel = $langs->trans("ImportSite"); $exportlabel = $langs->trans("ExportSite"); @@ -2449,11 +2439,9 @@ if (!GETPOST('hide_websitemenu')) $exportlabel = $langs->trans("Export"); } - if ($atleastonepage) - { + if ($atleastonepage) { print '<input type="submit" class="button bordertransp" disabled="disabled" value="'.dol_escape_htmltag($importlabel).'" name="importsite">'; - } - else { + } else { print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($importlabel).'" name="importsite">'; } @@ -2469,13 +2457,17 @@ if (!GETPOST('hide_websitemenu')) print ' &nbsp; '; + // Generate site map + print '<a href="'.$_SERVER["PHP_SEFL"].'?action=confirmgeneratesitemaps&website='.$website->ref.'" class="button bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("GenerateSitemaps")).'"><span class="fa fa-sitemap"><span></a>'; + + print ' &nbsp; '; + print '<a href="'.$_SERVER["PHP_SEFL"].'?action=replacesite&website='.$website->ref.'" class="button bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("ReplaceWebsiteContent")).'"><span class="fa fa-search"><span></a>'; } print '</span>'; - if ($websitekey && $websitekey != '-1' && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) - { + if ($websitekey && $websitekey != '-1' && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) { print '<span class="websiteselection">'; //print '<a href="'.$_SERVER["PHP_SELF"].'?action=file_manager&website='.$website->ref.'" class="button bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("MediaFiles")).'"><span class="fa fa-image"><span></a>'; print dolButtonToOpenUrlInDialogPopup('file_manager', $langs->transnoentitiesnoconv("MediaFiles"), '<span class="fa fa-image"><span>', '/website/index.php?action=file_manager&website='.$website->ref, $disabled); @@ -2494,8 +2486,7 @@ if (!GETPOST('hide_websitemenu')) print '<span class="websitetools websiteselection">'; - if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite') - { + if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite') { $urlext = $virtualurl; $urlint = $urlwithroot.'/public/website/index.php?website='.$websitekey; @@ -2504,22 +2495,16 @@ if (!GETPOST('hide_websitemenu')) $linktotestonwebserver .= '<span class="hideonsmartphone paddingrightonly">'.$langs->trans("TestDeployOnWeb", $virtualurl).'</span>'.img_picto('', 'globe'); $linktotestonwebserver .= '</a>'; $htmltext = ''; - if (empty($object->fk_default_home)) - { + if (empty($object->fk_default_home)) { $htmltext .= '<br><span class="error">'.$langs->trans("YouMustDefineTheHomePage").'</span><br><br>'; - } - elseif (empty($virtualurl)) - { + } elseif (empty($virtualurl)) { //$htmltext .= '<br><span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span><br><br>'; - } - else { + } else { $htmltext .= '<br><center>'.$langs->trans("GoTo").' <a href="'.$virtualurl.'" target="_website">'.$virtualurl.'</a></center><br>'; } - if (!empty($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER)) - { + if (!empty($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER)) { $htmltext .= '<br>'.$langs->trans($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER); - } - else { + } else { $htmltext .= $langs->trans("SetHereVirtualHost", $dataroot); $htmltext .= '<br>'; $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); @@ -2556,12 +2541,19 @@ if (!GETPOST('hide_websitemenu')) print '</span>'; } - if (in_array($action, array('editcss', 'editmenu', 'file_manager', 'replacesite', 'replacesiteconfirm'))) - { - if ($action == 'editcss') print '<input type="submit" id="savefilean stay" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("SaveAndStay")).'" name="updateandstay">'; - if (preg_match('/^create/', $action) && $action != 'file_manager' && $action != 'replacesite' && $action != 'replacesiteconfirm') print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; - if (preg_match('/^edit/', $action) && $action != 'file_manager' && $action != 'replacesite' && $action != 'replacesiteconfirm') print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; - if ($action != 'preview') print '<input type="submit" class="button button-cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="cancel">'; + if (in_array($action, array('editcss', 'editmenu', 'file_manager', 'replacesite', 'replacesiteconfirm'))) { + if ($action == 'editcss') { + print '<input type="submit" id="savefilean stay" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("SaveAndStay")).'" name="updateandstay">'; + } + if (preg_match('/^create/', $action) && $action != 'file_manager' && $action != 'replacesite' && $action != 'replacesiteconfirm') { + print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; + } + if (preg_match('/^edit/', $action) && $action != 'file_manager' && $action != 'replacesite' && $action != 'replacesiteconfirm') { + print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; + } + if ($action != 'preview') { + print '<input type="submit" class="button button-cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="cancel">'; + } } print '</span>'; @@ -2570,8 +2562,7 @@ if (!GETPOST('hide_websitemenu')) // Toolbar for pages // - if ($websitekey && $websitekey != '-1' && !in_array($action, array('editcss', 'editmenu', 'importsite', 'file_manager', 'replacesite', 'replacesiteconfirm')) && !$file_manager) - { + if ($websitekey && $websitekey != '-1' && !in_array($action, array('editcss', 'editmenu', 'importsite', 'file_manager', 'replacesite', 'replacesiteconfirm')) && !$file_manager) { print '</div>'; // Close current websitebar to open a new one print '<!-- Bar for websitepage -->'; @@ -2587,8 +2578,7 @@ if (!GETPOST('hide_websitemenu')) //print '<span class="websiteselection">'; - if ($action != 'addcontainer') - { + if ($action != 'addcontainer') { $out = ''; $s = $formwebsite->selectContainer($website, 'pageid', $pageid, 0, $action, 'maxwidth200onsmartphone'); @@ -2617,8 +2607,7 @@ if (!GETPOST('hide_websitemenu')) } print $out; - } - else { + } else { print $langs->trans("New"); } @@ -2629,47 +2618,50 @@ if (!GETPOST('hide_websitemenu')) // Print nav arrows $pagepreviousid = 0; $pagenextid = 0; - if ($pageid) - { + if ($pageid) { $sql = 'SELECT MAX(rowid) as pagepreviousid FROM '.MAIN_DB_PREFIX.'website_page WHERE rowid < '.$pageid.' AND fk_website = '.$object->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $pagepreviousid = $obj->pagepreviousid; } + } else { + dol_print_error($db); } - else dol_print_error($db); $sql = 'SELECT MIN(rowid) as pagenextid FROM '.MAIN_DB_PREFIX.'website_page WHERE rowid > '.$pageid.' AND fk_website = '.$object->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $pagenextid = $obj->pagenextid; } + } else { + dol_print_error($db); } - else dol_print_error($db); } - if ($pagepreviousid) print '<a class="valignmiddle" href="'.$_SERVER['PHP_SELF'].'?website='.urlencode($object->ref).'&pageid='.$pagepreviousid.'&action='.$action.'">'.img_previous($langs->trans("PreviousContainer")).'</a>'; - else print '<span class="valignmiddle opacitymedium">'.img_previous($langs->trans("Previous")).'</span>'; - if ($pagenextid) print '<a class="valignmiddle" href="'.$_SERVER['PHP_SELF'].'?website='.urlencode($object->ref).'&pageid='.$pagenextid.'&action='.$action.'">'.img_next($langs->trans("NextContainer")).'</a>'; - else print '<span class="valignmiddle opacitymedium">'.img_next($langs->trans("Next")).'</span>'; + if ($pagepreviousid) { + print '<a class="valignmiddle" href="'.$_SERVER['PHP_SELF'].'?website='.urlencode($object->ref).'&pageid='.$pagepreviousid.'&action='.$action.'">'.img_previous($langs->trans("PreviousContainer")).'</a>'; + } else { + print '<span class="valignmiddle opacitymedium">'.img_previous($langs->trans("Previous")).'</span>'; + } + if ($pagenextid) { + print '<a class="valignmiddle" href="'.$_SERVER['PHP_SELF'].'?website='.urlencode($object->ref).'&pageid='.$pagenextid.'&action='.$action.'">'.img_next($langs->trans("NextContainer")).'</a>'; + } else { + print '<span class="valignmiddle opacitymedium">'.img_next($langs->trans("Next")).'</span>'; + } $websitepage = new WebSitePage($db); - if ($pageid > 0 && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone')) - { + if ($pageid > 0 && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone')) { $websitepage->fetch($pageid); } - if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite') - { + if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite') { $disabled = ''; - if (empty($user->rights->website->write)) $disabled = ' disabled="disabled"'; + if (empty($user->rights->website->write)) { + $disabled = ' disabled="disabled"'; + } // Confirmation delete site if ($action == 'deletesite') { @@ -2698,8 +2690,7 @@ if (!GETPOST('hide_websitemenu')) print $formconfirm; } - if ($pageid > 0 && $atleastonepage) // pageid can be set without pages, if homepage of site is set and all pages were removed - { + if ($pageid > 0 && $atleastonepage) { // pageid can be set without pages, if homepage of site is set and all pages were removed // Confirmation to clone if ($action == 'createpagefromclone') { // Create an array for form @@ -2730,20 +2721,32 @@ if (!GETPOST('hide_websitemenu')) $value= $formadmin->select_language($preselectedlanguage, 'newlang', 0, null, $textifempty, 0, 0, 'minwidth200', 1, 0, 0, $onlylang, 1); $formquestion[] = array('type' => 'other', 'name' => 'newlang', 'label' => $form->textwithpicto($langs->trans("Language"), $langs->trans("DefineListOfAltLanguagesInWebsiteProperties")), 'value' => $value); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$pageid, $langs->trans('ClonePage'), '', 'confirm_createpagefromclone', $formquestion, 0, 1, 300, 550); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$pageid, $langs->trans('ClonePage'), '', 'confirm_createpagefromclone', $formquestion, 0, 1, 300, 550); print $formconfirm; } print ' &nbsp; '; - print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditPageMeta")).'" name="editmeta">'; + //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditPageMeta")).'" name="editmeta">'; + print '<a href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$pageid.'&action=editmeta" class="button bordertransp"'.$disabled.'>'.dol_escape_htmltag($langs->trans("EditPageMeta")).'</a>'; - print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditHTMLSource")).'" name="editsource">'; + //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditHTMLSource")).'" name="editsource">'; + print '<a href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$pageid.'&action=editsource" class="button bordertransp"'.$disabled.'>'.dol_escape_htmltag($langs->trans("EditHTMLSource")).'</a>'; print '<!-- button EditInLine and ShowSubcontainers -->'."\n"; print '<div class="websiteselectionsection inline-block">'; - print '<div class="inline-block marginrightonly">'; + + print '<div class="inline-block marginrightonly">'; // Button include dynamic contant + print $langs->trans("ShowSubcontainers"); + if (empty($conf->global->WEBSITE_SUBCONTAINERSINLINE)) { + print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=setshowsubcontainers&token='.newToken().'">'.img_picto($langs->trans("ShowSubContainersOnOff", $langs->transnoentitiesnoconv("Off")), 'switch_off', '', false, 0, 0, '', 'nomarginleft').'</a>'; + } else { + print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=unsetshowsubcontainers&token='.newToken().'">'.img_picto($langs->trans("ShowSubContainersOnOff", $langs->transnoentitiesnoconv("On")), 'switch_on', '', false, 0, 0, '', 'nomarginleft').'</a>'; + } + print '</div>'; + + print '<div class="inline-block marginrightonly">'; // Button edit inline print '<span id="switchckeditorinline">'."\n"; print '<!-- Code to enabled edit inline ckeditor -->'."\n"; @@ -2795,45 +2798,29 @@ if (!GETPOST('hide_websitemenu')) //$disableeditinline = $websitepage->grabbed_from; $disableeditinline = 0; - if ($disableeditinline) - { + if ($disableeditinline) { //print '<input type="submit" class="button bordertransp" disabled="disabled" title="'.dol_escape_htmltag($langs->trans("OnlyEditionOfSourceForGrabbedContent")).'" value="'.dol_escape_htmltag($langs->trans("EditWithEditor")).'" name="editcontent">'; print '<a class="nobordertransp opacitymedium nohoverborder marginleftonlyshort"'.$disabled.' href="#" disabled="disabled" title="'.dol_escape_htmltag($langs->trans("OnlyEditionOfSourceForGrabbedContent")).'">'.img_picto($langs->trans("OnlyEditionOfSourceForGrabbedContent"), 'switch_off', '', false, 0, 0, '', 'nomarginleft').'</a>'; - } - else { + } else { //print '<input type="submit" class="button nobordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditWithEditor")).'" name="editcontent">'; - if (empty($conf->global->WEBSITE_EDITINLINE)) - { + if (empty($conf->global->WEBSITE_EDITINLINE)) { print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=seteditinline&token='.newToken().'">'.img_picto($langs->trans("EditInLineOnOff", $langs->transnoentitiesnoconv("Off")), 'switch_off', '', false, 0, 0, '', 'nomarginleft').'</a>'; - } - else { + } else { print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=unseteditinline&token='.newToken().'">'.img_picto($langs->trans("EditInLineOnOff", $langs->transnoentitiesnoconv("On")), 'switch_on', '', false, 0, 0, '', 'nomarginleft').'</a>'; } } print '</div>'; - print '<div class="inline-block marginrightonly">'; - print $langs->trans("ShowSubcontainers"); - if (empty($conf->global->WEBSITE_SUBCONTAINERSINLINE)) - { - print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=setshowsubcontainers&token='.newToken().'">'.img_picto($langs->trans("ShowSubContainersOnOff", $langs->transnoentitiesnoconv("Off")), 'switch_off', '', false, 0, 0, '', 'nomarginleft').'</a>'; - } - else { - print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=unsetshowsubcontainers&token='.newToken().'">'.img_picto($langs->trans("ShowSubContainersOnOff", $langs->transnoentitiesnoconv("On")), 'switch_on', '', false, 0, 0, '', 'nomarginleft').'</a>'; - } - /*}*/ - print '</div>'; + print '</div>'; // Set page as homepage - if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) - { + if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) { //$disabled=' disabled="disabled"'; //print '<span class="button bordertransp disabled"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'"><span class="fa fa-home"></span></span>'; //print '<input type="submit" class="button bordertransp" disabled="disabled" value="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'" name="setashome">'; print '<a href="#" class="button bordertransp disabled" disabled="disabled" title="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'"><span class="fa fa-home valignmiddle btnTitle-icon"><span></a>'; - } - else { + } else { //$disabled=''; //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'" name="setashome">'; print '<a href="'.$_SERVER["PHP_SEFL"].'?action=setashome&token='.newToken().'&website='.$website->ref.'&pageid='.$pageid.'" class="button bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'"><span class="fa fa-home valignmiddle btnTitle-icon"><span></a>'; @@ -2847,15 +2834,15 @@ if (!GETPOST('hide_websitemenu')) print '<span class="websitetools">'; - if (($pageid > 0 && $atleastonepage) && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) - { + if (($pageid > 0 && $atleastonepage) && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) { $realpage = $urlwithroot.'/public/website/index.php?website='.$websitekey.'&pageref='.$websitepage->pageurl; $pagealias = $websitepage->pageurl; $htmltext = $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage, $dataroot); - $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); - $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), '{s1}'); - $htmltext = str_replace('{s1}', DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias', $htmltext); + $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), '{s1}'); + $htmltext = str_replace('{s1}', $dataroot.'<br>'.DOL_DATA_ROOT.'/medias<br>'.DOL_DOCUMENT_ROOT, $htmltext); + //$htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), '{s1}'); + //$htmltext = str_replace('{s1}', DOL_DATA_ROOT.'/medias', $htmltext); print '<div class="websiteinputurl inline-block paddingright">'; print '<a class="websitebuttonsitepreview inline-block" id="previewpage" href="'.$realpage.'&nocache='.dol_now().'" class="button" target="tab'.$websitekey.'" alt="'.dol_escape_htmltag($htmltext).'">'; @@ -2883,30 +2870,34 @@ if (!GETPOST('hide_websitemenu')) // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext } - if (!in_array($action, array('editcss', 'editmenu', 'file_manager', 'replacesite', 'replacesiteconfirm', 'createsite', 'createcontainer', 'createfromclone', 'createpagefromclone', 'deletesite'))) - { - if ($action == 'editsource' || $action == 'editmeta') print '<input type="submit" id="savefilean stay" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("SaveAndStay")).'" name="updateandstay">'; - if (preg_match('/^create/', $action)) print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; - if (preg_match('/^edit/', $action)) print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; - if ($action != 'preview') print '<input type="submit" class="button button-cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="cancel">'; + if (!in_array($action, array('editcss', 'editmenu', 'file_manager', 'replacesite', 'replacesiteconfirm', 'createsite', 'createcontainer', 'createfromclone', 'createpagefromclone', 'deletesite'))) { + if ($action == 'editsource' || $action == 'editmeta') { + print '<input type="submit" id="savefilean stay" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("SaveAndStay")).'" name="updateandstay">'; + } + if (preg_match('/^create/', $action)) { + print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; + } + if (preg_match('/^edit/', $action)) { + print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; + } + if ($action != 'preview') { + print '<input type="submit" class="button button-cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="cancel">'; + } } print '</span>'; // end websitetools print '<span class="websitehelp">'; - if (GETPOST('editsource', 'alpha') || GETPOST('editcontent', 'alpha')) - { + if (GETPOST('editsource', 'alpha') || GETPOST('editcontent', 'alpha')) { $url = 'https://wiki.dolibarr.org/index.php/Module_Website'; $htmltext = $langs->transnoentitiesnoconv("YouCanEditHtmlSource", $url); $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource2", $url); $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSourceMore", $url); $htmltext .= '<br>'; - if ($conf->browser->layout == 'phone') - { + if ($conf->browser->layout == 'phone') { print $form->textwithpicto('', $htmltext, 1, 'help', 'inline-block', 1, 2, 'tooltipsubstitution'); - } - else { + } else { //img_help(($tooltiptrigger != '' ? 2 : 1), $alt) print $form->textwithpicto($langs->trans("SyntaxHelp").' '.img_help(2, $langs->trans("SyntaxHelp")), $htmltext, 1, 'none', 'inline-block', 1, 2, 'tooltipsubstitution'); } @@ -2914,11 +2905,9 @@ if (!GETPOST('hide_websitemenu')) print '</span>'; // end websitehelp - if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') - { + if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') { // Adding jquery code to change on the fly url of preview ext - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print '<script type="text/javascript" language="javascript"> jQuery(document).ready(function() { jQuery("#websiteinputurl").keyup(function() { @@ -2976,115 +2965,96 @@ $head = array(); * Edit Site HTML header and CSS */ -if ($action == 'editcss') -{ +if ($action == 'editcss') { print '<div class="fiche">'; print '<br>'; - if (!GETPOSTISSET('WEBSITE_CSS_INLINE')) - { + if (!GETPOSTISSET('WEBSITE_CSS_INLINE')) { $csscontent = @file_get_contents($filecss); // Clean the php css file to remove php code and get only css part $csscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $csscontent); - } - else { + } else { $csscontent = GETPOST('WEBSITE_CSS_INLINE', 'none'); } if (!trim($csscontent)) { $csscontent = '/* CSS content (all pages) */'."\nbody.bodywebsite { margin: 0; font-family: 'Open Sans', sans-serif; }\n.bodywebsite h1 { margin-top: 0; margin-bottom: 0; padding: 10px;}"; } - if (!GETPOSTISSET('WEBSITE_JS_INLINE')) - { + if (!GETPOSTISSET('WEBSITE_JS_INLINE')) { $jscontent = @file_get_contents($filejs); // Clean the php js file to remove php code and get only js part $jscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $jscontent); - } - else { + } else { $jscontent = GETPOST('WEBSITE_JS_INLINE', 'none'); } - if (!trim($jscontent)) $jscontent = '/* JS content (all pages) */'."\n"; + if (!trim($jscontent)) { + $jscontent = '/* JS content (all pages) */'."\n"; + } - if (!GETPOSTISSET('WEBSITE_HTML_HEADER')) - { + if (!GETPOSTISSET('WEBSITE_HTML_HEADER')) { $htmlheadercontent = @file_get_contents($filehtmlheader); // Clean the php htmlheader file to remove php code and get only html part $htmlheadercontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $htmlheadercontent); - } - else { + } else { $htmlheadercontent = GETPOST('WEBSITE_HTML_HEADER', 'none'); } - if (!trim($htmlheadercontent)) - { + if (!trim($htmlheadercontent)) { $htmlheadercontent = "<html>\n"; $htmlheadercontent .= $htmlheadercontentdefault; $htmlheadercontent .= "</html>"; - } - else { + } else { $htmlheadercontent = preg_replace('/^\s*<html>/ims', '', $htmlheadercontent); $htmlheadercontent = preg_replace('/<\/html>\s*$/ims', '', $htmlheadercontent); $htmlheadercontent = '<html>'."\n".trim($htmlheadercontent)."\n".'</html>'; } - if (!GETPOSTISSET('WEBSITE_ROBOT')) - { + if (!GETPOSTISSET('WEBSITE_ROBOT')) { $robotcontent = @file_get_contents($filerobot); // Clean the php htmlheader file to remove php code and get only html part $robotcontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $robotcontent); - } - else { + } else { $robotcontent = GETPOST('WEBSITE_ROBOT', 'nothtml'); } - if (!trim($robotcontent)) - { + if (!trim($robotcontent)) { $robotcontent .= "# Robot file. Generated with ".DOL_APPLICATION_TITLE."\n"; $robotcontent .= "User-agent: *\n"; $robotcontent .= "Allow: /public/\n"; $robotcontent .= "Disallow: /administrator/\n"; } - if (!GETPOSTISSET('WEBSITE_HTACCESS')) - { + if (!GETPOSTISSET('WEBSITE_HTACCESS')) { $htaccesscontent = @file_get_contents($filehtaccess); // Clean the php htaccesscontent file to remove php code and get only html part $htaccesscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $htaccesscontent); - } - else { + } else { $htaccesscontent = GETPOST('WEBSITE_HTACCESS', 'nohtml'); } - if (!trim($htaccesscontent)) - { + if (!trim($htaccesscontent)) { $htaccesscontent .= "# Order allow,deny\n"; $htaccesscontent .= "# Deny from all\n"; } - if (!GETPOSTISSET('WEBSITE_MANIFEST_JSON')) - { + if (!GETPOSTISSET('WEBSITE_MANIFEST_JSON')) { $manifestjsoncontent = @file_get_contents($filemanifestjson); // Clean the manifestjson file to remove php code and get only html part $manifestjsoncontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $manifestjsoncontent); - } - else { + } else { $manifestjsoncontent = GETPOST('WEBSITE_MANIFEST_JSON', 'restricthtml'); } - if (!trim($manifestjsoncontent)) - { + if (!trim($manifestjsoncontent)) { //$manifestjsoncontent.=""; } - if (!GETPOSTISSET('WEBSITE_README')) - { + if (!GETPOSTISSET('WEBSITE_README')) { $readmecontent = @file_get_contents($filereadme); // Clean the readme file to remove php code and get only html part $readmecontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $readmecontent); - } - else { + } else { $readmecontent = GETPOST('WEBSITE_README', 'none'); } - if (!trim($readmecontent)) - { + if (!trim($readmecontent)) { //$readmecontent.=""; } @@ -3242,8 +3212,7 @@ if ($action == 'editcss') } -if ($action == 'createsite') -{ +if ($action == 'createsite') { print '<div class="fiche">'; print '<br>'; @@ -3253,12 +3222,14 @@ if ($action == 'createsite') $head[$h][0] = dol_buildpath('/website/index.php',1).'?id='.$object->id; $head[$h][1] = $langs->trans("AddSite"); - $head[$h][2] = 'card'; + $head[$h][2] = 'card'; $h++; - print dol_get_fiche_head($head, 'card', $langs->trans("AddSite"), -1, 'globe'); - */ - if ($action == 'createcontainer') print load_fiche_titre($langs->trans("AddSite")); + print dol_get_fiche_head($head, 'card', $langs->trans("AddSite"), -1, 'globe'); + */ + if ($action == 'createcontainer') { + print load_fiche_titre($langs->trans("AddSite")); + } print '<!-- Add site -->'."\n"; //print '<div class="fichecenter">'; @@ -3266,10 +3237,18 @@ if ($action == 'createsite') print '<table class="border centpercent">'; $siteref = $sitedesc = $sitelang = $siteotherlang = ''; - if (GETPOST('WEBSITE_REF')) $siteref = GETPOST('WEBSITE_REF', 'alpha'); - if (GETPOST('WEBSITE_DESCRIPTION')) $sitedesc = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); - if (GETPOST('WEBSITE_LANG')) $sitelang = GETPOST('WEBSITE_LANG', 'aZ09'); - if (GETPOST('WEBSITE_OTHERLANG')) $siteotherlang = GETPOST('WEBSITE_OTHERLANG', 'aZ09comma'); + if (GETPOST('WEBSITE_REF')) { + $siteref = GETPOST('WEBSITE_REF', 'alpha'); + } + if (GETPOST('WEBSITE_DESCRIPTION')) { + $sitedesc = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); + } + if (GETPOST('WEBSITE_LANG')) { + $sitelang = GETPOST('WEBSITE_LANG', 'aZ09'); + } + if (GETPOST('WEBSITE_OTHERLANG')) { + $siteotherlang = GETPOST('WEBSITE_OTHERLANG', 'aZ09comma'); + } print '<tr><td class="titlefieldcreate fieldrequired">'; print $form->textwithpicto($langs->trans('WebSite'), $langs->trans("Example").': www.mywebsite.com, myportal, ...'); @@ -3314,8 +3293,7 @@ if ($action == 'createsite') print '</table>'; - if ($action == 'createsite') - { + if ($action == 'createsite') { print '<div class="center">'; print '<input class="button" type="submit" name="addcontainer" value="'.$langs->trans("Create").'">'; @@ -3334,8 +3312,7 @@ if ($action == 'createsite') print '<br>'; } -if ($action == 'importsite') -{ +if ($action == 'importsite') { print '<div class="fiche">'; print '<br>'; @@ -3365,8 +3342,7 @@ if ($action == 'importsite') print '<br>'; } -if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of a web site OR properties of a web page -{ +if ($action == 'editmeta' || $action == 'createcontainer') { // Edit properties of a web site OR properties of a web page print '<div class="fiche">'; print '<br>'; @@ -3376,31 +3352,38 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of $head[$h][0] = dol_buildpath('/website/index.php',1).'?id='.$object->id; $head[$h][1] = $langs->trans("AddPage"); - $head[$h][2] = 'card'; + $head[$h][2] = 'card'; $h++; - print dol_get_fiche_head($head, 'card', $langs->trans("AddPage"), -1, 'globe'); - */ - if ($action == 'createcontainer') print load_fiche_titre($langs->trans("AddPage")); + print dol_get_fiche_head($head, 'card', $langs->trans("AddPage"), -1, 'globe'); + */ + if ($action == 'createcontainer') { + print load_fiche_titre($langs->trans("AddPage")); + } print '<!-- Edit or create page/container -->'."\n"; //print '<div class="fichecenter">'; $hiddenfromfetchingafterload = ' hideobject'; $hiddenmanuallyafterload = ' hideobject'; - if (GETPOST('radiocreatefrom') == 'checkboxcreatefromfetching') $hiddenfromfetchingafterload = ''; - if (GETPOST('radiocreatefrom') == 'checkboxcreatemanually') $hiddenmanuallyafterload = ''; + if (GETPOST('radiocreatefrom') == 'checkboxcreatefromfetching') { + $hiddenfromfetchingafterload = ''; + } + if (GETPOST('radiocreatefrom') == 'checkboxcreatemanually') { + $hiddenmanuallyafterload = ''; + } if ($action == 'editmeta' || empty($conf->use_javascript_ajax)) { // No autohide/show in such case $hiddenfromfetchingafterload = ''; $hiddenmanuallyafterload = ''; } - if ($action == 'createcontainer') - { + if ($action == 'createcontainer') { print '<br>'; - if (!empty($conf->use_javascript_ajax)) print '<input type="radio" name="radiocreatefrom" id="checkboxcreatefromfetching" value="checkboxcreatefromfetching"'.(GETPOST('radiocreatefrom') == 'checkboxcreatefromfetching' ? ' checked' : '').'> '; + if (!empty($conf->use_javascript_ajax)) { + print '<input type="radio" name="radiocreatefrom" id="checkboxcreatefromfetching" value="checkboxcreatefromfetching"'.(GETPOST('radiocreatefrom') == 'checkboxcreatefromfetching' ? ' checked' : '').'> '; + } print '<label for="checkboxcreatefromfetching"><span class="opacitymediumxx">'.$langs->trans("CreateByFetchingExternalPage").'</span></label><br>'; print '<hr class="tablecheckboxcreatefromfetching'.$hiddenfromfetchingafterload.'">'; print '<table class="tableforfield centpercent tablecheckboxcreatefromfetching'.$hiddenfromfetchingafterload.'">'; @@ -3421,15 +3404,16 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '<br>'; - if (!empty($conf->use_javascript_ajax)) print '<input type="radio" name="radiocreatefrom" id="checkboxcreatemanually" value="checkboxcreatemanually"'.(GETPOST('radiocreatefrom') == 'checkboxcreatemanually' ? ' checked' : '').'> '; + if (!empty($conf->use_javascript_ajax)) { + print '<input type="radio" name="radiocreatefrom" id="checkboxcreatemanually" value="checkboxcreatemanually"'.(GETPOST('radiocreatefrom') == 'checkboxcreatemanually' ? ' checked' : '').'> '; + } print '<label for="checkboxcreatemanually"><span class="opacitymediumxx">'.$langs->trans("OrEnterPageInfoManually").'</span></label><br>'; print '<hr class="tablecheckboxcreatemanually'.$hiddenmanuallyafterload.'">'; } print '<table class="border tableforfield nobackground centpercent tablecheckboxcreatemanually'.$hiddenmanuallyafterload.'">'; - if ($action != 'createcontainer') - { + if ($action != 'createcontainer') { print '<tr><td class="titlefield fieldrequired">'; print $langs->trans('IDOfPage').' - '.$langs->trans('InternalURLOfPage'); print '</td><td>'; @@ -3459,9 +3443,8 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of $pageauthorid = $objectpage->fk_user_creat; $pageusermodifid = $objectpage->fk_user_modif; $pageauthoralias = $objectpage->author_alias; - $pagestatus = $objectpage->status; - } - else { + $pagestatus = $objectpage->status; + } else { $type_container = 'page'; $pagedatecreation = dol_now(); $pageauthorid = $user->id; @@ -3469,18 +3452,35 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of $pageauthoralias = ''; $pagestatus = 1; } - if (GETPOST('WEBSITE_TITLE', 'alpha')) $pagetitle = str_replace(array('<', '>'), '', GETPOST('WEBSITE_TITLE', 'alphanohtml')); - if (GETPOST('WEBSITE_PAGENAME', 'alpha')) $pageurl = GETPOST('WEBSITE_PAGENAME', 'alpha'); - if (GETPOST('WEBSITE_ALIASALT', 'alpha')) $pagealiasalt = str_replace(array('<', '>'), '', GETPOST('WEBSITE_ALIASALT', 'alphanohtml')); - if (GETPOST('WEBSITE_DESCRIPTION', 'alpha')) $pagedescription = str_replace(array('<', '>'), '', GETPOST('WEBSITE_DESCRIPTION', 'alphanohtml')); - if (GETPOST('WEBSITE_IMAGE', 'alpha')) $pageimage = GETPOST('WEBSITE_IMAGE', 'alpha'); - if (GETPOST('WEBSITE_KEYWORDS', 'alpha')) $pagekeywords = str_replace(array('<', '>'), '', GETPOST('WEBSITE_KEYWORDS', 'alphanohtml')); - if (GETPOST('WEBSITE_LANG', 'aZ09')) $pagelang = GETPOST('WEBSITE_LANG', 'aZ09'); - if (GETPOST('WEBSITE_ALLOWED_IN_FRAMES', 'aZ09')) $pageallowedinframes = GETPOST('WEBSITE_ALLOWED_IN_FRAMES', 'aZ09'); - if (GETPOST('htmlheader', 'none')) $pagehtmlheader = GETPOST('htmlheader', 'none'); + if (GETPOST('WEBSITE_TITLE', 'alpha')) { + $pagetitle = str_replace(array('<', '>'), '', GETPOST('WEBSITE_TITLE', 'alphanohtml')); + } + if (GETPOST('WEBSITE_PAGENAME', 'alpha')) { + $pageurl = GETPOST('WEBSITE_PAGENAME', 'alpha'); + } + if (GETPOST('WEBSITE_ALIASALT', 'alpha')) { + $pagealiasalt = str_replace(array('<', '>'), '', GETPOST('WEBSITE_ALIASALT', 'alphanohtml')); + } + if (GETPOST('WEBSITE_DESCRIPTION', 'alpha')) { + $pagedescription = str_replace(array('<', '>'), '', GETPOST('WEBSITE_DESCRIPTION', 'alphanohtml')); + } + if (GETPOST('WEBSITE_IMAGE', 'alpha')) { + $pageimage = GETPOST('WEBSITE_IMAGE', 'alpha'); + } + if (GETPOST('WEBSITE_KEYWORDS', 'alpha')) { + $pagekeywords = str_replace(array('<', '>'), '', GETPOST('WEBSITE_KEYWORDS', 'alphanohtml')); + } + if (GETPOST('WEBSITE_LANG', 'aZ09')) { + $pagelang = GETPOST('WEBSITE_LANG', 'aZ09'); + } + if (GETPOST('WEBSITE_ALLOWED_IN_FRAMES', 'aZ09')) { + $pageallowedinframes = GETPOST('WEBSITE_ALLOWED_IN_FRAMES', 'aZ09'); + } + if (GETPOST('htmlheader', 'none')) { + $pagehtmlheader = GETPOST('htmlheader', 'none'); + } - if ($action != 'createcontainer') - { + if ($action != 'createcontainer') { print '<!-- Status of page -->'."\n"; print '<tr><td class="fieldrequired">'; print $langs->trans('Status'); @@ -3498,8 +3498,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of $formwebsite->selectTypeOfContainer('WEBSITE_TYPE_CONTAINER', (GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha') ? GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha') : $type_container), 0, '', 1); print '</td></tr>'; - if ($action == 'createcontainer') - { + if ($action == 'createcontainer') { print '<tr><td class="titlefield fieldrequired">'; print $langs->trans('WEBSITE_PAGE_EXAMPLE'); print '</td><td>'; @@ -3553,8 +3552,11 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print $langs->trans('Language'); print '</td><td>'; $onlykeys = array(); - if ($object->lang) $onlykeys[$object->lang] = $object->lang; - else $onlykeys[$langs->defaultlang] = $langs->defaultlang; + if ($object->lang) { + $onlykeys[$object->lang] = $object->lang; + } else { + $onlykeys[$langs->defaultlang] = $langs->defaultlang; + } if ($object->otherlang) { $tmparray = explode(',', $object->otherlang); foreach ($tmparray as $key) { @@ -3579,47 +3581,45 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '<!-- Translation of --><tr><td>'; print $langs->trans('TranslationLinks'); print '</td><td>'; - if ($action != 'createcontainer') - { + if ($action != 'createcontainer') { // Has translation pages $sql = 'SELECT rowid, lang from '.MAIN_DB_PREFIX.'website_page where fk_page = '.$objectpage->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num_rows = $db->num_rows($resql); - if ($num_rows > 0) - { + if ($num_rows > 0) { print '<span class="opacitymedium">'.$langs->trans('ThisPageHasTranslationPages').':</span>'; $i = 0; $tmppage = new WebsitePage($db); $tmpstring = ''; - while ($obj = $db->fetch_object($resql)) - { + while ($obj = $db->fetch_object($resql)) { $result = $tmppage->fetch($obj->rowid); if ($result > 0) { - if ($i > 0) $tmpstring .= '<br>'; + if ($i > 0) { + $tmpstring .= '<br>'; + } $tmpstring .= $tmppage->getNomUrl(1).' ('.$tmppage->lang.')'; $translatedby++; $i++; } } - if ($i > 1) print '<br>'; - else print ' '; + if ($i > 1) { + print '<br>'; + } else { + print ' '; + } print $tmpstring; } + } else { + dol_print_error($db); } - else dol_print_error($db); } - if (empty($translatedby) && ($action == 'editmeta' || $action == 'createcontainer' || $objectpage->fk_page > 0)) - { + if (empty($translatedby) && ($action == 'editmeta' || $action == 'createcontainer' || $objectpage->fk_page > 0)) { $sourcepage = new WebsitePage($db); $result = $sourcepage->fetch($objectpage->fk_page); - if ($result == 0) - { + if ($result == 0) { // not found, we can reset value to clean database - } - elseif ($result > 0) - { + } elseif ($result > 0) { $translationof = $objectpage->fk_page; print '<span class="opacitymedium">'.$langs->trans('ThisPageIsTranslationOf').'</span> '; print $formwebsite->selectContainer($website, 'pageidfortranslation', ($translationof ? $translationof : -1), 1, $action, 'minwidth300', array($objectpage->id)); @@ -3640,8 +3640,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '</td></tr>'; // Categories - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) - { + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { $langs->load('categories'); if (!GETPOSTISSET('categories')) { @@ -3683,8 +3682,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '<tr><td>'; print $langs->trans('Author'); print '</td><td>'; - if ($pageauthorid > 0) - { + if ($pageauthorid > 0) { $fuser->fetch($pageauthorid); print $fuser->getNomUrl(1); } else { @@ -3705,13 +3703,11 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of //print dol_print_date($pagedatecreation, 'dayhour'); print '</td></tr>'; - if ($action != 'createcontainer') - { + if ($action != 'createcontainer') { print '<tr><td>'; print $langs->trans('UserModif'); print '</td><td>'; - if ($pageusermodifid > 0) - { + if ($pageusermodifid > 0) { $fuser->fetch($pageusermodifid); print $fuser->getNomUrl(1); } @@ -3735,8 +3731,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '</td></tr>'; print '</table>'; - if ($action == 'createcontainer') - { + if ($action == 'createcontainer') { print '<div class="center tablecheckboxcreatemanually'.$hiddenmanuallyafterload.'">'; print '<input class="button" type="submit" name="addcontainer" value="'.$langs->trans("Create").'">'; @@ -3745,8 +3740,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '</div>'; } - if ($action == 'createcontainer') - { + if ($action == 'createcontainer') { print '<script type="text/javascript" language="javascript"> jQuery(document).ready(function() { var disableautofillofalias = 0; @@ -3791,27 +3785,32 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '<br>'; } -if ($action == 'editfile' || $action == 'file_manager') -{ + +// Print formconfirm +if ($action == 'preview') { + print $formconfirm; +} + +if ($action == 'editfile' || $action == 'file_manager') { print '<!-- Edit Media -->'."\n"; print '<div class="fiche"><br>'; //print '<div class="center">'.$langs->trans("FeatureNotYetAvailable").'</center>'; $module = 'medias'; - if (empty($url)) $url = DOL_URL_ROOT.'/website/index.php'; // Must be an url without param + if (empty($url)) { + $url = DOL_URL_ROOT.'/website/index.php'; // Must be an url without param + } include DOL_DOCUMENT_ROOT.'/core/tpl/filemanager.tpl.php'; print '</div>'; } -if ($action == 'editmenu') -{ +if ($action == 'editmenu') { print '<!-- Edit Menu -->'."\n"; print '<div class="center">'.$langs->trans("FeatureNotYetAvailable").'</center>'; } -if ($action == 'editsource') -{ +if ($action == 'editsource') { // Editing with source editor $contentforedit = ''; @@ -3821,10 +3820,13 @@ if ($action == 'editsource') $contentforedit .= $objectpage->content; //var_dump($_SESSION["dol_screenheight"]); $maxheightwin = 480; - if (isset($_SESSION["dol_screenheight"])) - { - if ($_SESSION["dol_screenheight"] > 680) $maxheightwin = $_SESSION["dol_screenheight"] - 400; - if ($_SESSION["dol_screenheight"] > 800) $maxheightwin = $_SESSION["dol_screenheight"] - 490; + if (isset($_SESSION["dol_screenheight"])) { + if ($_SESSION["dol_screenheight"] > 680) { + $maxheightwin = $_SESSION["dol_screenheight"] - 400; + } + if ($_SESSION["dol_screenheight"] > 800) { + $maxheightwin = $_SESSION["dol_screenheight"] - 490; + } } //var_dump($_SESSION["dol_screenheight"]); require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -3838,8 +3840,8 @@ if ($action == 'editsource') $contentforedit = ''; //$contentforedit.='<style scoped>'."\n"; // "scoped" means "apply to parent element only". Not yet supported by browsers - //$contentforedit.=$csscontent; - //$contentforedit.='</style>'."\n"; + //$contentforedit.=$csscontent; + //$contentforedit.='</style>'."\n"; $contentforedit .= $objectpage->content; $contentforedit = preg_replace('/(<img.*src=")(?!http)/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $contentforedit, -1, $nbrep); @@ -3853,8 +3855,7 @@ print "</div>\n"; print "</form>\n"; -if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction == 'replace') -{ +if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction == 'replace') { print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="replacesiteconfirm">'; @@ -3916,8 +3917,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print '</div>'; // Categories - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) - { + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { print '<div class="tagtr">'; print '<div class="tagtd paddingrightonly marginrightonly opacitymedium" style="padding-right: 10px !important">'; print $langs->trans("Category"); @@ -3936,16 +3936,14 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print '</div></div>'; - if ($action == 'replacesiteconfirm') - { + if ($action == 'replacesiteconfirm') { print '<!-- List of search result -->'."\n"; print '<div class="rowsearchresult clearboth">'; print '<br>'; print '<br>'; - if ($listofpages['code'] == 'OK') - { + if ($listofpages['code'] == 'OK') { $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; $nbtotalofrecords = count($listofpages['list']); @@ -3954,10 +3952,18 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = // List of mass actions available $arrayofmassactions = array(); - if ($user->rights->website->writephp && $searchkey) $arrayofmassactions['replace'] = $langs->trans("Replace"); - if ($user->rights->website->write) $arrayofmassactions['setcategory'] = $langs->trans("ClassifyInCategory"); - if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); - if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + if ($user->rights->website->writephp && $searchkey) { + $arrayofmassactions['replace'] = $langs->trans("Replace"); + } + if ($user->rights->website->write) { + $arrayofmassactions['setcategory'] = $langs->trans("ClassifyInCategory"); + } + if ($permissiontodelete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); + } + if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton .= '<div class="massactionother massactionreplace hidden">'; @@ -3985,12 +3991,24 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = $param = 'action=replacesiteconfirm&website='.urlencode($website->ref); $param .= '&searchstring='.urlencode($searchkey); - if (GETPOST('optioncontent')) $param .= '&optioncontent=content'; - if (GETPOST('optionmeta')) $param .= '&optionmeta=meta'; - if (GETPOST('optionsitefiles')) $param .= '&optionsitefiles=optionsitefiles'; - if (GETPOST('optioncontainertype')) $param .= '&optioncontainertype='.GETPOST('optioncontainertype', 'aZ09'); - if (GETPOST('optionlanguage')) $param .= '&optionlanguage='.GETPOST('optionlanguage', 'aZ09'); - if (GETPOST('optioncategory')) $param .= '&optioncategory='.GETPOST('optioncategory', 'aZ09'); + if (GETPOST('optioncontent')) { + $param .= '&optioncontent=content'; + } + if (GETPOST('optionmeta')) { + $param .= '&optionmeta=meta'; + } + if (GETPOST('optionsitefiles')) { + $param .= '&optionsitefiles=optionsitefiles'; + } + if (GETPOST('optioncontainertype')) { + $param .= '&optioncontainertype='.GETPOST('optioncontainertype', 'aZ09'); + } + if (GETPOST('optionlanguage')) { + $param .= '&optionlanguage='.GETPOST('optionlanguage', 'aZ09'); + } + if (GETPOST('optioncategory')) { + $param .= '&optioncategory='.GETPOST('optioncategory', 'aZ09'); + } print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; @@ -4000,6 +4018,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print getTitleFieldOfList("Categories", 0, $_SERVER['PHP_SELF']); print getTitleFieldOfList("", 0, $_SERVER['PHP_SELF']); print getTitleFieldOfList("", 0, $_SERVER['PHP_SELF']); + print getTitleFieldOfList("DateLastModification", 0, $_SERVER['PHP_SELF'], 'tms', '', $param, '', $sortfield, $sortorder, 'center ')."\n"; // Date last modif print getTitleFieldOfList("", 0, $_SERVER['PHP_SELF']); print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; print '</tr>'; @@ -4009,10 +4028,8 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = $totalnbwords = 0; - foreach ($listofpages['list'] as $answerrecord) - { - if (get_class($answerrecord) == 'WebsitePage') - { + foreach ($listofpages['list'] as $answerrecord) { + if (get_class($answerrecord) == 'WebsitePage') { print '<tr>'; // Type of container @@ -4032,8 +4049,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = // Categories - Tags print '<td>'; - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) - { + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { // Get current categories $existing = $c->containing($answerrecord->id, Categorie::TYPE_WEBSITE_PAGE, 'object'); if (is_array($existing)) { @@ -4073,6 +4089,10 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = } print '</td>'; + // Date last modification + print '<td class="center nowraponall">'; + print dol_print_date($answerrecord->date_modification, 'dayhour'); + print '</td>'; // Edit properties, HTML sources, status print '<td class="tdwebsitesearchresult right nowraponall">'; @@ -4100,10 +4120,11 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print '<td class="nowrap center">'; print '<!-- Status of page -->'."\n"; - if ($massactionbutton || $massaction) - { + if ($massactionbutton || $massaction) { $selected = 0; - if (in_array($answerrecord->id, $arrayofselected)) $selected = 1; + if (in_array($answerrecord->id, $arrayofselected)) { + $selected = 1; + } print '<input id="'.$answerrecord->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$answerrecord->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; @@ -4158,6 +4179,11 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print '<td>'; print '</td>'; + // Date last modification + print '<td class="center nowraponall">'; + //print dol_print_date(filemtime()); + print '</td>'; + // Edit properties, HTML sources, status print '<td>'; print '</td>'; @@ -4196,6 +4222,10 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print $totalnbwords.' '.$langs->trans("words"); print '</td>'; + // Date last modification + print '<td>'; + print '</td>'; + // Edit properties, HTML sources, status print '<td>'; print '</td>'; @@ -4210,8 +4240,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print '</table>'; print '</div>'; print '<br>'; - } - else { + } else { print '<div class="warning">'.$listofpages['message'].'</div>'; } @@ -4221,10 +4250,8 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print '</form>'; } -if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') -{ - if ($pageid > 0 && $atleastonepage) - { +if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') { + if ($pageid > 0 && $atleastonepage) { // $filejs // $filecss // $filephp @@ -4274,7 +4301,7 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa // REPLACEMENT OF LINKS When page called by website editor $out .= '<!-- style of website from file -->'."\n"; - $out .= '<style scoped>'."\n"; // "scoped" means "apply to parent element only". No more supported by browsers, snif ! + $out .= '<style scoped>'."\n"; // "scoped" means "apply to parent element only and not grand parent". No more supported by browsers, snif ! $tmpout = ''; $tmpout .= '/* Include website CSS file */'."\n"; //$csscontent = @file_get_contents($filecss); @@ -4288,10 +4315,11 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa $tmp = preg_split('(<style[^>]*>|</style>)', $objectpage->htmlheader); $tmpstyleinheader = ''; $i = 0; - foreach ($tmp as $valtmp) - { + foreach ($tmp as $valtmp) { $i++; - if ($i % 2 == 0) $tmpstyleinheader .= $valtmp."\n"; + if ($i % 2 == 0) { + $tmpstyleinheader .= $valtmp."\n"; + } } $tmpout .= $tmpstyleinheader."\n"; // Clean style that may affect global style of Dolibarr @@ -4309,8 +4337,7 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa $newcontent = $objectpage->content; // If mode WEBSITE_SUBCONTAINERSINLINE is on - if (!empty($conf->global->WEBSITE_SUBCONTAINERSINLINE)) - { + if (!empty($conf->global->WEBSITE_SUBCONTAINERSINLINE)) { // TODO Check file $filephp exists, if not create it. //var_dump($filetpl); @@ -4321,8 +4348,7 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa if (empty($res)) { print "ERROR: Failed to include file '".$filephp."'. Try to edit and save page."; } - } catch (Exception $e) - { + } catch (Exception $e) { print $e->getMessage(); } $newcontent = ob_get_contents(); @@ -4330,12 +4356,10 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa } // Change the contenteditable to "true" or "false" when mode Edit Inline is on or off - if (empty($conf->global->WEBSITE_EDITINLINE)) - { + if (empty($conf->global->WEBSITE_EDITINLINE)) { // Remove the contenteditable="true" $newcontent = preg_replace('/(div|section)(\s[^\>]*)contenteditable="true"/', '\1\2', $newcontent); - } - else { + } else { // Keep the contenteditable="true" when mode Edit Inline is on } $out .= dolWebsiteReplacementOfLinks($object, $newcontent, 0, 'html', $objectpage->id)."\n"; @@ -4356,33 +4380,30 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa print $out; /*file_put_contents($filetpl, $out); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filetpl, octdec($conf->global->MAIN_UMASK)); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filetpl, octdec($conf->global->MAIN_UMASK)); - // Output file on browser - dol_syslog("index.php include $filetpl $filename content-type=$type"); - $original_file_osencoded=dol_osencode($filetpl); // New file name encoded in OS encoding charset + // Output file on browser + dol_syslog("index.php include $filetpl $filename content-type=$type"); + $original_file_osencoded=dol_osencode($filetpl); // New file name encoded in OS encoding charset - // This test if file exists should be useless. We keep it to find bug more easily - if (! file_exists($original_file_osencoded)) - { - dol_print_error(0,$langs->trans("ErrorFileDoesNotExists",$original_file)); - exit; - } + // This test if file exists should be useless. We keep it to find bug more easily + if (! file_exists($original_file_osencoded)) + { + dol_print_error(0,$langs->trans("ErrorFileDoesNotExists",$original_file)); + exit; + } - //include_once $original_file_osencoded; - */ + //include_once $original_file_osencoded; + */ /*print '<iframe class="websiteiframenoborder centpercent" src="'.DOL_URL_ROOT.'/public/website/index.php?website='.$websitekey.'&pageid='.$pageid.'"/>'; - print '</iframe>';*/ - } - else { - if (empty($websitekey) || $websitekey == '-1') - { + print '</iframe>';*/ + } else { + if (empty($websitekey) || $websitekey == '-1') { print '<br><br><div class="center previewnotyetavailable"><span class="">'.$langs->trans("NoWebSiteCreateOneFirst").'</span></div><br><br><br>'; print '<div class="center"><div class="logo_setup"></div></div>'; - } - else { + } else { print '<br><br><div class="center previewnotyetavailable"><span class="">'.$langs->trans("PreviewOfSiteNotYetAvailable", $object->ref).'</span></div><br><br><br>'; print '<div class="center"><div class="logo_setup"></div></div>'; } diff --git a/htdocs/website/samples/wrapper.php b/htdocs/website/samples/wrapper.php index 24b804058ea..b847f607bf3 100644 --- a/htdocs/website/samples/wrapper.php +++ b/htdocs/website/samples/wrapper.php @@ -1,8 +1,12 @@ <?php // BEGIN PHP File wrapper.php - DO NOT MODIFY - It is just a copy of file website/samples/wrapper.php $websitekey = basename(__DIR__); -if (strpos($_SERVER["PHP_SELF"], 'website/samples/wrapper.php')) die("Sample file for website module. Can be called directly."); -if (!defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load master if not already loaded +if (strpos($_SERVER["PHP_SELF"], 'website/samples/wrapper.php')) { + die("Sample file for website module. Can be called directly."); +} +if (!defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) { + require_once './master.inc.php'; +} // Load master if not already loaded include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; $encoding = ''; @@ -17,42 +21,36 @@ $limit = GETPOST('limit', 'int'); // Parameters for RSS $rss = GETPOST('rss', 'aZ09'); -if ($rss) $original_file = 'blog.rss'; +if ($rss) { + $original_file = 'blog.rss'; +} // If we have a hash public (hashp), we guess the original_file. -if (!empty($hashp)) -{ +if (!empty($hashp)) { include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile = new EcmFiles($db); $result = $ecmfile->fetch(0, '', '', '', $hashp); - if ($result > 0) - { + if ($result > 0) { $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory // filepath can be 'users/X' or 'X/propale/PR11111' - if (is_numeric($tmp[0])) // If first tmp is numeric, it is subdir of company for multicompany, we take next part. - { + if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part. $tmp = explode('/', $tmp[1], 2); } $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path - if ($modulepart) // Not required, so often not defined, for link using public hashp parameter. - { - if ($moduleparttocheck == $modulepart) - { + if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter. + if ($moduleparttocheck == $modulepart) { // We remove first level of directory $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir //var_dump($original_file); exit; - } - else { + } else { print 'Bad link. File is from another module part.'; } - } - else { + } else { $modulepart = $moduleparttocheck; $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir } - } - else { + } else { print "ErrorFileNotFoundWithSharedLink"; exit; } @@ -60,21 +58,29 @@ if (!empty($hashp)) // Define attachment (attachment=true to force choice popup 'open'/'save as') $attachment = true; -if (preg_match('/\.(html|htm)$/i', $original_file)) $attachment = false; -if (isset($_GET["attachment"])) $attachment = (GETPOST("attachment", 'alphanohtml') ? true : false); -if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS_WEBSITE)) $attachment = false; +if (preg_match('/\.(html|htm)$/i', $original_file)) { + $attachment = false; +} +if (isset($_GET["attachment"])) { + $attachment = (GETPOST("attachment", 'alphanohtml') ? true : false); +} +if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS_WEBSITE)) { + $attachment = false; +} // Define mime type $type = 'application/octet-stream'; -if (GETPOSTISSET('type')) $type = GETPOST('type', 'alpha'); -else $type = dol_mimetype($original_file); +if (GETPOSTISSET('type')) { + $type = GETPOST('type', 'alpha'); +} else { + $type = dol_mimetype($original_file); +} // Security: Delete string ../ into $original_file $original_file = str_replace("../", "/", $original_file); // Cache or not -if (GETPOST("cache", 'aZ09') || image_format_supported($original_file) >= 0) -{ +if (GETPOST("cache", 'aZ09') || image_format_supported($original_file) >= 0) { // Important: Following code is to avoid page request by browser and PHP CPU at // each Dolibarr page access. header('Cache-Control: max-age=3600, public, must-revalidate'); @@ -99,7 +105,9 @@ if ($rss) { $website->fetch('', $websitekey); $filters = array('type_container'=>'blogpost'); - if ($l) $filters['lang'] = $l; + if ($l) { + $filters['lang'] = $l; + } $MAXNEWS = ($limit ? $limit : 20); $arrayofblogs = $websitepage->fetchAll($website->id, 'DESC', 'date_creation', $MAXNEWS, 0, $filters); @@ -118,8 +126,7 @@ if ($rss) { dol_syslog("build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG); // Clean parameters - if (!$filename) - { + if (!$filename) { $extension = 'rss'; $filename = $format.'.'.$extension; } @@ -132,19 +139,16 @@ if ($rss) { $buildfile = true; - if ($cachedelay) - { + if ($cachedelay) { $nowgmt = dol_now(); include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay)) - { + if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay)) { dol_syslog("build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled"); $buildfile = false; } } - if ($buildfile) - { + if ($buildfile) { $langs->load("other"); $title = $desc = $langs->transnoentities('LatestBlogPosts'); @@ -155,18 +159,17 @@ if ($rss) { // Write file $result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp, '', $website->virtualhost.'/wrapper.php?rss=1'.($l ? '&l='.$l : ''), $l); - if ($result >= 0) - { - if (dol_move($outputfiletmp, $outputfile, 0, 1)) $result = 1; - else { + if ($result >= 0) { + if (dol_move($outputfiletmp, $outputfile, 0, 1)) { + $result = 1; + } else { $error = 'Failed to rename '.$outputfiletmp.' into '.$outputfile; dol_syslog("build_exportfile ".$error, LOG_ERR); dol_delete_file($outputfiletmp, 0, 1); print $error; exit(-1); } - } - else { + } else { dol_syslog("build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR); dol_delete_file($outputfiletmp, 0, 1); $langs->load("errors"); @@ -175,56 +178,63 @@ if ($rss) { } } - if ($result >= 0) - { + if ($result >= 0) { $attachment = false; - if (isset($_GET["attachment"])) $attachment = $_GET["attachment"]; + if (isset($_GET["attachment"])) { + $attachment = $_GET["attachment"]; + } //$attachment = false; $contenttype = 'application/rss+xml'; - if (isset($_GET["contenttype"])) $contenttype = $_GET["contenttype"]; + if (isset($_GET["contenttype"])) { + $contenttype = $_GET["contenttype"]; + } //$contenttype='text/plain'; $outputencoding = 'UTF-8'; - if ($contenttype) header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : '')); - if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"'); + if ($contenttype) { + header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : '')); + } + if ($attachment) { + header('Content-Disposition: attachment; filename="'.$filename.'"'); + } // Ajout directives pour resoudre bug IE //header('Cache-Control: Public, must-revalidate'); //header('Pragma: public'); - if ($cachedelay) header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate'); - else header('Cache-Control: private, must-revalidate'); + if ($cachedelay) { + header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate'); + } else { + header('Cache-Control: private, must-revalidate'); + } // Clean parameters $outputfile = $dir_temp.'/'.$filename; $result = readfile($outputfile); - if (!$result) print 'File '.$outputfile.' was empty.'; + if (!$result) { + print 'File '.$outputfile.' was empty.'; + } // header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename)); exit; } -} -// Get logos -elseif ($modulepart == "mycompany" && preg_match('/^\/?logos\//', $original_file)) -{ +} elseif ($modulepart == "mycompany" && preg_match('/^\/?logos\//', $original_file)) { + // Get logos readfile(dol_osencode($conf->mycompany->dir_output."/".$original_file)); -} -else { +} else { // Find the subdirectory name as the reference include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $refname); $accessallowed = $check_access['accessallowed']; $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals']; $fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name - if ($hashp) - { + if ($hashp) { $accessallowed = 1; // When using hashp, link is public so we force $accessallowed $sqlprotectagainstexternals = ''; } // Security: // Limit access if permissions are wrong - if (!$accessallowed) - { + if (!$accessallowed) { print 'Access forbidden'; exit; } @@ -238,8 +248,7 @@ else { $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset // This test if file exists should be useless. We keep it to find bug more easily - if (!file_exists($fullpath_original_file_osencoded)) - { + if (!file_exists($fullpath_original_file_osencoded)) { print "ErrorFileDoesNotExists: ".$original_file; exit; } @@ -248,13 +257,20 @@ else { //top_httphead($type); header('Content-Type: '.$type); header('Content-Description: File Transfer'); - if ($encoding) header('Content-Encoding: '.$encoding); + if ($encoding) { + header('Content-Encoding: '.$encoding); + } // Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open) - if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"'); - else header('Content-Disposition: inline; filename="'.$filename.'"'); + if ($attachment) { + header('Content-Disposition: attachment; filename="'.$filename.'"'); + } else { + header('Content-Disposition: inline; filename="'.$filename.'"'); + } header('Content-Length: '.dol_filesize($fullpath_original_file)); readfile($fullpath_original_file_osencoded); } -if (is_object($db)) $db->close(); +if (is_object($db)) { + $db->close(); +} // END PHP diff --git a/htdocs/website/websiteaccount_card.php b/htdocs/website/websiteaccount_card.php index 17f50e709b7..e63c3cb8fef 100644 --- a/htdocs/website/websiteaccount_card.php +++ b/htdocs/website/websiteaccount_card.php @@ -53,12 +53,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); @@ -80,10 +83,11 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ $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 (empty($reshook)) { $error = 0; $permissiontoadd = $user->rights->website->write; @@ -130,8 +134,7 @@ jQuery(document).ready(function() { // Part to create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("WebsiteAccount"))); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; @@ -163,8 +166,7 @@ if ($action == 'create') } // Part to edit record -if (($id || $ref) && $action == 'edit') -{ +if (($id || $ref) && $action == 'edit') { print load_fiche_titre($langs->trans("WebsiteAccount")); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; @@ -194,9 +196,10 @@ if (($id || $ref) && $action == 'edit') } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ - if ($object->fk_soc > 0 && empty($socid)) $socid = $object->fk_soc; +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { + if ($object->fk_soc > 0 && empty($socid)) { + $socid = $object->fk_soc; + } $res = $object->fetch_optionals(); @@ -213,8 +216,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -223,8 +229,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Object card // ------------------------------------------------------------ $linkback = ''; - if ($socid) $linkback = '<a href="'.DOL_URL_ROOT.'/societe/website.php?socid='.$socid.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToListForThirdParty").'</a>'; - if ($fk_website) $linkback = '<a href="'.DOL_URL_ROOT.'/website/website_card.php?fk_website='.$fk_website.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>'; + if ($socid) { + $linkback = '<a href="'.DOL_URL_ROOT.'/societe/website.php?socid='.$socid.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToListForThirdParty").'</a>'; + } + if ($fk_website) { + $linkback = '<a href="'.DOL_URL_ROOT.'/website/website_card.php?fk_website='.$fk_website.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>'; + } $morehtmlref = '<div class="refidno">'; /* @@ -236,41 +246,43 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='<br>'.$langs->trans('Project') . ' '; - if ($user->rights->website->creer) - { - if ($action != 'classify') - { - $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; - $morehtmlref.='<input type="hidden" name="action" value="classin">'; - $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; - $morehtmlref.='</form>'; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">'; - $morehtmlref.=$proj->ref; - $morehtmlref.='</a>'; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='<br>'.$langs->trans('Project') . ' '; + if ($user->rights->website->creer) + { + if ($action != 'classify') + { + $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref.='<input type="hidden" name="action" value="classin">'; + $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref.='</form>'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">'; + $morehtmlref.=$proj->ref; + $morehtmlref.='</a>'; + } else { + $morehtmlref.=''; + } + } } */ $morehtmlref .= '</div>'; - if ($socid > 0) $object->next_prev_filter = 'te.fk_soc = '.$socid; + if ($socid > 0) { + $object->next_prev_filter = 'te.fk_soc = '.$socid; + } dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'rowid', $morehtmlref); @@ -301,36 +313,35 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<div class="tabsAction">'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Send if (empty($user->socid)) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>'."\n"; } - if ($user->rights->website->write) - { + if ($user->rights->website->write) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'."\n"; } /* - if ($user->rights->sellyoursaas->create) - { - if ($object->status == 1) - { - print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=disable">'.$langs->trans("Disable").'</a></div>'."\n"; - } - else - { - print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=enable">'.$langs->trans("Enable").'</a></div>'."\n"; - } - } - */ - - if ($user->rights->website->delete) + if ($user->rights->sellyoursaas->create) { + if ($object->status == 1) + { + print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=disable">'.$langs->trans("Disable").'</a></div>'."\n"; + } + else + { + print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=enable">'.$langs->trans("Enable").'</a></div>'."\n"; + } + } + */ + + if ($user->rights->website->delete) { print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>'."\n"; } } @@ -343,21 +354,20 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre print '</div><div class="fichehalfright"><div class="ficheaddleft">'; /* - $MAXEVENT = 10; + $MAXEVENT = 10; - // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; - $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'websiteaccount', $socid, 1, '', $MAXEVENT); - */ + // List of actions on element + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'websiteaccount', $socid, 1, '', $MAXEVENT); + */ print '</div></div></div>'; } diff --git a/htdocs/workstation/class/index.html b/htdocs/workstation/class/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/workstation/class/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/workstation/class/workstation.class.php b/htdocs/workstation/class/workstation.class.php index 31497cbc919..07edb353aa4 100755 --- a/htdocs/workstation/class/workstation.class.php +++ b/htdocs/workstation/class/workstation.class.php @@ -177,15 +177,19 @@ class Workstation extends CommonObject { global $conf, $langs; - dol_include_once('/workstation/class/workstationusergroup.class.php'); - dol_include_once('/workstation/class/workstationresource.class.php'); + require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstationusergroup.class.php'; + require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstationresource.class.php'; $this->db = $db; $this->fields['ref']['default'] = $this->getNextNumRef(); - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } // Example to show how to set values of fields definition dynamically /*if ($user->rights->workstation->workstation->read) { @@ -194,23 +198,17 @@ class Workstation extends CommonObject }*/ // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } // Translate some data of arrayofkeyval - if (is_object($langs)) - { - foreach ($this->fields as $key => $val) - { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } @@ -233,7 +231,9 @@ class Workstation extends CommonObject // Usergroups $groups = GETPOST('groups'); - if (empty($groups)) $groups = $this->usergroups; // createFromClone + if (empty($groups)) { + $groups = $this->usergroups; // createFromClone + } if (!empty($groups)) { foreach ($groups as $id_group) { $ws_usergroup = new WorkstationUserGroup($db); @@ -246,7 +246,9 @@ class Workstation extends CommonObject // Resources $resources = GETPOST('resources'); - if (empty($resources)) $resources = $this->resources; // createFromClone + if (empty($resources)) { + $resources = $this->resources; // createFromClone + } if (!empty($resources)) { foreach ($resources as $id_resource) { $ws_resource = new WorkstationResource($db); @@ -280,7 +282,9 @@ class Workstation extends CommonObject // Load source object $result = $object->fetch($fromid); - if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); + if ($result > 0 && !empty($object->table_element_line)) { + $object->fetchLines(); + } // get lines so they will be clone //foreach($this->lines as $line) @@ -292,21 +296,28 @@ class Workstation extends CommonObject unset($object->import_key); // Clear fields - if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; - if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; - if (property_exists($object, 'status')) { $object->status = self::STATUS_DISABLED; } - if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); } - if (property_exists($object, 'date_modification')) { $object->date_modification = null; } + if (property_exists($object, 'ref')) { + $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; + } + if (property_exists($object, 'label')) { + $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; + } + if (property_exists($object, 'status')) { + $object->status = self::STATUS_DISABLED; + } + if (property_exists($object, 'date_creation')) { + $object->date_creation = dol_now(); + } + if (property_exists($object, 'date_modification')) { + $object->date_modification = null; + } // ... // Clear extrafields that are unique - if (is_array($object->array_options) && count($object->array_options) > 0) - { + if (is_array($object->array_options) && count($object->array_options) > 0) { $extrafields->fetch_name_optionals_label($this->table_element); - foreach ($object->array_options as $key => $option) - { + foreach ($object->array_options as $key => $option) { $shortkey = preg_replace('/options_/', '', $key); - if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) - { + if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) { //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; unset($object->array_options[$key]); } @@ -322,22 +333,19 @@ class Workstation extends CommonObject $this->errors = $object->errors; } - if (!$error) - { + if (!$error) { // copy internal contacts - if ($this->copy_linked_contact($object, 'internal') < 0) - { + if ($this->copy_linked_contact($object, 'internal') < 0) { $error++; } } - if (!$error) - { + if (!$error) { // copy external contacts if same company - if (property_exists($this, 'socid') && $this->socid == $object->socid) - { - if ($this->copy_linked_contact($object, 'external') < 0) + if (property_exists($this, 'socid') && $this->socid == $object->socid) { + if ($this->copy_linked_contact($object, 'external') < 0) { $error++; + } } } @@ -367,7 +375,9 @@ class Workstation extends CommonObject $this->usergroups = WorkstationUserGroup::getAllGroupsOfWorkstation($this->id); $this->resources = WorkstationResource::getAllResourcesOfWorkstation($this->id); - if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); + if ($result > 0 && !empty($this->table_element_line)) { + $this->fetchLines(); + } return $result; } @@ -407,8 +417,11 @@ class Workstation extends CommonObject $sql = 'SELECT '; $sql .= $this->getFieldList(); $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; - else $sql .= ' WHERE 1 = 1'; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { + $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; + } else { + $sql .= ' WHERE 1 = 1'; + } // Manage filter $sqlwhere = array(); if (count($filter) > 0) { @@ -441,8 +454,7 @@ class Workstation extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < ($limit ? min($limit, $num) : $num)) - { + while ($i < ($limit ? min($limit, $num) : $num)) { $obj = $this->db->fetch_object($resql); $record = new self($this->db); @@ -526,8 +538,7 @@ class Workstation extends CommonObject */ public function deleteLine(User $user, $idline, $notrigger = false) { - if ($this->status < 0) - { + if ($this->status < 0) { $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; return -2; } @@ -552,8 +563,7 @@ class Workstation extends CommonObject $error = 0; // Protection - if ($this->status == self::STATUS_VALIDATED) - { + if ($this->status == self::STATUS_VALIDATED) { dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); return 0; } @@ -571,8 +581,7 @@ class Workstation extends CommonObject $this->db->begin(); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef(); } else { $num = $this->ref; @@ -584,57 +593,58 @@ class Workstation extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql .= " SET ref = '".$this->db->escape($num)."',"; $sql .= " status = ".self::STATUS_VALIDATED; - if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."'"; - if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".$user->id; + if (!empty($this->fields['date_validation'])) { + $sql .= ", date_validation = '".$this->db->idate($now)."'"; + } + if (!empty($this->fields['fk_user_valid'])) { + $sql .= ", fk_user_valid = ".$user->id; + } $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::validate()", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $this->error = $this->db->lasterror(); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('WORKSTATION_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'workstation/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'workstation/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->workstation->dir_output.'/workstation/'.$oldref; $dirdest = $conf->workstation->dir_output.'/workstation/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->workstation->dir_output.'/workstation/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -647,14 +657,12 @@ class Workstation extends CommonObject } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $num; $this->status = self::STATUS_VALIDATED; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -677,8 +685,11 @@ class Workstation extends CommonObject $this->status = $status; - if (empty($status)) return $this->setDisabled($user, $notrigger); - else return $this->setEnabled($user, $notrigger); + if (empty($status)) { + return $this->setDisabled($user, $notrigger); + } else { + return $this->setEnabled($user, $notrigger); + } } @@ -721,7 +732,9 @@ class Workstation extends CommonObject { global $conf, $langs, $hookmanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -734,25 +747,28 @@ class Workstation extends CommonObject $url = dol_buildpath('/workstation/workstation_card.php', 1).'?id='.$this->id; - if ($option != 'nolink') - { + 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'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowWorkstation"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = '<a href="'.$url.'"'; $linkstart .= $linkclose.'>'; @@ -761,7 +777,9 @@ class Workstation extends CommonObject $result .= $linkstart; if (empty($this->showphoto_on_popup)) { - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'mrp'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'mrp'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } } else { if ($withpicto) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -787,7 +805,9 @@ class Workstation extends CommonObject } } - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -796,8 +816,11 @@ class Workstation extends CommonObject $hookmanager->initHooks(array('workstationdao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -824,8 +847,7 @@ class Workstation extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("workstation@workstation"); $this->labelStatus[self::STATUS_DISABLED] = $langs->trans('Disabled'); @@ -850,30 +872,25 @@ class Workstation 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)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; @@ -913,8 +930,7 @@ class Workstation extends CommonObject $objectline = new WorkstationLine($this->db); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_workstation = '.$this->id)); - if (is_numeric($result)) - { + if (is_numeric($result)) { $this->error = $this->error; $this->errors = $this->errors; return $result; @@ -938,8 +954,7 @@ class Workstation extends CommonObject $conf->global->WORKSTATION_WORKSTATION_ADDON = 'mod_workstation_standard'; } - if (!empty($conf->global->WORKSTATION_WORKSTATION_ADDON)) - { + if (!empty($conf->global->WORKSTATION_WORKSTATION_ADDON)) { $mybool = false; $file = $conf->global->WORKSTATION_WORKSTATION_ADDON.".php"; @@ -947,16 +962,14 @@ class Workstation extends CommonObject // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/workstation/"); // Load file with numbering class (if found) $mybool |= @include_once $dir.$file; } - if ($mybool === false) - { + if ($mybool === false) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -965,8 +978,7 @@ class Workstation extends CommonObject $obj = new $classname(); $numref = $obj->getNextValue($this); - if ($numref != '' && $numref != '-1') - { + if ($numref != '' && $numref != '-1') { return $numref; } else { $this->error = $obj->error; diff --git a/htdocs/workstation/class/workstationresource.class.php b/htdocs/workstation/class/workstationresource.class.php index 6e6860f2230..72fb91cfe85 100644 --- a/htdocs/workstation/class/workstationresource.class.php +++ b/htdocs/workstation/class/workstationresource.class.php @@ -65,23 +65,17 @@ class WorkstationResource extends CommonObject $this->db = $db; // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } // Translate some data of arrayofkeyval - if (is_object($langs)) - { - foreach ($this->fields as $key => $val) - { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } @@ -95,7 +89,7 @@ class WorkstationResource extends CommonObject * @param int $fk_workstation Id of workstation we need to get linked resources * @return array Array of record */ - static public function getAllResourcesOfWorkstation($fk_workstation) + public static function getAllResourcesOfWorkstation($fk_workstation) { global $db; $obj = new self($db); @@ -108,7 +102,7 @@ class WorkstationResource extends CommonObject * @param int $fk_workstation Id of workstation we need to remove linked resources * @return int <0 if KO, 0 if nothing done, >0 if OK and something done */ - static public function deleteAllResourcesOfWorkstation($fk_workstation) + public static function deleteAllResourcesOfWorkstation($fk_workstation) { global $db; $obj = new self($db); diff --git a/htdocs/workstation/class/workstationusergroup.class.php b/htdocs/workstation/class/workstationusergroup.class.php index 920fb896bdc..86fdda7ce66 100644 --- a/htdocs/workstation/class/workstationusergroup.class.php +++ b/htdocs/workstation/class/workstationusergroup.class.php @@ -64,23 +64,17 @@ class WorkstationUserGroup extends CommonObject $this->db = $db; // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } // Translate some data of arrayofkeyval - if (is_object($langs)) - { - foreach ($this->fields as $key => $val) - { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } @@ -94,7 +88,7 @@ class WorkstationUserGroup extends CommonObject * @param int $fk_workstation id of workstation we need to get linked usergroups * @return array Array of record */ - static public function getAllGroupsOfWorkstation($fk_workstation) + public static function getAllGroupsOfWorkstation($fk_workstation) { global $db; @@ -108,7 +102,7 @@ class WorkstationUserGroup extends CommonObject * @param int $fk_workstation Id of workstation we need to remove linked usergroups * @return int <0 if KO, 0 if nothing done, >0 if OK and something done */ - static public function deleteAllGroupsOfWorkstation($fk_workstation) + public static function deleteAllGroupsOfWorkstation($fk_workstation) { global $db; diff --git a/htdocs/workstation/index.html b/htdocs/workstation/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/workstation/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/workstation/lib/index.html b/htdocs/workstation/lib/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/workstation/lib/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/workstation/lib/workstation_workstation.lib.php b/htdocs/workstation/lib/workstation_workstation.lib.php index cc7fcc58f89..a0cd7736d88 100755 --- a/htdocs/workstation/lib/workstation_workstation.lib.php +++ b/htdocs/workstation/lib/workstation_workstation.lib.php @@ -41,14 +41,19 @@ function workstationPrepareHead($object) $head[$h][2] = 'card'; $h++; - if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) - { + if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = dol_buildpath('/workstation/workstation_note.php', 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbNote.'</span>' : ''); + if ($nbNote > 0) { + $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbNote.'</span>' : ''); + } $head[$h][2] = 'note'; $h++; } @@ -60,7 +65,9 @@ function workstationPrepareHead($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = dol_buildpath("/workstation/workstation_document.php", 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; + } $head[$h][2] = 'document'; $h++; diff --git a/htdocs/workstation/workstation_agenda.php b/htdocs/workstation/workstation_agenda.php index e2951554488..385aa3c41f1 100755 --- a/htdocs/workstation/workstation_agenda.php +++ b/htdocs/workstation/workstation_agenda.php @@ -22,47 +22,13 @@ * \brief Tab of events on Workstation */ -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. -//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value -//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler -//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message -//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies -//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET -//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification - // Load Dolibarr environment -$res = 0; -// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; -// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; -// Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); - +require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -dol_include_once('/workstation/class/workstation.class.php'); -dol_include_once('/workstation/lib/workstation_workstation.lib.php'); +require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/workstation/lib/workstation_workstation.lib.php'; // Load translation files required by the page @@ -77,7 +43,9 @@ $backtopage = GETPOST('backtopage', 'alpha'); 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)); } @@ -87,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 (!$sortfield) $sortfield = 'a.datep,a.id'; -if (!$sortorder) $sortorder = 'DESC,DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC'; +} // Initialize technical objects $object = new Workstation($db); @@ -104,7 +78,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->workstation->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->workstation->multidir_output[$object->entity]."/".$object->id; +} // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); @@ -120,20 +96,19 @@ $permissiontoadd = $user->rights->workstation->workstation->write; // Used by th $parameters = array('id'=>$id); $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 (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // 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 $actioncode = ''; $search_agenda_label = ''; } @@ -147,14 +122,15 @@ if (empty($reshook)) $form = new Form($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $title = $langs->trans("Agenda"); //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; $help_url = ''; llxHeader('', $title, $help_url); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = workstationPrepareHead($object); @@ -228,10 +204,11 @@ if ($object->id > 0) $urlbacktopage = $_SERVER['PHP_SELF'].'?id='.$object->id; $out .= '&backtopage='.urlencode($urlbacktopage); $permok = $user->rights->agenda->myactions->create; - if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) - { + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { //$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'; - if (get_class($objthirdparty) == 'Societe') $out .= '&socid='.urlencode($objthirdparty->id); + if (get_class($objthirdparty) == 'Societe') { + $out .= '&socid='.urlencode($objthirdparty->id); + } $out .= (!empty($objcon->id) ? '&contactid='.urlencode($objcon->id) : '').'&percentage=-1'; //$out.=$langs->trans("AddAnAction").' '; //$out.=img_picto($langs->trans("AddAnAction"),'filenew'); @@ -241,10 +218,8 @@ if ($object->id > 0) print '<div class="tabsAction">'; - if (!empty($conf->agenda->enabled)) - { - if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) - { + if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'">'.$langs->trans("AddAction").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>'; @@ -253,11 +228,14 @@ if ($object->id > 0) print '</div>'; - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $param = '&id='.$object->id.'&socid='.$socid; - 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); + } //print load_fiche_titre($langs->trans("ActionsOnWorkstation"), '', ''); diff --git a/htdocs/workstation/workstation_card.php b/htdocs/workstation/workstation_card.php index e5d51b20c84..c15053bad5e 100755 --- a/htdocs/workstation/workstation_card.php +++ b/htdocs/workstation/workstation_card.php @@ -22,49 +22,15 @@ * \brief Page to create/edit/view workstation */ -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. -//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value -//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler -//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message -//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies -//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET -//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification - // Load Dolibarr environment -$res = 0; -// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; -// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; -// Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); - +require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php'; -dol_include_once('/workstation/class/workstation.class.php'); -dol_include_once('/workstation/lib/workstation_workstation.lib.php'); -dol_include_once('/workstation/class/workstationusergroup.class.php'); +require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/workstation/lib/workstation_workstation.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstationusergroup.class.php'; // Load translation files required by the page $langs->loadLangs(array("workstation@workstation", "other")); @@ -96,12 +62,15 @@ $hookmanager->initHooks(array('workstationcard', 'globalcard')); // Note that co // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. @@ -119,7 +88,9 @@ $upload_dir = $conf->workstation->multidir_output[isset($object->entity) ? $obje //$isdraft = (($object->statut == $object::STATUS_DRAFT) ? 1 : 0); //$result = restrictedArea($user, 'workstation', $object->id, '', '', 'fk_soc', 'rowid', $isdraft); -if (!$permissiontoread) accessforbidden(); +if (!$permissiontoread) { + accessforbidden(); +} /* @@ -128,18 +99,22 @@ if (!$permissiontoread) accessforbidden(); $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 (empty($reshook)) { $error = 0; $backurlforlist = dol_buildpath('/workstation/workstation_list.php', 1); if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = dol_buildpath('/workstation/workstation_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('/workstation/workstation_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + } } } @@ -161,9 +136,13 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; if ($action == 'confirm_enable' && $confirm == "yes" && $permissiontoadd) { - if (!empty($object->id)) $object->setStatus(1); + if (!empty($object->id)) { + $object->setStatus(1); + } } elseif ($action == 'confirm_disable' && $confirm == "yes" && $permissiontoadd) { - if (!empty($object->id)) $object->setStatus(0); + if (!empty($object->id)) { + $object->setStatus(0); + } } } @@ -181,7 +160,9 @@ $formfile = new FormFile($db); $formresource = new FormResource($db); $title = $langs->trans("Workstation"); -$help_url = ''; + +$help_url = 'EN:Module_Workstation'; + llxHeader('', $title, $help_url); // Example : Adding jquery code @@ -191,10 +172,10 @@ llxHeader('', $title, $help_url); jQuery(document).ready(function() { jQuery("#type").change(function() { if($(this).val() === 'MACHINE') { - $('#usergroups').hide(); - $('#nb_operators_required').parent('td').parent('tr').hide(); + $('#usergroups').hide(); + $('#nb_operators_required').parent('td').parent('tr').hide(); $('#wsresources').show(); - } else if($(this).val() === 'HUMAN') { + } else if($(this).val() === 'HUMAN') { $('#wsresources').hide(); $('#nb_operators_required').parent('td').parent('tr').show(); $('#usergroups').show(); @@ -212,15 +193,18 @@ llxHeader('', $title, $help_url); <?php // Part to create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("Workstation")), '', 'object_'.$object->picto); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } print dol_get_fiche_head(array(), ''); @@ -268,16 +252,19 @@ if ($action == 'create') } // Part to edit record -if (($id || $ref) && $action == 'edit') -{ +if (($id || $ref) && $action == 'edit') { print load_fiche_titre($langs->trans("Workstation"), '', 'object_'.$object->picto); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; - if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; - if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } print dol_get_fiche_head(); @@ -318,8 +305,7 @@ if (($id || $ref) && $action == 'edit') } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_optionals(); $head = workstationPrepareHead($object); @@ -339,19 +325,20 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Confirmation of action xxxx - if ($action == 'enable') - { + if ($action == 'enable') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('EnableAWorkstation'), $langs->trans("ConfirmEnableWorkstation", $object->ref), 'confirm_enable', $formquestion, 0, 1, 220); - } elseif ($action == 'disable') - { + } elseif ($action == 'disable') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DisableAWorkstation'), $langs->trans("ConfirmDisableWorkstation", $object->ref), 'confirm_disable', $formquestion, 0, 1, 220); } // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -413,7 +400,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea //$keyforbreak='fieldkeytoswitchonsecondcolumn'; // We change column just before this field //unset($object->fields['fk_project']); // Hide field already shown in banner //unset($object->fields['fk_soc']); // Hide field already shown in banner - if ($object->type === 'MACHINE') $object->fields['nb_operators_required']['visible'] = 0; + if ($object->type === 'MACHINE') { + $object->fields['nb_operators_required']['visible'] = 0; + } include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; // Groups @@ -460,10 +449,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<div class="tabsAction">'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Modify if ($permissiontoadd) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit">'.$langs->trans("Modify").'</a>'."\n"; @@ -477,8 +467,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } - if ($permissiontoadd) - { + if ($permissiontoadd) { if ($object->status == $object::STATUS_ENABLED) { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=disable">'.$langs->trans("Disable").'</a>'."\n"; } else { @@ -488,8 +477,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Delete (need delete permission, or if draft, just need create/modify permission) - if ($permissiontodelete) - { + if ($permissiontodelete) { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n"; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n"; diff --git a/htdocs/workstation/workstation_document.php b/htdocs/workstation/workstation_document.php index 89a34f55549..a85dd8e0e31 100755 --- a/htdocs/workstation/workstation_document.php +++ b/htdocs/workstation/workstation_document.php @@ -22,48 +22,14 @@ * \brief Tab for documents linked to Workstation */ -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. -//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value -//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler -//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message -//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies -//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET -//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification - // Load Dolibarr environment -$res = 0; -// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; -// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; -// Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); - +require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -dol_include_once('/workstation/class/workstation.class.php'); -dol_include_once('/workstation/lib/workstation_workstation.lib.php'); +require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/workstation/lib/workstation_workstation.lib.php'; // Load translation files required by the page $langs->loadLangs(array("workstation@workstation", "companies", "other", "mails")); @@ -79,12 +45,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 = $liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} //if (! $sortfield) $sortfield="position_name"; // Initialize technical objects @@ -98,7 +70,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->workstation->multidir_output[$object->entity ? $object->entity : $conf->entity]."/workstation/".get_exdir(0, 0, 0, 1, $object); +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->workstation->multidir_output[$object->entity ? $object->entity : $conf->entity]."/workstation/".get_exdir(0, 0, 0, 1, $object); +} // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); @@ -113,7 +87,7 @@ $permissiontoadd = $user->rights->workstation->workstation->write; // Used by th * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -127,8 +101,7 @@ $help_url = ''; //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($object->id) -{ +if ($object->id) { /* * Show tabs */ @@ -140,8 +113,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/workstation/workstation_list.php b/htdocs/workstation/workstation_list.php index 996e7dc34fd..7803139ef6d 100755 --- a/htdocs/workstation/workstation_list.php +++ b/htdocs/workstation/workstation_list.php @@ -22,42 +22,8 @@ * \brief List page for workstation */ -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. -//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value -//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler -//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message -//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies -//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET -//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification - // Load Dolibarr environment -$res = 0; -// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; -// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; -// Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); - +require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -66,11 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php'; // load workstation libraries require_once __DIR__.'/class/workstation.class.php'; -// for other modules -//dol_include_once('/othermodule/class/otherobject.class.php'); - // Load translation files required by the page -$langs->loadLangs(array("workstation@workstation", "other")); +$langs->loadLangs(array("workstation", "other")); $action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) @@ -89,7 +52,9 @@ $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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -107,17 +72,24 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Initialize array of search criterias $search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); - if (in_array($key, array('type', 'status')) && GETPOST('search_'.$key, 'alpha') == -1) $search[$key] = ''; +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } + if (in_array($key, array('type', 'status')) && GETPOST('search_'.$key, 'alpha') == -1) { + $search[$key] = ''; + } } $groups = GETPOST('groups'); @@ -125,15 +97,15 @@ $resources = GETPOST('resources'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of array of fields for columns $arrayfields = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field if (!empty($val['visible'])) { $visible = dol_eval($val['visible'], 1); @@ -174,10 +146,12 @@ $permissiontoadd = $user->rights->workstation->workstation->write; $permissiontodelete = $user->rights->workstation->workstation->delete; // Security check -if (empty($conf->workstation->enabled)) accessforbidden('Module not enabled'); +if (empty($conf->workstation->enabled)) { + accessforbidden('Module not enabled'); +} $socid = 0; -if ($user->socid > 0) // Protection if external user -{ +if ($user->socid > 0) { + // Protection if external user //$socid = $user->socid; accessforbidden(); } @@ -190,23 +164,26 @@ if ($user->socid > 0) // Protection if external user * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $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 (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // 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 - { - foreach ($object->fields as $key => $val) - { + 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 + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $groups=$resources=array(); @@ -214,8 +191,7 @@ if (empty($reshook)) $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -245,13 +221,14 @@ $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("Workstations")); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // 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.', ' : ''); + 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(); @@ -259,34 +236,54 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if (!empty($groups)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'workstation_workstation_usergroup wug ON (wug.fk_workstation = t.rowid)'; -if (!empty($resources)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'workstation_workstation_resource wr ON (wr.fk_workstation = t.rowid)'; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if (!empty($groups)) { + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'workstation_workstation_usergroup wug ON (wug.fk_workstation = t.rowid)'; +} +if (!empty($resources)) { + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'workstation_workstation_resource wr ON (wr.fk_workstation = t.rowid)'; +} // Add table from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -else $sql .= " WHERE 1 = 1"; -foreach ($search as $key => $val) -{ - if ($key == 'status' && $search[$key] == -1) continue; +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); if (strpos($object->fields[$key]['type'], 'integer:') === 0) { - if ($search[$key] == '-1') $search[$key] = ''; + if ($search[$key] == '-1') { + $search[$key] = ''; + } $mode_search = 2; } - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); // Add where from extra fields // usergroups -if (!empty($groups)) $sql.= ' AND wug.fk_usergroup IN('.implode(',', $groups).')'; +if (!empty($groups)) { + $sql.= ' AND wug.fk_usergroup IN('.implode(',', $groups).')'; +} // resources -if (!empty($resources)) $sql.= ' AND wr.fk_resource IN('.implode(',', $resources).')'; +if (!empty($resources)) { + $sql.= ' AND wr.fk_resource IN('.implode(',', $resources).')'; +} include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -315,26 +312,24 @@ $sql .= $db->order($sortfield, $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 || empty($limit))) -{ +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -343,8 +338,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".dol_buildpath('/workstation/workstation_card.php', 1).'?id='.$id); @@ -375,14 +369,24 @@ jQuery(document).ready(function() { $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ - if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); - else $param .= '&search_'.$key.'='.urlencode($search[$key]); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +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'; // Add $param from hooks @@ -397,12 +401,18 @@ $arrayofmassactions = array( //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); -if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($permissiontodelete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -421,9 +431,10 @@ $objecttmp = new Workstation($db); $trackid = 'xxxx'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } @@ -434,11 +445,13 @@ $moreforfilter.= '</div>';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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)) -{ +if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -456,20 +469,26 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - elseif (strpos($val['type'], 'integer:') === 0) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth125', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { + print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; + } print '</td>'; } } @@ -506,15 +525,18 @@ print '</tr>'."\n"; // Fields title label // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $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'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -542,11 +564,11 @@ print '</tr>'."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -555,10 +577,11 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->setVarsFromFetchObj($obj); @@ -567,28 +590,40 @@ while ($i < ($limit ? min($num, $limit) : $num)) // Show here line of result print '<tr class="oddeven">'; - foreach ($object->fields as $key => $val) - { + foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>'; - if ($key == 'status') print $object->getLibStatut(5); - else print $object->showOutputField($val, $key, $object->$key, ''); + if ($key == 'status') { + print $object->getLibStatut(5); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $object->$key; } } @@ -626,14 +661,17 @@ while ($i < ($limit ? min($num, $limit) : $num)) print $hookmanager->resPrint; // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + 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($object->id, $arrayofselected)) $selected = 1; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'."\n"; @@ -644,10 +682,13 @@ while ($i < ($limit ? min($num, $limit) : $num)) include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +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 '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } @@ -663,10 +704,11 @@ print '</div>'."\n"; print '</form>'."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/workstation/workstation_note.php b/htdocs/workstation/workstation_note.php index a9d8a7f3fc2..6cc6a36a3fd 100755 --- a/htdocs/workstation/workstation_note.php +++ b/htdocs/workstation/workstation_note.php @@ -22,47 +22,14 @@ * \brief Tab for notes on Workstation */ -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. -//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value -//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler -//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message -//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies -//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET -//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification - // Load Dolibarr environment -$res = 0; -// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; -// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; -if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; -// Try main.inc.php using relative path -if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; -if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if (!$res) die("Include of main fails"); +require '../main.inc.php'; -dol_include_once('/workstation/class/workstation.class.php'); -dol_include_once('/workstation/lib/workstation_workstation.lib.php'); +require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/workstation/lib/workstation_workstation.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("workstation@workstation", "companies")); +$langs->loadLangs(array("workstation", "companies")); // Get parameters $id = GETPOST('id', 'int'); @@ -86,7 +53,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->workstation->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->workstation->multidir_output[$object->entity]."/".$object->id; +} $permissionnote = $user->rights->workstation->workstation->write; // Used by the include of actions_setnotes.inc.php $permissiontoadd = $user->rights->workstation->workstation->write; // Used by the include of actions_addupdatedelete.inc.php @@ -110,8 +79,7 @@ $form = new Form($db); $help_url = ''; llxHeader('', $langs->trans('Workstation'), $help_url); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = workstationPrepareHead($object); diff --git a/htdocs/zapier/admin/about.php b/htdocs/zapier/admin/about.php index e67ba8861a2..b24fe42ed22 100644 --- a/htdocs/zapier/admin/about.php +++ b/htdocs/zapier/admin/about.php @@ -34,7 +34,9 @@ require_once '../lib/zapier.lib.php'; $langs->loadLangs(array("errors", "admin", "zapier@zapier")); // Access control -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Parameters $action = GETPOST('action', 'aZ09'); diff --git a/htdocs/zapier/admin/setup.php b/htdocs/zapier/admin/setup.php index 0d10ac95231..606da5509e3 100644 --- a/htdocs/zapier/admin/setup.php +++ b/htdocs/zapier/admin/setup.php @@ -33,7 +33,9 @@ require_once '../lib/zapier.lib.php'; $langs->loadLangs(array("admin", "zapier@zapier")); // Access control -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Parameters $action = GETPOST('action', 'aZ09'); diff --git a/htdocs/zapier/class/api_zapier.class.php b/htdocs/zapier/class/api_zapier.class.php index 945a6a69a8f..f5447bfa804 100644 --- a/htdocs/zapier/class/api_zapier.class.php +++ b/htdocs/zapier/class/api_zapier.class.php @@ -37,7 +37,7 @@ class ZapierApi extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'url', ); @@ -163,7 +163,9 @@ class ZapierApi extends DolibarrApi } $sql .= " FROM ".MAIN_DB_PREFIX."hook_mytable as t"; - if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= " WHERE 1 = 1"; // Example of use $mode @@ -270,33 +272,33 @@ class ZapierApi extends DolibarrApi // * @url PUT /hooks/{id} // */ /*public function put($id, $request_data = null) - { - if (! DolibarrApiAccess::$user->rights->zapier->write) { - throw new RestException(401); - } + { + if (! DolibarrApiAccess::$user->rights->zapier->write) { + throw new RestException(401); + } - $result = $this->hook->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Hook not found'); - } + $result = $this->hook->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Hook not found'); + } - if( ! DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if( ! DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - foreach($request_data as $field => $value) { - if ($field == 'id') { - continue; - } - $this->hook->$field = $value; - } + foreach($request_data as $field => $value) { + if ($field == 'id') { + continue; + } + $this->hook->$field = $value; + } - if ($this->hook->update($id, DolibarrApiAccess::$user) > 0) { - return $this->get($id); - } else { - throw new RestException(500, $this->hook->error); - } - }*/ + if ($this->hook->update($id, DolibarrApiAccess::$user) > 0) { + return $this->get($id); + } else { + throw new RestException(500, $this->hook->error); + } + }*/ /** * Delete hook diff --git a/htdocs/zapier/class/hook.class.php b/htdocs/zapier/class/hook.class.php index b71c5aec1d7..92066e496e2 100644 --- a/htdocs/zapier/class/hook.class.php +++ b/htdocs/zapier/class/hook.class.php @@ -385,13 +385,13 @@ class Hook extends CommonObject * @return int <0 if KO, 0 if not found, >0 if OK */ /*public function fetchLines() - { - $this->lines=array(); + { + $this->lines=array(); - // Load lines with object MyObjectLine + // Load lines with object MyObjectLine - return count($this->lines)?1:0; - }*/ + return count($this->lines)?1:0; + }*/ /** * Load list of objects in memory from the database. @@ -542,11 +542,11 @@ class Hook extends CommonObject $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; /* - $hookmanager->initHooks(array('hookdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ + $hookmanager->initHooks(array('hookdao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $linkclose = $hookmanager->resPrint; + */ } else { $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } @@ -621,7 +621,9 @@ class Hook extends CommonObject } $statusType = 'status5'; - if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -637,7 +639,7 @@ class Hook 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)) { @@ -720,11 +722,11 @@ class Hook extends CommonObject /* class MyObjectLine { - // @var int ID - public $id; - // @var mixed Sample line property 1 - public $prop1; - // @var mixed Sample line property 2 - public $prop2; + // @var int ID + public $id; + // @var mixed Sample line property 1 + public $prop1; + // @var mixed Sample line property 2 + public $prop2; } */ diff --git a/htdocs/zapier/hook_agenda.php b/htdocs/zapier/hook_agenda.php index 6ae9d7d57aa..14f1aeda682 100644 --- a/htdocs/zapier/hook_agenda.php +++ b/htdocs/zapier/hook_agenda.php @@ -43,7 +43,9 @@ $backtopage = GETPOST('backtopage', 'alpha'); 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)); } @@ -58,12 +60,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 (!$sortfield) $sortfield = 'a.datep,a.id'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} // Initialize technical objects $object = new MyObject($db); @@ -76,7 +84,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->mymodule->multidir_output[$object->entity]."/".$object->id; +} @@ -86,7 +96,9 @@ if ($id > 0 || !empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$obj $parameters = array('id'=>$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)) { // Cancel @@ -118,7 +130,9 @@ if ($object->id > 0) { $help_url = ''; llxHeader('', $title, $help_url); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = myobjectPrepareHead($object); @@ -143,31 +157,31 @@ if ($object->id > 0) { if ($user->rights->mymodule->creer) { if ($action != 'classify') - //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; - $morehtmlref.=' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; - $morehtmlref.='<input type="hidden" name="action" value="classin">'; - $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; - $morehtmlref.='</form>'; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">'; - $morehtmlref.=$proj->ref; - $morehtmlref.='</a>'; - } else { - $morehtmlref.=''; - } - } - }*/ + //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref.='<input type="hidden" name="action" value="classin">'; + $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref.='</form>'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">'; + $morehtmlref.=$proj->ref; + $morehtmlref.='</a>'; + } else { + $morehtmlref.=''; + } + } + }*/ $morehtmlref .= '</div>'; @@ -194,7 +208,9 @@ if ($object->id > 0) { $permok = $user->rights->agenda->myactions->create; if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { //$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'; - if (get_class($objthirdparty) == 'Societe') $out .= '&amp;socid='.$objthirdparty->id; + if (get_class($objthirdparty) == 'Societe') { + $out .= '&amp;socid='.$objthirdparty->id; + } $out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1'; //$out.=$langs->trans("AddAnAction").' '; //$out.=img_picto($langs->trans("AddAnAction"),'filenew'); @@ -216,8 +232,12 @@ if ($object->id > 0) { if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $param = '&socid='.$socid; - 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 load_fiche_titre($langs->trans("ActionsOnMyObject"), '', ''); diff --git a/htdocs/zapier/hook_card.php b/htdocs/zapier/hook_card.php index 43706c0c533..455efc95cc9 100644 --- a/htdocs/zapier/hook_card.php +++ b/htdocs/zapier/hook_card.php @@ -56,10 +56,14 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen $search_all = GETPOST("search_all", 'alpha'); $search = array(); foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals @@ -79,7 +83,9 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ $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)) { $error = 0; @@ -88,8 +94,11 @@ if (empty($reshook)) { $permissiontodelete = $user->rights->mymodule->delete || ($permissiontoadd && $object->status == 0); $backurlforlist = dol_buildpath('/mymodule/myobject_list.php', 1); if (empty($backtopage)) { - if (empty($id)) $backtopage = $backurlforlist; - else $backtopage = dol_buildpath('/mymodule/myobject_card.php', 1).($id > 0 ? $id : '__ID__'); + if (empty($id)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('/mymodule/myobject_card.php', 1).($id > 0 ? $id : '__ID__'); + } } $triggermodname = 'MYMODULE_MYOBJECT_MODIFY'; // Name of trigger action code to execute when we modify record @@ -223,21 +232,24 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea /* $forcecombo=0; if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy - $formquestion = array( - // 'text' => $langs->trans("ConfirmClone"), - // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), - // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), - // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) - ); - */ + $formquestion = array( + // 'text' => $langs->trans("ConfirmClone"), + // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), + // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), + // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) + ); + */ $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); } // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -257,32 +269,32 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='<br>'.$langs->trans('Project') . ' '; - if ($user->rights->mymodule->write) - { - if ($action != 'classify') - $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; - $morehtmlref.='<input type="hidden" name="action" value="classin">'; - $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; - $morehtmlref.='</form>'; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=$proj->getNomUrl(); - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='<br>'.$langs->trans('Project') . ' '; + if ($user->rights->mymodule->write) + { + if ($action != 'classify') + $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref.='<input type="hidden" name="action" value="classin">'; + $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref.='</form>'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=$proj->getNomUrl(); + } else { + $morehtmlref.=''; + } + } } */ $morehtmlref .= '</div>'; @@ -317,7 +329,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<div class="tabsAction">'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } if (empty($reshook)) { // Modify @@ -333,18 +347,18 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } /* - if ($user->rights->mymodule->write) - { - if ($object->status == 1) - { - print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=disable">'.$langs->trans("Disable").'</a>'."\n"; - } - else - { - print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=enable">'.$langs->trans("Enable").'</a>'."\n"; - } - } - */ + if ($user->rights->mymodule->write) + { + if ($object->status == 1) + { + print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=disable">'.$langs->trans("Disable").'</a>'."\n"; + } + else + { + print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=enable">'.$langs->trans("Enable").'</a>'."\n"; + } + } + */ if ($user->rights->mymodule->delete) { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n"; diff --git a/htdocs/zapier/hook_document.php b/htdocs/zapier/hook_document.php index 15ec591bea6..8751f184821 100644 --- a/htdocs/zapier/hook_document.php +++ b/htdocs/zapier/hook_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"; +} //if (! $sortfield) $sortfield="position_name"; // Initialize technical objects @@ -71,14 +77,16 @@ $extrafields->fetch_name_optionals_label($object->table_element); include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals //if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/myobject/" . dol_sanitizeFileName($object->id); -if ($id > 0 || !empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity]."/myobject/".dol_sanitizeFileName($object->ref); +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity]."/myobject/".dol_sanitizeFileName($object->ref); +} /* * Actions */ -include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -88,8 +96,8 @@ include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; $form = new Form($db); $title = $langs->trans("MyObject").' - '.$langs->trans("Files"); -$help_url = ''; -//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +$help_url = 'EN:Module_Zapier|ES:Módulo Zapier|FR:Module_Zapier_FR|DE:Modul_Zapier'; + llxHeader('', $title, $help_url); if ($object->id) { diff --git a/htdocs/zapier/hook_list.php b/htdocs/zapier/hook_list.php index 93461517107..3894ca3f0a3 100644 --- a/htdocs/zapier/hook_list.php +++ b/htdocs/zapier/hook_list.php @@ -96,20 +96,26 @@ if ($user->socid > 0) { $search_all = GETPOST("search_all", 'alpha'); $search = array(); foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); foreach ($object->fields as $key => $val) { - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of fields for list $arrayfields = array(); foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field - if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); + if (!empty($val['visible'])) { + $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); + } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; @@ -133,7 +139,9 @@ if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massa $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)) { // Selection of new fields @@ -195,7 +203,9 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= $hookmanager->resPrint; $sql = preg_replace('/, $/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} if ($object->ismultientitymanaged == 1) { $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; } else { @@ -224,11 +234,11 @@ $sql .= $hookmanager->resPrint; $sql.= " GROUP BY " foreach($object->fields as $key => $val) { - $sql.='t.'.$key.', '; + $sql.='t.'.$key.', '; } // 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.', ' : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : ''); // Add where from hooks $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters); // Note that $action and $object may have been modified by hook @@ -296,8 +306,12 @@ llxHeader('', $title, $help_url); $arrayofselected = is_array($toselect) ? $toselect : array(); $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); +} foreach ($search as $key => $val) { if (is_array($search[$key]) && count($search[$key])) { foreach ($search[$key] as $skey) { @@ -307,7 +321,9 @@ foreach ($search as $key => $val) { $param .= '&search_'.$key.'='.urlencode($search[$key]); } } -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'; @@ -316,12 +332,18 @@ $arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -if ($user->rights->zapier->delete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($user->rights->zapier->delete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -354,7 +376,9 @@ $trackid = 'zapier'.$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 '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } @@ -365,8 +389,11 @@ $moreforfilter.= '</div>';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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 '<div class="liste_titre liste_titre_bydiv centpercent">'; @@ -423,9 +450,15 @@ print '</tr>'."\n"; print '<tr class="liste_titre">'; foreach ($object->fields as $key => $val) { $cssforfield = ''; - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } if ($key == 'status') { $cssforfield .= ($cssforfield ? ' ' : '').'center'; } @@ -474,7 +507,9 @@ while ($i < min($num, $limit)) { // Store properties in $object $object->id = $obj->rowid; foreach ($object->fields as $key => $val) { - if (isset($obj->$key)) $object->$key = $obj->$key; + if (isset($obj->$key)) { + $object->$key = $obj->$key; + } } // Show here line of result @@ -487,26 +522,45 @@ while ($i < min($num, $limit)) { $cssforfield .= ($cssforfield ? ' ' : '').'center'; } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td'; - if ($cssforfield || $val['css']) print ' class="'; + if ($cssforfield || $val['css']) { + print ' class="'; + } print $cssforfield; - if ($cssforfield && $val['css']) print ' '; + if ($cssforfield && $val['css']) { + print ' '; + } print $val['css']; - if ($cssforfield || $val['css']) print '"'; + if ($cssforfield || $val['css']) { + print '"'; + } print '>'; - if ($key == 'status') print $object->getLibStatut(5); - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); - else print $object->showOutputField($val, $key, $obj->$key, ''); + if ($key == 'status') { + print $object->getLibStatut(5); + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); + } else { + print $object->showOutputField($val, $key, $obj->$key, ''); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } if (!empty($val['isameasure'])) { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $obj->$key; } } @@ -522,11 +576,15 @@ while ($i < min($num, $limit)) { 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'; diff --git a/htdocs/zapier/hook_note.php b/htdocs/zapier/hook_note.php index da0484160a3..ce613da2989 100644 --- a/htdocs/zapier/hook_note.php +++ b/htdocs/zapier/hook_note.php @@ -53,7 +53,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->mymodule->multidir_output[$object->entity]."/".$object->id; +} $permissionnote = 1; //$permissionnote=$user->rights->mymodule->creer; // Used by the include of actions_setnotes.inc.php @@ -98,35 +100,35 @@ if ($id > 0 || !empty($ref)) { // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='<br>'.$langs->trans('Project') . ' '; - if ($user->rights->mymodule->creer) - { - if ($action != 'classify') - //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; - $morehtmlref.=' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; - $morehtmlref.='<input type="hidden" name="action" value="classin">'; - $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; - $morehtmlref.='</form>'; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">'; - $morehtmlref.=$proj->ref; - $morehtmlref.='</a>'; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='<br>'.$langs->trans('Project') . ' '; + if ($user->rights->mymodule->creer) + { + if ($action != 'classify') + //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref.='<input type="hidden" name="action" value="classin">'; + $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref.='</form>'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">'; + $morehtmlref.=$proj->ref; + $morehtmlref.='</a>'; + } else { + $morehtmlref.=''; + } + } }*/ $morehtmlref .= '</div>'; diff --git a/htdocs/zapier/lib/zapier_hook.lib.php b/htdocs/zapier/lib/zapier_hook.lib.php index 114e7753512..3d4228325e2 100644 --- a/htdocs/zapier/lib/zapier_hook.lib.php +++ b/htdocs/zapier/lib/zapier_hook.lib.php @@ -43,11 +43,17 @@ function myobjectPrepareHead($object) if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = dol_buildpath('/mymodule/myobject_note.php', 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>'; + if ($nbNote > 0) { + $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>'; + } $head[$h][2] = 'note'; $h++; } @@ -59,7 +65,9 @@ function myobjectPrepareHead($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = dol_buildpath("/mymodule/myobject_document.php", 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; + } $head[$h][2] = 'document'; $h++; diff --git a/htdocs/zapier/zapierindex.php b/htdocs/zapier/zapierindex.php index 5ecdf24e6cd..357777000f6 100644 --- a/htdocs/zapier/zapierindex.php +++ b/htdocs/zapier/zapierindex.php @@ -35,7 +35,9 @@ $action = GETPOST('action', 'aZ09'); // Securite acces client -if (!$user->rights->zapier->read) accessforbidden(); +if (!$user->rights->zapier->read) { + accessforbidden(); +} $socid = GETPOST('socid', 'int'); if (isset($user->socid) && $user->socid > 0) { $action = ''; diff --git a/scripts/accountancy/export-thirdpartyaccount.php b/scripts/accountancy/export-thirdpartyaccount.php index 4dc22193262..519ab534cc6 100755 --- a/scripts/accountancy/export-thirdpartyaccount.php +++ b/scripts/accountancy/export-thirdpartyaccount.php @@ -25,7 +25,9 @@ * \brief Page to detect empty accounting account */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $path = __DIR__.'/'; @@ -36,8 +38,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $langs->loadLangs(array("companies", "compta", "main", "accountancy")); // Security check -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Date range $year = GETPOST("year"); @@ -54,8 +57,7 @@ $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); // Quarter -if (empty($date_start) || empty($date_end)) // We define date_start and date_end -{ +if (empty($date_start) || empty($date_end)) { // We define date_start and date_end $q = GETPOST("q") ? GETPOST("q") : 0; if ($q == 0) { // We define date_start and date_end @@ -67,10 +69,14 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end $year_end--; } $month_end = $month_start - 1; - if ($month_end < 1) + if ($month_end < 1) { $month_end = 12; - else $year_end++; - } else $month_end = $month_start; + } else { + $year_end++; + } + } 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); } @@ -128,11 +134,13 @@ $sql .= ", ".MAIN_DB_PREFIX."facture as f"; $sql .= ", ".MAIN_DB_PREFIX."c_country as cp"; $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND s.fk_pays = cp.rowid"; -if (!empty($date_start) && !empty($date_end)) +if (!empty($date_start) && !empty($date_end)) { $sql .= " AND f.datec >= '".$db->idate($date_start)."' AND f.datec <= '".$db->idate($date_end)."'"; +} $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; -if ($socid) +if ($socid) { $sql .= " AND f.fk_soc = ".$socid; +} $sql .= " GROUP BY name"; $sql .= ")"; $sql .= "UNION (SELECT s.rowid, s.nom as name , s.address, s.zip , s.town, s.code_compta_fournisseur as compta , "; @@ -142,11 +150,13 @@ $sql .= ", ".MAIN_DB_PREFIX."facture_fourn as ff"; $sql .= ", ".MAIN_DB_PREFIX."c_country as cp"; $sql .= " WHERE ff.fk_soc = s.rowid"; $sql .= " AND s.fk_pays = cp.rowid"; -if (!empty($date_start) && !empty($date_end)) +if (!empty($date_start) && !empty($date_end)) { $sql .= " AND ff.datec >= '".$db->idate($date_start)."' AND ff.datec <= '".$db->idate($date_end)."'"; +} $sql .= " AND ff.entity = ".$conf->entity; -if ($socid) +if ($socid) { $sql .= " AND f.fk_soc = ".$socid; +} $sql .= " GROUP BY name"; $sql .= ")"; @@ -200,8 +210,7 @@ if ($resql) { print '<td class="left">'.$langs->trans("Phone").'</td>'; print '<td class="left">'.$langs->trans("Fax").'</td></tr>'; - while ($obj = $db->fetch_object($resql)) - { + while ($obj = $db->fetch_object($resql)) { print '<tr class="oddeven">'; print '<td>'; $thirdpartystatic->id = $obj->rowid; diff --git a/scripts/bank/export-bank-receipts.php b/scripts/bank/export-bank-receipts.php index d8c4b91550d..a3876cb146f 100755 --- a/scripts/bank/export-bank-receipts.php +++ b/scripts/bank/export-bank-receipts.php @@ -23,7 +23,9 @@ * \brief Script file to export bank receipts into Excel files */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -154,8 +156,9 @@ if (!empty($num) && $num != "all") { $listofnum .= "'"; $arraynum = explode(',', $num); foreach ($arraynum as $val) { - if ($listofnum != "'") + if ($listofnum != "'") { $listofnum .= "','"; + } $listofnum .= $val; } $listofnum .= "'"; @@ -166,10 +169,12 @@ $sql .= " ba.rowid as bankid, ba.ref as bankref, ba.label as banklabel"; $sql .= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; $sql .= ", ".MAIN_DB_PREFIX."bank as b"; $sql .= " WHERE b.fk_account = ".$acct->id; -if ($listofnum) +if ($listofnum) { $sql .= " AND b.num_releve IN (".$listofnum.")"; -if (!isset($num)) +} +if (!isset($num)) { $sql .= " OR b.num_releve is null"; +} $sql .= " AND b.fk_account = ba.rowid"; $sql .= $db->order("b.num_releve, b.datev, b.datec", "ASC"); // We add date of creation to have correct order when everything is done the same day // print $sql; @@ -242,9 +247,11 @@ if ($resql) { // Libelle $reg = array(); preg_match('/\((.+)\)/i', $objp->label, $reg); // Si texte entoure de parenthese on tente recherche de traduction - if ($reg[1] && $langs->transnoentitiesnoconv($reg[1]) != $reg[1]) + if ($reg[1] && $langs->transnoentitiesnoconv($reg[1]) != $reg[1]) { $description = $langs->transnoentitiesnoconv($reg[1]); - else $description = $objp->label; + } else { + $description = $objp->label; + } /* * Ajout les liens (societe, company...) diff --git a/scripts/company/sync_contacts_dolibarr2ldap.php b/scripts/company/sync_contacts_dolibarr2ldap.php index 8e5274fb69a..53ec46ddcd8 100755 --- a/scripts/company/sync_contacts_dolibarr2ldap.php +++ b/scripts/company/sync_contacts_dolibarr2ldap.php @@ -24,7 +24,9 @@ * \brief Script to update all contacts from Dolibarr into a LDAP database */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -60,8 +62,9 @@ if (!isset($argv[1]) || !$argv[1]) { } foreach ($argv as $key => $val) { - if (preg_match('/-y$/', $val, $reg)) + if (preg_match('/-y$/', $val, $reg)) { $confirmed = 1; + } } $now = $argv[1]; diff --git a/scripts/contracts/email_expire_services_to_customers.php b/scripts/contracts/email_expire_services_to_customers.php index 802f0b14434..0979046ff28 100755 --- a/scripts/contracts/email_expire_services_to_customers.php +++ b/scripts/contracts/email_expire_services_to_customers.php @@ -25,7 +25,9 @@ * \brief Script to send a mail to customers with services to expire */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -80,24 +82,30 @@ if ($mode != 'confirm') { $sql = "SELECT c.ref, cd.date_fin_validite, cd.total_ttc, cd.description as description, p.label as plabel,"; $sql .= " s.rowid as sid, s.nom as name, s.email, s.default_lang"; -if ($targettype == 'contacts') +if ($targettype == 'contacts') { $sql .= ", sp.rowid as cid, sp.firstname as cfirstname, sp.lastname as clastname, sp.email as cemail"; +} $sql .= " FROM ".MAIN_DB_PREFIX."societe AS s"; -if ($targettype == 'contacts') +if ($targettype == 'contacts') { $sql .= ", ".MAIN_DB_PREFIX."socpeople as sp"; +} $sql .= ", ".MAIN_DB_PREFIX."contrat AS c"; $sql .= ", ".MAIN_DB_PREFIX."contratdet AS cd"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product AS p ON p.rowid = cd.fk_product"; $sql .= " WHERE s.rowid = c.fk_soc AND c.rowid = cd.fk_contrat AND c.statut > 0 AND cd.statut < 5"; -if (is_numeric($duration_value2)) +if (is_numeric($duration_value2)) { $sql .= " AND cd.date_fin_validite >= '".$db->idate(dol_time_plus_duree($now, $duration_value2, "d"))."'"; -if (is_numeric($duration_value)) +} +if (is_numeric($duration_value)) { $sql .= " AND cd.date_fin_validite < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'"; -if ($targettype == 'contacts') +} +if ($targettype == 'contacts') { $sql .= " AND s.rowid = sp.fk_soc"; +} $sql .= " ORDER BY"; -if ($targettype == 'contacts') +if ($targettype == 'contacts') { $sql .= " sp.email, sp.rowid,"; +} $sql .= " s.email ASC, s.rowid ASC, cd.date_fin_validite ASC"; // Order by email to allow one message per email // print $sql; @@ -145,9 +153,11 @@ if ($resql) { $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid; } else { if ($oldemail != 'none') { - if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) + if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) { print "- No email sent for '".$oldtarget."', total: ".$total."\n"; - else print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n"; + } else { + print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n"; + } } } $oldemail = $newemail; @@ -176,9 +186,11 @@ if ($resql) { $foundtoprocess++; } print "Service to expire ".$obj->ref.", label ".dol_concatdesc($obj->plabel, $obj->description).", due date ".dol_print_date($db->jdate($obj->date_fin_validite), 'day').", customer id ".$obj->sid." ".$obj->name.", ".(isset($obj->cid) ? "contact id ".$obj->cid." ".$obj->clastname." ".$obj->cfirstname.", " : "")."email ".$newemail.", lang ".$outputlangs->defaultlang.": "; - if (dol_strlen($newemail)) + if (dol_strlen($newemail)) { print "qualified."; - else print "disqualified (no email)."; + } else { + print "disqualified (no email)."; + } print "\n"; unset($outputlangs); @@ -190,15 +202,16 @@ if ($resql) { // Si il reste des envois en buffer if ($foundtoprocess) { - if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) // Break onto email (new email) - { + if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) { // Break onto email (new email) envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget, $duration_value); $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid; } else { if ($oldemail != 'none') { - if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) + if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) { print "- No email sent for '".$oldtarget."', total: ".$total."\n"; - else print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n"; + } else { + print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n"; + } } } } @@ -230,8 +243,9 @@ function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget, $ { global $conf, $langs; - if (getenv('DOL_FORCE_EMAIL_TO')) + if (getenv('DOL_FORCE_EMAIL_TO')) { $oldemail = getenv('DOL_FORCE_EMAIL_TO'); + } $newlangs = new Translate('', $conf); $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang); @@ -239,10 +253,14 @@ function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget, $ $newlangs->load("contracts"); if ($duration_value) { - if ($duration_value > 0) + if ($duration_value > 0) { $title = $newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value); - else $title = $newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value); - } else $title = $newlangs->transnoentities("ListOfServicesToExpire"); + } else { + $title = $newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value); + } + } else { + $title = $newlangs->transnoentities("ListOfServicesToExpire"); + } $subject = (empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT) ? $title : $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT); $sendto = $oldemail; @@ -254,10 +272,12 @@ function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget, $ dol_syslog("email_expire_services_to_customers.php: send mail to ".$oldemail); $usehtml = 0; - if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) + if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) { $usehtml += 1; - if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER)) + } + if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER)) { $usehtml += 1; + } $allmessage = ''; if (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER)) { @@ -270,8 +290,9 @@ function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget, $ // $allmessage.= $langs->trans("Total")." = ".price($total,0,$userlang,0,0,-1,$conf->currency).($usehtml?"<br>\n":"\n"); if (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) { $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER; - if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) + if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) { $usehtml += 1; + } } $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml); diff --git a/scripts/contracts/email_expire_services_to_representatives.php b/scripts/contracts/email_expire_services_to_representatives.php index 2c8429b6256..316994752e5 100755 --- a/scripts/contracts/email_expire_services_to_representatives.php +++ b/scripts/contracts/email_expire_services_to_representatives.php @@ -25,7 +25,9 @@ * \brief Script to send a mail to dolibarr users linked to companies with services to expire */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -79,8 +81,9 @@ $sql .= " u.rowid as uid, u.lastname, u.firstname, u.email, u.lang"; $sql .= " FROM ".MAIN_DB_PREFIX."societe AS s, ".MAIN_DB_PREFIX."contrat AS c, ".MAIN_DB_PREFIX."contratdet AS cd"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product AS p ON p.rowid = cd.fk_product, ".MAIN_DB_PREFIX."societe_commerciaux AS sc, ".MAIN_DB_PREFIX."user AS u"; $sql .= " WHERE s.rowid = c.fk_soc AND c.rowid = cd.fk_contrat AND c.statut > 0 AND cd.statut<5"; -if (is_numeric($duration_value)) +if (is_numeric($duration_value)) { $sql .= " AND cd.date_fin_validite < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'"; +} $sql .= " AND sc.fk_soc = s.rowid AND sc.fk_user = u.rowid"; $sql .= " ORDER BY u.email ASC, s.rowid ASC, c.ref ASC"; // Order by email to allow one message per email @@ -107,8 +110,9 @@ if ($resql) { if (dol_strlen($oldemail) && $oldemail != 'none') { envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative, $duration_value); } else { - if ($oldemail != 'none') + if ($oldemail != 'none') { print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n"; + } } $oldemail = $obj->email; $olduid = $obj->uid; @@ -118,8 +122,9 @@ if ($resql) { $total = 0; $foundtoprocess = 0; $salerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname); - if (empty($obj->email)) + if (empty($obj->email)) { print "Warning: Sale representative ".$salerepresentative." has no email. Notice disabled.\n"; + } } // Define line content @@ -135,9 +140,11 @@ if ($resql) { $foundtoprocess++; } print "Service to expire ".$obj->ref.", label ".dol_concatdesc($obj->plabel, $obj->description).", due date ".dol_print_date($db->jdate($obj->date_fin_validite), 'day')." (linked to company ".$obj->name.", sale representative ".dolGetFirstLastname($obj->firstname, $obj->lastname).", email ".$obj->email."): "; - if (dol_strlen($obj->email)) + if (dol_strlen($obj->email)) { print "qualified."; - else print "disqualified (no email)."; + } else { + print "disqualified (no email)."; + } print "\n"; unset($outputlangs); @@ -148,12 +155,12 @@ if ($resql) { // Si il reste des envois en buffer if ($foundtoprocess) { - if (dol_strlen($oldemail) && $oldemail != 'none') // Break onto email (new email) - { + if (dol_strlen($oldemail) && $oldemail != 'none') { // Break onto email (new email) envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative, $duration_value); } else { - if ($oldemail != 'none') + if ($oldemail != 'none') { print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n"; + } } } } else { @@ -184,8 +191,9 @@ function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldsalerepre { global $conf, $langs; - if (getenv('DOL_FORCE_EMAIL_TO')) + if (getenv('DOL_FORCE_EMAIL_TO')) { $oldemail = getenv('DOL_FORCE_EMAIL_TO'); + } $newlangs = new Translate('', $conf); $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang); @@ -230,8 +238,9 @@ function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldsalerepre $allmessage .= $langs->trans("Total")." = ".price($total, 0, $userlang, 0, 0, - 1, $conf->currency).($usehtml ? "<br>\n" : "\n"); if (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER)) { $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER; - if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER)) + if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER)) { $usehtml += 1; + } } $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml); diff --git a/scripts/cron/cron_run_jobs.php b/scripts/cron/cron_run_jobs.php index ecec277995d..80f586a6788 100755 --- a/scripts/cron/cron_run_jobs.php +++ b/scripts/cron/cron_run_jobs.php @@ -25,12 +25,24 @@ * \brief Execute pendings jobs */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOLOGIN')) define('NOLOGIN', '1'); -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', '1'); +} +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -106,7 +118,9 @@ if ($userlogin == 'firstadmin') { $userlogin = $obj->login; echo "First admin user found is login '".$userlogin."', entity ".$obj->entity."\n"; } - } else dol_print_error($db); + } else { + dol_print_error($db); + } } // Check user login @@ -125,7 +139,7 @@ if ($result < 0) { } $user->getrights(); -if (isset($argv[3]) || $argv[3]) { +if (isset($argv[3]) && $argv[3]) { $id = $argv[3]; } @@ -151,8 +165,7 @@ if ($result < 0) { $qualifiedjobs = array(); foreach ($object->lines as $val) { - if (!verifCond($val->test)) - { + if (!verifCond($val->test)) { continue; } $qualifiedjobs[] = $val; @@ -173,8 +186,7 @@ if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) { echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label; // Force reload of setup for the current entity - if ((empty($line->entity) ? 1 : $line->entity) != $conf->entity) - { + if ((empty($line->entity) ? 1 : $line->entity) != $conf->entity) { dol_syslog("cron_run_jobs.php we work on another entity conf than ".$conf->entity." so we reload mysoc, langs, user and conf", LOG_DEBUG); echo " -> we change entity so we reload mysoc, langs, user and conf"; @@ -183,17 +195,14 @@ if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) { $mysoc->setMysoc($conf); // Force recheck that user is ok for the entity to process and reload permission for entity - if ($conf->entity != $user->entity && $user->entity != 0) - { + if ($conf->entity != $user->entity && $user->entity != 0) { $result = $user->fetch('', $userlogin, '', 0, $conf->entity); - if ($result < 0) - { + if ($result < 0) { echo "\nUser Error: ".$user->error."\n"; dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR); exit(-1); } else { - if ($result == 0) - { + if ($result == 0) { echo "\nUser login: ".$userlogin." does not exists for entity ".$conf->entity."\n"; dol_syslog("User login:".$userlogin." does not exists", LOG_ERR); exit(-1); @@ -204,8 +213,12 @@ if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) { // Reload langs $langcode = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT); - if (!empty($user->conf->MAIN_LANG_DEFAULT)) $langcode = $user->conf->MAIN_LANG_DEFAULT; - if ($langs->getDefaultLang() != $langcode) $langs->setDefaultLang($langcode); + if (!empty($user->conf->MAIN_LANG_DEFAULT)) { + $langcode = $user->conf->MAIN_LANG_DEFAULT; + } + if ($langs->getDefaultLang() != $langcode) { + $langs->setDefaultLang($langcode); + } } //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database @@ -262,8 +275,9 @@ if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) { $db->close(); -if ($nbofjobslaunchedko) +if ($nbofjobslaunchedko) { exit(1); +} exit(0); /** diff --git a/scripts/emailings/mailing-send.php b/scripts/emailings/mailing-send.php index fcaa40e1fde..00ae2d64479 100755 --- a/scripts/emailings/mailing-send.php +++ b/scripts/emailings/mailing-send.php @@ -26,7 +26,9 @@ * \brief Script to send a prepared and validated emaling from command line */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -45,12 +47,17 @@ if (!isset($argv[1]) || !$argv[1]) { $id = $argv[1]; -if (isset($argv[2]) || !empty($argv[2])) $login = $argv[2]; -else $login = ''; +if (isset($argv[2]) || !empty($argv[2])) { + $login = $argv[2]; +} else { + $login = ''; +} $max = 0; -if (isset($argv[3]) || !empty($argv[3])) $max = $argv[3]; +if (isset($argv[3]) || !empty($argv[3])) { + $max = $argv[3]; +} require_once $path."../../htdocs/master.inc.php"; @@ -61,8 +68,7 @@ require_once DOL_DOCUMENT_ROOT."/comm/mailing/class/mailing.class.php"; $version = DOL_VERSION; $error = 0; -if (empty($conf->global->MAILING_LIMIT_SENDBYCLI)) -{ +if (empty($conf->global->MAILING_LIMIT_SENDBYCLI)) { $conf->global->MAILING_LIMIT_SENDBYCLI = 0; } @@ -78,12 +84,14 @@ if (!empty($conf->global->MAILING_DELAY)) { print 'A delay of '.((float) $conf->global->MAILING_DELAY * 1000000).' millisecond has been set between each email'."\n"; } -if ($conf->global->MAILING_LIMIT_SENDBYCLI == '-1') {} +if ($conf->global->MAILING_LIMIT_SENDBYCLI == '-1') { +} $user = new User($db); // for signature, we use user send as parameter -if (!empty($login)) +if (!empty($login)) { $user->fetch('', $login); +} // We get list of emailing id to process $sql = "SELECT m.rowid"; @@ -119,8 +127,9 @@ if ($resql) { $errorsto = $emailing->email_errorsto; // Le message est-il en html $msgishtml = - 1; // Unknown by default - if (preg_match('/[\s\t]*<html>/i', $message)) + if (preg_match('/[\s\t]*<html>/i', $message)) { $msgishtml = 1; + } $nbok = 0; $nbko = 0; @@ -202,12 +211,15 @@ if ($resql) { $substitutionarray['__UNSUBSCRIBE__'] = '<a href="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-unsubscribe.php?tag='.$obj->tag.'&unsuscrib=1&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" target="_blank">'.$langs->trans("MailUnsubcribe").'</a>'; $onlinepaymentenabled = 0; - if (!empty($conf->paypal->enabled)) + if (!empty($conf->paypal->enabled)) { $onlinepaymentenabled++; - if (!empty($conf->paybox->enabled)) + } + if (!empty($conf->paybox->enabled)) { $onlinepaymentenabled++; - if (!empty($conf->stripe->enabled)) + } + if (!empty($conf->stripe->enabled)) { $onlinepaymentenabled++; + } if ($onlinepaymentenabled && !empty($conf->global->PAYMENT_SECURITY_TOKEN)) { $substitutionarray['__SECUREKEYPAYMENT__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { @@ -226,21 +238,29 @@ if ($resql) { if (!empty($conf->paypal->enabled) && !empty($conf->global->PAYPAL_SECURITY_TOKEN)) { $substitutionarray['__SECUREKEYPAYPAL__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) { $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - else $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'membersubscription'.$obj->source_id, 2); + } else { + $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'membersubscription'.$obj->source_id, 2); + } - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) { $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - else $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'order'.$obj->source_id, 2); + } else { + $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'order'.$obj->source_id, 2); + } - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) { $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - else $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'invoice'.$obj->source_id, 2); + } else { + $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'invoice'.$obj->source_id, 2); + } - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) { $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - else $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'contractline'.$obj->source_id, 2); + } else { + $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'contractline'.$obj->source_id, 2); + } } complete_substitutions_array($substitutionarray, $langs); @@ -256,10 +276,8 @@ if ($resql) { $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0); - if (count($listofpaths)) - { - foreach ($listofpaths as $key => $val) - { + if (count($listofpaths)) { + foreach ($listofpaths as $key => $val) { $arr_file[] = $listofpaths[$key]['fullname']; $arr_mime[] = dol_mimetype($listofpaths[$key]['name']); $arr_name[] = $listofpaths[$key]['name']; @@ -364,8 +382,9 @@ if ($resql) { // Loop finished, set global statut of mail $statut = 2; - if (!$nbko) + if (!$nbko) { $statut = 3; + } $sqlenddate = "UPDATE ".MAIN_DB_PREFIX."mailing SET statut=".$statut." WHERE rowid=".$id; diff --git a/scripts/emailings/reset-invalid-emails.php b/scripts/emailings/reset-invalid-emails.php index 8730d66b96d..a15cad86072 100755 --- a/scripts/emailings/reset-invalid-emails.php +++ b/scripts/emailings/reset-invalid-emails.php @@ -22,8 +22,12 @@ * \brief Script to reset (set email to empty) from a list of email */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); -if (!defined('MAXEMAILS')) define('MAXEMAILS', 100); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} +if (!defined('MAXEMAILS')) { + define('MAXEMAILS', 100); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -71,8 +75,7 @@ $db->begin(); $myfile = fopen($fileofinvalidemail, "r"); -if (!$myfile) -{ +if (!$myfile) { echo "Failed to open file"; exit(-1); } @@ -81,14 +84,11 @@ $tmp = 1; $counter = 1; $numerasedtotal = 0; -while ($tmp != null) -{ +while ($tmp != null) { $groupofemails = array(); - for ($i = 0; $i < MAXEMAILS; $i++) - { + for ($i = 0; $i < MAXEMAILS; $i++) { $tmp = fgets($myfile); - if ($tmp == null) - { + if ($tmp == null) { break; } $groupofemails[$i] = trim($tmp, "\n"); @@ -109,8 +109,7 @@ while ($tmp != null) $sql_base = "UPDATE ".MAIN_DB_PREFIX; - if ($type == 'all' || $type == 'users') - { + if ($type == 'all' || $type == 'users') { // Loop on each record and update the email to null if email into $groupofemails $sql = $sql_base."user as u SET u.email = NULL WHERE u.email IN (".$emailsin.");"; print "Try to update users, "; @@ -121,8 +120,7 @@ while ($tmp != null) $numerased += $db->affected_rows($resql); } - if ($type == 'all' || $type == 'thirdparties') - { + if ($type == 'all' || $type == 'thirdparties') { // Loop on each record and update the email to null if email into $groupofemails $sql = $sql_base."societe as s SET s.email = NULL WHERE s.email IN (".$emailsin.");"; print "Try to update thirdparties, "; @@ -133,8 +131,7 @@ while ($tmp != null) $numerased += $db->affected_rows($resql); } - if ($type == 'all' || $type == 'contacts') - { + if ($type == 'all' || $type == 'contacts') { // Loop on each record and update the email to null if email into $groupofemails $sql = $sql_base."socpeople as s SET s.email = NULL WHERE s.email IN (".$emailsin.");"; @@ -146,8 +143,7 @@ while ($tmp != null) $numerased += $db->affected_rows($resql); } - if ($type == 'all' || $type == 'members') - { + if ($type == 'all' || $type == 'members') { // Loop on each record and update the email to null if email into $groupofemails $sql = $sql_base."adherent as a SET a.email = NULL WHERE a.email IN (".$emailsin.");"; diff --git a/scripts/invoices/email_unpaid_invoices_to_customers.php b/scripts/invoices/email_unpaid_invoices_to_customers.php index 5d4d3ff3e64..41c84ee4d41 100755 --- a/scripts/invoices/email_unpaid_invoices_to_customers.php +++ b/scripts/invoices/email_unpaid_invoices_to_customers.php @@ -25,7 +25,9 @@ * \brief Script to send a mail to customers with unpaid invoices */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -80,22 +82,28 @@ if ($mode != 'confirm') { $sql = "SELECT f.ref, f.total_ttc, f.date_lim_reglement as due_date,"; $sql .= " s.rowid as sid, s.nom as name, s.email, s.default_lang"; -if ($targettype == 'contacts') +if ($targettype == 'contacts') { $sql .= ", sp.rowid as cid, sp.firstname as cfirstname, sp.lastname as clastname, sp.email as cemail"; +} $sql .= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s"; -if ($targettype == 'contacts') +if ($targettype == 'contacts') { $sql .= ", ".MAIN_DB_PREFIX."socpeople as sp"; +} $sql .= " WHERE f.fk_statut = 1 AND f.paye = 0"; $sql .= " AND f.fk_soc = s.rowid"; -if (is_numeric($duration_value2)) +if (is_numeric($duration_value2)) { $sql .= " AND f.date_lim_reglement >= '".$db->idate(dol_time_plus_duree($now, $duration_value2, "d"))."'"; -if (is_numeric($duration_value)) +} +if (is_numeric($duration_value)) { $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'"; -if ($targettype == 'contacts') +} +if ($targettype == 'contacts') { $sql .= " AND s.rowid = sp.fk_soc"; +} $sql .= " ORDER BY"; -if ($targettype == 'contacts') +if ($targettype == 'contacts') { $sql .= " sp.email, sp.rowid,"; +} $sql .= " s.email ASC, s.rowid ASC, f.ref ASC"; // Order by email to allow one message per email // print $sql; @@ -143,9 +151,11 @@ if ($resql) { $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid; } else { if ($oldemail != 'none') { - if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) + if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) { print "- No email sent for '".$oldtarget."', total: ".$total."\n"; - else print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n"; + } else { + print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n"; + } } } $oldemail = $newemail; @@ -174,9 +184,11 @@ if ($resql) { $foundtoprocess++; } print "Unpaid invoice ".$obj->ref.", price ".price2num($obj->total_ttc).", due date ".dol_print_date($db->jdate($obj->due_date), 'day').", customer id ".$obj->sid." ".$obj->name.", ".(isset($obj->cid) ? "contact id ".$obj->cid." ".$obj->clastname." ".$obj->cfirstname.", " : "")."email ".$newemail.", lang ".$outputlangs->defaultlang.": "; - if (dol_strlen($newemail)) + if (dol_strlen($newemail)) { print "qualified."; - else print "disqualified (no email)."; + } else { + print "disqualified (no email)."; + } print "\n"; unset($outputlangs); @@ -188,15 +200,16 @@ if ($resql) { // Si il reste des envois en buffer if ($foundtoprocess) { - if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) // Break onto email (new email) - { + if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) { // Break onto email (new email) envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget); $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid; } else { if ($oldemail != 'none') { - if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) + if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) { print "- No email sent for '".$oldtarget."', total: ".$total."\n"; - else print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n"; + } else { + print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n"; + } } } } @@ -227,8 +240,9 @@ function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget) { global $conf, $langs; - if (getenv('DOL_FORCE_EMAIL_TO')) + if (getenv('DOL_FORCE_EMAIL_TO')) { $oldemail = getenv('DOL_FORCE_EMAIL_TO'); + } $newlangs = new Translate('', $conf); $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang); @@ -245,10 +259,12 @@ function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget) dol_syslog("email_unpaid_invoices_to_customers.php: send mail to ".$oldemail); $usehtml = 0; - if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER) && dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) + if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER) && dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) { $usehtml += 1; - if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER) && dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER)) + } + if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER) && dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER)) { $usehtml += 1; + } $allmessage = ''; if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER)) { @@ -262,8 +278,9 @@ function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget) $allmessage .= $langs->trans("Total")." = ".price($total, 0, $userlang, 0, 0, - 1, $conf->currency).($usehtml ? "<br>\n" : "\n"); if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) { $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER; - if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) + if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) { $usehtml += 1; + } } $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml); diff --git a/scripts/invoices/email_unpaid_invoices_to_representatives.php b/scripts/invoices/email_unpaid_invoices_to_representatives.php index d5c71c70565..3cc9ad1a0eb 100755 --- a/scripts/invoices/email_unpaid_invoices_to_representatives.php +++ b/scripts/invoices/email_unpaid_invoices_to_representatives.php @@ -25,7 +25,9 @@ * \brief Script to send a mail to dolibarr users linked to companies with unpaid invoices */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -82,8 +84,9 @@ $sql .= " , ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= " , ".MAIN_DB_PREFIX."user as u"; $sql .= " WHERE f.fk_statut = 1 AND f.paye = 0"; $sql .= " AND f.fk_soc = s.rowid"; -if (is_numeric($duration_value)) +if (is_numeric($duration_value)) { $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'"; +} $sql .= " AND sc.fk_soc = s.rowid"; $sql .= " AND sc.fk_user = u.rowid"; $sql .= " ORDER BY u.email ASC, s.rowid ASC, f.ref ASC"; // Order by email to allow one message per email @@ -111,8 +114,9 @@ if ($resql) { if (dol_strlen($oldemail) && $oldemail != 'none') { envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative); } else { - if ($oldemail != 'none') + if ($oldemail != 'none') { print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n"; + } } $oldemail = $obj->email; $olduid = $obj->uid; @@ -122,8 +126,9 @@ if ($resql) { $total = 0; $foundtoprocess = 0; $salerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname); - if (empty($obj->email)) + if (empty($obj->email)) { print "Warning: Sale representative ".$salerepresentative." has no email. Notice disabled.\n"; + } } // Define line content @@ -139,9 +144,11 @@ if ($resql) { $foundtoprocess++; } print "Unpaid invoice ".$obj->ref.", price ".price2num($obj->total_ttc).", due date ".dol_print_date($db->jdate($obj->due_date), 'day')." (linked to company ".$obj->name.", sale representative ".dolGetFirstLastname($obj->firstname, $obj->lastname).", email ".$obj->email.", lang ".$outputlangs->defaultlang."): "; - if (dol_strlen($obj->email)) + if (dol_strlen($obj->email)) { print "qualified."; - else print "disqualified (no email)."; + } else { + print "disqualified (no email)."; + } print "\n"; unset($outputlangs); @@ -152,12 +159,12 @@ if ($resql) { // Si il reste des envois en buffer if ($foundtoprocess) { - if (dol_strlen($oldemail) && $oldemail != 'none') // Break onto email (new email) - { + if (dol_strlen($oldemail) && $oldemail != 'none') { // Break onto email (new email) envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative); } else { - if ($oldemail != 'none') + if ($oldemail != 'none') { print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n"; + } } } } else { @@ -187,8 +194,9 @@ function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldsalerepre { global $conf, $langs; - if (getenv('DOL_FORCE_EMAIL_TO')) + if (getenv('DOL_FORCE_EMAIL_TO')) { $oldemail = getenv('DOL_FORCE_EMAIL_TO'); + } $newlangs = new Translate('', $conf); $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang); @@ -205,10 +213,12 @@ function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldsalerepre dol_syslog("email_unpaid_invoices_to_representatives.php: send mail to ".$oldemail); $usehtml = 0; - if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER) && dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) + if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER) && dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) { $usehtml += 1; - if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER) && dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER)) + } + if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER) && dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER)) { $usehtml += 1; + } $allmessage = ''; if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER)) { @@ -221,8 +231,9 @@ function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldsalerepre $allmessage .= $langs->trans("Total")." = ".price($total, 0, $newlangs, 0, 0, - 1, $conf->currency).($usehtml ? "<br>\n" : "\n"); if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) { $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER; - if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) + if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) { $usehtml += 1; + } } $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml); diff --git a/scripts/invoices/rebuild_merge_pdf.php b/scripts/invoices/rebuild_merge_pdf.php index 22c55eeeb99..309de5fe4bd 100755 --- a/scripts/invoices/rebuild_merge_pdf.php +++ b/scripts/invoices/rebuild_merge_pdf.php @@ -23,7 +23,9 @@ * \brief Script to rebuild PDF and merge PDF files into one */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); diff --git a/scripts/members/sync_members_dolibarr2ldap.php b/scripts/members/sync_members_dolibarr2ldap.php index f0edb2fb8f3..4ecbe2e9b08 100755 --- a/scripts/members/sync_members_dolibarr2ldap.php +++ b/scripts/members/sync_members_dolibarr2ldap.php @@ -24,7 +24,9 @@ * \brief Script de mise a jour des adherents dans LDAP depuis base Dolibarr */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -61,8 +63,9 @@ if (!isset($argv[1]) || !$argv[1]) { } foreach ($argv as $key => $val) { - if (preg_match('/-y$/', $val, $reg)) + if (preg_match('/-y$/', $val, $reg)) { $confirmed = 1; + } } $now = $argv[1]; diff --git a/scripts/members/sync_members_ldap2dolibarr.php b/scripts/members/sync_members_ldap2dolibarr.php index 21a5075326c..be312ec1932 100755 --- a/scripts/members/sync_members_ldap2dolibarr.php +++ b/scripts/members/sync_members_ldap2dolibarr.php @@ -24,7 +24,9 @@ * \brief Script de mise a jour des adherents dans Dolibarr depuis LDAP */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -98,12 +100,15 @@ if (!isset($argv[2]) || !is_numeric($argv[2])) { $typeid = $argv[2]; foreach ($argv as $key => $val) { - if ($val == 'commitiferror') + if ($val == 'commitiferror') { $forcecommit = 1; - if (preg_match('/--server=([^\s]+)$/', $val, $reg)) + } + if (preg_match('/--server=([^\s]+)$/', $val, $reg)) { $conf->global->LDAP_SERVER_HOST = $reg[1]; - if (preg_match('/-y$/', $val, $reg)) + } + if (preg_match('/-y$/', $val, $reg)) { $confirmed = 1; + } } print "Mails sending disabled (useless in batch mode)\n"; @@ -115,9 +120,11 @@ print "port=".$conf->global->LDAP_SERVER_PORT."\n"; print "login=".$conf->global->LDAP_ADMIN_DN."\n"; print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n"; print "DN to extract=".$conf->global->LDAP_MEMBER_DN."\n"; -if (!empty($conf->global->LDAP_MEMBER_FILTER)) +if (!empty($conf->global->LDAP_MEMBER_FILTER)) { print 'Filter=('.$conf->global->LDAP_MEMBER_FILTER.')'."\n"; // Note: filter is defined into function getRecords -else print 'Filter=('.$conf->global->LDAP_KEY_MEMBERS.'=*)'."\n"; +} else { + print 'Filter=('.$conf->global->LDAP_KEY_MEMBERS.'=*)'."\n"; +} print "----- To Dolibarr database:\n"; print "type=".$conf->db->type."\n"; print "host=".$conf->db->host."\n"; @@ -257,8 +264,9 @@ if ($result >= 0) { if ($datefirst && $datelast && $datelast <= $datefirst) { // On ne va inserer que la premiere $datelast = 0; - if (!$pricefirst && $pricelast) + if (!$pricefirst && $pricelast) { $pricefirst = $pricelast; + } } } @@ -278,9 +286,11 @@ if ($result >= 0) { } if (!$error || $forcecommit) { - if (!$error) + if (!$error) { print $langs->transnoentities("NoErrorCommitIsDone")."\n"; - else print $langs->transnoentities("ErrorButCommitIsDone")."\n"; + } else { + print $langs->transnoentities("ErrorButCommitIsDone")."\n"; + } $db->commit(); } else { print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n"; diff --git a/scripts/members/sync_members_types_dolibarr2ldap.php b/scripts/members/sync_members_types_dolibarr2ldap.php index d0cf6ae7f04..cec998abda5 100755 --- a/scripts/members/sync_members_types_dolibarr2ldap.php +++ b/scripts/members/sync_members_types_dolibarr2ldap.php @@ -25,7 +25,9 @@ * \brief Script de mise a jour des types de membres dans LDAP depuis base Dolibarr */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); diff --git a/scripts/members/sync_members_types_ldap2dolibarr.php b/scripts/members/sync_members_types_ldap2dolibarr.php index f24faf9b76a..9aea20fb209 100755 --- a/scripts/members/sync_members_types_ldap2dolibarr.php +++ b/scripts/members/sync_members_types_ldap2dolibarr.php @@ -26,7 +26,9 @@ * \brief Script to update members types into Dolibarr from LDAP */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -72,14 +74,18 @@ if (!isset($argv[1])) { } foreach ($argv as $key => $val) { - if ($val == 'commitiferror') + if ($val == 'commitiferror') { $forcecommit = 1; - if (preg_match('/--server=([^\s]+)$/', $val, $reg)) + } + if (preg_match('/--server=([^\s]+)$/', $val, $reg)) { $conf->global->LDAP_SERVER_HOST = $reg[1]; - if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) + } + if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) { $excludeuser = explode(',', $reg[1]); - if (preg_match('/-y$/', $val, $reg)) + } + if (preg_match('/-y$/', $val, $reg)) { $confirmed = 1; + } } print "Mails sending disabled (useless in batch mode)\n"; @@ -163,9 +169,11 @@ if ($result >= 0) { } if (!$error || $forcecommit) { - if (!$error) + if (!$error) { print $langs->transnoentities("NoErrorCommitIsDone")."\n"; - else print $langs->transnoentities("ErrorButCommitIsDone")."\n"; + } else { + print $langs->transnoentities("ErrorButCommitIsDone")."\n"; + } $db->commit(); } else { print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n"; diff --git a/scripts/product/migrate_picture_path.php b/scripts/product/migrate_picture_path.php index 849eca44514..2f5a772fe8e 100755 --- a/scripts/product/migrate_picture_path.php +++ b/scripts/product/migrate_picture_path.php @@ -24,7 +24,9 @@ * \brief Migrate pictures from old system prior to 3.7 to new path for 3.7+ */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); diff --git a/scripts/product/regenerate_thumbs.php b/scripts/product/regenerate_thumbs.php index 0d8c6380eb3..5230484a156 100755 --- a/scripts/product/regenerate_thumbs.php +++ b/scripts/product/regenerate_thumbs.php @@ -24,7 +24,9 @@ * \brief Migrate pictures from old system prior to 3.7 to new path for 3.7+ */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -90,14 +92,16 @@ foreach ($filearray as $keyf => $valf) { // Create small thumbs for image // Used on logon for example $imgThumbSmall = vignette($vali['fullname'], $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs"); - if (preg_match('/Error/', $imgThumbSmall)) + if (preg_match('/Error/', $imgThumbSmall)) { print $imgThumbSmall."\n"; + } // Create mini thumbs for image (Ratio is near 16/9) // Used on menu or for setup page for example $imgThumbMini = vignette($vali['fullname'], $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs"); - if (preg_match('/Error/', $imgThumbMini)) + if (preg_match('/Error/', $imgThumbMini)) { print $imgThumbMini."\n"; + } } } diff --git a/scripts/user/sync_groups_dolibarr2ldap.php b/scripts/user/sync_groups_dolibarr2ldap.php index eb229c3d4ed..dd0476bbfca 100755 --- a/scripts/user/sync_groups_dolibarr2ldap.php +++ b/scripts/user/sync_groups_dolibarr2ldap.php @@ -24,7 +24,9 @@ * \brief Script de mise a jour des groupes dans LDAP depuis base Dolibarr */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); diff --git a/scripts/user/sync_groups_ldap2dolibarr.php b/scripts/user/sync_groups_ldap2dolibarr.php index 26e12c2c5e4..67c14a4ee5d 100755 --- a/scripts/user/sync_groups_ldap2dolibarr.php +++ b/scripts/user/sync_groups_ldap2dolibarr.php @@ -25,7 +25,9 @@ * \brief Script to update groups into Dolibarr from LDAP */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -72,14 +74,18 @@ if (!isset($argv[1])) { } foreach ($argv as $key => $val) { - if ($val == 'commitiferror') + if ($val == 'commitiferror') { $forcecommit = 1; - if (preg_match('/--server=([^\s]+)$/', $val, $reg)) + } + if (preg_match('/--server=([^\s]+)$/', $val, $reg)) { $conf->global->LDAP_SERVER_HOST = $reg[1]; - if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) + } + if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) { $excludeuser = explode(',', $reg[1]); - if (preg_match('/-y$/', $val, $reg)) + } + if (preg_match('/-y$/', $val, $reg)) { $confirmed = 1; + } } print "Mails sending disabled (useless in batch mode)\n"; @@ -91,7 +97,11 @@ print "port=".$conf->global->LDAP_SERVER_PORT."\n"; print "login=".$conf->global->LDAP_ADMIN_DN."\n"; print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n"; print "DN to extract=".$conf->global->LDAP_GROUP_DN."\n"; -print 'Filter=('.$conf->global->LDAP_KEY_GROUPS.'=*)'."\n"; +if (!empty($conf->global->LDAP_GROUP_FILTER)) { + print 'Filter=('.$conf->global->LDAP_GROUP_FILTER.')'."\n"; // Note: filter is defined into function getRecords +} else { + print 'Filter=('.$conf->global->LDAP_KEY_GROUPS.'=*)'."\n"; +} print "----- To Dolibarr database:\n"; print "type=".$conf->db->type."\n"; print "host=".$conf->db->host."\n"; @@ -121,7 +131,7 @@ if ($result >= 0) { // We disable synchro Dolibarr-LDAP $conf->global->LDAP_SYNCHRO_ACTIVE = 0; - $ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_GROUP_DN, $conf->global->LDAP_KEY_GROUPS, $required_fields, 0, array($conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS)); + $ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_GROUP_DN, $conf->global->LDAP_KEY_GROUPS, $required_fields, 'group', array($conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS)); if (is_array($ldaprecords)) { $db->begin(); @@ -167,8 +177,9 @@ if ($result >= 0) { $userList = array(); $userIdList = array(); foreach ($ldapgroup[$conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS] as $key => $userdn) { - if ($key === 'count') + if ($key === 'count') { continue; + } if (empty($userList[$userdn])) { // Récupération de l'utilisateur // Schéma rfc2307: les membres sont listés dans l'attribut memberUid sous form de login uniquement if ($conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS === 'memberUid') { @@ -177,8 +188,9 @@ if ($result >= 0) { $userFilter = explode(',', $userdn); $userKey = $ldap->getAttributeValues('('.$userFilter[0].')', $conf->global->LDAP_KEY_USERS); } - if (!is_array($userKey)) + if (!is_array($userKey)) { continue; + } $fuser = new User($db); @@ -212,9 +224,11 @@ if ($result >= 0) { } if (!$error || $forcecommit) { - if (!$error) + if (!$error) { print $langs->transnoentities("NoErrorCommitIsDone")."\n"; - else print $langs->transnoentities("ErrorButCommitIsDone")."\n"; + } else { + print $langs->transnoentities("ErrorButCommitIsDone")."\n"; + } $db->commit(); } else { print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n"; diff --git a/scripts/user/sync_users_dolibarr2ldap.php b/scripts/user/sync_users_dolibarr2ldap.php index 4f6fd00d1c7..26b1363d5a1 100755 --- a/scripts/user/sync_users_dolibarr2ldap.php +++ b/scripts/user/sync_users_dolibarr2ldap.php @@ -24,7 +24,9 @@ * \brief Script de mise a jour des users dans LDAP depuis base Dolibarr */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); diff --git a/scripts/website/migrate-news-joomla2dolibarr.php b/scripts/website/migrate-news-joomla2dolibarr.php index dfd92a19acf..605f982bd16 100755 --- a/scripts/website/migrate-news-joomla2dolibarr.php +++ b/scripts/website/migrate-news-joomla2dolibarr.php @@ -22,7 +22,9 @@ * \brief Migrate news from a Joomla databse into a Dolibarr website */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -82,8 +84,7 @@ $websiteid = $website->id; $importid = dol_print_date(dol_now(), 'dayhourlog'); $dbjoomla = getDoliDBInstance('mysqli', $joomlahost, $joomlalogin, $joomlapass, $joomladatabase, $joomlaport); -if ($dbjoomla->error) -{ +if ($dbjoomla->error) { dol_print_error($dbjoomla, "host=".$joomlahost.", port=".$joomlaport.", user=".$joomlalogin.", databasename=".$joomladatabase.", ".$dbjoomla->error); exit(-1); } @@ -124,10 +125,14 @@ while ($obj = $dbjoomla->fetch_object($resql)) { $title = $obj->title; //$description = dol_string_nohtmltag($obj->introtext); $description = trim(dol_trunc(dol_string_nohtmltag($obj->metadesc), 250)); - if (empty($description)) $description = trim(dol_trunc(dol_string_nohtmltag($obj->introtext), 250)); + if (empty($description)) { + $description = trim(dol_trunc(dol_string_nohtmltag($obj->introtext), 250)); + } $htmltext = ""; - if ($blogpostheader) $htmltext .= $blogpostheader."\n"; + if ($blogpostheader) { + $htmltext .= $blogpostheader."\n"; + } $htmltext .= '<section id="mysectionnewsintro" contenteditable="true">'."\n"; $htmltext .= $obj->introtext; $htmltext .= '</section>'."\n"; @@ -137,7 +142,9 @@ while ($obj = $dbjoomla->fetch_object($resql)) { $htmltext .= $obj->fulltext; $htmltext .= "</section>"; } - if ($blogpostfooter) $htmltext .= "\n".$blogpostfooter; + if ($blogpostfooter) { + $htmltext .= "\n".$blogpostfooter; + } $language = ($forcelang ? $forcelang : ($obj->language && $obj->language != '*' ? $obj->language : 'en')); $keywords = $obj->metakey; diff --git a/scripts/website/regenerate-pages.php b/scripts/website/regenerate-pages.php index a50db09708d..46b9283a4cf 100755 --- a/scripts/website/regenerate-pages.php +++ b/scripts/website/regenerate-pages.php @@ -22,7 +22,9 @@ * \brief Regenerate all pages of a web site */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); diff --git a/scripts/withdrawals/build_withdrawal_file.php b/scripts/withdrawals/build_withdrawal_file.php index 5ae7ba70bf4..42bf5f6bb3f 100755 --- a/scripts/withdrawals/build_withdrawal_file.php +++ b/scripts/withdrawals/build_withdrawal_file.php @@ -24,7 +24,9 @@ * \brief Script de prelevement */ -if (!defined('NOSESSION')) define('NOSESSION', '1'); +if (!defined('NOSESSION')) { + define('NOSESSION', '1'); +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); diff --git a/test/other/test_serialize.php b/test/other/test_serialize.php index 873698e95c2..2fdfffaef3e 100644 --- a/test/other/test_serialize.php +++ b/test/other/test_serialize.php @@ -16,11 +16,12 @@ $object->bbb = 'bbb'; $object->thirdparty = new stdClass(); $tmp = new Societe($db); $tmp->name = 'MyBigCompany'; -foreach ($tmp as $key=>$value) -{ +foreach ($tmp as $key => $value) { if (!in_array($key, array( 'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code' - ))) continue; // Discard if not into a dedicated list + ))) { + continue; // Discard if not into a dedicated list + } if (!is_object($value)) $object->thirdparty->{$key} = $value; } diff --git a/test/phpunit/CodingPhpTest.php b/test/phpunit/CodingPhpTest.php index cf58c298206..06c702a6a58 100644 --- a/test/phpunit/CodingPhpTest.php +++ b/test/phpunit/CodingPhpTest.php @@ -378,16 +378,16 @@ class CodingPhpTest extends PHPUnit\Framework\TestCase $this->assertTrue($ok, 'Found a declaration @var array() instead of @var array in file '.$file['relativename'].'.'); - // Test we don't have CURDATE() - $ok=true; - $matches=array(); - preg_match_all('/CURDATE\(\)/', $filecontent, $matches, PREG_SET_ORDER); - foreach ($matches as $key => $val) { - $ok=false; - break; - } - $this->assertTrue($ok, 'Found a CURDATE\(\) into code. Do not use this SQL method in file '.$file['relativename'].'. You must use the PHP function dol_now() instead.'); - } + // Test we don't have CURDATE() + $ok=true; + $matches=array(); + preg_match_all('/CURDATE\(\)/', $filecontent, $matches, PREG_SET_ORDER); + foreach ($matches as $key => $val) { + $ok=false; + break; + } + $this->assertTrue($ok, 'Found a CURDATE\(\) into code. Do not use this SQL method in file '.$file['relativename'].'. You must use the PHP function dol_now() instead.'); + } return; } diff --git a/test/phpunit/CommandeFournisseurTest.php b/test/phpunit/CommandeFournisseurTest.php index 28fc9b8daac..b050005bcf1 100644 --- a/test/phpunit/CommandeFournisseurTest.php +++ b/test/phpunit/CommandeFournisseurTest.php @@ -183,7 +183,7 @@ class CommandeFournisseurTest extends PHPUnit\Framework\TestCase print __METHOD__." result=".$result."\n"; $this->assertEquals(-1, $result, 'Creation of too low quantity'); // must be -1 because quantity is lower than minimum of supplier price - $sql="DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur where ref=''"; + $sql="DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur where ref IN ('', '(PROV)')"; $db->query($sql); // Create purchase order diff --git a/test/phpunit/DateLibTest.php b/test/phpunit/DateLibTest.php index 366a8fd4ec8..03eacd13745 100644 --- a/test/phpunit/DateLibTest.php +++ b/test/phpunit/DateLibTest.php @@ -68,7 +68,13 @@ class DateLibTest extends PHPUnit\Framework\TestCase $this->savlangs=$langs; $this->savdb=$db; + $langs->load("admin"); + print __METHOD__." db->type=".$db->type." user->id=".$user->id; + + print "\n".$langs->trans("CurrentTimeZone").' : '.getServerTimeZoneString(); + print "\n".$langs->trans("CurrentHour").' : '.dol_print_date(dol_now('gmt'), 'dayhour', 'tzserver'); + //print " - db ".$db->db; print "\n"; } @@ -138,8 +144,8 @@ class DateLibTest extends PHPUnit\Framework\TestCase $db=$this->savdb; // With same hours - $date1=dol_mktime(0, 0, 0, 1, 1, 2012); - $date2=dol_mktime(0, 0, 0, 1, 2, 2012); + $date1=dol_mktime(0, 0, 0, 1, 1, 2012, 'gmt'); + $date2=dol_mktime(0, 0, 0, 1, 2, 2012, 'gmt'); $result=num_between_day($date1, $date2, 1); print __METHOD__." result=".$result."\n"; @@ -150,8 +156,8 @@ class DateLibTest extends PHPUnit\Framework\TestCase $this->assertEquals(1, $result); // With different hours - $date1=dol_mktime(0, 0, 0, 1, 1, 2012); - $date2=dol_mktime(12, 0, 0, 1, 2, 2012); + $date1=dol_mktime(0, 0, 0, 1, 1, 2012, 'gmt'); + $date2=dol_mktime(12, 0, 0, 1, 2, 2012, 'gmt'); $result=num_between_day($date1, $date2, 1); print __METHOD__." result=".$result."\n"; @@ -190,25 +196,26 @@ class DateLibTest extends PHPUnit\Framework\TestCase $db=$this->savdb; // With same hours - Tuesday/Wednesday jan 2013 - $date1=dol_mktime(0, 0, 0, 1, 1, 2013); - $date2=dol_mktime(0, 0, 0, 1, 2, 2013); - $date3=dol_mktime(0, 0, 0, 1, 3, 2013); + $date1=dol_mktime(0, 0, 0, 1, 1, 2013, 'gmt'); + $date2=dol_mktime(0, 0, 0, 1, 2, 2013, 'gmt'); + $date3=dol_mktime(0, 0, 0, 1, 3, 2013, 'gmt'); $result=num_public_holiday($date1, $date2, 'FR', 1); - print __METHOD__." result=".$result."\n"; + print __METHOD__." for Tuesday 1 - Wednesday 2 jan 2013 for FR result=".$result."\n"; $this->assertEquals(1, $result, 'NumPublicHoliday for Tuesday 1 - Wednesday 2 jan 2013 for FR'); // 1 closed days (country france) $result=num_public_holiday($date1, $date2, 'XX', 1); - print __METHOD__." result=".$result."\n"; + print __METHOD__." for Tuesday 1 - Wednesday 2 jan 2013 for XX result=".$result."\n"; $this->assertEquals(1, $result, 'NumPublicHoliday for Tuesday 1 - Wednesday 2 jan 2013 for XX'); // 1 closed days (country unknown) + print '----'."\n"; $result=num_public_holiday($date2, $date3, 'FR', 1); - print __METHOD__." result=".$result."\n"; + print __METHOD__." for Wednesday 2 - Thursday 3 jan 2013 for FR result=".$result."\n"; $this->assertEquals(0, $result, 'NumPublicHoliday for Wednesday 2 - Thursday 3 jan 2013 for FR'); // no closed days // Check with easter monday - $date1=dol_mktime(0, 0, 0, 4, 21, 2019); - $date2=dol_mktime(0, 0, 0, 4, 23, 2019); + $date1=dol_mktime(0, 0, 0, 4, 21, 2019, 'gmt'); + $date2=dol_mktime(0, 0, 0, 4, 23, 2019, 'gmt'); $result=num_public_holiday($date1, $date2, 'XX', 1); print __METHOD__." result=".$result."\n"; @@ -219,8 +226,8 @@ class DateLibTest extends PHPUnit\Framework\TestCase $this->assertEquals(2, $result, 'NumPublicHoliday including eastermonday for FR'); // 1 opened day, 2 closed days (sunday + easter monday) // Check for sunday/saturday - Friday 4 - Sunday 6 jan 2013 - $date1=dol_mktime(0, 0, 0, 1, 4, 2013); - $date2=dol_mktime(0, 0, 0, 1, 6, 2013); + $date1=dol_mktime(0, 0, 0, 1, 4, 2013, 'gmt'); + $date2=dol_mktime(0, 0, 0, 1, 6, 2013, 'gmt'); $result=num_public_holiday($date1, $date2, 'FR', 1); print __METHOD__." result=".$result."\n"; @@ -257,9 +264,9 @@ class DateLibTest extends PHPUnit\Framework\TestCase $db=$this->savdb; // With same hours - Tuesday/Wednesday jan 2013 - $date1=dol_mktime(0, 0, 0, 1, 1, 2013); - $date2=dol_mktime(0, 0, 0, 1, 2, 2013); - $date3=dol_mktime(0, 0, 0, 1, 3, 2013); + $date1=dol_mktime(0, 0, 0, 1, 1, 2013, 'gmt'); + $date2=dol_mktime(0, 0, 0, 1, 2, 2013, 'gmt'); + $date3=dol_mktime(0, 0, 0, 1, 3, 2013, 'gmt'); $result=num_open_day($date1, $date2, 0, 1, 0, 'FR'); print __METHOD__." result=".$result."\n"; @@ -274,8 +281,8 @@ class DateLibTest extends PHPUnit\Framework\TestCase $this->assertEquals(2, $result, 'NumOpenDay Wednesday 2 - Thursday 3 jan 2013 for FR'); // 2 opened days // With same hours - Friday/Sunday jan 2013 - $date1=dol_mktime(0, 0, 0, 1, 4, 2013); - $date2=dol_mktime(0, 0, 0, 1, 6, 2013); + $date1=dol_mktime(0, 0, 0, 1, 4, 2013, 'gmt'); + $date2=dol_mktime(0, 0, 0, 1, 6, 2013, 'gmt'); $result=num_open_day($date1, $date2, 0, 1, 0, 'FR'); print __METHOD__." result=".$result."\n"; @@ -325,8 +332,7 @@ class DateLibTest extends PHPUnit\Framework\TestCase $result=convertSecondToTime(86400, 'all', 86400); print __METHOD__." result=".$result."\n"; - $this->assertSame('1 '.$langs->trans("Day"), $result); - + $this->assertSame('1 '.strtolower(dol_substr($langs->trans("Day"), 0, 1).'.'), $result); return $result; } diff --git a/test/phpunit/DateLibTzFranceTest.php b/test/phpunit/DateLibTzFranceTest.php index 63893a9c881..63eadc1a98f 100644 --- a/test/phpunit/DateLibTzFranceTest.php +++ b/test/phpunit/DateLibTzFranceTest.php @@ -82,8 +82,8 @@ class DateLibTzFranceTest extends PHPUnit\Framework\TestCase { global $conf,$user,$langs,$db; - if (getServerTimeZoneString() != 'Europe/Paris') { - print "\n".__METHOD__." This PHPUnit test can be launched manually only onto a server with PHP timezone set to TZ+1 Europe/Paris, not a TZ=".getServerTimeZoneString().".\n"; die(); + if (getServerTimeZoneString() != 'Europe/Paris' && getServerTimeZoneString() != 'Europe/Berlin') { + print "\n".__METHOD__." This PHPUnit test can be launched manually only onto a server with PHP timezone set to TZ=Europe/Paris, not a TZ=".getServerTimeZoneString().".\n"; die(); } $db->begin(); // This is to have all actions inside a transaction even if test launched without suite. diff --git a/test/phpunit/ExportTest.php b/test/phpunit/ExportTest.php index 4051deb125b..7d837781897 100644 --- a/test/phpunit/ExportTest.php +++ b/test/phpunit/ExportTest.php @@ -279,14 +279,14 @@ class ExportTest extends PHPUnit\Framework\TestCase $expectedresult=1; $this->assertEquals($expectedresult, $result, 'Error in TSV export'); - $model='excel2007'; + $model='excel2007'; // Build export file /* ko on php 7.4 on travis (zip not available) */ print "Process build_file for model = ".$model."\n"; $result=$objexport->build_file($user, $model, $datatoexport, $array_selected, array(), $sql); $expectedresult=1; - $this->assertEquals($expectedresult, $result, 'Error in Excel2007 export'); + $this->assertEquals($expectedresult, $result, 'Error in Excel2007 export'); return true; } diff --git a/test/phpunit/FactureRecTest.php b/test/phpunit/FactureRecTest.php index 2a0b8823973..1fb62ecfd0e 100644 --- a/test/phpunit/FactureRecTest.php +++ b/test/phpunit/FactureRecTest.php @@ -127,13 +127,14 @@ class FactureRecTest extends PHPUnit\Framework\TestCase } /** - * testFactureCreate + * testFactureRecCreate * * @return int */ public function testFactureRecCreate() { global $conf,$user,$langs,$db; + $conf=$this->savconf; $user=$this->savuser; $langs=$this->savlangs; @@ -141,21 +142,51 @@ class FactureRecTest extends PHPUnit\Framework\TestCase $localobjectinv=new Facture($this->savdb); $localobjectinv->initAsSpecimen(); - $localobjectinv->create($user); + $result = $localobjectinv->create($user); + + print __METHOD__." result=".$result."\n"; $localobject=new FactureRec($this->savdb); $localobject->initAsSpecimen(); - $result=$localobject->create($user, $localobjectinv->id); + $result = $localobject->create($user, $localobjectinv->id); - $this->assertLessThan($result, 0); print __METHOD__." result=".$result."\n"; + $this->assertGreaterThan(0, $result, 'Create recurring invoice from common invoice'); + return $result; } + /** + * testFactureRecFetch + * + * @param int $id Id of created recuriing invoice + * @return int + * + * @depends testFactureRecCreate + * The depends says test is run only if previous is ok + */ + public function testFactureRecFetch($id) + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + $localobject=new FactureRec($this->savdb); + $result = $localobject->fetch($id); + + print __METHOD__." result=".$result."\n"; + $this->assertGreaterThan(0, $result); + return $result; + } + + + /** * Edit an object to test updates * - * @param Facture $localobject Object Facture + * @param FactureRec $localobject Object Facture rec * @return void */ public function changeProperties(&$localobject) diff --git a/test/phpunit/FilesLibTest.php b/test/phpunit/FilesLibTest.php index fddff66e9ea..b98237d1b29 100644 --- a/test/phpunit/FilesLibTest.php +++ b/test/phpunit/FilesLibTest.php @@ -424,6 +424,13 @@ class FilesLibTest extends PHPUnit\Framework\TestCase $result=dol_uncompress($fileout, $dirout); print __METHOD__." result=".join(',', $result)."\n"; $this->assertEquals(0, count($result), "Pb with dol_uncompress_file of file ".$fileout); + + $excludefiles = '/(\.back|\.old|\.log|documents[\/\\\]admin[\/\\\]documents[\/\\\])/i'; + if (preg_match($excludefiles, 'a/temp/b')) { echo '----- Regex OK -----'."\n"; } + $result=dol_compress_dir($dirout, $conf->admin->dir_temp.'/testdir.zip', 'zip', $excludefiles); + print __METHOD__." result=".$result."\n"; + print join(', ', $conf->logbuffer); + $this->assertGreaterThanOrEqual(1, $result, "Pb with dol_compress_dir of ".$dirout." into ".$conf->admin->dir_temp.'/testdir.zip'); } /** diff --git a/test/phpunit/FunctionsLibTest.php b/test/phpunit/FunctionsLibTest.php index 4f6bfb1963e..e43453b26ec 100644 --- a/test/phpunit/FunctionsLibTest.php +++ b/test/phpunit/FunctionsLibTest.php @@ -108,7 +108,15 @@ class FunctionsLibTest extends PHPUnit\Framework\TestCase //$db->begin(); // This is to have all actions inside a transaction even if test launched without suite. if (! function_exists('mb_substr')) { - print "\n".__METHOD__." function mb_substr must be enabled.\n"; die(); + print "\n".__METHOD__." function mb_substr must be enabled.\n"; die(1); + } + + if ($conf->global->MAIN_MAX_DECIMALS_UNIT != 5) { + print "\n".__METHOD__." bad setup for number of digits for unit amount. Must be 5 for this test.\n"; die(1); + } + + if ($conf->global->MAIN_MAX_DECIMALS_TOT != 2) { + print "\n".__METHOD__." bad setup for number of digits for unit amount. Must be 2 for this test.\n"; die(1); } print __METHOD__."\n"; @@ -765,36 +773,36 @@ class FunctionsLibTest extends PHPUnit\Framework\TestCase */ public function testDolTrunc() { - // Default trunc (will add ... if truncation truncation or keep last char if only one char) + // Default trunc (will add … if truncation truncation or keep last char if only one char) $input="éeéeéeàa"; $after=dol_trunc($input, 3); - $this->assertEquals("éeé...", $after, 'Test A1'); + $this->assertEquals("éeé…", $after, 'Test A1'); $after=dol_trunc($input, 2); - $this->assertEquals("ée...", $after, 'Test A2'); + $this->assertEquals("ée…", $after, 'Test A2'); $after=dol_trunc($input, 1); - $this->assertEquals("é...", $after, 'Test A3'); - $input="éeéeé"; + $this->assertEquals("é…", $after, 'Test A3'); + $input="éeée"; $after=dol_trunc($input, 3); - $this->assertEquals("éeéeé", $after, 'Test B1'); + $this->assertEquals("éeée", $after, 'Test B1'); $after=dol_trunc($input, 2); - $this->assertEquals("éeéeé", $after, 'Test B2'); + $this->assertEquals("ée…", $after, 'Test B2'); $after=dol_trunc($input, 1); - $this->assertEquals("é...", $after, 'Test B3'); + $this->assertEquals("é…", $after, 'Test B3'); $input="éeée"; $after=dol_trunc($input, 3); $this->assertEquals("éeée", $after, 'Test C1'); $after=dol_trunc($input, 2); - $this->assertEquals("éeée", $after, 'Test C2'); + $this->assertEquals("ée…", $after, 'Test C2'); $after=dol_trunc($input, 1); - $this->assertEquals("éeée", $after, 'Test C3'); + $this->assertEquals("é…", $after, 'Test C3'); $input="éeé"; $after=dol_trunc($input, 3); $this->assertEquals("éeé", $after, 'Test C'); $after=dol_trunc($input, 2); $this->assertEquals("éeé", $after, 'Test D'); $after=dol_trunc($input, 1); - $this->assertEquals("éeé", $after, 'Test E'); - // Trunc with no ... + $this->assertEquals("é…", $after, 'Test E'); + // Trunc with no … $input="éeéeéeàa"; $after=dol_trunc($input, 3, 'right', 'UTF-8', 1); $this->assertEquals("éeé", $after, 'Test F'); @@ -809,7 +817,7 @@ class FunctionsLibTest extends PHPUnit\Framework\TestCase $this->assertEquals("é", $after, 'Test J'); $input="éeéeéeàa"; $after=dol_trunc($input, 4, 'middle'); - $this->assertEquals("ée...àa", $after, 'Test K'); + $this->assertEquals("ée…àa", $after, 'Test K'); return true; } @@ -1294,7 +1302,7 @@ class FunctionsLibTest extends PHPUnit\Framework\TestCase $this->assertEquals(1000.123456, price2num('1 000.123456')); // Round down - $this->assertEquals(1000.12, price2num('1 000.123452', 'MT')); + $this->assertEquals(1000.12, price2num('1 000.123452', 'MT'), 'Error in round down with MT'); $this->assertEquals(1000.12345, price2num('1 000.123452', 'MU'), "Test MU"); // Round up diff --git a/test/phpunit/ImportTest.php b/test/phpunit/ImportTest.php index 1dd0853829c..ed285608690 100644 --- a/test/phpunit/ImportTest.php +++ b/test/phpunit/ImportTest.php @@ -162,6 +162,10 @@ class ImportTest extends PHPUnit\Framework\TestCase // according to option $this->assertEquals(0, 0); + // TODO Export and compare the file exported with the $file imported. + + + return true; } } diff --git a/test/phpunit/SecurityTest.php b/test/phpunit/SecurityTest.php index 6b157d2dcab..1d3b76cd4f2 100644 --- a/test/phpunit/SecurityTest.php +++ b/test/phpunit/SecurityTest.php @@ -184,9 +184,15 @@ class SecurityTest extends PHPUnit\Framework\TestCase // Should be OK $expectedresult=0; + /* + $test = ''; + $result=testSqlAndScriptInject($test, 0); + $this->assertGreaterThanOrEqual(0, $result, 'Error on testSqlAndScriptInject kkk'); + */ + $_SERVER["PHP_SELF"]='/DIR WITH SPACE/htdocs/admin/index.php?mainmenu=home&leftmenu=setup&username=weservices'; $result=testSqlAndScriptInject($_SERVER["PHP_SELF"], 2); - $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject expected 0a'); + $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for PHP_SELF that should be ok'); $test = 'This is a < inside string with < and > also and tag like <a> before the >'; $result=testSqlAndScriptInject($test, 0); @@ -197,7 +203,11 @@ class SecurityTest extends PHPUnit\Framework\TestCase $_SERVER["PHP_SELF"]='/DIR WITH SPACE/htdocs/admin/index.php?mainmenu=home&leftmenu=setup&username=weservices;badaction'; $result=testSqlAndScriptInject($_SERVER["PHP_SELF"], 2); - $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject 1b'); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject for PHP_SELF that should detect XSS'); + + $test = 'javascript&colon&#x3B;alert(1)'; + $result=testSqlAndScriptInject($test, 0); + $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject expected 1a'); $test="<img src='1.jpg' onerror =javascript:alert('XSS')>"; $result=testSqlAndScriptInject($test, 0); @@ -312,9 +322,13 @@ class SecurityTest extends PHPUnit\Framework\TestCase $_POST['param8c']='< with space after is ok'; $_POST['param8d']='<abc123 is html to clean'; $_POST['param8e']='<123abc is not html to clean'; + $_POST['param8f']='abc<<svg <><<animate onbegin=alert(document.domain) a'; $_POST["param9"]='is_object($object) ? ($object->id < 10 ? round($object->id / 2, 2) : (2 * $user->id) * (int) substr($mysoc->zip, 1, 2)) : \'objnotdefined\''; $_POST["param10"]='is_object($object) ? ($object->id < 10 ? round($object->id / 2, 2) : (2 * $user->id) * (int) substr($mysoc->zip, 1, 2)) : \'<abc>objnotdefined\''; $_POST["param11"]=' Name <email@email.com> '; + $_POST["param12"]='<!DOCTYPE html><html>aaa</html>'; + //$_POST["param13"]='javascript%26colon%26%23x3B%3Balert(1)'; + //$_POST["param14"]='javascripT&javascript#x3a alert(1)'; $result=GETPOST('id', 'int'); // Must return nothing print __METHOD__." result=".$result."\n"; @@ -329,6 +343,7 @@ class SecurityTest extends PHPUnit\Framework\TestCase $this->assertEquals($result, 333, 'Test on param1 with 3rd param = 2'); // Test alpha + $result=GETPOST("param2", 'alpha'); print __METHOD__." result=".$result."\n"; $this->assertEquals($result, $_GET["param2"], 'Test on param2'); @@ -342,6 +357,7 @@ class SecurityTest extends PHPUnit\Framework\TestCase $this->assertEquals($result, 'dir'); // Test aZ09 + $result=GETPOST("param1", 'aZ09'); print __METHOD__." result=".$result."\n"; $this->assertEquals($result, $_GET["param1"]); @@ -371,6 +387,7 @@ class SecurityTest extends PHPUnit\Framework\TestCase $this->assertEquals('">', $result); // With restricthtml we must remove html open/close tag and content but not htmlentities like &#110; + $result=GETPOST("param7", 'restricthtml'); print __METHOD__." result=".$result."\n"; $this->assertEquals('"c:\this is a path~1\aaa&#110;" abcdef', $result); @@ -388,17 +405,21 @@ class SecurityTest extends PHPUnit\Framework\TestCase print __METHOD__." result=".$result."\n"; $this->assertEquals($_POST['param8c'], $result, 'Test a string with non closing html tag with alphanohtml'); - $result=GETPOST("param8d", 'alphanohtml'); - print __METHOD__." result=".$result."\n"; - $this->assertEquals('abc123 is html to clean', $result, 'Test a string with non closing html tag with alphanohtml'); + $result=GETPOST("param8d", 'alphanohtml'); + print __METHOD__." result=".$result."\n"; + $this->assertEquals('abc123 is html to clean', $result, 'Test a string with non closing html tag with alphanohtml'); - $result=GETPOST("param8e", 'alphanohtml'); - print __METHOD__." result=".$result."\n"; - $this->assertEquals($_POST['param8e'], $result, 'Test a string with non closing html tag with alphanohtml'); + $result=GETPOST("param8e", 'alphanohtml'); + print __METHOD__." result=".$result."\n"; + $this->assertEquals($_POST['param8e'], $result, 'Test a string with non closing html tag with alphanohtml'); - $result=GETPOST("param9", 'alphanohtml'); - print __METHOD__." result=".$result."\n"; - $this->assertEquals($_POST["param9"], $result); + $result=GETPOST("param8f", 'alphanohtml'); + print __METHOD__." result=".$result."\n"; + $this->assertEquals('abcsvg animate onbegin=alert(document.domain) a', $result, 'Test a string with html tag open with several <'); + + $result=GETPOST("param9", 'alphanohtml'); + print __METHOD__." result=".$result."\n"; + $this->assertEquals($_POST["param9"], $result); $result=GETPOST("param10", 'alphanohtml'); print __METHOD__." result=".$result."\n"; @@ -412,6 +433,51 @@ class SecurityTest extends PHPUnit\Framework\TestCase print __METHOD__." result=".$result."\n"; $this->assertEquals(trim($_POST["param11"]), $result, 'Test an email string with alphawithlgt'); + $result=GETPOST("param12", 'restricthtml'); + print __METHOD__." result=".$result."\n"; + $this->assertEquals(trim($_POST["param12"]), $result, 'Test a string with DOCTYPE and restricthtml'); + + /*$result=GETPOST("param13", 'alphanohtml'); + print __METHOD__." result=".$result."\n"; + $this->assertEquals(trim($_POST["param13"]), $result, 'Test a string and alphanohtml'); + + $result=GETPOST("param14", 'alphanohtml'); + print __METHOD__." result=".$result."\n"; + $this->assertEquals(trim($_POST["param14"]), $result, 'Test a string and alphanohtml'); + */ + + // Special test for GETPOST of backtopage or backtolist parameter + + $_POST["backtopage"]='//www.google.com'; + $result=GETPOST("backtopage"); + print __METHOD__." result=".$result."\n"; + $this->assertEquals('www.google.com', $result, 'Test for backtopage param'); + + $_POST["backtopage"]='https:https://www.google.com'; + $result=GETPOST("backtopage"); + print __METHOD__." result=".$result."\n"; + $this->assertEquals('www.google.com', $result, 'Test for backtopage param'); + + $_POST["backtolist"]='::HTTPS://www.google.com'; + $result=GETPOST("backtolist"); + print __METHOD__." result=".$result."\n"; + $this->assertEquals('www.google.com', $result, 'Test for backtopage param'); + + $_POST["backtopage"]='http:www.google.com'; + $result=GETPOST("backtopage"); + print __METHOD__." result=".$result."\n"; + $this->assertEquals('httpwww.google.com', $result, 'Test for backtopage param'); + + $_POST["backtopage"]='/mydir/mypage.php?aa=a%10a'; + $result=GETPOST("backtopage"); + print __METHOD__." result=".$result."\n"; + $this->assertEquals('/mydir/mypage.php?aa=a%10a', $result, 'Test for backtopage param'); + + $_POST["backtopage"]='javascripT&javascript#javascriptxjavascript3a alert(1)'; + $result=GETPOST("backtopage"); + print __METHOD__." result=".$result."\n"; + $this->assertEquals('x3a alert(1)', $result, 'Test for backtopage param'); + return $result; } @@ -505,6 +571,21 @@ class SecurityTest extends PHPUnit\Framework\TestCase return 0; } + /** + * testDolStringOnlyTheseHtmlAttributes + * + * @return number + */ + public function testDolStringOnlyTheseHtmlAttributes() + { + $stringtotest = '<div onload="ee"><a href="123"><span class="abc">abc</span></a></div>'; + $decodedstring = dol_string_onlythesehtmlattributes($stringtotest); + $decodedstring = preg_replace("/\n$/", "", $decodedstring); + $this->assertEquals('<div><a href="123"><span class="abc">abc</span></a></div>', $decodedstring, 'Function did not sanitize correclty with test 1'); + + return 0; + } + /** * testGetRandomPassword * @@ -610,6 +691,32 @@ class SecurityTest extends PHPUnit\Framework\TestCase return 0; } + /** + * testDolSanitizeUrl + * + * @return void + */ + public function testDolSanitizeUrl() + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + $test = 'javascripT&javascript#x3a alert(1)'; + $result=dol_sanitizeUrl($test); + $this->assertEquals('x3a alert(1)', $result, 'Test on dol_sanitizeUrl A'); + + $test = 'javajavascriptscript&cjavascriptolon;alert(1)'; + $result=dol_sanitizeUrl($test); + $this->assertEquals('alert(1)', $result, 'Test on dol_sanitizeUrl B'); + + $test = '/javas:cript/google.com'; + $result=dol_sanitizeUrl($test); + $this->assertEquals('google.com', $result, 'Test on dol_sanitizeUrl C'); + } + /** * testDolSanitizeFileName * diff --git a/test/phpunit/SocieteTest.php b/test/phpunit/SocieteTest.php index 32b224bb584..aa57d987238 100755 --- a/test/phpunit/SocieteTest.php +++ b/test/phpunit/SocieteTest.php @@ -91,6 +91,10 @@ class SocieteTest extends PHPUnit\Framework\TestCase print "\n".__METHOD__." constant MAIN_DISABLEPROFIDRULES must be empty (if a module set it, disable module).\n"; die(); } + if ($langs->defaultlang != 'en_US') { + print "\n".__METHOD__." default language of company must be set to autodetect.\n"; die(); + } + $db->begin(); // This is to have all actions inside a transaction even if test launched without suite. print __METHOD__."\n"; @@ -347,9 +351,24 @@ class SocieteTest extends PHPUnit\Framework\TestCase print __METHOD__." id=".$localobject->id." result=".$result."\n"; $this->assertNotEquals($result, ''); + $localobject->country_code = 'FR'; + $result=$localobject->isInEEC(); print __METHOD__." id=".$localobject->id." country_code=".$localobject->country_code." result=".$result."\n"; - $this->assertTrue(true, $result); + $this->assertTrue($result); + + $localobject->country_code = 'US'; + + $result=$localobject->isInEEC(); + print __METHOD__." id=".$localobject->id." country_code=".$localobject->country_code." result=".$result."\n"; + $this->assertFalse($result); + + /*$localobject->country_code = 'GB'; + + $result=$localobject->isInEEC(); + print __METHOD__." id=".$localobject->id." country_code=".$localobject->country_code." result=".$result."\n"; + $this->assertTrue($result); + */ $localobject->info($localobject->id); print __METHOD__." localobject->date_creation=".$localobject->date_creation."\n";